text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import * as _ from "underscore";
import {KyloObject, ObjectChanged} from "../../../../lib/common/common.model";
import {CloneUtil} from "../../../common/utils/clone-util";
import {ObjectUtils} from "../../../../lib/common/utils/object-utils";
import {ConnectorPlugin} from "../../catalog/api/models/connector-plugin";
import {ConnectorPluginNifiProperties} from "../../catalog/api/models/connector-plugin-nifi-properties";
import {TableColumn} from "../../catalog/datasource/preview-schema/model/table-view-model";
import {TableSchemaUpdateMode} from "../../feeds/define-feed-ng2/services/define-feed.service";
import {FeedDetailsProcessorRenderingHelper} from "../../services/FeedDetailsProcessorRenderingHelper";
import {Templates} from "../../../../lib/feed-mgr/services/TemplateTypes";
import {Category} from "../category/category.model";
import {DefaultFeedDataTransformation, FeedDataTransformation} from "../feed-data-transformation";
import {SchemaParser} from "../field-policy";
import {SparkDataSet} from "../spark-data-set.model"
import {TableColumnDefinition} from "../TableColumnDefinition";
import {TableFieldPolicy} from "../TableFieldPolicy";
import {UserProperty, UserPropertyUtil} from "../user-property.model";
import {SourceTableSchema} from "./feed-source-table-schema.model";
import {Step} from "./feed-step.model";
import {FeedTableDefinition} from "./feed-table-definition.model";
import {FeedTableSchema} from "./feed-table-schema.model";
import {EntityVersion} from "../entity-version.model";
import {PartialObserver} from "rxjs/Observer";
import {Observable} from "rxjs/Observable";
import {Subject} from "rxjs/Subject";
import {SchemaField} from "../schema-field";
import {PreviewDataSet} from "../../catalog/datasource/preview-schema/model/preview-data-set";
import {PreviewFileDataSet} from "../../catalog/datasource/preview-schema/model/preview-file-data-set";
import {PreviewHiveDataSet} from "../../catalog/datasource/preview-schema/model/preview-hive-data-set";
import {PreviewJdbcDataSet} from "../../catalog/datasource/preview-schema/model/preview-jdbc-data-set";
import {FeedStepConstants} from "./feed-step-constants";
import {NifiFeedPropertyUtil} from "../../services/nifi-feed-property-util";
import {KyloFeed} from '../../../../lib/feed-mgr/model/feed/kylo-feed';
export interface TableOptions {
compress: boolean;
compressionFormat: string;
auditLogging: boolean;
encrypt: boolean;
trackHistory: boolean;
}
export interface FeedSchedule {
schedulingPeriod: string;
schedulingStrategy: string;
concurrentTasks: number;
preconditions: any[],
executionNode: any;
}
export enum FeedMode {
DRAFT="DRAFT", DEPLOYED="DEPLOYED", DEPLDYED_WITH_ACTIVE_DRAFT="DEPLOYED_ACTIVE_DRAFT"
}
export enum FeedState {
NEW = "NEW", ENABLED = "ENABLED", DISABLED = "DISABLED"
}
export enum FeedOperationsState {
RUNNING = "RUNNING", WAITING = "WAITING"
}
export enum FeedTemplateType {
DEFINE_TABLE = "DEFINE_TABLE", DATA_TRANSFORMATION = "DATA_TRANSFORMATION", SIMPLE_FEED = "SIMPLE_FEED"
}
export enum LoadMode {
LATEST="LATEST",DEPLOYED="DEPLOYED",DRAFT="DRAFT"
}
export enum TableMethod {
SAMPLE_FILE="SAMPLE_FILE",EXISTING_TABLE="EXISTING_TABLE",MANUAL="MANUAL"
}
export class FeedAccessControl {
allowEdit:boolean;
allowChangePermissions:boolean;
allowAdmin:boolean;
allowSlaAccess:boolean;
allowExport:boolean;
allowStart:boolean;
/**
* Access to the feed.sourceDataSet
*/
datasourceAccess:boolean;
accessMessage:string;
public constructor(init?: Partial<FeedAccessControl>) {
Object.assign(this, init);
}
static NO_ACCESS = new FeedAccessControl();
allAccess(){
this.accessMessage = '';
this.datasourceAccess = true;
this.allowEdit = true;
this.allowChangePermissions = true;
this.allowAdmin = true;
this.allowSlaAccess = true;
this.allowExport = true;
this.allowStart=true;
return this;
}
static adminAccess = () => new FeedAccessControl().allAccess();
}
export class StepStateChangeEvent {
public changes:ObjectChanged<Step>[] = [];
public constructor(public feed:Feed){}
addChange(oldStep:Step,newStep:Step){
this.changes.push({oldValue:oldStep,newValue:newStep});
}
hasChanges():boolean {
return this.changes.length >0;
}
}
/**
* Key set on the step metadata when a user acknowledges that they want to proceed without selecting a source
* @type {string}
*/
export const SKIP_SOURCE_CATALOG_KEY = "SKIP_SOURCE_CATALOG"
export class Feed implements KyloObject, KyloFeed {
public static OBJECT_TYPE: string = 'Feed'
public objectType: string = Feed.OBJECT_TYPE;
static UI_STATE_STEPS_KEY = "STEPS";
/**
* internal id to track feed instances
*/
userInterfaceId: string;
/**
* What options does the template provide for the feed
*/
templateTableOption: string = null;
/**
* Number of presteps allowed for the feed
* TODO wire into new feed step framework
*/
totalPreSteps: number = 0;
/**
* Wire in for the feed step framework
*/
totalSteps: number = null;
/**
* wire into the feed step framework
*/
renderTemporaryPreStep: boolean = false;
/**
* Steps allowed for the feed
*/
steps: Step[] = [];
/**
* reference to the Template
* TODO ref to Template type
* @TODO IS THIS NEEDED!!!!!
*/
template: any = null;
state: FeedState; //NEW, ENABLED, DISABLED
mode: FeedMode; //DRAFT or DEPLOYED
updateDate: Date;
createdDate:Date;
/**
* The Feed ID
*/
id: string = null;
/**
* The feed version name (1.1, 1.2..)
*/
versionName: string = null;
/**
* The Feed RegisteredTemplateId
*/
templateId: string = '';
/**
* the template name
*/
templateName: string = '';
/**
* the name of the feed
*/
feedName: string = '';
/**
* the system name
* TODO consolidate with systemName?
*/
systemFeedName: string = '';
/**
* Feed Description
*/
description: string = '';
/**
* The class name for the selected input processor (i.e. org.nifi.GetFile)
*/
inputProcessorType: string = '';
/**
* The name of the input processor (i.e. FileSystem)
*/
inputProcessorName: string = null;
inputProcessor: Templates.Processor = null;
inputProcessors: Templates.Processor[] = [];
/**
* The array of all other processors in the feed flow
*/
nonInputProcessors: Templates.Processor[] = [];
/**
* Array of properties
*/
properties: Templates.Property[] = [];
securityGroups: any[] = [];
/**
* The feed schedule
*/
schedule: FeedSchedule = {schedulingPeriod: "0 0 12 1/1 * ? *", schedulingStrategy: 'CRON_DRIVEN', concurrentTasks: 1, preconditions: null, executionNode: null};
/**
* does this feed use a template that requires target table definition
*/
defineTable: boolean = false;
/**
* Does this feed have a template with a TriggerFeed that requires Precondition rendering
*/
allowPreconditions: boolean;
/**
* Does this feed use a Data Transformation template
*/
dataTransformationFeed: boolean;
/**
* The table definitions for the feed
*/
table: FeedTableDefinition;
/**
* A copy of the orig schema if it exists
*/
originalTableSchema:FeedTableSchema;
/**
* Category ref of the feed
*/
category: Category;
/**
* the feed owner
*/
dataOwner: string;
/**
* the feed tags
*/
tags: any[];
/**
* is this a reusable feed?
* TODO REMOVE
* @deprecated
*/
reusableFeed: boolean;
/**
* if this is a DataTransformation feed, the metadata needed for the transform
*/
dataTransformation: FeedDataTransformation;
/**
* Additional properties supplied by the user
*/
userProperties: UserProperty[] = [];
/**
* Additional options (i.e. skipHeader
*/
options: any = {skipHeader: false};
/**
* Is the feed active (enabled)
*/
active: boolean = true;
/**
* Entity Access controls
*/
roleMemberships: any[] = [];
/**
* Entity Access Control owner (different than DataOwnewr property)
*/
owner: string = null;
/**
* flag to indicate the roleMemberships are stale
*/
roleMembershipsUpdated: boolean;
/**
* TODO fill in with desc
*/
tableOption: any = {};
/**
* is this a cloned feed
*/
cloned: boolean;
/**
* What other feeds use this feed
* array of feed system names
*/
usedByFeeds: any[] = [];
/**
* Does this feed allow Reindexing of the data in Global Search
*/
allowIndexing: boolean = true;
/**
* the status of the reindex job if appliciable
*/
historyReindexingStatus: string = 'NEVER_RUN';
/**
* metadata around the view states for this feed.
* Used for feed rendering and plugins
*/
view: any;
registeredTemplate: any;
readonly: boolean;
accessControl:FeedAccessControl;
/**
* The name of the sample file used to parse for table schema
* Optional
*/
sampleFile?: string;
/**
* the name of the schema parser used to build the schema
*/
schemaParser?: SchemaParser;
/**
* Should this feed show the "Skip Header" option
*/
allowSkipHeaderOption: boolean;
/**
* Has the schema changed since creation
*/
schemaChanged?: boolean;
/**
* Source Datasets selected for this feed
* @type {any[]}
*/
sourceDataSets?: SparkDataSet[] = [];
/**
* sample Datasets selected for this feed
* @type {any[]}
*/
sampleDataSet?: SparkDataSet;
/**
* is this a streaming feed
*/
isStream: boolean;
/**
* Have the properties been merged and initialized with the template
*/
propertiesInitialized?: boolean;
isValid: boolean;
/**
* map of userinterface state objects persisted to the feed
*/
uiState: { [key: string]: any; }
/**
* The versionId for the feed
*/
versionId: string;
/**
* The version that is deployed for this feed
* This will be null if this.mode != DRAFT
*/
deployedVersion:EntityVersion
/**
* if we are viewing a deployed versoin and it has a draft
*/
loadMode:LoadMode;
stepChangesSubject = new Subject<StepStateChangeEvent>();
subscribeToStepStateChanges(o:PartialObserver<StepStateChangeEvent>) {
return this.stepChangesSubject.subscribe(o);
}
public constructor(init?: Partial<Feed>) {
this.initialize();
Object.assign(this, init);
if (this.sourceDataSets) {
//ensure they are of the right class objects
if (this.sourceDataSets) {
this.sourceDataSets = this.sourceDataSets.map(ds => new SparkDataSet(ds));
}
}
if (this.sampleDataSet) {
//ensure they are of the right class objects
if (this.sampleDataSet) {
this.sampleDataSet = new SparkDataSet(this.sampleDataSet);
}
}
if (this.uiState == undefined) {
this.uiState = {}
}
//ensure the tableDef model
this.table = ObjectUtils.getAs(this.table, FeedTableDefinition, FeedTableDefinition.OBJECT_TYPE);
this.table.ensureObjectTypes();
this.originalTableSchema = CloneUtil.deepCopy(this.table.tableSchema)
if (this.isDataTransformation()) {
//ensure types
this.dataTransformation = ObjectUtils.getAs(this.dataTransformation, DefaultFeedDataTransformation, DefaultFeedDataTransformation.OBJECT_TYPE);
}
this.userInterfaceId = _.uniqueId("feed-");
if(this.registeredTemplate){
this.isStream = this.registeredTemplate.isStream
}
}
getCountOfTemplateInputProcessors() :number{
return this.registeredTemplate && this.registeredTemplate.inputProcessors ? this.registeredTemplate.inputProcessors.length : 0;
}
renderSourceStep()
{
let sourceStep = this.getStepBySystemName(FeedStepConstants.STEP_FEED_SOURCE);
let render = !this.isDataTransformation() || (this.isDataTransformation() && this.getCountOfTemplateInputProcessors() >1 );
return render;
}
getFullName(){
return this.category.systemName+"."+this.systemFeedName;
}
getFeedNameAndVersion(){
if(this.isDraft()){
return this.feedName+" - DRAFT";
}
else {
return this.feedName + "- v"+this.versionName;
}
}
updateNonNullFields(model: any) {
let keys = Object.keys(model);
let obj = {}
keys.forEach((key: string) => {
if (model[key] && model[key] != null) {
obj[key] = model[key];
}
});
Object.assign(this, obj);
}
update(model: Partial<Feed>): void {
//keep the internal ids saved for the table.tableSchema.fields and table.partitions
let oldFields = <TableColumnDefinition[]>this.table.feedDefinitionTableSchema.fields;
let oldPartitions = this.table.partitions;
let oldUserProperties = this.userProperties;
this.updateNonNullFields(model);
this.table.update(oldFields, oldPartitions);
UserPropertyUtil.updatePropertyIds(oldUserProperties, this.userProperties);
}
initialize() {
this.readonly = true;
this.accessControl = FeedAccessControl.NO_ACCESS;
this.systemFeedName = '';
this.feedName = '';
this.mode = FeedMode.DRAFT;
this.category = {id: null, name: null, systemName: null, description: null};
this.table = new FeedTableDefinition()
this.dataTransformation = new DefaultFeedDataTransformation();
this.view = {
generalInfo: {disabled: false},
feedDetails: {disabled: false},
table: {disabled: false},
dataPolicies: {disabled: false},
properties: {
disabled: false,
dataOwner: {disabled: false},
tags: {disabled: false}
},
accessControl: {disabled: false},
schedule: {
disabled: false,
schedulingPeriod: {disabled: false},
schedulingStrategy: {disabled: false},
active: {disabled: false},
executionNode: {disabled: false},
preconditions: {disabled: false}
},
uiState: {}
};
this.loadMode = LoadMode.LATEST;
}
isNew() {
return this.id == undefined;
}
/**
* Does this draft feed have a deployed version
* @return {boolean}
*/
hasBeenDeployed(){
return (!this.isDraft()) ||
(this.isDraft() && !_.isUndefined(this.deployedVersion) && !_.isUndefined(this.deployedVersion.id));
}
isDraft(){
return this.mode == FeedMode.DRAFT
}
isDeployed(){
return this.mode == FeedMode.DEPLOYED || this.mode == FeedMode.DEPLDYED_WITH_ACTIVE_DRAFT;
}
isDeployedWithActiveDraft() {
return this.mode == FeedMode.DEPLDYED_WITH_ACTIVE_DRAFT;
}
getStepBySystemName(stepName: string) {
return this.steps.find(step => step.systemName == stepName);
}
validate(updateStepState?: boolean): boolean {
let valid = true;
let model = this;
let disabledSteps: Step[] = [];
//copy off the old steps
let copySteps = this._copySteps();
let stepMap = _.indexBy(copySteps,'systemName');
let changes = new StepStateChangeEvent(this);
this.steps.forEach((step: Step) => {
if(!step.hidden) {
valid = valid && step.validate(<Feed>this);
if (updateStepState) {
step.updateStepState().forEach(step => disabledSteps.push(step));
}
}
});
let enabledSteps = this.steps.filter(step => disabledSteps.indexOf(step) == -1);
enabledSteps.forEach(step => step.disabled = false);
//detect step changes
this.steps.forEach((step:Step) => {
let oldStep = stepMap[step.systemName];
if(oldStep && step.isStepStateChange(oldStep)){
changes.addChange(oldStep,step);
}
});
this.isValid = valid;
if(changes.hasChanges()){
this.stepChangesSubject.next(changes);
}
return valid;
}
getTemplateType(): string {
return this.templateTableOption ? this.templateTableOption : (this.registeredTemplate ? this.registeredTemplate.templateTableOption : '')
}
/**
* is this a feed to define a target table
* @return {boolean}
*/
isDefineTable() {
return FeedTemplateType.DEFINE_TABLE == this.getTemplateType();
}
/**
* Is this a data transformation feed
* @return {boolean}
*/
isDataTransformation() {
return FeedTemplateType.DATA_TRANSFORMATION == this.getTemplateType();
}
/**
* Does this feed have any data transformation sets defined
* @return {boolean}
*/
hasDataTransformationDataSets() {
return this.isDataTransformation() && this.dataTransformation && this.dataTransformation.datasets && this.dataTransformation.datasets.length > 0;
}
/**
* Are all the steps for this feed complete
* @return {boolean}
*/
isComplete() {
let complete = true;
this.steps.filter(step => !step.hidden).forEach(step => complete = complete && step.complete);
return complete;
}
/**
* Is the feed editable
* Does the user have access to edit and make sure its not a 'deployed' feed
* @return {boolean}
*/
canEdit(){
return this.accessControl.allowEdit && this.loadMode != LoadMode.DEPLOYED;
}
/**
* Sets the table method as to where the target table was build from (i.e. database, sample file, manual)
* @param {TableMethod | string} method
*/
setTableMethod(method:(TableMethod | string)){
this.table.method = method;
if(method == TableMethod.EXISTING_TABLE){
this.options.skipHeader = true;
}
}
/**
* mark the data as structured (i.e. JSON, or not (CSV) )
* @param {boolean} structured
*/
structuredData(structured:boolean){
this.table.structured = structured;
if(structured){
this.options.skipHeader = false;
}
else {
this.options.skipHeader = true;
}
}
/**
* returns the array of paths used for the source sample preview
* will return an empty array of no paths are used
* @return {string[]}
*/
getSourcePaths(): string[] {
let paths: string[] = [];
if (this.sourceDataSets && this.sourceDataSets.length > 0) {
//get the array of paths to use
paths = this.sourceDataSets.map((dataset: SparkDataSet) => {
return dataset.resolvePaths();
}).reduce((a: string[], b: string[]) => {
return a.concat(b);
}, []);
}
return paths;
}
private _copySteps():Step[]{
//steps have self references back to themselves.
let allSteps: Step[] = [];
this.steps.forEach(step => {
let copy = step.shallowCopy();
allSteps.push(copy);
copy.allSteps = allSteps;
});
return allSteps;
}
/**
* Deep copy of this object
* @return {Feed}
*/
copy(keepCircularReference: boolean = true): Feed {
let allSteps = this._copySteps();
let newFeed: Feed = new Feed(this)
// Object.assign(newFeed,this)
newFeed.steps = null;
let copy: Feed;
if (keepCircularReference) {
copy = CloneUtil.deepCopy(newFeed);
}
else {
copy = CloneUtil.deepCopyWithoutCircularReferences(newFeed);
}
copy.steps = allSteps;
return copy;
}
/**
* Return a copy of this model that is stripped of un necessary properties ready to be saved
* @param {Feed} copy
* @return {Feed}
*/
copyModelForSave(): Feed {
//create a deep copy
let copy = this.copy();
copy.stepChangesSubject = undefined;
copy.originalTableSchema = undefined;
//only do this if the schema could have changed (i.e. never been deployed)
if (copy.table && copy.table.feedDefinitionFieldPolicies && copy.table.feedDefinitionTableSchema && copy.table.feedDefinitionTableSchema.fields) {
//if the sourceSchema is not defined then set it to match the target
let addSourceSchemaFields: boolean = copy.table.sourceTableSchema.fields.length == 0;
let addFeedSchemaFields = copy.table.feedTableSchema.fields.length == 0;
/**
* Undeleted fields
* @type {any[]}
*/
let tableFields: TableColumnDefinition[] = [];
/**
* Field Policies ensuring the names match the column fields
* @type {any[]}
*/
var newPolicies: TableFieldPolicy[] = [];
/**
* Feed Schema
* @type {any[]}
*/
var feedFields: TableColumnDefinition[] = [];
/**
* Source Schema
* @type {any[]}
*/
var sourceFields: TableColumnDefinition[] = [];
copy.table.feedDefinitionTableSchema.fields.forEach((columnDef: TableColumnDefinition, idx: number) => {
let sourceField: TableColumnDefinition = columnDef.copy();
let feedField: TableColumnDefinition = columnDef.copy();
//set the original names as the source field names
sourceField.name = columnDef.origName;
sourceField.derivedDataType = columnDef.origDataType;
//remove sample
sourceField.prepareForSave();
feedField.prepareForSave();
// structured files must use the original names
if (copy.table.structured == true) {
feedField.name = columnDef.origName;
feedField.derivedDataType = columnDef.origDataType;
}
if (!columnDef.deleted) {
//remove sample
columnDef.prepareForSave();
tableFields.push(columnDef);
let policy = copy.table.feedDefinitionFieldPolicies[idx];
if (policy) {
policy.feedFieldName = feedField.name;
policy.name = columnDef.name;
policy.field = null;
newPolicies.push(policy);
}
sourceFields.push(sourceField)
feedFields.push(feedField)
}
else {
// For files the feed table must contain all the columns from the source even if unused in the target
if (copy.table.method == 'SAMPLE_FILE' || copy.isDataTransformation()) {
feedFields.push(feedField);
}
//if we somehow deleted the source incremental field from the target we need to push it back into the source map
if( sourceField.name == copy.table.sourceTableIncrementalDateField) {
feedFields.push(feedField);
sourceFields.push(sourceField);
} else if(copy.table.method == "EXISTING_TABLE"){
sourceFields.push(sourceField);
}
}
/*
// For files the feed table must contain all the columns from the source even if unused in the target
if (copy.table.method == 'SAMPLE_FILE') {
feedFields.push(feedField);
} else if (copy.table.method == 'EXISTING_TABLE' && copy.table.sourceTableIncrementalDateField == sourceField.name) {
feedFields.push(feedField);
sourceFields.push(sourceField);
}
*/
});
//update the table schema and policies
copy.table.fieldPolicies = newPolicies;
copy.table.tableSchema.fields = tableFields;
if (copy.table.sourceTableSchema == undefined) {
copy.table.sourceTableSchema = new SourceTableSchema();
}
if (copy.table.feedTableSchema == undefined) {
copy.table.feedTableSchema = new FeedTableSchema();
}
//ensure the source and feed tables match those defined by this feed
if (!this.hasBeenDeployed() && sourceFields.length != 0 ) {
copy.table.sourceTableSchema.fields = sourceFields;
}
if (!this.hasBeenDeployed() && feedFields.length != 0 ) {
copy.table.feedTableSchema.fields = feedFields;
}
if (copy.registeredTemplate) {
copy.registeredTemplate = undefined;
}
}
if (copy.inputProcessor != null) {
_.each(copy.inputProcessor.properties, (property: any) => {
NifiFeedPropertyUtil.initSensitivePropertyForSaving(property)
// properties.push(property);
});
}
_.each(copy.nonInputProcessors, (processor: any) => {
_.each(processor.properties, (property: any) => {
NifiFeedPropertyUtil.initSensitivePropertyForSaving(property)
// properties.push(property);
});
});
return copy;
}
/**
* updates the target and or source with the schem provided in the sourceDataSet
*/
setSourceDataSetAndUpdateTarget(sourceDataSet: SparkDataSet, mode: TableSchemaUpdateMode = TableSchemaUpdateMode.UPDATE_SOURCE_AND_TARGET, connectorPlugin?: ConnectorPlugin) {
if (sourceDataSet && sourceDataSet != null) {
this.sourceDataSets = [sourceDataSet];
}
this.updateTarget(sourceDataSet)
}
/**
* updates the target and or source with the schem provided in the sourceDataSet
*/
setSampleDataSetAndUpdateTarget(sampleDataSet: SparkDataSet, previewDataSet: PreviewDataSet,mode: TableSchemaUpdateMode = TableSchemaUpdateMode.UPDATE_SOURCE_AND_TARGET, connectorPlugin?: ConnectorPlugin) {
this.sampleDataSet = sampleDataSet;
this.updateTarget(sampleDataSet)
if(previewDataSet){
let sampleFile = previewDataSet instanceof PreviewFileDataSet;
let table = previewDataSet instanceof PreviewHiveDataSet || previewDataSet instanceof PreviewJdbcDataSet;
if(sampleFile) {
this.table.method = "SAMPLE_FILE";
if(!(previewDataSet as PreviewFileDataSet).schemaParser.allowSkipHeader) {
this.options.skipHeader = false
}
}
else if(table) {
this.table.method = "EXISTING_TABLE";
}
}
}
/**
* updates the target and or source with the schem provided in the sourceDataSet
*/
updateTarget(sourceDataSet: SparkDataSet, mode: TableSchemaUpdateMode = TableSchemaUpdateMode.UPDATE_SOURCE_AND_TARGET, connectorPlugin?: ConnectorPlugin) {
if (sourceDataSet && sourceDataSet != null) {
let dataSet = sourceDataSet
let sourceColumns: TableColumnDefinition[] = [];
let targetColumns: TableColumnDefinition[] = [];
let feedColumns: TableColumnDefinition[] = [];
let columns: TableColumn[] = dataSet.schema
if (columns) {
columns.forEach(col => {
let def = _.extend({}, col);
def.derivedDataType = def.dataType;
//sample data
if (dataSet.preview && dataSet.preview.preview) {
let sampleValues: string[] = dataSet.preview.preview.columnData(def.name)
def.sampleValues = sampleValues
}
sourceColumns.push(new TableColumnDefinition((def)));
targetColumns.push(new TableColumnDefinition((def)));
feedColumns.push(new TableColumnDefinition((def)));
});
}
else {
//WARN Columns are empty.
//console.log("EMPTY columns for ", dataSet);
}
if (TableSchemaUpdateMode.UPDATE_SOURCE == mode || TableSchemaUpdateMode.UPDATE_SOURCE_AND_TARGET == mode) {
this.table.sourceTableSchema.fields = sourceColumns;
}
if (TableSchemaUpdateMode.UPDATE_TARGET == mode || TableSchemaUpdateMode.UPDATE_SOURCE_AND_TARGET == mode) {
this.table.feedTableSchema.fields = feedColumns;
this.table.tableSchema.fields = targetColumns;
this.table.feedDefinitionTableSchema.fields = targetColumns;
this.table.feedDefinitionFieldPolicies = targetColumns.map(field => {
let policy = TableFieldPolicy.forName(field.name);
policy.field = field;
field.fieldPolicy = policy;
return policy;
});
//flip the changed flag
this.table.schemaChanged = true;
}
// Update NiFi properties based on Spark data set
if (connectorPlugin != null && connectorPlugin.nifiProperties != null) {
const renderingHelper = new FeedDetailsProcessorRenderingHelper();
// Find matching NiFi input processor
let connectorProperties: ConnectorPluginNifiProperties = null;
let inputProcessor = this.inputProcessors.find(processor => {
connectorProperties = connectorPlugin.nifiProperties.find(properties =>
properties.processorTypes.indexOf(processor.type) > -1
|| (
renderingHelper.isWatermarkProcessor(processor)
&& (
properties.processorTypes.indexOf(renderingHelper.GET_TABLE_DATA_PROCESSOR_TYPE) > -1
|| properties.processorTypes.indexOf(renderingHelper.GET_TABLE_DATA_PROCESSOR_TYPE2) > -1
|| properties.processorTypes.indexOf(renderingHelper.SQOOP_PROCESSOR) > -1
)
)
);
return typeof connectorProperties !== "undefined";
});
// Update feed properties
if (typeof inputProcessor !== "undefined") {
this.inputProcessor = inputProcessor;
let propertiesProcessor = inputProcessor;
if (renderingHelper.isWatermarkProcessor(inputProcessor)) {
propertiesProcessor = this.nonInputProcessors.find(processor => renderingHelper.isGetTableDataProcessor(processor) || renderingHelper.isSqoopProcessor(processor));
}
if (typeof propertiesProcessor !== "undefined") {
const context = {...sourceDataSet.mergeTemplates(), dataSource: sourceDataSet.dataSource};
propertiesProcessor.properties.filter(property => property.userEditable).forEach(inputProperty => {
if (typeof connectorProperties.properties[inputProperty.key] !== "undefined") {
const valueFn = _.template(connectorProperties.properties[inputProperty.key], {escape: null, interpolate: /\{\{(.+?)\}\}/g, evaluate: null});
inputProperty.value = valueFn(context);
}
});
}
}
}
}
else {
if (TableSchemaUpdateMode.UPDATE_SOURCE == mode || TableSchemaUpdateMode.UPDATE_SOURCE_AND_TARGET == mode) {
this.sourceDataSets = [];
this.table.sourceTableSchema.fields = [];
}
if (TableSchemaUpdateMode.UPDATE_TARGET == mode || TableSchemaUpdateMode.UPDATE_SOURCE_AND_TARGET == mode) {
this.table.feedTableSchema.fields = [];
this.table.tableSchema.fields = [];
this.table.feedDefinitionTableSchema.fields = [];
this.table.feedDefinitionFieldPolicies = [];
}
}
}
validateSchemaDidNotChange(fields?:TableColumnDefinition[]| SchemaField[]){
var valid = true;
if(fields == undefined && this.table){
fields = this.table.feedDefinitionTableSchema.fields
}
//if we are editing we need to make sure we dont modify the originalTableSchema
if(this.hasBeenDeployed() && this.originalTableSchema && fields) {
//if model.originalTableSchema != model.table.tableSchema ... ERROR
//mark as invalid if they dont match
var origFields = _.chain(this.originalTableSchema.fields).sortBy('name').map(function (i) {
return i.name + " " + i.derivedDataType;
}).value().join()
var updatedFields = _.chain(fields).sortBy('name').map(function (i) {
return i.name + " " + i.derivedDataType;
}).value().join()
valid = origFields == updatedFields;
}
this.table.schemaChanged = !valid;
return valid
}
} | the_stack |
import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { DatePipe } from '@angular/common';
import {
ActivatedRoute,
Router,
RouterEvent,
NavigationEnd
} from '@angular/router';
import { NbDialogService } from '@nebular/theme';
import { TranslateService } from '@ngx-translate/core';
import { filter, first, tap } from 'rxjs/operators';
import { LocalDataSource, Ng2SmartTableComponent } from 'ng2-smart-table';
import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy';
import {
IEmployee,
IOrganization,
IOrganizationContact,
IOrganizationProject,
IOrganizationProjectsCreateInput,
PermissionsEnum,
ComponentLayoutStyleEnum,
CrudActionEnum
} from '@gauzy/contracts';
import { TranslationBaseComponent } from '../../@shared/language-base';
import {
EmployeesService,
OrganizationContactService,
OrganizationProjectsService,
OrganizationProjectStore,
Store,
ToastrService
} from '../../@core/services';
import { ComponentEnum } from '../../@core/constants';
import { PictureNameTagsComponent } from '../../@shared/table-components';
import { DeleteConfirmationComponent } from '../../@shared/user/forms';
@UntilDestroy({ checkProperties: true })
@Component({
selector: 'ga-projects',
templateUrl: './projects.component.html',
styleUrls: ['./projects.component.scss']
})
export class ProjectsComponent
extends TranslationBaseComponent
implements OnInit, OnDestroy {
loading: boolean;
settingsSmartTable: object;
viewComponentName: ComponentEnum;
dataLayoutStyle = ComponentLayoutStyleEnum.CARDS_GRID;
organization: IOrganization;
showAddCard: boolean;
projects: IOrganizationProject[] = [];
organizationContacts: IOrganizationContact[] = [];
employees: IEmployee[] = [];
projectToEdit: IOrganizationProject;
viewPrivateProjects: boolean;
disableButton = true;
selectedProject: IOrganizationProject;
smartTableSource = new LocalDataSource();
projectsTable: Ng2SmartTableComponent;
@ViewChild('projectsTable') set content(content: Ng2SmartTableComponent) {
if (content) {
this.projectsTable = content;
this.onChangedSource();
}
}
constructor(
private readonly organizationContactService: OrganizationContactService,
private readonly organizationProjectsService: OrganizationProjectsService,
private readonly toastrService: ToastrService,
private readonly store: Store,
private readonly employeesService: EmployeesService,
public readonly translateService: TranslateService,
private readonly route: ActivatedRoute,
private readonly router: Router,
private readonly dialogService: NbDialogService,
private readonly organizationProjectStore: OrganizationProjectStore
) {
super(translateService);
this.setView();
}
ngOnInit(): void {
this.loadSmartTable();
this._applyTranslationOnSmartTable();
this.store.selectedOrganization$
.pipe(
filter((organization) => !!organization),
tap(
(organization: IOrganization) =>
(this.organization = organization)
),
tap(() => this._initMethod()),
untilDestroyed(this)
)
.subscribe();
this.store.userRolePermissions$
.pipe(untilDestroyed(this))
.subscribe(() => {
this.viewPrivateProjects = this.store.hasPermission(
PermissionsEnum.ACCESS_PRIVATE_PROJECTS
);
});
this.router.events
.pipe(untilDestroyed(this))
.subscribe((event: RouterEvent) => {
if (event instanceof NavigationEnd) {
this.setView();
}
});
this.route.queryParamMap
.pipe(untilDestroyed(this))
.subscribe((params) => {
if (params.get('openAddDialog')) {
this.showAddCard =
params.get('openAddDialog') === 'true' ? true : false;
this._initMethod();
}
});
}
ngOnDestroy() {}
private _initMethod() {
if (!this.organization) {
return;
}
this.loadProjects();
this.loadEmployees();
this.loadOrganizationContacts();
}
private async loadEmployees() {
const { tenantId } = this.store.user;
const { id: organizationId } = this.organization;
const { items } = await this.employeesService
.getAll(['user'], {
organization: { id: organizationId },
tenantId
})
.pipe(first())
.toPromise();
this.employees = items;
}
setView() {
this.viewComponentName = ComponentEnum.PROJECTS;
this.store
.componentLayout$(this.viewComponentName)
.pipe(untilDestroyed(this))
.subscribe((componentLayout) => {
this.dataLayoutStyle = componentLayout;
this.selectedProject =
this.dataLayoutStyle === 'CARDS_GRID'
? null
: this.selectedProject;
});
}
async removeProject(id?: string, name?: string) {
const result = await this.dialogService
.open(DeleteConfirmationComponent, {
context: {
recordType: 'Project'
}
})
.onClose.pipe(first())
.toPromise();
if (result) {
await this.organizationProjectsService
.delete(this.selectedProject ? this.selectedProject.id : id)
.then(() => {
this.organizationProjectStore.organizationProjectAction = {
project: this.selectedProject,
action: CrudActionEnum.DELETED
};
});
this.toastrService.success(
'NOTES.ORGANIZATIONS.EDIT_ORGANIZATIONS_PROJECTS.REMOVE_PROJECT',
{
name: this.selectedProject
? this.selectedProject.name
: name
}
);
this.loadProjects();
}
}
cancel() {
this.projectToEdit = null;
this.showAddCard = false;
this.selectProject({
isSelected: false,
data: null
});
}
public async addOrEditProject({
action,
project
}: {
action: 'add' | 'edit';
project: IOrganizationProjectsCreateInput;
}) {
switch (action) {
case 'add':
if (project.name) {
await this.organizationProjectsService
.create(project)
.then((project: IOrganizationProject) => {
this.organizationProjectStore.organizationProjectAction = {
project,
action: CrudActionEnum.CREATED
};
});
} else {
this.toastrService.danger(
this.getTranslation(
'NOTES.ORGANIZATIONS.EDIT_ORGANIZATIONS_PROJECTS.INVALID_PROJECT_NAME'
),
this.getTranslation(
'TOASTR.MESSAGE.NEW_ORGANIZATION_PROJECT_INVALID_NAME'
)
);
}
break;
case 'edit':
await this.organizationProjectsService
.edit(project)
.then((project: IOrganizationProject) => {
this.organizationProjectStore.organizationProjectAction = {
project,
action: CrudActionEnum.UPDATED
};
});
break;
}
this.toastrService.success(
'NOTES.ORGANIZATIONS.EDIT_ORGANIZATIONS_PROJECTS.ADD_PROJECT',
{
name: project.name
}
);
this.cancel();
this.loadProjects();
}
async loadProjects() {
this.loading = true;
const { tenantId } = this.store.user;
const { id: organizationId } = this.organization;
this.organizationProjectsService
.getAll(
['organizationContact', 'members', 'members.user', 'tags'],
{ organizationId, tenantId }
)
.then(({ items }) => {
const canView = [];
if (this.viewPrivateProjects) {
this.projects = items;
this.smartTableSource.load(items);
} else {
items.forEach((item) => {
if (item.public) {
canView.push(item);
} else {
item.members.forEach((member) => {
if (member.id === this.store.userId) {
canView.push(item);
}
});
}
});
this.projects = canView;
}
})
.finally(() => {
this.loading = false;
});
}
async loadSmartTable() {
this.settingsSmartTable = {
noDataMessage: this.getTranslation('SM_TABLE.NO_DATA'),
actions: false,
columns: {
name: {
title: this.getTranslation('ORGANIZATIONS_PAGE.NAME'),
type: 'custom',
renderComponent: PictureNameTagsComponent
},
projectUrl: {
title: this.getTranslation(
'ORGANIZATIONS_PAGE.EDIT.PROJECT_URL'
),
type: 'text'
},
organizationContact: {
title: this.getTranslation(
'ORGANIZATIONS_PAGE.EDIT.CONTACT'
),
type: 'string',
class: 'text-center',
valuePrepareFunction: (value, item) => {
if (item.hasOwnProperty('organizationContact')) {
return item.organizationContact
? item.organizationContact.name
: null;
}
return value;
}
},
startDate: {
title: this.getTranslation(
'ORGANIZATIONS_PAGE.EDIT.START_DATE'
),
type: 'date',
filter: false,
valuePrepareFunction: (date) =>
new DatePipe('en-GB').transform(date, 'dd/MM/yyyy'),
class: 'text-center'
},
endDate: {
title: this.getTranslation(
'ORGANIZATIONS_PAGE.EDIT.END_DATE'
),
type: 'date',
filter: false,
valuePrepareFunction: (date) =>
new DatePipe('en-GB').transform(date, 'dd/MM/yyyy'),
class: 'text-center'
},
billing: {
title: this.getTranslation(
'ORGANIZATIONS_PAGE.EDIT.BILLING'
),
type: 'string',
filter: false
},
currency: {
title: this.getTranslation(
'ORGANIZATIONS_PAGE.EDIT.CURRENCY'
),
type: 'string',
filter: false
},
owner: {
title: this.getTranslation('ORGANIZATIONS_PAGE.EDIT.OWNER'),
type: 'string',
filter: false
}
}
};
}
async selectProject({ isSelected, data }) {
this.disableButton = !isSelected;
this.selectedProject = isSelected ? data : null;
}
_applyTranslationOnSmartTable() {
this.translateService.onLangChange
.pipe(untilDestroyed(this))
.subscribe(() => {
this.loadSmartTable();
});
}
private loadOrganizationContacts() {
const { tenantId } = this.store.user;
const { id: organizationId } = this.organization;
this.organizationContactService
.getAll(['projects'], {
organizationId,
tenantId
})
.then(({ items }) => {
this.organizationContacts = items;
});
}
async editProject(project: IOrganizationProject) {
this.projectToEdit = project;
this.showAddCard = true;
}
/*
* Table on changed source event
*/
onChangedSource() {
this.projectsTable.source.onChangedSource
.pipe(
untilDestroyed(this),
tap(() => this.clearItem())
)
.subscribe();
}
/*
* Clear selected item
*/
clearItem() {
this.selectProject({
isSelected: false,
data: null
});
this.deselectAll();
}
/*
* Deselect all table rows
*/
deselectAll() {
if (this.projectsTable && this.projectsTable.grid) {
this.projectsTable.grid.dataSet['willSelect'] = 'false';
this.projectsTable.grid.dataSet.deselectAll();
}
}
} | the_stack |
import {
render,
RenderOptions,
RenderResult,
screen,
waitFor,
within,
} from "@testing-library/react"
import userEvent from "@testing-library/user-event"
import React from "react"
import { MemoryRouter } from "react-router"
import { AnalyticsAction } from "./analytics"
import {
cleanupMockAnalyticsCalls,
expectIncrs,
mockAnalyticsCalls,
} from "./analytics_test_helpers"
import { accessorsForTesting, tiltfileKeyContext } from "./BrowserStorage"
import Features, { FeaturesTestProvider, Flag } from "./feature"
import LogStore from "./LogStore"
import PathBuilder from "./PathBuilder"
import { ResourceGroupsContextProvider } from "./ResourceGroupsContext"
import {
DEFAULT_OPTIONS,
ResourceListOptions,
ResourceListOptionsProvider,
RESOURCE_LIST_OPTIONS_KEY,
} from "./ResourceListOptionsContext"
import SidebarItem from "./SidebarItem"
import SidebarResources from "./SidebarResources"
import { StarredResourcesContextProvider } from "./StarredResourcesContext"
import { nResourceView, nResourceWithLabelsView, oneResource } from "./testdata"
import { ResourceStatus, ResourceView } from "./types"
let pathBuilder = PathBuilder.forTesting("localhost", "/")
const resourceListOptionsAccessor = accessorsForTesting<ResourceListOptions>(
RESOURCE_LIST_OPTIONS_KEY,
sessionStorage
)
const starredItemsAccessor = accessorsForTesting<string[]>(
"pinned-resources",
localStorage
)
function createSidebarItems(n: number, withLabels = false) {
const logStore = new LogStore()
const resourceView = withLabels ? nResourceWithLabelsView : nResourceView
const resources = resourceView(n).uiResources
return resources.map((r) => new SidebarItem(r, logStore))
}
function createSidebarItemsWithAlerts() {
const logStore = new LogStore()
return [
oneResource({ isBuilding: true }),
oneResource({ name: "a" }),
oneResource({ name: "b" }),
oneResource({ name: "c", disabled: true }),
].map((res) => new SidebarItem(res, logStore))
}
function customRender(
componentOptions: {
items: SidebarItem[]
selected?: string
resourceListOptions?: ResourceListOptions
},
renderOptions?: RenderOptions
) {
const features = new Features({
[Flag.Labels]: true,
})
const listOptions = componentOptions.resourceListOptions ?? DEFAULT_OPTIONS
return render(
<SidebarResources
items={componentOptions.items}
selected={componentOptions.selected ?? ""}
resourceView={ResourceView.Log}
pathBuilder={pathBuilder}
resourceListOptions={listOptions}
/>,
{
wrapper: ({ children }) => (
<MemoryRouter>
<tiltfileKeyContext.Provider value="test">
<FeaturesTestProvider value={features}>
<StarredResourcesContextProvider>
<ResourceGroupsContextProvider>
<ResourceListOptionsProvider>
{children}
</ResourceListOptionsProvider>
</ResourceGroupsContextProvider>
</StarredResourcesContextProvider>
</FeaturesTestProvider>
</tiltfileKeyContext.Provider>
</MemoryRouter>
),
...renderOptions,
}
)
}
describe("SidebarResources", () => {
beforeEach(() => {
mockAnalyticsCalls()
sessionStorage.clear()
localStorage.clear()
})
afterEach(() => {
cleanupMockAnalyticsCalls()
sessionStorage.clear()
localStorage.clear()
})
describe("starring resources", () => {
const items = createSidebarItems(2)
it("adds items to the starred list when items are starred", async () => {
const itemToStar = items[1].name
customRender({ items: items })
userEvent.click(
screen.getByRole("button", { name: `Star ${itemToStar}` })
)
await waitFor(() => {
expect(starredItemsAccessor.get()).toEqual([itemToStar])
})
expectIncrs(
{
name: "ui.web.star",
tags: { starCount: "0", action: AnalyticsAction.Load },
},
{
name: "ui.web.sidebarStarButton",
tags: {
action: AnalyticsAction.Click,
newStarState: "true",
target: "k8s",
},
},
{
name: "ui.web.star",
tags: { starCount: "1", action: AnalyticsAction.Star },
}
)
})
it("removes items from the starred list when items are unstarred", async () => {
starredItemsAccessor.set(items.map((i) => i.name))
customRender({ items })
userEvent.click(
screen.getByRole("button", { name: `Unstar ${items[1].name}` })
)
await waitFor(() => {
expect(starredItemsAccessor.get()).toEqual([items[0].name])
})
expectIncrs(
{
name: "ui.web.star",
tags: { starCount: "2", action: AnalyticsAction.Load },
},
{
name: "ui.web.sidebarStarButton",
tags: {
action: AnalyticsAction.Click,
newStarState: "false",
target: "k8s",
},
},
{
name: "ui.web.star",
tags: { starCount: "1", action: AnalyticsAction.Unstar },
}
)
})
})
describe("resource list options", () => {
const items = createSidebarItemsWithAlerts()
const loadCases: [string, ResourceListOptions, string[]][] = [
[
"alertsOnTop",
{ ...DEFAULT_OPTIONS, alertsOnTop: true },
["vigoda", "a", "b"],
],
[
"resourceNameFilter",
{ ...DEFAULT_OPTIONS, resourceNameFilter: "vig" },
["vigoda"],
],
[
"showDisabledResources",
{ ...DEFAULT_OPTIONS, showDisabledResources: true },
["vigoda", "a", "b", "c"],
],
]
test.each(loadCases)(
"loads %p from browser storage",
(_name, resourceListOptions, expectedItems) => {
resourceListOptionsAccessor.set(resourceListOptions)
customRender({ items, resourceListOptions })
// Find the sidebar items for the expected list
expectedItems.forEach((item) => {
expect(screen.getByText(item, { exact: true })).toBeInTheDocument()
})
// Check that each option reflects the storage value
const aotToggle = screen.getByLabelText("Alerts on top")
expect((aotToggle as HTMLInputElement).checked).toBe(
resourceListOptions.alertsOnTop
)
const resourceNameFilter = screen.getByPlaceholderText(
"Filter resources by name"
)
expect(resourceNameFilter).toHaveValue(
resourceListOptions.resourceNameFilter
)
const disabledToggle = screen.getByLabelText("Show disabled resources")
expect(disabledToggle).toBeTruthy()
expect((disabledToggle as HTMLInputElement).checked).toBe(
resourceListOptions.showDisabledResources
)
}
)
const saveCases: [string, ResourceListOptions][] = [
["alertsOnTop", { ...DEFAULT_OPTIONS, alertsOnTop: true }],
["resourceNameFilter", { ...DEFAULT_OPTIONS, resourceNameFilter: "foo" }],
[
"showDisabledResources",
{ ...DEFAULT_OPTIONS, showDisabledResources: true },
],
]
test.each(saveCases)(
"saves option %s to browser storage",
(_name, expectedOptions) => {
customRender({ items })
const aotToggle = screen.getByLabelText("Alerts on top")
if (
(aotToggle as HTMLInputElement).checked !==
expectedOptions.alertsOnTop
) {
userEvent.click(aotToggle)
}
const resourceNameFilter = screen.getByPlaceholderText(
"Filter resources by name"
)
if (expectedOptions.resourceNameFilter) {
userEvent.type(resourceNameFilter, expectedOptions.resourceNameFilter)
}
const disabledToggle = screen.getByLabelText("Show disabled resources")
if (
(disabledToggle as HTMLInputElement).checked !==
expectedOptions.showDisabledResources
) {
userEvent.click(disabledToggle)
}
const observedOptions = resourceListOptionsAccessor.get()
expect(observedOptions).toEqual(expectedOptions)
}
)
})
describe("disabled resources", () => {
describe("when feature flag is enabled and `showDisabledResources` option is true", () => {
let rerender: RenderResult["rerender"]
beforeEach(() => {
// Create a list of sidebar items with disable resources interspersed
const items = createSidebarItems(5)
items[1].runtimeStatus = ResourceStatus.Disabled
items[3].runtimeStatus = ResourceStatus.Disabled
rerender = customRender({
items,
resourceListOptions: {
...DEFAULT_OPTIONS,
showDisabledResources: true,
},
}).rerender
})
it("displays disabled resources list title", () => {
expect(
screen.getByText("Disabled", { exact: true })
).toBeInTheDocument()
})
it("displays disabled resources in their own list", () => {
// Get the disabled resources list and query within it
const disabledResourceList = screen.getByLabelText("Disabled resources")
expect(within(disabledResourceList).getByText("_1")).toBeInTheDocument()
expect(within(disabledResourceList).getByText("_3")).toBeInTheDocument()
})
describe("when there is a resource name filter", () => {
beforeEach(() => {
// Create a list of sidebar items with disable resources interspersed
const itemsWithFilter = createSidebarItems(11)
itemsWithFilter[1].runtimeStatus = ResourceStatus.Disabled
itemsWithFilter[3].runtimeStatus = ResourceStatus.Disabled
itemsWithFilter[8].runtimeStatus = ResourceStatus.Disabled
const options = {
resourceNameFilter: "1",
alertsOnTop: true,
showDisabledResources: true,
}
rerender(
<SidebarResources
items={itemsWithFilter}
selected=""
resourceView={ResourceView.Log}
pathBuilder={pathBuilder}
resourceListOptions={options}
/>
)
})
it("displays disabled resources that match the filter", () => {
// Expect that all matching resources (enabled + disabled) are displayed
expect(screen.getByText("_1", { exact: true })).toBeInTheDocument()
expect(screen.getByText("_10", { exact: true })).toBeInTheDocument()
// Expect that all disabled resources appear in their own section
const disabledItemsList = screen.getByLabelText("Disabled resources")
expect(within(disabledItemsList).getByText("_1")).toBeInTheDocument()
})
})
describe("when there are groups and multiple groups have disabled resources", () => {
it("displays disabled resources within each group", () => {
const itemsWithLabels = createSidebarItems(10, true)
// Add disabled items in different label groups based on hardcoded data
itemsWithLabels[2].runtimeStatus = ResourceStatus.Disabled
itemsWithLabels[5].runtimeStatus = ResourceStatus.Disabled
rerender(
<SidebarResources
items={itemsWithLabels}
selected=""
resourceView={ResourceView.Log}
pathBuilder={pathBuilder}
resourceListOptions={{
...DEFAULT_OPTIONS,
showDisabledResources: true,
}}
/>
)
expect(screen.getAllByLabelText("Disabled resources")).toHaveLength(2)
})
})
})
describe("`showDisabledResources` is false", () => {
it("does NOT display disabled resources at all", () => {
expect(screen.queryByLabelText("Disabled resources")).toBeNull()
expect(screen.queryByText("_1", { exact: true })).toBeNull()
expect(screen.queryByText("_3", { exact: true })).toBeNull()
})
it("does NOT display disabled resources list title", () => {
expect(screen.queryByText("Disabled", { exact: true })).toBeNull()
})
describe("when there are groups and an entire group is disabled", () => {
it("does NOT display the group section", () => {
const items = createSidebarItems(5, true)
// Disable the resource that's in the label group with only one resource
items[3].runtimeStatus = ResourceStatus.Disabled
customRender({ items })
// The test data has one group with only disabled resources,
// so expect that it doesn't show up
expect(screen.queryByText("very_long_long_long_label")).toBeNull()
})
})
})
})
}) | the_stack |
module tetrisbug {
var width = 1280,
height = 500;
var color = d3.scaleOrdinal(d3.schemeCategory10);
var makeEdgeBetween;
var colans = <any>cola;
var graphfile = "graphdata/pre_trip.json";
function makeSVG() {
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
// define arrow markers for graph links
svg.append('svg:defs').append('svg:marker')
.attr('id', 'end-arrow')
.attr('viewBox', '0 -5 10 10')
.attr('refX', 5)
.attr('markerWidth', 3)
.attr('markerHeight', 3)
.attr('orient', 'auto')
.append('svg:path')
.attr('d', 'M0,-5L10,0L0,5L2,0')
.attr('stroke-width', '0px')
//.attr('fill', '#661141');
return svg;
}
function flatGraph() {
var d3cola = colans.d3adaptor(d3)
.linkDistance(150)
.avoidOverlaps(true)
.size([width, height]);
var svg = <any>makeSVG();
d3.json(graphfile, function (error, graph: {nodes, links}) {
graph.nodes.forEach(v=> {
v.width = 200; v.height = 50;
});
d3cola
.nodes(graph.nodes)
.links(graph.links)
.start(10, 10, 10);
var linkTypes = getLinkTypes(graph.links);
var link = svg.selectAll(".link")
.data(graph.links)
.enter().append("line")
.attr("stroke", l => color(linkTypes.lookup[l.type]))
.attr("fill", l => color(linkTypes.lookup[l.type]))
.attr("class", "link");
var margin = 10;
var node = svg.selectAll(".node")
.data(graph.nodes)
.enter().append("rect")
.attr("class", "node")
.attr("width", d => d.width + 2 * margin)
.attr("height", d => d.height + 2 * margin)
.attr("rx", 4).attr("ry", 4)
.call(d3cola.drag);
var label = svg.selectAll(".label")
.data(graph.nodes)
.enter().append("text")
.attr("class", "label")
.text(d => d.name)
.call(d3cola.drag);
node.append("title")
.text(d => d.name);
d3cola.on("tick", function () {
node.each(
d => d.innerBounds = d.bounds.inflate(-margin)
);
link.each(function (d) {
d.route = cola.makeEdgeBetween(d.source.innerBounds, d.target.innerBounds, 5);
if (isIE()) this.parentNode.insertBefore(this, this);
});
link.attr("x1", d => d.route.sourceIntersection.x)
.attr("y1", d => d.route.sourceIntersection.y)
.attr("x2", d => d.route.arrowStart.x)
.attr("y2", d => d.route.arrowStart.y);
node.attr("x", d => d.innerBounds.x)
.attr("y", d => d.innerBounds.y)
.attr("width", d => d.innerBounds.width())
.attr("height", d => d.innerBounds.height());
label.attr("x", d => d.x)
.attr("y", function (d) {
var h = this.getBBox().height;
return d.y + h / 3.5;
});
});
var indent = 100, topindent = 120;
var swatches = svg.selectAll('.swatch')
.data(linkTypes.list)
.enter().append('rect').attr('x', indent).attr('y', (l, i) => topindent + 40 * i)
.attr('width', 30).attr('height', 30).attr('fill', (l, i) => color(i))
.attr('class', 'swatch');
var swatchlabels = svg.selectAll('.swatchlabel')
.data(linkTypes.list)
.enter()
.append('text').text(t => t ? t : "Any").attr('x', indent + 40).attr('y', (l, i) => topindent + 20 + 40 * i).attr('fill', 'black')
.attr('class', 'swatchlabel');
});
}
function expandGroup(g, ms) {
if (g.groups) {
g.groups.forEach(cg => expandGroup(cg, ms));
}
if (g.leaves) {
g.leaves.forEach(l => {
ms.push(l.index + 1);
});
}
}
function getId(v, n) {
return (typeof v.index === 'number' ? v.index : v.id + n) + 1;
}
function powerGraph() {
var d3cola = colans.d3adaptor(d3)
.linkDistance(80)
.handleDisconnected(false)
.avoidOverlaps(true)
.size([width, height]);
var svg = <any>makeSVG();
d3.json(graphfile, function (error, graph: {nodes, links}) {
graph.nodes.forEach((v, i) => {
v.index = i;
v.width = 200;
v.height = 50;
});
var powerGraph;
var doLayout = function (response) {
var vs = response.nodes.filter(v=> v.label);
vs.forEach(v=> {
var index = Number(v.label) - 1;
var node = graph.nodes[index];
node.y = Number(v.x) / 1.5 + 50;
node.x = Number(v.y) * 2 + 50;
node.fixed = 1;
});
d3cola.start(1, 1, 1);
var group = svg.selectAll(".group")
.data(powerGraph.groups)
.enter().append("rect")
.attr("rx", 8).attr("ry", 8)
.attr("class", "group");
var link = svg.selectAll(".link")
.data(powerGraph.powerEdges)
.enter().append("line")
.attr("stroke", l => color(l.type))
.attr("fill", l => color(l.type))
.attr("class", "link");
var margin = 10;
var node = svg.selectAll(".node")
.data(graph.nodes)
.enter().append("rect")
.attr("class", "node")
.attr("width", d => d.width + 2 * margin)
.attr("height", d => d.height + 2 * margin)
.attr("rx", 4).attr("ry", 4)
.call(d3cola.drag);
var label = svg.selectAll(".label")
.data(graph.nodes)
.enter().append("text")
.attr("class", "label")
.text(d => d.name)
.call(d3cola.drag);
node.append("title")
.text(d => d.name);
d3cola.on("tick", function () {
node.each(
d => {
d.bounds.setXCentre(d.x);
d.bounds.setYCentre(d.y);
d.innerBounds = d.bounds.inflate(-margin);
});
group.each(d => d.innerBounds = d.bounds.inflate(-margin));
link.each(function (d) {
d.route = cola.makeEdgeBetween(d.source.innerBounds, d.target.innerBounds, 5);
if (isIE()) this.parentNode.insertBefore(this, this);
});
link.attr("x1", d => d.route.sourceIntersection.x)
.attr("y1", d => d.route.sourceIntersection.y)
.attr("x2", d => d.route.arrowStart.x)
.attr("y2", d => d.route.arrowStart.y);
node.attr("x", d => d.innerBounds.x)
.attr("y", d => d.innerBounds.y)
.attr("width", d => d.innerBounds.width())
.attr("height", d => d.innerBounds.height());
group.attr("x", d => d.innerBounds.x)
.attr("y", d => d.innerBounds.y)
.attr("width", d => d.innerBounds.width())
.attr("height", d => d.innerBounds.height());
label.attr("x", d => d.x)
.attr("y", function (d) {
var h = this.getBBox().height;
return d.y + h / 3.5;
});
});
}
var linkTypes = getLinkTypes(graph.links);
d3cola
.nodes(graph.nodes)
.links(graph.links)
.linkType(l => linkTypes.lookup[l.type])
.powerGraphGroups(d => (powerGraph = d).groups.forEach(v => v.padding = 10));
var modules = { N: graph.nodes.length, ms: [], edges: [] };
var n = modules.N;
powerGraph.groups.forEach(g => {
var m = [];
expandGroup(g, m);
modules.ms.push(m);
});
powerGraph.powerEdges.forEach(e => {
var N = graph.nodes.length;
modules.edges.push({ source: getId(e.source, N), target: getId(e.target, N) });
});
//if (document.URL.toLowerCase().indexOf('marvl.infotech.monash.edu') >= 0) {
// $.ajax({
// type: 'post',
// url: 'http://marvl.infotech.monash.edu/cgi-bin/test.py',
// data: JSON.stringify(modules),
// datatype: "json",
// success: function (response) {
// doLayout(response);
// },
// error: function (jqXHR, status, err) {
// alert(status);
// }
// });
//} else
{
d3.json(graphfile.replace(/.json/,'pgresponse.json'), function (error, response) {
doLayout(response);
});
}
});
}
function getLinkTypes(links) {
var linkTypes = { list: [], lookup: {} };
links.forEach(l=> linkTypes.lookup[l.type] = {});
var typeCount = 0;
for (var type in linkTypes.lookup) {
linkTypes.list.push(type);
linkTypes.lookup[type] = typeCount++;
}
return linkTypes;
}
function isIE() { return ((navigator.appName == 'Microsoft Internet Explorer') || ((navigator.appName == 'Netscape') && (new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})").exec(navigator.userAgent) != null))); }
flatGraph();
powerGraph();
} | the_stack |
import * as fs from 'fs';
import * as path from 'path';
import { promisify } from 'util';
import * as cp from 'child_process';
import * as yazl from 'yazl';
import { ExtensionKind, Manifest } from './manifest';
import { ITranslations, patchNLS } from './nls';
import * as util from './util';
import glob from 'glob';
import minimatch from 'minimatch';
import markdownit from 'markdown-it';
import * as cheerio from 'cheerio';
import * as url from 'url';
import mime from 'mime';
import * as semver from 'semver';
import urljoin from 'url-join';
import {
validateExtensionName,
validateVersion,
validateEngineCompatibility,
validateVSCodeTypesCompatibility,
} from './validation';
import { detectYarn, getDependencies } from './npm';
import * as GitHost from 'hosted-git-info';
import parseSemver from 'parse-semver';
const MinimatchOptions: minimatch.IOptions = { dot: true };
export interface IInMemoryFile {
path: string;
mode?: number;
readonly contents: Buffer | string;
}
export interface ILocalFile {
path: string;
mode?: number;
readonly localPath: string;
}
export type IFile = IInMemoryFile | ILocalFile;
function isInMemoryFile(file: IFile): file is IInMemoryFile {
return !!(file as IInMemoryFile).contents;
}
export function read(file: IFile): Promise<string> {
if (isInMemoryFile(file)) {
return Promise.resolve(file.contents).then(b => (typeof b === 'string' ? b : b.toString('utf8')));
} else {
return fs.promises.readFile(file.localPath, 'utf8');
}
}
export interface IPackage {
manifest: Manifest;
packagePath: string;
}
export interface IPackageResult extends IPackage {
files: IFile[];
}
export interface IAsset {
type: string;
path: string;
}
export interface IPackageOptions {
readonly packagePath?: string;
readonly version?: string;
readonly target?: string;
readonly commitMessage?: string;
readonly gitTagVersion?: boolean;
readonly updatePackageJson?: boolean;
readonly cwd?: string;
readonly githubBranch?: string;
readonly gitlabBranch?: string;
readonly rewriteRelativeLinks?: boolean;
readonly baseContentUrl?: string;
readonly baseImagesUrl?: string;
readonly useYarn?: boolean;
readonly dependencyEntryPoints?: string[];
readonly ignoreFile?: string;
readonly gitHubIssueLinking?: boolean;
readonly gitLabIssueLinking?: boolean;
readonly dependencies?: boolean;
readonly preRelease?: boolean;
readonly allowStarActivation?: boolean;
readonly allowMissingRepository?: boolean;
}
export interface IProcessor {
onFile(file: IFile): Promise<IFile>;
onEnd(): Promise<void>;
assets: IAsset[];
tags: string[];
vsix: any;
}
export interface VSIX {
id: string;
displayName: string;
version: string;
publisher: string;
target?: string;
engine: string;
description: string;
categories: string;
flags: string;
icon?: string;
license?: string;
assets: IAsset[];
tags: string;
links: {
repository?: string;
bugs?: string;
homepage?: string;
github?: string;
};
galleryBanner: NonNullable<Manifest['galleryBanner']>;
badges?: Manifest['badges'];
githubMarkdown: boolean;
enableMarketplaceQnA?: boolean;
customerQnALink?: Manifest['qna'];
extensionDependencies: string;
extensionPack: string;
extensionKind: string;
localizedLanguages: string;
preRelease: boolean;
}
export class BaseProcessor implements IProcessor {
constructor(protected manifest: Manifest) {}
assets: IAsset[] = [];
tags: string[] = [];
vsix: VSIX = Object.create(null);
async onFile(file: IFile): Promise<IFile> {
return file;
}
async onEnd() {
// noop
}
}
// https://github.com/npm/cli/blob/latest/lib/utils/hosted-git-info-from-manifest.js
function getGitHost(manifest: Manifest): GitHost | undefined {
const url = getRepositoryUrl(manifest);
return url ? GitHost.fromUrl(url, { noGitPlus: true }) : undefined;
}
// https://github.com/npm/cli/blob/latest/lib/repo.js
function getRepositoryUrl(manifest: Manifest, gitHost?: GitHost | null): string | undefined {
if (gitHost) {
return gitHost.https();
}
let url: string | undefined = undefined;
if (manifest.repository) {
if (typeof manifest.repository === 'string') {
url = manifest.repository;
} else if (
typeof manifest.repository === 'object' &&
manifest.repository.url &&
typeof manifest.repository.url === 'string'
) {
url = manifest.repository.url;
}
}
return url;
}
// https://github.com/npm/cli/blob/latest/lib/bugs.js
function getBugsUrl(manifest: Manifest, gitHost: GitHost | undefined): string | undefined {
if (manifest.bugs) {
if (typeof manifest.bugs === 'string') {
return manifest.bugs;
}
if (typeof manifest.bugs === 'object' && manifest.bugs.url) {
return manifest.bugs.url;
}
if (typeof manifest.bugs === 'object' && manifest.bugs.email) {
return `mailto:${manifest.bugs.email}`;
}
}
if (gitHost) {
return gitHost.bugs();
}
return undefined;
}
// https://github.com/npm/cli/blob/latest/lib/docs.js
function getHomepageUrl(manifest: Manifest, gitHost: GitHost | undefined): string | undefined {
if (manifest.homepage) {
return manifest.homepage;
}
if (gitHost) {
return gitHost.docs();
}
return undefined;
}
// Contributed by Mozilla developer authors
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
function escapeRegExp(value: string) {
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
function toExtensionTags(extensions: string[]): string[] {
return extensions
.map(s => s.replace(/\W/g, ''))
.filter(s => !!s)
.map(s => `__ext_${s}`);
}
function toLanguagePackTags(translations: { id: string }[], languageId: string): string[] {
return (translations ?? [])
.map(({ id }) => [`__lp_${id}`, `__lp-${languageId}_${id}`])
.reduce((r, t) => [...r, ...t], []);
}
/* This list is also maintained by the Marketplace team.
* Remember to reach out to them when adding new domains.
*/
const TrustedSVGSources = [
'api.bintray.com',
'api.travis-ci.com',
'api.travis-ci.org',
'app.fossa.io',
'badge.buildkite.com',
'badge.fury.io',
'badge.waffle.io',
'badgen.net',
'badges.frapsoft.com',
'badges.gitter.im',
'badges.greenkeeper.io',
'cdn.travis-ci.com',
'cdn.travis-ci.org',
'ci.appveyor.com',
'circleci.com',
'cla.opensource.microsoft.com',
'codacy.com',
'codeclimate.com',
'codecov.io',
'coveralls.io',
'david-dm.org',
'deepscan.io',
'dev.azure.com',
'docs.rs',
'flat.badgen.net',
'gemnasium.com',
'githost.io',
'gitlab.com',
'godoc.org',
'goreportcard.com',
'img.shields.io',
'isitmaintained.com',
'marketplace.visualstudio.com',
'nodesecurity.io',
'opencollective.com',
'snyk.io',
'travis-ci.com',
'travis-ci.org',
'visualstudio.com',
'vsmarketplacebadge.apphb.com',
'www.bithound.io',
'www.versioneye.com',
];
function isGitHubRepository(repository: string | undefined): boolean {
return /^https:\/\/github\.com\/|^git@github\.com:/.test(repository ?? '');
}
function isGitLabRepository(repository: string | undefined): boolean {
return /^https:\/\/gitlab\.com\/|^git@gitlab\.com:/.test(repository ?? '');
}
function isGitHubBadge(href: string): boolean {
return /^https:\/\/github\.com\/[^/]+\/[^/]+\/(actions\/)?workflows\/.*badge\.svg/.test(href || '');
}
function isHostTrusted(url: url.URL): boolean {
return (url.host && TrustedSVGSources.indexOf(url.host.toLowerCase()) > -1) || isGitHubBadge(url.href);
}
export interface IVersionBumpOptions {
readonly cwd?: string;
readonly version?: string;
readonly commitMessage?: string;
readonly gitTagVersion?: boolean;
readonly updatePackageJson?: boolean;
}
export async function versionBump(options: IVersionBumpOptions): Promise<void> {
if (!options.version) {
return;
}
if (!(options.updatePackageJson ?? true)) {
return;
}
const cwd = options.cwd ?? process.cwd();
const manifest = await readManifest(cwd);
if (manifest.version === options.version) {
return;
}
switch (options.version) {
case 'major':
case 'minor':
case 'patch':
break;
case 'premajor':
case 'preminor':
case 'prepatch':
case 'prerelease':
case 'from-git':
return Promise.reject(`Not supported: ${options.version}`);
default:
if (!semver.valid(options.version)) {
return Promise.reject(`Invalid version ${options.version}`);
}
}
let command = `npm version ${options.version}`;
if (options.commitMessage) {
command = `${command} -m "${options.commitMessage}"`;
}
if (!(options.gitTagVersion ?? true)) {
command = `${command} --no-git-tag-version`;
}
// call `npm version` to do our dirty work
const { stdout, stderr } = await promisify(cp.exec)(command, { cwd });
if (!process.env['VSCE_TESTS']) {
process.stdout.write(stdout);
process.stderr.write(stderr);
}
}
const Targets = new Set([
'win32-x64',
'win32-ia32',
'win32-arm64',
'linux-x64',
'linux-arm64',
'linux-armhf',
'darwin-x64',
'darwin-arm64',
'alpine-x64',
'alpine-arm64',
'web',
]);
export class ManifestProcessor extends BaseProcessor {
constructor(manifest: Manifest, private readonly options: IPackageOptions = {}) {
super(manifest);
const flags = ['Public'];
if (manifest.preview) {
flags.push('Preview');
}
const gitHost = getGitHost(manifest);
const repository = getRepositoryUrl(manifest, gitHost);
const isGitHub = isGitHubRepository(repository);
let enableMarketplaceQnA: boolean | undefined;
let customerQnALink: string | undefined;
if (manifest.qna === 'marketplace') {
enableMarketplaceQnA = true;
} else if (typeof manifest.qna === 'string') {
customerQnALink = manifest.qna;
} else if (manifest.qna === false) {
enableMarketplaceQnA = false;
}
const extensionKind = getExtensionKind(manifest);
const target = options.target;
const preRelease = options.preRelease;
if (target || preRelease) {
let engineVersion: string;
try {
const engineSemver = parseSemver(`vscode@${manifest.engines['vscode']}`);
engineVersion = engineSemver.version;
} catch (err) {
throw new Error('Failed to parse semver of engines.vscode');
}
if (target) {
if (engineVersion !== 'latest' && !semver.satisfies(engineVersion, '>=1.61', { includePrerelease: true })) {
throw new Error(
`Platform specific extension is supported by VS Code >=1.61. Current 'engines.vscode' is '${manifest.engines['vscode']}'.`
);
}
if (!Targets.has(target)) {
throw new Error(`'${target}' is not a valid VS Code target. Valid targets: ${[...Targets].join(', ')}`);
}
}
if (preRelease) {
if (engineVersion !== 'latest' && !semver.satisfies(engineVersion, '>=1.63', { includePrerelease: true })) {
throw new Error(
`Pre-release versions are supported by VS Code >=1.63. Current 'engines.vscode' is '${manifest.engines['vscode']}'.`
);
}
}
}
this.vsix = {
...this.vsix,
id: manifest.name,
displayName: manifest.displayName ?? manifest.name,
version: options.version && !(options.updatePackageJson ?? true) ? options.version : manifest.version,
publisher: manifest.publisher,
target,
engine: manifest.engines['vscode'],
description: manifest.description ?? '',
categories: (manifest.categories ?? []).join(','),
flags: flags.join(' '),
links: {
repository,
bugs: getBugsUrl(manifest, gitHost),
homepage: getHomepageUrl(manifest, gitHost),
},
galleryBanner: manifest.galleryBanner ?? {},
badges: manifest.badges,
githubMarkdown: manifest.markdown !== 'standard',
enableMarketplaceQnA,
customerQnALink,
extensionDependencies: [...new Set(manifest.extensionDependencies ?? [])].join(','),
extensionPack: [...new Set(manifest.extensionPack ?? [])].join(','),
extensionKind: extensionKind.join(','),
localizedLanguages:
manifest.contributes && manifest.contributes.localizations
? manifest.contributes.localizations
.map(loc => loc.localizedLanguageName ?? loc.languageName ?? loc.languageId)
.join(',')
: '',
preRelease: !!this.options.preRelease,
};
if (isGitHub) {
this.vsix.links.github = repository;
}
}
async onFile(file: IFile): Promise<IFile> {
const path = util.normalize(file.path);
if (!/^extension\/package.json$/i.test(path)) {
return Promise.resolve(file);
}
if (this.options.version && !(this.options.updatePackageJson ?? true)) {
const contents = await read(file);
const packageJson = JSON.parse(contents);
packageJson.version = this.options.version;
file = { ...file, contents: JSON.stringify(packageJson, undefined, 2) };
}
// Ensure that package.json is writable as VS Code needs to
// store metadata in the extracted file.
return { ...file, mode: 0o100644 };
}
async onEnd(): Promise<void> {
if (typeof this.manifest.extensionKind === 'string') {
util.log.warn(
`The 'extensionKind' property should be of type 'string[]'. Learn more at: https://aka.ms/vscode/api/incorrect-execution-location`
);
}
if (this.manifest.publisher === 'vscode-samples') {
throw new Error(
"It's not allowed to use the 'vscode-samples' publisher. Learn more at: https://code.visualstudio.com/api/working-with-extensions/publishing-extension."
);
}
if (!this.options.allowMissingRepository && !this.manifest.repository) {
util.log.warn(`A 'repository' field is missing from the 'package.json' manifest file.`);
if (!/^y$/i.test(await util.read('Do you want to continue? [y/N] '))) {
throw new Error('Aborted');
}
}
if (!this.options.allowStarActivation && this.manifest.activationEvents?.some(e => e === '*')) {
util.log.warn(
`Using '*' activation is usually a bad idea as it impacts performance.\nMore info: https://code.visualstudio.com/api/references/activation-events#Start-up`
);
if (!/^y$/i.test(await util.read('Do you want to continue? [y/N] '))) {
throw new Error('Aborted');
}
}
}
}
export class TagsProcessor extends BaseProcessor {
private static Keywords: Record<string, string[]> = {
git: ['git'],
npm: ['node'],
spell: ['markdown'],
bootstrap: ['bootstrap'],
lint: ['linters'],
linting: ['linters'],
react: ['javascript'],
js: ['javascript'],
node: ['javascript', 'node'],
'c++': ['c++'],
Cplusplus: ['c++'],
xml: ['xml'],
angular: ['javascript'],
jquery: ['javascript'],
php: ['php'],
python: ['python'],
latex: ['latex'],
ruby: ['ruby'],
java: ['java'],
erlang: ['erlang'],
sql: ['sql'],
nodejs: ['node'],
'c#': ['c#'],
css: ['css'],
javascript: ['javascript'],
ftp: ['ftp'],
haskell: ['haskell'],
unity: ['unity'],
terminal: ['terminal'],
powershell: ['powershell'],
laravel: ['laravel'],
meteor: ['meteor'],
emmet: ['emmet'],
eslint: ['linters'],
tfs: ['tfs'],
rust: ['rust'],
};
async onEnd(): Promise<void> {
const keywords = this.manifest.keywords ?? [];
const contributes = this.manifest.contributes;
const activationEvents = this.manifest.activationEvents ?? [];
const doesContribute = (...properties: string[]) => {
let obj = contributes;
for (const property of properties) {
if (!obj) {
return false;
}
obj = obj[property];
}
return obj && obj.length > 0;
};
const colorThemes = doesContribute('themes') ? ['theme', 'color-theme'] : [];
const iconThemes = doesContribute('iconThemes') ? ['theme', 'icon-theme'] : [];
const productIconThemes = doesContribute('productIconThemes') ? ['theme', 'product-icon-theme'] : [];
const snippets = doesContribute('snippets') ? ['snippet'] : [];
const keybindings = doesContribute('keybindings') ? ['keybindings'] : [];
const debuggers = doesContribute('debuggers') ? ['debuggers'] : [];
const json = doesContribute('jsonValidation') ? ['json'] : [];
const remoteMenu = doesContribute('menus', 'statusBar/remoteIndicator') ? ['remote-menu'] : [];
const localizationContributions = ((contributes && contributes['localizations']) ?? []).reduce<string[]>(
(r, l) => [...r, `lp-${l.languageId}`, ...toLanguagePackTags(l.translations, l.languageId)],
[]
);
const languageContributions = ((contributes && contributes['languages']) ?? []).reduce<string[]>(
(r, l) => [...r, l.id, ...(l.aliases ?? []), ...toExtensionTags(l.extensions ?? [])],
[]
);
const languageActivations = activationEvents
.map(e => /^onLanguage:(.*)$/.exec(e))
.filter(util.nonnull)
.map(r => r[1]);
const grammars = ((contributes && contributes['grammars']) ?? []).map(g => g.language);
const description = this.manifest.description || '';
const descriptionKeywords = Object.keys(TagsProcessor.Keywords).reduce<string[]>(
(r, k) =>
r.concat(
new RegExp('\\b(?:' + escapeRegExp(k) + ')(?!\\w)', 'gi').test(description) ? TagsProcessor.Keywords[k] : []
),
[]
);
const webExensionTags = isWebKind(this.manifest) ? ['__web_extension'] : [];
const tags = new Set([
...keywords,
...colorThemes,
...iconThemes,
...productIconThemes,
...snippets,
...keybindings,
...debuggers,
...json,
...remoteMenu,
...localizationContributions,
...languageContributions,
...languageActivations,
...grammars,
...descriptionKeywords,
...webExensionTags,
]);
this.tags = [...tags].filter(tag => !!tag);
}
}
export class MarkdownProcessor extends BaseProcessor {
private baseContentUrl: string | undefined;
private baseImagesUrl: string | undefined;
private rewriteRelativeLinks: boolean;
private isGitHub: boolean;
private isGitLab: boolean;
private repositoryUrl: string | undefined;
private gitHubIssueLinking: boolean;
private gitLabIssueLinking: boolean;
constructor(
manifest: Manifest,
private name: string,
private regexp: RegExp,
private assetType: string,
options: IPackageOptions = {}
) {
super(manifest);
const guess = this.guessBaseUrls(options.githubBranch || options.gitlabBranch);
this.baseContentUrl = options.baseContentUrl || (guess && guess.content);
this.baseImagesUrl = options.baseImagesUrl || options.baseContentUrl || (guess && guess.images);
this.rewriteRelativeLinks = options.rewriteRelativeLinks ?? true;
this.repositoryUrl = guess && guess.repository;
this.isGitHub = isGitHubRepository(this.repositoryUrl);
this.isGitLab = isGitLabRepository(this.repositoryUrl);
this.gitHubIssueLinking = typeof options.gitHubIssueLinking === 'boolean' ? options.gitHubIssueLinking : true;
this.gitLabIssueLinking = typeof options.gitLabIssueLinking === 'boolean' ? options.gitLabIssueLinking : true;
}
async onFile(file: IFile): Promise<IFile> {
const filePath = util.normalize(file.path);
if (!this.regexp.test(filePath)) {
return Promise.resolve(file);
}
this.assets.push({ type: this.assetType, path: filePath });
let contents = await read(file);
if (/This is the README for your extension /.test(contents)) {
throw new Error(`Make sure to edit the README.md file before you package or publish your extension.`);
}
if (this.rewriteRelativeLinks) {
const markdownPathRegex = /(!?)\[([^\]\[]*|!\[[^\]\[]*]\([^\)]+\))\]\(([^\)]+)\)/g;
const urlReplace = (_: string, isImage: string, title: string, link: string) => {
if (/^mailto:/i.test(link)) {
return `${isImage}[${title}](${link})`;
}
const isLinkRelative = !/^\w+:\/\//.test(link) && link[0] !== '#';
if (!this.baseContentUrl && !this.baseImagesUrl) {
const asset = isImage ? 'image' : 'link';
if (isLinkRelative) {
throw new Error(
`Couldn't detect the repository where this extension is published. The ${asset} '${link}' will be broken in ${this.name}. GitHub/GitLab repositories will be automatically detected. Otherwise, please provide the repository URL in package.json or use the --baseContentUrl and --baseImagesUrl options.`
);
}
}
title = title.replace(markdownPathRegex, urlReplace);
const prefix = isImage ? this.baseImagesUrl : this.baseContentUrl;
if (!prefix || !isLinkRelative) {
return `${isImage}[${title}](${link})`;
}
return `${isImage}[${title}](${urljoin(prefix, path.posix.normalize(link))})`;
};
// Replace Markdown links with urls
contents = contents.replace(markdownPathRegex, urlReplace);
// Replace <img> links with urls
contents = contents.replace(/<img.+?src=["']([/.\w\s-]+)['"].*?>/g, (all, link) => {
const isLinkRelative = !/^\w+:\/\//.test(link) && link[0] !== '#';
if (!this.baseImagesUrl && isLinkRelative) {
throw new Error(
`Couldn't detect the repository where this extension is published. The image will be broken in ${this.name}. GitHub/GitLab repositories will be automatically detected. Otherwise, please provide the repository URL in package.json or use the --baseContentUrl and --baseImagesUrl options.`
);
}
const prefix = this.baseImagesUrl;
if (!prefix || !isLinkRelative) {
return all;
}
return all.replace(link, urljoin(prefix, path.posix.normalize(link)));
});
if ((this.gitHubIssueLinking && this.isGitHub) || (this.gitLabIssueLinking && this.isGitLab)) {
const markdownIssueRegex = /(\s|\n)([\w\d_-]+\/[\w\d_-]+)?#(\d+)\b/g;
const issueReplace = (
all: string,
prefix: string,
ownerAndRepositoryName: string,
issueNumber: string
): string => {
let result = all;
let owner: string | undefined;
let repositoryName: string | undefined;
if (ownerAndRepositoryName) {
[owner, repositoryName] = ownerAndRepositoryName.split('/', 2);
}
if (owner && repositoryName && issueNumber) {
// Issue in external repository
const issueUrl = this.isGitHub
? urljoin('https://github.com', owner, repositoryName, 'issues', issueNumber)
: urljoin('https://gitlab.com', owner, repositoryName, '-', 'issues', issueNumber);
result = prefix + `[${owner}/${repositoryName}#${issueNumber}](${issueUrl})`;
} else if (!owner && !repositoryName && issueNumber && this.repositoryUrl) {
// Issue in own repository
result =
prefix +
`[#${issueNumber}](${
this.isGitHub
? urljoin(this.repositoryUrl, 'issues', issueNumber)
: urljoin(this.repositoryUrl, '-', 'issues', issueNumber)
})`;
}
return result;
};
// Replace Markdown issue references with urls
contents = contents.replace(markdownIssueRegex, issueReplace);
}
}
const html = markdownit({ html: true }).render(contents);
const $ = cheerio.load(html);
if (this.rewriteRelativeLinks) {
$('img').each((_, img) => {
const rawSrc = $(img).attr('src');
if (!rawSrc) {
throw new Error(`Images in ${this.name} must have a source.`);
}
const src = decodeURI(rawSrc);
const srcUrl = new url.URL(src);
if (/^data:$/i.test(srcUrl.protocol) && /^image$/i.test(srcUrl.host) && /\/svg/i.test(srcUrl.pathname)) {
throw new Error(`SVG data URLs are not allowed in ${this.name}: ${src}`);
}
if (!/^https:$/i.test(srcUrl.protocol)) {
throw new Error(`Images in ${this.name} must come from an HTTPS source: ${src}`);
}
if (/\.svg$/i.test(srcUrl.pathname) && !isHostTrusted(srcUrl)) {
throw new Error(
`SVGs are restricted in ${this.name}; please use other file image formats, such as PNG: ${src}`
);
}
});
}
$('svg').each(() => {
throw new Error(`SVG tags are not allowed in ${this.name}.`);
});
return {
path: file.path,
contents: Buffer.from(contents, 'utf8'),
};
}
// GitHub heuristics
private guessBaseUrls(
githostBranch: string | undefined
): { content: string; images: string; repository: string } | undefined {
let repository = null;
if (typeof this.manifest.repository === 'string') {
repository = this.manifest.repository;
} else if (this.manifest.repository && typeof this.manifest.repository['url'] === 'string') {
repository = this.manifest.repository['url'];
}
if (!repository) {
return undefined;
}
const gitHubRegex = /(?<domain>github(\.com\/|:))(?<project>(?:[^/]+)\/(?:[^/]+))(\/|$)/;
const gitLabRegex = /(?<domain>gitlab(\.com\/|:))(?<project>(?:[^/]+)(\/(?:[^/]+))+)(\/|$)/;
const match = ((gitHubRegex.exec(repository) || gitLabRegex.exec(repository)) as unknown) as {
groups: Record<string, string>;
};
if (!match) {
return undefined;
}
const project = match.groups.project.replace(/\.git$/i, '');
const branchName = githostBranch ? githostBranch : 'HEAD';
if (/^github/.test(match.groups.domain)) {
return {
content: `https://github.com/${project}/blob/${branchName}`,
images: `https://github.com/${project}/raw/${branchName}`,
repository: `https://github.com/${project}`,
};
} else if (/^gitlab/.test(match.groups.domain)) {
return {
content: `https://gitlab.com/${project}/-/blob/${branchName}`,
images: `https://gitlab.com/${project}/-/raw/${branchName}`,
repository: `https://gitlab.com/${project}`,
};
}
return undefined;
}
}
export class ReadmeProcessor extends MarkdownProcessor {
constructor(manifest: Manifest, options: IPackageOptions = {}) {
super(manifest, 'README.md', /^extension\/readme.md$/i, 'Microsoft.VisualStudio.Services.Content.Details', options);
}
}
export class ChangelogProcessor extends MarkdownProcessor {
constructor(manifest: Manifest, options: IPackageOptions = {}) {
super(
manifest,
'CHANGELOG.md',
/^extension\/changelog.md$/i,
'Microsoft.VisualStudio.Services.Content.Changelog',
options
);
}
}
class LicenseProcessor extends BaseProcessor {
private didFindLicense = false;
private expectedLicenseName: string;
filter: (name: string) => boolean;
constructor(manifest: Manifest) {
super(manifest);
const match = /^SEE LICENSE IN (.*)$/.exec(manifest.license || '');
if (!match || !match[1]) {
this.expectedLicenseName = 'LICENSE.md, LICENSE.txt or LICENSE';
this.filter = name => /^extension\/license(\.(md|txt))?$/i.test(name);
} else {
this.expectedLicenseName = match[1];
const regexp = new RegExp('^extension/' + match[1] + '$');
this.filter = regexp.test.bind(regexp);
}
delete this.vsix.license;
}
onFile(file: IFile): Promise<IFile> {
if (!this.didFindLicense) {
let normalizedPath = util.normalize(file.path);
if (this.filter(normalizedPath)) {
if (!path.extname(normalizedPath)) {
file.path += '.txt';
normalizedPath += '.txt';
}
this.assets.push({ type: 'Microsoft.VisualStudio.Services.Content.License', path: normalizedPath });
this.vsix.license = normalizedPath;
this.didFindLicense = true;
}
}
return Promise.resolve(file);
}
async onEnd(): Promise<void> {
if (!this.didFindLicense) {
util.log.warn(`${this.expectedLicenseName} not found`);
if (!/^y$/i.test(await util.read('Do you want to continue? [y/N] '))) {
throw new Error('Aborted');
}
}
}
}
class LaunchEntryPointProcessor extends BaseProcessor {
private entryPoints: Set<string> = new Set<string>();
constructor(manifest: Manifest) {
super(manifest);
if (manifest.main) {
this.entryPoints.add(util.normalize(path.join('extension', this.appendJSExt(manifest.main))));
}
if (manifest.browser) {
this.entryPoints.add(util.normalize(path.join('extension', this.appendJSExt(manifest.browser))));
}
}
appendJSExt(filePath: string): string {
if (filePath.endsWith('.js')) {
return filePath;
}
return filePath + '.js';
}
onFile(file: IFile): Promise<IFile> {
this.entryPoints.delete(util.normalize(file.path));
return Promise.resolve(file);
}
async onEnd(): Promise<void> {
if (this.entryPoints.size > 0) {
const files: string = [...this.entryPoints].join(',\n ');
throw new Error(
`Extension entrypoint(s) missing. Make sure these files exist and aren't ignored by '.vscodeignore':\n ${files}`
);
}
}
}
class IconProcessor extends BaseProcessor {
private icon: string | undefined;
private didFindIcon = false;
constructor(manifest: Manifest) {
super(manifest);
this.icon = manifest.icon && `extension/${manifest.icon}`;
delete this.vsix.icon;
}
onFile(file: IFile): Promise<IFile> {
const normalizedPath = util.normalize(file.path);
if (normalizedPath === this.icon) {
this.didFindIcon = true;
this.assets.push({ type: 'Microsoft.VisualStudio.Services.Icons.Default', path: normalizedPath });
this.vsix.icon = this.icon;
}
return Promise.resolve(file);
}
async onEnd(): Promise<void> {
if (this.icon && !this.didFindIcon) {
return Promise.reject(new Error(`The specified icon '${this.icon}' wasn't found in the extension.`));
}
}
}
const ValidExtensionKinds = new Set(['ui', 'workspace']);
export function isWebKind(manifest: Manifest): boolean {
const extensionKind = getExtensionKind(manifest);
return extensionKind.some(kind => kind === 'web');
}
const extensionPointExtensionKindsMap = new Map<string, ExtensionKind[]>();
extensionPointExtensionKindsMap.set('jsonValidation', ['workspace', 'web']);
extensionPointExtensionKindsMap.set('localizations', ['ui', 'workspace']);
extensionPointExtensionKindsMap.set('debuggers', ['workspace']);
extensionPointExtensionKindsMap.set('terminal', ['workspace']);
extensionPointExtensionKindsMap.set('typescriptServerPlugins', ['workspace']);
extensionPointExtensionKindsMap.set('markdown.previewStyles', ['workspace', 'web']);
extensionPointExtensionKindsMap.set('markdown.previewScripts', ['workspace', 'web']);
extensionPointExtensionKindsMap.set('markdown.markdownItPlugins', ['workspace', 'web']);
extensionPointExtensionKindsMap.set('html.customData', ['workspace', 'web']);
extensionPointExtensionKindsMap.set('css.customData', ['workspace', 'web']);
function getExtensionKind(manifest: Manifest): ExtensionKind[] {
const deduced = deduceExtensionKinds(manifest);
// check the manifest
if (manifest.extensionKind) {
const result: ExtensionKind[] = Array.isArray(manifest.extensionKind)
? manifest.extensionKind
: manifest.extensionKind === 'ui'
? ['ui', 'workspace']
: [manifest.extensionKind];
// Add web kind if the extension can run as web extension
if (deduced.includes('web') && !result.includes('web')) {
result.push('web');
}
return result;
}
return deduced;
}
function deduceExtensionKinds(manifest: Manifest): ExtensionKind[] {
// Not an UI extension if it has main
if (manifest.main) {
if (manifest.browser) {
return ['workspace', 'web'];
}
return ['workspace'];
}
if (manifest.browser) {
return ['web'];
}
let result: ExtensionKind[] = ['ui', 'workspace', 'web'];
const isNonEmptyArray = (obj: any) => Array.isArray(obj) && obj.length > 0;
// Extension pack defaults to workspace,web extensionKind
if (isNonEmptyArray(manifest.extensionPack) || isNonEmptyArray(manifest.extensionDependencies)) {
result = ['workspace', 'web'];
}
if (manifest.contributes) {
for (const contribution of Object.keys(manifest.contributes)) {
const supportedExtensionKinds = extensionPointExtensionKindsMap.get(contribution);
if (supportedExtensionKinds) {
result = result.filter(extensionKind => supportedExtensionKinds.indexOf(extensionKind) !== -1);
}
}
}
return result;
}
export class NLSProcessor extends BaseProcessor {
private translations: { [path: string]: string } = Object.create(null);
constructor(manifest: Manifest) {
super(manifest);
if (
!manifest.contributes ||
!manifest.contributes.localizations ||
manifest.contributes.localizations.length === 0
) {
return;
}
const localizations = manifest.contributes.localizations;
const translations: { [languageId: string]: string } = Object.create(null);
// take last reference in the manifest for any given language
for (const localization of localizations) {
for (const translation of localization.translations) {
if (translation.id === 'vscode' && !!translation.path) {
const translationPath = util.normalize(translation.path.replace(/^\.[\/\\]/, ''));
translations[localization.languageId.toUpperCase()] = `extension/${translationPath}`;
}
}
}
// invert the map for later easier retrieval
for (const languageId of Object.keys(translations)) {
this.translations[translations[languageId]] = languageId;
}
}
onFile(file: IFile): Promise<IFile> {
const normalizedPath = util.normalize(file.path);
const language = this.translations[normalizedPath];
if (language) {
this.assets.push({ type: `Microsoft.VisualStudio.Code.Translation.${language}`, path: normalizedPath });
}
return Promise.resolve(file);
}
}
export class ValidationProcessor extends BaseProcessor {
private files = new Map<string, string[]>();
private duplicates = new Set<string>();
async onFile(file: IFile): Promise<IFile> {
const lower = file.path.toLowerCase();
const existing = this.files.get(lower);
if (existing) {
this.duplicates.add(lower);
existing.push(file.path);
} else {
this.files.set(lower, [file.path]);
}
return file;
}
async onEnd() {
if (this.duplicates.size === 0) {
return;
}
const messages = [
`The following files have the same case insensitive path, which isn't supported by the VSIX format:`,
];
for (const lower of this.duplicates) {
for (const filePath of this.files.get(lower)!) {
messages.push(` - ${filePath}`);
}
}
throw new Error(messages.join('\n'));
}
}
export function validateManifest(manifest: Manifest): Manifest {
validateExtensionName(manifest.name);
if (!manifest.version) {
throw new Error('Manifest missing field: version');
}
validateVersion(manifest.version);
if (!manifest.engines) {
throw new Error('Manifest missing field: engines');
}
if (!manifest.engines['vscode']) {
throw new Error('Manifest missing field: engines.vscode');
}
validateEngineCompatibility(manifest.engines['vscode']);
const hasActivationEvents = !!manifest.activationEvents;
const hasMain = !!manifest.main;
const hasBrowser = !!manifest.browser;
if (hasActivationEvents) {
if (!hasMain && !hasBrowser) {
throw new Error(
"Manifest needs either a 'main' or 'browser' property, given it has a 'activationEvents' property."
);
}
} else if (hasMain) {
throw new Error("Manifest needs the 'activationEvents' property, given it has a 'main' property.");
} else if (hasBrowser) {
throw new Error("Manifest needs the 'activationEvents' property, given it has a 'browser' property.");
}
if (manifest.devDependencies && manifest.devDependencies['@types/vscode']) {
validateVSCodeTypesCompatibility(manifest.engines['vscode'], manifest.devDependencies['@types/vscode']);
}
if (/\.svg$/i.test(manifest.icon || '')) {
throw new Error(`SVGs can't be used as icons: ${manifest.icon}`);
}
(manifest.badges ?? []).forEach(badge => {
const decodedUrl = decodeURI(badge.url);
const srcUrl = new url.URL(decodedUrl);
if (!/^https:$/i.test(srcUrl.protocol)) {
throw new Error(`Badge URLs must come from an HTTPS source: ${badge.url}`);
}
if (/\.svg$/i.test(srcUrl.pathname) && !isHostTrusted(srcUrl)) {
throw new Error(`Badge SVGs are restricted. Please use other file image formats, such as PNG: ${badge.url}`);
}
});
Object.keys(manifest.dependencies || {}).forEach(dep => {
if (dep === 'vscode') {
throw new Error(
`You should not depend on 'vscode' in your 'dependencies'. Did you mean to add it to 'devDependencies'?`
);
}
});
if (manifest.extensionKind) {
const extensionKinds = Array.isArray(manifest.extensionKind) ? manifest.extensionKind : [manifest.extensionKind];
for (const kind of extensionKinds) {
if (!ValidExtensionKinds.has(kind)) {
throw new Error(
`Manifest contains invalid value '${kind}' in the 'extensionKind' property. Allowed values are ${[
...ValidExtensionKinds,
]
.map(k => `'${k}'`)
.join(', ')}.`
);
}
}
}
return manifest;
}
export function readManifest(cwd = process.cwd(), nls = true): Promise<Manifest> {
const manifestPath = path.join(cwd, 'package.json');
const manifestNLSPath = path.join(cwd, 'package.nls.json');
const manifest = fs.promises
.readFile(manifestPath, 'utf8')
.catch(() => Promise.reject(`Extension manifest not found: ${manifestPath}`))
.then<Manifest>(manifestStr => {
try {
return Promise.resolve(JSON.parse(manifestStr));
} catch (e) {
return Promise.reject(`Error parsing 'package.json' manifest file: not a valid JSON file.`);
}
})
.then(validateManifest);
if (!nls) {
return manifest;
}
const manifestNLS = fs.promises
.readFile(manifestNLSPath, 'utf8')
.catch<string>(err => (err.code !== 'ENOENT' ? Promise.reject(err) : Promise.resolve('{}')))
.then<ITranslations>(raw => {
try {
return Promise.resolve(JSON.parse(raw));
} catch (e) {
return Promise.reject(`Error parsing JSON manifest translations file: ${manifestNLSPath}`);
}
});
return Promise.all([manifest, manifestNLS]).then(([manifest, translations]) => {
return patchNLS(manifest, translations);
});
}
const escapeChars = new Map([
["'", '''],
['"', '"'],
['<', '<'],
['>', '>'],
['&', '&'],
]);
function escape(value: any): string {
return String(value).replace(/(['"<>&])/g, (_, char) => escapeChars.get(char)!);
}
export async function toVsixManifest(vsix: VSIX): Promise<string> {
return `<?xml version="1.0" encoding="utf-8"?>
<PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011">
<Metadata>
<Identity Language="en-US" Id="${escape(vsix.id)}" Version="${escape(vsix.version)}" Publisher="${escape(
vsix.publisher
)}" ${vsix.target ? `TargetPlatform="${escape(vsix.target)}"` : ''}/>
<DisplayName>${escape(vsix.displayName)}</DisplayName>
<Description xml:space="preserve">${escape(vsix.description)}</Description>
<Tags>${escape(vsix.tags)}</Tags>
<Categories>${escape(vsix.categories)}</Categories>
<GalleryFlags>${escape(vsix.flags)}</GalleryFlags>
${
!vsix.badges
? ''
: `<Badges>${vsix.badges
.map(
badge =>
`<Badge Link="${escape(badge.href)}" ImgUri="${escape(badge.url)}" Description="${escape(
badge.description
)}" />`
)
.join('\n')}</Badges>`
}
<Properties>
<Property Id="Microsoft.VisualStudio.Code.Engine" Value="${escape(vsix.engine)}" />
<Property Id="Microsoft.VisualStudio.Code.ExtensionDependencies" Value="${escape(vsix.extensionDependencies)}" />
<Property Id="Microsoft.VisualStudio.Code.ExtensionPack" Value="${escape(vsix.extensionPack)}" />
<Property Id="Microsoft.VisualStudio.Code.ExtensionKind" Value="${escape(vsix.extensionKind)}" />
<Property Id="Microsoft.VisualStudio.Code.LocalizedLanguages" Value="${escape(vsix.localizedLanguages)}" />
${vsix.preRelease ? `<Property Id="Microsoft.VisualStudio.Code.PreRelease" Value="${escape(vsix.preRelease)}" />` : ''}
${
!vsix.links.repository
? ''
: `<Property Id="Microsoft.VisualStudio.Services.Links.Source" Value="${escape(vsix.links.repository)}" />
<Property Id="Microsoft.VisualStudio.Services.Links.Getstarted" Value="${escape(vsix.links.repository)}" />
${
vsix.links.github
? `<Property Id="Microsoft.VisualStudio.Services.Links.GitHub" Value="${escape(vsix.links.github)}" />`
: `<Property Id="Microsoft.VisualStudio.Services.Links.Repository" Value="${escape(
vsix.links.repository
)}" />`
}`
}
${
vsix.links.bugs
? `<Property Id="Microsoft.VisualStudio.Services.Links.Support" Value="${escape(vsix.links.bugs)}" />`
: ''
}
${
vsix.links.homepage
? `<Property Id="Microsoft.VisualStudio.Services.Links.Learn" Value="${escape(vsix.links.homepage)}" />`
: ''
}
${
vsix.galleryBanner.color
? `<Property Id="Microsoft.VisualStudio.Services.Branding.Color" Value="${escape(
vsix.galleryBanner.color
)}" />`
: ''
}
${
vsix.galleryBanner.theme
? `<Property Id="Microsoft.VisualStudio.Services.Branding.Theme" Value="${escape(
vsix.galleryBanner.theme
)}" />`
: ''
}
<Property Id="Microsoft.VisualStudio.Services.GitHubFlavoredMarkdown" Value="${escape(vsix.githubMarkdown)}" />
${
vsix.enableMarketplaceQnA !== undefined
? `<Property Id="Microsoft.VisualStudio.Services.EnableMarketplaceQnA" Value="${escape(
vsix.enableMarketplaceQnA
)}" />`
: ''
}
${
vsix.customerQnALink !== undefined
? `<Property Id="Microsoft.VisualStudio.Services.CustomerQnALink" Value="${escape(
vsix.customerQnALink
)}" />`
: ''
}
</Properties>
${vsix.license ? `<License>${escape(vsix.license)}</License>` : ''}
${vsix.icon ? `<Icon>${escape(vsix.icon)}</Icon>` : ''}
</Metadata>
<Installation>
<InstallationTarget Id="Microsoft.VisualStudio.Code"/>
</Installation>
<Dependencies/>
<Assets>
<Asset Type="Microsoft.VisualStudio.Code.Manifest" Path="extension/package.json" Addressable="true" />
${vsix.assets
.map(asset => `<Asset Type="${escape(asset.type)}" Path="${escape(asset.path)}" Addressable="true" />`)
.join('\n')}
</Assets>
</PackageManifest>`;
}
const defaultMimetypes = new Map<string, string>([
['.json', 'application/json'],
['.vsixmanifest', 'text/xml'],
]);
export async function toContentTypes(files: IFile[]): Promise<string> {
const mimetypes = new Map<string, string>(defaultMimetypes);
for (const file of files) {
const ext = path.extname(file.path).toLowerCase();
if (ext) {
mimetypes.set(ext, mime.lookup(ext));
}
}
const contentTypes: string[] = [];
for (const [extension, contentType] of mimetypes) {
contentTypes.push(`<Default Extension="${extension}" ContentType="${contentType}"/>`);
}
return `<?xml version="1.0" encoding="utf-8"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">${contentTypes.join('')}</Types>
`;
}
const defaultIgnore = [
'.vscodeignore',
'package-lock.json',
'npm-debug.log',
'yarn.lock',
'yarn-error.log',
'npm-shrinkwrap.json',
'.editorconfig',
'.npmrc',
'.yarnrc',
'.gitattributes',
'*.todo',
'tslint.yaml',
'.eslintrc*',
'.babelrc*',
'.prettierrc*',
'.cz-config.js',
'.commitlintrc*',
'webpack.config.js',
'ISSUE_TEMPLATE.md',
'CONTRIBUTING.md',
'PULL_REQUEST_TEMPLATE.md',
'CODE_OF_CONDUCT.md',
'.github',
'.travis.yml',
'appveyor.yml',
'**/.git/**',
'**/*.vsix',
'**/.DS_Store',
'**/*.vsixmanifest',
'**/.vscode-test/**',
'**/.vscode-test-web/**',
];
const notIgnored = ['!package.json', '!README.md'];
async function collectAllFiles(
cwd: string,
dependencies: 'npm' | 'yarn' | 'none' | undefined,
dependencyEntryPoints?: string[]
): Promise<string[]> {
const deps = await getDependencies(cwd, dependencies, dependencyEntryPoints);
const promises = deps.map(dep =>
promisify(glob)('**', { cwd: dep, nodir: true, dot: true, ignore: 'node_modules/**' }).then(files =>
files.map(f => path.relative(cwd, path.join(dep, f))).map(f => f.replace(/\\/g, '/'))
)
);
return Promise.all(promises).then(util.flatten);
}
function collectFiles(
cwd: string,
dependencies: 'npm' | 'yarn' | 'none' | undefined,
dependencyEntryPoints?: string[],
ignoreFile?: string
): Promise<string[]> {
return collectAllFiles(cwd, dependencies, dependencyEntryPoints).then(files => {
files = files.filter(f => !/\r$/m.test(f));
return (
fs.promises
.readFile(ignoreFile ? ignoreFile : path.join(cwd, '.vscodeignore'), 'utf8')
.catch<string>(err =>
err.code !== 'ENOENT' ? Promise.reject(err) : ignoreFile ? Promise.reject(err) : Promise.resolve('')
)
// Parse raw ignore by splitting output into lines and filtering out empty lines and comments
.then(rawIgnore =>
rawIgnore
.split(/[\n\r]/)
.map(s => s.trim())
.filter(s => !!s)
.filter(i => !/^\s*#/.test(i))
)
// Add '/**' to possible folder names
.then(ignore => [
...ignore,
...ignore.filter(i => !/(^|\/)[^/]*\*[^/]*$/.test(i)).map(i => (/\/$/.test(i) ? `${i}**` : `${i}/**`)),
])
// Combine with default ignore list
.then(ignore => [...defaultIgnore, ...ignore, ...notIgnored])
// Split into ignore and negate list
.then(ignore =>
ignore.reduce<[string[], string[]]>(
(r, e) => (!/^\s*!/.test(e) ? [[...r[0], e], r[1]] : [r[0], [...r[1], e]]),
[[], []]
)
)
.then(r => ({ ignore: r[0], negate: r[1] }))
// Filter out files
.then(({ ignore, negate }) =>
files.filter(
f =>
!ignore.some(i => minimatch(f, i, MinimatchOptions)) ||
negate.some(i => minimatch(f, i.substr(1), MinimatchOptions))
)
)
);
});
}
export function processFiles(processors: IProcessor[], files: IFile[]): Promise<IFile[]> {
const processedFiles = files.map(file => util.chain(file, processors, (file, processor) => processor.onFile(file)));
return Promise.all(processedFiles).then(files => {
return util.sequence(processors.map(p => () => p.onEnd())).then(() => {
const assets = processors.reduce<IAsset[]>((r, p) => [...r, ...p.assets], []);
const tags = [
...processors.reduce<Set<string>>((r, p) => {
for (const tag of p.tags) {
if (tag) {
r.add(tag);
}
}
return r;
}, new Set()),
].join(',');
const vsix = processors.reduce<VSIX>((r, p) => ({ ...r, ...p.vsix }), { assets, tags } as VSIX);
return Promise.all([toVsixManifest(vsix), toContentTypes(files)]).then(result => {
return [
{ path: 'extension.vsixmanifest', contents: Buffer.from(result[0], 'utf8') },
{ path: '[Content_Types].xml', contents: Buffer.from(result[1], 'utf8') },
...files,
];
});
});
});
}
export function createDefaultProcessors(manifest: Manifest, options: IPackageOptions = {}): IProcessor[] {
return [
new ManifestProcessor(manifest, options),
new TagsProcessor(manifest),
new ReadmeProcessor(manifest, options),
new ChangelogProcessor(manifest, options),
new LaunchEntryPointProcessor(manifest),
new LicenseProcessor(manifest),
new IconProcessor(manifest),
new NLSProcessor(manifest),
new ValidationProcessor(manifest),
];
}
function getDependenciesOption(options: {
readonly dependencies?: boolean;
readonly useYarn?: boolean;
}): 'npm' | 'yarn' | 'none' | undefined {
if (options.dependencies === false) {
return 'none';
}
switch (options.useYarn) {
case true:
return 'yarn';
case false:
return 'npm';
default:
return undefined;
}
}
export function collect(manifest: Manifest, options: IPackageOptions = {}): Promise<IFile[]> {
const cwd = options.cwd || process.cwd();
const packagedDependencies = options.dependencyEntryPoints || undefined;
const ignoreFile = options.ignoreFile || undefined;
const processors = createDefaultProcessors(manifest, options);
return collectFiles(cwd, getDependenciesOption(options), packagedDependencies, ignoreFile).then(fileNames => {
const files = fileNames.map(f => ({ path: `extension/${f}`, localPath: path.join(cwd, f) }));
return processFiles(processors, files);
});
}
function writeVsix(files: IFile[], packagePath: string): Promise<void> {
return fs.promises
.unlink(packagePath)
.catch(err => (err.code !== 'ENOENT' ? Promise.reject(err) : Promise.resolve(null)))
.then(
() =>
new Promise((c, e) => {
const zip = new yazl.ZipFile();
files.forEach(f =>
isInMemoryFile(f)
? zip.addBuffer(typeof f.contents === 'string' ? Buffer.from(f.contents, 'utf8') : f.contents, f.path, {
mode: f.mode,
})
: zip.addFile(f.localPath, f.path, { mode: f.mode })
);
zip.end();
const zipStream = fs.createWriteStream(packagePath);
zip.outputStream.pipe(zipStream);
zip.outputStream.once('error', e);
zipStream.once('error', e);
zipStream.once('finish', () => c());
})
);
}
function getDefaultPackageName(manifest: Manifest, options: IPackageOptions): string {
let version = manifest.version;
if (options.version && !(options.updatePackageJson ?? true)) {
version = options.version;
}
if (options.target) {
return `${manifest.name}-${options.target}-${version}.vsix`;
}
return `${manifest.name}-${version}.vsix`;
}
export async function prepublish(cwd: string, manifest: Manifest, useYarn?: boolean): Promise<void> {
if (!manifest.scripts || !manifest.scripts['vscode:prepublish']) {
return;
}
if (useYarn === undefined) {
useYarn = await detectYarn(cwd);
}
console.log(`Executing prepublish script '${useYarn ? 'yarn' : 'npm'} run vscode:prepublish'...`);
await new Promise<void>((c, e) => {
const tool = useYarn ? 'yarn' : 'npm';
const child = cp.spawn(tool, ['run', 'vscode:prepublish'], { cwd, shell: true, stdio: 'inherit' });
child.on('exit', code => (code === 0 ? c() : e(`${tool} failed with exit code ${code}`)));
child.on('error', e);
});
}
async function getPackagePath(cwd: string, manifest: Manifest, options: IPackageOptions = {}): Promise<string> {
if (!options.packagePath) {
return path.join(cwd, getDefaultPackageName(manifest, options));
}
try {
const _stat = await fs.promises.stat(options.packagePath);
if (_stat.isDirectory()) {
return path.join(options.packagePath, getDefaultPackageName(manifest, options));
} else {
return options.packagePath;
}
} catch {
return options.packagePath;
}
}
export async function pack(options: IPackageOptions = {}): Promise<IPackageResult> {
const cwd = options.cwd || process.cwd();
const manifest = await readManifest(cwd);
const files = await collect(manifest, options);
const jsFiles = files.filter(f => /\.js$/i.test(f.path));
if (files.length > 5000 || jsFiles.length > 100) {
console.log(
`This extension consists of ${files.length} files, out of which ${jsFiles.length} are JavaScript files. For performance reasons, you should bundle your extension: https://aka.ms/vscode-bundle-extension . You should also exclude unnecessary files by adding them to your .vscodeignore: https://aka.ms/vscode-vscodeignore`
);
}
if (options.version) {
manifest.version = options.version;
}
const packagePath = await getPackagePath(cwd, manifest, options);
await writeVsix(files, path.resolve(packagePath));
return { manifest, packagePath, files };
}
export async function packageCommand(options: IPackageOptions = {}): Promise<any> {
const cwd = options.cwd || process.cwd();
const manifest = await readManifest(cwd);
util.patchOptionsWithManifest(options, manifest);
await prepublish(cwd, manifest, options.useYarn);
await versionBump(options);
const { packagePath, files } = await pack(options);
const stats = await fs.promises.stat(packagePath);
let size = 0;
let unit = '';
if (stats.size > 1048576) {
size = Math.round(stats.size / 10485.76) / 100;
unit = 'MB';
} else {
size = Math.round(stats.size / 10.24) / 100;
unit = 'KB';
}
util.log.done(`Packaged: ${packagePath} (${files.length} files, ${size}${unit})`);
}
export interface IListFilesOptions {
readonly cwd?: string;
readonly useYarn?: boolean;
readonly packagedDependencies?: string[];
readonly ignoreFile?: string;
readonly dependencies?: boolean;
readonly prepublish?: boolean;
}
/**
* Lists the files included in the extension's package.
*/
export async function listFiles(options: IListFilesOptions = {}): Promise<string[]> {
const cwd = options.cwd ?? process.cwd();
const manifest = await readManifest(cwd);
if (options.prepublish) {
await prepublish(cwd, manifest, options.useYarn);
}
return await collectFiles(cwd, getDependenciesOption(options), options.packagedDependencies, options.ignoreFile);
}
/**
* Lists the files included in the extension's package. Runs prepublish.
*/
export async function ls(options: IListFilesOptions = {}): Promise<void> {
const files = await listFiles({ ...options, prepublish: true });
for (const file of files) {
console.log(`${file}`);
}
} | the_stack |
* rest-api.ts contains all entities from the Gerrit REST API that are also
* relevant to plugins and gr-diff users. These entities should be exactly what
* the backend defines and returns and should eventually be generated.
*
* Sorting order:
* - enums in alphabetical order
* - types and interfaces in alphabetical order
* - type checking functions after their corresponding type
*/
/**
* enums =======================================================================
*/
/**
* The authentication type that is configured on the server.
* https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#auth-info
*/
export enum AuthType {
OPENID = 'OPENID',
OPENID_SSO = 'OPENID_SSO',
OAUTH = 'OAUTH',
HTTP = 'HTTP',
HTTP_LDAP = 'HTTP_LDAP',
CLIENT_SSL_CERT_LDAP = 'CLIENT_SSL_CERT_LDAP',
LDAP = 'LDAP',
LDAP_BIND = 'LDAP_BIND',
CUSTOM_EXTENSION = 'CUSTOM_EXTENSION',
DEVELOPMENT_BECOME_ANY_ACCOUNT = 'DEVELOPMENT_BECOME_ANY_ACCOUNT',
}
/**
* @desc Specifies status for a change
*/
export enum ChangeStatus {
ABANDONED = 'ABANDONED',
MERGED = 'MERGED',
NEW = 'NEW',
}
/**
* The type in ConfigParameterInfo entity.
* https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#config-parameter-info
*/
export enum ConfigParameterInfoType {
// Should be kept in sync with
// gerrit/java/com/google/gerrit/extensions/api/projects/ProjectConfigEntryType.java.
STRING = 'STRING',
INT = 'INT',
LONG = 'LONG',
BOOLEAN = 'BOOLEAN',
LIST = 'LIST',
ARRAY = 'ARRAY',
}
/**
* @desc Used for server config of accounts
*/
export enum DefaultDisplayNameConfig {
USERNAME = 'USERNAME',
FIRST_NAME = 'FIRST_NAME',
FULL_NAME = 'FULL_NAME',
}
/**
* Account fields that are editable
* https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#auth-info
*/
export enum EditableAccountField {
FULL_NAME = 'FULL_NAME',
USER_NAME = 'USER_NAME',
REGISTER_NEW_EMAIL = 'REGISTER_NEW_EMAIL',
}
/**
* @desc The status of the file
*/
export enum FileInfoStatus {
ADDED = 'A',
DELETED = 'D',
RENAMED = 'R',
COPIED = 'C',
REWRITTEN = 'W',
// Modifed = 'M', // but API not set it if the file was modified
UNMODIFIED = 'U', // Not returned by BE, but added by UI for certain files
}
/**
* @desc The status of the file
*/
export enum GpgKeyInfoStatus {
BAD = 'BAD',
OK = 'OK',
TRUSTED = 'TRUSTED',
}
/**
* Enum for all http methods used in Gerrit.
*/
export enum HttpMethod {
HEAD = 'HEAD',
POST = 'POST',
GET = 'GET',
DELETE = 'DELETE',
PUT = 'PUT',
}
/**
* Enum for possible configured value in InheritedBooleanInfo.
* https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#inherited-boolean-info
*/
export enum InheritedBooleanInfoConfiguredValue {
TRUE = 'TRUE',
FALSE = 'FALSE',
INHERITED = 'INHERITED',
}
/**
* This setting determines when Gerrit computes if a change is mergeable or not.
* https://gerrit-review.googlesource.com/Documentation/config-gerrit.html#change.mergeabilityComputationBehavior
*/
export enum MergeabilityComputationBehavior {
API_REF_UPDATED_AND_CHANGE_REINDEX = 'API_REF_UPDATED_AND_CHANGE_REINDEX',
REF_UPDATED_AND_CHANGE_REINDEX = 'REF_UPDATED_AND_CHANGE_REINDEX',
NEVER = 'NEVER',
}
/**
* @desc The status of fixing the problem
*/
export enum ProblemInfoStatus {
FIXED = 'FIXED',
FIX_FAILED = 'FIX_FAILED',
}
/**
* @desc The state of the projects
*/
export enum ProjectState {
ACTIVE = 'ACTIVE',
READ_ONLY = 'READ_ONLY',
HIDDEN = 'HIDDEN',
}
/**
* @desc The reviewer state
*/
export enum RequirementStatus {
OK = 'OK',
NOT_READY = 'NOT_READY',
RULE_ERROR = 'RULE_ERROR',
}
/**
* @desc The reviewer state
*/
export enum ReviewerState {
REVIEWER = 'REVIEWER',
CC = 'CC',
REMOVED = 'REMOVED',
}
/**
* @desc The patchset kind
*/
export enum RevisionKind {
REWORK = 'REWORK',
TRIVIAL_REBASE = 'TRIVIAL_REBASE',
MERGE_FIRST_PARENT_UPDATE = 'MERGE_FIRST_PARENT_UPDATE',
NO_CODE_CHANGE = 'NO_CODE_CHANGE',
NO_CHANGE = 'NO_CHANGE',
}
/**
* All supported submit types.
* https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#submit-type-info
*/
export enum SubmitType {
MERGE_IF_NECESSARY = 'MERGE_IF_NECESSARY',
FAST_FORWARD_ONLY = 'FAST_FORWARD_ONLY',
REBASE_IF_NECESSARY = 'REBASE_IF_NECESSARY',
REBASE_ALWAYS = 'REBASE_ALWAYS',
MERGE_ALWAYS = 'MERGE_ALWAYS ',
CHERRY_PICK = 'CHERRY_PICK',
INHERIT = 'INHERIT',
}
/**
* types and interfaces ========================================================
*/
// This is a "meta type", so it comes first and is not sored alphabetically with
// the other types.
export type BrandType<T, BrandName extends string> = T &
{[__brand in BrandName]: never};
export type AccountId = BrandType<number, '_accountId'>;
/**
* The AccountInfo entity contains information about an account.
* https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#account-info
*/
export declare interface AccountInfo {
// Normally _account_id is defined (for known Gerrit users), but users can
// also be CCed just with their email address. So you have to be prepared that
// _account_id is undefined, but then email must be set.
_account_id?: AccountId;
name?: string;
display_name?: string;
// Must be set, if _account_id is undefined.
email?: EmailAddress;
secondary_emails?: string[];
username?: string;
avatars?: AvatarInfo[];
_more_accounts?: boolean; // not set if false
status?: string; // status message of the account
inactive?: boolean; // not set if false
tags?: string[];
}
/**
* The AccountDetailInfo entity contains detailed information about an account.
* https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#account-detail-info
*/
export declare interface AccountDetailInfo extends AccountInfo {
registered_on: Timestamp;
}
/**
* The AccountsConfigInfo entity contains information about Gerrit configuration
* from the accounts section.
* https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#accounts-config-info
*/
export declare interface AccountsConfigInfo {
visibility: string;
default_display_name: DefaultDisplayNameConfig;
}
/**
* The ActionInfo entity describes a REST API call the client can make to
* manipulate a resource. These are frequently implemented by plugins and may
* be discovered at runtime.
* https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#action-info
*/
export declare interface ActionInfo {
method?: HttpMethod; // Most actions use POST, PUT or DELETE to cause state changes.
label?: string; // Short title to display to a user describing the action
title?: string; // Longer text to display describing the action
enabled?: boolean; // not set if false
}
export declare interface ActionNameToActionInfoMap {
[actionType: string]: ActionInfo | undefined;
// List of actions explicitly used in code:
wip?: ActionInfo;
publishEdit?: ActionInfo;
rebaseEdit?: ActionInfo;
deleteEdit?: ActionInfo;
edit?: ActionInfo;
stopEdit?: ActionInfo;
download?: ActionInfo;
rebase?: ActionInfo;
cherrypick?: ActionInfo;
move?: ActionInfo;
revert?: ActionInfo;
revert_submission?: ActionInfo;
abandon?: ActionInfo;
submit?: ActionInfo;
topic?: ActionInfo;
hashtags?: ActionInfo;
ready?: ActionInfo;
includedIn?: ActionInfo;
}
/**
* The ApprovalInfo entity contains information about an approval from auser
* for a label on a change.
* https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#approval-info
*/
export declare interface ApprovalInfo extends AccountInfo {
value?: number;
permitted_voting_range?: VotingRangeInfo;
date?: Timestamp;
tag?: ReviewInputTag;
post_submit?: boolean; // not set if false
}
/**
* The AttentionSetInfo entity contains details of users that are in the attention set.
* https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#attention-set-info
*/
export declare interface AttentionSetInfo {
account: AccountInfo;
last_update?: Timestamp;
reason?: string;
reason_account?: AccountInfo;
}
/**
* The AuthInfo entity contains information about the authentication
* configuration of the Gerrit server.
* https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#auth-info
*/
export declare interface AuthInfo {
auth_type: AuthType; // docs incorrectly names it 'type'
use_contributor_agreements?: boolean;
contributor_agreements?: ContributorAgreementInfo[];
editable_account_fields: EditableAccountField[];
login_url?: string;
login_text?: string;
switch_account_url?: string;
register_url?: string;
register_text?: string;
edit_full_name_url?: string;
http_password_url?: string;
git_basic_auth_policy?: string;
}
/**
* The AvartarInfo entity contains information about an avatar image ofan
* account.
* https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#avatar-info
*/
export declare interface AvatarInfo {
url: string;
height: number;
width: number;
}
export type BasePatchSetNum = BrandType<'PARENT' | number, '_patchSet'>;
// The refs/heads/ prefix is omitted in Branch name
export type BranchName = BrandType<string, '_branchName'>;
/**
* The ChangeConfigInfo entity contains information about Gerrit configuration
* from the change section.
* https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#change-config-info
*/
export declare interface ChangeConfigInfo {
allow_blame?: boolean;
large_change: number;
update_delay: number;
submit_whole_topic?: boolean;
disable_private_changes?: boolean;
mergeability_computation_behavior: MergeabilityComputationBehavior;
}
export type ChangeId = BrandType<string, '_changeId'>;
/**
* The ChangeInfo entity contains information about a change.
* https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#change-info
*/
export declare interface ChangeInfo {
id: ChangeInfoId;
project: RepoName;
branch: BranchName;
topic?: TopicName;
attention_set?: IdToAttentionSetMap;
hashtags?: Hashtag[];
change_id: ChangeId;
subject: string;
status: ChangeStatus;
created: Timestamp;
updated: Timestamp;
submitted?: Timestamp;
submitter?: AccountInfo;
starred?: boolean; // not set if false
stars?: StarLabel[];
submit_type?: SubmitType;
mergeable?: boolean;
submittable?: boolean;
insertions: number; // Number of inserted lines
deletions: number; // Number of deleted lines
total_comment_count?: number;
unresolved_comment_count?: number;
_number: NumericChangeId;
owner: AccountInfo;
actions?: ActionNameToActionInfoMap;
requirements?: Requirement[];
labels?: LabelNameToInfoMap;
permitted_labels?: LabelNameToValueMap;
removable_reviewers?: AccountInfo[];
// This is documented as optional, but actually always set.
reviewers: Reviewers;
pending_reviewers?: AccountInfo[];
reviewer_updates?: ReviewerUpdateInfo[];
messages?: ChangeMessageInfo[];
current_revision?: CommitId;
revisions?: {[revisionId: string]: RevisionInfo};
tracking_ids?: TrackingIdInfo[];
_more_changes?: boolean; // not set if false
problems?: ProblemInfo[];
is_private?: boolean; // not set if false
work_in_progress?: boolean; // not set if false
has_review_started?: boolean; // not set if false
revert_of?: NumericChangeId;
submission_id?: ChangeSubmissionId;
cherry_pick_of_change?: NumericChangeId;
cherry_pick_of_patch_set?: PatchSetNum;
contains_git_conflicts?: boolean;
internalHost?: string; // TODO(TS): provide an explanation what is its
submit_requirements?: SubmitRequirementResultInfo[];
submit_records?: SubmitRecordInfo[];
}
// The ID of the change in the format "'<project>~<branch>~<Change-Id>'"
export type ChangeInfoId = BrandType<string, '_changeInfoId'>;
export type ChangeMessageId = BrandType<string, '_changeMessageId'>;
/**
* The ChangeMessageInfo entity contains information about a message attached
* to a change.
* https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#change-message-info
*/
export declare interface ChangeMessageInfo {
id: ChangeMessageId;
author?: AccountInfo;
reviewer?: AccountInfo;
updated_by?: AccountInfo;
real_author?: AccountInfo;
date: Timestamp;
message: string;
accounts_in_message?: AccountInfo[];
tag?: ReviewInputTag;
_revision_number?: PatchSetNum;
}
// This ID is equal to the numeric ID of the change that triggered the
// submission. If the change that triggered the submission also has a topic, it
// will be "<id>-<topic>" of the change that triggered the submission
// The callers must not rely on the format of the submission ID.
export type ChangeSubmissionId = BrandType<
string | number,
'_changeSubmissionId'
>;
export type CloneCommandMap = {[name: string]: string};
/**
* The CommentLinkInfo entity describes acommentlink.
* https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#commentlink-info
*/
export declare interface CommentLinkInfo {
match: string;
link?: string;
enabled?: boolean;
html?: string;
}
export declare interface CommentLinks {
[name: string]: CommentLinkInfo;
}
export type CommitId = BrandType<string, '_commitId'>;
/**
* The CommitInfo entity contains information about a commit.
* https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#commit-info
*/
export declare interface CommitInfo {
commit?: CommitId;
parents: ParentCommitInfo[];
author: GitPersonInfo;
committer: GitPersonInfo;
subject: string;
message: string;
web_links?: WebLinkInfo[];
resolve_conflicts_web_links?: WebLinkInfo[];
}
export declare interface ConfigArrayParameterInfo
extends ConfigParameterInfoBase {
type: ConfigParameterInfoType.ARRAY;
values: string[];
}
/**
* The ConfigInfo entity contains information about the effective
* project configuration.
* https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#config-info
*/
export declare interface ConfigInfo {
description?: string;
use_contributor_agreements?: InheritedBooleanInfo;
use_content_merge?: InheritedBooleanInfo;
use_signed_off_by?: InheritedBooleanInfo;
create_new_change_for_all_not_in_target?: InheritedBooleanInfo;
require_change_id?: InheritedBooleanInfo;
enable_signed_push?: InheritedBooleanInfo;
require_signed_push?: InheritedBooleanInfo;
reject_implicit_merges?: InheritedBooleanInfo;
private_by_default: InheritedBooleanInfo;
work_in_progress_by_default: InheritedBooleanInfo;
max_object_size_limit: MaxObjectSizeLimitInfo;
default_submit_type: SubmitTypeInfo;
submit_type: SubmitType;
match_author_to_committer_date?: InheritedBooleanInfo;
state?: ProjectState;
commentlinks: CommentLinks;
plugin_config?: PluginNameToPluginParametersMap;
actions?: {[viewName: string]: ActionInfo};
reject_empty_commit?: InheritedBooleanInfo;
enable_reviewer_by_email: InheritedBooleanInfo;
}
export declare interface ConfigListParameterInfo
extends ConfigParameterInfoBase {
type: ConfigParameterInfoType.LIST;
permitted_values?: string[];
}
export type ConfigParameterInfo =
| ConfigParameterInfoBase
| ConfigArrayParameterInfo
| ConfigListParameterInfo;
/**
* The ConfigParameterInfo entity describes a project configurationparameter.
* https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#config-parameter-info
*/
export declare interface ConfigParameterInfoBase {
display_name?: string;
description?: string;
warning?: string;
type: ConfigParameterInfoType;
value?: string;
values?: string[];
editable?: boolean;
permitted_values?: string[];
inheritable?: boolean;
configured_value?: string;
inherited_value?: string;
}
// https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#contributor-agreement-info
export declare interface ContributorAgreementInfo {
name: string;
description: string;
url: string;
auto_verify_group?: GroupInfo;
}
/**
* LabelInfo when DETAILED_LABELS are requested.
* https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#_fields_set_by_code_detailed_labels_code
*/
export declare interface DetailedLabelInfo extends LabelCommonInfo {
// This is not set when the change has no reviewers.
all?: ApprovalInfo[];
// Docs claim that 'values' is optional, but it is actually always set.
values?: LabelValueToDescriptionMap; // A map of all values that are allowed for this label
default_value?: number;
}
export function isDetailedLabelInfo(
label: LabelInfo
): label is DetailedLabelInfo | (QuickLabelInfo & DetailedLabelInfo) {
return !!(label as DetailedLabelInfo).values;
}
/**
* The DownloadInfo entity contains information about supported download
* options.
* https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#download-info
*/
export declare interface DownloadInfo {
schemes: SchemesInfoMap;
archives: string[];
}
/**
* The DownloadSchemeInfo entity contains information about a supported download
* scheme and its commands.
* https://gerrit-review.googlesource.com/Documentation/rest-api-config.html
*/
export declare interface DownloadSchemeInfo {
url: string;
is_auth_required: boolean;
is_auth_supported: boolean;
commands: string;
clone_commands: CloneCommandMap;
}
export type EmailAddress = BrandType<string, '_emailAddress'>;
/**
* The FetchInfo entity contains information about how to fetch a patchset via
* a certain protocol.
* https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#fetch-info
*/
export declare interface FetchInfo {
url: string;
ref: string;
commands?: {[commandName: string]: string};
}
/**
* The FileInfo entity contains information about a file in a patch set.
* https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#file-info
*/
export declare interface FileInfo {
status?: FileInfoStatus;
binary?: boolean; // not set if false
old_path?: string;
lines_inserted?: number;
lines_deleted?: number;
size_delta: number; // in bytes
size: number; // in bytes
}
/**
* The GerritInfo entity contains information about Gerrit configuration from
* the gerrit section.
* https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#gerrit-info
*/
export declare interface GerritInfo {
all_projects: string; // Doc contains incorrect name
all_users: string; // Doc contains incorrect name
doc_search: boolean;
doc_url?: string;
edit_gpg_keys?: boolean;
report_bug_url?: string;
// The following property is missed in doc
primary_weblink_name?: string;
}
export type GitRef = BrandType<string, '_gitRef'>;
// The 40-char (plus spaces) hex GPG key fingerprint
export type GpgKeyFingerprint = BrandType<string, '_gpgKeyFingerprint'>;
// The 8-char hex GPG key ID.
export type GpgKeyId = BrandType<string, '_gpgKeyId'>;
/**
* The GpgKeyInfo entity contains information about a GPG public key.
* https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#gpg-key-info
*/
export declare interface GpgKeyInfo {
id?: GpgKeyId;
fingerprint?: GpgKeyFingerprint;
user_ids?: OpenPgpUserIds[];
key?: string; // ASCII armored public key material
status?: GpgKeyInfoStatus;
problems?: string[];
}
/**
* The GitPersonInfo entity contains information about theauthor/committer of
* a commit.
* https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#git-person-info
*/
export declare interface GitPersonInfo {
name: string;
email: EmailAddress;
date: Timestamp;
tz: TimezoneOffset;
}
export type GroupId = BrandType<string, '_groupId'>;
/**
* The GroupInfo entity contains information about a group. This can be a
* Gerrit internal group, or an external group that is known to Gerrit.
* https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#group-info
*/
export declare interface GroupInfo {
id: GroupId;
name?: GroupName;
url?: string;
options?: GroupOptionsInfo;
description?: string;
group_id?: number;
owner?: string;
owner_id?: string;
created_on?: string;
_more_groups?: boolean;
members?: AccountInfo[];
includes?: GroupInfo[];
}
export type GroupName = BrandType<string, '_groupName'>;
/**
* Options of the group.
* https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html
*/
export declare interface GroupOptionsInfo {
visible_to_all: boolean;
}
export type Hashtag = BrandType<string, '_hashtag'>;
export type IdToAttentionSetMap = {[accountId: string]: AttentionSetInfo};
/**
* A boolean value that can also be inherited.
* https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#inherited-boolean-info
*/
export declare interface InheritedBooleanInfo {
value: boolean;
configured_value: InheritedBooleanInfoConfiguredValue;
inherited_value?: boolean;
}
export declare interface LabelCommonInfo {
optional?: boolean; // not set if false
}
export type LabelNameToInfoMap = {[labelName: string]: LabelInfo};
// {Verified: ["-1", " 0", "+1"]}
export type LabelNameToValueMap = {[labelName: string]: string[]};
/**
* The LabelInfo entity contains information about a label on a change, always
* corresponding to the current patch set.
* https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#label-info
*/
export type LabelInfo =
| QuickLabelInfo
| DetailedLabelInfo
| (QuickLabelInfo & DetailedLabelInfo);
export type LabelNameToLabelTypeInfoMap = {[labelName: string]: LabelTypeInfo};
/**
* The LabelTypeInfo entity contains metadata about the labels that a project
* has.
* https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#label-type-info
*/
export declare interface LabelTypeInfo {
values: LabelTypeInfoValues;
default_value: number;
}
export type LabelTypeInfoValues = {[value: string]: string};
// The map maps the values (“-2”, “-1”, " `0`", “+1”, “+2”) to the value descriptions.
export type LabelValueToDescriptionMap = {[labelValue: string]: string};
/**
* The MaxObjectSizeLimitInfo entity contains information about the max object
* size limit of a project.
* https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#max-object-size-limit-info
*/
export declare interface MaxObjectSizeLimitInfo {
value?: string;
configured_value?: string;
summary?: string;
}
export type NumericChangeId = BrandType<number, '_numericChangeId'>;
// OpenPGP User IDs (https://tools.ietf.org/html/rfc4880#section-5.11).
export type OpenPgpUserIds = BrandType<string, '_openPgpUserIds'>;
/**
* The parent commits of this commit as a list of CommitInfo entities.
* In each parent only the commit and subject fields are populated.
* https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#commit-info
*/
export declare interface ParentCommitInfo {
commit: CommitId;
subject: string;
}
export type PatchSetNum = BrandType<'PARENT' | 'edit' | number, '_patchSet'>;
/**
* The PluginConfigInfo entity contains information about Gerrit extensions by
* plugins.
* https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#plugin-config-info
*/
export declare interface PluginConfigInfo {
has_avatars: boolean;
// Exists in Java class, but not mentioned in docs.
js_resource_paths: string[];
}
/**
* Plugin configuration values as map which maps the plugin name to a map of parameter names to values
* https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#config-input
*/
export type PluginNameToPluginParametersMap = {
[pluginName: string]: PluginParameterToConfigParameterInfoMap;
};
export type PluginParameterToConfigParameterInfoMap = {
[parameterName: string]: ConfigParameterInfo;
};
/**
* The ProblemInfo entity contains a description of a potential consistency
* problem with a change. These are not related to the code review process,
* but rather indicate some inconsistency in Gerrit’s database or repository
* metadata related to the enclosing change.
* https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#problem-info
*/
export declare interface ProblemInfo {
message: string;
status?: ProblemInfoStatus; // Only set if a fix was attempted
outcome?: string;
}
/**
* The ProjectInfo entity contains information about a project
* https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#project-info
*/
export declare interface ProjectInfo {
id: UrlEncodedRepoName;
// name is not set if returned in a map where the project name is used as
// map key
name?: RepoName;
// ?-<n> if the parent project is not visible (<n> is a number which
// is increased for each non-visible project).
parent?: RepoName;
description?: string;
state?: ProjectState;
branches?: {[branchName: string]: CommitId};
// labels is filled for Create Project and Get Project calls.
labels?: LabelNameToLabelTypeInfoMap;
// Links to the project in external sites
web_links?: WebLinkInfo[];
}
export declare interface ProjectInfoWithName extends ProjectInfo {
name: RepoName;
}
/**
* The PushCertificateInfo entity contains information about a pushcertificate
* provided when the user pushed for review with git push
* --signed HEAD:refs/for/<branch>. Only used when signed push is
* enabled on the server.
* https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#push-certificate-info
*/
export declare interface PushCertificateInfo {
certificate: string;
key: GpgKeyInfo;
}
export declare interface QuickLabelInfo extends LabelCommonInfo {
approved?: AccountInfo;
rejected?: AccountInfo;
recommended?: AccountInfo;
disliked?: AccountInfo;
blocking?: boolean; // not set if false
value?: number; // The voting value of the user who recommended/disliked this label on the change if it is not “+1”/“-1”.
default_value?: number;
}
export function isQuickLabelInfo(
l: LabelInfo
): l is QuickLabelInfo | (QuickLabelInfo & DetailedLabelInfo) {
const quickLabelInfo = l as QuickLabelInfo;
return (
quickLabelInfo.approved !== undefined ||
quickLabelInfo.rejected !== undefined ||
quickLabelInfo.recommended !== undefined ||
quickLabelInfo.disliked !== undefined ||
quickLabelInfo.blocking !== undefined ||
quickLabelInfo.blocking !== undefined ||
quickLabelInfo.value !== undefined
);
}
/**
* The ReceiveInfo entity contains information about the configuration of
* git-receive-pack behavior on the server.
* https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#receive-info
*/
export declare interface ReceiveInfo {
enable_signed_push?: string;
}
export type RepoName = BrandType<string, '_repoName'>;
/**
* The Requirement entity contains information about a requirement relative to
* a change.
* https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#requirement
*/
export declare interface Requirement {
status: RequirementStatus;
fallbackText: string; // A human readable reason
type: RequirementType;
}
export type RequirementType = BrandType<string, '_requirementType'>;
/**
* The reviewers as a map that maps a reviewer state to a list of AccountInfo
* entities. Possible reviewer states are REVIEWER, CC and REMOVED.
* REVIEWER: Users with at least one non-zero vote on the change.
* CC: Users that were added to the change, but have not voted.
* REMOVED: Users that were previously reviewers on the change, but have been removed.
*/
export type Reviewers = Partial<Record<ReviewerState, AccountInfo[]>>;
/**
* The ReviewerUpdateInfo entity contains information about updates to change’s
* reviewers set.
* https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#review-update-info
*/
export declare interface ReviewerUpdateInfo {
updated: Timestamp;
updated_by: AccountInfo;
reviewer: AccountInfo;
state: ReviewerState;
}
export type ReviewInputTag = BrandType<string, '_reviewInputTag'>;
/**
* The RevisionInfo entity contains information about a patch set.Not all
* fields are returned by default. Additional fields can be obtained by
* adding o parameters as described in Query Changes.
* https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#revision-info
* basePatchNum is present in case RevisionInfo is of type 'edit'
*/
export declare interface RevisionInfo {
kind: RevisionKind;
_number: PatchSetNum;
created: Timestamp;
uploader: AccountInfo;
ref: GitRef;
fetch?: {[protocol: string]: FetchInfo};
commit?: CommitInfo;
files?: {[filename: string]: FileInfo};
reviewed?: boolean;
commit_with_footers?: boolean;
push_certificate?: PushCertificateInfo;
description?: string;
basePatchNum?: BasePatchSetNum;
}
export type SchemesInfoMap = {[name: string]: DownloadSchemeInfo};
/**
* The ServerInfo entity contains information about the configuration of the
* Gerrit server.
* https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#server-info
*/
export declare interface ServerInfo {
accounts: AccountsConfigInfo;
auth: AuthInfo;
change: ChangeConfigInfo;
download: DownloadInfo;
gerrit: GerritInfo;
// docs mentions index property, but it doesn't exists in Java class
// index: IndexConfigInfo;
note_db_enabled?: boolean;
plugin: PluginConfigInfo;
receive?: ReceiveInfo;
sshd?: SshdInfo;
suggest: SuggestInfo;
user: UserConfigInfo;
default_theme?: string;
}
/**
* The SshdInfo entity contains information about Gerrit configuration from the sshd section.
* https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#sshd-info
* This entity doesn’t contain any data, but the presence of this (empty) entity
* in the ServerInfo entity means that SSHD is enabled on the server.
*/
export type SshdInfo = {};
export type StarLabel = BrandType<string, '_startLabel'>;
// Timestamps are given in UTC and have the format
// "'yyyy-mm-dd hh:mm:ss.fffffffff'"
// where "'ffffffffff'" represents nanoseconds.
/**
* Information about the default submittype of a project, taking into account
* project inheritance.
* https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#submit-type-info
*/
export declare interface SubmitTypeInfo {
value: Exclude<SubmitType, SubmitType.INHERIT>;
configured_value: SubmitType;
inherited_value: Exclude<SubmitType, SubmitType.INHERIT>;
}
/**
* The SuggestInfo entity contains information about Gerritconfiguration from
* the suggest section.
* https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#suggest-info
*/
export declare interface SuggestInfo {
from: number;
}
export type Timestamp = BrandType<string, '_timestamp'>;
// The timezone offset from UTC in minutes
export type TimezoneOffset = BrandType<number, '_timezoneOffset'>;
export type TopicName = BrandType<string, '_topicName'>;
export type TrackingId = BrandType<string, '_trackingId'>;
/**
* The TrackingIdInfo entity describes a reference to an external tracking
* system.
* https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#tracking-id-info
*/
export declare interface TrackingIdInfo {
system: string;
id: TrackingId;
}
/**
* The UserConfigInfo entity contains information about Gerrit configuration
* from the user section.
* https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#user-config-info
*/
export declare interface UserConfigInfo {
anonymous_coward_name: string;
}
/**
* The VotingRangeInfo entity describes the continuous voting range from minto
* max values.
* https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#voting-range-info
*/
export declare interface VotingRangeInfo {
min: number;
max: number;
}
/**
* The WebLinkInfo entity describes a link to an external site.
* https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#web-link-info
*/
export declare interface WebLinkInfo {
/** The link name. */
name: string;
/** The link URL. */
url: string;
/** URL to the icon of the link. */
image_url?: string;
/* Value of the "target" attribute for anchor elements. */
target?: string;
}
/**
* The SubmitRequirementResultInfo describes the result of evaluating
* a submit requirement on a change.
* https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#submit-requirement-result-info
*/
export declare interface SubmitRequirementResultInfo {
name: string;
description?: string;
status: SubmitRequirementStatus;
applicability_expression_result?: SubmitRequirementExpressionInfo;
submittability_expression_result: SubmitRequirementExpressionInfo;
override_expression_result?: SubmitRequirementExpressionInfo;
is_legacy?: boolean;
}
/**
* The SubmitRequirementExpressionInfo describes the result of evaluating
* a single submit requirement expression, for example label:code-review=+2.
* https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#submit-requirement-expression-info
*/
export declare interface SubmitRequirementExpressionInfo {
expression: string;
fulfilled: boolean;
passing_atoms: string[];
failing_atoms: string[];
}
/**
* Status describing the result of evaluating the submit requirement.
* https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#submit-requirement-result-info
*/
export enum SubmitRequirementStatus {
SATISFIED = 'SATISFIED',
UNSATISFIED = 'UNSATISFIED',
OVERRIDDEN = 'OVERRIDDEN',
NOT_APPLICABLE = 'NOT_APPLICABLE',
ERROR = 'ERROR',
FORCED = 'FORCED',
}
export type UrlEncodedRepoName = BrandType<string, '_urlEncodedRepoName'>;
/**
* The SubmitRecordInfo entity describes results from a submit_rule.
* https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#submit-record-info
*/
export declare interface SubmitRecordInfo {
rule_name: string;
status?: SubmitRecordInfoStatus;
labels?: SubmitRecordInfoLabel[];
requirements?: Requirement[];
error_message?: string;
}
export enum SubmitRecordInfoStatus {
OK = 'OK',
NOT_READY = 'NOT_READY',
CLOSED = 'CLOSED',
FORCED = 'FORCED',
RULE_ERROR = 'RULE_ERROR',
}
export enum LabelStatus {
/**
* This label provides what is necessary for submission.
*/
OK = 'OK',
/**
* This label prevents the change from being submitted.
*/
REJECT = 'REJECT',
/**
* The label may be set, but it's neither necessary for submission
* nor does it block submission if set.
*/
MAY = 'MAY',
/**
* The label is required for submission, but has not been satisfied.
*/
NEED = 'NEED',
/**
* The label is required for submission, but is impossible to complete.
* The likely cause is access has not been granted correctly by the
* project owner or site administrator.
*/
IMPOSSIBLE = 'IMPOSSIBLE',
OPTIONAL = 'OPTIONAL',
}
/**
* https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#submit-record-info
*/
export declare interface SubmitRecordInfoLabel {
label: string;
status: LabelStatus;
appliedBy: AccountInfo;
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs } from "../types";
import * as utilities from "../utilities";
/**
* Jobs are actions that BigQuery runs on your behalf to load data, export data, query data, or copy data.
* Once a BigQuery job is created, it cannot be changed or deleted.
*
* To get more information about Job, see:
*
* * [API documentation](https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs)
* * How-to Guides
* * [BigQuery Jobs Intro](https://cloud.google.com/bigquery/docs/jobs-overview)
*
* ## Example Usage
* ### Bigquery Job Query
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const bar = new gcp.bigquery.Dataset("bar", {
* datasetId: "job_query_dataset",
* friendlyName: "test",
* description: "This is a test description",
* location: "US",
* });
* const foo = new gcp.bigquery.Table("foo", {
* deletionProtection: false,
* datasetId: bar.datasetId,
* tableId: "job_query_table",
* });
* const job = new gcp.bigquery.Job("job", {
* jobId: "job_query",
* labels: {
* "example-label": "example-value",
* },
* query: {
* query: "SELECT state FROM [lookerdata:cdc.project_tycho_reports]",
* destinationTable: {
* projectId: foo.project,
* datasetId: foo.datasetId,
* tableId: foo.tableId,
* },
* allowLargeResults: true,
* flattenResults: true,
* scriptOptions: {
* keyResultStatement: "LAST",
* },
* },
* });
* ```
* ### Bigquery Job Query Table Reference
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const bar = new gcp.bigquery.Dataset("bar", {
* datasetId: "job_query_dataset",
* friendlyName: "test",
* description: "This is a test description",
* location: "US",
* });
* const foo = new gcp.bigquery.Table("foo", {
* deletionProtection: false,
* datasetId: bar.datasetId,
* tableId: "job_query_table",
* });
* const job = new gcp.bigquery.Job("job", {
* jobId: "job_query",
* labels: {
* "example-label": "example-value",
* },
* query: {
* query: "SELECT state FROM [lookerdata:cdc.project_tycho_reports]",
* destinationTable: {
* tableId: foo.id,
* },
* defaultDataset: {
* datasetId: bar.id,
* },
* allowLargeResults: true,
* flattenResults: true,
* scriptOptions: {
* keyResultStatement: "LAST",
* },
* },
* });
* ```
* ### Bigquery Job Load
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const bar = new gcp.bigquery.Dataset("bar", {
* datasetId: "job_load_dataset",
* friendlyName: "test",
* description: "This is a test description",
* location: "US",
* });
* const foo = new gcp.bigquery.Table("foo", {
* deletionProtection: false,
* datasetId: bar.datasetId,
* tableId: "job_load_table",
* });
* const job = new gcp.bigquery.Job("job", {
* jobId: "job_load",
* labels: {
* my_job: "load",
* },
* load: {
* sourceUris: ["gs://cloud-samples-data/bigquery/us-states/us-states-by-date.csv"],
* destinationTable: {
* projectId: foo.project,
* datasetId: foo.datasetId,
* tableId: foo.tableId,
* },
* skipLeadingRows: 1,
* schemaUpdateOptions: [
* "ALLOW_FIELD_RELAXATION",
* "ALLOW_FIELD_ADDITION",
* ],
* writeDisposition: "WRITE_APPEND",
* autodetect: true,
* },
* });
* ```
* ### Bigquery Job Extract
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const source_oneDataset = new gcp.bigquery.Dataset("source-oneDataset", {
* datasetId: "job_extract_dataset",
* friendlyName: "test",
* description: "This is a test description",
* location: "US",
* });
* const source_oneTable = new gcp.bigquery.Table("source-oneTable", {
* deletionProtection: false,
* datasetId: source_oneDataset.datasetId,
* tableId: "job_extract_table",
* schema: `[
* {
* "name": "name",
* "type": "STRING",
* "mode": "NULLABLE"
* },
* {
* "name": "post_abbr",
* "type": "STRING",
* "mode": "NULLABLE"
* },
* {
* "name": "date",
* "type": "DATE",
* "mode": "NULLABLE"
* }
* ]
* `,
* });
* const dest = new gcp.storage.Bucket("dest", {
* location: "US",
* forceDestroy: true,
* });
* const job = new gcp.bigquery.Job("job", {
* jobId: "job_extract",
* extract: {
* destinationUris: [pulumi.interpolate`${dest.url}/extract`],
* sourceTable: {
* projectId: source_oneTable.project,
* datasetId: source_oneTable.datasetId,
* tableId: source_oneTable.tableId,
* },
* destinationFormat: "NEWLINE_DELIMITED_JSON",
* compression: "GZIP",
* },
* });
* ```
*
* ## Import
*
* Job can be imported using any of these accepted formats
*
* ```sh
* $ pulumi import gcp:bigquery/job:Job default projects/{{project}}/jobs/{{job_id}}/location/{{location}}
* ```
*
* ```sh
* $ pulumi import gcp:bigquery/job:Job default projects/{{project}}/jobs/{{job_id}}
* ```
*
* ```sh
* $ pulumi import gcp:bigquery/job:Job default {{project}}/{{job_id}}/{{location}}
* ```
*
* ```sh
* $ pulumi import gcp:bigquery/job:Job default {{job_id}}/{{location}}
* ```
*
* ```sh
* $ pulumi import gcp:bigquery/job:Job default {{project}}/{{job_id}}
* ```
*
* ```sh
* $ pulumi import gcp:bigquery/job:Job default {{job_id}}
* ```
*/
export class Job extends pulumi.CustomResource {
/**
* Get an existing Job 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?: JobState, opts?: pulumi.CustomResourceOptions): Job {
return new Job(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'gcp:bigquery/job:Job';
/**
* Returns true if the given object is an instance of Job. 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 Job {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === Job.__pulumiType;
}
/**
* Copies a table.
* Structure is documented below.
*/
public readonly copy!: pulumi.Output<outputs.bigquery.JobCopy | undefined>;
/**
* Configures an extract job.
* Structure is documented below.
*/
public readonly extract!: pulumi.Output<outputs.bigquery.JobExtract | undefined>;
/**
* The ID of the job. The ID must contain only letters (a-z, A-Z), numbers (0-9), underscores (_), or dashes (-). The maximum length is 1,024 characters.
*/
public readonly jobId!: pulumi.Output<string>;
/**
* Job timeout in milliseconds. If this time limit is exceeded, BigQuery may attempt to terminate the job.
*/
public readonly jobTimeoutMs!: pulumi.Output<string | undefined>;
/**
* The type of the job.
*/
public /*out*/ readonly jobType!: pulumi.Output<string>;
/**
* The labels associated with this job. You can use these to organize and group your jobs.
*/
public readonly labels!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* Configures a load job.
* Structure is documented below.
*/
public readonly load!: pulumi.Output<outputs.bigquery.JobLoad | undefined>;
/**
* The geographic location of the job. The default value is US.
*/
public readonly location!: pulumi.Output<string | undefined>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
public readonly project!: pulumi.Output<string>;
/**
* Configures a query job.
* Structure is documented below.
*/
public readonly query!: pulumi.Output<outputs.bigquery.JobQuery | undefined>;
/**
* The status of this job. Examine this value when polling an asynchronous job to see if the job is complete.
*/
public /*out*/ readonly statuses!: pulumi.Output<outputs.bigquery.JobStatus[]>;
/**
* Email address of the user who ran the job.
*/
public /*out*/ readonly userEmail!: pulumi.Output<string>;
/**
* Create a Job 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: JobArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: JobArgs | JobState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as JobState | undefined;
inputs["copy"] = state ? state.copy : undefined;
inputs["extract"] = state ? state.extract : undefined;
inputs["jobId"] = state ? state.jobId : undefined;
inputs["jobTimeoutMs"] = state ? state.jobTimeoutMs : undefined;
inputs["jobType"] = state ? state.jobType : undefined;
inputs["labels"] = state ? state.labels : undefined;
inputs["load"] = state ? state.load : undefined;
inputs["location"] = state ? state.location : undefined;
inputs["project"] = state ? state.project : undefined;
inputs["query"] = state ? state.query : undefined;
inputs["statuses"] = state ? state.statuses : undefined;
inputs["userEmail"] = state ? state.userEmail : undefined;
} else {
const args = argsOrState as JobArgs | undefined;
if ((!args || args.jobId === undefined) && !opts.urn) {
throw new Error("Missing required property 'jobId'");
}
inputs["copy"] = args ? args.copy : undefined;
inputs["extract"] = args ? args.extract : undefined;
inputs["jobId"] = args ? args.jobId : undefined;
inputs["jobTimeoutMs"] = args ? args.jobTimeoutMs : undefined;
inputs["labels"] = args ? args.labels : undefined;
inputs["load"] = args ? args.load : undefined;
inputs["location"] = args ? args.location : undefined;
inputs["project"] = args ? args.project : undefined;
inputs["query"] = args ? args.query : undefined;
inputs["jobType"] = undefined /*out*/;
inputs["statuses"] = undefined /*out*/;
inputs["userEmail"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(Job.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering Job resources.
*/
export interface JobState {
/**
* Copies a table.
* Structure is documented below.
*/
copy?: pulumi.Input<inputs.bigquery.JobCopy>;
/**
* Configures an extract job.
* Structure is documented below.
*/
extract?: pulumi.Input<inputs.bigquery.JobExtract>;
/**
* The ID of the job. The ID must contain only letters (a-z, A-Z), numbers (0-9), underscores (_), or dashes (-). The maximum length is 1,024 characters.
*/
jobId?: pulumi.Input<string>;
/**
* Job timeout in milliseconds. If this time limit is exceeded, BigQuery may attempt to terminate the job.
*/
jobTimeoutMs?: pulumi.Input<string>;
/**
* The type of the job.
*/
jobType?: pulumi.Input<string>;
/**
* The labels associated with this job. You can use these to organize and group your jobs.
*/
labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* Configures a load job.
* Structure is documented below.
*/
load?: pulumi.Input<inputs.bigquery.JobLoad>;
/**
* The geographic location of the job. The default value is US.
*/
location?: pulumi.Input<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* Configures a query job.
* Structure is documented below.
*/
query?: pulumi.Input<inputs.bigquery.JobQuery>;
/**
* The status of this job. Examine this value when polling an asynchronous job to see if the job is complete.
*/
statuses?: pulumi.Input<pulumi.Input<inputs.bigquery.JobStatus>[]>;
/**
* Email address of the user who ran the job.
*/
userEmail?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a Job resource.
*/
export interface JobArgs {
/**
* Copies a table.
* Structure is documented below.
*/
copy?: pulumi.Input<inputs.bigquery.JobCopy>;
/**
* Configures an extract job.
* Structure is documented below.
*/
extract?: pulumi.Input<inputs.bigquery.JobExtract>;
/**
* The ID of the job. The ID must contain only letters (a-z, A-Z), numbers (0-9), underscores (_), or dashes (-). The maximum length is 1,024 characters.
*/
jobId: pulumi.Input<string>;
/**
* Job timeout in milliseconds. If this time limit is exceeded, BigQuery may attempt to terminate the job.
*/
jobTimeoutMs?: pulumi.Input<string>;
/**
* The labels associated with this job. You can use these to organize and group your jobs.
*/
labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* Configures a load job.
* Structure is documented below.
*/
load?: pulumi.Input<inputs.bigquery.JobLoad>;
/**
* The geographic location of the job. The default value is US.
*/
location?: pulumi.Input<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* Configures a query job.
* Structure is documented below.
*/
query?: pulumi.Input<inputs.bigquery.JobQuery>;
} | the_stack |
namespace ergometer {
import IRawCommand = ergometer.csafe.IRawCommand;
export interface SendBufferQueued {
commandArray: number[],
resolve : ()=>void,
reject : (e)=>void,
rawCommandBuffer: IRawCommand[]
}
export interface ParsedCSafeCommand {
command: number;
detailCommand : number;
data : Uint8Array;
}
export const enum FrameState {initial,statusByte,parseCommand,parseCommandLength,
parseDetailCommand,parseDetailCommandLength,parseCommandData}
export interface PowerCurveEvent extends pubSub.ISubscription {
(data : number[]) : void;
}
export class WaitResponseBuffer implements ergometer.csafe.IResponseBuffer {
//variables for parsing the csafe buffer
//needs to be in the buffer because the parsing can be split
//over multiple messages
public command =0;
public commandDataIndex =0;
public commandData : Uint8Array;
public frameState = FrameState.initial;
public nextDataLength = 0;
public detailCommand =0;
public statusByte = 0;
public monitorStatus : ergometer.csafe.SlaveState = 0;
public prevFrameState : ergometer.csafe.PrevFrameState =0;
public calcCheck=0;
private _monitor : PerformanceMonitorBase;
//commands where we are waiting for
private _commands : csafe.IRawCommand[] = [];
public _resolve : ()=>void;// only for internal use
/** @internal */
public _reject : (e : any)=>void;// only for internal use
public _responseState: number;
private _timeOutHandle: number;
stuffByteActive: boolean = false;
endCommand: number;
public get commands() : csafe.IRawCommand[] {
return this._commands
}
removeRemainingCommands() {
this._commands.forEach(command=>{
if (this._monitor.logLevel>=LogLevel.error)
this._monitor.handleError(`command removed without result command=${command.command} detial= ${command.detailCommand}`);
if (command.onError) command.onError("command removed without result");
});
this._commands=[];
}
private timeOut() {
this.removeRemainingCommands();
this.remove();
if (this._reject)
this._reject("Time out buffer");
if (this._monitor.logLevel>=LogLevel.error)
this._monitor.handleError("buffer time out");
}
constructor (monitor : PerformanceMonitorBase,
resolve : ()=>void, reject : (e)=>void,
commands : csafe.IRawCommand[],
timeOut : number) {
this._monitor = monitor;
this._resolve=resolve;
this._reject=reject;
this._timeOutHandle= setTimeout(this.timeOut.bind(this),timeOut);
commands.forEach((command : IRawCommand)=> {
if (command.waitForResponse)
this._commands.push(command);
});
}
public remove() {
if (this._timeOutHandle) {
clearTimeout(this._timeOutHandle);
this._timeOutHandle=null;
}
this._monitor.removeResponseBuffer(this);
}
public processedBuffer() {
this.removeRemainingCommands();
this.remove();
if (this._resolve)
this._resolve();
}
public removedWithError(e : any) {
this._commands.forEach((command : IRawCommand)=>{
if (command.onError) command.onError(e);
});
if (this._reject)
this._reject(e);
}
public receivedCSaveCommand(parsed : ParsedCSafeCommand) {
if (this._monitor.logLevel==LogLevel.trace)
this._monitor.traceInfo("received command:"+JSON.stringify(parsed));
//check on all the commands which where send and
for(let i=0;i<this._commands.length;i++){
let command=this._commands[i];
if (command.command==parsed.command &&
( command.detailCommand==parsed.detailCommand ||
(!command.detailCommand && !parsed.detailCommand) )
) {
if (command.onDataReceived) {
var dataView= new DataView(parsed.data.buffer);
this._monitor.traceInfo("call received");
command.responseBuffer=this;
command.onDataReceived(dataView);
}
this._commands.splice(i,1);//remove the item from the send list
break;
}
}
}
}
type EmptyResolveFunc = ()=>void;
/**
*
* Usage:
*
* Create this class to acess the performance data
* var performanceMonitor= new ergometer.PerformanceMonitor();
*
* after this connect to the events to get data
* performanceMonitor.rowingGeneralStatusEvent.sub(this,this.onRowingGeneralStatus);
* On some android phones you can connect to a limited number of events. Use the multiplex property to overcome
* this problem. When the multi plex mode is switched on the data send to the device can be a a bit different, see
* the documentation in the properties You must set the multi plex property before connecting
* performanceMonitor.multiplex=true;
*
* to start the connection first start scanning for a device,
* you should call when the cordova deviceready event is called (or later)
* performanceMonitor.startScan((device : ergometer.DeviceInfo) : boolean => {
* //return true when you want to connect to the device
* return device.name=='My device name';
* });
* to connect at at a later time
* performanceMonitor.connectToDevice('my device name');
* the devices which where found during the scan are collected in
* performanceMonitor.devices
* when you connect to a device the scan is stopped, when you want to stop the scan earlier you need to call
* performanceMonitor.stopScan
*
*/
export class PerformanceMonitorBase extends MonitorBase {
private _waitResonseBuffers : WaitResponseBuffer[] = [];
protected _powerCurve : number[];
protected _splitCommandsWhenToBig : boolean;
protected _receivePartialBuffers : boolean;
//events
private _powerCurveEvent: pubSub.Event<PowerCurveEvent>;
private _checksumCheckEnabled =false;
protected _commandTimeout: number;
public sortCommands : boolean = false;
private _sendBufferQueue: SendBufferQueued[]=[];
protected initialize() {
this._powerCurveEvent = new pubSub.Event<PowerCurveEvent>();
this._powerCurveEvent.registerChangedEvent(this.enableDisableNotification.bind(this));
this._splitCommandsWhenToBig=false;
this._receivePartialBuffers=false;
this._commandTimeout=1000;
}
removeResponseBuffer(buffer: WaitResponseBuffer) {
var i= this._waitResonseBuffers.indexOf(buffer);
if (i>=0) this._waitResonseBuffers.splice(i,1);
}
protected enableDisableNotification() : Promise<void> {
return Promise.resolve()
}
/**
* returns error and other log information. Some errors can only be received using the logEvent
* @returns {pubSub.Event<LogEvent>}
*/
get powerCurveEvent():pubSub.Event<ergometer.PowerCurveEvent> {
return this._powerCurveEvent;
}
get powerCurve():number[] {
return this._powerCurve;
}
protected clearAllBuffers() {
this.clearWaitResponseBuffers();
this._sendBufferQueue=[];
}
protected beforeConnected() {
this.clearAllBuffers();
}
/* ***************************************************************************************
* csafe
***************************************************************************************** */
protected clearWaitResponseBuffers() {
var list=this._waitResonseBuffers;
list.forEach(b=>b.remove());
this._waitResonseBuffers=[];
}
protected driver_write( data:ArrayBufferView) :Promise<void> {
return Promise.reject("not implemented");
}
/**
* send everyt thing which is put into the csave buffer
*
* @param success
* @param error
* @returns {Promise<void>|Promise} use promis instead of success and error function
*/
public sendCSafeBuffer(csafeBuffer : ergometer.csafe.IBuffer) : Promise<void>{
return new Promise((resolve,reject)=>{
//prepare the array to be send
var rawCommandBuffer = csafeBuffer.rawCommands;
var commandArray : number[] = [];
var prevCommand=-1;
var prevCommandIndex=-1;
if (this.sortCommands)
rawCommandBuffer.sort((first,next)=>{return first.command-next.command;});
rawCommandBuffer.forEach((command : IRawCommand)=>{
var commandMerged=false;
var commandIndex=commandArray.length;
if (command.command>= csafe.defs.CTRL_CMD_SHORT_MIN) {
commandArray.push(command.command);
//it is an short command
if (command.detailCommand|| command.data) {
throw "short commands can not contain data or a detail command"
}
}
else {
if (command.detailCommand) {
if (prevCommand===command.command) {
//add it to the last command if it is the same command
//this is more efficent
var dataLength=1;
if (command.data && command.data.length>0)
dataLength+=command.data.length;
commandArray[prevCommandIndex+1]+=dataLength;
commandMerged=true;
}
else {
commandArray.push(command.command);
var dataLength=1;
if (command.data && command.data.length>0)
dataLength+=command.data.length+1;
commandArray.push(dataLength);
}
//length for the short command
//the detail command
commandArray.push(command.detailCommand);
}
else commandArray.push(command.command);
//the data
if (command.data && command.data.length>0) {
commandArray.push(command.data.length);
commandArray=commandArray.concat(command.data);
}
}
if (!commandMerged) {
prevCommand=command.command;
prevCommandIndex=commandIndex;
}
});
this._sendBufferQueue.push({
commandArray: commandArray,
resolve: resolve,
reject: reject,
rawCommandBuffer: rawCommandBuffer
});
this.checkSendBuffer();
//send all the csafe commands in one go
})
}
protected checkSendBufferAtEnd() {
if (this._sendBufferQueue.length>0)
setTimeout(this.checkSendBuffer.bind(this),0);
}
protected checkSendBuffer() {
//make sure that only one buffer is send/received at a time
//when something to send and all received then send the next
if (this._waitResonseBuffers.length==0 && this._sendBufferQueue.length>0) {
//directly add a wait buffer so no others can send commands
//extract the send data
var sendData : SendBufferQueued=this._sendBufferQueue.shift();
this.sendBufferFromQueue(sendData);
}
}
protected sendBufferFromQueue(sendData : SendBufferQueued) {
var resolve=()=>{
if (sendData.resolve) sendData.resolve();
this.checkSendBufferAtEnd();
}
var reject=(err)=>{
if (sendData.reject) sendData.reject(err);
this.checkSendBufferAtEnd();
}
var waitBuffer=new WaitResponseBuffer(this,resolve,reject,sendData.rawCommandBuffer,this._commandTimeout);
this._waitResonseBuffers.push(waitBuffer);
//then send the data
this.sendCsafeCommands(sendData.commandArray)
.catch((e)=>{
//When it could not be send remove it
this.removeResponseBuffer(waitBuffer);
//send the error to all items
waitBuffer.removedWithError(e);
this.checkSendBufferAtEnd();
});
}
protected sendCsafeCommands(byteArray : number[]) : Promise<void> {
return new Promise<void>((resolve, reject) => {
//is there anything to send?
if (byteArray && byteArray.length>0 ) {
//calc the checksum of the data to be send
var checksum =0;
for (let i=0;i<byteArray.length;i++) checksum=checksum ^ byteArray[i];
var newArray=[];
for (let i=0;i<byteArray.length;i++) {
var value=byteArray[i];
if (value>=0xF0 && value<=0xF3) {
newArray.push(0xF3);
newArray.push(value-0xF0);
if (this.logLevel==LogLevel.trace)
this.traceInfo("stuffed to byte:"+value);
}
else newArray.push(value);
}
//prepare all the data to be send in one array
//begin with a start byte ad end with a checksum and an end byte
var bytesToSend : number[] =
([csafe.defs.FRAME_START_BYTE].concat(byteArray)).concat([checksum,csafe.defs.FRAME_END_BYTE]);
if (this._splitCommandsWhenToBig && bytesToSend.length>this.getPacketSize())
reject(`Csafe commands with length ${bytesToSend.length} does not fit into buffer with size ${this.getPacketSize()} `)
else {
var sendBytesIndex=0;
//continue while not all bytes are send
while (sendBytesIndex<bytesToSend.length) {
//prepare a buffer with the data which can be send in one packet
var bufferLength = Math.min(this.getPacketSize(),bytesToSend.length-sendBytesIndex);
var buffer = new ArrayBuffer(bufferLength); //start and end and
var dataView = new DataView(buffer);
var bufferIndex = 0;
while (bufferIndex<bufferLength) {
dataView.setUint8(bufferIndex, bytesToSend[sendBytesIndex]);
sendBytesIndex++;
bufferIndex++;
}
if (this.logLevel==LogLevel.trace)
this.traceInfo("send csafe: "+utils.typedArrayToHexString(buffer));
this.driver_write(dataView).then(
()=>{
this.traceInfo("csafe command send");
if (sendBytesIndex>=bytesToSend.length) {
//resolve when all data is send
resolve();
}
})
.catch( (e)=> {
sendBytesIndex=bytesToSend.length;//stop the loop
reject(e);
});
}
}
//send in packages of max 20 bytes (ble.PACKET_SIZE)
}
else resolve();
})
}
protected moveToNextBuffer() : WaitResponseBuffer{
var result : WaitResponseBuffer=null;
if (this.logLevel==LogLevel.trace)
this.traceInfo("next buffer: count="+this._waitResonseBuffers.length);
if (this._waitResonseBuffers.length>0) {
var waitBuffer=this._waitResonseBuffers[0];
//if the first then do not wait any more
waitBuffer.processedBuffer();
}
if (this._waitResonseBuffers.length>0) {
result=this._waitResonseBuffers[0];;
}
return result;
}
//because of the none blocking nature, the receive
//function tries to match the send command with the received command
//if they are not in the same order this routine tries to match them
public handeReceivedDriverData(dataView : DataView) {
//skipp empty 0 ble blocks
if (this._waitResonseBuffers.length>0 && (dataView.byteLength!=1 || dataView.getUint8(0)!=0) ) {
var waitBuffer=this._waitResonseBuffers[0];
if (this.logLevel==LogLevel.trace)
this.traceInfo("continious receive csafe: "+utils.typedArrayToHexString(dataView.buffer));
var i=0;
var moveToNextBuffer=false;
while (i<dataView.byteLength && !moveToNextBuffer) {
var currentByte= dataView.getUint8(i);
if (waitBuffer.stuffByteActive && currentByte<=3) {
currentByte=0xF0+currentByte;//unstuff
if (this.logLevel==LogLevel.trace)
this.traceInfo("unstuffed to byte:"+currentByte);
waitBuffer.stuffByteActive=false;
}
else {
waitBuffer.stuffByteActive= (currentByte==0xF3);
if (waitBuffer.stuffByteActive && this.logLevel==LogLevel.trace)
this.traceInfo("start stuff byte");
}
//when stuffbyte is active then move to the next
if (!waitBuffer.stuffByteActive) {
if (waitBuffer.frameState!=FrameState.initial) {
waitBuffer.calcCheck=waitBuffer.calcCheck ^ currentByte; //xor for a simple crc check
}
if (this.logLevel==LogLevel.trace)
this.traceInfo(`parse: ${i}: ${utils.toHexString(currentByte,1)} state: ${waitBuffer.frameState} checksum:${utils.toHexString(waitBuffer.calcCheck,1)} `);
switch(waitBuffer.frameState) {
case FrameState.initial : {
//expect a start frame
if (currentByte!=csafe.defs.FRAME_START_BYTE) {
moveToNextBuffer=true ;
if (this.logLevel==LogLevel.trace)
this.traceInfo("stop byte "+utils.toHexString(currentByte,1))
}
else waitBuffer.frameState=FrameState.statusByte;
waitBuffer.calcCheck=0;
break;
}
case FrameState.statusByte :
{
waitBuffer.frameState= FrameState.parseCommand;
waitBuffer.statusByte=currentByte
waitBuffer.monitorStatus=currentByte & csafe.defs.SLAVESTATE_MSK;
waitBuffer.prevFrameState= ((currentByte & csafe.defs.PREVFRAMESTATUS_MSK) >>4);
if (this.logLevel==LogLevel.trace)
this.traceInfo(`monitor status: ${waitBuffer.monitorStatus},prev frame state: ${waitBuffer.prevFrameState}`);
waitBuffer._responseState=currentByte;
break;
}
case FrameState.parseCommand : {
waitBuffer.command=currentByte;
waitBuffer.frameState= FrameState.parseCommandLength;
//the real command follows so skip this
break;
}
case FrameState.parseCommandLength : {
//first work arround strange results where the status byte is the same
//as the the command and the frame directly ends, What is the meaning of
//this? some kind of status??
if (waitBuffer.statusByte==waitBuffer.command && currentByte==csafe.defs.FRAME_END_BYTE) {
waitBuffer.command=0; //do not check checksum
moveToNextBuffer=true;
}
else if (i==dataView.byteLength-1 && currentByte==csafe.defs.FRAME_END_BYTE ) {
var checksum=waitBuffer.command;
//remove the last 2 bytes from the checksum which was added too much
waitBuffer.calcCheck=waitBuffer.calcCheck ^ currentByte;
waitBuffer.calcCheck=waitBuffer.calcCheck ^ waitBuffer.command;
//check the calculated with the message checksum
if (this._checksumCheckEnabled && checksum!=waitBuffer.calcCheck)
this.handleError(`Wrong checksum ${utils.toHexString(checksum,1)} expected ${utils.toHexString(waitBuffer.calcCheck,1) } `);
waitBuffer.command=0; //do not check checksum
moveToNextBuffer=true;
}
else if (i<dataView.byteLength) {
waitBuffer.endCommand=i+currentByte;
waitBuffer.nextDataLength= currentByte;
if (waitBuffer.command>= csafe.defs.CTRL_CMD_SHORT_MIN) {
waitBuffer.frameState= FrameState.parseCommandData;
}
else waitBuffer.frameState= FrameState.parseDetailCommand;
}
break;
}
case FrameState.parseDetailCommand : {
waitBuffer.detailCommand= currentByte;
waitBuffer.frameState= FrameState.parseDetailCommandLength;
break;
}
case FrameState.parseDetailCommandLength : {
waitBuffer.nextDataLength=currentByte;
waitBuffer.frameState= FrameState.parseCommandData;
break;
}
case FrameState.parseCommandData : {
if (!waitBuffer.commandData) {
waitBuffer.commandDataIndex=0;
waitBuffer.commandData = new Uint8Array(waitBuffer.nextDataLength);
}
waitBuffer.commandData[waitBuffer.commandDataIndex]=currentByte;
waitBuffer.nextDataLength--;
waitBuffer.commandDataIndex++;
if (waitBuffer.nextDataLength==0) {
if (waitBuffer.command< csafe.defs.CTRL_CMD_SHORT_MIN
&& i<waitBuffer.endCommand)
waitBuffer.frameState= FrameState.parseDetailCommand;
else waitBuffer.frameState= FrameState.parseCommand;
try {
waitBuffer.receivedCSaveCommand({
command:waitBuffer.command,
detailCommand:waitBuffer.detailCommand,
data:waitBuffer.commandData});
}
catch (e) {
this.handleError(e); //never let the receive crash the main loop
}
waitBuffer.commandData=null;
waitBuffer.detailCommand=0;
}
break;
}
}
}
i++;
}
if (this._receivePartialBuffers ) {
//when something went wrong, the bluetooth block is endend but the frame not
//this is for blue tooth
if (moveToNextBuffer)
waitBuffer=this.moveToNextBuffer();
else if ( dataView.byteLength!=this.getPacketSize() && waitBuffer && waitBuffer.frameState!=FrameState.initial) {
waitBuffer=this.moveToNextBuffer();
this.handleError("wrong csafe frame ending.");
}
}
else {
//for usb all should be processd,
//so allways move to the next buffer at the end of parsing
waitBuffer=this.moveToNextBuffer();
}
}
}
protected getPacketSize() : number {
throw "getPacketSize not implemented"
}
public newCsafeBuffer() : ergometer.csafe.IBuffer {
//init the buffer when needed
var csafeBuffer = <any> {
rawCommands: []
}
csafeBuffer.send= (sucess? : ()=>void,error? : ErrorHandler) => {
return this.sendCSafeBuffer(csafeBuffer)
.then(sucess)
.catch(e=>{
this.handleError(e);
if (error) error(e);
return Promise.reject(e);
});
}
csafeBuffer.addRawCommand=(info:csafe.IRawCommand):csafe.IBuffer=> {
csafeBuffer.rawCommands.push(info);
return csafeBuffer;
}
csafe.commandManager.apply(csafeBuffer, this);
return csafeBuffer;
}
}
} | the_stack |
import {ChromeEvent} from '/tools/typescript/definitions/chrome_event.js';
import {assert} from 'chrome://resources/js/assert.m.js';
import {ActivityLogDelegate} from './activity_log/activity_log_history.js';
import {ActivityLogEventDelegate} from './activity_log/activity_log_stream.js';
import {ErrorPageDelegate} from './error_page.js';
import {ItemDelegate} from './item.js';
import {KeyboardShortcutDelegate} from './keyboard_shortcut_delegate.js';
import {LoadErrorDelegate} from './load_error.js';
import {Dialog, navigation, Page} from './navigation_helper.js';
import {PackDialogDelegate} from './pack_dialog.js';
import {ToolbarDelegate} from './toolbar.js';
export class Service implements ActivityLogDelegate, ActivityLogEventDelegate,
ErrorPageDelegate, ItemDelegate,
KeyboardShortcutDelegate, LoadErrorDelegate,
PackDialogDelegate, ToolbarDelegate {
private isDeleting_: boolean = false;
private eventsToIgnoreOnce_: Set<string> = new Set();
getProfileConfiguration(): Promise<chrome.developerPrivate.ProfileInfo> {
return new Promise(function(resolve) {
chrome.developerPrivate.getProfileConfiguration(resolve);
});
}
getItemStateChangedTarget() {
return chrome.developerPrivate.onItemStateChanged;
}
shouldIgnoreUpdate(
extensionId: string,
eventType: chrome.developerPrivate.EventType): boolean {
return this.eventsToIgnoreOnce_.delete(`${extensionId}_${eventType}`);
}
ignoreNextEvent(
extensionId: string, eventType: chrome.developerPrivate.EventType): void {
this.eventsToIgnoreOnce_.add(`${extensionId}_${eventType}`);
}
getProfileStateChangedTarget() {
return chrome.developerPrivate.onProfileStateChanged;
}
getExtensionsInfo(): Promise<Array<chrome.developerPrivate.ExtensionInfo>> {
return new Promise(function(resolve) {
chrome.developerPrivate.getExtensionsInfo(
{includeDisabled: true, includeTerminated: true}, resolve);
});
}
getExtensionSize(id: string): Promise<string> {
return new Promise(function(resolve) {
chrome.developerPrivate.getExtensionSize(id, resolve);
});
}
addRuntimeHostPermission(id: string, host: string): Promise<void> {
return new Promise((resolve, reject) => {
chrome.developerPrivate.addHostPermission(id, host, () => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError.message);
return;
}
resolve();
});
});
}
removeRuntimeHostPermission(id: string, host: string): Promise<void> {
return new Promise((resolve, reject) => {
chrome.developerPrivate.removeHostPermission(id, host, () => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError.message);
return;
}
resolve();
});
});
}
recordUserAction(metricName: string): void {
chrome.metricsPrivate.recordUserAction(metricName);
}
/**
* Opens a file browser dialog for the user to select a file (or directory).
* @return The promise to be resolved with the selected path.
*/
chooseFilePath_(
selectType: chrome.developerPrivate.SelectType,
fileType: chrome.developerPrivate.FileType): Promise<string> {
return new Promise(function(resolve, reject) {
chrome.developerPrivate.choosePath(selectType, fileType, function(path) {
if (chrome.runtime.lastError &&
chrome.runtime.lastError.message !==
'File selection was canceled.') {
reject(chrome.runtime.lastError);
} else {
resolve(path || '');
}
});
});
}
updateExtensionCommandKeybinding(
extensionId: string, commandName: string, keybinding: string) {
chrome.developerPrivate.updateExtensionCommand({
extensionId: extensionId,
commandName: commandName,
keybinding: keybinding,
});
}
updateExtensionCommandScope(
extensionId: string, commandName: string,
scope: chrome.developerPrivate.CommandScope): void {
// The COMMAND_REMOVED event needs to be ignored since it is sent before
// the command is added back with the updated scope but can be handled
// after the COMMAND_ADDED event.
this.ignoreNextEvent(
extensionId, chrome.developerPrivate.EventType.COMMAND_REMOVED);
chrome.developerPrivate.updateExtensionCommand({
extensionId: extensionId,
commandName: commandName,
scope: scope,
});
}
setShortcutHandlingSuspended(isCapturing: boolean) {
chrome.developerPrivate.setShortcutHandlingSuspended(isCapturing);
}
/**
* @return A signal that loading finished, rejected if any error occurred.
*/
private loadUnpackedHelper_(opt_options?:
chrome.developerPrivate.LoadUnpackedOptions):
Promise<boolean> {
return new Promise(function(resolve, reject) {
const options = Object.assign(
{
failQuietly: true,
populateError: true,
},
opt_options);
chrome.developerPrivate.loadUnpacked(options, (loadError) => {
if (chrome.runtime.lastError &&
chrome.runtime.lastError.message !==
'File selection was canceled.') {
throw new Error(chrome.runtime.lastError.message);
}
if (loadError) {
return reject(loadError);
}
// The load was successful if there's no lastError indicated (and
// no loadError, which is checked above).
const loadSuccessful = typeof chrome.runtime.lastError === 'undefined';
resolve(loadSuccessful);
});
});
}
deleteItem(id: string) {
if (this.isDeleting_) {
return;
}
chrome.metricsPrivate.recordUserAction('Extensions.RemoveExtensionClick');
this.isDeleting_ = true;
chrome.management.uninstall(id, {showConfirmDialog: true}, () => {
// The "last error" was almost certainly the user canceling the dialog.
// Do nothing. We only check it so we don't get noisy logs.
/** @suppress {suspiciousCode} */
chrome.runtime.lastError;
this.isDeleting_ = false;
});
}
setItemEnabled(id: string, isEnabled: boolean) {
chrome.metricsPrivate.recordUserAction(
isEnabled ? 'Extensions.ExtensionEnabled' :
'Extensions.ExtensionDisabled');
chrome.management.setEnabled(id, isEnabled);
}
setItemAllowedIncognito(id: string, isAllowedIncognito: boolean) {
chrome.developerPrivate.updateExtensionConfiguration({
extensionId: id,
incognitoAccess: isAllowedIncognito,
});
}
setItemAllowedOnFileUrls(id: string, isAllowedOnFileUrls: boolean) {
chrome.developerPrivate.updateExtensionConfiguration({
extensionId: id,
fileAccess: isAllowedOnFileUrls,
});
}
setItemHostAccess(id: string, hostAccess: chrome.developerPrivate.HostAccess):
void {
chrome.developerPrivate.updateExtensionConfiguration({
extensionId: id,
hostAccess: hostAccess,
});
}
setItemCollectsErrors(id: string, collectsErrors: boolean): void {
chrome.developerPrivate.updateExtensionConfiguration({
extensionId: id,
errorCollection: collectsErrors,
});
}
inspectItemView(id: string, view: chrome.developerPrivate.ExtensionView):
void {
chrome.developerPrivate.openDevTools({
extensionId: id,
renderProcessId: view.renderProcessId,
renderViewId: view.renderViewId,
incognito: view.incognito,
isServiceWorker: view.type === 'EXTENSION_SERVICE_WORKER_BACKGROUND',
});
}
openUrl(url: string): void {
window.open(url);
}
reloadItem(id: string): Promise<void> {
return new Promise(function(resolve, reject) {
chrome.developerPrivate.reload(
id, {failQuietly: true, populateErrorForUnpacked: true},
(loadError) => {
if (loadError) {
reject(loadError);
return;
}
resolve();
});
});
}
repairItem(id: string): void {
chrome.developerPrivate.repairExtension(id);
}
showItemOptionsPage(extension: chrome.developerPrivate.ExtensionInfo): void {
assert(extension && extension.optionsPage);
if (extension.optionsPage!.openInTab) {
chrome.developerPrivate.showOptions(extension.id);
} else {
navigation.navigateTo({
page: Page.DETAILS,
subpage: Dialog.OPTIONS,
extensionId: extension.id,
});
}
}
setProfileInDevMode(inDevMode: boolean) {
chrome.developerPrivate.updateProfileConfiguration(
{inDeveloperMode: inDevMode});
}
loadUnpacked(): Promise<boolean> {
return this.loadUnpackedHelper_();
}
retryLoadUnpacked(retryGuid: string): Promise<boolean> {
// Attempt to load an unpacked extension, optionally as another attempt at
// a previously-specified load.
return this.loadUnpackedHelper_({retryGuid: retryGuid});
}
choosePackRootDirectory(): Promise<string> {
return this.chooseFilePath_(
chrome.developerPrivate.SelectType.FOLDER,
chrome.developerPrivate.FileType.LOAD);
}
choosePrivateKeyPath(): Promise<string> {
return this.chooseFilePath_(
chrome.developerPrivate.SelectType.FILE,
chrome.developerPrivate.FileType.PEM);
}
packExtension(
rootPath: string, keyPath: string, flag?: number,
callback?:
(response: chrome.developerPrivate.PackDirectoryResponse) => void):
void {
chrome.developerPrivate.packDirectory(rootPath, keyPath, flag, callback);
}
updateAllExtensions(extensions: chrome.developerPrivate.ExtensionInfo[]):
Promise<string> {
/**
* Attempt to reload local extensions. If an extension fails to load, the
* user is prompted to try updating the broken extension using loadUnpacked
* and we skip reloading the remaining local extensions.
*/
return new Promise<void>((resolve) => {
chrome.developerPrivate.autoUpdate(() => resolve());
chrome.metricsPrivate.recordUserAction('Options_UpdateExtensions');
})
.then(() => {
return new Promise((resolve, reject) => {
const loadLocalExtensions = async () => {
for (const extension of extensions) {
if (extension.location === 'UNPACKED') {
try {
await this.reloadItem(extension.id);
} catch (loadError) {
reject(loadError);
break;
}
}
}
resolve('Loaded local extensions.');
};
loadLocalExtensions();
});
});
}
deleteErrors(
extensionId: string, errorIds?: number[],
type?: chrome.developerPrivate.ErrorType) {
chrome.developerPrivate.deleteExtensionErrors({
extensionId: extensionId,
errorIds: errorIds,
type: type,
});
}
requestFileSource(args: chrome.developerPrivate.RequestFileSourceProperties):
Promise<chrome.developerPrivate.RequestFileSourceResponse> {
return new Promise(function(resolve) {
chrome.developerPrivate.requestFileSource(args, resolve);
});
}
showInFolder(id: string) {
chrome.developerPrivate.showPath(id);
}
getExtensionActivityLog(extensionId: string):
Promise<chrome.activityLogPrivate.ActivityResultSet> {
return new Promise(function(resolve) {
chrome.activityLogPrivate.getExtensionActivities(
{
activityType: chrome.activityLogPrivate.ExtensionActivityFilter.ANY,
extensionId: extensionId
},
resolve);
});
}
getFilteredExtensionActivityLog(extensionId: string, searchTerm: string) {
const anyType = chrome.activityLogPrivate.ExtensionActivityFilter.ANY;
// Construct one filter for each API call we will make: one for substring
// search by api call, one for substring search by page URL, and one for
// substring search by argument URL. % acts as a wildcard.
const activityLogFilters = [
{
activityType: anyType,
extensionId: extensionId,
apiCall: `%${searchTerm}%`,
},
{
activityType: anyType,
extensionId: extensionId,
pageUrl: `%${searchTerm}%`,
},
{
activityType: anyType,
extensionId: extensionId,
argUrl: `%${searchTerm}%`
}
];
const promises:
Array<Promise<chrome.activityLogPrivate.ActivityResultSet>> =
activityLogFilters.map(
filter => new Promise(function(resolve) {
chrome.activityLogPrivate.getExtensionActivities(
filter, resolve);
}));
return Promise.all(promises).then(results => {
// We may have results that are present in one or more searches, so
// we merge them here. We also assume that every distinct activity
// id corresponds to exactly one activity.
const activitiesById = new Map();
for (const result of results) {
for (const activity of result.activities) {
activitiesById.set(activity.activityId, activity);
}
}
return {activities: Array.from(activitiesById.values())};
});
}
deleteActivitiesById(activityIds: string[]): Promise<void> {
return new Promise(function(resolve) {
chrome.activityLogPrivate.deleteActivities(activityIds, resolve);
});
}
deleteActivitiesFromExtension(extensionId: string): Promise<void> {
return new Promise(function(resolve) {
chrome.activityLogPrivate.deleteActivitiesByExtension(
extensionId, resolve);
});
}
getOnExtensionActivity(): ChromeEvent<
(activity: chrome.activityLogPrivate.ExtensionActivity) => void> {
return chrome.activityLogPrivate.onExtensionActivity;
}
downloadActivities(rawActivityData: string, fileName: string) {
const blob = new Blob([rawActivityData], {type: 'application/json'});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = fileName;
a.click();
}
/**
* Attempts to load an unpacked extension via a drag-n-drop gesture.
* @return {!Promise}
*/
loadUnpackedFromDrag() {
return this.loadUnpackedHelper_({useDraggedPath: true});
}
installDroppedFile() {
chrome.developerPrivate.installDroppedFile();
}
notifyDragInstallInProgress() {
chrome.developerPrivate.notifyDragInstallInProgress();
}
static getInstance(): Service {
return instance || (instance = new Service());
}
static setInstance(obj: Service) {
instance = obj;
}
}
let instance: Service|null = null; | the_stack |
import {Profile, FrameInfo, CallTreeProfileBuilder, ProfileGroup} from '../lib/profile'
import {getOrInsert, lastOf, sortBy, itForEach} from '../lib/utils'
import {TimeFormatter} from '../lib/value-formatters'
import {chromeTreeToNodes, OldCPUProfile} from './v8cpuFormatter'
// See: https://github.com/v8/v8/blob/master/src/inspector/js_protocol.json
interface TimelineEvent {
pid: number
tid: number
ts: number
ph: string
cat: string
name: string
dur: number
tdur: number
tts: number
args: {[key: string]: any}
id?: string
}
interface PositionTickInfo {
line: number
ticks: number
}
interface CPUProfileCallFrame {
columnNumber: number
functionName: string
lineNumber: number
scriptId: string
url: string
}
export interface CPUProfileNode {
callFrame: CPUProfileCallFrame
hitCount: number
id: number
children?: number[]
positionTicks?: PositionTickInfo[]
parent?: CPUProfileNode
}
export interface CPUProfile {
startTime: number
endTime: number
nodes: CPUProfileNode[]
samples: number[]
timeDeltas: number[]
}
export function isChromeTimeline(rawProfile: any): boolean {
if (!Array.isArray(rawProfile)) return false
if (rawProfile.length < 1) return false
const first = rawProfile[0]
if (!('pid' in first && 'tid' in first && 'ph' in first && 'cat' in first)) return false
if (
!rawProfile.find(
e => e.name === 'CpuProfile' || e.name === 'Profile' || e.name === 'ProfileChunk',
)
)
return false
return true
}
export function importFromChromeTimeline(events: TimelineEvent[], fileName: string): ProfileGroup {
// It seems like sometimes Chrome timeline files contain multiple CpuProfiles?
// For now, choose the first one in the list.
const cpuProfileByID = new Map<string, CPUProfile>()
// Maps profile IDs (like "0x3") to pid/tid pairs formatted as `${pid}:${tid}`
const pidTidById = new Map<string, string>()
// Maps pid/tid pairs to thread names
const threadNameByPidTid = new Map<string, string>()
// The events aren't necessarily recorded in chronological order. Sort them so
// that they are.
sortBy(events, e => e.ts)
for (let event of events) {
if (event.name === 'CpuProfile') {
const pidTid = `${event.pid}:${event.tid}`
const id = event.id || pidTid
cpuProfileByID.set(id, event.args.data.cpuProfile as CPUProfile)
pidTidById.set(id, pidTid)
}
if (event.name === 'Profile') {
const pidTid = `${event.pid}:${event.tid}`
cpuProfileByID.set(event.id || pidTid, {
startTime: 0,
endTime: 0,
nodes: [],
samples: [],
timeDeltas: [],
...event.args.data,
})
if (event.id) {
pidTidById.set(event.id, `${event.pid}:${event.tid}`)
}
}
if (event.name === 'thread_name') {
threadNameByPidTid.set(`${event.pid}:${event.tid}`, event.args.name)
}
if (event.name === 'ProfileChunk') {
const pidTid = `${event.pid}:${event.tid}`
const cpuProfile = cpuProfileByID.get(event.id || pidTid)
if (cpuProfile) {
const chunk = event.args.data
if (chunk.cpuProfile) {
if (chunk.cpuProfile.nodes) {
cpuProfile.nodes = cpuProfile.nodes.concat(chunk.cpuProfile.nodes)
}
if (chunk.cpuProfile.samples) {
cpuProfile.samples = cpuProfile.samples.concat(chunk.cpuProfile.samples)
}
}
if (chunk.timeDeltas) {
cpuProfile.timeDeltas = cpuProfile.timeDeltas.concat(chunk.timeDeltas)
}
if (chunk.startTime != null) {
cpuProfile.startTime = chunk.startTime
}
if (chunk.endTime != null) {
cpuProfile.endTime = chunk.endTime
}
} else {
console.warn(`Ignoring ProfileChunk for undeclared Profile with id ${event.id || pidTid}`)
}
}
}
if (cpuProfileByID.size > 0) {
const profiles: Profile[] = []
let indexToView = 0
itForEach(cpuProfileByID.keys(), profileId => {
let threadName: string | null = null
let pidTid = pidTidById.get(profileId)
if (pidTid) {
threadName = threadNameByPidTid.get(pidTid) || null
if (threadName) {
}
}
const profile = importFromChromeCPUProfile(cpuProfileByID.get(profileId)!)
if (threadName && cpuProfileByID.size > 1) {
profile.setName(`${fileName} - ${threadName}`)
if (threadName === 'CrRendererMain') {
indexToView = profiles.length
}
} else {
profile.setName(`${fileName}`)
}
profiles.push(profile)
})
return {name: fileName, indexToView, profiles}
} else {
throw new Error('Could not find CPU profile in Timeline')
}
}
const callFrameToFrameInfo = new Map<CPUProfileCallFrame, FrameInfo>()
function frameInfoForCallFrame(callFrame: CPUProfileCallFrame) {
return getOrInsert(callFrameToFrameInfo, callFrame, callFrame => {
const name = callFrame.functionName || '(anonymous)'
const file = callFrame.url
// In Chrome profiles, line numbers & column numbers are both 0-indexed.
//
// We're going to normalize these to be 1-based to avoid needing to normalize
// these at the presentation layer.
let line = callFrame.lineNumber
if (line != null) line++
let col = callFrame.columnNumber
if (col != null) col++
return {
key: `${name}:${file}:${line}:${col}`,
name,
file,
line,
col,
}
})
}
function shouldIgnoreFunction(callFrame: CPUProfileCallFrame) {
const {functionName, url} = callFrame
if (url === 'native dummy.js') {
// I'm not really sure what this is about, but this seems to be used
// as a way of avoiding edge cases in V8's implementation.
// See: https://github.com/v8/v8/blob/b8626ca4/tools/js2c.py#L419-L424
return true
}
return functionName === '(root)' || functionName === '(idle)'
}
function shouldPlaceOnTopOfPreviousStack(functionName: string) {
return functionName === '(garbage collector)' || functionName === '(program)'
}
export function importFromChromeCPUProfile(chromeProfile: CPUProfile): Profile {
const profile = new CallTreeProfileBuilder(chromeProfile.endTime - chromeProfile.startTime)
const nodeById = new Map<number, CPUProfileNode>()
for (let node of chromeProfile.nodes) {
nodeById.set(node.id, node)
}
for (let node of chromeProfile.nodes) {
if (typeof node.parent === 'number') {
node.parent = nodeById.get(node.parent)
}
if (!node.children) continue
for (let childId of node.children) {
const child = nodeById.get(childId)
if (!child) continue
child.parent = node
}
}
const samples: number[] = []
const sampleTimes: number[] = []
// The first delta is relative to the profile startTime.
// Ref: https://github.com/v8/v8/blob/44bd8fd7/src/inspector/js_protocol.json#L1485
let elapsed = chromeProfile.timeDeltas[0]
// Prevents negative time deltas from causing bad data. See
// https://github.com/jlfwong/speedscope/pull/305 for details.
let lastValidElapsed = elapsed
let lastNodeId = NaN
// The chrome CPU profile format doesn't collapse identical samples. We'll do that
// here to save a ton of work later doing mergers.
for (let i = 0; i < chromeProfile.samples.length; i++) {
const nodeId = chromeProfile.samples[i]
if (nodeId != lastNodeId) {
samples.push(nodeId)
if (elapsed < lastValidElapsed) {
sampleTimes.push(lastValidElapsed)
} else {
sampleTimes.push(elapsed)
lastValidElapsed = elapsed
}
}
if (i === chromeProfile.samples.length - 1) {
if (!isNaN(lastNodeId)) {
samples.push(lastNodeId)
if (elapsed < lastValidElapsed) {
sampleTimes.push(lastValidElapsed)
} else {
sampleTimes.push(elapsed)
lastValidElapsed = elapsed
}
}
} else {
const timeDelta = chromeProfile.timeDeltas[i + 1]
elapsed += timeDelta
lastNodeId = nodeId
}
}
let prevStack: CPUProfileNode[] = []
for (let i = 0; i < samples.length; i++) {
const value = sampleTimes[i]
const nodeId = samples[i]
let stackTop = nodeById.get(nodeId)
if (!stackTop) continue
// Find lowest common ancestor of the current stack and the previous one
let lca: CPUProfileNode | null = null
// This is O(n^2), but n should be relatively small here (stack height),
// so hopefully this isn't much of a problem
for (
lca = stackTop;
lca && prevStack.indexOf(lca) === -1;
lca = shouldPlaceOnTopOfPreviousStack(lca.callFrame.functionName)
? lastOf(prevStack)
: lca.parent || null
) {}
// Close frames that are no longer open
while (prevStack.length > 0 && lastOf(prevStack) != lca) {
const closingNode = prevStack.pop()!
const frame = frameInfoForCallFrame(closingNode.callFrame)
profile.leaveFrame(frame, value)
}
// Open frames that are now becoming open
const toOpen: CPUProfileNode[] = []
for (
let node: CPUProfileNode | null = stackTop;
node && node != lca && !shouldIgnoreFunction(node.callFrame);
// Place Chrome internal functions on top of the previous call stack
node = shouldPlaceOnTopOfPreviousStack(node.callFrame.functionName)
? lastOf(prevStack)
: node.parent || null
) {
toOpen.push(node)
}
toOpen.reverse()
for (let node of toOpen) {
profile.enterFrame(frameInfoForCallFrame(node.callFrame), value)
}
prevStack = prevStack.concat(toOpen)
}
// Close frames that are open at the end of the trace
for (let i = prevStack.length - 1; i >= 0; i--) {
profile.leaveFrame(frameInfoForCallFrame(prevStack[i].callFrame), lastOf(sampleTimes)!)
}
profile.setValueFormatter(new TimeFormatter('microseconds'))
return profile.build()
}
export function importFromOldV8CPUProfile(content: OldCPUProfile): Profile {
return importFromChromeCPUProfile(chromeTreeToNodes(content))
} | the_stack |
export interface SegmentPortraitPicResponse {
/**
* 处理后的图片 base64 数据,透明背景图
*/
ResultImage?: string;
/**
* 一个通过 Base64 编码的文件,解码后文件由 Float 型浮点数组成。这些浮点数代表原图从左上角开始的每一行的每一个像素点,每一个浮点数的值是原图相应像素点位于人体轮廓内的置信度(0-1)转化的灰度值(0-255)
*/
ResultMask?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DetectBodyJoints返回参数结构体
*/
export interface DetectBodyJointsResponse {
/**
* 图中检测出的人体框和人体关键点, 包含14个人体关键点的坐标,建议根据人体框置信度筛选出合格的人体;
*/
BodyJointsResults: Array<BodyJointsResult>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 识别出的最相似候选人。
*/
export interface Candidate {
/**
* 人员ID。
*/
PersonId: string;
/**
* 人体轨迹ID。
*/
TraceId: string;
/**
* 候选者的匹配得分。
十万人体库下,误识率百分之五对应的分数为70分;误识率百分之二对应的分数为80分;误识率百分之一对应的分数为90分。
二十万人体库下,误识率百分之五对应的分数为80分;误识率百分之二对应的分数为90分;误识率百分之一对应的分数为95分。
通常情况建议使用分数80分(保召回)。若希望获得较高精度,建议使用分数90分(保准确)。
*/
Score: number;
}
/**
* 视频基础信息
*/
export interface VideoBasicInformation {
/**
* 视频宽度
*/
FrameWidth: number;
/**
* 视频高度
*/
FrameHeight: number;
/**
* 视频帧速率(FPS)
*/
FramesPerSecond: number;
/**
* 视频时长
*/
Duration: number;
/**
* 视频帧数
*/
TotalFrames: number;
}
/**
* DeletePerson请求参数结构体
*/
export interface DeletePersonRequest {
/**
* 人员ID。
*/
PersonId: string;
}
/**
* ModifyGroup返回参数结构体
*/
export interface ModifyGroupResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* TerminateSegmentationTask返回参数结构体
*/
export interface TerminateSegmentationTaskResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 图中检测出的人体属性信息。
*/
export interface BodyAttributeInfo {
/**
* 人体年龄信息。
AttributesType 不含 Age 或检测超过 5 个人体时,此参数仍返回,但不具备参考意义。
注意:此字段可能返回 null,表示取不到有效值。
*/
Age: Age;
/**
* 人体是否挎包。
AttributesType 不含 Bag 或检测超过 5 个人体时,此参数仍返回,但不具备参考意义。
注意:此字段可能返回 null,表示取不到有效值。
*/
Bag: Bag;
/**
* 人体性别信息。
AttributesType 不含 Gender 或检测超过 5 个人体时,此参数仍返回,但不具备参考意义。
注意:此字段可能返回 null,表示取不到有效值。
*/
Gender: Gender;
/**
* 人体朝向信息。
AttributesType 不含 UpperBodyCloth 或检测超过 5 个人体时,此参数仍返回,但不具备参考意义。
注意:此字段可能返回 null,表示取不到有效值。
*/
Orientation: Orientation;
/**
* 人体上衣属性信息。
AttributesType 不含 Orientation 或检测超过 5 个人体时,此参数仍返回,但不具备参考意义。
注意:此字段可能返回 null,表示取不到有效值。
*/
UpperBodyCloth: UpperBodyCloth;
/**
* 人体下衣属性信息。
AttributesType 不含 LowerBodyCloth 或检测超过 5 个人体时,此参数仍返回,但不具备参考意义。
注意:此字段可能返回 null,表示取不到有效值。
*/
LowerBodyCloth: LowerBodyCloth;
}
/**
* GetSummaryInfo请求参数结构体
*/
export declare type GetSummaryInfoRequest = null;
/**
* GetGroupList返回参数结构体
*/
export interface GetGroupListResponse {
/**
* 返回的人体库信息。
*/
GroupInfos: Array<GroupInfo>;
/**
* 人体库总数量。
*/
GroupNum: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 返回的人员库信息。
*/
export interface GroupInfo {
/**
* 人体库名称。
*/
GroupName: string;
/**
* 人体库ID。
*/
GroupId: string;
/**
* 人体库信息备注。
*/
Tag: string;
/**
* 人体识别所用的算法模型版本。
*/
BodyModelVersion: string;
/**
* Group的创建时间和日期 CreationTimestamp。CreationTimestamp 的值是自 Unix 纪元时间到Group创建时间的毫秒数。
Unix 纪元时间是 1970 年 1 月 1 日星期四,协调世界时 (UTC) 。
*/
CreationTimestamp: number;
}
/**
* DescribeSegmentationTask请求参数结构体
*/
export interface DescribeSegmentationTaskRequest {
/**
* 在提交分割任务成功时返回的任务标识ID。
*/
TaskID: string;
}
/**
* 此参数为分割选项,请根据需要选择自己所想从图片中分割的部分。注意所有选项均为非必选,如未选择则值默认为false, 但是必须要保证多于一个选项的描述为true。
*/
export interface SegmentationOptions {
/**
* 分割选项-背景
*/
Background?: boolean;
/**
* 分割选项-头发
*/
Hair?: boolean;
/**
* 分割选项-左眉
*/
LeftEyebrow?: boolean;
/**
* 分割选项-右眉
*/
RightEyebrow?: boolean;
/**
* 分割选项-左眼
*/
LeftEye?: boolean;
/**
* 分割选项-右眼
*/
RightEye?: boolean;
/**
* 分割选项-鼻子
*/
Nose?: boolean;
/**
* 分割选项-上唇
*/
UpperLip?: boolean;
/**
* 分割选项-下唇
*/
LowerLip?: boolean;
/**
* 分割选项-牙齿
*/
Tooth?: boolean;
/**
* 分割选项-口腔(不包含牙齿)
*/
Mouth?: boolean;
/**
* 分割选项-左耳
*/
LeftEar?: boolean;
/**
* 分割选项-右耳
*/
RightEar?: boolean;
/**
* 分割选项-面部(不包含眼、耳、口、鼻等五官及头发。)
*/
Face?: boolean;
/**
* 复合分割选项-头部(包含所有的头部元素,相关装饰除外)
*/
Head?: boolean;
/**
* 分割选项-身体(包含脖子)
*/
Body?: boolean;
/**
* 分割选项-帽子
*/
Hat?: boolean;
/**
* 分割选项-头饰
*/
Headdress?: boolean;
/**
* 分割选项-耳环
*/
Earrings?: boolean;
/**
* 分割选项-项链
*/
Necklace?: boolean;
/**
* 分割选项-随身物品( 例如伞、包、手机等。 )
*/
Belongings?: boolean;
}
/**
* 上衣纹理信息。
*/
export interface UpperBodyClothTexture {
/**
* 上衣纹理信息,返回值为以下集合中的一个, {纯色, 格子, 大色块}。
*/
Type: string;
/**
* Type识别概率值,[0.0,1.0], 代表判断正确的概率。如0.8则代表有Type值有80%概率正确。
*/
Probability: number;
}
/**
* TerminateSegmentationTask请求参数结构体
*/
export interface TerminateSegmentationTaskRequest {
/**
* 在提交分割任务成功时返回的任务标识ID。
*/
TaskID: string;
}
/**
* ModifyGroup请求参数结构体
*/
export interface ModifyGroupRequest {
/**
* 人体库ID。
*/
GroupId: string;
/**
* 人体库名称。
*/
GroupName?: string;
/**
* 人体库信息备注。
*/
Tag?: string;
}
/**
* CreatePerson请求参数结构体
*/
export interface CreatePersonRequest {
/**
* 待加入的人员库ID。
*/
GroupId: string;
/**
* 人员名称。[1,60]个字符,可修改,可重复。
*/
PersonName: string;
/**
* 人员ID,单个腾讯云账号下不可修改,不可重复。
支持英文、数字、-%@#&_,,长度限制64B。
*/
PersonId: string;
/**
* 人体轨迹信息。
*/
Trace: Trace;
}
/**
* ModifyPersonInfo返回参数结构体
*/
export interface ModifyPersonInfoResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateSegmentationTask返回参数结构体
*/
export interface CreateSegmentationTaskResponse {
/**
* 任务标识ID,可以用与追溯任务状态,查看任务结果
*/
TaskID: string;
/**
* 预估处理时间,单位为秒
*/
EstimatedProcessingTime: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DeleteGroup请求参数结构体
*/
export interface DeleteGroupRequest {
/**
* 人体库ID。
*/
GroupId: string;
}
/**
* GetSummaryInfo返回参数结构体
*/
export interface GetSummaryInfoResponse {
/**
* 人体库总数量。
*/
GroupCount: number;
/**
* 人员总数量
*/
PersonCount: number;
/**
* 人员轨迹总数量
*/
TraceCount: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyPersonInfo请求参数结构体
*/
export interface ModifyPersonInfoRequest {
/**
* 人员ID。
*/
PersonId: string;
/**
* 人员名称。
*/
PersonName?: string;
}
/**
* 人体性别信息。
AttributesType 不含 Gender 或检测超过 5 个人体时,此参数仍返回,但不具备参考意义。
*/
export interface Gender {
/**
* 性别信息,返回值为以下集合中的一个 {男性, 女性}
*/
Type: string;
/**
* Type识别概率值,[0.0,1.0],代表判断正确的概率。如0.8则代表有Type值有80%概率正确。
*/
Probability: number;
}
/**
* SegmentCustomizedPortraitPic请求参数结构体
*/
export interface SegmentCustomizedPortraitPicRequest {
/**
* 此参数为分割选项,请根据需要选择自己所想从图片中分割的部分。注意所有选项均为非必选,如未选择则值默认为false, 但是必须要保证多于一个选项的描述为true。
*/
SegmentationOptions: SegmentationOptions;
/**
* 图片 base64 数据,base64 编码后大小不可超过5M。
图片分辨率须小于2000*2000。
支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。
*/
Image?: string;
/**
* 图片的 Url 。
Url、Image必须提供一个,如果都提供,只使用 Url。
图片分辨率须小于2000*2000 ,图片 base64 编码后大小不可超过5M。
图片存储于腾讯云的Url可保障更高下载速度和稳定性,建议图片存储于腾讯云。
非腾讯云存储的Url速度和稳定性可能受一定影响。
支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。
*/
Url?: string;
}
/**
* CreateGroup请求参数结构体
*/
export interface CreateGroupRequest {
/**
* 人体库名称,[1,60]个字符,可修改,不可重复。
*/
GroupName: string;
/**
* 人体库 ID,不可修改,不可重复。支持英文、数字、-%@#&_,长度限制64B。
*/
GroupId: string;
/**
* 人体库信息备注,[0,40]个字符。
*/
Tag?: string;
/**
* 人体识别所用的算法模型版本。
目前入参仅支持 “1.0”1个输入。 默认为"1.0"。
不同算法模型版本对应的人体识别算法不同,新版本的整体效果会优于旧版本,后续我们将推出更新版本。
*/
BodyModelVersion?: string;
}
/**
* 下衣属性信息
*/
export interface LowerBodyCloth {
/**
* 下衣颜色信息。
*/
Color: LowerBodyClothColor;
/**
* 下衣长度信息 。
*/
Length: LowerBodyClothLength;
/**
* 下衣类型信息。
*/
Type: LowerBodyClothType;
}
/**
* CreateSegmentationTask请求参数结构体
*/
export interface CreateSegmentationTaskRequest {
/**
* 需要分割的视频URL,可外网访问。
*/
VideoUrl: string;
/**
* 背景图片URL。
可以将视频背景替换为输入的图片。
如果不输入背景图片,则输出人像区域mask。
*/
BackgroundImageUrl?: string;
/**
* 预留字段,后期用于展示更多识别信息。
*/
Config?: string;
}
/**
* 人体轨迹信息。
*/
export interface TraceInfo {
/**
* 人体轨迹ID。
*/
TraceId: string;
/**
* 包含的人体轨迹图片Id列表。
*/
BodyIds: Array<string>;
}
/**
* DeleteGroup返回参数结构体
*/
export interface DeleteGroupResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 人体框
*/
export interface BodyRect {
/**
* 人体框左上角横坐标。
*/
X: number;
/**
* 人体框左上角纵坐标。
*/
Y: number;
/**
* 人体宽度。
*/
Width: number;
/**
* 人体高度。
*/
Height: number;
}
/**
* DescribeSegmentationTask返回参数结构体
*/
export interface DescribeSegmentationTaskResponse {
/**
* 当前任务状态:
QUEUING 排队中
PROCESSING 处理中
FINISHED 处理完成
*/
TaskStatus?: string;
/**
* 分割后视频URL, 存储于腾讯云COS
注意:此字段可能返回 null,表示取不到有效值。
*/
ResultVideoUrl?: string;
/**
* 分割后视频MD5,用于校验
注意:此字段可能返回 null,表示取不到有效值。
*/
ResultVideoMD5?: string;
/**
* 视频基本信息
注意:此字段可能返回 null,表示取不到有效值。
*/
VideoBasicInformation?: VideoBasicInformation;
/**
* 分割任务错误信息
注意:此字段可能返回 null,表示取不到有效值。
*/
ErrorMsg?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DetectBody请求参数结构体
*/
export interface DetectBodyRequest {
/**
* 人体图片 Base64 数据。
图片 base64 编码后大小不可超过5M。
图片分辨率不得超过 1920 * 1080 。
支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。
*/
Image?: string;
/**
* 最多检测的人体数目,默认值为1(仅检测图片中面积最大的那个人体); 最大值10 ,检测图片中面积最大的10个人体。
*/
MaxBodyNum?: number;
/**
* 人体图片 Url 。
Url、Image必须提供一个,如果都提供,只使用 Url。
图片 base64 编码后大小不可超过5M。
图片分辨率不得超过 1920 * 1080 。
图片存储于腾讯云的Url可保障更高下载速度和稳定性,建议图片存储于腾讯云。
非腾讯云存储的Url速度和稳定性可能受一定影响。
支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。
*/
Url?: string;
/**
* 是否返回年龄、性别、朝向等属性。
可选项有 Age、Bag、Gender、UpperBodyCloth、LowerBodyCloth、Orientation。
如果此参数为空则为不需要返回。
需要将属性组成一个用逗号分隔的字符串,属性之间的顺序没有要求。
关于各属性的详细描述,参见下文出参。
最多返回面积最大的 5 个人体属性信息,超过 5 个人体(第 6 个及以后的人体)的 BodyAttributesInfo 不具备参考意义。
*/
AttributesOptions?: AttributesOptions;
}
/**
* 人体年龄信息。
AttributesType 不含 Age 或检测超过 5 个人体时,此参数仍返回,但不具备参考意义。
*/
export interface Age {
/**
* 人体年龄信息,返回值为以下集合中的一个{小孩,青年,中年,老年}。
*/
Type: string;
/**
* Type识别概率值,[0.0,1.0],代表判断正确的概率。如0.8则代表有Type值有80%概率正确。
*/
Probability: number;
}
/**
* SearchTrace请求参数结构体
*/
export interface SearchTraceRequest {
/**
* 希望搜索的人体库ID。
*/
GroupId: string;
/**
* 人体轨迹信息。
*/
Trace: Trace;
/**
* 单张被识别的人体轨迹返回的最相似人员数量。
默认值为5,最大值为100。
例,设MaxPersonNum为8,则返回Top8相似的人员信息。 值越大,需要处理的时间越长。建议不要超过10。
*/
MaxPersonNum?: number;
/**
* 出参Score中,只有超过TraceMatchThreshold值的结果才会返回。
默认为0。范围[0, 100.0]。
*/
TraceMatchThreshold?: number;
}
/**
* 人体关键点信息
*/
export interface KeyPointInfo {
/**
* 代表不同位置的人体关键点信息,返回值为以下集合中的一个 [头部,颈部,右肩,右肘,右腕,左肩,左肘,左腕,右髋,右膝,右踝,左髋,左膝,左踝]
*/
KeyPointType: string;
/**
* 人体关键点横坐标
*/
X: number;
/**
* 人体关键点纵坐标
*/
Y: number;
}
/**
* DetectBody返回参数结构体
*/
export interface DetectBodyResponse {
/**
* 图中检测出来的人体框。
*/
BodyDetectResults: Array<BodyDetectResult>;
/**
* 人体识别所用的算法模型版本。
*/
BodyModelVersion: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 人员信息。
*/
export interface PersonInfo {
/**
* 人员名称。
*/
PersonName: string;
/**
* 人员ID。
*/
PersonId: string;
/**
* 包含的人体轨迹图片信息列表。
*/
TraceInfos: Array<TraceInfo>;
}
/**
* 人体是否挎包。
AttributesType 不含 Bag 或检测超过 5 个人体时,此参数仍返回,但不具备参考意义。
*/
export interface Bag {
/**
* 挎包信息,返回值为以下集合中的一个{双肩包, 斜挎包, 手拎包, 无包}。
*/
Type: string;
/**
* Type识别概率值,[0.0,1.0],代表判断正确的概率。如0.8则代表有Type值有80%概率正确。
*/
Probability: number;
}
/**
* SegmentCustomizedPortraitPic返回参数结构体
*/
export interface SegmentCustomizedPortraitPicResponse {
/**
* 根据指定标签分割输出的透明背景人像图片的 base64 数据。
*/
PortraitImage?: string;
/**
* 指定标签处理后的Mask。一个通过 Base64 编码的文件,解码后文件由 Float 型浮点数组成。这些浮点数代表原图从左上角开始的每一行的每一个像素点,每一个浮点数的值是原图相应像素点位于人体轮廓内的置信度(0-1)转化的灰度值(0-255)
*/
MaskImage?: string;
/**
* 坐标信息。
注意:此字段可能返回 null,表示取不到有效值。
*/
ImageRects?: Array<ImageRect>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 人体轨迹信息
*/
export interface Trace {
/**
* 人体轨迹图片 Base64 数组。
数组长度最小为1最大为5。
单个图片 base64 编码后大小不可超过2M。
支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。
*/
Images?: Array<string>;
/**
* 人体轨迹图片 Url 数组。
数组长度最小为1最大为5。
单个图片 base64 编码后大小不可超过2M。
Urls、Images必须提供一个,如果都提供,只使用 Urls。
图片存储于腾讯云的Url可保障更高下载速度和稳定性,建议图片存储于腾讯云。
非腾讯云存储的Url速度和稳定性可能受一定影响。
支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。
*/
Urls?: Array<string>;
/**
* 若输入的Images 和 Urls 是已经裁剪后的人体小图,则可以忽略本参数。
若否,或图片中包含多个人体,则需要通过本参数来指定图片中的人体框。
顺序对应 Images 或 Urls 中的顺序。
当不输入本参数时,我们将认为输入图片已是经过裁剪后的人体小图,不会进行人体检测而直接进行特征提取处理。
*/
BodyRects?: Array<BodyRect>;
}
/**
* DetectBodyJoints请求参数结构体
*/
export interface DetectBodyJointsRequest {
/**
* 图片 base64 数据,base64 编码后大小不可超过5M。
支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。
*/
Image?: string;
/**
* 图片的 Url 。对应图片 base64 编码后大小不可超过5M。
Url、Image必须提供一个,如果都提供,只使用 Url。
图片存储于腾讯云的Url可保障更高下载速度和稳定性,建议图片存储于腾讯云。
非腾讯云存储的Url速度和稳定性可能受一定影响。
支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。
*/
Url?: string;
}
/**
* SegmentPortraitPic请求参数结构体
*/
export interface SegmentPortraitPicRequest {
/**
* 图片 base64 数据,base64 编码后大小不可超过5M。
图片分辨率须小于2000*2000。
支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。
*/
Image?: string;
/**
* 图片的 Url 。
Url、Image必须提供一个,如果都提供,只使用 Url。
图片分辨率须小于2000*2000 ,图片 base64 编码后大小不可超过5M。
图片存储于腾讯云的Url可保障更高下载速度和稳定性,建议图片存储于腾讯云。
非腾讯云存储的Url速度和稳定性可能受一定影响。
支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。
*/
Url?: string;
}
/**
* 上衣颜色信息。
*/
export interface UpperBodyClothColor {
/**
* 上衣颜色信息,返回值为以下集合中的一个 {红色系, 黄色系, 绿色系, 蓝色系, 黑色系, 灰白色系。
*/
Type: string;
/**
* Type识别概率值,[0.0,1.0],代表判断正确的概率。如0.8则代表有Type值有80%概率正确。
*/
Probability: number;
}
/**
* GetGroupList请求参数结构体
*/
export interface GetGroupListRequest {
/**
* 起始序号,默认值为0。
*/
Offset?: number;
/**
* 返回数量,默认值为10,最大值为1000。
*/
Limit?: number;
}
/**
* 图像坐标信息。
*/
export interface ImageRect {
/**
* 左上角横坐标。
*/
X: number;
/**
* 左上角纵坐标。
*/
Y: number;
/**
* 人体宽度。
*/
Width: number;
/**
* 人体高度。
*/
Height: number;
/**
* 分割选项名称。
*/
Label: string;
}
/**
* 图中检测出来的人体框。
*/
export interface BodyDetectResult {
/**
* 检测出的人体置信度。
误识率百分之十对应的阈值是0.14;误识率百分之五对应的阈值是0.32;误识率百分之二对应的阈值是0.62;误识率百分之一对应的阈值是0.81。
通常情况建议使用阈值0.32,可适用大多数情况。
*/
Confidence: number;
/**
* 图中检测出来的人体框
*/
BodyRect: BodyRect;
/**
* 图中检测出的人体属性信息。
*/
BodyAttributeInfo: BodyAttributeInfo;
}
/**
* 人体朝向信息。
AttributesType 不含 Orientation 或检测超过 5 个人体时,此参数仍返回,但不具备参考意义。
*/
export interface Orientation {
/**
* 人体朝向信息,返回值为以下集合中的一个 {正向, 背向, 左, 右}。
*/
Type: string;
/**
* Type识别概率值,[0.0,1.0],代表判断正确的概率。如0.8则代表有Type值有80%概率正确。
*/
Probability: number;
}
/**
* 人体框和人体关键点信息。
*/
export interface BodyJointsResult {
/**
* 图中检测出来的人体框。
*/
BoundBox: BoundRect;
/**
* 14个人体关键点的坐标,人体关键点详见KeyPointInfo。
*/
BodyJoints: Array<KeyPointInfo>;
/**
* 检测出的人体置信度,0-1之间,数值越高越准确。
*/
Confidence: number;
}
/**
* 上衣衣袖信息。
*/
export interface UpperBodyClothSleeve {
/**
* 上衣衣袖信息, 返回值为以下集合中的一个 {长袖, 短袖}。
*/
Type: string;
/**
* Type识别概率值,[0.0,1.0],代表判断正确的概率。如0.8则代表有Type值有80%概率正确。
*/
Probability: number;
}
/**
* 上衣属性信息
*/
export interface UpperBodyCloth {
/**
* 上衣纹理信息。
*/
Texture: UpperBodyClothTexture;
/**
* 上衣颜色信息。
*/
Color: UpperBodyClothColor;
/**
* 上衣衣袖信息。
*/
Sleeve: UpperBodyClothSleeve;
}
/**
* 下衣长度信息
*/
export interface LowerBodyClothLength {
/**
* 下衣长度信息,返回值为以下集合中的一个,{长, 短} 。
*/
Type: string;
/**
* Type识别概率值,[0.0,1.0],代表判断正确的概率。如0.8则代表有Type值有80%概率正确。
*/
Probability: number;
}
/**
* SearchTrace返回参数结构体
*/
export interface SearchTraceResponse {
/**
* 识别出的最相似候选人。
*/
Candidates?: Array<Candidate>;
/**
* 输入的人体轨迹图片中的合法性校验结果。
只有为0时结果才有意义。
-1001: 输入图片不合法。-1002: 输入图片不能构成轨迹。
*/
InputRetCode?: number;
/**
* 输入的人体轨迹图片中的合法性校验结果详情。
-1101:图片无效,-1102:url不合法。-1103:图片过大。-1104:图片下载失败。-1105:图片解码失败。-1109:图片分辨率过高。-2023:轨迹中有非同人图片。-2024: 轨迹提取失败。-2025: 人体检测失败。
*/
InputRetCodeDetails?: Array<number>;
/**
* 人体识别所用的算法模型版本。
*/
BodyModelVersion?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateTrace返回参数结构体
*/
export interface CreateTraceResponse {
/**
* 人员轨迹唯一标识。
*/
TraceId?: string;
/**
* 人体识别所用的算法模型版本。
*/
BodyModelVersion?: string;
/**
* 输入的人体轨迹图片中的合法性校验结果。
只有为0时结果才有意义。
-1001: 输入图片不合法。-1002: 输入图片不能构成轨迹。
*/
InputRetCode?: number;
/**
* 输入的人体轨迹图片中的合法性校验结果详情。
-1101:图片无效,-1102:url不合法。-1103:图片过大。-1104:图片下载失败。-1105:图片解码失败。-1109:图片分辨率过高。-2023:轨迹中有非同人图片。-2024: 轨迹提取失败。-2025: 人体检测失败。
*/
InputRetCodeDetails?: Array<number>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreatePerson返回参数结构体
*/
export interface CreatePersonResponse {
/**
* 人员轨迹唯一标识。
*/
TraceId?: string;
/**
* 人体识别所用的算法模型版本。
*/
BodyModelVersion?: string;
/**
* 输入的人体轨迹图片中的合法性校验结果。
只有为0时结果才有意义。
-1001: 输入图片不合法。-1002: 输入图片不能构成轨迹。
*/
InputRetCode?: number;
/**
* 输入的人体轨迹图片中的合法性校验结果详情。
-1101:图片无效,-1102:url不合法。-1103:图片过大。-1104:图片下载失败。-1105:图片解码失败。-1109:图片分辨率过高。-2023:轨迹中有非同人图片。-2024: 轨迹提取失败。-2025: 人体检测失败。
RetCode 的顺序和入参中Images 或 Urls 的顺序一致。
*/
InputRetCodeDetails?: Array<number>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 人体框
*/
export interface BoundRect {
/**
* 人体框左上角横坐标。
*/
X: number;
/**
* 人体框左上角纵坐标。
*/
Y: number;
/**
* 人体宽度。
*/
Width: number;
/**
* 人体高度。
*/
Height: number;
}
/**
* 下衣颜色信息
*/
export interface LowerBodyClothColor {
/**
* 下衣颜色信息,返回值为以下集合中的一个{ 黑色系, 灰白色系, 彩色} 。
*/
Type: string;
/**
* Type识别概率值,[0.0,1.0],代表判断正确的概率。如0.8则代表有Type值有80%概率正确。
*/
Probability: number;
}
/**
* GetPersonList返回参数结构体
*/
export interface GetPersonListResponse {
/**
* 返回的人员信息。
*/
PersonInfos?: Array<PersonInfo>;
/**
* 该人体库的人员数量。
*/
PersonNum?: number;
/**
* 人体识别所用的算法模型版本。
*/
BodyModelVersion?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* GetPersonList请求参数结构体
*/
export interface GetPersonListRequest {
/**
* 人体库ID。
*/
GroupId: string;
/**
* 起始序号,默认值为0。
*/
Offset?: number;
/**
* 返回数量,默认值为10,最大值为1000。
*/
Limit?: number;
}
/**
* 下衣类型信息
*/
export interface LowerBodyClothType {
/**
* 下衣类型,返回值为以下集合中的一个 {裤子,裙子} 。
*/
Type: string;
/**
* Type识别概率值,[0.0,1.0],代表判断正确的概率。如0.8则代表有Type值有80%概率正确。
*/
Probability: number;
}
/**
* CreateTrace请求参数结构体
*/
export interface CreateTraceRequest {
/**
* 人员ID。
*/
PersonId: string;
/**
* 人体轨迹信息。
*/
Trace: Trace;
}
/**
* DeletePerson返回参数结构体
*/
export interface DeletePersonResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 返回人体属性选项,此值不填则为不需要返回,可以选择的值为以下六个。
Age、Bag、Gender、Orientation、UpperBodyCloth、LowerBodyCloth,详细的解释请看对象描述
需注意本接口最多返回面积最大的 5 个人体属性信息,超过 5 个人体(第 6 个及以后的人体)的人体属性不具备参考意义。
*/
export interface AttributesOptions {
/**
* 返回年龄信息
*/
Age?: boolean;
/**
* 返回随身挎包信息
*/
Bag?: boolean;
/**
* 返回性别信息
*/
Gender?: boolean;
/**
* 返回朝向信息
*/
Orientation?: boolean;
/**
* 返回上装信息
*/
UpperBodyCloth?: boolean;
/**
* 返回下装信息
*/
LowerBodyCloth?: boolean;
}
/**
* CreateGroup返回参数结构体
*/
export interface CreateGroupResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
} | the_stack |
import type { SliderContext } from './token'
import type { SliderProps, SliderThumbInstance } from './types'
import type { ComputedRef, Ref } from 'vue'
import { computed, nextTick, ref, toRaw, watch } from 'vue'
import { Logger, callEmit, getMouseClientXY, isNumeric, off, on } from '@idux/cdk/utils'
import { useFormAccessor, useFormElement } from '@idux/components/utils'
import { sliderStartDirection } from './token'
export type Nullable<T> = T | null
export interface SliderBindings {
valuesRef: Ref<number[]>
thumbListRef: Ref<SliderThumbInstance[]>
railRef: Ref<Nullable<HTMLElement>>
direction: SliderContext['direction']
isDisabled: ComputedRef<boolean>
isDragging: Ref<boolean>
focus: (options?: FocusOptions | undefined) => void
blur: () => void
setThumbRefs: (index: number) => (el: unknown) => void
handleMouseDown: (evt: MouseEvent | TouchEvent) => void
handleMouseUp: () => void
handleKeyDown: (evt: KeyboardEvent) => void
handleMarkClick: (evt: MouseEvent | TouchEvent, newValue: number) => void
}
export function useSlider(props: SliderProps): SliderBindings {
const { elementRef, focus, blur } = useFormElement<HTMLElement>()
const accessor = useFormAccessor<number | number[]>()
const valuesRef = ref<number[]>([props.min, props.min])
const thumbListRef = ref<SliderThumbInstance[]>([])
const activeIndex = ref<number>(-1)
const railRef = ref<Nullable<HTMLElement>>(null)
const isDragging = ref(false)
const isDisabled = computed(() => accessor?.disabled.value)
const precision = computed(() => {
const precisions = [props.min, props.max, props.step].map(num => {
const decimal = `${num}`.split('.')[1]
return decimal ? decimal.length : 0
})
return Math.max(...precisions)
})
const stepPrecision = computed(() => {
const decimal = `${props.step}`.split('.')[1]
return decimal ? decimal.length : 0
})
const direction = computed(() => {
if (props.vertical) {
return props.reverse ? sliderStartDirection.ttb : sliderStartDirection.btt
}
return props.reverse ? sliderStartDirection.rtl : sliderStartDirection.ltr
})
function setThumbRefs(index: number) {
return (el: unknown) => {
if (index === 0) {
elementRef.value = (el as SliderThumbInstance)?.thumbRef
}
thumbListRef.value[index] = el as SliderThumbInstance
}
}
function handleMouseDown(evt: MouseEvent | TouchEvent) {
const index = thumbListRef.value.findIndex(v => v?.thumbRef === evt.target)
if (index !== -1) {
// avoid triggering scrolling on touch
evt.preventDefault()
activeIndex.value = index
thumbListRef.value[index]?.thumbRef?.focus()
startDragging()
} else {
const newValue = calcValueByMouseEvent(evt)
setActiveIndex(newValue)
updateModelValue(newValue)
}
}
function handleKeyDown(evt: KeyboardEvent) {
if (props.keyboard) {
const index = thumbListRef.value.findIndex(v => v?.thumbRef === evt.target)
if (index !== -1) {
let value: Nullable<number> = null
if (evt.code === 'ArrowUp' || evt.code === 'ArrowRight') {
activeIndex.value = index
value = incValueByActiveIndex(+1)
} else if (evt.code === 'ArrowDown' || evt.code === 'ArrowLeft') {
activeIndex.value = index
value = incValueByActiveIndex(-1)
}
if (value !== null) {
evt.preventDefault()
updateModelValue(value)
checkAcross(value)
}
}
}
}
function handleMarkClick(evt: MouseEvent | TouchEvent, newValue: number) {
evt.stopPropagation()
setActiveIndex(newValue)
updateModelValue(newValue)
}
function startDragging() {
if (!isDragging.value) {
isDragging.value = true
on(window, 'mousemove', handleMouseMove)
on(window, 'touchmove', handleMouseMove)
on(window, 'mouseup', handleMouseUpOnDocument)
on(window, 'touchend', handleMouseUpOnDocument)
on(window, 'contextmenu', handleMouseUpOnDocument)
}
}
function stopDragging() {
if (isDragging.value) {
const activeThumbRef = thumbListRef.value[activeIndex.value]
isDragging.value = false
activeIndex.value = -1
if (!activeThumbRef?.isHovering) {
nextTick(() => activeThumbRef?.hideTooltip())
}
off(window, 'mousemove', handleMouseMove)
off(window, 'touchmove', handleMouseMove)
off(window, 'mouseup', handleMouseUpOnDocument)
off(window, 'touchend', handleMouseUpOnDocument)
off(window, 'contextmenu', handleMouseUpOnDocument)
}
}
function handleMouseMove(evt: MouseEvent | TouchEvent) {
if (!isDragging.value) {
stopDragging()
return
}
const newValue = calcValueByMouseEvent(evt)
updateModelValue(newValue)
checkAcross(newValue)
}
function handleMouseUpOnDocument() {
stopDragging()
callEmit(props.onChange, toRaw(valuesRef.value))
}
function handleMouseUp() {
const { value: index } = activeIndex
if (index !== -1) {
thumbListRef.value[index]?.thumbRef?.focus()
}
}
function updateModelValue(newValue: number) {
const { value: index } = activeIndex
if (valuesRef.value[index] !== newValue) {
const newValues = valuesRef.value.slice()
newValues[index] = newValue
const modelValue = props.range ? newValues : newValues[0]
accessor.setValue(modelValue)
isDragging.value ? callEmit(props.onInput, modelValue) : callEmit(props.onChange, modelValue)
// sync position of thumb
nextTick(() => setValues())
}
}
function setActiveIndex(newValue: number) {
const { value: oldValues } = valuesRef
activeIndex.value = props.range
? Math.abs(oldValues[0] - newValue) < Math.abs(oldValues[1] - newValue)
? 0
: 1
: 0
}
function checkAcross(value: number) {
if (props.range) {
const { value: thumbValues } = valuesRef
let newIndex = activeIndex.value
if (value > thumbValues[1]) {
newIndex = 1
} else if (value < thumbValues[0]) {
newIndex = 0
}
if (newIndex !== activeIndex.value) {
activeIndex.value = newIndex
thumbListRef.value[activeIndex.value]?.thumbRef?.focus()
}
}
}
function calcValueByMouseEvent(evt: MouseEvent | TouchEvent) {
const client = getMouseClientXY(evt)
const railRect = railRef.value!.getBoundingClientRect()
let percentage: number
if (props.vertical) {
percentage = (railRect.bottom - client.clientY) / railRect.height
} else {
percentage = (client.clientX - railRect.left) / railRect.width
}
if (props.reverse) {
percentage = 1 - percentage
}
return calcValueByStep(percentage * (props.max - props.min))
}
function calcValueByStep(value: number) {
value = Math.max(props.min, Math.min(props.max, value))
const marks = props.marks ?? {}
const points = Object.keys(marks).map(parseFloat)
if (props.step !== null) {
// convert to integer for calculation to ensure decimal accuracy
const convertNum = Math.pow(10, precision.value)
const totalSteps = Math.floor((props.max * convertNum - props.min * convertNum) / (props.step * convertNum))
const steps = Math.min((value - props.min) / props.step, totalSteps)
const closestStepValue = Math.round(steps) * props.step + props.min
points.push(parseFloat(closestStepValue.toFixed(precision.value)))
}
const diffs = points.map(point => Math.abs(value - point))
const index = diffs.indexOf(Math.min(...diffs))
return points[index] ?? props.min
}
function incValueByActiveIndex(flag: number) {
if (props.step !== null) {
const step = flag < 0 ? -props.step : +props.step
const currValue = valuesRef.value[activeIndex.value]
return Math.max(props.min, Math.min(props.max, parseFloat((currValue + step).toFixed(stepPrecision.value))))
}
return props.min
}
watch(
accessor.valueRef,
(val, oldVal) => {
if (isDragging.value || (Array.isArray(val) && Array.isArray(oldVal) && val.every((v, i) => v === oldVal[i]))) {
return
}
setValues()
},
{ immediate: true },
)
watch(
() => [props.max, props.min, props.range, props.step],
() => {
setValues()
},
)
function setValues() {
if (props.min > props.max) {
if (__DEV__) {
Logger.error('components/slider', 'min should not be greater than max.')
}
return
}
if (__DEV__ && props.step !== null && props.step <= 0) {
Logger.error('components/slider', `step(${props.step}) should be greater than 0.`)
}
const { value: modelValue } = accessor.valueRef
let val: number[]
if (props.range) {
if (!Array.isArray(modelValue)) {
if (__DEV__) {
Logger.error('components/slider', 'value should be [number, number] in range mode.')
}
return
}
val = [modelValue[0] ?? props.min, modelValue[1] ?? props.min]
} else {
if (!isNumeric(modelValue)) {
if (__DEV__) {
Logger.error('components/slider', 'value should be a number.')
}
return
}
val = [modelValue as number]
}
const newVal = val
.map(num => {
if (!isNumeric(num)) {
return props.min
}
return calcValueByStep(num)
})
.sort((a, b) => a - b) // order
// When the legal value is not equal to the modelValue, update modelValue
if (val.every((v, i) => v !== newVal[i])) {
const modelValue = props.range ? newVal : newVal[0]
callEmit(props.onChange, modelValue)
accessor.setValue(modelValue)
}
valuesRef.value = newVal
}
return {
valuesRef,
thumbListRef,
railRef,
direction,
isDisabled,
isDragging,
focus,
blur,
setThumbRefs,
handleMouseDown,
handleMouseUp,
handleKeyDown,
handleMarkClick,
}
} | the_stack |
import * as ABIDecoder from "abi-decoder";
import * as _ from "lodash";
import * as compact from "lodash.compact";
import * as Web3 from "web3";
// Utils
import { BigNumber } from "../../utils/bignumber";
import { DISABLED_TOKEN_SYMBOLS, TOKEN_REGISTRY_TRACKED_TOKENS } from "../../utils/constants";
import * as Units from "../../utils/units";
import { Web3Utils } from "../../utils/web3_utils";
// Test Utils
import { isNonNullAddress } from "../utils/utils";
import { ContractsAPI, TokenAPI } from "../../src/apis";
import { TokenAPIErrors } from "../../src/apis/token_api";
import { TokenAssertionErrors } from "../../src/invariants/token";
import { DummyTokenContract, TokenTransferProxyContract } from "../../src/wrappers";
import { CONTRACT_WRAPPER_ERRORS } from "../../src/wrappers/contract_wrappers/base_contract_wrapper";
import { ACCOUNTS } from "../accounts";
// Given that this is an integration test, we unmock the Dharma
// smart contracts artifacts package to pull the most recently
// deployed contracts on the current network.
jest.unmock("@dharmaprotocol/contracts");
const provider = new Web3.providers.HttpProvider("http://localhost:8545");
const web3 = new Web3(provider);
const web3Utils = new Web3Utils(web3);
const contractsApi = new ContractsAPI(web3);
const tokenApi = new TokenAPI(web3, contractsApi);
const TX_DEFAULTS = { from: ACCOUNTS[0].address, gas: 400000 };
const CONTRACT_OWNER = ACCOUNTS[0].address;
const SPENDER = ACCOUNTS[1].address;
const RECIPIENT = ACCOUNTS[2].address;
const OPERATOR = ACCOUNTS[3].address;
const TEST_ACCOUNTS = [SPENDER, RECIPIENT, OPERATOR];
const NON_CONTRACT_ADDRESS = ACCOUNTS[4].address;
const DEFAULT_STARTING_BALANCE = Units.ether(100);
describe("Token API (Integration Tests)", () => {
let dummyREPToken: DummyTokenContract;
let dummyZRXToken: DummyTokenContract;
let dummyMKRToken: DummyTokenContract;
let tokenTransferProxy: TokenTransferProxyContract;
let currentNetworkId: number;
let currentSnapshotId: number;
let dummyREPAddress: string;
beforeEach(async () => {
currentSnapshotId = await web3Utils.saveTestSnapshot();
const dummyTokenRegistry = await contractsApi.loadTokenRegistry();
dummyREPAddress = await dummyTokenRegistry.getTokenAddressBySymbol.callAsync("REP");
const dummyZRXAddress = await dummyTokenRegistry.getTokenAddressBySymbol.callAsync("ZRX");
const dummyMKRAddress = await dummyTokenRegistry.getTokenAddressBySymbol.callAsync("MKR");
dummyREPToken = await DummyTokenContract.at(dummyREPAddress, web3, TX_DEFAULTS);
dummyZRXToken = await DummyTokenContract.at(dummyZRXAddress, web3, TX_DEFAULTS);
dummyMKRToken = await DummyTokenContract.at(dummyMKRAddress, web3, TX_DEFAULTS);
const dummyTokens = [dummyREPToken, dummyZRXToken, dummyMKRToken];
for (const testAccount of TEST_ACCOUNTS) {
for (const dummyToken of dummyTokens) {
await dummyToken.setBalance.sendTransactionAsync(
testAccount,
DEFAULT_STARTING_BALANCE,
{ from: CONTRACT_OWNER },
);
}
}
tokenTransferProxy = await contractsApi.loadTokenTransferProxyAsync();
ABIDecoder.addABI(dummyREPToken.abi);
});
afterEach(async () => {
await web3Utils.revertToSnapshot(currentSnapshotId);
ABIDecoder.removeABI(dummyREPToken.abi);
});
beforeAll(async () => {
currentNetworkId = await web3Utils.getNetworkIdAsync();
});
describe("#transferAsync", () => {
describe("no contract at token address", () => {
test("should throw CONTRACT_NOT_FOUND_ON_NETWORK", async () => {
await expect(
tokenApi.transferAsync(NON_CONTRACT_ADDRESS, RECIPIENT, new BigNumber(10), {
from: SPENDER,
}),
).rejects.toThrow(
CONTRACT_WRAPPER_ERRORS.CONTRACT_NOT_FOUND_ON_NETWORK(
"ERC20",
currentNetworkId,
),
);
});
});
describe("contract exists at token address", () => {
describe("the sender has insufficient balance", async () => {
beforeEach(async () => {
await dummyREPToken.setBalance.sendTransactionAsync(SPENDER, Units.ether(0), {
from: CONTRACT_OWNER,
});
});
test("should throw INSUFFICIENT_SENDER_BALANCE", async () => {
await expect(
tokenApi.transferAsync(
dummyREPToken.address,
RECIPIENT,
new BigNumber(10),
{ from: SPENDER },
),
).rejects.toThrow(TokenAPIErrors.INSUFFICIENT_SENDER_BALANCE(SPENDER));
});
});
describe("sender transfers 10 tokens to recipient", () => {
let txHash: string;
let spenderBalanceBefore: BigNumber;
let recipientBalanceBefore: BigNumber;
beforeEach(async () => {
spenderBalanceBefore = await dummyREPToken.balanceOf.callAsync(SPENDER);
recipientBalanceBefore = await dummyREPToken.balanceOf.callAsync(RECIPIENT);
txHash = await tokenApi.transferAsync(
dummyREPToken.address,
RECIPIENT,
new BigNumber(10),
{ from: SPENDER },
);
});
test("should emit log indicating transfer success", async () => {
const receipt = await web3Utils.getTransactionReceiptAsync(txHash);
const [transferLog] = compact(ABIDecoder.decodeLogs(receipt.logs));
expect(transferLog.name).toBe("Transfer");
});
test("should debit sender 10 tokens", async () => {
await expect(dummyREPToken.balanceOf.callAsync(SPENDER)).resolves.toEqual(
spenderBalanceBefore.minus(10),
);
});
test("should credit recipient 10 tokens", async () => {
await expect(dummyREPToken.balanceOf.callAsync(RECIPIENT)).resolves.toEqual(
recipientBalanceBefore.plus(10),
);
});
// TODO: Add fault tolerance to cases in which
// sender does not have sufficient balance, or in which
// contract does not implement ERC20 interface
});
});
});
describe("#transferFromAsync", () => {
describe("no contract at token address", () => {
test("should throw CONTRACT_NOT_FOUND_ON_NETWORK", async () => {
await expect(
tokenApi.transferFromAsync(
NON_CONTRACT_ADDRESS,
SPENDER,
RECIPIENT,
new BigNumber(10),
{ from: OPERATOR },
),
).rejects.toThrow(
CONTRACT_WRAPPER_ERRORS.CONTRACT_NOT_FOUND_ON_NETWORK(
"ERC20",
currentNetworkId,
),
);
});
});
describe("contract exists at token address", () => {
describe("sender has insufficient balance", () => {
beforeEach(async () => {
await dummyZRXToken.approve.sendTransactionAsync(OPERATOR, new BigNumber(10), {
from: SPENDER,
});
await dummyZRXToken.setBalance.sendTransactionAsync(SPENDER, Units.ether(0), {
from: CONTRACT_OWNER,
});
});
test("should throw INSUFFICIENT_SENDER_BALANCE", async () => {
await expect(
tokenApi.transferFromAsync(
dummyZRXToken.address,
SPENDER,
RECIPIENT,
new BigNumber(10),
{ from: OPERATOR },
),
).rejects.toThrow(TokenAPIErrors.INSUFFICIENT_SENDER_BALANCE(SPENDER));
});
});
describe("spender has given operator insufficient allowance", async () => {
test("should throw INSUFFICIENT_SENDER_ALLOWANCE", async () => {
await expect(
tokenApi.transferFromAsync(
dummyZRXToken.address,
SPENDER,
RECIPIENT,
new BigNumber(10),
{ from: OPERATOR },
),
).rejects.toThrow(TokenAPIErrors.INSUFFICIENT_SENDER_ALLOWANCE(SPENDER));
});
});
describe("sender transfers 10 tokens to recipient", () => {
let txHash: string;
let spenderBalanceBefore: BigNumber;
let recipientBalanceBefore: BigNumber;
beforeEach(async () => {
spenderBalanceBefore = await dummyZRXToken.balanceOf.callAsync(SPENDER);
recipientBalanceBefore = await dummyZRXToken.balanceOf.callAsync(RECIPIENT);
await dummyZRXToken.approve.sendTransactionAsync(OPERATOR, new BigNumber(10), {
from: SPENDER,
});
txHash = await tokenApi.transferFromAsync(
dummyZRXToken.address,
SPENDER,
RECIPIENT,
new BigNumber(10),
{ from: OPERATOR },
);
});
test("should emit log indicating transferFrom success", async () => {
const receipt = await web3Utils.getTransactionReceiptAsync(txHash);
const [transferLog] = compact(ABIDecoder.decodeLogs(receipt.logs));
expect(transferLog.name).toBe("Transfer");
});
test("should debit sender 10 tokens", async () => {
await expect(dummyZRXToken.balanceOf.callAsync(SPENDER)).resolves.toEqual(
spenderBalanceBefore.minus(10),
);
});
test("should credit recipient 10 tokens", async () => {
await expect(dummyZRXToken.balanceOf.callAsync(RECIPIENT)).resolves.toEqual(
recipientBalanceBefore.plus(10),
);
});
// TODO: Add fault tolerance to cases in which
// sender does not have sufficient balance, or in which
// contract does not implement ERC20 interface
});
});
});
describe("#getBalanceAsync", () => {
describe("no contract at token address", () => {
test("should throw CONTRACT_NOT_FOUND_ON_NETWORK", async () => {
await expect(
tokenApi.getBalanceAsync(NON_CONTRACT_ADDRESS, SPENDER),
).rejects.toThrow(
CONTRACT_WRAPPER_ERRORS.CONTRACT_NOT_FOUND_ON_NETWORK(
"ERC20",
currentNetworkId,
),
);
});
});
describe("contract exists at token address", () => {
beforeEach(async () => {
await dummyMKRToken.setBalance.sendTransactionAsync(SPENDER, Units.ether(99), {
from: CONTRACT_OWNER,
});
await dummyMKRToken.setBalance.sendTransactionAsync(RECIPIENT, Units.ether(70), {
from: CONTRACT_OWNER,
});
await dummyMKRToken.setBalance.sendTransactionAsync(OPERATOR, Units.ether(200), {
from: CONTRACT_OWNER,
});
});
describe("token does not implement ERC20", () => {
let nonERC20;
beforeEach(async () => {
nonERC20 = await contractsApi.loadRepaymentRouterAsync();
});
test("should throw MISSING_ERC20_METHOD", async () => {
await expect(
tokenApi.getBalanceAsync(nonERC20.address, SPENDER),
).rejects.toThrow(TokenAssertionErrors.MISSING_ERC20_METHOD(nonERC20.address));
});
});
describe("Account #1", () => {
test("should return correct balance for account", async () => {
await expect(
tokenApi.getBalanceAsync(dummyMKRToken.address, SPENDER),
).resolves.toEqual(Units.ether(99));
});
});
describe("Account #2", () => {
test("should return correct balance for account", async () => {
await expect(
tokenApi.getBalanceAsync(dummyMKRToken.address, RECIPIENT),
).resolves.toEqual(Units.ether(70));
});
});
describe("Account #3", () => {
test("should return correct balance for account", async () => {
await expect(
tokenApi.getBalanceAsync(dummyMKRToken.address, OPERATOR),
).resolves.toEqual(Units.ether(200));
});
});
// TODO: Add fault tolerance to cases in which
// contract does not implement ERC20 interface
});
});
describe("#setProxyAllowanceAsync", () => {
describe("no contract at token address", () => {
test("should throw CONTRACT_NOT_FOUND_ON_NETWORK", async () => {
await expect(
tokenApi.setProxyAllowanceAsync(NON_CONTRACT_ADDRESS, Units.ether(100)),
).rejects.toThrow(
CONTRACT_WRAPPER_ERRORS.CONTRACT_NOT_FOUND_ON_NETWORK(
"ERC20",
currentNetworkId,
),
);
});
});
describe("contract exists at token address", () => {
describe("sender is owner of account", () => {
let txHash: string;
beforeEach(async () => {
txHash = await tokenApi.setProxyAllowanceAsync(
dummyREPToken.address,
Units.ether(100),
{ from: SPENDER },
);
});
test("should emit log indicating successful", async () => {
const receipt = await web3Utils.getTransactionReceiptAsync(txHash);
const [approveLog] = compact(ABIDecoder.decodeLogs(receipt.logs));
expect(approveLog.name).toBe("Approval");
});
test("should return specified allowance to proxy", async () => {
await expect(
dummyREPToken.allowance.callAsync(SPENDER, tokenTransferProxy.address),
).resolves.toEqual(Units.ether(100));
});
// TODO: Add fault tolerance
});
});
});
describe("#setUnlimitedProxyAllowanceAsync", () => {
describe("no contract at token address", () => {
test("should throw CONTRACT_NOT_FOUND_ON_NETWORK", async () => {
await expect(
tokenApi.setUnlimitedProxyAllowanceAsync(NON_CONTRACT_ADDRESS),
).rejects.toThrow(
CONTRACT_WRAPPER_ERRORS.CONTRACT_NOT_FOUND_ON_NETWORK(
"ERC20",
currentNetworkId,
),
);
});
});
describe("contract exists at token address", () => {
describe("sender is owner of account", () => {
let txHash: string;
beforeEach(async () => {
txHash = await tokenApi.setUnlimitedProxyAllowanceAsync(dummyZRXToken.address, {
from: RECIPIENT,
});
});
test("should emit log indicating successful", async () => {
const receipt = await web3Utils.getTransactionReceiptAsync(txHash);
const [approveLog] = compact(ABIDecoder.decodeLogs(receipt.logs));
expect(approveLog.name).toBe("Approval");
});
test("should return specified allowance to proxy", async () => {
const unlimitedAllowance = new BigNumber(2).pow(256).sub(1);
await expect(
dummyZRXToken.allowance.callAsync(RECIPIENT, tokenTransferProxy.address),
).resolves.toEqual(unlimitedAllowance);
});
// TODO: Add fault tolerance
});
});
});
describe("#getProxyAllowanceAsync", () => {
describe("no contract at token address", () => {
test("should throw CONTRACT_NOT_FOUND_ON_NETWORK", async () => {
await expect(
tokenApi.getProxyAllowanceAsync(NON_CONTRACT_ADDRESS, SPENDER),
).rejects.toThrow(
CONTRACT_WRAPPER_ERRORS.CONTRACT_NOT_FOUND_ON_NETWORK(
"ERC20",
currentNetworkId,
),
);
});
});
describe("contract exists at token address", () => {
beforeEach(async () => {
await dummyMKRToken.approve.sendTransactionAsync(
tokenTransferProxy.address,
Units.ether(99),
{ from: SPENDER },
);
await dummyMKRToken.approve.sendTransactionAsync(
tokenTransferProxy.address,
Units.ether(70),
{ from: RECIPIENT },
);
await dummyMKRToken.approve.sendTransactionAsync(
tokenTransferProxy.address,
Units.ether(200),
{ from: OPERATOR },
);
});
describe("Account #1", () => {
test("should return correct balance for account", async () => {
await expect(
tokenApi.getProxyAllowanceAsync(dummyMKRToken.address, SPENDER),
).resolves.toEqual(Units.ether(99));
});
});
describe("Account #2", () => {
test("should return correct balance for account", async () => {
await expect(
tokenApi.getProxyAllowanceAsync(dummyMKRToken.address, RECIPIENT),
).resolves.toEqual(Units.ether(70));
});
});
describe("Account #3", () => {
test("should return correct balance for account", async () => {
await expect(
tokenApi.getProxyAllowanceAsync(dummyMKRToken.address, OPERATOR),
).resolves.toEqual(Units.ether(200));
});
});
});
});
describe("#getTokenAttributesBySymbol", () => {
describe("given a symbol for a token in the token registry", () => {
test("should return an object with the token's attributes ", async () => {
const expectedAttributes = _.find(TOKEN_REGISTRY_TRACKED_TOKENS, { symbol: "REP" });
const attributes = await tokenApi.getTokenAttributesBySymbol("REP");
expect(attributes.address).toEqual(dummyREPAddress);
expect(attributes.name).toEqual(expectedAttributes.name);
expect(attributes.symbol).toEqual(expectedAttributes.symbol);
expect(attributes.numDecimals.toNumber()).toEqual(expectedAttributes.decimals);
});
});
});
describe("#getSupportedTokens", () => {
describe("token registry has tokens", () => {
test("should return the list of token symbols and names", async () => {
// Get the result of the function we are testing.
const tokenSymbolList = await tokenApi.getSupportedTokens();
// Get a reference from an unsorted array of data we know is correct.
const expectedTokenSymbolList = _.chain(TOKEN_REGISTRY_TRACKED_TOKENS)
.map((token) => {
return {
symbol: token.symbol,
name: token.name,
numDecimals: token.decimals,
};
})
.filter((token) => {
return !DISABLED_TOKEN_SYMBOLS.includes(token.symbol);
})
.value();
// Sort both arrays for comparison.
const sortedResult = _.sortBy(tokenSymbolList, "symbol");
const sortedReference = _.sortBy(expectedTokenSymbolList, "symbol");
// For each set of token attributes, assert expectations.
sortedResult.forEach((tokenAttributes, index) => {
const reference = sortedReference[index];
expect(isNonNullAddress(tokenAttributes.address)).toEqual(true);
expect(tokenAttributes.name).toEqual(reference.name);
expect(tokenAttributes.symbol).toEqual(reference.symbol);
expect(tokenAttributes.numDecimals.toNumber()).toEqual(reference.numDecimals);
});
});
});
});
describe("#getTokenSymbolList", () => {
describe("token registry has tokens", () => {
test("should return the list of token symbols", async () => {
const tokenSymbolList = await tokenApi.getTokenSymbolList();
const expectedTokenSymbolList = _.chain(TOKEN_REGISTRY_TRACKED_TOKENS)
.map((token) => token.symbol)
.filter((tokenSymbol) => {
return !DISABLED_TOKEN_SYMBOLS.includes(tokenSymbol);
})
.value();
expect(tokenSymbolList.sort()).toEqual(expectedTokenSymbolList.sort());
});
});
});
describe("#getNumDecimals", () => {
test("should return the number of decimal places that the token uses", async () => {
const numDecimals = await tokenApi.getNumDecimals("REP");
expect(numDecimals).toEqual(new BigNumber(18));
});
test("should throw an error if the token does not exist on the registry", async () => {
const tokenSymbol = "MIN";
await expect(tokenApi.getNumDecimals(tokenSymbol)).rejects.toThrow(
TokenAPIErrors.TOKEN_DOES_NOT_EXIST(tokenSymbol),
);
});
});
}); | the_stack |
import { SeedDescription, Uuid } from "@emeraldpay/emerald-vault-core";
import { BlockchainCode } from "@emeraldwallet/core";
import { HDPathIndexes } from '@emeraldwallet/store/lib/hdpath-preview/types';
import { ImportPkType } from '@emeraldwallet/ui';
import {
defaultResult,
isLedger,
isLedgerStart,
isPk,
isPkJson,
isPkRaw,
isSeedCreate,
isSeedSelected,
KeySourceType,
KeysSource,
Result,
SeedCreate,
StepDescription,
StepDetails,
TWalletOptions,
} from "./types";
export enum STEP_CODE {
KEY_SOURCE = "keySource",
OPTIONS = "options",
SELECT_BLOCKCHAIN = "selectCoins",
UNLOCK_SEED = "unlockSeed",
LOCK_SEED = "lockSeed",
SELECT_HD_ACCOUNT = "selectAccount",
CREATED = "created",
MNEMONIC_GENERATE = "mnemonicGenerate",
MNEMONIC_IMPORT = "mnemonicImport",
PK_IMPORT = "pkImport",
LEDGER_OPEN = "ledgerOpen"
}
const STEPS: { [key in STEP_CODE]: StepDescription } = {
"keySource": {
code: STEP_CODE.KEY_SOURCE,
title: "Choose Key Source",
},
"options": {
code: STEP_CODE.OPTIONS,
title: "Wallet Options",
},
"selectCoins": {
code: STEP_CODE.SELECT_BLOCKCHAIN,
title: "Select Blockchains",
},
"unlockSeed": {
code: STEP_CODE.UNLOCK_SEED,
title: "Unlock Seed",
},
"selectAccount": {
code: STEP_CODE.SELECT_HD_ACCOUNT,
title: "Select HD Account",
},
"created": {
code: STEP_CODE.CREATED,
title: "Wallet Created",
},
"mnemonicGenerate": {
code: STEP_CODE.MNEMONIC_GENERATE,
title: "Generate Secret Phrase"
},
"mnemonicImport": {
code: STEP_CODE.MNEMONIC_IMPORT,
title: "Import Secret Phrase"
},
"lockSeed": {
code: STEP_CODE.LOCK_SEED,
title: "Save Secret Phrase"
},
"pkImport": {
code: STEP_CODE.PK_IMPORT,
title: "Import Private Key"
},
"ledgerOpen": {
code: STEP_CODE.LEDGER_OPEN,
title: "Connect to Ledger"
}
}
type OnCreate = (result: Result) => void;
export class CreateWalletFlow {
private result: Result = defaultResult();
private step: STEP_CODE = STEP_CODE.KEY_SOURCE;
private onCreate: OnCreate;
constructor(onCreate: OnCreate) {
this.onCreate = onCreate;
}
static create(result: Result, step: STEP_CODE, onCreate: OnCreate): CreateWalletFlow {
const instance = new CreateWalletFlow(onCreate);
instance.result = result;
instance.step = step;
return instance;
}
getSteps(): StepDescription[] {
const useSeedBased = isSeedCreate(this.result.type) || isSeedSelected(this.result.type);
const useLedger = isLedgerStart(this.result.type) || isLedger(this.result.type);
const needHdAccount = useSeedBased || useLedger;
const needBlockchain = this.result.type != "empty";
const result: StepDescription[] = [];
result.push(STEPS[STEP_CODE.KEY_SOURCE]);
result.push(STEPS[STEP_CODE.OPTIONS]);
if (isSeedCreate(this.result.type)) {
if (this.result.type.type == KeySourceType.SEED_GENERATE) {
result.push(STEPS[STEP_CODE.MNEMONIC_GENERATE]);
} else if (this.result.type.type == KeySourceType.SEED_IMPORT) {
result.push(STEPS[STEP_CODE.MNEMONIC_IMPORT]);
}
result.push(STEPS[STEP_CODE.LOCK_SEED]);
} else if (isPk(this.result.type)) {
result.push(STEPS[STEP_CODE.PK_IMPORT]);
} else if (useLedger) {
result.push(STEPS[STEP_CODE.LEDGER_OPEN]);
}
if (needBlockchain) {
result.push(STEPS[STEP_CODE.SELECT_BLOCKCHAIN]);
}
if (isSeedSelected(this.result.type)) {
result.push(STEPS[STEP_CODE.UNLOCK_SEED]);
}
if (needHdAccount) {
result.push(STEPS[STEP_CODE.SELECT_HD_ACCOUNT]);
}
result.push(STEPS[STEP_CODE.CREATED]);
return result
}
getCurrentStep(): StepDetails {
return {
code: this.step,
index: this.getSteps().findIndex((it) => it.code == this.step)
}
}
canGoNext(): boolean {
if (
this.step == STEP_CODE.CREATED ||
this.step == STEP_CODE.KEY_SOURCE ||
this.step == STEP_CODE.UNLOCK_SEED ||
this.step == STEP_CODE.MNEMONIC_GENERATE ||
this.step == STEP_CODE.MNEMONIC_IMPORT ||
this.step == STEP_CODE.LOCK_SEED ||
this.step == STEP_CODE.LEDGER_OPEN
) {
return false
}
if (this.step == STEP_CODE.SELECT_BLOCKCHAIN) {
return this.result.blockchains.length > 0;
}
if (this.step == STEP_CODE.SELECT_HD_ACCOUNT) {
return typeof this.result.seedAccount == 'number';
}
if (this.step == STEP_CODE.PK_IMPORT) {
const { type } = this.result;
return (
isPkJson(type)
&& type.json.length > 0
&& type.jsonPassword.length > 0
&& type.password.length > 0
) || (
isPkRaw(type)
&& type.pk.length > 0
&& type.password.length > 0
);
}
return true;
}
getMnemonic(): SeedCreate {
if (!isSeedCreate(this.result.type)) {
throw new Error("Not a generated seed");
}
return this.result.type;
}
getResult(): Result {
return this.result;
}
getSeedId(): Uuid {
if (isSeedSelected(this.result.type)) {
return this.result.type.id;
}
throw new Error("Not a seed")
}
private copy(): CreateWalletFlow {
const copy = new CreateWalletFlow(this.onCreate);
copy.result = this.result;
copy.step = this.step;
return copy;
}
// actions
applyNext(): CreateWalletFlow {
const copy = this.copy();
if (this.step == STEP_CODE.OPTIONS) {
if (this.result.type == 'empty') {
this.onCreate(this.result);
copy.step = STEP_CODE.CREATED;
} else if (isSeedSelected(this.result.type)) {
copy.step = STEP_CODE.SELECT_BLOCKCHAIN;
} else if (isSeedCreate(this.result.type)) {
if (this.result.type.type == KeySourceType.SEED_GENERATE) {
copy.step = STEP_CODE.MNEMONIC_GENERATE;
} else if (this.result.type.type == KeySourceType.SEED_IMPORT) {
copy.step = STEP_CODE.MNEMONIC_IMPORT;
} else {
throw new Error("Invalid seed type: " + this.result.type.type)
}
} else if (isPk(this.result.type)) {
copy.step = STEP_CODE.PK_IMPORT;
} else if (isLedger(this.result.type)) {
copy.step = STEP_CODE.LEDGER_OPEN;
}
} else if (this.step == STEP_CODE.SELECT_BLOCKCHAIN) {
if (isSeedSelected(this.result.type)) {
copy.step = STEP_CODE.UNLOCK_SEED;
} else if (isSeedCreate(this.result.type)) {
copy.step = STEP_CODE.SELECT_HD_ACCOUNT;
} else if (isPk(this.result.type)) {
this.onCreate(this.result);
copy.step = STEP_CODE.CREATED;
} else if (isLedger(this.result.type)) {
copy.step = STEP_CODE.SELECT_HD_ACCOUNT;
}
} else if (this.step == STEP_CODE.SELECT_HD_ACCOUNT) {
this.onCreate(this.result);
copy.step = STEP_CODE.CREATED;
} else if (this.step == STEP_CODE.PK_IMPORT) {
copy.step = STEP_CODE.SELECT_BLOCKCHAIN;
}
return copy;
}
applySource(value: KeysSource): CreateWalletFlow {
const copy = this.copy();
let type: KeysSource = value;
if (isLedgerStart(type)) {
type = {
type: KeySourceType.LEDGER,
id: undefined
};
copy.result.seed = {
type: "ledger"
}
}
copy.result = {...copy.result, type};
copy.step = STEP_CODE.OPTIONS;
return copy;
}
applyOptions(value: TWalletOptions): CreateWalletFlow {
const copy = this.copy();
copy.result = {...this.result, options: value};
return copy;
}
applyBlockchains(value: BlockchainCode[]): CreateWalletFlow {
const copy = this.copy();
copy.result = {...this.result, blockchains: value};
return copy;
}
applySeedPassword(value: string): CreateWalletFlow {
const copy = this.copy();
if (!isSeedSelected(copy.result.type)) {
throw new Error("Not a seed reference");
}
copy.result = {...this.result, seed: {type: "id", password: value, value: copy.result.type.id}};
copy.step = STEP_CODE.SELECT_HD_ACCOUNT;
return copy;
}
applyHDAccount(
value: number | undefined,
addresses: Partial<Record<BlockchainCode, string>>,
indexes: HDPathIndexes,
): CreateWalletFlow {
const copy = this.copy();
copy.result = { ...this.result, seedAccount: value, addresses, indexes };
return copy;
}
/**
*
* @param mnemonic mnemonic phrase
* @param password optional mnemonic password (not for encryption)
*/
applyMnemonic(mnemonic: string, password: string | undefined): CreateWalletFlow {
const copy = this.copy();
if (!isSeedCreate(copy.result.type)) {
throw new Error("Not a generated seed");
}
const current: SeedCreate = copy.result.type;
const type: SeedCreate = {...current, mnemonic, password};
copy.result = {...this.result, type};
copy.step = STEP_CODE.LOCK_SEED;
return copy;
}
/**
*
* @param id saved seed id
* @param password encryption password
*/
applyMnemonicSaved(id: Uuid, password: string): CreateWalletFlow {
const copy = this.copy();
if (!isSeedCreate(copy.result.type)) {
throw new Error("Not a generated seed");
}
copy.result = {...this.result, seed: {type: "id", value: id, password}};
copy.step = STEP_CODE.SELECT_BLOCKCHAIN;
return copy;
}
applyImportPk(value: ImportPkType): CreateWalletFlow {
const copy = this.copy();
if (!isPk(copy.result.type)) {
throw new Error("Not a PK import");
}
if (value.raw != null) {
copy.result.type = {
type: KeySourceType.PK_RAW,
pk: value.raw,
password: value.password,
};
} else if (value.json != null && value.jsonPassword != null) {
copy.result.type = {
type: KeySourceType.PK_WEB3_JSON,
json: value.json,
jsonPassword: value.jsonPassword,
password: value.password,
};
}
return copy;
}
applyLedgerConnected(seed: SeedDescription): CreateWalletFlow {
if (seed.type != "ledger") {
return this;
}
const copy = this.copy();
copy.step = STEP_CODE.SELECT_BLOCKCHAIN;
copy.result.type = {
type: KeySourceType.LEDGER,
id: seed.id
}
copy.result.seed = {
type: "ledger",
}
return copy;
}
} | the_stack |
declare module 'vscode' {
/**
* Represents the alignment of status bar items.
*/
export enum StatusBarAlignment {
/**
* Aligned to the left side.
*/
Left = 1,
/**
* Aligned to the right side.
*/
Right = 2,
}
/**
* A status bar item is a status bar contribution that can
* show text and icons and run a command on click.
*/
export interface StatusBarItem {
/**
* The identifier of this item.
*
* *Note*: if no identifier was provided by the {@link window.createStatusBarItem `window.createStatusBarItem`}
* method, the identifier will match the {@link Extension.id extension identifier}.
*/
readonly id: string;
/**
* The alignment of this item.
*/
readonly alignment: StatusBarAlignment;
/**
* The priority of this item. Higher value means the item should
* be shown more to the left.
*/
readonly priority?: number;
/**
* The name of the entry, like 'Python Language Indicator', 'Git Status' etc.
* Try to keep the length of the name short, yet descriptive enough that
* users can understand what the status bar item is about.
*/
name: string | undefined;
/**
* The text to show for the entry. You can embed icons in the text by leveraging the syntax:
*
* `My text $(icon-name) contains icons like $(icon-name) this one.`
*
* Where the icon-name is taken from the [octicon](https://octicons.github.com) icon set, e.g.
* `light-bulb`, `thumbsup`, `zap` etc.
*/
text: string;
/**
* The tooltip text when you hover over this entry.
*/
tooltip: string | MarkdownString | undefined;
/**
* The foreground color for this entry.
*/
color: string | ThemeColor | undefined;
/**
* The background color for this entry.
*
* *Note*: only the following colors are supported:
* * `new ThemeColor('statusBarItem.errorBackground')`
* * `new ThemeColor('statusBarItem.warningBackground')`
*
* More background colors may be supported in the future.
*
* *Note*: when a background color is set, the statusbar may override
* the `color` choice to ensure the entry is readable in all themes.
*/
backgroundColor: ThemeColor | undefined;
/**
* The identifier of a command to run on click. The command must be
* [known](#commands.getCommands).
*/
command: string | Command | undefined;
/**
* Accessibility information used when screen reader interacts with this StatusBar item
*/
accessibilityInformation?: AccessibilityInformation;
/**
* Shows the entry in the status bar.
*/
show(): void;
/**
* Hide the entry in the status bar.
*/
hide(): void;
/**
* Dispose and free associated resources. Call
* [hide](#StatusBarItem.hide).
*/
dispose(): void;
}
export interface OutputChannel {
/**
* The human-readable name of this output channel.
*/
readonly name: string;
/**
* Append the given value to the channel.
*
* @param value A string, falsy values will not be printed.
*/
append(value: string): void;
/**
* Append the given value and a line feed character
* to the channel.
*
* @param value A string, falsy values will be printed.
*/
appendLine(value: string): void;
/**
* Removes all output from the channel.
*/
clear(): void;
/**
* Reveal this channel in the UI.
*
* @param preserveFocus When `true` the channel will not take focus.
*/
show(preserveFocus?: boolean): void;
/**
* Hide this channel from the UI.
*/
hide(): void;
/**
* Replaces all output from the channel with the given value.
*
* @param value A string, falsy values will not be printed.
*/
replace(value: string): void;
/**
* Dispose and free associated resources.
*/
dispose(): void;
}
/**
* Options to configure the behaviour of a file open dialog.
*
* * Note 1: A dialog can select files, folders, or both. This is not true for Windows
* which enforces to open either files or folder, but *not both*.
* * Note 2: Explicitly setting `canSelectFiles` and `canSelectFolders` to `false` is futile
* and the editor then silently adjusts the options to select files.
*/
export interface OpenDialogOptions {
/**
* The resource the dialog shows when opened.
*/
defaultUri?: Uri;
/**
* A human-readable string for the open button.
*/
openLabel?: string;
/**
* Allow to select files, defaults to `true`.
*/
canSelectFiles?: boolean;
/**
* Allow to select folders, defaults to `false`.
*/
canSelectFolders?: boolean;
/**
* Allow to select many files or folders.
*/
canSelectMany?: boolean;
/**
* A set of file filters that are used by the dialog. Each entry is a human readable label,
* like "TypeScript", and an array of extensions, e.g.
* ```ts
* {
* 'Images': ['png', 'jpg']
* 'TypeScript': ['ts', 'tsx']
* }
* ```
*/
filters?: { [name: string]: string[] };
/**
* Dialog title.
*
* This parameter might be ignored, as not all operating systems display a title on open dialogs
* (for example, macOS).
*/
title?: string;
}
/**
* Options to configure the behaviour of a file save dialog.
*/
export interface SaveDialogOptions {
/**
* The resource the dialog shows when opened.
*/
defaultUri?: Uri;
/**
* A human-readable string for the save button.
*/
saveLabel?: string;
/**
* A set of file filters that are used by the dialog. Each entry is a human readable label,
* like "TypeScript", and an array of extensions, e.g.
* ```ts
* {
* 'Images': ['png', 'jpg']
* 'TypeScript': ['ts', 'tsx']
* }
* ```
*/
filters?: { [name: string]: string[] };
/**
* Dialog title.
*
* This parameter might be ignored, as not all operating systems display a title on save dialogs
* (for example, macOS).
*/
title?: string;
}
export namespace window {
/**
* Set a message to the status bar. This is a short hand for the more powerful
* status bar [items](#window.createStatusBarItem).
*
* @param text The message to show, supports icon substitution as in status bar [items](#StatusBarItem.text).
* @param hideAfterTimeout Timeout in milliseconds after which the message will be disposed.
* @return A disposable which hides the status bar message.
*/
// tslint:disable-next-line: unified-signatures
export function setStatusBarMessage(text: string, hideAfterTimeout: number): Disposable;
/**
* Set a message to the status bar. This is a short hand for the more powerful
* status bar [items](#window.createStatusBarItem).
*
* @param text The message to show, supports icon substitution as in status bar [items](#StatusBarItem.text).
* @param hideWhenDone Thenable on which completion (resolve or reject) the message will be disposed.
* @return A disposable which hides the status bar message.
*/
// tslint:disable-next-line: unified-signatures
export function setStatusBarMessage(text: string, hideWhenDone: Thenable<any>): Disposable;
/**
* Set a message to the status bar. This is a short hand for the more powerful
* status bar [items](#window.createStatusBarItem).
*
* *Note* that status bar messages stack and that they must be disposed when no
* longer used.
*
* @param text The message to show, supports icon substitution as in status bar [items](#StatusBarItem.text).
* @return A disposable which hides the status bar message.
*/
export function setStatusBarMessage(text: string): Disposable;
/**
* Creates a status bar [item](#StatusBarItem).
*
* @param alignment The alignment of the item.
* @param priority The priority of the item. Higher values mean the item should be shown more to the left.
* @return A new status bar item.
*/
export function createStatusBarItem(alignment?: StatusBarAlignment, priority?: number): StatusBarItem;
/**
* Creates a status bar {@link StatusBarItem item}.
*
* @param id The unique identifier of the item.
* @param alignment The alignment of the item.
* @param priority The priority of the item. Higher values mean the item should be shown more to the left.
* @return A new status bar item.
*/
export function createStatusBarItem(id: string, alignment?: StatusBarAlignment, priority?: number): StatusBarItem;
/**
* Creates a new [output channel](#OutputChannel) with the given name.
*
* @param name Human-readable string which will be used to represent the channel in the UI.
*/
export function createOutputChannel(name: string): OutputChannel;
/**
* The currently opened terminals or an empty array.
*/
export const terminals: ReadonlyArray<Terminal>;
/**
* The currently active terminal or `undefined`. The active terminal is the one that
* currently has focus or most recently had focus.
*/
export const activeTerminal: Terminal | undefined;
/**
* An [event](#Event) which fires when the [active terminal](#window.activeTerminal)
* has changed. *Note* that the event also fires when the active terminal changes
* to `undefined`.
*/
export const onDidChangeActiveTerminal: Event<Terminal | undefined>;
/**
* An [event](#Event) which fires when a terminal has been created, either through the
* [createTerminal](#window.createTerminal) API or commands.
*/
export const onDidOpenTerminal: Event<Terminal>;
/**
* An [event](#Event) which fires when a terminal is disposed.
*/
export const onDidCloseTerminal: Event<Terminal>;
/**
* Represents the current window's state.
*/
export const state: WindowState;
/**
* An [event](#Event) which fires when the focus state of the current window
* changes. The value of the event represents whether the window is focused.
*/
export const onDidChangeWindowState: Event<WindowState>;
/**
* Creates a [Terminal](#Terminal). The cwd of the terminal will be the workspace directory
* if it exists, regardless of whether an explicit customStartPath setting exists.
*
* @param name Optional human-readable string which will be used to represent the terminal in the UI.
* @param shellPath Optional path to a custom shell executable to be used in the terminal.
* @param shellArgs Optional args for the custom shell executable. A string can be used on Windows only which
* allows specifying shell args in [command-line format](https://msdn.microsoft.com/en-au/08dfcab2-eb6e-49a4-80eb-87d4076c98c6).
* @return A new Terminal.
*/
export function createTerminal(name?: string, shellPath?: string, shellArgs?: string[] | string): Terminal;
/**
* Create and show a new webview panel.
*
* @param viewType Identifies the type of the webview panel.
* @param title Title of the panel.
* @param showOptions Where to show the webview in the editor. If preserveFocus is set, the new webview will not take focus.
* @param options Settings for the new panel.
*
* @return New webview panel.
*/
export function createWebviewPanel(viewType: string, title: string, showOptions: ViewColumn | { viewColumn: ViewColumn, preserveFocus?: boolean }, options?: WebviewPanelOptions & WebviewOptions): WebviewPanel;
/**
* Registers a webview panel serializer.
*
* Extensions that support reviving should have an `"onWebviewPanel:viewType"` activation event and
* make sure that [registerWebviewPanelSerializer](#registerWebviewPanelSerializer) is called during activation.
*
* Only a single serializer may be registered at a time for a given `viewType`.
*
* @param viewType Type of the webview panel that can be serialized.
* @param serializer Webview serializer.
*/
export function registerWebviewPanelSerializer(viewType: string, serializer: WebviewPanelSerializer): Disposable;
/**
* Register a new provider for webview views.
*
* @param viewId Unique id of the view. This should match the `id` from the
* `views` contribution in the package.json.
* @param provider Provider for the webview views.
*
* @return Disposable that unregisters the provider.
*/
export function registerWebviewViewProvider(viewId: string, provider: WebviewViewProvider, options?: {
/**
* Content settings for the webview created for this view.
*/
readonly webviewOptions?: {
/**
* Controls if the webview element itself (iframe) is kept around even when the view
* is no longer visible.
*
* Normally the webview's html context is created when the view becomes visible
* and destroyed when it is hidden. Extensions that have complex state
* or UI can set the `retainContextWhenHidden` to make VS Code keep the webview
* context around, even when the webview moves to a background tab. When a webview using
* `retainContextWhenHidden` becomes hidden, its scripts and other dynamic content are suspended.
* When the view becomes visible again, the context is automatically restored
* in the exact same state it was in originally. You cannot send messages to a
* hidden webview, even with `retainContextWhenHidden` enabled.
*
* `retainContextWhenHidden` has a high memory overhead and should only be used if
* your view's context cannot be quickly saved and restored.
*/
readonly retainContextWhenHidden?: boolean;
};
}): Disposable;
/**
* Register a provider for custom editors for the `viewType` contributed by the `customEditors` extension point.
*
* When a custom editor is opened, VS Code fires an `onCustomEditor:viewType` activation event. Your extension
* must register a [`CustomTextEditorProvider`](#CustomTextEditorProvider), [`CustomReadonlyEditorProvider`](#CustomReadonlyEditorProvider),
* [`CustomEditorProvider`](#CustomEditorProvider)for `viewType` as part of activation.
*
* @param viewType Unique identifier for the custom editor provider. This should match the `viewType` from the
* `customEditors` contribution point.
* @param provider Provider that resolves custom editors.
* @param options Options for the provider.
*
* @return Disposable that unregisters the provider.
*/
export function registerCustomEditorProvider(viewType: string, provider: CustomTextEditorProvider | CustomReadonlyEditorProvider | CustomEditorProvider, options?: {
/**
* Content settings for the webview panels created for this custom editor.
*/
readonly webviewOptions?: WebviewPanelOptions;
/**
* Only applies to `CustomReadonlyEditorProvider | CustomEditorProvider`.
*
* Indicates that the provider allows multiple editor instances to be open at the same time for
* the same resource.
*
* By default, VS Code only allows one editor instance to be open at a time for each resource. If the
* user tries to open a second editor instance for the resource, the first one is instead moved to where
* the second one was to be opened.
*
* When `supportsMultipleEditorsPerDocument` is enabled, users can split and create copies of the custom
* editor. In this case, the custom editor must make sure it can properly synchronize the states of all
* editor instances for a resource so that they are consistent.
*/
readonly supportsMultipleEditorsPerDocument?: boolean;
}): Disposable;
/**
* Register provider that enables the detection and handling of links within the terminal.
* @param provider The provider that provides the terminal links.
* @return Disposable that unregisters the provider.
*/
export function registerTerminalLinkProvider(provider: TerminalLinkProvider): Disposable;
/**
* Registers a provider for a contributed terminal profile.
* @param id The ID of the contributed terminal profile.
* @param provider The terminal profile provider.
*/
export function registerTerminalProfileProvider(id: string, provider: TerminalProfileProvider): Disposable;
/**
* ~~Show progress in the Source Control viewlet while running the given callback and while
* its returned promise isn't resolve or rejected.~~
*
* @deprecated Use `withProgress` instead.
*
* @param task A callback returning a promise. Progress increments can be reported with
* the provided [progress](#Progress)-object.
* @return The thenable the task did return.
*/
export function withScmProgress<R>(task: (progress: Progress<number>) => Thenable<R>): Thenable<R>;
/**
* Show progress in the editor. Progress is shown while running the given callback
* and while the promise it returned isn't resolved nor rejected. The location at which
* progress should show (and other details) is defined via the passed [`ProgressOptions`](#ProgressOptions).
*
* @param task A callback returning a promise. Progress state can be reported with
* the provided [progress](#Progress)-object.
*
* To report discrete progress, use `increment` to indicate how much work has been completed. Each call with
* a `increment` value will be summed up and reflected as overall progress until 100% is reached (a value of
* e.g. `10` accounts for `10%` of work done).
* Note that currently only `ProgressLocation.Notification` is capable of showing discrete progress.
*
* To monitor if the operation has been cancelled by the user, use the provided [`CancellationToken`](#CancellationToken).
* Note that currently only `ProgressLocation.Notification` is supporting to show a cancel button to cancel the
* long running operation.
*
* @return The thenable the task-callback returned.
*/
export function withProgress<R>(options: ProgressOptions, task: (progress: Progress<{ message?: string; increment?: number }>, token: CancellationToken) => Thenable<R>): Thenable<R>;
/**
* Register a [TreeDataProvider](#TreeDataProvider) for the view contributed using the extension point `views`.
* This will allow you to contribute data to the [TreeView](#TreeView) and update if the data changes.
*
* **Note:** To get access to the [TreeView](#TreeView) and perform operations on it, use [createTreeView](#window.createTreeView).
*
* @param viewId Id of the view contributed using the extension point `views`.
* @param treeDataProvider A [TreeDataProvider](#TreeDataProvider) that provides tree data for the view
*/
export function registerTreeDataProvider<T>(viewId: string, treeDataProvider: TreeDataProvider<T>): Disposable;
/**
* Create a [TreeView](#TreeView) for the view contributed using the extension point `views`.
* @param viewId Id of the view contributed using the extension point `views`.
* @param options Options for creating the [TreeView](#TreeView)
* @returns a [TreeView](#TreeView).
*/
export function createTreeView<T>(viewId: string, options: TreeViewOptions<T>): TreeView<T>;
/**
* Options for creating a [TreeView](#TreeView)
*/
export interface TreeViewOptions<T> {
/**
* A data provider that provides tree data.
*/
treeDataProvider: TreeDataProvider<T>;
/**
* Whether to show collapse all action or not.
*/
showCollapseAll?: boolean;
}
/**
* Shows a file open dialog to the user which allows to select a file
* for opening-purposes.
*
* @param options Options that control the dialog.
* @returns A promise that resolves to the selected resources or `undefined`.
*/
export function showOpenDialog(options: OpenDialogOptions): Thenable<Uri[] | undefined>;
/**
* Shows a file save dialog to the user which allows to select a file
* for saving-purposes.
*
* @param options Options that control the dialog.
* @returns A promise that resolves to the selected resource or `undefined`.
*/
export function showSaveDialog(options: SaveDialogOptions): Thenable<Uri | undefined>;
/**
* Shows a selection list of [workspace folders](#workspace.workspaceFolders) to pick from.
* Returns `undefined` if no folder is open.
*
* @param options Configures the behavior of the workspace folder list.
* @return A promise that resolves to the workspace folder or `undefined`.
*/
export function showWorkspaceFolderPick(options?: WorkspaceFolderPickOptions): Thenable<WorkspaceFolder | undefined>;
/**
* Registers a [uri handler](#UriHandler) capable of handling system-wide [uris](#Uri).
* In case there are multiple windows open, the topmost window will handle the uri.
* A uri handler is scoped to the extension it is contributed from; it will only
* be able to handle uris which are directed to the extension itself. A uri must respect
* the following rules:
*
* - The uri-scheme must be `vscode.env.uriScheme`;
* - The uri-authority must be the extension id (e.g. `my.extension`);
* - The uri-path, -query and -fragment parts are arbitrary.
*
* For example, if the `my.extension` extension registers a uri handler, it will only
* be allowed to handle uris with the prefix `product-name://my.extension`.
*
* An extension can only register a single uri handler in its entire activation lifetime.
*
* * *Note:* There is an activation event `onUri` that fires when a uri directed for
* the current extension is about to be handled.
*
* @param handler The uri handler to register for this extension.
*/
export function registerUriHandler(handler: UriHandler): Disposable;
/**
* The currently active color theme as configured in the settings. The active
* theme can be changed via the `workbench.colorTheme` setting.
*/
export let activeColorTheme: ColorTheme;
/**
* An [event](#Event) which fires when the active theme changes or one of it's colors chnage.
*/
export const onDidChangeActiveColorTheme: Event<ColorTheme>;
}
/**
* A panel that contains a webview.
*/
interface WebviewPanel {
/**
* Identifies the type of the webview panel, such as `'markdown.preview'`.
*/
readonly viewType: string;
/**
* Title of the panel shown in UI.
*/
title: string;
/**
* Icon for the panel shown in UI.
*/
iconPath?: Uri | { light: Uri; dark: Uri };
/**
* Webview belonging to the panel.
*/
readonly webview: Webview;
/**
* Content settings for the webview panel.
*/
readonly options: WebviewPanelOptions;
/**
* Editor position of the panel. This property is only set if the webview is in
* one of the editor view columns.
*/
readonly viewColumn?: ViewColumn;
/**
* Whether the panel is active (focused by the user).
*/
readonly active: boolean;
/**
* Whether the panel is visible.
*/
readonly visible: boolean;
/**
* Fired when the panel's view state changes.
*/
readonly onDidChangeViewState: Event<WebviewPanelOnDidChangeViewStateEvent>;
/**
* Fired when the panel is disposed.
*
* This may be because the user closed the panel or because `.dispose()` was
* called on it.
*
* Trying to use the panel after it has been disposed throws an exception.
*/
readonly onDidDispose: Event<void>;
/**
* Show the webview panel in a given column.
*
* A webview panel may only show in a single column at a time. If it is already showing, this
* method moves it to a new column.
*
* @param viewColumn View column to show the panel in. Shows in the current `viewColumn` if undefined.
* @param preserveFocus When `true`, the webview will not take focus.
*/
reveal(viewColumn?: ViewColumn, preserveFocus?: boolean): void;
/**
* Dispose of the webview panel.
*
* This closes the panel if it showing and disposes of the resources owned by the webview.
* Webview panels are also disposed when the user closes the webview panel. Both cases
* fire the `onDispose` event.
*/
dispose(): any;
}
/**
* Restore webview panels that have been persisted when vscode shuts down.
*
* There are two types of webview persistence:
*
* - Persistence within a session.
* - Persistence across sessions (across restarts of VS Code).
*
* A `WebviewPanelSerializer` is only required for the second case: persisting a webview across sessions.
*
* Persistence within a session allows a webview to save its state when it becomes hidden
* and restore its content from this state when it becomes visible again. It is powered entirely
* by the webview content itself. To save off a persisted state, call `acquireVsCodeApi().setState()` with
* any json serializable object. To restore the state again, call `getState()`
*
* ```js
* // Within the webview
* const vscode = acquireVsCodeApi();
*
* // Get existing state
* const oldState = vscode.getState() || { value: 0 };
*
* // Update state
* setState({ value: oldState.value + 1 })
* ```
*
* A `WebviewPanelSerializer` extends this persistence across restarts of VS Code. When the editor is shutdown,
* VS Code will save off the state from `setState` of all webviews that have a serializer. When the
* webview first becomes visible after the restart, this state is passed to `deserializeWebviewPanel`.
* The extension can then restore the old `WebviewPanel` from this state.
*
* @param T Type of the webview's state.
*/
interface WebviewPanelSerializer<T = unknown> {
/**
* Restore a webview panel from its serialized `state`.
*
* Called when a serialized webview first becomes visible.
*
* @param webviewPanel Webview panel to restore. The serializer should take ownership of this panel. The
* serializer must restore the webview's `.html` and hook up all webview events.
* @param state Persisted state from the webview content.
*
* @return Thenable indicating that the webview has been fully restored.
*/
deserializeWebviewPanel(webviewPanel: WebviewPanel, state: T): Thenable<void>;
}
/**
* Event fired when a webview panel's view state changes.
*/
export interface WebviewPanelOnDidChangeViewStateEvent {
/**
* Webview panel whose view state changed.
*/
readonly webviewPanel: WebviewPanel;
}
/**
* A webview based view.
*/
/**
* A webview based view.
*/
export interface WebviewView {
/**
* Identifies the type of the webview view, such as `'hexEditor.dataView'`.
*/
readonly viewType: string;
/**
* The underlying webview for the view.
*/
readonly webview: Webview;
/**
* View title displayed in the UI.
*
* The view title is initially taken from the extension `package.json` contribution.
*/
title?: string;
/**
* Human-readable string which is rendered less prominently in the title.
*/
description?: string;
/**
* Event fired when the view is disposed.
*
* Views are disposed when they are explicitly hidden by a user (this happens when a user
* right clicks in a view and unchecks the webview view).
*
* Trying to use the view after it has been disposed throws an exception.
*/
readonly onDidDispose: Event<void>;
/**
* Tracks if the webview is currently visible.
*
* Views are visible when they are on the screen and expanded.
*/
readonly visible: boolean;
/**
* Event fired when the visibility of the view changes.
*
* Actions that trigger a visibility change:
*
* - The view is collapsed or expanded.
* - The user switches to a different view group in the sidebar or panel.
*
* Note that hiding a view using the context menu instead disposes of the view and fires `onDidDispose`.
*/
readonly onDidChangeVisibility: Event<void>;
/**
* Reveal the view in the UI.
*
* If the view is collapsed, this will expand it.
*
* @param preserveFocus When `true` the view will not take focus.
*/
show(preserveFocus?: boolean): void;
}
/**
* Additional information the webview view being resolved.
*
* @param T Type of the webview's state.
*/
interface WebviewViewResolveContext<T = unknown> {
/**
* Persisted state from the webview content.
*
* To save resources, VS Code normally deallocates webview documents (the iframe content) that are not visible.
* For example, when the user collapse a view or switches to another top level activity in the sidebar, the
* `WebviewView` itself is kept alive but the webview's underlying document is deallocated. It is recreated when
* the view becomes visible again.
*
* You can prevent this behavior by setting `retainContextWhenHidden` in the `WebviewOptions`. However this
* increases resource usage and should be avoided wherever possible. Instead, you can use persisted state to
* save off a webview's state so that it can be quickly recreated as needed.
*
* To save off a persisted state, inside the webview call `acquireVsCodeApi().setState()` with
* any json serializable object. To restore the state again, call `getState()`. For example:
*
* ```js
* // Within the webview
* const vscode = acquireVsCodeApi();
*
* // Get existing state
* const oldState = vscode.getState() || { value: 0 };
*
* // Update state
* setState({ value: oldState.value + 1 })
* ```
*
* VS Code ensures that the persisted state is saved correctly when a webview is hidden and across
* editor restarts.
*/
readonly state: T | undefined;
}
/**
* Provider for creating `WebviewView` elements.
*/
export interface WebviewViewProvider {
/**
* Revolves a webview view.
*
* `resolveWebviewView` is called when a view first becomes visible. This may happen when the view is
* first loaded or when the user hides and then shows a view again.
*
* @param webviewView Webview view to restore. The provider should take ownership of this view. The
* provider must set the webview's `.html` and hook up all webview events it is interested in.
* @param context Additional metadata about the view being resolved.
* @param token Cancellation token indicating that the view being provided is no longer needed.
*
* @return Optional thenable indicating that the view has been fully resolved.
*/
resolveWebviewView(webviewView: WebviewView, context: WebviewViewResolveContext, token: CancellationToken): Thenable<void> | void;
}
/**
* Represents a color theme kind.
*/
export enum ColorThemeKind {
Light = 1,
Dark = 2,
HighContrast = 3,
}
/**
* Represents a color theme.
*/
export interface ColorTheme {
/**
* The kind of this color theme: light, dark or high contrast.
*/
readonly kind: ColorThemeKind;
}
} | the_stack |
import { Dom7Array } from 'dom7';
import Framework7, { CSSSelector, Framework7EventsClass, Framework7Plugin } from '../app/app-class';
import { Searchbar } from '../searchbar/searchbar';
import { View } from '../view/view';
export namespace Autocomplete {
interface Autocomplete extends Framework7EventsClass<Events> {
/** Link to global app instance */
app: Framework7;
/** Object with passed initialization parameters */
params: Parameters;
/** Array with selected items */
value: unknown[];
/** true if Autocomplete is currently opened */
opened: boolean;
/** HTML element of Autocomplete opener element (if passed on init) */
openerEl: HTMLElement | undefined;
/** Dom7 instance of of Autocomplete opener element (if passed on init) */
$openerEl: Dom7Array | undefined;
/** HTML element of Autocomplete input (if passed on init) */
inputEl: HTMLElement | undefined;
/** Dom7 instance of of Autocomplete input (if passed on init) */
$inputEl: Dom7Array | undefined;
/** Dom7 instance of Autocomplete dropdown */
$dropdownEl: Dom7Array | undefined;
/** Autocomplete URL (that was passed in url parameter) */
url: string;
/** Autocomplete View (that was passed in view parameter) or found parent view */
view: View.View;
/** HTML element of Autocomplete container: dropdown element, or popup element, or page element. Available when Autocomplete opened */
el: HTMLElement | undefined;
/** Dom7 instance of Autocomplete container: dropdown element, or popup element, or page element. Available when Autocomplete opened */
$el: Dom7Array | undefined;
/** Autocomplete page Searchbar instance */
searchbar: Searchbar.Searchbar;
/** Open Autocomplete (Dropdown, Page or Popup) */
open(): void;
/** Close Autocomplete */
close(): void;
/** Show autocomplete preloader */
preloaderShow(): void;
/** Hide autocomplete preloader */
preloaderHide(): void;
/** Destroy Autocomplete instance and remove all events */
destroy(): void;
}
interface Parameters {
/** Defines how to open Autocomplete, can be page or popup (for Standalone) or dropdown. (default page) */
openIn?: string;
/** Function which accepts search query and render function where you need to pass array with matched items. */
source: (query: string, render: (items: any[]) => void) => void;
/** Limit number of maximum displayed items in autocomplete per query. */
limit?: number;
/** Set to true to include Preloader to autocomplete layout. (default false) */
preloader?: boolean;
/** Preloader color, one of the default colors. */
preloaderColor?: string;
/** Array with default selected values. */
value?: unknown[];
/** Name of matched item object's key that represents item value. (default id) */
valueProperty?: string;
/** Name of matched item object's key that represents item display value which is used as title of displayed options. (default text) */
textProperty?: string;
/** If enabled, then it will request passed to source function on autocomplete open. (default false) */
requestSourceOnOpen?: boolean;
/** String with CSS selector or HTMLElement of link which will open standalone autocomplete page or popup on click. */
openerEl?: HTMLElement | CSSSelector;
/** Default text for "Close" button when opened as Popup. (default Close) */
popupCloseLinkText?: string;
/** Default text for "Back" link when opened as Page. (default Back) */
pageBackLinkText?: string;
/** Autocomplete page title. If nothing is specified and passed openerEl is an item of List View, then text value of item-title element will be used. */
pageTitle?: string;
/** Searchbar placeholder text. (default Search...) */
searchbarPlaceholder?: string;
/** Searchbar "Cancel" button text. (default Cancel) */
searchbarDisableText?: string;
/** Enables searchbar disable button. By default, disabled for Aurora theme */
searchbarDisableButton?: boolean;
/** Value of "spellcheck" attribute on searchbar input (default false) */
searchbarSpellcheck?: boolean;
/** Enables Autocomplete popup to push view/s behind on open (default false)*/
popupPush?: boolean;
/** Enables ability to close Autocomplete popup with swipe (default undefined) */
popupSwipeToClose?: boolean | undefined;
/** Text which is displayed when no matches found. (default Nothing found) */
notFoundText?: string;
/** Set to true to allow multiple selections. (default false) */
multiple?: boolean;
/** Set to true and autocomplete will be closed when user picks value. Not available if multiple is enabled. (default false) */
closeOnSelect?: boolean;
/** Set to true to auto focus search field on autocomplete open. (default false) */
autoFocus?: boolean;
/** Set to false to open standalone autocomplete without animation. (default true) */
animate?: boolean;
/** Navbar color theme. One of the default color themes. */
navbarColorTheme?: string;
/** Form (checkboxes or radios) color theme. One of the default color themes. */
formColorTheme?: string;
/** Will add opened autocomplete modal (when openIn: 'popup') to router history which gives ability to close autocomplete by going back in router history and set current route to the autocomplete modal. (default false) */
routableModals?: boolean;
/** Standalone autocomplete URL that will be set as a current route. (default select/) */
url?: string;
/** Link to initialized View instance if you want use standalone Autocomplete. By default, if not specified, it will be opened in Main View.. */
view?: View.View;
/** String with CSS selector or HTMLElement of related text input. */
inputEl?: HTMLElement | CSSSelector;
/** Allows to configure input events used to handle Autocomplete actions and source request. Can be changed for example to change keyup compositionend if you use keyboard with composition of Chinese characters. (default input) */
inputEvents?: string;
/** Highlight matches in autocomplete results. (default true) */
highlightMatches?: boolean;
/** Enables type ahead, will prefill input value with first item in match. (default false) */
typeahead?: boolean;
/** Specify dropdown placeholder text. */
dropdownPlaceholderText?: string;
/** If true then value of related input will be update as well. (default true) */
updateInputValueOnSelect?: boolean;
/** If true then input which is used as item-input in List View will be expanded to full screen wide during dropdown visible.. (default false) */
expandInput?: boolean;
/** By default dropdown will be added to parent page-content element. You can specify here different element where to add dropdown element. */
dropdownContainerEl?: HTMLElement | CSSSelector;
/** Function to render autocomplete dropdown, must return dropdown HTML string. */
renderDropdown?: (items: any[]) => string;
/** Function to render autocomplete page, must return page HTML string. */
renderPage?: (items: any[]) => string;
/** Function to render autocomplete popup, must return popup HTML string. */
renderPopup?: (items: any[]) => string;
/** Function to render single autocomplete, must return item HTML string. */
renderItem?: (item: any, index: number) => string;
/** Function to render searchbar, must return searchbar HTML string. */
renderSearchbar?: () => string;
/** Function to render navbar, must return navbar HTML string. */
renderNavbar?: () => string;
on?: {
[event in keyof Events]?: Events[event];
};
}
interface Events {
/** Event will be triggered when Autocomplete value changed. Returned value is an array with selected items */
change: (values: any[]) => void;
/** Event will be triggered when Autocomplete starts its opening animation. As an argument event handler receives autocomplete instance */
open: (autocomplete: Autocomplete) => void;
/** Event will be triggered after Autocomplete completes its opening animation. As an argument event handler receives autocomplete instance */
opened: (autocomplete: Autocomplete) => void;
/** Event will be triggered when Autocomplete starts its closing animation. As an argument event handler receives autocomplete instance */
close: (autocomplete: Autocomplete) => void;
/** Event will be triggered after Autocomplete completes its closing animation. As an argument event handler receives autocomplete instance */
closed: (autocomplete: Autocomplete) => void;
/** Event will be triggered right before Autocomplete instance will be destroyed. As an argument event handler receives autocomplete instance */
beforeDestroy: (autocomplete: Autocomplete) => void;
}
interface AppMethods {
autocomplete: {
/** create Autocomplete instance */
create(parameters: Parameters): Autocomplete;
/** destroy Autocomplete instance */
destroy(el: HTMLElement | CSSSelector): void;
/** get Autocomplete instance by HTML element */
get(el: HTMLElement | CSSSelector): Autocomplete;
/** open Autocomplete */
open(el: HTMLElement | CSSSelector): Autocomplete;
/** closes Autocomplete */
close(el: HTMLElement | CSSSelector): Autocomplete;
};
}
interface AppParams {
autocomplete?: Parameters | undefined;
}
interface AppEvents {
/** Event will be triggered when Autocomplete value changed. Returned value is an array with selected items */
autocompleteChange: (autocomplete: Autocomplete, value: unknown) => void;
/** Event will be triggered when Autocomplete starts its opening animation. As an argument event handler receives autocomplete instance */
autocompleteOpen: (autocomplete: Autocomplete) => void;
/** Event will be triggered after Autocomplete completes its opening animation. As an argument event handler receives autocomplete instance */
autocompleteOpened: (autocomplete: Autocomplete) => void;
/** Event will be triggered when Autocomplete starts its closing animation. As an argument event handler receives autocomplete instance */
autocompleteClose: (autocomplete: Autocomplete) => void;
/** Event will be triggered after Autocomplete completes its closing animation. As an argument event handler receives autocomplete instance */
autocompleteClosed: (autocomplete: Autocomplete) => void;
/** Event will be triggered right before Autocomplete instance will be destroyed. As an argument event handler receives autocomplete instance */
autocompleteBeforeDestroy: (autocomplete: Autocomplete) => void;
}
}
declare const AutocompleteComponent: Framework7Plugin;
export default AutocompleteComponent; | the_stack |
export const black: string;
export const black100: string;
export const blue: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
export const blue10: string;
export const blue100: string;
export const blue20: string;
export const blue30: string;
export const blue40: string;
export const blue50: string;
export const blue60: string;
export const blue70: string;
export const blue80: string;
export const blue90: string;
export const colors: {
black: {
'100': string;
};
blue: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
coolGray: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
cyan: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
gray: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
green: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
magenta: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
orange: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
purple: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
red: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
teal: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
warmGray: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
white: {
'0': string;
};
yellow: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
};
export const coolGray: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
export const coolGray10: string;
export const coolGray100: string;
export const coolGray20: string;
export const coolGray30: string;
export const coolGray40: string;
export const coolGray50: string;
export const coolGray60: string;
export const coolGray70: string;
export const coolGray80: string;
export const coolGray90: string;
export const cyan: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
export const cyan10: string;
export const cyan100: string;
export const cyan20: string;
export const cyan30: string;
export const cyan40: string;
export const cyan50: string;
export const cyan60: string;
export const cyan70: string;
export const cyan80: string;
export const cyan90: string;
export const gray: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
export const gray10: string;
export const gray100: string;
export const gray20: string;
export const gray30: string;
export const gray40: string;
export const gray50: string;
export const gray60: string;
export const gray70: string;
export const gray80: string;
export const gray90: string;
export const green: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
export const green10: string;
export const green100: string;
export const green20: string;
export const green30: string;
export const green40: string;
export const green50: string;
export const green60: string;
export const green70: string;
export const green80: string;
export const green90: string;
export const magenta: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
export const magenta10: string;
export const magenta100: string;
export const magenta20: string;
export const magenta30: string;
export const magenta40: string;
export const magenta50: string;
export const magenta60: string;
export const magenta70: string;
export const magenta80: string;
export const magenta90: string;
export const orange: string;
export const orange10: string;
export const orange20: string;
export const orange30: string;
export const orange40: string;
export const orange50: string;
export const orange60: string;
export const orange70: string;
export const orange80: string;
export const orange90: string;
export const orange100: string;
export const purple: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
export const purple10: string;
export const purple100: string;
export const purple20: string;
export const purple30: string;
export const purple40: string;
export const purple50: string;
export const purple60: string;
export const purple70: string;
export const purple80: string;
export const purple90: string;
export const red: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
export const red10: string;
export const red100: string;
export const red20: string;
export const red30: string;
export const red40: string;
export const red50: string;
export const red60: string;
export const red70: string;
export const red80: string;
export const red90: string;
export const teal: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
export const teal10: string;
export const teal100: string;
export const teal20: string;
export const teal30: string;
export const teal40: string;
export const teal50: string;
export const teal60: string;
export const teal70: string;
export const teal80: string;
export const teal90: string;
export const warmGray: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
export const warmGray10: string;
export const warmGray100: string;
export const warmGray20: string;
export const warmGray30: string;
export const warmGray40: string;
export const warmGray50: string;
export const warmGray60: string;
export const warmGray70: string;
export const warmGray80: string;
export const warmGray90: string;
export const white: string;
export const white0: string;
export const yellow: string;
export const yellow10: string;
export const yellow100: string;
export const yellow20: string;
export const yellow30: string;
export const yellow40: string;
export const yellow50: string;
export const yellow60: string;
export const yellow70: string;
export const yellow80: string;
export const yellow90: string;
// hover colors
export const whiteHover: string;
export const blackHover: string;
export const yellow10Hover: string;
export const yellow20Hover: string;
export const yellow30Hover: string;
export const yellow40Hover: string;
export const yellow50Hover: string;
export const yellow60Hover: string;
export const yellow70Hover: string;
export const yellow80Hover: string;
export const yellow90Hover: string;
export const yellow100Hover: string;
export const yellowHover: {
'10': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
'100': string;
};
export const orange10Hover: string;
export const orange20Hover: string;
export const orange30Hover: string;
export const orange40Hover: string;
export const orange50Hover: string;
export const orange60Hover: string;
export const orange70Hover: string;
export const orange80Hover: string;
export const orange90Hover: string;
export const orange100Hover: string;
export const orangeHover: {
'10': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
'100': string;
};
export const red10Hover: string;
export const red20Hover: string;
export const red30Hover: string;
export const red40Hover: string;
export const red50Hover: string;
export const red60Hover: string;
export const red70Hover: string;
export const red80Hover: string;
export const red90Hover: string;
export const red100Hover: string;
export const redHover: {
'10': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
'100': string;
};
export const magenta10Hover: string;
export const magenta20Hover: string;
export const magenta30Hover: string;
export const magenta40Hover: string;
export const magenta50Hover: string;
export const magenta60Hover: string;
export const magenta70Hover: string;
export const magenta80Hover: string;
export const magenta90Hover: string;
export const magenta100Hover: string;
export const magentaHover: {
'10': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
'100': string;
};
export const purple10Hover: string;
export const purple20Hover: string;
export const purple30Hover: string;
export const purple40Hover: string;
export const purple50Hover: string;
export const purple60Hover: string;
export const purple70Hover: string;
export const purple80Hover: string;
export const purple90Hover: string;
export const purple100Hover: string;
export const purpleHover: {
'10': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
'100': string;
};
export const blue10Hover: string;
export const blue20Hover: string;
export const blue30Hover: string;
export const blue40Hover: string;
export const blue50Hover: string;
export const blue60Hover: string;
export const blue70Hover: string;
export const blue80Hover: string;
export const blue90Hover: string;
export const blue100Hover: string;
export const blueHover: {
'10': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
'100': string;
};
export const cyan10Hover: string;
export const cyan20Hover: string;
export const cyan30Hover: string;
export const cyan40Hover: string;
export const cyan50Hover: string;
export const cyan60Hover: string;
export const cyan70Hover: string;
export const cyan80Hover: string;
export const cyan90Hover: string;
export const cyan100Hover: string;
export const cyanHover: {
'10': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
'100': string;
};
export const teal10Hover: string;
export const teal20Hover: string;
export const teal30Hover: string;
export const teal40Hover: string;
export const teal50Hover: string;
export const teal60Hover: string;
export const teal70Hover: string;
export const teal80Hover: string;
export const teal90Hover: string;
export const teal100Hover: string;
export const tealHover: {
'10': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
'100': string;
};
export const green10Hover: string;
export const green20Hover: string;
export const green30Hover: string;
export const green40Hover: string;
export const green50Hover: string;
export const green60Hover: string;
export const green70Hover: string;
export const green80Hover: string;
export const green90Hover: string;
export const green100Hover: string;
export const greenHover: {
'10': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
'100': string;
};
export const coolGray10Hover: string;
export const coolGray20Hover: string;
export const coolGray30Hover: string;
export const coolGray40Hover: string;
export const coolGray50Hover: string;
export const coolGray60Hover: string;
export const coolGray70Hover: string;
export const coolGray80Hover: string;
export const coolGray90Hover: string;
export const coolGray100Hover: string;
export const coolGrayHover: {
'10': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
'100': string;
};
export const gray10Hover: string;
export const gray20Hover: string;
export const gray30Hover: string;
export const gray40Hover: string;
export const gray50Hover: string;
export const gray60Hover: string;
export const gray70Hover: string;
export const gray80Hover: string;
export const gray90Hover: string;
export const gray100Hover: string;
export const grayHover: {
'10': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
'100': string;
};
export const warmGray10Hover: string;
export const warmGray20Hover: string;
export const warmGray30Hover: string;
export const warmGray40Hover: string;
export const warmGray50Hover: string;
export const warmGray60Hover: string;
export const warmGray70Hover: string;
export const warmGray80Hover: string;
export const warmGray90Hover: string;
export const warmGray100Hover: string;
export const warmGrayHover: {
'10': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
'100': string;
};
export function rgba(hexcode: string, opacity: number): string;
export namespace rgba {
const prototype: {};
}
export const unstable_hoverColors: {
whiteHover: string;
blackHover: string;
blueHover: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
coolGrayHover: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
cyanHover: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
grayHover: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
greenHover: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
magentaHover: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
orangeHover: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
purpleHover: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
redHover: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
tealHover: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
warmGrayHover: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
yellowHover: {
'10': string;
'100': string;
'20': string;
'30': string;
'40': string;
'50': string;
'60': string;
'70': string;
'80': string;
'90': string;
};
}; | the_stack |
import * as path from 'path';
import { IProductionContext } from '../ProductionContext';
import { ISplitEntry } from '../module/SplitEntries';
import { CodeSplittingPhase } from '../phases/CodeSplittingPhase';
import { WarmupPhase } from '../phases/WarmupPhase';
import { createTestEnvironment, ITestEnvironment } from './testUtils';
describe('Code Splitting test', () => {
let environment: ITestEnvironment;
let cachedModule: ISplitEntry;
const getProductionContext = async (files: Record<string, string>): Promise<IProductionContext> => {
environment = await createTestEnvironment({ entry: 'index.ts' }, files);
const context = await environment.run([WarmupPhase, CodeSplittingPhase]);
return context;
};
/**
* Helper function to get the SplitEntry based on the original filename
* This is convenient cause orders of modules might change in the future.
* @param fileName
* @param entries
*/
const getSplitEntry = (fileName: string, entries: Array<ISplitEntry>): ISplitEntry => {
if (!!cachedModule && cachedModule.entry.absPath === path.join(environment.sourceDir + fileName)) {
return cachedModule;
}
cachedModule = undefined;
for (const entry of entries) {
const moduleFileName = entry.entry.absPath.replace(environment.sourceDir + path.sep, '');
if (fileName === moduleFileName) {
cachedModule = entry;
break;
}
}
return cachedModule;
};
// cleanup after each test
afterEach(() => {
if (environment) {
environment.cleanup();
environment = undefined;
}
cachedModule = undefined;
});
/**
* This test is to ensure we have a splitted module
* 'bar' is dynamically required, so we would have 1 splitEntry
*/
it('should have splitEntry', async () => {
const context = await getProductionContext({
'bar.ts': `
export default function() {}
`,
'foo.ts': `
export default function() {}
`,
'index.ts': `
import './foo';
async function load() {
const dynamicFunc = await import('./bar');
}
`,
});
const {
modules,
splitEntries: { entries },
} = context;
expect(modules).toHaveLength(3);
expect(entries).toHaveLength(1);
const barModule = getSplitEntry('bar.ts', entries);
expect(barModule.modules).toHaveLength(1);
expect(barModule.modules[0].publicPath).toContain('src/bar.ts');
expect(barModule.references).toHaveLength(1);
expect(barModule.references[0].module.publicPath).toContain('src/index.ts');
});
/**
* This test ensures we have a split entry
* and modules required by that entry should end up in the
* subModules of the splitted module
*/
it('should have splitEntry with submodules', async () => {
const context = await getProductionContext({
'bar.ts': `
import './foo';
export default function() {}
`,
'foo.ts': `
export default function() {}
`,
'index.ts': `
async function load() {
const dynamicFunc = await import('./bar');
}
`,
});
const {
modules,
splitEntries: { entries },
} = context;
expect(modules).toHaveLength(3);
expect(entries).toHaveLength(1);
const barModule = getSplitEntry('bar.ts', entries);
expect(barModule.modules).toHaveLength(2);
expect(barModule.modules[0].publicPath).toContain('src/bar.ts');
expect(barModule.modules[1].publicPath).toContain('src/foo.ts');
expect(barModule.references).toHaveLength(1);
expect(barModule.references[0].module.publicPath).toContain('src/index.ts');
});
/**
* In this test case, we have one dynamic import 'bar.ts'
*
* 1.
* index.ts AND bar.ts import the module './test'
* - 'test' should not be in bar.subModules
* 2.
* bar requires 'ignored.ts' but doesn't use it
* - 'ignored' should not be in bar.subModules
*/
it('should drop imported module thats required directly somewhere else', async () => {
const context = await getProductionContext({
'bar.ts': `
import { test } from './test';
import { ignored } from './ignored';
export default function() {};
console.log(test);
`,
'foo.ts': `
export function foo() {}
`,
'ignored.ts': `
export const ignored = 'this module is being ignored';
`,
'index.ts': `
import './foo';
import { test } from './test';
async function load() {
const dynamicFunc = await import('./bar');
}
console.log(test);
`,
'test.ts': `
export const test = 'test';
`,
});
const {
modules,
splitEntries: { entries },
} = context;
expect(modules).toHaveLength(4);
expect(entries).toHaveLength(1);
const barModule = getSplitEntry('bar.ts', entries);
expect(barModule.modules).toHaveLength(1);
expect(barModule.modules[0].publicPath).toContain('src/bar.ts');
});
/**
* In this test case we make sure we can have multiple
* splitEntries and each entry has it's own isolated submodules
*/
it('should have multiple splitEntries with submodules', async () => {
const context = await getProductionContext({
'bar.ts': `
import './foo';
export default function() {}
`,
'foo.ts': `
export default function() {}
`,
'index.ts': `
async function load() {
const bar = await import('./bar');
const oi = await import('./oi');
}
`,
'oi.ts': `
import './utils';
export default function() {}
`,
'utils.ts': `
export default function() {}
`,
});
const {
modules,
splitEntries: { entries },
} = context;
expect(modules).toHaveLength(5);
expect(entries).toHaveLength(2);
const barModule = getSplitEntry('bar.ts', entries);
expect(barModule.modules).toHaveLength(2);
expect(barModule.modules[0].publicPath).toContain('src/bar.ts');
expect(barModule.modules[1].publicPath).toContain('src/foo.ts');
expect(barModule.references).toHaveLength(1);
expect(barModule.references[0].module.publicPath).toContain('src/index.ts');
const oiModule = getSplitEntry('oi.ts', entries);
expect(oiModule.modules).toHaveLength(2);
expect(oiModule.modules[0].publicPath).toContain('src/oi.ts');
expect(oiModule.modules[1].publicPath).toContain('src/utils.ts');
expect(oiModule.references).toHaveLength(1);
expect(oiModule.references[0].module.publicPath).toContain('src/index.ts');
});
/**
* This test case will test that a module required by a splitted module
* but also required by a module outside of the split is being dropped
* from the subModules of the splitEntry
*/
it('should drop imported module thats required directly somewhere else', async () => {
const context = await getProductionContext({
'ai.ts': `
export const ai = 'ai';
`,
'bar.ts': `
import { oi } from './oi';
console.log(oi);
export default function() {};
`,
'foo.ts': `
export default function() {};
`,
'index.ts': `
import './foo';
import { oi } from './oi';
import { ai } from './ai';
async function load() {
const dynamicFunc = await import('./bar');
}
console.log(oi);
console.log(ai);
`,
'oi.ts': `
export const oi = 'oi!';
`,
});
const {
modules,
splitEntries: { entries },
} = context;
expect(modules).toHaveLength(5);
expect(entries).toHaveLength(1);
const barModule = getSplitEntry('bar.ts', entries);
expect(barModule.modules).toHaveLength(1);
expect(barModule.modules[0].publicPath).toContain('src/bar.ts');
});
/**
* Another test to test multiple split entries.
*/
it('should have multiple splitEntries with submodules', async () => {
const context = await getProductionContext({
'bar.ts': `
import './foo';
export default function() {}
`,
'foo.ts': `
async function load() {
const oi = await import('./oi');
}
export default function() {}
`,
'index.ts': `
async function load() {
const bar = await import('./bar');
}
`,
'oi.ts': `
import './utils';
export default function() {}
`,
'utils.ts': `
export default function() {}
`,
});
const {
modules,
splitEntries: { entries },
} = context;
expect(modules).toHaveLength(5);
expect(entries).toHaveLength(2);
const barModule = getSplitEntry('bar.ts', entries);
expect(barModule.modules).toHaveLength(2);
expect(barModule.modules[0].publicPath).toContain('src/bar.ts');
expect(barModule.modules[1].publicPath).toContain('src/foo.ts');
expect(barModule.references).toHaveLength(1);
expect(barModule.references[0].module.publicPath).toContain('src/index.ts');
const oiModule = getSplitEntry('oi.ts', entries);
expect(oiModule.modules).toHaveLength(2);
expect(oiModule.modules[0].publicPath).toContain('src/oi.ts');
expect(oiModule.modules[1].publicPath).toContain('src/utils.ts');
expect(oiModule.references).toHaveLength(1);
expect(oiModule.references[0].module.publicPath).toContain('src/foo.ts');
});
/**
* This is a test where we test that a dynamic imported module can ALSO
* dynamically import modules and those will have their own splitEntry
*/
it('should work with dynamic in dynamic in dynamic', async () => {
const context = await getProductionContext({
'bar.ts': `
console.log('empty');
`,
'entry1.ts': `
import('./one');
`,
'foo.ts': `
import './bar';
`,
'index.ts': `
import './entry1';
`,
'one.ts': `
import './foo';
import('./two');
`,
'three.ts': `
import './utils';
`,
'two.ts': `
import('./three');
import './bar';
`,
'utils.ts': `
console.log('empty');
`,
});
const {
modules,
splitEntries: { entries },
} = context;
expect(modules).toHaveLength(8);
expect(entries).toHaveLength(3);
// we're not splitting commons atm
const oneModule = getSplitEntry('one.ts', entries);
expect(oneModule.entry.publicPath).toContain('src/one.ts');
// expect(oneModule.modules).toHaveLength(3);
expect(oneModule.modules).toHaveLength(2);
const twoModule = getSplitEntry('two.ts', entries);
expect(twoModule.entry.publicPath).toContain('src/two.ts');
// expect(twoModule.modules).toHaveLength(2);
expect(twoModule.modules).toHaveLength(1);
const threeModule = getSplitEntry('three.ts', entries);
expect(threeModule.entry.publicPath).toContain('src/three.ts');
expect(threeModule.modules).toHaveLength(2);
expect(modules[7].isCommonsEligible).toBe(false);
// expect(modules[7].isCommonsEligible).toBe(true);
});
/**
* If a module is required from within different splitEntries and not outside
* of splittedModules it should be flagged as commons, so we can create
* another isolated splitted module
*
* This feature is disabled until further notice
*/
it('should NOT flag commons', async () => {
const context = await getProductionContext({
'bar.ts': `
import './utils';
import './foo';
export default function() {}
`,
'foo.ts': `
export default function() {}
`,
'index.ts': `
import './foo';
async function load() {
await import('./bar');
await import('./one');
}
`,
'one.ts': `
import './utils';
`,
'utils.ts': `
console.log('empty');
`,
});
const {
modules,
splitEntries: { entries },
} = context;
expect(modules).toHaveLength(5);
expect(entries).toHaveLength(2);
// utils.ts
expect(modules[2].isCommonsEligible).toBe(false);
// expect(modules[2].isCommonsEligible).toBe(true);
// foo.ts
expect(modules[4].isCommonsEligible).toBe(false);
});
/**
* If there's an circular dependency, we prevent entering
* a loop of death and prevent duplicate subModules
*/
it('should detect circular dependency', async () => {
const context = await getProductionContext({
'a.ts': `
import './b';
export default function() {};
`,
'b.ts': `
import './c';
`,
'c.ts': `
import './b';
`,
'index.ts': `
async function load() {
const dynamicFunc = await import('./a');
}
`,
});
const {
modules,
splitEntries: { entries },
} = context;
expect(modules).toHaveLength(4);
// we only have 1 split
expect(entries).toHaveLength(1);
// the split we have has 3 modules: a, b, c
expect(getSplitEntry('a.ts', entries).modules).toHaveLength(3);
});
/**
* This test is to ensure that a 'deep' circular dependency
* is resolved too.
*/
it('should detect deep circular dependency', async () => {
const context = await getProductionContext({
'a.ts': `
import './b';
export default function() {};
`,
'b.ts': `
import './c';
`,
'c.ts': `
import './d';
`,
'd.ts': `
import './e';
`,
'e.ts': `
import './f';
`,
'f.ts': `
import './g';
`,
'g.ts': `
import './b';
`,
'index.ts': `
async function load() {
const dynamicFunc = await import('./a');
}
`,
});
const {
modules,
splitEntries: { entries },
} = context;
expect(modules).toHaveLength(8);
// we only have 1 split
expect(entries).toHaveLength(1);
// the split we have has 7 modules: a, b, c, d, e, f, g
expect(getSplitEntry('a.ts', entries).modules).toHaveLength(7);
});
/**
* Another dynamic in dynamic test
*/
it('should detect dynamic in dynamic', async () => {
const context = await getProductionContext({
'entry1.ts': `
import('./one');
`,
'index.ts': `
import './entry1';
`,
'one.ts': `
import('./two');
`,
'three.ts': `
import './utils';
`,
'two.ts': `
import('./three');
`,
'utils.ts': `
console.log('emtpy');
`,
});
const {
modules,
splitEntries: { entries },
} = context;
expect(modules).toHaveLength(6);
expect(entries).toHaveLength(3);
expect(getSplitEntry('one.ts', entries).modules).toHaveLength(1);
expect(getSplitEntry('two.ts', entries).modules).toHaveLength(1);
expect(getSplitEntry('three.ts', entries).modules).toHaveLength(2);
});
/**
* A weird badly written code base shouldn't fail
*/
it('should handle funky setups', async () => {
const context = await getProductionContext({
'entry1.ts': `
import('./one');
import('./two');
`,
'foo.ts': `
import './utils';
`,
'index.ts': `
import './entry1';
`,
'one.ts': `
import './two';
import './utils';
`,
'three.ts': `
import './utils';
`,
'two.ts': `
import './foo';
`,
'utils.ts': `
console.log('emtpy');
`,
});
const {
modules,
splitEntries: { entries },
} = context;
// three.ts isn't required, so being dropped
expect(modules).toHaveLength(6);
// two is required normally, so shouldn't be a dynamic!
expect(entries).toHaveLength(1);
expect(getSplitEntry('one.ts', entries).modules).toHaveLength(1);
expect(getSplitEntry('two.ts', entries)).toBe(undefined);
});
/**
* We support all types of imports for modules in the splitEntry
* With this test we ensure that that works ;)
*/
it('should handle all type import types; require, import and export from', async () => {
const context = await getProductionContext({
'a.ts': `
console.log('emtpy');
`,
'b.ts': `
import './utils';
export const b = 'b';
`,
'c.ts': `
console.log('emtpy');
`,
'd.ts': `
import './two';
import './utils';
`,
'entry1.ts': `
import { c } from './c';
import('./d');
const a = require('./a');
export { b } from './b';
console.log(c);
console.log(a);
export default function() {};
`,
'index.ts': `
import a, { b } from './entry1';
console.log(a, b);
`,
'two.ts': `
console.log('emtpy');
`,
'utils.ts': `
console.log('emtpy');
`,
});
const {
modules,
splitEntries: { entries },
} = context;
// three.ts isn't required, so being dropped
expect(modules).toHaveLength(8);
expect(entries).toHaveLength(1);
expect(getSplitEntry('d.ts', entries).modules).toHaveLength(2);
});
/**
* We support circular dependencies without erroring
* We should also be able to support multiple circular dependencies
*/
it('should handle multiple circular dependencies', async () => {
const context = await getProductionContext({
'a.ts': `
import './b';
`,
'b.ts': `
import './c';
`,
'c.ts': `
import './b';
import './d';
`,
'd.ts': `
import './b';
`,
'index.ts': `
import('./a');
`,
});
const {
modules,
splitEntries: { entries },
} = context;
expect(modules).toHaveLength(5);
expect(entries).toHaveLength(1);
expect(getSplitEntry('a.ts', entries).modules).toHaveLength(4);
});
}); | the_stack |
import { Meteor } from 'meteor/meteor'
import { check } from '../../lib/check'
import { meteorPublish, AutoFillSelector } from './lib'
import { PubSub } from '../../lib/api/pubsub'
import { PeripheralDeviceReadAccess } from '../security/peripheralDevice'
import { PeripheralDevices, PeripheralDeviceId, PeripheralDevice } from '../../lib/collections/PeripheralDevices'
import { PeripheralDeviceCommands } from '../../lib/collections/PeripheralDeviceCommands'
import { MediaWorkFlowSteps } from '../../lib/collections/MediaWorkFlowSteps'
import { MediaWorkFlows } from '../../lib/collections/MediaWorkFlows'
import { OrganizationReadAccess } from '../security/organization'
import { StudioReadAccess } from '../security/studio'
import { FindOptions, UserId } from '../../lib/typings/meteor'
import { Credentials, ResolvedCredentials } from '../security/lib/credentials'
import { NoSecurityReadAccess } from '../security/noSecurity'
import { meteorCustomPublishArray } from '../lib/customPublication'
import {
getActiveRoutes,
getRoutedMappings,
MappingExt,
MappingsExt,
MappingsExtWithPackage,
routeExpectedPackages,
Studio,
StudioId,
StudioPackageContainer,
Studios,
} from '../../lib/collections/Studios'
import { setUpOptimizedObserver } from '../lib/optimizedObserver'
import {
ExpectedPackageDB,
ExpectedPackageId,
ExpectedPackages,
getPreviewPackageSettings,
getThumbnailPackageSettings,
} from '../../lib/collections/ExpectedPackages'
import _, { map } from 'underscore'
import {
ExpectedPackage,
PackageContainer,
Accessor,
PackageContainerOnPackage,
AccessorOnPackage,
} from '@sofie-automation/blueprints-integration'
import { DBRundownPlaylist, RundownPlaylist, RundownPlaylists } from '../../lib/collections/RundownPlaylists'
import { DBRundown, Rundowns } from '../../lib/collections/Rundowns'
import { clone, DBObj, literal, omit, protectString, unprotectObject, unprotectString } from '../../lib/lib'
import { PeripheralDeviceAPI } from '../../lib/api/peripheralDevice'
import { PlayoutDeviceSettings } from '../../lib/collections/PeripheralDeviceSettings/playoutDevice'
import deepExtend from 'deep-extend'
import { logger } from '../logging'
import { generateExpectedPackagesForPartInstance } from '../api/ingest/expectedPackages'
import { PartInstance } from '../../lib/collections/PartInstances'
/*
* This file contains publications for the peripheralDevices, such as playout-gateway, mos-gateway and package-manager
*/
function checkAccess(cred: Credentials | ResolvedCredentials, selector) {
if (!selector) throw new Meteor.Error(400, 'selector argument missing')
return (
NoSecurityReadAccess.any() ||
(selector._id && PeripheralDeviceReadAccess.peripheralDevice(selector, cred)) ||
(selector.organizationId && OrganizationReadAccess.organizationContent(selector, cred)) ||
(selector.studioId && StudioReadAccess.studioContent(selector, cred))
)
}
meteorPublish(PubSub.peripheralDevices, function (selector0, token) {
const { cred, selector } = AutoFillSelector.organizationId(this.userId, selector0, token)
if (checkAccess(cred, selector)) {
const modifier: FindOptions<PeripheralDevice> = {
fields: {
token: 0,
secretSettings: 0,
},
}
if (selector._id && token && modifier.fields) {
// in this case, send the secretSettings:
delete modifier.fields.secretSettings
}
return PeripheralDevices.find(selector, modifier)
}
return null
})
meteorPublish(PubSub.peripheralDevicesAndSubDevices, function (selector0, token) {
const { cred, selector } = AutoFillSelector.organizationId(this.userId, selector0, token)
if (checkAccess(cred, selector)) {
const parents = PeripheralDevices.find(selector).fetch()
const modifier: FindOptions<PeripheralDevice> = {
fields: {
token: 0,
secretSettings: 0,
},
}
const cursor = PeripheralDevices.find(
{
$or: [
{
parentDeviceId: { $in: parents.map((i) => i._id) },
},
selector,
],
},
modifier
)
return cursor
}
return null
})
meteorPublish(PubSub.peripheralDeviceCommands, function (deviceId: PeripheralDeviceId, token) {
if (!deviceId) throw new Meteor.Error(400, 'deviceId argument missing')
check(deviceId, String)
if (PeripheralDeviceReadAccess.peripheralDeviceContent({ deviceId: deviceId }, { userId: this.userId, token })) {
return PeripheralDeviceCommands.find({ deviceId: deviceId })
}
return null
})
meteorPublish(PubSub.mediaWorkFlows, function (selector0, token) {
const { cred, selector } = AutoFillSelector.deviceId(this.userId, selector0, token)
if (PeripheralDeviceReadAccess.peripheralDeviceContent(selector, cred)) {
return MediaWorkFlows.find(selector)
}
return null
})
meteorPublish(PubSub.mediaWorkFlowSteps, function (selector0, token) {
const { cred, selector } = AutoFillSelector.deviceId(this.userId, selector0, token)
if (PeripheralDeviceReadAccess.peripheralDeviceContent(selector, cred)) {
return MediaWorkFlowSteps.find(selector)
}
return null
})
meteorCustomPublishArray(
PubSub.expectedPackagesForDevice,
'deviceExpectedPackages',
function (
pub,
deviceId: PeripheralDeviceId,
filterPlayoutDeviceIds: PeripheralDeviceId[] | undefined,
token: string
) {
logger.info(`Pub.expectedPackagesForDevice: publication`)
if (
PeripheralDeviceReadAccess.peripheralDeviceContent({ deviceId: deviceId }, { userId: this.userId, token })
) {
let peripheralDevice = PeripheralDevices.findOne(deviceId)
if (!peripheralDevice) throw new Meteor.Error('PeripheralDevice "' + deviceId + '" not found')
const studioId = peripheralDevice.studioId
if (!studioId) {
logger.warn(`Pub.expectedPackagesForDevice: device "${peripheralDevice._id}" has no studioId`)
return this.ready()
}
const observer = setUpOptimizedObserver(
`pub_${PubSub.expectedPackagesForDevice}_${studioId}`,
(triggerUpdate) => {
// Set up observers:
return [
Studios.find(studioId, {
fields: {
mappingsHash: 1, // is changed when routes are changed
packageContainers: 1,
},
}).observe({
added: () => triggerUpdate({ studioId: studioId, invalidateStudio: true }),
changed: () => triggerUpdate({ studioId: studioId, invalidateStudio: true }),
removed: () => triggerUpdate({ studioId: null, invalidateStudio: true }),
}),
PeripheralDevices.find(
{ studioId: studioId },
{
fields: {
// Only monitor settings
settings: 1,
},
}
).observe({
added: () => triggerUpdate({ invalidatePeripheralDevices: true }),
changed: () => triggerUpdate({ invalidatePeripheralDevices: true }),
removed: () => triggerUpdate({ invalidatePeripheralDevices: true }),
}),
ExpectedPackages.find({
studioId: studioId,
}).observe({
added: () => triggerUpdate({ invalidateExpectedPackages: true }),
changed: () => triggerUpdate({ invalidateExpectedPackages: true }),
removed: () => triggerUpdate({ invalidateExpectedPackages: true }),
}),
RundownPlaylists.find(
{
studioId: studioId,
},
{
fields: {
// It should be enough to watch these fields for changes
_id: 1,
activationId: 1,
rehearsal: 1,
currentPartInstanceId: 1, // So that it invalidates when the current changes
nextPartInstanceId: 1, // So that it invalidates when the next changes
},
}
).observe({
added: () => triggerUpdate({ invalidateRundownPlaylist: true }),
changed: () => triggerUpdate({ invalidateRundownPlaylist: true }),
removed: () => triggerUpdate({ invalidateRundownPlaylist: true }),
}),
]
},
() => {
// Initialize data
return {
studioId: studioId,
deviceId: deviceId,
// All invalidate flags should be true, so that they run on first run:
invalidateStudio: true,
invalidatePeripheralDevices: true,
invalidateExpectedPackages: true,
invalidateRundownPlaylist: true,
studio: undefined,
expectedPackages: [],
routedExpectedPackages: [],
routedPlayoutExpectedPackages: [],
activePlaylist: undefined,
activeRundowns: [],
currentPartInstance: undefined,
nextPartInstance: undefined,
}
},
(context: {
// Input data:
studioId: StudioId | undefined
deviceId: PeripheralDeviceId
// Data invalidation flags:
invalidateStudio: boolean
invalidatePeripheralDevices: boolean
invalidateExpectedPackages: boolean
invalidateRundownPlaylist: boolean
// cache:
studio: Studio | undefined
expectedPackages: ExpectedPackageDB[]
routedExpectedPackages: ResultingExpectedPackage[]
/** ExpectedPackages relevant for playout */
routedPlayoutExpectedPackages: ResultingExpectedPackage[]
activePlaylist: DBRundownPlaylist | undefined
activeRundowns: DBRundown[]
currentPartInstance: PartInstance | undefined
nextPartInstance: PartInstance | undefined
}) => {
// Prepare data for publication:
let invalidateRoutedExpectedPackages = false
let invalidateRoutedPlayoutExpectedPackages = false
if (context.invalidateStudio) {
context.invalidateStudio = false
invalidateRoutedExpectedPackages = true
context.studio = Studios.findOne(context.studioId)
if (!context.studio) {
logger.warn(`Pub.expectedPackagesForDevice: studio "${context.studioId}" not found!`)
}
}
if (!context.studio) {
return []
}
if (context.invalidatePeripheralDevices) {
context.invalidatePeripheralDevices = false
invalidateRoutedExpectedPackages = true
invalidateRoutedPlayoutExpectedPackages = true
}
if (context.invalidateExpectedPackages) {
context.invalidateExpectedPackages = false
invalidateRoutedExpectedPackages = true
invalidateRoutedPlayoutExpectedPackages = true
context.expectedPackages = ExpectedPackages.find({
studioId: studioId,
}).fetch()
if (!context.expectedPackages.length) {
logger.info(
`Pub.expectedPackagesForDevice: no ExpectedPackages for studio "${context.studioId}" found`
)
}
}
if (context.invalidateRundownPlaylist) {
context.invalidateRundownPlaylist = false
const activePlaylist = RundownPlaylists.findOne({
studioId: studioId,
activationId: { $exists: true },
})
context.activePlaylist = activePlaylist
context.activeRundowns = context.activePlaylist
? Rundowns.find({
playlistId: context.activePlaylist._id,
}).fetch()
: []
const selectPartInstances = activePlaylist?.getSelectedPartInstances()
context.nextPartInstance = selectPartInstances?.nextPartInstance
context.currentPartInstance = selectPartInstances?.currentPartInstance
invalidateRoutedPlayoutExpectedPackages = true
}
const studio: Studio = context.studio
if (invalidateRoutedExpectedPackages) {
// Map the expectedPackages onto their specified layer:
const routedMappingsWithPackages = routeExpectedPackages(studio, context.expectedPackages)
if (context.expectedPackages.length && !Object.keys(routedMappingsWithPackages).length) {
logger.info(`Pub.expectedPackagesForDevice: routedMappingsWithPackages is empty`)
}
context.routedExpectedPackages = generateExpectedPackages(
context.studio,
filterPlayoutDeviceIds,
routedMappingsWithPackages,
Priorities.OTHER // low priority
)
}
if (invalidateRoutedPlayoutExpectedPackages) {
// Use the expectedPackages of the Current and Next Parts:
const playoutNextExpectedPackages: ExpectedPackageDB[] = context.nextPartInstance
? generateExpectedPackagesForPartInstance(
context.studio,
context.nextPartInstance.rundownId,
context.nextPartInstance
)
: []
const playoutCurrentExpectedPackages: ExpectedPackageDB[] = context.currentPartInstance
? generateExpectedPackagesForPartInstance(
context.studio,
context.currentPartInstance.rundownId,
context.currentPartInstance
)
: []
// Map the expectedPackages onto their specified layer:
const currentRoutedMappingsWithPackages = routeExpectedPackages(
studio,
playoutCurrentExpectedPackages
)
const nextRoutedMappingsWithPackages = routeExpectedPackages(
studio,
playoutNextExpectedPackages
)
if (
context.currentPartInstance &&
!Object.keys(currentRoutedMappingsWithPackages).length &&
!Object.keys(nextRoutedMappingsWithPackages).length
) {
logger.debug(
`Pub.expectedPackagesForDevice: Both currentRoutedMappingsWithPackages and nextRoutedMappingsWithPackages are empty`
)
}
// Filter, keep only the routed mappings for this device:
context.routedPlayoutExpectedPackages = [
...generateExpectedPackages(
context.studio,
filterPlayoutDeviceIds,
currentRoutedMappingsWithPackages,
Priorities.PLAYOUT_CURRENT
),
...generateExpectedPackages(
context.studio,
filterPlayoutDeviceIds,
nextRoutedMappingsWithPackages,
Priorities.PLAYOUT_NEXT
),
]
}
const packageContainers: { [containerId: string]: PackageContainer } = {}
for (const [containerId, studioPackageContainer] of Object.entries(studio.packageContainers)) {
packageContainers[containerId] = studioPackageContainer.container
}
const pubData = literal<DBObj[]>([
{
_id: protectString(`${deviceId}_expectedPackages`),
type: 'expected_packages',
studioId: studioId,
expectedPackages: context.routedExpectedPackages,
},
{
_id: protectString(`${deviceId}_playoutExpectedPackages`),
type: 'expected_packages',
studioId: studioId,
expectedPackages: context.routedPlayoutExpectedPackages,
},
{
_id: protectString(`${deviceId}_packageContainers`),
type: 'package_containers',
studioId: studioId,
packageContainers: packageContainers,
},
{
_id: protectString(`${deviceId}_rundownPlaylist`),
type: 'active_playlist',
studioId: studioId,
activeplaylist: context.activePlaylist
? {
_id: context.activePlaylist._id,
active: !!context.activePlaylist.activationId,
rehearsal: context.activePlaylist.rehearsal,
}
: undefined,
activeRundowns: context.activeRundowns.map((rundown) => {
return {
_id: rundown._id,
_rank: rundown._rank,
}
}),
},
])
return pubData
},
(newData) => {
pub.updatedDocs(newData)
},
500 // ms, wait this time before sending an update
)
pub.onStop(() => {
observer.stop()
})
} else {
logger.warn(`Pub.expectedPackagesForDevice: Not allowed: "${deviceId}"`)
}
}
)
interface ResultingExpectedPackage {
expectedPackage: ExpectedPackage.Base & { rundownId?: string }
/** Lower should be done first */
priority: number
sources: PackageContainerOnPackage[]
targets: PackageContainerOnPackage[]
playoutDeviceId: PeripheralDeviceId
}
enum Priorities {
// Lower priorities are done first
/** Highest priority */
PLAYOUT_CURRENT = 0,
/** Second-to-highest priority */
PLAYOUT_NEXT = 1,
OTHER = 9,
}
function generateExpectedPackages(
studio: Studio,
filterPlayoutDeviceIds: PeripheralDeviceId[] | undefined,
routedMappingsWithPackages: MappingsExtWithPackage,
priority: Priorities
) {
const routedExpectedPackages: ResultingExpectedPackage[] = []
for (const layerName of Object.keys(routedMappingsWithPackages)) {
const mapping = routedMappingsWithPackages[layerName]
// Filter, keep only the routed mappings for this device:
if (!filterPlayoutDeviceIds || filterPlayoutDeviceIds.includes(mapping.deviceId)) {
for (const expectedPackage of mapping.expectedPackages) {
// Lookup Package sources:
const combinedSources: PackageContainerOnPackage[] = []
for (const packageSource of expectedPackage.sources) {
const lookedUpSource = studio.packageContainers[packageSource.containerId]
if (lookedUpSource) {
// We're going to combine the accessor attributes set on the Package with the ones defined on the source
const combinedSource: PackageContainerOnPackage = {
...omit(clone(lookedUpSource.container), 'accessors'),
accessors: {},
containerId: packageSource.containerId,
}
/** Array of both the accessors of the expected package and the source */
const accessorIds = _.uniq(
Object.keys(lookedUpSource.container.accessors).concat(
Object.keys(packageSource.accessors || {})
)
)
for (const accessorId of accessorIds) {
const sourceAccessor: Accessor.Any | undefined =
lookedUpSource.container.accessors[accessorId]
const packageAccessor: AccessorOnPackage.Any | undefined =
packageSource.accessors?.[accessorId]
if (packageAccessor && sourceAccessor && packageAccessor.type === sourceAccessor.type) {
combinedSource.accessors[accessorId] = deepExtend({}, sourceAccessor, packageAccessor)
} else if (packageAccessor) {
combinedSource.accessors[accessorId] = clone<AccessorOnPackage.Any>(packageAccessor)
} else if (sourceAccessor) {
combinedSource.accessors[accessorId] = clone<Accessor.Any>(
sourceAccessor
) as AccessorOnPackage.Any
}
}
combinedSources.push(combinedSource)
} else {
logger.warn(
`Pub.expectedPackagesForDevice: Source package container "${packageSource.containerId}" not found`
)
}
}
// Lookup Package targets:
const mappingDeviceId = unprotectString(mapping.deviceId)
let packageContainerId: string | undefined
for (const [containerId, packageContainer] of Object.entries(studio.packageContainers)) {
if (packageContainer.deviceIds.includes(mappingDeviceId)) {
// TODO: how to handle if a device has multiple containers?
packageContainerId = containerId
break // just picking the first one found, for now
}
}
if (!packageContainerId) {
logger.warn(`Pub.expectedPackagesForDevice: No package container found for "${mappingDeviceId}"`)
}
const combinedTargets: PackageContainerOnPackage[] = []
if (packageContainerId) {
const lookedUpTarget = studio.packageContainers[packageContainerId]
if (lookedUpTarget) {
// Todo: should the be any combination of properties here?
combinedTargets.push({
...omit(clone(lookedUpTarget.container), 'accessors'),
accessors: lookedUpTarget.container.accessors as {
[accessorId: string]: AccessorOnPackage.Any
},
containerId: packageContainerId,
})
}
}
if (combinedSources.length) {
if (combinedTargets.length) {
expectedPackage.sideEffect = deepExtend(
{},
literal<ExpectedPackage.Base['sideEffect']>({
previewContainerId: studio.previewContainerIds[0], // just pick the first. Todo: something else?
thumbnailContainerId: studio.thumbnailContainerIds[0], // just pick the first. Todo: something else?
previewPackageSettings: getPreviewPackageSettings(
expectedPackage as ExpectedPackage.Any
),
thumbnailPackageSettings: getThumbnailPackageSettings(
expectedPackage as ExpectedPackage.Any
),
}),
expectedPackage.sideEffect
)
routedExpectedPackages.push({
expectedPackage: unprotectObject(expectedPackage),
sources: combinedSources,
targets: combinedTargets,
priority: priority,
playoutDeviceId: mapping.deviceId,
})
} else {
logger.warn(`Pub.expectedPackagesForDevice: No targets found for "${expectedPackage._id}"`)
}
} else {
logger.warn(`Pub.expectedPackagesForDevice: No sources found for "${expectedPackage._id}"`)
}
}
}
}
return routedExpectedPackages
} | the_stack |
import * as Delir from '@delirvfx/core'
import { operation } from '@fleur/fleur'
import archiver from 'archiver'
import { remote } from 'electron'
import glob from 'fast-glob'
import fs from 'fs-extra'
import _ from 'lodash'
import cloneDeep from 'lodash/cloneDeep'
import MsgPack from 'msgpack5'
import path from 'path'
import unzipper from 'unzipper'
import uuid from 'uuid'
import { SpreadType } from '../../utils/Spread'
import { HistoryGroup } from 'domain/History/HistoryGroup'
import { Command } from 'domain/History/HistoryStore'
import { ProjectActions } from 'domain/Project/actions'
import { AddClipCommand } from 'domain/Project/Commands/AddClipCommand'
import * as HistoryOps from '../History/operations'
import { migrateProject } from '../Project/models'
import * as ProjectOps from '../Project/operations'
import { getProject } from '../Project/selectors'
import RendererStore from '../Renderer/RendererStore'
import { EditorActions } from './actions'
import EditorStore from './EditorStore'
import { NotificationTimeouts } from './models'
import t from './operations.i18n'
import { getActiveComp, getClipboardEntry, getCurrentPreviewFrame, getSelectedClipIds } from './selectors'
import { ClipboardEntryClip, ParameterTarget } from './types'
export type DragEntity =
| { type: 'asset'; asset: Delir.Entity.Asset }
| { type: 'clip'; baseClipId: string }
| { type: 'clip-resizing'; clip: SpreadType<Delir.Entity.Clip> }
type ProjectPackAssetMap = Record<string, { fileName: string; tmpName: string }>
//
// App services
//
export const openPluginDirectory = operation(context => {
const userDir = remote.app.getPath('appData')
const pluginsDir = path.join(userDir, 'delir/plugins')
remote.shell.openItem(pluginsDir)
})
export const setActiveProject = operation(
async (context, payload: { project: Delir.Entity.Project; path?: string | null }) => {
const { project: activeProject } = context.getStore(EditorStore).getState()
const projectChanged = payload.project !== activeProject
if (!activeProject || projectChanged) {
context.dispatch(EditorActions.clearActiveProject, {})
}
context.dispatch(EditorActions.setActiveProject, {
project: payload.project,
path: payload.path,
})
if (projectChanged) {
await context.executeOperation(HistoryOps.clearHistory)
}
},
)
export const setDragEntity = operation((context, arg: { entity: DragEntity }) => {
context.dispatch(EditorActions.setDragEntity, arg.entity)
})
export const clearDragEntity = operation(context => {
context.dispatch(EditorActions.clearDragEntity, {})
})
export const notify = operation(
(
context,
arg: {
id?: string
message?: string
title?: string
level: 'info' | 'error'
timeout?: number
detail?: string
},
) => {
const id = arg.id || _.uniqueId('notify')
context.dispatch(EditorActions.addMessage, {
id,
title: arg.title,
message: arg.message,
detail: arg.detail,
level: arg.level || 'info',
timeout: arg.timeout,
})
},
)
export const removeNotification = operation((context, arg: { id: string }) => {
context.dispatch(EditorActions.removeMessage, { id: arg.id })
})
//
// Change active element
//
export const changeActiveComposition = operation((context, { compositionId }: { compositionId: string }) => {
context.dispatch(EditorActions.changeActiveComposition, {
compositionId,
})
})
export const changeActiveLayer = operation(({ dispatch }, layerId: string) => {
dispatch(EditorActions.changeActiveLayer, { layerId })
})
export const addOrRemoveSelectClip = operation((context, args: { clipIds: string[] }) => {
context.dispatch(EditorActions.addOrRemoveSelectClip, {
clipIds: args.clipIds,
})
})
export const changeSelectClip = operation((context, { clipIds }: { clipIds: string[] }) => {
context.dispatch(EditorActions.changeSelectClip, { clipIds })
})
export const changeActiveParam = operation((context, { target }: { target: ParameterTarget | null }) => {
context.dispatch(EditorActions.changeActiveParam, { target })
})
export const seekPreviewFrame = operation((context, { frame = undefined }: { frame?: number }) => {
const currentPreviewFrame = getCurrentPreviewFrame(context.getStore)
const activeComp = getActiveComp(context.getStore)
const { previewPlaying } = context.getStore(RendererStore)
if (!activeComp || previewPlaying) return
frame = _.isNumber(frame) ? frame : currentPreviewFrame
const overloadGuardedFrame = _.clamp(frame, 0, activeComp.durationFrames)
context.dispatch(EditorActions.seekPreviewFrame, {
frame: overloadGuardedFrame,
})
})
//
// Import & Export
//
export const newProject = operation(async context => {
await context.executeOperation(setActiveProject, {
project: new Delir.Entity.Project({}),
})
})
export const openProject = operation(async (context, { path }: { path: string }) => {
const projectMpk = await fs.readFile(path)
const projectJson = MsgPack().decode(projectMpk).project
const project = Delir.Exporter.deserializeProject(projectJson)
const migrated = migrateProject(Delir.ProjectMigrator.migrate(project))
await context.executeOperation(setActiveProject, {
project: migrated,
path,
})
})
export const saveProject = operation(
async (
context,
{ path, silent = false, keepPath = false }: { path: string; silent?: boolean; keepPath?: boolean },
) => {
const project = context.getStore(EditorStore).getState().project
if (!project) return
await fs.writeFile(
path,
(MsgPack().encode({
project: Delir.Exporter.serializeProject(project),
}) as any) as Buffer,
)
let newPath: string | null = path
if (keepPath) {
newPath = context.getStore(EditorStore).getState().projectPath
}
context.executeOperation(setActiveProject, { project, path: newPath }) // update path
!silent &&
(await context.executeOperation(notify, {
message: t(t.k.saved),
title: '',
level: 'info',
timeout: 1000,
}))
},
)
export const autoSaveProject = operation(async context => {
const { project, projectPath } = context.getStore(EditorStore).getState()
const isInRendering = context.getStore(RendererStore).isInRendering()
if (isInRendering) return
if (!project || !projectPath) {
context.executeOperation(notify, {
message: t(t.k.letsSave),
title: '',
level: 'info',
timeout: NotificationTimeouts.verbose,
})
return
}
const frag = path.parse(projectPath)
const autoSaveFileName = `${frag.name}.auto-saved${frag.ext}`
const autoSavePath = path.join(frag.dir, autoSaveFileName)
await context.executeOperation(saveProject, {
path: autoSavePath,
silent: true,
keepPath: true,
})
context.executeOperation(notify, {
message: t(t.k.autoSaved, { fileName: autoSaveFileName }),
title: '',
level: 'info',
timeout: NotificationTimeouts.verbose,
})
})
export const exportProjectPack = operation(async ({ getStore, executeOperation }, { dist }: { dist: string }) => {
const project = cloneDeep(getProject(getStore)) as Delir.Entity.Project | null
if (!project) return
await executeOperation(notify, {
level: 'info',
timeout: NotificationTimeouts.verbose,
message: t(t.k.packageExporting),
})
const tmpDir = path.join(remote.app.getPath('temp'), `delirpp-export-${uuid.v4()}`)
const fileNames = new Set()
const assetMap: ProjectPackAssetMap = {}
await fs.mkdirp(tmpDir)
await Promise.all(
(project.assets as Delir.Entity.Asset[]).map(async asset => {
const assetPath = /^file:\/\/(.*)$/.exec(asset.path)?.[1]
if (!assetPath) return
const sourceFileName = path.basename(assetPath)
let distFileName: string = sourceFileName
{
let idx = 0
while (true) {
if (!fileNames.has(distFileName)) break
idx++
const { name, ext } = path.parse(sourceFileName)
distFileName = `${name} (${idx})${ext}`
}
}
fileNames.add(distFileName)
const ext = path.extname(assetPath)
const tmpName = `${uuid.v4()}${ext}`
assetMap[asset.id] = { fileName: distFileName, tmpName }
asset.patch({ path: `file:///__DELIR_TEMPORARY_/${tmpName}` })
await fs.copyFile(assetPath, path.join(tmpDir, tmpName))
}),
)
await fs.writeFile(
path.join(tmpDir, 'project.msgpack'),
(MsgPack().encode({
project: Delir.Exporter.serializeProject(project),
assets: assetMap,
}) as any) as Buffer,
)
const archive = archiver('zip', { zlib: { level: 9 } })
archive.pipe(fs.createWriteStream(dist))
archive.directory(tmpDir, false)
await archive.finalize()
await executeOperation(notify, {
level: 'info',
timeout: NotificationTimeouts.verbose,
message: t(t.k.packageExportCompleted),
})
})
export const importProjectPack = operation(
async ({ executeOperation }, { src, dist: distDir }: { src: string; dist: string }) => {
const tmpDir = path.join(remote.app.getPath('temp'), `delirpp-import-${uuid.v4()}`)
await fs.mkdirp(tmpDir)
await new Promise(resolve => {
fs.createReadStream(src)
.pipe(unzipper.Extract({ path: tmpDir }))
.once('close', resolve)
})
const msgpack = MsgPack()
const packProjectPath = path.join(tmpDir, 'project.msgpack')
const { project: rawProject, assets } = msgpack.decode(await fs.readFile(packProjectPath))
const project = Delir.Exporter.deserializeProject(rawProject)
// Restore asset paths
await Promise.all(
Object.entries(assets as ProjectPackAssetMap).map(async ([id, { fileName, tmpName }]) => {
const asset = project.findAsset(id)!
await fs.rename(path.join(tmpDir, tmpName), path.join(tmpDir, fileName))
asset.patch({ path: 'file://' + path.join(/* Target to finalized dir */ distDir, fileName) })
}),
)
// Save project to .delir
const packFileName = path.parse(src).name
const tmpProjectPath = path.join(tmpDir, `${packFileName}.delir`)
await fs.writeFile(
tmpProjectPath,
msgpack.encode({
project: Delir.Exporter.serializeProject(project),
}),
)
// Finalize
await fs.remove(packProjectPath)
const files = await glob(`**`, { cwd: tmpDir, absolute: true })
await Promise.all(
files.map(async file => {
const distName = path.relative(tmpDir, file)
await fs.move(file, path.join(distDir, distName))
}),
)
const projectPath = path.join(distDir, `${packFileName}.delir`)
await executeOperation(setActiveProject, { project, path: projectPath })
},
)
export const changePreferenceOpenState = operation((context, { open }: { open: boolean }) => {
context.dispatch(EditorActions.changePreferenceOpenState, {
open,
})
})
//
// Internal clipboard
//
export const copyClips = operation(({ getStore, dispatch }) => {
const clipIds = getSelectedClipIds(getStore)
const comp = getActiveComp(getStore)!
const firstLayerIndexOfSelection = comp.layers.findIndex(layer => !!layer.findClip(clipIds[0]))
const entities: ClipboardEntryClip['entities'] = []
let offset = 0
for (let idx = firstLayerIndexOfSelection; idx < comp.layers.length; idx++) {
const layer = comp.layers[idx]
// find clips in current layer
const containedClips = clipIds
.map(clipId => layer.findClip(clipId))
.filter((clip): clip is Delir.Entity.Clip => !!clip)
entities[offset] = { offset, clips: containedClips }
offset++
}
dispatch(EditorActions.setClipboardEntry, {
entry: { type: 'clip', entities },
})
})
export const cutClips = operation(({ executeOperation, getStore }) => {
executeOperation(copyClips)
executeOperation(ProjectOps.removeClips, { clipIds: getSelectedClipIds(getStore) })
})
export const pasteClipIntoLayer = operation(async (context, { layerId }: { layerId: string }) => {
const entry = getClipboardEntry(context.getStore)
if (!entry || entry.type !== 'clip') return
const { entities } = entry
const project = getProject(context.getStore)!
const placedFrame = getCurrentPreviewFrame(context.getStore)
const composition = project.findLayerOwnerComposition(layerId)!
const firstLayerIdxOfEntity = composition.layers.findIndex(layer => layer.id === layerId)
const headClipPlacedFrame = entities
.flatMap(({ clips }) => clips)
.reduce((headPlacedFrame: number, next) => Math.min(headPlacedFrame, next.placedFrame), Infinity)
const commands: Command[] = []
for (const { offset, clips } of entities) {
const layer = composition.layers[Math.min(firstLayerIdxOfEntity + offset, composition.layers.length - 1)]
for (const sourceClip of clips) {
const clip = sourceClip.clone()
clip.patch({
placedFrame: sourceClip.placedFrame - headClipPlacedFrame + placedFrame,
})
context.dispatch(ProjectActions.addClip, {
targetLayerId: layer.id,
newClip: clip,
})
commands.push(new AddClipCommand(composition.id, layer.id, clip))
}
}
await context.executeOperation(HistoryOps.pushHistory, {
command: new HistoryGroup(commands),
})
await context.executeOperation(seekPreviewFrame, {})
}) | the_stack |
import * as DataTableModel from 'app/client/models/DataTableModel';
import {DocModel} from 'app/client/models/DocModel';
import {BaseFilteredRowSource, RowId, RowList, RowSource} from 'app/client/models/rowset';
import {TableData} from 'app/client/models/TableData';
import {ActiveDocAPI, ClientQuery, QueryOperation} from 'app/common/ActiveDocAPI';
import {CellValue, TableDataAction} from 'app/common/DocActions';
import {DocData} from 'app/common/DocData';
import {nativeCompare} from 'app/common/gutil';
import {IRefCountSub, RefCountMap} from 'app/common/RefCountMap';
import {TableData as BaseTableData} from 'app/common/TableData';
import {RowFilterFunc} from 'app/common/RowFilterFunc';
import {tbind} from 'app/common/tbind';
import {Disposable, Holder, IDisposableOwnerT} from 'grainjs';
import * as ko from 'knockout';
import debounce = require('lodash/debounce');
import {isList} from "app/common/gristTypes";
import {decodeObject} from "app/plugin/objtypes";
// Limit on the how many rows to request for OnDemand tables.
const ON_DEMAND_ROW_LIMIT = 10000;
// Copied from app/server/lib/DocStorage.js. Actually could be 999, we are just playing it safe.
const MAX_SQL_PARAMS = 500;
/**
* A representation of a Query that uses tableRef/colRefs (i.e. metadata rowIds) to remain stable
* across table/column renames.
*/
export interface QueryRefs {
tableRef: number;
filterTuples: Array<FilterTuple>;
}
type ColRef = number | 'id';
type FilterTuple = [ColRef, QueryOperation, any[]];
/**
* QuerySetManager keeps track of all queries for a GristDoc instance. It is also responsible for
* disposing all state associated with queries when a GristDoc is disposed.
*
* Note that queries are made using tableId + colIds, which is a more suitable interface for a
* (future) public API, and easier to interact with DocData/TableData. However, it creates
* problems when tables or columns are renamed or deleted.
*
* To handle renames, we keep track of queries using their QueryRef representation, using
* tableRef/colRefs, i.e. metadata rowIds that aren't affected by renames.
*
* To handle deletes, we subscribe to isDeleted() observables of the needed tables and columns,
* and purge the query from QuerySetManager if any isDeleted() flag becomes true.
*/
export class QuerySetManager extends Disposable {
private _queryMap: RefCountMap<string, QuerySet>;
constructor(private _docModel: DocModel, docComm: ActiveDocAPI) {
super();
this._queryMap = this.autoDispose(new RefCountMap<string, QuerySet>({
create: (query: string) => QuerySet.create(null, _docModel, docComm, query, this),
dispose: (query: string, querySet: QuerySet) => querySet.dispose(),
gracePeriodMs: 60000, // Dispose after a minute of disuse.
}));
}
public useQuerySet(owner: IDisposableOwnerT<IRefCountSub<QuerySet>>, query: ClientQuery): QuerySet {
// Convert the query to a string key which identifies it.
const queryKey: string = encodeQuery(convertQueryToRefs(this._docModel, query));
// Look up or create the query in the RefCountMap. The returned object is a RefCountSub
// subscription, which decrements reference count when disposed.
const querySetRefCount = this._queryMap.use(queryKey);
// The passed-in owner is what will dispose this subscription (decrement reference count).
owner.autoDispose(querySetRefCount);
return querySetRefCount.get();
}
public purgeKey(queryKey: string) {
this._queryMap.purgeKey(queryKey);
}
// For testing: set gracePeriodMs, returning the previous value.
public testSetGracePeriodMs(ms: number): number {
return this._queryMap.testSetGracePeriodMs(ms);
}
}
/**
* DynamicQuerySet wraps one QuerySet, and allows changing it on the fly. It serves as a
* RowSource.
*/
export class DynamicQuerySet extends RowSource {
// Holds a reference to the currently active QuerySet.
private _holder = Holder.create<IRefCountSub<QuerySet>>(this);
// Shortcut to _holder.get().get().
private _querySet?: QuerySet;
// We could switch between several different queries quickly. If several queries are done
// fetching at the same time (e.g. were already ready), debounce lets us only update the
// query-set once to the last query.
private _updateQuerySetDebounced = debounce(tbind(this._updateQuerySet, this), 0);
constructor(private _querySetManager: QuerySetManager, private _tableModel: DataTableModel) {
super();
}
public getAllRows(): RowList {
return this._querySet ? this._querySet.getAllRows() : [];
}
public getNumRows(): number {
return this._querySet ? this._querySet.getNumRows() : 0;
}
/**
* Tells whether the query's result got truncated, i.e. not all rows are included.
*/
public get isTruncated(): boolean {
return this._querySet ? this._querySet.isTruncated : false;
}
/**
* Replace the query represented by this DynamicQuerySet. If multiple makeQuery() calls are made
* quickly (while waiting for the server), cb() may only be called for the latest one.
*
* If there is an error fetching data, cb(err) will be called with that error. The second
* argument to cb() is true if any data was changed, and false if not. Note that for a series of
* makeQuery() calls, cb() is always called at least once, and always asynchronously.
*/
public makeQuery(filters: {[colId: string]: any[]},
operations: {[colId: string]: QueryOperation},
cb: (err: Error|null, changed: boolean) => void): void {
const query: ClientQuery = {tableId: this._tableModel.tableData.tableId, filters, operations};
const newQuerySet = this._querySetManager.useQuerySet(this._holder, query);
// CB should be called asynchronously, since surprising hard-to-debug interactions can happen
// if it's sometimes synchronous and sometimes not.
newQuerySet.fetchPromise.then(() => {
this._updateQuerySetDebounced(newQuerySet, cb);
})
.catch((err) => { cb(err, false); });
}
private _updateQuerySet(nextQuerySet: QuerySet, cb: (err: Error|null, changed: boolean) => void): void {
try {
if (nextQuerySet !== this._querySet) {
const oldQuerySet = this._querySet;
this._querySet = nextQuerySet;
if (oldQuerySet) {
this.stopListening(oldQuerySet, 'rowChange');
this.stopListening(oldQuerySet, 'rowNotify');
this.trigger('rowChange', 'remove', oldQuerySet.getAllRows());
}
this.trigger('rowChange', 'add', this._querySet.getAllRows());
this.listenTo(this._querySet, 'rowNotify', tbind(this.trigger, this, 'rowNotify'));
this.listenTo(this._querySet, 'rowChange', tbind(this.trigger, this, 'rowChange'));
}
cb(null, true);
} catch (err) {
cb(err, true);
}
}
}
/**
* Class representing a query, which knows how to fetch the data, an presents a RowSource with
* matching rows. It uses new Comm calls for onDemand tables, but for regular tables, fetching
* data uses the good old tableModel.fetch(). In in most cases the data is already available, so
* this class is little more than a FilteredRowSource.
*/
export class QuerySet extends BaseFilteredRowSource {
// A publicly exposed promise, which may be waited on in order to know that the data has
// arrived. Until then, the RowSource underlying this QuerySet is empty.
public readonly fetchPromise: Promise<void>;
// Whether the fetched result is considered incomplete, i.e. not all rows were fetched.
public isTruncated: boolean;
constructor(docModel: DocModel, docComm: ActiveDocAPI, queryKey: string, qsm: QuerySetManager) {
const queryRefs: QueryRefs = decodeQuery(queryKey);
const query: ClientQuery = convertQueryFromRefs(docModel, queryRefs);
super(getFilterFunc(docModel.docData, query));
this.isTruncated = false;
// When table or any needed columns are deleted, purge this QuerySet from the map.
const isInvalid = this.autoDispose(makeQueryInvalidComputed(docModel, queryRefs));
this.autoDispose(isInvalid.subscribe((invalid) => {
if (invalid) { qsm.purgeKey(queryKey); }
}));
// Find the relevant DataTableModel.
const tableModel = docModel.dataTables[query.tableId];
// The number of values across all filters is limited to MAX_SQL_PARAMS. Normally a query has
// a single filter column, but in case there are multiple we divide the limit across all
// columns. It's OK to modify the query in place, since this modified version is not used
// elsewhere.
// (It might be better to limit this in DocStorage.js, but by limiting here, it's easier to
// know when to set isTruncated flag, to inform the user that data is incomplete.)
const colIds = Object.keys(query.filters);
if (colIds.length > 0) {
const maxParams = Math.floor(MAX_SQL_PARAMS / colIds.length);
for (const c of colIds) {
const values = query.filters[c];
if (values.length > maxParams) {
query.filters[c] = values.slice(0, maxParams);
this.isTruncated = true;
}
}
}
let fetchPromise: Promise<void>;
if (tableModel.tableMetaRow.onDemand()) {
const tableQS = tableModel.tableQuerySets;
fetchPromise = docComm.useQuerySet({limit: ON_DEMAND_ROW_LIMIT, ...query}).then((data) => {
// We assume that if we fetched the max number of rows, that there are likely more and the
// result should be reported as truncated.
// TODO: Better to fetch ON_DEMAND_ROW_LIMIT + 1 and omit one of them, so that isTruncated
// is only set if the row limit really was exceeded.
const rowIds = data.tableData[2];
if (rowIds.length >= ON_DEMAND_ROW_LIMIT) {
this.isTruncated = true;
}
this.onDispose(() => {
docComm.disposeQuerySet(data.querySubId).catch((err) => {
// tslint:disable-next-line:no-console
console.log(`Promise rejected for disposeQuerySet: ${err.message}`);
});
tableQS.removeQuerySet(this);
});
tableQS.addQuerySet(this, data.tableData);
});
} else {
// For regular (small), we fetch in bulk (and do nothing if already fetched).
fetchPromise = tableModel.fetch(false);
}
// This is a FilteredRowSource; subscribe it to the underlying data once the fetch resolves.
this.fetchPromise = fetchPromise.then(() => this.subscribeTo(tableModel));
}
}
/**
* Helper for use in a DataTableModel to maintain all QuerySets.
*/
export class TableQuerySets {
private _querySets: Set<QuerySet> = new Set();
constructor(private _tableData: TableData) {}
public addQuerySet(querySet: QuerySet, data: TableDataAction): void {
this._querySets.add(querySet);
this._tableData.loadPartial(data);
}
// Returns a Set of unused RowIds from querySet.
public removeQuerySet(querySet: QuerySet): void {
this._querySets.delete(querySet);
// Figure out which rows are not used by any other QuerySet in this DataTableModel.
const unusedRowIds = new Set(querySet.getAllRows());
for (const qs of this._querySets) {
for (const rowId of qs.getAllRows()) {
unusedRowIds.delete(rowId);
}
}
this._tableData.unloadPartial(Array.from(unusedRowIds) as number[]);
}
}
/**
* Returns a filtering function which tells whether a row matches the given query.
*/
export function getFilterFunc(docData: DocData, query: ClientQuery): RowFilterFunc<RowId> {
// NOTE we rely without checking on tableId and colIds being valid.
const tableData: BaseTableData = docData.getTable(query.tableId)!;
const colFuncs = Object.keys(query.filters).sort().map(
(colId) => {
const getter = tableData.getRowPropFunc(colId)!;
const values = new Set(query.filters[colId]);
switch (query.operations![colId]) {
case "intersects":
return (rowId: RowId) => {
const value = getter(rowId) as CellValue;
return isList(value) &&
(decodeObject(value) as unknown[]).some(v => values.has(v));
};
case "in":
return (rowId: RowId) => values.has(getter(rowId));
default:
throw new Error("Unknown operation");
}
});
return (rowId: RowId) => colFuncs.every(f => f(rowId));
}
/**
* Helper that converts a Query (with tableId/colIds) to an object with tableRef/colRefs (i.e.
* rowIds), and consistently sorted. We use that to identify a Query across table/column renames.
*/
function convertQueryToRefs(docModel: DocModel, query: ClientQuery): QueryRefs {
const tableRec: any = docModel.dataTables[query.tableId].tableMetaRow;
const colRefsByColId: {[colId: string]: ColRef} = {id: 'id'};
for (const col of tableRec.columns.peek().peek()) {
colRefsByColId[col.colId.peek()] = col.getRowId();
}
const filterTuples = Object.keys(query.filters).map((colId) => {
const values = query.filters[colId];
// Keep filter values sorted by value, for consistency.
values.sort(nativeCompare);
return [colRefsByColId[colId], query.operations![colId], values] as FilterTuple;
});
// Keep filters sorted by colRef, for consistency.
filterTuples.sort((a, b) =>
nativeCompare(a[0], b[0]) || nativeCompare(a[1], b[1]));
return {tableRef: tableRec.getRowId(), filterTuples};
}
/**
* Helper to convert a QueryRefs (using tableRef/colRefs) object back to a Query (using
* tableId/colIds).
*/
function convertQueryFromRefs(docModel: DocModel, queryRefs: QueryRefs): ClientQuery {
const tableRec = docModel.dataTablesByRef.get(queryRefs.tableRef)!.tableMetaRow;
const filters: {[colId: string]: any[]} = {};
const operations: {[colId: string]: QueryOperation} = {};
for (const [colRef, operation, values] of queryRefs.filterTuples) {
const colId = colRef === 'id' ? 'id' : docModel.columns.getRowModel(colRef).colId.peek();
filters[colId] = values;
operations[colId] = operation;
}
return {tableId: tableRec.tableId.peek(), filters, operations};
}
/**
* Encodes a query (converted to QueryRefs using convertQueryToRefs()) as a string, to be usable
* as a key into a map.
*
* It uses JSON.stringify, but avoids objects since their order of keys in serialization is not
* guaranteed. This is important to produce consistent results (same query => same encoding).
*/
function encodeQuery(queryRefs: QueryRefs): string {
return JSON.stringify([queryRefs.tableRef, queryRefs.filterTuples]);
}
// Decode an encoded QueryRefs.
function decodeQuery(queryKey: string): QueryRefs {
const [tableRef, filterTuples] = JSON.parse(queryKey);
return {tableRef, filterTuples};
}
/**
* Returns a ko.computed() which turns to true when the table or any of the columns needed by the
* given query are deleted.
*/
function makeQueryInvalidComputed(docModel: DocModel, queryRefs: QueryRefs): ko.Computed<boolean> {
const tableFlag: ko.Observable<boolean> = docModel.tables.getRowModel(queryRefs.tableRef)._isDeleted;
const colFlags: Array<ko.Observable<boolean> | null> = queryRefs.filterTuples.map(
([colRef, , ]) => colRef === 'id' ? null : docModel.columns.getRowModel(colRef)._isDeleted);
return ko.computed(() => Boolean(tableFlag() || colFlags.some((c) => c?.())));
} | the_stack |
import { is, List, Repeat } from 'immutable'
import React from 'react'
import { connect } from 'react-redux'
import { match, Redirect, Route } from 'react-router-dom'
import { goBack, replace } from 'react-router-redux'
import { Dispatch } from 'redux'
import { StageConfig, StageDifficulty, State, TankRecord } from '../types/index'
import { defaultBotsConfig, MapItem, MapItemType, StageConfigConverter } from '../types/StageConfig'
import * as actions from '../utils/actions'
import { add, dec, inc } from '../utils/common'
import { BLOCK_SIZE as B, FIELD_BLOCK_SIZE as FBZ, ZOOM_LEVEL } from '../utils/constants'
import AreaButton from './AreaButton'
import BrickWall from './BrickWall'
import Eagle from './Eagle'
import Forest from './Forest'
import Grid from './Grid'
import PopupProvider, { PopupHandle } from './PopupProvider'
import River from './River'
import Screen from './Screen'
import Snow from './Snow'
import StagePreview from './StagePreview'
import SteelWall from './SteelWall'
import { Tank } from './tanks'
import Text from './Text'
import TextButton from './TextButton'
import TextInput from './TextInput'
const HexBrickWall = ({ x, y, hex }: { x: number; y: number; hex: number }) => (
<g className="hex-brick-wall">
{[[0b0001, 0, 0], [0b0010, 8, 0], [0b0100, 0, 8], [0b1000, 8, 8]].map(
([mask, dx, dy], index) => (
<g
key={index}
style={{ opacity: hex & mask ? 1 : 0.3 }}
transform={`translate(${dx},${dy})`}
>
<BrickWall x={x} y={y} />
<BrickWall x={x + 4} y={y} />
<BrickWall x={x} y={y + 4} />
<BrickWall x={x + 4} y={y + 4} />
</g>
),
)}
</g>
)
const HexSteelWall = ({ x, y, hex }: { x: number; y: number; hex: number }) => (
<g className="hex-steel-wall">
<g style={{ opacity: hex & 0b0001 ? 1 : 0.3 }}>
<SteelWall x={x} y={y} />
</g>
<g style={{ opacity: hex & 0b0010 ? 1 : 0.3 }}>
<SteelWall x={x + 8} y={y} />
</g>
<g style={{ opacity: hex & 0b0100 ? 1 : 0.3 }}>
<SteelWall x={x} y={y + 8} />
</g>
<g style={{ opacity: hex & 0b1000 ? 1 : 0.3 }}>
<SteelWall x={x + 8} y={y + 8} />
</g>
</g>
)
const positionMap = {
X: B,
B: 2.5 * B,
T: 4 * B,
R: 5.5 * B,
S: 7 * B,
F: 8.5 * B,
E: 10 * B,
}
export interface EditorProps {
view: string
dispatch: Dispatch
initialCotnent: StageConfig
stages: List<StageConfig>
popupHandle: PopupHandle
}
class Editor extends React.Component<EditorProps> {
private svg: SVGSVGElement
private pressed = false
state = {
t: -1,
name: '',
difficulty: 1 as StageDifficulty,
bots: defaultBotsConfig,
itemList: Repeat(new MapItem(), FBZ ** 2).toList(),
itemType: 'X' as MapItemType,
brickHex: 0xf,
steelHex: 0xf,
}
componentDidMount() {
// custom 在这里不需要取出来,因为 custom 永远为 true
const { name, difficulty, itemList, bots } = StageConfigConverter.s2e(this.props.initialCotnent)
this.setState({ name, difficulty, itemList, bots: bots })
}
getT(event: React.MouseEvent<SVGSVGElement>) {
let totalTop = 0
let totalLeft = 0
let node: Element = this.svg
while (node) {
totalTop += node.scrollTop + node.clientTop
totalLeft += node.scrollLeft + node.clientLeft
node = node.parentElement
}
const row = Math.floor((event.clientY + totalTop - this.svg.clientTop) / ZOOM_LEVEL / B)
const col = Math.floor((event.clientX + totalLeft - this.svg.clientLeft) / ZOOM_LEVEL / B)
if (row >= 0 && row < FBZ && col >= 0 && col < FBZ) {
return row * FBZ + col
} else {
return -1
}
}
getCurrentItem() {
const { itemType, brickHex, steelHex } = this.state
if (itemType === 'B') {
return new MapItem({ type: 'B', hex: brickHex })
} else if (itemType === 'T') {
return new MapItem({ type: 'T', hex: steelHex })
} else {
return new MapItem({ type: itemType })
}
}
setAsCurrentItem(t: number) {
const { itemList } = this.state
const item = this.getCurrentItem()
if (t == -1 || is(itemList.get(t), item)) {
return
}
if (item.type === 'E') {
// 先将已存在的eagle移除 保证Eagle最多出现一次
const eagleRemoved = itemList.map(item => (item.type === 'E' ? new MapItem() : item))
this.setState({ itemList: eagleRemoved.set(t, item) })
} else {
this.setState({ itemList: itemList.set(t, item) })
}
}
onMouseDown = (event: React.MouseEvent<SVGSVGElement>) => {
const {
view,
popupHandle: { popup },
} = this.props
if (view === 'map' && popup == null && this.getT(event) !== -1) {
this.pressed = true
}
}
onMouseMove = (event: React.MouseEvent<SVGSVGElement>) => {
const {
view,
popupHandle: { popup },
} = this.props
const { t: lastT } = this.state
const t = this.getT(event)
if (t !== lastT) {
this.setState({ t })
}
if (view === 'map' && popup == null && this.pressed) {
this.setAsCurrentItem(t)
}
}
onMouseUp = (event: React.MouseEvent<SVGSVGElement>) => {
const {
view,
popupHandle: { popup },
} = this.props
this.pressed = false
if (view === 'map' && popup == null) {
this.setAsCurrentItem(this.getT(event))
}
}
onMouseLeave = () => {
this.pressed = false
this.setState({ t: -1 })
}
onIncDifficulty = () => {
const { difficulty } = this.state
this.setState({ difficulty: difficulty + 1 })
}
onDecDifficulty = () => {
const { difficulty } = this.state
this.setState({ difficulty: difficulty - 1 })
}
onIncBotLevel = (index: number) => {
const { bots } = this.state
this.setState({
bots: bots.update(index, e => e.incTankLevel()),
})
}
onDecBotLevel = (index: number) => {
const { bots } = this.state
this.setState({
bots: bots.update(index, e => e.decTankLevel()),
})
}
onIncBotCount = (index: number) => {
const { bots } = this.state
this.setState({
bots: bots.updateIn([index, 'count'], inc(1)),
})
}
onDecBotCount = (index: number) => {
const { bots } = this.state
this.setState({
bots: bots.updateIn([index, 'count'], dec(1)),
})
}
/** 检查当前编辑器中的关卡配置是否合理. 返回 true 表示关卡配置合理 */
async check() {
const {
stages,
popupHandle: { showAlertPopup, showConfirmPopup },
} = this.props
const { name, bots, itemList } = this.state
const totalBotCount = bots.map(e => e.count).reduce(add)
// 检查stageName
if (name === '') {
await showAlertPopup('Please enter stage name.')
this.props.dispatch(replace('/editor/config'))
return false
}
// 检查是否与已有的default-stage 重名
if (stages.some(s => !s.custom && s.name === name)) {
await showAlertPopup(`Stage ${name} already exists.`)
return false
}
// 检查bots数量
if (totalBotCount === 0) {
await showAlertPopup('no bot.')
return false
}
// 检查老鹰是否存在
const hasEagle = itemList.some(mapItem => mapItem.type === 'E')
if (!hasEagle) {
await showAlertPopup('no eagle.')
return false
}
// 检查是否与已有的custom-stage 重名
if (stages.some(s => s.custom && s.name === name)) {
const confirmed = await showConfirmPopup('Override exsiting custome stage. continue?')
if (!confirmed) {
return false
}
}
if (totalBotCount !== 20) {
const confirmed = await showConfirmPopup('total bot count is not 20. continue?')
if (!confirmed) {
return false
}
}
return true
}
onBack = async () => {
const { dispatch } = this.props
dispatch(actions.setEditorContent(this.getStage()))
dispatch(goBack())
}
onSave = async () => {
if (await this.check()) {
const { dispatch } = this.props
const stage = StageConfigConverter.e2s(Object.assign({ custom: true }, this.state))
dispatch(actions.setCustomStage(stage))
dispatch(actions.syncCustomStages())
dispatch(replace('/list/custom'))
}
}
onShowHelpInfo = async () => {
const {
popupHandle: { showAlertPopup },
} = this.props
await showAlertPopup('1. Choose an item type below.')
await showAlertPopup('2. Click or pan in the left.')
await showAlertPopup('3. After selecting Brick or Steel you can change the item shape')
}
getStage() {
return StageConfigConverter.e2s(Object.assign({ custom: false }, this.state))
}
renderItemSwitchButtons() {
return (
<g className="item-switch-buttons">
{Object.entries(positionMap).map(([type, y]: [MapItemType, number]) => (
<AreaButton
key={type}
x={0.25 * B}
y={y}
width={2.5 * B}
height={B}
onClick={() => this.setState({ itemType: type })}
/>
))}
</g>
)
}
renderHexAdjustButtons() {
const { itemType, brickHex, steelHex } = this.state
let brickHexAdjustButtons: JSX.Element[] = null
let steelHexAdjustButtons: JSX.Element[] = null
if (itemType === 'B') {
brickHexAdjustButtons = [0b0001, 0b0010, 0b0100, 0b1000].map(bin => (
<AreaButton
key={bin}
x={B + (bin & 0b1010 ? 0.5 * B : 0)}
y={2.5 * B + (bin & 0b1100 ? 0.5 * B : 0)}
width={0.5 * B}
height={0.5 * B}
spreadX={0}
spreadY={0}
onClick={() => this.setState({ brickHex: brickHex ^ bin })}
/>
))
}
if (itemType === 'T') {
steelHexAdjustButtons = [0b0001, 0b0010, 0b0100, 0b1000].map(bin => (
<AreaButton
key={bin}
x={B + (bin & 0b1010 ? 0.5 * B : 0)}
y={4 * B + (bin & 0b1100 ? 0.5 * B : 0)}
width={0.5 * B}
height={0.5 * B}
spreadX={0}
spreadY={0}
onClick={() => this.setState({ steelHex: steelHex ^ bin })}
/>
))
}
return (
<g className="hex-adjust-buttons">
{brickHexAdjustButtons}
{steelHexAdjustButtons}
{itemType === 'B' ? (
<TextButton
content="f"
spreadX={0.125 * B}
x={2.25 * B}
y={2.75 * B}
onClick={() => this.setState({ itemType: 'B', brickHex: 0xf })}
/>
) : null}
{itemType === 'T' ? (
<TextButton
content="f"
spreadX={0.125 * B}
x={2.25 * B}
y={4.25 * B}
onClick={() => this.setState({ itemType: 'T', steelHex: 0xf })}
/>
) : null}
</g>
)
}
renderMapView() {
const { brickHex, steelHex, itemType, t } = this.state
return (
<g className="map-view">
<StagePreview disableImageCache stage={this.getStage()} />
<Grid t={t} />
<g className="tools" transform={`translate(${13 * B},0)`}>
<TextButton
content="?"
x={2.25 * B}
y={0.25 * B}
spreadX={0.05 * B}
spreadY={0.05 * B}
onClick={this.onShowHelpInfo}
/>
<Text
content={'\u2192'}
fill="#E91E63"
x={0.25 * B}
y={0.25 * B + positionMap[itemType]}
/>
<rect x={B} y={B} width={B} height={B} fill="black" />
<HexBrickWall x={B} y={2.5 * B} hex={brickHex} />
<HexSteelWall x={B} y={4 * B} hex={steelHex} />
<River shape={0} x={B} y={5.5 * B} />
<Snow x={B} y={7 * B} />
<Forest x={B} y={8.5 * B} />
<Eagle x={B} y={10 * B} broken={false} />
{this.renderItemSwitchButtons()}
{this.renderHexAdjustButtons()}
</g>
</g>
)
}
renderConfigView() {
const { bots, name, difficulty, t } = this.state
const totalBotCount = bots.map(e => e.count).reduce(add)
return (
<g className="config-view">
<Grid t={t} />
<Text content="name:" x={3.5 * B} y={1 * B} fill="#ccc" />
<TextInput
x={6.5 * B}
y={B}
maxLength={12}
value={name}
onChange={name => this.setState({ name })}
/>
<Text content="difficulty:" x={0.5 * B} y={2.5 * B} fill="#ccc" />
<TextButton
content="-"
x={6.25 * B}
y={2.5 * B}
disabled={difficulty === 1}
onClick={this.onDecDifficulty}
/>
<Text content={String(difficulty)} x={7.25 * B} y={2.5 * B} fill="#ccc" />
<TextButton
content="+"
x={8.25 * B}
y={2.5 * B}
disabled={difficulty === 4}
onClick={this.onIncDifficulty}
/>
<Text content="bots:" x={2 * B} y={4 * B} fill="#ccc" />
<g className="bots-config" transform={`translate(${6 * B}, ${4 * B})`}>
{bots.map(({ tankLevel, count }, index) => (
<g key={index} transform={`translate(0, ${1.5 * B * index})`}>
<TextButton
content={'\u2190'}
x={0.25 * B}
y={0.25 * B}
disabled={tankLevel === 'basic'}
onClick={() => this.onDecBotLevel(index)}
/>
<Tank tank={new TankRecord({ side: 'bot', level: tankLevel, x: B, y: 0 })} />
<TextButton
content={'\u2192'}
x={2.25 * B}
y={0.25 * B}
disabled={tankLevel === 'armor'}
onClick={() => this.onIncBotLevel(index)}
/>
<TextButton
content="-"
x={3.75 * B}
y={0.25 * B}
disabled={count === 0}
onClick={() => this.onDecBotCount(index)}
/>
<Text content={String(count).padStart(2, '0')} x={4.5 * B} y={0.25 * B} fill="#ccc" />
<TextButton
content="+"
x={5.75 * B}
y={0.25 * B}
disabled={count === 99}
onClick={() => this.onIncBotCount(index)}
/>
</g>
))}
<Text content="total:" x={0.25 * B} y={6 * B} fill="#ccc" />
<Text
content={String(totalBotCount).padStart(2, '0')}
x={4.5 * B}
y={6 * B}
fill="#ccc"
/>
</g>
</g>
)
}
render() {
const {
dispatch,
view,
popupHandle: { popup },
} = this.props
return (
<Screen
background="#333"
refFn={node => (this.svg = node)}
onMouseDown={this.onMouseDown}
onMouseUp={this.onMouseUp}
onMouseMove={this.onMouseMove}
onMouseLeave={this.onMouseLeave}
>
{view === 'map' ? this.renderMapView() : null}
{view === 'config' ? this.renderConfigView() : null}
<g className="menu" transform={`translate(0, ${13 * B})`}>
<TextButton
content="config"
x={0.5 * B}
y={0.5 * B}
selected={view === 'config'}
onClick={() => dispatch(replace('/editor/config'))}
/>
<TextButton
content="map"
x={4 * B}
y={0.5 * B}
selected={view === 'map'}
onClick={() => dispatch(replace('/editor/map'))}
/>
<TextButton content="save" x={10 * B} y={0.5 * B} onClick={this.onSave} />
<TextButton content="back" x={12.5 * B} y={0.5 * B} onClick={this.onBack} />
</g>
{popup}
</Screen>
)
}
}
const EditorWrapper = ({
match,
dispatch,
initialCotnent,
stages,
}: EditorProps & { match: match<{ view: string }> }) => (
<Route
path={`${match.url}/:view`}
children={({ match }) => {
// match 在这里可能为 null
const view = match && match.params.view
if (!['map', 'config'].includes(view)) {
return <Redirect to="/editor/config" />
}
return (
<PopupProvider>
{popupHandle => (
<Editor
view={view}
dispatch={dispatch}
initialCotnent={initialCotnent}
stages={stages}
popupHandle={popupHandle}
/>
)}
</PopupProvider>
)
}}
/>
)
const mapStateToProps = (s: State) => ({ initialCotnent: s.editorContent, stages: s.stages })
export default connect(mapStateToProps)(EditorWrapper) | the_stack |
var getArguments = function () {
return arguments;
};
var arguments = getArguments();
is.arguments(arguments);
is.not.arguments({ foo: 'bar' });
is.all.arguments(arguments, 'bar');
is.any.arguments(['foo'], arguments);
is.all.arguments([arguments, 'foo', 'bar']);
is.array(['foo', 'bar', 'baz']);
is.not.array({ foo: 'bar' });
is.all.array(['foo'], 'bar');
is.any.array(['foo'], 'bar');
is.all.array([[1, 2], 'foo', 'bar']);
is.boolean(true);
is.not.boolean({ foo: 'bar' });
is.all.boolean(true, 'bar');
is.any.boolean(true, 'bar');
is.all.boolean([true, 'foo', 'bar']);
is.date(new Date());
is.not.date({ foo: 'bar' });
is.all.date(new Date(), 'bar');
is.any.date(new Date(), 'bar');
is.all.date([new Date(), 'foo', 'bar']);
is.error(new Error());
is.not.error({ foo: 'bar' });
is.all.error(new Error(), 'bar');
is.any.error(new Error(), 'bar');
is.all.error([new Error(), 'foo', 'bar']);
is.fn(toString);
is.not.fn({ foo: 'bar' });
is.all.fn(toString, 'bar');
is.any.fn(toString, 'bar');
is.all.fn([toString, 'foo', 'bar']);
is.function(toString);
is.not.function({ foo: 'bar' });
is.all.function(toString, 'bar');
is.any.function(toString, 'bar');
is.all.function([toString, 'foo', 'bar']);
is.nan(NaN);
is.not.nan(42);
is.all.nan(NaN, 1);
is.any.nan(NaN, 2);
is.all.nan([NaN, 'foo', 1]);
is.null(null);
is.not.null(42);
is.all.null(null, 1);
is.any.null(null, 2);
is.all.null([null, 'foo', 1]);
is.number(42);
is.not.number('42');
is.all.number('foo', 1);
is.any.number({}, 2);
is.all.number([42, 'foo', 1]);
is.object({ foo: 'bar' });
is.object(toString);
is.not.object('foo');
is.all.object({}, 1);
is.any.object({}, 2);
is.all.object([{}, new Object()]);
is.json({ foo: 'bar' });
is.json(toString);
is.not.json([]);
is.all.json({}, 1);
is.any.json({}, 2);
is.all.json([{}, { foo: 'bar' }]);
is.regexp(/test/);
is.not.regexp(['foo']);
is.all.regexp(/test/, 1);
is.any.regexp(new RegExp('ab+c'), 2);
is.all.regexp([{}, /test/]);
is.string('foo');
is.not.string(['foo']);
is.all.string('foo', 1);
is.any.string('foo', 2);
is.all.string([{}, 'foo']);
is.char('f');
is.not.char(['foo']);
is.all.char('f', 1);
is.any.char('f', 2);
is.all.char(['f', 'o', 'o']);
is.undefined(undefined);
is.not.undefined(null);
is.all.undefined(undefined, 1);
is.any.undefined(undefined, 2);
is.all.undefined([{}, undefined]);
is.defined(undefined);
is.not.defined(null);
is.all.defined(undefined, 1);
is.any.defined(undefined, 2);
is.all.defined([{}, undefined]);
is.sameType(42, 7);
is.sameType(42, '7');
is.not.sameType(42, 7);
//#endregion
//#region Presence checks
is.empty({});
is.empty([]);
is.empty('');
is.not.empty(['foo']);
is.all.empty('', {}, ['foo']);
is.any.empty([], 42);
is.all.empty([{}, 'foo']);
is.existy({});
is.existy(null);
is.not.existy(undefined);
is.all.existy(null, ['foo']);
is.any.existy(undefined, 42);
is.all.existy([{}, 'foo']);
is.truthy(true);
is.truthy(null);
is.not.truthy(false);
is.all.truthy(null, true);
is.any.truthy(undefined, true);
is.all.truthy([{}, true]);
is.falsy(false);
is.falsy(null);
is.not.falsy(true);
is.all.falsy(null, false);
is.any.falsy(undefined, true);
is.all.falsy([false, true, undefined]);
is.space(' ');
is.space('foo');
is.not.space(true);
is.all.space(' ', 'foo');
is.any.space(' ', true);
is.all.space([' ', 'foo', undefined]);
//#endregion
//#region RegExp checks
is.url('http://www.test.com');
is.url('foo');
is.not.url(true);
is.all.url('http://www.test.com', 'foo');
is.any.url('http://www.test.com', true);
is.all.url(['http://www.test.com', 'foo', undefined]);
is.email('test@test.com');
is.email('foo');
is.not.email('foo');
is.all.email('test@test.com', 'foo');
is.any.email('test@test.com', 'foo');
is.all.email(['test@test.com', 'foo', undefined]);
is.creditCard(378282246310005);
is.creditCard(123);
is.not.creditCard(123);
is.all.creditCard(378282246310005, 123);
is.any.creditCard(378282246310005, 123);
is.all.creditCard([378282246310005, 123, undefined]);
is.alphaNumeric('alphaNu3er1k');
is.alphaNumeric('*?');
is.not.alphaNumeric('*?');
is.all.alphaNumeric('alphaNu3er1k', '*?');
is.any.alphaNumeric('alphaNu3er1k', '*?');
is.all.alphaNumeric(['alphaNu3er1k', '*?']);
is.timeString('13:45:30');
is.timeString('90:90:90');
is.not.timeString('90:90:90');
is.all.timeString('13:45:30', '90:90:90');
is.any.timeString('13:45:30', '90:90:90');
is.all.timeString(['13:45:30', '90:90:90']);
is.dateString('11/11/2011');
is.dateString('90/11/2011');
is.not.dateString('90/11/2011');
is.all.dateString('11/11/2011', '90/11/2011');
is.any.dateString('11/11/2011', '90/11/2011');
is.all.dateString(['11/11/2011', '90/11/2011']);
is.usZipCode('02201-1020');
is.usZipCode('123');
is.not.usZipCode('123');
is.all.usZipCode('02201-1020', '123');
is.any.usZipCode('02201-1020', '123');
is.all.usZipCode(['02201-1020', '123']);
is.caPostalCode('L8V3Y1');
is.caPostalCode('L8V 3Y1');
is.caPostalCode('123');
is.not.caPostalCode('123');
is.all.caPostalCode('L8V3Y1', '123');
is.any.caPostalCode('L8V3Y1', '123');
is.all.caPostalCode(['L8V3Y1', '123']);
is.ukPostCode('B184BJ');
is.ukPostCode('123');
is.not.ukPostCode('123');
is.all.ukPostCode('B184BJ', '123');
is.any.ukPostCode('B184BJ', '123');
is.all.ukPostCode(['B184BJ', '123']);
is.nanpPhone('609-555-0175');
is.nanpPhone('123');
is.not.nanpPhone('123');
is.all.nanpPhone('609-555-0175', '123');
is.any.nanpPhone('609-555-0175', '123');
is.all.nanpPhone(['609-555-0175', '123']);
is.eppPhone('+90.2322456789');
is.eppPhone('123');
is.not.eppPhone('123');
is.all.eppPhone('+90.2322456789', '123');
is.any.eppPhone('+90.2322456789', '123');
is.all.eppPhone(['+90.2322456789', '123']);
is.socialSecurityNumber('017-90-7890');
is.socialSecurityNumber('123');
is.not.socialSecurityNumber('123');
is.all.socialSecurityNumber('017-90-7890', '123');
is.any.socialSecurityNumber('017-90-7890', '123');
is.all.socialSecurityNumber(['017-90-7890', '123']);
is.affirmative('yes');
is.affirmative('no');
is.not.affirmative('no');
is.all.affirmative('yes', 'no');
is.any.affirmative('yes', 'no');
is.all.affirmative(['yes', 'y', 'true', 't', 'ok', 'okay']);
is.hexadecimal('f0f0f0');
is.hexadecimal(2.5);
is.not.hexadecimal('string');
is.all.hexadecimal('ff', 'f50');
is.any.hexadecimal('ff5500', true);
is.all.hexadecimal(['fff', '333', 'f50']);
is.hexColor('#333');
is.hexColor('#3333');
is.not.hexColor(0.5);
is.all.hexColor('fff', 'f50');
is.any.hexColor('ff5500', 0.5);
is.all.hexColor(['fff', '333', 'f50']);
is.ip('198.156.23.5');
is.ip('1.2..5');
is.not.ip('8:::::::7');
is.all.ip('0:1::4:ff5:54:987:C', '123.123.123.123');
is.any.ip('123.8.4.3', '0.0.0.0');
is.all.ip(['123.123.23.12', 'A:B:C:D:E:F:0:0']);
is.ipv4('198.12.3.142');
is.ipv4('1.2..5');
is.not.ipv4('8:::::::7');
is.all.ipv4('198.12.3.142', '123.123.123.123');
is.any.ipv4('255.255.255.255', '850..1.4');
is.all.ipv4(['198.12.3.142', '1.2.3']);
is.ipv6('2001:DB8:0:0:1::1');
is.ipv6('985.12.3.4');
is.not.ipv6('8:::::::7');
is.all.ipv6('2001:DB8:0:0:1::1', '1:50:198:2::1:2:8');
is.any.ipv6('255.255.255.255', '2001:DB8:0:0:1::1');
is.all.ipv6(['2001:DB8:0:0:1::1', '1.2.3']);
//#endregion
//#region String checks
is.include('Some text goes here', 'text');
is.include('test', 'text');
is.not.include('test', 'text');
is.upperCase('YEAP');
is.upperCase('nope');
is.not.upperCase('Nope');
is.all.upperCase('YEAP', 'nope');
is.any.upperCase('YEAP', 'nope');
is.all.upperCase(['YEAP', 'ALL UPPERCASE']);
is.lowerCase('yeap');
is.lowerCase('NOPE');
is.not.lowerCase('Nope');
is.all.lowerCase('yeap', 'NOPE');
is.any.lowerCase('yeap', 'NOPE');
is.all.lowerCase(['yeap', 'all lowercase']);
is.startWith('yeap', 'ye');
is.startWith('nope', 'ye');
is.not.startWith('nope not that', 'not');
is.endWith('yeap', 'ap');
is.endWith('nope', 'no');
is.not.endWith('nope not that', 'not');
is.endWith('yeap that one', 'one');
is.capitalized('Yeap');
is.capitalized('nope');
is.not.capitalized('nope not capitalized');
is.not.capitalized('nope Capitalized');
is.all.capitalized('Yeap', 'All', 'Capitalized');
is.any.capitalized('Yeap', 'some', 'Capitalized');
is.all.capitalized(['Nope', 'not']);
is.palindrome('testset');
is.palindrome('nope');
is.not.palindrome('nope not palindrome');
is.not.palindrome('tt');
is.all.palindrome('testset', 'tt');
is.any.palindrome('Yeap', 'some', 'testset');
is.all.palindrome(['Nope', 'testset']);
//#endregion
//#region Arithmetic checks
is.equal(42, 40 + 2);
is.equal('yeap', 'yeap');
is.equal(true, true);
is.not.equal('yeap', 'nope');
is.even(42);
is.not.even(41);
is.all.even(40, 42, 44);
is.any.even(39, 42, 43);
is.all.even([40, 42, 43]);
is.odd(41);
is.not.odd(42);
is.all.odd(39, 41, 43);
is.any.odd(39, 42, 44);
is.all.odd([40, 42, 43]);
is.positive(41);
is.not.positive(-42);
is.all.positive(39, 41, 43);
is.any.positive(-39, 42, -44);
is.all.positive([40, 42, -43]);
is.negative(-41);
is.not.negative(42);
is.all.negative(-39, -41, -43);
is.any.negative(-39, 42, 44);
is.all.negative([40, 42, -43]);
is.above(41, 30);
is.not.above(42, 50);
is.under(30, 35);
is.not.under(42, 30);
is.within(30, 20, 40);
is.not.within(40, 30, 35);
is.decimal(41.5);
is.not.decimal(42);
is.all.decimal(39.5, 41.5, -43.5);
is.any.decimal(-39, 42.5, 44);
is.all.decimal([40, 42.5, -43]);
is.integer(41);
is.not.integer(42.5);
is.all.integer(39, 41, -43);
is.any.integer(-39, 42.5, 44);
is.all.integer([40, 42.5, -43]);
is.finite(41);
is.not.finite(42 / 0);
is.all.finite(39, 41, -43);
is.any.finite(-39, Infinity, 44);
is.all.finite([Infinity, -Infinity, 42.5]);
is.infinite(Infinity);
is.not.infinite(42);
is.all.infinite(Infinity, -Infinity, -43 / 0);
is.any.infinite(-39, Infinity, 44);
is.all.infinite([Infinity, -Infinity, 42.5]);
//#endregion
//#region Object checks
is.propertyCount({ this: 'is', 'sample': {} }, 2);
is.propertyCount({ this: 'is', 'sample': {} }, 3);
is.not.propertyCount({}, 2);
is.propertyDefined({ yeap: 'yeap' }, 'yeap');
is.propertyDefined({ yeap: 'yeap' }, 'nope');
is.not.propertyDefined({}, 'nope');
is.windowObject(window);
is.windowObject({ nope: 'nope' });
is.not.windowObject({});
is.all.windowObject(window, { nope: 'nope' });
is.any.windowObject(window, { nope: 'nope' });
is.all.windowObject([window, { nope: 'nope' }]);
var obj = document.createElement('div');
is.domNode(obj);
is.domNode({ nope: 'nope' });
is.not.domNode({});
is.all.domNode(obj, obj);
is.any.domNode(obj, { nope: 'nope' });
is.all.domNode([obj, { nope: 'nope' }]);
//#endregion
//#region Array checks
is.inArray(2, [1, 2, 3]);
is.inArray(4, [1, 2, 3]);
is.not.inArray(4, [1, 2, 3]);
is.sorted([1, 2, 3]);
is.sorted([1, 2, 4, 3]);
is.not.sorted([5, 4, 3]);
is.all.sorted([1, 2], [3, 4]);
is.any.sorted([1, 2], [5, 4]);
is.all.sorted([[1, 2], [5, 4]]);
//#endregion
//#region Environment checks
is.ie();
is.not.ie();
is.ie(10);
is.ie('>=10');
is.not.ie('<9');
is.chrome();
is.not.chrome();
is.chrome(50);
is.chrome('>=40');
is.not.chrome('<30');
is.firefox();
is.not.firefox();
is.firefox(41);
is.firefox('>=40');
is.not.firefox('<30');
is.edge();
is.not.edge();
is.edge(13);
is.edge('>=12');
is.not.edge('<13');
is.opera();
is.not.opera();
is.opera(36);
is.opera('>=35');
is.not.opera('<20');
is.safari();
is.not.safari();
is.safari(9);
is.safari('>=8');
is.not.safari('<7');
is.phantom();
is.not.phantom();
is.phantom(2);
is.phantom('>=1');
is.not.phantom('<2');
is.ios();
is.not.ios();
is.iphone();
is.not.iphone();
is.iphone(9);
is.iphone('>=7');
is.not.iphone('<8');
is.ipad();
is.not.ipad();
is.ipad(9);
is.ipad('>=7');
is.not.ipad('<8');
is.ipod();
is.not.ipod();
is.ipod(7);
is.ipod('>=5');
is.not.ipod('<5');
is.android();
is.not.android();
is.androidPhone();
is.not.androidPhone();
is.androidTablet();
is.not.androidTablet();
is.blackberry();
is.not.blackberry();
is.windowsPhone();
is.not.windowsPhone();
is.windowsTablet();
is.not.windowsTablet();
is.windows();
is.not.windows();
is.mac();
is.not.mac();
is.linux();
is.not.linux();
is.desktop();
is.not.desktop();
is.mobile();
is.not.mobile();
is.tablet();
is.not.tablet();
is.online();
is.not.online();
is.offline();
is.not.offline();
is.touchDevice();
is.not.touchDevice();
//#endregion
//#region Time checks
var today = new Date();
var yesterday = new Date(new Date().setDate(new Date().getDate() - 1));
var tomorrow = new Date(new Date().setDate(new Date().getDate() + 1));
var monday = new Date('01/26/2015');
var sunday = new Date('01/25/2015');
var saturday = new Date('01/24/2015');
is.today(today);
is.today(yesterday)
is.not.today(yesterday);
is.all.today(today, today);
is.any.today(today, yesterday);
is.all.today([today, yesterday]);
is.yesterday(today);
is.yesterday(yesterday);
is.not.yesterday(today);
is.all.yesterday(yesterday, today);
is.any.yesterday(today, yesterday);
is.all.yesterday([today, yesterday]);
is.tomorrow(today);
is.tomorrow(tomorrow);
is.not.tomorrow(today);
is.all.tomorrow(tomorrow, today);
is.any.tomorrow(today, tomorrow);
is.all.tomorrow([today, tomorrow]);
is.past(yesterday);
is.past(tomorrow);
is.not.past(tomorrow);
is.all.past(tomorrow, yesterday);
is.any.past(yesterday, tomorrow);
is.all.past([yesterday, tomorrow]);
is.future(yesterday);
is.future(tomorrow);
is.not.future(yesterday);
is.all.future(tomorrow, yesterday);
is.any.future(yesterday, tomorrow);
is.all.future([yesterday, tomorrow]);
var mondayObj = new Date('01/26/2015');
var tuesdayObj = new Date('01/27/2015');
is.day(mondayObj, 'monday');
is.day(mondayObj, 'tuesday');
is.not.day(mondayObj, 'tuesday');
var januaryObj = new Date('01/26/2015');
var februaryObj = new Date('02/26/2015');
is.month(januaryObj, 'january');
is.month(februaryObj, 'january');
is.not.month(februaryObj, 'january');
var year2015 = new Date('01/26/2015');
var year2016 = new Date('01/26/2016');
is.year(year2015, 2015);
is.year(year2016, 2015);
is.not.year(year2016, 2015);
is.leapYear(2016);
is.leapYear(2015);
is.not.leapYear(2015);
is.all.leapYear(2015, 2016);
is.any.leapYear(2015, 2016);
is.all.leapYear([2016, 2080]);
is.weekend(sunday);
is.weekend(monday);
is.not.weekend(monday);
is.all.weekend(sunday, saturday);
is.any.weekend(sunday, saturday, monday);
is.all.weekend([sunday, saturday, monday]);
is.weekday(monday);
is.weekday(sunday);
is.not.weekday(sunday);
is.all.weekday(monday, saturday);
is.any.weekday(sunday, saturday, monday);
is.all.weekday([sunday, saturday, monday]);
is.inDateRange(sunday, saturday, monday);
is.inDateRange(saturday, sunday, monday);
is.not.inDateRange(saturday, sunday, monday);
var twoDaysAgo = new Date(new Date().setDate(new Date().getDate() - 2));
var nineDaysAgo = new Date(new Date().setDate(new Date().getDate() - 9));
is.inLastWeek(twoDaysAgo);
is.inLastWeek(nineDaysAgo);
is.not.inLastWeek(nineDaysAgo);
var tenDaysAgo = new Date(new Date().setDate(new Date().getDate() - 10));
var fortyDaysAgo = new Date(new Date().setDate(new Date().getDate() - 40));
is.inLastMonth(tenDaysAgo);
is.inLastMonth(fortyDaysAgo);
is.not.inLastMonth(fortyDaysAgo);
var twoMonthsAgo = new Date(new Date().setMonth(new Date().getMonth() - 2));
var thirteenMonthsAgo = new Date(new Date().setMonth(new Date().getMonth() - 13));
is.inLastYear(twoMonthsAgo);
is.inLastYear(thirteenMonthsAgo);
is.not.inLastYear(thirteenMonthsAgo);
var twoDaysLater = new Date(new Date().setDate(new Date().getDate() + 2));
var nineDaysLater = new Date(new Date().setDate(new Date().getDate() + 9));
is.inNextWeek(twoDaysLater);
is.inNextWeek(nineDaysLater);
is.not.inNextWeek(nineDaysLater);
var tenDaysLater = new Date(new Date().setDate(new Date().getDate() + 10));
var fortyDaysLater = new Date(new Date().setDate(new Date().getDate() + 40));
is.inNextMonth(tenDaysLater);
is.inNextMonth(fortyDaysLater);
is.not.inNextMonth(fortyDaysLater);
var twoMonthsLater = new Date(new Date().setMonth(new Date().getMonth() + 2));
var thirteenMonthsLater = new Date(new Date().setMonth(new Date().getMonth() + 13));
is.inNextYear(twoMonthsLater);
is.inNextYear(thirteenMonthsLater);
is.not.inNextYear(thirteenMonthsLater);
var firstQuarter = new Date('01/26/2015');
var secondQuarter = new Date('05/26/2015');
is.quarterOfYear(firstQuarter, 1);
is.quarterOfYear(secondQuarter, 1);
is.not.quarterOfYear(secondQuarter, 1);
var january1 = new Date('01/01/2015');
var june1 = new Date('06/01/2015');
is.dayLightSavingTime(june1);
is.dayLightSavingTime(january1);
is.not.dayLightSavingTime(january1);
//#endregion
//#region Configuration methods
is.url('https://www.duckduckgo.com');
is.setRegexp(/quack/, 'url');
is.url('quack');
var customName = is.setNamespace();
customName.odd(3);
//#endregion | the_stack |
import { ActionButton, TextField } from '@fluentui/react';
import { Assessments } from 'assessments/assessments';
import { FlaggedComponent } from 'common/components/flagged-component';
import { CapturedInstanceActionType } from 'common/types/captured-instance-action-type';
import { FeatureFlagStoreData } from 'common/types/store-data/feature-flag-store-data';
import { VisualizationType } from 'common/types/visualization-type';
import { ActionAndCancelButtonsComponent } from 'DetailsView/components/action-and-cancel-buttons-component';
import {
FailureInstancePanelControl,
FailureInstancePanelControlProps,
} from 'DetailsView/components/failure-instance-panel-control';
import { FailureInstancePanelDetailsProps } from 'DetailsView/components/failure-instance-panel-details';
import { GenericPanel } from 'DetailsView/components/generic-panel';
import { shallow } from 'enzyme';
import * as React from 'react';
import { IMock, Mock, Times } from 'typemoq';
describe('FailureInstancePanelControlTest', () => {
let addPathForValidationMock: IMock<(path) => void>;
let addInstanceMock: IMock<(instanceData, test, step) => void>;
let editInstanceMock: IMock<(instanceData, test, step, id) => void>;
let clearPathSnippetDataMock: IMock<() => void>;
beforeEach(() => {
addInstanceMock = Mock.ofInstance(() => {});
editInstanceMock = Mock.ofInstance(() => {});
addPathForValidationMock = Mock.ofInstance(() => {});
clearPathSnippetDataMock = Mock.ofInstance(() => {});
});
test('render FailureInstancePanelControl: create without instance', () => {
const props = createPropsWithType(CapturedInstanceActionType.CREATE);
const rendered = shallow(<FailureInstancePanelControl {...props} />);
expect(rendered.getElement()).toMatchSnapshot();
});
test('render FailureInstancePanelControl: partial original instance', () => {
const props = {
step: 'missingHeadings',
test: VisualizationType.HeadingsAssessment,
addFailureInstance: addInstanceMock.object,
addPathForValidation: addPathForValidationMock.object,
clearPathSnippetData: clearPathSnippetDataMock.object,
actionType: CapturedInstanceActionType.CREATE,
assessmentsProvider: Assessments,
featureFlagStoreData: null,
failureInstance: { failureDescription: 'original text' },
};
const rendered = shallow<FailureInstancePanelControl>(
<FailureInstancePanelControl {...props} />,
);
expect(rendered.getElement()).toMatchSnapshot();
expect(rendered.state().currentInstance.path).toBeNull();
});
test('render FailureInstancePanelControl: edit without instance', () => {
const props = createPropsWithType(CapturedInstanceActionType.EDIT);
const rendered = shallow(<FailureInstancePanelControl {...props} />);
expect(rendered.getElement()).toMatchSnapshot();
});
test('onFailureDescriptionChange', () => {
const description = 'abc';
const props = createPropsWithType(CapturedInstanceActionType.CREATE);
const wrapper = shallow<FailureInstancePanelControl>(
<FailureInstancePanelControl {...props} />,
);
wrapper.find(TextField).props().onChange(null, description);
expect(wrapper.state().currentInstance.failureDescription).toEqual(description);
});
test('onSelectorChange ', () => {
const selector = 'some selector';
const eventStub = null;
const props = createPropsWithType(CapturedInstanceActionType.CREATE);
const wrapper = shallow<FailureInstancePanelControl>(
<FailureInstancePanelControl {...props} />,
);
const flaggedComponent = wrapper.find(FlaggedComponent);
const flaggedComponentProps = flaggedComponent.props();
const failureInstancePanelDetails = flaggedComponentProps.enableJSXElement;
const failureInstancePanelDetailsProps =
failureInstancePanelDetails.props as FailureInstancePanelDetailsProps;
failureInstancePanelDetailsProps.onSelectorChange(eventStub, selector);
expect(wrapper.state().currentInstance.path).toEqual(selector);
});
test('onValidateSelector ', () => {
const eventStub = null;
const props = createPropsWithType(CapturedInstanceActionType.CREATE);
const failureInstance = {
failureDescription: 'new text',
path: 'some selector',
snippet: null,
};
props.failureInstance = failureInstance;
addPathForValidationMock
.setup(handler => handler(failureInstance.path))
.verifiable(Times.once());
const wrapper = shallow<FailureInstancePanelControl>(
<FailureInstancePanelControl {...props} />,
);
const flaggedComponent = wrapper.find(FlaggedComponent);
const flaggedComponentProps = flaggedComponent.props();
const failureInstancePanelDetails = flaggedComponentProps.enableJSXElement;
const failureInstancePanelDetailsProps =
failureInstancePanelDetails.props as FailureInstancePanelDetailsProps;
failureInstancePanelDetailsProps.onValidateSelector(eventStub);
addPathForValidationMock.verifyAll();
});
test('openFailureInstancePanel', () => {
const props = createPropsWithType(CapturedInstanceActionType.CREATE);
const eventStub = null;
const failureInstance = {
failureDescription: 'new text',
path: 'new path',
snippet: 'new snippet',
};
props.failureInstance = failureInstance;
const wrapper = shallow<FailureInstancePanelControl>(
<FailureInstancePanelControl {...props} />,
);
wrapper.find(TextField).props().onChange(eventStub, 'a previously entered description');
wrapper.find(ActionButton).props().onClick(eventStub);
expect(wrapper.state().isPanelOpen).toBe(true);
expect(wrapper.state().currentInstance.failureDescription).toEqual(
props.failureInstance.failureDescription,
);
expect(wrapper.state().currentInstance.path).toEqual(props.failureInstance.path);
expect(wrapper.state().currentInstance.snippet).toEqual(props.failureInstance.snippet);
});
test('closeFailureInstancePanel', () => {
const description = 'description';
const props = createPropsWithType(CapturedInstanceActionType.CREATE);
const wrapper = shallow<FailureInstancePanelControl>(
<FailureInstancePanelControl {...props} />,
);
wrapper.find(TextField).props().onChange(null, description);
wrapper.find(GenericPanel).props().onDismiss();
expect(wrapper.state().isPanelOpen).toBe(false);
// This shouldn't be cleared because it stays briefly visible as the panel close animation happens
expect(wrapper.state().currentInstance.failureDescription).toEqual(description);
clearPathSnippetDataMock.verify(handler => handler(), Times.exactly(2));
});
test('onSaveEditedFailureInstance', () => {
const description = 'text';
const props = createPropsWithType(CapturedInstanceActionType.EDIT);
props.instanceId = '1';
props.editFailureInstance = editInstanceMock.object;
const instanceData = {
failureDescription: description,
path: null,
snippet: null,
};
editInstanceMock
.setup(handler => handler(instanceData, props.test, props.step, props.instanceId))
.verifiable(Times.once());
const wrapper = shallow<FailureInstancePanelControl>(
<FailureInstancePanelControl {...props} />,
);
wrapper.find(TextField).props().onChange(null, description);
wrapper.find(ActionAndCancelButtonsComponent).props().primaryButtonOnClick(null);
expect(wrapper.state().isPanelOpen).toBe(false);
// This shouldn't be cleared because it stays briefly visible as the panel close animation happens
expect(wrapper.state().currentInstance.failureDescription).toEqual(description);
editInstanceMock.verifyAll();
clearPathSnippetDataMock.verify(handler => handler(), Times.exactly(2));
});
test('onAddFailureInstance', () => {
const description = 'text';
const props = createPropsWithType(CapturedInstanceActionType.CREATE);
const instanceData = {
failureDescription: description,
path: null,
snippet: null,
};
addInstanceMock
.setup(handler => handler(instanceData, props.test, props.step))
.verifiable(Times.once());
const wrapper = shallow<FailureInstancePanelControl>(
<FailureInstancePanelControl {...props} />,
);
wrapper.find(TextField).props().onChange(null, description);
wrapper.find(ActionAndCancelButtonsComponent).props().primaryButtonOnClick(null);
expect(wrapper.state().isPanelOpen).toBe(false);
// This shouldn't be cleared because it stays briefly visible as the panel close animation happens
expect(wrapper.state().currentInstance.failureDescription).toEqual(description);
addInstanceMock.verifyAll();
clearPathSnippetDataMock.verify(handler => handler(), Times.exactly(2));
});
test('componentDidMount clears store', () => {
const props = createPropsWithType(CapturedInstanceActionType.CREATE);
const failureInstance = {
failureDescription: null,
path: 'inputed path',
snippet: 'snippet for path',
};
props.failureInstance = failureInstance;
const component = new FailureInstancePanelControl(props);
component.componentDidMount();
clearPathSnippetDataMock.verify(handler => handler(), Times.exactly(1));
});
test('componentDidUpdate reassigns state', () => {
const prevProps = createPropsWithType(CapturedInstanceActionType.CREATE);
const newProps = createPropsWithType(CapturedInstanceActionType.CREATE);
const newFailureInstance = {
failureDescription: null,
path: 'inputed path',
snippet: 'snippet for path',
};
newProps.failureInstance = newFailureInstance;
const wrapper = shallow<FailureInstancePanelControl>(
<FailureInstancePanelControl {...newProps} />,
);
(wrapper.instance() as FailureInstancePanelControl).setState({
currentInstance: prevProps.failureInstance,
});
const firstStateCurrentInstance = (wrapper.instance() as FailureInstancePanelControl).state
.currentInstance;
(wrapper.instance() as FailureInstancePanelControl).componentDidUpdate(prevProps);
const secondStateCurrentInstance = (wrapper.instance() as FailureInstancePanelControl).state
.currentInstance;
expect(firstStateCurrentInstance).toEqual(prevProps.failureInstance);
expect(secondStateCurrentInstance).toEqual(newProps.failureInstance);
});
function createPropsWithType(
actionType: CapturedInstanceActionType,
): FailureInstancePanelControlProps {
const featureData = {} as FeatureFlagStoreData;
const emptyFailureInstance = {
failureDescription: null,
path: null,
snippet: null,
};
return {
step: 'missingHeadings',
test: VisualizationType.HeadingsAssessment,
addFailureInstance: addInstanceMock.object,
addPathForValidation: addPathForValidationMock.object,
clearPathSnippetData: clearPathSnippetDataMock.object,
actionType: actionType,
assessmentsProvider: Assessments,
featureFlagStoreData: featureData,
failureInstance: emptyFailureInstance,
};
}
}); | the_stack |
import request = require('request');
import http = require('http');
import Promise = require('bluebird');
let defaultBasePath = 'http://petstore.swagger.io/v1';
// ===============================================
// This file is autogenerated - Please do not edit
// ===============================================
/* tslint:disable:no-unused-variable */
export class Category {
'id': number;
'name': string;
}
export class Pet {
'id': number;
'category': Category;
'name': string;
}
export interface Authentication {
/**
* Apply authentication settings to header and query params.
*/
applyToRequest(requestOptions: request.Options): void;
}
export class HttpBasicAuth implements Authentication {
public username: string;
public password: string;
applyToRequest(requestOptions: request.Options): void {
requestOptions.auth = {
username: this.username, password: this.password
}
}
}
export class ApiKeyAuth implements Authentication {
public apiKey: string;
constructor(private location: string, private paramName: string) {
}
applyToRequest(requestOptions: request.Options): void {
if (this.location == "query") {
(<any>requestOptions.qs)[this.paramName] = this.apiKey;
} else if (this.location == "header") {
requestOptions.headers[this.paramName] = this.apiKey;
}
}
}
export class OAuth implements Authentication {
public accessToken: string;
applyToRequest(requestOptions: request.Options): void {
requestOptions.headers["Authorization"] = "Bearer " + this.accessToken;
}
}
export class VoidAuth implements Authentication {
public username: string;
public password: string;
applyToRequest(requestOptions: request.Options): void {
// Do nothing
}
}
export enum PetApiApiKeys {
}
export class PetApi {
protected basePath = defaultBasePath;
protected defaultHeaders : any = {};
protected authentications = {
'default': <Authentication>new VoidAuth(),
}
constructor(basePath?: string);
constructor(basePathOrUsername: string, password?: string, basePath?: string) {
if (password) {
if (basePath) {
this.basePath = basePath;
}
} else {
if (basePathOrUsername) {
this.basePath = basePathOrUsername
}
}
}
public setApiKey(key: PetApiApiKeys, value: string) {
this.authentications[PetApiApiKeys[key]].apiKey = value;
}
private extendObj<T1,T2>(objA: T1, objB: T2) {
for(let key in objB){
if(objB.hasOwnProperty(key)){
objA[key] = objB[key];
}
}
return <T1&T2>objA;
}
/**
* Add a new pet to the store
*
* @param body Pet object that needs to be added to the store
*/
public addPet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> {
const localVarPath = this.basePath + '/pet';
let queryParameters: any = {};
let headerParams: any = this.extendObj({}, this.defaultHeaders);
let formParams: any = {};
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
json: true,
body: body,
};
this.authentications.default.applyToRequest(requestOptions);
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject({ response: response, body: body });
}
}
});
});
}
/**
* Deletes a pet
*
* @param petId Pet id to delete
* @param apiKey
*/
public deletePet (petId: number, apiKey?: string) : Promise<{ response: http.ClientResponse; body?: any; }> {
const localVarPath = this.basePath + '/pet/{petId}'
.replace('{' + 'petId' + '}', String(petId));
let queryParameters: any = {};
let headerParams: any = this.extendObj({}, this.defaultHeaders);
let formParams: any = {};
// verify required parameter 'petId' is not null or undefined
if (petId === null || petId === undefined) {
throw new Error('Required parameter petId was null or undefined when calling deletePet.');
}
headerParams['api_key'] = apiKey;
let useFormData = false;
let requestOptions: request.Options = {
method: 'DELETE',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
json: true,
};
this.authentications.default.applyToRequest(requestOptions);
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject({ response: response, body: body });
}
}
});
});
}
/**
* Find pet by ID
* Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions
* @param petId ID of pet that needs to be fetched
*/
public getPetById (petId: number) : Promise<{ response: http.ClientResponse; body: Pet; }> {
const localVarPath = this.basePath + '/pet/{petId}'
.replace('{' + 'petId' + '}', String(petId));
let queryParameters: any = {};
let headerParams: any = this.extendObj({}, this.defaultHeaders);
let formParams: any = {};
// verify required parameter 'petId' is not null or undefined
if (petId === null || petId === undefined) {
throw new Error('Required parameter petId was null or undefined when calling getPetById.');
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
json: true,
};
this.authentications.default.applyToRequest(requestOptions);
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.ClientResponse; body: Pet; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject({ response: response, body: body });
}
}
});
});
}
/**
* Update an existing pet
*
* @param body Pet object that needs to be added to the store
*/
public updatePet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> {
const localVarPath = this.basePath + '/pet';
let queryParameters: any = {};
let headerParams: any = this.extendObj({}, this.defaultHeaders);
let formParams: any = {};
let useFormData = false;
let requestOptions: request.Options = {
method: 'PUT',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
json: true,
body: body,
};
this.authentications.default.applyToRequest(requestOptions);
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject({ response: response, body: body });
}
}
});
});
}
/**
* Updates a pet in the store with form data
*
* @param petId ID of pet that needs to be updated
* @param name Updated name of the pet
* @param status Updated status of the pet
*/
public updatePetWithForm (petId: string, name?: string, status?: string) : Promise<{ response: http.ClientResponse; body?: any; }> {
const localVarPath = this.basePath + '/pet/{petId}'
.replace('{' + 'petId' + '}', String(petId));
let queryParameters: any = {};
let headerParams: any = this.extendObj({}, this.defaultHeaders);
let formParams: any = {};
// verify required parameter 'petId' is not null or undefined
if (petId === null || petId === undefined) {
throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.');
}
let useFormData = false;
if (name !== undefined) {
formParams['name'] = name;
}
if (status !== undefined) {
formParams['status'] = status;
}
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
json: true,
};
this.authentications.default.applyToRequest(requestOptions);
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject({ response: response, body: body });
}
}
});
});
}
}
export enum StoreApiApiKeys {
}
export class StoreApi {
protected basePath = defaultBasePath;
protected defaultHeaders : any = {};
protected authentications = {
'default': <Authentication>new VoidAuth(),
}
constructor(basePath?: string);
constructor(basePathOrUsername: string, password?: string, basePath?: string) {
if (password) {
if (basePath) {
this.basePath = basePath;
}
} else {
if (basePathOrUsername) {
this.basePath = basePathOrUsername
}
}
}
public setApiKey(key: StoreApiApiKeys, value: string) {
this.authentications[StoreApiApiKeys[key]].apiKey = value;
}
private extendObj<T1,T2>(objA: T1, objB: T2) {
for(let key in objB){
if(objB.hasOwnProperty(key)){
objA[key] = objB[key];
}
}
return <T1&T2>objA;
}
/**
* Delete purchase order by ID
* For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
* @param orderId ID of the order that needs to be deleted
*/
public deleteOrder (orderId: string) : Promise<{ response: http.ClientResponse; body?: any; }> {
const localVarPath = this.basePath + '/store/order/{orderId}'
.replace('{' + 'orderId' + '}', String(orderId));
let queryParameters: any = {};
let headerParams: any = this.extendObj({}, this.defaultHeaders);
let formParams: any = {};
// verify required parameter 'orderId' is not null or undefined
if (orderId === null || orderId === undefined) {
throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.');
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'DELETE',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
json: true,
};
this.authentications.default.applyToRequest(requestOptions);
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject({ response: response, body: body });
}
}
});
});
}
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
*/
public getInventory () : Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }> {
const localVarPath = this.basePath + '/store/inventory';
let queryParameters: any = {};
let headerParams: any = this.extendObj({}, this.defaultHeaders);
let formParams: any = {};
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
json: true,
};
this.authentications.default.applyToRequest(requestOptions);
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject({ response: response, body: body });
}
}
});
});
}
/**
* Find purchase order by ID
* For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
* @param orderId ID of pet that needs to be fetched
*/
public getOrderById (orderId: string) : Promise<{ response: http.ClientResponse; body: Order; }> {
const localVarPath = this.basePath + '/store/order/{orderId}'
.replace('{' + 'orderId' + '}', String(orderId));
let queryParameters: any = {};
let headerParams: any = this.extendObj({}, this.defaultHeaders);
let formParams: any = {};
// verify required parameter 'orderId' is not null or undefined
if (orderId === null || orderId === undefined) {
throw new Error('Required parameter orderId was null or undefined when calling getOrderById.');
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
json: true,
};
this.authentications.default.applyToRequest(requestOptions);
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.ClientResponse; body: Order; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject({ response: response, body: body });
}
}
});
});
}
/**
* Place an order for a pet
*
* @param body order placed for purchasing the pet
*/
public placeOrder (body?: Order) : Promise<{ response: http.ClientResponse; body: Order; }> {
const localVarPath = this.basePath + '/store/order';
let queryParameters: any = {};
let headerParams: any = this.extendObj({}, this.defaultHeaders);
let formParams: any = {};
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
json: true,
body: body,
};
this.authentications.default.applyToRequest(requestOptions);
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.ClientResponse; body: Order; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject({ response: response, body: body });
}
}
});
});
}
} | the_stack |
import {Injectable} from '@angular/core';
import {merge, Observable, Subject, Subscription} from 'rxjs';
import {filter, tap} from 'rxjs/operators';
import {BreakPoint} from '../breakpoints/break-point';
import {sortDescendingPriority} from '../utils/sort';
import {BreakPointRegistry} from '../breakpoints/break-point-registry';
import {MatchMedia} from '../match-media/match-media';
import {MediaChange} from '../media-change';
import {PrintHook, HookTarget} from './print-hook';
import {mergeAlias} from '../add-alias';
type ClearCallback = () => void;
type UpdateCallback = (val: any) => void;
type Builder = UpdateCallback | ClearCallback;
type ValueMap = Map<string, string>;
type BreakpointMap = Map<string, ValueMap>;
type ElementMap = Map<HTMLElement, BreakpointMap>;
type ElementKeyMap = WeakMap<HTMLElement, Set<string>>;
type SubscriptionMap = Map<string, Subscription>;
type WatcherMap = WeakMap<HTMLElement, SubscriptionMap>;
type BuilderMap = WeakMap<HTMLElement, Map<string, Builder>>;
export interface ElementMatcher {
element: HTMLElement;
key: string;
value: any;
}
/**
* MediaMarshaller - register responsive values from directives and
* trigger them based on media query events
*/
@Injectable({providedIn: 'root'})
export class MediaMarshaller {
private activatedBreakpoints: BreakPoint[] = [];
private elementMap: ElementMap = new Map();
private elementKeyMap: ElementKeyMap = new WeakMap();
private watcherMap: WatcherMap = new WeakMap(); // special triggers to update elements
private updateMap: BuilderMap = new WeakMap(); // callback functions to update styles
private clearMap: BuilderMap = new WeakMap(); // callback functions to clear styles
private subject: Subject<ElementMatcher> = new Subject();
get activatedAlias(): string {
return this.activatedBreakpoints[0] ? this.activatedBreakpoints[0].alias : '';
}
constructor(protected matchMedia: MatchMedia,
protected breakpoints: BreakPointRegistry,
protected hook: PrintHook) {
this.observeActivations();
}
/**
* Update styles on breakpoint activates or deactivates
* @param mc
*/
onMediaChange(mc: MediaChange) {
const bp: BreakPoint | null = this.findByQuery(mc.mediaQuery);
if (bp) {
mc = mergeAlias(mc, bp);
if (mc.matches && this.activatedBreakpoints.indexOf(bp) === -1) {
this.activatedBreakpoints.push(bp);
this.activatedBreakpoints.sort(sortDescendingPriority);
this.updateStyles();
} else if (!mc.matches && this.activatedBreakpoints.indexOf(bp) !== -1) {
// Remove the breakpoint when it's deactivated
this.activatedBreakpoints.splice(this.activatedBreakpoints.indexOf(bp), 1);
this.activatedBreakpoints.sort(sortDescendingPriority);
this.updateStyles();
}
}
}
/**
* initialize the marshaller with necessary elements for delegation on an element
* @param element
* @param key
* @param updateFn optional callback so that custom bp directives don't have to re-provide this
* @param clearFn optional callback so that custom bp directives don't have to re-provide this
* @param extraTriggers other triggers to force style updates (e.g. layout, directionality, etc)
*/
init(element: HTMLElement,
key: string,
updateFn?: UpdateCallback,
clearFn?: ClearCallback,
extraTriggers: Observable<any>[] = []): void {
initBuilderMap(this.updateMap, element, key, updateFn);
initBuilderMap(this.clearMap, element, key, clearFn);
this.buildElementKeyMap(element, key);
this.watchExtraTriggers(element, key, extraTriggers);
}
/**
* get the value for an element and key and optionally a given breakpoint
* @param element
* @param key
* @param bp
*/
getValue(element: HTMLElement, key: string, bp?: string): any {
const bpMap = this.elementMap.get(element);
if (bpMap) {
const values = bp !== undefined ? bpMap.get(bp) : this.getActivatedValues(bpMap, key);
if (values) {
return values.get(key);
}
}
return undefined;
}
/**
* whether the element has values for a given key
* @param element
* @param key
*/
hasValue(element: HTMLElement, key: string): boolean {
const bpMap = this.elementMap.get(element);
if (bpMap) {
const values = this.getActivatedValues(bpMap, key);
if (values) {
return values.get(key) !== undefined || false;
}
}
return false;
}
/**
* Set the value for an input on a directive
* @param element the element in question
* @param key the type of the directive (e.g. flex, layout-gap, etc)
* @param bp the breakpoint suffix (empty string = default)
* @param val the value for the breakpoint
*/
setValue(element: HTMLElement, key: string, val: any, bp: string): void {
let bpMap: BreakpointMap | undefined = this.elementMap.get(element);
if (!bpMap) {
bpMap = new Map().set(bp, new Map().set(key, val));
this.elementMap.set(element, bpMap);
} else {
const values = (bpMap.get(bp) ?? new Map()).set(key, val);
bpMap.set(bp, values);
this.elementMap.set(element, bpMap);
}
const value = this.getValue(element, key);
if (value !== undefined) {
this.updateElement(element, key, value);
}
}
/** Track element value changes for a specific key */
trackValue(element: HTMLElement, key: string): Observable<ElementMatcher> {
return this.subject
.asObservable()
.pipe(filter(v => v.element === element && v.key === key));
}
/** update all styles for all elements on the current breakpoint */
updateStyles(): void {
this.elementMap.forEach((bpMap, el) => {
const keyMap = new Set(this.elementKeyMap.get(el)!);
let valueMap = this.getActivatedValues(bpMap);
if (valueMap) {
valueMap.forEach((v, k) => {
this.updateElement(el, k, v);
keyMap.delete(k);
});
}
keyMap.forEach(k => {
valueMap = this.getActivatedValues(bpMap, k);
if (valueMap) {
const value = valueMap.get(k);
this.updateElement(el, k, value);
} else {
this.clearElement(el, k);
}
});
});
}
/**
* clear the styles for a given element
* @param element
* @param key
*/
clearElement(element: HTMLElement, key: string): void {
const builders = this.clearMap.get(element);
if (builders) {
const clearFn: ClearCallback = builders.get(key) as ClearCallback;
if (!!clearFn) {
clearFn();
this.subject.next({element, key, value: ''});
}
}
}
/**
* update a given element with the activated values for a given key
* @param element
* @param key
* @param value
*/
updateElement(element: HTMLElement, key: string, value: any): void {
const builders = this.updateMap.get(element);
if (builders) {
const updateFn: UpdateCallback = builders.get(key) as UpdateCallback;
if (!!updateFn) {
updateFn(value);
this.subject.next({element, key, value});
}
}
}
/**
* release all references to a given element
* @param element
*/
releaseElement(element: HTMLElement): void {
const watcherMap = this.watcherMap.get(element);
if (watcherMap) {
watcherMap.forEach(s => s.unsubscribe());
this.watcherMap.delete(element);
}
const elementMap = this.elementMap.get(element);
if (elementMap) {
elementMap.forEach((_, s) => elementMap.delete(s));
this.elementMap.delete(element);
}
}
/**
* trigger an update for a given element and key (e.g. layout)
* @param element
* @param key
*/
triggerUpdate(element: HTMLElement, key?: string): void {
const bpMap = this.elementMap.get(element);
if (bpMap) {
const valueMap = this.getActivatedValues(bpMap, key);
if (valueMap) {
if (key) {
this.updateElement(element, key, valueMap.get(key));
} else {
valueMap.forEach((v, k) => this.updateElement(element, k, v));
}
}
}
}
/** Cross-reference for HTMLElement with directive key */
private buildElementKeyMap(element: HTMLElement, key: string) {
let keyMap = this.elementKeyMap.get(element);
if (!keyMap) {
keyMap = new Set();
this.elementKeyMap.set(element, keyMap);
}
keyMap.add(key);
}
/**
* Other triggers that should force style updates:
* - directionality
* - layout changes
* - mutationobserver updates
*/
private watchExtraTriggers(element: HTMLElement,
key: string,
triggers: Observable<any>[]) {
if (triggers && triggers.length) {
let watchers = this.watcherMap.get(element);
if (!watchers) {
watchers = new Map();
this.watcherMap.set(element, watchers);
}
const subscription = watchers.get(key);
if (!subscription) {
const newSubscription = merge(...triggers).subscribe(() => {
const currentValue = this.getValue(element, key);
this.updateElement(element, key, currentValue);
});
watchers.set(key, newSubscription);
}
}
}
/** Breakpoint locator by mediaQuery */
private findByQuery(query: string) {
return this.breakpoints.findByQuery(query);
}
/**
* get the fallback breakpoint for a given element, starting with the current breakpoint
* @param bpMap
* @param key
*/
private getActivatedValues(bpMap: BreakpointMap, key?: string): ValueMap | undefined {
for (let i = 0; i < this.activatedBreakpoints.length; i++) {
const activatedBp = this.activatedBreakpoints[i];
const valueMap = bpMap.get(activatedBp.alias);
if (valueMap) {
if (key === undefined || (valueMap.has(key) && valueMap.get(key) != null)) {
return valueMap;
}
}
}
const lastHope = bpMap.get('');
return (key === undefined || lastHope && lastHope.has(key)) ? lastHope : undefined;
}
/**
* Watch for mediaQuery breakpoint activations
*/
private observeActivations() {
const target = this as unknown as HookTarget;
const queries = this.breakpoints.items.map(bp => bp.mediaQuery);
this.matchMedia
.observe(this.hook.withPrintQuery(queries))
.pipe(
tap(this.hook.interceptEvents(target)),
filter(this.hook.blockPropagation())
)
.subscribe(this.onMediaChange.bind(this));
}
}
function initBuilderMap(map: BuilderMap,
element: HTMLElement,
key: string,
input?: UpdateCallback | ClearCallback): void {
if (input !== undefined) {
let oldMap = map.get(element);
if (!oldMap) {
oldMap = new Map();
map.set(element, oldMap);
}
oldMap.set(key, input);
}
} | the_stack |
import { expect } from 'chai'
import {
EncryptedDataKey,
NodeAlgorithmSuite,
AlgorithmSuiteIdentifier,
SignatureKey,
VerificationKey,
WebCryptoAlgorithmSuite,
KeyringTraceFlag,
} from '../src'
import {
decorateCryptographicMaterial,
decorateEncryptionMaterial,
decorateDecryptionMaterial,
decorateWebCryptoMaterial,
NodeEncryptionMaterial,
NodeDecryptionMaterial,
WebCryptoEncryptionMaterial,
WebCryptoDecryptionMaterial,
subtleFunctionForMaterial,
keyUsageForMaterial,
isValidCryptoKey,
isCryptoKey,
unwrapDataKey,
wrapWithKeyObjectIfSupported,
supportsKeyObject,
} from '../src/cryptographic_material'
import { createSecretKey } from 'crypto'
describe('decorateCryptographicMaterial', () => {
it('will decorate', () => {
const test = decorateCryptographicMaterial(
{} as any,
KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY
)
expect(test)
.to.haveOwnProperty('setUnencryptedDataKey')
.and.to.be.a('function')
expect(test)
.to.haveOwnProperty('getUnencryptedDataKey')
.and.to.be.a('function')
expect(test)
.to.haveOwnProperty('zeroUnencryptedDataKey')
.and.to.be.a('function')
expect(test).to.haveOwnProperty('hasUnencryptedDataKey').and.to.equal(false)
})
it('Precondition: setFlag must be in the set of KeyringTraceFlag.SET_FLAGS.', () => {
expect(() =>
decorateCryptographicMaterial(
{} as any,
KeyringTraceFlag.WRAPPING_KEY_SIGNED_ENC_CTX
)
).to.throw('')
})
it('set, inspect, get works', () => {
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const test = decorateCryptographicMaterial(
{ suite, keyringTrace: [] } as any,
KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY
)
const dataKey = new Uint8Array(suite.keyLengthBytes).fill(1)
test.setUnencryptedDataKey(new Uint8Array(dataKey), {
keyNamespace: 'k',
keyName: 'k',
flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY,
})
expect(test.hasUnencryptedDataKey).to.equal(true)
const udk = unwrapDataKey(test.getUnencryptedDataKey())
expect(udk).to.deep.equal(dataKey)
})
it('zeroing out the unencrypted data key', () => {
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const test = decorateCryptographicMaterial(
{ suite, keyringTrace: [] } as any,
KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY
)
const dataKey = new Uint8Array(suite.keyLengthBytes).fill(1)
/* This is complicated.
* Now that I support KeyObjects it is good to pass a copy,
* i.e. new Uint8Array(dataKey).
* But in this case, if this is a version of Node.js that does not support KeyObjects
* passing the dataKey lets me verify that the value memory is really zeroed.
*/
test.setUnencryptedDataKey(dataKey, {
keyNamespace: 'k',
keyName: 'k',
flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY,
})
test.zeroUnencryptedDataKey()
expect(test.hasUnencryptedDataKey).to.equal(false)
if (!supportsKeyObject) {
expect(dataKey).to.deep.equal(
new Uint8Array(suite.keyLengthBytes).fill(0)
)
} else {
// If the environment supports KeyObjects then the udk was wrapped.
// There is no way to confirm that
}
})
it('Precondition: The data key length must agree with algorithm specification.', () => {
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const test = decorateCryptographicMaterial(
{ suite, keyringTrace: [] } as any,
KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY
)
const dataKey = new Uint8Array(suite.keyLengthBytes - 1).fill(1)
expect(() => test.setUnencryptedDataKey(new Uint8Array(dataKey))).to.throw()
})
it('Precondition: unencryptedDataKey must not be Zeroed out.', () => {
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const test = decorateCryptographicMaterial(
{ suite, keyringTrace: [] } as any,
KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY
)
const dataKey = new Uint8Array(suite.keyLengthBytes).fill(1)
test.setUnencryptedDataKey(new Uint8Array(dataKey), {
keyNamespace: 'k',
keyName: 'k',
flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY,
})
test.zeroUnencryptedDataKey()
expect(() => test.getUnencryptedDataKey()).to.throw()
})
it('Precondition: unencryptedDataKey must be set before we can return it.', () => {
const test: any = decorateCryptographicMaterial(
{} as any,
KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY
)
expect(() => test.getUnencryptedDataKey()).to.throw()
})
it(`Precondition: If the unencryptedDataKey has not been set, it should not be settable later.
Precondition: If the udkForVerification has not been set, it should not be settable later.`, () => {
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const test = decorateCryptographicMaterial(
{ suite, keyringTrace: [] } as any,
KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY
)
test.zeroUnencryptedDataKey()
const dataKey = new Uint8Array(suite.keyLengthBytes).fill(1)
const trace = {
keyNamespace: 'k',
keyName: 'k',
flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY,
}
// It is very hard to test this perfectly. However, this tests the spirit.
expect(() =>
test.setUnencryptedDataKey(new Uint8Array(dataKey), trace)
).to.throw()
})
it('Precondition: dataKey must be Binary Data', () => {
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const test = decorateCryptographicMaterial(
{ suite, keyringTrace: [] } as any,
KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY
)
expect(() => test.setUnencryptedDataKey('')).to.throw()
})
it('Precondition: unencryptedDataKey must not be set. Modifying the unencryptedDataKey is denied', () => {
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const test = decorateCryptographicMaterial(
{ suite, keyringTrace: [] } as any,
KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY
)
const dataKey = new Uint8Array(suite.keyLengthBytes).fill(1)
const trace = {
keyNamespace: 'k',
keyName: 'k',
flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY,
}
test.setUnencryptedDataKey(new Uint8Array(dataKey), trace)
expect(() =>
test.setUnencryptedDataKey(new Uint8Array(dataKey), trace)
).to.throw('unencryptedDataKey has already been set')
})
it('Precondition: dataKey should have an ArrayBuffer that *only* stores the key.', () => {
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const test = decorateCryptographicMaterial(
{ suite, keyringTrace: [] } as any,
KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY
)
const dataKey = new Uint8Array(
new ArrayBuffer(suite.keyLengthBytes + 10),
5,
suite.keyLengthBytes
).fill(1)
const trace = {
keyNamespace: 'k',
keyName: 'k',
flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY,
}
expect(() => test.setUnencryptedDataKey(dataKey, trace)).to.throw(
'Unencrypted Master Key must be an isolated buffer.'
)
})
it('Precondition: Trace must be set, and the flag must indicate that the data key was generated.', () => {
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const test = decorateCryptographicMaterial(
{ suite, keyringTrace: [] } as any,
KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY
)
const dataKey = new Uint8Array(suite.keyLengthBytes).fill(1)
expect(() =>
test.setUnencryptedDataKey(new Uint8Array(dataKey), {} as any)
).to.throw('Malformed KeyringTrace')
})
it('Precondition: On set the required KeyringTraceFlag must be set.', () => {
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const test = decorateCryptographicMaterial(
{ suite, keyringTrace: [] } as any,
KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY
)
const dataKey = new Uint8Array(suite.keyLengthBytes).fill(1)
const trace = {
keyNamespace: 'k',
keyName: 'k',
flags: KeyringTraceFlag.WRAPPING_KEY_SIGNED_ENC_CTX,
}
expect(() =>
test.setUnencryptedDataKey(new Uint8Array(dataKey), trace)
).to.throw('Required KeyringTraceFlag not set')
})
it('Precondition: Only valid flags are allowed.', () => {
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const test = decorateCryptographicMaterial(
{ suite, keyringTrace: [] } as any,
KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY
)
const dataKey = new Uint8Array(suite.keyLengthBytes).fill(1)
const trace = {
keyNamespace: 'k',
keyName: 'k',
flags:
KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY |
KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY,
}
expect(() =>
test.setUnencryptedDataKey(new Uint8Array(dataKey), trace)
).to.throw('Invalid KeyringTraceFlags set.')
})
it('Precondition: The unencryptedDataKey must not have been modified.', () => {
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const material = decorateCryptographicMaterial(
{ suite, keyringTrace: [] } as any,
KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY
)
const dataKey = new Uint8Array(suite.keyLengthBytes).fill(1)
material.setUnencryptedDataKey(dataKey, {
keyNamespace: 'k',
keyName: 'k',
flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY,
})
const test = material.getUnencryptedDataKey()
test[0] = 12
expect(() => {
const udk = unwrapDataKey(material.getUnencryptedDataKey())
if (supportsKeyObject) {
/* This should NOT be true.
* If the udk is a KeyObject then the change above was on independent memory.
* This check follows the code, and is *intended* to fail.
*/
expect(udk[0]).to.equal(12)
}
}).to.throw()
})
})
describe('decorateEncryptionMaterial', () => {
it('will decorate', () => {
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const test: any = decorateEncryptionMaterial({
suite,
keyringTrace: [],
} as any)
expect(test)
.to.haveOwnProperty('addEncryptedDataKey')
.and.to.be.a('function')
expect(test).to.haveOwnProperty('setSignatureKey').and.to.be.a('function')
expect(test)
.to.haveOwnProperty('encryptedDataKeys')
.and.to.be.a('array')
.with.lengthOf(0)
expect(test).to.haveOwnProperty('signatureKey').and.to.equal(undefined)
})
it('add EncryptedDataKey', () => {
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const test: any = decorateEncryptionMaterial({
suite,
keyringTrace: [],
hasUnencryptedDataKey: true,
} as any)
const edk = new EncryptedDataKey({
providerId: 'p',
providerInfo: 'p',
encryptedDataKey: new Uint8Array(3),
})
test.addEncryptedDataKey(
edk,
KeyringTraceFlag.WRAPPING_KEY_ENCRYPTED_DATA_KEY
)
expect(test.encryptedDataKeys).to.have.length(1)
expect(test.encryptedDataKeys[0] === edk).to.equal(true)
})
it('add SignatureKey', () => {
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256
)
const test: any = decorateEncryptionMaterial({
suite,
keyringTrace: [],
} as any)
const key = new SignatureKey(new Uint8Array(3), new Uint8Array(3), suite)
test.setSignatureKey(key)
expect(test.signatureKey === key).to.equal(true)
})
it('Precondition: If a data key has not already been generated, there must be no EDKs.', () => {
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const edk = new EncryptedDataKey({
providerId: 'p',
providerInfo: 'p',
encryptedDataKey: new Uint8Array(3),
})
const test: any = decorateEncryptionMaterial({
suite,
keyringTrace: [],
hasUnencryptedDataKey: false,
} as any)
expect(() =>
test.addEncryptedDataKey(
edk,
KeyringTraceFlag.WRAPPING_KEY_ENCRYPTED_DATA_KEY
)
).to.throw()
})
it('Precondition: Edk must be EncryptedDataKey', () => {
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const edk: any = {}
const test: any = decorateEncryptionMaterial({
suite,
keyringTrace: [],
} as any)
expect(() =>
test.addEncryptedDataKey(
edk,
KeyringTraceFlag.WRAPPING_KEY_ENCRYPTED_DATA_KEY
)
).to.throw()
})
it('Precondition: flags must indicate that the key was encrypted.', () => {
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const test: any = decorateEncryptionMaterial({
suite,
keyringTrace: [],
hasUnencryptedDataKey: true,
} as any)
const edk = new EncryptedDataKey({
providerId: 'p',
providerInfo: 'p',
encryptedDataKey: new Uint8Array(3),
})
expect(() =>
test.addEncryptedDataKey(
edk,
KeyringTraceFlag.WRAPPING_KEY_SIGNED_ENC_CTX
)
).to.throw('Encrypted data key flag must be set.')
})
it('Precondition: flags must not include a setFlag or a decrypt flag.', () => {
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const test: any = decorateEncryptionMaterial({
suite,
keyringTrace: [],
hasUnencryptedDataKey: true,
} as any)
const edk = new EncryptedDataKey({
providerId: 'p',
providerInfo: 'p',
encryptedDataKey: new Uint8Array(3),
})
expect(() =>
test.addEncryptedDataKey(
edk,
KeyringTraceFlag.WRAPPING_KEY_ENCRYPTED_DATA_KEY |
KeyringTraceFlag.WRAPPING_KEY_VERIFIED_ENC_CTX
)
).to.throw('Invalid flag for EncryptedDataKey.')
})
it('Precondition: The SignatureKey stored must agree with the algorithm specification.', () => {
const suiteWithSig = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384
)
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const key = new SignatureKey(
new Uint8Array(3),
new Uint8Array(3),
suiteWithSig
)
const test: any = decorateEncryptionMaterial({
suite,
keyringTrace: [],
} as any)
expect(() => test.setSignatureKey(key)).to.throw()
})
it('Precondition: signatureKey must not be set. Modifying the signatureKey is denied.', () => {
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256
)
const key = new SignatureKey(new Uint8Array(3), new Uint8Array(3), suite)
const test: any = decorateEncryptionMaterial({
suite,
keyringTrace: [],
} as any)
test.setSignatureKey(key)
expect(() => test.setSignatureKey(key)).to.throw()
})
it('Precondition: key must be a SignatureKey.', () => {
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256
)
const key: any = {}
const test: any = decorateEncryptionMaterial({
suite,
keyringTrace: [],
} as any)
expect(() => test.setSignatureKey(key)).to.throw()
})
it('Precondition: The SignatureKey requested must agree with the algorithm specification.', () => {
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256
)
const test: any = decorateEncryptionMaterial({
suite,
keyringTrace: [],
} as any)
expect(() => test.signatureKey).to.throw()
})
})
describe('decorateDecryptionMaterial', () => {
it('will decorate', () => {
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const test: any = decorateDecryptionMaterial({
suite,
keyringTrace: [],
} as any)
expect(test)
.to.haveOwnProperty('setVerificationKey')
.and.to.be.a('function')
expect(test).to.haveOwnProperty('verificationKey').and.to.equal(undefined)
})
it('add VerificationKey', () => {
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256
)
const test: any = decorateDecryptionMaterial({
suite,
keyringTrace: [],
} as any)
const key = new VerificationKey(new Uint8Array(3), suite)
test.setVerificationKey(key)
expect(test.verificationKey === key).to.equal(true)
})
it('Precondition: The VerificationKey stored must agree with the algorithm specification.', () => {
const suiteWithSig = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384
)
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const key = new VerificationKey(new Uint8Array(3), suiteWithSig)
const test: any = decorateDecryptionMaterial({
suite,
keyringTrace: [],
} as any)
expect(() => test.setVerificationKey(key)).to.throw()
})
it('Precondition: verificationKey must not be set. Modifying the verificationKey is denied.', () => {
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256
)
const key = new VerificationKey(new Uint8Array(3), suite)
const test: any = decorateDecryptionMaterial({
suite,
keyringTrace: [],
} as any)
test.setVerificationKey(key)
expect(() => test.setVerificationKey(key)).to.throw()
})
it('Precondition: key must be a VerificationKey.', () => {
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256
)
const key: any = {}
const test: any = decorateDecryptionMaterial({
suite,
keyringTrace: [],
} as any)
expect(() => test.setVerificationKey(key)).to.throw()
})
it('Precondition: The VerificationKey requested must agree with the algorithm specification.', () => {
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256
)
const test: any = decorateDecryptionMaterial({
suite,
keyringTrace: [],
} as any)
expect(() => test.verificationKey).to.throw()
})
})
describe('decorateWebCryptoMaterial', () => {
it('add CryptoKey', () => {
const suite = new WebCryptoAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256
)
const test: any = decorateWebCryptoMaterial(
{ suite, keyringTrace: [] } as any,
KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY
)
// setCryptoKey uses `zeroUnencryptedDataKey` when setting a cryptoKey *without* a unencrypted data key
decorateCryptographicMaterial(
test,
KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY
)
test.validUsages = ['deriveKey']
const key: any = {
type: 'secret',
algorithm: { name: 'HKDF' },
usages: ['deriveKey'],
extractable: false,
}
const trace = {
keyNamespace: 'k',
keyName: 'k',
flags: KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY,
}
test.setCryptoKey(key, trace)
expect(test.getCryptoKey() === key).to.equal(true)
expect(test.hasCryptoKey).to.equal(true)
expect(test.hasUnencryptedDataKey).to.equal(false)
})
it('add MixedBackendCryptoKey', () => {
const suite = new WebCryptoAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256
)
const test: any = decorateWebCryptoMaterial(
{ suite, keyringTrace: [] } as any,
KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY
)
test.validUsages = ['deriveKey']
// setCryptoKey uses `zeroUnencryptedDataKey` when setting a cryptoKey *without* a unencrypted data key
decorateCryptographicMaterial(
test,
KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY
)
const key: any = {
type: 'secret',
algorithm: { name: 'HKDF' },
usages: ['deriveKey'],
extractable: false,
}
const mixedKey: any = { zeroByteCryptoKey: key, nonZeroByteCryptoKey: key }
const trace = {
keyNamespace: 'k',
keyName: 'k',
flags: KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY,
}
test.setCryptoKey(mixedKey, trace)
expect(test.getCryptoKey() !== mixedKey).to.equal(true)
expect(test.hasCryptoKey).to.equal(true)
expect(test.hasUnencryptedDataKey).to.equal(false)
expect(
test.getCryptoKey().zeroByteCryptoKey === mixedKey.zeroByteCryptoKey
).to.equal(true)
expect(
test.getCryptoKey().nonZeroByteCryptoKey === mixedKey.nonZeroByteCryptoKey
).to.equal(true)
expect(Object.isFrozen(test.getCryptoKey())).to.equal(true)
})
it('Precondition: The cryptoKey must be set before we can return it.', () => {
const test: any = decorateWebCryptoMaterial(
{} as any,
KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY
)
expect(() => test.getCryptoKey()).to.throw()
})
it('Precondition: cryptoKey must not be set. Modifying the cryptoKey is denied', () => {
const suite = new WebCryptoAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256
)
const test: any = decorateWebCryptoMaterial(
{ suite, keyringTrace: [] } as any,
KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY
)
test.validUsages = ['deriveKey']
// setCryptoKey uses `zeroUnencryptedDataKey` when setting a cryptoKey *without* a unencrypted data key
decorateCryptographicMaterial(
test,
KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY
)
const key: any = {
type: 'secret',
algorithm: { name: 'HKDF' },
usages: ['deriveKey'],
extractable: false,
}
const trace = {
keyNamespace: 'k',
keyName: 'k',
flags: KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY,
}
test.setCryptoKey(key, trace)
expect(() => test.setCryptoKey(key, trace)).to.throw()
})
it('Precondition: The CryptoKey must match the algorithm suite specification.', () => {
const test: any = decorateWebCryptoMaterial(
{} as any,
KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY
)
const key: any = {
type: 'secret',
algorithm: { name: 'HKDF' },
usages: ['deriveKey'],
extractable: true,
}
const key1: any = {
zeroByteCryptoKey: {
type: 'secret',
algorithm: { name: 'HKDF' },
usages: ['deriveKey'],
extractable: true,
},
nonZeroByteCryptoKey: {
type: 'secret',
algorithm: { name: 'HKDF' },
usages: ['deriveKey'],
extractable: false,
},
}
const key2: any = {
zeroByteCryptoKey: {
type: 'secret',
algorithm: { name: 'HKDF' },
usages: ['deriveKey'],
extractable: false,
},
nonZeroByteCryptoKey: {
type: 'secret',
algorithm: { name: 'HKDF' },
usages: ['deriveKey'],
extractable: true,
},
}
const trace = {
keyNamespace: 'k',
keyName: 'k',
flags: KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY,
}
expect(() => test.setCryptoKey(key, trace)).to.throw()
expect(() => test.setCryptoKey(key1, trace)).to.throw()
expect(() => test.setCryptoKey(key2, trace)).to.throw()
})
it('Precondition: If the CryptoKey is the only version, the trace information must be set here.', () => {
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256
)
const test: any = decorateWebCryptoMaterial(
{ suite, validUsages: ['deriveKey'], keyringTrace: [] } as any,
KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY
)
decorateCryptographicMaterial(
test,
KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY
)
const key: any = {
type: 'secret',
algorithm: { name: 'HKDF' },
usages: ['deriveKey'],
extractable: false,
}
expect(() =>
test.setCryptoKey(key, {
keyNamespace: 'k',
flags: KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY,
})
).to.throw('Malformed KeyringTrace')
expect(() =>
test.setCryptoKey(key, {
keyName: 'k',
flags: KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY,
})
).to.throw('Malformed KeyringTrace')
expect(() => test.setCryptoKey(key)).to.throw('Malformed KeyringTrace')
})
it('Precondition: On setting the CryptoKey the required KeyringTraceFlag must be set.', () => {
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256
)
const test: any = decorateWebCryptoMaterial(
{ suite, validUsages: ['deriveKey'], keyringTrace: [] } as any,
KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY
)
decorateCryptographicMaterial(
test,
KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY
)
const key: any = {
type: 'secret',
algorithm: { name: 'HKDF' },
usages: ['deriveKey'],
extractable: false,
}
const trace = {
keyNamespace: 'k',
keyName: 'k',
flags: KeyringTraceFlag.WRAPPING_KEY_SIGNED_ENC_CTX,
}
expect(() => test.setCryptoKey(key, trace)).to.throw(
'Required KeyringTraceFlag not set'
)
})
it('Precondition: dataKey must be a supported type.', () => {
const test: any = decorateWebCryptoMaterial(
{} as any,
KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY
)
const key: any = {}
const trace = {
keyNamespace: 'k',
keyName: 'k',
flags: KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY,
}
expect(() => test.setCryptoKey(key, trace)).to.throw()
})
})
describe('decorateWebCryptoMaterial:Helpers', () => {
describe('subtleFunctionForMaterial', () => {
it('WebCryptoDecryptionMaterial is decrypt', () => {
const suite = new WebCryptoAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256
)
const material = new WebCryptoDecryptionMaterial(suite, {})
expect(subtleFunctionForMaterial(material)).to.equal('decrypt')
})
it('WebCryptoEncryptionMaterial is encrypt', () => {
const suite = new WebCryptoAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256
)
const material = new WebCryptoEncryptionMaterial(suite, {})
expect(subtleFunctionForMaterial(material)).to.equal('encrypt')
})
it('unsupported', () => {
const material = {} as any
expect(() => subtleFunctionForMaterial(material)).to.throw()
})
})
describe('keyUsageForMaterial', () => {
it('ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256 is deriveKey', () => {
const suite = new WebCryptoAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256
)
const material = new WebCryptoDecryptionMaterial(suite, {})
expect(keyUsageForMaterial(material)).to.equal('deriveKey')
})
it('ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256 is decrypt', () => {
const suite = new WebCryptoAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256
)
const material = new WebCryptoEncryptionMaterial(suite, {})
expect(keyUsageForMaterial(material)).to.equal('deriveKey')
})
it('WebCryptoDecryptionMaterial is decrypt', () => {
const suite = new WebCryptoAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const material = new WebCryptoDecryptionMaterial(suite, {})
expect(keyUsageForMaterial(material)).to.equal('decrypt')
})
it('WebCryptoEncryptionMaterial is encrypt', () => {
const suite = new WebCryptoAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const material = new WebCryptoEncryptionMaterial(suite, {})
expect(keyUsageForMaterial(material)).to.equal('encrypt')
})
it('unsupported', () => {
const material = {} as any
expect(() => keyUsageForMaterial(material)).to.throw()
})
})
it('isCryptoKey', () => {
const key: any = {
type: 'secret',
algorithm: { name: 'HKDF' },
usages: ['deriveKey'],
extractable: false,
}
expect(isCryptoKey(key)).to.equal(true)
})
describe('isValidCryptoKey', () => {
it('Suite with KDF is valid for both the derivable key and the derived key', () => {
const suite = new WebCryptoAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256
)
const material = new WebCryptoEncryptionMaterial(suite, {})
const keyKdf: any = {
type: 'secret',
algorithm: { name: suite.kdf },
usages: ['deriveKey'],
extractable: false,
}
const deriveKey: any = {
type: 'secret',
algorithm: { name: suite.encryption, length: suite.keyLength },
usages: ['encrypt'],
extractable: false,
}
expect(isValidCryptoKey(keyKdf, material)).to.equal(true)
expect(isValidCryptoKey(deriveKey, material)).to.equal(true)
})
it('Suite without the KDF is only derivable with the key', () => {
const suite = new WebCryptoAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const material = new WebCryptoEncryptionMaterial(suite, {})
const keyKdf: any = {
type: 'secret',
algorithm: { name: 'HKDF' },
usages: ['deriveKey'],
extractable: false,
}
const key: any = {
type: 'secret',
algorithm: { name: suite.encryption, length: suite.keyLength },
usages: ['encrypt'],
extractable: false,
}
expect(isValidCryptoKey(keyKdf, material)).to.equal(false)
expect(isValidCryptoKey(key, material)).to.equal(true)
})
it('only type === secret is valid', () => {
const suite = new WebCryptoAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const material = new WebCryptoEncryptionMaterial(suite, {})
const key: any = {
type: 'private',
algorithm: { name: suite.encryption, length: suite.keyLength },
usages: ['encrypt'],
extractable: false,
}
expect(isValidCryptoKey(key, material)).to.equal(false)
})
it('length must match', () => {
const suite = new WebCryptoAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const material = new WebCryptoEncryptionMaterial(suite, {})
const key: any = {
type: 'secret',
algorithm: { name: suite.encryption, length: suite.keyLength - 1 },
usages: ['encrypt'],
extractable: false,
}
expect(isValidCryptoKey(key, material)).to.equal(false)
})
it('can not be extractable', () => {
const suite = new WebCryptoAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const material = new WebCryptoEncryptionMaterial(suite, {})
const key: any = {
type: 'secret',
algorithm: { name: suite.encryption, length: suite.keyLength },
usages: ['encrypt'],
extractable: true,
}
expect(isValidCryptoKey(key, material)).to.equal(false)
})
it('usage must match', () => {
const suite = new WebCryptoAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const material = new WebCryptoEncryptionMaterial(suite, {})
const key: any = {
type: 'secret',
algorithm: { name: suite.encryption, length: suite.keyLength },
usages: ['decrypt'],
extractable: false,
}
expect(isValidCryptoKey(key, material)).to.equal(false)
})
})
})
describe('NodeEncryptionMaterial', () => {
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const test: any = new NodeEncryptionMaterial(suite, {})
it('instance is frozen', () => expect(Object.isFrozen(test)).to.equal(true))
it('has a suite', () => expect(test.suite === suite).to.equal(true))
it('class is frozen', () =>
expect(Object.isFrozen(NodeAlgorithmSuite)).to.equal(true))
it('class prototype is frozen', () =>
expect(Object.isFrozen(NodeAlgorithmSuite.prototype)).to.equal(true))
it('Precondition: NodeEncryptionMaterial suite must be NodeAlgorithmSuite.', () => {
const suite: any = new WebCryptoAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
expect(() => new NodeEncryptionMaterial(suite, {})).to.throw()
})
it('Precondition: NodeEncryptionMaterial encryptionContext must be an object, even if it is empty.', () => {
expect(() => new NodeEncryptionMaterial(suite, undefined as any)).to.throw()
expect(() => new NodeEncryptionMaterial(suite, true as any)).to.throw()
})
})
describe('NodeDecryptionMaterial', () => {
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const test: any = new NodeDecryptionMaterial(suite, {})
it('instance is frozen', () => expect(Object.isFrozen(test)).to.equal(true))
it('has a suite', () => expect(test.suite === suite).to.equal(true))
it('class is frozen', () =>
expect(Object.isFrozen(NodeAlgorithmSuite)).to.equal(true))
it('class prototype is frozen', () =>
expect(Object.isFrozen(NodeAlgorithmSuite.prototype)).to.equal(true))
it('Precondition: NodeDecryptionMaterial suite must be NodeAlgorithmSuite.', () => {
const suite: any = new WebCryptoAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
expect(() => new NodeDecryptionMaterial(suite, {})).to.throw()
})
it('Precondition: NodeDecryptionMaterial encryptionContext must be an object, even if it is empty.', () => {
expect(() => new NodeDecryptionMaterial(suite, undefined as any)).to.throw()
expect(() => new NodeDecryptionMaterial(suite, true as any)).to.throw()
})
})
describe('WebCryptoEncryptionMaterial', () => {
const suite = new WebCryptoAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const test: any = new WebCryptoEncryptionMaterial(suite, {})
it('instance is frozen', () => expect(Object.isFrozen(test)).to.equal(true))
it('has a suite', () => expect(test.suite === suite).to.equal(true))
it('class is frozen', () =>
expect(Object.isFrozen(WebCryptoAlgorithmSuite)).to.equal(true))
it('class prototype is frozen', () =>
expect(Object.isFrozen(WebCryptoAlgorithmSuite.prototype)).to.equal(true))
it('Precondition: WebCryptoEncryptionMaterial suite must be WebCryptoAlgorithmSuite.', () => {
const suite: any = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
expect(() => new WebCryptoEncryptionMaterial(suite, {})).to.throw()
})
it('Precondition: WebCryptoEncryptionMaterial encryptionContext must be an object, even if it is empty.', () => {
expect(
() => new WebCryptoEncryptionMaterial(suite, undefined as any)
).to.throw()
expect(() => new WebCryptoEncryptionMaterial(suite, true as any)).to.throw()
})
})
describe('WebCryptoDecryptionMaterial', () => {
const suite = new WebCryptoAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const test: any = new WebCryptoDecryptionMaterial(suite, {})
it('instance is frozen', () => expect(Object.isFrozen(test)).to.equal(true))
it('has a suite', () => expect(test.suite === suite).to.equal(true))
it('class is frozen', () =>
expect(Object.isFrozen(WebCryptoAlgorithmSuite)).to.equal(true))
it('class prototype is frozen', () =>
expect(Object.isFrozen(WebCryptoAlgorithmSuite.prototype)).to.equal(true))
it('Precondition: WebCryptoDecryptionMaterial suite must be WebCryptoAlgorithmSuite.', () => {
const suite: any = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
expect(() => new WebCryptoDecryptionMaterial(suite, {})).to.throw()
})
it('Precondition: WebCryptoDecryptionMaterial encryptionContext must be an object, even if it is empty.', () => {
expect(
() => new WebCryptoDecryptionMaterial(suite, undefined as any)
).to.throw()
expect(() => new WebCryptoDecryptionMaterial(suite, true as any)).to.throw()
})
})
describe('KeyObject support', () => {
it('supportsKeyObject tracks values of crypto module', () => {
// supportsKeyObject should track the createSecretKey value...
expect(!!supportsKeyObject === !!createSecretKey).to.equal(true)
})
if (supportsKeyObject) {
const { KeyObject, createSecretKey } = supportsKeyObject
describe('wrapWithKeyObjectIfSupported', () => {
it('Uint8Array are wrapped in a KeyObject if supported', () => {
const test = wrapWithKeyObjectIfSupported(new Uint8Array(16))
expect(test).to.be.instanceOf(KeyObject)
})
it('KeyObject are return unchanged', () => {
const dataKey = createSecretKey(new Uint8Array(16))
expect(dataKey === wrapWithKeyObjectIfSupported(dataKey)).to.equal(true)
})
it('throws for unsupported types', () => {
expect(() => wrapWithKeyObjectIfSupported({} as any)).to.throw(
'Unsupported dataKey type'
)
})
it('Postcondition: Zero the secret. It is now inside the KeyObject.', () => {
const dataKey = new Uint8Array(16).fill(1)
wrapWithKeyObjectIfSupported(dataKey)
expect(dataKey).to.deep.equal(new Uint8Array(16).fill(0))
})
})
describe('unwrapDataKey', () => {
it('returns Uint8Array unmodified', () => {
const dataKey = new Uint8Array(16).fill(1)
const test = unwrapDataKey(dataKey)
expect(test === dataKey).to.equal(true)
})
it('exports the secret key', () => {
const rawKey = new Uint8Array(16).fill(1)
const dataKey = createSecretKey(rawKey)
const test = unwrapDataKey(dataKey)
expect(test).to.deep.equal(rawKey)
})
it('throws for unsupported types', () => {
expect(() => unwrapDataKey({} as any)).to.throw(
'Unsupported dataKey type'
)
})
})
} else {
describe('wrapWithKeyObjectIfSupported', () => {
it('Uint8Array are returned unchanged', () => {
const dataKey = new Uint8Array(16)
const test = wrapWithKeyObjectIfSupported(dataKey)
expect(test).to.be.instanceOf(Uint8Array)
expect(test === dataKey).to.equal(true)
})
it('throws for unsupported types', () => {
expect(() => wrapWithKeyObjectIfSupported({} as any)).to.throw(
'Unsupported dataKey type'
)
})
})
describe('unwrapDataKey', () => {
it('returns Uint8Array unmodified', () => {
const dataKey = new Uint8Array(16).fill(1)
const test = unwrapDataKey(dataKey)
expect(test === dataKey).to.equal(true)
})
it('throws for unsupported types', () => {
expect(() => unwrapDataKey({} as any)).to.throw(
'Unsupported dataKey type'
)
})
})
}
}) | the_stack |
import Transaction from "./transaction";
import { Database, tuple, TupleItem, util } from ".";
import { Transformer, defaultTransformer } from "./transformer";
import { TransactionOptionCode } from "./opts.g";
import { concat2, startsWith, strInc, asBuf } from "./util";
import Subspace, { root } from "./subspace";
import { inspect } from "util";
import { NativeValue, NativeTransaction } from "./native";
// import FDBError from './error'
export class DirectoryError extends Error {
constructor(description: string) {
super(description)
Object.setPrototypeOf(this, DirectoryError.prototype);
// Error.captureStackTrace(this, this.constructor);
}
}
// The directory layer provides a way to use key subspaces without needing to
// make increasingly longer key prefixes over time.
// Every application should put its data inside a directory.
// For more information see the developer guide:
// https://apple.github.io/foundationdb/developer-guide.html#directories
// Or this great write-up of how and why the HCA allocator works:
// https://activesphere.com/blog/2018/08/05/high-contention-allocator
type DbAny = Database<any, any, any, any>
type TxnAny = Transaction<any, any, any, any>
type SubspaceAny = Subspace<any, any, any, any>
type TupleIn = undefined | TupleItem | TupleItem[]
/** Node subspaces have tuple keys like [SUBDIRS, (bytes)] and [b'layer']. */
type NodeSubspace = Subspace<TupleIn, TupleItem[], NativeValue, Buffer>
const BUF_EMPTY = Buffer.alloc(0)
const arrStartsWith = <T>(arr: T[], prefix: T[]): boolean => {
if (arr.length < prefix.length) return false
for (let i = 0; i < prefix.length; i++) {
if (arr[i] !== prefix[i]) return false
}
return true
}
const arrEq = <T>(x: T[], y: T[]): boolean => {
if (x.length !== y.length) return false
for (let i = 0; i < y.length; i++) {
if (x[i] !== y[i]) return false
}
return true
}
// Wrapper for functions which take a database or a transaction.
const doTxn = <KeyIn, KeyOut, ValIn, ValOut, T>(
dbOrTxn: Database<KeyIn, KeyOut, ValIn, ValOut> | Transaction<KeyIn, KeyOut, ValIn, ValOut>,
body: (tn: Transaction<KeyIn, KeyOut, ValIn, ValOut>) => Promise<T>): Promise<T> => {
return (dbOrTxn instanceof Database) ? dbOrTxn.doTn(body) : body(dbOrTxn)
}
// Technically the counter encoding supports 64 bit numbers. We'll only support
// numbers in the JS safe range (up to 2^53) but thats honestly gonna be fine.
// Consider exporting this via transformer.
//
// Only exported for testing.
export const counterEncoding: Transformer<number, number> = {
pack(val) {
const b = Buffer.alloc(8)
if (!Number.isSafeInteger(val)) throw new DirectoryError('Invalid counter (number outside JS safe range)')
// If we're using node 12+ everywhere we could just call this:
//b.writeBigUInt64LE(BigInt(val))
const lowBits = (val & 0xffffffff) >>> 0
const highBits = ((val - lowBits) / 0x100000000) >>> 0
b.writeUInt32LE(lowBits, 0) // low
b.writeUInt32LE(highBits, 4) // high
return b
},
unpack: (buf) => {
const val = buf.readUInt32LE(0) + (buf.readUInt32LE(4) * 0x100000000)
if (!Number.isSafeInteger(val)) throw new DirectoryError('Invalid counter (number outside JS safe range)')
return val
},
}
const voidEncoding: Transformer<void, void> = {
pack(val) { return BUF_EMPTY },
unpack(buf) { return null }
}
type Version = [number, number, number]
// I really wish I could just use python's pack here. This is <III written out
// in long form. (And counterEncoding above is <q). I could use a module like
// https://www.npmjs.com/package/python-struct , but it feels like overkill for
// this.
const versionEncoder: Transformer<Version, Version> = {
pack(ver) {
const buf = Buffer.alloc(12)
buf.writeUInt32LE(ver[0], 0)
buf.writeUInt32LE(ver[1], 4)
buf.writeUInt32LE(ver[2], 8)
return buf
},
unpack(buf) {
return [buf.readUInt32LE(0), buf.readUInt32LE(4), buf.readUInt32LE(8)]
}
}
const window_size = (start: number) => (
// From the python bindings:
// Larger window sizes are better for high contention, smaller sizes for
// keeping the keys small. But if there are many allocations, the keys
// can't be too small. So start small and scale up. We don't want this
// to ever get *too* big because we have to store about window_size/2
// recent items.
start < 255 ? 64
: (start < 65535) ? 1024
: 8192
)
const hcaLock = new WeakMap<NativeTransaction, Promise<void>>()
async function synchronized(tn: TxnAny, block: () => Promise<void>) {
// Nodejs is single threaded and the FDB transaction system protects us
// against multiple concurrent transactions allocating using the HCA.
// Unfortunately, we still need to protect against the case where a single
// transaction initiates multiple concurrent calls into HCA (using
// Promise.all / race or similar).
// We're using tn._tn because that references the underlying fdb transaction
// object, shared between all scoped versions of the transaction.
const ref = tn._tn
const lock = hcaLock.get(ref)
const nextStep = lock != null
? lock.then(block) // Run next
: block() // Run now
hcaLock.set(ref, nextStep)
await nextStep
// We're using a WeakMap so the GC *should* take care of this, but ...
if (hcaLock.get(ref) === nextStep) hcaLock.delete(ref)
}
// Exported for testing.
export class HighContentionAllocator {
// db: Database<any, any, any, any>
counters: Subspace<TupleIn, TupleItem[], number, number>
recent: Subspace<TupleIn, TupleItem[], void, void> // The value here will always be BUF_EMPTY.
constructor(subspace: SubspaceAny) {
// this.db = db.withKeyEncoding(tuple) //.at([counters, recent])
this.counters = subspace.withKeyEncoding(tuple).at(0).withValueEncoding(counterEncoding)
this.recent = subspace.withKeyEncoding(tuple).at(1).withValueEncoding(voidEncoding)
}
// For debugging.
async _debugGetInternalState(dbOrTxn: DbAny | TxnAny) {
return await doTxn(dbOrTxn, async txn => ({
counters: (await txn.at(this.counters).getRangeAllStartsWith(undefined))
.map(([[start], count]) => ({start, count}))[0],
recent: (await txn.at(this.recent).getRangeAllStartsWith(undefined))
.map(([[k]]) => k)
}))
}
async allocate(_tn: TxnAny): Promise<Buffer> {
// Counters stores the number of allocations in each window.
const counters = _tn.at(this.counters)
// Recent marks all allocations inside the current window.
const recent = _tn.at(this.recent)
// This logic is a direct port of the equivalent code in the ruby bindings.
// const snap = tn.snapshot()
while (true) {
let [[start], count] = (await counters.snapshot().getRangeAllStartsWith(undefined, {limit: 1, reverse: true}))[0] as [[number], number]
|| [[0],0]
let window_advanced = false
let window
// 1. Consider growing the window if the count has changed the window size.
while (true) {
// TODO: I think we can narrow this synchronized block to the
// window_advanced logic, but I'm not game to change it before we have
// tests that can spot the bug. Maybe the binding tester can assess this
// change.
await synchronized(_tn, async () => {
// This logic makes more sense at the bottom of the enclosing while
// block, but its here so we don't need to do two synchronized blocks.
if (window_advanced) {
counters.clearRange([], start)
recent.setOption(TransactionOptionCode.NextWriteNoWriteConflictRange)
recent.clearRange([], start)
}
counters.add(start, 1)
count = (await counters.snapshot().get(start))!
// console.log('incremented count to', count)
})
window = window_size(start)
// Almost all the time, the window is a reasonable size and we break here.
if (count * 2 < window) break
// But if we've run out of room in the window (fill >= 50%), discard the
// window and increment the window start by the window size.
start += window
window_advanced = true
}
// 2. Look for a candidate name we can allocate
while (true) {
let candidate = start + Math.floor(Math.random() * window)
let latest_counter: any[]
let candidate_in_use: boolean
// Again, not sure if this synchronized block is needed.
await synchronized(_tn, async () => {
latest_counter = (await counters.snapshot().getRangeAllStartsWith(undefined, {limit: 1, reverse: true})).map(([k]) => k)
candidate_in_use = await recent.exists(candidate)
// Take ownership of the candidate key, but there's no need to retry
// the whole txn if another allocation call has claimed it.
recent.setOption(TransactionOptionCode.NextWriteNoWriteConflictRange)
recent.set(candidate)
})
// If the window size changes concurrently while we're allocating, restart the whole process.
if (latest_counter!.length > 0 && latest_counter![0] > start) break
if (candidate_in_use! === false) {
// Hooray! The candidate key isn't used by anyone else. Tag and bag! Marking it as a write conflict key stops
recent.addWriteConflictKey(candidate)
return tuple.pack(candidate)
}
}
}
}
}
const DEFAULT_NODE_PREFIX = Buffer.from([0xfe])
const HCA_PREFIX = Buffer.from('hca', 'ascii')
const VERSION_KEY = Buffer.from('version', 'ascii')
const LAYER_KEY = Buffer.from('layer', 'ascii')
const PARTITION_BUF = Buffer.from('partition', 'ascii') // I hate this.
const SUBDIRS_KEY = 0 // Why is this 0 when version / layers are byte strings? I have no idea. History, I assume.
const EXPECTED_VERSION: Version = [1, 0, 0]
type PathIn = string | string[] | null | undefined
type Path = string[]
// Clean up whatever junk the user gives us. I ordinarily wouldn't do this but
// its consistent with the python and ruby bindings.
const normalize_path = (path: PathIn): Path => {
return path == null
? []
: Array.isArray(path)
? path
: [path]
// if (!Array.isArray(path)) path = [path]
// for (let i = 0; i < path.length; i++) {
// if (typeof path[i] !== 'string') path[i] = path[i].toString()
// }
// return path as string[]
}
// Ugh why is this called 'node'?? The word 'node' is used throughout this file
// interchangably to mean a 'Node' (instance of this node class) or a node in
// the directory graph, represented by a subspace element representing directory
// metadata inside the node_root subspace. Its super confusing.
//
// This class is also *awful*. It has 3 states:
// - The target doesn't exist - in which case subspace is null
// - The target exists but metadata (the layer) hasn't been loaded. subspace
// exists but layer is null
// - The target exists and metadata has been loaded.
class Node {
// Frankly, I don't think this deserves a class all of its own, but this whole
// file is complex enough, so I'm going to stick to a pretty straight
// reimplementation of the python / ruby code here.
subspace: NodeSubspace | null
path: Path
target_path: Path
// The layer should be defined as a string, but the binding tester insists on
// testing this with binary buffers which are invalid inside a string, so
// we'll use buffers internally and expose an API accepting either. Sigh.
layer: Buffer | null // Filled in lazily. Careful - this will most often be empty.
constructor(subspace: NodeSubspace | null, path: Path, targetPath: Path) {
this.subspace = subspace
this.path = path
this.target_path = targetPath
this.layer = null
}
exists(): boolean {
return this.subspace != null
}
async prefetchMetadata(txn: TxnAny) {
if (this.exists() && this.layer == null) await this.getLayer(txn)
return this
}
async getLayer(txn?: TxnAny) {
if (this.layer == null) {
// txn && console.log('key', txn!.at(this.subspace!).packKey(LAYER_KEY))
// if (txn) console.log('xxx', (await txn.at(this.subspace!).get(LAYER_KEY)), this.path, this.target_path)
// There's a semi-bug in the upstream code where layer won't be specified
// on the root of the directory structure (thats the only directory which
// has an implicit layer).
//
// What should the implicit layer be? The other bindings leave it as '',
// even though its kinda a directory partition, so it probably should be
// 'partition'.
if (txn) this.layer = (await txn.at(this.subspace!).get(LAYER_KEY)) || BUF_EMPTY
else throw new DirectoryError('Layer has not been read')
}
return this.layer!
}
isInPartition(includeEmptySubpath: boolean = false) {
return this.exists()
&& this.layer && this.layer.equals(PARTITION_BUF)
&& (includeEmptySubpath || this.target_path.length > this.path.length)
}
getPartitionSubpath() {
return this.target_path.slice(this.path.length)
}
async getContents(directoryLayer: DirectoryLayer, txn?: TxnAny) {
return this.subspace == null ? null : directoryLayer._contentsOfNode(this.subspace, this.path, await this.getLayer(txn))
}
getContentsSync(directoryLayer: DirectoryLayer) {
if (this.layer == null) throw new DirectoryError('Node metadata has not been fetched.')
return this.subspace == null ? null : directoryLayer._contentsOfNode(this.subspace, this.path, this.layer!)
}
}
// A directory is either a 'normal' directory or a directory partition.
// Partitions contain a separate directory layer inline into which the children
// are allocated.
// More on partitions: https://apple.github.io/foundationdb/developer-guide.html#directory-partitions
export class Directory<KeyIn = NativeValue, KeyOut = Buffer, ValIn = NativeValue, ValOut = Buffer> {
/** The full path of the directory from the root */
_path: Path
_directoryLayer: DirectoryLayer
_layer: Buffer | null
content: Subspace<KeyIn, KeyOut, ValIn, ValOut>
// If the directory is a partition, it also has a reference to the parent subspace.
_parentDirectoryLayer?: DirectoryLayer
constructor(parentDirectoryLayer: DirectoryLayer, path: Path, contentSubspace: Subspace<KeyIn, KeyOut, ValIn, ValOut>, isPartition: boolean, layer?: NativeValue) {
this._path = path
this.content = contentSubspace
if (isPartition) {
if (layer != null) throw new DirectoryError('Directory partitions cannot specify a layer.')
// In partitions, the passed directory layer is the parent directory
// layer. We create our own internally inside the partition.
const directoryLayer = new DirectoryLayer({
nodeSubspace: contentSubspace.atRaw(DEFAULT_NODE_PREFIX).withKeyEncoding(tuple).withValueEncoding(defaultTransformer),
contentSubspace: contentSubspace,
})
directoryLayer._path = path
// super(directoryLayer, path, subspace, 'partition')
this._layer = PARTITION_BUF
this._directoryLayer = directoryLayer
this._parentDirectoryLayer = parentDirectoryLayer
} else {
this._layer = layer ? asBuf(layer) : null
this._directoryLayer = parentDirectoryLayer
// this._parentDirectoryLayer is left as undefined for normal directories.
}
}
getSubspace() {
// Soooo I'm not entirely sure this is the right behaviour. The partition
// itself should be read-only - that is, you shouldn't be inserting your own
// children inside the directory partition. That said, one of the uses of a
// directory partition is in being able to do a single range query to fetch
// all children - and by refusing to return a subspace here we're making it
// hard to run those queries.
//
// Refusing getSubspace() calls on directory partitions is the safe option
// here from an API standpoint. I'll consider relaxing this constraint if
// people complain about it.
if (this.isPartition()) throw new DirectoryError('Cannot use a directory partition as a subspace.')
else return this.content
}
// TODO: Add withKeyEncoding / withValueEncoding here.
createOrOpen(txnOrDb: TxnAny | DbAny, path: PathIn, layer?: 'partition' | NativeValue) { // partition specified for autocomplete.
return this._directoryLayer.createOrOpen(txnOrDb, this._partitionSubpath(path), layer)
}
open(txnOrDb: TxnAny | DbAny, path: PathIn, layer?: 'partition' | NativeValue) {
return this._directoryLayer.open(txnOrDb, this._partitionSubpath(path), layer)
}
create(txnOrDb: TxnAny | DbAny, path: PathIn, layer?: 'partition' | NativeValue, prefix?: Buffer) {
return this._directoryLayer.create(txnOrDb, this._partitionSubpath(path), layer, prefix)
}
async *list(txn: TxnAny, path: PathIn = []) {
yield *this._directoryLayer.list(txn, this._partitionSubpath(path))
}
listAll(txnOrDb: TxnAny | DbAny, path: PathIn = []): Promise<Buffer[]> {
return this._directoryLayer.listAll(txnOrDb, this._partitionSubpath(path))
}
move(txnOrDb: TxnAny | DbAny, oldPath: PathIn, newPath: PathIn) {
return this._directoryLayer.move(txnOrDb, this._partitionSubpath(oldPath), this._partitionSubpath(newPath))
}
moveTo(txnOrDb: TxnAny | DbAny, _newAbsolutePath: PathIn) {
const directoryLayer = this.getLayerForPath([])
const newAbsolutePath = normalize_path(_newAbsolutePath)
const partition_len = directoryLayer._path.length
const partition_path = newAbsolutePath.slice(0, partition_len)
if (!arrEq(partition_path, directoryLayer._path)) throw new DirectoryError('Cannot move between partitions.')
return directoryLayer.move(txnOrDb, this._path.slice(partition_len), newAbsolutePath.slice(partition_len))
}
remove(txnOrDb: TxnAny | DbAny, path?: PathIn) {
const layer = this.getLayerForPath(path)
return layer.remove(txnOrDb, this._partitionSubpath(path, layer))
}
async removeIfExists(txnOrDb: TxnAny | DbAny, path?: PathIn) {
const layer = this.getLayerForPath(path)
return layer.removeIfExists(txnOrDb, this._partitionSubpath(path, layer))
}
exists(txnOrDb: TxnAny | DbAny, path?: PathIn): Promise<boolean> {
const layer = this.getLayerForPath(path)
return layer.exists(txnOrDb, this._partitionSubpath(path, layer))
}
getLayer() {
// will be 'partition' for partitions.
return this._layer ? this._layer.toString() : null
}
getLayerRaw() {
return this._layer
}
getPath() {
return this._path
}
isPartition() {
return this._parentDirectoryLayer != null
}
private _partitionSubpath(path: PathIn, directoryLayer: DirectoryLayer = this._directoryLayer) {
// console.log('_partitionSubpath', path, directoryLayer._path, this._path, this._path?.slice(directoryLayer._path.length).concat(normalize_path(path)))
return this._path?.slice(directoryLayer._path.length).concat(normalize_path(path))
}
private getLayerForPath(path: PathIn): DirectoryLayer {
return this.isPartition()
? normalize_path(path).length === 0
? this._parentDirectoryLayer!
: this._directoryLayer
: this._directoryLayer
}
}
interface DirectoryLayerOpts {
/** The prefix for directory metadata nodes. Defaults to '\xfe' */
nodePrefix?: string | Buffer
// We really actually want a NodeSubspace here, but we'll set the kv encoding
// ourselves to make the API simpler.
nodeSubspace?: SubspaceAny
/** The prefix for content. Defaults to ''. */
contentPrefix?: string | Buffer // Defaults to '', the root.
contentSubspace?: SubspaceAny
allowManualPrefixes?: boolean // default false
}
export class DirectoryLayer {
_nodeSubspace: NodeSubspace
_contentSubspace: Subspace<TupleIn, TupleItem[], any, any>
_allowManualPrefixes: boolean
_rootNode: NodeSubspace
_allocator: HighContentionAllocator
_path: Path
constructor(opts: DirectoryLayerOpts = {}) {
// By default, metadata for the nodes & allocator lives at the 0xfe prefix.
// The root of the database has the values themselves, using the allocation
// number as the prefix. Note that 0xfe (the default node prefix) is intentionally
// an invalid tuple.
this._nodeSubspace = opts.nodeSubspace?.withKeyEncoding(tuple)
|| new Subspace(opts.nodePrefix == null ? DEFAULT_NODE_PREFIX : opts.nodePrefix, tuple, defaultTransformer)
this._contentSubspace = opts.contentSubspace?.withKeyEncoding(tuple)
|| new Subspace(opts.contentPrefix == null ? BUF_EMPTY : opts.contentPrefix, tuple, defaultTransformer)
this._allowManualPrefixes = opts.allowManualPrefixes || false
this._rootNode = this._nodeSubspace.at(this._nodeSubspace.prefix)
this._allocator = new HighContentionAllocator(this._rootNode.at(HCA_PREFIX))
// When the directory layer is actually a partition, this is overwritten.
this._path = []
}
getPath() { return this._path }
/**
* Opens the directory with the given path.
*
* If the directory does not exist, it is created (creating parent directories
* if necessary).
*
* If layer is specified, it is checked against the layer of an existing
* directory or set as the layer of a new directory.
*/
createOrOpen(txnOrDb: TxnAny | DbAny, path: PathIn, layer?: 'partition' | NativeValue) {
return this._createOrOpenInternal(txnOrDb, path, layer)
}
private async _createOrOpenInternal(txnOrDb: TxnAny | DbAny, _path: PathIn, layer: NativeValue = BUF_EMPTY, prefix?: Buffer, allowCreate: boolean = true, allowOpen: boolean = true): Promise<Directory> {
const path = normalize_path(_path)
// For layers, an empty string is treated the same as a missing layer property.
const layerBuf = asBuf(layer)
if (prefix != null && !this._allowManualPrefixes) {
if (path.length === 0) throw new DirectoryError('Cannot specify a prefix unless manual prefixes are enabled.')
else throw new DirectoryError('Cannot specify a prefix in a partition.')
}
if (path.length === 0) throw new DirectoryError('The root directory cannot be opened.')
return doTxn(txnOrDb, async txn => {
await this._checkVersion(txn, false)
const existing_node = await this.findWithMeta(txn, path)
if (existing_node.exists()) {
// The directory exists. Open it!
if (existing_node.isInPartition()) {
const subpath = existing_node.getPartitionSubpath()
// console.log('existing node is in partition at path', existing_node, existing_node.getPartitionSubpath())
return await existing_node.getContentsSync(this)!._directoryLayer._createOrOpenInternal(
txn, subpath, layer, prefix, allowCreate, allowOpen
)
} else {
if (!allowOpen) throw new DirectoryError('The directory already exists.')
// console.log('existing_node.layer', existing_node.layer, layerBuf)
if (layerBuf.length && !existing_node.layer!.equals(layerBuf)) throw new DirectoryError('The directory was created with an incompatible layer.')
return existing_node.getContentsSync(this)!
}
} else {
// The directory does not exist. Create it!
if (!allowCreate) throw new DirectoryError('The directory does not exist.')
await this._checkVersion(txn, true)
if (prefix == null) {
// const subspace = this._contentSubspace.at(await this._allocator.allocate(txn))
prefix = concat2(this._contentSubspace.prefix, await this._allocator.allocate(txn))
if ((await txn.at(root).getRangeAllStartsWith(prefix, {limit: 1})).length > 0) {
throw new DirectoryError('The database has keys stored at the prefix chosen by the automatic prefix allocator: ' + inspect(prefix))
}
if (!await this._isPrefixFree(txn.snapshot(), prefix)) {
throw new DirectoryError('The directory layer has manually allocated prefixes that conflict with the automatic prefix allocator.')
}
} else if (!await this._isPrefixFree(txn, prefix)) {
throw new DirectoryError('The given prefix is already in use.')
}
const parentNode = path.length > 1
? this._nodeWithPrefix((await this._createOrOpenInternal(txn, path.slice(0, -1))).content.prefix)
: this._rootNode
if (parentNode == null) throw new DirectoryError('The parent directory does not exist.')
const node = this._nodeWithPrefix(prefix)
// Write metadata
txn.at(parentNode).set([SUBDIRS_KEY, path[path.length - 1]], prefix)
txn.at(node).set(LAYER_KEY, layerBuf)
return this._contentsOfNode(node, path, layerBuf)
}
})
}
/**
* Opens the directory with the given path.
*
* An error is raised if the directory does not exist, or if a layer is
* specified and a different layer was specified when the directory was
* created.
*/
open(txnOrDb: TxnAny | DbAny, path: PathIn, layer: 'partition' | NativeValue = BUF_EMPTY) {
return this._createOrOpenInternal(txnOrDb, path, layer, undefined, false, true)
}
/**
* Creates a directory with the given path (creating parent directories if
* necessary).
*
* An error is raised if the given directory already exists.
*
* If prefix is specified, the directory is created with the given physical
* prefix; otherwise a prefix is allocated automatically.
*
* If layer is specified, it is recorded with the directory and will be
* checked by future calls to open.
*/
create(txnOrDb: TxnAny | DbAny, path: PathIn, layer: 'partition' | NativeValue = BUF_EMPTY, prefix?: Buffer) {
return this._createOrOpenInternal(txnOrDb, path, layer, prefix, true, false)
}
/**
* Moves the directory found at `old_path` to `new_path`.
*
* There is no effect on the physical prefix of the given directory, or on
* clients that already have the directory open.
*
* An error is raised if the old directory does not exist, a directory already
* exists at `new_path`, or the parent directory of `new_path` does not exist.
*/
move(txnOrDb: TxnAny | DbAny, _oldPath: PathIn, _newPath: PathIn): Promise<Directory> {
const oldPath = normalize_path(_oldPath)
const newPath = normalize_path(_newPath)
return doTxn(txnOrDb, async txn => {
// Ideally this call should only write the version information to the
// database after performing the other checks, to make sure the input here
// is valid. But that would be inconsistent with the other bindings, and
// it matters because that inconsistency causes the binding tester to
// fail: https://github.com/apple/foundationdb/issues/2925
await this._checkVersion(txn, true)
if (arrStartsWith(newPath, oldPath)) {
throw new DirectoryError('The destination directory cannot be a subdirectory of the source directory.')
}
const oldNode = await this.findWithMeta(txn, oldPath)
const newNode = await this.findWithMeta(txn, newPath)
if (!oldNode.exists()) throw new DirectoryError('The source directory does not exist.')
if (oldNode.isInPartition() || newNode.isInPartition()) {
// This is allowed if and only if we're moving between two paths within the same partition.
if (!oldNode.isInPartition() || !newNode.isInPartition() || !arrEq(oldNode.path, newNode.path)) {
throw new DirectoryError('Cannot move between partitions.')
}
// Delegate to the partition.
return newNode.getContentsSync(this)!.move(txn, oldNode.getPartitionSubpath(), newNode.getPartitionSubpath())
}
if (newNode.exists()) throw new DirectoryError('The destination directory already exists. Remove it first.')
const parentNode = await this.find(txn, newPath.slice(0, -1))
if (!parentNode.exists()) throw new DirectoryError('The parent of the destination directory does not exist. Create it first.')
// Ok actually move.
const oldPrefix = this.getPrefixForNode(oldNode.subspace!)
txn.at(parentNode.subspace!).set([SUBDIRS_KEY, newPath[newPath.length - 1]], oldPrefix)
await this._removeFromParent(txn, oldPath)
return this._contentsOfNode(oldNode.subspace!, newPath, oldNode.layer!)
})
}
/**
* Removes the directory, its contents, and all subdirectories. Throws an
* exception if the directory does not exist.
*
* Warning: Clients that have already opened the directory might still insert
* data into its contents after it is removed.
*/
remove(txnOrDb: TxnAny | DbAny, path: PathIn) {
return this._removeInternal(txnOrDb, path, true)
}
/**
* Removes the directory, its contents, and all subdirectories, if it exists.
* Returns true if the directory existed and false otherwise.
*
* Warning: Clients that have already opened the directory might still insert
* data into its contents after it is removed.
*/
removeIfExists(txnOrDb: TxnAny | DbAny, path: PathIn) {
return this._removeInternal(txnOrDb, path, false)
}
private _removeInternal(txnOrDb: TxnAny | DbAny, _path: PathIn, failOnNonexistent: boolean): Promise<boolean> {
const path = normalize_path(_path)
return doTxn(txnOrDb, async txn => {
await this._checkVersion(txn, true)
if (path.length === 0) throw new DirectoryError('The root directory cannot be removed.')
const node = await this.findWithMeta(txn, path)
if (!node.exists()) {
if (failOnNonexistent) throw new DirectoryError('The directory does not exist.')
else return false
}
if (node.isInPartition()) {
return await node.getContentsSync(this)!
._directoryLayer
._removeInternal(txn, node.getPartitionSubpath(), failOnNonexistent)
}
await this._removeRecursive(txn, node.subspace!)
await this._removeFromParent(txn, path)
return true
})
}
/**
* Streams the names of the specified directory's subdirectories via a
* generator.
*/
async *list(txn: TxnAny, _path: PathIn): AsyncGenerator<Buffer, void, void> {
await this._checkVersion(txn, false)
const path = normalize_path(_path)
const node = await this.findWithMeta(txn, path)
if (!node.exists()) throw new DirectoryError('The directory does not exist.')
if (node.isInPartition(true)) {
yield* node.getContentsSync(this)!.list(txn, node.getPartitionSubpath())
} else {
for await (const [name] of this._subdirNamesAndNodes(txn, node.subspace!)) {
yield name
}
}
}
/**
* Returns the names of the specified directory's subdirectories as a list of
* strings.
*/
listAll(txnOrDb: TxnAny | DbAny, _path: PathIn = []): Promise<Buffer[]> {
return doTxn(txnOrDb, async txn => {
const results = []
for await (const path of this.list(txn, _path)) results.push(path)
return results
})
}
/**
* Returns whether or not the specified directory exists.
*/
async exists(txnOrDb: TxnAny | DbAny, _path: PathIn = []): Promise<boolean> {
return doTxn(txnOrDb, async txn => {
await this._checkVersion(txn, false)
const path = normalize_path(_path)
const node = await this.findWithMeta(txn, path)
if (!node.exists()) return false
else if (node.isInPartition()) return node.getContentsSync(this)!.exists(txn, node.getPartitionSubpath())
else return true
})
}
private async _nodeContainingKey(txn: TxnAny, key: Buffer) {
// This is a straight port of the equivalent function in the ruby / python
// bindings.
// Check if the key is actually *in* the node subspace
if (startsWith(key, this._nodeSubspace.prefix)) return this._rootNode
// .. check for any nodes in nodeSubspace which have the same name as key.
// Note the null here is used because null is encoded as Buffer<00>, which
// preserves the behaviour from the other bindings.
const [prev] = await txn.at(this._nodeSubspace).getRangeAll(null, [key, null], {reverse: true, limit: 1})
if (prev) {
const [k] = prev
const prev_prefix = k[0] as Buffer
if (startsWith(key, prev_prefix)) return this._nodeWithPrefix(prev_prefix)
}
return null
}
private _nodeWithPrefix(prefix: Buffer): NodeSubspace {
return this._nodeSubspace.at(prefix)
}
private getPrefixForNode(node: NodeSubspace) {
// This is some black magic. We have a reference to the node's subspace, but
// what we really want is the prefix. So we want to do the inverse to
// this._nodeSubspace.at(...).
return this._nodeSubspace._bakedKeyXf.unpack(node.prefix)[0] as Buffer
}
private contentSubspaceForNode(node: NodeSubspace) {
return new Subspace(this.getPrefixForNode(node), defaultTransformer, defaultTransformer)
}
private async find(txn: TxnAny, path: Path) {
let node = new Node(this._rootNode, [], path)
// There's an interesting problem where the node at the root will not have
// the layer property set, because the layer in that case is implicit.
// if (this._path.length === 0) node.layer = ''
for (let i = 0; i < path.length; i++) {
const ref = await txn.at(node.subspace!).get([SUBDIRS_KEY, path[i]])
node = new Node(ref == null ? null : this._nodeSubspace.at(ref), path.slice(0, i+1), path)
if (ref == null || (await node.getLayer(txn)).equals(PARTITION_BUF)) break
}
return node
}
private async findWithMeta(txn: TxnAny, target_path: Path) {
const node = await this.find(txn, target_path)
await node.prefetchMetadata(txn)
return node
}
_contentsOfNode(nodeSubspace: NodeSubspace, path: Path, layer: NativeValue = BUF_EMPTY): Directory {
// This is some black magic. We have a reference to the node's subspace, but
// what we really want is the prefix. So we want to do the inverse to
// this._nodeSubspace.at(...).
const contentSubspace = this.contentSubspaceForNode(nodeSubspace)
const layerBuf = asBuf(layer)
if (layerBuf.equals(PARTITION_BUF)) {
return new Directory(this, this._path.concat(path), contentSubspace, true)
} else {
// We concat the path because even though the child might not be a partition, we might be.
return new Directory(this, this._path.concat(path), contentSubspace, false, layerBuf)
}
}
private async _checkVersion(_tn: TxnAny, writeAccess: boolean) {
const tn = _tn.at(this._rootNode)
const actualRaw = await tn.get(VERSION_KEY)
if (actualRaw == null) {
if (writeAccess) tn.set(VERSION_KEY, versionEncoder.pack(EXPECTED_VERSION))
} else {
// Check the version matches the version of this directory implementation.
const actualVersion = versionEncoder.unpack(actualRaw)
if (actualVersion[0] > EXPECTED_VERSION[0]) {
throw new DirectoryError(`Cannot load directory with version ${actualVersion.join('.')} using directory layer ${EXPECTED_VERSION.join('.')}`)
} else if (actualVersion[1] > EXPECTED_VERSION[1] && writeAccess) {
throw new DirectoryError(`Directory with version ${actualVersion.join('.')} is read-only when opened using directory layer ${EXPECTED_VERSION.join('.')}`)
}
}
}
private async* _subdirNamesAndNodes(txn: TxnAny, node: NodeSubspace) {
// TODO: This could work using async iterators to improve performance of searches on very large directories.
for await (const [key, prefix] of txn.at(node).getRange(SUBDIRS_KEY)) {
yield [key[1], this._nodeWithPrefix(prefix)] as [Buffer, NodeSubspace]
}
}
private async _subdirNamesAndNodesAll(txn: TxnAny, node: NodeSubspace) {
const items = []
for await(const pair of this._subdirNamesAndNodes(txn, node)) items.push(pair)
return items
}
private async _removeFromParent(txn: TxnAny, path: Path) {
const parent = await this.find(txn, path.slice(0, -1))
txn.at(parent.subspace!).clear([SUBDIRS_KEY, path[path.length - 1]])
}
private async _removeRecursive(txn: TxnAny, node: NodeSubspace) {
for await (const [name, subnode] of this._subdirNamesAndNodes(txn, node)) {
await this._removeRecursive(txn, subnode)
}
// Clear content
txn.at(this.contentSubspaceForNode(node)).clearRangeStartsWith(BUF_EMPTY)
// Clear metadata
txn.at(node).clearRangeStartsWith(undefined)
}
// private _isPrefixFree(txn: TxnAny, subspace: Subspace<TupleIn, TupleItem, any, any>) {
private async _isPrefixFree(txn: TxnAny, prefix: Buffer) {
// Returns true if the given prefix does not "intersect" any currently
// allocated prefix (including the root node). This means that it neither
// contains any other prefix nor is contained by any other prefix.
return prefix.length > 0
&& await this._nodeContainingKey(txn, prefix) == null
&& (await txn.at(this._nodeSubspace).getRangeAll(prefix, strInc(prefix), {limit: 1})).length === 0
}
} | the_stack |
import React, { Component } from 'react';
import { Animated, PanResponder, PanResponderInstance, PanResponderGestureState, ImageCropData } from 'react-native';
// @ts-ignore; 'react-native-image-rotate' does not have typescript support
import RNImageRotate from 'react-native-image-rotate';
import ImageEditor from '@react-native-community/image-editor';
import { Q } from '../constants';
import Cropper from './Cropper';
import { getCropperLimits } from '../utils';
type CropperPageProps = {
footerComponent: JSX.Element;
onDone: (croppedImageUri: string) => void;
onError: (err: Error) => void;
onCancel: () => void;
imageUri: string;
imageWidth: number;
imageHeight: number;
TOP_VALUE: number;
LEFT_VALUE: number;
BOTTOM_VALUE: number;
RIGHT_VALUE: number;
initialRotation: number;
NOT_SELECTED_AREA_OPACITY: number;
BORDER_WIDTH: number;
COMPONENT_WIDTH: number;
COMPONENT_HEIGHT: number;
};
interface ExtendedAnimatedValue extends Animated.Value {
_value: number;
_offset: number;
}
interface ExtendedAnimatedValueXY extends Animated.AnimatedValueXY {
x: ExtendedAnimatedValue;
y: ExtendedAnimatedValue;
}
type Position = 'topPosition' | 'leftPosition' | 'bottomPosition' | 'rightPosition';
interface State {
topOuterPosition: ExtendedAnimatedValueXY;
topOuterPanResponder: PanResponderInstance;
leftOuterPosition: ExtendedAnimatedValueXY;
leftOuterPanResponder: PanResponderInstance;
bottomOuterPosition: ExtendedAnimatedValueXY;
bottomOuterPanResponder: PanResponderInstance;
rightOuterPosition: ExtendedAnimatedValueXY;
rightOuterPanResponder: PanResponderInstance;
topPosition: ExtendedAnimatedValueXY;
topPanResponder: PanResponderInstance;
leftPosition: ExtendedAnimatedValueXY;
leftPanResponder: PanResponderInstance;
bottomPosition: ExtendedAnimatedValueXY;
bottomPanResponder: PanResponderInstance;
rightPosition: ExtendedAnimatedValueXY;
rightPanResponder: PanResponderInstance;
topLeftPosition: ExtendedAnimatedValueXY;
topLeftPanResponder: PanResponderInstance;
bottomLeftPosition: ExtendedAnimatedValueXY;
bottomLeftPanResponder: PanResponderInstance;
bottomRightPosition: ExtendedAnimatedValueXY;
bottomRightPanResponder: PanResponderInstance;
topRightPosition: ExtendedAnimatedValueXY;
topRightPanResponder: PanResponderInstance;
rectanglePosition: ExtendedAnimatedValueXY;
rectanglePanResponder: PanResponderInstance;
TOP_LIMIT: number;
LEFT_LIMIT: number;
BOTTOM_LIMIT: number;
RIGHT_LIMIT: number;
TOP_VALUE: number;
LEFT_VALUE: number;
BOTTOM_VALUE: number;
RIGHT_VALUE: number;
rotation: number;
}
class CropperPage extends Component<CropperPageProps, State> {
constructor(props: CropperPageProps) {
super(props);
const { imageWidth, imageHeight, BORDER_WIDTH, COMPONENT_WIDTH, COMPONENT_HEIGHT } = props;
const W_INT = this.W - 2 * BORDER_WIDTH;
const H_INT = this.H - 2 * BORDER_WIDTH;
const { TOP_LIMIT, LEFT_LIMIT, BOTTOM_LIMIT, RIGHT_LIMIT, DIFF } = getCropperLimits(
imageWidth,
imageHeight,
props.initialRotation,
W_INT,
H_INT,
this.W,
this.H,
BORDER_WIDTH,
Q,
);
const TOP_VALUE = props.TOP_VALUE !== 0 ? props.TOP_VALUE : TOP_LIMIT;
const LEFT_VALUE = props.LEFT_VALUE !== 0 ? props.LEFT_VALUE : LEFT_LIMIT;
const BOTTOM_VALUE = props.BOTTOM_VALUE !== 0 ? props.BOTTOM_VALUE : BOTTOM_LIMIT;
const RIGHT_VALUE = props.RIGHT_VALUE !== 0 ? props.RIGHT_VALUE : RIGHT_LIMIT;
const topOuterPosition = new Animated.ValueXY({ x: LEFT_VALUE - BORDER_WIDTH, y: TOP_VALUE - BORDER_WIDTH }) as ExtendedAnimatedValueXY;
const topOuterPanResponder = PanResponder.create({ onStartShouldSetPanResponder: () => false });
const leftOuterPosition = new Animated.ValueXY({ x: LEFT_VALUE - BORDER_WIDTH, y: TOP_VALUE - BORDER_WIDTH }) as ExtendedAnimatedValueXY;
const leftOuterPanResponder = PanResponder.create({ onStartShouldSetPanResponder: () => false });
const bottomOuterPosition = new Animated.ValueXY({ x: LEFT_VALUE - BORDER_WIDTH, y: COMPONENT_HEIGHT - BOTTOM_VALUE }) as ExtendedAnimatedValueXY;
const bottomOuterPanResponder = PanResponder.create({ onStartShouldSetPanResponder: () => false });
const rightOuterPosition = new Animated.ValueXY({ x: COMPONENT_WIDTH - RIGHT_VALUE, y: TOP_VALUE - BORDER_WIDTH }) as ExtendedAnimatedValueXY;
const rightOuterPanResponder = PanResponder.create({ onStartShouldSetPanResponder: () => false });
const topPosition = new Animated.ValueXY({ x: LEFT_VALUE - BORDER_WIDTH, y: TOP_VALUE - BORDER_WIDTH }) as ExtendedAnimatedValueXY;
const topPanResponder = this.initSidePanResponder('topPosition');
const leftPosition = new Animated.ValueXY({ x: LEFT_VALUE - BORDER_WIDTH, y: TOP_VALUE - BORDER_WIDTH }) as ExtendedAnimatedValueXY;
const leftPanResponder = this.initSidePanResponder('leftPosition');
const bottomPosition = new Animated.ValueXY({ x: LEFT_VALUE - BORDER_WIDTH, y: COMPONENT_HEIGHT - BOTTOM_VALUE }) as ExtendedAnimatedValueXY;
const bottomPanResponder = this.initSidePanResponder('bottomPosition');
const rightPosition = new Animated.ValueXY({
x: COMPONENT_WIDTH - RIGHT_VALUE,
y: TOP_VALUE - BORDER_WIDTH - DIFF / 2,
}) as ExtendedAnimatedValueXY;
const rightPanResponder = this.initSidePanResponder('rightPosition');
const topLeftPosition = new Animated.ValueXY({ x: LEFT_VALUE - BORDER_WIDTH, y: TOP_VALUE - BORDER_WIDTH }) as ExtendedAnimatedValueXY;
const topLeftPanResponder = this.initCornerPanResponder('topPosition', 'leftPosition');
const bottomLeftPosition = new Animated.ValueXY({ x: LEFT_VALUE - BORDER_WIDTH, y: COMPONENT_HEIGHT - BOTTOM_VALUE }) as ExtendedAnimatedValueXY;
const bottomLeftPanResponder = this.initCornerPanResponder('bottomPosition', 'leftPosition');
const bottomRightPosition = new Animated.ValueXY({
x: COMPONENT_WIDTH - RIGHT_VALUE,
y: COMPONENT_HEIGHT - BOTTOM_VALUE,
}) as ExtendedAnimatedValueXY;
const bottomRightPanResponder = this.initCornerPanResponder('bottomPosition', 'rightPosition');
const topRightPosition = new Animated.ValueXY({ x: COMPONENT_WIDTH - RIGHT_VALUE, y: TOP_VALUE - BORDER_WIDTH }) as ExtendedAnimatedValueXY;
const topRightPanResponder = this.initCornerPanResponder('topPosition', 'rightPosition');
const rectanglePosition = new Animated.ValueXY({ x: LEFT_VALUE, y: TOP_VALUE }) as ExtendedAnimatedValueXY;
const rectanglePanResponder = this.initRectanglePanResponder();
this.state = {
topOuterPosition,
topOuterPanResponder,
leftOuterPosition,
leftOuterPanResponder,
bottomOuterPosition,
bottomOuterPanResponder,
rightOuterPosition,
rightOuterPanResponder,
topPosition,
topPanResponder,
leftPosition,
leftPanResponder,
bottomPosition,
bottomPanResponder,
rightPosition,
rightPanResponder,
topLeftPosition,
topLeftPanResponder,
bottomLeftPosition,
bottomLeftPanResponder,
bottomRightPosition,
bottomRightPanResponder,
topRightPosition,
topRightPanResponder,
rectanglePosition,
rectanglePanResponder,
TOP_LIMIT,
LEFT_LIMIT,
BOTTOM_LIMIT,
RIGHT_LIMIT,
TOP_VALUE,
LEFT_VALUE,
BOTTOM_VALUE,
RIGHT_VALUE,
rotation: props.initialRotation,
};
}
isRectangleMoving = false;
topOuter = undefined;
leftOuter = undefined;
bottomOuter = undefined;
rightOuter = undefined;
W = this.props.COMPONENT_WIDTH;
H = this.props.COMPONENT_HEIGHT - Q;
onCancel = () => {
this.props.onCancel();
};
getTopOuterStyle = () => {
return {
...this.state.topOuterPosition.getLayout(),
top: this.state.TOP_LIMIT,
left: this.state.LEFT_LIMIT,
height: Animated.add(this.props.BORDER_WIDTH - this.state.TOP_LIMIT, this.state.topPosition.y),
width: this.W,
backgroundColor: `rgba(0, 0, 0, ${this.props.NOT_SELECTED_AREA_OPACITY})`,
};
};
getLeftOuterStyle = () => {
return {
...this.state.leftOuterPosition.getLayout(),
top: Animated.add(this.props.BORDER_WIDTH, this.state.topPosition.y),
left: this.state.LEFT_LIMIT,
height: Animated.add(-this.props.BORDER_WIDTH, Animated.add(this.state.bottomPosition.y, Animated.multiply(-1, this.state.topPosition.y))),
width: Animated.add(this.props.BORDER_WIDTH - this.state.LEFT_LIMIT, this.state.leftPosition.x),
backgroundColor: `rgba(0, 0, 0, ${this.props.NOT_SELECTED_AREA_OPACITY})`,
};
};
getBottomOuterStyle = () => {
return {
...this.state.bottomOuterPosition.getLayout(),
top: this.state.bottomPosition.y,
left: this.state.LEFT_LIMIT,
height: Animated.add(this.props.COMPONENT_HEIGHT - this.state.BOTTOM_LIMIT, Animated.multiply(-1, this.state.bottomPosition.y)),
width: this.W,
backgroundColor: `rgba(0, 0, 0, ${this.props.NOT_SELECTED_AREA_OPACITY})`,
};
};
getRightOuterStyle = () => {
return {
...this.state.rightOuterPosition.getLayout(),
top: Animated.add(this.props.BORDER_WIDTH, this.state.topPosition.y),
left: this.state.rightPosition.x,
height: Animated.add(-this.props.BORDER_WIDTH, Animated.add(this.state.bottomPosition.y, Animated.multiply(-1, this.state.topPosition.y))),
right: this.state.RIGHT_LIMIT,
backgroundColor: `rgba(0, 0, 0, ${this.props.NOT_SELECTED_AREA_OPACITY})`,
};
};
getTopLeftStyle = () => {
return {
...this.state.topLeftPosition.getLayout(),
top: this.state.topPosition.y,
left: this.state.leftPosition.x,
width: this.props.BORDER_WIDTH,
paddingBottom: this.props.BORDER_WIDTH,
};
};
getBottomLeftStyle = () => {
return {
...this.state.bottomLeftPosition.getLayout(),
top: this.state.bottomPosition.y,
left: this.state.leftPosition.x,
width: this.props.BORDER_WIDTH,
paddingTop: this.props.BORDER_WIDTH,
};
};
getBottomRightStyle = () => {
return {
...this.state.bottomRightPosition.getLayout(),
top: this.state.bottomPosition.y,
left: this.state.rightPosition.x,
height: this.props.BORDER_WIDTH,
paddingLeft: this.props.BORDER_WIDTH,
};
};
getTopRightStyle = () => {
return {
...this.state.topRightPosition.getLayout(),
top: this.state.topPosition.y,
left: this.state.rightPosition.x,
height: this.props.BORDER_WIDTH,
paddingLeft: this.props.BORDER_WIDTH,
};
};
getTopSideStyle = () => {
return {
...this.state.topPosition.getLayout(),
left: Animated.add(this.props.BORDER_WIDTH, this.state.leftPosition.x),
width: Animated.add(-this.props.BORDER_WIDTH, Animated.add(this.state.rightPosition.x, Animated.multiply(-1, this.state.leftPosition.x))),
paddingBottom: this.props.BORDER_WIDTH,
};
};
getLeftSideStyle = () => {
return {
...this.state.leftPosition.getLayout(),
top: Animated.add(this.props.BORDER_WIDTH, this.state.topPosition.y),
height: Animated.add(-this.props.BORDER_WIDTH, Animated.add(this.state.bottomPosition.y, Animated.multiply(-1, this.state.topPosition.y))),
paddingLeft: this.props.BORDER_WIDTH,
};
};
getBottomSideStyle = () => {
return {
...this.state.bottomPosition.getLayout(),
left: Animated.add(this.props.BORDER_WIDTH, this.state.leftPosition.x),
width: Animated.add(-this.props.BORDER_WIDTH, Animated.add(this.state.rightPosition.x, Animated.multiply(-1, this.state.leftPosition.x))),
paddingTop: this.props.BORDER_WIDTH,
};
};
getRightSideStyle = () => {
return {
...this.state.rightPosition.getLayout(),
top: Animated.add(this.props.BORDER_WIDTH, this.state.topPosition.y),
height: Animated.add(-this.props.BORDER_WIDTH, Animated.add(this.state.bottomPosition.y, Animated.multiply(-1, this.state.topPosition.y))),
paddingLeft: this.props.BORDER_WIDTH,
};
};
getRectangleStyle = () => {
return {
...this.state.rectanglePosition.getLayout(),
top: Animated.add(this.props.BORDER_WIDTH, this.state.topPosition.y),
left: Animated.add(this.props.BORDER_WIDTH, this.state.leftPosition.x),
width: Animated.add(-this.props.BORDER_WIDTH, Animated.add(this.state.rightPosition.x, Animated.multiply(-1, this.state.leftPosition.x))),
height: Animated.add(-this.props.BORDER_WIDTH, Animated.add(this.state.bottomPosition.y, Animated.multiply(-1, this.state.topPosition.y))),
zIndex: 3,
};
};
getImageStyle = () => {
const DIFF = this.state.topPosition.y._value - this.state.rightPosition.y._value;
return {
position: 'absolute',
top: this.state.TOP_LIMIT - DIFF,
left: this.state.LEFT_LIMIT + DIFF,
bottom: this.state.BOTTOM_LIMIT - DIFF,
right: this.state.RIGHT_LIMIT + DIFF,
resizeMode: 'stretch',
transform: [{ rotate: `${this.state.rotation.toString()}deg` }],
};
};
isAllowedToMoveTopSide = (gesture: PanResponderGestureState) => {
return (
this.state.topPosition.y._offset + gesture.dy >= this.state.TOP_LIMIT - this.props.BORDER_WIDTH &&
this.state.topPosition.y._offset + gesture.dy + this.props.BORDER_WIDTH + 1 < this.state.bottomPosition.y._offset
);
};
isAllowedToMoveLeftSide = (gesture: PanResponderGestureState) => {
return (
this.state.leftPosition.x._offset + gesture.dx >= this.state.LEFT_LIMIT - this.props.BORDER_WIDTH &&
this.state.leftPosition.x._offset + gesture.dx + this.props.BORDER_WIDTH + 1 < this.state.rightPosition.x._offset
);
};
isAllowedToMoveBottomSide = (gesture: PanResponderGestureState) => {
return (
this.state.bottomPosition.y._offset + gesture.dy <= this.props.COMPONENT_HEIGHT - this.state.BOTTOM_LIMIT &&
this.state.topPosition.y._offset + this.props.BORDER_WIDTH + 1 < this.state.bottomPosition.y._offset + gesture.dy
);
};
isAllowedToMoveRightSide = (gesture: PanResponderGestureState) => {
return (
this.state.rightPosition.x._offset + gesture.dx <= this.props.COMPONENT_WIDTH - this.state.RIGHT_LIMIT &&
this.state.leftPosition.x._offset + this.props.BORDER_WIDTH + 1 < this.state.rightPosition.x._offset + gesture.dx
);
};
isAllowedToMove = (position: Position, gesture: PanResponderGestureState) => {
if (position === 'topPosition') {
return this.isAllowedToMoveTopSide(gesture);
}
if (position === 'leftPosition') {
return this.isAllowedToMoveLeftSide(gesture);
}
if (position === 'bottomPosition') {
return this.isAllowedToMoveBottomSide(gesture);
}
if (position === 'rightPosition') {
return this.isAllowedToMoveRightSide(gesture);
}
};
initSidePanResponder = (position: Position) => {
return PanResponder.create({
onStartShouldSetPanResponder: () => !this.isRectangleMoving,
onPanResponderMove: (_event, gesture) => {
if (this.isAllowedToMove(position, gesture)) {
this.state[position].setValue({ x: gesture.dx, y: gesture.dy });
}
},
onPanResponderRelease: () => {
// make to not reset position
this.state.topPosition.flattenOffset();
this.state.leftPosition.flattenOffset();
this.state.bottomPosition.flattenOffset();
this.state.rightPosition.flattenOffset();
},
onPanResponderGrant: () => {
this.state.topPosition.setOffset({
x: this.state.topPosition.x._value,
y: this.state.topPosition.y._value,
});
this.state.leftPosition.setOffset({
x: this.state.leftPosition.x._value,
y: this.state.leftPosition.y._value,
});
this.state.bottomPosition.setOffset({
x: this.state.bottomPosition.x._value,
y: this.state.bottomPosition.y._value,
});
this.state.rightPosition.setOffset({
x: this.state.rightPosition.x._value,
y: this.state.rightPosition.y._value,
});
this.state.topPosition.setValue({ x: 0, y: 0 });
this.state.leftPosition.setValue({ x: 0, y: 0 });
this.state.bottomPosition.setValue({ x: 0, y: 0 });
this.state.rightPosition.setValue({ x: 0, y: 0 });
},
});
};
initRectanglePanResponder = () => {
return PanResponder.create({
onStartShouldSetPanResponder: () => !this.isRectangleMoving,
onPanResponderMove: (_event, gesture) => {
this.state.topPosition.setValue({ x: gesture.dx, y: gesture.dy });
this.state.leftPosition.setValue({ x: gesture.dx, y: gesture.dy });
this.state.bottomPosition.setValue({ x: gesture.dx, y: gesture.dy });
this.state.rightPosition.setValue({ x: gesture.dx, y: gesture.dy });
},
onPanResponderRelease: () => {
this.isRectangleMoving = true;
// make to not reset position
this.state.topPosition.flattenOffset();
this.state.leftPosition.flattenOffset();
this.state.bottomPosition.flattenOffset();
this.state.rightPosition.flattenOffset();
const width = this.state.rightPosition.x._value - this.state.leftPosition.x._value - this.props.BORDER_WIDTH;
const height = this.state.bottomPosition.y._value - this.state.topPosition.y._value - this.props.BORDER_WIDTH;
let isOutside = false;
if (this.state.leftPosition.x._value < this.state.LEFT_LIMIT - this.props.BORDER_WIDTH) {
isOutside = true;
Animated.parallel([
Animated.spring(this.state.leftPosition.x, { toValue: this.state.LEFT_LIMIT - this.props.BORDER_WIDTH, useNativeDriver: false }),
Animated.spring(this.state.rightPosition.x, { toValue: this.state.LEFT_LIMIT + width, useNativeDriver: false }),
]).start(() => {
this.isRectangleMoving = false;
});
}
if (this.state.topPosition.y._value < this.state.TOP_LIMIT - this.props.BORDER_WIDTH) {
isOutside = true;
Animated.parallel([
Animated.spring(this.state.topPosition.y, { toValue: this.state.TOP_LIMIT - this.props.BORDER_WIDTH, useNativeDriver: false }),
Animated.spring(this.state.bottomPosition.y, { toValue: this.state.TOP_LIMIT + height, useNativeDriver: false }),
]).start(() => {
this.isRectangleMoving = false;
});
}
if (width + this.state.leftPosition.x._value + this.props.BORDER_WIDTH > this.props.COMPONENT_WIDTH - this.state.RIGHT_LIMIT) {
isOutside = true;
Animated.parallel([
Animated.spring(this.state.leftPosition.x, {
toValue: this.props.COMPONENT_WIDTH - this.state.RIGHT_LIMIT - width - this.props.BORDER_WIDTH,
useNativeDriver: false,
}),
Animated.spring(this.state.rightPosition.x, { toValue: this.props.COMPONENT_WIDTH - this.state.RIGHT_LIMIT, useNativeDriver: false }),
]).start(() => {
this.isRectangleMoving = false;
});
}
if (height + this.state.topPosition.y._value + this.props.BORDER_WIDTH > this.props.COMPONENT_HEIGHT - this.state.BOTTOM_LIMIT) {
isOutside = true;
Animated.parallel([
Animated.spring(this.state.topPosition.y, {
toValue: this.props.COMPONENT_HEIGHT - this.state.BOTTOM_LIMIT - height - this.props.BORDER_WIDTH,
useNativeDriver: false,
}),
Animated.spring(this.state.bottomPosition.y, { toValue: this.props.COMPONENT_HEIGHT - this.state.BOTTOM_LIMIT, useNativeDriver: false }),
]).start(() => {
this.isRectangleMoving = false;
});
}
if (!isOutside) {
this.isRectangleMoving = false;
}
},
onPanResponderGrant: () => {
this.state.topPosition.setOffset({
x: this.state.topPosition.x._value,
y: this.state.topPosition.y._value,
});
this.state.leftPosition.setOffset({
x: this.state.leftPosition.x._value,
y: this.state.leftPosition.y._value,
});
this.state.bottomPosition.setOffset({
x: this.state.bottomPosition.x._value,
y: this.state.bottomPosition.y._value,
});
this.state.rightPosition.setOffset({
x: this.state.rightPosition.x._value,
y: this.state.rightPosition.y._value,
});
this.state.topPosition.setValue({ x: 0, y: 0 });
this.state.leftPosition.setValue({ x: 0, y: 0 });
this.state.bottomPosition.setValue({ x: 0, y: 0 });
this.state.rightPosition.setValue({ x: 0, y: 0 });
},
});
};
initCornerPanResponder = (pos1: Position, pos2: Position) => {
return PanResponder.create({
onStartShouldSetPanResponder: () => !this.isRectangleMoving,
onPanResponderMove: (_event, gesture) => {
if (this.isAllowedToMove(pos1, gesture)) {
this.state[pos1].setValue({ x: gesture.dx, y: gesture.dy });
}
if (this.isAllowedToMove(pos2, gesture)) {
this.state[pos2].setValue({ x: gesture.dx, y: gesture.dy });
}
},
onPanResponderRelease: () => {
this.state.topPosition.flattenOffset();
this.state.leftPosition.flattenOffset();
this.state.bottomPosition.flattenOffset();
this.state.rightPosition.flattenOffset();
},
onPanResponderGrant: () => {
this.state.topPosition.setOffset({ x: this.state.topPosition.x._value, y: this.state.topPosition.y._value });
this.state.leftPosition.setOffset({ x: this.state.leftPosition.x._value, y: this.state.leftPosition.y._value });
this.state.bottomPosition.setOffset({ x: this.state.bottomPosition.x._value, y: this.state.bottomPosition.y._value });
this.state.rightPosition.setOffset({ x: this.state.rightPosition.x._value, y: this.state.rightPosition.y._value });
this.state.topPosition.setValue({ x: 0, y: 0 });
this.state.leftPosition.setValue({ x: 0, y: 0 });
this.state.bottomPosition.setValue({ x: 0, y: 0 });
this.state.rightPosition.setValue({ x: 0, y: 0 });
},
});
};
setCropBoxLimits = ({
TOP_LIMIT,
LEFT_LIMIT,
BOTTOM_LIMIT,
RIGHT_LIMIT,
}: {
TOP_LIMIT: number;
LEFT_LIMIT: number;
BOTTOM_LIMIT: number;
RIGHT_LIMIT: number;
}) => {
this.setState({
TOP_LIMIT,
LEFT_LIMIT,
BOTTOM_LIMIT,
RIGHT_LIMIT,
});
};
setCropBoxValues = ({
TOP_VALUE,
LEFT_VALUE,
BOTTOM_VALUE,
RIGHT_VALUE,
}: {
TOP_VALUE: number;
LEFT_VALUE: number;
BOTTOM_VALUE: number;
RIGHT_VALUE: number;
}) => {
this.setState({
TOP_VALUE,
LEFT_VALUE,
BOTTOM_VALUE,
RIGHT_VALUE,
});
};
setCropBoxRotation = (rotation: number) => {
this.setState({ rotation });
};
rotate90 = () => {
this.setCropBoxRotation((360 + (this.state.rotation - 90)) % 360);
};
onRotate = () => {
const W_INT = this.W - 2 * this.props.BORDER_WIDTH;
const H_INT = this.H - 2 * this.props.BORDER_WIDTH;
let imageWidth = 0;
let imageHeight = 0;
let rotation = 0;
if (this.state.rotation % 180 === 90) {
imageWidth = this.props.imageWidth > 0 ? this.props.imageWidth : 1280; // 340
imageHeight = this.props.imageHeight > 0 ? this.props.imageHeight : 747; // 500
rotation = 0;
} else {
imageWidth = this.props.COMPONENT_WIDTH - this.state.LEFT_LIMIT - this.state.RIGHT_LIMIT;
imageHeight = this.props.COMPONENT_HEIGHT - this.state.TOP_LIMIT - this.state.BOTTOM_LIMIT;
rotation = 90;
}
const { TOP_LIMIT, LEFT_LIMIT, BOTTOM_LIMIT, RIGHT_LIMIT, DIFF } = getCropperLimits(
imageWidth,
imageHeight,
rotation,
W_INT,
H_INT,
this.W,
this.H,
this.props.BORDER_WIDTH,
Q,
);
this.rotate90();
this.setCropBoxLimits({ TOP_LIMIT, LEFT_LIMIT, BOTTOM_LIMIT, RIGHT_LIMIT });
const startPositionBeforeRotationX = this.state.leftPosition.x._value - this.state.LEFT_LIMIT + this.props.BORDER_WIDTH;
const startPositionBeforeRotationY = this.state.topPosition.y._value - this.state.TOP_LIMIT + this.props.BORDER_WIDTH;
const imageWidthBeforeRotation = this.props.COMPONENT_WIDTH - this.state.RIGHT_LIMIT - this.state.LEFT_LIMIT;
const imageHeightBeforeRotation = this.props.COMPONENT_HEIGHT - this.state.BOTTOM_LIMIT - this.state.TOP_LIMIT;
const rectangleWidthBeforeRotation = this.state.rightPosition.x._value - this.state.leftPosition.x._value - this.props.BORDER_WIDTH;
const rectangleHeightBeforeRotation = this.state.bottomPosition.y._value - this.state.topPosition.y._value - this.props.BORDER_WIDTH;
const imageWidthAfterRotation = this.props.COMPONENT_WIDTH - RIGHT_LIMIT - LEFT_LIMIT;
const imageHeightAfterRotation = this.props.COMPONENT_HEIGHT - BOTTOM_LIMIT - TOP_LIMIT;
const rectangleWidthAfterRotation = (imageWidthAfterRotation * rectangleHeightBeforeRotation) / imageHeightBeforeRotation;
const rectangleHeightAfterRotation = (imageHeightAfterRotation * rectangleWidthBeforeRotation) / imageWidthBeforeRotation;
const startPositionAfterRotationX = (startPositionBeforeRotationY * imageWidthAfterRotation) / imageHeightBeforeRotation;
const startPositionAfterRotationY =
((imageWidthBeforeRotation - startPositionBeforeRotationX - rectangleWidthBeforeRotation) * imageHeightAfterRotation) /
imageWidthBeforeRotation;
this.state.topPosition.setValue({
x: LEFT_LIMIT + startPositionAfterRotationX - this.props.BORDER_WIDTH,
y: TOP_LIMIT + startPositionAfterRotationY - this.props.BORDER_WIDTH,
});
this.state.leftPosition.setValue({
x: LEFT_LIMIT + startPositionAfterRotationX - this.props.BORDER_WIDTH,
y: TOP_LIMIT + startPositionAfterRotationY - this.props.BORDER_WIDTH,
});
this.state.bottomPosition.setValue({
x: LEFT_LIMIT + startPositionAfterRotationX - this.props.BORDER_WIDTH,
y: TOP_LIMIT + startPositionAfterRotationY + rectangleHeightAfterRotation,
});
this.state.rightPosition.setValue({
x: LEFT_LIMIT + startPositionAfterRotationX + rectangleWidthAfterRotation,
y: TOP_LIMIT + startPositionAfterRotationY - this.props.BORDER_WIDTH - DIFF / 2,
});
// @ts-ignore
this.topOuter.setNativeProps({ style: { top: TOP_LIMIT, height: 0 } });
// @ts-ignore
this.leftOuter.setNativeProps({ style: { left: LEFT_LIMIT, width: 0 } });
// @ts-ignore
this.bottomOuter.setNativeProps({ style: { top: BOTTOM_LIMIT, height: 0 } });
// @ts-ignore
this.rightOuter.setNativeProps({ style: { top: TOP_LIMIT, height: 0 } });
};
onDone = () => {
if (this.isRectangleMoving) {
return null;
}
//this.setState({ isSaving: true });
const IMAGE_W = this.props.COMPONENT_WIDTH - this.state.RIGHT_LIMIT - this.state.LEFT_LIMIT;
const IMAGE_H = this.props.COMPONENT_HEIGHT - this.state.BOTTOM_LIMIT - this.state.TOP_LIMIT;
let x = this.state.leftPosition.x._value - this.state.LEFT_LIMIT + this.props.BORDER_WIDTH;
let y = this.state.topPosition.y._value - this.state.TOP_LIMIT + this.props.BORDER_WIDTH;
let width = this.state.rightPosition.x._value - this.state.leftPosition.x._value - this.props.BORDER_WIDTH;
let height = this.state.bottomPosition.y._value - this.state.topPosition.y._value - this.props.BORDER_WIDTH;
let imageWidth = this.props.imageWidth > 0 ? this.props.imageWidth : 1280; // 340
let imageHeight = this.props.imageHeight > 0 ? this.props.imageHeight : 747; // 500
if (this.state.rotation % 180 === 90) {
const pivot = imageWidth;
imageWidth = imageHeight;
imageHeight = pivot;
}
width = (width * imageWidth) / IMAGE_W;
height = (height * imageHeight) / IMAGE_H;
x = (x * imageWidth) / IMAGE_W;
y = (y * imageHeight) / IMAGE_H;
const cropData = {
offset: { x, y },
size: { width, height },
resizeMode: 'stretch',
} as ImageCropData;
RNImageRotate.rotateImage(
this.props.imageUri,
this.state.rotation,
(rotatedUri: string) => {
//
ImageEditor.cropImage(rotatedUri, cropData)
.then(croppedUri => {
this.props.onDone(croppedUri);
})
.catch((err: Error) => {
this.props.onError(err);
});
//
},
(err: Error) => {
this.props.onError(err);
},
);
};
render() {
return (
<Cropper
imageUri={this.props.imageUri} // 'https://3.imimg.com/data3/SN/NO/MY-10244508/vertical-building-parking-500x500.jpg'
footerComponent={this.props.footerComponent}
getTopOuterStyle={this.getTopOuterStyle}
getLeftOuterStyle={this.getLeftOuterStyle}
getBottomOuterStyle={this.getBottomOuterStyle}
getRightOuterStyle={this.getRightOuterStyle}
getTopLeftStyle={this.getTopLeftStyle}
getBottomLeftStyle={this.getBottomLeftStyle}
getBottomRightStyle={this.getBottomRightStyle}
getTopRightStyle={this.getTopRightStyle}
getTopSideStyle={this.getTopSideStyle}
getLeftSideStyle={this.getLeftSideStyle}
getBottomSideStyle={this.getBottomSideStyle}
getRightSideStyle={this.getRightSideStyle}
getRectangleStyle={this.getRectangleStyle}
getImageStyle={this.getImageStyle}
onDone={this.onDone}
onRotate={this.onRotate}
onCancel={this.onCancel}
topOuterPanResponder={this.state.topOuterPanResponder}
leftOuterPanResponder={this.state.leftOuterPanResponder}
bottomOuterPanResponder={this.state.bottomOuterPanResponder}
rightOuterPanResponder={this.state.rightOuterPanResponder}
topPanResponder={this.state.topPanResponder}
leftPanResponder={this.state.leftPanResponder}
bottomPanResponder={this.state.bottomPanResponder}
rightPanResponder={this.state.rightPanResponder}
topLeftPanResponder={this.state.topLeftPanResponder}
bottomLeftPanResponder={this.state.bottomLeftPanResponder}
bottomRightPanResponder={this.state.bottomRightPanResponder}
topRightPanResponder={this.state.topRightPanResponder}
rectanglePanResponder={this.state.rectanglePanResponder}
topOuterRef={ref => (this.topOuter = ref)}
leftOuterRef={ref => (this.leftOuter = ref)}
bottomOuterRef={ref => (this.bottomOuter = ref)}
rightOuterRef={ref => (this.rightOuter = ref)}
COMPONENT_WIDTH={this.props.COMPONENT_WIDTH}
COMPONENT_HEIGHT={this.props.COMPONENT_HEIGHT}
W={this.W}
H={this.H}
/>
);
}
}
export default CropperPage; | the_stack |
import type { TVec3 } from '@oito/type';
import type { Pose } from '@oito/armature';
import type { IKChain, Link } from '../rigs/IKChain';
import { Vec3, Transform, Quat } from '@oito/core';
import { ISolver } from './ISolver';
//#endregion
class NaturalCCDSolver implements ISolver{
//#region TARGETTING DATA
effectorPos = [ 0, 0, 0 ];
_minEffRng = 0.001**2; // Min Effector Range Square
_chainCnt = 0;
_local !: Transform[];
_world !: Transform[];
_kFactor !: any;
_tries = 30;
//#endregion
initData( pose?: Pose, chain?: IKChain ): this{
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Get the Chain's Tail Position as the Effector Position
if( pose && chain ){
const lnk = chain.last();
const eff = new Vec3( 0, lnk.len, 0 );
pose.bones[ lnk.idx ].world.transformVec3( eff ); // The Trail Position in WorldSpace
eff.copyTo( this.effectorPos );
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Setup Transform Chains to handle Iterative Processing of CCD
if( chain ){
const cnt = chain.count;
this._chainCnt = cnt;
this._world = new Array( cnt + 1 ); // Extra Transform for Final Tail
this._local = new Array( cnt + 1 );
// Create a Transform for each link/bone
for( let i=0; i < cnt; i++ ){
this._world[ i ] = new Transform();
this._local[ i ] = new Transform();
}
// Tail Transform
this._world[ cnt ] = new Transform();
this._local[ cnt ] = new Transform( [0,0,0,1], [0,chain.last().len,0], [1,1,1] );
}
return this;
}
//#region SETTING TARGET DATA
setTargetPos( v: TVec3 ): this{
this.effectorPos[ 0 ] = v[ 0 ];
this.effectorPos[ 1 ] = v[ 1 ];
this.effectorPos[ 2 ] = v[ 2 ];
return this;
}
useArcSqrFactor( c: number, offset: number, useInv = false ): this{
this._kFactor = new KFactorArcSqr( c, offset, useInv );
return this
}
setTries( v: number ){ this._tries = v; return this; }
//#endregion
resolve( chain: IKChain, pose: Pose, debug?:any ): void{
const root = new Transform();
let lnk: Link = chain.first();
// Get the Starting Transform
if( lnk.pidx == -1 ) root.copy( pose.offset );
else pose.getWorldTransform( lnk.pidx, root );
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
let i: number;
// Set the Initial Local Space from the chain Bind Pose
for( i=0; i < chain.count; i++ ){
this._local[ i ].copy( chain.links[ i ].bind );
}
this._updateWorld( 0, root ); // Update World Space
if( Vec3.lenSq( this.effectorPos, this._getTailPos() ) < this._minEffRng ){
//console.log( 'CCD Chain is already at endEffector at initial call' );
return;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
for( i=0; i < this._tries; i++ ){
if( this._iteration( chain, pose, root, debug ) ) break; // Exit early if reaching effector
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Save Results to Pose
for( i=0; i < chain.count; i++ ){
pose.setLocalRot( chain.links[ i ].idx, this._local[ i ].rot );
}
/*
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Start by Using SwingTwist to target the bone toward the EndEffector
const ST = this._swingTwist
const [ rot, pt ] = ST.getWorldRot( chain, pose, debug );
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
let b0 = chain.links[ 0 ],
b1 = chain.links[ 1 ],
alen = b0.len,
blen = b1.len,
clen = Vec3.len( ST.effectorPos, ST.originPos ),
prot = [0,0,0,0],
rad : number;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// FIRST BONE
rad = lawcos_sss( alen, clen, blen ); // Get the Angle between First Bone and Target.
rot
.pmulAxisAngle( ST.orthoDir as TVec3, -rad ) // Use the Axis X to rotate by Radian Angle
.copyTo( prot ) // Save For Next Bone as Starting Point.
.pmulInvert( pt.rot ); // To Local
pose.setLocalRot( b0.idx, rot ); // Save to Pose
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// SECOND BONE
// Need to rotate from Right to Left, So take the angle and subtract it from 180 to rotate from
// the other direction. Ex. L->R 70 degrees == R->L 110 degrees
rad = Math.PI - lawcos_sss( alen, blen, clen );
rot
.fromMul( prot, b1.bind.rot ) // Get the Bind WS Rotation for this bone
.pmulAxisAngle( ST.orthoDir as TVec3, rad ) // Rotation that needs to be applied to bone.
.pmulInvert( prot ); // To Local Space
pose.setLocalRot( b1.idx, rot ); // Save to Pose
*/
}
// Update the Iteration Transform Chain, helps know the position of
// each joint & end effector ( Last point on the chain )
_updateWorld( startIdx: number, root: Transform ){
const w = this._world;
const l = this._local;
let i : number;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HANDLE ROOT TRANSFORM
if( startIdx == 0 ){
w[ 0 ].fromMul( root, l[ 0 ] ); // ( Pose Offset * Chain Parent ) * First Link
startIdx++; // Start on the Nex Transform
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HANDLE MIDDLE TRANSFORMS
for( i=startIdx; i < w.length; i++ ){
w[ i ].fromMul( w[ i-1 ], l[ i ] ); // Parent * Child
}
}
_getTailPos(){ return this._world[ this._world.length - 1 ].pos; }
_iteration( chain: IKChain, pose: Pose, root: Transform, debug ?:any ): boolean{
const w = this._world;
const l = this._local;
const cnt = w.length - 1;
const tail = w[ cnt ];
const tailDir = new Vec3();
const effDir = new Vec3();
const lerpDir = new Vec3();
const q = new Quat;
const k = this._kFactor;
let i : number;
let diff : number;
let b : Transform;
if( k ) k.reset();
for( i=cnt-1; i >= 0; i-- ){ // Skip End Effector Transform
//--------------------------------------
// Check how far tail is from End Effector
diff = Vec3.lenSq( tail.pos, this.effectorPos ); // Distance Squared from Tail to Effector
if( diff <= this._minEffRng ) return true; // Point Reached, can Stop
//--------------------------------------
b = w[ i ];
tailDir.fromSub( tail.pos, b.pos ).norm(); // Direction from current joint to end effector
effDir.fromSub( this.effectorPos, b.pos ).norm(); // Direction from current joint to target
if( k ) k.apply( chain, chain.links[ i ], tailDir, effDir, lerpDir ); // How Factor to Rotation Movement
else lerpDir.copy( effDir );
q .fromUnitVecs( tailDir, lerpDir ) // Create Rotation toward target
.mul( b.rot ); // Apply to current World rotation
if( i != 0 ) q.pmulInvert( w[ i-1 ].rot ); // To Local Space
else q.pmulInvert( root.rot );
l[ i ].rot.copy( q ); // Save back to bone
//--------------------------------------
this._updateWorld( i, root ); // Update Chain from this bone and up.
}
return false;
}
}
/*
class KFactorCircle{
constructor( c, r ){
this.k = Maths.clamp( c / r, 0, 1 ); // K = Constant / Radius
}
static fromChainLen( c, chainLen ){
// Radius = ( 180 + ArcLength ) / ( PI * ArcAngle )
let r = ( 180 * chainLen ) / ( Math.PI * Math.PI * 2 );
return new KFactorCircle( c, r );
}
static fromChain( c, chain ){
// Radius = ( 180 + ArcLength ) / ( PI * ArcAngle )
let r = ( 180 * chain.len ) / ( Math.PI * Math.PI * 2 );
return new KFactorCircle( c, r );
}
reset(){} // No State to reset
apply( bone, effDir, tarDir, out ){
out.from_lerp( effDir, tarDir, this.k ).norm();
}
}
*/
class KFactorArcSqr{
c : number;
offset : number;
arcLen = 0;
useInv = false;
constructor( c: number, offset: number, useInv = false ){
this.c = c;
this.offset = offset;
this.useInv = useInv;
}
reset(){ this.arcLen = 0; }
apply( chain: IKChain, lnk: Link, tailDir: TVec3 , effDir: TVec3, out: Vec3 ){
// Notes, Can do the inverse of pass in chain's length so chain.len - this.arcLen
// This causes the beginning of the chain to move more and the tail less.
this.arcLen += lnk.len; // Accumulate the Arc length for each bone
//const k = this.c / Math.sqrt( this.arcLen + this.offset ); // k = Constant / sqrt( CurrentArcLen )
const k = ( !this.useInv )?
this.c / Math.sqrt( this.arcLen + this.offset ) :
this.c / Math.sqrt( ( chain.length - this.arcLen ) + this.offset )
out.fromLerp( tailDir, effDir, k ).norm();
}
}
/*
class KFactorArc{
constructor( c, offset ){
this.c = c;
this.arcLen = 0;
this.offset = offset;
}
reset(){
this.arcLen = 0;
}
apply( bone, effDir, tarDir, out ){
// Notes, Can do the inverse of pass in chain's length so chain.len - this.arcLen
// This causes the beginning of the chain to move more and the tail less.
this.arcLen += bone.len; //Accumulate the Arc length for each bone
let k = this.c / ( this.arcLen + this.offset ); // k = Constant / CurrentArcLen
out.from_lerp( effDir, tarDir, k ).norm();
}
}
class KFactorOther{
constructor( chainLen ){
this.chainLen = chainLen;
this.arcLen = 0;
this.offset = 0.1;
this.scalar = 1.3;
}
reset(){ this.arcLen = 0; }
apply( bone, effDir, tarDir, out ){
// Just messing around with numbers to see if there is ways to alter the movement of the chain
this.arcLen += bone.len;
let k = ( ( this.chainLen - this.arcLen + this.offset ) / ( this.chainLen*this.scalar ) )**2;
out.from_lerp( effDir, tarDir, k ).norm();
}
}
*/
export default NaturalCCDSolver; | the_stack |
import acceptLanguageParser from 'accept-language-parser';
import Cache from 'nice-cache';
import Client from 'oc-client';
import Domain from 'domain';
import emptyResponseHandler from 'oc-empty-response-handler';
import vm from 'vm';
import _ from 'lodash';
import applyDefaultValues from './apply-default-values';
import eventsHandler from '../../domain/events-handler';
import GetComponentRetrievingInfo from './get-component-retrieving-info';
import * as getComponentFallback from './get-component-fallback';
import isTemplateLegacy from '../../../utils/is-template-legacy';
import NestedRenderer from '../../domain/nested-renderer';
import RequireWrapper from '../../domain/require-wrapper';
import * as sanitiser from '../../domain/sanitiser';
import settings from '../../../resources/settings';
import strings from '../../../resources';
import * as urlBuilder from '../../domain/url-builder';
import * as validator from '../../domain/validators';
import { Config, Repository } from '../../../types';
import { IncomingHttpHeaders } from 'http';
import { fromPromise } from 'universalify';
export interface RendererOptions {
conf: Config;
headers: IncomingHttpHeaders;
ip: string;
name: string;
parameters: Record<string, string>;
version: string;
omitHref?: boolean;
}
export interface GetComponentResult {
status: number;
headers?: Record<string, string>;
response: {
type?: string;
code?: string;
error?: unknown;
version?: string;
html?: string;
requestVersion?: string;
name?: string;
details?: {
message: string;
stack: string;
originalError: unknown;
};
missingPlugins?: string[];
missingDependencies?: string[];
};
}
export default function getComponent(conf: Config, repository: Repository) {
const client = Client({ templates: conf.templates });
const cache = new Cache({
verbose: !!conf.verbosity,
refreshInterval: conf.refreshInterval
});
const renderer = function (
options: RendererOptions,
cb: (result: GetComponentResult) => void
) {
const nestedRenderer = NestedRenderer(renderer, options.conf);
const retrievingInfo = GetComponentRetrievingInfo(options);
let responseHeaders: Record<string, string> = {};
const getLanguage = () => {
const paramOverride =
!!options.parameters && options.parameters['__ocAcceptLanguage'];
return paramOverride || options.headers['accept-language'];
};
const callback = (result: GetComponentResult) => {
if (result.response.error) {
retrievingInfo.extend(result.response);
}
retrievingInfo.extend({ status: result.status });
Object.assign(result.response, {
name: options.name,
requestVersion: options.version || ''
});
eventsHandler.fire('component-retrieved', retrievingInfo.getData());
return cb(result);
};
let componentCallbackDone = false;
const conf = options.conf;
const acceptLanguage = getLanguage();
const requestedComponent = {
name: options.name,
version: options.version || '',
parameters: options.parameters
};
fromPromise(repository.getComponent)(
requestedComponent.name,
requestedComponent.version,
(err, component) => {
// check route exist for component and version
if (err) {
if (conf.fallbackRegistryUrl) {
return getComponentFallback.getComponent(
conf.fallbackRegistryUrl,
options.headers,
requestedComponent,
callback as any
);
}
return callback({
status: 404,
response: {
code: 'NOT_FOUND',
error: err
}
});
}
// Skip rendering and return only the component info in case of 'accept: application/vnd.oc.info+json'
if (options.headers.accept === settings.registry.acceptInfoHeader) {
return callback({
status: 200,
response: {
type: conf.local ? 'oc-component-local' : 'oc-component',
version: component.version,
requestVersion: requestedComponent.version,
name: requestedComponent.name
}
});
}
// check component requirements are satisfied by registry
const pluginsCompatibility = validator.validatePluginsRequirements(
component.oc.plugins,
conf.plugins
);
if (!pluginsCompatibility.isValid) {
return callback({
status: 501,
response: {
code: 'PLUGIN_MISSING_FROM_REGISTRY',
error: strings.errors.registry.PLUGIN_NOT_IMPLEMENTED(
pluginsCompatibility.missing.join(', ')
),
missingPlugins: pluginsCompatibility.missing
}
});
}
// sanitise and check params
const appliedParams = applyDefaultValues(
requestedComponent.parameters,
component.oc.parameters
);
const params = sanitiser.sanitiseComponentParameters(
appliedParams,
component.oc.parameters
);
const validationResult = validator.validateComponentParameters(
// @ts-ignore
params,
component.oc.parameters
);
if (!validationResult.isValid) {
return callback({
status: 400,
response: {
code: 'NOT_VALID_REQUEST',
error: validationResult.errors.message
}
});
}
// Support legacy templates
let templateType = component.oc.files.template.type;
const isLegacyTemplate = isTemplateLegacy(templateType);
if (isLegacyTemplate) {
templateType = `oc-template-${templateType}`;
}
if (!repository.getTemplate(templateType)) {
return callback({
status: 400,
response: {
code: 'TEMPLATE_NOT_SUPPORTED',
error:
strings.errors.registry.TEMPLATE_NOT_SUPPORTED(templateType)
}
});
}
const filterCustomHeaders = (
headers: Record<string, string>,
requestedVersion: string,
actualVersion: string
) => {
const needFiltering =
!_.isEmpty(headers) &&
!_.isEmpty(conf.customHeadersToSkipOnWeakVersion) &&
requestedVersion !== actualVersion;
return needFiltering
? _.omit(headers, conf.customHeadersToSkipOnWeakVersion)
: headers;
};
const returnComponent = (err: any, data: any) => {
if (componentCallbackDone) {
return;
}
componentCallbackDone = true;
const componentHref = urlBuilder.component(
{
name: component.name,
version: requestedComponent.version,
// @ts-ignore
parameters: params
},
conf.baseUrl
);
const isUnrendered =
options.headers.accept === settings.registry.acceptUnrenderedHeader;
const isValidClientRequest =
options.headers['user-agent'] &&
!!options.headers['user-agent'].match('oc-client-');
const parseTemplatesHeader = (t: string) =>
t.split(';').map(t => t.split(',')[0]);
const supportedTemplates = options.headers['templates']
? parseTemplatesHeader(options.headers['templates'] as string)
: [];
const isTemplateSupportedByClient = Boolean(
isValidClientRequest &&
options.headers['templates'] &&
(_.includes(
supportedTemplates,
component.oc.files.template.type
) ||
_.includes(supportedTemplates, templateType))
);
let renderMode = 'rendered';
if (isUnrendered) {
renderMode = 'unrendered';
if (
isValidClientRequest &&
!isTemplateSupportedByClient &&
!isLegacyTemplate
) {
renderMode = 'rendered';
}
}
retrievingInfo.extend({
href: componentHref,
version: component.version,
renderMode
});
if (!!err || !data) {
err =
err ||
new Error(strings.errors.registry.DATA_OBJECT_IS_UNDEFINED);
return callback({
status: Number(err.status) || 500,
response: {
code: 'GENERIC_ERROR',
error: strings.errors.registry.COMPONENT_EXECUTION_ERROR(
err.message || ''
),
details: {
message: err.message,
stack: err.stack,
originalError: err
}
}
});
}
const response: {
type: string;
version: string;
requestVersion: string;
name: string;
renderMode: string;
href?: string;
} = {
type: conf.local ? 'oc-component-local' : 'oc-component',
version: component.version,
requestVersion: requestedComponent.version,
name: requestedComponent.name,
renderMode
};
if (!options.omitHref) {
response.href = componentHref;
}
responseHeaders = filterCustomHeaders(
responseHeaders,
requestedComponent.version,
component.version
);
if (renderMode === 'unrendered') {
callback({
status: 200,
headers: responseHeaders,
response: Object.assign(response, {
data: data,
template: {
src: repository.getStaticFilePath(
component.name,
component.version,
'template.js'
),
type: component.oc.files.template.type,
key: component.oc.files.template.hashKey
}
})
});
} else {
const cacheKey = `${component.name}/${component.version}/template.js`;
const cached = cache.get('file-contents', cacheKey);
const key = component.oc.files.template.hashKey;
const renderOptions = {
href: componentHref,
key,
version: component.version,
name: component.name,
templateType: component.oc.files.template.type,
container: component.oc.container,
renderInfo: component.oc.renderInfo
};
const returnResult = (template: any) => {
client.renderTemplate(
template,
data,
renderOptions,
(err: Error, html: string) => {
if (err) {
return callback({
status: 500,
response: {
code: 'INTERNAL_SERVER_ERROR',
error: err
}
});
}
callback({
status: 200,
headers: responseHeaders,
response: Object.assign(response, { html })
});
}
);
};
if (!!cached && !conf.hotReloading) {
returnResult(cached);
} else {
fromPromise(repository.getCompiledView)(
component.name,
component.version,
(_err, templateText) => {
let ocTemplate;
try {
ocTemplate = repository.getTemplate(templateType);
} catch (err) {
return callback({
status: 400,
response: {
code: 'TEMPLATE_NOT_SUPPORTED',
error:
strings.errors.registry.TEMPLATE_NOT_SUPPORTED(
templateType
)
}
});
}
const template = ocTemplate.getCompiledTemplate(
templateText,
key
);
cache.set('file-contents', cacheKey, template);
returnResult(template);
}
);
}
}
};
if (!component.oc.files.dataProvider) {
returnComponent(null, {});
} else {
const cacheKey = `${component.name}/${component.version}/server.js`;
const cached = cache.get('file-contents', cacheKey);
const domain = Domain.create();
const setEmptyResponse =
emptyResponseHandler.contextDecorator(returnComponent);
const contextObj = {
acceptLanguage: acceptLanguageParser.parse(acceptLanguage!),
baseUrl: conf.baseUrl,
env: conf.env,
params,
plugins: conf.plugins,
renderComponent: fromPromise(nestedRenderer.renderComponent),
renderComponents: fromPromise(nestedRenderer.renderComponents),
requestHeaders: options.headers,
requestIp: options.ip,
setEmptyResponse,
staticPath: repository
.getStaticFilePath(component.name, component.version, '')
.replace('https:', ''),
setHeader: (header?: string, value?: string) => {
if (!(typeof header === 'string' && typeof value === 'string')) {
throw strings.errors.registry
.COMPONENT_SET_HEADER_PARAMETERS_NOT_VALID;
}
if (header && value) {
responseHeaders = responseHeaders || {};
responseHeaders[header.toLowerCase()] = value;
}
},
templates: repository.getTemplatesInfo()
};
const setCallbackTimeout = () => {
const executionTimeout = conf.executionTimeout;
if (executionTimeout) {
setTimeout(() => {
const message = `timeout (${executionTimeout * 1000}ms)`;
returnComponent({ message }, undefined);
domain.exit();
}, executionTimeout * 1000);
}
};
if (!!cached && !conf.hotReloading) {
domain.on('error', returnComponent);
try {
domain.run(() => {
cached(contextObj, returnComponent);
setCallbackTimeout();
});
} catch (e) {
return returnComponent(e, undefined);
}
} else {
fromPromise(repository.getDataProvider)(
component.name,
component.version,
(err, dataProvider) => {
if (err) {
componentCallbackDone = true;
return callback({
status: 502,
response: {
code: 'DATA_RESOLVING_ERROR',
error: strings.errors.registry.RESOLVING_ERROR
}
});
}
const context = {
require: RequireWrapper(conf.dependencies),
module: {
exports: {} as Record<
string,
(...args: unknown[]) => unknown
>
},
console: conf.local ? console : { log: _.noop },
setTimeout,
Buffer
};
const handleError = (err: {
code: string;
missing: string[];
}) => {
if (err.code === 'DEPENDENCY_MISSING_FROM_REGISTRY') {
componentCallbackDone = true;
return callback({
status: 501,
response: {
code: err.code,
error: strings.errors.registry.DEPENDENCY_NOT_FOUND(
err.missing.join(', ')
),
missingDependencies: err.missing
}
});
}
returnComponent(err, undefined);
};
const options = conf.local
? {
displayErrors: true,
filename: dataProvider.filePath
}
: {};
try {
vm.runInNewContext(dataProvider.content, context, options);
const processData = context.module.exports['data'];
cache.set('file-contents', cacheKey, processData);
domain.on('error', handleError);
domain.run(() => {
processData(contextObj, returnComponent);
setCallbackTimeout();
});
} catch (err) {
handleError(err as any);
}
}
);
}
}
}
);
};
return renderer;
} | the_stack |
import {
assert,
createContainer,
createFixture,
createObserverLocator,
createScopeForTest,
} from '@aurelia/testing';
import {
CustomElement,
InterpolationBinding,
Interpolation,
ConditionalExpression,
AccessScopeExpression,
BindingMode,
LifecycleFlags,
SVGAnalyzerRegistration,
IPlatform,
ValueConverter,
} from '@aurelia/runtime-html';
type CaseType = {
expected: number | string;
expectedStrictMode?: number | string;
expectedValueAfterChange?: number | string;
changeFnc?: (val: any, platform: IPlatform) => any;
app: any;
interpolation: string;
it: string;
only?: boolean;
};
const testDateString = new Date('Sat Feb 02 2002 00:00:00 GMT+0000 (Coordinated Universal Time)').toString();
const ThreeHoursAheadDateString = new Date('Sat Feb 02 2002 03:00:00 GMT+0000 (Coordinated Universal Time)').toString();
const ThreeDaysDateString = new Date('Sat Feb 03 2002 00:00:00 GMT+0000 (Coordinated Universal Time)').toString();
describe('3-runtime/interpolation.spec.ts -- [UNIT]interpolation', function () {
const cases: CaseType[] = [
{
expected: 'wOOt', expectedStrictMode: 'wOOt', app: class { public value?: string | number = 'wOOt'; public value1?: string | number; }, interpolation: `$\{value}`, it: 'Renders expected text'
},
{
expected: '', expectedStrictMode: 'undefined', app: class { public value = undefined; }, interpolation: `$\{value}`, it: 'Undefined value renders nothing'
},
{
expected: 5, expectedStrictMode: 'NaN', app: class { public value1 = undefined; public value = 5; }, interpolation: `$\{value1 + value}`, it: 'Two values one undefined sum correctly'
},
{
expected: -5, expectedStrictMode: 'NaN', app: class { public value = undefined; public value1 = 5; }, interpolation: `$\{value - value1}`, it: 'Two values one undefined minus correctly'
},
{
expected: '', expectedStrictMode: 'null', app: class { isStrictMode = true; public value = null; }, interpolation: `$\{value}`, it: 'Null value renders nothing'
},
{
expected: 5, expectedStrictMode: '5', app: class { public value1 = null; public value = 5; }, interpolation: `$\{value1 + value}`, it: 'Two values one Null sum correctly'
},
{
expected: -5, expectedStrictMode: '-5', app: class { public value = null; public value1 = 5; }, interpolation: `$\{value - value1}`, it: 'Two values one Null minus correctly'
},
{
expected: 'Infinity', expectedStrictMode: 'NaN', expectedValueAfterChange: 5, app: class { public value = undefined; public value1 = 5; }, interpolation: `$\{value1/value}`, it: 'Number divided by undefined is Infinity'
},
{
expected: 1, expectedStrictMode: 1, expectedValueAfterChange: 0.8333333333333334, app: class { public value = 5; public value1 = 5; }, interpolation: `$\{value1/value}`, it: 'Number divided by number works as planned'
},
{
expected: 1, expectedStrictMode: 1, app: class { Math = Math; public value = 1.2; public value1 = 5; }, interpolation: `$\{Math.round(value)}`, it: 'Global Aliasing works'
},
{
expected: 2, expectedStrictMode: 2, app: class { Math = Math; public value = 1.5; public value1 = 5; }, interpolation: `$\{Math.round(value)}`, it: 'Global Aliasing works #2'
},
{
expected: 'true', expectedValueAfterChange: 'false', changeFnc: (val) => !val, app: class { public value = true; }, interpolation: `$\{value}`, it: 'Boolean prints true'
},
{
expected: 'false', expectedValueAfterChange: 'true', changeFnc: (val) => !val, app: class { public value = false; }, interpolation: `$\{value}`, it: 'Boolean prints false'
},
{
expected: 'false', expectedValueAfterChange: 'false', changeFnc: (val) => !val, app: class { public value = false; }, interpolation: `$\{value && false}`, it: 'Boolean prints false with && no matter what'
},
{
expected: 'test',
app: class { public value = 'test'; },
interpolation: `$\{true && value}`,
it: 'Coalesce works properly'
},
{
expected: testDateString,
expectedValueAfterChange: ThreeDaysDateString,
changeFnc: (val: Date) => {
return new Date(ThreeDaysDateString);
}, app: class { public value = new Date('Sat Feb 02 2002 00:00:00 GMT+0000 (Coordinated Universal Time)'); },
interpolation: `$\{value}`, it: 'Date works and setDate triggers change properly'
},
{
expected: testDateString,
expectedStrictMode: `undefined${testDateString}`,
expectedValueAfterChange: ThreeDaysDateString,
changeFnc: (val: Date) => {
return new Date(ThreeDaysDateString);
}, app: class { public value = new Date('Sat Feb 02 2002 00:00:00 GMT+0000 (Coordinated Universal Time)'); },
interpolation: `$\{undefined + value}`, it: 'Date works with undefined expression and setDate triggers change properly'
},
{
expected: testDateString,
expectedStrictMode: `null${testDateString}`,
expectedValueAfterChange: ThreeDaysDateString,
changeFnc: (val: Date) => {
return new Date(ThreeDaysDateString);
}, app: class { public value = new Date('Sat Feb 02 2002 00:00:00 GMT+0000 (Coordinated Universal Time)'); },
interpolation: `$\{null + value}`, it: 'Date works with null expression and setDate triggers change properly'
},
{
expected: testDateString,
expectedValueAfterChange: ThreeHoursAheadDateString,
changeFnc: (val: Date) => {
return new Date(ThreeHoursAheadDateString);
}, app: class { public value = new Date('Sat Feb 02 2002 00:00:00 GMT+0000 (Coordinated Universal Time)'); },
interpolation: `$\{value}`, it: 'Date works and setHours triggers change properly'
},
{
expected: { foo: 'foo', bar: 'bar' }.toString(),
expectedValueAfterChange: { foo: 'foo', bar: 'bar', wat: 'wat' }.toString(),
changeFnc: (val) => {
val.wat = 'wat';
return val;
}, app: class { public value = { foo: 'foo', bar: 'bar', wat: 'wat' }; }, interpolation: `$\{value}`, it: 'Object binding works'
},
{
expected: [0, 1, 2].toString(),
expectedValueAfterChange: [0, 1, 2, 3].toString(),
changeFnc: (val) => {
val.push(3);
return val; // Array observation no worky
}, app: class { public value = [0, 1, 2]; },
interpolation: `$\{value}`,
it: 'Array prints comma delimited values and observes push correctly'
},
{
expected: [0, 1, 2].toString(),
expectedValueAfterChange: [0, 1].toString(),
changeFnc: (val) => {
val.pop();
return val; // Array observation no worky
}, app: class { public value = [0, 1, 2]; },
interpolation: `$\{value}`,
it: 'Array prints comma delimited values and observes pop correctly'
},
{
expected: [0, 1, 2].toString(),
expectedValueAfterChange: [0, 2].toString(),
changeFnc: (val) => {
val.splice(1, 1);
return val; // Array observation no worky
}, app: class { public value = [0, 1, 2]; },
interpolation: `$\{value}`,
it: 'Array prints comma delimited values and observes splice correctly'
},
{
expected: [0, 1, 2].toString(),
expectedValueAfterChange: [5, 6].toString(),
changeFnc: () => {
return [5, 6];
}, app: class { public value = [0, 1, 2]; },
interpolation: `$\{value}`,
it: 'Array prints comma delimited values and observes new array correctly'
},
{
expected: 'test foo out bar',
expectedValueAfterChange: 'test foo woot out bar',
changeFnc: (val) => {
return `${val} woot`;
}, app: class { public value = 'foo'; public value2 = 'bar'; },
interpolation: `test $\{value} out $\{value2}`,
it: 'Multiple statements work in interpolation'
},
{
expected: 'test foo out foo',
expectedValueAfterChange: 'test foo woot out foo woot',
changeFnc: (val) => {
return `${val} woot`;
}, app: class { public value = 'foo'; },
interpolation: `test $\{value} out $\{value}`,
it: 'Multiple SAME statements work in interpolation'
},
{
expected: 'test out ',
expectedValueAfterChange: 'test foo out foo',
changeFnc: () => {
return 'foo';
}, app: class { public value: any; },
interpolation: `test $\{value} out $\{value}`,
it: 'Multiple SAME statements work in interpolation with undefined'
},
{
expected: 'test out ',
expectedValueAfterChange: 'test foo-node out ',
changeFnc: (_, platform) => {
const span = platform.document.createElement('span');
span.appendChild(platform.document.createTextNode('foo-node'));
return span;
}, app: class { public value: any; },
interpolation: `test $\{value} out `,
it: 'works with HTML Element'
},
{
expected: 'test out ',
// special edcase, same node is appended in multiple positions
// resulting in the last place that uses it wins
expectedValueAfterChange: 'test out foo-node',
changeFnc: (_, platform) => {
return platform.document.createTextNode('foo-node');
}, app: class { public value: any; },
interpolation: `test $\{value} out $\{value}`,
it: 'Multiple SAME statements work in interpolation with HTML Text'
},
{
expected: 'test 1,2,3 out',
expectedValueAfterChange: 'test foo-node out',
changeFnc: (_, platform) => {
return platform.document.createTextNode('foo-node');
},
app: class { public value: any = [1, 2, 3]; },
interpolation: `test $\{value} out`,
it: 'changes from array to node',
},
{
expected: 'test foo-node out',
expectedValueAfterChange: 'test 1,2,3 out',
changeFnc: (_, platform) => {
return [1, 2, 3];
},
app: class {
public static get inject() { return [IPlatform]; }
public value: any;
public constructor(
p: IPlatform,
) {
this.value = p.document.createTextNode('foo-node');
}
},
interpolation: `test $\{value} out`,
it: 'changes from node array',
}
];
cases.forEach((x) => {
const $it = x.only ? it.only : it;
$it(x.it, async function () {
const { tearDown, appHost } = createFixture(`<template>${x.interpolation}</template>`, x.app);
assert.strictEqual(appHost.textContent, x.expected.toString(), `host.textContent`);
await tearDown();
});
$it(`${x.it} change tests work`, async function () {
const { tearDown, appHost, platform, component } = createFixture(`<template>${x.interpolation}</template>`, x.app);
if (x.changeFnc !== undefined) {
const val = x.changeFnc(component.value, platform);
if (val != null) {
component.value = val;
}
} else if (typeof x.expected === 'string' && x.expected !== 'Infinity') {
component.value = `${component.value || ``}1`;
} else {
component.value = (component.value as number || 0) + 1;
}
platform.domWriteQueue.flush();
assert.strictEqual(appHost.textContent, (x.expectedValueAfterChange && x.expectedValueAfterChange.toString()) || (x.expected as number + 1).toString(), `host.textContent`);
await tearDown();
});
if (x.expectedStrictMode) {
$it(`${x.it} STRICT MODE `, async function () {
const strict = CustomElement.define({ name: 'strict', template: `${x.interpolation}`, isStrictBinding: true }, x.app);
const { tearDown, appHost } = createFixture(`<template><strict></strict></template>`, class { }, [strict]);
assert.strictEqual(appHost.textContent, x.expectedStrictMode.toString(), `host.textContent`);
await tearDown();
});
}
});
describe('volatile expressions', function () {
it('handles single', function () {
const container = createContainer();
const observerLocator = createObserverLocator(container);
const interpolation = new Interpolation(
['', ''],
[new ConditionalExpression(
new AccessScopeExpression('checked'),
new AccessScopeExpression('yesMsg'),
new AccessScopeExpression('noMsg'),
)]
);
const target = { value: '' };
const binding = new InterpolationBinding(
observerLocator,
interpolation,
target,
'value',
BindingMode.toView,
container,
{} as any,
);
const source = { checked: false, yesMsg: 'yes', noMsg: 'no' };
let handleChangeCallCount = 0;
let updateTargetCallCount = 0;
binding.updateTarget = (updateTarget => {
return function (...args: unknown[]) {
updateTargetCallCount++;
return updateTarget.apply(this, args);
};
})(binding.updateTarget);
binding.partBindings[0].handleChange = (handleChange => {
return function (...args: unknown[]) {
handleChangeCallCount++;
return handleChange.apply(this, args);
};
})(binding.partBindings[0].handleChange);
binding.$bind(LifecycleFlags.fromBind, createScopeForTest(source));
assert.strictEqual(target.value, 'no');
assert.deepStrictEqual(
[handleChangeCallCount, updateTargetCallCount],
[0, 1],
);
// inactive branch of conditional shouldn't call handleChange
source.yesMsg = 'hello';
assert.deepStrictEqual(
[handleChangeCallCount, updateTargetCallCount],
[0, 1],
);
source.noMsg = 'hello';
assert.strictEqual(target.value, 'hello');
assert.deepStrictEqual(
[handleChangeCallCount, updateTargetCallCount],
[1, 2],
);
source.yesMsg = 'yes';
source.checked = true;
assert.strictEqual(target.value, 'yes');
assert.deepStrictEqual(
[handleChangeCallCount, updateTargetCallCount],
[2, 3],
);
source.noMsg = 'no1111';
assert.strictEqual(target.value, 'yes');
assert.deepStrictEqual(
[handleChangeCallCount, updateTargetCallCount],
[2, 3],
);
});
it('handles multiple', function () {
const container = createContainer();
const observerLocator = createObserverLocator(container);
const interpolation = new Interpolation(
['', '--', ''],
[
new ConditionalExpression(
new AccessScopeExpression('checked1'),
new AccessScopeExpression('yes1'),
new AccessScopeExpression('no1'),
),
new ConditionalExpression(
new AccessScopeExpression('checked2'),
new AccessScopeExpression('yes2'),
new AccessScopeExpression('no2'),
)
]
);
const target = { value: '' };
const binding = new InterpolationBinding(
observerLocator,
interpolation,
target,
'value',
BindingMode.toView,
container,
{} as any,
);
const source = {
checked1: false,
yes1: 'yes1',
no1: 'no1',
checked2: false,
yes2: 'yes2',
no2: 'no2'
};
let handleChange1CallCount = 0;
let handleChange2CallCount = 0;
let updateTargetCallCount = 0;
binding.updateTarget = (updateTarget => {
return function (...args: unknown[]) {
updateTargetCallCount++;
return updateTarget.apply(this, args);
};
})(binding.updateTarget);
binding.partBindings[0].handleChange = (handleChange => {
return function (...args: unknown[]) {
handleChange1CallCount++;
return handleChange.apply(this, args);
};
})(binding.partBindings[0].handleChange);
binding.partBindings[1].handleChange = (handleChange => {
return function (...args: unknown[]) {
handleChange2CallCount++;
return handleChange.apply(this, args);
};
})(binding.partBindings[1].handleChange);
binding.$bind(LifecycleFlags.fromBind, createScopeForTest(source));
assert.strictEqual(target.value, 'no1--no2');
assert.deepStrictEqual(
[handleChange1CallCount, handleChange2CallCount, updateTargetCallCount],
[0, 0, 1],
);
// inactive branch of conditional shouldn't call handleChange
source.yes2 = 'yes22';
assert.strictEqual(target.value, 'no1--no2');
assert.deepStrictEqual(
[handleChange1CallCount, handleChange2CallCount, updateTargetCallCount],
[0, 0, 1],
);
source.yes1 = 'yes11';
assert.deepStrictEqual(
[handleChange1CallCount, handleChange2CallCount, updateTargetCallCount],
[0, 0, 1],
);
// reset for next assertion
source.yes2 = 'yes2';
source.yes1 = 'yes1';
source.checked2 = true;
assert.strictEqual(target.value, 'no1--yes2');
assert.deepStrictEqual(
[handleChange1CallCount, handleChange2CallCount, updateTargetCallCount],
[0, 1, 2],
);
source.checked1 = true;
assert.strictEqual(target.value, 'yes1--yes2');
assert.deepStrictEqual(
[handleChange1CallCount, handleChange2CallCount, updateTargetCallCount],
[1, 1, 3],
);
source.no1 = source.no2 = 'hello';
assert.strictEqual(target.value, 'yes1--yes2');
assert.deepStrictEqual(
[handleChange1CallCount, handleChange2CallCount, updateTargetCallCount],
[1, 1, 3],
);
});
});
});
describe('3-runtime/interpolation.spec.ts', function () {
it('observes and updates when bound with array', async function () {
const { tearDown, appHost, ctx, startPromise } = createFixture(
`<label repeat.for="product of products">
<input
type="checkbox"
model.bind="product.id"
checked.bind="selectedProductIds"></label>
Selected product IDs: \${selectedProductIds}`,
class App {
public products = [
{ id: 0, name: 'Motherboard' },
{ id: 1, name: 'CPU' },
{ id: 2, name: 'Memory' },
];
public selectedProductIds = [];
}
);
await startPromise;
assert.includes(appHost.textContent, 'Selected product IDs: ');
const [box1, box2, box3] = Array.from(appHost.querySelectorAll('input'));
box1.checked = true;
box1.dispatchEvent(new ctx.CustomEvent('change'));
assert.includes(appHost.textContent, 'Selected product IDs: ');
ctx.platform.domWriteQueue.flush();
assert.includes(appHost.textContent, 'Selected product IDs: 0');
box2.checked = true;
box2.dispatchEvent(new ctx.CustomEvent('change'));
assert.includes(appHost.textContent, 'Selected product IDs: 0');
ctx.platform.domWriteQueue.flush();
assert.includes(appHost.textContent, 'Selected product IDs: 0,1');
await tearDown();
});
it('[Repeat] interpolates expression with value converter that returns HTML nodes', async function () {
const { tearDown, appHost, ctx, component, startPromise } = createFixture(
`<template><div repeat.for="item of items">\${item.value | $}</div></template>`,
class App {
public items = Array.from({ length: 10 }, (_, idx) => {
return { value: idx + 1 };
});
},
[
ValueConverter.define('$', class MoneyValueConverter {
public static get inject() {
return [IPlatform];
}
public constructor(private readonly p: IPlatform) {}
public toView(val: string) {
let num = Number(val);
num = isNaN(num) ? 0 : num;
return this.toNode(`<span>$<b>${num}</b></span>`);
}
private toNode(html: string) {
const parser = this.p.document.createElement('div');
parser.innerHTML = html;
return parser.firstChild;
}
})
]
);
await startPromise;
let divs = Array.from(appHost.querySelectorAll('div'));
assert.strictEqual(divs.length, 10);
divs.forEach((div, idx) => {
assert.strictEqual(div.textContent, `$${idx + 1}`);
const b = div.querySelector('b');
assert.strictEqual(b.textContent, String(idx + 1));
});
component.items = Array.from({ length: 10 }, (_, idx) => {
return { value: idx + 11 };
});
divs = Array.from(appHost.querySelectorAll('div'));
assert.strictEqual(divs.length, 10);
divs.forEach((div, idx) => {
assert.strictEqual(div.textContent, `$${idx + 11}`);
const b = div.querySelector('b');
assert.strictEqual(b.textContent, String(idx + 11));
});
ctx.platform.domWriteQueue.flush();
divs.forEach((div, idx) => {
assert.strictEqual(div.textContent, `$${idx + 11}`);
const b = div.querySelector('b');
assert.strictEqual(b.textContent, String(idx + 11));
});
assert.strictEqual(appHost.textContent, component.items.map(item => `$${item.value}`).join(''));
component.items = [];
divs = Array.from(appHost.querySelectorAll('div'));
assert.strictEqual(divs.length, 0);
assert.strictEqual(appHost.textContent, '');
await tearDown();
assert.strictEqual(appHost.textContent, '');
});
it('[IF/Else] interpolates expression with value converter that returns HTML nodes in <template/>', async function () {
const { tearDown, appHost, component, startPromise } = createFixture(
`<template if.bind="show">\${message | $:'if'}</template><template else>\${message | $:'else'}</template>`,
class App {
public show = true;
public message = 'foo';
},
[
ValueConverter.define('$', class MoneyValueConverter {
public static get inject() {
return [IPlatform];
}
public constructor(private readonly p: IPlatform) {}
public toView(val: string, prefix: string) {
return this.toNode(`<${prefix}>${prefix} ${val}</${prefix}>`);
}
private toNode(html: string) {
const parser = this.p.document.createElement('div');
parser.innerHTML = html;
return parser.firstChild;
}
})
]
);
await startPromise;
assert.strictEqual(appHost.textContent, 'if foo');
assert.html.innerEqual(appHost, '<if>if foo</if>');
component.show = false;
assert.strictEqual(appHost.textContent, 'else foo');
assert.html.innerEqual(appHost, '<else>else foo</else>');
await tearDown();
// when a <template else/> is removed, it doesn't leave any nodes in the appended target
// so the app host text content is turned back to empty
assert.strictEqual(appHost.textContent, '');
assert.html.innerEqual(appHost, '');
});
});
describe('3-runtime/interpolation.spec.ts -- interpolation -- attributes', function () {
it('interpolates on value attr of <progress/>', async function () {
const { ctx, component, appHost, startPromise, tearDown } = createFixture(
`<progress value="\${progress}">`,
class App {
public progress = 0;
},
);
await startPromise;
const progress = appHost.querySelector('progress');
assert.strictEqual(progress.value, 0);
component.progress = 1;
ctx.platform.domWriteQueue.flush();
assert.strictEqual(progress.value, 1);
await tearDown();
});
it('interpolates value attr of <input />', async function () {
const { ctx, component, appHost, startPromise, tearDown } = createFixture(
`<input value="\${progress}">`,
class App {
public progress = 0;
},
);
await startPromise;
const input = appHost.querySelector('input');
assert.strictEqual(input.value, '0');
component.progress = 1;
assert.strictEqual(input.value, '0');
ctx.platform.domWriteQueue.flush();
assert.strictEqual(input.value, '1');
await tearDown();
});
it('interpolates value attr of <textarea />', async function () {
const { ctx, component, appHost, startPromise, tearDown } = createFixture(
`<textarea value="\${progress}">`,
class App {
public progress = 0;
},
);
await startPromise;
const textArea = appHost.querySelector('textarea');
assert.strictEqual(textArea.value, '0');
component.progress = 1;
assert.strictEqual(textArea.value, '0');
ctx.platform.domWriteQueue.flush();
assert.strictEqual(textArea.value, '1');
await tearDown();
});
it('interpolates the xlint:href attr of <use />', async function () {
const { ctx, component, appHost, startPromise, tearDown } = createFixture(
`<svg>
<circle id="blue" cx="5" cy="5" r="40" stroke="blue"/>
<circle id="red" cx="5" cy="5" r="40" stroke="red"/>
<use href="#\${progress > 0 ? 'blue' : 'red'}" x="10" fill="blue" />
`,
class App {
public progress = 0;
},
[SVGAnalyzerRegistration],
);
await startPromise;
const textArea = appHost.querySelector('use');
assert.strictEqual(textArea.getAttribute('href'), '#red');
component.progress = 1;
assert.strictEqual(textArea.getAttribute('href'), '#red');
ctx.platform.domWriteQueue.flush();
assert.strictEqual(textArea.getAttribute('href'), '#blue');
await tearDown();
});
}); | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace FormOpportunityProduct_Field_Service_Information {
interface tab_general_Sections {
pricing: DevKit.Controls.Section;
}
interface tab_tab_2_Sections {
tab_2_section_1: DevKit.Controls.Section;
tab_2_section_2: DevKit.Controls.Section;
tab_2_section_3: DevKit.Controls.Section;
}
interface tab_general extends DevKit.Controls.ITab {
Section: tab_general_Sections;
}
interface tab_tab_2 extends DevKit.Controls.ITab {
Section: tab_tab_2_Sections;
}
interface Tabs {
general: tab_general;
tab_2: tab_tab_2;
}
interface Body {
Tab: Tabs;
/** Shows the total price of the opportunity product, based on the price per unit, volume discount, and quantity. */
BaseAmount: DevKit.Controls.Money;
/** Date and time when the record was created. */
CreatedOn: DevKit.Controls.DateTime;
/** Shows the total amount due for the opportunity product, calculated on the Amount value minus the Manual Discount amount. */
ExtendedAmount: DevKit.Controls.Money;
/** Select whether the pricing on the opportunity product reflects an override of the product catalog pricing. */
IsPriceOverridden: DevKit.Controls.Boolean;
/** For system use only. */
IsProductOverridden: DevKit.Controls.Boolean;
/** Type the manual discount amount for the opportunity product to deduct any negotiated or other savings from the product total. */
ManualDiscountAmount: DevKit.Controls.Money;
/** Enter the duration of the agreement */
msdyn_Duration: DevKit.Controls.Integer;
/** Enter the end date of the agreement */
msdyn_enddate: DevKit.Controls.Date;
/** The field to distinguish the order lines to be of project service or field service */
msdyn_LineType: DevKit.Controls.OptionSet;
/** Select a price list for the opportunity line */
msdyn_pricelist: DevKit.Controls.Lookup;
/** Select the service account for the opportunity line */
msdyn_serviceaccount: DevKit.Controls.Lookup;
/** Start date of the Agreement */
msdyn_startdate: DevKit.Controls.Date;
/** Unique identifier of the opportunity with which the opportunity product is associated. */
OpportunityId: DevKit.Controls.Lookup;
/** Shows the price per unit of the opportunity product, based on the price list specified on the parent opportunity. */
PricePerUnit: DevKit.Controls.Money;
/** Type a detailed product description or additional notes about the opportunity product, such as talking points or product updates, that will assist the sales team when they discuss the product with the customer. */
ProductDescription: DevKit.Controls.String;
/** Choose the product to include on the opportunity to link the product's pricing and other information to the opportunity. */
ProductId: DevKit.Controls.Lookup;
/** Product Type */
ProductTypeCode: DevKit.Controls.OptionSet;
/** Type the amount or quantity of the product the customer would like to purchase. */
Quantity: DevKit.Controls.Decimal;
/** Type the tax amount to be applied on the opportunity product. */
Tax: DevKit.Controls.Money;
/** Choose the local currency for the record to make sure budgets are reported in the correct currency. */
TransactionCurrencyId: DevKit.Controls.Lookup;
/** Choose the unit of measurement for the base unit quantity for this purchase, such as each or dozen. */
UoMId: DevKit.Controls.Lookup;
/** Shows the discount amount per unit if a specified volume is purchased. Configure volume discounts in the Product Catalog in the Settings area. */
VolumeDiscountAmount: DevKit.Controls.Money;
}
}
class FormOpportunityProduct_Field_Service_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form OpportunityProduct_Field_Service_Information
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form OpportunityProduct_Field_Service_Information */
Body: DevKit.FormOpportunityProduct_Field_Service_Information.Body;
}
namespace FormOpportunityProduct_Information {
interface tab_general_Sections {
opportunity_product_information: DevKit.Controls.Section;
pricing: DevKit.Controls.Section;
}
interface tab_general extends DevKit.Controls.ITab {
Section: tab_general_Sections;
}
interface Tabs {
general: tab_general;
}
interface Body {
Tab: Tabs;
/** Shows the total price of the opportunity product, based on the price per unit, volume discount, and quantity. */
BaseAmount: DevKit.Controls.Money;
/** Shows the total amount due for the opportunity product, calculated on the Amount value minus the Manual Discount amount. */
ExtendedAmount: DevKit.Controls.Money;
/** Select whether the pricing on the opportunity product reflects an override of the product catalog pricing. */
IsPriceOverridden: DevKit.Controls.Boolean;
/** For system use only. */
IsProductOverridden: DevKit.Controls.Boolean;
/** Type the manual discount amount for the opportunity product to deduct any negotiated or other savings from the product total. */
ManualDiscountAmount: DevKit.Controls.Money;
/** Shows the price per unit of the opportunity product, based on the price list specified on the parent opportunity. */
PricePerUnit: DevKit.Controls.Money;
/** Type a detailed product description or additional notes about the opportunity product, such as talking points or product updates, that will assist the sales team when they discuss the product with the customer. */
ProductDescription: DevKit.Controls.String;
/** Choose the product to include on the opportunity to link the product's pricing and other information to the opportunity. */
ProductId: DevKit.Controls.Lookup;
/** Type the amount or quantity of the product the customer would like to purchase. */
Quantity: DevKit.Controls.Decimal;
/** Type the tax amount to be applied on the opportunity product. */
Tax: DevKit.Controls.Money;
/** Choose the unit of measurement for the base unit quantity for this purchase, such as each or dozen. */
UoMId: DevKit.Controls.Lookup;
/** Shows the discount amount per unit if a specified volume is purchased. Configure volume discounts in the Product Catalog in the Settings area. */
VolumeDiscountAmount: DevKit.Controls.Money;
}
}
class FormOpportunityProduct_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form OpportunityProduct_Information
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form OpportunityProduct_Information */
Body: DevKit.FormOpportunityProduct_Information.Body;
}
namespace FormOpportunityProduct {
interface tab_editproductpropertiesinlinetab_Sections {
productpropertiessection: DevKit.Controls.Section;
}
interface tab_general_Sections {
opportunity_product_information: DevKit.Controls.Section;
pricing: DevKit.Controls.Section;
}
interface tab_editproductpropertiesinlinetab extends DevKit.Controls.ITab {
Section: tab_editproductpropertiesinlinetab_Sections;
}
interface tab_general extends DevKit.Controls.ITab {
Section: tab_general_Sections;
}
interface Tabs {
editproductpropertiesinlinetab: tab_editproductpropertiesinlinetab;
general: tab_general;
}
interface Body {
Tab: Tabs;
/** Shows the total price of the opportunity product, based on the price per unit, volume discount, and quantity. */
BaseAmount: DevKit.Controls.Money;
/** Shows the total amount due for the opportunity product, calculated on the Amount value minus the Manual Discount amount. */
ExtendedAmount: DevKit.Controls.Money;
/** Select whether the pricing on the opportunity product reflects an override of the product catalog pricing. */
IsPriceOverridden: DevKit.Controls.Boolean;
/** For system use only. */
IsProductOverridden: DevKit.Controls.Boolean;
/** Type the manual discount amount for the opportunity product to deduct any negotiated or other savings from the product total. */
ManualDiscountAmount: DevKit.Controls.Money;
/** Unique identifier of the opportunity with which the opportunity product is associated. */
OpportunityId: DevKit.Controls.Lookup;
/** Shows the price per unit of the opportunity product, based on the price list specified on the parent opportunity. */
PricePerUnit: DevKit.Controls.Money;
/** Type a detailed product description or additional notes about the opportunity product, such as talking points or product updates, that will assist the sales team when they discuss the product with the customer. */
ProductDescription: DevKit.Controls.String;
/** Choose the product to include on the opportunity to link the product's pricing and other information to the opportunity. */
ProductId: DevKit.Controls.Lookup;
/** Type the amount or quantity of the product the customer would like to purchase. */
Quantity: DevKit.Controls.Decimal;
/** Type the tax amount to be applied on the opportunity product. */
Tax: DevKit.Controls.Money;
/** Choose the unit of measurement for the base unit quantity for this purchase, such as each or dozen. */
UoMId: DevKit.Controls.Lookup;
/** Shows the discount amount per unit if a specified volume is purchased. Configure volume discounts in the Product Catalog in the Settings area. */
VolumeDiscountAmount: DevKit.Controls.Money;
}
}
class FormOpportunityProduct extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form OpportunityProduct
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form OpportunityProduct */
Body: DevKit.FormOpportunityProduct.Body;
}
namespace FormOpportunityProduct_Project_Information {
interface tab_ProductGeneralTab_Sections {
opportunity_product_information: DevKit.Controls.Section;
pricing: DevKit.Controls.Section;
}
interface tab_ProjectGeneralTab_Sections {
ProjectSection: DevKit.Controls.Section;
}
interface tab_ProductGeneralTab extends DevKit.Controls.ITab {
Section: tab_ProductGeneralTab_Sections;
}
interface tab_ProjectGeneralTab extends DevKit.Controls.ITab {
Section: tab_ProjectGeneralTab_Sections;
}
interface Tabs {
ProductGeneralTab: tab_ProductGeneralTab;
ProjectGeneralTab: tab_ProjectGeneralTab;
}
interface Body {
Tab: Tabs;
/** Shows the total price of the opportunity product, based on the price per unit, volume discount, and quantity. */
BaseAmount: DevKit.Controls.Money;
/** Shows the total amount due for the opportunity product, calculated on the Amount value minus the Manual Discount amount. */
ExtendedAmount: DevKit.Controls.Money;
/** Select whether the pricing on the opportunity product reflects an override of the product catalog pricing. */
IsPriceOverridden: DevKit.Controls.Boolean;
/** For system use only. */
IsProductOverridden: DevKit.Controls.Boolean;
/** Type the manual discount amount for the opportunity product to deduct any negotiated or other savings from the product total. */
ManualDiscountAmount: DevKit.Controls.Money;
/** Billing method for the project opportunity line. Valid values are Time and Material and Fixed Price */
msdyn_BillingMethod: DevKit.Controls.OptionSet;
/** Enter the customer budget amount for this opportunity line. */
msdyn_BudgetAmount: DevKit.Controls.Money;
/** Enter the customer budget amount for this opportunity line. */
msdyn_BudgetAmount_1: DevKit.Controls.Money;
/** The field to distinguish the order lines to be of project service or field service */
msdyn_LineType: DevKit.Controls.OptionSet;
/** Unique identifier of the opportunity with which the opportunity product is associated. */
OpportunityId: DevKit.Controls.Lookup;
/** Unique identifier of the opportunity with which the opportunity product is associated. */
OpportunityId_1: DevKit.Controls.Lookup;
/** Shows the price per unit of the opportunity product, based on the price list specified on the parent opportunity. */
PricePerUnit: DevKit.Controls.Money;
/** Type a detailed product description or additional notes about the opportunity product, such as talking points or product updates, that will assist the sales team when they discuss the product with the customer. */
ProductDescription: DevKit.Controls.String;
/** Type a detailed product description or additional notes about the opportunity product, such as talking points or product updates, that will assist the sales team when they discuss the product with the customer. */
ProductDescription_1: DevKit.Controls.String;
/** Choose the product to include on the opportunity to link the product's pricing and other information to the opportunity. */
ProductId: DevKit.Controls.Lookup;
/** Product Type */
ProductTypeCode: DevKit.Controls.OptionSet;
/** Product Type */
ProductTypeCode_1: DevKit.Controls.OptionSet;
/** Product Type */
ProductTypeCode_2: DevKit.Controls.OptionSet;
/** Type the amount or quantity of the product the customer would like to purchase. */
Quantity: DevKit.Controls.Decimal;
/** Type the tax amount to be applied on the opportunity product. */
Tax: DevKit.Controls.Money;
/** Choose the unit of measurement for the base unit quantity for this purchase, such as each or dozen. */
UoMId: DevKit.Controls.Lookup;
/** Shows the discount amount per unit if a specified volume is purchased. Configure volume discounts in the Product Catalog in the Settings area. */
VolumeDiscountAmount: DevKit.Controls.Money;
}
}
class FormOpportunityProduct_Project_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form OpportunityProduct_Project_Information
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form OpportunityProduct_Project_Information */
Body: DevKit.FormOpportunityProduct_Project_Information.Body;
}
class OpportunityProductApi {
/**
* DynamicsCrm.DevKit OpportunityProductApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Shows the total price of the opportunity product, based on the price per unit, volume discount, and quantity. */
BaseAmount: DevKit.WebApi.MoneyValue;
/** Value of the Amount in base currency. */
BaseAmount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows who created the record. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was created. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who created the record on behalf of another user. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Type additional information to describe the opportunity product, such as manufacturing details. */
Description: DevKit.WebApi.StringValue;
/** The default image for the entity. */
EntityImage: DevKit.WebApi.StringValue;
EntityImage_Timestamp: DevKit.WebApi.BigIntValueReadonly;
EntityImage_URL: DevKit.WebApi.StringValueReadonly;
EntityImageId: DevKit.WebApi.GuidValueReadonly;
/** Shows the conversion rate of the record's currency. The exchange rate is used to convert all money fields in the record from the local currency to the system's default currency. */
ExchangeRate: DevKit.WebApi.DecimalValueReadonly;
/** Shows the total amount due for the opportunity product, calculated on the Amount value minus the Manual Discount amount. */
ExtendedAmount: DevKit.WebApi.MoneyValue;
/** Value of the Extended Amount in base currency. */
ExtendedAmount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Sequence number of the import that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Select whether the pricing on the opportunity product reflects an override of the product catalog pricing. */
IsPriceOverridden: DevKit.WebApi.BooleanValue;
/** For system use only. */
IsProductOverridden: DevKit.WebApi.BooleanValue;
/** Type the line item number for the opportunity product to easily identify the product in the opportunity documents and make sure it's listed in the correct order. */
LineItemNumber: DevKit.WebApi.IntegerValue;
/** Type the manual discount amount for the opportunity product to deduct any negotiated or other savings from the product total. */
ManualDiscountAmount: DevKit.WebApi.MoneyValue;
/** Value of the Manual Discount Amount in base currency. */
ManualDiscountAmount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows who last updated the record. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was modified. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who last modified the opportunityproduct. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Billing method for the project opportunity line. Valid values are Time and Material and Fixed Price */
msdyn_BillingMethod: DevKit.WebApi.OptionSetValue;
/** Enter the customer budget amount for this opportunity line. */
msdyn_BudgetAmount: DevKit.WebApi.MoneyValue;
/** Value of the Budget Amount in base currency. */
msdyn_budgetamount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the total cost price of the product based on the cost price per unit and quantity. */
msdyn_CostAmount: DevKit.WebApi.MoneyValue;
/** Value of the Cost Amount in base currency. */
msdyn_costamount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Cost price per unit of the product. The default is the cost price of the product. */
msdyn_CostPricePerUnit: DevKit.WebApi.MoneyValue;
/** Value of the Cost Price Per Unit in base currency. */
msdyn_costpriceperunit_Base: DevKit.WebApi.MoneyValueReadonly;
/** Enter the duration of the agreement */
msdyn_Duration: DevKit.WebApi.IntegerValue;
/** Enter the end date of the agreement */
msdyn_enddate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** The field to distinguish the order lines to be of project service or field service */
msdyn_LineType: DevKit.WebApi.OptionSetValue;
/** Select a price list for the opportunity line */
msdyn_pricelist: DevKit.WebApi.LookupValue;
/** Select the project for this opportunity line. */
msdyn_Project: DevKit.WebApi.LookupValue;
/** Select the service account for the opportunity line */
msdyn_serviceaccount: DevKit.WebApi.LookupValue;
/** Start date of the Agreement */
msdyn_startdate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Unique identifier of the opportunity with which the opportunity product is associated. */
OpportunityId: DevKit.WebApi.LookupValue;
/** Unique identifier of the opportunity product. */
OpportunityProductId: DevKit.WebApi.GuidValue;
/** Opportunity Product Name. Added for 1:n referential relationship (internal purposes only) */
OpportunityProductName: DevKit.WebApi.StringValue;
/** Select the status of the opportunity product. */
OpportunityStateCode: DevKit.WebApi.OptionSetValueReadonly;
/** Date and time that the record was migrated. */
OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */
OwnerId_systemuser: DevKit.WebApi.LookupValueReadonly;
/** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */
OwnerId_team: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the business unit that owns the record */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the team that owns the record. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the user that owns the record. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** Choose the parent bundle associated with this product */
ParentBundleId: DevKit.WebApi.GuidValue;
/** Choose the parent bundle associated with this product */
ParentBundleIdRef: DevKit.WebApi.LookupValue;
/** Shows the price per unit of the opportunity product, based on the price list specified on the parent opportunity. */
PricePerUnit: DevKit.WebApi.MoneyValue;
/** Value of the Price Per Unit in base currency. */
PricePerUnit_Base: DevKit.WebApi.MoneyValueReadonly;
/** Select the pricing error for the opportunity product. */
PricingErrorCode: DevKit.WebApi.OptionSetValue;
/** Unique identifier of the product line item association with bundle in the opportunity */
ProductAssociationId: DevKit.WebApi.GuidValue;
/** Type a detailed product description or additional notes about the opportunity product, such as talking points or product updates, that will assist the sales team when they discuss the product with the customer. */
ProductDescription: DevKit.WebApi.StringValue;
/** Choose the product to include on the opportunity to link the product's pricing and other information to the opportunity. */
ProductId: DevKit.WebApi.LookupValue;
/** Calculated field that will be populated by name and description of the product. */
ProductName: DevKit.WebApi.StringValue;
/** Product Type */
ProductTypeCode: DevKit.WebApi.OptionSetValue;
/** Status of the property configuration. */
PropertyConfigurationStatus: DevKit.WebApi.OptionSetValue;
/** Type the amount or quantity of the product the customer would like to purchase. */
Quantity: DevKit.WebApi.DecimalValue;
/** Shows the ID of the data that maintains the sequence. */
SequenceNumber: DevKit.WebApi.IntegerValue;
/** Skip price calculation */
SkipPriceCalculation: DevKit.WebApi.OptionSetValue;
/** Type the tax amount to be applied on the opportunity product. */
Tax: DevKit.WebApi.MoneyValue;
/** Value of the Tax in base currency. */
Tax_Base: DevKit.WebApi.MoneyValueReadonly;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Choose the local currency for the record to make sure budgets are reported in the correct currency. */
TransactionCurrencyId: DevKit.WebApi.LookupValue;
/** Choose the unit of measurement for the base unit quantity for this purchase, such as each or dozen. */
UoMId: DevKit.WebApi.LookupValue;
/** Time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
/** Version Number */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
/** Shows the discount amount per unit if a specified volume is purchased. Configure volume discounts in the Product Catalog in the Settings area. */
VolumeDiscountAmount: DevKit.WebApi.MoneyValueReadonly;
/** Value of the Volume Discount in base currency. */
VolumeDiscountAmount_Base: DevKit.WebApi.MoneyValueReadonly;
}
}
declare namespace OptionSet {
namespace OpportunityProduct {
enum msdyn_BillingMethod {
/** 192350001 */
Fixed_Price,
/** 192350000 */
Time_and_Material
}
enum msdyn_LineType {
/** 690970001 */
Field_Service_Line,
/** 690970000 */
Project_Service_Line
}
enum OpportunityStateCode {
}
enum PricingErrorCode {
/** 36 */
Base_Currency_Attribute_Overflow,
/** 37 */
Base_Currency_Attribute_Underflow,
/** 1 */
Detail_Error,
/** 27 */
Discount_Type_Invalid_State,
/** 33 */
Inactive_Discount_Type,
/** 3 */
Inactive_Price_Level,
/** 20 */
Invalid_Current_Cost,
/** 28 */
Invalid_Discount,
/** 26 */
Invalid_Discount_Type,
/** 19 */
Invalid_Price,
/** 17 */
Invalid_Price_Level_Amount,
/** 34 */
Invalid_Price_Level_Currency,
/** 18 */
Invalid_Price_Level_Percentage,
/** 9 */
Invalid_Pricing_Code,
/** 30 */
Invalid_Pricing_Precision,
/** 7 */
Invalid_Product,
/** 29 */
Invalid_Quantity,
/** 24 */
Invalid_Rounding_Amount,
/** 23 */
Invalid_Rounding_Option,
/** 22 */
Invalid_Rounding_Policy,
/** 21 */
Invalid_Standard_Cost,
/** 15 */
Missing_Current_Cost,
/** 14 */
Missing_Price,
/** 2 */
Missing_Price_Level,
/** 12 */
Missing_Price_Level_Amount,
/** 13 */
Missing_Price_Level_Percentage,
/** 8 */
Missing_Pricing_Code,
/** 6 */
Missing_Product,
/** 31 */
Missing_Product_Default_UOM,
/** 32 */
Missing_Product_UOM_Schedule_,
/** 4 */
Missing_Quantity,
/** 16 */
Missing_Standard_Cost,
/** 5 */
Missing_Unit_Price,
/** 10 */
Missing_UOM,
/** 0 */
None,
/** 35 */
Price_Attribute_Out_Of_Range,
/** 25 */
Price_Calculation_Error,
/** 11 */
Product_Not_In_Price_Level,
/** 38 */
Transaction_currency_is_not_set_for_the_product_price_list_item
}
enum ProductTypeCode {
/** 2 */
Bundle,
/** 4 */
Optional_Bundle_Product,
/** 1 */
Product,
/** 5 */
Project_based_Service,
/** 3 */
Required_Bundle_Product
}
enum PropertyConfigurationStatus {
/** 0 */
Edit,
/** 2 */
Not_Configured,
/** 1 */
Rectify
}
enum SkipPriceCalculation {
/** 0 */
DoPriceCalcAlways,
/** 1 */
SkipPriceCalcOnCreate,
/** 2 */
SkipPriceCalcOnUpdate,
/** 3 */
SkipPriceCalcOnUpSert
}
enum RollupState {
/** 0 - Attribute value is yet to be calculated */
NotCalculated,
/** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */
Calculated,
/** 2 - Attribute value calculation lead to overflow error */
OverflowError,
/** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */
OtherError,
/** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */
RetryLimitExceeded,
/** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */
HierarchicalRecursionLimitReached,
/** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */
LoopDetected
}
}
}
//{'JsForm':['Field Service Information','Information','OpportunityProduct','Project Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import { IUniq, readAnyFile } from "@creditkarma/mimic-core";
import {
Comment,
ConstValue,
EnumDefinition,
ExceptionDefinition,
FieldDefinition,
FunctionDefinition,
FunctionType,
Identifier,
parse,
StructDefinition,
SyntaxType,
TextLocation,
ThriftStatement,
TypedefDefinition,
UnionDefinition,
} from "@creditkarma/thrift-parser";
import * as path from "path";
import { ThriftFile } from "./index";
/* tslint:disable:radix */
enum KEYWORDS {
// Composite
StructDefinition = "struct",
UnionDefinition = "union",
ExceptionDefinition = "exception",
// Container
SetType = "set",
ListType = "list",
MapType = "map",
// Base
StringKeyword = "string",
DoubleKeyword = "double",
BoolKeyword = "bool",
I8Keyword = "i8",
I16Keyword = "i16",
I32Keyword = "i32",
I64Keyword = "i64",
BinaryKeyword = "binary",
ByteKeyword = "byte",
VoidKeyword = "void",
}
// List of initializer options
export interface IThriftOptions {
includes: string[];
}
// List of Identifiers
type Ident = StructDefinition | UnionDefinition | ExceptionDefinition | EnumDefinition | TypedefDefinition;
class FilesReadError extends Error {
public type = "FilesRead";
public file: string;
public includes: string[];
constructor(file: string, includes: string[]) {
super("Coudn't find/read file");
this.file = file;
this.includes = includes;
}
}
class ThriftError extends Error {
public type = "ThriftError";
public file: string;
public loc: TextLocation;
constructor(message: string, file: string, loc: TextLocation) {
super(message);
this.file = file;
this.loc = loc;
}
}
export interface IAstFile {
file: string;
content: ThriftStatement[];
}
/**
* Process Thrift file
*
* @class ThriftParser
*/
export class ThriftParser {
private identifiers: { [key: string]: Ident } = {};
private includes: string[];
// Constructor
constructor({ includes }: IThriftOptions) {
this.includes = includes;
}
/**
* Parse Thrift file and return JSON representation
*/
public parse(filePath: string, callback: (err: Error | null, data?: ThriftFile.IJSON) => void) {
// Reset type definitions
this.identifiers = {};
const name = path.basename(filePath, ".thrift");
this.parseThriftFiles(filePath, [""]).then(
(ast) => {
try {
const data = this.astToJson(name, ast);
callback(null, data);
} catch (error) {
callback(error);
}
},
(err) => callback(err),
);
}
/**
* Parse Thrift file with all includes recursively
*/
public parseThriftFiles = (filePath: string, includes: string[]): Promise<IAstFile[]> => {
// Construct a list of files to look for
const filePaths = includes.map((include) => path.join(include, filePath));
// Read any file from the list
return readAnyFile(filePaths).then(({ file, data }) => {
// Parse Thrift file
const thriftAST = parse(data);
// Switch parse result
switch (thriftAST.type) {
// On success
case SyntaxType.ThriftDocument:
const promises: Array<Promise<IAstFile[]>> = [];
thriftAST.body.forEach((st) => {
switch (st.type) {
// Read all files from include statements
case SyntaxType.IncludeDefinition:
const current = path.dirname(file);
promises.push(this.parseThriftFiles(st.path.value, [current, ...this.includes]));
break;
// Index identifiers
case SyntaxType.TypedefDefinition:
case SyntaxType.EnumDefinition:
case SyntaxType.StructDefinition:
case SyntaxType.UnionDefinition:
case SyntaxType.ExceptionDefinition:
if (!this.identifiers.hasOwnProperty(st.name.value)) {
this.identifiers[st.name.value] = st;
}
}
});
// Return promise with merged files content
return Promise.all(promises).then(
(val) => Promise.resolve([...val, [{ file, content: thriftAST.body }]].reduce((a, b) => a.concat(b))),
(errors) => Promise.reject(errors),
);
case SyntaxType.ThriftErrors:
return Promise.reject(thriftAST);
}
}, () => Promise.reject(new FilesReadError(filePath, includes)));
}
/**
* Convert AST statements to JSON representation
*/
public astToJson = (name: string, ast: IAstFile[]): ThriftFile.IJSON => {
const enums: IUniq<ThriftFile.IEnum> = {};
const typedefs: IUniq<ThriftFile.ITypeDef> = {};
const structs: IUniq<ThriftFile.IStruct> = {};
const constants: IUniq<ThriftFile.IConstant> = {};
const services: IUniq<ThriftFile.IService> = {};
for (const { file, content } of ast) {
for (const def of content) {
switch (def.type) {
case SyntaxType.EnumDefinition:
let value = -1;
enums[def.name.value] = {
name: def.name.value,
...this.comments(def.comments),
members: def.members.map((m) => {
value = m.initializer ? parseInt(m.initializer.value.value) : value + 1;
return { name: m.name.value, value };
}),
};
break;
case SyntaxType.TypedefDefinition:
typedefs[def.name.value] = {
name: def.name.value,
...this.comments(def.comments),
...this.astToType(def.definitionType, file),
};
break;
case SyntaxType.StructDefinition:
case SyntaxType.UnionDefinition:
case SyntaxType.ExceptionDefinition:
structs[def.name.value] = {
name: def.name.value,
isException: def.type === SyntaxType.ExceptionDefinition,
isUnion: def.type === SyntaxType.UnionDefinition,
fields: def.fields.map((f) => this.fieldToJson(f, file)),
...this.comments(def.comments),
};
break;
case SyntaxType.ConstDefinition:
constants[def.name.value] = {
name: def.name.value,
...this.comments(def.comments),
value: this.constToJson(def.initializer),
...this.astToType(def.fieldType, file),
};
break;
case SyntaxType.ServiceDefinition:
services[def.name.value] = {
name: def.name.value,
...def.extends && { extends: this.ident(def.extends) },
...this.comments(def.comments),
functions: def.functions.map((f) => this.funcToJson(f, file))
.sort((a, b) => a.name.localeCompare(b.name)),
};
}
}
}
return {
name,
enums: Object.keys(enums).sort().map((k) => enums[k]),
typedefs: Object.keys(typedefs).sort().map((k) => typedefs[k]),
structs: Object.keys(structs).sort().map((k) => structs[k]),
constants: Object.keys(constants).sort().map((k) => constants[k]),
services: Object.keys(services).map((key) => services[key]),
};
}
/**
* Convert Function AST statement to JSON representation
*/
public funcToJson = (func: FunctionDefinition, file: string): ThriftFile.IFunction => {
const { typeId: returnTypeId, type: returnType, extra: returnExtra } = this.astToType(func.returnType, file);
return {
name: func.name.value,
returnTypeId,
...returnType && { returnType },
...returnExtra && { returnExtra },
oneway: func.oneway,
...this.comments(func.comments),
arguments: func.fields.map((f) => this.fieldToJson(f, file)),
exceptions: func.throws.map((t) => this.fieldToJson(t, file) as ThriftFile.IException),
};
}
/**
* Convert Field AST statement to JSON representation
*/
public fieldToJson = (field: FieldDefinition, file: string): ThriftFile.IField => {
if (!field.fieldID || field.fieldID.value < 1) {
throw new ThriftError("Invalid field id", file, field.loc);
}
return {
key: field.fieldID.value,
name: field.name.value,
...this.astToType(field.fieldType, file),
required: field.requiredness || "req_out" as "req_out",
...field.defaultValue && { default: this.constToJson(field.defaultValue) },
};
}
/**
* Convert Type AST representation to JSON type
*/
public astToType = (ast: FunctionType, file: string): ThriftFile.IFieldType => {
switch (ast.type) {
case SyntaxType.Identifier:
return this.identToType(ast, file);
case SyntaxType.SetType:
case SyntaxType.ListType:
const { typeId: elemTypeId, type: elemType, extra } = this.astToType(ast.valueType, file);
return {
typeId: KEYWORDS[ast.type],
type: {
typeId: KEYWORDS[ast.type] as "set",
elemTypeId, elemType, extra,
},
};
case SyntaxType.MapType:
const { typeId: keyTypeId, type: keyType, extra: keyExtra } = this.astToType(ast.keyType, file);
const { typeId: valueTypeId, type: valueType, extra: valueExtra } = this.astToType(ast.valueType, file);
return {
typeId: KEYWORDS.MapType,
type: {
typeId: KEYWORDS.MapType,
keyTypeId, valueTypeId,
...keyType && { keyType }, ...valueType && { valueType },
...keyExtra && { keyExtra }, ...valueExtra && { valueExtra },
},
};
case SyntaxType.StringKeyword:
case SyntaxType.DoubleKeyword:
case SyntaxType.BoolKeyword:
case SyntaxType.I8Keyword:
case SyntaxType.I16Keyword:
case SyntaxType.I32Keyword:
case SyntaxType.I64Keyword:
case SyntaxType.BinaryKeyword:
case SyntaxType.ByteKeyword:
case SyntaxType.VoidKeyword:
return {
typeId: KEYWORDS[ast.type],
};
}
}
/**
* Convert Identifier AST to JSON type
*/
public identToType = (ast: Identifier, file: string): ThriftFile.IFieldType => {
const ident = this.identifiers[this.ident(ast)];
if (!ident) {
throw new ThriftError(`Can't find "${ast.value}" identifier`, file, ast.loc);
}
switch (ident.type) {
case SyntaxType.StructDefinition:
return {
typeId: KEYWORDS.StructDefinition,
type: {
typeId: KEYWORDS.StructDefinition,
class: this.ident(ast),
},
};
case SyntaxType.UnionDefinition:
return {
typeId: KEYWORDS.UnionDefinition,
type: {
typeId: KEYWORDS.UnionDefinition,
class: this.ident(ast),
},
};
case SyntaxType.ExceptionDefinition:
return {
typeId: "exception",
type: {
typeId: "exception",
class: this.ident(ast),
},
};
case SyntaxType.EnumDefinition:
return {
typeId: KEYWORDS.I32Keyword,
extra: {
typeId: "enum",
class: this.ident(ast),
},
};
case SyntaxType.TypedefDefinition:
return {
...this.astToType(ident.definitionType, file),
extra: {
typeId: "typedef",
class: this.ident(ast),
},
};
}
}
/**
* Convert Constant value to JSON type
*/
public constToJson = (constant: ConstValue): any => {
switch (constant.type) {
case SyntaxType.StringLiteral:
case SyntaxType.BooleanLiteral:
case SyntaxType.Identifier:
return constant.value;
case SyntaxType.IntConstant:
return parseInt(constant.value.value);
case SyntaxType.DoubleConstant:
return parseFloat(constant.value.value);
case SyntaxType.ConstMap:
return constant.properties.reduce((acum, v) => ({
...acum, [this.constToJson(v.name)]: this.constToJson(v.initializer),
}), {});
case SyntaxType.ConstList:
return constant.elements.map(this.constToJson);
}
}
public comments = (input: Comment[]) => {
if (input.length === 0) { return {}; }
const doc = input.reduce((a, v) => {
switch (v.type) {
case SyntaxType.CommentLine:
return a + v.value;
case SyntaxType.CommentBlock:
return a + v.value.join("");
}
}, "");
return { doc };
}
public ident = (input: Identifier) => (
input.value.split(".").pop() || input.value
)
}
export default ThriftParser; | the_stack |
import { extractHeadings } from './lib/extract'
import { enterReadableMode, leaveReadableMode } from './lib/readable'
import { getScrollElement, getScrollTop, smoothScroll } from './lib/scroll'
import { Article, Content, Heading, Scroller } from './types'
import { ui } from './ui/index'
import { createEventEmitter } from './util/event'
import { Stream } from './util/stream'
export interface TocPreference {
offset: {
x: number
y: number
}
}
export interface TocEvents {
error: {
reason: string
}
}
function activeHeadingStream({
scroller,
$isShown,
$content,
$topbarHeight,
addDisposer,
}: {
scroller: HTMLElement
$isShown: Stream<boolean>
$content: Stream<Content>
$topbarHeight: Stream<number>
addDisposer: (unsub: () => void) => number
}) {
const calcActiveHeading = ({
article,
scroller,
headings,
topbarHeight,
}: {
article: Article
scroller: Scroller
headings: Heading[]
topbarHeight: number
}): number => {
const visibleAreaHeight = Math.max(topbarHeight, scroller.rect.top)
const scrollY = getScrollTop(scroller.dom)
let i = 0
for (; i < headings.length; i++) {
const heading = headings[i]
const headingRectTop =
scroller.rect.top -
scrollY +
article.fromScrollerTop +
heading.fromArticleTop!
const isCompletelyVisible = headingRectTop >= visibleAreaHeight + 15
if (isCompletelyVisible) {
break
}
}
// the 'nearly-visible' heading (headings[i-1]) is the current heading
const curIndex = Math.max(0, i - 1)
return curIndex
}
const $scroll = Stream.fromEvent(
scroller === document.body ? window : scroller,
'scroll',
addDisposer,
)
.map(() => null)
.startsWith(null)
.log('scroll')
const $activeHeading: Stream<number> = Stream.combine(
$content,
$topbarHeight,
$scroll,
$isShown,
)
.filter(() => $isShown())
.map(([content, topbarHeight, _]) => {
const { article, scroller, headings } = content
if (!(headings && headings.length)) {
return 0
} else {
return calcActiveHeading({
article,
scroller,
headings,
topbarHeight: topbarHeight || 0,
})
}
})
return $activeHeading
}
function contentStream({
$isShown,
$periodicCheck,
$triggerContentChange,
article,
scroller,
addDisposer,
}: {
article: HTMLElement
scroller: HTMLElement
$triggerContentChange: Stream<null>
$isShown: Stream<boolean>
$periodicCheck: Stream<null>
addDisposer: (unsub: () => void) => number
}) {
const $resize = Stream.fromEvent(window, 'resize', addDisposer)
.throttle(100)
.log('resize')
const $content: Stream<Content> = Stream.merge(
$triggerContentChange,
$isShown,
$resize,
$periodicCheck,
)
.filter(() => $isShown())
.map((): Content => {
const articleRect = article.getBoundingClientRect()
const scrollerRect =
scroller === document.body || scroller === document.documentElement
? {
left: 0,
right: window.innerWidth,
top: 0,
bottom: window.innerHeight,
height: window.innerHeight,
width: window.innerWidth,
}
: scroller.getBoundingClientRect()
const headings = extractHeadings(article)
const scrollY = getScrollTop(scroller)
const headingsMeasured = headings.map((h) => {
const headingRect = h.dom.getBoundingClientRect()
return {
...h,
fromArticleTop:
headingRect.top - (articleRect.top - article.scrollTop),
}
})
return {
article: {
dom: article,
fromScrollerTop:
article === scroller
? 0
: articleRect.top - scrollerRect.top + scrollY,
left: articleRect.left,
right: articleRect.right,
height: articleRect.height,
},
scroller: {
dom: scroller,
rect: scrollerRect,
},
headings: headingsMeasured,
}
})
return $content
}
function topbarStream($triggerTopbarMeasure: Stream<HTMLElement>) {
const getTopbarHeight = (targetElem: HTMLElement): number => {
const findFixedParent = (elem: HTMLElement | null) => {
const isFixed = (elem: HTMLElement) => {
let { position, zIndex } = window.getComputedStyle(elem)
return position === 'fixed' && zIndex
}
while (elem && elem !== document.body && !isFixed(elem)) {
elem = elem.parentElement
}
return elem === document.body ? null : elem
}
const { top, left, right, bottom } = targetElem.getBoundingClientRect()
const leftTopmost = document.elementFromPoint(left + 1, top + 1)
const rightTopmost = document.elementFromPoint(right - 1, top + 1)
const leftTopFixed =
leftTopmost && findFixedParent(leftTopmost as HTMLElement)
const rightTopFixed =
rightTopmost && findFixedParent(rightTopmost as HTMLElement)
if (leftTopFixed && rightTopFixed && leftTopFixed === rightTopFixed) {
return leftTopFixed.offsetHeight
} else {
return 0
}
}
const $topbarHeightMeasured: Stream<number> = $triggerTopbarMeasure
.throttle(50)
.map((elem) => getTopbarHeight(elem))
.unique()
.log('topbarHeightMeasured')
const $topbarHeight: Stream<number> = $topbarHeightMeasured.scan(
(height, measured) => Math.max(height, measured),
0 as number,
)
return $topbarHeight
}
export function createToc(options: {
article: HTMLElement
preference: TocPreference
}) {
const article = options.article
const scroller = getScrollElement(article)
//-------------- Helpers --------------
const disposers: (() => void)[] = []
const addDisposer = (dispose: () => void) => disposers.push(dispose)
const emitter = createEventEmitter<TocEvents>()
//-------------- Triggers --------------
const $triggerTopbarMeasure = Stream<HTMLElement>().log(
'triggerTopbarMeasure',
)
const $triggerContentChange = Stream<null>(null).log('triggerContentChange')
const $triggerIsShown = Stream<boolean>().log('triggerIsShown')
const $periodicCheck = Stream.fromInterval(1000 * 60, addDisposer).log(
'check',
)
//-------------- Observables --------------
const $isShown = $triggerIsShown.unique().log('isShown')
const $topbarHeight = topbarStream($triggerTopbarMeasure).log('topbarHeight')
const $content = contentStream({
$triggerContentChange,
$periodicCheck,
$isShown,
article,
scroller,
addDisposer,
}).log('content')
const $activeHeading: Stream<number> = activeHeadingStream({
scroller,
$isShown,
$content,
$topbarHeight,
addDisposer,
}).log('activeHeading')
const $offset = Stream<TocPreference['offset']>(
options.preference.offset,
).log('offset')
const $readableMode = Stream.combine(
$isShown.unique(),
$content.map((c) => c.article.height).unique(),
$content.map((c) => c.scroller.rect.height).unique(),
$content.map((c) => c.headings.length).unique(),
)
.map(([isShown]) => isShown)
.log('readable')
//-------------- Effects --------------
const scrollToHeading = (headingIndex: number): Promise<void> => {
return new Promise((resolve, reject) => {
const { headings, scroller } = $content()
const topbarHeight = $topbarHeight()
const heading = headings[headingIndex]
if (heading) {
smoothScroll({
target: heading.dom,
scroller: scroller.dom,
topMargin: topbarHeight || 0 + 10,
callback() {
$triggerTopbarMeasure(heading.dom)
resolve()
},
})
} else {
resolve()
}
})
}
$readableMode.subscribe((enableReadableMode) => {
if (enableReadableMode) {
enterReadableMode($content(), { topbarHeight: $topbarHeight() })
} else {
leaveReadableMode()
}
$triggerContentChange(null)
})
const validate = (content: Content): void => {
const { article, headings, scroller } = content
const isScrollerValid =
document.documentElement === scroller.dom ||
document.documentElement.contains(scroller.dom)
const isArticleValid =
scroller.dom === article.dom || scroller.dom.contains(article.dom)
const isHeadingsValid =
headings.length &&
article.dom.contains(headings[0].dom) &&
article.dom.contains(headings[headings.length - 1].dom)
const isValid = isScrollerValid && isArticleValid && isHeadingsValid
if (!isValid) {
emitter.emit('error', { reason: 'Article Changed' })
}
}
$content.subscribe(validate)
ui.render({
$isShown,
$article: $content.map((c) => c.article),
$scroller: $content.map((c) => c.scroller),
$headings: $content.map((c) => c.headings),
$offset,
$activeHeading,
$topbarHeight,
onDrag(offset) {
$offset(offset)
},
onScrollToHeading: scrollToHeading,
})
//-------------- Exposed Commands --------------
const next = () => {
const { headings } = $content()
const activeHeading = $activeHeading()
const nextIndex = Math.min(headings.length - 1, activeHeading + 1)
scrollToHeading(nextIndex)
}
const prev = () => {
const activeHeading = $activeHeading()
const prevIndex = Math.max(0, activeHeading - 1)
scrollToHeading(prevIndex)
}
const show = () => {
$triggerIsShown(true)
}
const hide = () => {
$triggerIsShown(false)
}
const toggle = () => {
if ($isShown()) {
hide()
} else {
show()
}
}
const dispose = () => {
hide()
disposers.forEach((dispose) => dispose())
emitter.removeAllListeners()
}
const getPreference = (): TocPreference => {
return {
offset: $offset(),
}
}
return {
...emitter,
show,
hide,
toggle,
prev,
next,
getPreference,
dispose,
}
}
export type Toc = ReturnType<typeof createToc> | the_stack |
import { ClassType, CompilerContext } from '@deepkit/core';
import { ClassSchema, getClassSchema, getSortedUnionTypes, PropertySchema } from '@deepkit/type';
import { BaseParser, ParserV2 } from './bson-parser';
import { bsonTypeGuards } from './bson-typeguards';
import { seekElementSize } from './continuation';
import { BSON_BINARY_SUBTYPE_UUID, BSONType, digitByteSize } from './utils';
function createPropertyConverter(setter: string, property: PropertySchema, compiler: CompilerContext, parentProperty?: PropertySchema): string {
//we want the isNullable value from the actual property, not the decorated.
const defaultValue = !property.hasDefaultValue && property.defaultValue !== undefined ?
`${compiler.reserveVariable('defaultValue', property.defaultValue)}()`
: 'undefined';
if (property.type === 'promise') {
property = property.templateArgs[0] || new PropertySchema(property.name);
}
const nullCheck = `
if (elementType === ${BSONType.UNDEFINED}) {
if (${property.isOptional}) ${setter} = ${defaultValue};
} else if (elementType === ${BSONType.NULL}) {
if (${property.isOptional}) ${setter} = ${defaultValue};
if (${property.isNullable}) ${setter} = null;
}`;
const nullOrSeek = `
${nullCheck} else {
seekElementSize(elementType, parser);
}
`;
// if (property.type === 'class' && property.getResolvedClassSchema().decorator) {
// property = property.getResolvedClassSchema().getDecoratedPropertySchema();
// }
const propertyVar = compiler.reserveVariable('_property_' + property.name, property);
if (property.type === 'string') {
return `
if (elementType === ${BSONType.STRING}) {
const size = parser.eatUInt32(); //size
${setter} = parser.eatString(size);
} else {
${nullOrSeek}
}
`;
} else if (property.type === 'literal') {
const literalValue = compiler.reserveVariable('literalValue', property.literalValue);
if (property.isOptional || property.isNullable) {
return `
if (${property.isOptional} && (elementType === ${BSONType.UNDEFINED} || elementType === ${BSONType.NULL})) {
${setter} = ${defaultValue};
} else if (${property.isNullable} && elementType === ${BSONType.NULL}) {
${setter} = null;
} else {
${setter} = ${literalValue};
seekElementSize(elementType, parser);
}
`;
} else {
return `
${setter} = ${literalValue};
seekElementSize(elementType, parser);
`;
}
} else if (property.type === 'enum') {
return `
if (elementType === ${BSONType.STRING} || elementType === ${BSONType.NUMBER} || elementType === ${BSONType.INT} || elementType === ${BSONType.LONG}) {
${setter} = parser.parse(elementType);
} else {
${nullOrSeek}
}`;
} else if (property.type === 'boolean') {
return `
if (elementType === ${BSONType.BOOLEAN}) {
${setter} = parser.parseBoolean();
} else {
${nullOrSeek}
}
`;
} else if (property.type === 'date') {
return `
if (elementType === ${BSONType.DATE}) {
${setter} = parser.parseDate();
} else {
${nullOrSeek}
}
`;
} else if (property.type === 'bigint') {
return `
if (elementType === ${BSONType.INT}) {
${setter} = BigInt(parser.parseInt());
} else if (elementType === ${BSONType.NUMBER}) {
${setter} = BigInt(parser.parseNumber());
} else if (elementType === ${BSONType.LONG} || elementType === ${BSONType.TIMESTAMP}) {
${setter} = parser.parseLong();
} else if (elementType === ${BSONType.BINARY}) {
${setter} = parser.parseBinary();
} else {
${nullOrSeek}
}
`;
} else if (property.type === 'number') {
return `
if (elementType === ${BSONType.INT}) {
${setter} = parser.parseInt();
} else if (elementType === ${BSONType.NUMBER}) {
${setter} = parser.parseNumber();
} else if (elementType === ${BSONType.LONG} || elementType === ${BSONType.TIMESTAMP}) {
${setter} = parser.parseLong();
} else {
${nullOrSeek}
}
`;
} else if (property.type === 'uuid') {
return `
if (elementType === ${BSONType.BINARY}) {
parser.eatUInt32(); //size
const subType = parser.eatByte();
if (subType !== ${BSON_BINARY_SUBTYPE_UUID}) throw new Error('${property.name} BSON binary type invalid. Expected UUID(4), but got ' + subType);
${setter} = parser.parseUUID();
} else {
${nullOrSeek}
}
`;
} else if (property.type === 'objectId') {
return `
if (elementType === ${BSONType.OID}) {
${setter} = parser.parseOid();
} else {
${nullOrSeek}
}
`;
} else if (property.type === 'partial') {
const object = compiler.reserveVariable('partialObject', {});
const propertyCode: string[] = [];
const schema = property.getResolvedClassSchema();
for (let subProperty of schema.getProperties()) {
//todo, support non-ascii names
const bufferCompare: string[] = [];
for (let i = 0; i < subProperty.name.length; i++) {
bufferCompare.push(`parser.buffer[parser.offset + ${i}] === ${subProperty.name.charCodeAt(i)}`);
}
bufferCompare.push(`parser.buffer[parser.offset + ${subProperty.name.length}] === 0`);
propertyCode.push(`
//partial: property ${subProperty.name} (${subProperty.toString()})
if (${bufferCompare.join(' && ')}) {
parser.offset += ${subProperty.name.length} + 1;
${createPropertyConverter(`${object}.${subProperty.name}`, subProperty, compiler)}
continue;
}
`);
}
return `
if (elementType === ${BSONType.OBJECT}) {
${object} = {};
const end = parser.eatUInt32() + parser.offset;
while (parser.offset < end) {
const elementType = parser.eatByte();
if (elementType === 0) break;
${propertyCode.join('\n')}
//jump over this property when not registered in schema
while (parser.offset < end && parser.buffer[parser.offset++] != 0);
//seek property value
if (parser.offset >= end) break;
seekElementSize(elementType, parser);
}
${setter} = ${object};
} else {
${nullOrSeek}
}
`;
} else if (property.type === 'class') {
const schema = property.getResolvedClassSchema();
if (schema.decorator) {
//we need to create the instance and assign
const forwardProperty = schema.getDecoratedPropertySchema();
const decoratedVar = compiler.reserveVariable('decorated');
const classTypeVar = compiler.reserveVariable('classType', property.classType);
let arg = '';
const propertyAssign: string[] = [];
const check = forwardProperty.isOptional ? `'v' in ${decoratedVar}` : `${decoratedVar}.v !== undefined`;
if (forwardProperty.methodName === 'constructor') {
arg = `(${check} ? ${decoratedVar}.v : undefined)`;
} else {
propertyAssign.push(`if (${check}) ${setter}.${forwardProperty.name} = ${decoratedVar}.v;`);
}
return `
//decorated
if (elementType !== ${BSONType.UNDEFINED} && elementType !== ${BSONType.NULL}) {
${decoratedVar} = {};
${createPropertyConverter(`${decoratedVar}.v`, schema.getDecoratedPropertySchema(), compiler)}
${setter} = new ${classTypeVar}(${arg});
${propertyAssign.join('\n')}
} else {
${nullOrSeek}
}
`;
}
const propertySchema = compiler.reserveVariable('_propertySchema_' + property.name, property.getResolvedClassSchema());
compiler.context.set('getRawBSONDecoder', getRawBSONDecoder);
let primaryKeyHandling = '';
if (property.isReference) {
primaryKeyHandling = createPropertyConverter(setter, property.getResolvedClassSchema().getPrimaryField(), compiler);
}
return `
if (elementType === ${BSONType.OBJECT}) {
${setter} = getRawBSONDecoder(${propertySchema})(parser);
} else if (${property.isReference}) {
${primaryKeyHandling}
} else {
${nullOrSeek}
}
`;
} else if (property.type === 'array') {
compiler.context.set('digitByteSize', digitByteSize);
const v = compiler.reserveName('v');
return `
if (elementType === ${BSONType.ARRAY}) {
${setter} = [];
parser.seek(4);
for (let i = 0; ; i++) {
const elementType = parser.eatByte();
if (elementType === 0) break;
//arrays are represented as objects, so we skip the key name
parser.seek(digitByteSize(i));
let ${v} = undefined;
${createPropertyConverter(v, property.getSubType(), compiler, property)}
${setter}.push(${v});
}
} else {
${nullOrSeek}
}
`;
} else if (property.type === 'map') {
const name = compiler.reserveVariable('propertyName');
return `
if (elementType === ${BSONType.OBJECT}) {
${setter} = {};
parser.seek(4);
while (true) {
const elementType = parser.eatByte();
if (elementType === 0) break;
${name} = parser.eatObjectPropertyName();
${createPropertyConverter(`${setter}[${name}]`, property.getSubType(), compiler)}
}
} else {
${nullOrSeek}
}
`;
} else if (property.type === 'union') {
let discriminator: string[] = [`if (false) {\n}`];
const discriminants: string[] = [];
for (const unionType of getSortedUnionTypes(property, bsonTypeGuards)) {
discriminants.push(unionType.property.type);
}
for (const unionType of getSortedUnionTypes(property, bsonTypeGuards)) {
const guardVar = compiler.reserveVariable('guard_' + unionType.property.type, unionType.guard);
discriminator.push(`
//guard:${unionType.property.type}
else if (${guardVar}(elementType, parser)) {
${createPropertyConverter(setter, unionType.property, compiler, property)}
}
`);
}
return `
${discriminator.join('\n')}
else {
${nullOrSeek}
}
`;
}
return `
${nullCheck} else {
${setter} = parser.parse(elementType, ${propertyVar});
}
`;
}
interface DecoderFn {
buildId: number;
(parser: BaseParser, offset?: number): any;
}
function createSchemaDecoder(schema: ClassSchema): DecoderFn {
const compiler = new CompilerContext();
compiler.context.set('seekElementSize', seekElementSize);
const setProperties: string[] = [];
const constructorArgumentNames: string[] = [];
const constructorParameter = schema.getMethodProperties('constructor');
const resetDefaultSets: string[] = [];
const setDefaults: string[] = [];
const propertyCode: string[] = [];
for (const property of schema.getProperties()) {
//todo, support non-ascii names
const bufferCompare: string[] = [];
for (let i = 0; i < property.name.length; i++) {
bufferCompare.push(`parser.buffer[parser.offset + ${i}] === ${property.name.charCodeAt(i)}`);
}
bufferCompare.push(`parser.buffer[parser.offset + ${property.name.length}] === 0`);
const valueSetVar = compiler.reserveVariable('valueSetVar', false);
const defaultValue = property.defaultValue !== undefined ? compiler.reserveVariable('defaultValue', property.defaultValue) : 'undefined';
if (property.hasManualDefaultValue() || property.type === 'literal') {
resetDefaultSets.push(`${valueSetVar} = false;`)
if (property.defaultValue !== undefined) {
setDefaults.push(`if (!${valueSetVar}) object.${property.name} = ${defaultValue};`)
} else if (property.type === 'literal' && !property.isOptional) {
setDefaults.push(`if (!${valueSetVar}) object.${property.name} = ${JSON.stringify(property.literalValue)};`)
}
} else if (property.isNullable) {
resetDefaultSets.push(`${valueSetVar} = false;`)
setDefaults.push(`if (!${valueSetVar}) object.${property.name} = null;`)
}
const check = property.isOptional ? `${JSON.stringify(property.name)} in object` : `object.${property.name} !== undefined`;
if (property.methodName === 'constructor') {
constructorArgumentNames[constructorParameter.indexOf(property)] = `(${check} ? object.${property.name} : ${defaultValue})`;
} else {
if (property.isParentReference) {
throw new Error('Parent references not supported in BSON.');
} else {
setProperties.push(`if (${check}) _instance.${property.name} = object.${property.name};`);
}
}
propertyCode.push(`
//property ${property.name} (${property.toString()})
if (${bufferCompare.join(' && ')}) {
parser.offset += ${property.name.length} + 1;
${valueSetVar ? `${valueSetVar} = true;` : ''}
${createPropertyConverter(`object.${property.name}`, property, compiler)}
continue;
} `);
}
let instantiate = '';
compiler.context.set('_classType', schema.classType);
if (schema.isCustomClass()) {
instantiate = `
_instance = new _classType(${constructorArgumentNames.join(', ')});
${setProperties.join('\n')}
return _instance;
`;
}
const functionCode = `
var object = ${schema.isCustomClass() ? '{}' : 'new _classType'};
${schema.isCustomClass() ? 'var _instance;' : ''}
const end = parser.eatUInt32() + parser.offset;
${resetDefaultSets.join('\n')}
while (parser.offset < end) {
const elementType = parser.eatByte();
if (elementType === 0) break;
${propertyCode.join('\n')}
//jump over this property when not registered in schema
while (parser.offset < end && parser.buffer[parser.offset++] != 0);
//seek property value
if (parser.offset >= end) break;
seekElementSize(elementType, parser);
}
${setDefaults.join('\n')}
${schema.isCustomClass() ? instantiate : 'return object;'}
`;
const fn = compiler.build(functionCode, 'parser', 'partial');
fn.buildId = schema.buildId;
return fn;
}
export function getRawBSONDecoder<T>(schema: ClassSchema<T> | ClassType<T>): (parser: BaseParser) => T {
schema = schema instanceof ClassSchema ? schema : getClassSchema(schema);
if (schema.jit.rawBson) return schema.jit.rawBson;
schema.jit.rawBson = createSchemaDecoder(schema);
return schema.jit.rawBson;
}
export type BSONDecoder<T> = (bson: Uint8Array, offset?: number) => T;
export function getBSONDecoder<T>(schema: ClassSchema<T> | ClassType<T>): BSONDecoder<T> {
const fn = getRawBSONDecoder(schema);
schema = schema instanceof ClassSchema ? schema : getClassSchema(schema);
if (schema.jit.bsonEncoder) return schema.jit.bsonEncoder;
schema.jit.bsonEncoder = (bson: Uint8Array, offset: number = 0) => {
return fn(new ParserV2(bson, offset));
};
return schema.jit.bsonEncoder;
} | the_stack |
import { SagaIterator, buffers, delay } from 'redux-saga';
import {
select,
take,
call,
apply,
fork,
put,
all,
takeLatest,
actionChannel,
race
} from 'redux-saga/effects';
import BN from 'bn.js';
import { toTokenBase, Wei, fromWei } from 'libs/units';
import {
EAC_SCHEDULING_CONFIG,
parseSchedulingParametersValidity,
getScheduledTransactionAddressFromReceipt
} from 'libs/scheduling';
import RequestFactory from 'libs/scheduling/contracts/RequestFactory';
import { validDecimal, validNumber } from 'libs/validators';
import * as derivedSelectors from 'features/selectors';
import * as configMetaSelectors from 'features/config/meta/selectors';
import * as configNodesSelectors from 'features/config/nodes/selectors';
import {
transactionFieldsTypes,
transactionFieldsActions,
transactionMetaSelectors,
transactionHelpers,
transactionBroadcastTypes
} from 'features/transaction';
import * as types from './types';
import * as actions from './actions';
import * as selectors from './selectors';
import { IGetTransaction } from 'features/types';
import * as networkActions from '../transaction/network/actions';
import { getTransactionFields, IHexStrTransaction } from 'libs/transaction';
import { localGasEstimation } from '../transaction/network/sagas';
import { INode } from 'libs/nodes/INode';
import { IWallet } from 'libs/wallet';
import { walletSelectors } from 'features/wallet';
import erc20 from 'libs/erc20';
import { BroadcastTransactionSucceededAction } from 'features/transaction/broadcast/types';
import { TransactionReceipt } from 'shared/types/transactions';
import { getNonce, getGasPrice } from 'features/transaction/fields/selectors';
//#region Schedule Timestamp
export function* setCurrentScheduleTimestampSaga({
payload: raw
}: types.SetCurrentScheduleTimestampAction): SagaIterator {
let value: Date | null = null;
value = new Date(raw);
yield put(actions.setScheduleTimestampField({ value, raw }));
}
export const currentScheduleTimestamp = takeLatest(
[types.ScheduleActions.CURRENT_SCHEDULE_TIMESTAMP_SET],
setCurrentScheduleTimestampSaga
);
//#endregion Schedule Timestamp
//#region Schedule Timezone
export function* setCurrentScheduleTimezoneSaga({
payload: raw
}: types.SetCurrentScheduleTimezoneAction): SagaIterator {
const value = raw;
yield put(actions.setScheduleTimezone({ value, raw }));
}
export const currentScheduleTimezone = takeLatest(
[types.ScheduleActions.CURRENT_SCHEDULE_TIMEZONE_SET],
setCurrentScheduleTimezoneSaga
);
//#endregion Schedule Timezone
//#region Scheduling Toggle
export function* setGasLimitForSchedulingSaga({
payload: { value: useScheduling }
}: types.SetSchedulingToggleAction): SagaIterator {
if (useScheduling) {
// setDefaultTimeBounty
yield put(
actions.setCurrentTimeBounty(fromWei(EAC_SCHEDULING_CONFIG.TIME_BOUNTY_DEFAULT, 'ether'))
);
} else {
// setGasLimitForSchedulingSaga
const gasLimit = EAC_SCHEDULING_CONFIG.SCHEDULE_GAS_LIMIT_FALLBACK;
yield put(
transactionFieldsActions.setGasLimitField({
raw: gasLimit.toString(),
value: gasLimit
})
);
}
}
export const currentSchedulingToggle = takeLatest(
[types.ScheduleActions.TOGGLE_SET],
setGasLimitForSchedulingSaga
);
//#endregion Scheduling Toggle
//#region Time Bounty
export function* setCurrentTimeBountySaga({
payload: raw
}: types.SetCurrentTimeBountyAction): SagaIterator {
const decimal: number = yield select(transactionMetaSelectors.getDecimal);
const unit: string = yield select(derivedSelectors.getUnit);
if (!validNumber(parseInt(raw, 10)) || !validDecimal(raw, decimal)) {
yield put(actions.setTimeBountyField({ raw, value: new BN(0) }));
}
const value = toTokenBase(raw, decimal);
const isInputValid: boolean = yield call(transactionHelpers.validateInput, value, unit);
const isValid = isInputValid && value.gte(Wei('0'));
yield put(actions.setTimeBountyField({ raw, value: isValid ? value : new BN(0) }));
}
export const currentTimeBounty = takeLatest(
[types.ScheduleActions.CURRENT_TIME_BOUNTY_SET],
setCurrentTimeBountySaga
);
//#endregion Time Bounty
//#region Deposit
export function* copyTimeBountyToDeposit({
payload: { value }
}: types.SetTimeBountyFieldAction): SagaIterator {
if (value && value.gte(new BN(0))) {
const multipliedValue = value.mul(new BN(EAC_SCHEDULING_CONFIG.BOUNTY_TO_DEPOSIT_MULTIPLIER));
const raw = fromWei(multipliedValue, 'ether');
yield put(actions.setScheduleDepositField({ raw, value: multipliedValue }));
}
}
export const mirrorTimeBountyToDeposit = takeLatest(
[types.ScheduleActions.TIME_BOUNTY_FIELD_SET],
copyTimeBountyToDeposit
);
//#endregion
//#region Window Size
export function* setCurrentWindowSizeSaga({
payload: raw
}: types.SetCurrentWindowSizeAction): SagaIterator {
let value: BN | null = null;
if (!validNumber(parseInt(raw, 10))) {
yield put(actions.setWindowSizeField({ raw, value: null }));
}
value = new BN(raw);
yield put(actions.setWindowSizeField({ value, raw }));
}
export const currentWindowSize = takeLatest(
[types.ScheduleActions.CURRENT_WINDOW_SIZE_SET],
setCurrentWindowSizeSaga
);
export const setDefaultWindowSize = takeLatest(
[types.ScheduleActions.TYPE_SET],
function* setDefaultWindowSizeFn(): SagaIterator {
const currentScheduleType: selectors.ICurrentScheduleType = yield select(
selectors.getCurrentScheduleType
);
if (currentScheduleType.value === 'time') {
yield put(
actions.setCurrentWindowSize(EAC_SCHEDULING_CONFIG.WINDOW_SIZE_DEFAULT_TIME.toString())
);
} else {
yield put(
actions.setCurrentWindowSize(EAC_SCHEDULING_CONFIG.WINDOW_SIZE_DEFAULT_BLOCK.toString())
);
}
}
);
//#endregion Window Size
//#region Window Start
export function* setCurrentWindowStartSaga({
payload: raw
}: types.SetCurrentWindowStartAction): SagaIterator {
let value: number | null = null;
value = parseInt(raw, 10);
yield put(actions.setWindowStartField({ value, raw }));
}
export const currentWindowStart = takeLatest(
[types.ScheduleActions.CURRENT_WINDOW_START_SET],
setCurrentWindowStartSaga
);
//#endregion Window Start
//#region Params Validity
export function* shouldValidateParams(): SagaIterator {
while (true) {
yield take([
transactionFieldsTypes.TransactionFieldsActions.TO_FIELD_SET,
transactionFieldsTypes.TransactionFieldsActions.DATA_FIELD_SET,
transactionFieldsTypes.TransactionFieldsActions.VALUE_FIELD_SET,
types.ScheduleActions.CURRENT_TIME_BOUNTY_SET,
types.ScheduleActions.WINDOW_SIZE_FIELD_SET,
types.ScheduleActions.WINDOW_START_FIELD_SET,
types.ScheduleActions.TIMESTAMP_FIELD_SET,
types.ScheduleActions.TIME_BOUNTY_FIELD_SET,
types.ScheduleActions.TYPE_SET,
types.ScheduleActions.TOGGLE_SET,
types.ScheduleActions.TIMEZONE_SET
]);
yield call(delay, 250);
const isOffline: boolean = yield select(configMetaSelectors.getOffline);
const scheduling: boolean = yield select(selectors.isSchedulingEnabled);
if (isOffline || !scheduling) {
continue;
}
yield call(estimateGasForScheduling);
yield call(checkSchedulingParametersValidity);
}
}
function* checkSchedulingParametersValidity() {
const validateParamsCallData: derivedSelectors.IGetValidateScheduleParamsCallPayload = yield select(
derivedSelectors.getValidateScheduleParamsCallPayload
);
if (!validateParamsCallData) {
return yield put(
actions.setScheduleParamsValidity({
value: false
})
);
}
const node = yield select(configNodesSelectors.getNodeLib);
const callResult: string = yield apply(node, node.sendCallRequest, [validateParamsCallData]);
const { paramsValidity } = RequestFactory.validateRequestParams.decodeOutput(callResult);
const errors = parseSchedulingParametersValidity(paramsValidity);
yield put(
actions.setScheduleParamsValidity({
value: errors.length === 0
})
);
}
function* estimateGasForScheduling() {
const { transaction }: IGetTransaction = yield select(derivedSelectors.getSchedulingTransaction);
const { gasLimit, gasPrice, nonce, chainId, ...rest }: IHexStrTransaction = yield call(
getTransactionFields,
transaction
);
yield put(networkActions.estimateGasRequested(rest));
}
export const schedulingParamsValidity = fork(shouldValidateParams);
//#endregion Params Validity
//#region Estimate Scheduling Gas
export function* estimateSchedulingGas(): SagaIterator {
const requestChan = yield actionChannel(
types.ScheduleActions.ESTIMATE_SCHEDULING_GAS_REQUESTED,
buffers.sliding(1)
);
while (true) {
const autoGasLimitEnabled: boolean = yield select(configMetaSelectors.getAutoGasLimitEnabled);
const isOffline = yield select(configMetaSelectors.getOffline);
if (!autoGasLimitEnabled) {
continue;
}
if (isOffline) {
const gasLimit = EAC_SCHEDULING_CONFIG.SCHEDULING_GAS_LIMIT;
const gasSetOptions = {
raw: gasLimit.toString(),
value: gasLimit
};
yield put(actions.setScheduleGasLimitField(gasSetOptions));
yield put(actions.estimateSchedulingGasSucceeded());
continue;
}
const { payload }: types.EstimateSchedulingGasRequestedAction = yield take(requestChan);
// debounce 250 ms
yield call(delay, 250);
const node: INode = yield select(configNodesSelectors.getNodeLib);
const walletInst: IWallet = yield select(walletSelectors.getWalletInst);
try {
const from: string = yield apply(walletInst, walletInst.getAddressString);
const txObj = { ...payload, from };
const { gasLimit } = yield race({
gasLimit: apply(node, node.estimateGas, [txObj]),
timeout: call(delay, 10000)
});
if (gasLimit) {
const gasSetOptions = {
raw: gasLimit.toString(),
value: gasLimit
};
yield put(actions.setScheduleGasLimitField(gasSetOptions));
yield put(actions.estimateSchedulingGasSucceeded());
} else {
yield put(actions.estimateSchedulingGasTimedout());
yield call(localGasEstimation, payload);
}
} catch (e) {
yield put(actions.estimateSchedulingGasFailed());
yield call(localGasEstimation, payload);
}
}
}
//#endregion Estimate Scheduling Gas
//#region Prepare Approve Token Transaction
export function* prepareApproveTokenTransaction(): SagaIterator {
while (true) {
const action: BroadcastTransactionSucceededAction = yield take([
transactionBroadcastTypes.TransactionBroadcastActions.TRANSACTION_SUCCEEDED
]);
const isSchedulingEnabled: boolean = yield select(selectors.isSchedulingEnabled);
const isEtherTransaction: boolean = yield select(derivedSelectors.isEtherTransaction);
const tokenTransferAmount: { raw: string; value: BN | null } = yield select(
transactionMetaSelectors.getTokenValue
);
const tokenAddress: string = yield select(derivedSelectors.getSelectedTokenContractAddress);
const tokenSymbol: string = yield select(derivedSelectors.getUnit);
const node: INode = yield select(configNodesSelectors.getNodeLib);
if (isSchedulingEnabled && !isEtherTransaction) {
yield put(
actions.setScheduledTokenTransferSymbol({
raw: tokenSymbol,
value: tokenSymbol
})
);
yield put(
actions.setScheduledTransactionHash({
raw: action.payload.broadcastedHash,
value: action.payload.broadcastedHash
})
);
yield put(
actions.setScheduledTransactionAddress({
raw: '',
value: ''
})
);
let receipt: TransactionReceipt | null = null;
while (!receipt) {
yield call(delay, 5000);
try {
receipt = yield call(node.getTransactionReceipt, action.payload.broadcastedHash);
} catch (error) {
continue;
}
}
const transactionBlockNumber = receipt.blockNumber;
let currentBlock: number | null = null;
while (!currentBlock || transactionBlockNumber + 1 >= currentBlock) {
currentBlock = parseInt(yield call(node.getCurrentBlock), 10);
yield call(delay, 2000);
}
yield put(actions.setSchedulingToggle({ value: false }));
yield call(delay, 100);
yield put(
transactionFieldsActions.setValueField({
raw: '0',
value: new BN('0')
})
);
const scheduledTransactionAddress: string | null = yield call(
getScheduledTransactionAddressFromReceipt,
receipt
);
if (!scheduledTransactionAddress) {
return;
}
yield put(
actions.setScheduledTransactionAddress({
raw: scheduledTransactionAddress,
value: scheduledTransactionAddress
})
);
const approveTokensData = erc20.approve.encodeInput({
_spender: scheduledTransactionAddress,
_value: tokenTransferAmount.value
});
const { value: nonce } = yield select(getNonce);
const { value: gasPrice } = yield select(getGasPrice);
const scheduledTokensApproveTransaction = {
to: tokenAddress,
value: '',
data: approveTokensData,
nonce,
gasLimit: undefined,
gasPrice
};
const { gasLimit } = yield race({
gasLimit: apply(node, node.estimateGas, [scheduledTokensApproveTransaction]),
timeout: call(delay, 10000)
});
scheduledTokensApproveTransaction.gasLimit = gasLimit;
yield put(actions.setScheduledTokensApproveTransaction(scheduledTokensApproveTransaction));
}
}
}
//#endregion Prepare Approve Token Transaction
export function* scheduleSaga(): SagaIterator {
yield all([
currentWindowSize,
currentWindowStart,
currentScheduleTimestamp,
currentTimeBounty,
currentSchedulingToggle,
currentScheduleTimezone,
mirrorTimeBountyToDeposit,
fork(estimateSchedulingGas),
schedulingParamsValidity,
fork(prepareApproveTokenTransaction),
setDefaultWindowSize
]);
} | the_stack |
import * as assert from "assert";
import {BespokeClient} from "../../lib/client/bespoke-client";
import {Node} from "../../lib/server/node";
import {NodeManager} from "../../lib/server/node-manager";
import {Global} from "../../lib/core/global";
import {KeepAlive} from "../../lib/client/keep-alive";
import {SocketHandler, SocketMessage} from "../../lib/core/socket-handler";
import {HTTPClient} from "../../lib/core/http-client";
let keepAlive: KeepAlive = null;
class MockBespokeClient extends BespokeClient {
protected newKeepAlive(handler: SocketHandler): KeepAlive {
keepAlive = new KeepAlive(handler);
keepAlive.pingPeriod = 20;
keepAlive.warningThreshold = 10;
keepAlive.windowPeriod = 400;
return keepAlive;
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Much of the testing for this class is done by NodeManager, the other side of its interface
// These tests related to the keep alive, which are tricky to write
// I believe they are worth it because this is critical functionality to our robustness
describe("BespokeClient", function() {
const nodeMajorVersion = parseInt(process.version.substr(1, 2), 10);
const testPort = 9000 + nodeMajorVersion;
describe("#connect()", function() {
it("Fails to connect", function() {
this.timeout(13000);
return new Promise((resolve, reject) => {
const client = new BespokeClient("JPKa", "localhost", 9000, "localhost", 9000 );
let reconnectAttempts = 0;
client.onReconnect = function (error: any) {
reconnectAttempts++;
};
client.onConnect = function (error: any) {
try {
assert.equal(reconnectAttempts, BespokeClient.RECONNECT_MAX_RETRIES, "Not enough reconnects");
assert(error);
resolve();
} catch (assertErr) {
reject(assertErr);
}
};
client.connect();
});
});
it("Connects to something other than localhost", function() {
this.timeout(5000);
return new Promise(resolve => {
const client = new BespokeClient("JPKb" + nodeMajorVersion,
"proxy.bespoken.tools",
5000,
"127.0.0.1",
testPort);
client.onConnect = function (error: any) {
const webhookCaller = new HTTPClient();
webhookCaller.post("proxy.bespoken.tools",
443,
"/test?node-id=JPKb" + nodeMajorVersion,
"Test",
function (data: Buffer, statusCode: number, success: boolean) {
assert.equal(data.toString(),
"BST Proxy - Local Forwarding Error\nconnect ECONNREFUSED 127.0.0.1:" + testPort);
assert.equal(statusCode, 500);
client.shutdown(function () {
resolve();
});
});
};
client.onError = function (errorType, message) {
// We expect an error - make sure it contains the correct domain name
assert(message.indexOf("127.0.0.1") !== -1);
};
client.connect();
});
});
it("Rejects messages on a secure server", function() {
this.timeout(5000);
return new Promise(resolve => {
const client = new BespokeClient("JPKc" + nodeMajorVersion, "proxy.bespoken.tools", 5000, "127.0.0.1", 443, "JPKc");
client.onConnect = function (error: any) {
const webhookCaller = new HTTPClient();
webhookCaller.post("proxy.bespoken.tools", 443, "/test?node-id=JPKc" + nodeMajorVersion, "Test", function (data: Buffer, statusCode: number, success: boolean) {
assert.equal(data.toString(), "Unauthorized request");
assert.equal(statusCode, 500);
client.shutdown(function () {
resolve();
});
});
};
client.onError = function (errorType, message) {
// We expect an error - make sure it contains the correct domain name
assert(message.indexOf("127.0.0.1") !== -1);
};
client.connect();
});
});
it("Accepts messages on a secure server when secret on query string", function() {
this.timeout(8000);
return new Promise(resolve => {
const client = new BespokeClient("JPKd" + nodeMajorVersion, "proxy.bespoken.tools", 5000, "127.0.0.1", testPort, "JPKd");
client.onConnect = function (error: any) {
const webhookCaller = new HTTPClient();
const path = "/test?node-id=JPKd" + nodeMajorVersion + "&bespoken-key=JPKd";
webhookCaller.post("proxy.bespoken.tools", 443, path, "Test", function (data: Buffer, statusCode: number, success: boolean) {
// This error comes from the webhook client instead of rejecting
assert.equal(data.toString(), "BST Proxy - Local Forwarding Error\nconnect ECONNREFUSED 127.0.0.1:" + testPort);
assert.equal(statusCode, 500);
client.shutdown(function () {
resolve();
});
});
};
client.onError = function (errorType, message) {
// We expect an error - make sure it contains the correct domain name
assert(message.indexOf("127.0.0.1") !== -1);
};
client.connect();
});
});
it("Accepts messages on a secure server when secret on header", function() {
this.timeout(5000);
return new Promise(resolve => {
const client = new BespokeClient("JPKe" + nodeMajorVersion, "proxy.bespoken.tools", 5000, "127.0.0.1", testPort, "JPKe");
client.onConnect = function (error: any) {
const webhookCaller = new HTTPClient();
const path = "/test?node-id=JPKe" + nodeMajorVersion;
const extraHeader = {
"bespoken-key": "JPKe",
};
webhookCaller.postWithExtraHeaders("proxy.bespoken.tools", 443, path, "Test", extraHeader, function (data: Buffer, statusCode: number, success: boolean) {
// This error comes from the webhook client instead of rejecting
assert.equal(data.toString(), "BST Proxy - Local Forwarding Error\nconnect ECONNREFUSED 127.0.0.1:" + testPort);
assert.equal(statusCode, 500);
client.shutdown(function () {
resolve();
});
});
};
client.onError = function (errorType, message) {
// We expect an error - make sure it contains the correct domain name
assert(message.indexOf("127.0.0.1") !== -1);
};
client.connect();
});
});
});
describe("KeepAlive failed", function() {
it("Fails", function() {
this.timeout(8000);
return new Promise(async (resolve, reject) => {
const nodeManager = new NodeManager([testPort]);
let wasFailureFunctionOverwritten = false;
let failureCount = 0;
let count = 0;
(<any> NodeManager).onKeepAliveReceived = function (node: Node) {
// We overwrite the failure callback on first keepAlive to ensure keepAlive is already populate
if (!wasFailureFunctionOverwritten) {
const originalCallback = (<any> keepAlive).onFailureCallback;
(<any> keepAlive).onFailureCallback = function () {
originalCallback();
console.log("Adding a failure :(");
failureCount++;
};
wasFailureFunctionOverwritten = true;
}
count++;
if (count < 10) {
node.socketHandler.send(new SocketMessage(Global.KeepAliveMessage));
}
};
BespokeClient.RECONNECT_MAX_RETRIES = 0;
const client = new MockBespokeClient("JPKg", "127.0.0.1", testPort, "127.0.0.1", testPort + 1);
nodeManager.start();
client.connect();
setTimeout(function () {
if (failureCount > 2) {
try {
assert(false, "Too many failures received");
} catch (error) {
reject(error);
return;
}
}
client.shutdown(function () {
nodeManager.stop().then(() => {
BespokeClient.RECONNECT_MAX_RETRIES = 3;
resolve();
});
});
}, 1000);
});
});
});
describe("KeepAlive worked", function() {
// we need to give this time to retry shutdown then close
this.timeout(8000);
it("Gets lots of keep alives", async function() {
return new Promise(async (resolve, reject) => {
const nodeManager = new NodeManager([testPort]);
let count = 0;
(<any> NodeManager).onKeepAliveReceived = function (node: Node) {
count++;
node.socketHandler.send(new SocketMessage(Global.KeepAliveMessage));
};
const client = new MockBespokeClient("JPKf", "localhost", testPort, "localhost", testPort + 1);
nodeManager.start();
client.connect();
// We give time to stablish connection and set keepAlive
await sleep(100);
let originalCallback = (<any> keepAlive).onFailureCallback;
(<any> keepAlive).onFailureCallback = function () {
originalCallback();
assert(false, "This callback should not be hit");
};
// Let everything run for one second and ensure no errors are received
setTimeout(function () {
// Mac and Linux generate more events than windows due threading in windows
if ((process.platform.includes("win") && count < 8) ||
(!process.platform.includes("win") && count < 40)) {
try {
assert(false, "Not enough keep alives received");
} catch (error) {
reject(error);
return;
}
}
client.shutdown(function () {
nodeManager.stop().then (() => {
resolve();
});
});
}, 1000);
});
});
});
}); | the_stack |
import { PdfGanttCellStyle } from './../../base/interface';
import { PdfTreeGrid } from '../pdf-treegrid';
import { isNullOrUndefined } from '@syncfusion/ej2-base';
import { PdfPaddings } from './index';
import {
RectangleF, PdfTextAlignment, PdfBorderOverlapStyle, PointF, PdfDashStyle,
PdfLineCap, PdfSolidBrush, PdfStandardFont
} from '@syncfusion/ej2-pdf-export';
import { SizeF, PdfBrush, PdfPen, PdfFontStyle, PdfFont, PdfGraphics } from '@syncfusion/ej2-pdf-export';
import { PdfStringFormat, PdfStringLayouter, PdfStringLayoutResult } from '@syncfusion/ej2-pdf-export';
/**
*
*/
export class PdfTreeGridCell {
/**
* Gets or sets the parent `row`.
*
* @private
*/
public row: PdfTreeGridRow;
/**
* Gets or sets the cell `style`.
*
* @private
*/
public style: PdfGanttCellStyle;
private cellWidth: number = 0;
private cellHeight: number = 0;
/**
* Gets or sets a value that indicates the total number of rows that cell `spans` within a PdfGrid.
*
* @private
*/
public rowSpan: number;
/**
* Gets or sets a value that indicates the total number of columns that cell `spans` within a PdfGrid.
*
* @private
*/
public columnSpan: number;
public value: Object;
/** @private */
public remainingString: string;
/** @private */
public finishedDrawingCell: boolean = true;
/** @private */
public isCellMergeContinue: boolean;
/** @private */
public isRowMergeContinue: boolean;
/** @private */
public isCellMergeStart: boolean;
/** @private */
public isRowMergeStart: boolean;
/** @private */
public isHeaderCell: boolean;
constructor(row?: PdfTreeGridRow) {
if (isNullOrUndefined(row)) {
this.rowSpan = 1;
this.columnSpan = 1;
} else {
this.row = row;
}
this.style = {};
}
/**
* Gets the `height` of the PdfTreeGrid cell.[Read-Only].
*
* @returns {number} .
* @private
*/
public get height(): number {
if (this.cellHeight === 0) {
this.cellHeight = this.measureHeight();
}
return this.cellHeight;
}
public set height(value: number) {
this.cellHeight = value;
}
/**
* Gets the `width` of the PdfTreeGrid cell.[Read-Only].
*
* @returns {number} .
* @private
*/
public get width(): number {
if (this.cellWidth === 0) {
this.cellWidth = this.measureWidth();
}
return Math.round(this.cellWidth);
}
public set width(value: number) {
this.cellWidth = value;
}
private measureWidth(): number {
let width: number = 0;
const layouter: PdfStringLayouter = new PdfStringLayouter();
if (typeof this.value === 'string') {
/* eslint-disable-next-line */
const font: PdfStandardFont = new PdfStandardFont(this.row.treegrid.ganttStyle.fontFamily, this.style.fontSize, this.style.fontStyle);
/* eslint-disable-next-line */
const slr: PdfStringLayoutResult = layouter.layout((this.value as string), font, this.style.format, new SizeF(Number.MAX_VALUE, Number.MAX_VALUE), false, new SizeF(0, 0));
width += slr.actualSize.width;
width += (this.style.borders.left.width + this.style.borders.right.width) * 2;
}
if (typeof this.row.treegrid.style.cellPadding.left !== 'undefined' && this.row.treegrid.style.cellPadding.hasLeftPad) {
width += this.row.treegrid.style.cellPadding.left;
}
if (typeof this.row.treegrid.style.cellPadding.right !== 'undefined' && this.row.treegrid.style.cellPadding.hasRightPad) {
width += this.row.treegrid.style.cellPadding.right;
}
width += this.row.treegrid.style.cellSpacing;
return width;
}
/**
* @returns {number} .
* @private
*/
/* eslint-disable */
public measureHeight(): number {
const rowHeight: number = this.row.treegrid.rowHeight;
let height = 0;
let width: number = this.calculateWidth();
width -= this.row.treegrid.style.cellPadding.right + this.row.treegrid.style.cellPadding.left;
width -= this.style.borders.left.width + this.style.borders.right.width;
const layouter: PdfStringLayouter = new PdfStringLayouter();
if (typeof this.value === 'string' || typeof this.remainingString === 'string') {
let currentValue: string = this.value as string;
if (!this.finishedDrawingCell) {
currentValue = !(isNullOrUndefined(this.remainingString) || this.remainingString === '') ? this.remainingString : (this.value as string);
}
/* eslint-disable */
const font: PdfStandardFont = new PdfStandardFont(this.row.treegrid.ganttStyle.fontFamily, this.style.fontSize, this.style.fontStyle);
/* eslint-disable */
const slr: PdfStringLayoutResult = layouter.layout(currentValue, font, this.style.format, new SizeF(width, 0), false, new SizeF(0, 0));
height += slr.actualSize.height;
height += (this.style.borders.top.width + this.style.borders.bottom.width) * 2;
}
height += this.row.treegrid.style.cellPadding.top + this.row.treegrid.style.cellPadding.bottom;
height += this.row.treegrid.style.cellSpacing;
return height > rowHeight ? height : rowHeight;
}
/* eslint-enable */
private calculateWidth(): number {
const cellIndex: number = this.row.cells.indexOf(this);
const columnSpan: number = this.columnSpan;
let width: number = 0;
for (let i: number = 0; i < columnSpan; i++) {
width += this.row.treegrid.columns.getColumn(cellIndex + i).width;
}
if (this.row.treegrid.columns.getColumn(cellIndex).isTreeColumn) {
width -= (this.row.level * 10);
}
return width;
}
/**
* `Draws` the specified graphics.
*
* @param {PdfGraphics} graphics .
* @param {RectangleF} bounds .
* @param {boolean} cancelSubsequentSpans .
* @param {number} leftAdjustment .
* @returns {PdfStringLayoutResult} .
* @private
*/
public draw(graphics: PdfGraphics, bounds: RectangleF, cancelSubsequentSpans: boolean, leftAdjustment: number): PdfStringLayoutResult {
let result: PdfStringLayoutResult = null; const padding: number = 10;
if (cancelSubsequentSpans) {
// Cancel all subsequent cell spans, if no space exists.
const currentCellIndex: number = this.row.cells.indexOf(this);
for (let i: number = currentCellIndex + 1; i <= currentCellIndex + this.columnSpan; i++) {
this.row.cells.getCell(i).isCellMergeContinue = false;
this.row.cells.getCell(i).isRowMergeContinue = false;
}
this.columnSpan = 1;
}
// Skip cells which were already covered by span map.
if (this.isCellMergeContinue || this.isRowMergeContinue) {
if (this.isCellMergeContinue && this.row.treegrid.style.allowHorizontalOverflow) {
if ((this.row.rowOverflowIndex > 0 && (this.row.cells.indexOf(this) !== this.row.rowOverflowIndex + 1)) ||
(this.row.rowOverflowIndex === 0 && this.isCellMergeContinue)) {
return result;
} else {
return result;
}
}
}
//bounds = this.adjustContentLayoutArea(bounds);
this.drawCellBackground(graphics, bounds);
const textPen: PdfPen = null;
const textBrush: PdfBrush = new PdfSolidBrush(this.style.fontColor);
let font: PdfFont = null;
if (this.row.isParentRow) {
font = new PdfStandardFont(this.row.treegrid.ganttStyle.fontFamily, this.style.fontSize, PdfFontStyle.Bold);
} else {
font = new PdfStandardFont(this.row.treegrid.ganttStyle.fontFamily, this.style.fontSize, this.style.fontStyle);
}
let innerLayoutArea: RectangleF = bounds;
if (!this.isHeaderCell) {
/* eslint-disable-next-line */
innerLayoutArea.x = innerLayoutArea.x;
/* eslint-disable-next-line */
innerLayoutArea.width = innerLayoutArea.width;
}
if (innerLayoutArea.height >= graphics.clientSize.height) {
// To break row to next page
if (this.row.treegrid.allowRowBreakAcrossPages) {
innerLayoutArea.height -= innerLayoutArea.y;
bounds.height -= bounds.y;
} else {
innerLayoutArea.height = graphics.clientSize.height;
bounds.height = graphics.clientSize.height;
}
}
innerLayoutArea = this.adjustContentLayoutArea(innerLayoutArea);
if (typeof this.value === 'string' || typeof this.remainingString === 'string') {
let temp: string = null;
if (this.finishedDrawingCell) {
temp = (this.remainingString === '') ? this.remainingString : this.value as string;
/* eslint-disable-next-line */
graphics.drawString(temp, font, textPen, textBrush, (innerLayoutArea.x + leftAdjustment), innerLayoutArea.y, (innerLayoutArea.width - leftAdjustment - padding), (innerLayoutArea.height - padding), this.style.format);
} else {
/* eslint-disable-next-line */
graphics.drawString(this.remainingString, font, textPen, textBrush, (innerLayoutArea.x + leftAdjustment), innerLayoutArea.y, this.style.format);
}
result = graphics.stringLayoutResult;
}
if (this.style.borders != null) {
this.drawCellBorder(graphics, bounds);
}
return result;
}
/**
* Draw the `cell background`.
*
* @param {PdfGraphics} graphics .
* @param {RectangleF} bounds .
* @returns {void} .
* @private
*/
public drawCellBackground(graphics: PdfGraphics, bounds: RectangleF): void {
const backgroundBrush: PdfBrush = new PdfSolidBrush(this.style.backgroundColor);
if (backgroundBrush != null) {
graphics.save();
graphics.drawRectangle(backgroundBrush, bounds.x, bounds.y, bounds.width, bounds.height);
graphics.restore();
}
// if (this.style.backgroundImage != null) {
// let image: PdfImage = this.getBackgroundImage();
// graphics.drawImage(this.style.backgroundImage, bounds.x, bounds.y, bounds.width, bounds.height);
// }
}
/**
* `Adjusts the text layout area`.
*
* @param {RectangleF} bounds .
* @returns {RectangleF} .
* @private
*/
private adjustContentLayoutArea(bounds: RectangleF): RectangleF {
//Add Padding value to its Cell Bounds
const returnBounds: RectangleF = new RectangleF(new PointF(bounds.x, bounds.y), new SizeF(bounds.width, bounds.height));
const cellPadding: PdfPaddings = this.style.padding;
if (this.value instanceof PdfTreeGrid) {
const size: SizeF = (this.value as PdfTreeGrid).size;
if (this.style.format.alignment === PdfTextAlignment.Center) {
returnBounds.x += cellPadding.left + (returnBounds.width - size.width) / 2;
returnBounds.y += cellPadding.top + (returnBounds.height - size.height) / 2;
} else if (this.style.format.alignment === PdfTextAlignment.Left) {
returnBounds.x += cellPadding.left;
returnBounds.y += cellPadding.top;
} else if (this.style.format.alignment === PdfTextAlignment.Right) {
returnBounds.x += cellPadding.left + (returnBounds.width - size.width);
returnBounds.y += cellPadding.top;
}
} else {
returnBounds.x += cellPadding.left;
returnBounds.y += cellPadding.top;
}
return returnBounds;
}
/**
* @param {PdfGraphics} graphics .
* @param {RectangleF} bounds .
* @returns {void} .
* @private
*/
private drawCellBorder(graphics: PdfGraphics, bounds: RectangleF): void {
if (this.row.treegrid.style.borderOverlapStyle === PdfBorderOverlapStyle.Inside) {
bounds.x += this.style.borders.left.width;
bounds.y += this.style.borders.top.width;
bounds.width -= this.style.borders.right.width;
bounds.height -= this.style.borders.bottom.width;
}
if (this.style.borders.isAll && this.isHeaderCell) {
graphics.drawRectangle(this.style.borders.left, bounds.x, bounds.y, bounds.width, bounds.height);
graphics.restore();
return;
} else {
let p1: PointF = new PointF(bounds.x, bounds.y + bounds.height);
let p2: PointF = new PointF(bounds.x, bounds.y);
let pen: PdfPen = this.style.borders.left;
if (this.style.borders.left.dashStyle === PdfDashStyle.Solid) {
pen.lineCap = PdfLineCap.Square;
}
graphics.drawLine(pen, p1, p2);
graphics.restore();
p1 = new PointF(bounds.x + bounds.width, bounds.y);
p2 = new PointF(bounds.x + bounds.width, bounds.y + bounds.height);
pen = this.style.borders.right;
if ((bounds.x + bounds.width) > (graphics.clientSize.width - (pen.width / 2))) {
p1 = new PointF(graphics.clientSize.width - (pen.width / 2), bounds.y);
p2 = new PointF(graphics.clientSize.width - (pen.width / 2), bounds.y + bounds.height);
}
if (this.style.borders.right.dashStyle === PdfDashStyle.Solid) {
pen.lineCap = PdfLineCap.Square;
}
graphics.drawLine(pen, p1, p2);
graphics.restore();
p1 = new PointF(bounds.x, bounds.y);
p2 = new PointF(bounds.x + bounds.width, bounds.y);
pen = this.style.borders.top;
if (this.style.borders.top.dashStyle === PdfDashStyle.Solid) {
pen.lineCap = PdfLineCap.Square;
}
graphics.drawLine(pen, p1, p2);
graphics.restore();
p1 = new PointF(bounds.x + bounds.width, bounds.y + bounds.height);
p2 = new PointF(bounds.x, bounds.y + bounds.height);
pen = this.style.borders.bottom;
if (bounds.y + bounds.height > graphics.clientSize.height - pen.width / 2) {
p1 = new PointF(bounds.x + bounds.width, graphics.clientSize.height - pen.width / 2);
p2 = new PointF(bounds.x, graphics.clientSize.height - pen.width / 2);
}
if (this.style.borders.bottom.dashStyle === PdfDashStyle.Solid) {
pen.lineCap = PdfLineCap.Square;
}
graphics.drawLine(pen, p1, p2);
graphics.restore();
}
}
}
/**
* `PdfTreeGridCellCollection` class provides access to an ordered,
* strongly typed collection of 'PdfTreeGridCell' objects.
*
* @private
*/
export class PdfTreeGridCellCollection {
//Fields
/**
* @private
*/
private treegridRow: PdfTreeGridRow;
/**
* @private
*/
private cells: PdfTreeGridCell[];
//Constructor
/**
* Initializes a new instance of the `PdfGridCellCollection` class with the row.
*
* @param { PdfTreeGridRow} row .
* @private
*/
public constructor(row: PdfTreeGridRow) {
this.treegridRow = row;
this.cells = [];
}
//Properties
/**
* Gets the current `cell`.
*
* @param {number} index .
* @returns {PdfTreeGridCell} .
* @private
*/
public getCell(index: number): PdfTreeGridCell {
if (index < 0 || index >= this.count) {
throw new Error('IndexOutOfRangeException');
}
return this.cells[index];
}
/**
* Gets the cells `count`.[Read-Only].
*
* @returns {number} .
* @private
*/
public get count(): number {
return this.cells.length;
}
//Implementation
/**
* `Adds` this instance.
*
* @param {PdfTreeGridCell} cell .
* @returns {PdfTreeGridCell | void} .
* @private
*/
public add(cell?: PdfTreeGridCell): PdfTreeGridCell | void {
if (typeof cell === 'undefined') {
const tempcell: PdfTreeGridCell = new PdfTreeGridCell();
this.add(tempcell);
return cell;
} else {
cell.row = this.treegridRow;
this.cells.push(cell);
}
}
/**
* Returns the `index of` a particular cell in the collection.
*
* @param {PdfTreeGridCell} cell .
* @returns {number} .
* @private
*/
public indexOf(cell: PdfTreeGridCell): number {
return this.cells.indexOf(cell);
}
}
/**
*
*/
export class PdfTreeGridRow {
private treegridCells: PdfTreeGridCellCollection;
private pdfTreeGrid: PdfTreeGrid;
private treegridRowOverflowIndex: number = 0;
private treegridRowBreakHeight: number;
private rowHeight: number = 0;
private rowWidth: number = 0;
/* eslint-disable-next-line */
private _isParentRow = false;
private intendLevel: number = 0;
/**
* The `Maximum span` of the row.
*
* @public
*/
public maximumRowSpan: number;
constructor(treegrid: PdfTreeGrid) {
this.pdfTreeGrid = treegrid;
}
public get cells(): PdfTreeGridCellCollection {
if (isNullOrUndefined(this.treegridCells)) {
this.treegridCells = new PdfTreeGridCellCollection(this);
}
return this.treegridCells;
}
public get isParentRow(): boolean {
return this._isParentRow;
}
public set isParentRow(value: boolean) {
this._isParentRow = value;
}
public get treegrid(): PdfTreeGrid {
return this.pdfTreeGrid;
}
public set treegrid(value: PdfTreeGrid) {
this.pdfTreeGrid = value;
}
/**
* `Height` of the row yet to be drawn after split.
*
* @returns {number} .
* @private
*/
public get rowBreakHeight(): number {
if (typeof this.treegridRowBreakHeight === 'undefined') {
this.treegridRowBreakHeight = 0;
}
return this.treegridRowBreakHeight;
}
public set rowBreakHeight(value: number) {
this.treegridRowBreakHeight = value;
}
/**
* `over flow index` of the row.
*
* @returns {number} .
* @private
*/
public get rowOverflowIndex(): number {
return this.treegridRowOverflowIndex;
}
public set rowOverflowIndex(value: number) {
this.treegridRowOverflowIndex = value;
}
public get level(): number {
return this.intendLevel;
}
public set level(value: number) {
this.intendLevel = value;
}
/**
* Gets or sets the `height` of the row.
*
* @returns {number} .
* @private
*/
public get height(): number {
if (this.rowHeight === 0) {
this.rowHeight = this.measureHeight();
}
return this.rowHeight;
}
public set height(value: number) {
this.rowHeight = value;
}
/**
* Gets or sets the `width` of the row.
*
* @returns {number} .
* @private
*/
public get width(): number {
if (this.rowWidth === 0) {
this.rowWidth = this.measureWidth();
}
return this.rowWidth;
}
public get rowIndex(): number {
return this.treegrid.rows.rowCollection.indexOf(this);
}
private measureWidth(): number {
const columns: PdfTreeGridColumn[] = this.treegrid.columns.columns;
let totalWidth: number = 0;
for (let i: number = 0; i < columns.length; i++) {
const column: PdfTreeGridColumn = columns[i];
totalWidth += column.width;
}
return totalWidth;
}
private measureHeight(): number {
let rowHeight: number = this.cells.getCell(0).height;
for (let i: number = 0; i < this.cells.count; i++) {
const cell: PdfTreeGridCell = this.cells.getCell(i);
if (cell.columnSpan === 1 || cell.rowSpan === 1) {
rowHeight = Math.max(rowHeight, cell.height);
} else {
rowHeight = Math.min(rowHeight, cell.height);
}
cell.height = rowHeight;
}
return rowHeight;
}
}
/**
* `PdfTreeGridRowCollection` class provides access to an ordered, strongly typed collection of 'PdfTreeGridRow' objects.
*
* @private
*/
export class PdfTreeGridRowCollection {
// Fields
/**
* @private
*/
private treegrid: PdfTreeGrid;
/**
* The row collection of the `treegrid`.
*
* @private
*/
private rows: PdfTreeGridRow[];
// Constructor
/**
* Initializes a new instance of the `PdfTreeGridRowCollection` class with the parent grid.
*
* @param {PdfTreeGrid} treegrid .
* @private
*/
public constructor(treegrid: PdfTreeGrid) {
this.rows = [];
this.treegrid = treegrid;
}
//Properties
/**
* Gets the number of header in the `PdfTreeGrid`.[Read-Only].
*
* @returns {number} .
* @private
*/
public get count(): number {
return this.rows.length;
}
//Implementation
/**
* Return the row collection of the `treegrid`.
*
* @returns {PdfTreeGridRow[]} .
* @private
*/
public get rowCollection(): PdfTreeGridRow[] {
return this.rows;
}
public addRow(): PdfTreeGridRow;
public addRow(row: PdfTreeGridRow): void;
public addRow(row?: PdfTreeGridRow): void | PdfTreeGridRow {
if (typeof row === 'undefined') {
const row: PdfTreeGridRow = new PdfTreeGridRow(this.treegrid);
this.addRow(row);
return row;
} else {
if (row.cells.count === 0) {
for (let i: number = 0; i < this.treegrid.columns.count; i++) {
row.cells.add(new PdfTreeGridCell());
}
}
this.rows.push(row);
}
}
/**
* Return the row by index.
*
* @param {number} index .
* @returns {PdfTreeGridRow} .
* @private
*/
public getRow(index: number): PdfTreeGridRow {
return this.rows[index];
}
}
/**
* `PdfTreeGridHeaderCollection` class provides customization of the settings for the header.
*
* @private
*/
export class PdfTreeGridHeaderCollection {
/**
* The `treegrid`.
*
* @returns {PdfTreeGrid} .
* @private
*/
private treegrid: PdfTreeGrid;
/**
* The array to store the `rows` of the grid header.
*
* @returns {PdfTreeGridRow[]} .
* @private
*/
private rows: PdfTreeGridRow[] = [];
//constructor
/**
* Initializes a new instance of the `PdfTreeGridHeaderCollection` class with the parent grid.
*
* @param {PdfTreeGrid} treegrid .
* @private
*/
public constructor(treegrid: PdfTreeGrid) {
this.treegrid = treegrid;
this.rows = [];
}
//Properties
/**
* Gets a 'PdfTreeGridRow' object that represents the `header` row in a 'PdfGridHeaderCollection' control.[Read-Only].
*
* @param {number} index .
* @returns {PdfTreeGridRow} .
* @private
*/
public getHeader(index: number): PdfTreeGridRow {
return (this.rows[index]);
}
/**
* Gets the `number of header` in the 'PdfGrid'.[Read-Only]
*
* @returns {number} .
* @private
*/
public get count(): number {
return this.rows.length;
}
//Implementation
/**
* `Adds` the specified row.
*
* @param {PdfTreeGridRow} row .
* @returns {void} .
* @private
*/
public add(row: PdfTreeGridRow): void {
this.rows.push(row);
}
public indexOf(row: PdfTreeGridRow): number {
return this.rows.indexOf(row);
}
}
export class PdfTreeGridColumn {
private treegrid: PdfTreeGrid;
private columnWidth: number = 0;
private stringFormat: PdfStringFormat;
private treeColumnIndex: boolean = false;
private _headerText: string = '';
private _field: string = '';
constructor(treegrid: PdfTreeGrid) {
this.treegrid = treegrid;
}
public get headerText(): string {
return this._headerText;
}
public set headerText(value: string) {
this._headerText = value;
}
public get field(): string {
return this._field;
}
public set field(value: string) {
this._field = value;
}
public get width(): number {
return this.columnWidth;
}
public set width(value: number) {
this.columnWidth = value;
}
public get isTreeColumn(): boolean {
return this.treeColumnIndex;
}
public set isTreeColumn(value: boolean) {
this.treeColumnIndex = value;
}
/**
* Gets or sets the information about the text `formatting`.
*
* @returns {PdfStringFormat} .
* @private
*/
public get format(): PdfStringFormat {
if (this.stringFormat == null) {
this.stringFormat = new PdfStringFormat(); //GetDefaultFormat();
}
return this.stringFormat;
}
public set format(value: PdfStringFormat) {
this.stringFormat = value;
}
}
/**
* `PdfTreeGridColumnCollection` class provides access to an ordered,
* strongly typed collection of 'PdfTreeGridColumn' objects.
*
* @private
*/
export class PdfTreeGridColumnCollection {
//Fields
/**
* @private
*/
private treegrid: PdfTreeGrid;
/**
* @private
*/
private internalColumns: PdfTreeGridColumn[] = [];
/**
* @private
*/
public columnWidth: number = 0;
//properties
//Constructors
/**
* Initializes a new instance of the `PdfTreeGridColumnCollection` class with the parent grid.
*
* @param { PdfTreeGrid} treegrid .
* @private
*/
public constructor(treegrid: PdfTreeGrid) {
this.treegrid = treegrid;
this.internalColumns = [];
}
//Implementation
/**
* `Add` a new column to the 'PdfGrid'.
*
* @param {number} count .
* @returns {void} .
* @private
*/
public add(count: number): void {
// public add(column : PdfGridColumn) : void
// public add(arg : number|PdfGridColumn) : void {
// if (typeof arg === 'number') {
for (let i: number = 0; i < count; i++) {
this.internalColumns.push(new PdfTreeGridColumn(this.treegrid));
for (let index: number = 0; index < this.treegrid.rows.count; index++) {
const row: PdfTreeGridRow = this.treegrid.rows.getRow(index);
const cell: PdfTreeGridCell = new PdfTreeGridCell();
cell.value = '';
row.cells.add(cell);
}
}
// } else {
// let column : PdfGridColumn = new PdfGridColumn(this.grid);
// this.columns.push(column);
// return column;
// }
}
/**
* Gets the `number of columns` in the 'PdfGrid'.[Read-Only].
*
* @returns {number} .
* @private
*/
public get count(): number {
return this.internalColumns.length;
}
/**
* Gets the `widths`.
*
* @returns {number} .
* @private
*/
public get width(): number {
if (this.columnWidth === 0) {
this.columnWidth = this.measureColumnsWidth();
}
return this.columnWidth;
}
/**
* Gets the `array of PdfGridColumn`.[Read-Only]
*
* @returns {PdfTreeGridColumn[]} .
* @private
*/
public get columns(): PdfTreeGridColumn[] {
return this.internalColumns;
}
/**
* Gets the `PdfTreeGridColumn` from the specified index.[Read-Only]
*
* @param {number} index .
* @returns {PdfTreeGridColumn} .
* @private
*/
public getColumn(index: number): PdfTreeGridColumn {
if (index >= 0 && index <= this.columns.length) {
return this.columns[index];
} else {
throw Error('can not get the column from the index: ' + index);
}
}
//Implementation
/**
* `Calculates the column widths`.
*
* @returns {number} .
* @private
*/
public measureColumnsWidth(): number {
let totalWidth: number = 0;
this.treegrid.measureColumnsWidth();
for (let i: number = 0, count: number = this.internalColumns.length; i < count; i++) {
totalWidth += this.internalColumns[i].width;
}
return totalWidth;
}
/**
* Gets the `widths of the columns`.
*
* @param {number} totalWidth .
* @returns {number} .
* @private
*/
public getDefaultWidths(totalWidth: number): number[] {
const widths: number[] = [];
let subFactor: number = this.count;
for (let i: number = 0; i < this.count; i++) {
widths[i] = this.internalColumns[i].width;
if (this.internalColumns[i].width > 0) {
totalWidth -= this.internalColumns[i].width;
subFactor--;
} else {
widths[i] = 0;
}
}
for (let i: number = 0; i < this.count; i++) {
const width: number = totalWidth / subFactor;
if (widths[i] <= 0) {
widths[i] = width;
}
}
return widths;
}
} | the_stack |
import os from 'os';
import { URL } from 'url';
import path from 'path';
import { promises as fspromises, createWriteStream, createReadStream, constants } from 'fs';
import md5File from 'md5-file';
import https from 'https';
import { createUnzip } from 'zlib';
import tar from 'tar-stream';
import yauzl from 'yauzl';
import MongoBinaryDownloadUrl from './MongoBinaryDownloadUrl';
import { HttpsProxyAgent } from 'https-proxy-agent';
import resolveConfig, { envToBool, ResolveConfigVariables } from './resolveConfig';
import debug from 'debug';
import { assertion, pathExists } from './utils';
import { DryMongoBinary } from './DryMongoBinary';
import mkdirp from 'mkdirp';
import { MongoBinaryOpts } from './MongoBinary';
import { clearLine } from 'readline';
import { Md5CheckFailedError } from './errors';
const log = debug('MongoMS:MongoBinaryDownload');
export interface MongoBinaryDownloadProgress {
current: number;
length: number;
totalMb: number;
lastPrintedAt: number;
}
/**
* Download and extract the "mongod" binary
*/
export class MongoBinaryDownload {
dlProgress: MongoBinaryDownloadProgress;
_downloadingUrl?: string;
/**These options are kind of raw, they are not run through DryMongoBinary.generateOptions */
binaryOpts: Required<MongoBinaryOpts>;
// TODO: for an major version, remove the compat get/set
// the following get/set are to not break existing stuff
get checkMD5(): boolean {
return this.binaryOpts.checkMD5;
}
set checkMD5(val: boolean) {
this.binaryOpts.checkMD5 = val;
}
get downloadDir(): string {
return this.binaryOpts.downloadDir;
}
set downloadDir(val: string) {
this.binaryOpts.downloadDir = val;
}
get arch(): string {
return this.binaryOpts.arch;
}
set arch(val: string) {
this.binaryOpts.arch = val;
}
get version(): string {
return this.binaryOpts.version;
}
set version(val: string) {
this.binaryOpts.version = val;
}
get platform(): string {
return this.binaryOpts.platform;
}
set platform(val: string) {
this.binaryOpts.platform = val;
}
// end get/set backwards compat section
constructor(opts: MongoBinaryOpts) {
assertion(typeof opts.downloadDir === 'string', new Error('An DownloadDir must be specified!'));
const version = opts.version ?? resolveConfig(ResolveConfigVariables.VERSION);
assertion(
typeof version === 'string',
new Error('An MongoDB Binary version must be specified!')
);
// DryMongoBinary.generateOptions cannot be used here, because its async
this.binaryOpts = {
platform: opts.platform ?? os.platform(),
arch: opts.arch ?? os.arch(),
version: version,
downloadDir: opts.downloadDir,
checkMD5: opts.checkMD5 ?? envToBool(resolveConfig(ResolveConfigVariables.MD5_CHECK)),
systemBinary: opts.systemBinary ?? '',
os: opts.os ?? { os: 'unknown' },
};
this.dlProgress = {
current: 0,
length: 0,
totalMb: 0,
lastPrintedAt: 0,
};
}
/**
* Get the full path with filename
* @returns Absoulte Path with FileName
*/
protected async getPath(): Promise<string> {
const opts = await DryMongoBinary.generateOptions(this.binaryOpts);
return DryMongoBinary.combineBinaryName(this.downloadDir, DryMongoBinary.getBinaryName(opts));
}
/**
* Get the path of the already downloaded "mongod" file
* otherwise download it and then return the path
*/
async getMongodPath(): Promise<string> {
log('getMongodPath');
const mongodPath = await this.getPath();
if (await pathExists(mongodPath)) {
log(`getMongodPath: mongod path "${mongodPath}" already exists, using this`);
return mongodPath;
}
const mongoDBArchive = await this.startDownload();
await this.extract(mongoDBArchive);
await fspromises.unlink(mongoDBArchive);
if (await pathExists(mongodPath)) {
return mongodPath;
}
throw new Error(`Cannot find downloaded mongod binary by path "${mongodPath}"`);
}
/**
* Download the MongoDB Archive and check it against an MD5
* @returns The MongoDB Archive location
*/
async startDownload(): Promise<string> {
log('startDownload');
const mbdUrl = new MongoBinaryDownloadUrl(this.binaryOpts);
await mkdirp(this.downloadDir);
try {
await fspromises.access(this.downloadDir, constants.X_OK | constants.W_OK); // check that this process has permissions to create files & modify file contents & read file contents
} catch (err) {
console.error(
`Download Directory at "${this.downloadDir}" does not have sufficient permissions to be used by this process\n` +
'Needed Permissions: Write & Execute (-wx)\n'
);
throw err;
}
const downloadUrl = await mbdUrl.getDownloadUrl();
const mongoDBArchive = await this.download(downloadUrl);
await this.makeMD5check(`${downloadUrl}.md5`, mongoDBArchive);
return mongoDBArchive;
}
/**
* Download MD5 file and check it against the MongoDB Archive
* @param urlForReferenceMD5 URL to download the MD5
* @param mongoDBArchive The MongoDB Archive file location
*
* @returns {undefined} if "checkMD5" is falsey
* @returns {true} if the md5 check was successful
* @throws if the md5 check failed
*/
async makeMD5check(
urlForReferenceMD5: string,
mongoDBArchive: string
): Promise<boolean | undefined> {
log('makeMD5check: Checking MD5 of downloaded binary...');
if (!this.checkMD5) {
log('makeMD5check: checkMD5 is disabled');
return undefined;
}
const mongoDBArchiveMd5 = await this.download(urlForReferenceMD5);
const signatureContent = (await fspromises.readFile(mongoDBArchiveMd5)).toString('utf-8');
const regexMatch = signatureContent.match(/^\s*([\w\d]+)\s*/i);
const md5Remote = regexMatch ? regexMatch[1] : null;
const md5Local = md5File.sync(mongoDBArchive);
log(`makeMD5check: Local MD5: ${md5Local}, Remote MD5: ${md5Remote}`);
if (md5Remote !== md5Local) {
throw new Md5CheckFailedError(md5Local, md5Remote || 'unknown');
}
await fspromises.unlink(mongoDBArchiveMd5);
return true;
}
/**
* Download file from downloadUrl
* @param downloadUrl URL to download a File
* @returns The Path to the downloaded archive file
*/
async download(downloadUrl: string): Promise<string> {
log('download');
const proxy =
process.env['yarn_https-proxy'] ||
process.env.yarn_proxy ||
process.env['npm_config_https-proxy'] ||
process.env.npm_config_proxy ||
process.env.https_proxy ||
process.env.http_proxy ||
process.env.HTTPS_PROXY ||
process.env.HTTP_PROXY;
const strictSsl = process.env.npm_config_strict_ssl === 'true';
const urlObject = new URL(downloadUrl);
urlObject.port = urlObject.port || '443';
const requestOptions: https.RequestOptions = {
method: 'GET',
rejectUnauthorized: strictSsl,
protocol: envToBool(resolveConfig(ResolveConfigVariables.USE_HTTP)) ? 'http:' : 'https:',
agent: proxy ? new HttpsProxyAgent(proxy) : undefined,
};
const filename = urlObject.pathname.split('/').pop();
if (!filename) {
throw new Error(`MongoBinaryDownload: missing filename for url "${downloadUrl}"`);
}
const downloadLocation = path.resolve(this.downloadDir, filename);
const tempDownloadLocation = path.resolve(this.downloadDir, `${filename}.downloading`);
log(`download: Downloading${proxy ? ` via proxy "${proxy}"` : ''}: "${downloadUrl}"`);
if (await pathExists(downloadLocation)) {
log('download: Already downloaded archive found, skipping download');
return downloadLocation;
}
this.assignDownloadingURL(urlObject);
const downloadedFile = await this.httpDownload(
urlObject,
requestOptions,
downloadLocation,
tempDownloadLocation
);
return downloadedFile;
}
/**
* Extract given Archive
* @param mongoDBArchive Archive location
* @returns extracted directory location
*/
async extract(mongoDBArchive: string): Promise<string> {
log('extract');
const mongodbFullPath = await this.getPath();
log(`extract: archive: "${mongoDBArchive}" final: "${mongodbFullPath}"`);
await mkdirp(path.dirname(mongodbFullPath));
const filter = (file: string) => /(?:bin\/(?:mongod(?:\.exe)?)|(?:.*\.dll))$/i.test(file);
if (/(.tar.gz|.tgz)$/.test(mongoDBArchive)) {
await this.extractTarGz(mongoDBArchive, mongodbFullPath, filter);
} else if (/.zip$/.test(mongoDBArchive)) {
await this.extractZip(mongoDBArchive, mongodbFullPath, filter);
} else {
throw new Error(
`MongoBinaryDownload: unsupported archive "${mongoDBArchive}" (downloaded from "${
this._downloadingUrl ?? 'unknown'
}"). Broken archive from MongoDB Provider?`
);
}
if (!(await pathExists(mongodbFullPath))) {
throw new Error(
`MongoBinaryDownload: missing mongod binary in "${mongoDBArchive}" (downloaded from "${
this._downloadingUrl ?? 'unknown'
}"). Broken archive from MongoDB Provider?`
);
}
return mongodbFullPath;
}
/**
* Extract a .tar.gz archive
* @param mongoDBArchive Archive location
* @param extractPath Directory to extract to
* @param filter Method to determine which files to extract
*/
async extractTarGz(
mongoDBArchive: string,
extractPath: string,
filter: (file: string) => boolean
): Promise<void> {
log('extractTarGz');
const extract = tar.extract();
extract.on('entry', (header, stream, next) => {
if (filter(header.name)) {
stream.pipe(
createWriteStream(extractPath, {
mode: 0o775,
})
);
}
stream.on('end', () => next());
stream.resume();
});
return new Promise((resolve, reject) => {
createReadStream(mongoDBArchive)
.on('error', (err) => {
reject('Unable to open tarball ' + mongoDBArchive + ': ' + err);
})
.pipe(createUnzip())
.on('error', (err) => {
reject('Error during unzip for ' + mongoDBArchive + ': ' + err);
})
.pipe(extract)
.on('error', (err) => {
reject('Error during untar for ' + mongoDBArchive + ': ' + err);
})
.on('finish', (result) => {
resolve(result);
});
});
}
/**
* Extract a .zip archive
* @param mongoDBArchive Archive location
* @param extractPath Directory to extract to
* @param filter Method to determine which files to extract
*/
async extractZip(
mongoDBArchive: string,
extractPath: string,
filter: (file: string) => boolean
): Promise<void> {
log('extractZip');
return new Promise((resolve, reject) => {
yauzl.open(mongoDBArchive, { lazyEntries: true }, (e, zipfile) => {
if (e || !zipfile) {
return reject(e);
}
zipfile.readEntry();
zipfile.on('end', () => resolve());
zipfile.on('entry', (entry) => {
if (!filter(entry.fileName)) {
return zipfile.readEntry();
}
zipfile.openReadStream(entry, (e, r) => {
if (e || !r) {
return reject(e);
}
r.on('end', () => zipfile.readEntry());
r.pipe(
createWriteStream(extractPath, {
mode: 0o775,
})
);
});
});
});
});
}
/**
* Downlaod given httpOptions to tempDownloadLocation, then move it to downloadLocation
* @param httpOptions The httpOptions directly passed to https.get
* @param downloadLocation The location the File should be after the download
* @param tempDownloadLocation The location the File should be while downloading
*/
async httpDownload(
url: URL,
httpOptions: https.RequestOptions,
downloadLocation: string,
tempDownloadLocation: string
): Promise<string> {
log('httpDownload');
const downloadUrl = this.assignDownloadingURL(url);
return new Promise((resolve, reject) => {
log(`httpDownload: trying to download "${downloadUrl}"`);
https
.get(url, httpOptions, (response) => {
if (response.statusCode != 200) {
if (response.statusCode === 403) {
reject(
new Error(
"Status Code is 403 (MongoDB's 404)\n" +
"This means that the requested version-platform combination doesn't exist\n" +
` Used Url: "${downloadUrl}"\n` +
"Try to use different version 'new MongoMemoryServer({ binary: { version: 'X.Y.Z' } })'\n" +
'List of available versions can be found here:\n' +
' https://www.mongodb.org/dl/linux for Linux\n' +
' https://www.mongodb.org/dl/osx for OSX\n' +
' https://www.mongodb.org/dl/win32 for Windows'
)
);
return;
}
reject(new Error('Status Code isnt 200!'));
return;
}
if (typeof response.headers['content-length'] != 'string') {
reject(new Error('Response header "content-length" is empty!'));
return;
}
this.dlProgress.current = 0;
this.dlProgress.length = parseInt(response.headers['content-length'], 10);
this.dlProgress.totalMb = Math.round((this.dlProgress.length / 1048576) * 10) / 10;
const fileStream = createWriteStream(tempDownloadLocation);
response.pipe(fileStream);
fileStream.on('finish', async () => {
if (
this.dlProgress.current < this.dlProgress.length &&
!httpOptions.path?.endsWith('.md5')
) {
reject(
new Error(
`Too small (${this.dlProgress.current} bytes) mongod binary downloaded from ${downloadUrl}`
)
);
return;
}
this.printDownloadProgress({ length: 0 }, true);
fileStream.close();
await fspromises.rename(tempDownloadLocation, downloadLocation);
log(`httpDownload: moved "${tempDownloadLocation}" to "${downloadLocation}"`);
resolve(downloadLocation);
});
response.on('data', (chunk: any) => {
this.printDownloadProgress(chunk);
});
})
.on('error', (e: Error) => {
// log it without having debug enabled
console.error(`Couldnt download "${downloadUrl}"!`, e.message);
reject(e);
});
});
}
/**
* Print the Download Progress to STDOUT
* @param chunk A chunk to get the length
*/
printDownloadProgress(chunk: { length: number }, forcePrint: boolean = false): void {
this.dlProgress.current += chunk.length;
const now = Date.now();
if (now - this.dlProgress.lastPrintedAt < 2000 && !forcePrint) {
return;
}
this.dlProgress.lastPrintedAt = now;
const percentComplete =
Math.round(((100.0 * this.dlProgress.current) / this.dlProgress.length) * 10) / 10;
const mbComplete = Math.round((this.dlProgress.current / 1048576) * 10) / 10;
const crReturn = this.platform === 'win32' ? '\x1b[0G' : '\r';
const message = `Downloading MongoDB "${this.version}": ${percentComplete}% (${mbComplete}mb / ${this.dlProgress.totalMb}mb)${crReturn}`;
if (process.stdout.isTTY) {
// if TTY overwrite last line over and over until finished and clear line to avoid residual characters
clearLine(process.stdout, 0); // this is because "process.stdout.clearLine" does not exist anymore
process.stdout.write(message);
} else {
console.log(message);
}
}
/**
* Helper function to de-duplicate assigning "_downloadingUrl"
*/
assignDownloadingURL(url: URL): string {
this._downloadingUrl = url.href;
return this._downloadingUrl;
}
}
export default MongoBinaryDownload; | the_stack |
import * as vscode from 'vscode';
// import * as azdata from 'azdata';
import * as child_process from 'child_process';
import { Dependencies } from './dependencies';
import { COMMAND_DASHBOARD, LogLevel } from './constants';
import { Options, Setting } from './options';
import { Logger } from './logger';
import { Libs } from './libs';
interface FileSelection {
selection: vscode.Position
lastHeartbeatAt: number
}
interface FileSelectionMap {
[key: string]: FileSelection;
}
export class WakaTime {
private appNames = {
'Azure Data Studio': 'azdata',
'SQL Operations Studio': 'sqlops',
'Visual Studio Code': 'vscode',
Onivim: 'onivim',
'Onivim 2': 'onivim',
};
private agentName: string;
private extension;
private statusBar: vscode.StatusBarItem = vscode.window.createStatusBarItem(
vscode.StatusBarAlignment.Left,
);
private disposable: vscode.Disposable;
private lastFile: string;
private lastHeartbeat: number = 0;
private dedupe: FileSelectionMap = {};
private dependencies: Dependencies;
private options: Options;
private logger: Logger;
private getCodingActivityTimeout: NodeJS.Timer;
private fetchTodayInterval: number = 60000;
private lastFetchToday: number = 0;
private showStatusBar: boolean;
private showCodingActivity: boolean;
private disabled: boolean = true;
private extensionPath: string;
constructor(extensionPath: string, logger: Logger, options: Options) {
this.extensionPath = extensionPath;
this.logger = logger;
this.options = options;
}
public initialize(global: boolean): void {
this.dependencies = new Dependencies(
this.options,
this.logger,
this.extensionPath,
global,
);
this.statusBar.command = COMMAND_DASHBOARD;
let extension = vscode.extensions.getExtension('WakaTime.vscode-wakatime');
this.extension = (extension != undefined && extension.packageJSON) || { version: '0.0.0' };
this.logger.debug(`Initializing WakaTime v${this.extension.version}`);
this.agentName = this.appNames[vscode.env.appName] || 'vscode';
this.statusBar.text = '$(clock) WakaTime Initializing...';
this.statusBar.show();
this.setupEventListeners();
this.options.getSetting('settings', 'disabled', this.options.getConfigFile(), (disabled: Setting) => {
this.disabled = disabled.value === 'true';
if (this.disabled) {
this.setStatusBarVisibility(false);
this.logger.debug('Extension disabled, will not report coding stats to dashboard.');
return;
}
this.checkApiKey();
this.initializeDependencies();
});
}
public initializeDependencies(): void {
this.dependencies.checkAndInstall(() => {
this.logger.debug('WakaTime initialized.');
this.statusBar.text = '$(clock)';
this.statusBar.tooltip = 'WakaTime: Initialized';
this.options.getSetting('settings', 'status_bar_enabled', this.options.getConfigFile(), (setting: Setting) => {
this.showStatusBar = setting.value !== 'false';
this.setStatusBarVisibility(this.showStatusBar);
});
this.options.getSetting('settings', 'status_bar_coding_activity', this.options.getConfigFile(), (setting: Setting) => {
if (setting.value == 'false') {
this.showCodingActivity = false;
} else {
this.showCodingActivity = true;
this.getCodingActivity();
}
});
});
}
public promptForApiKey(): void {
this.options.getSetting('settings', 'api_key', this.options.getConfigFile(), (setting: Setting) => {
let defaultVal = setting.value;
if (Libs.validateKey(defaultVal) != '') defaultVal = '';
let promptOptions = {
prompt: 'WakaTime Api Key',
placeHolder: 'Enter your api key from https://wakatime.com/settings',
value: defaultVal,
ignoreFocusOut: true,
validateInput: Libs.validateKey.bind(this),
};
vscode.window.showInputBox(promptOptions).then(val => {
if (val != undefined) {
let validation = Libs.validateKey(val);
if (validation === '') this.options.setSetting('settings', 'api_key', val);
else vscode.window.setStatusBarMessage(validation);
} else vscode.window.setStatusBarMessage('WakaTime api key not provided');
});
});
}
public promptForProxy(): void {
this.options.getSetting('settings', 'proxy', this.options.getConfigFile(), (proxy: Setting) => {
let defaultVal = proxy.value;
if (!defaultVal) defaultVal = '';
let promptOptions = {
prompt: 'WakaTime Proxy',
placeHolder: `Proxy format is https://user:pass@host:port (current value \"${defaultVal}\")`,
value: defaultVal,
ignoreFocusOut: true,
validateInput: Libs.validateProxy.bind(this),
};
vscode.window.showInputBox(promptOptions).then(val => {
if (val || val === '') this.options.setSetting('settings', 'proxy', val);
});
});
}
public promptForDebug(): void {
this.options.getSetting('settings', 'debug', this.options.getConfigFile(), (debug: Setting) => {
let defaultVal = debug.value;
if (!defaultVal || defaultVal !== 'true') defaultVal = 'false';
let items: string[] = ['true', 'false'];
let promptOptions = {
placeHolder: `true or false (current value \"${defaultVal}\")`,
value: defaultVal,
ignoreFocusOut: true,
};
vscode.window.showQuickPick(items, promptOptions).then(newVal => {
if (newVal == null) return;
this.options.setSetting('settings', 'debug', newVal);
if (newVal === 'true') {
this.logger.setLevel(LogLevel.DEBUG);
this.logger.debug('Debug enabled');
} else {
this.logger.setLevel(LogLevel.INFO);
}
});
});
}
public promptToDisable(): void {
this.options.getSetting('settings', 'disabled', this.options.getConfigFile(), (setting: Setting) => {
let currentVal = setting.value;
if (!currentVal || currentVal !== 'true') currentVal = 'false';
let items: string[] = ['disable', 'enable'];
const helperText = currentVal === 'true' ? 'disabled' : 'enabled';
let promptOptions = {
placeHolder: `disable or enable (extension is currently "${helperText}")`,
ignoreFocusOut: true,
};
vscode.window.showQuickPick(items, promptOptions).then(newVal => {
if (newVal !== 'enable' && newVal !== 'disable') return;
this.disabled = newVal === 'disable';
if (this.disabled) {
this.options.setSetting('settings', 'disabled', 'true');
this.setStatusBarVisibility(false);
this.logger.debug('Extension disabled, will not report coding stats to dashboard.');
} else {
this.options.setSetting('settings', 'disabled', 'false');
this.checkApiKey();
this.initializeDependencies();
if (this.showStatusBar) this.setStatusBarVisibility(true);
this.logger.debug('Extension enabled and reporting coding stats to dashboard.');
}
});
});
}
public promptStatusBarIcon(): void {
this.options.getSetting('settings', 'status_bar_enabled', this.options.getConfigFile(), (setting: Setting) => {
let defaultVal = setting.value;
if (!defaultVal || defaultVal !== 'false') defaultVal = 'true';
let items: string[] = ['true', 'false'];
let promptOptions = {
placeHolder: `true or false (current value \"${defaultVal}\")`,
value: defaultVal,
ignoreFocusOut: true,
};
vscode.window.showQuickPick(items, promptOptions).then(newVal => {
if (newVal !== 'true' && newVal !== 'false') return;
this.options.setSetting('settings', 'status_bar_enabled', newVal);
this.showStatusBar = newVal === 'true'; // cache setting to prevent reading from disc too often
this.setStatusBarVisibility(this.showStatusBar);
});
});
}
public promptStatusBarCodingActivity(): void {
this.options.getSetting('settings', 'status_bar_coding_activity', this.options.getConfigFile(), (setting: Setting) => {
let defaultVal = setting.value;
if (!defaultVal || defaultVal !== 'false') defaultVal = 'true';
let items: string[] = ['true', 'false'];
let promptOptions = {
placeHolder: `true or false (current value \"${defaultVal}\")`,
value: defaultVal,
ignoreFocusOut: true,
};
vscode.window.showQuickPick(items, promptOptions).then(newVal => {
if (newVal !== 'true' && newVal !== 'false') return;
this.options.setSetting('settings', 'status_bar_coding_activity', newVal);
if (newVal === 'true') {
this.logger.debug('Coding activity in status bar has been enabled');
this.showCodingActivity = true;
this.getCodingActivity(true);
} else {
this.logger.debug('Coding activity in status bar has been disabled');
this.showCodingActivity = false;
if (this.statusBar.text.indexOf('Error') == -1) {
this.statusBar.text = '$(clock)';
}
}
});
});
}
public openDashboardWebsite(): void {
let url = 'https://wakatime.com/';
vscode.env.openExternal(vscode.Uri.parse(url));
}
public openConfigFile(): void {
let path = this.options.getConfigFile();
if (path) {
let uri = vscode.Uri.file(path);
vscode.window.showTextDocument(uri);
}
}
public openLogFile(): void {
let path = this.options.getLogFile();
if (path) {
let uri = vscode.Uri.file(path);
vscode.window.showTextDocument(uri);
}
}
public dispose() {
this.statusBar.dispose();
this.disposable.dispose();
clearTimeout(this.getCodingActivityTimeout);
}
private checkApiKey(): void {
this.hasApiKey(hasApiKey => {
if (!hasApiKey) this.promptForApiKey();
});
}
private hasApiKey(callback: (arg0: boolean) => void): void {
this.options
.getApiKeyAsync()
.then(apiKey => callback(Libs.validateKey(apiKey) === ''))
.catch(err => {
this.logger.error(`Error reading api key: ${err}`);
callback(false);
});
}
private setStatusBarVisibility(isVisible: boolean): void {
if (isVisible) {
this.statusBar.show();
this.logger.debug('Status bar icon enabled.');
} else {
this.statusBar.hide();
this.logger.debug('Status bar icon disabled.');
}
}
private setupEventListeners(): void {
// subscribe to selection change and editor activation events
let subscriptions: vscode.Disposable[] = [];
vscode.window.onDidChangeTextEditorSelection(this.onChange, this, subscriptions);
vscode.window.onDidChangeActiveTextEditor(this.onChange, this, subscriptions);
vscode.workspace.onDidSaveTextDocument(this.onSave, this, subscriptions);
// create a combined disposable from both event subscriptions
this.disposable = vscode.Disposable.from(...subscriptions);
}
private onChange(): void {
this.onEvent(false);
}
private onSave(): void {
this.onEvent(true);
}
private onEvent(isWrite: boolean): void {
if (this.disabled) return;
let editor = vscode.window.activeTextEditor;
if (editor) {
let doc = editor.document;
if (doc) {
let file: string = doc.fileName;
if (file) {
let time: number = Date.now();
if (isWrite || this.enoughTimePassed(time) || this.lastFile !== file) {
this.sendHeartbeat(file, time, editor.selection.start, doc.lineCount, isWrite);
this.lastFile = file;
this.lastHeartbeat = time;
}
}
}
}
}
private sendHeartbeat(file: string, time: number, selection: vscode.Position, lines: number, isWrite: boolean): void {
this.hasApiKey(hasApiKey => {
if (hasApiKey) {
this._sendHeartbeat(file, time, selection, lines, isWrite);
} else {
this.promptForApiKey();
}
});
}
private _sendHeartbeat(file: string, time: number, selection: vscode.Position, lines: number, isWrite: boolean): void {
if (!this.dependencies.isCliInstalled()) return;
// prevent sending the same heartbeat (https://github.com/wakatime/vscode-wakatime/issues/163)
if (isWrite && this.isDuplicateHeartbeat(file, time, selection)) return;
let user_agent =
this.agentName + '/' + vscode.version + ' vscode-wakatime/' + this.extension.version;
let args = ['--entity', Libs.quote(file), '--plugin', Libs.quote(user_agent)];
args.push('--lineno', String(selection.line + 1));
args.push('--cursorpos', String(selection.character + 1));
args.push('--lines-in-file', String(lines));
let project = this.getProjectName(file);
if (project) args.push('--alternate-project', Libs.quote(project));
if (isWrite) args.push('--write');
if (process.env.WAKATIME_API_KEY) args.push('--key', Libs.quote(process.env.WAKATIME_API_KEY))
if (Dependencies.isWindows() || Dependencies.isPortable()) {
args.push(
'--config',
Libs.quote(this.options.getConfigFile()),
'--log-file',
Libs.quote(this.options.getLogFile()),
);
}
const binary = this.dependencies.getCliLocation();
this.logger.debug(`Sending heartbeat: ${this.formatArguments(binary, args)}`);
const options = this.dependencies.buildOptions();
let proc = child_process.execFile(binary, args, options, (error, stdout, stderr) => {
if (error != null) {
if (stderr && stderr.toString() != '') this.logger.error(stderr.toString());
if (stdout && stdout.toString() != '') this.logger.error(stdout.toString());
this.logger.error(error.toString());
}
});
proc.on('close', (code, _signal) => {
if (code == 0) {
if (this.showStatusBar) {
if (!this.showCodingActivity) this.statusBar.text = '$(clock)';
this.getCodingActivity();
}
let today = new Date();
this.logger.debug(`last heartbeat sent ${this.formatDate(today)}`);
} else if (code == 102) {
if (this.showStatusBar) {
if (!this.showCodingActivity) this.statusBar.text = '$(clock)';
this.statusBar.tooltip =
'WakaTime: working offline... coding activity will sync next time we are online';
}
this.logger.warn(
`Api eror (102); Check your ${this.options.getLogFile()} file for more details`,
);
} else if (code == 103) {
let error_msg = `Config parsing error (103); Check your ${this.options.getLogFile()} file for more details`;
if (this.showStatusBar) {
this.statusBar.text = '$(clock) WakaTime Error';
this.statusBar.tooltip = `WakaTime: ${error_msg}`;
}
this.logger.error(error_msg);
} else if (code == 104) {
let error_msg = 'Invalid Api Key (104); Make sure your Api Key is correct!';
if (this.showStatusBar) {
this.statusBar.text = '$(clock) WakaTime Error';
this.statusBar.tooltip = `WakaTime: ${error_msg}`;
}
this.logger.error(error_msg);
} else {
let error_msg = `Unknown Error (${code}); Check your ${this.options.getLogFile()} file for more details`;
if (this.showStatusBar) {
this.statusBar.text = '$(clock) WakaTime Error';
this.statusBar.tooltip = `WakaTime: ${error_msg}`;
}
this.logger.error(error_msg);
}
});
}
private getCodingActivity(force: boolean = false) {
if (!this.showCodingActivity || !this.showStatusBar) return;
const cutoff = Date.now() - this.fetchTodayInterval;
if (!force && this.lastFetchToday > cutoff) return;
this.lastFetchToday = Date.now();
this.getCodingActivityTimeout = setTimeout(this.getCodingActivity, this.fetchTodayInterval);
this.hasApiKey(hasApiKey => {
if (!hasApiKey) return;
this._getCodingActivity();
});
}
private _getCodingActivity() {
if (!this.dependencies.isCliInstalled()) return;
let user_agent =
this.agentName + '/' + vscode.version + ' vscode-wakatime/' + this.extension.version;
let args = ['--today', '--plugin', Libs.quote(user_agent)];
if (process.env.WAKATIME_API_KEY) args.push('--key', Libs.quote(process.env.WAKATIME_API_KEY))
if (Dependencies.isWindows()) {
args.push(
'--config',
Libs.quote(this.options.getConfigFile()),
'--logfile',
Libs.quote(this.options.getLogFile()),
);
}
const binary = this.dependencies.getCliLocation();
this.logger.debug(
`Fetching coding activity for Today from api: ${this.formatArguments(binary, args)}`,
);
const options = this.dependencies.buildOptions();
let proc = child_process.execFile(binary, args, options, (error, stdout, stderr) => {
if (error != null) {
if (stderr && stderr.toString() != '') this.logger.error(stderr.toString());
if (stdout && stdout.toString() != '') this.logger.error(stdout.toString());
this.logger.error(error.toString());
}
});
let output = '';
if (proc.stdout) {
proc.stdout.on('data', (data: string | null) => {
if (data) output += data;
});
}
proc.on('close', (code, _signal) => {
if (code == 0) {
if (this.showStatusBar && this.showCodingActivity) {
if (output && output.trim()) {
this.statusBar.text = `$(clock) ${output.trim()}`;
this.statusBar.tooltip = `WakaTime: Today you’ve spent ${output.trim()}.`;
} else {
this.statusBar.text = `$(clock)`;
this.statusBar.tooltip = `WakaTime: Calculating time spent today in background...`;
}
}
} else if (code == 102) {
// noop, working offline
} else {
let error_msg = `Error fetching today coding activity (${code}); Check your ${this.options.getLogFile()} file for more details`;
this.logger.debug(error_msg);
}
});
}
private formatDate(date: Date): String {
let months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
];
let ampm = 'AM';
let hour = date.getHours();
if (hour > 11) {
ampm = 'PM';
hour = hour - 12;
}
if (hour == 0) {
hour = 12;
}
let minute = date.getMinutes();
return `${months[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()} ${hour}:${
minute < 10 ? `0${minute}` : minute
} ${ampm}`;
}
private enoughTimePassed(time: number): boolean {
return this.lastHeartbeat + 120000 < time;
}
private isDuplicateHeartbeat(file: string, time: number, selection: vscode.Position): boolean {
let duplicate = false;
let minutes = 30;
let milliseconds = minutes * 60000;
if (this.dedupe[file] && this.dedupe[file].lastHeartbeatAt + milliseconds < time && this.dedupe[file].selection.line == selection.line && this.dedupe[file].selection.character == selection.character) {
duplicate = true;
}
this.dedupe[file] = {
selection: selection,
lastHeartbeatAt: time,
}
return duplicate;
}
private getProjectName(file: string): string {
let uri = vscode.Uri.file(file);
let workspaceFolder = vscode.workspace.getWorkspaceFolder(uri);
if (vscode.workspace && workspaceFolder) {
try {
return workspaceFolder.name;
} catch (e) {}
}
return '';
}
private obfuscateKey(key: string): string {
let newKey = '';
if (key) {
newKey = key;
if (key.length > 4)
newKey = 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX' + key.substring(key.length - 4);
}
return newKey;
}
private wrapArg(arg: string): string {
if (arg.indexOf(' ') > -1) return '"' + arg.replace(/"/g, '\\"') + '"';
return arg;
}
private formatArguments(binary: string, args: string[]): string {
let clone = args.slice(0);
clone.unshift(this.wrapArg(binary));
let newCmds: string[] = [];
let lastCmd = '';
for (let i = 0; i < clone.length; i++) {
if (lastCmd == '--key') newCmds.push(this.wrapArg(this.obfuscateKey(clone[i])));
else newCmds.push(this.wrapArg(clone[i]));
lastCmd = clone[i];
}
return newCmds.join(' ');
}
} | the_stack |
import classNames from "classnames";
import clamp from "lodash.clamp";
import isEqual from "lodash.isequal";
import React, {
forwardRef,
useCallback,
useEffect,
useImperativeHandle,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import useResizeObserver from "use-resize-observer";
import styles from "./allotment.module.css";
import { isIOS } from "./helpers/platform";
import { LayoutService } from "./layout-service";
import { PaneView } from "./pane-view";
import { Orientation, setGlobalSashSize } from "./sash";
import {
LayoutPriority,
Sizing,
SplitView,
SplitViewOptions,
} from "./split-view";
function isPane(item: React.ReactNode): item is typeof Pane {
return (item as any).type.displayName === "Allotment.Pane";
}
function isPaneProps(props: AllotmentProps | PaneProps): props is PaneProps {
return (
(props as PaneProps).minSize !== undefined ||
(props as PaneProps).maxSize !== undefined ||
(props as PaneProps).preferredSize !== undefined ||
(props as PaneProps).priority !== undefined ||
(props as PaneProps).visible !== undefined
);
}
export interface CommonProps {
/** Sets a className attribute on the outer component */
className?: string;
/** Maximum size of each element */
maxSize?: number;
/** Minimum size of each element */
minSize?: number;
/** Enable snap to zero size */
snap?: boolean;
}
export type PaneProps = {
children: React.ReactNode;
/**
* Preferred size of this pane. Allotment will attempt to use this size when adding this pane (including on initial mount) as well as when a user double clicks a sash, or the `reset` method is called on the Allotment instance.
* @remarks The size can either be a number or a string. If it is a number it will be interpreted as a number of pixels. If it is a string it should end in either "px" or "%". If it ends in "px" it will be interpreted as a number of pixels, e.g. "120px". If it ends in "%" it will be interpreted as a percentage of the size of the Allotment component, e.g. "50%".
*/
preferredSize?: number | string;
/**
* The priority of the pane when the layout algorithm runs. Panes with higher priority will be resized first.
* @remarks Only used when `proportionalLayout` is false.
*/
priority?: LayoutPriority;
/** Whether the pane should be visible */
visible?: boolean;
} & CommonProps;
/**
* Pane component.
*/
export const Pane = forwardRef<HTMLDivElement, PaneProps>(
({ className, children }: PaneProps, ref) => {
return (
<div ref={ref} className={classNames(styles.splitViewView, className)}>
{children}
</div>
);
}
);
Pane.displayName = "Allotment.Pane";
export type AllotmentHandle = {
reset: () => void;
resize: (sizes: number[]) => void;
};
export type AllotmentProps = {
children: React.ReactNode;
/** Initial size of each element */
defaultSizes?: number[];
/** Resize each view proportionally when resizing container */
proportionalLayout?: boolean;
/**
* Initial size of each element
* @deprecated Use {@link AllotmentProps.defaultSizes defaultSizes} instead
*/
sizes?: number[];
/** Direction to split */
vertical?: boolean;
/** Callback on drag */
onChange?: (sizes: number[]) => void;
/** Callback on reset */
onReset?: () => void;
/** Callback on visibility change */
onVisibleChange?: (index: number, visible: boolean) => void;
} & CommonProps;
/**
* React split-pane component.
*/
const Allotment = forwardRef<AllotmentHandle, AllotmentProps>(
(
{
children,
className,
maxSize = Infinity,
minSize = 30,
proportionalLayout = true,
sizes,
defaultSizes = sizes,
snap = false,
vertical = false,
onChange,
onReset,
onVisibleChange,
},
ref
) => {
const containerRef = useRef<HTMLDivElement>(null!);
const previousKeys = useRef<string[]>([]);
const splitViewPropsRef = useRef(new Map<React.Key, PaneProps>());
const splitViewRef = useRef<SplitView | null>(null);
const splitViewViewRef = useRef(new Map<React.Key, HTMLElement>());
const layoutService = useRef<LayoutService>(new LayoutService());
const views = useRef<PaneView[]>([]);
const [dimensionsInitialized, setDimensionsInitialized] = useState(false);
if (process.env.NODE_ENV !== "production" && sizes) {
console.warn(
`Prop sizes is deprecated. Please use defaultSizes instead.`
);
}
const childrenArray = useMemo(
() => React.Children.toArray(children).filter(React.isValidElement),
[children]
);
const resizeToPreferredSize = useCallback((index: number): boolean => {
const view = views.current?.[index];
if (typeof view?.preferredSize !== "number") {
return false;
}
splitViewRef.current?.resizeView(index, Math.round(view.preferredSize));
return true;
}, []);
useImperativeHandle(ref, () => ({
reset: () => {
if (onReset) {
onReset();
} else {
splitViewRef.current?.distributeViewSizes();
for (let index = 0; index < views.current.length; index++) {
resizeToPreferredSize(index);
}
}
},
resize: (sizes) => {
splitViewRef.current?.resizeViews(sizes);
},
}));
useLayoutEffect(() => {
let initializeSizes = true;
if (
defaultSizes &&
splitViewViewRef.current.size !== defaultSizes.length
) {
initializeSizes = false;
console.warn(
`Expected ${defaultSizes.length} children based on defaultSizes but found ${splitViewViewRef.current.size}`
);
}
if (initializeSizes && defaultSizes) {
previousKeys.current = childrenArray.map(
(child) => child.key as string
);
}
const options: SplitViewOptions = {
orientation: vertical ? Orientation.Vertical : Orientation.Horizontal,
proportionalLayout,
...(initializeSizes &&
defaultSizes && {
descriptor: {
size: defaultSizes.reduce((a, b) => a + b, 0),
views: defaultSizes.map((size, index) => {
const props = splitViewPropsRef.current.get(
previousKeys.current[index]
);
const view = new PaneView(layoutService.current, {
element: document.createElement("div"),
minimumSize: props?.minSize ?? minSize,
maximumSize: props?.maxSize ?? maxSize,
priority: props?.priority ?? LayoutPriority.Normal,
...(props?.preferredSize && {
preferredSize: props?.preferredSize,
}),
snap: props?.snap ?? snap,
});
views.current.push(view);
return {
container: [...splitViewViewRef.current.values()][index],
size: size,
view: view,
};
}),
},
}),
};
splitViewRef.current = new SplitView(
containerRef.current,
options,
onChange
);
splitViewRef.current.on("sashchange", (_index: number) => {
if (onVisibleChange && splitViewRef.current) {
const keys = childrenArray.map((child) => child.key as string);
for (let index = 0; index < keys.length; index++) {
const props = splitViewPropsRef.current.get(keys[index]);
if (props?.visible !== undefined) {
if (props.visible !== splitViewRef.current.isViewVisible(index)) {
onVisibleChange(
index,
splitViewRef.current.isViewVisible(index)
);
}
}
}
}
});
splitViewRef.current.on("sashreset", (index: number) => {
if (onReset) {
onReset();
} else {
if (resizeToPreferredSize(index)) {
return;
}
if (resizeToPreferredSize(index + 1)) {
return;
}
splitViewRef.current?.distributeViewSizes();
}
});
const that = splitViewRef.current;
return () => {
that.dispose();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
/**
* Add, remove or update views as children change
*/
useEffect(() => {
if (dimensionsInitialized) {
const keys = childrenArray.map((child) => child.key as string);
const panes = [...previousKeys.current];
const enter = keys.filter((key) => !previousKeys.current.includes(key));
const update = keys.filter((key) => previousKeys.current.includes(key));
const exit = previousKeys.current.map((key) => !keys.includes(key));
exit.forEach((flag, index) => {
if (flag) {
splitViewRef.current?.removeView(index);
panes.splice(index, 1);
views.current.splice(index, 1);
}
});
for (const enterKey of enter) {
const props = splitViewPropsRef.current.get(enterKey);
const view = new PaneView(layoutService.current, {
element: document.createElement("div"),
minimumSize: props?.minSize ?? minSize,
maximumSize: props?.maxSize ?? maxSize,
priority: props?.priority ?? LayoutPriority.Normal,
...(props?.preferredSize && {
preferredSize: props?.preferredSize,
}),
snap: props?.snap ?? snap,
});
splitViewRef.current?.addView(
splitViewViewRef.current.get(enterKey)!,
view,
Sizing.Distribute,
keys.findIndex((key) => key === enterKey)
);
panes.splice(
keys.findIndex((key) => key === enterKey),
0,
enterKey
);
views.current.splice(
keys.findIndex((key) => key === enterKey),
0,
view
);
}
// Move panes if order has changed
while (!isEqual(keys, panes)) {
for (const [i, key] of keys.entries()) {
const index = panes.findIndex((pane) => pane === key);
if (index !== i) {
splitViewRef.current?.moveView(
splitViewViewRef.current.get(key) as HTMLElement,
index,
i
);
const tempKey = panes[index];
panes.splice(index, 1);
panes.splice(i, 0, tempKey);
break;
}
}
}
for (const enterKey of enter) {
const index = keys.findIndex((key) => key === enterKey);
const preferredSize = views.current[index].preferredSize;
if (preferredSize !== undefined) {
splitViewRef.current?.resizeView(index, preferredSize);
}
}
for (const updateKey of [...enter, ...update]) {
const props = splitViewPropsRef.current.get(updateKey);
const index = keys.findIndex((key) => key === updateKey);
if (props && isPaneProps(props)) {
if (props.visible !== undefined) {
if (
splitViewRef.current?.isViewVisible(index) !== props.visible
) {
splitViewRef.current?.setViewVisible(index, props.visible);
}
}
}
}
for (const updateKey of update) {
const props = splitViewPropsRef.current.get(updateKey);
const index = keys.findIndex((key) => key === updateKey);
if (props && isPaneProps(props)) {
if (
props.preferredSize !== undefined &&
views.current[index].preferredSize !== props.preferredSize
) {
views.current[index].preferredSize = props.preferredSize;
}
let sizeChanged = false;
if (
props.minSize !== undefined &&
views.current[index].minimumSize !== props.minSize
) {
views.current[index].minimumSize = props.minSize;
sizeChanged = true;
}
if (
props.maxSize !== undefined &&
views.current[index].maximumSize !== props.maxSize
) {
views.current[index].maximumSize = props.maxSize;
sizeChanged = true;
}
if (sizeChanged) {
splitViewRef.current?.layout();
}
}
}
if (enter.length > 0 || exit.length > 0) {
previousKeys.current = keys;
}
}
}, [childrenArray, dimensionsInitialized, maxSize, minSize, snap]);
useEffect(() => {
if (splitViewRef.current) {
splitViewRef.current.onDidChange = onChange;
}
}, [onChange]);
useResizeObserver({
ref: containerRef,
onResize: ({ width, height }) => {
if (width && height) {
splitViewRef.current?.layout(vertical ? height : width);
layoutService.current.setSize(vertical ? height : width);
setDimensionsInitialized(true);
}
},
});
useEffect(() => {
if (isIOS) {
setSashSize(20);
}
}, []);
return (
<div
ref={containerRef}
className={classNames(
styles.splitView,
vertical ? styles.vertical : styles.horizontal,
styles.separatorBorder,
className
)}
>
<div className={styles.splitViewContainer}>
{React.Children.toArray(children).map((child) => {
if (!React.isValidElement(child)) {
return null;
}
// toArray flattens and converts nulls to non-null keys
const key = child.key!;
if (isPane(child)) {
splitViewPropsRef.current.set(key, child.props);
return React.cloneElement(child, {
key: key,
ref: (el: HTMLElement | null) => {
if (el) {
splitViewViewRef.current.set(key, el);
} else {
splitViewViewRef.current.delete(key);
}
},
});
} else {
return (
<Pane
key={key}
ref={(el: HTMLElement | null) => {
if (el) {
splitViewViewRef.current.set(key, el);
} else {
splitViewViewRef.current.delete(key);
}
}}
>
{child}
</Pane>
);
}
})}
</div>
</div>
);
}
);
Allotment.displayName = "Allotment";
/**
* Set sash size. This is set in both css and js and this function keeps the two in sync.
*
* @param sashSize Sash size in pixels
*/
export function setSashSize(sashSize: number) {
const size = clamp(sashSize, 4, 20);
const hoverSize = clamp(sashSize, 1, 8);
document.documentElement.style.setProperty("--sash-size", size + "px");
document.documentElement.style.setProperty(
"--sash-hover-size",
hoverSize + "px"
);
setGlobalSashSize(size);
}
export default Object.assign(Allotment, { Pane: Pane }); | the_stack |
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest';
import * as models from '../models';
/**
* @class
* Accounts
* __NOTE__: An instance of this class is automatically created for an
* instance of the MapsManagementClient.
*/
export interface Accounts {
/**
* Create or update a Maps Account. A Maps Account holds the keys which allow
* access to the Maps REST APIs.
*
* @param {string} resourceGroupName The name of the Azure Resource Group.
*
* @param {string} accountName The name of the Maps Account.
*
* @param {object} mapsAccountCreateParameters The new or updated parameters
* for the Maps Account.
*
* @param {string} mapsAccountCreateParameters.location The location of the
* resource.
*
* @param {object} [mapsAccountCreateParameters.tags] Gets or sets a list of
* key value pairs that describe the resource. These tags can be used in
* viewing and grouping this resource (across resource groups). A maximum of 15
* tags can be provided for a resource. Each tag must have a key no greater
* than 128 characters and value no greater than 256 characters.
*
* @param {object} mapsAccountCreateParameters.sku The SKU of this account.
*
* @param {string} mapsAccountCreateParameters.sku.name The name of the SKU, in
* standard format (such as S0).
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<MapsAccount>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createOrUpdateWithHttpOperationResponse(resourceGroupName: string, accountName: string, mapsAccountCreateParameters: models.MapsAccountCreateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MapsAccount>>;
/**
* Create or update a Maps Account. A Maps Account holds the keys which allow
* access to the Maps REST APIs.
*
* @param {string} resourceGroupName The name of the Azure Resource Group.
*
* @param {string} accountName The name of the Maps Account.
*
* @param {object} mapsAccountCreateParameters The new or updated parameters
* for the Maps Account.
*
* @param {string} mapsAccountCreateParameters.location The location of the
* resource.
*
* @param {object} [mapsAccountCreateParameters.tags] Gets or sets a list of
* key value pairs that describe the resource. These tags can be used in
* viewing and grouping this resource (across resource groups). A maximum of 15
* tags can be provided for a resource. Each tag must have a key no greater
* than 128 characters and value no greater than 256 characters.
*
* @param {object} mapsAccountCreateParameters.sku The SKU of this account.
*
* @param {string} mapsAccountCreateParameters.sku.name The name of the SKU, in
* standard format (such as S0).
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {MapsAccount} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {MapsAccount} [result] - The deserialized result object if an error did not occur.
* See {@link MapsAccount} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
createOrUpdate(resourceGroupName: string, accountName: string, mapsAccountCreateParameters: models.MapsAccountCreateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.MapsAccount>;
createOrUpdate(resourceGroupName: string, accountName: string, mapsAccountCreateParameters: models.MapsAccountCreateParameters, callback: ServiceCallback<models.MapsAccount>): void;
createOrUpdate(resourceGroupName: string, accountName: string, mapsAccountCreateParameters: models.MapsAccountCreateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MapsAccount>): void;
/**
* Updates a Maps Account. Only a subset of the parameters may be updated after
* creation, such as Sku and Tags.
*
* @param {string} resourceGroupName The name of the Azure Resource Group.
*
* @param {string} accountName The name of the Maps Account.
*
* @param {object} mapsAccountUpdateParameters The updated parameters for the
* Maps Account.
*
* @param {object} [mapsAccountUpdateParameters.tags] Gets or sets a list of
* key value pairs that describe the resource. These tags can be used in
* viewing and grouping this resource (across resource groups). A maximum of 15
* tags can be provided for a resource. Each tag must have a key no greater
* than 128 characters and value no greater than 256 characters.
*
* @param {object} [mapsAccountUpdateParameters.sku] The SKU of this account.
*
* @param {string} mapsAccountUpdateParameters.sku.name The name of the SKU, in
* standard format (such as S0).
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<MapsAccount>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
updateWithHttpOperationResponse(resourceGroupName: string, accountName: string, mapsAccountUpdateParameters: models.MapsAccountUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MapsAccount>>;
/**
* Updates a Maps Account. Only a subset of the parameters may be updated after
* creation, such as Sku and Tags.
*
* @param {string} resourceGroupName The name of the Azure Resource Group.
*
* @param {string} accountName The name of the Maps Account.
*
* @param {object} mapsAccountUpdateParameters The updated parameters for the
* Maps Account.
*
* @param {object} [mapsAccountUpdateParameters.tags] Gets or sets a list of
* key value pairs that describe the resource. These tags can be used in
* viewing and grouping this resource (across resource groups). A maximum of 15
* tags can be provided for a resource. Each tag must have a key no greater
* than 128 characters and value no greater than 256 characters.
*
* @param {object} [mapsAccountUpdateParameters.sku] The SKU of this account.
*
* @param {string} mapsAccountUpdateParameters.sku.name The name of the SKU, in
* standard format (such as S0).
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {MapsAccount} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {MapsAccount} [result] - The deserialized result object if an error did not occur.
* See {@link MapsAccount} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
update(resourceGroupName: string, accountName: string, mapsAccountUpdateParameters: models.MapsAccountUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.MapsAccount>;
update(resourceGroupName: string, accountName: string, mapsAccountUpdateParameters: models.MapsAccountUpdateParameters, callback: ServiceCallback<models.MapsAccount>): void;
update(resourceGroupName: string, accountName: string, mapsAccountUpdateParameters: models.MapsAccountUpdateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MapsAccount>): void;
/**
* Delete a Maps Account.
*
* @param {string} resourceGroupName The name of the Azure Resource Group.
*
* @param {string} accountName The name of the Maps Account.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(resourceGroupName: string, accountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Delete a Maps Account.
*
* @param {string} resourceGroupName The name of the Azure Resource Group.
*
* @param {string} accountName The name of the Maps Account.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
deleteMethod(resourceGroupName: string, accountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteMethod(resourceGroupName: string, accountName: string, callback: ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, accountName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Get a Maps Account.
*
* @param {string} resourceGroupName The name of the Azure Resource Group.
*
* @param {string} accountName The name of the Maps Account.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<MapsAccount>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, accountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MapsAccount>>;
/**
* Get a Maps Account.
*
* @param {string} resourceGroupName The name of the Azure Resource Group.
*
* @param {string} accountName The name of the Maps Account.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {MapsAccount} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {MapsAccount} [result] - The deserialized result object if an error did not occur.
* See {@link MapsAccount} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(resourceGroupName: string, accountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.MapsAccount>;
get(resourceGroupName: string, accountName: string, callback: ServiceCallback<models.MapsAccount>): void;
get(resourceGroupName: string, accountName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MapsAccount>): void;
/**
* Get all Maps Accounts in a Resource Group
*
* @param {string} resourceGroupName The name of the Azure Resource Group.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<MapsAccounts>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MapsAccounts>>;
/**
* Get all Maps Accounts in a Resource Group
*
* @param {string} resourceGroupName The name of the Azure Resource Group.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {MapsAccounts} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {MapsAccounts} [result] - The deserialized result object if an error did not occur.
* See {@link MapsAccounts} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByResourceGroup(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.MapsAccounts>;
listByResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.MapsAccounts>): void;
listByResourceGroup(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MapsAccounts>): void;
/**
* Get all Maps Accounts in a Subscription
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<MapsAccounts>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listBySubscriptionWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MapsAccounts>>;
/**
* Get all Maps Accounts in a Subscription
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {MapsAccounts} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {MapsAccounts} [result] - The deserialized result object if an error did not occur.
* See {@link MapsAccounts} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listBySubscription(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.MapsAccounts>;
listBySubscription(callback: ServiceCallback<models.MapsAccounts>): void;
listBySubscription(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MapsAccounts>): void;
/**
* Moves Maps Accounts from one ResourceGroup (or Subscription) to another
*
* @param {string} resourceGroupName The name of the resource group that
* contains Maps Account to move.
*
* @param {object} moveRequest The details of the Maps Account move.
*
* @param {string} moveRequest.targetResourceGroup The name of the destination
* resource group.
*
* @param {array} moveRequest.resourceIds A list of resource names to move from
* the source resource group.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
moveWithHttpOperationResponse(resourceGroupName: string, moveRequest: models.MapsAccountsMoveRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Moves Maps Accounts from one ResourceGroup (or Subscription) to another
*
* @param {string} resourceGroupName The name of the resource group that
* contains Maps Account to move.
*
* @param {object} moveRequest The details of the Maps Account move.
*
* @param {string} moveRequest.targetResourceGroup The name of the destination
* resource group.
*
* @param {array} moveRequest.resourceIds A list of resource names to move from
* the source resource group.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
move(resourceGroupName: string, moveRequest: models.MapsAccountsMoveRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
move(resourceGroupName: string, moveRequest: models.MapsAccountsMoveRequest, callback: ServiceCallback<void>): void;
move(resourceGroupName: string, moveRequest: models.MapsAccountsMoveRequest, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Get the keys to use with the Maps APIs. A key is used to authenticate and
* authorize access to the Maps REST APIs. Only one key is needed at a time;
* two are given to provide seamless key regeneration.
*
* @param {string} resourceGroupName The name of the Azure Resource Group.
*
* @param {string} accountName The name of the Maps Account.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<MapsAccountKeys>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listKeysWithHttpOperationResponse(resourceGroupName: string, accountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MapsAccountKeys>>;
/**
* Get the keys to use with the Maps APIs. A key is used to authenticate and
* authorize access to the Maps REST APIs. Only one key is needed at a time;
* two are given to provide seamless key regeneration.
*
* @param {string} resourceGroupName The name of the Azure Resource Group.
*
* @param {string} accountName The name of the Maps Account.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {MapsAccountKeys} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {MapsAccountKeys} [result] - The deserialized result object if an error did not occur.
* See {@link MapsAccountKeys} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listKeys(resourceGroupName: string, accountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.MapsAccountKeys>;
listKeys(resourceGroupName: string, accountName: string, callback: ServiceCallback<models.MapsAccountKeys>): void;
listKeys(resourceGroupName: string, accountName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MapsAccountKeys>): void;
/**
* Regenerate either the primary or secondary key for use with the Maps APIs.
* The old key will stop working immediately.
*
* @param {string} resourceGroupName The name of the Azure Resource Group.
*
* @param {string} accountName The name of the Maps Account.
*
* @param {object} keySpecification Which key to regenerate: primary or
* secondary.
*
* @param {string} keySpecification.keyType Whether the operation refers to the
* primary or secondary key. Possible values include: 'primary', 'secondary'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<MapsAccountKeys>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
regenerateKeysWithHttpOperationResponse(resourceGroupName: string, accountName: string, keySpecification: models.MapsKeySpecification, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MapsAccountKeys>>;
/**
* Regenerate either the primary or secondary key for use with the Maps APIs.
* The old key will stop working immediately.
*
* @param {string} resourceGroupName The name of the Azure Resource Group.
*
* @param {string} accountName The name of the Maps Account.
*
* @param {object} keySpecification Which key to regenerate: primary or
* secondary.
*
* @param {string} keySpecification.keyType Whether the operation refers to the
* primary or secondary key. Possible values include: 'primary', 'secondary'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {MapsAccountKeys} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {MapsAccountKeys} [result] - The deserialized result object if an error did not occur.
* See {@link MapsAccountKeys} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
regenerateKeys(resourceGroupName: string, accountName: string, keySpecification: models.MapsKeySpecification, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.MapsAccountKeys>;
regenerateKeys(resourceGroupName: string, accountName: string, keySpecification: models.MapsKeySpecification, callback: ServiceCallback<models.MapsAccountKeys>): void;
regenerateKeys(resourceGroupName: string, accountName: string, keySpecification: models.MapsKeySpecification, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MapsAccountKeys>): void;
/**
* List operations available for the Maps Resource Provider
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<MapsOperations>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listOperationsWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MapsOperations>>;
/**
* List operations available for the Maps Resource Provider
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {MapsOperations} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {MapsOperations} [result] - The deserialized result object if an error did not occur.
* See {@link MapsOperations} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listOperations(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.MapsOperations>;
listOperations(callback: ServiceCallback<models.MapsOperations>): void;
listOperations(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MapsOperations>): void;
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { Queue, Topic } from ".";
import { EventHub, EventHubConsumerGroup, getEventhubNamespace } from ".";
import * as eventgrid from "../eventgrid";
import * as servicebus from "../servicebus";
import * as appservice from "../appservice";
/** @internal */
/** This is only exported to be used internally by the /iot/zMixins.ts file */
export interface EventHubBindingDefinition extends appservice.BindingDefinition {
/**
* The name of the property in the context object to bind the actual event to.
*/
name: string;
/**
* The type of an event hub binding. Must be 'eventHubTrigger'.
*/
type: "eventHubTrigger";
/**
* The direction of the binding. We only support events being inputs to functions.
*/
direction: "in";
/**
* The name of the event hub we are subscribing to.
*/
eventHubName: pulumi.Input<string>;
/**
* An optional property that sets the consumer group used to subscribe to events in the hub.
* If not present, a new Consumer Group resource will be created.
*/
consumerGroup?: pulumi.Input<string>;
/**
* Set to 'many' in order to enable batching. If omitted or set to 'one', single message passed to function.
*/
cardinality?: pulumi.Input<"many" | "one">;
/**
* The name of an app setting that contains the Event Hub connection string to use for this binding.
*/
connection: pulumi.Input<string>;
}
/**
* Data that will be passed along in the context object to the EventHubCallback.
*/
export interface EventHubContext extends appservice.Context<appservice.FunctionDefaultResponse> {
invocationId: string;
executionContext: {
invocationId: string;
functionName: string;
functionDirectory: string;
};
bindings: { eventHub: string };
bindingData: {
partitionContext: {
consumerGroupName: string;
eventHubPath: string;
partitionId: string;
owner: string;
runtimeInformation: {
partitionId: string;
lastSequenceNumber: number;
lastEnqueuedTimeUtc: string;
retrievalTime: string;
};
},
partitionKey: string;
offset: number,
sequenceNumber: number;
enqueuedTimeUtc: string;
properties: Record<string, any>;
systemProperties: Record<string, any>;
sys: {
methodName: string;
utcNow: string;
},
invocationId: string;
};
}
/**
* Signature of the callback that can receive event hub notifications.
*/
export type EventHubCallback = appservice.Callback<EventHubContext, string, appservice.FunctionDefaultResponse>;
export interface GetEventHubFunctionArgs extends appservice.CallbackFunctionArgs<EventHubContext, any, appservice.FunctionDefaultResponse> {
/**
* Optional Consumer Group to subscribe the FunctionApp to. If not present, the default consumer group will be used.
*/
consumerGroup?: EventHubConsumerGroup;
/**
* Set to 'many' in order to enable batching. If omitted or set to 'one', single message passed to function.
*/
cardinality?: pulumi.Input<"many" | "one">;
}
export interface EventHubFunctionArgs extends GetEventHubFunctionArgs {
/**
* Event Hub to subscribe the Function to.
*/
eventHub: EventHub;
}
export interface EventHubSubscriptionArgs extends GetEventHubFunctionArgs, appservice.CallbackFunctionAppArgs<EventHubContext, any, appservice.FunctionDefaultResponse> {
/**
* The name of the resource group in which to create the event subscription. [resourceGroup] takes precedence over [resourceGroupName].
* If none of the two is supplied, the Event Hub's resource group will be used.
*/
resourceGroupName?: pulumi.Input<string>;
}
declare module "./eventHub" {
interface EventHub {
/**
* Subscribes to events logged to this Event Hub to the handler provided, along
* with options to control the behavior of the subscription.
* A dedicated Function App is created behind the scenes with a single Azure Function in it.
* Use [getEventFunction] if you want to compose multiple Functions into the same App manually.
*/
onEvent(
name: string, args: EventHubCallback | EventHubSubscriptionArgs, opts?: pulumi.ComponentResourceOptions): EventHubSubscription;
/**
* Creates a new Function triggered by events in the given Event Hub using the callback provided.
* [getEventFunction] creates no Azure resources automatically: the returned Function should be used as part of
* a [MultiCallbackFunctionApp]. Use [onEvent] if you want to create a Function App with a single Function.
*/
getEventFunction(name: string, args: EventHubCallback | GetEventHubFunctionArgs): EventHubFunction;
}
}
EventHub.prototype.onEvent = function(this: EventHub, name, args, opts) {
const functionArgs = args instanceof Function
? <EventHubSubscriptionArgs>{ callback: args }
: args;
return new EventHubSubscription(name, this, functionArgs, opts);
};
EventHub.prototype.getEventFunction = function(this: EventHub, name, args) {
const functionArgs = args instanceof Function
? { callback: args, eventHub: this }
: { ...args, eventHub: this };
return new EventHubFunction(name, functionArgs);
};
export class EventHubSubscription extends appservice.EventSubscription<EventHubContext, string, appservice.FunctionDefaultResponse> {
readonly eventHub: EventHub;
readonly consumerGroup?: EventHubConsumerGroup;
constructor(
name: string, eventHub: EventHub,
args: EventHubSubscriptionArgs, opts: pulumi.ComponentResourceOptions = {}) {
opts = { parent: eventHub, ...opts };
const resourceGroupName = appservice.getResourceGroupName(args, eventHub.resourceGroupName);
super("azure:eventhub:EventHubSubscription",
name,
new EventHubFunction(name, { ...args, eventHub }),
{ ...args, resourceGroupName },
opts);
this.eventHub = eventHub;
this.consumerGroup = args.consumerGroup;
this.registerOutputs();
}
}
export const DefaultConsumerGroup = "$Default";
/**
* Azure Function triggered by an Event Hub.
*/
export class EventHubFunction extends appservice.Function<EventHubContext, string, appservice.FunctionDefaultResponse> {
constructor(name: string, args: EventHubFunctionArgs) {
// The event hub binding does not store the Event Hubs connection string directly. Instead, the
// connection string is put into the app settings (under whatever key we want). Then, the
// .connection property of the binding contains the *name* of that app setting key.
const bindingConnectionKey = pulumi.interpolate`EventHub${args.eventHub.namespaceName}ConnectionKey`;
const trigger = {
name: "eventHub",
direction: "in",
type: "eventHubTrigger",
eventHubName: args.eventHub.name,
consumerGroup: args.consumerGroup !== undefined ? args.consumerGroup.name : DefaultConsumerGroup,
cardinality: args.cardinality,
connection: bindingConnectionKey,
} as EventHubBindingDefinition;
// Fold the event hub ID into the all so we don't attempt to fetch the namespace until we're sure it has been created.
const namespace = pulumi.all([args.eventHub.namespaceName, args.eventHub.resourceGroupName, args.eventHub.id])
.apply(([namespaceName, resourceGroupName]) =>
getEventhubNamespace({ name: namespaceName, resourceGroupName }));
// Place the mapping from the well known key name to the Event Hubs account connection string in
// the 'app settings' object.
const appSettings = pulumi.all([namespace.defaultPrimaryConnectionString, bindingConnectionKey]).apply(
([connectionString, key]) => ({ [key]: connectionString }));
super(name, trigger, args, appSettings);
}
}
// Legacy exports we keep around for compat. All of these forward to the respective
// functionality in their new module locations.
// Re-export these classes so we get the value *and* type side of things.
import { QueueEventSubscription, ServiceBusFunction, TopicEventSubscription } from "../servicebus"
export { QueueEventSubscription, ServiceBusFunction, TopicEventSubscription };
/**
* @deprecated This type has moved to the [servicebus] module.
*/
export type ServiceBusContext = servicebus.ServiceBusContext;
/**
* @deprecated This type has moved to the [servicebus] module.
*/
export type ServiceBusHostExtensions = servicebus.ServiceBusHostExtensions;
/**
* @deprecated This type has moved to the [servicebus] module.
*/
export type ServiceBusHostSettings = servicebus.ServiceBusHostSettings;
/**
* @deprecated This type has moved to the [servicebus] module.
*/
export type ServiceBusCallback = servicebus.ServiceBusCallback;
/**
* @deprecated This type has moved to the [servicebus] module.
*/
export type ServiceBusFunctionArgs = servicebus.ServiceBusFunctionArgs;
/**
* @deprecated This type has moved to the [servicebus] module.
*/
export type QueueEventSubscriptionArgs = servicebus.QueueEventSubscriptionArgs;
declare module "./queue" {
interface Queue {
/**
* @deprecated The [Queue] type has moved to the [servicebus] module.
*/
onEvent(
name: string, args: ServiceBusCallback | QueueEventSubscriptionArgs, opts?: pulumi.ComponentResourceOptions): QueueEventSubscription;
/**
* @deprecated The [Queue] type has moved to the [servicebus] module.
*/
getEventFunction(name: string, args: ServiceBusCallback | appservice.CallbackFunctionArgs<ServiceBusContext, string, appservice.FunctionDefaultResponse>): ServiceBusFunction;
}
}
Queue.prototype.onEvent = servicebus.Queue.prototype.onEvent;
Queue.prototype.getEventFunction = servicebus.Queue.prototype.getEventFunction;
/**
* @deprecated This type has moved to the [servicebus] module.
*/
export type GetTopicFunctionArgs = servicebus.GetTopicFunctionArgs;
/**
* @deprecated This type has moved to the [servicebus] module.
*/
export type TopicEventSubscriptionArgs = servicebus.TopicAuthorizationRuleArgs;
declare module "./topic" {
interface Topic {
/**
* @deprecated The [Topic] type has moved to the [servicebus] module.
*/
onEvent(
name: string, args: ServiceBusCallback | TopicEventSubscriptionArgs, opts?: pulumi.ComponentResourceOptions): TopicEventSubscription;
/**
* @deprecated The [Topic] type has moved to the [servicebus] module.
*/
getEventFunction(name: string, args: GetTopicFunctionArgs): ServiceBusFunction;
}
}
Topic.prototype.onEvent = servicebus.Topic.prototype.onEvent;
Topic.prototype.getEventFunction = servicebus.Topic.prototype.getEventFunction;
/**
* @deprecated This type has moved to the [eventgrid] module.
*/
export type EventGridEvent<T> = eventgrid.EventGridEvent<T>;
/**
* @deprecated This type has moved to the [eventgrid] module.
*/
export type EventGridContext<T> = eventgrid.EventGridContext<T>;
/**
* @deprecated This type has moved to the [eventgrid] module.
*/
export type EventGridFunctionArgs<T> = eventgrid.EventGridFunctionArgs<T>;
export { EventGridFunction, EventGridCallbackSubscription } from "../eventgrid";
/**
* @deprecated This type has moved to the [eventgrid] module.
*/
export type EventGridCallbackSubscriptionArgs<T> = eventgrid.EventGridCallbackSubscriptionArgs<T>;
/**
* @deprecated This type has moved to the [eventgrid] module.
*/
export type EventGridScope = eventgrid.EventGridScope;
/**
* @deprecated This type has moved to the [eventgrid] module.
*/
export type StorageAccountEventGridCallbackSubscriptionArgs<T> = eventgrid.StorageAccountEventGridCallbackSubscriptionArgs<T>;
/**
* @deprecated This type has moved to the [eventgrid] module.
*/
export type ResourceGroupEventGridCallbackSubscriptionArgs = eventgrid.ResourceGroupEventGridCallbackSubscriptionArgs;
/**
* Contains hooks to subscribe to different kinds of Event Grid events.
*/
export namespace events {
/**
* @deprecated This function has moved to the [eventgrid] module.
*/
export const onGridBlobCreated = eventgrid.events.onGridBlobCreated;
/**
* @deprecated This function has moved to the [eventgrid] module.
*/
export const onGridBlobDeleted = eventgrid.events.onGridBlobDeleted;
/**
* @deprecated This function has moved to the [eventgrid] module.
*/
export const onResourceGroupEvent = eventgrid.events.onResourceGroupEvent;
} | the_stack |
import * as blessed from "blessed";
import { format, callbackify } from "util";
import chalk from "chalk";
import { TreeItem } from "../widget/tree_item";
import { ClientAlarmList, resolveNodeId, DataValue, ResultMask, VariantArrayType } from "node-opcua-client";
import { Tree } from "../widget/widget_tree";
import { Model } from "../model/model";
import { updateAlarmBox } from "./alarm_box";
import { w } from "../utils/utils";
import { threadId } from "worker_threads";
const w2 = "40%";
const scrollbar = {
ch: " ",
track: {
bg: "cyan"
},
style: {
inverse: true
}
};
const style = {
focus: {
border: {
fg: "yellow"
},
bold: false
},
item: {
hover: {
bg: "blue"
}
},
selected: {
bg: "blue",
bold: true
}
};
let old_console_log: any;
export function makeItems(arr: any[], width: number): string[] {
return arr.map((a) => {
return w(a[0], 25, ".") + ": " + w(a[1], width, " ");
});
}
let refreshTimer: NodeJS.Timeout | null = null;
export class View {
private monitoredItemsList: any;
private $headers: string[] = [];
public screen: blessed.Widgets.Screen;
public area1: blessed.Widgets.BoxElement;
public area2: blessed.Widgets.BoxElement;
public menuBar: blessed.Widgets.ListbarElement;
public alarmBox?: blessed.Widgets.ListTableElement;
public attributeList: blessed.Widgets.ListElement;
public logWindow: blessed.Widgets.ListElement;
public tree: Tree;
public writeForm: blessed.Widgets.BoxElement;
public valuesToWriteElement: blessed.Widgets.TextboxElement;
public model: Model;
constructor(model: Model) {
this.model = model;
// Create a screen object.
this.screen = blessed.screen({
smartCSR: true,
autoPadding: false,
fullUnicode: true,
title: "OPCUA CLI-Client"
});
// create the main area
this.area1 = blessed.box({
top: 0,
left: 0,
width: "100%",
height: "90%-10",
});
this.area2 = blessed.box({
top: "90%-9",
left: 0,
width: "100%",
height: "shrink",
});
this.screen.append(this.area1);
this.screen.append(this.area2);
this.attributeList = this.install_attributeList();
this.install_monitoredItemsWindow();
this.install_writeFormWindow();
this.logWindow = this.install_logWindow();
this.menuBar = this.install_mainMenu();
this.tree = this.install_address_space_explorer();
// Render the screen.
this.screen.render();
}
install_writeFormWindow() {
this.writeForm = blessed.box({
parent: this.area1,
tags: true,
top: "50%",
left: w2 + "+1",
width: "60%-1",
height: "50%",
keys: true,
mouse: true,
label: " Write item ",
border: "line",
scrollbar: scrollbar,
noCellBorders: true,
style: {...style},
align: "left",
hidden: true
});
{
const form = blessed.form({
parent: this.writeForm,
width: "100%-2",
height: "100%-2",
top: 1,
left: 1,
keys: true
});
blessed.text({
parent: form,
top: 0,
left: 0,
content: 'VALUES (Comma separated for array):'
});
this.valuesToWriteElement = blessed.textbox({
parent: form,
name: 'valuesToWrite',
top: 1,
left: 0,
height: "100%-2",
inputOnFocus: true,
mouse: false,
vi: false,
keys: false,
content: '',
border: {
type: 'line'
},
focus: {
fg: 'blue'
}
});
const padding = {
top: 0,
right: 2,
bottom: 0,
left: 2
};
const buttonTop = "100%-1";
var submit = blessed.button({
parent: form,
name: 'submit',
content: 'Submit',
top: buttonTop,
left: 0,
shrink: true,
mouse: true,
padding,
style: {
bold: true,
fg: 'white',
bg: 'green',
focus: {
inverse: true
}
}
});
submit.on('press', function () {
form.submit();
});
var closeForm = blessed.button({
parent: form,
name: 'close',
content: 'close',
top: buttonTop,
right: 0,
shrink: true,
mouse: true,
padding,
style: {
bold: true,
fg: 'white',
bg: 'red',
focus: {
inverse: true
}
}
});
closeForm.on('press', () => {
this.writeForm.hide();
this.screen.render();
});
const writeResultMsg = blessed.text({
parent: form,
top: submit.top,
left: "center",
content: ''
});
form.on('submit',async (data: any) => {
const treeItem = this.tree.getSelectedItem();
if (treeItem.node) {
// check if it is an array
const dataValues = await this.model.readNode(treeItem.node);
let valuesToWrite = data.valuesToWrite;
if (dataValues && dataValues.value) {
if (dataValues.value.arrayType == VariantArrayType.Array) {
// since it is an array I will split by comma
valuesToWrite = valuesToWrite.split(",");
}
}
// send data to opc
const res = await this.model.writeNode(treeItem.node, valuesToWrite);
console.log(res);
if (res.valueOf() == 0) {
writeResultMsg.setContent("Write successful");
} else {
writeResultMsg.setContent("Write error");
}
this.screen.render();
}
});
}
this.area1.append(this.writeForm);
}
install_monitoredItemsWindow() {
this.monitoredItemsList = blessed.listtable({
parent: this.area1,
tags: true,
top: "50%",
left: w2 + "+1",
width: "60%-1",
height: "50%",
keys: true,
label: " Monitored Items ",
border: "line",
scrollbar: scrollbar,
noCellBorders: true,
style: {...style},
align: "left"
});
this.area1.append(this.monitoredItemsList);
// binding .....
this.model.on("monitoredItemListUpdated", (monitoredItemsListData: any) => {
if (monitoredItemsListData.length > 0) {
this.monitoredItemsList.setRows(monitoredItemsListData);
} else {
// when using setRows with empty array, the view does not update.
// setting an empty row.
const empty = [
[" "]
];
this.monitoredItemsList.setRows(empty);
}
this.monitoredItemsList.render();
});
this.model.on("monitoredItemChanged", this._onMonitoredItemChanged.bind(this));
}
private _onMonitoredItemChanged(monitoredItemsListData: any, /*node: any, dataValue: DataValue*/) {
this.monitoredItemsList.setRows(monitoredItemsListData);
this.monitoredItemsList.render();
}
private install_logWindow() {
const logWindow = blessed.list({
parent: this.area2,
tags: true,
label: " {bold}{cyan-fg}Info{/cyan-fg}{/bold} ",
top: "top",
left: "left",
width: "100%",
height: "100%-4",
keys: true,
border: "line",
scrollable: true,
scrollbar: {
ch: " ",
track: {
bg: "cyan"
},
style: {
inverse: true
}
},
style: {...style}
});
old_console_log = console.log;
console.log = function (...args: [any]) {
const str = format.apply(null, args);
const lines = str.split("\n");
lines.forEach((str: string) => {
logWindow.addItem(str);
});
logWindow.select((logWindow as any).items.length - 1);
};
this.area2.append(logWindow);
return logWindow;
}
public install_mainMenu(): blessed.Widgets.ListbarElement {
const menuBarOptions: blessed.Widgets.ListbarOptions = {
parent: this.area2,
top: "100%-2",
left: "left",
width: "100%",
height: 2,
keys: true,
style: {...style},
//xx label: " {bold}{cyan-fg}Info{/cyan-fg}{/bold}",
//xx border: "line",
bg: "cyan",
commands: [],
items: [],
autoCommandKeys: true,
};
const menuBar = blessed.listbar(menuBarOptions);
this.area2.append(menuBar);
(menuBar as any).setItems({
"Monitor":
{
//xx prefix: "M",
keys: ["m"],
callback: () => this._onMonitoredSelectedItem()
},
"Write":
{
keys: ["w"],
callback: () => this._onWriteSelectedItem()
},
"Exit": {
keys: ["q"], //["C-c", "escape"],
callback: () => this._onExit()
},
"Tree": {
keys: ["t"],
callback: () => this.tree.focus()
},
"Attributes": {
keys: ["l"],
callback: () => this.attributeList.focus()
},
"Info": {
keys: ["i"],
callback: () => this.logWindow.focus()
},
"Clear": {
keys: ["c"],
callback: () => {
this.logWindow.clearItems();
this.logWindow.screen.render();
}
},
"Unmonitor": {
keys: ["u"],
callback: () => this._onUnmonitoredSelectedItem()
},
"Stat": {
keys: ["s"],
callback: () => this._onDumpStatistics()
},
"Alarm": {
keys: ["a"],
callback: this._onToggleAlarmWindows.bind(this)
},
// "Menu": { keys: ["A-a", "x"], callback: () => this.menuBar.focus() }
});
return menuBar;
}
private install_address_space_explorer(): Tree {
this.tree = new Tree({
parent: this.area1,
tags: true,
fg: "green",
//Xx keys: true,
label: " {bold}{cyan-fg}Address Space{/cyan-fg}{/bold} ",
top: "top",
left: "left",
width: "40%",
height: "100%",
keys: true,
vi: true,
mouse: true,
border: "line",
style: {...style}
});
//allow control the table with the keyboard
this.tree.on("select", (treeItem: any) => {
if (treeItem) {
this.fill_attributesRegion(treeItem.node);
}
});
this.tree.on("keypress", (ch: any, key: any) => {
if (key.name === "up" || key.name === "down") {
if (refreshTimer) {
return;
}
refreshTimer = setTimeout(() => {
const treeItem = this.tree.getSelectedItem();
if (treeItem && treeItem.node) {
this.fill_attributesRegion(treeItem.node);
}
refreshTimer = null;
}, 100);
}
});
this.area1.append(this.tree);
this.populateTree();
this.tree.focus();
return this.tree;
}
private populateTree() {
this.tree.setData({
name: "RootFolder",
nodeId: resolveNodeId("RootFolder"),
children: this.expand_opcua_node.bind(this)
});
};
private expand_opcua_node(node: any, callback: () => void) {
async function f(this: any, node: any) {
try {
const children = await this.model.expand_opcua_node(node);
const results = children.map((c: any) => (
new TreeItem({ ...c, children: this.expand_opcua_node.bind(this) })
));
return results;
} catch (err) {
throw new Error("cannot expand");
}
}
callbackify(f).call(this, node, callback);
}
private async fill_attributesRegion(node: any) {
type ATT = [string, string];
const attr: ATT[] = [];
function append_text(prefix: string, s: string, attr: ATT[]) {
const a = s.split("\n");
if (a.length === 1) {
attr.push([prefix, s]);
} else {
attr.push([prefix, a[0]]);
for (let j = 1; j < a.length; j++) {
attr.push([" | ", a[j]]);
}
}
}
const attributes = await this.model.readNodeAttributes(node);
if (attributes.length === 0) {
return;
}
for (const r of attributes) {
append_text(r.attribute, r.text, attr);
}
const width = (this.attributeList as any).width - 28;
this.attributeList.setItems(makeItems(attr, width) as any);
this.attributeList.screen.render();
}
private install_attributeList(): blessed.Widgets.ListElement {
this.attributeList = blessed.list({
parent: this.area1,
label: " {bold}{cyan-fg}Attribute List{/cyan-fg}{/bold} ",
top: 0,
tags: true,
left: w2 + "+1",
width: "60%-1",
height: "50%",
border: "line",
// noCellBorders: true,
scrollbar: scrollbar,
style: {...style},
align: "left",
keys: true
});
this.area1.append(this.attributeList);
const width = (this.attributeList as any).width - 28;
this.attributeList.setItems(makeItems([], width) as any);
return this.attributeList;
}
private install_alarm_windows() {
if (this.alarmBox) {
this.alarmBox.show();
this.alarmBox.focus();
return;
}
this.alarmBox = blessed.listtable({
parent: this.area1,
tags: true,
fg: "green",
// label: "{bold}{cyan-fg}Alarms - Conditions {/cyan-fg}{/bold} ",
label: "Alarms - Conditions",
top: "top+6",
left: "left+2",
width: "100%-10",
height: "100%-10",
keys: true,
border: "line",
scrollbar: scrollbar,
noCellBorders: false,
style: {...style}
});
this.$headers = ["EventType", "ConditionId",
// "BranchId",
// "EventId",
"Message",
"Severity",
//"Enabled?", "Active?", "Acked?", "Confirmed?", "Retain",
"E!AC",
"Comment",
];
const data = [this.$headers];
this.alarmBox.setData(data);
this.model.installAlarmMonitoring();
this.model.on("alarmChanged", (list: ClientAlarmList) => updateAlarmBox(list, this.alarmBox, this.$headers));
this.alarmBox.focus();
}
private hide_alarm_windows() {
this.alarmBox!.hide();
}
private async _onExit() {
console.log(chalk.red(" disconnecting .... "));
await this.model.disconnect();
console.log(chalk.green(" disconnected .... "));
await new Promise((resolve) => setTimeout(resolve, 1000));
process.exit(0);
}
private async _onToggleAlarmWindows() {
if (this.alarmBox && this.alarmBox.visible) {
this.hide_alarm_windows();
} else {
this.install_alarm_windows();
this.alarmBox!.show();
}
this.screen.render();
}
private _onMonitoredSelectedItem() {
const treeItem = this.tree.getSelectedItem();
if (treeItem.node.monitoredItem) {
console.log(" Already monitoring ", treeItem.node.nodeId.toString());
return;
}
this.model.monitor_item(treeItem);
}
private async _onWriteSelectedItem() {
this.writeForm.show();
const treeItem = this.tree.getSelectedItem();
if (treeItem.node) {
const treeItemToUse = this.model.request_write_item(treeItem);
if (treeItemToUse) {
const value = await this.model.readNodeValue(treeItem.node);
if (value) {
this.valuesToWriteElement.setValue(value);
} else {
this.valuesToWriteElement.setValue("");
}
this.screen.render();
this.valuesToWriteElement.focus();
this.screen.render();
}
return;
}
}
private _onUnmonitoredSelectedItem() {
const treeItem = this.tree.getSelectedItem();
if (!treeItem.node.monitoredItem) {
console.log(treeItem.node.nodeId.toString(), " was not being monitored");
return;
}
this.model.unmonitor_item(treeItem);
}
private _onDumpStatistics() {
console.log("----------------------------------------------------------------------------");
console.log(chalk.green(" transaction count : ", chalk.yellow(this.model.data.transactionCount)));
console.log(chalk.green(" sent bytes : ", chalk.yellow(this.model.data.sentBytes)));
console.log(chalk.green(" received bytes : ", chalk.yellow(this.model.data.receivedBytes)));
console.log(chalk.green(" token renewal count : ", chalk.yellow(this.model.data.tokenRenewalCount)));
console.log(chalk.green(" reconnection count : ", chalk.yellow(this.model.data.reconnectionCount)));
}
}; | the_stack |
import {Store, Event, is, launch, createEvent, sample, merge} from 'effector'
import type {StateRef} from '../../effector/index.h'
import type {
DOMElement,
ElementDraft,
NSType,
PropertyMap,
StoreOrData,
DOMProperty,
StylePropertyMap,
Leaf,
LeafDataElement,
Template,
HandlerRecord,
PropertyOperationDef,
PropertyOperationKind,
} from '../index.h'
import type {ElementBlock, TextBlock} from '../relation.h'
import {pushOpToQueue, forceSetOpValue, createOp} from '../plan'
import {
applyStyle,
applyStyleVar,
applyDataAttr,
applyAttr,
applyText,
applyStaticOps,
} from '../bindings'
import {createTemplate, currentTemplate} from '../template'
import {
findParentDOMElement,
findPreviousVisibleSibling,
findPreviousVisibleSiblingBlock,
} from '../search'
import {
appendChild,
onMount as onMountSync,
mountChildTemplates,
setInParentIndex,
} from '../mountChild'
import {assertClosure} from '../assert'
import {mutualSample} from '../mutualSample'
import {forIn} from '../forIn'
import {spec} from './spec'
function createPropsOp<T, S>(
draft: ElementDraft,
{
initCtx,
runOp,
hooks: {onMount, onState},
}: {
initCtx(value: T, leaf: Leaf): S
runOp(value: T, ctx: S): void
hooks: {
onMount: Event<{leaf: Leaf; value: T}>
onState: Event<{leaf: Leaf; value: T}>
}
},
) {
const opID = draft.opsAmount++
onMount.watch(({value, leaf}) => {
const op = createOp({
value,
priority: 'props',
runOp(value) {
runOp(value, ctx)
},
group: leaf.root.leafOps[leaf.fullID].group,
})
leaf.root.leafOps[leaf.fullID].group.ops[opID] = op
const ctx = initCtx(value, leaf)
})
onState.watch(({value, leaf}) => {
pushOpToQueue(value, leaf.root.leafOps[leaf.fullID].group.ops[opID])
})
}
const syncOperations: Array<{
field: string
type: PropertyOperationKind
}> = [
{type: 'attr', field: 'value'},
{type: 'attr', field: 'checked'},
{type: 'attr', field: 'min'},
{type: 'attr', field: 'max'},
]
const propertyOperationBinding: Record<
PropertyOperationKind,
(
element: DOMElement,
field: string,
value: string | number | boolean | null,
) => void
> = {
attr: applyAttr,
data: applyDataAttr,
style: applyStyle,
styleVar: applyStyleVar,
}
const readElement = (leaf: Leaf) => (leaf.data as LeafDataElement).block.value
/** operation family for things represented as <el "thing"="value" /> */
function propertyMapToOpDef(
draft: ElementDraft,
type: PropertyOperationKind,
ops: {
attr: PropertyMap
data: PropertyMap
style: StylePropertyMap
styleVar: PropertyMap
},
) {
draft[type].forEach(record => {
forIn(record as unknown as PropertyMap, (value, key) => {
switch (type) {
case 'data':
case 'styleVar':
ops[type][key] = value
break
case 'attr':
ops.attr[key === 'xlink:href' ? 'href' : key] = value
break
case 'style':
if (key.startsWith('--')) {
ops.styleVar[key.slice(2)] = value
} else {
//@ts-expect-error inconsistency in StylePropertyMap key type
ops.style[key] = value
}
break
}
})
})
}
function installTextNode(leaf: Leaf, value: string, childIndex: number) {
const parentBlock = leaf.data.block as ElementBlock
const textBlock: TextBlock = {
type: 'text',
parent: parentBlock,
visible: false,
index: childIndex,
//@ts-expect-error
value: null,
}
parentBlock.child[childIndex] = textBlock
if (leaf.hydration) {
const siblingBlock = findPreviousVisibleSiblingBlock(textBlock)
if (siblingBlock) {
switch (siblingBlock.type) {
case 'text': {
textBlock.value = leaf.root.env.document.createTextNode(value)
siblingBlock.value.after(textBlock.value)
break
}
case 'element': {
textBlock.value = siblingBlock.value.nextSibling! as Text
applyText(textBlock.value, value)
break
}
}
} else {
const parentElement = findParentDOMElement(textBlock)
textBlock.value = parentElement!.firstChild! as Text
applyText(textBlock.value, value)
}
textBlock.visible = true
} else {
textBlock.value = leaf.root.env.document.createTextNode(value)
appendChild(textBlock)
}
return textBlock
}
function processStoreRef(store: Store<any>) {
//@ts-expect-error
const ref: StateRef = store.stateRef
const templ: Template = currentTemplate!
if (!templ.plain.includes(ref) && !templ.closure.includes(ref)) {
templ.closure.push(ref)
}
}
export function h(tag: string): void
export function h(tag: string, cb: () => void): void
export function h(
tag: string,
spec: {
fn?: () => void
attr?: PropertyMap
data?: PropertyMap
text?: StoreOrData<DOMProperty> | Array<StoreOrData<DOMProperty>>
visible?: Store<boolean>
style?: StylePropertyMap
styleVar?: PropertyMap
handler?:
| {
config?: {
passive?: boolean
capture?: boolean
prevent?: boolean
stop?: boolean
}
on: Partial<
{[K in keyof HTMLElementEventMap]: Event<HTMLElementEventMap[K]>}
>
}
| Partial<
{[K in keyof HTMLElementEventMap]: Event<HTMLElementEventMap[K]>}
>
},
): void
export function h(tag: string, opts?: any) {
let hasCb = false
let hasOpts = false
let cb: () => void
if (typeof opts === 'function') {
hasCb = true
cb = opts
} else {
if (opts) {
hasOpts = true
if (opts.fn) {
hasCb = true
cb = opts.fn
}
if (opts.ɔ) {
if (typeof opts.ɔ === 'function') {
hasCb = true
cb = opts.ɔ
} else if (typeof opts.ɔ.fn === 'function') {
hasCb = true
cb = opts.ɔ.fn
}
}
}
}
assertClosure(currentTemplate, 'h')
const env = currentTemplate.env
const parentNS = currentTemplate.namespace
let ns: NSType = parentNS
let type = 'html'
ns = type = parentNS === 'svg' ? 'svg' : 'html'
if (tag === 'svg') {
type = 'svg'
ns = 'svg'
}
let node: DOMElement
if (!currentTemplate.isBlock) {
node =
type === 'svg'
? env.document.createElementNS('http://www.w3.org/2000/svg', tag)
: env.document.createElement(tag)
}
const stencil = node!
const draft: ElementDraft = {
type: 'element',
tag,
attr: [],
data: [],
text: [],
style: [],
styleVar: [],
handler: [],
stencil,
seq: [],
staticSeq: [],
childTemplates: [],
childCount: 0,
inParentIndex: -1,
opsAmount: 1,
node: [],
}
if (parentNS === 'foreignObject') {
draft.attr.push({
xmlns: 'http://www.w3.org/1999/xhtml',
})
ns = 'html'
} else if (tag === 'svg') {
draft.attr.push({
xmlns: 'http://www.w3.org/2000/svg',
})
ns = 'svg'
} else if (tag === 'foreignObject') {
ns = 'foreignObject'
}
const elementTemplate = createTemplate({
name: 'element',
draft,
isSvgRoot: tag === 'svg',
namespace: ns,
fn(_, {mount}) {
//@ts-expect-error
const domElementCreated = createEvent<Leaf>({named: 'domElementCreated'})
if (hasCb) {
cb()
}
if (hasOpts) {
spec(opts)
}
if (is.unit(draft.visible)) {
draft.seq.push({type: 'visible', value: draft.visible})
processStoreRef(draft.visible)
}
const ops: {
attr: PropertyMap
data: PropertyMap
style: StylePropertyMap
styleVar: PropertyMap
} = {
attr: {},
data: {},
style: {},
styleVar: {},
}
propertyMapToOpDef(draft, 'attr', ops)
propertyMapToOpDef(draft, 'data', ops)
propertyMapToOpDef(draft, 'style', ops)
propertyMapToOpDef(draft, 'styleVar', ops)
forIn(ops, (opsMap, type) => {
forIn(opsMap as unknown as PropertyMap, (value, field) => {
if (is.unit(value)) {
draft.seq.push({type, field, value})
processStoreRef(value)
} else {
draft.staticSeq.push({type, field, value})
}
})
})
draft.text.forEach(item => {
if (item.value === null) return
if (is.unit(item.value)) {
draft.seq.push({
type: 'dynamicText',
value: item.value,
childIndex: item.index,
})
processStoreRef(item.value)
} else {
draft.seq.push({
type: 'staticText',
value: String(item.value),
childIndex: item.index,
})
}
})
draft.handler.forEach(item => {
forIn(item.map, (handler, key) => {
draft.seq.push({
type: 'handler',
for: key,
//@ts-expect-error
handler,
options: item.options,
domConfig: item.domConfig,
})
})
})
if (stencil) applyStaticOps(stencil, draft.staticSeq)
draft.seq.forEach(item => {
switch (item.type) {
case 'visible': {
const {onMount, onState} = mutualSample({
mount,
state: item.value,
onMount: (value, leaf) => ({
leaf,
value,
hydration: leaf.hydration,
}),
onState: (leaf, value) => ({leaf, value, hydration: false}),
})
onMount.watch(({leaf, value, hydration}) => {
const leafData = leaf.data as LeafDataElement
const visibleOp = leafData.ops.visible
const parentBlock = leafData.block
if (hydration) {
forceSetOpValue(value, visibleOp)
if (value) {
const visibleSibling = findPreviousVisibleSibling(parentBlock)
let foundElement: DOMElement
if (visibleSibling) {
foundElement = visibleSibling.nextSibling! as DOMElement
} else {
foundElement = findParentDOMElement(parentBlock)!
.firstChild! as DOMElement
}
if (foundElement.nodeName === '#text') {
const emptyText = foundElement
foundElement = foundElement.nextSibling! as DOMElement
emptyText.remove()
}
parentBlock.value = foundElement
parentBlock.visible = true
}
}
const svgRoot = elementTemplate.isSvgRoot
? (parentBlock.value as SVGSVGElement)
: null
mountChildTemplates(draft, {
parentBlockFragment: parentBlock,
leaf,
node: parentBlock.value,
svgRoot,
})
if (value) {
if (leafData.needToCallNode) {
leafData.needToCallNode = false
launch({
target: onMountSync,
params: {
element: leafData.block.value,
fns: draft.node,
},
page: leaf,
defer: true,
//@ts-expect-error
scope: leaf.root.scope,
})
}
}
launch({
target: domElementCreated,
params: leaf,
defer: true,
page: leaf,
//@ts-expect-error
scope: leaf.root.scope,
})
})
merge([onState, onMount]).watch(({leaf, value, hydration}) => {
const leafData = leaf.data as LeafDataElement
const visibleOp = leafData.ops.visible
if (!hydration) {
pushOpToQueue(value, visibleOp)
}
})
break
}
case 'attr':
case 'data':
case 'style':
case 'styleVar': {
const fn = propertyOperationBinding[item.type]
const immediate = syncOperations.some(
({type, field}) => item.type === type && item.field === field,
)
const hooks = mutualSample({
mount: domElementCreated,
state: item.value,
onMount: (value, leaf) => ({leaf, value}),
onState: (leaf, value) => ({leaf, value}),
})
if (immediate) {
merge([hooks.onState, hooks.onMount]).watch(({leaf, value}) => {
fn(readElement(leaf), item.field, value)
})
} else {
createPropsOp(draft, {
initCtx(value: DOMProperty, leaf) {
const element = readElement(leaf)
fn(element, item.field, value)
return element
},
runOp(value, element: DOMElement) {
fn(element, item.field, value)
},
hooks,
})
}
break
}
case 'dynamicText':
createPropsOp(draft, {
initCtx(value: string, leaf) {
return installTextNode(leaf, value, item.childIndex)
},
runOp(value, ctx: TextBlock) {
applyText(ctx.value, value)
},
hooks: mutualSample({
mount: domElementCreated,
state: item.value,
onMount: (value, leaf) => ({leaf, value: String(value)}),
onState: (leaf, value) => ({leaf, value: String(value)}),
}),
})
break
case 'staticText':
domElementCreated.watch(leaf => {
installTextNode(leaf, item.value, item.childIndex)
})
break
case 'handler': {
const handlerTemplate: Template | null =
//@ts-expect-error
item.handler.graphite.meta.nativeTemplate || null
domElementCreated.watch(leaf => {
let page: Leaf | null = null
if (handlerTemplate) {
let handlerPageFound = false
let currentPage: Leaf | null = leaf
while (!handlerPageFound && currentPage) {
if (currentPage.template === handlerTemplate) {
handlerPageFound = true
page = currentPage
} else {
currentPage = currentPage.parent
}
}
} else {
page = null //leaf
}
readElement(leaf).addEventListener(
item.for,
value => {
if (item.options.prevent) value.preventDefault()
if (item.options.stop) value.stopPropagation()
launch({
target: item.handler,
params: value,
page,
//@ts-expect-error
scope: leaf.root.scope,
})
},
item.domConfig,
)
})
break
}
}
})
mount.watch(leaf => {
const leafData = leaf.data as LeafDataElement
if (!draft.visible) {
const visibleOp = leafData.ops.visible
const parentBlock = leafData.block
if (leaf.hydration) {
forceSetOpValue(true, visibleOp)
const visibleSibling = findPreviousVisibleSibling(parentBlock)
let foundElement: DOMElement
if (visibleSibling) {
foundElement = visibleSibling.nextSibling! as DOMElement
} else {
foundElement = findParentDOMElement(parentBlock)!
.firstChild! as DOMElement
}
if (foundElement.nodeName === '#text') {
const emptyText = foundElement
foundElement = foundElement.nextSibling! as DOMElement
emptyText.remove()
}
parentBlock.value = foundElement
parentBlock.visible = true
}
const svgRoot = elementTemplate.isSvgRoot
? (parentBlock.value as SVGSVGElement)
: null
mountChildTemplates(draft, {
parentBlockFragment: parentBlock,
leaf,
node: parentBlock.value,
svgRoot,
})
launch({
target: domElementCreated,
params: leaf,
defer: true,
page: leaf,
//@ts-expect-error
scope: leaf.root.scope,
})
if (leaf.hydration) {
if (leafData.needToCallNode) {
leafData.needToCallNode = false
launch({
target: onMountSync,
params: {
element: leafData.block.value,
fns: draft.node,
},
page: leaf,
defer: true,
//@ts-expect-error
scope: leaf.root.scope,
})
}
} else {
pushOpToQueue(true, visibleOp)
}
}
})
},
env,
})
setInParentIndex(elementTemplate)
} | the_stack |
/////*1*/ class a {
/////*2*/ constructor ( n : number ) ;
/////*3*/ constructor ( s : string ) ;
/////*4*/ constructor ( ns : any ) {
////
/////*5*/ }
////
/////*6*/ public pgF ( ) { }
////
/////*7*/ public pv ;
/////*8*/ public get d ( ) {
/////*9*/ return 30 ;
/////*10*/ }
/////*11*/ public set d ( number ) {
/////*12*/ }
////
/////*13*/ public static get p2 ( ) {
/////*14*/ return { x : 30 , y : 40 } ;
/////*15*/ }
////
/////*16*/ private static d2 ( ) {
/////*17*/ }
/////*18*/ private static get p3 ( ) {
/////*19*/ return "string" ;
/////*20*/ }
/////*21*/ private pv3 ;
////
/////*22*/ private foo ( n : number ) : string ;
/////*23*/ private foo ( s : string ) : string ;
/////*24*/ private foo ( ns : any ) {
/////*25*/ return ns.toString ( ) ;
/////*26*/ }
/////*27*/}
////
/////*28*/ class b extends a {
/////*29*/}
////
/////*30*/ class m1b {
////
/////*31*/}
////
/////*32*/ interface m1ib {
////
/////*33*/ }
/////*34*/ class c extends m1b {
/////*35*/}
////
/////*36*/ class ib2 implements m1ib {
/////*37*/}
////
/////*38*/ declare class aAmbient {
/////*39*/ constructor ( n : number ) ;
/////*40*/ constructor ( s : string ) ;
/////*41*/ public pgF ( ) : void ;
/////*42*/ public pv ;
/////*43*/ public d : number ;
/////*44*/ static p2 : { x : number ; y : number ; } ;
/////*45*/ static d2 ( ) ;
/////*46*/ static p3 ;
/////*47*/ private pv3 ;
/////*48*/ private foo ( s ) ;
/////*49*/}
////
/////*50*/ class d {
/////*51*/ private foo ( n : number ) : string ;
/////*52*/ private foo ( s : string ) : string ;
/////*53*/ private foo ( ns : any ) {
/////*54*/ return ns.toString ( ) ;
/////*55*/ }
/////*56*/}
////
/////*57*/ class e {
/////*58*/ private foo ( s : string ) : string ;
/////*59*/ private foo ( n : number ) : string ;
/////*60*/ private foo ( ns : any ) {
/////*61*/ return ns.toString ( ) ;
/////*62*/ }
/////*63*/ protected bar ( ) { }
/////*64*/ protected static bar2 ( ) { }
/////*65*/}
format.document();
goTo.marker("1");
verify.currentLineContentIs("class a {");
goTo.marker("2");
verify.currentLineContentIs(" constructor(n: number);");
goTo.marker("3");
verify.currentLineContentIs(" constructor(s: string);");
goTo.marker("4");
verify.currentLineContentIs(" constructor(ns: any) {");
goTo.marker("5");
verify.currentLineContentIs(" }");
goTo.marker("6");
verify.currentLineContentIs(" public pgF() { }");
goTo.marker("7");
verify.currentLineContentIs(" public pv;");
goTo.marker("8");
verify.currentLineContentIs(" public get d() {");
goTo.marker("9");
verify.currentLineContentIs(" return 30;");
goTo.marker("10");
verify.currentLineContentIs(" }");
goTo.marker("11");
verify.currentLineContentIs(" public set d(number) {");
goTo.marker("12");
verify.currentLineContentIs(" }");
goTo.marker("13");
verify.currentLineContentIs(" public static get p2() {");
goTo.marker("14");
verify.currentLineContentIs(" return { x: 30, y: 40 };");
goTo.marker("15");
verify.currentLineContentIs(" }");
goTo.marker("16");
verify.currentLineContentIs(" private static d2() {");
goTo.marker("17");
verify.currentLineContentIs(" }");
goTo.marker("18");
verify.currentLineContentIs(" private static get p3() {");
goTo.marker("19");
verify.currentLineContentIs(' return "string";');
goTo.marker("20");
verify.currentLineContentIs(" }");
goTo.marker("21");
verify.currentLineContentIs(" private pv3;");
goTo.marker("22");
verify.currentLineContentIs(" private foo(n: number): string;");
goTo.marker("23");
verify.currentLineContentIs(" private foo(s: string): string;");
goTo.marker("24");
verify.currentLineContentIs(" private foo(ns: any) {");
goTo.marker("25");
verify.currentLineContentIs(" return ns.toString();");
goTo.marker("26");
verify.currentLineContentIs(" }");
goTo.marker("27");
verify.currentLineContentIs("}");
goTo.marker("28");
verify.currentLineContentIs("class b extends a {");
goTo.marker("29");
verify.currentLineContentIs("}");
goTo.marker("30");
verify.currentLineContentIs("class m1b {");
goTo.marker("31");
verify.currentLineContentIs("}");
goTo.marker("32");
verify.currentLineContentIs("interface m1ib {");
goTo.marker("33");
verify.currentLineContentIs("}");
goTo.marker("34");
verify.currentLineContentIs("class c extends m1b {");
goTo.marker("35");
verify.currentLineContentIs("}");
goTo.marker("36");
verify.currentLineContentIs("class ib2 implements m1ib {");
goTo.marker("37");
verify.currentLineContentIs("}");
goTo.marker("38");
verify.currentLineContentIs("declare class aAmbient {");
goTo.marker("39");
verify.currentLineContentIs(" constructor(n: number);");
goTo.marker("40");
verify.currentLineContentIs(" constructor(s: string);");
goTo.marker("41");
verify.currentLineContentIs(" public pgF(): void;");
goTo.marker("42");
verify.currentLineContentIs(" public pv;");
goTo.marker("43");
verify.currentLineContentIs(" public d: number;");
goTo.marker("44");
verify.currentLineContentIs(" static p2: { x: number; y: number; };");
goTo.marker("45");
verify.currentLineContentIs(" static d2();");
goTo.marker("46");
verify.currentLineContentIs(" static p3;");
goTo.marker("47");
verify.currentLineContentIs(" private pv3;");
goTo.marker("48");
verify.currentLineContentIs(" private foo(s);");
goTo.marker("49");
verify.currentLineContentIs("}");
goTo.marker("50");
verify.currentLineContentIs("class d {");
goTo.marker("51");
verify.currentLineContentIs(" private foo(n: number): string;");
goTo.marker("52");
verify.currentLineContentIs(" private foo(s: string): string;");
goTo.marker("53");
verify.currentLineContentIs(" private foo(ns: any) {");
goTo.marker("54");
verify.currentLineContentIs(" return ns.toString();");
goTo.marker("55");
verify.currentLineContentIs(" }");
goTo.marker("56");
verify.currentLineContentIs("}");
goTo.marker("57");
verify.currentLineContentIs("class e {");
goTo.marker("58");
verify.currentLineContentIs(" private foo(s: string): string;");
goTo.marker("59");
verify.currentLineContentIs(" private foo(n: number): string;");
goTo.marker("60");
verify.currentLineContentIs(" private foo(ns: any) {");
goTo.marker("61");
verify.currentLineContentIs(" return ns.toString();");
goTo.marker("62");
verify.currentLineContentIs(" }");
goTo.marker("63");
verify.currentLineContentIs(" protected bar() { }");
goTo.marker("64");
verify.currentLineContentIs(" protected static bar2() { }");
goTo.marker("65");
verify.currentLineContentIs("}"); | the_stack |
import * as types from "../constants/ActionTypes";
import { Action } from "../constants/ActionTypes";
import { ActionCreator } from "redux";
import IState, { IWorkspace, IWorkspaceInfo, IWorkspaceFile, IWorkspaceBuffer } from "../IState";
import { decodeWorkspace } from "../workspaces";
import { error } from "./errorActionCreators";
import { setCodeSource } from "./configActionCreators";
import { loadSource } from "./sourceCodeActionCreators";
import * as uiActions from "./uiActionCreators";
import { IStore } from "../IStore";
import { ThunkDispatch, ThunkAction } from "redux-thunk";
import { isNullOrUndefinedOrWhitespace } from "../utilities/stringUtilities";
import { SupportedLanguages, toSupportedLanguage } from "../constants/supportedLanguages";
export function setWorkspaceInfo(workspaceInfo: IWorkspaceInfo): Action {
return {
type: types.SET_WORKSPACE_INFO,
workspaceInfo
};
}
export function setWorkspace(workspace: IWorkspace): Action {
return {
type: types.SET_WORKSPACE,
workspace
};
}
export const setWorkspaceAndActiveBuffer: ActionCreator<ThunkAction<Promise<Action>, IState, void, Action>> =
(workspace: IWorkspace, activeBufferId: string) =>
async (dispatch: ThunkDispatch<IState, void, Action>): Promise<Action> => {
dispatch(setWorkspace(workspace));
dispatch(setWorkspaceLanguage(toSupportedLanguage(workspace.language)));
return dispatch(setActiveBufferAndLoadCode(activeBufferId));
};
export function setWorkspaceType(workspaceType: string): Action {
return {
type: types.SET_WORKSPACE_TYPE as typeof types.SET_WORKSPACE_TYPE,
workspaceType: workspaceType
};
}
export function setWorkspaceLanguage(workspaceLanguage: SupportedLanguages): Action {
return {
type: types.SET_WORKSPACE_LANGUAGE as typeof types.SET_WORKSPACE_LANGUAGE,
workspaceLanguage: workspaceLanguage
};
}
export function updateWorkspaceBuffer(content: string, bufferId: string): Action {
return {
type: types.UPDATE_WORKSPACE_BUFFER,
content,
bufferId
};
}
export function setActiveBuffer(bufferId: string): Action {
return {
type: types.SET_ACTIVE_BUFFER,
bufferId
};
}
export function setInstrumentation(enabled: boolean): Action {
return {
type: types.SET_INSTRUMENTATION,
enabled: enabled
};
}
export const setActiveBufferAndLoadCode: ActionCreator<ThunkAction<Promise<Action>, IState, void, Action>> =
(bufferId: string) =>
async (dispatch: ThunkDispatch<IState, void, Action>): Promise<Action> => {
dispatch(setActiveBuffer(bufferId));
dispatch(setCodeSource("workspace"));
return dispatch(loadSource());
};
export const updateCurrentWorkspaceBuffer: ActionCreator<ThunkAction<Action, IState, void, Action>> =
(content: string) =>
(dispatch: ThunkDispatch<IState, void, Action>, getState: () => IState): Action => {
const state = getState();
const bufferId = state.monaco.bufferId;
return dispatch(updateWorkspaceBuffer(content, bufferId));
};
export const LoadWorkspaceFromGist: ActionCreator<ThunkAction<Promise<Action>, IState, void, Action>> =
(gistId: string, bufferId: string = null, workspaceType: string, canShowGitHubPanel: boolean = false) =>
async (dispatch: ThunkDispatch<IState, void, Action>, getState: () => IState): Promise<Action> => {
const state = getState();
const client = state.config.client;
let activeBufferId = bufferId;
let extractBuffers = false;
if (activeBufferId) {
extractBuffers = activeBufferId.indexOf("@") >= 0;
}
const workspaceInfo = await client.getWorkspaceFromGist(gistId, workspaceType, extractBuffers);
if (!activeBufferId) {
activeBufferId = workspaceInfo.workspace.buffers[0].id;
}
dispatch(setWorkspaceInfo(workspaceInfo));
if (canShowGitHubPanel) {
dispatch(uiActions.canShowGitHubPanel(true));
}
else {
dispatch(uiActions.canShowGitHubPanel(false));
}
return dispatch(setWorkspaceAndActiveBuffer(workspaceInfo.workspace, activeBufferId));
};
export function configureWorkspace(configuration: { store: IStore, workspaceParameter?: string, workspaceTypeParameter?: string, language?: SupportedLanguages, fromParameter?: string, bufferIdParameter?: string, fromGistParameter?: string, canShowGitHubPanelQueryParameter?: string }) {
let bufferId = "Program.cs";
if (configuration.bufferIdParameter) {
bufferId = decodeURIComponent(configuration.bufferIdParameter);
}
let LoadFromWorkspace = false;
let workspace: IWorkspace = {
workspaceType: "script",
files: [],
buffers: [{ id: bufferId, content: "", position: 0 }],
usings: []
};
if (configuration.workspaceParameter) {
if (configuration.fromParameter) {
configuration.store.dispatch(error("parameter loading", "cannot define `workspace` and `from` simultaneously"));
}
if (configuration.workspaceTypeParameter) {
configuration.store.dispatch(error("parameter loading", "cannot define `workspace` and `workspaceTypeParameter` simultaneously"));
}
LoadFromWorkspace = true;
workspace = decodeWorkspace(configuration.workspaceParameter);
} else {
if (configuration.workspaceTypeParameter) {
workspace.workspaceType = decodeURIComponent(configuration.workspaceTypeParameter);
}
}
if (!isNullOrUndefinedOrWhitespace(configuration.language)) {
workspace.language = configuration.language;
} else if (isNullOrUndefinedOrWhitespace(workspace.language)) {
workspace.language = "csharp";
}
configuration.store.dispatch(setWorkspaceType(workspace.workspaceType));
configuration.store.dispatch(setWorkspaceLanguage(toSupportedLanguage(workspace.language)));
configuration.store.dispatch(setWorkspace(workspace));
configuration.store.dispatch(setActiveBuffer(bufferId));
if (LoadFromWorkspace) {
configuration.store.dispatch(setCodeSource("workspace"));
}
else if (configuration.fromGistParameter) {
if (configuration.canShowGitHubPanelQueryParameter) {
let canShowGitHubPanel = decodeURIComponent(configuration.canShowGitHubPanelQueryParameter) === "true";
if (canShowGitHubPanel) {
configuration.store.dispatch(uiActions.canShowGitHubPanel(true));
}
else {
configuration.store.dispatch(uiActions.canShowGitHubPanel(false));
}
}
const fromGist = `gist::${decodeURIComponent(configuration.fromGistParameter)}`;
configuration.store.dispatch(setCodeSource(fromGist));
}
else if (configuration.fromParameter) {
const from = decodeURIComponent(configuration.fromParameter);
configuration.store.dispatch(setCodeSource(from));
}
}
export type Scaffolding =
"None" | "Class" | "Method";
function getContent(type: Scaffolding, additionalUsings: string[]): string {
let usings = "";
additionalUsings.forEach(using => {
usings += `using ${using};
`});
switch (type) {
case "Class":
return `${usings}class C
{
#region scaffold
#endregion
}`;
case "Method":
return `${usings}class C
{
public static void Main()
{
#region scaffold
#endregion
}
}`;
case "None":
return "";
default:
throw "Invalid scaffolding type";
}
}
function getActiveBufferId(type: Scaffolding, fileName: string): string {
switch (type) {
case "Class":
case "Method":
return `${fileName}@scaffold`;
case "None":
return fileName;
default:
throw "Invalid scaffolding type";
}
}
export const applyScaffolding: ActionCreator<ThunkAction<Promise<Action>, IState, void, Action>> =
(type: Scaffolding, fileName: string, additionalUsings: string[] = []) =>
(dispatch: ThunkDispatch<IState, void, Action>, getState: () => IState): Promise<Action> => {
if (type === null || !fileName) {
dispatch(error("general", "invalid scaffolding parameter"))
}
let workspaceType = getState().workspace.workspace.workspaceType;
let file: IWorkspaceFile = {
name: fileName,
text: getContent(type, additionalUsings)
};
let activeBufferId = getActiveBufferId(type, fileName);
let buffer: IWorkspaceBuffer = {
content: "",
id: activeBufferId,
position: 0
};
let workspace: IWorkspace = {
activeBufferId: activeBufferId,
buffers: [buffer],
files: [file],
workspaceType,
};
dispatch(setWorkspace(workspace));
dispatch(setActiveBuffer(activeBufferId));
dispatch(setCodeSource("workspace"));
return dispatch(loadSource());
};
export function getProjectTemplateFromStore(store: IStore): string {
let template = "unspecified";
if (store) {
let state = store.getState();
template = getProjectTemplateFromState(state);
}
return template;
}
export function getProjectTemplateFromState(state: IState): string {
let template = "unspecified";
if (state && state.workspace && state.workspace.workspace && state.workspace.workspace.workspaceType) {
template = state.workspace.workspace.workspaceType;
}
return template;
} | the_stack |
"use strict";
import i18next from "i18next";
import { observable } from "mobx";
import RequestErrorEvent from "terriajs-cesium/Source/Core/RequestErrorEvent";
import { Notification } from "../ReactViewModels/NotificationState";
import { terriaErrorNotification } from "../ReactViews/Notification/terriaErrorNotification";
import filterOutUndefined from "./filterOutUndefined";
import flatten from "./flatten";
import isDefined from "./isDefined";
/** This is used for I18n translation strings so we can "resolve" them when the Error is displayed to the user.
* This means we can create TerriaErrors before i18next has been initialised.
*/
export interface I18nTranslateString {
key: string;
parameters?: Record<string, string>;
}
function resolveI18n(i: I18nTranslateString | string) {
return typeof i === "string" ? i : i18next.t(i.key, i.parameters);
}
/** `TerriaErrorSeverity` can be `Error` or `Warning`.
* Errors with severity `Error` are presented to the user. `Warning` will just be printed to console.
*/
export enum TerriaErrorSeverity {
/** Errors which should be shown to the user. This is the default value for all errors.
*/
Error,
/** Errors which can be ignored by the user. These will be printed to console s
* For example:
* - Failing to load models (from share links or stories) if they are **NOT** in the workbench
*/
Warning
}
/** Object used to create a TerriaError */
export interface TerriaErrorOptions {
/** A detailed message describing the error. This message may be HTML and it should be sanitized before display to the user. */
message: string | I18nTranslateString;
/** Importance of the error message, this is used to determine which message is displayed to the user if multiple error messages exist.
* Higher importance messages are shown to user over lower importance. Default value is 0
* If two errors of equal importance are found - the first error found through depth-first search will be shown
*/
importance?: number;
/** A short title describing the error. */
title?: string | I18nTranslateString;
/** The object that raised the error. */
sender?: unknown;
/** True if error message should be shown to user *regardless* of error severity. If this is undefined, then error severity will be used to determine if shouldRaiseToUser (severity `Error` are presented to the user. `Warning` will just be printed to console) */
shouldRaiseToUser?: boolean;
/** True if the user has seen this error; otherwise, false. */
raisedToUser?: boolean;
/** Error which this error was created from. This means TerriaErrors can be represented as a tree of errors - and therefore a stacktrace can be generated */
originalError?: TerriaError | Error | (TerriaError | Error)[];
/** TerriaErrorSeverity - will default to `Error`
* A function can be used here, which will be resolved when the error is raised to user.
*/
severity?: TerriaErrorSeverity | (() => TerriaErrorSeverity);
/** If true, show error details in terriaErrorNotification by default. If false, error details will be collapsed by default */
showDetails?: boolean;
}
/** Object used to clone an existing TerriaError (see `TerriaError.createParentError()`).
*
* If this is a `string` it will be used to set `TerriaError.message`
* If this is `TerriaErrorSeverity` it will be used to set `TerriaError.severity`
*/
export type TerriaErrorOverrides =
| Partial<TerriaErrorOptions>
| string
| TerriaErrorSeverity;
/** Turn TerriaErrorOverrides to TerriaErrorOptions so it can be passed to TerriaError constructor */
export function parseOverrides(
overrides: TerriaErrorOverrides | undefined
): Partial<TerriaErrorOptions> {
// If overrides is a string - we treat is as the `message` parameter
if (typeof overrides === "string") {
overrides = { message: overrides };
} else if (typeof overrides === "number") {
overrides = { severity: overrides };
}
// Remove undefined properties
if (overrides)
Object.keys(overrides).forEach(key =>
(overrides as any)[key] === undefined
? delete (overrides as any)[key]
: null
);
return overrides ?? {};
}
/**
* Represents an error that occurred in a TerriaJS module, especially an asynchronous one that cannot be raised
* by throwing an exception because no one would be able to catch it.
*/
export default class TerriaError {
private readonly _message: string | I18nTranslateString;
private readonly _title: string | I18nTranslateString;
/** Override shouldRaiseToUser (see `get shouldRaiseToUser()`) */
private _shouldRaiseToUser: boolean | undefined;
private _raisedToUser: boolean;
readonly importance: number = 0;
readonly severity: TerriaErrorSeverity | (() => TerriaErrorSeverity);
/** `sender` isn't really used for anything at the moment... */
readonly sender: unknown;
readonly originalError?: (TerriaError | Error)[];
readonly stack: string;
@observable showDetails: boolean;
/**
* Convenience function to generate a TerriaError from some unknown error. It will try to extract a meaningful message from whatever object it is given.
*
* `overrides` can be used to add more context to the TerriaError
*
* If error is a `TerriaError`, and `overrides` are provided - then `createParentError` will be used to create a tree of `TerriaErrors` (see {@link `TerriaError#createParentError}`).
*
* Note, you can not pass `TerriaErrorOptions` (or JSON version of `TerriaError`) as the error parameter.
*
* For example:
*
* This is **incorrect**:
*
* ```
* TerriaError.from({message: "Some message", title: "Some title"})
* ```
*
* Instead you must use TerriaError constructor
*
* This is **correct**:
*
* ```
* new TerriaError({message: "Some message", title: "Some title"})
* ```
*/
static from(error: unknown, overrides?: TerriaErrorOverrides): TerriaError {
if (error instanceof TerriaError) {
return isDefined(overrides) ? error.createParentError(overrides) : error;
}
// Try to find message/title from error object
let message: string | I18nTranslateString = {
key: "core.terriaError.defaultMessage"
};
let title: string | I18nTranslateString = {
key: "core.terriaError.defaultTitle"
};
// Create original Error from `error` object
let originalError: Error | undefined;
if (typeof error === "string") {
message = error;
originalError = new Error(message);
}
// If error is RequestErrorEvent - use networkRequestTitle and networkRequestMessage
else if (error instanceof RequestErrorEvent) {
title = { key: "core.terriaError.networkRequestTitle" };
message = {
key: "core.terriaError.networkRequestMessage"
};
originalError = new Error(error.toString());
} else if (error instanceof Error) {
message = error.message;
originalError = error;
} else if (typeof error === "object" && error !== null) {
message = error.toString();
originalError = new Error(error.toString());
}
return new TerriaError({
title,
message,
originalError,
...parseOverrides(overrides)
});
}
/** Combine an array of `TerriaErrors` into a single `TerriaError`.
* `overrides` can be used to add more context to the combined `TerriaError`.
*/
static combine(
errors: (TerriaError | undefined)[],
overrides: TerriaErrorOverrides
): TerriaError | undefined {
const filteredErrors = errors.filter(e => isDefined(e)) as TerriaError[];
if (filteredErrors.length === 0) return;
// If only one error, just create parent error - this is so we don't get unnecessary levels of TerriaError created
if (filteredErrors.length === 1) {
return filteredErrors[0].createParentError(overrides);
}
// Find highest severity across errors (eg if one if `Error`, then the new TerriaError will also be `Error`)
const severity = () =>
filteredErrors
.map(error =>
typeof error.severity === "function"
? error.severity()
: error.severity
)
.includes(TerriaErrorSeverity.Error)
? TerriaErrorSeverity.Error
: TerriaErrorSeverity.Warning;
// shouldRaiseToUser will be true if at least one error includes shouldRaiseToUser = true
const shouldRaiseToUser = filteredErrors
.map(error => error._shouldRaiseToUser ?? false)
.includes(true);
return new TerriaError({
// Set default title and message
title: { key: "core.terriaError.defaultCombineTitle" },
message: { key: "core.terriaError.defaultCombineMessage" },
// Add original errors and overrides
originalError: filteredErrors,
severity,
shouldRaiseToUser,
...parseOverrides(overrides)
});
}
constructor(options: TerriaErrorOptions) {
this._message = options.message;
this._title = options.title ?? { key: "core.terriaError.defaultTitle" };
this.sender = options.sender;
this._raisedToUser = options.raisedToUser ?? false;
this._shouldRaiseToUser = options.shouldRaiseToUser;
this.importance = options.importance ?? 0;
this.showDetails = options.showDetails ?? false;
// Transform originalError to an array if needed
this.originalError = isDefined(options.originalError)
? Array.isArray(options.originalError)
? options.originalError
: [options.originalError]
: [];
this.severity = options.severity ?? TerriaErrorSeverity.Error;
this.stack = (new Error().stack ?? "")
.split("\n")
// Filter out some less useful lines in the stack trace
.filter(s =>
["result.ts", "terriaerror.ts", "opendatasoft.apiclient.umd.js"].every(
remove => !s.toLowerCase().includes(remove)
)
)
.join("\n");
}
get message() {
return resolveI18n(this._message);
}
/** Return error with message of highest importance in Error tree */
get highestImportanceError() {
return this.flatten().sort((a, b) => b.importance - a.importance)[0];
}
get title() {
return resolveI18n(this._title);
}
set shouldRaiseToUser(s: boolean | undefined) {
this._shouldRaiseToUser = s;
}
/** True if `severity` is `Error` and the error hasn't been raised yet - or return this._shouldRaiseToUser if it is defined */
get shouldRaiseToUser() {
return (
// Return this._shouldRaiseToUser override if it is defined
this._shouldRaiseToUser ??
// Otherwise, we should raise the error if it hasn't already been raised and the severity is ERROR
(!this.raisedToUser &&
(typeof this.severity === "function"
? this.severity()
: this.severity) === TerriaErrorSeverity.Error)
);
}
/** Has any error in the error tree been raised to the user? */
get raisedToUser() {
return this.flatten().find(error => error._raisedToUser) ? true : false;
}
/** Set raisedToUser value for **all** `TerriaErrors` in this tree. */
set raisedToUser(r: boolean) {
this._raisedToUser = r;
if (this.originalError) {
this.originalError.forEach(err =>
err instanceof TerriaError ? (err.raisedToUser = r) : null
);
}
}
/** Convert `TerriaError` to `Notification` */
toNotification(): Notification {
return {
title: () => this.highestImportanceError.title, // Title may need to be resolved when error is raised to user (for example after i18next initialisation)
message: terriaErrorNotification(this),
// Don't show TerriaError Notification if shouldRaiseToUser is false, or we have already raisedToUser
ignore: () => !this.shouldRaiseToUser,
// Set raisedToUser to true on dismiss
onDismiss: () => (this.raisedToUser = true)
};
}
/**
* Create a new parent `TerriaError` from this error. This essentially "clones" the `TerriaError` and applied `overrides` on top. It will also set `originalError` so we get a nice tree of `TerriaErrors`
*/
createParentError(overrides?: TerriaErrorOverrides): TerriaError {
// Note: we don't copy over `raisedToUser` or `importance` here
// We don't need `raisedToUser` as the getter will check all errors in the tree when called
// We don't want `importance` copied over, as it may vary between errors in the tree - and we want to be able to find errors with highest importance when diplaying the entire error tree to the user
return new TerriaError({
message: this._message,
title: this._title,
sender: this.sender,
originalError: this,
severity: this.severity,
shouldRaiseToUser: this._shouldRaiseToUser,
...parseOverrides(overrides)
});
}
/** Depth-first flatten */
flatten(): TerriaError[] {
return filterOutUndefined([
this,
...flatten(
this.originalError
? this.originalError.map(error =>
error instanceof TerriaError ? error.flatten() : []
)
: []
)
]);
}
/**
* Returns a plain error object for this TerriaError instance.
*
* The `message` string for the returned plain error will include the
* messages from all the nested `originalError`s for this instance.
*/
toError(): Error {
// indentation required per nesting when stringifying nested error messages
const indentChar = " ";
const buildNested: (
prop: "message" | "stack"
) => (error: TerriaError, depth: number) => string | undefined = prop => (
error,
depth
) => {
if (!Array.isArray(error.originalError)) {
return;
}
const indent = indentChar.repeat(depth);
const nestedMessage = error.originalError
.map(e => {
if (e instanceof TerriaError) {
// recursively build the message for nested errors
return `${e[prop]
?.split("\n")
.map(s => indent + s)
.join("\n")}\n${buildNested(prop)(e, depth + 1)}`;
} else {
return `${e[prop]
?.split("\n")
.map(s => indent + s)
.join("\n")}`;
}
})
.join("\n");
return nestedMessage;
};
let message = this.message;
const nestedMessage = buildNested("message")(this, 1);
if (nestedMessage) {
message = `${message}\nNested error:\n${nestedMessage}`;
}
const error = new Error(message);
error.name = this.title;
let stack = this.stack;
const nestedStack = buildNested("stack")(this, 1);
if (nestedStack) {
stack = `${stack}\n${nestedStack}`;
}
error.stack = stack;
return error;
}
}
/** Wrap up network requets error with user-friendly message */
export function networkRequestError(error: TerriaError | TerriaErrorOptions) {
// Combine network error with "networkRequestMessageDetailed" - this contains extra info about what could cause network error
return TerriaError.combine(
[
error instanceof TerriaError ? error : new TerriaError(error),
new TerriaError({
message: {
key: "core.terriaError.networkRequestMessageDetailed"
}
})
],
// Override combined error with user-friendly title and message
{
title: { key: "core.terriaError.networkRequestTitle" },
message: {
key: "core.terriaError.networkRequestMessage"
},
importance: 1
}
);
} | the_stack |
import { schemaDefaultValue } from '../../collectionUtils'
import { arrayOfForeignKeysField, denormalizedCountOfReferences, foreignKeyField, resolverOnlyField, accessFilterMultiple } from '../../utils/schemaUtils';
import SimpleSchema from 'simpl-schema';
import { Utils, slugify } from '../../vulcan-lib/utils';
import { addGraphQLSchema } from '../../vulcan-lib/graphql';
import { getWithLoader } from '../../loaders';
import GraphQLJSON from 'graphql-type-json';
import moment from 'moment';
import { captureException } from '@sentry/core';
import { forumTypeSetting, taggingNamePluralSetting, taggingNameSetting } from '../../instanceSettings';
import { SORT_ORDER_OPTIONS, SettingsOption } from '../posts/schema';
import omit from 'lodash/omit';
const formGroups: Partial<Record<string,FormGroup>> = {
advancedOptions: {
name: "advancedOptions",
order: 20,
label: "Advanced Options",
startCollapsed: true,
},
};
addGraphQLSchema(`
type TagContributor {
user: User
contributionScore: Int!
numCommits: Int!
voteCount: Int!
}
type TagContributorsList {
contributors: [TagContributor!]
totalCount: Int!
}
`);
export const TAG_POSTS_SORT_ORDER_OPTIONS: { [key: string]: SettingsOption; } = {
relevance: { label: 'Most Relevant' },
...omit(SORT_ORDER_OPTIONS, 'topAdjusted')
}
export const schema: SchemaType<DbTag> = {
createdAt: {
optional: true,
type: Date,
canRead: ['guests'],
onInsert: (document, currentUser) => new Date(),
},
name: {
type: String,
viewableBy: ['guests'],
insertableBy: ['members'],
editableBy: ['members'],
order: 1,
},
slug: {
type: String,
optional: true,
viewableBy: ['guests'],
insertableBy: ['admins', 'sunshineRegiment'],
editableBy: ['admins', 'sunshineRegiment'],
group: formGroups.advancedOptions,
onInsert: async (tag) => {
const basicSlug = slugify(tag.name);
return await Utils.getUnusedSlugByCollectionName('Tags', basicSlug, true);
},
onUpdate: async ({data, oldDocument}) => {
if (data.slug && data.slug !== oldDocument.slug) {
const slugIsUsed = await Utils.slugIsUsed("Tags", data.slug)
if (slugIsUsed) {
throw Error(`Specified slug is already used: ${data.slug}`)
}
} else if (data.name && data.name !== oldDocument.name) {
return await Utils.getUnusedSlugByCollectionName("Tags", slugify(data.name), true, oldDocument._id)
}
}
},
oldSlugs: {
type: Array,
optional: true,
canRead: ['guests'],
onUpdate: ({data, oldDocument}) => {
if ((data.slug && data.slug !== oldDocument.slug) || (data.name && data.name !== oldDocument.name)) {
return [...(oldDocument.oldSlugs || []), oldDocument.slug]
}
}
},
'oldSlugs.$': {
type: String,
optional: true,
canRead: ['guests'],
},
core: {
label: "Core Tag (moderators check whether it applies when reviewing new posts)",
type: Boolean,
viewableBy: ['guests'],
insertableBy: ['admins', 'sunshineRegiment'],
editableBy: ['admins', 'sunshineRegiment'],
group: formGroups.advancedOptions,
optional: true,
...schemaDefaultValue(false),
},
suggestedAsFilter: {
label: "Suggested Filter (appears as a default option in filter settings without having to use the search box)",
type: Boolean,
viewableBy: ['guests'],
insertableBy: ['admins', 'sunshineRegiment'],
editableBy: ['admins', 'sunshineRegiment'],
group: formGroups.advancedOptions,
optional: true,
...schemaDefaultValue(false),
},
defaultOrder: {
type: Number,
viewableBy: ['guests'],
insertableBy: ['admins', 'sunshineRegiment'],
editableBy: ['admins', 'sunshineRegiment'],
group: formGroups.advancedOptions,
optional: true,
...schemaDefaultValue(0),
tooltip: `Rank this ${taggingNameSetting.get()} higher in lists of ${taggingNamePluralSetting.get()}?`
},
descriptionTruncationCount: {
// number of paragraphs to display above-the-fold
type: Number,
viewableBy: ['guests'],
insertableBy: ['admins', 'sunshineRegiment'],
editableBy: ['admins', 'sunshineRegiment'],
group: formGroups.advancedOptions,
optional: true,
...schemaDefaultValue(0),
},
postCount: {
...denormalizedCountOfReferences({
fieldName: "postCount",
collectionName: "Tags",
foreignCollectionName: "TagRels",
foreignTypeName: "TagRel",
foreignFieldName: "tagId",
//filterFn: tagRel => tagRel.baseScore > 0, //TODO: Didn't work with filter; votes are bypassing the relevant callback?
}),
viewableBy: ['guests'],
},
userId: {
...foreignKeyField({
idFieldName: "userId",
resolverName: "user",
collectionName: "Users",
type: "User",
nullable: true,
}),
onCreate: ({currentUser}) => currentUser!._id,
viewableBy: ['guests'],
optional: true
},
adminOnly: {
label: "Admin Only",
type: Boolean,
viewableBy: ['guests'],
insertableBy: ['admins', 'sunshineRegiment'],
editableBy: ['admins', 'sunshineRegiment'],
group: formGroups.advancedOptions,
optional: true,
...schemaDefaultValue(false),
},
charsAdded: {
type: Number,
optional: true,
viewableBy: ['guests'],
},
charsRemoved: {
type: Number,
optional: true,
viewableBy: ['guests'],
},
deleted: {
type: Boolean,
viewableBy: ['guests'],
editableBy: ['admins', 'sunshineRegiment'],
optional: true,
group: formGroups.advancedOptions,
...schemaDefaultValue(false),
},
lastCommentedAt: {
type: Date,
denormalized: true,
optional: true,
viewableBy: ['guests'],
},
needsReview: {
type: Boolean,
canRead: ['guests'],
canUpdate: ['admins', 'sunshineRegiment'],
group: formGroups.advancedOptions,
optional: true,
...schemaDefaultValue(true)
},
reviewedByUserId: {
...foreignKeyField({
idFieldName: "reviewedByUserId",
resolverName: "reviewedByUser",
collectionName: "Users",
type: "User",
}),
optional: true,
viewableBy: ['guests'],
editableBy: ['sunshineRegiment', 'admins'],
insertableBy: ['sunshineRegiment', 'admins'],
hidden: true,
},
// What grade is the current tag? See the wikiGradeDefinitions variable defined below for details.
wikiGrade: {
type: SimpleSchema.Integer,
canRead: ['guests'],
canUpdate: ['admins', 'sunshineRegiment'],
canCreate: ['admins', 'sunshineRegiment'],
control: 'select',
options: () => Object.entries(wikiGradeDefinitions).map(([grade, name]) => ({
value: parseInt(grade),
label: name
})),
group: formGroups.advancedOptions,
optional: true,
...schemaDefaultValue(2),
},
recentComments: resolverOnlyField({
type: Array,
graphQLtype: "[Comment]",
viewableBy: ['guests'],
graphqlArguments: 'tagCommentsLimit: Int, maxAgeHours: Int, af: Boolean',
resolver: async (tag, { tagCommentsLimit=5, maxAgeHours=18, af=false }, context: ResolverContext) => {
const { currentUser, Comments } = context;
const timeCutoff = moment(tag.lastCommentedAt).subtract(maxAgeHours, 'hours').toDate();
const comments = await Comments.find({
...Comments.defaultView({}).selector,
tagId: tag._id,
score: {$gt:0},
deletedPublic: false,
postedAt: {$gt: timeCutoff},
...(af ? {af:true} : {}),
}, {
limit: tagCommentsLimit,
sort: {postedAt:-1}
}).fetch();
return await accessFilterMultiple(currentUser, Comments, comments, context);
}
}),
'recentComments.$': {
type: Object,
foreignKey: 'Comments',
},
wikiOnly: {
type: Boolean,
canRead: ['guests'],
canUpdate: ['admins', 'sunshineRegiment'],
canCreate: ['admins', 'sunshineRegiment'],
group: formGroups.advancedOptions,
optional: true,
...schemaDefaultValue(false),
},
// Cloudinary image id for the banner image (high resolution)
bannerImageId: {
type: String,
optional: true,
viewableBy: ['guests'],
editableBy: ['admins', 'sunshineRegiment'],
insertableBy: ['admins', 'sunshineRegiment'],
label: "Banner Image",
control: "ImageUpload",
tooltip: "Minimum 200x600 px",
group: formGroups.advancedOptions,
hidden: forumTypeSetting.get() !== 'EAForum',
},
tagFlagsIds: {
...arrayOfForeignKeysField({
idFieldName: "tagFlagsIds",
resolverName: "tagFlags",
collectionName: "TagFlags",
type: "TagFlag",
}),
control: 'TagFlagToggleList',
label: "Flags: ",
order: 30,
optional: true,
viewableBy: ['guests'],
editableBy: ['members', 'sunshineRegiment', 'admins'],
insertableBy: ['sunshineRegiment', 'admins']
},
'tagFlagsIds.$': {
type: String,
foreignKey: 'TagFlags',
optional: true
},
// Populated by the LW 1.0 wiki import, with the revision number
// that has the last full state of the imported post
lesswrongWikiImportRevision: {
type: String,
optional: true,
viewableBy: ['guests']
},
lesswrongWikiImportSlug: {
type: String,
optional: true,
viewableBy: ['guests']
},
lesswrongWikiImportCompleted: {
type: Boolean,
optional: true,
viewableBy: ['guests']
},
// lastVisitedAt: If the user is logged in and has viewed this tag, the date
// they last viewed it. Otherwise, null.
lastVisitedAt: resolverOnlyField({
type: Date,
viewableBy: ['guests'],
optional: true,
resolver: async (tag: DbTag, args: void, context: ResolverContext) => {
const { ReadStatuses, currentUser } = context;
if (!currentUser) return null;
const readStatus = await getWithLoader(context, ReadStatuses,
`tagReadStatuses`,
{ userId: currentUser._id },
'tagId', tag._id
);
if (!readStatus.length) return null;
return readStatus[0].lastUpdated;
}
}),
isRead: resolverOnlyField({
type: Boolean,
viewableBy: ['guests'],
optional: true,
resolver: async (tag: DbTag, args: void, context: ResolverContext) => {
const { ReadStatuses, currentUser } = context;
if (!currentUser) return false;
const readStatus = await getWithLoader(context, ReadStatuses,
`tagReadStatuses`,
{ userId: currentUser._id },
'tagId', tag._id
);
if (!readStatus.length) return false;
return readStatus[0].isRead;
}
}),
tableOfContents: resolverOnlyField({
type: Object,
viewableBy: ['guests'],
graphQLtype: GraphQLJSON,
graphqlArguments: 'version: String',
resolver: async (document: DbTag, args: {version: string}, context: ResolverContext) => {
try {
return await Utils.getToCforTag({document, version: args.version||null, context});
} catch(e) {
captureException(e);
return null;
}
}
}),
htmlWithContributorAnnotations: {
type: String,
viewableBy: ['guests'],
optional: true,
hidden: true,
denormalized: true,
},
// See resolver in tagResolvers.ts. Takes optional limit and version arguments.
// Returns a list of contributors and the total karma of their contributions
// (counting only up to the specified revision, if a revision is specified).
contributors: {
viewableBy: ['guests'],
type: "TagContributorsList",
optional: true,
},
// Denormalized copy of contribution-stats, for the latest revision.
// Replaces contributionScores, which was the same denormalized thing but for
// contribution scores only, without number of commits and vote count, and
// which is no longer on the schema.
contributionStats: {
type: Object,
optional: true,
blackbox: true,
hidden: true,
viewableBy: ['guests'],
denormalized: true,
},
introSequenceId: {
...foreignKeyField({
idFieldName: "introSequenceId",
resolverName: "sequence",
collectionName: "Sequences",
type: "Sequence",
nullable: true,
}),
optional: true,
group: formGroups.advancedOptions,
viewableBy: ['guests'],
editableBy: ['sunshineRegiment', 'admins'],
insertableBy: ['sunshineRegiment', 'admins'],
},
postsDefaultSortOrder: {
type: String,
optional: true,
group: formGroups.advancedOptions,
viewableBy: ['guests'],
editableBy: ['sunshineRegiment', 'admins'],
insertableBy: ['sunshineRegiment', 'admins'],
control: 'select',
options: () => Object.entries(TAG_POSTS_SORT_ORDER_OPTIONS).map(([key, val]) => ({
value: key,
label: val.label
})),
},
}
export const wikiGradeDefinitions: Partial<Record<number,string>> = {
0: "Uncategorized",
1: "Flagged",
2: "Stub",
3: "C-Class",
4: "B-Class",
5: "A-Class"
} | the_stack |
import { ResourceConstants } from 'graphql-transformer-common';
import { GraphQLTransform } from '@aws-amplify/graphql-transformer-core';
import { SearchableModelTransformer } from '@aws-amplify/graphql-searchable-transformer';
import { ModelTransformer } from '@aws-amplify/graphql-model-transformer';
import { CloudFormationClient } from '../CloudFormationClient';
import { S3Client } from '../S3Client';
import { Output } from 'aws-sdk/clients/cloudformation';
import { GraphQLClient } from '../GraphQLClient';
import { cleanupStackAfterTest, deploy } from '../deployNestedStacks';
import { default as moment } from 'moment';
import { default as S3 } from 'aws-sdk/clients/s3';
// tslint:disable: no-magic-numbers
jest.setTimeout(60000 * 60);
const cf = new CloudFormationClient('us-east-1');
const customS3Client = new S3Client('us-east-1');
const awsS3Client = new S3({ region: 'us-east-1' });
let GRAPHQL_CLIENT: GraphQLClient = undefined;
const featureFlags = {
getBoolean: jest.fn().mockImplementation((name, defaultValue) => {
if (name === 'improvePluralization') {
return true;
}
return;
}),
getNumber: jest.fn(),
getObject: jest.fn(),
getString: jest.fn(),
};
const BUILD_TIMESTAMP = moment().format('YYYYMMDDHHmmss');
const STACK_NAME = `TestSearchableAggregatesv2-${BUILD_TIMESTAMP}`;
const BUCKET_NAME = `testsearchableaggregatesv2-${BUILD_TIMESTAMP}`;
const LOCAL_FS_BUILD_DIR = '/tmp/model_searchable_aggregates_v2_tests/';
const S3_ROOT_DIR_KEY = 'deployments';
const fragments = [`fragment FullTodo on Todo { id name description count }`];
const runQuery = async (query: string) => {
try {
const q = [query, ...fragments].join('\n');
const response = await GRAPHQL_CLIENT.query(q, {});
return response;
} catch (e) {
console.error(e);
return null;
}
};
const createEntries = async () => {
// create todos
await runQuery(getCreateTodosMutation('test1', 'test1', 10));
await runQuery(getCreateTodosMutation('test2', 'test2', 20));
await runQuery(getCreateTodosMutation('test3', 'test3', 30));
// Waiting for the ES Cluster + Streaming Lambda infra to be setup
await cf.wait(120, () => Promise.resolve());
await waitForESPropagate();
};
const waitForESPropagate = async (initialWaitSeconds = 5, maxRetryCount = 5) => {
const expectedCount = 3;
let waitInMilliseconds = initialWaitSeconds * 1000;
let currentRetryCount = 0;
let searchResponse;
do {
await new Promise(r => setTimeout(r, waitInMilliseconds));
searchResponse = await GRAPHQL_CLIENT.query(
`query {
searchTodos {
items {
id
}
}
}`,
{},
);
currentRetryCount += 1;
waitInMilliseconds = waitInMilliseconds * 2;
} while (searchResponse.data.searchTodos?.items?.length < expectedCount && currentRetryCount <= maxRetryCount);
};
beforeAll(async () => {
const validSchema = `
type Todo @model @searchable {
id: ID!
name: String!
description: String
count: Int
}
`;
const transformer = new GraphQLTransform({
featureFlags,
transformers: [new ModelTransformer(), new SearchableModelTransformer()],
sandboxModeEnabled: true,
});
try {
await awsS3Client.createBucket({ Bucket: BUCKET_NAME }).promise();
} catch (e) {
console.error(`Failed to create bucket: ${e}`);
}
try {
const out = transformer.transform(validSchema);
const finishedStack = await deploy(
customS3Client,
cf,
STACK_NAME,
out,
{},
LOCAL_FS_BUILD_DIR,
BUCKET_NAME,
S3_ROOT_DIR_KEY,
BUILD_TIMESTAMP,
);
// Arbitrary wait to make sure everything is ready.
await cf.wait(120, () => Promise.resolve());
expect(finishedStack).toBeDefined();
const getApiEndpoint = outputValueSelector(ResourceConstants.OUTPUTS.GraphQLAPIEndpointOutput);
const getApiKey = outputValueSelector(ResourceConstants.OUTPUTS.GraphQLAPIApiKeyOutput);
const endpoint = getApiEndpoint(finishedStack.Outputs);
const apiKey = getApiKey(finishedStack.Outputs);
expect(apiKey).toBeDefined();
expect(endpoint).toBeDefined();
GRAPHQL_CLIENT = new GraphQLClient(endpoint, { 'x-api-key': apiKey });
// Create sample mutations to test search queries
await createEntries();
} catch (e) {
console.error(e);
throw e;
}
});
afterAll(async () => {
await cleanupStackAfterTest(BUCKET_NAME, STACK_NAME, cf);
});
test('query for aggregate scalar results', async () => {
const expectedValue = 10;
const searchResponse = await GRAPHQL_CLIENT.query(
`query {
searchTodos(aggregates: [{
name: "Minimum",
type: min,
field: count
}]) {
aggregateItems {
name
result {
... on SearchableAggregateScalarResult {
value
}
}
}
}
}`,
{},
);
expect(searchResponse).toBeDefined();
const result = searchResponse.data.searchTodos.aggregateItems[0].result.value;
expect(result).toEqual(expectedValue);
});
test('query for aggregate bucket results', async () => {
const expectedValue = 3;
const searchResponse = await GRAPHQL_CLIENT.query(
`query {
searchTodos(aggregates: [{
name: "Terms",
type: terms,
field: name
}]) {
aggregateItems {
name
result {
... on SearchableAggregateBucketResult {
buckets {
doc_count
key
}
}
}
}
}
}`,
{},
);
expect(searchResponse).toBeDefined();
const result = searchResponse.data.searchTodos.aggregateItems[0].result.buckets.length;
expect(result).toEqual(expectedValue);
});
test('query for multiple aggregates', async () => {
const expectedValue = 5;
const searchResponse = await GRAPHQL_CLIENT.query(
`query {
searchTodos(aggregates: [
{ name: "Minimum", type: min, field: count },
{ name: "Maximum", type: max, field: count },
{ name: "Average", type: avg, field: count },
{ name: "Total", type: sum, field: count },
{ name: "Terms", type: terms, field: count }
]) {
aggregateItems {
name
result {
... on SearchableAggregateScalarResult {
value
}
... on SearchableAggregateBucketResult {
buckets {
doc_count
key
}
}
}
}
}
}`,
{},
);
expect(searchResponse).toBeDefined();
const result = searchResponse.data.searchTodos.aggregateItems.length;
expect(result).toEqual(expectedValue);
expect(searchResponse.data.searchTodos.aggregateItems[0].result).toBeDefined();
expect(searchResponse.data.searchTodos.aggregateItems[1].result).toBeDefined();
expect(searchResponse.data.searchTodos.aggregateItems[2].result).toBeDefined();
expect(searchResponse.data.searchTodos.aggregateItems[3].result).toBeDefined();
expect(searchResponse.data.searchTodos.aggregateItems[4].result).toBeDefined();
});
test('query with sort return results', async () => {
const searchResponse = await GRAPHQL_CLIENT.query(
`query {
searchTodos(sort: [
{
direction: asc,
field: name
},
{
direction: asc,
field: description
}
]) {
items {
id
name
description
}
}
}`,
{},
);
expect(searchResponse).toBeDefined();
expect(searchResponse.data).toBeDefined();
expect(searchResponse.data.searchTodos).toBeDefined();
expect(searchResponse.data.searchTodos.items).toBeDefined();
});
test('query searchable with eq filter', async () => {
const expectedRecords = 1;
const searchResponse = await GRAPHQL_CLIENT.query(
`query {
searchTodos(sort: [{
direction: asc,
field: name
}],
filter: {
name: {
eq: "test1"
}
}
) {
items {
id
name
description
}
}
}`,
{},
);
expect(searchResponse).toBeDefined();
expect(searchResponse.data).toBeDefined();
expect(searchResponse.data.searchTodos).toBeDefined();
expect(searchResponse.data.searchTodos.items).toHaveLength(expectedRecords);
expect(searchResponse.data.searchTodos.items).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: expect.any(String),
name: 'test1',
description: 'test1'
}),
]),
);
});
test('query searchable with ne filter', async () => {
const expectedRecords = 2;
const searchResponse = await GRAPHQL_CLIENT.query(
`query {
searchTodos(sort: [{
direction: asc,
field: name
}],
filter: {
name: {
ne: "test1"
}
}
) {
items {
id
name
description
}
}
}`,
{},
);
expect(searchResponse).toBeDefined();
expect(searchResponse.data).toBeDefined();
expect(searchResponse.data.searchTodos).toBeDefined();
expect(searchResponse.data.searchTodos.items).toHaveLength(expectedRecords);
expect(searchResponse.data.searchTodos.items).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: expect.any(String),
name: 'test2',
description: 'test2'
}),
expect.objectContaining({
id: expect.any(String),
name: 'test3',
description: 'test3'
}),
]),
);
});
test('query searchable with gt filter', async () => {
const expectedRecords = 2;
const searchResponse = await GRAPHQL_CLIENT.query(
`query {
searchTodos(sort: [{
direction: asc,
field: name
}],
filter: {
count: {
gt: 10
}
}
) {
items {
id
name
description
}
}
}`,
{},
);
expect(searchResponse).toBeDefined();
expect(searchResponse.data).toBeDefined();
expect(searchResponse.data.searchTodos).toBeDefined();
expect(searchResponse.data.searchTodos.items).toHaveLength(expectedRecords);
expect(searchResponse.data.searchTodos.items).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: expect.any(String),
name: 'test2',
description: 'test2'
}),
expect.objectContaining({
id: expect.any(String),
name: 'test3',
description: 'test3'
}),
]),
);
});
test('query searchable with gte filter', async () => {
const expectedRecords = 3;
const searchResponse = await GRAPHQL_CLIENT.query(
`query {
searchTodos(sort: [{
direction: asc,
field: name
}],
filter: {
count: {
gte: 10
}
}
) {
items {
id
name
description
}
}
}`,
{},
);
expect(searchResponse).toBeDefined();
expect(searchResponse.data).toBeDefined();
expect(searchResponse.data.searchTodos).toBeDefined();
expect(searchResponse.data.searchTodos.items).toHaveLength(expectedRecords);
expect(searchResponse.data.searchTodos.items).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: expect.any(String),
name: 'test1',
description: 'test1'
}),
expect.objectContaining({
id: expect.any(String),
name: 'test2',
description: 'test2'
}),
expect.objectContaining({
id: expect.any(String),
name: 'test3',
description: 'test3'
}),
]),
);
});
test('query searchable with lt filter', async () => {
const expectedRecords = 1;
const searchResponse = await GRAPHQL_CLIENT.query(
`query {
searchTodos(sort: [{
direction: asc,
field: name
}],
filter: {
count: {
lt: 20
}
}
) {
items {
id
name
description
}
}
}`,
{},
);
expect(searchResponse).toBeDefined();
expect(searchResponse.data).toBeDefined();
expect(searchResponse.data.searchTodos).toBeDefined();
expect(searchResponse.data.searchTodos.items).toHaveLength(expectedRecords);
expect(searchResponse.data.searchTodos.items).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: expect.any(String),
name: 'test1',
description: 'test1'
}),
]),
);
});
test('query searchable with lte filter', async () => {
const expectedRecords = 2;
const searchResponse = await GRAPHQL_CLIENT.query(
`query {
searchTodos(sort: [{
direction: asc,
field: name
}],
filter: {
count: {
lte: 20
}
}
) {
items {
id
name
description
}
}
}`,
{},
);
expect(searchResponse).toBeDefined();
expect(searchResponse.data).toBeDefined();
expect(searchResponse.data.searchTodos).toBeDefined();
expect(searchResponse.data.searchTodos.items).toHaveLength(expectedRecords);
expect(searchResponse.data.searchTodos.items).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: expect.any(String),
name: 'test1',
description: 'test1'
}),
expect.objectContaining({
id: expect.any(String),
name: 'test2',
description: 'test2'
}),
]),
);
});
test('query searchable with eq and lt filter', async () => {
const expectedRecords = 1;
const searchResponse = await GRAPHQL_CLIENT.query(
`query {
searchTodos(sort: [{
direction: asc,
field: name
}],
filter: {
name: {
eq: "test1"
},
and: {
count: {
lt: 20
}
}
}
) {
items {
id
name
description
}
}
}`,
{},
);
expect(searchResponse).toBeDefined();
expect(searchResponse.data).toBeDefined();
expect(searchResponse.data.searchTodos).toBeDefined();
expect(searchResponse.data.searchTodos.items).toHaveLength(expectedRecords);
expect(searchResponse.data.searchTodos.items).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: expect.any(String),
name: 'test1',
description: 'test1'
}),
]),
);
});
test('query searchable with wildcard filter', async () => {
const expectedRecords = 3;
const searchResponse = await GRAPHQL_CLIENT.query(
`query {
searchTodos(sort: [{
direction: asc,
field: name
}],
filter: {
name: {
wildcard: "test*"
}
}
) {
items {
id
name
description
}
}
}`,
{},
);
expect(searchResponse).toBeDefined();
expect(searchResponse.data).toBeDefined();
expect(searchResponse.data.searchTodos).toBeDefined();
expect(searchResponse.data.searchTodos.items).toHaveLength(expectedRecords);
expect(searchResponse.data.searchTodos.items).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: expect.any(String),
name: 'test1',
description: 'test1'
}),
expect.objectContaining({
id: expect.any(String),
name: 'test2',
description: 'test2'
}),
expect.objectContaining({
id: expect.any(String),
name: 'test3',
description: 'test3'
}),
]),
);
});
test('query searchable with matchPhrasePrefix filter', async () => {
const expectedRecords = 3;
const searchResponse = await GRAPHQL_CLIENT.query(
`query {
searchTodos(sort: [{
direction: asc,
field: name
}],
filter: {
name: {
matchPhrasePrefix: "t"
}
}
) {
items {
id
name
description
}
}
}`,
{},
);
expect(searchResponse).toBeDefined();
expect(searchResponse.data).toBeDefined();
expect(searchResponse.data.searchTodos).toBeDefined();
expect(searchResponse.data.searchTodos.items).toHaveLength(expectedRecords);
expect(searchResponse.data.searchTodos.items).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: expect.any(String),
name: 'test1',
description: 'test1'
}),
expect.objectContaining({
id: expect.any(String),
name: 'test2',
description: 'test2'
}),
expect.objectContaining({
id: expect.any(String),
name: 'test3',
description: 'test3'
}),
]),
);
});
function getCreateTodosMutation(
name: string,
description: string,
count: number,
): string {
return `mutation {
createTodo(input: {
name: "${name}"
description: "${description}"
count: ${count}
}) { ...FullTodo }
}`;
}
function outputValueSelector(key: string) {
return (outputs: Output[]) => {
const output = outputs.find((o: Output) => o.OutputKey === key);
return output ? output.OutputValue : null;
};
} | the_stack |
import "../../Operator"
import * as C from "../../Cause"
import type { HasClock } from "../../Clock"
import { currentTime } from "../../Clock"
import * as A from "../../Collections/Immutable/Chunk"
import * as List from "../../Collections/Immutable/List"
import type * as MP from "../../Collections/Immutable/Map"
import * as Tp from "../../Collections/Immutable/Tuple"
import * as E from "../../Either"
import * as Ex from "../../Exit/api"
import { identity, pipe } from "../../Function"
import * as H from "../../Hub"
import * as L from "../../Layer"
import * as O from "../../Option"
import * as Q from "../../Queue"
import { matchTag } from "../../Utils"
import * as T from "../_internal/effect"
import * as F from "../_internal/fiber"
import * as M from "../_internal/managed"
import * as R from "../_internal/ref"
import * as Push from "../Push"
import type { Transducer } from "../Transducer"
import { transducer } from "../Transducer"
// Important notes while writing sinks and combinators:
// - What return values for sinks mean:
// Effect.unit - "need more values"
// Effect.fail([Either.Right(z), l]) - "ended with z and emit leftover l"
// Effect.fail([Either.Left(e), l]) - "failed with e and emit leftover l"
// - Result of processing of the stream using the sink must not depend on how the stream is chunked
// (chunking-invariance)
// pipe(stream, run(sink), Effect.either) === pipe(stream, chunkN(1), run(sink), Effect.either)
// - Sinks should always end when receiving a `None`. It is a defect to not end with some
// sort of result (even a failure) when receiving a `None`.
// - Sinks can assume they will not be pushed again after emitting a value.
export class Sink<R, E, I, L, Z> {
constructor(readonly push: M.Managed<R, never, Push.Push<R, E, I, L, Z>>) {}
}
/**
* Replaces this sink's result with the provided value.
*/
export function as_<R, E, I, L, Z, Z1>(
self: Sink<R, E, I, L, Z>,
z: Z1
): Sink<R, E, I, L, Z1> {
return map_(self, (_) => z)
}
/**
* Replaces this sink's result with the provided value.
*/
export function as<Z1>(z: Z1) {
return <R, E, I, L, Z>(self: Sink<R, E, I, L, Z>) => as_(self, z)
}
/**
* Repeatedly runs the sink for as long as its results satisfy
* the predicate `p`. The sink's results will be accumulated
* using the stepping function `f`.
*/
export function collectAllWhileWith<S>(z: S) {
return <Z>(p: (z: Z) => boolean) =>
(f: (s: S, z: Z) => S) =>
<R, E, I, L extends I>(self: Sink<R, E, I, L, Z>): Sink<R, E, I, L, S> =>
new Sink(
pipe(
R.makeManagedRef(z),
M.chain((acc) => {
return pipe(
Push.restartable(self.push),
M.map(({ tuple: [push, restart] }) => {
const go = (
s: S,
in_: O.Option<A.Chunk<I>>,
end: boolean
): T.Effect<R, Tp.Tuple<[E.Either<E, S>, A.Chunk<L>]>, S> =>
T.catchAll_(T.as_(push(in_), s), ({ tuple: [e, leftover] }) =>
E.fold_(
e,
(e) => Push.fail(e, leftover),
(z) => {
if (p(z)) {
const s1 = f(s, z)
if (A.isEmpty(leftover)) {
if (end) {
return Push.emit(s1, A.empty())
} else {
return T.as_(restart, s1)
}
} else {
return T.zipRight_(restart, go(s1, O.some(leftover), end))
}
} else {
return Push.emit(s, leftover)
}
}
)
)
return (in_: O.Option<A.Chunk<I>>) =>
T.chain_(acc.get, (s) =>
T.chain_(go(s, in_, O.isNone(in_)), (s1) => acc.set(s1))
)
})
)
})
)
)
}
/**
* Transforms this sink's input elements.
*/
export function contramap_<R, E, I, I2, L, Z>(
self: Sink<R, E, I, L, Z>,
f: (i2: I2) => I
): Sink<R, E, I2, L, Z> {
return contramapChunks_(self, A.map(f))
}
/**
* Transforms this sink's input elements.
*/
export function contramap<I, I2>(f: (i2: I2) => I) {
return <R, E, L, Z>(self: Sink<R, E, I, L, Z>) => contramap_(self, f)
}
/**
* Effectfully transforms this sink's input elements.
*/
export function contramapM_<R, R1, E, E1, I, I2, L, Z>(
self: Sink<R, E, I, L, Z>,
f: (i2: I2) => T.Effect<R1, E1, I>
): Sink<R & R1, E | E1, I2, L, Z> {
return contramapChunksM_(self, A.mapM(f))
}
/**
* Effectfully transforms this sink's input elements.
*/
export function contramapM<R1, E1, I, I2>(f: (i2: I2) => T.Effect<R1, E1, I>) {
return <R, E, L, Z>(self: Sink<R, E, I, L, Z>) => contramapM_(self, f)
}
/**
* Transforms this sink's input chunks.
* `f` must preserve chunking-invariance
*/
export function contramapChunks_<R, E, I, I2, L, Z>(
self: Sink<R, E, I, L, Z>,
f: (a: A.Chunk<I2>) => A.Chunk<I>
): Sink<R, E, I2, L, Z> {
return new Sink(M.map_(self.push, (push) => (input) => push(O.map_(input, f))))
}
/**
* Transforms this sink's input chunks.
* `f` must preserve chunking-invariance
*/
export function contramapChunks<I, I2>(f: (a: A.Chunk<I2>) => A.Chunk<I>) {
return <R, E, L, Z>(self: Sink<R, E, I, L, Z>) => contramapChunks_(self, f)
}
/**
* Effectfully transforms this sink's input chunks.
* `f` must preserve chunking-invariance
*/
export function contramapChunksM_<R, R1, E, E1, I, I2, L, Z>(
self: Sink<R, E, I, L, Z>,
f: (a: A.Chunk<I2>) => T.Effect<R1, E1, A.Chunk<I>>
): Sink<R & R1, E | E1, I2, L, Z> {
return new Sink(
M.map_(self.push, (push) => {
return (input: O.Option<A.Chunk<I2>>) =>
O.fold_(
input,
() => push(O.none),
(value) =>
pipe(
f(value),
T.mapError((e: E | E1) => Tp.tuple(E.left(e), A.empty<L>())),
T.chain((is) => push(O.some(is)))
)
)
})
)
}
/**
* Effectfully transforms this sink's input chunks.
* `f` must preserve chunking-invariance
*/
export function contramapChunksM<R1, E1, I, I2>(
f: (a: A.Chunk<I2>) => T.Effect<R1, E1, A.Chunk<I>>
) {
return <R, E, L, Z>(self: Sink<R, E, I, L, Z>) => contramapChunksM_(self, f)
}
/**
* Transforms both inputs and result of this sink using the provided functions.
*/
export function dimap_<R, E, I, I2, L, Z, Z2>(
self: Sink<R, E, I, L, Z>,
f: (i2: I2) => I,
g: (z: Z) => Z2
): Sink<R, E, I2, L, Z2> {
return map_(contramap_(self, f), g)
}
/**
* Transforms both inputs and result of this sink using the provided functions.
*/
export function dimap<I, I2, Z, Z2>(f: (i2: I2) => I, g: (z: Z) => Z2) {
return <R, E, L>(self: Sink<R, E, I, L, Z>) => dimap_(self, f, g)
}
/**
* Effectfully transforms both inputs and result of this sink using the provided functions.
*/
export function dimapM_<R, R1, E, E1, I, I2, L, Z, Z2>(
self: Sink<R, E, I, L, Z>,
f: (i2: I2) => T.Effect<R1, E1, I>,
g: (z: Z) => T.Effect<R1, E1, Z2>
): Sink<R & R1, E | E1, I2, L, Z2> {
return mapM_(contramapM_(self, f), g)
}
/**
* Effectfully transforms both inputs and result of this sink using the provided functions.
*/
export function dimapM<R1, E1, I, I2, Z, Z2>(
f: (i2: I2) => T.Effect<R1, E1, I>,
g: (z: Z) => T.Effect<R1, E1, Z2>
) {
return <R, E, L>(self: Sink<R, E, I, L, Z>) => dimapM_(self, f, g)
}
/**
* Transforms both input chunks and result of this sink using the provided functions.
*/
export function dimapChunks_<R, E, I, I2, L, Z, Z2>(
self: Sink<R, E, I, L, Z>,
f: (i2: A.Chunk<I2>) => A.Chunk<I>,
g: (z: Z) => Z2
): Sink<R, E, I2, L, Z2> {
return map_(contramapChunks_(self, f), g)
}
/**
* Transforms both input chunks and result of this sink using the provided functions.
*/
export function dimapChunks<I, I2, Z, Z2>(
f: (i2: A.Chunk<I2>) => A.Chunk<I>,
g: (z: Z) => Z2
) {
return <R, E, L>(self: Sink<R, E, I, L, Z>) => dimapChunks_(self, f, g)
}
/**
* Effectfully transforms both input chunks and result of this sink using the provided functions.
* `f` and `g` must preserve chunking-invariance
*/
export function dimapChunksM_<R, R1, E, E1, I, I2, L, Z, Z2>(
self: Sink<R, E, I, L, Z>,
f: (i2: A.Chunk<I2>) => T.Effect<R1, E1, A.Chunk<I>>,
g: (z: Z) => T.Effect<R1, E1, Z2>
): Sink<R & R1, E | E1, I2, L, Z2> {
return mapM_(contramapChunksM_(self, f), g)
}
/**
* Effectfully transforms both input chunks and result of this sink using the provided functions.
* `f` and `g` must preserve chunking-invariance
*/
export function dimapChunksM<R1, E1, I, I2, Z, Z2>(
f: (i2: A.Chunk<I2>) => T.Effect<R1, E1, A.Chunk<I>>,
g: (z: Z) => T.Effect<R1, E1, Z2>
) {
return <R, E, L>(self: Sink<R, E, I, L, Z>) => dimapChunksM_(self, f, g)
}
/**
* Runs this sink until it yields a result, then uses that result to create another
* sink from the provided function which will continue to run until it yields a result.
*
* This function essentially runs sinks in sequence.
*/
export function chain_<R, E, I, L extends I1, Z, R1, E1, I1 extends I, L1, Z1>(
self: Sink<R, E, I, L, Z>,
f: (z: Z) => Sink<R1, E1, I1, L1, Z1>
): Sink<R & R1, E | E1, I1, L1, Z1> {
return foldM_(
self,
(e) => fail(e)<I1>() as unknown as Sink<R1, E | E1, I1, L1, Z1>,
f
)
}
/**
* Runs this sink until it yields a result, then uses that result to create another
* sink from the provided function which will continue to run until it yields a result.
*
* This function essentially runs sinks in sequence.
*/
export function chain<Z, R, R1, E1, I, I1 extends I, L1, Z1>(
f: (z: Z) => Sink<R1, E1, I1, L1, Z1>
) {
return <E, L extends I1>(self: Sink<R, E, I, L, Z>) => chain_(self, f)
}
/**
* Recovers from errors by accepting one effect to execute for the case of an
* error, and one effect to execute for the case of success.
*
* This method has better performance than `either` since no intermediate
* value is allocated and does not require subsequent calls to `flatMap` to
* define the next effect.
*
* The error parameter of the returned `IO` may be chosen arbitrarily, since
* it will depend on the `IO`s returned by the given continuations.
*/
export function foldM_<R, R1, R2, E, E1, E2, I, I1, I2, L, L1, L2, Z, Z1, Z2>(
self: Sink<R, E, I, L, Z>,
failure: (e: E) => Sink<R1, E1, I1, L1, Z1>,
success: (z: Z) => Sink<R2, E2, I2, L2, Z2>
): Sink<R & R1 & R2, E1 | E2, I & I1 & I2, L1 | L2, Z1 | Z2> {
return new Sink(
pipe(
M.do,
M.bind("switched", () => T.toManaged(R.makeRef(false))),
M.bind("thisPush", () => self.push),
M.bind("thatPush", () =>
T.toManaged(
R.makeRef<Push.Push<R1 & R2, E1 | E2, I & I1 & I2, L1 | L2, Z1 | Z2>>(
(_) => T.unit
)
)
),
M.bind("openThatPush", () =>
M.switchable<
R1 & R2,
never,
Push.Push<R1 & R2, E1 | E2, I & I1 & I2, L1 | L2, Z1 | Z2>
>()
),
M.map(({ openThatPush, switched, thatPush, thisPush }) => {
return (in_: O.Option<A.Chunk<I & I1 & I2>>) =>
T.chain_(switched.get, (sw) => {
if (!sw) {
return T.catchAll_(thisPush(in_), (v) => {
const leftover = v[1]
const nextSink = E.fold_(v[0], failure, success)
return pipe(
openThatPush(nextSink.push),
T.tap(thatPush.set),
T.chain((p) =>
T.zipRight_(
switched.set(true),
O.fold_(
in_,
() =>
pipe(
p(O.some(leftover) as O.Option<A.Chunk<I & I1 & I2>>),
T.when(() => !A.isEmpty(leftover)),
T.zipRight(p(O.none))
),
() =>
pipe(
p(O.some(leftover) as O.Option<A.Chunk<I & I1 & I2>>),
T.when(() => !A.isEmpty(leftover))
)
)
)
)
)
})
} else {
return T.chain_(thatPush.get, (p) => p(in_))
}
})
})
)
)
}
/**
* Recovers from errors by accepting one effect to execute for the case of an
* error, and one effect to execute for the case of success.
*
* This method has better performance than `either` since no intermediate
* value is allocated and does not require subsequent calls to `flatMap` to
* define the next effect.
*
* The error parameter of the returned `IO` may be chosen arbitrarily, since
* it will depend on the `IO`s returned by the given continuations.
*/
export function foldM<R1, R2, E, E1, E2, I1, I2, L1, L2, Z, Z1, Z2>(
failure: (e: E) => Sink<R1, E1, I1, L1, Z1>,
success: (z: Z) => Sink<R2, E2, I2, L2, Z2>
) {
return <R, I, L>(self: Sink<R, E, I, L, Z>) => foldM_(self, failure, success)
}
/**
* Transforms this sink's result.
*/
export function map_<R, E, I, L, Z, Z2>(
self: Sink<R, E, I, L, Z>,
f: (z: Z) => Z2
): Sink<R, E, I, L, Z2> {
return new Sink(
M.map_(
self.push,
(sink) => (inputs: O.Option<A.Chunk<I>>) =>
T.mapError_(sink(inputs), (e) => Tp.tuple(E.map_(e.get(0), f), e.get(1)))
)
)
}
/**
* Transforms this sink's result.
*/
export function map<Z, Z2>(f: (z: Z) => Z2) {
return <R, E, I, L>(self: Sink<R, E, I, L, Z>) => map_(self, f)
}
/**
* Transforms the errors emitted by this sink using `f`.
*/
export function mapError_<R, E, E2, I, L, Z>(
self: Sink<R, E, I, L, Z>,
f: (e: E) => E2
): Sink<R, E | E2, I, L, Z> {
return new Sink(
M.map_(self.push, (p) => {
return (in_: O.Option<A.Chunk<I>>) =>
T.mapError_(p(in_), (e) => Tp.tuple(E.mapLeft_(e.get(0), f), e.get(1)))
})
)
}
/**
* Transforms the errors emitted by this sink using `f`.
*/
export function mapError<E, E2>(f: (e: E) => E2) {
return <R, I, L, Z>(self: Sink<R, E, I, L, Z>) => mapError_(self, f)
}
/**
* Effectfully transforms this sink's result.
*/
export function mapM_<R, R1, E, E1, I, L, Z, Z2>(
self: Sink<R, E, I, L, Z>,
f: (z: Z) => T.Effect<R1, E1, Z2>
): Sink<R & R1, E | E1, I, L, Z2> {
return new Sink(
M.map_(self.push, (push) => {
return (inputs: O.Option<A.Chunk<I>>) =>
T.catchAll_(push(inputs), ({ tuple: [e, left] }) =>
E.fold_(
e,
(e) => Push.fail(e, left),
(z) =>
T.foldM_(
f(z),
(e: E | E1) => Push.fail(e, left),
(z2) => Push.emit(z2, left)
)
)
)
})
)
}
/**
* Effectfully transforms this sink's result.
*/
export function mapM<R1, E1, Z, Z2>(f: (z: Z) => T.Effect<R1, E1, Z2>) {
return <R, E, I, L>(self: Sink<R, E, I, L, Z>) => mapM_(self, f)
}
/**
* Runs both sinks in parallel on the input, , returning the result or the error from the
* one that finishes first.
*/
export function race_<R, R1, E, E1, I, I1, L, L1, Z, Z1>(
self: Sink<R, E, I, L, Z>,
that: Sink<R1, E1, I1, L1, Z1>
): Sink<R & R1, E | E1, I & I1, L | L1, Z | Z1> {
return map_(raceBoth_(self, that), E.merge)
}
/**
* Runs both sinks in parallel on the input, , returning the result or the error from the
* one that finishes first.
*/
export function race<R1, E1, I1, L1, Z1>(that: Sink<R1, E1, I1, L1, Z1>) {
return <R, E, I, L, Z>(self: Sink<R, E, I, L, Z>) => race_(self, that)
}
/**
* Runs both sinks in parallel on the input, returning the result or the error from the
* one that finishes first.
*/
export function raceBoth_<R, R1, E, E1, I, I1, L, L1, Z, Z1>(
self: Sink<R, E, I, L, Z>,
that: Sink<R1, E1, I1, L1, Z1>
): Sink<R1 & R, E1 | E, I & I1, L1 | L, E.Either<Z, Z1>> {
return new Sink(
pipe(
M.do,
M.bind("p1", () => self.push),
M.bind("p2", () => that.push),
M.map(
({ p1, p2 }) =>
(
i: O.Option<A.Chunk<I & I1>>
): T.Effect<
R1 & R,
Tp.Tuple<[E.Either<E | E1, E.Either<Z, Z1>>, A.Chunk<L | L1>]>,
void
> =>
T.raceWith_(
p1(i),
p2(i),
(res1, fib2) =>
Ex.foldM_(
res1,
(f) =>
T.zipRight_(
F.interrupt(fib2),
T.halt(
pipe(
f,
C.map(({ tuple: [r, leftover] }) =>
Tp.tuple(E.map_(r, E.left), leftover)
)
)
)
),
() =>
T.mapError_(F.join(fib2), ({ tuple: [r, leftover] }) =>
Tp.tuple(E.map_(r, E.right), leftover)
)
),
(res2, fib1) =>
Ex.foldM_(
res2,
(f) =>
T.zipRight_(
F.interrupt(fib1),
T.halt(
pipe(
f,
C.map(({ tuple: [r, leftover] }) =>
Tp.tuple(E.map_(r, E.right), leftover)
)
)
)
),
() =>
T.mapError_(F.join(fib1), ({ tuple: [r, leftover] }) =>
Tp.tuple(E.map_(r, E.left), leftover)
)
)
)
)
)
)
}
/**
* Runs both sinks in parallel on the input, returning the result or the error from the
* one that finishes first.
*/
export function raceBoth<R1, E1, I1, L1, Z1>(that: Sink<R1, E1, I1, L1, Z1>) {
return <R, E, I, L, Z>(self: Sink<R, E, I, L, Z>) => raceBoth_(self, that)
}
/**
* Returns the sink that executes this one and times its execution.
*/
export function timed<R, E, I, L, Z>(
self: Sink<R, E, I, L, Z>
): Sink<R & HasClock, E, I, L, Tp.Tuple<[Z, number]>> {
return new Sink(
pipe(
self.push,
M.zipWith(T.toManaged(currentTime), (push, start) => {
return (in_: O.Option<A.Chunk<I>>) =>
T.catchAll_(
push(in_),
({
tuple: [e, leftover]
}): T.Effect<
R & HasClock,
Tp.Tuple<[E.Either<E, Tp.Tuple<[Z, number]>>, A.Chunk<L>]>,
never
> =>
E.fold_(
e,
(e) => Push.fail(e, leftover),
(z) =>
T.chain_(currentTime, (stop) =>
Push.emit(Tp.tuple(z, stop - start), leftover)
)
)
)
})
)
)
}
/**
* Converts this sink to a transducer that feeds incoming elements to the sink
* and emits the sink's results as outputs. The sink will be restarted when
* it ends.
*/
export function toTransducer<R, E, I, L extends I, Z>(
self: Sink<R, E, I, L, Z>
): Transducer<R, E, I, Z> {
return transducer(
M.map_(Push.restartable(self.push), ({ tuple: [push, restart] }) => {
const go = (input: O.Option<A.Chunk<I>>): T.Effect<R, E, A.Chunk<Z>> =>
T.foldM_(
push(input),
({ tuple: [e, leftover] }) =>
E.fold_(
e,
(e) => T.fail(e),
(z) =>
T.zipRight_(
restart,
A.isEmpty(leftover) || O.isNone(input)
? T.succeed(A.single(z))
: T.map_(go(O.some(leftover)), (more) => A.prepend_(more, z))
)
),
(_) => T.succeed(A.empty())
)
return (input: O.Option<A.Chunk<I>>) => go(input)
})
)
}
/**
* Feeds inputs to this sink until it yields a result, then switches over to the
* provided sink until it yields a result, combining the two results in a tuple.
*/
export function zip_<R, R1, E, E1, I, I1 extends I, L extends I1, L1, Z, Z1>(
self: Sink<R, E, I, L, Z>,
that: Sink<R1, E1, I1, L1, Z1>
): Sink<R & R1, E | E1, I & I1, L | L1, Tp.Tuple<[Z, Z1]>> {
return zipWith_(self, that, Tp.tuple)
}
/**
* Feeds inputs to this sink until it yields a result, then switches over to the
* provided sink until it yields a result, combining the two results in a tuple.
*/
export function zip<R1, E1, I, I1 extends I, L1, Z1>(that: Sink<R1, E1, I1, L1, Z1>) {
return <R, E, L extends I1, Z>(self: Sink<R, E, I, L, Z>) => zip_(self, that)
}
/**
* Like `zip`, but keeps only the result from the `that` sink.
*/
export function zipLeft_<R, R1, E, E1, I, I1 extends I, L extends I1, L1, Z, Z1>(
self: Sink<R, E, I, L, Z>,
that: Sink<R1, E1, I1, L1, Z1>
): Sink<R & R1, E | E1, I & L1 & I1, L | L1, Z> {
return zipWith_(self, that, (z) => z)
}
/**
* Like `zip`, but keeps only the result from the `that` sink.
*/
export function zipLeft<R1, E1, I, I1 extends I, L1, Z1>(
that: Sink<R1, E1, I1, L1, Z1>
) {
return <R, E, L extends I1, Z>(self: Sink<R, E, I, L, Z>) => zipLeft_(self, that)
}
/**
* Runs both sinks in parallel on the input and combines the results in a tuple.
*/
export function zipPar_<R, R1, E, E1, I, I1, L, L1, Z, Z1>(
self: Sink<R, E, I, L, Z>,
that: Sink<R1, E1, I1, L1, Z1>
): Sink<R & R1, E | E1, I & I1, L | L1, Tp.Tuple<[Z, Z1]>> {
return zipWithPar_(self, that, Tp.tuple)
}
/**
* Runs both sinks in parallel on the input and combines the results in a tuple.
*/
export function zipPar<R1, E1, I1, L1, Z1>(that: Sink<R1, E1, I1, L1, Z1>) {
return <R, E, I, L, Z>(self: Sink<R, E, I, L, Z>) => zipPar_(self, that)
}
/**
* Like `zipPar`, but keeps only the result from this sink.
*/
export function zipParLeft_<R, R1, E, E1, I, I1, L, L1, Z>(
self: Sink<R, E, I, L, Z>,
that: Sink<R1, E1, I1, L1, unknown>
): Sink<R & R1, E | E1, I & I1, L | L1, Z> {
return zipWithPar_(self, that, (b, _) => b)
}
/**
* Like `zipPar`, but keeps only the result from this sink.
*/
export function zipParLeft<R1, E1, I1, L1>(that: Sink<R1, E1, I1, L1, unknown>) {
return <R, E, I, L, Z>(self: Sink<R, E, I, L, Z>) => zipParLeft_(self, that)
}
/**
* Like `zipPar`, but keeps only the result from the `that` sink.
*/
export function zipParRight_<R, R1, E, E1, I, I1, L, L1, Z, Z1>(
self: Sink<R, E, I, L, Z>,
that: Sink<R1, E1, I1, L1, Z1>
): Sink<R & R1, E | E1, I & I1, L | L1, Z1> {
return zipWithPar_(self, that, (_, c) => c)
}
/**
* Like `zipPar`, but keeps only the result from the `that` sink.
*/
export function zipParRight<R1, E1, I1, L1, Z1>(that: Sink<R1, E1, I1, L1, Z1>) {
return <R, E, I, L, Z>(self: Sink<R, E, I, L, Z>) => zipParRight_(self, that)
}
/**
* Like `zip`, but keeps only the result from this sink.
*/
export function zipRight_<R, R1, E, E1, I, I1 extends I, L extends I1, L1, Z, Z1>(
self: Sink<R, E, I, L, Z>,
that: Sink<R1, E1, I1, L1, Z1>
): Sink<R & R1, E | E1, I & L1 & I1, L | L1, Z1> {
return zipWith_(self, that, (_, z1) => z1)
}
/**
* Like `zip`, but keeps only the result from this sink.
*/
export function zipRight<R1, E1, I, I1 extends I, L1, Z, Z1>(
that: Sink<R1, E1, I1, L1, Z1>
) {
return <R, E, L extends I1>(self: Sink<R, E, I, L, Z>) => zipRight_(self, that)
}
/**
* Feeds inputs to this sink until it yields a result, then switches over to the
* provided sink until it yields a result, finally combining the two results with `f`.
*/
export function zipWith_<R, R1, E, E1, I, I1 extends I, L extends I1, L1, Z, Z1, Z2>(
self: Sink<R, E, I, L, Z>,
that: Sink<R1, E1, I1, L1, Z1>,
f: (z: Z, z1: Z1) => Z2
): Sink<R & R1, E | E1, I & I1, L | L1, Z2> {
return chain_(self, (z) => map_(that, (_) => f(z, _)))
}
/**
* Feeds inputs to this sink until it yields a result, then switches over to the
* provided sink until it yields a result, finally combining the two results with `f`.
*/
export function zipWith<R1, E1, I, I1 extends I, L1, Z, Z1, Z2>(
that: Sink<R1, E1, I1, L1, Z1>,
f: (z: Z, z1: Z1) => Z2
) {
return <R, E, L extends I1>(self: Sink<R, E, I, L, Z>) => zipWith_(self, that, f)
}
class BothRunning {
readonly _tag = "BothRunning"
}
const bothRunning = new BothRunning()
class LeftDone<Z> {
readonly _tag = "LeftDone"
constructor(readonly value: Z) {}
}
class RightDone<Z1> {
readonly _tag = "RightDone"
constructor(readonly value: Z1) {}
}
type State<Z, Z1> = BothRunning | LeftDone<Z> | RightDone<Z1>
/**
* Runs both sinks in parallel on the input and combines the results
* using the provided function.
*/
export function zipWithPar_<R, R1, E, E1, I, I1, L, L1, Z, Z1, Z2>(
self: Sink<R, E, I, L, Z>,
that: Sink<R1, E1, I1, L1, Z1>,
f: (z: Z, z1: Z1) => Z2
): Sink<R & R1, E | E1, I & I1, L | L1, Z2> {
return new Sink(
pipe(
M.do,
M.bind("ref", () => T.toManaged(R.makeRef<State<Z, Z1>>(bothRunning))),
M.bind("p1", () => self.push),
M.bind("p2", () => that.push),
M.map(({ p1, p2, ref }) => {
return (in_: O.Option<A.Chunk<I & I1>>) =>
T.chain_(ref.get, (state) => {
const newState = pipe(
state,
matchTag({
BothRunning: (): T.Effect<
R & R1,
Tp.Tuple<[E.Either<E | E1, Z2>, A.Chunk<L | L1>]>,
State<Z, Z1>
> => {
const l: T.Effect<
R & R1,
Tp.Tuple<[E.Either<E | E1, Z2>, A.Chunk<L | L1>]>,
O.Option<Tp.Tuple<[Z, A.Chunk<L>]>>
> = T.foldM_(
p1(in_),
({ tuple: [e, l] }) =>
E.fold_(
e,
(e) =>
Push.fail(e, l) as T.Effect<
R & R1,
Tp.Tuple<[E.Either<E | E1, Z2>, A.Chunk<L | L1>]>,
O.Option<Tp.Tuple<[Z, A.Chunk<L>]>>
>,
(z) =>
T.succeed(O.some(Tp.tuple(z, l))) as T.Effect<
R & R1,
Tp.Tuple<[E.Either<E | E1, Z2>, A.Chunk<L | L1>]>,
O.Option<Tp.Tuple<[Z, A.Chunk<L>]>>
>
),
(_) =>
T.succeed(O.none) as T.Effect<
R & R1,
Tp.Tuple<[E.Either<E | E1, Z2>, A.Chunk<L | L1>]>,
O.Option<Tp.Tuple<[Z, A.Chunk<L>]>>
>
)
const r: T.Effect<
R & R1,
Tp.Tuple<[E.Either<E | E1, never>, A.Chunk<L | L1>]>,
O.Option<Tp.Tuple<[Z1, A.Chunk<L1>]>>
> = T.foldM_(
p2(in_),
({ tuple: [e, l] }) =>
E.fold_(
e,
(e) =>
Push.fail(e, l) as T.Effect<
R & R1,
Tp.Tuple<[E.Either<E | E1, never>, A.Chunk<L | L1>]>,
O.Option<Tp.Tuple<[Z1, A.Chunk<L1>]>>
>,
(z) =>
T.succeed(O.some(Tp.tuple(z, l))) as T.Effect<
R & R1,
Tp.Tuple<[E.Either<E | E1, never>, A.Chunk<L | L1>]>,
O.Option<Tp.Tuple<[Z1, A.Chunk<L1>]>>
>
),
(_) =>
T.succeed(O.none) as T.Effect<
R & R1,
Tp.Tuple<[E.Either<E | E1, never>, A.Chunk<L | L1>]>,
O.Option<Tp.Tuple<[Z1, A.Chunk<L1>]>>
>
)
return T.chain_(
T.zipPar_(l, r),
({
tuple: [lr, rr]
}): T.Effect<
R & R1,
Tp.Tuple<[E.Either<E1, Z2>, A.Chunk<L | L1>]>,
State<Z, Z1>
> => {
if (O.isSome(lr)) {
const [z, l] = lr.value.tuple
if (O.isSome(rr)) {
const [z1, l1] = rr.value.tuple
return T.fail(
Tp.tuple(E.right(f(z, z1)), A.size(l) > A.size(l1) ? l1 : l)
)
} else {
return T.succeed(new LeftDone(z))
}
} else {
if (O.isSome(rr)) {
const [z1] = rr.value.tuple
return T.succeed(new RightDone(z1))
} else {
return T.succeed(bothRunning)
}
}
}
) as T.Effect<
R & R1,
Tp.Tuple<[E.Either<E1, Z2>, A.Chunk<L | L1>]>,
State<Z, Z1>
>
},
LeftDone: ({ value: z }) =>
T.as_(
T.catchAll_(
p2(in_),
({
tuple: [e, leftover]
}): T.Effect<
R & R1,
Tp.Tuple<[E.Either<E | E1, Z2>, A.Chunk<L | L1>]>,
State<Z, Z1>
> =>
E.fold_(
e,
(e) => Push.fail(e, leftover),
(z1) => Push.emit(f(z, z1), leftover)
)
),
state
),
RightDone: ({ value: z1 }) =>
T.as_(
T.catchAll_(
p1(in_),
({
tuple: [e, leftover]
}): T.Effect<
R & R1,
Tp.Tuple<[E.Either<E | E1, Z2>, A.Chunk<L | L1>]>,
State<Z, Z1>
> =>
E.fold_(
e,
(e) => Push.fail(e, leftover),
(z) => Push.emit(f(z, z1), leftover)
)
),
state
)
})
)
return T.chain_(newState, (ns) => (ns === state ? T.unit : ref.set(ns)))
})
})
)
)
}
/**
* Runs both sinks in parallel on the input and combines the results
* using the provided function.
*/
export function zipWithPar<R1, E1, I1, L1, Z, Z1, Z2>(
that: Sink<R1, E1, I1, L1, Z1>,
f: (z: Z, z1: Z1) => Z2
) {
return <R, E, I, L>(self: Sink<R, E, I, L, Z>) => zipWithPar_(self, that, f)
}
/**
* Exposes leftover
*/
export function exposeLeftover<R, E, I, L, Z>(
self: Sink<R, E, I, L, Z>
): Sink<R, E, I, never, Tp.Tuple<[Z, A.Chunk<L>]>> {
return new Sink(
M.map_(self.push, (p) => {
return (in_: O.Option<A.Chunk<I>>) =>
T.mapError_(p(in_), ({ tuple: [v, leftover] }) =>
Tp.tuple(
E.map_(v, (z) => Tp.tuple(z, leftover)),
A.empty()
)
)
})
)
}
/**
* Drops any leftover
*/
export function dropLeftover<R, E, I, L, Z>(
self: Sink<R, E, I, L, Z>
): Sink<R, E, I, never, Z> {
return new Sink(
M.map_(
self.push,
(p) => (in_: O.Option<A.Chunk<I>>) =>
T.mapError_(p(in_), ({ tuple: [v, _] }) => Tp.tuple(v, A.empty()))
)
)
}
function untilOutputMGo<E, I, R, R1, E1, L, Z>(
in_: O.Option<A.Chunk<I>>,
end: boolean,
push: Push.Push<R, E, I, L, Z>,
restart: T.Effect<R, never, void>,
f: (z: Z) => T.Effect<R1, E1, boolean>
): T.Effect<R & R1, Tp.Tuple<[E.Either<E | E1, O.Option<Z>>, A.Chunk<L>]>, void> {
return T.catchAll_(push(in_), ({ tuple: [e, leftover] }) =>
E.fold_(
e,
(e) => Push.fail(e, leftover),
(z) =>
T.chain_(
T.mapError_(f(z), (err) => Tp.tuple(E.left(err), leftover)),
(satisfied) => {
if (satisfied) {
return Push.emit(O.some(z), leftover)
} else if (A.isEmpty(leftover)) {
return end
? Push.emit(O.none, A.empty())
: T.zipRight_(restart, Push.more)
} else {
return untilOutputMGo(
O.some(leftover) as O.Option<A.Chunk<I>>,
end,
push,
restart,
f
)
}
}
)
)
)
}
/**
* Creates a sink that produces values until one verifies
* the predicate `f`.
*/
export function untilOutputM_<R, R1, E, E1, I, L extends I, Z>(
self: Sink<R, E, I, L, Z>,
f: (z: Z) => T.Effect<R1, E1, boolean>
): Sink<R & R1, E | E1, I, L, O.Option<Z>> {
return new Sink(
M.map_(
Push.restartable(self.push),
({ tuple: [push, restart] }) =>
(is: O.Option<A.Chunk<I>>) =>
untilOutputMGo(is, O.isNone(is), push, restart, f)
)
)
}
/**
* Creates a sink that produces values until one verifies
* the predicate `f`.
*/
export function untilOutputM<R1, E1, Z>(f: (z: Z) => T.Effect<R1, E1, boolean>) {
return <R, E, I, L extends I>(self: Sink<R, E, I, L, Z>) => untilOutputM_(self, f)
}
/**
* Provides the sink with its required environment, which eliminates
* its dependency on `R`.
*/
export function provideAll_<R, E, I, L, Z>(
self: Sink<R, E, I, L, Z>,
r: R
): Sink<unknown, E, I, L, Z> {
return new Sink(
M.map_(
M.provideAll_(self.push, r),
(push) => (i: O.Option<A.Chunk<I>>) => T.provideAll_(push(i), r)
)
)
}
/**
* Provides the sink with its required environment, which eliminates
* its dependency on `R`.
*/
export function provideAll<R>(r: R) {
return <E, I, L, Z>(self: Sink<R, E, I, L, Z>) => provideAll_(self, r)
}
/**
* Provides some of the environment required to run this effect,
* leaving the remainder `R0`.
*/
export function provideSome_<R0, R, E, I, L, Z>(
self: Sink<R, E, I, L, Z>,
f: (r0: R0) => R
) {
return new Sink(
M.map_(
M.provideSome_(self.push, f),
(push) => (i: O.Option<A.Chunk<I>>) => T.provideSome_(push(i), f)
)
)
}
/**
* Provides some of the environment required to run this effect,
* leaving the remainder `R0`.
*/
export function provideSome<R0, R>(f: (r0: R0) => R) {
return <E, I, L, Z>(self: Sink<R, E, I, L, Z>) => provideSome_(self, f)
}
/**
* Provides a layer to the `Managed`, which translates it to another level.
*/
export function provideLayer<R2, R>(layer: L.Layer<R2, never, R>) {
return <E, I, L, Z>(self: Sink<R, E, I, L, Z>) => provideLayer_(self, layer)
}
/**
* Provides a layer to the `Managed`, which translates it to another level.
*/
export function provideLayer_<R, E, I, L, Z, R2>(
self: Sink<R, E, I, L, Z>,
layer: L.Layer<R2, never, R>
) {
return new Sink<R2, E, I, L, Z>(
M.chain_(L.build(layer), (r) =>
M.map_(
M.provideAll_(self.push, r),
(push) => (i: O.Option<A.Chunk<I>>) => T.provideAll_(push(i), r)
)
)
)
}
/**
* Splits the environment into two parts, providing one part using the
* specified layer and leaving the remainder `R0`.
*/
export function provideSomeLayer<R2, R>(layer: L.Layer<R2, never, R>) {
return <R0, E, I, L, Z>(self: Sink<R & R0, E, I, L, Z>): Sink<R0 & R2, E, I, L, Z> =>
provideLayer(layer["+++"](L.identity<R0>()))(self)
}
/**
* Creates a Sink from a managed `Push`
*/
export function managedPush<R, E, I, L, Z>(
push: M.Managed<R, never, Push.Push<R, E, I, L, Z>>
): Sink<R, E, I, L, Z> {
return new Sink(push)
}
/**
* Accesses the environment of the sink in the context of a sink.
*/
export function accessM<R, R2, E, I, L, Z>(
f: (r: R) => Sink<R2, E, I, L, Z>
): Sink<R & R2, E, I, L, Z> {
return new Sink(M.chain_(M.environment<R>(), (env) => f(env).push))
}
/**
* A sink that collects all of its inputs into an array.
*/
export function collectAll<A>(): Sink<unknown, never, A, never, A.Chunk<A>> {
return reduceLeftChunks(A.empty<A>())((s, i: A.Chunk<A>) => A.concat_(s, i))
}
/**
* A sink that collects all of its inputs into an list.
*/
export function collectAllToList<A>(): Sink<unknown, never, A, never, List.List<A>> {
return reduceLeftChunks(List.empty<A>())((s, i: A.Chunk<A>) =>
List.concat_(s, List.from(i))
)
}
/**
* A sink that collects all of its inputs into a map. The keys are extracted from inputs
* using the keying function `key`; if multiple inputs use the same key, they are merged
* using the `f` function.
*/
export function collectAllToMap<A, K>(key: (a: A) => K) {
return (f: (a: A, a1: A) => A): Sink<unknown, never, A, never, MP.Map<K, A>> =>
new Sink(
M.suspend(
() =>
reduceLeftChunks<Map<K, A>>(new Map())((acc, as: A.Chunk<A>) =>
A.reduce_(as, acc, (acc, a) => {
const k = key(a)
const v = acc.get(k)
return acc.set(k, v ? f(v, a) : a)
})
).push
)
)
}
/**
* A sink that collects all of its inputs into a set.
*/
export function collectAllToSet<A>(): Sink<unknown, never, A, never, Set<A>> {
return map_(collectAll<A>(), (as) => new Set(as))
}
/**
* A sink that counts the number of elements fed to it.
*/
export const count: Sink<unknown, never, unknown, never, number> = reduceLeft(0)(
(s, _) => s + 1
)
/**
* Creates a sink halting with the specified `Throwable`.
*/
export function die(e: unknown): Sink<unknown, never, unknown, never, never> {
return halt(C.die(e))
}
/**
* Creates a sink halting with the specified message, wrapped in a
* `RuntimeException`.
*/
export function dieMessage(m: string): Sink<unknown, never, unknown, never, never> {
return halt(C.die(new C.RuntimeError(m)))
}
/**
* A sink that ignores its inputs.
*/
export const drain: Sink<unknown, never, unknown, never, void> = dropLeftover(
forEach((_) => T.unit)
)
/**
* A sink that always fails with the specified error.
*/
export function fail<E>(e: E) {
return <I>(): Sink<unknown, E, I, I, never> =>
fromPush((c) => {
const leftover: A.Chunk<I> = O.fold_(
c,
() => A.empty(),
(x) => x
)
return Push.fail(e, leftover)
})
}
const reduceChunkGo = <S, I>(
s: S,
chunk: A.Chunk<I>,
idx: number,
len: number,
contFn: (s: S) => boolean,
f: (s: S, i: I) => S
): readonly [S, O.Option<A.Chunk<I>>] => {
if (idx === len) {
return [s, O.none] as const
} else {
const s1 = f(s, A.unsafeGet_(chunk, idx))
if (contFn(s1)) {
return reduceChunkGo(s1, chunk, idx + 1, len, contFn, f)
} else {
return [s1, O.some(A.drop_(chunk, idx + 1))] as const
}
}
}
/**
* A sink that folds its inputs with the provided function, termination predicate and initial state.
*/
export function reduce<S, I>(
z: S,
contFn: (s: S) => boolean,
f: (s: S, i: I) => S
): Sink<unknown, never, I, I, S> {
if (contFn(z)) {
return new Sink(
pipe(
M.do,
M.bind("state", () => T.toManaged(R.makeRef(z))),
M.map(
({ state }) =>
(is: O.Option<A.Chunk<I>>) =>
O.fold_(
is,
() => T.chain_(state.get, (s) => Push.emit(s, A.empty())),
(is) =>
T.chain_(state.get, (s) => {
const [st, l] = reduceChunkGo(s, is, 0, A.size(is), contFn, f)
return O.fold_(
l,
() => T.zipRight_(state.set(st), Push.more),
(leftover) => Push.emit(st, leftover)
)
})
)
)
)
)
} else {
return succeed(z)
}
}
/**
* A sink that folds its input chunks with the provided function, termination predicate and initial state.
* `contFn` condition is checked only for the initial value and at the end of processing of each chunk.
* `f` and `contFn` must preserve chunking-invariance.
*/
export function reduceChunks<Z>(z: Z) {
return (contFn: (s: Z) => boolean) =>
<I>(f: (s: Z, i: A.Chunk<I>) => Z): Sink<unknown, never, I, I, Z> =>
reduceChunksM(z)(contFn)((z, i: A.Chunk<I>) => T.succeed(f(z, i)))
}
/**
* A sink that effectfully folds its input chunks with the provided function, termination predicate and initial state.
* `contFn` condition is checked only for the initial value and at the end of processing of each chunk.
* `f` and `contFn` must preserve chunking-invariance.
*/
export function reduceChunksM<S>(z: S) {
return (contFn: (s: S) => boolean) =>
<R, E, I>(f: (a: S, i: A.Chunk<I>) => T.Effect<R, E, S>): Sink<R, E, I, I, S> => {
if (contFn(z)) {
return new Sink(
pipe(
M.do,
M.bind("state", () => T.toManaged(R.makeRef(z))),
M.map(({ state }) => {
return (is: O.Option<A.Chunk<I>>) =>
O.fold_(
is,
() => T.chain_(state.get, (s) => Push.emit(s, A.empty<I>())),
(is) =>
pipe(
state.get,
T.chain((_) => f(_, is)),
T.mapError((e) => Tp.tuple(E.left(e), A.empty<I>())),
T.chain((s) => {
if (contFn(s)) {
return T.zipRight_(state.set(s), Push.more)
} else {
return Push.emit(s, A.empty<I>())
}
})
)
)
})
)
)
} else {
return succeed(z)
}
}
}
function reduceMGo<R, E, S, I>(
s: S,
chunk: A.Chunk<I>,
idx: number,
len: number,
contFn: (s: S) => boolean,
f: (s: S, i: I) => T.Effect<R, E, S>
): T.Effect<R, readonly [E, A.Chunk<I>], readonly [S, O.Option<A.Chunk<I>>]> {
if (idx === len) {
return T.succeed([s, O.none] as const)
} else {
return T.foldM_(
f(s, A.unsafeGet_(chunk, idx)),
(e) => T.fail([e, A.drop_(chunk, idx + 1)] as const),
(s1) =>
contFn(s1)
? reduceMGo(s1, chunk, idx + 1, len, contFn, f)
: T.succeed([s1, O.some(A.drop_(chunk, idx + 1))])
)
}
}
/**
* A sink that effectfully folds its inputs with the provided function, termination predicate and initial state.
*
* This sink may terminate in the middle of a chunk and discard the rest of it. See the discussion on the
* ZSink class scaladoc on sinks vs. transducers.
*/
export function reduceM<S, R, E, I>(
z: S,
contFn: (s: S) => boolean,
f: (s: S, i: I) => T.Effect<R, E, S>
): Sink<R, E, I, I, S> {
if (contFn(z)) {
return new Sink(
pipe(
M.do,
M.bind("state", () => T.toManaged(R.makeRef(z))),
M.map(
({ state }) =>
(is: O.Option<A.Chunk<I>>) =>
O.fold_(
is,
() => T.chain_(state.get, (s) => Push.emit(s, A.empty())),
(is) =>
T.chain_(state.get, (s) =>
T.foldM_(
reduceMGo(s, is, 0, A.size(is), contFn, f),
(err) => Push.fail(...err),
([st, l]) =>
O.fold_(
l,
() => T.zipRight_(state.set(st), Push.more),
(leftover) => Push.emit(st, leftover)
)
)
)
)
)
)
)
} else {
return succeed(z)
}
}
/**
* A sink that folds its inputs with the provided function and initial state.
*/
export function reduceLeft<S>(z: S) {
return <I>(f: (s: S, i: I) => S): Sink<unknown, never, I, never, S> =>
dropLeftover(reduce(z, (_) => true, f))
}
/**
* A sink that folds its input chunks with the provided function and initial state.
* `f` must preserve chunking-invariance.
*/
export function reduceLeftChunks<S>(z: S) {
return <I>(f: (s: S, i: A.Chunk<I>) => S): Sink<unknown, never, I, never, S> =>
dropLeftover(reduceChunks(z)(() => true)(f))
}
/**
* A sink that effectfully folds its input chunks with the provided function and initial state.
* `f` must preserve chunking-invariance.
*/
export function reduceLeftChunksM<S>(z: S) {
return <R, E, I>(
f: (s: S, i: A.Chunk<I>) => T.Effect<R, E, S>
): Sink<R, E, I, never, S> => dropLeftover(reduceChunksM(z)((_) => true)(f))
}
/**
* A sink that effectfully folds its inputs with the provided function and initial state.
*/
export function reduceLeftM<S>(z: S) {
return <R, E, I>(f: (s: S, i: I) => T.Effect<R, E, S>): Sink<R, E, I, never, S> =>
dropLeftover(reduceM(z, (_) => true, f))
}
function forEachGo<I, R1, E1, X>(
chunk: A.Chunk<I>,
idx: number,
len: number,
f: (i: I) => T.Effect<R1, E1, X>
): T.Effect<R1, Tp.Tuple<[E.Either<E1, never>, A.Chunk<I>]>, void> {
if (idx === len) {
return Push.more
} else {
return pipe(
f(A.unsafeGet_(chunk, idx)),
T.foldM(
(e) => Push.fail(e, A.drop_(chunk, idx + 1)),
() => forEachGo(chunk, idx + 1, len, f)
)
)
}
}
/**
* A sink that executes the provided effectful function for every element fed to it.
*/
export function forEach<I, R1, E1, X>(f: (i: I) => T.Effect<R1, E1, X>) {
return fromPush(
O.fold(
() => Push.emit<never, void>(undefined, A.empty()),
(is: A.Chunk<I>) => forEachGo(is, 0, A.size(is), f)
)
)
}
/**
* A sink that executes the provided effectful function for every chunk fed to it.
*/
export function forEachChunk<R, E, I, X>(
f: (a: A.Chunk<I>) => T.Effect<R, E, X>
): Sink<R, E, I, never, void> {
return fromPush((in_: O.Option<A.Chunk<I>>) =>
O.fold_(
in_,
() => Push.emit<never, void>(undefined, A.empty()),
(is) =>
T.zipRight_(
T.mapError_(f(is), (e) => Tp.tuple(E.left(e), A.empty())),
Push.more
)
)
)
}
/**
* A sink that executes the provided effectful function for every element fed to it
* until `f` evaluates to `false`.
*/
export function forEachWhile<R, E, I>(
f: (i: I) => T.Effect<R, E, boolean>
): Sink<R, E, I, I, void> {
const go = (
chunk: A.Chunk<I>,
idx: number,
len: number
): T.Effect<R, Tp.Tuple<[E.Either<E, void>, A.Chunk<I>]>, void> => {
if (idx === len) {
return Push.more
} else {
return T.foldM_(
f(A.unsafeGet_(chunk, idx)),
(e) => Push.fail(e, A.drop_(chunk, idx + 1)),
(b) => {
if (b) {
return go(chunk, idx + 1, len)
} else {
return Push.emit<I, void>(undefined, A.drop_(chunk, idx))
}
}
)
}
}
return fromPush((in_: O.Option<A.Chunk<I>>) =>
O.fold_(
in_,
() => Push.emit<never, void>(undefined, A.empty()),
(is) => go(is, 0, A.size(is))
)
)
}
/**
* Creates a single-value sink produced from an effect
*/
export function fromEffect<R, E, Z>(b: T.Effect<R, E, Z>) {
return <I>(): Sink<R, E, I, I, Z> =>
fromPush<R, E, I, I, Z>((in_: O.Option<A.Chunk<I>>) => {
const leftover = O.fold_(in_, () => A.empty<I>(), identity)
return T.foldM_(
b,
(e) => Push.fail(e, leftover),
(z) => Push.emit(z, leftover)
)
})
}
/**
* Creates a sink from a Push
*/
export function fromPush<R, E, I, L, Z>(push: Push.Push<R, E, I, L, Z>) {
return new Sink(M.succeed(push))
}
/**
* Creates a sink halting with a specified cause.
*/
export function halt<E>(e: C.Cause<E>): Sink<unknown, E, unknown, never, never> {
return fromPush((_) => Push.halt(e))
}
/**
* Creates a sink containing the first value.
*/
export function head<I>(): Sink<unknown, never, I, I, O.Option<I>> {
return new Sink(
M.succeed((in_: O.Option<A.Chunk<I>>) =>
O.fold_(
in_,
() => Push.emit(O.none, A.empty()),
(ch) => (A.isEmpty(ch) ? Push.more : Push.emit(A.head(ch), A.empty()))
)
)
)
}
/**
* Creates a sink containing the last value.
*/
export function last<I>(): Sink<unknown, never, I, never, O.Option<I>> {
return new Sink(
pipe(
M.do,
M.bind("state", () => T.toManaged(R.makeRef<O.Option<I>>(O.none))),
M.map(
({ state }) =>
(is: O.Option<A.Chunk<I>>) =>
T.chain_(state.get, (last) =>
O.fold_(
is,
() => Push.emit(last, A.empty()),
(ch) =>
O.fold_(
A.last(ch),
() => Push.more,
(l) => T.zipRight_(state.set(O.some(l)), Push.more)
)
)
)
)
)
)
}
/**
* A sink that depends on another managed value
* `resource` will be finalized after the processing.
*
* @deprecated Use unwrapManaged
*/
export function managed_<R, E, A, I, L extends I, Z>(
resource: M.Managed<R, E, A>,
fn: (a: A) => Sink<R, E, I, L, Z>
) {
return M.chain_(
M.fold_(
resource,
(err) => fail(err)<I>() as Sink<R, E, I, I, Z>,
(m) => fn(m)
),
(_) => _.push
)
}
/**
* A sink that depends on another managed value
* `resource` will be finalized after the processing.
*
* @deprecated Use unwrapManaged
*/
export function managed<R, E, A>(resource: M.Managed<R, E, A>) {
return <I, L extends I, Z>(fn: (a: A) => Sink<R, E, I, L, Z>) =>
managed_(resource, fn)
}
/**
* A sink that immediately ends with the specified value.
*/
export function succeed<Z, I>(z: Z): Sink<unknown, never, I, I, Z> {
return fromPush<unknown, never, I, I, Z>((c) => {
const leftover = O.fold_(
c,
() => A.empty<I>(),
(x) => x
)
return Push.emit(z, leftover)
})
}
/**
* A sink that sums incoming numeric values.
*/
export const sum: Sink<unknown, never, number, never, number> = reduceLeft(0)(
(a, b) => a + b
)
/**
* A sink that takes the specified number of values.
*/
export function take<I>(n: number): Sink<unknown, never, I, I, A.Chunk<I>> {
return new Sink(
pipe(
M.do,
M.bind("state", () => T.toManaged(R.makeRef<A.Chunk<I>>(A.empty()))),
M.map(({ state }) => {
return (is: O.Option<A.Chunk<I>>) =>
T.chain_(state.get, (take) =>
O.fold_(
is,
() => {
if (n >= 0) {
return Push.emit(take, A.empty() as A.Chunk<I>)
} else {
return Push.emit(A.empty(), take)
}
},
(ch) => {
const remaining = n - A.size(take)
if (remaining <= A.size(ch)) {
const {
tuple: [chunk, leftover]
} = A.splitAt_(ch, remaining)
return T.zipRight_(
state.set(A.empty()),
Push.emit(A.concat_(take, chunk), leftover)
)
} else {
return T.zipRight_(state.set(A.concat_(take, ch)), Push.more)
}
}
)
)
})
)
)
}
/**
* A sink with timed execution.
*/
export const timedDrain: Sink<HasClock, never, unknown, never, number> = map_(
timed(drain),
(_) => _.get(1)
)
/**
* A sink that executes the provided effectful function for every chunk fed to it.
*/
export function foreachChunk<R, E, I, A>(
f: (c: A.Chunk<I>) => T.Effect<R, E, A>
): Sink<R, E, I, never, void> {
return fromPush((o) =>
O.fold_(
o,
() => Push.emit(undefined, A.empty<never>()),
(is) =>
pipe(
f(is),
T.mapError((e) => Tp.tuple(E.left(e), A.empty<never>())),
T.zipRight(Push.more)
)
)
)
}
/**
* Create a sink which enqueues each element into the specified queue.
*/
export function fromQueue<R, E, I, A>(
queue: Q.XQueue<R, never, E, unknown, I, A>
): Sink<R, E, I, never, void> {
return forEachChunk((x) => Q.offerAll_(queue, x))
}
/**
* Create a sink which enqueues each element into the specified queue.
* The queue will be shutdown once the stream is closed.
*/
export function fromQueueWithShutdown<R, E, I, A>(
queue: Q.XQueue<R, never, E, unknown, I, A>
): Sink<R, E, I, never, void> {
return new Sink(
pipe(
M.make_(T.succeed(queue), Q.shutdown),
M.map(fromQueue),
M.chain((_) => _.push)
)
)
}
/**
* Create a sink which publishes each element to the specified hub.
*/
export function fromHub<R, E, I, A>(
hub: H.XHub<R, never, E, unknown, I, A>
): Sink<R, E, I, never, void> {
return fromQueue(H.toQueue(hub))
}
/**
* Create a sink which publishes each element to the specified hub.
* The hub will be shutdown once the stream is closed.
*/
export function fromHubWithShutdown<R, E, I, A>(
hub: H.XHub<R, never, E, unknown, I, A>
): Sink<R, E, I, never, void> {
return fromQueueWithShutdown(H.toQueue(hub))
}
/**
* Creates a sink produced from an effect.
*/
export function unwrap<R, E, I, L extends I, Z>(
effect: T.Effect<R, E, Sink<R, E, I, L, Z>>
): Sink<R, E, I, I, Z> {
return unwrapManaged(T.toManaged(effect))
}
/**
* Creates a sink produced from a managed effect.
*/
export function unwrapManaged<R, E, I, L extends I, Z>(
managed: M.Managed<R, E, Sink<R, E, I, L, Z>>
): Sink<R, E, I, I, Z> {
return new Sink(
M.chain_(
M.fold_(
managed,
(err): Sink<R, E, I, I, Z> => fail<E>(err)<I>(),
(_) => _
),
(_) => _.push
)
)
} | the_stack |
import SeriesData from '@/src/data/SeriesData';
import Model from '@/src/model/Model';
import { createSourceFromSeriesDataOption, Source, createSource } from '@/src/data/Source';
import { OptionDataItemObject,
OptionDataValue,
SOURCE_FORMAT_ARRAY_ROWS,
SOURCE_FORMAT_ORIGINAL } from '@/src/util/types';
import SeriesDimensionDefine from '@/src/data/SeriesDimensionDefine';
import OrdinalMeta from '@/src/data/OrdinalMeta';
import DataStore from '@/src/data/DataStore';
import { DefaultDataProvider } from '@/src/data/helper/dataProvider';
import { SeriesDataSchema } from '@/src/data/helper/SeriesDataSchema';
const ID_PREFIX = 'e\0\0';
const NAME_REPEAT_PREFIX = '__ec__';
describe('SeriesData', function () {
describe('Data Manipulation', function () {
it('initData 1d', function () {
const data = new SeriesData(['x', 'y'], new Model());
data.initData([10, 20, 30]);
expect(data.get('x', 0)).toEqual(10);
expect(data.get('x', 1)).toEqual(20);
expect(data.get('x', 2)).toEqual(30);
expect(data.get('y', 1)).toEqual(20);
});
it('initData 2d', function () {
const data = new SeriesData(['x', 'y'], new Model());
data.initData([[10, 15], [20, 25], [30, 35]]);
expect(data.get('x', 1)).toEqual(20);
expect(data.get('y', 1)).toEqual(25);
});
it('initData 2d yx', function () {
const data = new SeriesData(['y', 'x'], new Model());
data.initData([[10, 15], [20, 25], [30, 35]]);
expect(data.get('x', 1)).toEqual(25);
expect(data.get('y', 1)).toEqual(20);
});
it('Data with option 1d', function () {
const data = new SeriesData(['x', 'y'], new Model());
data.initData([
1,
{
value: 2,
somProp: 'foo'
} as OptionDataItemObject<OptionDataValue>
]);
expect(data.getItemModel(1).get('somProp' as any)).toEqual('foo');
expect(data.getItemModel(0).get('somProp' as any)).toBeNull();
});
it('Empty data', function () {
const data = new SeriesData(['x', 'y'], new Model());
data.initData([1, '-']);
expect(data.get('y', 1)).toBeNaN();
});
it('getRawValue', function () {
const data1 = new SeriesData(['x', 'y'], new Model());
// here construct a new data2 because if we only use one data
// to call initData() twice, data._chunkCount will be accumulated
// to 1 instead of 0.
const data2 = new SeriesData(['x', 'y'], new Model());
data1.initData([1, 2, 3]);
expect(data1.getItemModel(1).option).toEqual(2);
data2.initData([[10, 15], [20, 25], [30, 35]]);
expect(data2.getItemModel(1).option).toEqual([20, 25]);
});
it('indexOfRawIndex', function () {
const data = new SeriesData(['x'], new Model());
data.initData([]);
expect(data.indexOfRawIndex(1)).toEqual(-1);
const data1 = new SeriesData(['x'], new Model());
data1.initData([0]);
expect(data1.indexOfRawIndex(0)).toEqual(0);
expect(data1.indexOfRawIndex(1)).toEqual(-1);
const data2 = new SeriesData(['x'], new Model());
data2.initData([0, 1, 2, 3]);
expect(data2.indexOfRawIndex(1)).toEqual(1);
expect(data2.indexOfRawIndex(2)).toEqual(2);
expect(data2.indexOfRawIndex(5)).toEqual(-1);
const data3 = new SeriesData(['x'], new Model());
data3.initData([0, 1, 2, 3, 4]);
expect(data3.indexOfRawIndex(2)).toEqual(2);
expect(data3.indexOfRawIndex(3)).toEqual(3);
expect(data3.indexOfRawIndex(5)).toEqual(-1);
data3.filterSelf(function (idx) {
return idx >= 2;
});
expect(data3.indexOfRawIndex(2)).toEqual(0);
});
it('getDataExtent', function () {
const data = new SeriesData(['x', 'y'], new Model());
data.initData([1, 2, 3]);
expect(data.getDataExtent('x')).toEqual([1, 3]);
expect(data.getDataExtent('y')).toEqual([1, 3]);
});
it('Data types', function () {
const data = new SeriesData([{
name: 'x',
type: 'int'
}, {
name: 'y',
type: 'float'
}], new Model());
data.initData([[1.1, 1.1]]);
expect(data.get('x', 0)).toEqual(1);
expect(data.get('y', 0)).toBeCloseTo(1.1, 5);
});
it('map', function () {
const data = new SeriesData(['x', 'y'], new Model());
data.initData([[10, 15], [20, 25], [30, 35]]);
expect(data.map(['x', 'y'], function (x: number, y: number) {
return [x + 2, y + 2];
}).mapArray('x', function (x) {
return x;
})).toEqual([12, 22, 32]);
});
it('mapArray', function () {
const data = new SeriesData(['x', 'y'], new Model());
data.initData([[10, 15], [20, 25], [30, 35]]);
expect(data.mapArray(['x', 'y'], function (x, y) {
return [x, y];
})).toEqual([[10, 15], [20, 25], [30, 35]]);
});
it('filterSelf', function () {
const data = new SeriesData(['x', 'y'], new Model());
data.initData([[10, 15], [20, 25], [30, 35]]);
expect(data.filterSelf(['x', 'y'], function (x, y) {
return x < 30 && x > 10;
}).mapArray('x', function (x) {
return x;
})).toEqual([20]);
});
it('dataProvider', function () {
const data = new SeriesData(['x', 'y'], new Model());
const typedArray = new Float32Array([10, 10, 20, 20]);
const source = createSourceFromSeriesDataOption(typedArray);
data.initData({
count: function (): number {
return typedArray.length / 2;
},
getItem: function (idx: number): number[] {
return [typedArray[idx * 2], typedArray[idx * 2 + 1]];
},
getSource: function (): Source {
return source;
}
});
expect(data.mapArray(['x', 'y'], function (x, y) {
return [x, y];
})).toEqual([[10, 10], [20, 20]]);
expect(data.getRawDataItem(0)).toEqual([10, 10]);
expect(data.getItemModel(0).option).toEqual([10, 10]);
});
});
describe('Data store', function () {
it('should guess ordinal correctly', function () {
const source = createSource([['A', 15], ['B', 25], ['C', 35]], {
dimensions: ['A', 'B'],
seriesLayoutBy: null,
sourceHeader: false
}, SOURCE_FORMAT_ORIGINAL);
expect(source.dimensionsDefine[0].type).toEqual('ordinal');
});
function createStore() {
const provider = new DefaultDataProvider([['A', 15], ['B', 25], ['C', 35]]);
const store = new DataStore();
store.initData(provider, [{type: 'ordinal'}, {type: 'float'}]);
return store;
}
it('SeriesData can still get other dims value from store when only part of dims are given.', function () {
const source = createSource(
[['A', 15, 20, 'cat'], ['B', 25, 30, 'mouse'], ['C', 35, 40, 'dog']],
{
dimensions: null,
seriesLayoutBy: null,
sourceHeader: false
},
SOURCE_FORMAT_ARRAY_ROWS
);
const store = new DataStore();
store.initData(new DefaultDataProvider(source), [
{type: 'ordinal'}, {type: 'float'}, {type: 'float'}, {type: 'ordinal'}
]);
const schema = new SeriesDataSchema({
source: source,
dimensions: [
{ type: 'float', name: 'dim1', storeDimIndex: 1 },
{ type: 'ordinal', name: 'dim3', storeDimIndex: 3 }
],
fullDimensionCount: 2,
dimensionOmitted: true
});
const data = new SeriesData(schema, null);
data.initData(store);
// Store should be the same.
expect(data.getStore()).toBe(store);
// Get self dim
expect(data.get('dim1', 0)).toEqual(15);
expect(data.get('dim1', 1)).toEqual(25);
// Get other dim
expect(data.getStore().get(0, 0)).toEqual('A');
expect(data.getStore().get(0, 1)).toEqual('B');
expect(data.getStore().get(2, 0)).toEqual(20);
expect(data.getStore().get(2, 1)).toEqual(30);
// Get all
expect(data.getValues(['dim3', 'dim1'], 0)).toEqual(['cat', 15]);
expect(data.getValues(1)).toEqual(['B', 25, 30, 'mouse']);
});
it('SeriesData#cloneShallow should share store', function () {
const store = createStore();
const dims = [{ type: 'float', name: 'dim2' }];
const data = new SeriesData(dims, null);
data.initData(store);
const data2 = data.cloneShallow();
expect(data2.getStore()).toBe(data.getStore());
});
});
describe('Data read', function () {
it('indicesOfNearest', function () {
const data = new SeriesData(['value'], new Model());
// ---- index: 0 1 2 3 4 5 6 7
data.initData([10, 20, 30, 35, 40, 40, 35, 50]);
expect(data.indicesOfNearest('value', 24.5)).toEqual([1]);
expect(data.indicesOfNearest('value', 25)).toEqual([1]);
expect(data.indicesOfNearest('value', 25.5)).toEqual([2]);
expect(data.indicesOfNearest('value', 25.5)).toEqual([2]);
expect(data.indicesOfNearest('value', 41)).toEqual([4, 5]);
expect(data.indicesOfNearest('value', 39)).toEqual([4, 5]);
expect(data.indicesOfNearest('value', 41)).toEqual([4, 5]);
expect(data.indicesOfNearest('value', 36)).toEqual([3, 6]);
expect(data.indicesOfNearest('value', 50.6, 0.5)).toEqual([]);
expect(data.indicesOfNearest('value', 50.5, 0.5)).toEqual([7]);
});
});
describe('id_and_name', function () {
function makeOneByOneChecker(list: SeriesData) {
let getIdDataIndex = 0;
let getNameDataIndex = 0;
return {
nextIdEqualsTo: function (expectedId: string): void {
expect(list.getId(getIdDataIndex)).toEqual(expectedId);
getIdDataIndex++;
},
nextNameEqualsTo: function (expectedName: string): void {
expect(list.getName(getNameDataIndex)).toEqual(expectedName);
getNameDataIndex++;
},
currGetIdDataIndex: function (): number {
return getIdDataIndex;
},
currGetNameDataIndex: function (): number {
return getNameDataIndex;
}
};
}
describe('only_name_declared', function () {
function doChecks(list: SeriesData) {
const oneByOne = makeOneByOneChecker(list);
oneByOne.nextIdEqualsTo('a');
oneByOne.nextIdEqualsTo('b');
oneByOne.nextIdEqualsTo(`b${NAME_REPEAT_PREFIX}2`);
oneByOne.nextIdEqualsTo('c');
oneByOne.nextIdEqualsTo(`${ID_PREFIX}4`);
oneByOne.nextIdEqualsTo(`c${NAME_REPEAT_PREFIX}2`);
oneByOne.nextIdEqualsTo('d');
oneByOne.nextIdEqualsTo(`c${NAME_REPEAT_PREFIX}3`);
oneByOne.nextNameEqualsTo('a');
oneByOne.nextNameEqualsTo('b');
oneByOne.nextNameEqualsTo('b');
oneByOne.nextNameEqualsTo('c');
oneByOne.nextNameEqualsTo('');
oneByOne.nextNameEqualsTo('c');
oneByOne.nextNameEqualsTo('d');
oneByOne.nextNameEqualsTo('c');
}
it('sourceFormatOriginal', function () {
const list = new SeriesData(['x', 'y'], new Model());
list.initData([
{ value: 10, name: 'a' },
{ value: 20, name: 'b' },
{ value: 30, name: 'b' },
{ value: 40, name: 'c' },
{ value: 50 }, // name not declared
{ value: 60, name: 'c' },
{ value: 70, name: 'd' },
{ value: 80, name: 'c' }
]);
doChecks(list);
});
it('sourceFormatArrayRows', function () {
const list = new SeriesData(
[
'x',
{ name: 'q', type: 'ordinal', otherDims: { itemName: 0 } }
],
new Model()
);
const source = createSource(
[
[ 10, 'a' ],
[ 20, 'b' ],
[ 30, 'b' ],
[ 40, 'c' ],
[ 50, null ],
[ 60, 'c' ],
[ 70, 'd' ],
[ 80, 'c' ]
],
{
seriesLayoutBy: 'column',
sourceHeader: 0,
dimensions: null
},
SOURCE_FORMAT_ARRAY_ROWS
);
list.initData(source);
doChecks(list);
});
});
describe('id_name_declared_sourceFormat_original', function () {
it('sourceFormatOriginal', function () {
const list = new SeriesData(['x'], new Model());
const oneByOne = makeOneByOneChecker(list);
list.initData([
{ value: 0, id: 'myId_10' },
{ value: 10, id: 555 }, // numeric id.
{ value: 20, id: '666%' },
{ value: 30, id: 'myId_good', name: 'b' },
{ value: 40, name: 'b' },
{ value: 50, id: null },
{ value: 60, id: undefined },
{ value: 70, id: NaN },
{ value: 80, id: '' },
{ value: 90, name: 'b' },
{ value: 100 },
{ value: 110, id: 'myId_better' },
{ value: 120, id: 'myId_better' } // duplicated id.
]);
oneByOne.nextIdEqualsTo('myId_10');
oneByOne.nextIdEqualsTo('555');
oneByOne.nextIdEqualsTo('666%');
oneByOne.nextIdEqualsTo('myId_good');
oneByOne.nextIdEqualsTo('b');
oneByOne.nextIdEqualsTo(`${ID_PREFIX}${oneByOne.currGetIdDataIndex()}`);
oneByOne.nextIdEqualsTo(`${ID_PREFIX}${oneByOne.currGetIdDataIndex()}`);
oneByOne.nextIdEqualsTo('NaN');
oneByOne.nextIdEqualsTo('');
oneByOne.nextIdEqualsTo(`b${NAME_REPEAT_PREFIX}2`);
oneByOne.nextIdEqualsTo(`${ID_PREFIX}${oneByOne.currGetIdDataIndex()}`);
oneByOne.nextIdEqualsTo('myId_better');
oneByOne.nextIdEqualsTo('myId_better');
oneByOne.nextNameEqualsTo('');
oneByOne.nextNameEqualsTo('');
oneByOne.nextNameEqualsTo('');
oneByOne.nextNameEqualsTo('b');
oneByOne.nextNameEqualsTo('b');
oneByOne.nextNameEqualsTo('');
oneByOne.nextNameEqualsTo('');
oneByOne.nextNameEqualsTo('');
oneByOne.nextNameEqualsTo('');
oneByOne.nextNameEqualsTo('b');
oneByOne.nextNameEqualsTo('');
oneByOne.nextNameEqualsTo('');
oneByOne.nextNameEqualsTo('');
list.appendData([
{ value: 200, id: 'myId_best' },
{ value: 210, id: 999 }, // numeric id.
{ value: 220, id: '777px' },
{ value: 230, name: 'b' },
{ value: 240 }
]);
oneByOne.nextIdEqualsTo('myId_best');
oneByOne.nextIdEqualsTo('999');
oneByOne.nextIdEqualsTo('777px');
oneByOne.nextIdEqualsTo(`b${NAME_REPEAT_PREFIX}3`);
oneByOne.nextIdEqualsTo(`${ID_PREFIX}${oneByOne.currGetIdDataIndex()}`);
oneByOne.nextNameEqualsTo('');
oneByOne.nextNameEqualsTo('');
oneByOne.nextNameEqualsTo('');
oneByOne.nextNameEqualsTo('b');
oneByOne.nextNameEqualsTo('');
list.appendValues([], ['b', 'c', null]);
oneByOne.nextIdEqualsTo(`b${NAME_REPEAT_PREFIX}4`);
oneByOne.nextIdEqualsTo('c');
oneByOne.nextIdEqualsTo(`${ID_PREFIX}${oneByOne.currGetIdDataIndex()}`);
oneByOne.nextNameEqualsTo('b');
oneByOne.nextNameEqualsTo('c');
oneByOne.nextNameEqualsTo('');
});
});
describe('id_name_declared_sourceFormat_arrayRows', function () {
it('no_ordinalMeta', function () {
testArrayRowsInSource([
{ name: 'x', type: 'number' },
{ name: 'p', type: 'ordinal', otherDims: { itemId: 0 } },
{ name: 'q', type: 'ordinal', otherDims: { itemName: 0 } }
]);
});
it('has_ordinalMeta', function () {
const ordinalMetaP = new OrdinalMeta({
categories: [],
needCollect: true,
deduplication: true
});
const ordinalMetaQ = new OrdinalMeta({
categories: [],
needCollect: true,
deduplication: true
});
testArrayRowsInSource([
{ name: 'x', type: 'number' },
{ name: 'p', type: 'ordinal', otherDims: { itemId: 0 }, ordinalMeta: ordinalMetaP },
{ name: 'q', type: 'ordinal', otherDims: { itemName: 0 }, ordinalMeta: ordinalMetaQ }
]);
});
function testArrayRowsInSource(dimensionsInfo: SeriesDimensionDefine[]): void {
const list = new SeriesData(dimensionsInfo, new Model());
const oneByOne = makeOneByOneChecker(list);
const source = createSource(
[
[0, 'myId_10', null],
[10, 555, null], // numeric id.
[20, '666%', null],
[30, 'myId_good', 'b'],
[40, null, 'b'],
[50, null, null],
[60, undefined, null],
[70, NaN, null],
[80, '', null],
[90, null, 'b'],
[100, null, null],
[110, 'myId_better', null],
[120, 'myId_better', null] // duplicated id.
],
{
seriesLayoutBy: 'column',
sourceHeader: 0,
dimensions: null
},
SOURCE_FORMAT_ARRAY_ROWS
);
list.initData(source);
oneByOne.nextIdEqualsTo('myId_10');
oneByOne.nextIdEqualsTo('555');
oneByOne.nextIdEqualsTo('666%');
oneByOne.nextIdEqualsTo('myId_good');
oneByOne.nextIdEqualsTo(`${ID_PREFIX}${oneByOne.currGetIdDataIndex()}`);
oneByOne.nextIdEqualsTo(`${ID_PREFIX}${oneByOne.currGetIdDataIndex()}`);
oneByOne.nextIdEqualsTo(`${ID_PREFIX}${oneByOne.currGetIdDataIndex()}`);
oneByOne.nextIdEqualsTo('NaN');
oneByOne.nextIdEqualsTo('');
oneByOne.nextIdEqualsTo(`${ID_PREFIX}${oneByOne.currGetIdDataIndex()}`);
oneByOne.nextIdEqualsTo(`${ID_PREFIX}${oneByOne.currGetIdDataIndex()}`);
oneByOne.nextIdEqualsTo('myId_better');
oneByOne.nextIdEqualsTo('myId_better');
oneByOne.nextNameEqualsTo('');
oneByOne.nextNameEqualsTo('');
oneByOne.nextNameEqualsTo('');
oneByOne.nextNameEqualsTo('b');
oneByOne.nextNameEqualsTo('b');
oneByOne.nextNameEqualsTo('');
oneByOne.nextNameEqualsTo('');
oneByOne.nextNameEqualsTo('');
oneByOne.nextNameEqualsTo('');
oneByOne.nextNameEqualsTo('b');
oneByOne.nextNameEqualsTo('');
oneByOne.nextNameEqualsTo('');
oneByOne.nextNameEqualsTo('');
list.appendData([
[ 200, 'myId_best', null ],
[ 210, 999, null ], // numeric id.
[ 220, '777px', null],
[ 230, null, 'b' ],
[ 240, null, null ]
]);
oneByOne.nextIdEqualsTo('myId_best');
oneByOne.nextIdEqualsTo('999');
oneByOne.nextIdEqualsTo('777px');
oneByOne.nextIdEqualsTo(`${ID_PREFIX}${oneByOne.currGetIdDataIndex()}`);
oneByOne.nextIdEqualsTo(`${ID_PREFIX}${oneByOne.currGetIdDataIndex()}`);
oneByOne.nextNameEqualsTo('');
oneByOne.nextNameEqualsTo('');
oneByOne.nextNameEqualsTo('');
oneByOne.nextNameEqualsTo('b');
oneByOne.nextNameEqualsTo('');
list.appendValues([], ['b', 'c', null]);
oneByOne.nextIdEqualsTo(`${ID_PREFIX}${oneByOne.currGetIdDataIndex()}`);
oneByOne.nextIdEqualsTo(`${ID_PREFIX}${oneByOne.currGetIdDataIndex()}`);
oneByOne.nextIdEqualsTo(`${ID_PREFIX}${oneByOne.currGetIdDataIndex()}`);
oneByOne.nextNameEqualsTo('b');
oneByOne.nextNameEqualsTo('c');
oneByOne.nextNameEqualsTo('');
}
});
});
}); | the_stack |
import { Button } from 'amis'
import { uuid } from 'amis/lib/utils/helper'
import { get, map, omit, find } from 'lodash'
import React, { useEffect, useRef } from 'react'
import { app } from '@core/app'
import { Amis } from '@core/components/amis/schema'
import { useImmer } from '@core/utils/hooks'
import { emptyListHolder } from '~/app/constants'
import saveFile from '~/assets/savefile'
import PopOver from '~/components/popover'
import ScrollBar from '~/components/scroll_bar'
import apis from './apis'
import * as S from './styled'
import * as utils from './utils'
const getColumns = (tableInfo: any) => {
const { fields = [], isSearchMode = false, isViewMode = false } = tableInfo
let items = fields
if (isSearchMode) {
items = items.filter((item) => get(item, 'meta.searchable'))
}
const columns = map(items, (field: any) => {
const { id: name, type = 'text', name: label, ...rest } = field
const editType = get(rest, 'editStyle.type') || 'text'
let column: any = {}
let searchInfo: any = {}
switch (editType) {
case 'url':
column = {
type: 'tpl',
tpl: `
<% if (data[${name}]) {%>
<a class="text-truncate d-inline-block" title="<%= data[${name}] %>"
style="${
isViewMode ? '' : 'width:150px;'
}" target="_blank" href="<%= data[${name}] %>"><%= data[${name}] %></a>
<%} else {%>
-
<%}%>`,
}
break
case 'file':
column = {
isViewMode,
type: 'container',
body: {
component: (props) => {
const fileUrl = props.data[name] || ''
return !fileUrl ? (
'-'
) : (
<S.FileItem>
{isViewMode && <span className="m-r-md">{fileUrl}</span>}
<span className="file-actions">
<i
className="fa fa-copy"
data-tooltip="复制链接"
onClick={() => props.env.copy(fileUrl)}
/>
<i
className="fa fa-download m-l-sm"
data-tooltip="下载文件"
onClick={() => saveFile(fileUrl, `${label}-${uuid()}`)}
/>
</span>
</S.FileItem>
)
},
},
}
break
case 'image':
column = {
type: 'image',
className: 'table-cell-image',
thumbMode: 'cover',
enlargeAble: true,
}
break
case 'switch':
column = {
type: 'mapping',
isViewMode,
map: {
'0': '<span class=\'label bg-secondary\'>否</span>',
'1': '<span class=\'label label-info\'>是</span>',
},
}
searchInfo.type = 'boolean'
break
case 'checkboxes':
column = {
name,
type: 'each',
isViewMode,
items: {
type: 'tpl',
tpl: '<span class=\'label label-default m-l-sm\'><%= data.item %></span> ',
},
}
searchInfo = {
type: 'select',
searchable: true,
options: rest.editStyle.options,
}
break
case 'date':
case 'datetime':
case 'time':
searchInfo.type = editType
break
case 'month':
case 'year':
searchInfo.type = 'date'
break
case 'number':
searchInfo.type = 'number'
break
default:
}
column = {
name,
label,
type,
fieldExtra: {
...rest,
searchInfo,
},
toggled: true,
sortable: get(rest, 'meta.sortable'),
...column,
}
return column
})
const dateTimeField = {
toggled: false,
sortable: true,
// searchable: true,
fieldExtra: {
editStyle: {
type: 'datetime',
},
},
}
const tableColumns = [
{
name: 'id',
label: 'ID',
type: 'text',
sortable: true,
toggled: true,
} as any,
].concat(columns, [
{
name: 'addTime',
label: '添加时间',
type: 'text',
width: 160,
toggled: false,
...dateTimeField,
},
{
name: 'updateTime',
label: '更新时间',
width: 160,
type: 'text',
toggled: false,
...dateTimeField,
},
])
return tableColumns
}
const getAdvanceQueryForm = (info) => {
const columns = getColumns({
...info,
isSearchMode: true,
})
const fields = columns.map((field) => {
const { name, label, fieldExtra = {} } = field
const filedInfo: any = {
name,
label,
type: 'text',
...fieldExtra.searchInfo,
}
return filedInfo
})
// let formRef: any = {}
const advanceQueryForm = {
type: 'form',
title: '',
mode: 'normal',
// horizontal: { left: 'col-sm-2', right: 'col-sm-10' },
target: 'modelDataTable',
// onInit: (...args: any[]) => {
// formRef = args[1]
// },
controls: [
{
type: 'group',
controls: [
getSearchLogSchema('select', {
...info,
props: {
label: '查询列表',
mode: 'inline',
className: 'm-b-sm',
},
}),
{
type: 'container',
body: {
type: 'action',
actionType: 'clear',
icon: 'fa fa-remove pull-left text-error',
label: '清空条件',
disabledOn: 'data.searchLog',
onClick: () => {
//
},
// onAction: (...args: any[]) => {
// // formRef.store.setInited({})
// formRef.store.setValueByName('searchLog', '')
// // const names = ['searchLog', 'label1', 'label2', 'conditions']
// // names.forEach((name) => {
// // })
// },
},
},
],
},
{
type: 'hidden',
name: 'id',
},
{
type: 'group',
mode: 'inline',
controls: [
{
type: 'text',
name: 'label1',
inputClassName: 'w-md',
label: '查询名称',
placeholder: '请输入查询名称',
},
{
type: 'text',
mode: 'normal',
name: 'label2',
placeholder: '请输入查询描述',
},
],
},
{
type: 'condition-builder',
label: '查询条件组合',
name: 'conditions',
required: true,
fields,
},
],
}
return advanceQueryForm
}
const onPreReqModelData = (reqOpts) => {
const { page = 1, size = 50, orderDir, orderBy, op, ...rest } = reqOpts.data
reqOpts.data = {
paging:
op === 'export-csv'
? {
page: 1,
size: 10000,
}
: { page, size },
...rest,
}
if (orderBy) {
reqOpts.data.ordering = [
{
fieldId: orderBy,
asc: orderDir === 'asc',
},
]
}
return reqOpts
}
const onReqSucModelData = (source, reqOpt) => {
const { data: items = [], count: total = 0 } = source.data || {}
const { size } = reqOpt.data.paging
source.data = {
items,
pageCount: Math.ceil(total / size),
total,
}
return source
}
const onUpdatePreReq = (reqOpts) => {
const fields = []
const { ids } = reqOpts.data
map(reqOpts.data, (value, id) => {
if (/^\d+$/.test(id)) {
fields.push({
id,
value,
})
}
})
reqOpts.data = ids ? { fields, ids } : { fields }
return reqOpts
}
const getUpdateForm = (type, tableInfo: any) => {
const { fields = {}, detailDataApis } = tableInfo
const controls: any = map(omit(fields, ['id', 'addTime', 'updateTime']), (field: any) => {
const { id: name, name: label, editStyle } = field
const column = {
name,
label,
type: 'text',
...editStyle,
required: type === 'batchEdit' ? false : editStyle.required,
}
return column
})
const schema = {
type: 'form',
api: detailDataApis[type],
className: type,
controls,
}
if (type === 'batchEdit') {
schema.controls.unshift({
type: 'hidden',
name: 'ids',
})
return schema
}
return schema
}
const getViewModel = (info) => {
const columns = getColumns({
...info,
isViewMode: true,
})
const controls = columns.map((item) => {
const { type, isViewMode } = item
let viewType = 'static'
switch (type) {
case 'image':
viewType = 'static-image'
break
case 'json':
viewType = 'static-json'
break
default:
}
const staticTypes = ['container']
return {
...item,
type: isViewMode ? type : viewType,
inputClassName: staticTypes.includes(type) ? `${app.theme.getName()}-Form-static` : '',
}
})
const schema = {
controls,
type: 'form',
mode: 'horizontal',
wrapWithPanel: false,
actions: [],
}
return schema
}
const getSearchLogSchema = (type: string, options: any = {}) => {
const doAdvanceQuery = () => {
options.tableRef.current.getComponentByName('curd.advanceQueryDrawer').tryChildrenToHandle({
actionType: 'submit',
})
}
const doCrudQuery = (query) => {
options.tableRef.current.getComponentByName('curd.modelDataTable').handleQuery(query, true)
}
const storeData = {
parentKey: 'modelDetailData',
key: `modelTableId_${options.id}`,
}
const logApis = {
list: {
url: 'GET ovhapi/fontstored',
domain: 'modelApi',
data: storeData,
onSuccess: (source) => {
source.data = {
options: source.data.data.map((item) => {
return {
id: item.id,
label1: item.label1,
label2: item.label2,
stored: item.value,
}
}),
}
return source
},
},
add: {
url: 'POST ovhapi/fontstored',
domain: 'modelApi',
data: {
'&': '$$',
value: '$conditions',
...storeData,
},
onPreRequest: (reqOpts) => {
reqOpts.data.value = JSON.stringify({ conditions: reqOpts.data.value })
return reqOpts
},
onSuccess: (source) => {
doAdvanceQuery()
return source
},
},
edit: {
url: 'PUT ovhapi/fontstored/$id',
domain: 'modelApi',
data: {
'&': '$$',
...storeData,
},
onPreRequest: (reqOpts) => {
const { conditions } = reqOpts.data
reqOpts.data.id = reqOpts.data.searchLog
if (conditions) {
reqOpts.data.value = JSON.stringify({ conditions })
}
return reqOpts
},
onSuccess: (source) => {
doAdvanceQuery()
return source
},
},
del: {
url: 'DELETE ovhapi/fontstored/$id',
domain: 'modelApi',
},
}
if (type === 'update') {
return {
type: 'action',
label: '更新条件',
visibleOn: '!!data.searchLog',
actionType: 'ajax',
api: logApis.edit,
}
}
if (type === 'add') {
return {
type: 'action',
label: '保存条件',
visibleOn: '!data.searchLog',
actionType: 'ajax',
api: logApis.add,
}
}
const selectControl = {
type: 'select',
name: 'searchLog',
placeholder: '选择查询条件',
className: 'm-none',
inputClassName: 'w-md',
searchable: true,
removable: true,
clearable: true,
labelField: 'label1',
valueField: 'id',
source: logApis.list,
deleteApi: logApis.del,
menuTpl: {
type: 'container',
body: {
component: (props) => {
const { label1, label2, onClick = () => {} } = props.data
return (
<div onClick={onClick}>
<span className="font-weight-bold">{label1}</span>
<span className="p-l-sm text-black-50">{label2}</span>
</div>
)
},
},
},
onChange: (selectId, _, itemIns, formIns) => {
if (!selectId) {
return
}
const item = find(itemIns.options.toJSON(), { id: selectId })
const formData = { ...omit(item, ['stored']), ...JSON.parse(item.stored) }
if (type === 'select') {
formIns.setValues(formData)
} else if (type === 'search') {
formData.searchLog = selectId
doCrudQuery(omit(formData, ['id', 'value']))
options.close()
}
},
...options.props,
}
if (type === 'search') {
const fromSchema = {
type: 'form',
className: 'p-sm',
wrapWithPanel: false,
autoFocus: true,
mode: 'inline',
controls: selectControl,
onSubmit: () => {
// options.close()
},
}
return fromSchema
}
if (type === 'select') {
return selectControl
}
}
const getModelDataTable = (info) => {
const { id, name, tableRef } = info
const doCrudQuery = (query) => {
const crudIns = tableRef.current.getComponentByName('curd.modelDataTable')
crudIns.props.store.updateQuery(query, undefined, 'page', 'size', true)
crudIns.search(undefined, undefined, undefined, undefined, true)
}
const detailDataApis = {
list: {
url: `POST ovhapi/model/api/model/${id}/list`,
domain: 'modelApi',
onPreRequest: onPreReqModelData,
onSuccess: onReqSucModelData,
},
add: {
url: `POST ovhapi/model/api/model/${id}`,
domain: 'modelApi',
onPreRequest: onUpdatePreReq,
},
edit: {
url: `PUT ovhapi/model/api/model/${id}/$id`,
domain: 'modelApi',
onPreRequest: onUpdatePreReq,
},
del: {
url: `DELETE ovhapi/model/api/model/${id}/$id`,
domain: 'modelApi',
},
batchEdit: {
url: `PUT ovhapi/model/api/model/${id}/batch`,
domain: 'modelApi',
onPreRequest: onUpdatePreReq,
},
batchDel: {
url: `DELETE ovhapi/model/api/model/${id}/batch`,
domain: 'modelApi',
data: {
ids: '$ids',
},
},
}
const columns = getColumns(info)
const modelCrud = {
columns,
type: 'lib-crud',
name: 'modelDataTable',
// alwaysShowPagination: true,
syncLocation: false,
api: detailDataApis.list,
filterTogglable: false,
perPageAvailable: [50, 100, 200],
placeholder: emptyListHolder,
defaultParams: {
size: 50,
},
// checkOnItemClick: true,
perPageField: 'size',
pageField: 'page',
headerToolbar: [
{
type: 'action',
icon: 'fa fa-plus pull-left',
level: 'primary',
label: '添加',
className: 'toolbar-divider',
size: 'sm',
align: 'left',
actionType: 'drawer',
drawer: {
title: `【${name}】添加一项`,
size: 'lg',
body: getUpdateForm('add', { ...info, detailDataApis }),
},
},
{
type: 'bulkActions',
align: 'left',
},
{
type: 'action',
icon: 'fa fa-search pull-left',
label: '高级查询',
className: 'btn-open-query-drawer',
reload: 'none',
align: 'left',
size: 'sm',
actionType: 'drawer',
drawer: {
title: `【${name}】高级查询`,
size: 'lg',
name: 'advanceQueryDrawer',
actions: [
{
type: 'action',
label: '立即查询',
level: 'primary',
className: 'btn-advance-query',
actionType: 'submit',
},
getSearchLogSchema('update', info),
getSearchLogSchema('add', info),
{
type: 'action',
actionType: 'close',
label: '取消',
},
],
body: getAdvanceQueryForm(info),
},
},
{
// limits: 'add',
type: 'container',
body: {
component: (btnProps) => {
return (
<PopOver
placement="bottom"
Popup={(popProps) => (
<Amis schema={getSearchLogSchema('search', { ...popProps, id, tableRef })} />
)}
>
<Button
iconOnly
tooltipPlacement="top"
tooltip="选择查询条件"
theme={btnProps.theme}
size="sm"
>
<i className={btnProps.classnames('Button-icon fa fa-sliders')} />
</Button>
</PopOver>
)
},
},
align: 'left',
tooltip: '筛选条件',
className: 'search-select',
tooltipPlacement: 'top',
icon: 'fa fa-sliders',
size: 'sm',
iconOnly: true,
onClick: () => {
tableRef.current.getComponentByName('curd.modelDataTable').handleFilterReset()
},
},
{
// limits: 'add',
type: 'button',
align: 'left',
tooltip: '清空筛选条件',
tooltipPlacement: 'top',
icon: 'fa fa-refresh',
size: 'sm',
iconOnly: true,
onClick: () => {
tableRef.current.getComponentByName('curd.modelDataTable').handleFilterReset()
},
},
{
type: 'columns-toggler',
align: 'left',
},
{
type: 'export-csv',
align: 'left',
},
{
type: 'container',
align: 'left',
className: 'toolbar-divider',
body: {
component: (props) => (
<QueryItem {...props} doCrudQuery={doCrudQuery} columns={columns} />
),
},
},
{
type: 'tpl',
align: 'left',
tpl: `<% if(data.pageCount) {%>
第 <%= data.page/data.pageCount %> 页, 共有 <%= data.total || 0%> 项
<%} else { %>
<span class="text-black-50">列表暂无数据</span>
<%}%>`,
},
{
type: 'pagination',
align: 'left',
},
{
type: 'switch-per-page',
align: 'left',
},
],
footerToolbar: [],
bulkActions: [
{
type: 'action',
icon: 'fa fa-edit pull-left',
label: '批量修改',
align: 'left',
actionType: 'drawer',
drawer: {
title: `【${name}】批量修改`,
size: 'lg',
data: {
ids: '$ids',
},
body: getUpdateForm('batchEdit', { ...info, detailDataApis }),
},
},
{
type: 'action',
icon: 'fa fa-remove text-danger pull-left',
label: '批量删除',
actionType: 'ajax',
confirmText: '删除后将不可恢复,您确认要批量删除?',
align: 'left',
api: detailDataApis.batchDel,
messages: {
success: '删除成功',
failed: '删除失败',
},
},
],
itemActions: [
{
type: 'button',
label: '查看',
icon: 'fa fa-eye pull-left',
actionType: 'drawer',
drawer: {
title: '查看信息',
closeOnOutside: true,
size: 'lg',
actions: [],
body: getViewModel(info),
},
},
{
type: 'action',
label: '编辑',
icon: 'fa fa-edit pull-left',
actionType: 'drawer',
drawer: {
position: 'right',
size: 'lg',
title: '编辑信息',
body: getUpdateForm('edit', { ...info, detailDataApis }),
},
},
{
type: 'button',
label: '删除',
icon: 'fa fa-remove text-danger pull-left',
actionType: 'ajax',
confirmText: '删除后将不可恢复,您确认要删除?',
api: detailDataApis.del,
messages: {
success: '删除成功',
failed: '删除失败',
},
},
],
}
return modelCrud
}
const Nav = (props) => {
const { cls, displayMode, tableList, activeId, setActiveId, setDisplayMode } = props
const modeBtnStyle = (isActive) =>
cls('Button', 'Button--default', 'Button--xs', { 'Button--primary is-active': isActive })
const setActiveItem = (e) => {
setActiveId(e.currentTarget.dataset.tid)
}
// 列表/表单 切换功能
return (
<div className="detail-nav border-right">
<ScrollBar>
<div className="detail-nav-hd border-bottom">
<h6 className="m-b-none">模型导航</h6>
<div className={cls('ButtonGroup', 'd-none')}>
<button
type="button"
onClick={() => setDisplayMode('list')}
className={modeBtnStyle(displayMode === 'list')}
>
<span>列表</span>
</button>
<button
type="button"
onClick={() => setDisplayMode('form')}
className={modeBtnStyle(displayMode === 'form')}
>
<span>表单</span>
</button>
</div>
</div>
<div className={cls('Nav', 'Nav--stacked')}>
{tableList.map((item) => {
const isActive = item.id === activeId
return (
<div
key={item.id}
className={`${isActive ? 'is-active' : ''} ${cls('Nav-item text-truncate')}`}
data-tid={item.id}
onClick={setActiveItem}
>
<a> {item.name}</a>
</div>
)
})}
</div>
</ScrollBar>
</div>
)
}
const QueryItem = (props: any) => {
const { store, columns, doCrudQuery } = props
const { query = {} } = store
// const getQueryInfo = () => {
// if (tableRef.current) {
// console.log('@==>.tableRef', tableRef)
// }
// }
const filed = columns.find((i) => i.name === query.orderBy)
const isAsc = query.orderDir === 'asc'
const clearSort = () => {
doCrudQuery(omit(query, ['orderBy', 'orderDir']))
}
const sortList = () => {
doCrudQuery({
...query,
orderDir: isAsc ? 'desc' : 'asc',
})
}
const clearQuery = () => {
const newQuery = omit(query, ['label1', 'label2', 'searchLog', 'id', 'value', 'conditions'])
doCrudQuery(newQuery)
}
const openQuery = () => {
$('.btn-open-query-drawer').trigger('click')
}
return (
<S.QueryItem>
{query.conditions && (
<div>
<span>查询:</span>
<span
className="cursor-pointer"
data-tooltip="编辑查询"
data-position="bottom"
onClick={openQuery}
>
{query.label1 || '未命名查询'}
</span>
<i
data-tooltip="取消查询"
data-position="bottom"
className="iconfont icon-close"
onClick={clearQuery}
/>
</div>
)}
{query.orderBy && (
<div>
<span>{get(filed, 'label')}:</span>
<span
className="cursor-pointer"
data-tooltip={isAsc ? '切换为降序' : '切换为降序'}
data-position="bottom"
onClick={sortList}
>
{isAsc ? '升序' : '降序'}
</span>
<i
data-tooltip="取消排序"
data-position="bottom"
className="iconfont icon-close"
onClick={clearSort}
/>
</div>
)}
</S.QueryItem>
)
}
const Crud = (props) => {
const { info = {} } = props
const tableRef = useRef()
const amisProps = {
scopeRef: (ref) => {
tableRef.current = ref
},
}
const schema = {
type: 'page',
name: 'curd',
bodyClassName: 'p-none',
body: getModelDataTable({ ...info, tableRef }),
}
return (
<div className="detail-crud">
<Amis schema={schema} props={amisProps} />
</div>
)
}
const ModeDetail = (props) => {
const { classnames: cls } = props
const [state, setState] = useImmer<any>({
tableList: [],
activeId: '',
displayMode: 'list',
})
const { tableList, activeId, displayMode } = state
const activeInfo = tableList.find((i) => `${i.id}` === activeId)
const setActiveId = (id) => {
setState((d) => {
d.activeId = id
})
}
const setDisplayMode = (mode) => {
setState((d) => {
d.displayMode = mode
})
}
useEffect(() => {
app
.request({
...apis.listTable,
onSuccess: utils.onGetTableListSuc,
})
.then((source) => {
const { items = [] } = source.data.data
setState((d) => {
d.tableList = items
d.activeId = get(items, '0.id') || ''
})
})
}, [])
const navProps = {
displayMode,
tableList,
activeId,
cls,
setActiveId,
setDisplayMode,
}
return (
<S.ModelDetail>
<Nav {...navProps} />
{activeId && <Crud key={activeId} cls={cls} info={activeInfo} displayMode={displayMode} />}
</S.ModelDetail>
)
}
export const modelDetailSchema = {
type: 'container',
body: {
component: ModeDetail,
},
} | the_stack |
declare module "love.filesystem" {
import { Data } from "love.data";
/**
* Appends data to a file.
*
* There will be an attempt to create the file if it doesn't exist.
*
* @param filepath A file's path.
* @param data Data to append.
* @param bytes How many bytes of data to append.
* @returns success, true on success, or _nil/undefined_ on error.
* @returns errormsg, The error message.
* @link [love.filesystem.append](https://love2d.org/wiki/love.filesystem.append)
* @since 0.9.0
*/
function append(
filepath: string,
data: string | Data,
bytes?: number
): LuaMultiReturn<[success: true] | [success: false, errormsg: string]>;
/**
* Returns whether love.filesystem follows symbolic links.
*
* @link [love.filesystem.areSymlinksEnabled](https://love2d.org/wiki/love.filesystem.areSymlinksEnabled)
* @since 0.9.2
*/
function areSymlinksEnabled(): boolean;
/**
* Creates a directory.
*
* Does nothing but return true if that directory already exists.
*
* @param name The new directory's name.
* @returns true if that directory exists.
* @link [love.filesystem.createDirectory](https://love2d.org/wiki/love.filesystem.createDirectory)
* @since 0.9.0
*/
function createDirectory(name: string): boolean;
/**
* Returns an absolute path to the application data directory.
*
* @link [love.filesystem.getAppdataDirectory](https://love2d.org/wiki/love.filesystem.getAppdataDirectory)
*/
function getAppdataDirectory(): string;
/**
* Returns a path string used for importing C libraries.
*
* @link [love.filesystem.getCRequirePath](https://love2d.org/wiki/love.filesystem.getCRequirePath)
* @since 11.0
*/
function getCRequirePath(): string;
/**
* Returns an unsorted array of item names within a specified directory.
*
* If the path passed to the function exists in the game and the save directory,
* it will list the files and directories from both places.
*
* @param dir A path to a filesystem.
* @returns The names of all items in the specified directory.
* @link [love.filesystem.getDirectoryItems](https://love2d.org/wiki/love.filesystem.getDirectoryItems)
* @since 0.9.0
*/
function getDirectoryItems(dir: string): string[];
/**
* Returns the write directory name for your game.
*
* Not the full location of that directory.
*
* @returns The write directory name for your game.
* @link [love.filesystem.getIdentity](https://love2d.org/wiki/love.filesystem.getIdentity)
* @since 0.9.0
*/
function getIdentity(): string;
type FileInfo<T extends FileType = FileType> = {
/**
* The {@link FileType} of the object at the path.
*/
type: T;
/**
* The size in bytes of the file.
*/
size?: number;
/**
* The file's last modification time in seconds since the unix epoch.
*/
modtime?: number;
};
/**
* Returns {@link FileInfo} for something on the filesystem.
*
* @param path A filesystem path.
* @param filetype Used to filter only items matching this {@link FileType}.
* @returns _nil/undefined_ if nothing exists at the specified path.
* @link [love.filesystem.getInfo](https://love2d.org/wiki/love.filesystem.getInfo)
* @since 11.0
*/
function getInfo<T extends FileType>(path: string, filetype?: T): FileInfo<T> | undefined;
/**
* Returns {@link FileInfo} for something on the filesystem.
*
* Avoids creating a new object by mutating an existing one.
*
* @param path A filesystem path.
* @param info An object to mutate.
* @returns The mutated object or _nil/undefined_.
* @link [love.filesystem.getInfo](https://love2d.org/wiki/love.filesystem.getInfo)
* @since 11.0
*/
function getInfo(path: string, info?: object): FileInfo | undefined;
/**
* Returns {@link FileInfo} for something on the filesystem.
*
* Avoids creating a new object by mutating an existing one.
*
* @param path A filesystem path.
* @param filetype Used to filter only items matching this {@link FileType}.
* @param info The mutated object or _nil/undefined_.
* @link [love.filesystem.getInfo](https://love2d.org/wiki/love.filesystem.getInfo)
* @since 11.0
*/
function getInfo<T extends FileType>(path: string, filetype: T, info: object): FileInfo<T> | undefined;
/**
* Returns an absolute path to a path's directory.
*
* @param filepath A relative file path.
* @returns The platform-specific full path of the directory containing the filepath.
* @link [love.filesystem.getRealDirectory](https://love2d.org/wiki/love.filesystem.getRealDirectory)
* @since 0.9.2
*/
function getRealDirectory(filepath: string): string;
/**
* Returns a path string used for importing lua files.
*
* @link [love.filesystem.getRequirePath](https://love2d.org/wiki/love.filesystem.getRequirePath)
* @since 0.10.0
*/
function getRequirePath(): string;
/**
* Returns a full path to the designated save directory.
*
* @link [love.filesystem.getSaveDirectory](https://love2d.org/wiki/love.filesystem.getSaveDirectory)
* @since 0.5.0
*/
function getSaveDirectory(): string;
/**
* Returns the full path to the the .love file or directory.
*
* If the game is fused to the LÖVE executable, then the executable is
* returned.
*
* @link [love.filesystem.getSource](https://love2d.org/wiki/love.filesystem.getSource)
* @since 0.9.0
*/
function getSource(): string;
/**
* Like {@link "love.filesystem".getSource} but returns the parent directory.
*
* @link [love.filesystem.getSourceBaseDirectory](https://love2d.org/wiki/love.filesystem.getSourceBaseDirectory)
* @since 0.9.0
*/
function getSourceBaseDirectory(): string;
/**
* Returns an absolute path to the user's directory.
*
* @link [love.filesystem.getUserDirectory](https://love2d.org/wiki/love.filesystem.getUserDirectory)
*/
function getUserDirectory(): string;
/**
* Returns the current working directory.
*
* @link [love.filesystem.getWorkingDirectory](https://love2d.org/wiki/love.filesystem.getWorkingDirectory)
* @since 0.5.0
*/
function getWorkingDirectory(): string;
/**
* Initializes love.filesystem, will be called internally, so should not be used
* explicitly.
*
* @param appname The name of the application binary, typically love.
* @link [love.filesystem.init](https://love2d.org/wiki/love.filesystem.init)
*/
function init(appname: string): void;
/**
* Returns whether the game is in fused mode or not.
*
* @link [love.filesystem.isFused](https://love2d.org/wiki/love.filesystem.isFused)
* @since 0.9.0
*/
function isFused(): boolean;
/**
* Iterate over the lines in a file.
*
* Will throw a fatal error if there is trouble accessing the specified
* file.
*
* ```ts
* for (const line of love.filesystem.lines("file.txt")) {
* print(line);
* }
* ```
*
* @param filepath A file's path.
* @returns An iterator that goes over each line of content in the file.
* @link [love.filesystem.lines](https://love2d.org/wiki/love.filesystem.lines)
*/
function lines(filepath: string): LuaIterable<string>;
/**
* Loads a Lua file (but does not run it).
*
* @param name The path to a Lua file.
* @returns chunk, The loaded chunk.
* @returns errormsg, The error message if file could not be opened.
* @link [love.filesystem.load](https://love2d.org/wiki/love.filesystem.load)
* @since 0.5.0
*/
function load(name: string): LuaMultiReturn<[chunk: (this: void) => any] | [chunk: undefined, errormsg: string]>;
/**
* Mounts a zip file or folder in the game's save directory for reading. It is also possible to mount love.filesystem.getSourceBaseDirectory if the game is in fused mode.
*
* @param archive The folder or zip file in the game's save directory to mount.
* @param mountpoint The new path the archive will be mounted to.
* @param appendToPath Whether the archive will be searched when reading a filepath before or after already-mounted archives. This includes the game's source and save directories. (Default false)
* @returns true if the archive was successfully mounted, false otherwise.
* @link [love.filesystem.mount](https://love2d.org/wiki/love.filesystem.mount)
* @since 0.9.0
*/
function mount(archive: string, mountpoint: string, appendToPath?: boolean): boolean;
/**
* Mounts the contents of the given FileData in memory. The FileData's data must contain a zipped directory structure.
*
* @param filedata The FileData object in memory to mount.
* @param mountpoint The new path the archive will be mounted to.
* @param appendToPath Whether the archive will be searched when reading a filepath before or after already-mounted archives. This includes the game's source and save directories. (Default false)
* @returns true if the archive was successfully mounted, false otherwise.
* @link [love.filesystem.mount](https://love2d.org/wiki/love.filesystem.mount)
* @since 11.0
*/
function mount(filedata: FileData, mountpoint: string, appendToPath?: boolean): boolean;
/**
* Mounts {@link Data} in memory. The {@link Data} must contain a zipped directory structure.
*
* @param data The Data object in memory to mount.
* @param archivename The unique name to associate the mounted data with, for use with love.filesystem.unmount. Must be unique compared to other mounted data.
* @param mountpoint The new path the archive will be mounted to.
* @param appendToPath Whether the archive will be searched when reading a filepath before or after already-mounted archives. This includes the game's source and save directories. (Default false)
* @returns true if the archive was successfully mounted, false otherwise.
* @link [love.filesystem.mount](https://love2d.org/wiki/love.filesystem.mount)
* @since 11.0
*/
function mount(data: Data, archivename: string, mountpoint: string, appendToPath?: boolean): boolean;
/**
* Creates a new {@link File} object. Use {@link File.open} to start using it.
*
* @param filename The name of the File.
* @link [love.filesystem.newFile](https://love2d.org/wiki/love.filesystem.newFile)
*/
function newFile(filename: string): File;
/**
* Creates a new {@link File} object and opens it.
*
* @param filename The filename of the file.
* @param mode The mode to open the file in.
* @returns file, The new File object, or _nil/undefined_ if an error occurred.
* @returns errormsg, The error string if an error occurred.
* @link [love.filesystem.newFile](https://love2d.org/wiki/love.filesystem.newFile)
* @since 0.9.0
*/
function newFile(
filename: string,
mode: FileMode
): LuaMultiReturn<[file: File] | [file: undefined, errormsg: string]>;
/**
* Creates a new {@link FileData} object.
*
* @param contents The contents of the file.
* @param name The name of the file.
* @returns Your new FileData.
* @link [love.filesystem.newFileData](https://love2d.org/wiki/love.filesystem.newFileData)
*/
function newFileData(contents: string, name: string): FileData;
/**
* Creates a new {@link FileData} from a file on the storage device.
*
* @param filepath Path to the file.
* @return data, The new FileData, or _nil/undefined_ if an error occurred.
* @return errormsg, The error string, if an error occurred.
* @link [love.filesystem.newFileData](https://love2d.org/wiki/love.filesystem.newFileData)
* @since 0.9.0
*/
function newFileData(filepath: string): LuaMultiReturn<[data: FileData] | [data: undefined, errormsg: string]>;
/**
* Read the contents of a file.
*
* @param name The name (and path) of the file.
* @param size How many bytes to read.
* @return contents, The file contents, or _nil/undefined_ if an error occurred.
* @return size, How many bytes have been read, or the error string.
* @link [love.filesystem.read](https://love2d.org/wiki/love.filesystem.read)
*/
function read(
name: string,
size?: number
): LuaMultiReturn<[contents: string, size: number] | [contents: undefined, errormsg: string]>;
/**
* Reads the contents of a file into either a string or a {@link FileData} object.
*
* @param container What type to return the file's contents as.
* @param name The name (and path) of the file
* @param size How many bytes to read (Default all)
* @link [love.filesystem.read](https://love2d.org/wiki/love.filesystem.read)
* @since 11.0
*/
function read(
container: "string",
name: string,
size?: number
): LuaMultiReturn<[contents: string, size: number] | [contents: undefined, errormsg: string]>;
function read(
container: "data",
name: string,
size?: number
): LuaMultiReturn<[contents: FileData, size: number] | [contents: undefined, errormsg: string]>;
/**
* Removes a file or directory.
*
* @param name The file or directory to remove.
* @return success, True if the file/directory was removed, false otherwise.
* @link [love.filesystem.remove](https://love2d.org/wiki/love.filesystem.remove)
*/
function remove(name: string): boolean;
/**
* Sets the filesystem paths that will be searched for c libraries when
* require is called.
*
* @param paths The paths that the require function will check in love's filesystem.
* @link [love.filesystem.setCRequirePath](https://love2d.org/wiki/love.filesystem.setCRequirePath)
* @since 11.0
*/
function setCRequirePath(paths: string): void;
/**
* Sets the write directory for your game. Note that you can only set the name of
* the folder to store your files in, not the location.
*
* @param name The new identity that will be used as write directory.
* @param appendToPath Whether the identity directory will be searched when reading a filepath before or after the game's source directory and any currently mounted archives.
* @link [love.filesystem.setIdentity](https://love2d.org/wiki/love.filesystem.setIdentity)
* @since 0.9.0
*/
function setIdentity(name: string, appendToPath?: boolean): void;
/**
* Sets the filesystem paths that will be searched when require is called.
*
* @param paths The paths that the require function will check in love's filesystem.
* @link [love.filesystem.setRequirePath](https://love2d.org/wiki/love.filesystem.setRequirePath)
* @since 0.10.0
*/
function setRequirePath(paths: string): void;
/**
* Sets the source of the game, where the code is present. This function can only
* be called once, and is normally automatically done by LÖVE.
*
* @param path Absolute path to the game's source folder.
* @link [love.filesystem.setSource](https://love2d.org/wiki/love.filesystem.setSource)
*/
function setSource(path: string): void;
/**
* Sets whether love.filesystem follows symbolic links. It is enabled by default
* in version 0.10.0 and newer, and disabled by default in 0.9.2.
*
* @param enable Whether love.filesystem should follow symbolic links.
* @link [love.filesystem.setSymlinksEnabled](https://love2d.org/wiki/love.filesystem.setSymlinksEnabled)
* @since 0.9.2
*/
function setSymlinksEnabled(enable: boolean): void;
/**
* Unmounts a zip file or folder previously mounted for reading with
* love.filesystem.mount.
*
* @param archive The folder or zip file in the game's save directory which is currently mounted.
* @return success, True if the archive was successfully unmounted, false otherwise.
* @link [love.filesystem.unmount](https://love2d.org/wiki/love.filesystem.unmount)
* @since 0.9.0
*/
function unmount(archive: string): boolean;
/**
* Write data to a file in the save directory.
*
* If the file existed already, it will be completely replaced by the new contents.
*
* @param filepath The file to write to.
* @param data The string or Data to write to the file.
* @param size How many bytes to write.
* @returns success, If the operation was successful.
* @returns message, Error message if operation was unsuccessful.
* @link [love.filesystem.write](https://love2d.org/wiki/love.filesystem.write)
*/
function write(
filepath: string,
data: string,
size?: number
): LuaMultiReturn<[success: true] | [success: false, message: string]>;
function write(
filepath: string,
data: Data,
size?: number
): LuaMultiReturn<[success: true] | [success: false, message: string]>;
} | the_stack |
import * as core from '@actions/core'
import * as path from 'path'
import * as io from '@actions/io'
import {promises as fs} from 'fs'
import {findFilesToUpload} from '../src/search'
const root = path.join(__dirname, '_temp', 'search')
const searchItem1Path = path.join(
root,
'folder-a',
'folder-b',
'folder-c',
'search-item1.txt'
)
const searchItem2Path = path.join(root, 'folder-d', 'search-item2.txt')
const searchItem3Path = path.join(root, 'folder-d', 'search-item3.txt')
const searchItem4Path = path.join(root, 'folder-d', 'search-item4.txt')
const searchItem5Path = path.join(root, 'search-item5.txt')
const extraSearchItem1Path = path.join(
root,
'folder-a',
'folder-b',
'folder-c',
'extraSearch-item1.txt'
)
const extraSearchItem2Path = path.join(
root,
'folder-d',
'extraSearch-item2.txt'
)
const extraSearchItem3Path = path.join(
root,
'folder-f',
'extraSearch-item3.txt'
)
const extraSearchItem4Path = path.join(
root,
'folder-h',
'folder-i',
'extraSearch-item4.txt'
)
const extraSearchItem5Path = path.join(
root,
'folder-h',
'folder-i',
'extraSearch-item5.txt'
)
const extraFileInFolderCPath = path.join(
root,
'folder-a',
'folder-b',
'folder-c',
'extra-file-in-folder-c.txt'
)
const amazingFileInFolderHPath = path.join(root, 'folder-h', 'amazing-item.txt')
const lonelyFilePath = path.join(
root,
'folder-h',
'folder-j',
'folder-k',
'lonely-file.txt'
)
describe('Search', () => {
beforeAll(async () => {
// mock all output so that there is less noise when running tests
jest.spyOn(console, 'log').mockImplementation(() => {})
jest.spyOn(core, 'debug').mockImplementation(() => {})
jest.spyOn(core, 'info').mockImplementation(() => {})
jest.spyOn(core, 'warning').mockImplementation(() => {})
// clear temp directory
await io.rmRF(root)
await fs.mkdir(path.join(root, 'folder-a', 'folder-b', 'folder-c'), {
recursive: true
})
await fs.mkdir(path.join(root, 'folder-a', 'folder-b', 'folder-e'), {
recursive: true
})
await fs.mkdir(path.join(root, 'folder-d'), {
recursive: true
})
await fs.mkdir(path.join(root, 'folder-f'), {
recursive: true
})
await fs.mkdir(path.join(root, 'folder-g'), {
recursive: true
})
await fs.mkdir(path.join(root, 'folder-h', 'folder-i'), {
recursive: true
})
await fs.mkdir(path.join(root, 'folder-h', 'folder-j', 'folder-k'), {
recursive: true
})
await fs.writeFile(searchItem1Path, 'search item1 file')
await fs.writeFile(searchItem2Path, 'search item2 file')
await fs.writeFile(searchItem3Path, 'search item3 file')
await fs.writeFile(searchItem4Path, 'search item4 file')
await fs.writeFile(searchItem5Path, 'search item5 file')
await fs.writeFile(extraSearchItem1Path, 'extraSearch item1 file')
await fs.writeFile(extraSearchItem2Path, 'extraSearch item2 file')
await fs.writeFile(extraSearchItem3Path, 'extraSearch item3 file')
await fs.writeFile(extraSearchItem4Path, 'extraSearch item4 file')
await fs.writeFile(extraSearchItem5Path, 'extraSearch item5 file')
await fs.writeFile(extraFileInFolderCPath, 'extra file')
await fs.writeFile(amazingFileInFolderHPath, 'amazing file')
await fs.writeFile(lonelyFilePath, 'all by itself')
/*
Directory structure of files that get created:
root/
folder-a/
folder-b/
folder-c/
search-item1.txt
extraSearch-item1.txt
extra-file-in-folder-c.txt
folder-e/
folder-d/
search-item2.txt
search-item3.txt
search-item4.txt
extraSearch-item2.txt
folder-f/
extraSearch-item3.txt
folder-g/
folder-h/
amazing-item.txt
folder-i/
extraSearch-item4.txt
extraSearch-item5.txt
folder-j/
folder-k/
lonely-file.txt
search-item5.txt
*/
})
it('Single file search - Absolute Path', async () => {
const searchResult = await findFilesToUpload(extraFileInFolderCPath)
expect(searchResult.filesToUpload.length).toEqual(1)
expect(searchResult.filesToUpload[0]).toEqual(extraFileInFolderCPath)
expect(searchResult.rootDirectory).toEqual(
path.join(root, 'folder-a', 'folder-b', 'folder-c')
)
})
it('Single file search - Relative Path', async () => {
const relativePath = path.join(
'__tests__',
'_temp',
'search',
'folder-a',
'folder-b',
'folder-c',
'search-item1.txt'
)
const searchResult = await findFilesToUpload(relativePath)
expect(searchResult.filesToUpload.length).toEqual(1)
expect(searchResult.filesToUpload[0]).toEqual(searchItem1Path)
expect(searchResult.rootDirectory).toEqual(
path.join(root, 'folder-a', 'folder-b', 'folder-c')
)
})
it('Single file using wildcard', async () => {
const expectedRoot = path.join(root, 'folder-h')
const searchPath = path.join(root, 'folder-h', '**/*lonely*')
const searchResult = await findFilesToUpload(searchPath)
expect(searchResult.filesToUpload.length).toEqual(1)
expect(searchResult.filesToUpload[0]).toEqual(lonelyFilePath)
expect(searchResult.rootDirectory).toEqual(expectedRoot)
})
it('Single file using directory', async () => {
const searchPath = path.join(root, 'folder-h', 'folder-j')
const searchResult = await findFilesToUpload(searchPath)
expect(searchResult.filesToUpload.length).toEqual(1)
expect(searchResult.filesToUpload[0]).toEqual(lonelyFilePath)
expect(searchResult.rootDirectory).toEqual(searchPath)
})
it('Directory search - Absolute Path', async () => {
const searchPath = path.join(root, 'folder-h')
const searchResult = await findFilesToUpload(searchPath)
expect(searchResult.filesToUpload.length).toEqual(4)
expect(
searchResult.filesToUpload.includes(amazingFileInFolderHPath)
).toEqual(true)
expect(searchResult.filesToUpload.includes(extraSearchItem4Path)).toEqual(
true
)
expect(searchResult.filesToUpload.includes(extraSearchItem5Path)).toEqual(
true
)
expect(searchResult.filesToUpload.includes(lonelyFilePath)).toEqual(true)
expect(searchResult.rootDirectory).toEqual(searchPath)
})
it('Directory search - Relative Path', async () => {
const searchPath = path.join('__tests__', '_temp', 'search', 'folder-h')
const expectedRootDirectory = path.join(root, 'folder-h')
const searchResult = await findFilesToUpload(searchPath)
expect(searchResult.filesToUpload.length).toEqual(4)
expect(
searchResult.filesToUpload.includes(amazingFileInFolderHPath)
).toEqual(true)
expect(searchResult.filesToUpload.includes(extraSearchItem4Path)).toEqual(
true
)
expect(searchResult.filesToUpload.includes(extraSearchItem5Path)).toEqual(
true
)
expect(searchResult.filesToUpload.includes(lonelyFilePath)).toEqual(true)
expect(searchResult.rootDirectory).toEqual(expectedRootDirectory)
})
it('Wildcard search - Absolute Path', async () => {
const searchPath = path.join(root, '**/*[Ss]earch*')
const searchResult = await findFilesToUpload(searchPath)
expect(searchResult.filesToUpload.length).toEqual(10)
expect(searchResult.filesToUpload.includes(searchItem1Path)).toEqual(true)
expect(searchResult.filesToUpload.includes(searchItem2Path)).toEqual(true)
expect(searchResult.filesToUpload.includes(searchItem3Path)).toEqual(true)
expect(searchResult.filesToUpload.includes(searchItem4Path)).toEqual(true)
expect(searchResult.filesToUpload.includes(searchItem5Path)).toEqual(true)
expect(searchResult.filesToUpload.includes(extraSearchItem1Path)).toEqual(
true
)
expect(searchResult.filesToUpload.includes(extraSearchItem2Path)).toEqual(
true
)
expect(searchResult.filesToUpload.includes(extraSearchItem3Path)).toEqual(
true
)
expect(searchResult.filesToUpload.includes(extraSearchItem4Path)).toEqual(
true
)
expect(searchResult.filesToUpload.includes(extraSearchItem5Path)).toEqual(
true
)
expect(searchResult.rootDirectory).toEqual(root)
})
it('Wildcard search - Relative Path', async () => {
const searchPath = path.join(
'__tests__',
'_temp',
'search',
'**/*[Ss]earch*'
)
const searchResult = await findFilesToUpload(searchPath)
expect(searchResult.filesToUpload.length).toEqual(10)
expect(searchResult.filesToUpload.includes(searchItem1Path)).toEqual(true)
expect(searchResult.filesToUpload.includes(searchItem2Path)).toEqual(true)
expect(searchResult.filesToUpload.includes(searchItem3Path)).toEqual(true)
expect(searchResult.filesToUpload.includes(searchItem4Path)).toEqual(true)
expect(searchResult.filesToUpload.includes(searchItem5Path)).toEqual(true)
expect(searchResult.filesToUpload.includes(extraSearchItem1Path)).toEqual(
true
)
expect(searchResult.filesToUpload.includes(extraSearchItem2Path)).toEqual(
true
)
expect(searchResult.filesToUpload.includes(extraSearchItem3Path)).toEqual(
true
)
expect(searchResult.filesToUpload.includes(extraSearchItem4Path)).toEqual(
true
)
expect(searchResult.filesToUpload.includes(extraSearchItem5Path)).toEqual(
true
)
expect(searchResult.rootDirectory).toEqual(root)
})
it('Multi path search - root directory', async () => {
const searchPath1 = path.join(root, 'folder-a')
const searchPath2 = path.join(root, 'folder-d')
const searchPaths = searchPath1 + '\n' + searchPath2
const searchResult = await findFilesToUpload(searchPaths)
expect(searchResult.rootDirectory).toEqual(root)
expect(searchResult.filesToUpload.length).toEqual(7)
expect(searchResult.filesToUpload.includes(searchItem1Path)).toEqual(true)
expect(searchResult.filesToUpload.includes(searchItem2Path)).toEqual(true)
expect(searchResult.filesToUpload.includes(searchItem3Path)).toEqual(true)
expect(searchResult.filesToUpload.includes(searchItem4Path)).toEqual(true)
expect(searchResult.filesToUpload.includes(extraSearchItem1Path)).toEqual(
true
)
expect(searchResult.filesToUpload.includes(extraSearchItem2Path)).toEqual(
true
)
expect(searchResult.filesToUpload.includes(extraFileInFolderCPath)).toEqual(
true
)
})
it('Multi path search - with exclude character', async () => {
const searchPath1 = path.join(root, 'folder-a')
const searchPath2 = path.join(root, 'folder-d')
const searchPath3 = path.join(root, 'folder-a', 'folder-b', '**/extra*.txt')
// negating the third search path
const searchPaths = searchPath1 + '\n' + searchPath2 + '\n!' + searchPath3
const searchResult = await findFilesToUpload(searchPaths)
expect(searchResult.rootDirectory).toEqual(root)
expect(searchResult.filesToUpload.length).toEqual(5)
expect(searchResult.filesToUpload.includes(searchItem1Path)).toEqual(true)
expect(searchResult.filesToUpload.includes(searchItem2Path)).toEqual(true)
expect(searchResult.filesToUpload.includes(searchItem3Path)).toEqual(true)
expect(searchResult.filesToUpload.includes(searchItem4Path)).toEqual(true)
expect(searchResult.filesToUpload.includes(extraSearchItem2Path)).toEqual(
true
)
})
it('Multi path search - non root directory', async () => {
const searchPath1 = path.join(root, 'folder-h', 'folder-i')
const searchPath2 = path.join(root, 'folder-h', 'folder-j', 'folder-k')
const searchPath3 = amazingFileInFolderHPath
const searchPaths = [searchPath1, searchPath2, searchPath3].join('\n')
const searchResult = await findFilesToUpload(searchPaths)
expect(searchResult.rootDirectory).toEqual(path.join(root, 'folder-h'))
expect(searchResult.filesToUpload.length).toEqual(4)
expect(
searchResult.filesToUpload.includes(amazingFileInFolderHPath)
).toEqual(true)
expect(searchResult.filesToUpload.includes(extraSearchItem4Path)).toEqual(
true
)
expect(searchResult.filesToUpload.includes(extraSearchItem5Path)).toEqual(
true
)
expect(searchResult.filesToUpload.includes(lonelyFilePath)).toEqual(true)
})
}) | the_stack |
import 'mocha';
import { expect } from 'chai';
import { verificationConditions } from '../src';
import { code, incorrect, verified, unverified } from './helpers';
declare function assert (x: boolean): void;
declare function ensures (x: boolean | ((y: any) => boolean)): void;
declare function requires (x: boolean): void;
declare function pure (): boolean;
declare function spec (f: any, r: (rx: any) => boolean, s: (sx: any, sy: any) => boolean): boolean;
describe('simple class invariant', () => {
code(() => {
function greaterThree (y: number) {
return y > 3;
}
class A {
readonly x: number;
constructor (x: number) {
this.x = x;
}
invariant () {
return greaterThree(this.x);
}
}
function greaterTwo (a: A) {
requires(a instanceof A);
ensures(a.x > 2);
greaterThree(a.x);
}
});
verified('greaterTwo: a has property "x"');
verified('greaterTwo: (a.x > 2)');
});
describe('class invariant with reference to mutable variable', () => {
const code = () => {
let x = 23;
class A {
readonly x: number;
constructor (x: number) {
this.x = x;
}
invariant () {
return x > 4;
}
}
};
it('gets rejected', () => {
const src = code.toString();
const t = verificationConditions(src.substring(14, src.length - 2));
expect(t).to.have.property('status', 'error');
expect(t).to.have.property('type', 'reference-in-invariant');
});
});
describe('mapLen internal', () => {
code(() => {
class List {
head: any;
tail: List;
constructor (head, tail) {
this.head = head; this.tail = tail;
}
invariant () { return this.tail === null || this.tail instanceof List; }
}
function len (lst) {
requires(lst === null || lst instanceof List);
ensures(res => typeof(res) === 'number');
ensures(pure());
return lst === null ? 0 : 1 + len(lst.tail);
}
function map (f, lst) {
requires(lst === null || lst instanceof List);
requires(spec(f, x => true, x => pure()));
ensures(pure());
ensures(res => res === null || res instanceof List);
ensures(res => len(lst) === len(res));
len(lst);
const res = lst === null ? null : new List(f(lst.head), map(f, lst.tail));
len(res);
return res;
}
});
verified('len: lst has property "tail"');
verified('len: precondition len(lst.tail)');
verified('len: (typeof(res) === "number")');
verified('len: pure()');
verified('map: precondition len(lst)');
verified('map: lst has property "head"');
verified('map: precondition f(lst.head)');
verified('map: lst has property "tail"');
verified('map: precondition map(f, lst.tail)');
verified('map: class invariant List');
verified('map: precondition len(res)');
verified('map: pure()');
verified('map: ((res === null) || (res instanceof List))');
verified('map: (len(lst) === len(res))');
});
describe('mapLen external', () => {
code(() => {
class List {
head: any;
tail: List;
constructor (head, tail) { this.head = head; this.tail = tail; }
invariant () { return this.tail === null || this.tail instanceof List; }
}
function map (lst, f) {
requires(lst === null || lst instanceof List);
requires(spec(f, x => true, x => pure()));
ensures(pure());
ensures(res => res === null || res instanceof List);
if (lst === null) return null;
return new List(f(lst.head), map(lst.tail, f));
}
function len (lst) {
requires(lst === null || lst instanceof List);
ensures(pure());
ensures(res => typeof res === 'number' && res >= 0);
return lst === null ? 0 : len(lst.tail) + 1;
}
function mapLen (lst, f) {
requires(lst === null || lst instanceof List);
requires(spec(f, x => true, x => pure()));
ensures(pure());
ensures(len(lst) === len(map(lst, f)));
const l = len(lst);
const r = len(map(lst, f));
if (lst === null) {
assert(l === 0);
assert(r === 0);
} else {
const l1 = len(lst.tail);
assert(l === l1 + 1);
f(lst.head);
const r1 = len(map(lst.tail, f));
assert(r === r1 + 1);
mapLen(lst.tail, f);
assert(l1 === r1);
assert(l === r);
}
}
});
verified('map: lst has property "head"');
verified('map: precondition f(lst.head)');
verified('map: lst has property "tail"');
verified('map: precondition map(lst.tail, f)');
verified('map: class invariant List');
verified('map: pure()');
verified('map: ((res === null) || (res instanceof List))');
verified('len: lst has property "tail"');
verified('len: precondition len(lst.tail)');
verified('len: pure()');
verified('len: ((typeof(res) === "number") && (res >= 0))');
verified('mapLen: precondition len(lst)');
verified('mapLen: precondition map(lst, f)');
verified('mapLen: precondition len(map(lst, f))');
verified('mapLen: assert: (l === 0)');
verified('mapLen: assert: (r === 0)');
verified('mapLen: lst has property "tail"');
verified('mapLen: precondition len(lst.tail)');
verified('mapLen: assert: (l === (l1 + 1))');
verified('mapLen: lst has property "head"');
verified('mapLen: precondition f(lst.head)');
verified('mapLen: precondition map(lst.tail, f)');
verified('mapLen: precondition len(map(lst.tail, f))');
verified('mapLen: assert: (r === (r1 + 1))');
verified('mapLen: precondition mapLen(lst.tail, f)');
verified('mapLen: assert: (l1 === r1)');
verified('mapLen: assert: (l === r)');
verified('mapLen: pure()');
verified('mapLen: (len(lst) === len(map(lst, f)))');
});
describe('map invariant', () => {
code(() => {
class List {
head: any;
tail: List;
each: (element: any) => boolean;
constructor (head, tail, each) {
this.head = head; this.tail = tail; this.each = each;
}
invariant () {
return spec(this.each, x => true, (x, y) => pure() && typeof(y) === 'boolean') &&
(true && this.each)(this.head) &&
(this.tail === null || this.tail instanceof List && this.each === this.tail.each);
}
}
function map (f, lst, newEach) {
requires(spec(newEach, x => true, (x, y) => pure() && typeof(y) === 'boolean'));
requires(lst === null || spec(f, x => (true && lst.each)(x), (x, y) => pure() && newEach(y)));
requires(lst === null || lst instanceof List);
ensures(res => res === null || (res instanceof List && res.each === newEach));
ensures(pure());
if (lst === null) {
return null;
} else {
return new List(f(lst.head), map(f, lst.tail, newEach), newEach);
}
}
});
verified('map: lst has property "head"');
verified('map: lst has property "tail"');
verified('map: precondition f(lst.head)');
verified('map: precondition map(f, lst.tail, newEach)');
verified('map: class invariant List');
verified('map: pure()');
verified('map: ((res === null) || ((res instanceof List) && (res.each === newEach)))');
});
describe('map invariant method', () => {
code(() => {
// custom linked list class with predicate and map function
class List {
head: any;
tail: List;
each: (element: any) => boolean;
constructor (head, tail, each) {
this.head = head; this.tail = tail; this.each = each;
}
invariant () {
// this.each is a predicate that is true for each element
return spec(this.each, (x) => true,
(x, y) => pure() && typeof(y) === 'boolean') &&
(true && this.each)(this.head) &&
(this.tail === null ||
this.tail instanceof List && this.each === this.tail.each);
}
map (f, newEach) {
// new each neeeds to be a predicate
// (a pure function without precondition that returns a boolean)
requires(spec(newEach, (x) => true,
(x, y) => pure() && typeof(y) === 'boolean'));
// the current predicate 'this.each' must satisfy the precondition of 'f'
// and the output of 'f' needs to satisfy the new predicate
requires(spec(f, (x) => (true && this.each)(x),
(x, y) => pure() && newEach(y)));
ensures(res => res instanceof List && res.each === newEach);
ensures(pure());
return new List(
f(this.head),
this.tail === null ? null : this.tail.map(f, newEach),
newEach);
}
}
});
verified('map: this has property "head"');
verified('map: precondition f(this.head)');
verified('map: this has property "tail"');
verified('map: this.tail has property "map"');
verified('map: precondition this.tail.map(f, newEach)');
verified('map: class invariant List');
verified('map: ((res instanceof List) && (res.each === newEach))');
verified('map: pure()');
});
describe('promise', () => {
code(() => {
class Promise {
value: any;
constructor (value) {
this.value = value;
}
}
function resolve (fulfill) {
// fulfill is value, promise or then-able
requires(!('then' in fulfill) || spec(fulfill.then, () => true, () => true));
if (fulfill instanceof Promise) {
return fulfill;
} else if ('then' in fulfill) {
return new Promise(fulfill.then());
} else {
return new Promise(fulfill);
}
}
function then (promise, fulfill) {
// fulfill returns value or promise
requires(promise instanceof Promise);
requires(spec(fulfill, x => true, (x, res) => true));
const res = fulfill(promise.value);
if (res instanceof Promise) {
return res;
} else {
return new Promise(res);
}
}
const p = resolve(0);
const p2 = then(p, n => {
return n + 2;
});
const p3 = then(p2, n => {
return new Promise(n + 5);
});
});
verified('resolve: fulfill has property "then"');
verified('resolve: precondition fulfill.then()');
verified('resolve: class invariant Promise');
verified('resolve: class invariant Promise');
verified('then: promise has property "value"');
verified('then: precondition fulfill(promise.value)');
verified('then: class invariant Promise');
verified('precondition resolve(0)');
verified('precondition then(p, n => (n + 2))');
verified('func: class invariant Promise');
verified('precondition then(p2, n => new Promise((n + 5)))');
});
describe('simple class instance access', () => {
code(() => {
class A {
b: number;
constructor (b) {
this.b = b;
}
invariant () {
return this.b >= 0;
}
}
function f (a: A) {
requires(a instanceof A);
ensures(res => res >= 0);
return a.b;
}
function g (a: A) {
requires(a instanceof A);
ensures(res => res < 0);
return a.b;
}
const a = new A(23);
assert(a instanceof A);
assert(a instanceof Object);
assert('b' in a);
assert(a.b > 22);
assert(a['b'] > 22);
const p = 'b';
assert(a[p] > 22);
});
verified('f: a has property "b"');
verified('f: (res >= 0)');
verified('g: a has property "b"');
incorrect('g: (res < 0)', ['a', { _cls_: 'A', _args_: [0] }]);
verified('class invariant A');
verified('assert: (a instanceof A)');
verified('assert: (a instanceof Object)');
verified('assert: ("b" in a)');
verified('assert: (a.b > 22)');
verified('assert: (a[p] > 22)');
});
describe('static methods', () => {
code(() => {
class A {
constructor () { /* emtpy */ }
method () {
return 23;
}
}
const a = new A();
const m = a.method();
assert(m === 23);
});
verified('a has property "method"');
verified('precondition a.method()');
verified('assert: (m === 23)');
});
describe('methods', () => {
code(() => {
class Adder {
base: number;
constructor (base) {
this.base = base;
}
invariant () {
return typeof this.base === 'number';
}
addTo (n) {
requires(typeof n === 'number');
return this.base + n;
}
}
const adder = new Adder(5);
const m = adder.addTo(3);
assert(m === 8);
function f (a: Adder) {
requires(a instanceof Adder);
ensures(res => res !== 2);
return a.addTo(1);
}
});
verified('addTo: this has property "base"');
verified('class invariant Adder');
verified('adder has property "addTo"');
verified('precondition adder.addTo(3)');
verified('assert: (m === 8)');
incorrect('f: (res !== 2)', ['a', { _cls_: 'Adder', _args_: [1] }]);
});
describe('methods calling other methods', () => {
code(() => {
class A {
b: number;
constructor (b) {
this.b = b;
}
invariant () {
return typeof this.b === 'number';
}
m (x) {
requires(x >= 4);
ensures(y => y > 4);
return this.n(x) + x;
}
n (x) {
requires(x > 3);
ensures(y => y >= 1);
return 1;
}
o () {
return this.n(7);
}
p () {
requires(this.b >= 0);
ensures(y => y >= 0);
return this.b + this.n(4);
}
q () {
this.n(2);
(this as any).x();
}
r () {
return this.n(2);
}
}
const a = new A(5);
const m = a.m(4);
assert(m > 4);
const o = a.o();
assert(o === 1);
a.n(0);
const n = a.n(5);
assert(n === 1);
const p = a.p();
assert(p >= 0);
(new A(-1)).p();
});
verified('m: this has property "n"');
verified('m: precondition this.n(x)');
verified('m: (y > 4)');
verified('n: (y >= 1)');
verified('o: this has property "n"');
verified('o: precondition this.n(7)');
verified('p: this has property "b"');
verified('p: this has property "n"');
verified('p: precondition this.n(4)');
verified('p: (y >= 0)');
verified('q: this has property "n"');
incorrect('q: precondition this.n(2)', ['_this_14', { _cls_: 'A', _args_: [0] }]);
incorrect('q: this has property "x"', ['_this_14', { _cls_: 'A', _args_: [0] }]);
incorrect('q: precondition this.x()', ['_this_14', { _cls_: 'A', _args_: [-1] }]);
verified('r: this has property "n"');
incorrect('r: precondition this.n(2)', ['_this_15', { _cls_: 'A', _args_: [0] }]);
verified('class invariant A');
verified('a has property "m"');
verified('precondition a.m(4)');
verified('assert: (m > 4)');
verified('a has property "n"');
verified('a has property "o"');
verified('precondition a.o()');
unverified('assert: (o === 1)');
incorrect('precondition a.n(0)');
verified('a has property "n"');
verified('precondition a.n(5)');
verified('assert: (n === 1)');
verified('a has property "p"');
verified('precondition a.p()');
verified('assert: (p >= 0)');
verified('class invariant A');
verified('new A(-1) has property "p"');
incorrect('precondition new A(-1).p()');
});
describe('access method as function', () => {
code(() => {
class A {
constructor () { /* emtpy */ }
method () {
return 23;
}
}
const a = new A();
const m = a.method;
m();
});
verified('a has property "method"');
incorrect('precondition m()');
}); | the_stack |
import { mat4, vec3, vec4 } from 'gl-matrix';
import { assert } from './auxiliaries';
import {
decode_float24x1_from_uint8x3,
decode_uint32_from_rgba8,
} from './gl-matrix-extensions';
import { Context } from './context';
import { Framebuffer } from './framebuffer';
import { Initializable } from './initializable';
import { NdcFillingTriangle } from './ndcfillingtriangle';
import { Program } from './program';
import { Shader } from './shader';
import { Texture2D } from './texture2d';
import { GLsizei2 } from './tuples';
/* spellchecker: enable */
/**
* This stage provides means to sample G-Buffers, in order to give access to world space coordinates, depth values and
* IDs. World space coordinates are calculated by sampling the depth value and unprojecting the normalized device
* coordinates. Depth and ID values are read from the GPU by rendering the requested pixel to a 1x1 texture and reading
* back the value from this texture. Note that depth and ID values are cached as long as no redraw (frame) was invoked.
*/
export class ReadbackPass extends Initializable {
/**
* Read-only access to the objects context, used to get context information and WebGL API access.
*/
protected _context: Context;
/** @see {@link cache} */
protected _cache = false;
/** @see {@link depthFBO} */
protected _depthFBO: Framebuffer; // This is used if depth is already uint8x3 encoded
/** @see {@link depthAttachment} */
protected _depthAttachment: GLenum = 0;
/**
* Cache providing previously read depth values for a given position hash.
*/
protected _cachedDepths = new Map<GLsizei, GLfloat | undefined>();
/** @see {@link idFBO} */
protected _idFBO: Framebuffer;
/** @see {@link idAttachment} */
protected _idAttachment: GLenum;
/**
* Cache providing previously read id values for a given position hash.
*/
protected _cachedIDs = new Map<GLsizei, GLsizei | undefined>();
/**
* Buffer to read into.
*/
protected _buffer = new Uint8Array(4);
/**
* Properties required for 24bit depth readback workaround. If a valid depth format is available as renderable
* texture format, a single fragment is rasterized in order to encode the depth of at a specific location into
* uint8x3 format, rendered into a RGBA texture for readback. This workaround is currently necessary since reading
* back depth buffer data is not supported. All following protected properties are undefined when this workaround
* is not required (i.e., in IE11), since the depth texture is already rendered explicitly in a previous render
* pass.
*/
protected _texture: Texture2D;
protected _framebuffer: Framebuffer;
/**
* Coordinate reference size @see {@link coordinateReferenceSize}.
*/
protected _referenceSize: GLsizei2 | undefined;
/**
* Geometry used to draw on. This is not provided by default to allow for geometry sharing. If no triangle is given,
* the ndc triangle will be created and managed internally.
*/
protected _ndcTriangle: NdcFillingTriangle;
/**
* Tracks ownership of the ndc-filling triangle.
*/
protected _ndcTriangleShared = false;
protected _program: Program;
protected _uOffset: WebGLUniformLocation;
protected _uScale: WebGLUniformLocation;
/**
* Read the the depth of a fragment in normalized device coordinates. The implementation of this function is
* assigned at initialization based on the available WebGL features.
* @param x - Horizontal coordinate for the upper left corner of the viewport origin.
* @param y - Vertical coordinate for the upper left corner of the viewport origin.
*/
readDepthAt: (x: GLsizei, y: GLsizei) => Uint8Array;
/**
* Returns the maximal depth value that can be encoded when using a uint8[3] - @see{@link depthAt}.
*/
static maxClearDepth(): GLfloat {
return decode_float24x1_from_uint8x3(vec3.fromValues(255, 255, 255));
}
constructor(context: Context) {
super();
this._context = context;
}
/**
* Frame implementation clearing depth and ID caches. To avoid unnecessary readbacks (potentially causing sync
* points), the requested and found IDs and depths are cached by position. Hence, these cached values have to be
* cleared whenever the framebuffers are written/rendered to.
*/
protected onFrame(): void {
this._cachedDepths.clear();
this._cachedIDs.clear();
}
/**
* Create a numerical hash that can be used for efficient look-up (number preferred, no string for now). Note that
* the implementation assumes that we do not exceed 65k pixel in horizontal or vertical resolution soon.
* @param x - Horizontal coordinate from the upper left corner of the viewport origin.
* @param y - Vertical coordinate from the upper left corner of the viewport origin.
*/
protected hash(x: GLsizei, y: GLsizei): GLsizei {
return 0xffff * y + x;
}
/**
* Implements the direct readback of uint8x3 encoded depth values from a given framebuffer (see depthFBO and
* depthAttachment).
* @param x - Horizontal coordinate from the upper left corner of the viewport origin.
* @param y - Vertical coordinate from the upper left corner of the viewport origin.
* @returns - An array with 4 uint8 entries, the first three of which encode the depth.
*/
@Initializable.assert_initialized()
protected directReadDepthAt(x: GLsizei, y: GLsizei): Uint8Array {
assert(this._depthFBO !== undefined && this._depthFBO.valid, `valid depth FBO expected for reading back depth`);
const texture = this._depthFBO.texture(this._depthAttachment) as Texture2D;
const gl = this._context.gl;
const size = texture.size;
this._depthFBO.bind();
const scale = this._referenceSize === undefined ? [1.0, 1.0] :
[size[0] / this._referenceSize[0], size[1] / this._referenceSize[1]];
if (this._context.isWebGL2 || this._context.supportsDrawBuffers) {
gl.readBuffer(this._depthAttachment);
}
gl.readPixels(x * scale[0], size[1] - y * scale[1], 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, this._buffer);
return this._buffer;
}
/**
* Implements the indirect readback of uint8x3 encoded depth values from a given framebuffer (see depthFBO and
* depthAttachment). This renders a single pixel (1x1 pixel viewport) with the depth fbo as texture and reads this
* afterwards. This is a fallback required when direct pixel read from depth attachments is not supported.
* @param x - Horizontal coordinate for the upper left corner of the viewport origin.
* @param y - Vertical coordinate for the upper left corner of the viewport origin.
* @returns - An array with 4 uint8 entries, the first three of which encode the depth.
*/
@Initializable.assert_initialized()
renderThenReadDepthAt(x: GLsizei, y: GLsizei): Uint8Array {
assert(this._depthFBO !== undefined && this._depthFBO.valid, `valid depth FBO expected for reading back depth`);
const texture = this._depthFBO.texture(this._depthAttachment) as Texture2D;
const gl = this._context.gl;
const size = texture.size;
const scale = this._referenceSize === undefined ? [1.0, 1.0] :
[size[0] / this._referenceSize[0], size[1] / this._referenceSize[1]];
/* Render a single fragment, thereby encoding the depth render texture data of the requested position. */
gl.viewport(0, 0, 1, 1);
this._program.bind();
gl.uniform2f(this._uOffset, x * scale[0] / size[0], (size[1] - y * scale[1]) / size[1]);
gl.uniform2f(this._uScale, 1.0 / size[0], 1.0 / size[1]);
texture.bind(gl.TEXTURE0);
this._framebuffer.bind();
this._ndcTriangle.bind();
this._ndcTriangle.draw();
this._ndcTriangle.unbind();
texture.unbind();
/** Every stage is expected to bind its own program when drawing, thus, unbinding is not necessary. */
// this._program.unbind();
if ((this._context.isWebGL2 || this._context.supportsDrawBuffers) && gl.readBuffer) {
gl.readBuffer(gl.COLOR_ATTACHMENT0);
}
gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, this._buffer);
this._framebuffer.unbind();
return this._buffer;
}
/**
* Specializes this pass's initialization. If required. ad screen-filling triangle geometry and a single program
* are created. All attribute and dynamic uniform locations are cached.
* @param ndcTriangle - If specified, assumed to be used as shared geometry. If none is specified, a ndc-filling
* triangle will be created internally.
* @param direct - If depth is already uint8x3 encoded into a rgb/rgba target no readback workaround is required.
*/
@Initializable.initialize()
initialize(ndcTriangle: NdcFillingTriangle | undefined, direct: boolean): boolean {
const gl = this._context.gl;
const gl2facade = this._context.gl2facade;
if (direct) {
this.readDepthAt = this.directReadDepthAt;
return true;
}
/* Configure read back for depth data. */
this.readDepthAt = this.renderThenReadDepthAt;
const vert = new Shader(this._context, gl.VERTEX_SHADER, 'ndcvertices.vert (readback)');
// eslint-disable-next-line @typescript-eslint/no-var-requires
vert.initialize(require('./shaders/ndcvertices.vert'));
const frag = new Shader(this._context, gl.FRAGMENT_SHADER, 'readbackdepth.frag');
// eslint-disable-next-line @typescript-eslint/no-var-requires
frag.initialize(require('./shaders/readbackdepth.frag'));
this._program = new Program(this._context, 'ReadbackDepthProgram');
this._program.initialize([vert, frag], false);
if (ndcTriangle === undefined) {
this._ndcTriangle = new NdcFillingTriangle(this._context);
} else {
this._ndcTriangle = ndcTriangle;
this._ndcTriangleShared = true;
}
if (!this._ndcTriangle.initialized) {
this._ndcTriangle.initialize();
}
this._program.attribute('a_vertex', this._ndcTriangle.vertexLocation);
this._program.link();
this._uOffset = this._program.uniform('u_offset');
this._program.bind();
gl.uniform1i(this._program.uniform('u_texture'), 0);
this._program.unbind();
/* Configure read back framebuffer and color attachment. */
this._texture = new Texture2D(this._context, 'ReadbackRenderTexture');
this._texture.initialize(1, 1, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE);
this._framebuffer = new Framebuffer(this._context, 'ReadbackFBO');
this._framebuffer.initialize([[gl2facade.COLOR_ATTACHMENT0, this._texture]]);
return true;
}
/**
* Specializes this stage's uninitialization. Program and geometry resources are released (if allocated). Cached
* uniform and attribute locations are invalidated.
*/
@Initializable.uninitialize()
uninitialize(): void {
if (this._context.isWebGL1 && !this._context.supportsDepthTexture) {
return;
}
if (!this._ndcTriangleShared && this._ndcTriangle.initialized) {
this._ndcTriangle.uninitialize();
}
this._program.uninitialize();
this._texture.uninitialize();
this._framebuffer.uninitialize();
}
/**
* Retrieve the depth of a fragment in normalized device coordinates. The implementation of this function is
* assigned at initialization based on the available WebGL features. Please note that in order to get the far plane
* depth at just below 1.0, the clear depth should be set to:
* float24x1_from_uint8x3([255,255, 255]) = 0.9999999403953552
* This will result in a readback of [255, 255, 255] and is the deepest depth value representable using a uint8x3.
* Using 1.0 should result in [256, 0, 0] and would be easy to detect, however, it is somehow clamped to [255, 0, 0]
* which is highly misleading and actual not nearly the far plane's depth. Thus, if [255, 255, 255] is read back,
* undefined will be returned by this query and thereby reduce the effective depth range by 1 over 255^3 - sorry.
* @param x - Horizontal coordinate for the upper left corner of the viewport origin.
* @param y - Vertical coordinate for the upper left corner of the viewport origin.
*/
@Initializable.assert_initialized()
depthAt(x: GLsizei, y: GLsizei): GLfloat | undefined {
const hash = this.hash(x, y);
if (this._cache && this._cachedDepths.has(hash)) {
return this._cachedDepths.get(hash);
}
const buffer: Uint8Array = this.readDepthAt(x, y);
/* See notes above for more info on this weird convention. */
const depth: GLfloat | undefined = buffer[0] === 255 && buffer[1] === 255 && buffer[2] === 255 ?
undefined : decode_float24x1_from_uint8x3(vec3.fromValues(buffer[0], buffer[1], buffer[2]));
if (this._cache) {
this._cachedDepths.set(hash, depth);
}
return depth;
}
/**
* Retrieving the world space coordinate of a fragment.
* @param x - Horizontal coordinate for the upper left corner of the viewport origin.
* @param y - Vertical coordinate for the upper left corner of the viewport origin.
* @param zInNDC - optional depth parameter (e.g., from previous query).
* @param viewProjectionInverse - matrix used to unproject the coordinate from ndc to world space.
* @returns - The unprojected world space coordinate at location x, y.
*/
@Initializable.assert_initialized()
coordsAt(x: GLsizei, y: GLsizei, zInNDC: number | undefined, viewProjectionInverse: mat4): vec3 | undefined {
const size = (this._depthFBO.texture(this._depthAttachment) as Texture2D).size;
const depth = zInNDC === undefined ? this.depthAt(x, y) : zInNDC;
if (depth === undefined) {
return undefined;
}
const scale = this._referenceSize === undefined ? [1.0, 1.0] :
[size[0] / this._referenceSize[0], size[1] / this._referenceSize[1]];
const p = vec3.fromValues(
x * scale[0] * 2.0 / size[0] - 1.0, 1.0 - y * scale[1] * 2.0 / size[1], depth * 2.0 - 1.0);
return vec3.transformMat4(vec3.create(), p, viewProjectionInverse);
}
/**
* Retrieve the id of an object at fragment position.
* @param x - Horizontal coordinate for the upper left corner of the viewport origin.
* @param y - Vertical coordinate for the upper left corner of the viewport origin.
* @returns - The id rendered at location x, y.
*/
@Initializable.assert_initialized()
idAt(x: GLsizei, y: GLsizei): GLsizei | undefined {
const hash = this.hash(x, y);
if (this._cache && this._cachedIDs.has(hash)) {
return this._cachedIDs.get(hash);
}
const gl = this._context.gl;
const size = (this._idFBO.texture(this._idAttachment) as Texture2D).size;
const scale = this._referenceSize === undefined ? [1.0, 1.0] :
[size[0] / this._referenceSize[0], size[1] / this._referenceSize[1]];
this._idFBO.bind();
if (this._context.isWebGL2) {
gl.readBuffer(this._idAttachment);
}
gl.readPixels(x * scale[0], size[1] - y * scale[1], 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, this._buffer);
const id = decode_uint32_from_rgba8(
vec4.fromValues(this._buffer[0], this._buffer[1], this._buffer[2], this._buffer[3]));
if (this._cache) {
this._cachedIDs.set(hash, id);
}
return id;
}
/**
* Invokes the frame implementation @see{@link onFrame}.
*/
frame(): void {
this.onFrame();
}
/**
* Whether or not caching of requested depths and ids should be used to reduce performance impact.
*/
set cache(value: boolean) {
this._cache = value;
}
/**
* Sets the framebuffer object that is to be used for depth readback.
* @param framebuffer - Framebuffer that is to be used for depth readback.
*/
set depthFBO(framebuffer: Framebuffer) {
this._depthFBO = framebuffer;
}
/**
* Sets the framebuffer's {@link depthFBO} depth attachment that is to be used for depth readback.
* @param attachment - Depth attachment that is to be used for depth readback.
*/
set depthAttachment(attachment: GLenum) {
this._depthAttachment = attachment;
}
/**
* Sets the framebuffer object that is to be used for id readback.
* @param framebuffer - Framebuffer that is to be used for id readback.
*/
set idFBO(framebuffer: Framebuffer) {
this._idFBO = framebuffer;
}
/**
* Sets the framebuffer's {@link idFBO} id attachment that is to be used for id readback.
* @param attachment - ID attachment that is to be used for id readback.
*/
set idAttachment(attachment: GLenum) {
this._idAttachment = attachment;
}
/**
* Sets the coordinate-reference size that is, if not undefined, used to scale incomming x and y coordinates.
* @param size - Size of the output, e.g., the canvas, the buffer is rendered to.
*/
set coordinateReferenceSize(size: GLsizei2 | undefined) {
this._referenceSize = size;
}
} | the_stack |
import {
unsignedLEB128,
signedLEB128,
encodeString,
ieee754
} from "./encoding";
import traverse from "./traverse";
const flatten = (arr: any[]) => [].concat.apply([], arr);
// https://webassembly.github.io/spec/core/binary/modules.html#sections
enum Section {
custom = 0,
type = 1,
import = 2,
func = 3,
table = 4,
memory = 5,
global = 6,
export = 7,
start = 8,
element = 9,
code = 10,
data = 11
}
// https://webassembly.github.io/spec/core/binary/types.html
enum Valtype {
i32 = 0x7f,
f32 = 0x7d
}
// https://webassembly.github.io/spec/core/binary/types.html#binary-blocktype
enum Blocktype {
void = 0x40
}
// https://webassembly.github.io/spec/core/binary/instructions.html
enum Opcodes {
block = 0x02,
loop = 0x03,
br = 0x0c,
br_if = 0x0d,
end = 0x0b,
call = 0x10,
get_local = 0x20,
set_local = 0x21,
i32_store_8 = 0x3a,
i32_const = 0x41,
f32_const = 0x43,
i32_eqz = 0x45,
i32_eq = 0x46,
f32_eq = 0x5b,
f32_lt = 0x5d,
f32_gt = 0x5e,
i32_and = 0x71,
f32_add = 0x92,
f32_sub = 0x93,
f32_mul = 0x94,
f32_div = 0x95,
i32_trunc_f32_s = 0xa8
}
const binaryOpcode = {
"+": Opcodes.f32_add,
"-": Opcodes.f32_sub,
"*": Opcodes.f32_mul,
"/": Opcodes.f32_div,
"==": Opcodes.f32_eq,
">": Opcodes.f32_gt,
"<": Opcodes.f32_lt,
"&&": Opcodes.i32_and
};
// http://webassembly.github.io/spec/core/binary/modules.html#export-section
enum ExportType {
func = 0x00,
table = 0x01,
mem = 0x02,
global = 0x03
}
// http://webassembly.github.io/spec/core/binary/types.html#function-types
const functionType = 0x60;
const emptyArray = 0x0;
// https://webassembly.github.io/spec/core/binary/modules.html#binary-module
const magicModuleHeader = [0x00, 0x61, 0x73, 0x6d];
const moduleVersion = [0x01, 0x00, 0x00, 0x00];
// https://webassembly.github.io/spec/core/binary/conventions.html#binary-vec
// Vectors are encoded with their length followed by their element sequence
const encodeVector = (data: any[]) => [
...unsignedLEB128(data.length),
...flatten(data)
];
// https://webassembly.github.io/spec/core/binary/modules.html#code-section
const encodeLocal = (count: number, type: Valtype) => [
...unsignedLEB128(count),
type
];
// https://webassembly.github.io/spec/core/binary/modules.html#sections
// sections are encoded by their type followed by their vector contents
const createSection = (sectionType: Section, data: any[]) => [
sectionType,
...encodeVector(data)
];
const codeFromProc = (node: ProcStatementNode, program: TransformedProgram) => {
const code: number[] = [];
const symbols = new Map<string, number>(
node.args.map((arg, index) => [arg.value, index])
);
const localIndexForSymbol = (name: string) => {
if (!symbols.has(name)) {
symbols.set(name, symbols.size);
}
return symbols.get(name);
};
const emitExpression = (node: ExpressionNode) =>
traverse(node, (node: ExpressionNode) => {
switch (node.type) {
case "numberLiteral":
code.push(Opcodes.f32_const);
code.push(...ieee754(node.value));
break;
case "identifier":
code.push(Opcodes.get_local);
code.push(...unsignedLEB128(localIndexForSymbol(node.value)));
break;
case "binaryExpression":
code.push(binaryOpcode[node.operator]);
break;
}
});
const emitStatements = (statements: StatementNode[]) =>
statements.forEach(statement => {
switch (statement.type) {
case "printStatement":
emitExpression(statement.expression);
code.push(Opcodes.call);
code.push(...unsignedLEB128(0));
break;
case "variableDeclaration":
emitExpression(statement.initializer);
code.push(Opcodes.set_local);
code.push(...unsignedLEB128(localIndexForSymbol(statement.name)));
break;
case "variableAssignment":
emitExpression(statement.value);
code.push(Opcodes.set_local);
code.push(...unsignedLEB128(localIndexForSymbol(statement.name)));
break;
case "whileStatement":
// outer block
code.push(Opcodes.block);
code.push(Blocktype.void);
// inner loop
code.push(Opcodes.loop);
code.push(Blocktype.void);
// compute the while expression
emitExpression(statement.expression);
code.push(Opcodes.i32_eqz);
// br_if $label0
code.push(Opcodes.br_if);
code.push(...signedLEB128(1));
// the nested logic
emitStatements(statement.statements);
// br $label1
code.push(Opcodes.br);
code.push(...signedLEB128(0));
// end loop
code.push(Opcodes.end);
// end block
code.push(Opcodes.end);
break;
case "ifStatement":
// if block
code.push(Opcodes.block);
code.push(Blocktype.void);
// compute the if expression
emitExpression(statement.expression);
code.push(Opcodes.i32_eqz);
// br_if $label0
code.push(Opcodes.br_if);
code.push(...signedLEB128(0));
// the nested logic
emitStatements(statement.consequent);
// end block
code.push(Opcodes.end);
// else block
code.push(Opcodes.block);
code.push(Blocktype.void);
// compute the if expression
emitExpression(statement.expression);
code.push(Opcodes.i32_const);
code.push(...signedLEB128(1));
code.push(Opcodes.i32_eq);
// br_if $label0
code.push(Opcodes.br_if);
code.push(...signedLEB128(0));
// the nested logic
emitStatements(statement.alternate);
// end block
code.push(Opcodes.end);
break;
case "callStatement":
if (statement.name === "setpixel") {
// compute and cache the setpixel parameters
emitExpression(statement.args[0]);
code.push(Opcodes.set_local);
code.push(...unsignedLEB128(localIndexForSymbol("x")));
emitExpression(statement.args[1]);
code.push(Opcodes.set_local);
code.push(...unsignedLEB128(localIndexForSymbol("y")));
emitExpression(statement.args[2]);
code.push(Opcodes.set_local);
code.push(...unsignedLEB128(localIndexForSymbol("color")));
// compute the offset (x * 100) + y
code.push(Opcodes.get_local);
code.push(...unsignedLEB128(localIndexForSymbol("y")));
code.push(Opcodes.f32_const);
code.push(...ieee754(100));
code.push(Opcodes.f32_mul);
code.push(Opcodes.get_local);
code.push(...unsignedLEB128(localIndexForSymbol("x")));
code.push(Opcodes.f32_add);
// convert to an integer
code.push(Opcodes.i32_trunc_f32_s);
// fetch the color
code.push(Opcodes.get_local);
code.push(...unsignedLEB128(localIndexForSymbol("color")));
code.push(Opcodes.i32_trunc_f32_s);
// write
code.push(Opcodes.i32_store_8);
code.push(...[0x00, 0x00]); // align and offset
} else {
statement.args.forEach(arg => {
emitExpression(arg);
});
const index = program.findIndex(f => f.name === statement.name);
code.push(Opcodes.call);
code.push(...unsignedLEB128(index + 1));
}
break;
}
});
emitStatements(node.statements);
const localCount = symbols.size;
const locals = localCount > 0 ? [encodeLocal(localCount, Valtype.f32)] : [];
return encodeVector([...encodeVector(locals), ...code, Opcodes.end]);
};
export const emitter: Emitter = (ast: TransformedProgram) => {
// Function types are vectors of parameters and return types. Currently
// WebAssembly only supports single return values
const printFunctionType = [
functionType,
...encodeVector([Valtype.f32]),
emptyArray
];
// TODO: optimise - some of the procs might have the same type signature
const funcTypes = ast.map(proc => [
functionType,
...encodeVector(proc.args.map(_ => Valtype.f32)),
emptyArray
]);
// the type section is a vector of function types
const typeSection = createSection(
Section.type,
encodeVector([printFunctionType, ...funcTypes])
);
// the function section is a vector of type indices that indicate the type of each function
// in the code section
const funcSection = createSection(
Section.func,
encodeVector(ast.map((_, index) => index + 1 /* type index */))
);
// the import section is a vector of imported functions
const printFunctionImport = [
...encodeString("env"),
...encodeString("print"),
ExportType.func,
0x00 // type index
];
const memoryImport = [
...encodeString("env"),
...encodeString("memory"),
ExportType.mem,
/* limits https://webassembly.github.io/spec/core/binary/types.html#limits -
indicates a min memory size of one page */
0x00,
0x01
];
const importSection = createSection(
Section.import,
encodeVector([printFunctionImport, memoryImport])
);
// the export section is a vector of exported functions
const exportSection = createSection(
Section.export,
encodeVector([
[
...encodeString("run"),
ExportType.func,
ast.findIndex(a => a.name === "main") + 1
]
])
);
// the code section contains vectors of functions
const codeSection = createSection(
Section.code,
encodeVector(ast.map(a => codeFromProc(a, ast)))
);
return Uint8Array.from([
...magicModuleHeader,
...moduleVersion,
...typeSection,
...importSection,
...funcSection,
...exportSection,
...codeSection
]);
}; | the_stack |
import { CommonModule } from '@angular/common';
import {
AfterViewInit,
Component,
ElementRef,
EventEmitter,
Inject,
Input,
NgModule,
Output,
ViewChild,
} from '@angular/core';
import {
FormsModule,
} from '@angular/forms';
import { CRS, latLng, LatLngBounds, Point } from 'leaflet';
import { IExampleProperties } from './app-component-blueprint';
/* tslint:disable:max-line-length */
export const PROPERTIES_WRAPPER: string = `<div class="row">
<div class="col-md-4">
<h3>Duplex</h3>
<example-property *ngFor="let property of properties.duplex" [name]="property.name" [type]="property.type" [(value)]="property.value" [additional]="property.additional"></example-property>
</div>
<div class="col-md-4">
<h3>Output</h3>
<example-property *ngFor="let property of properties.output" [name]="property.name" [type]="property.type" [value]="property.value" [additional]="property.additional"></example-property>
</div>
<div class="col-md-4">
<h3>Input</h3>
<example-property *ngFor="let property of properties.input" [name]="property.name" [type]="property.type" [(value)]="property.value" [additional]="property.additional"></example-property>
</div>
</div>`;
/* tslint:enable */
/* tslint:disable:max-line-length */
@Component({
selector: 'example-property',
template: `
<div *ngIf="type === 'text'" class="input-group btn-group-sm">
<div class="input-group-prepend">
<span class="input-group-text fixed-space">{{ name }}</span>
</div>
<input type="text" class="form-control" [ngModel]="value" (ngModelChange)="valueChange.emit($event)" />
</div>
<div *ngIf="type === 'number'" class="input-group btn-group-sm">
<div class="input-group-prepend">
<span class="input-group-text fixed-space">{{ name }}</span>
</div>
<input type="number" class="form-control" [ngModel]="value" (ngModelChange)="valueChange.emit($event)" />
</div>
<div *ngIf="type === 'event'" class="btn-group btn-group-sm">
<button disabled class="btn" [ngClass]="value ? 'btn-primary': ''">{{ name }}</button>
</div>
<div *ngIf="type === 'checkbox'" class="input-group">
<div class="input-group-prepend">
<span class="input-group-text fixed-space">{{ name }}</span>
</div>
<input type="checkbox" class="form-control" [ngModel]="value" (ngModelChange)="valueChange.emit($event)" />
</div>
<div *ngIf="type === 'select'" class="input-group">
<div class="input-group-prepend">
<span class="input-group-text fixed-space">{{ name }}</span>
</div>
<select class="form-control" [ngModel]="value" (ngModelChange)="valueChange.emit($event)">
<option *ngFor="let state of additional.states" [ngValue]="state">
{{ state }}
</option>
</select>
</div>
<div *ngIf="type === 'relative'" class="input-group">
<div class="input-group-prepend">
<span class="input-group-text fixed-space">{{ name }}</span>
</div>
<input type="range" min="0" max="1" step="0.05" class="form-control" [ngModel]="value" (ngModelChange)="valueChange.emit($event)" />
</div>
<div *ngIf="type === 'latlng'">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text fixed-space">{{ name }}</span>
</div>
<input type="number" class="form-control" [ngModel]="value.lat" (ngModelChange)="valueChange.emit(updateLat($event))" />
<input type="number" class="form-control" [ngModel]="value.lng" (ngModelChange)="valueChange.emit(updateLng($event))" />
</div>
</div>
<div *ngIf="type === 'latlngBounds'">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text fixed-space">{{ name }} (SWNE)</span>
</div>
<input type="number" class="form-control" [ngModel]="value.getSouth()" (ngModelChange)="valueChange.emit(updateLatLngBoundsSouth($event))" />
<input type="number" class="form-control" [ngModel]="value.getWest()" (ngModelChange)="valueChange.emit(updateLatLngBoundsWest($event))" />
<input type="number" class="form-control" [ngModel]="value.getNorth()" (ngModelChange)="valueChange.emit(updateLatLngBoundsNorth($event))" />
<input type="number" class="form-control" [ngModel]="value.getEast()" (ngModelChange)="valueChange.emit(updateLatLngBoundsEast($event))" />
</div>
</div>
<div *ngIf="type === 'point'">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text fixed-space">{{ name }}</span>
</div>
<input type="number" class="form-control" [ngModel]="value.x" (ngModelChange)="valueChange.emit(updatePointX($event))" />
<input type="number" class="form-control" [ngModel]="value.y" (ngModelChange)="valueChange.emit(updatePointY($event))" />
</div>
</div>
<div *ngIf="type === 'crs'">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text fixed-space">{{ name }}</span>
</div>
<select [ngModel]="getCRS(value)" (ngModelChange)="valueChange.emit(setCRS($event))">
<option value="Simple">Simple</option>
<option value="EPSG3395">EPSG:3395</option>
<option value="EPSG3857">EPSG:3857</option>
<option value="EPSG4326">EPSG:4326</option>
</select>
</div>
</div>
<div *ngIf="type === 'text[]'">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text fixed-space">{{ name }}</span>
</div>
</div>
<div *ngFor="let entry of value" class="input-group">
<div class="input-group-prepend">
<span class="input-group-text fixed-space">{{ value.indexOf(entry) + 1 }}</span>
</div>
<input type="text" class="form-control" [ngModel]="entry" (ngModelChange)="updateInArray($event, entry)" />
<span class="input-group-btn"><button class="btn btn-danger" (click)="spliceArray(entry)"><span class="fa fa-minus"></span></button></span>
</div>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text fixed-space">{{ name }}</span>
</div>
<input type="text" class="form-control" placeholder="Add an element to array" [(ngModel)]="addToArrayValue">
<span class="input-group-btn"><button class="btn btn-success" (click)="addToArray(addToArrayValue)"><span class="fa fa-plus"></span></button></span>
</div>
</div>`,
})
/* tslint:enable */
export class ExamplePropertyComponent {
@Output() public valueChange: EventEmitter<any> = new EventEmitter();
@Input() public name: string;
@Input() public type: string;
@Input() public value: any;
@Input() public additional: any;
public addToArrayValue: any;
public addToArray(value: any): void {
this.value.push(value);
this.valueChange.emit(this.value);
}
public updateInArray(value: any, element: any): void {
this.value[(<any[]> this.value).indexOf(element)] = value;
this.valueChange.emit(this.value);
}
public spliceArray(element: any): void {
this.value.splice(this.value.indexOf(element), 1);
this.valueChange.emit(this.value);
}
public updateLat(value: number) {
this.value.lat = value;
this.value = this.value.clone();
this.valueChange.emit(this.value);
}
public updateLng(value: number) {
this.value.lng = value;
this.value = this.value.clone();
this.valueChange.emit(this.value);
}
public updatePointX(value: number): Point {
this.value.x = value;
this.value = this.value.clone();
return this.value;
}
public updatePointY(value: number): Point {
this.value.y = value;
this.value = this.value.clone();
return this.value;
}
public updateLatLngBoundsSouth(value: number): LatLngBounds {
this.value = new LatLngBounds(
latLng(value, (this.value as LatLngBounds).getWest()),
latLng((this.value as LatLngBounds).getNorth(), (this.value as LatLngBounds).getEast()),
);
return this.value;
}
public updateLatLngBoundsWest(value: number): LatLngBounds {
this.value = new LatLngBounds(
latLng((this.value as LatLngBounds).getSouth(), value),
latLng((this.value as LatLngBounds).getNorth(), (this.value as LatLngBounds).getEast()),
);
return this.value;
}
public updateLatLngBoundsNorth(value: number): LatLngBounds {
this.value = new LatLngBounds(
latLng((this.value as LatLngBounds).getSouth(), (this.value as LatLngBounds).getWest()),
latLng(value, (this.value as LatLngBounds).getEast()),
);
return this.value;
}
public updateLatLngBoundsEast(value: number): LatLngBounds {
this.value = new LatLngBounds(
latLng((this.value as LatLngBounds).getSouth(), (this.value as LatLngBounds).getWest()),
latLng((this.value as LatLngBounds).getNorth(), value),
);
return this.value;
}
public getCRS(value: CRS): string {
switch (value) {
case CRS.EPSG3857:
return 'EPSG3857';
case CRS.EPSG3395:
return 'EPSG3395';
case CRS.EPSG4326:
return 'EPSG4326';
case CRS.Simple:
return 'Simple';
}
}
public setCRS(value: string): CRS {
return CRS[value];
}
}
/* tslint:disable:max-classes-per-file */
@Component({
selector: 'example-properties',
template: PROPERTIES_WRAPPER,
})
export class ExamplePropertiesComponent {
@Output() public propertiesChange: EventEmitter<IExampleProperties> = new EventEmitter();
@Input() public properties: IExampleProperties;
}
/* tslint:disable:max-line-length max-classes-per-file */
@Component({
selector: 'example-header',
template: `
<header role="navigation" class="navbar navbar-expand-lg navbar-dark bg-dark shadow-sm">
<div class="container">
<a class="navbar-brand" href="https://yagajs.org">YAGA</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="nav navbar-nav">
<li class="nav-item nav-link"><a href="https://leaflet-ng2.yagajs.org" title="leaflet-ng2" class="nav-link"><span class="fa fa-cube" aria-hidden="true"></span> leaflet-ng2</a></li>
<li class="nav-item nav-link"><a href="../../" title="Last release" class="nav-link"><span class="fa fa-flag" aria-hidden="true"></span> Release</a></li>
<li class="nav-item nav-link active"><a href="../" title="YAGA Examples" class="nav-link"><span class="fa fa-tv" aria-hidden="true"></span> Examples</a></li>
<li class="nav-item nav-link active"><a href="#" class="nav-link"><span class="fa fa-stethoscope" aria-hidden="true"></span> {{ title }}</a></li>
</ul>
</div>
</div>
</header>`,
})
export class ExampleHeaderComponent {
@Input() public title: string;
}
/* tslint:enable */
/* tslint:disable:max-line-length max-classes-per-file */
@Component({
selector: 'example-footer',
template: `
<footer class="footer">
<div class="container">
<p class="text-muted">© <a href="https://yagajs.org">YAGA</a> 2018. Links:
<span>
<a href="https://github.com/yagajs/">GitHub</a>
</span>
<span>
<a href="https://npmjs.org/org/yaga/">NPM</a>
</span>
</p>
</div>
</footer>`,
})
export class ExampleFooterComponent {}
@NgModule({
declarations: [
ExamplePropertyComponent,
ExamplePropertiesComponent,
ExampleHeaderComponent,
ExampleFooterComponent,
],
exports: [
ExamplePropertyComponent,
ExamplePropertiesComponent,
ExampleHeaderComponent,
ExampleFooterComponent,
],
imports: [
CommonModule,
FormsModule,
],
})
export class ExamplePropertiesModule { } | the_stack |
import { TypedEmitter } from "tiny-typed-emitter";
import { fixEnt } from "string-fix-broken-named-entities";
import { traverse } from "ast-monkey-traverse";
import { lineCol, getLineStartIndexes } from "line-column-mini";
import clone from "lodash.clonedeep";
import { cparser } from "codsen-parser";
import { keys } from "ts-transformer-keys";
import validateCharEncoding from "../src/util/validateCharEncoding";
import { get, normaliseRequestedRules } from "./rules";
import {
isAnEnabledValue,
isAnEnabledRule,
astErrMessages,
isObj,
} from "./util/util";
import {
Obj,
ErrorObj,
Attrib,
Severity,
Config,
MessageObj,
Ranges,
RulesObj,
EventNames,
RuleObjType,
} from "./util/commonTypes";
interface ErrorObjWithRuleId extends ErrorObj {
ruleId: string;
}
// disable the max limit of listeners
TypedEmitter.defaultMaxListeners = 0;
/**
* Pluggable email template code linter
*/
class Linter extends TypedEmitter<RuleObjType> {
constructor() {
super();
this.messages = [];
this.str = "";
this.strLineStartIndexes = [];
this.config = {} as Config;
this.hasBeenCalledWithKeepSeparateWhenFixing = false;
this.processedRulesConfig = {} as RulesObj;
}
messages: MessageObj[];
str: string;
strLineStartIndexes: number[]; // comes from line-column-mini
config: Config;
hasBeenCalledWithKeepSeparateWhenFixing: boolean;
processedRulesConfig: RulesObj;
verify(str: string, config: Config): ErrorObj[] {
this.messages = [];
this.str = str;
// calculate line start indexes for row/column
// reporting later, it allows line-column-mini to cut corners
this.strLineStartIndexes = getLineStartIndexes(str);
this.config = clone(config);
this.hasBeenCalledWithKeepSeparateWhenFixing = false;
this.processedRulesConfig = {};
const has = Object.prototype.hasOwnProperty;
// console.log(
// `069 ${`\u001b[${31}m${`██`}\u001b[${39}m`}${`\u001b[${33}m${`██`}\u001b[${39}m`} ${`\u001b[${32}m${`linter.js`}\u001b[${39}m`}: verify called for "${str}" and ${JSON.stringify(
// config,
// null,
// 4
// )}`
// );
// VALIDATION FIRST
if (config) {
if (typeof config !== "object") {
throw new Error(
`emlint/verify(): [THROW_ID_01] second input argument, config is not a plain object but ${typeof config}. It's equal to:\n${JSON.stringify(
config,
null,
4
)}`
);
} else if (!Object.keys(config).length) {
// empty config => early return
return [];
} else if (!config.rules || typeof config.rules !== "object") {
throw new Error(
`emlint/verify(): [THROW_ID_02] config contains no rules! It was given as:\n${JSON.stringify(
config,
null,
4
)}`
);
}
} else {
// falsey config => early return
return [];
}
// detect the language
// const lang = detectLanguage(str);
// filter out all applicable values and make them listen for events that
// tokenizer emits
// TODO - rebase, avoid using const, assign directly to "this."
const processedRulesConfig = normaliseRequestedRules(config.rules);
console.log(
`110 ${`\u001b[${33}m${`processedRulesConfig`}\u001b[${39}m`} = ${JSON.stringify(
processedRulesConfig,
null,
4
)}`
);
this.processedRulesConfig = processedRulesConfig;
Object.keys(processedRulesConfig)
// filter out the rules coming from external packages - they'll be
// processed separately, in the callbacks coming out of external packages,
// see the section "rules coming from standalone packages".
.filter((ruleName) => get(ruleName))
// filter out enabled rules:
.filter((ruleName) => {
// same config like in ESLint - 0 is off, 1 is warning, 2 is error
if (typeof processedRulesConfig[ruleName] === "number") {
return processedRulesConfig[ruleName] > 0;
}
if (Array.isArray(processedRulesConfig[ruleName])) {
console.log(
`131 ███████████████████████████████████████ ${`\u001b[${33}m${`ruleName`}\u001b[${39}m`} = ${JSON.stringify(
ruleName,
null,
4
)}`
);
return (processedRulesConfig as any)[ruleName][0] > 0;
}
return false;
})
.forEach((rule) => {
console.log(
`143 ${`\u001b[${32}m${`linter.js`}\u001b[${39}m`}: filtering rule ${rule}`
);
// extract all the options, second array element onwards - the length is indeterminable
let rulesFunction: RulesObj;
if (
Array.isArray(processedRulesConfig[rule]) &&
(processedRulesConfig[rule] as any).length > 1
) {
// pass not only "this", the context, but also all the opts, as args
rulesFunction = get(rule)(
this,
...(processedRulesConfig as any)[rule].slice(1)
);
} else {
// just pass "this", the context
rulesFunction = get(rule)(this);
}
Object.keys(rulesFunction).forEach((consumedNode: string) => {
this.on(consumedNode as EventNames, (...args: any[]) => {
// console.log(
// `106 ${`\u001b[${32}m${`linter.js`}\u001b[${39}m`}: ${`\u001b[${33}m${`consumedNode`}\u001b[${39}m`} = ${JSON.stringify(
// consumedNode,
// null,
// 4
// )}`
// );
(rulesFunction as Obj)[consumedNode](...args);
});
});
});
// emlint runs on codsen-parser which in turn runs on codsen-tokenizer.
// Tokenizer recognises string as various token types and "pings" the
// callback function given to the tokenizer with those lumps, plain objects.
// Now, Parser consumes those tokens and assembles a tree, an AST.
// EMLint is plugin-based. Plugins work on code source - consuming either
// raw tokens, each token of particular kind, listening to event emitted
// called after that token type, or plugins consume whole AST, listening
// to "ast"-type event.
// Now, the less work done the faster program runs.
// The quickest way for emlint to obtain tokens is from codsen-parser,
// to tap them raw, bypassing the AST tree, as they come from tokenizer.
// But the problem is, this approach does not work with broken code.
// We can't consume tokenizer's nodes because parser can change the
// nodes, correcting the errors - it's possible because parser "sees" the
// whole picture.
// Therefore, we don't consume tokens from the tokenizer, we consume AST
// from parser, then we send the monkey (ast-monkey-traverse) to traverse
// that AST and emit the token events.
this.emit(
"ast",
traverse(
cparser(str, {
charCb: (obj) => {
// We call the character-level callback from raw characters, coming
// if from parser which comes straight from tokenizer.
// console.log(
// `160 ██ ${`\u001b[${35}m${`linter/charCb():`}\u001b[${39}m`} incoming ${`\u001b[${33}m${`obj`}\u001b[${39}m`} = ${JSON.stringify(
// obj,
// null,
// 4
// )}`
// );
this.emit("character", obj);
},
errCb: (obj) => {
console.log(
`221 ██ ${`\u001b[${35}m${`linter/errCb():`}\u001b[${39}m`} incoming ${`\u001b[${33}m${`obj`}\u001b[${39}m`} = ${JSON.stringify(
obj,
null,
4
)}`
);
console.log(
`228 ${`\u001b[${33}m${`config.rules`}\u001b[${39}m`} = ${JSON.stringify(
config.rules,
null,
4
)}`
);
// check, is rule enabled at the first place:
const currentRulesSeverity: Severity = isAnEnabledRule(
config.rules,
obj.ruleId as string
);
if (currentRulesSeverity) {
let message = `Something is wrong.`;
if (
isObj(obj) &&
typeof obj.ruleId === "string" &&
has.call(astErrMessages, obj.ruleId)
) {
message = (astErrMessages as any)[obj.ruleId];
}
console.log(
`252 ${`\u001b[${32}m${`REPORT`}\u001b[${39}m`} "${message}"`
);
this.report({
message,
severity: currentRulesSeverity,
fix: null,
...(obj as any),
});
}
},
}),
(key, val, innerObj) => {
const current = val !== undefined ? val : key;
if (
isObj(current) &&
(!innerObj.parentKey || !innerObj.parentKey.startsWith("attrib"))
) {
// console.log(` `);
// console.log(
// `-----------------------------------------------------------------------------`
// );
// console.log(` `);
// console.log(
// `275 ${`\u001b[${33}m${`██`}\u001b[${39}m`} ${`\u001b[${33}m${`innerObj`}\u001b[${39}m`} = ${JSON.stringify(
// innerObj,
// null,
// 4
// )}`
// );
// monkey will traverse every key, every string within.
// We need to pick the objects of a type we need: "tag", "comment" etc.
// tag-level callback
// console.log(
// `286 ██ ${`\u001b[${35}m${`linter/tagCb():`}\u001b[${39}m`} PING ${
// current.type
// } - ${`\u001b[${33}m${`current`}\u001b[${39}m`} = ${JSON.stringify(
// current,
// null,
// 4
// )}`
// );
this.emit(current.type, current);
// plus, for type:html also ping each attribute
if (
current.type === "tag" &&
Array.isArray(current.attribs) &&
current.attribs.length
) {
current.attribs.forEach((attribObj: Attrib) => {
console.log(
`303 ${`\u001b[${36}m${`██`}\u001b[${39}m`} ping attribute ${JSON.stringify(
attribObj,
null,
4
)}`
);
this.emit("attribute", {
...attribObj,
parent: { ...current },
});
});
}
}
return current;
}
)
);
console.log(` `);
console.log(
`-----------------------------------------------------------------------------`
);
console.log(` `);
//
//
//
//
//
//
// rules coming from standalone packages
//
//
//
//
//
//
// 1. if any of bad named HTML entity catcher rules is requested, run it
// rules come from "string-fix-broken-named-entities":
// - bad-html-entity-malformed-...
// - bad-html-entity-malformed-numeric
// - bad-html-entity-encoded-...
// - bad-html-entity-encoded-numeric
// - bad-html-entity-unrecognised
// - bad-html-entity-multiple-encoding
// 2. also, using the raw ampersand-as-text catcher, feed
// the rule "character-encode" - we need to be aware which
// ampersand is raw text, which-one is part of entity
let severity: 0 | 1 | 2 = 0;
const letsCatchBadEntities = Object.keys(config.rules).some(
(ruleName) =>
(ruleName === "all" || ruleName.startsWith("bad-html-entity")) &&
(severity =
isAnEnabledValue(config.rules[ruleName]) ||
isAnEnabledValue(processedRulesConfig[ruleName]))
);
const letsCatchRawTextAmpersands = Object.keys(config.rules).some(
(ruleName) =>
(ruleName === "all" || ruleName === "character-encode") &&
(isAnEnabledValue(config.rules[ruleName]) ||
isAnEnabledValue(processedRulesConfig[ruleName]))
);
if (letsCatchBadEntities || letsCatchRawTextAmpersands) {
console.log(
`370 linter.js: we'll call fixEnt(); ${`\u001b[${
letsCatchBadEntities ? 32 : 31
}m${"letsCatchBadEntities"}\u001b[${39}m`}; ${`\u001b[${
letsCatchRawTextAmpersands ? 32 : 31
}m${"letsCatchRawTextAmpersands"}\u001b[${39}m`};`
);
fixEnt(str, {
cb: letsCatchBadEntities
? (obj) => {
console.log(
`380 ${`\u001b[${32}m${`linter.js`}\u001b[${39}m`}: ${`\u001b[${33}m${`obj`}\u001b[${39}m`} = ${JSON.stringify(
obj,
null,
4
)}`
);
// Object.keys(config.rules).includes("bad-html-entity")
if (Number.isInteger(severity) && severity) {
let message;
if (obj.ruleName === "bad-html-entity-malformed-nbsp") {
message = "Malformed nbsp entity.";
} else if (obj.ruleName === "bad-html-entity-unrecognised") {
message = "Unrecognised named entity.";
} else if (
obj.ruleName === "bad-html-entity-multiple-encoding"
) {
message = "HTML entity encoding over and over.";
} else if (
obj.ruleName === "bad-html-entity-malformed-numeric"
) {
message = "Malformed numeric entity.";
} else {
message = `Malformed ${
obj.entityName ? obj.entityName : "named"
} entity.`;
}
console.log(
`410 FIY, ${`\u001b[${33}m${`message`}\u001b[${39}m`} = ${JSON.stringify(
message,
null,
4
)}`
);
let ranges: Ranges = [
[
obj.rangeFrom,
obj.rangeTo,
obj.rangeValEncoded ? obj.rangeValEncoded : "",
],
];
if (obj.ruleName === "bad-html-entity-unrecognised") {
ranges = [];
}
this.report({
severity,
ruleId: obj.ruleName,
message,
idxFrom: obj.rangeFrom,
idxTo: obj.rangeTo,
fix: {
ranges,
},
});
}
}
: undefined,
entityCatcherCb: letsCatchBadEntities
? (from, to) => {
console.log(
`444 linter.js: entityCatcher pinging { from: ${from}, to: ${to} }`
);
this.emit("entity", { idxFrom: from, idxTo: to });
}
: undefined,
textAmpersandCatcherCb: letsCatchRawTextAmpersands
? (posIdx) => {
console.log(`451`);
let mode: "numeric" | "named" | undefined;
if (
Array.isArray(processedRulesConfig["character-encode"]) &&
processedRulesConfig["character-encode"].includes("numeric")
) {
mode = "numeric";
// else, it's undefined which will fall back to "named"
}
console.log(
`461 RAW AMP, ${`\u001b[${32}m${`CALL`}\u001b[${39}m`} validateCharEncoding()`
);
console.log(
`464 ███████████████████*███████████████████ Object.keys(this) = ${JSON.stringify(
Object.keys(this),
null,
4
)}`
);
validateCharEncoding("&", posIdx, mode, this);
}
: undefined,
});
}
// remove all listeners
// extract all keys from the events interface
const allEventNames = keys<RuleObjType>();
allEventNames.forEach((eventName) => {
this.removeAllListeners(eventName as any);
});
console.log(
`485 ${`\u001b[${32}m${`linter.js`}\u001b[${39}m`}: verify() final return is called;\nthis.messages=${JSON.stringify(
this.messages,
null,
4
)}`
);
return clone(this.messages);
}
report(obj: ErrorObjWithRuleId): void {
console.log(
`496 ${`\u001b[${32}m${`linter.js/report()`}\u001b[${39}m`}: called with ${JSON.stringify(
obj,
null,
4
)}; this.hasBeenCalledWithKeepSeparateWhenFixing = ${
this.hasBeenCalledWithKeepSeparateWhenFixing
}`
);
// fill in other data points:
const { line, col } = lineCol(
this.strLineStartIndexes,
obj.idxFrom,
true
) as Obj;
let severity: Severity = obj.severity || 0; // rules coming from 3rd party packages will give the severity value
console.log(
`513 ${`\u001b[${32}m${`linter.js/report()`}\u001b[${39}m`}: ${`\u001b[${33}m${`this.processedRulesConfig[obj.ruleId]`}\u001b[${39}m`} = ${JSON.stringify(
this.processedRulesConfig[obj.ruleId],
null,
4
)}`
);
if (
!Number.isInteger(obj.severity) &&
typeof this.processedRulesConfig[obj.ruleId] === "number"
) {
severity = this.processedRulesConfig[obj.ruleId] as Severity;
} else if (
!Number.isInteger(obj.severity) &&
Array.isArray(this.processedRulesConfig[obj.ruleId])
) {
severity = (this.processedRulesConfig[obj.ruleId] as any[])[0];
}
console.log(
`531 ${`\u001b[${32}m${`linter.js/report()`}\u001b[${39}m`}: line = ${line}; column = ${col}`
);
console.log(
`534 ${`\u001b[${32}m${`linter.js/report()`}\u001b[${39}m`}: ${`\u001b[${33}m${`this.messages`}\u001b[${39}m`} BEFORE: ${JSON.stringify(
this.messages,
null,
4
)}`
);
this.messages.push({
keepSeparateWhenFixing: false,
line,
column: col,
severity,
...obj,
...(this.hasBeenCalledWithKeepSeparateWhenFixing ? { fix: null } : {}),
});
console.log(
`550 ${`\u001b[${32}m${`linter.js/report()`}\u001b[${39}m`}: ${`\u001b[${33}m${`this.messages`}\u001b[${39}m`} AFTER: ${JSON.stringify(
this.messages,
null,
4
)}`
);
// After pushing, let's manage "keepSeparateWhenFixing" messages -
// make a note of the first incoming message with "keepSeparateWhenFixing"
// key, in order to remove "fix" values from all other incoming messages
// with "keepSeparateWhenFixing" key. That's necessary to support certain
// fixes composition.
if (
obj.keepSeparateWhenFixing &&
!this.hasBeenCalledWithKeepSeparateWhenFixing &&
obj.fix
) {
this.hasBeenCalledWithKeepSeparateWhenFixing = true;
}
console.log(
`571 ${`\u001b[${32}m${`linter.js/report()`}\u001b[${39}m`}: ENDING this.hasBeenCalledWithKeepSeparateWhenFixing = ${
this.hasBeenCalledWithKeepSeparateWhenFixing
}`
);
}
}
export { Linter, RuleObjType }; | the_stack |
import { StatementPtr, Wasm } from "../build/sqlite.js";
import { getStr, setArr, setStr } from "./wasm.ts";
import { Status, Types, Values } from "./constants.ts";
import { SqliteError } from "./error.ts";
/**
* The default type for returned rows.
*/
export type Row = Array<unknown>;
/**
* The default type for row returned
* as objects.
*/
export type RowObject = Record<string, unknown>;
/**
* Possible parameter values to be bound to a query.
*
* When values are bound to a query, they are
* converted between JavaScript and SQLite types
* in the following way:
*
* | JS type in | SQL type | JS type out |
* |------------|-----------------|------------------|
* | number | INTEGER or REAL | number or bigint |
* | bigint | INTEGER | number or bigint |
* | boolean | INTEGER | number |
* | string | TEXT | string |
* | Date | TEXT | string |
* | Uint8Array | BLOB | Uint8Array |
* | null | NULL | null |
* | undefined | NULL | null |
*
* If no value is provided for a given parameter,
* SQLite will default to NULL.
*
* If a `bigint` is bound, it is converted to a
* signed 64 bit integer, which may overflow.
*
* If an integer value is read from the database, which
* is too big to safely be contained in a `number`, it
* is automatically returned as a `bigint`.
*
* If a `Date` is bound, it will be converted to
* an ISO 8601 string: `YYYY-MM-DDTHH:MM:SS.SSSZ`.
* This format is understood by built-in SQLite
* date-time functions. Also see https://sqlite.org/lang_datefunc.html.
*/
export type QueryParameter =
| boolean
| number
| bigint
| string
| null
| undefined
| Date
| Uint8Array;
/**
* A set of query parameters.
*
* When a query is constructed, it can contain
* either positional or named parameters. For
* more information see https://www.sqlite.org/lang_expr.html#parameters.
*
* A set of parameters can be passed to
* a query method either as an array of
* parameters (in positional order), or
* as an object which maps parameter names
* to their values:
*
* | SQL Parameter | QueryParameterSet |
* |---------------|-------------------------|
* | `?NNN` or `?` | NNN-th value in array |
* | `:AAAA` | value `AAAA` or `:AAAA` |
* | `@AAAA` | value `@AAAA` |
* | `$AAAA` | value `$AAAA` |
*
* See `QueryParameter` for documentation on
* how values are converted between SQL
* and JavaScript types.
*/
export type QueryParameterSet =
| Record<string, QueryParameter>
| Array<QueryParameter>;
/**
* Name of a column in a database query.
*/
export interface ColumnName {
name: string;
originName: string;
tableName: string;
}
interface RowsIterator<R> {
next: () => IteratorResult<R>;
[Symbol.iterator]: () => RowsIterator<R>;
}
export class PreparedQuery<
R extends Row = Row,
O extends RowObject = RowObject,
P extends QueryParameterSet = QueryParameterSet,
> {
private _wasm: Wasm;
private _stmt: StatementPtr;
private _openStatements: Set<StatementPtr>;
private _status: number;
private _iterKv: boolean;
private _rowKeys?: Array<string>;
private _finalized: boolean;
/**
* A prepared query which can be executed many
* times.
*
* The constructor should never be used directly.
* Instead a prepared query can be obtained by
* calling `DB.prepareQuery`.
*/
constructor(
wasm: Wasm,
stmt: StatementPtr,
openStatements: Set<StatementPtr>,
) {
this._wasm = wasm;
this._stmt = stmt;
this._openStatements = openStatements;
this._status = Status.Unknown;
this._iterKv = false;
this._finalized = false;
}
private startQuery(params?: P) {
if (this._finalized) {
throw new SqliteError("Query is finalized.");
}
// Reset query
this._wasm.reset(this._stmt);
this._wasm.clear_bindings(this._stmt);
// Prepare parameter array
let parameters = [];
if (Array.isArray(params)) {
parameters = params;
} else if (typeof params === "object") {
// Resolve parameter index for named parameter
for (const key of Object.keys(params)) {
let name = key;
// blank names default to ':'
if (name[0] !== ":" && name[0] !== "@" && name[0] !== "$") {
name = `:${name}`;
}
const idx = setStr(
this._wasm,
name,
(ptr) => this._wasm.bind_parameter_index(this._stmt, ptr),
);
if (idx === Values.Error) {
throw new SqliteError(`No parameter named '${name}'.`);
}
parameters[idx - 1] = params[key];
}
}
// Bind parameters
for (let i = 0; i < parameters.length; i++) {
let value = parameters[i];
let status;
switch (typeof value) {
case "boolean":
value = value ? 1 : 0;
// fall through
case "number":
if (Number.isSafeInteger(value)) {
status = this._wasm.bind_int(this._stmt, i + 1, value);
} else {
status = this._wasm.bind_double(this._stmt, i + 1, value);
}
break;
case "bigint":
// bigint is bound as two 32bit integers and reassembled on the C side
if (value > 9223372036854775807n || value < -9223372036854775808n) {
throw new SqliteError(
`BigInt value ${value} overflows 64 bit integer.`,
);
} else {
const posVal = value >= 0n ? value : -value;
const sign = value >= 0n ? 1 : -1;
const upper = Number(BigInt.asUintN(32, posVal >> 32n));
const lower = Number(BigInt.asUintN(32, posVal));
status = this._wasm.bind_big_int(
this._stmt,
i + 1,
sign,
upper,
lower,
);
}
break;
case "string":
status = setStr(
this._wasm,
value,
(ptr) => this._wasm.bind_text(this._stmt, i + 1, ptr),
);
break;
default:
if (value instanceof Date) {
// Dates are allowed and bound to TEXT, formatted `YYYY-MM-DDTHH:MM:SS.SSSZ`
status = setStr(
this._wasm,
value.toISOString(),
(ptr) => this._wasm.bind_text(this._stmt, i + 1, ptr),
);
} else if (value instanceof Uint8Array) {
// Uint8Arrays are allowed and bound to BLOB
const size = value.length;
status = setArr(
this._wasm,
value,
(ptr) => this._wasm.bind_blob(this._stmt, i + 1, ptr, size),
);
} else if (value === null || value === undefined) {
// Both null and undefined result in a NULL entry
status = this._wasm.bind_null(this._stmt, i + 1);
} else {
throw new SqliteError(`Can not bind ${typeof value}.`);
}
break;
}
if (status !== Status.SqliteOk) {
throw new SqliteError(this._wasm, status);
}
}
}
private getQueryRow(): R {
if (this._finalized) {
throw new SqliteError("Query is finalized.");
}
const columnCount = this._wasm.column_count(this._stmt);
const row: Row = [];
for (let i = 0; i < columnCount; i++) {
switch (this._wasm.column_type(this._stmt, i)) {
case Types.Integer:
row.push(this._wasm.column_int(this._stmt, i));
break;
case Types.Float:
row.push(this._wasm.column_double(this._stmt, i));
break;
case Types.Text:
row.push(
getStr(
this._wasm,
this._wasm.column_text(this._stmt, i),
),
);
break;
case Types.Blob: {
const ptr = this._wasm.column_blob(this._stmt, i);
if (ptr === 0) {
// Zero pointer results in null
row.push(null);
} else {
const length = this._wasm.column_bytes(this._stmt, i);
// Slice should copy the bytes, as it makes a shallow copy
row.push(
new Uint8Array(this._wasm.memory.buffer, ptr, length).slice(),
);
}
break;
}
case Types.BigInteger: {
const ptr = this._wasm.column_text(this._stmt, i);
row.push(BigInt(getStr(this._wasm, ptr)));
break;
}
default:
// TODO(dyedgreen): Differentiate between NULL and not-recognized?
row.push(null);
break;
}
}
return row as R;
}
private makeRowObject(row: Row): O {
if (this._rowKeys == null) {
const rowCount = this._wasm.column_count(this._stmt);
this._rowKeys = [];
for (let i = 0; i < rowCount; i++) {
this._rowKeys.push(
getStr(this._wasm, this._wasm.column_name(this._stmt, i)),
);
}
}
const obj = row.reduce<RowObject>((obj, val, idx) => {
obj[this._rowKeys![idx]] = val;
return obj;
}, {});
return obj as O;
}
/**
* Binds the given parameters to the query
* and returns an iterator over rows.
*
* Using an iterator avoids loading all returned
* rows into memory and hence allows to process a large
* number of rows.
*
* Example:
* ```typescript
* const query = db.prepareQuery<[number, string]>("SELECT id, name FROM people");
* for (const [id, name] of query.iter()) {
* // ...
* }
* ```
*
* Calling `iter` invalidates any iterators previously returned
* from this prepared query. Using an invalidated iterator is a bug.
*
* To avoid SQL injection, user-provided values
* should always be passed to the database through
* a query parameter.
*
* See `QueryParameterSet` for documentation on
* how values can be bound to SQL statements.
*
* See `QueryParameter` for documentation on how
* values are returned from the database.
*/
iter(params?: P): RowsIterator<R> {
this.startQuery(params);
this._status = this._wasm.step(this._stmt);
if (
this._status !== Status.SqliteRow && this._status !== Status.SqliteDone
) {
throw new SqliteError(this._wasm, this._status);
}
this._iterKv = false;
return this as RowsIterator<R>;
}
/**
* Like `iter` except each row is returned
* as an object containing key-value pairs.
*/
iterEntries(params?: P): RowsIterator<O> {
this.iter(params);
this._iterKv = true;
return this as RowsIterator<O>;
}
/**
* @ignore
*
* Implements the iterable protocol. It is
* a bug to call this method directly.
*/
[Symbol.iterator](): RowsIterator<R | O> {
return this;
}
/**
* @ignore
*
* Implements the iterator protocol. It is
* a bug to call this method directly.
*/
next(): IteratorResult<R | O> {
if (this._status === Status.SqliteRow) {
const value = this.getQueryRow();
this._status = this._wasm.step(this._stmt);
if (this._iterKv) {
return { value: this.makeRowObject(value), done: false };
} else {
return { value, done: false };
}
} else if (this._status === Status.SqliteDone) {
return { value: null, done: true };
} else {
throw new SqliteError(this._wasm, this._status);
}
}
/**
* Binds the given parameters to the query
* and returns an array containing all resulting
* rows.
*
* Calling `all` invalidates any iterators
* previously returned by calls to `iter`.
* Using an invalidated iterator is a bug.
*
* To avoid SQL injection, user-provided values
* should always be passed to the database through
* a query parameter.
*
* See `QueryParameterSet` for documentation on
* how values can be bound to SQL statements.
*
* See `QueryParameter` for documentation on how
* values are returned from the database.
*/
all(params?: P): Array<R> {
this.startQuery(params);
const rows: Array<R> = [];
this._status = this._wasm.step(this._stmt);
while (this._status === Status.SqliteRow) {
rows.push(this.getQueryRow());
this._status = this._wasm.step(this._stmt);
}
if (this._status !== Status.SqliteDone) {
throw new SqliteError(this._wasm, this._status);
}
return rows;
}
/**
* Like `all` except each row is returned
* as an object containing key-value pairs.
*/
allEntries(params?: P): Array<O> {
return this.all(params).map((row) => this.makeRowObject(row));
}
/**
* Binds the given parameters to the query and
* returns exactly one row.
*
* If the query does not return exactly one row,
* this throws an error.
*
* Calling `one` invalidates any iterators
* previously returned by calls to `iter`.
* Using an invalidated iterator is a bug.
*
* To avoid SQL injection, user-provided values
* should always be passed to the database through
* a query parameter.
*
* See `QueryParameterSet` for documentation on
* how values can be bound to SQL statements.
*
* See `QueryParameter` for documentation on how
* values are returned from the database.
*/
one(params?: P): R {
this.startQuery(params);
// Get first row
this._status = this._wasm.step(this._stmt);
if (this._status !== Status.SqliteRow) {
if (this._status === Status.SqliteDone) {
throw new SqliteError("The query did not return any rows.");
} else {
throw new SqliteError(this._wasm, this._status);
}
}
const row = this.getQueryRow();
// Ensure the query only returns one row
this._status = this._wasm.step(this._stmt);
if (this._status !== Status.SqliteDone) {
if (this._status === Status.SqliteRow) {
throw new SqliteError("The query returned more than one row.");
} else {
throw new SqliteError(this._wasm, this._status);
}
}
return row;
}
/**
* Like `one` except the row is returned
* as an object containing key-value pairs.
*/
oneEntry(params?: P): O {
return this.makeRowObject(this.one(params));
}
/**
* Binds the given parameters to the query and
* executes the query, ignoring any rows which
* might be returned.
*
* Using this method is more efficient when the
* rows returned by a query are not needed or
* the query does not return any rows.
*
* Calling `execute` invalidates any iterators
* previously returned by calls to `iter`.
* Using an invalidated iterator is a bug.
*
* To avoid SQL injection, user-provided values
* should always be passed to the database through
* a query parameter.
*
* See `QueryParameterSet` for documentation on
* how values can be bound to SQL statements.
*/
execute(params?: P) {
this.startQuery(params);
this._status = this._wasm.step(this._stmt);
while (this._status === Status.SqliteRow) {
this._status = this._wasm.step(this._stmt);
}
if (this._status !== Status.SqliteDone) {
throw new SqliteError(this._wasm, this._status);
}
}
/**
* Closes the prepared query. This must be
* called once the query is no longer needed
* to avoid leaking resources.
*
* After a prepared query has been finalized,
* trying to call `iter`, `all`, `one`,
* `execute`, or `columns`, or using iterators which where
* previously obtained from the finalized query
* is a bug.
*
* `finalize` may safely be called multiple
* times.
*/
finalize() {
if (!this._finalized) {
this._wasm.finalize(this._stmt);
this._openStatements.delete(this._stmt);
this._finalized = true;
}
}
/**
* Returns the column names for the query
* results.
*
* This method returns an array of objects,
* where each object has the following properties:
*
* | Property | Value |
* |--------------|--------------------------------------------|
* | `name` | the result of `sqlite3_column_name` |
* | `originName` | the result of `sqlite3_column_origin_name` |
* | `tableName` | the result of `sqlite3_column_table_name` |
*/
columns(): Array<ColumnName> {
if (this._finalized) {
throw new SqliteError(
"Unable to retrieve column names from finalized transaction.",
);
}
const columnCount = this._wasm.column_count(this._stmt);
const columns: Array<ColumnName> = [];
for (let i = 0; i < columnCount; i++) {
const name = getStr(
this._wasm,
this._wasm.column_name(this._stmt, i),
);
const originName = getStr(
this._wasm,
this._wasm.column_origin_name(this._stmt, i),
);
const tableName = getStr(
this._wasm,
this._wasm.column_table_name(this._stmt, i),
);
columns.push({ name, originName, tableName });
}
return columns;
}
} | the_stack |
import { $TSContext, CFNTemplateFormat, readCFNTemplate, pathManager, stateManager, writeCFNTemplate } from 'amplify-cli-core';
import { glob } from 'glob';
import * as inquirer from 'inquirer';
import { prompter } from 'amplify-prompts';
import * as fs from 'fs-extra';
import {
getResourceCfnOutputAttributes,
getAllResources,
addCDKResourceDependency,
addCFNResourceDependency,
} from '../../utils/dependency-management-utils';
import * as cdk from '@aws-cdk/core';
jest.mock('amplify-cli-core');
jest.mock('amplify-prompts');
jest.mock('glob');
jest.mock('fs-extra');
jest.mock('inquirer');
const readCFNTemplate_mock = readCFNTemplate as jest.MockedFunction<typeof readCFNTemplate>;
const writeCFNTemplate_mock = writeCFNTemplate as jest.MockedFunction<typeof writeCFNTemplate>;
writeCFNTemplate_mock.mockResolvedValue();
const glob_mock = glob as jest.Mocked<typeof glob>;
const fs_mock = fs as jest.Mocked<typeof fs>;
pathManager.getBackendDirPath = jest.fn().mockReturnValue('mockTargetDir');
pathManager.getResourceDirectoryPath = jest.fn().mockReturnValue('mockResourceDir');
describe('getResourceCfnOutputAttributes() scenarios', () => {
let mockContext: $TSContext;
beforeEach(() => {
jest.clearAllMocks();
mockContext = {
amplify: {
openEditor: jest.fn(),
updateamplifyMetaAfterResourceAdd: jest.fn(),
copyBatch: jest.fn(),
getResourceStatus: jest.fn().mockResolvedValue({
allResources: [
{
resourceName: 'mockresource1',
service: 'customCDK',
},
{
resourceName: 'mockresource2',
service: 'customCDK',
},
],
}),
},
} as unknown as $TSContext;
});
it('get resource attr for resources with build folder with one cfn file', async () => {
fs_mock.existsSync.mockReturnValue(true); // if build dir exists
readCFNTemplate_mock.mockReturnValueOnce({
templateFormat: CFNTemplateFormat.JSON,
cfnTemplate: { Outputs: { mockKey: { Value: 'mockValue' } } },
});
glob_mock.sync.mockReturnValueOnce(['mockFileName']);
expect(getResourceCfnOutputAttributes('mockCategory', 'mockResourceName')).toEqual(['mockKey']);
});
it('get resource attr for resources with build folder with multiple cfn files', async () => {
fs_mock.existsSync.mockReturnValue(true); // if build dir exists
readCFNTemplate_mock.mockReturnValueOnce({
templateFormat: CFNTemplateFormat.JSON,
cfnTemplate: { Outputs: { mockKey: { Value: 'mockValue' } } },
});
glob_mock.sync.mockReturnValueOnce(['mockFileName1', 'mockFileName2']);
expect(getResourceCfnOutputAttributes('mockCategory', 'mockResourceName')).toEqual([]);
});
it('get resource attr for resources without build folder', async () => {
fs_mock.existsSync.mockReturnValue(false); // if build dir exists
readCFNTemplate_mock.mockReturnValueOnce({
templateFormat: CFNTemplateFormat.JSON,
cfnTemplate: { Outputs: { mockKey: { Value: 'mockValue' } } },
});
glob_mock.sync.mockReturnValueOnce(['mockFileName']);
expect(getResourceCfnOutputAttributes('mockCategory', 'mockResourceName')).toEqual(['mockKey']);
});
it('get resource attr for resources without build folder with multiple cfn files', async () => {
fs_mock.existsSync.mockReturnValue(false); // if build dir exists
readCFNTemplate_mock.mockReturnValueOnce({
templateFormat: CFNTemplateFormat.JSON,
cfnTemplate: { Outputs: { mockKey: { Value: 'mockValue' } } },
});
glob_mock.sync.mockReturnValueOnce(['mockFileName1', 'mockFileName2']);
expect(getResourceCfnOutputAttributes('mockCategory', 'mockResourceName')).toEqual([]);
});
it('get resource attr for resources without any cfn files', async () => {
fs_mock.existsSync.mockReturnValue(false); // if build dir exists
glob_mock.sync.mockReturnValueOnce([]);
expect(getResourceCfnOutputAttributes('mockCategory', 'mockResourceName')).toEqual([]);
});
});
describe('getAllResources() scenarios', () => {
let mockContext: $TSContext;
beforeEach(() => {
jest.clearAllMocks();
mockContext = {
amplify: {
openEditor: jest.fn(),
updateamplifyMetaAfterResourceAdd: jest.fn(),
copyBatch: jest.fn(),
getResourceStatus: jest.fn().mockResolvedValue({
allResources: [
{
resourceName: 'mockresource1',
service: 'customCDK',
},
{
resourceName: 'mockresource2',
service: 'customCDK',
},
],
}),
},
} as unknown as $TSContext;
});
it('get all resource types', async () => {
fs_mock.existsSync.mockReturnValue(false); // if build dir exists
readCFNTemplate_mock.mockReturnValue({
templateFormat: CFNTemplateFormat.JSON,
cfnTemplate: { Outputs: { mockKey: { Value: 'mockValue' } } },
});
glob_mock.sync.mockReturnValue(['mockFileName']);
stateManager.getMeta = jest.fn().mockReturnValue({
mockCategory1: {
mockResourceName1: {},
},
mockCategory2: {
mockResourceName2: {},
},
});
expect(getAllResources()).toEqual({
mockCategory1: { mockResourceName1: { mockKey: 'string' } },
mockCategory2: { mockResourceName2: { mockKey: 'string' } },
});
});
});
describe('addCDKResourceDependency() scenarios', () => {
let mockContext: $TSContext;
beforeEach(() => {
jest.clearAllMocks();
mockContext = {
amplify: {
openEditor: jest.fn(),
updateamplifyMetaAfterResourceAdd: jest.fn(),
copyBatch: jest.fn(),
getResourceStatus: jest.fn().mockResolvedValue({
allResources: [
{
resourceName: 'mockresource1',
service: 'customCDK',
},
{
resourceName: 'mockresource2',
service: 'customCDK',
},
],
}),
},
} as unknown as $TSContext;
});
it('get depenencies for a custom CDK stack', async () => {
fs_mock.existsSync.mockReturnValue(false); // if build dir exists
readCFNTemplate_mock.mockReturnValue({
templateFormat: CFNTemplateFormat.JSON,
cfnTemplate: { Outputs: { mockKey: { Value: 'mockValue' } } },
});
glob_mock.sync.mockReturnValue(['mockFileName']);
const mockBackendConfig = {
mockCategory1: {
mockResourceName1: {},
},
mockCategory2: {
mockResourceName2: {},
},
mockCategory3: {
mockResourceName3: {},
},
mockCategory4: {
mockResourceName4: {},
},
};
stateManager.getBackendConfig = jest.fn().mockReturnValue(mockBackendConfig);
stateManager.setBackendConfig = jest.fn();
stateManager.getMeta = jest.fn().mockReturnValue(mockBackendConfig);
stateManager.setMeta = jest.fn();
const mockStack = new cdk.Stack();
// test with adding one dependency at once
let retVal = addCDKResourceDependency(mockStack, 'mockCategory1', 'mockResourceName1', [
{ category: 'mockCategory2', resourceName: 'mockResourceName2' },
]);
expect(retVal).toEqual({
mockCategory2: {
mockResourceName2: { mockKey: 'mockCategory2mockResourceName2mockKey' },
},
});
const postUpdateBackendConfig: any = mockBackendConfig;
postUpdateBackendConfig.mockCategory1.mockResourceName1.dependsOn = [
{
attributes: ['mockKey'],
category: 'mockCategory2',
resourceName: 'mockResourceName2',
},
];
expect(stateManager.setMeta).toBeCalledWith(undefined, postUpdateBackendConfig);
expect(stateManager.setBackendConfig).toBeCalledWith(undefined, postUpdateBackendConfig);
// test with adding multiple dependencies at once
retVal = addCDKResourceDependency(mockStack, 'mockCategory1', 'mockResourceName1', [
{ category: 'mockCategory4', resourceName: 'mockResourceName4' },
{ category: 'mockCategory3', resourceName: 'mockResourceName3' },
]);
expect(retVal).toEqual({
mockCategory4: {
mockResourceName4: { mockKey: 'mockCategory4mockResourceName4mockKey' },
},
mockCategory3: {
mockResourceName3: { mockKey: 'mockCategory3mockResourceName3mockKey' },
},
});
postUpdateBackendConfig.mockCategory1.mockResourceName1.dependsOn = [
{
attributes: ['mockKey'],
category: 'mockCategory3',
resourceName: 'mockResourceName3',
},
{
attributes: ['mockKey'],
category: 'mockCategory4',
resourceName: 'mockResourceName4',
},
];
expect(stateManager.setMeta).toBeCalledWith(undefined, postUpdateBackendConfig);
expect(stateManager.setBackendConfig).toBeCalledWith(undefined, postUpdateBackendConfig);
// test when adding multiple dependencies but none of the dependencies have outputs exported
readCFNTemplate_mock.mockReturnValue({ templateFormat: CFNTemplateFormat.JSON, cfnTemplate: {} });
retVal = addCDKResourceDependency(mockStack, 'mockCategory1', 'mockResourceName1', [
{ category: 'mockCategory4', resourceName: 'mockResourceName4' },
{ category: 'mockCategory3', resourceName: 'mockResourceName3' },
]);
expect(retVal).toEqual({});
expect(stateManager.setMeta).toBeCalledTimes(2); // from the previous two successful calls - and skip the last call
expect(stateManager.setBackendConfig).toBeCalledTimes(2); // from the previous two successful calls - and skip the last call
});
});
describe('addCFNResourceDependency() scenarios', () => {
let mockContext: $TSContext;
beforeEach(() => {
jest.clearAllMocks();
mockContext = {
amplify: {
openEditor: jest.fn(),
updateamplifyMetaAfterResourceAdd: jest.fn(),
copyBatch: jest.fn(),
updateamplifyMetaAfterResourceUpdate: jest.fn(),
getResourceStatus: jest.fn().mockResolvedValue({
allResources: [
{
resourceName: 'mockresource1',
service: 'customCDK',
},
{
resourceName: 'mockresource2',
service: 'customCDK',
},
],
}),
},
} as unknown as $TSContext;
});
it('add new resource dependency to custom cfn stack ', async () => {
prompter.yesOrNo = jest.fn().mockReturnValueOnce(true);
fs_mock.existsSync.mockReturnValue(false); // if build dir exists
readCFNTemplate_mock.mockReturnValue({
templateFormat: CFNTemplateFormat.JSON,
cfnTemplate: { Outputs: { mockKey: { Value: 'mockValue' } } },
});
glob_mock.sync.mockReturnValue(['mockFileName']);
const mockBackendConfig = {
mockCategory1: {
mockResourceName1: {},
},
mockCategory2: {
mockResourceName2: {},
},
mockCategory3: {
mockResourceName3: {},
},
custom: {
customResourcename: {},
},
};
stateManager.getBackendConfig = jest.fn().mockReturnValue(mockBackendConfig);
stateManager.setBackendConfig = jest.fn();
stateManager.getMeta = jest.fn().mockReturnValue(mockBackendConfig);
stateManager.setMeta = jest.fn();
// test with adding one dependency at once
const inqurer_mock = inquirer as jest.Mocked<typeof inquirer>;
inqurer_mock.prompt
.mockResolvedValueOnce({ categories: ['mockCategory1'] })
.mockResolvedValueOnce({ resources: ['mockResourceName1'] });
await addCFNResourceDependency(mockContext, 'customResourcename');
expect(writeCFNTemplate_mock).toBeCalledWith(
{
Outputs: { mockKey: { Value: 'mockValue' } },
Parameters: {
mockCategory1mockResourceName1mockKey: {
Description: 'Input parameter describing mockKey attribute for mockCategory1/mockResourceName1 resource',
Type: 'String',
},
},
},
expect.anything(),
{ templateFormat: 'json' },
);
expect(mockContext.amplify.updateamplifyMetaAfterResourceUpdate).toBeCalledWith('custom', 'customResourcename', 'dependsOn', [
{ attributes: ['mockKey'], category: 'mockCategory1', resourceName: 'mockResourceName1' },
]);
});
}); | the_stack |
import { isEmptyObject, isPlainObject } from '@mpkit/util';
import { getMpViewType, has, log } from '../../modules/util';
import {
JSONType,
JSONValue,
JSONChunk,
JSONProp,
JSONTree,
JSONComma,
GlobalObjectConstructorNames,
JSONNode,
JSONPropFilter,
JSONPropDesc,
JSONPropPath
} from '../../types/json';
export const ELLIPSIS_CHAR = '…';
export const FUNC_CHAR = 'ƒ';
export const PROTO_PROP = '__proto__';
export const equalJSONPropPath = (a: JSONPropPath, b: JSONPropPath): boolean => {
if (!a && !b) {
return true;
}
if (!a) {
return false;
}
if (!b) {
return false;
}
if (a.length !== b.length) {
return false;
}
return a.every((item, index) => item === b[index]);
};
export const likeInt = (obj: string | symbol) => {
if (typeof obj === 'symbol') {
return false;
}
return String(parseInt(obj)) === String(obj);
};
export const isNum = (obj) => typeof obj === 'number' && !isNaN(obj);
export const isFunc = (obj) => typeof obj === 'function' || obj instanceof Function;
export const isObject = (obj) => typeof obj === 'object' && obj;
export const isArray = (obj) => Array.isArray(obj);
export const getPathValue = <T = any>(obj: any, path: JSONPropPath, throwError = false): T | undefined => {
if (!isObject(obj) && !isArray(obj)) {
return;
}
const arr = path;
const readyPath: JSONPropPath = [];
for (let i = 0, len = arr.length; i < len; i++) {
if (!isObject(obj) && !isArray(obj)) {
const err = new Error(`此${readyPath}路径对应的值非对象`);
(err as any).stopPath = readyPath;
if (throwError) {
throw err;
} else {
log('error', err);
return;
}
}
const item = arr[i];
readyPath.push(item);
const propName: string | symbol = item;
if (propName === PROTO_PROP) {
obj = getPrototypeOf(obj);
if (typeof obj === 'undefined') {
const err = new Error(`无法找到在对象上找到${readyPath}路径对应的值`);
(err as any).stopPath = readyPath;
if (throwError) {
throw err;
} else {
log('error', err);
return;
}
}
continue;
}
if (!(propName in obj)) {
const err = new Error(`无法找到在对象上找到${readyPath}路径对应的值`);
(err as any).stopPath = readyPath;
if (throwError) {
throw err;
} else {
log('error', err);
return;
}
}
try {
obj = obj[propName];
} catch (error) {
if (throwError) {
throw error;
} else {
log('error', error);
return;
}
}
}
return obj;
};
export const getClassName = (obj: any): string => {
if (!obj || (!isFunc(obj) && !isObject(obj))) {
return '';
}
const viewType = getMpViewType(obj);
if (viewType === 'App') {
return 'App';
}
if (viewType === 'Page') {
return 'Page';
}
if (viewType === 'Component') {
return 'Component';
}
if ('constructor' in obj && 'name' in obj.constructor && obj.constructor.name) {
return obj.constructor.name;
}
if (
'prototype' in obj &&
'constructor' in obj.prototype &&
'name' in obj.prototype.constructor &&
obj.prototype.constructor.name
) {
return obj.prototype.constructor.name;
}
const proto = getPrototypeOf(obj);
if (proto) {
return getClassName(proto);
}
return '';
};
export const getJSONType = (obj: any): JSONType => {
const type = typeof obj;
if (type === 'string') {
return JSONType.string;
}
if (type === 'number') {
return JSONType.num;
}
if (type === 'bigint') {
return JSONType.bigint;
}
if (type === 'symbol') {
return JSONType.symbol;
}
if (type === 'boolean') {
return JSONType.bool;
}
if (type === 'undefined') {
return JSONType.undefined;
}
if (type === 'function') {
return JSONType.func;
}
if (type === 'object') {
if (!obj) {
return JSONType.null;
}
return JSONType.object;
}
};
export const getGlobalObjectConstructor = (clsName: GlobalObjectConstructorNames): Function => {
if (clsName === 'Number') {
return Number;
}
if (clsName === 'Array') {
return Array;
}
if (clsName === 'Object') {
return Object;
}
if (clsName === 'Boolean') {
return Boolean;
}
if (clsName === 'Date') {
return Date;
}
if (clsName === 'Map') {
return Map;
}
if (clsName === 'Set') {
return Set;
}
if (clsName === 'String') {
return String;
}
if (clsName === 'BigInt' && typeof BigInt === 'function') {
return BigInt;
}
if (clsName === 'Symbol' && typeof Symbol === 'function') {
return Symbol;
}
};
export const isGlobalObjectInstance = (obj: any, clsName: GlobalObjectConstructorNames): boolean => {
const cons = getGlobalObjectConstructor(clsName);
if (!cons) {
return false;
}
return obj instanceof cons;
};
export const getGlobalObjectJSONChunk = (obj: any, chunk?: JSONChunk) => {
const type = getJSONType(obj);
if (type !== JSONType.object) {
return;
}
const clsName = getClassName(obj);
if (isGlobalObjectInstance(obj, clsName as GlobalObjectConstructorNames)) {
chunk = chunk || {};
chunk.type = type;
if (clsName === 'Date') {
chunk.content = obj.toString();
return chunk;
}
if (clsName !== 'Object') {
chunk.className = clsName;
}
if (
clsName === 'Number' ||
clsName === 'Boolean' ||
clsName === 'String' ||
clsName === 'BigInt' ||
clsName === 'Symbol'
) {
chunk.leftBoundary = ' {';
chunk.rightBoundary = '}';
const tschunk: JSONChunk<JSONChunk> = chunk as JSONChunk<JSONChunk>;
tschunk.content = getSummaryJSONChunk((obj as Object).valueOf());
return chunk;
}
// if (clsName === "BigInt") {
// chunk.content = (obj as Object).toString() + "n";
// return chunk;
// }
}
};
export const createEllipsisJSONChunk = (): JSONChunk => {
return {
type: JSONType.ellipsis,
content: ELLIPSIS_CHAR
};
};
/**
* 以简略的方式返回JSONChunk
* @param perspective 对于一些装包的值(new Number(3))是否将其中的值透视显示出来
*/
export const getSummaryJSONChunk = (obj: any, perspective?: boolean): JSONChunk => {
const type = getJSONType(obj);
const chunk: JSONChunk = {};
chunk.type = type;
if (type === JSONType.string) {
chunk.leftBoundary = chunk.rightBoundary = '"';
chunk.content = obj as string;
return chunk;
}
if (type === JSONType.num) {
chunk.content = String(obj);
return chunk;
}
if (type === JSONType.bool) {
chunk.content = String(obj);
return chunk;
}
if (type === JSONType.bigint) {
chunk.content = obj.toString() + 'n';
return chunk;
}
if (type === JSONType.symbol) {
chunk.content = obj.toString();
return chunk;
}
if (type === JSONType.null) {
chunk.content = 'null';
return chunk;
}
if (type === JSONType.undefined) {
chunk.content = 'undefined';
return chunk;
}
if (type === JSONType.func) {
chunk.content = FUNC_CHAR;
return chunk;
}
if (type === JSONType.object) {
const clsName = getClassName(obj);
if (clsName !== 'Object') {
if (clsName === 'Date') {
chunk.content = (obj as Date).toString();
return chunk;
}
if (clsName === 'Array') {
chunk.className = clsName;
chunk.leftBoundary = '(';
chunk.rightBoundary = ')';
chunk.content = String((obj as Array<any>).length);
return chunk;
}
if (!perspective) {
chunk.className = clsName;
return chunk;
}
getGlobalObjectJSONChunk(obj, chunk);
if (!chunk.content) {
const tschunk: JSONChunk<JSONChunk> = chunk as JSONChunk<JSONChunk>;
tschunk.content = createEllipsisJSONChunk();
return chunk;
}
}
chunk.leftBoundary = '{';
chunk.rightBoundary = '}';
chunk.content = ELLIPSIS_CHAR;
return chunk;
}
return chunk;
};
export const getJSONProp = (prop: string | symbol): JSONProp => {
const chunk = getSummaryJSONChunk(prop) as JSONProp;
chunk.prop = true;
delete chunk.leftBoundary;
chunk.rightBoundary = ': ';
delete chunk.type;
return chunk;
};
/**
* 以Object.keys的方式获取对象的JSONChunk集合
*/
export const getObjectKeysJSONChunks = (
obj: any,
maxPropLength?: number,
filter?: JSONPropFilter
): JSONChunk[] | undefined => {
const type = getJSONType(obj);
if (type !== JSONType.object) {
return;
}
maxPropLength = maxPropLength || Infinity;
const isArr = isArray(obj);
const chunks: JSONChunk[] = [];
const pushItem = (key: string | symbol, isLastKey: boolean) => {
if (!isArr) {
chunks.push(getJSONProp(key));
}
chunks.push(getSummaryJSONChunk(obj[key]));
if (!isLastKey) {
const item: JSONComma = {
comma: true,
content: ', '
};
chunks.push(item);
}
};
const propDescList = getOwnPropertyDescriptors(obj, (name, desc, index) => {
let pass = 'value' in desc && index < maxPropLength;
if (typeof filter === 'function') {
pass = pass && filter(name, desc, index);
}
return pass;
});
propDescList.forEach(({ prop }, index, arr) => {
pushItem(prop, index === arr.length - 1);
});
return chunks;
};
export const getPrototypeOf = (obj): any => {
if (Object.getPrototypeOf) {
return Object.getPrototypeOf(obj);
}
// eslint-disable-next-line no-proto
return obj.__proto__;
};
export const getPrototypeOfDesc = (obj): PropertyDescriptor | undefined => {
const proto = getPrototypeOf(obj);
if (typeof proto !== 'undefined' && proto !== null) {
return {
writable: false,
enumerable: false,
configurable: false,
value: proto
};
}
};
export const getOwnPropertyDescriptors = (() => {
let hasNative;
let polyfill;
let mock;
const setPolyfill = () => {
polyfill = function getOwnPropertyDescriptors(object, filter?: JSONPropFilter) {
let maxIndex = 0;
const res = Reflect.ownKeys(object).reduce((res, key, index) => {
maxIndex = index;
const val = Object.getOwnPropertyDescriptor(object, key);
let pass = true;
if (typeof filter === 'function') {
pass = filter(key, val, index);
}
pass &&
res.push({
prop: key,
desc: val
});
return res;
}, [] as JSONPropDesc[]);
maxIndex = handleMpView(object, res, maxIndex + 1, filter);
pushProtoDesc(object, res, maxIndex + 1, filter);
return res;
};
};
const setMock = () => {
mock = (object, filter?: JSONPropFilter) => {
const res: JSONPropDesc[] = [];
let index = -1;
for (const prop in object) {
if (has(object, prop)) {
index++;
let pass = true;
const val = Object.getOwnPropertyDescriptor(object, prop);
if (typeof filter === 'function') {
pass = filter(prop, val, index);
}
pass &&
res.push({
prop,
desc: val
});
}
}
index = handleMpView(object, res, index + 1, filter);
pushProtoDesc(object, res, index + 1, filter);
return res;
};
};
const pushProtoDesc = (obj: any, res: JSONPropDesc[], index: number, filter?: JSONPropFilter) => {
const protoDesc = getPrototypeOfDesc(obj);
if (protoDesc && (!filter || filter(PROTO_PROP, protoDesc, index))) {
res.push({
prop: PROTO_PROP,
desc: protoDesc
});
}
};
const handleMpView = (obj: any, res: JSONPropDesc[], index: number, filter?: JSONPropFilter) => {
const type = getMpViewType(obj);
if (type === 'Page' || type === 'Component') {
const props = ['data', 'dataset', 'properties'];
props.forEach((name) => {
if (name in obj) {
const desc: JSONPropDesc = {
prop: name,
desc: {
enumerable: false,
writable: true,
configurable: false,
get() {
return obj[name];
}
}
};
index++;
if (!filter || filter(desc.prop, desc.desc, index)) {
res.push(desc);
}
}
});
}
return index;
};
return (obj: any, filter?: JSONPropFilter): JSONPropDesc[] => {
const res: JSONPropDesc[] = [];
if (hasNative === true) {
const desc = Object.getOwnPropertyDescriptors(obj);
let maxIndex = 0;
Object.getOwnPropertyNames(desc).forEach((name, index) => {
maxIndex = index;
if (name in desc && 'enumerable' in desc[name] && (!filter || filter(name, desc[name], index))) {
res.push({
prop: name,
desc: desc[name]
});
}
});
Object.getOwnPropertySymbols(desc).forEach((name, index) => {
maxIndex += index;
if (!filter || filter(name, desc[name as unknown as string], maxIndex)) {
res.push({
prop: name,
desc: desc[name as unknown as string]
});
}
});
maxIndex = handleMpView(obj, res, maxIndex + 1, filter);
pushProtoDesc(obj, res, maxIndex + 1, filter);
return res;
}
if (hasNative === false) {
return (polyfill || mock)(obj, filter);
}
if (Object.getOwnPropertyDescriptors) {
hasNative = true;
return getOwnPropertyDescriptors(obj, filter);
}
hasNative = false;
if (typeof Reflect !== 'undefined') {
setPolyfill();
} else {
setMock();
}
return getOwnPropertyDescriptors(obj, filter);
};
})();
export const getObjectJSONChunk = (obj: any, maxPropLength?: number): JSONChunk<any> | undefined => {
const type = getJSONType(obj);
if (type !== JSONType.object) {
return;
}
if (isArray(obj)) {
const chunk: JSONChunk<JSONChunk[]> = {
type,
leftBoundary: '[',
rightBoundary: ']',
content: getObjectKeysJSONChunks(obj, maxPropLength, (name) => name !== 'length' && name !== PROTO_PROP)
};
if (obj.length) {
chunk.remark = `(${obj.length})`;
}
return chunk;
}
const chunk: JSONChunk<JSONChunk[]> = {
type
};
getGlobalObjectJSONChunk(obj, chunk as any);
if (!chunk.content) {
const clsName = getClassName(obj);
chunk.rightBoundary = '}';
if (clsName !== 'Object') {
chunk.className = clsName;
chunk.leftBoundary = ' {';
} else {
chunk.leftBoundary = '{';
}
chunk.content = getObjectKeysJSONChunks(obj, maxPropLength, (name) => name !== PROTO_PROP);
}
return chunk;
};
export const isProtected = (desc: PropertyDescriptor): boolean => {
return !desc.configurable || !desc.enumerable || !desc.writable || isFunc(desc.get) || isFunc(desc.set);
};
export const getJSONNode = (obj: any, maxPropLength?: number): JSONNode<any> => {
const type = getJSONType(obj);
if (type !== JSONType.object) {
const chunk = getSummaryJSONChunk(obj, true) as JSONNode<any>;
// chunk.node = true;
return chunk;
}
const chunk = getObjectJSONChunk(obj, maxPropLength) as JSONNode<JSONChunk[]>;
if ((isPlainObject(obj) && isEmptyObject(obj)) || (Array.isArray(obj) && !obj.length)) {
chunk.empty = true;
}
// if (isArray(obj)) {
// chunk.content = chunk.content.filter((item) => item.content);
// }
chunk.node = true;
return chunk;
};
export const getJSONTree = (
obj: any,
path?: JSONPropPath,
startPropIndex?: number,
endPropIndex?: number
): JSONTree => {
if (!obj || !isObject(obj)) {
return [];
}
const linkPath = (prop: string | symbol): JSONPropPath => {
if (path) {
return path.concat(prop);
}
return [prop];
};
const res: JSONTree = [];
let filter: JSONPropFilter;
// TODO:属性过多时,需要处理
if (startPropIndex >= 0 && endPropIndex > 0) {
let index = -1;
filter = (): boolean => {
index++;
if (index >= startPropIndex && index < endPropIndex) {
return true;
}
return false;
};
}
const propDescs = getOwnPropertyDescriptors(obj, filter).sort((a, b) => {
if (isProtected(a.desc) && isProtected(b.desc)) {
return 0;
}
return isProtected(a.desc) ? 1 : -1;
});
const isArr = isArray(obj);
propDescs.forEach(({ prop, desc }) => {
if (prop === PROTO_PROP) {
if (!desc.value) {
return;
}
if (isArr && desc.value.constructor && desc.value.constructor === getGlobalObjectConstructor('Array')) {
return;
}
if (desc.value.constructor && desc.value.constructor === getGlobalObjectConstructor('Object')) {
return;
}
}
const propChunk = getJSONProp(prop);
propChunk.protected = isProtected(desc);
let node: JSONValue;
if (isFunc(desc.get)) {
node = {
type: JSONType.compute,
leftBoundary: '(',
rightBoundary: ')',
content: '...'
} as any;
} else {
node = getJSONNode(obj[prop]) as JSONValue;
}
node.value = true;
node.path = linkPath(prop);
res.push({
row: true,
path: linkPath(prop),
prop: propChunk,
value: node
});
});
return res;
};
export const includeString = (str: string, keyword: string): boolean => {
str = typeof str === 'undefined' ? '' : String(str);
keyword = typeof keyword === 'undefined' ? '' : String(keyword);
if (str.indexOf(keyword) !== -1) {
return true;
}
const lwA = str.toLowerCase();
const lwB = keyword.toLowerCase();
return lwA.indexOf(lwB) !== -1;
};
const _include = (obj: any, keyword: string, searchPosition?: 'key' | 'val' | 'all', deepCount?: number): boolean => {
const type = typeof obj;
const res: boolean | undefined = type1Include(type, obj, keyword);
if (typeof res !== 'undefined') {
return res;
}
if (type === 'object') {
if (!obj) {
return _include(String(obj), keyword);
}
const clsName = getClassName(obj);
const res = type2Include(clsName, obj, keyword);
if (typeof res !== 'undefined') {
return res;
}
if (deepCount < 0) {
return false;
}
if (clsName === 'Map') {
let pass = false;
for (const [key, val] of obj as Map<any, any>) {
if (searchPosition === 'all' || searchPosition === 'key') {
pass = _include(key, keyword, searchPosition, deepCount - 1);
if (pass) {
return true;
}
}
if (searchPosition === 'all' || searchPosition === 'val') {
pass = _include(val, keyword, searchPosition, deepCount - 1);
if (pass) {
return true;
}
}
}
return pass;
}
}
return false;
};
const type1Include = (type: string, obj: any, keyword: string): boolean | undefined => {
if (
type === 'string' ||
type === 'boolean' ||
type === 'number' ||
type === 'undefined' ||
type === 'bigint' ||
type === 'symbol'
) {
let str;
if (type === 'symbol') {
str = (obj as Symbol).toString();
} else if (type === 'bigint') {
str = (obj as Symbol).toString() + 'n';
} else {
str = String(obj);
}
return includeString(str, keyword);
}
};
const type2Include = (clsName: string, obj: any, keyword: string): boolean | undefined => {
if (clsName === 'Date') {
return _include((obj as Date).toString(), keyword);
}
if (clsName === 'String') {
return _include((obj as String).valueOf(), keyword);
}
if (clsName === 'Number') {
return _include((obj as Number).valueOf(), keyword);
}
if (clsName === 'Boolean') {
return _include((obj as Number).valueOf(), keyword);
}
if (clsName === 'Symbol') {
return _include((obj as Symbol).valueOf(), keyword);
}
if (clsName === 'BigInt') {
return _include((obj as BigInt).valueOf(), keyword);
}
};
export const include = (
obj: any,
keyword: string,
searchPosition: 'key' | 'val' | 'all' = 'all',
deep: true | false | number = 100
): boolean => {
return _include(
obj,
keyword,
searchPosition,
deep === false ? 0 : deep === true ? Infinity : typeof deep === 'number' ? deep : 0
);
}; | the_stack |
import { EventEmitter } from 'events';
import { Stats as FileStats } from 'fs';
import { Server as HttpServer } from 'http';
import { Readable as ReadableStream } from 'stream';
import * as VinylFile from 'vinyl';
export namespace fractal {
namespace core {
interface StatusInfo {
label: string;
description?: string | undefined;
color?: string | undefined;
}
namespace entities {
abstract class Entity extends mixins.Entity {
readonly isComponent?: true | undefined;
readonly isCollection?: true | undefined;
readonly isDoc?: true | undefined;
readonly isVariant?: true | undefined;
readonly status: StatusInfo;
getResolvedContext(): any;
hasContext(): Promise<boolean>;
setContext(data: any): void;
getContext(): any;
toJSON(): {};
}
interface EntitySource<T extends Entity, TConfig = any> extends mixins.Source<T, TConfig> {
entities(): T[];
engine<TEngine = any>(adapterFactory?: string | {
register(source: EntitySource<T>, app: any): Adapter<TEngine>;
} | (() => ({
register(source: EntitySource<T>, app: any): Adapter<TEngine>;
}))): Adapter<TEngine>;
getProp(key: string): string | {};
statusInfo(handle: string): StatusInfo | null;
toJSON(): {};
}
interface EntityCollection<T extends Entity> extends mixins.Entity, mixins.Collection<T> {
readonly entities: this;
toJSON(): {};
}
}
namespace mixins {
abstract class Configurable<T = any> {
config(): T;
config(config: T): this;
set<K extends keyof T>(path: K, value: T[K] | null): this;
get<K extends keyof T, V = T[K]>(path: K, defaultValue?: V): T[K] | V | null | undefined;
}
/**
* Combined EventEmitter and Configurable mixins
*/
abstract class ConfigurableEmitter<T = any> extends EventEmitter { }
interface ConfigurableEmitter<T = any> extends Configurable<T> { }
interface Collection<T = any> {
readonly isAsset: undefined;
readonly isComponent: undefined;
readonly isCollection: true;
readonly isDoc: undefined;
readonly isFile: undefined;
readonly isVariant: undefined;
readonly size: number;
readonly items: T[];
toArray(): T[];
setItems(items: T[]): this;
pushItem(item: T): this;
removeItem(item: T): this;
toJSON(): {};
toStream(): ReadableStream;
each(fn: (item: T) => void): this;
forEach(fn: (item: T) => void): this;
map(fn: (item: T) => T): this;
first(): T | undefined;
last(): T | undefined;
eq(pos: number): T | undefined;
collections(): this;
orderBy(): this;
find(handle: string): T;
find<TKey extends keyof T>(name: TKey, value: T[TKey]): T;
findCollection(handle: string): Collection<T>;
findCollection<TKey extends keyof T>(name: TKey, value: T[TKey]): Collection<T>;
flatten(): this;
flattenDeep(): this;
squash(): this;
filter(handle: string): T[];
filter<TKey extends keyof T>(name: TKey, value: T[TKey]): T[];
filterItems(items: T[], handle: string): T[];
filterItems<TKey extends keyof T>(items: T[], name: TKey, value: T[TKey]): T[];
flattenItems(items: T[], deep?: boolean): T[];
squashItems(items: T[]): T[];
newSelf(items: T[]): this;
[Symbol.iterator](): IterableIterator<T>;
}
abstract class Entity {
initEntity(name: string, config: any, parent: Entity): void;
name: string;
handle: string;
label: string;
title: string;
order: number;
id: string;
config: any;
readonly alias: string | null;
readonly source: entities.EntitySource<entities.Entity>;
readonly parent: Entity;
readonly isHidden: boolean;
toJSON(): {};
}
interface Source<T = any, TConfig = any> extends ConfigurableEmitter<TConfig>, Collection<T> {
readonly label: string;
readonly title: string;
readonly source: this;
readonly isWatching: boolean;
readonly fullPath: string | null;
readonly relPath: string;
toStream(): ReadableStream;
exists(): boolean;
load(force?: boolean): Promise<this>;
refresh(): Promise<this>;
watch(): void;
unwatch(): void;
isConfig(file: string): boolean;
}
}
}
namespace api {
namespace assets {
class Asset extends core.entities.Entity {
readonly isAsset: true;
readonly isComponent: undefined;
readonly isCollection: undefined;
readonly isDoc: undefined;
readonly isFile: undefined;
readonly isVariant: undefined;
toVinyl(): VinylFile;
}
interface AssetCollection extends core.entities.EntityCollection<Asset> {
assets(): this;
toVinylArray(): VinylFile[];
}
interface AssetSource extends core.mixins.Source<VinylFile> {
assets(): VinylFile[];
toVinylArray(): VinylFile[];
toVinylStream(): ReadableStream;
gulpify(): ReadableStream;
}
interface AssetSourceCollection extends core.mixins.ConfigurableEmitter {
readonly label: string;
readonly title: string;
add(name: string, config: any): AssetSource;
remove(name: string): this;
find(name: string): AssetSource | undefined;
sources(): AssetSource[];
toArray(): AssetSource[];
visible(): AssetSource[];
watch(): this;
unwatch(): this;
load(): Promise<void>;
toJSON(): {};
[Symbol.iterator](): IterableIterator<AssetSource>;
}
}
namespace components {
class Component extends core.entities.Entity {
constructor(config: {}, files: files.FileCollection, resources: assets.AssetCollection, parent: core.entities.Entity);
readonly isAsset: undefined;
readonly isComponent: true;
readonly isCollection: undefined;
readonly isDoc: undefined;
readonly isFile: undefined;
readonly isVariant: undefined;
defaultName: string;
lang: string;
editorMode: string;
editorScope: string;
viewPath: string;
viewDir: string;
configData: string;
relViewPath: string;
isCollated(): boolean;
readonly content: string;
readonly references: any[];
readonly referencedBy: any[];
readonly baseHandle: string;
readonly notes: string;
render(context: any, env: any, opts: any): Promise<string>;
getPreviewContext(): Promise<any>;
getPreviewContent(): Promise<string>;
setVariants(variantCollection: variants.VariantCollection): void;
hasTag(tag: string): boolean;
resources(): assets.AssetCollection;
resourcesJSON(): {};
flatten(): variants.VariantCollection;
component(): this;
variants(): variants.VariantCollection;
static create(config: {}, files: files.FileCollection, resources: assets.AssetCollection, parent: core.entities.Entity): IterableIterator<{} | variants.VariantCollection | Component>;
}
interface ComponentCollection extends core.entities.EntityCollection<Component> {
components(): this;
variants(): this;
}
type Collator = (markup: string, item: { handle: string; }) => string;
interface ComponentDefaultConfig {
collated?: boolean | undefined;
collator?: Collator | undefined;
context?: any;
display?: any;
prefix?: string | undefined;
preview?: string | undefined;
status?: string | undefined;
}
interface ComponentConfig {
path?: string | undefined;
ext?: string | undefined;
default?: ComponentDefaultConfig | undefined;
label?: string | undefined;
statuses?: {
[status: string]: core.StatusInfo;
} | undefined;
title?: string | undefined;
yield?: string | undefined;
'default.collated'?: boolean | undefined;
'default.collator'?: Collator | undefined;
'default.context'?: any;
'default.display'?: any;
'default.prefix'?: string | undefined;
'default.preview'?: string | undefined;
'default.status'?: string | undefined;
}
interface ComponentSource extends core.entities.EntitySource<Component, ComponentConfig> {
resources(): files.FileCollection;
components(): Component[];
getReferencesOf(target: { id: string; handle: string; alias: string; }): any[];
variants(): this;
find(): any;
findFile(filePath: string): files.File | undefined;
resolve(context: any): any;
renderString(str: string, context: any, env: any): Promise<string>;
renderPreview(entity: string | core.entities.Entity, preview?: boolean, env?: any): Promise<string>;
render(entity: string | core.entities.Entity, context: any, env?: any, opts?: {}): Promise<string>;
}
}
namespace docs {
class Doc extends core.entities.Entity {
constructor(config: any, content: string, parent: core.entities.Entity);
readonly isAsset: undefined;
readonly isComponent: undefined;
readonly isCollection: undefined;
readonly isDoc: true;
readonly isFile: undefined;
readonly isVariant: undefined;
readonly isIndex: boolean;
getContent(): Promise<string>;
getContentSync(): string;
render(context: any, env?: any, opts?: any): Promise<string>;
toc(maxDepth?: number): Promise<string>;
static create(config: any, content: string, parent: core.entities.Entity): Doc;
}
interface DocCollection extends core.entities.EntityCollection<Doc> {
pages(): this;
}
interface DocDefaultConfig {
context?: any;
prefix?: string | undefined;
status?: string | undefined;
}
interface DocMarkdownConfig {
gfm?: boolean | undefined;
tables?: boolean | undefined;
breaks?: boolean | undefined;
pedantic?: boolean | undefined;
sanitize?: boolean | undefined;
smartLists?: boolean | undefined;
smartypants?: boolean | undefined;
}
interface DocConfig {
default?: DocDefaultConfig | undefined;
ext?: string | undefined;
indexLabel?: string | undefined;
label?: string | undefined;
markdown?: boolean | DocMarkdownConfig | undefined;
path?: string | undefined;
statuses?: {
[status: string]: core.StatusInfo;
} | undefined;
title?: string | undefined;
'default.context'?: any;
'default.prefix'?: string | undefined;
'default.status'?: string | undefined;
'markdown.gfm'?: boolean | undefined;
'markdown.tables'?: boolean | undefined;
'markdown.breaks'?: boolean | undefined;
'markdown.pedantic'?: boolean | undefined;
'markdown.sanitize'?: boolean | undefined;
'markdown.smartLists'?: boolean | undefined;
'markdown.smartypants'?: boolean | undefined;
}
interface DocSource extends core.entities.EntitySource<Doc, DocConfig> {
pages(): this;
docs(): this;
resolve(context: any): any;
toc(page: files.File, maxDepth?: number): Promise<string>;
render(page: string | files.File, context?: any, env?: any, opts?: {}): Promise<string>;
renderString(str: string, context: any, env?: any): Promise<string>;
isPage(file: string): boolean;
isTemplate(file: string): boolean;
}
}
namespace files {
interface FileCollection extends core.mixins.Collection<File> {
files(): this;
match(test: string | RegExp | Array<string | RegExp>): this;
matchItems(items: core.mixins.Collection<File>, test: string | RegExp | Array<string | RegExp>): File;
toVinylArray(): VinylFile[];
toVinylStream(): ReadableStream;
gulpify(): ReadableStream;
}
interface File {
readonly isAsset: undefined;
readonly isComponent: undefined;
readonly isCollection: undefined;
readonly isDoc: undefined;
readonly isFile: true;
readonly isVariant: undefined;
id: string;
path: string;
cwd: string;
relPath: string;
base: string;
dir: string;
handle: string;
name: string;
ext: string;
stat: FileStats | null;
lang: string;
editorMode: string;
editorScope: string;
githubColor: string;
isBinary: boolean;
mime: string;
getContext(): any;
readonly contents: Buffer;
readonly isImage: boolean;
getContent(): Promise<string>;
getContentSync(): string;
read(): Promise<string>;
readSync(): string;
toVinyl(): VinylFile;
}
}
namespace variants {
class Variant extends core.entities.Entity {
constructor(config: {}, view: any, resources: assets.AssetCollection, parent: components.Component);
readonly isAsset: undefined;
readonly isComponent: undefined;
readonly isCollection: undefined;
readonly isDoc: undefined;
readonly isFile: true;
readonly isVariant: true;
view: any;
viewPath: string;
viewDir: string;
relViewPath: string;
isDefault: boolean;
lang: string;
editorMode: string;
editorScope: string;
readonly notes: string;
readonly alias: string | null;
readonly siblings: VariantCollection;
readonly content: string;
readonly baseHandle: string;
readonly references: any[];
readonly referencedBy: any[];
render(context: any, env?: any, opts?: any): Promise<string>;
getPreviewContext(): Promise<any>;
getPreviewContent(): Promise<string>;
component(): components.Component;
variant(): this;
defaultVariant(): this;
resources(): assets.AssetCollection;
resourcesJSON(): {};
getContent(): Promise<string>;
getContentSync(): string;
static create(config: {}, view: any, resources: assets.AssetCollection, parent: components.Component): Variant;
}
interface VariantCollection extends core.entities.EntityCollection<Variant> {
default(): Variant;
getCollatedContent(): Promise<string>;
getCollatedContentSync(): string;
getCOllatedContext(): Promise<any>;
readonly references: any[];
readonly referencedBy: any[];
}
}
}
namespace cli {
class Cli {
console: Console;
notify: Notifier;
has(command: string): boolean;
get(command: string): any;
isInteractive(): boolean;
command(
commandString: string,
callback: (this: Cli & { fractal: Fractal }, args: any, done: () => void) => void, opts?: string | {
description?: string | undefined;
options?: string[][] | undefined;
}): void;
exec(command: string): void;
log(message: string): void;
error(message: string): void;
}
class Console {
theme: CliTheme;
br(): this;
log(text: string): this;
debug(text: string, data?: any): this;
success(text: string): this;
warn(text: string): this;
update(text: string, type?: string): this;
clear(): this;
persist(): this;
error(err: Error): this;
error(err: string, data: Error): this;
dump(data: any): void;
box(header?: string, body?: string[], footer?: string): this;
write(str: string, type?: string): void;
columns(data: any, options?: any): this;
slog(): this;
unslog(): this;
isSlogging(): boolean;
debugMode(status: boolean): void;
}
class Notifier {
updateAvailable(details: {
current: string;
latest: string;
name: string;
}): void;
versionMismatch(details: {
cli: string;
local: string;
}): void;
}
}
namespace web {
class Builder extends EventEmitter {
/**
* @deprecated Use start() instead.
*/
build(): Promise<{ errorCount: number; }>;
start(): Promise<{ errorCount: number; }>;
stop(): void;
use(): void;
}
class Server extends EventEmitter {
readonly isSynced: boolean;
readonly port?: number | undefined;
readonly ports: {
sync?: number | undefined;
server?: number | undefined;
};
readonly url?: string | undefined;
readonly urls: {
sync?: {
local?: string | undefined;
external?: string | undefined;
ui?: string | undefined;
} | undefined;
server?: string | undefined;
};
start(sync?: boolean): Promise<HttpServer>;
stop(): void;
use(mount: string, middleware: any): void;
}
interface WebServerSyncOptions {
open?: boolean | undefined;
browser?: string[] | undefined;
notify?: boolean | undefined;
}
interface WebServerConfig {
sync?: boolean | undefined;
syncOptions?: WebServerSyncOptions | undefined;
port?: number | undefined;
watch?: boolean | undefined;
theme?: WebTheme | string | undefined;
}
interface WebBuilderUrls {
ext?: string | undefined;
}
interface WebBuilderConfig {
concurrency?: number | undefined;
dest?: string | undefined;
ext?: string | undefined;
urls?: WebBuilderUrls | undefined;
theme?: WebTheme | string | undefined;
}
interface WebStaticConfig {
path?: string | undefined;
mount?: string | undefined;
}
interface WebConfig {
builder?: WebBuilderConfig | undefined;
server?: WebServerConfig | undefined;
static?: WebStaticConfig | undefined;
'builder.concurrency'?: number | undefined;
'builder.dest'?: string | undefined;
'builder.ext'?: string | undefined;
'builder.urls'?: WebBuilderUrls | undefined;
'builder.urls.ext'?: string | undefined;
'builder.theme'?: WebTheme | string | undefined;
'server.sync'?: boolean | undefined;
'server.syncOptions'?: WebServerSyncOptions | undefined;
'server.syncOptions.open'?: boolean | undefined;
'server.syncOptions.browser'?: string[] | undefined;
'server.syncOptions.notify'?: boolean | undefined;
'server.port'?: number | undefined;
'server.watch'?: boolean | undefined;
'server.theme'?: WebTheme | string | undefined;
'static.path'?: string | undefined;
'static.mount'?: string | undefined;
}
class Web extends core.mixins.ConfigurableEmitter<WebConfig> {
server(config?: WebServerConfig): Server;
builder(config?: WebBuilderConfig): Builder;
theme(name: string, instance?: WebTheme): this;
defaultTheme(): WebTheme;
defaultTheme(instance: WebTheme): this;
}
}
const Fractal: {
new: Fractal;
};
}
export interface FractalConfig {
project?: {
title?: string | undefined;
version?: string | undefined;
author?: string | undefined;
} | undefined;
'project.title'?: string | undefined;
'project.version'?: string | undefined;
'project.author'?: string | undefined;
}
export function create(config?: FractalConfig): Fractal;
export class Fractal extends fractal.core.mixins.ConfigurableEmitter<FractalConfig> {
constructor(config?: FractalConfig);
readonly components: fractal.api.components.ComponentSource;
readonly docs: fractal.api.docs.DocSource;
readonly assets: fractal.api.assets.AssetSourceCollection;
readonly cli: fractal.cli.Cli;
readonly web: fractal.web.Web;
readonly version: string;
readonly debug: boolean;
extend(plugin: string | ((this: this, core: any) => void)): this;
watch(): this;
unwatch(): this;
load(): Promise<void>;
}
export interface CliThemeConfig {
delimiter?: {
text?: string | undefined;
format?: ((str: string) => string) | undefined;
} | undefined;
styles?: {
[key: string]: any;
} | undefined;
'delimiter.text'?: string | undefined;
'delimiter.format'?: ((str: string) => string) | undefined;
}
export class CliTheme extends fractal.core.mixins.ConfigurableEmitter<CliThemeConfig> {
constructor(config?: CliThemeConfig);
setDelimiter(text: string, formatter: (str: string) => string): void;
delimiter(): string;
setStyle(name: string, opts: any): void;
style(name: string): any;
format(str: string, style?: string, strip?: boolean): string;
}
export interface WebThemeOptions {
skin?: string | undefined;
panels?: string[] | undefined;
rtl: boolean;
lang?: string | undefined;
styles?: string[] | undefined;
scripts?: string[] | undefined;
format?: string | undefined;
static?: {
mount?: string | undefined;
} | undefined;
version?: string | undefined;
favicon?: string | undefined;
nav?: string[] | undefined;
'static.mount': string;
}
export class WebTheme extends fractal.core.mixins.ConfigurableEmitter<WebThemeOptions> {
constructor(viewPaths: string[], options?: WebThemeOptions);
options(): WebThemeOptions;
options(value: WebThemeOptions): this;
setOption<K extends keyof WebThemeOptions>(key: K, value: WebThemeOptions[K]): this;
getOption<K extends keyof WebThemeOptions>(key: K): WebThemeOptions[K];
addLoadPath(path: string): this;
loadPaths(): string[];
setErrorView(view: string): void;
errorView(): string;
setRedirectView(view: string): void;
redirectView(): string;
addStatic(path: string, mount: string): void;
static(): Array<{ path: string; mount: string; }>;
addRoute(path: string, opts: {
handle?: string | undefined;
}, resolver?: any): this;
addResolver(handle: string, resolvers: any): this;
routes(): any[];
resolvers(): any;
matchRoute(urlPath: string): {
route: {
handle: string;
view: string;
};
params: any;
} | false;
urlFromRoute(handle: string, params: any, noRedirect?: boolean): string | null;
}
export abstract class Adapter<TEngine> extends EventEmitter {
constructor(engine: TEngine, source: fractal.core.entities.EntitySource<any>);
protected _source: fractal.core.entities.EntitySource<any>;
readonly engine: TEngine;
readonly views: Array<{
handle: string;
path: string;
content: string;
}>;
setHandlePrefix(prefix: string): this;
load(): void;
getReferencesForView(handle: string): any[];
getView(handle: string): any;
protected _resolve<T>(value: PromiseLike<T> | T): Promise<T>;
abstract render(path: string, str: string, context: any, meta: any): Promise<string>;
}
export namespace utils {
function lang(filePath: string): {
name: string,
mode: string,
scope: string | null,
color: string | null,
};
function titlize(str: string): string;
function slugify(str: string): string;
function toJSON(item: any): {};
function escapeForRegexp(str: string): string;
function parseArgv(): {
command: string;
args: string[];
opts: any;
};
function stringify(data: any, indent?: number): string;
function fileExistsSync(path: string): boolean;
function isPromise<T>(value: T | PromiseLike<T>): value is PromiseLike<T>;
function isPromise(value: any): value is PromiseLike<any>;
function md5(str: string): string;
function mergeProp(prop: any, upstream: any): any;
function defaultsDeep<T>(...args: T[]): T;
function relUrlPath(toPath: string, fromPath: string, opts?: any): string;
}
export namespace core {
type Component = fractal.api.components.Component;
const Component: typeof fractal.api.components.Component;
type Variant = fractal.api.variants.Variant;
const Variant: typeof fractal.api.variants.Variant;
type Doc = fractal.api.docs.Doc;
const Doc: typeof fractal.api.docs.Doc;
} | the_stack |
import { AssetDatabase, EditorGUI, EditorGUILayout, EditorGUIUtility, EditorStyles, GenericMenu, Handles } from "UnityEditor";
import { Color, Event, EventType, FocusType, GUI, GUIContent, GUILayout, GUIUtility, KeyCode, Rect, Texture, Vector2, Vector3 } from "UnityEngine";
import { EventDispatcher } from "../../../plover/events/dispatcher";
import { MenuBuilder } from "./menu_builder";
import { UTreeView } from "./treeview";
export interface ITreeNodeEventHandler {
onTreeNodeContextMenu(node: UTreeNode, builder: MenuBuilder);
onTreeNodeCreated(node: UTreeNode);
onTreeNodeNameEditEnded(node: UTreeNode, newName: string);
onTreeNodeNameChanged(node: UTreeNode, oldName: string);
}
export class BuiltinIcons {
private static _cache: { [key: string]: Texture } = {};
static getIcon(name: string) {
let icon = this._cache[name];
if (typeof icon === "undefined") {
icon = this._cache[name] = <Texture>AssetDatabase.LoadAssetAtPath(`Assets/jsb/Editor/Icons/${name}.png`, Texture);
}
return icon;
}
}
export class UTreeNode {
protected _tree: UTreeView;
protected _parent: UTreeNode;
protected _children: Array<UTreeNode> = null;
protected _expanded: boolean = true;
protected _name: string = "noname";
protected _events: EventDispatcher;
data: any;
isSearchable: boolean = true;
isEditable: boolean = true;
// _lineStart = Vector3.zero;
// _lineStartIn = Vector3.zero;
// protected _lineEnd = Vector3.zero;
_foldoutRect = Rect.zero;
protected _label: GUIContent;
protected _folderClose: Texture;
protected _folderOpen: Texture;
private _bFocusTextField = false;
private _bVisible = true;
private _height = 0;
private _bMatch = true;
get isMatch() { return this._bMatch; }
get height() { return this._height; }
/**
* 当前层级是否展开
*/
get expanded() { return this._expanded; }
set expanded(value: boolean) {
if (this._expanded != value) {
this._expanded = value;
}
}
get isFolder() { return !!this._children; }
get visible() { return this._bVisible; }
set visible(value: boolean) {
if (this._bVisible != value) {
this._bVisible = value;
}
}
get parent() { return this._parent; }
get isRoot() { return this._parent == null; }
get name() { return this._name; }
set name(value: string) {
if (this._name != value) {
let oldName = this._name;
this._name = value;
this._tree.handler.onTreeNodeNameChanged(this, oldName);
}
}
get fullPath() {
let path = this._name;
let node = this._parent;
while (node && !node.isRoot) {
if (node._name && node._name.length > 0) {
path = node._name + "/" + path;
}
node = node._parent;
}
return path;
}
get treeView() { return this._tree; }
constructor(tree: UTreeView, parent: UTreeNode, isFolder: boolean, name: string) {
this._name = name;
this._tree = tree;
this._parent = parent;
this._children = isFolder ? [] : null
}
get childCount() { return this._children ? this._children.length : 0; }
on(evt: string, caller: any, fn?: Function) {
if (!this._events) {
this._events = new EventDispatcher();
}
this._events.on(evt, caller, fn);
}
off(evt: string, caller: any, fn?: Function) {
if (this._events) {
this._events.off(evt, caller, fn);
}
}
dispatch(name: string, arg0?: any, arg1?: any, arg2?: any) {
if (!this._events) {
this._events = new EventDispatcher();
}
this._events.dispatch(name, arg0, arg1, arg2);
}
match(p: string) {
if (p == null || p.length == 0) {
return this._bMatch = true;
}
return this._bMatch = this.isSearchable && this._name.indexOf(p) >= 0;
}
getRelativePath(top: UTreeNode) {
let path = this._name;
let node = this._parent;
while (node && node != top) {
path = node._name + "/" + path;
node = node._parent;
}
return path;
}
expandAll() {
this._setExpandAll(true);
}
collapseAll() {
this._setExpandAll(false);
}
private _setExpandAll(state: boolean) {
this._expanded = state;
if (this._children) {
for (let i = 0, count = this._children.length; i < count; i++) {
this._children[i]._setExpandAll(state);
}
}
}
expandUp() {
let node = this._parent;
while (node) {
node.expanded = true;
node = node.parent;
}
}
/**
* 获取指定节点的在当前层级中的下一个相邻节点
*/
findNextSibling(node: UTreeNode) {
if (this._children) {
let index = this._children.indexOf(node);
if (index >= 0 && index < this._children.length - 1) {
return this._children[index + 1];
}
}
return null;
}
/**
* 获取指定节点的在当前层级中的上一个相邻节点
*/
findLastSibling(node: UTreeNode) {
if (this._children) {
let index = this._children.indexOf(node);
if (index > 0) {
return this._children[index - 1];
}
}
return null;
}
forEachChild(fn: (child: UTreeNode) => void) {
if (this._children) {
for (let i = 0, count = this._children.length; i < count; i++) {
fn(this._children[i]);
}
}
}
/**
* 获取当前层级下的子节点
* @param index 索引 或者 命名
* @param autoNew 不存在时是否创建 (仅通过命名获取时有效)
* @returns 子节点
*/
getFolderByName(name: string, isAutoCreate: boolean, data: any) {
if (this._children) {
for (let i = 0, size = this._children.length; i < size; i++) {
let child = this._children[i];
if (child.isFolder && child.name == name) {
return child;
}
}
if (isAutoCreate) {
let child = this._addChild(name, true, data);
return child;
}
}
return null;
}
getLeafByName(name: string, isAutoCreate: boolean, data: any) {
if (this._children) {
for (let i = 0, size = this._children.length; i < size; i++) {
let child = this._children[i];
if (!child.isFolder && child.name == name) {
return child;
}
}
if (isAutoCreate) {
let child = this._addChild(name, false, data);
return child;
}
}
return null;
}
getChildByIndex(index: number) {
return this._children[index];
}
/**
* 当前层级最后一个子节点
*/
getLastChild() {
return this._children && this._children.length > 0 ? this._children[this._children.length - 1] : null;
}
/**
* 当前层级第一个子节点
*/
getFirstChild() {
return this._children && this._children.length > 0 ? this._children[0] : null;
}
addFolderChild(name: string) {
return this.getFolderByName(name, true, null);
}
addLeafChild(name: string) {
return this.getLeafByName(name, true, null);
}
allocLeafChild(name: string, data: any) {
return this.getLeafByName(name, true, data);
}
/**
* 在当前层级添加一个子节点
*/
private _addChild(name: string, isFolder: boolean, data: any) {
if (this._children) {
let node = new UTreeNode(this._tree, this, isFolder, name);
this._children.push(node);
node._expanded = true;
node.data = data;
this._tree.handler.onTreeNodeCreated(node);
return node;
}
return null;
}
/**
* 将一个子节点从当前层级中移除
*/
removeChild(node: UTreeNode) {
if (this._children) {
let index = this._children.indexOf(node);
if (index >= 0) {
this._children.splice(index, 1);
return true;
}
}
return false;
}
removeAll() {
if (this._children) {
this._children.splice(0);
}
}
calcRowHeight() {
this._height = EditorGUIUtility.singleLineHeight;
return this._height;
}
drawMenu(treeView: UTreeView, pos: Vector2, handler: ITreeNodeEventHandler) {
let builder = new MenuBuilder();
handler.onTreeNodeContextMenu(this, builder);
treeView.dispatch(UTreeView.CONTEXT_MENU, builder, this);
let menu = builder.build();
if (menu) {
menu.ShowAsContext();
}
}
draw(rect: Rect, bSelected: boolean, bEditing: boolean, indentSize: number) {
// let lineY = rect.y + rect.height * 0.5;
// this._lineStartIn.Set(rect.x - indentSize * 1.5, lineY, 0);
// this._lineStart.Set(rect.x - indentSize * 1.5, rect.y + rect.height, 0);
this._bVisible = true;
if (this._children && this._children.length > 0) {
this._foldoutRect.Set(rect.x - 14, rect.y, 12, rect.height);
/*this._expanded =*/EditorGUI.Foldout(this._foldoutRect, this._expanded, GUIContent.none);
// this._lineEnd.Set(rect.x - indentSize, lineY, 0);
let image = this._expanded ? BuiltinIcons.getIcon("FolderOpened") : BuiltinIcons.getIcon("Folder");
if (!this._label) {
this._label = new GUIContent(this._name, image);
} else {
this._label.image = image;
}
} else {
// this._lineEnd.Set(rect.x - 4, lineY, 0);
if (!this._label) {
this._label = new GUIContent(this._name, BuiltinIcons.getIcon("JsScript"));
}
}
// Handles.color = Color.gray;
// Handles.DrawLine(this._lineStartIn, this._lineEnd);
if (bEditing) {
let text: string;
if (this._bFocusTextField) {
GUI.SetNextControlName("TreeViewNode.Editing");
this._label.text = EditorGUI.TextField(rect, this._label.text);
} else {
GUI.SetNextControlName("TreeViewNode.Editing");
this._label.text = EditorGUI.TextField(rect, this._label.text);
GUI.FocusControl("TreeViewNode.Editing");
}
} else {
this._bFocusTextField = false;
EditorGUI.LabelField(rect, this._label, bSelected ? EditorStyles.whiteLabel : EditorStyles.label);
}
}
endEdit() {
if (this._label.text != this._name) {
this._tree.handler.onTreeNodeNameEditEnded(this, this._label.text);
}
}
} | the_stack |
import express from 'express';
import * as db from '../util/db';
import * as organization from '../model/organization';
import * as device from '../model/device';
import * as oauth2 from '../model/oauth2';
import * as userModel from '../model/user';
import * as user from '../util/user';
import * as SendMail from '../util/sendmail';
import * as iv from '../util/input_validation';
import { tokenize } from '../util/tokenize';
import { BadRequestError } from '../util/errors';
import * as Config from '../config';
import * as EngineManager from '../almond/enginemanagerclient';
const router = express.Router();
const HAS_ABOUT_GET_INVOLVED = Config.EXTRA_ABOUT_PAGES.some((p) => p.url === 'get-involved');
router.get('/', (req, res, next) => {
if (!user.isAuthenticated(req) || !req.user.developer_org) {
if (HAS_ABOUT_GET_INVOLVED)
res.redirect('/about/get-involved');
else
res.redirect('/user/request-developer');
return;
}
db.withTransaction((dbClient) => {
return Promise.all([
organization.get(dbClient, req.user!.developer_org!),
organization.getMembers(dbClient, req.user!.developer_org!),
organization.getInvitations(dbClient, req.user!.developer_org!),
organization.getStatistics(dbClient, req.user!.developer_org!)
]);
}).then(([developer_org, developer_org_members, developer_org_invitations, developer_org_stats]) => {
res.render('dev_overview', { page_title: req._("Genie Developer Console"),
csrfToken: req.csrfToken(),
developer_org,
developer_org_members,
developer_org_invitations,
developer_org_stats
});
}).catch(next);
});
router.get('/oauth', user.requireLogIn, user.requireDeveloper(), (req, res, next) => {
db.withClient((dbClient) => {
return oauth2.getClientsByOwner(dbClient, req.user!.developer_org!);
}).then((developer_oauth2_clients) => {
res.render('dev_oauth', { page_title: req._("Genie Developer Console - OAuth 2.0 Applications"),
csrfToken: req.csrfToken(),
developer_oauth2_clients: developer_oauth2_clients
});
}).catch(next);
});
router.post('/organization/add-member', user.requireLogIn, user.requireDeveloper(user.DeveloperStatus.ORG_ADMIN), (req, res, next) => {
db.withTransaction(async (dbClient) => {
const [row] = await userModel.getByName(dbClient, req.body.username);
try {
if (!row)
throw new BadRequestError(req._("No such user %s").format(req.body.username));
if (row.developer_org !== null)
throw new BadRequestError(req._("%s is already a member of another developer organization.").format(req.body.username));
if (!row.email_verified)
throw new BadRequestError(req._("%s has not verified their email address yet.").format(req.body.username));
} catch(e) {
res.status(400).render('error', { page_title: req._("Genie - Error"),
message: e });
return false;
}
// check if the user was already invited to this org
// if so, we do nothing, silently
const [invitation] = await organization.findInvitation(dbClient, req.user!.developer_org!, row.id);
if (invitation)
return true;
const org = await organization.get(dbClient, req.user!.developer_org!);
let developerStatus = parseInt(req.body.developer_status);
if (isNaN(developerStatus) || developerStatus < 0)
developerStatus = 0;
if (developerStatus > user.DeveloperStatus.ORG_ADMIN)
developerStatus = user.DeveloperStatus.ORG_ADMIN;
await sendInvitationEmail(req.user!, org, row);
await organization.inviteUser(dbClient, req.user!.developer_org!, row.id, developerStatus);
return true;
}).then((ok) => {
if (ok)
res.redirect(303, '/developers');
}).catch(next);
});
async function sendInvitationEmail(fromUser : userModel.Row, org : organization.Row, toUser : userModel.Row) {
const mailOptions = {
from: Config.EMAIL_FROM_USER,
to: toUser.email,
subject: 'You are invited to join a Thingpedia developer organization',
text:
`Hello!
${fromUser.human_name || fromUser.username} is inviting you to join the “${org.name}” developer organization.
To accept, click here:
<${Config.SERVER_ORIGIN}/developers/organization/accept-invitation/${org.id_hash}>
----
You are receiving this email because this address is associated
with your Almond account.
`
};
return SendMail.send(mailOptions);
}
router.get('/organization/accept-invitation/:id_hash', user.requireLogIn, (req, res, next) => {
db.withTransaction(async (dbClient) => {
let org, invitation;
try {
if (req.user!.developer_org !== null)
throw new BadRequestError(req._("You are already a member of another developer organization."));
org = await organization.getByIdHash(dbClient, req.params.id_hash);
[invitation] = await organization.findInvitation(dbClient, org.id, req.user!.id);
if (!invitation)
throw new BadRequestError(req._("The invitation is no longer valid. It might have expired or might have been rescinded by the organization administrator."));
} catch(e) {
res.status(400).render('error', { page_title: req._("Genie - Error"),
message: e });
return [null, null];
}
await user.makeDeveloper(dbClient, req.user!.id, org.id, invitation.developer_status);
await organization.rescindAllInvitations(dbClient, req.user!.id);
return [req.user!.id, org.name] as const;
}).then(async ([userId, orgName]) => {
if (userId !== null) {
await EngineManager.get().restartUser(userId);
res.render('message', {
page_title: req._("Genie - Developer Invitation"),
message: req._("You're now a member of the %s organization.").format(orgName)
});
}
}).catch(next);
});
router.post('/organization/rescind-invitation', user.requireLogIn, user.requireDeveloper(user.DeveloperStatus.ORG_ADMIN), (req, res, next) => {
db.withTransaction(async (dbClient) => {
const [row] = await userModel.getByCloudId(dbClient, req.body.user_id);
if (!row)
throw new BadRequestError(req._("No such user"));
await organization.rescindInvitation(dbClient, req.user!.developer_org!, row.id);
}).then(() => {
res.redirect(303, '/developers');
}).catch(next);
});
router.post('/organization/remove-member', user.requireLogIn, user.requireDeveloper(user.DeveloperStatus.ORG_ADMIN), (req, res, next) => {
db.withTransaction(async (dbClient) => {
const users = await userModel.getByCloudId(dbClient, req.body.user_id);
if (users[0].cloud_id === req.user!.cloud_id)
throw new BadRequestError(req._("You cannot remove yourself from your developer organization."));
if (users.length === 0)
throw new BadRequestError(req._("No such user"));
if (users[0].developer_org !== req.user!.developer_org)
throw new BadRequestError(req._("The user is not a member of your developer organization."));
await user.makeDeveloper(dbClient, users[0].id, null);
const userId = users[0].id;
await EngineManager.get().restartUserWithoutCache(userId);
res.redirect(303, '/developers');
}).catch(next);
});
router.post('/organization/promote', user.requireLogIn, user.requireDeveloper(user.DeveloperStatus.ORG_ADMIN), (req, res, next) => {
db.withTransaction(async (dbClient) => {
const users = await userModel.getByCloudId(dbClient, req.body.user_id);
if (users.length === 0)
throw new BadRequestError(req._("No such user"));
if (users[0].developer_org !== req.user!.developer_org)
throw new BadRequestError(req._("The user is not a member of your developer organization."));
if (users[0].developer_status >= user.DeveloperStatus.ORG_ADMIN)
return;
await userModel.update(dbClient, users[0].id, {
developer_status: users[0].developer_status + 1,
});
}).then(() => {
res.redirect(303, '/developers');
}).catch(next);
});
router.post('/organization/demote', user.requireLogIn, user.requireDeveloper(user.DeveloperStatus.ORG_ADMIN), (req, res, next) => {
db.withTransaction(async (dbClient) => {
const users = await userModel.getByCloudId(dbClient, req.body.user_id);
if (users[0].cloud_id === req.user!.cloud_id)
throw new BadRequestError(req._("You cannot demote yourself."));
if (users.length === 0)
throw new BadRequestError(req._("No such user"));
if (users[0].developer_org !== req.user!.developer_org)
throw new BadRequestError(req._("The user is not a member of your developer organization."));
if (users[0].developer_status <= 0)
return;
await userModel.update(dbClient, users[0].id, {
developer_status: users[0].developer_status - 1,
});
}).then(() => {
res.redirect(303, '/developers');
}).catch(next);
});
router.post('/organization/edit-profile', user.requireLogIn, user.requireDeveloper(user.DeveloperStatus.ORG_ADMIN),
iv.validatePOST({ name: 'string' }), (req, res, next) => {
for (const token of tokenize(req.body.name)) {
if (['stanford', 'almond'].indexOf(token) >= 0) {
res.status(400).render('error', { page_title: req._("Genie - Error"),
message: req._("You cannot use the word “%s” in your organization name.").format(token) });
return;
}
}
db.withTransaction((dbClient) => {
return organization.update(dbClient, req.user!.developer_org!, { name: req.body.name });
}).then(() => {
res.redirect(303, '/developers');
}).catch(next);
});
router.get('/status', (req, res) => {
res.redirect('/me/status');
});
if (Config.WITH_THINGPEDIA === 'embedded') {
router.get('/devices', user.requireLogIn, user.requireDeveloper(), (req, res, next) => {
db.withClient((dbClient) => {
return device.getByOwner(dbClient, req.user!.developer_org!);
}).then((developer_devices) => {
res.render('dev_devices', { page_title: req._("Genie Developer Console - Devices"),
developer_devices });
}).catch(next);
});
}
export default router; | the_stack |
import {DomUtils} from "../domParsers/domUtils";
import * as Log from "../logging/log";
import {Constants} from "../constants";
import {ClientType} from "../clientType";
import {Status} from "./status";
import {ClipperStateProp} from "./clipperState";
import {ComponentBase} from "./componentBase";
import {Clipper} from "./frontEndGlobals";
import {ExtensionUtils} from "../extensions/extensionUtils";
import {Localization} from "../localization/localization";
export interface Point {
x: number;
y: number;
};
interface RegionSelectorState {
firstPoint?: Point;
secondPoint?: Point;
mousePosition?: Point;
selectionInProgress?: boolean;
keyboardSelectionInProgress?: boolean;
winWidth?: number;
winHeight?: number;
}
class RegionSelectorClass extends ComponentBase<RegionSelectorState, ClipperStateProp> {
private devicePixelRatio: number = 1;
private cursorSpeed: number = 1;
private resizeHandler = this.handleResize.bind(this);
private mouseMovementHandler = this.globalMouseMoveHandler.bind(this);
private mouseOverHandler = this.globalMouseOverHandler.bind(this);
private keyDownDict: { [key: number]: boolean } = {};
getInitialState(): RegionSelectorState {
return {
selectionInProgress: false,
keyboardSelectionInProgress: false,
winHeight: window.innerHeight,
winWidth: window.innerWidth,
mousePosition: {x: window.innerWidth / 2, y: window.innerHeight / 2}
};
}
constructor(props: ClipperStateProp) {
super(props);
this.resetState();
window.addEventListener("resize", this.resizeHandler);
window.addEventListener("mousemove", this.mouseMovementHandler);
window.addEventListener("mouseover", this.mouseOverHandler);
}
private onunload() {
window.removeEventListener("resize", this.resizeHandler);
window.removeEventListener("mousemove", this.mouseMovementHandler);
window.removeEventListener("mouseover", this.mouseOverHandler);
}
/**
* Start the selection process over
*/
private resetState() {
this.setState({ firstPoint: undefined, secondPoint: undefined, selectionInProgress: false, keyboardSelectionInProgress: false});
this.props.clipperState.setState({ regionResult: { status: Status.NotStarted, data: this.props.clipperState.regionResult.data } });
}
/**
* Define the starting point for the selection
*/
private startSelection(point: Point, fromKeyboard = false) {
if (this.props.clipperState.regionResult.status !== Status.InProgress) {
this.setState({ firstPoint: point, secondPoint: undefined, selectionInProgress: true, keyboardSelectionInProgress: fromKeyboard });
this.props.clipperState.setState({ regionResult: { status: Status.InProgress, data: this.props.clipperState.regionResult.data } });
}
}
/**
* The selection is complete
*/
private completeSelection(dataUrl: string) {
let regionList = this.props.clipperState.regionResult.data;
if (!regionList) {
regionList = [];
}
regionList.push(dataUrl);
this.props.clipperState.setState({ regionResult: { status: Status.Succeeded, data: regionList } });
}
/**
* They are selecting, update the second point
*/
private moveSelection(point: Point) {
this.setState({ secondPoint: point });
}
/**
* Update Mouse Position for custom cursor
*/
private setMousePosition(point: Point) {
this.setState({ mousePosition: point});
}
/**
* Define the ending point, and notify the main UI
*/
private stopSelection(point: Point) {
if (this.state.selectionInProgress) {
if (!this.state.firstPoint || !this.state.secondPoint || this.state.firstPoint.x === this.state.secondPoint.x || this.state.firstPoint.y === this.state.secondPoint.y) {
// Nothing to clip, start over
this.resetState();
} else {
this.setState({ secondPoint: point, selectionInProgress: false, keyboardSelectionInProgress: false });
// Get the image immediately
this.startRegionClip();
}
}
}
private mouseDownHandler(e: MouseEvent) {
// Prevent default "dragging" which sometimes occurs
e.preventDefault();
this.startSelection({ x: e.pageX, y: e.pageY });
}
private keyDownHandler(e: KeyboardEvent) {
this.keyDownDict[e.which] = true;
if (e.which === Constants.KeyCodes.enter ) {
if (!this.state.selectionInProgress) {
this.startSelection({ x: this.state.mousePosition.x, y: this.state.mousePosition.y }, true /* fromKeyboard */);
} else {
this.stopSelection({ x: this.state.mousePosition.x, y: this.state.mousePosition.y });
}
e.preventDefault();
} else if (e.which === Constants.KeyCodes.up
|| e.which === Constants.KeyCodes.down
|| e.which === Constants.KeyCodes.left
|| e.which === Constants.KeyCodes.right) {
let delta: Point = {x: 0, y: 0};
if (this.keyDownDict[Constants.KeyCodes.up]) {
delta.y -= this.cursorSpeed;
}
if (this.keyDownDict[Constants.KeyCodes.down]) {
delta.y += this.cursorSpeed;
}
if (this.keyDownDict[Constants.KeyCodes.left]) {
delta.x -= this.cursorSpeed;
}
if (this.keyDownDict[Constants.KeyCodes.right]) {
delta.x += this.cursorSpeed;
}
let newPosition: Point = {x: Math.max(Math.min(this.state.mousePosition.x + delta.x, this.state.winWidth), 0), y: Math.max(Math.min(this.state.mousePosition.y + delta.y, this.state.winHeight), 0)};
this.setMousePosition(newPosition);
if (this.state.selectionInProgress) {
this.moveSelection(newPosition);
}
if (this.cursorSpeed < 5) {
this.cursorSpeed++;
}
e.preventDefault();
}
}
private keyUpHandler(e: KeyboardEvent) {
this.keyDownDict[e.which] = false;
if (e.which === Constants.KeyCodes.up
|| e.which === Constants.KeyCodes.down
|| e.which === Constants.KeyCodes.left
|| e.which === Constants.KeyCodes.right) {
this.cursorSpeed = 1;
}
}
private globalMouseMoveHandler(e: MouseEvent) {
this.setMousePosition({ x: e.pageX, y: e.pageY });
}
private globalMouseOverHandler(e: MouseEvent) {
window.removeEventListener("mouseover", this.mouseOverHandler);
this.setMousePosition({ x: e.pageX, y: e.pageY });
}
private mouseMoveHandler(e: MouseEvent) {
if (this.state.selectionInProgress) {
if (e.buttons === 0 && !this.state.keyboardSelectionInProgress) {
// They let go of the mouse while outside the window, stop the selection where they went out
this.stopSelection(this.state.secondPoint);
return;
}
this.moveSelection({ x: e.pageX, y: e.pageY });
}
}
private mouseUpHandler(e: MouseEvent) {
this.stopSelection({ x: e.pageX, y: e.pageY });
}
private touchStartHandler(e: TouchEvent) {
let eventPoint = e.changedTouches[0];
this.startSelection({ x: eventPoint.clientX, y: eventPoint.clientY });
}
private touchMoveHandler(e: TouchEvent) {
if (this.state.selectionInProgress) {
let eventPoint = e.changedTouches[0];
this.moveSelection({ x: eventPoint.clientX, y: eventPoint.clientY });
e.preventDefault();
}
}
private touchEndHandler(e: TouchEvent) {
let eventPoint = e.changedTouches[0];
this.stopSelection({ x: eventPoint.clientX, y: eventPoint.clientY });
}
private handleResize() {
this.setState({ winHeight: window.innerHeight, winWidth: window.innerWidth });
}
/**
* Update all of the frames and elements according to the selection
*/
private updateVisualElements(element: HTMLElement, isInitialized: boolean) {
let outerFrame: HTMLCanvasElement = this.refs.outerFrame as HTMLCanvasElement;
if (!outerFrame) {
return;
}
let cursor: HTMLImageElement = this.refs.cursor as HTMLImageElement;
if (cursor) {
cursor.style.left = this.state.mousePosition.x + "px";
cursor.style.top = this.state.mousePosition.y + "px";
}
let xMin: number;
let yMin: number;
let xMax: number;
let yMax: number;
if (!this.state.firstPoint || !this.state.secondPoint) {
xMin = 0;
yMin = 0;
xMax = 0;
yMax = 0;
} else {
xMin = Math.min(this.state.firstPoint.x, this.state.secondPoint.x);
yMin = Math.min(this.state.firstPoint.y, this.state.secondPoint.y);
xMax = Math.max(this.state.firstPoint.x, this.state.secondPoint.x);
yMax = Math.max(this.state.firstPoint.y, this.state.secondPoint.y);
let innerFrame: HTMLCanvasElement = this.refs.innerFrame as HTMLCanvasElement;
if (innerFrame) {
// We don't worry about -1 values as they simply go offscreen neatly
let borderWidth = 1;
innerFrame.style.top = yMin - borderWidth + "px";
innerFrame.style.left = xMin - borderWidth + "px";
innerFrame.style.height = yMax - yMin + "px";
innerFrame.style.width = xMax - xMin + "px";
}
}
let winWidth = this.state.winWidth;
let winHeight = this.state.winHeight;
let context = outerFrame.getContext("2d");
context.canvas.width = winWidth;
context.canvas.height = winHeight;
context.beginPath();
context.fillStyle = "black";
context.fillRect(0, 0, xMin, winHeight);
context.fillRect(xMin, 0, xMax - xMin, yMin);
context.fillRect(xMax, 0, winWidth - xMax, winHeight);
context.fillRect(xMin, yMax, xMax - xMin, winHeight - yMax);
if (!isInitialized) {
element.focus();
}
}
/**
* Get the browser to capture a screenshot, and save off the portion they selected (which may be compressed until it's below
* the maximum allowed size)
*/
private startRegionClip() {
// Taken from https://www.kirupa.com/html5/detecting_retina_high_dpi.htm
// We check this here so that we can log it as a custom property on the regionSelectionProcessingEvent
const query = "(-webkit-min-device-pixel-ratio: 2), (min-device-pixel-ratio: 2), (min-resolution: 192dpi)";
const isHighDpiScreen = matchMedia(query).matches;
const isFirefoxWithHighDpiDisplay = this.props.clipperState.clientInfo.clipperType === ClientType.FirefoxExtension && isHighDpiScreen;
// Firefox reports this value incorrectly if this iframe is hidden, so store it now since we know we're visible
// In addition to this, Firefox currently has a bug where they are not using devicePixelRatio correctly
// on HighDPI screens such as Retina screens or the Surface Pro 4
// Bug link: https://bugzilla.mozilla.org/show_bug.cgi?id=1278507
this.devicePixelRatio = isFirefoxWithHighDpiDisplay ? window.devicePixelRatio / 2 : window.devicePixelRatio;
let regionSelectionProcessingEvent = new Log.Event.BaseEvent(Log.Event.Label.RegionSelectionProcessing);
let regionSelectionCapturingEvent = new Log.Event.BaseEvent(Log.Event.Label.RegionSelectionCapturing);
regionSelectionCapturingEvent.setCustomProperty(Log.PropertyName.Custom.Width, Math.abs(this.state.firstPoint.x - this.state.secondPoint.x));
regionSelectionCapturingEvent.setCustomProperty(Log.PropertyName.Custom.Height, Math.abs(this.state.firstPoint.y - this.state.secondPoint.y));
Clipper.getExtensionCommunicator().callRemoteFunction(Constants.FunctionKeys.takeTabScreenshot, {
callback: (dataUrl: string) => {
Clipper.logger.logEvent(regionSelectionCapturingEvent);
this.saveCompressedSelectionToState(dataUrl).then((canvas) => {
regionSelectionProcessingEvent.setCustomProperty(Log.PropertyName.Custom.Width, canvas.width);
regionSelectionProcessingEvent.setCustomProperty(Log.PropertyName.Custom.Height, canvas.height);
regionSelectionProcessingEvent.setCustomProperty(Log.PropertyName.Custom.IsHighDpiScreen, isHighDpiScreen);
Clipper.logger.logEvent(regionSelectionProcessingEvent);
});
}
});
}
/**
* Given a base image in url form, captures the sub-image defined by the state's first and second points, compresses it if
* necessary, then saves it to state if the process was successful
*/
private saveCompressedSelectionToState(baseDataUrl: string): Promise<HTMLCanvasElement> {
return this.createSelectionAsCanvas(baseDataUrl).then((canvas) => {
let compressedSelection = this.getCompressedDataUrl(canvas);
this.completeSelection(compressedSelection);
return Promise.resolve(canvas);
}).catch((error: Error) => {
Clipper.logger.logFailure(Log.Failure.Label.RegionSelectionProcessing, Log.Failure.Type.Unexpected,
{ error: error.message });
this.resetState();
return Promise.reject(error);
});
}
/**
* Given a base image in url form, creates a canvas containing the sub-image defined by the state's first and second points
*/
private createSelectionAsCanvas(baseDataUrl: string): Promise<HTMLCanvasElement> {
if (!baseDataUrl) {
return Promise.reject(new Error("baseDataUrl should be a non-empty string, but was: " + baseDataUrl));
}
if (!this.state.firstPoint || !this.state.secondPoint) {
return Promise.reject(new Error("Expected the two points to be set, but they were not"));
}
const devicePixelRatio = this.devicePixelRatio;
return new Promise<HTMLCanvasElement>((resolve) => {
let regionSelectionLoadingEvent = new Log.Event.BaseEvent(Log.Event.Label.RegionSelectionLoading);
let img: HTMLImageElement = new Image();
img.onload = () => {
Clipper.logger.logEvent(regionSelectionLoadingEvent);
let xMin = Math.min(this.state.firstPoint.x, this.state.secondPoint.x);
let yMin = Math.min(this.state.firstPoint.y, this.state.secondPoint.y);
let xMax = Math.min(img.width, Math.max(this.state.firstPoint.x, this.state.secondPoint.x));
let yMax = Math.min(img.height, Math.max(this.state.firstPoint.y, this.state.secondPoint.y));
let destinationOffsetX = 0;
let destinationOffsetY = 0;
let width = (xMax - xMin);
let height = (yMax - yMin);
let sourceOffsetX = xMin * devicePixelRatio;
let sourceOffsetY = yMin * devicePixelRatio;
let sourceWidth = (xMax - xMin) * devicePixelRatio;
let sourceHeight = (yMax - yMin) * devicePixelRatio;
let canvas: HTMLCanvasElement = document.createElement("canvas") as HTMLCanvasElement;
canvas.width = width;
canvas.height = height;
let ctx: CanvasRenderingContext2D = canvas.getContext("2d");
ctx.drawImage(img, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, destinationOffsetX, destinationOffsetY, width, height);
resolve(canvas);
};
img.src = baseDataUrl;
});
}
/*
* Converts the canvas to a Base64 encoded URI, compressing it by lowering its quality if above the maxBytes threshold
*/
private getCompressedDataUrl(node: Node): string {
let compressEvent = new Log.Event.BaseEvent(Log.Event.Label.CompressRegionSelection);
let canvas: HTMLCanvasElement = node as HTMLCanvasElement;
// First, see if the best quality PNG will work.
let dataUrl: string = canvas.toDataURL("image/png");
compressEvent.setCustomProperty(Log.PropertyName.Custom.InitialDataUrlLength, dataUrl.length);
dataUrl = DomUtils.adjustImageQualityIfNecessary(canvas, dataUrl);
compressEvent.setCustomProperty(Log.PropertyName.Custom.FinalDataUrlLength, dataUrl.length);
Clipper.logger.logEvent(compressEvent);
return dataUrl;
}
private getInnerFrame() {
if (this.state.secondPoint) {
return <div id={Constants.Ids.innerFrame} {...this.ref(Constants.Ids.innerFrame) }></div>;
}
return undefined;
}
render() {
let innerFrameElement = this.getInnerFrame();
return (
<div tabindex="1" config={this.updateVisualElements.bind(this)} id={Constants.Ids.regionSelectorContainer}
aria-label={Localization.getLocalizedString("WebClipper.Accessibility.ScreenReader.RegionSelectionCanvas")} role="application"
onmousedown={this.mouseDownHandler.bind(this)} onmousemove={this.mouseMoveHandler.bind(this)}
onmouseup={this.mouseUpHandler.bind(this)} ontouchstart={this.touchStartHandler.bind(this)}
ontouchmove={this.touchMoveHandler.bind(this)} ontouchend={this.touchEndHandler.bind(this)}
onkeydown={this.keyDownHandler.bind(this)} onkeyup={this.keyUpHandler.bind(this)}>
<img id="cursor" {...this.ref("cursor")} src={ExtensionUtils.getImageResourceUrl("crosshair_cursor.svg")}
width={Constants.Styles.customCursorSize + "px"} height={Constants.Styles.customCursorSize + "px"} />
<canvas id={Constants.Ids.outerFrame} {...this.ref(Constants.Ids.outerFrame)}></canvas>
{innerFrameElement}
</div>
);
}
}
let component = RegionSelectorClass.componentize();
export {component as RegionSelector}; | the_stack |
import * as binders from "./../binders";
import {TsSourceFile, TsNode, TsTypeNode, TsSignature, TsType, TsSymbol, TsExpression} from "./../compiler";
import * as definitions from "./../definitions";
import {KeyValueCache, Logger} from "./../utils";
import {MainFactory} from "./MainFactory";
function bindToDefinition<DefType>(binder: { bind(def: DefType): void; }, def: DefType) {
binder.bind(def);
return def;
}
export interface TsFactoryOptions {
includeTsNodes: boolean;
getTypesFromTypeNodes: boolean;
}
export class TsFactory {
private readonly definitionByNode = new KeyValueCache<TsNode, definitions.NodeDefinitions>();
private readonly files = new KeyValueCache<TsSourceFile, definitions.FileDefinition>();
private readonly deferredBindings: { binder: binders.IBaseBinder; definition: definitions.BaseDefinition; }[] = [];
private readonly createdTypesWithDefinition: { type: TsType; definition: definitions.BaseTypeDefinition; }[] = [];
constructor(private readonly mainFactory: MainFactory, private readonly options: TsFactoryOptions) {
}
getShouldIncludeTsNodes() {
return this.options.includeTsNodes;
}
getCallSignatureFromNode(node: TsNode) {
return bindToDefinition(new binders.TsCallSignatureBinderByNode(this, node), new definitions.CallSignatureDefinition());
}
getCallSignatureFromSignature(signature: TsSignature) {
return bindToDefinition(new binders.TsCallSignatureBinderBySignature(this, signature), new definitions.CallSignatureDefinition());
}
getClassConstructor(nodes: TsNode[]) {
return bindToDefinition(new binders.TsClassConstructorBinder(this, nodes), new definitions.ClassConstructorDefinition());
}
getClassMethod(nodes: TsNode[]) {
return bindToDefinition(new binders.TsClassMethodBinder(this, nodes), new definitions.ClassMethodDefinition());
}
getClassStaticMethod(nodes: TsNode[]) {
return bindToDefinition(new binders.TsClassStaticMethodBinder(this, nodes), new definitions.ClassStaticMethodDefinition());
}
getClassProperty(nodes: TsNode[]) {
return bindToDefinition(new binders.TsClassPropertyBinder(this, nodes), new definitions.ClassPropertyDefinition());
}
getClassStaticProperty(node: TsNode) {
return bindToDefinition(new binders.TsClassStaticPropertyBinder(this, node), new definitions.ClassStaticPropertyDefinition());
}
getDecorator(node: TsNode) {
return bindToDefinition(new binders.TsDecoratorBinder(this, node), new definitions.DecoratorDefinition());
}
getEnumMember(node: TsNode) {
return bindToDefinition(new binders.TsEnumMemberBinder(this, node), new definitions.EnumMemberDefinition());
}
getExpression(tsExpression: TsExpression) {
return bindToDefinition(new binders.TsExpressionBinder(tsExpression), new definitions.ExpressionDefinition());
}
getIndexSignatureFromNode(node: TsNode) {
return this.getIndexSignatureFromSignature(node.getSignatureFromThis());
}
getIndexSignatureFromSignature(signature: TsSignature) {
return bindToDefinition(new binders.TsIndexSignatureBinder(this, signature), new definitions.IndexSignatureDefinition());
}
getInterfaceMethod(nodes: TsNode[]) {
return bindToDefinition(new binders.TsInterfaceMethodBinder(this, nodes), new definitions.InterfaceMethodDefinition());
}
getInterfaceProperty(node: TsNode) {
return bindToDefinition(new binders.TsInterfacePropertyBinder(this, node), new definitions.InterfacePropertyDefinition());
}
getObjectProperty(node: TsNode) {
return bindToDefinition(new binders.TsObjectPropertyBinder(this, node), new definitions.ObjectPropertyDefinition());
}
getNamedImportPart(node: TsNode) {
return bindToDefinition(new binders.TsNamedImportPartBinder(this, node), new definitions.NamedImportPartDefinition());
}
getDefaultImportPart(node: TsNode) {
return bindToDefinition(new binders.TsDefaultImportPartBinder(this, node), new definitions.DefaultImportPartDefinition());
}
getStarImportPart(name: string, symbol: TsSymbol) {
return bindToDefinition(new binders.TsStarImportPartBinder(this, name, symbol), new definitions.StarImportPartDefinition());
}
getTypeParameter(node: TsNode) {
return bindToDefinition(new binders.TsTypeParameterBinder(this, node), new definitions.TypeParameterDefinition());
}
getTypePropertyFromSymbol(symbol: TsSymbol) {
const nodes = symbol.getNodes();
if (nodes.length === 1)
return this.getTypePropertyFromNode(nodes[0]);
else
return bindToDefinition(new binders.TsTypePropertyBinderBySymbol(this, symbol), new definitions.TypePropertyDefinition());
}
getTypePropertyFromNode(node: TsNode) {
return bindToDefinition(new binders.TsTypePropertyBinderByNode(this, node), new definitions.TypePropertyDefinition());
}
getTypeNode(node: TsTypeNode) {
const definition = bindToDefinition(new binders.TsTypeNodeBinder(this, node), new definitions.TypeNodeDefinition());
this.createdTypesWithDefinition.push({
type: node.getType(),
definition
});
return definition;
}
getTypeFromTypeNode(node: TsTypeNode) {
return this.getType(node.getType(), node);
}
getType(type: TsType, node: TsTypeNode | null) {
if (this.options.getTypesFromTypeNodes === true && node != null)
return bindToDefinition(new binders.TsTypeBinderByTypeNode(this, node), new definitions.TypeDefinition());
else
return this.getTypeFromType(type, node);
}
private getTypeFromType(type: TsType, node: TsTypeNode | null) {
const definition = bindToDefinition(new binders.TsTypeBinder(this, type, node), new definitions.TypeDefinition());
this.createdTypesWithDefinition.push({
type,
definition
});
return definition;
}
getTypeFromText(text: string | undefined) {
return this.mainFactory.createStructureFactory().getTypeFromText(text);
}
getUserDefinedTypeGuardFromNode(node: TsNode) {
return bindToDefinition(new binders.TsUserDefinedTypeGuardBinderByNode(this, node), new definitions.UserDefinedTypeGuardDefinition());
}
getUserDefinedTypeGuardFromSignature(signature: TsSignature) {
return bindToDefinition(new binders.TsUserDefinedTypeGuardBinderBySignature(this, signature), new definitions.UserDefinedTypeGuardDefinition());
}
getAllExportableDefinitionsBySymbol(symbol: TsSymbol) {
symbol = symbol.isAlias() ? symbol.getAliasSymbol()! : symbol;
const defs = this.getAllDefinitionsBySymbol(symbol);
const exportableDefinitions: definitions.ExportableDefinitions[] = [];
function handleDefinition(definition: (definitions.ExportableDefinitions | definitions.ReExportDefinition)) {
if (definition instanceof definitions.ReExportDefinition)
handleReExport(definition);
else
exportableDefinitions.push(definition);
}
function handleReExport(reExportDefinition: definitions.ReExportDefinition) {
reExportDefinition.getExports().forEach(handleDefinition);
}
defs.forEach(handleDefinition);
return exportableDefinitions;
}
getAllDefinitionsBySymbol(symbol: TsSymbol) {
const definitions: (definitions.NodeDefinitions | null)[] = [];
const functionNodes: TsNode[] = [];
symbol.getNodes().map(node => {
if (node.isTypeLiteral()) {
const parentNode = node.getParent();
if (parentNode != null && parentNode.isTypeAlias())
node = parentNode;
}
if (node.isFunction())
functionNodes.push(node);
else
definitions.push(this.getDefinitionByNode(node));
});
if (functionNodes.length > 0)
definitions.push(this.getFunctionDefinitionByNodes(functionNodes));
return definitions.filter(d => d != null);
}
getDefinitionByNode(node: TsNode) {
return this.definitionByNode.get(node) || this.createDefinition(node);
}
getFunctionDefinitionByNodes(nodes: TsNode[]) {
const def = this.definitionByNode.get(nodes[nodes.length - 1]) as definitions.FunctionDefinition | null;
if (def != null)
return def;
return bindToDefinition(new binders.TsFunctionBinderByNodes(this, nodes), new definitions.FunctionDefinition());
}
getFileDefinition(file: TsSourceFile) {
return this.files.getOrCreate(file, () => {
const def = new definitions.FileDefinition();
const binder = new binders.TsFileBinder(this, file);
binder.bind(def);
return def;
});
}
getDefinitionsOrExpressionFromExportSymbol(symbol: TsSymbol) {
const obj: { definitions: definitions.ExportableDefinitions[]; expression: definitions.ExpressionDefinition | null; } = { definitions: [], expression: null };
if (symbol != null) {
if (symbol.isAlias())
symbol = symbol.getAliasSymbol()!;
const expression = this.getExpressionFromExportSymbol(symbol);
if (expression != null)
obj.expression = expression;
else
obj.definitions.push(...this.getAllDefinitionsBySymbol(symbol) as definitions.ExportableDefinitions[]);
}
return obj;
}
getExpressionFromExportSymbol(symbol: TsSymbol) {
const nodes = symbol.getNodes();
if (nodes.length === 1) {
const tsExpression = nodes[0].getExpression();
if (tsExpression != null)
return this.getExpression(tsExpression);
}
return null;
}
fillAllCachedTypesWithDefinitions() {
this.createdTypesWithDefinition.forEach(typeAndDef => {
const {type, definition} = typeAndDef;
const symbols = type.getSymbols();
symbols.forEach(s => {
const hasChildTypes = definition.unionTypes.length > 0 || definition.intersectionTypes.length > 0 || definition.isArrayType();
if (!hasChildTypes)
definition.definitions.push(...this.getAllDefinitionsBySymbol(s) as definitions.ModuleMemberDefinitions[]);
});
});
}
bindDeferred() {
this.deferredBindings.forEach(obj => {
obj.binder.bind(obj.definition);
});
}
private createDefinition(node: TsNode) {
let definition: definitions.NodeDefinitions | null = null;
// todo: all these if statements are very similar. Need to reduce the redundancy
if (node.isClass())
definition = bindToDefinition(new binders.TsClassBinder(this, node), new definitions.ClassDefinition());
else if (node.isInterface())
definition = bindToDefinition(new binders.TsInterfaceBinder(this, node), new definitions.InterfaceDefinition());
else if (node.isEnum())
definition = bindToDefinition(new binders.TsEnumBinder(this, node), new definitions.EnumDefinition());
else if (node.isVariable())
definition = bindToDefinition(new binders.TsVariableBinder(this, node), new definitions.VariableDefinition());
else if (node.isTypeAlias())
definition = bindToDefinition(new binders.TsTypeAliasBinder(this, node), new definitions.TypeAliasDefinition());
else if (node.isNamespace())
definition = bindToDefinition(new binders.TsNamespaceBinder(this, node), new definitions.NamespaceDefinition());
else if (node.isFunction())
Logger.error(`Don't use ${nameof(TsFactory)}.${nameof<TsFactory>(f => f.createDefinition)} to get a function.`);
else if (node.isExportDeclaration()) {
const binder = new binders.TsReExportBinder(this, node);
definition = new definitions.ReExportDefinition();
this.deferredBindings.push({
binder,
definition
});
}
else if (node.isImport()) {
const binder = new binders.TsImportBinder(this, node);
definition = new definitions.ImportDefinition();
this.deferredBindings.push({
binder,
definition
});
}
else if (node.isExportAssignment()) {
// ignore exports here, handled in ExportableDefinition
}
else if (node.isTypeParameter()) {
// ignore type parameter here, handled in TypedParameterDefinition
}
else if (node.isMethodSignature() || node.isFunctionType()) {
// ignore
}
else {
Logger.warn(`Unknown node kind: ${node.nodeKindToString()}`);
}
if (definition != null)
this.definitionByNode.add(node, definition);
return definition;
}
} | the_stack |
import {
Component,
ElementRef,
Input,
Output,
ChangeDetectionStrategy,
ChangeDetectorRef,
ViewChild,
EventEmitter,
Renderer2,
OnDestroy,
NgZone,
Inject,
OnInit
} from '@angular/core';
import { mergeDeep, LY_COMMON_STYLES, ThemeVariables, lyl, ThemeRef, StyleCollection, LyClasses, StyleTemplate, StyleRenderer } from '@alyle/ui';
import { Subject, Observable } from 'rxjs';
import { take, takeUntil } from 'rxjs/operators';
import { normalizePassiveListenerOptions } from '@angular/cdk/platform';
import { DOCUMENT } from '@angular/common';
import { resizeCanvas } from './resize-canvas';
import { ViewportRuler } from '@angular/cdk/scrolling';
export interface LyImageCropperTheme {
/** Styles for Image Cropper Component */
root?: StyleCollection<((classes: LyClasses<typeof STYLES>) => StyleTemplate)>
| ((classes: LyClasses<typeof STYLES>) => StyleTemplate);
}
export interface LyImageCropperVariables {
cropper?: LyImageCropperTheme;
}
const activeEventOptions = normalizePassiveListenerOptions({passive: false});
const STYLE_PRIORITY = -2;
export const STYLES = (theme: ThemeVariables & LyImageCropperVariables, ref: ThemeRef) => {
const cropper = ref.selectorsOf(STYLES);
const { after } = theme;
return {
$name: LyImageCropper.и,
$priority: STYLE_PRIORITY,
root: ( ) => lyl `{
-webkit-user-select: none
-moz-user-select: none
-ms-user-select: none
user-select: none
display: flex
overflow: hidden
position: relative
justify-content: center
align-items: center
{
...${
(theme.cropper
&& theme.cropper.root
&& (theme.cropper.root instanceof StyleCollection
? theme.cropper.root.setTransformer(fn => fn(cropper))
: theme.cropper.root(cropper))
)
}
}
}`,
imgContainer: lyl `{
cursor: move
position: absolute
top: 0
left: 0
display: flex
touch-action: none
& > canvas {
display: block
}
}`,
overlay: lyl `{
...${LY_COMMON_STYLES.fill}
}`,
area: lyl `{
pointer-events: none
box-shadow: 0 0 0 20000px rgba(0, 0, 0, 0.4)
...${LY_COMMON_STYLES.fill}
margin: auto
&:before, &:after {
...${LY_COMMON_STYLES.fill}
content: ''
}
&:before {
width: 0
height: 0
margin: auto
border-radius: 50%
background: #fff
border: solid 2px rgb(255, 255, 255)
}
&:after {
border: solid 2px rgb(255, 255, 255)
border-radius: inherit
}
}`,
resizer: lyl `{
width: 10px
height: 10px
background: #fff
border-radius: 3px
position: absolute
touch-action: none
bottom: 0
${after}: 0
pointer-events: all
cursor: ${
after === 'right'
? 'nwse-resize'
: 'nesw-resize'
}
&:before {
...${LY_COMMON_STYLES.fill}
content: ''
width: 20px
height: 20px
transform: translate(-25%, -25%)
}
}`,
defaultContent: lyl `{
display: flex
align-items: center
justify-content: center
&, & > input {
...${LY_COMMON_STYLES.fill}
}
& *:not(input) {
pointer-events: none
}
& > input {
background: transparent
opacity: 0
width: 100%
height: 100%
}
}`
};
};
/** Image Cropper Config */
export class ImgCropperConfig {
/** Cropper area width */
width: number = 250;
/** Cropper area height */
height: number = 200;
minWidth?: number = 40;
minHeight?: number = 40;
/** If this is not defined, the new image will be automatically defined. */
type?: string;
/** Background color( default: null), if is null in png is transparent but not in jpg. */
fill?: string | null;
/**
* Set anti-aliased (default: true)
* @deprecated this is not necessary as the cropper will automatically resize the image
* to the best quality
*/
antiAliased?: boolean = true;
autoCrop?: boolean;
output?: ImgOutput | ImgResolution = ImgResolution.Default;
/**
* Zoom out until the entire image fits into the cropping area.
* default: false
*/
extraZoomOut?: boolean;
/**
* Emit event `error` if the file size in bytes for the limit.
* Note: It only works when the image is received from the `<input>` event.
*/
maxFileSize?: number | null;
/**
* Whether the cropper area will be round.
* This implies that the cropper area will maintain its aspect ratio.
* default: false
*/
round?: boolean;
/**
* Whether the cropper area is resizable.
* default: false
*/
resizableArea?: boolean;
/**
* Keep the width and height of the growing area the same according
* to `ImgCropperConfig.width` and `ImgCropperConfig.height`
* default: false
*/
keepAspectRatio?: boolean;
/**
* Whether the cropper area is responsive.
* By default, the width and height of the cropper area is fixed,
* so can use when the cropper area is larger than its container,
* otherwise this will bring problems when cropping.
*/
responsiveArea?: boolean;
}
/**
* The output image
* With this option you can resize the output image.
* If `width` or `height` are 0, this will be set automatically.
* Both cannot be 0.
*/
export interface ImgOutput {
/**
* The cropped image will be resized to this `width`.
*/
width: number;
/**
* Cropped image will be resized to this `height`.
*/
height: number;
}
/** Image output */
export enum ImgResolution {
/**
* The output image will be equal to the initial size of the cropper area.
*/
Default,
/** Just crop the image without resizing */
OriginalImage
}
/** Image output */
export enum ImgCropperError {
/** The loaded image exceeds the size limit set. */
Size,
/** The file loaded is not image. */
Type,
/** When the image has not been loaded. */
Other
}
export interface ImgCropperEvent {
/** Cropped image data URL */
dataURL?: string;
name: string | null;
/** Filetype */
type?: string;
/** Cropped area width */
areaWidth: number;
/** Cropped area height */
areaHeight: number;
/** Cropped image width */
width: number;
/** Cropped image height */
height: number;
/** Original Image data URL */
originalDataURL?: string;
scale: number;
/** Current rotation in degrees */
rotation: number;
/** Size of the image in bytes */
size: number;
/** Scaled offset from the left edge of the image */
left: number;
/** Scaled offset from the top edge of the image */
top: number;
/**
* Scaled offset from the left edge of the image to center of area
* Can be used to set image position
*/
xOrigin: number;
/**
* Scaled offset from the top edge of the image to center of area
* Can be used to set image position
*/
yOrigin: number;
/** @deprecated Use `xOrigin & yOrigin` instead. */
position?: {
x: number
y: number
};
}
export interface ImgCropperErrorEvent {
name?: string;
/** Size of the image in bytes */
size: number;
/** Filetype */
type: string;
/** Type of error */
error: ImgCropperError;
errorMsg?: string;
}
interface ImgRect {
x: number;
y: number;
xc: number;
yc: number;
/** transform with */
wt: number;
ht: number;
}
export interface ImgCropperLoaderConfig {
name?: string | null;
/** Filetype */
type?: string;
/** Cropped area width */
areaWidth?: number;
/** Cropped area height */
areaHeight?: number;
/** Cropped image width */
width?: number;
/** Cropped image height */
height?: number;
/** Original Image data URL */
originalDataURL: string;
scale?: number;
/** Current rotation in degrees */
rotation?: number;
/** Size of the image in bytes */
size?: number;
/** Offset from the left edge of the image to center of area */
xOrigin?: number;
/** Offset from the top edge of the image to center of area */
yOrigin?: number;
}
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
preserveWhitespaces: false,
selector: 'ly-img-cropper, ly-image-cropper',
templateUrl: 'image-cropper.html',
providers: [
StyleRenderer
]
})
export class LyImageCropper implements OnInit, OnDestroy {
static readonly и = 'LyImageCropper';
/**
* styles
* @docs-private
*/
readonly classes = this.sRenderer.renderSheet(STYLES, true);
private _currentLoadConfig?: ImgCropperLoaderConfig;
// _originalImgBase64?: string;
// private _fileName: string | null;
/** Original image */
private _img: HTMLImageElement;
private offset?: {
x: number
y: number
left: number
top: number
};
private _scale?: number;
private _scal3Fix?: number;
private _minScale?: number;
private _maxScale?: number;
/** Initial config */
private _configPrimary: ImgCropperConfig;
private _config: ImgCropperConfig;
private _imgRect: ImgRect = {} as any;
private _rotation: number = 0;
// private _sizeInBytes: number | null;
private _isSliding: boolean;
/** Keeps track of the last pointer event that was captured by the crop area. */
private _lastPointerEvent: MouseEvent | TouchEvent | null;
private _startPointerEvent: {
x: number
y: number
} | null;
_primaryAreaWidth: number;
_primaryAreaHeight: number;
_absoluteScale: number;
/**
* When is loaded image
* @internal
*/
_isLoadedImg: boolean;
/** When is loaded image & ready for crop */
isLoaded: boolean;
/** When the cropper is ready to be interacted */
isReady: boolean;
isCropped: boolean;
@ViewChild('_imgContainer', { static: true }) _imgContainer: ElementRef;
@ViewChild('_area', {
read: ElementRef
}) _areaRef: ElementRef;
@ViewChild('_imgCanvas', { static: true }) _imgCanvas: ElementRef<HTMLCanvasElement>;
@Input()
get config(): ImgCropperConfig {
return this._config;
}
set config(val: ImgCropperConfig) {
this._config = mergeDeep({}, new ImgCropperConfig(), val);
this._configPrimary = mergeDeep({}, this._config);
this._primaryAreaWidth = this.config.width;
this._primaryAreaHeight = this.config.height;
if (
this._config.round
&& this.config.width !== this.config.height
) {
throw new Error(`${LyImageCropper.и}: Both width and height must be equal when using \`ImgCropperConfig.round = true\``);
}
const maxFileSize = this._config.maxFileSize;
if (maxFileSize) {
this.maxFileSize = maxFileSize;
}
}
/** Set scale */
@Input()
get scale(): number | undefined {
return this._scale;
}
set scale(val: number | undefined) {
this.setScale(val);
}
/**
* Emit event `error` if the file size for the limit.
* Note: It only works when the image is received from the `<input>` event.
*/
@Input() maxFileSize: number;
/** Get min scale */
get minScale(): number | undefined {
return this._minScale;
}
@Output() readonly scaleChange = new EventEmitter<number>();
/** Emits minimum supported image scale */
@Output('minScale') readonly minScaleChange = new EventEmitter<number>();
/** Emits maximum supported image scale */
@Output('maxScale') readonly maxScaleChange = new EventEmitter<number>();
/** @deprecated Emits when the image is loaded, instead use `ready` */
@Output() readonly loaded = new EventEmitter<ImgCropperEvent>();
/** Emits when the image is loaded */
@Output() readonly imageLoaded = new EventEmitter<ImgCropperEvent>();
/** Emits when the cropper is ready to be interacted */
@Output() readonly ready = new EventEmitter<ImgCropperEvent>();
/** On crop new image */
@Output() readonly cropped = new EventEmitter<ImgCropperEvent>();
/** Emits when the cropper is cleaned */
@Output() readonly cleaned = new EventEmitter<void>();
/** Emit an error when the loaded image is not valid */
// tslint:disable-next-line: no-output-native
@Output() readonly error = new EventEmitter<ImgCropperErrorEvent>();
private _currentInputElement?: HTMLInputElement;
/** Emits whenever the component is destroyed. */
private readonly _destroy = new Subject<void>();
/** Used to subscribe to global move and end events */
protected _document: Document;
constructor(
readonly sRenderer: StyleRenderer,
private _renderer: Renderer2,
readonly _elementRef: ElementRef<HTMLElement>,
private cd: ChangeDetectorRef,
private _ngZone: NgZone,
@Inject(DOCUMENT) _document: any,
viewPortRuler: ViewportRuler
) {
this._document = _document;
viewPortRuler.change()
.pipe(takeUntil(this._destroy))
.subscribe(() =>
this._ngZone.run(() => this.updateCropperPosition())
);
}
ngOnInit() {
this._ngZone.runOutsideAngular(() => {
const element = this._imgContainer.nativeElement;
element.addEventListener('mousedown', this._pointerDown, activeEventOptions);
element.addEventListener('touchstart', this._pointerDown, activeEventOptions);
});
}
ngOnDestroy() {
this._destroy.next();
this._destroy.complete();
const element = this._imgContainer.nativeElement;
this._lastPointerEvent = null;
this._removeGlobalEvents();
element.removeEventListener('mousedown', this._pointerDown, activeEventOptions);
element.removeEventListener('touchstart', this._pointerDown, activeEventOptions);
}
/** Load image with canvas */
private _imgLoaded(imgElement: HTMLImageElement) {
if (imgElement) {
this._img = imgElement;
const canvas = this._imgCanvas.nativeElement;
canvas.width = imgElement.width;
canvas.height = imgElement.height;
const ctx = canvas.getContext('2d')!;
ctx.clearRect(0, 0, imgElement.width, imgElement.height);
ctx.drawImage(imgElement, 0, 0);
/** set min scale */
this._updateMinScale(canvas);
this._updateMaxScale();
}
}
private _setStylesForContImg(values: {
x?: number
y?: number
}) {
const newStyles = { } as any;
if (values.x != null && values.y != null) {
const rootRect = this._rootRect();
const x = rootRect.width / 2 - (values.x);
const y = rootRect.height / 2 - (values.y);
this._imgRect.x = (values.x);
this._imgRect.y = (values.y);
this._imgRect.xc = (x);
this._imgRect.yc = (y);
}
newStyles.transform = `translate3d(${(this._imgRect.x)}px,${(this._imgRect.y)}px, 0)`;
newStyles.transform += `scale(${this._scal3Fix})`;
newStyles.transformOrigin = `${this._imgRect.xc}px ${this._imgRect.yc}px 0`;
newStyles['-webkit-transform'] = newStyles.transform;
newStyles['-webkit-transform-origin'] = newStyles.transformOrigin;
for (const key in newStyles) {
if (newStyles.hasOwnProperty(key)) {
this._renderer.setStyle(this._imgContainer.nativeElement, key, newStyles[key]);
}
}
}
/**
* Update area and image position only if needed,
* this is used when window resize
*/
updateCropperPosition() {
if (this.isLoaded) {
this.updatePosition();
this._updateAreaIfNeeded();
}
}
/** Load Image from input event */
selectInputEvent(img: Event) {
this._currentInputElement = img.target as HTMLInputElement;
const _img = img.target as HTMLInputElement;
if (_img.files && _img.files.length !== 1) {
return;
}
const fileSize = _img.files![0].size;
const fileName = _img.value.replace(/.*(\/|\\)/, '');
if (this.maxFileSize && fileSize > this.maxFileSize) {
const cropEvent: ImgCropperErrorEvent = {
name: fileName,
type: _img.files![0].type,
size: fileSize,
error: ImgCropperError.Size
};
this.clean();
this.error.emit(cropEvent as ImgCropperErrorEvent);
return;
}
new Observable<ProgressEvent>(observer => {
const reader = new FileReader();
reader.onerror = err => observer.error(err);
reader.onabort = err => observer.error(err);
reader.onload = (ev) => setTimeout(() => {
observer.next(ev);
observer.complete();
});
reader.readAsDataURL(_img.files![0]);
})
.pipe(take(1), takeUntil(this._destroy))
.subscribe(
(loadEvent) => {
const originalDataURL = (loadEvent.target as FileReader).result as string;
this.loadImage({
name: fileName,
size: _img.files![0].size, // size in bytes
type: this.config.type || _img.files![0].type,
originalDataURL
});
this.cd.markForCheck();
},
() => {
const cropEvent: ImgCropperErrorEvent = {
name: fileName,
size: fileSize,
error: ImgCropperError.Other,
errorMsg: 'The File could not be loaded.',
type: _img.files![0].type
};
this.clean();
this.error.emit(cropEvent as ImgCropperErrorEvent);
}
);
}
/** Set the size of the image, the values can be 0 between 1, where 1 is the original size */
setScale(size?: number, noAutoCrop?: boolean) {
// fix min scale
const newSize = size! >= this.minScale! && size! <= 1 ? size : this.minScale;
// check
const changed = size != null && size !== this.scale && newSize !== this.scale;
this._scale = size;
if (!changed) {
return;
}
this._scal3Fix = newSize;
this._updateAbsoluteScale();
if (this.isLoaded) {
if (changed) {
const originPosition = {...this._imgRect};
this.offset = {
x: originPosition.x,
y: originPosition.y,
left: originPosition.xc,
top: originPosition.yc
};
this._setStylesForContImg({});
this._simulatePointerMove();
} else {
return;
}
} else if (this.minScale) {
this._setStylesForContImg({
...this._getCenterPoints()
});
} else {
return;
}
this.scaleChange.emit(size);
if (!noAutoCrop) {
this._cropIfAutoCrop();
}
}
private _getCenterPoints() {
const root = this._elementRef.nativeElement as HTMLElement;
const img = this._imgCanvas.nativeElement;
const x = (root.offsetWidth - (img.width)) / 2;
const y = (root.offsetHeight - (img.height)) / 2;
return {
x,
y
};
}
/**
* Fit to screen
*/
fitToScreen() {
const container = this._elementRef.nativeElement as HTMLElement;
const min = {
width: container.offsetWidth,
height: container.offsetHeight
};
const { width, height } = this._img;
const minScale = {
width: min.width / width,
height: min.height / height
};
const result = Math.max(minScale.width, minScale.height);
this.setScale(result);
}
fit() {
this.setScale(this.minScale);
}
private _pointerDown = (event: TouchEvent | MouseEvent) => {
// Don't do anything if the
// user is using anything other than the main mouse button.
if (this._isSliding || (!isTouchEvent(event) && event.button !== 0)) {
return;
}
this._ngZone.run(() => {
this._isSliding = true;
this.offset = {
x: this._imgRect.x,
y: this._imgRect.y,
left: this._imgRect.xc,
top: this._imgRect.yc
};
this._lastPointerEvent = event;
this._startPointerEvent = getGesturePointFromEvent(event);
event.preventDefault();
this._bindGlobalEvents(event);
});
}
/**
* Simulate pointerMove with clientX = 0 and clientY = 0,
* this is used by `setScale` and `rotate`
*/
private _simulatePointerMove() {
this._isSliding = true;
this._startPointerEvent = {
x: 0,
y: 0
};
this._pointerMove({
clientX: 0,
clientY: 0,
type: 'n',
preventDefault: () => {}
} as MouseEvent);
this._isSliding = false;
this._startPointerEvent = null;
}
_markForCheck() {
this.cd.markForCheck();
}
/**
* Called when the user has moved their pointer after
* starting to drag.
*/
private _pointerMove = (event: TouchEvent | MouseEvent) => {
if (this._isSliding) {
event.preventDefault();
this._lastPointerEvent = event;
let x: number | undefined, y: number | undefined;
const canvas = this._imgCanvas.nativeElement;
const scaleFix = this._scal3Fix;
const config = this.config;
const startP = this.offset;
const point = getGesturePointFromEvent(event);
const deltaX = point.x - this._startPointerEvent!.x;
const deltaY = point.y - this._startPointerEvent!.y;
if (!scaleFix || !startP) {
return;
}
const isMinScaleY = canvas.height * scaleFix < config.height && config.extraZoomOut;
const isMinScaleX = canvas.width * scaleFix < config.width && config.extraZoomOut;
const limitLeft = (config.width / 2 / scaleFix) >= startP.left - (deltaX / scaleFix);
const limitRight = (config.width / 2 / scaleFix) + (canvas.width) - (startP.left - (deltaX / scaleFix)) <= config.width / scaleFix;
const limitTop = ((config.height / 2 / scaleFix) >= (startP.top - (deltaY / scaleFix)));
const limitBottom = (
((config.height / 2 / scaleFix) + (canvas.height) - (startP.top - (deltaY / scaleFix))) <= (config.height / scaleFix)
);
// Limit for left
if ((limitLeft && !isMinScaleX) || (!limitLeft && isMinScaleX)) {
x = startP.x + (startP.left) - (config.width / 2 / scaleFix);
}
// Limit for right
if ((limitRight && !isMinScaleX) || (!limitRight && isMinScaleX)) {
x = startP.x + (startP.left) + (config.width / 2 / scaleFix) - canvas.width;
}
// Limit for top
if ((limitTop && !isMinScaleY) || (!limitTop && isMinScaleY)) {
y = startP.y + (startP.top) - (config.height / 2 / scaleFix);
}
// Limit for bottom
if ((limitBottom && !isMinScaleY) || (!limitBottom && isMinScaleY)) {
y = startP.y + (startP.top) + (config.height / 2 / scaleFix) - canvas.height;
}
// When press shiftKey, deprecated
// if (event.srcEvent && event.srcEvent.shiftKey) {
// if (Math.abs(event.deltaX) === Math.max(Math.abs(event.deltaX), Math.abs(event.deltaY))) {
// y = this.offset.top;
// } else {
// x = this.offset.left;
// }
// }
if (x === void 0) { x = (deltaX / scaleFix) + (startP.x); }
if (y === void 0) { y = (deltaY / scaleFix) + (startP.y); }
this._setStylesForContImg({
x, y
});
}
}
updatePosition(): void;
updatePosition(xOrigin: number, yOrigin: number): void;
updatePosition(xOrigin?: number, yOrigin?: number) {
const hostRect = this._rootRect();
const areaRect = this._areaCropperRect();
const areaWidth = areaRect.width > hostRect.width
? hostRect.width
: areaRect.width;
const areaHeight = areaRect.height > hostRect.height
? hostRect.height
: areaRect.height;
let x: number, y: number;
if (xOrigin == null && yOrigin == null) {
xOrigin = this._imgRect.xc;
yOrigin = this._imgRect.yc;
}
x = (areaRect.left - hostRect.left);
y = (areaRect.top - hostRect.top);
x -= (xOrigin! - (areaWidth / 2));
y -= (yOrigin! - (areaHeight / 2));
this._setStylesForContImg({
x, y
});
}
_slideEnd() {
this._cropIfAutoCrop();
}
private _cropIfAutoCrop() {
if (this.config.autoCrop) {
this.crop();
}
}
/** + */
zoomIn() {
const scale = this._scal3Fix! + .05;
if (scale > this.minScale! && scale <= this._maxScale!) {
this.setScale(scale);
} else {
this.setScale(this._maxScale!);
}
}
/** Clean the img cropper */
clean() {
// fix choosing the same image does not load
if (this._currentInputElement) {
this._currentInputElement.value = '';
this._currentInputElement = null!;
}
if (this.isLoaded) {
this._imgRect = { } as any;
this.offset = undefined;
this.scale = undefined as any;
this._scal3Fix = undefined;
this._rotation = 0;
this._minScale = undefined;
this._isLoadedImg = false;
this.isLoaded = false;
this.isCropped = false;
this._currentLoadConfig = undefined;
this.config = this._configPrimary;
const canvas = this._imgCanvas.nativeElement;
canvas.width = 0;
canvas.height = 0;
this.cleaned.emit(null!);
this.cd.markForCheck();
}
}
/** - */
zoomOut() {
const scale = this._scal3Fix! - .05;
if (scale > this.minScale! && scale <= this._maxScale!) {
this.setScale(scale);
} else {
this.fit();
}
}
center() {
const newStyles = {
...this._getCenterPoints()
};
this._setStylesForContImg(newStyles);
this._cropIfAutoCrop();
}
/**
* load an image from a given configuration,
* or from the result of a cropped image
*/
loadImage(config: ImgCropperLoaderConfig | string, fn?: () => void) {
this.clean();
const _config = this._currentLoadConfig = typeof config === 'string'
? { originalDataURL: config }
: { ...config };
let src = _config.originalDataURL;
this._primaryAreaWidth = this._configPrimary.width;
this._primaryAreaHeight = this._configPrimary.height;
if (_config.areaWidth && _config.areaHeight) {
this.config.width = _config.areaWidth;
this.config.height = _config.areaHeight;
}
src = normalizeSVG(src);
const img = createHtmlImg(src);
const cropEvent = { ..._config } as ImgCropperEvent;
new Observable<void>(observer => {
img.onerror = err => observer.error(err);
img.onabort = err => observer.error(err);
img.onload = () => observer.next(null!);
})
.pipe(take(1), takeUntil(this._destroy))
.subscribe(
() => {
this._imgLoaded(img);
this._isLoadedImg = true;
this.imageLoaded.emit(cropEvent);
this.cd.markForCheck();
this._ngZone.runOutsideAngular(() => {
this._ngZone
.onStable
.asObservable()
.pipe(take(1), takeUntil(this._destroy))
.subscribe(
() => setTimeout(() => this._ngZone.run(() => this._positionImg(cropEvent, fn)))
);
});
},
() => {
const error: ImgCropperErrorEvent = {
name: _config.name!,
error: ImgCropperError.Type,
type: _config.type!,
size: _config.size!
};
this.error.emit(error);
}
);
}
private _updateAreaIfNeeded() {
if (!this._config.responsiveArea) {
return;
}
const rootRect = this._rootRect();
const areaRect = this._areaCropperRect();
const minWidth = this.config.minWidth || 1;
const minHeight = this.config.minHeight || 1;
if (!(
areaRect.width > rootRect.width
|| areaRect.height > rootRect.height
|| areaRect.width < this._primaryAreaWidth
|| areaRect.height < this._primaryAreaHeight
)) {
return;
}
const areaWidthConf = Math.max(this.config.width, minWidth);
const areaWidthMax = Math.max(rootRect.width, minWidth);
const minHost = Math.min(
Math.max(rootRect.width, minWidth), Math.max(rootRect.height, minHeight)
);
const currentScale = this._scal3Fix!;
let newScale = 0;
const roundConf = this.config.round;
if (roundConf) {
this.config.width = this.config.height = minHost;
} else {
if (areaWidthConf === areaRect.width) {
if (areaWidthMax > this._primaryAreaWidth) {
this.config.width = this._primaryAreaWidth;
this.config.height = (this._primaryAreaWidth * areaRect.height) / areaRect.width;
newScale = (currentScale * this._primaryAreaWidth) / areaRect.width;
} else {
this.config.width = areaWidthMax;
this.config.height = (areaWidthMax * areaRect.height) / areaRect.width;
newScale = (currentScale * areaWidthMax) / areaRect.width;
}
this._updateMinScale();
this._updateMaxScale();
this.setScale(newScale, true);
this._markForCheck();
}
}
}
private _updateAbsoluteScale() {
const scale = this._scal3Fix! / (this.config.width / this._primaryAreaWidth);
this._absoluteScale = scale;
}
/**
* Load Image from URL
* @deprecated Use `loadImage` instead of `setImageUrl`
* @param src URL
* @param fn function that will be called before emit the event loaded
*/
setImageUrl(src: string, fn?: () => void) {
this.loadImage(src, fn);
}
private _positionImg(cropEvent: ImgCropperEvent, fn?: () => void) {
const loadConfig = this._currentLoadConfig!;
this._updateMinScale(this._imgCanvas.nativeElement);
this._updateMaxScale();
this.isLoaded = false;
if (fn) {
fn();
} else {
if (loadConfig.scale) {
this.setScale(loadConfig.scale, true);
} else {
this.setScale(this.minScale, true);
}
this.rotate(loadConfig.rotation || 0);
this._updateAreaIfNeeded();
this._markForCheck();
this._ngZone.runOutsideAngular(() => {
this._ngZone
.onStable
.asObservable()
.pipe(take(1), takeUntil(this._destroy))
.subscribe(() => {
if (loadConfig.xOrigin != null && loadConfig.yOrigin != null) {
this.updatePosition(loadConfig.xOrigin, loadConfig.yOrigin);
}
this._updateAreaIfNeeded();
this.isLoaded = true;
this._cropIfAutoCrop();
this._ngZone.run(() => {
this._markForCheck();
this.ready.emit(cropEvent);
// tslint:disable-next-line: deprecation
this.loaded.emit(cropEvent);
});
});
});
}
}
rotate(degrees: number) {
let validDegrees = _normalizeDegrees(degrees);
// If negative convert to positive
if (validDegrees < 0) {
validDegrees += 360;
}
const newRotation = _normalizeDegrees((this._rotation || 0) + validDegrees);
if (newRotation === this._rotation) {
return;
}
const degreesRad = validDegrees * Math.PI / 180;
const canvas = this._imgCanvas.nativeElement;
const canvasClon = createCanvasImg(canvas);
const ctx = canvas.getContext('2d')!;
this._rotation = newRotation;
// clear
ctx.clearRect(0, 0, canvasClon.width, canvasClon.height);
// rotate canvas image
const transform = `rotate(${validDegrees}deg) scale(${1 / this._scal3Fix!})`;
const transformOrigin = `${this._imgRect.xc}px ${this._imgRect.yc}px 0`;
canvas.style.transform = transform;
// tslint:disable-next-line: deprecation
canvas.style.webkitTransform = transform;
canvas.style.transformOrigin = transformOrigin;
// tslint:disable-next-line: deprecation
canvas.style.webkitTransformOrigin = transformOrigin;
const { left, top } = canvas.getBoundingClientRect() as DOMRect;
// save rect
const canvasRect = canvas.getBoundingClientRect();
// remove rotate styles
canvas.removeAttribute('style');
// set w & h
const w = canvasRect.width;
const h = canvasRect.height;
ctx.canvas.width = w;
ctx.canvas.height = h;
// clear
ctx.clearRect(0, 0, w, h);
// translate and rotate
ctx.translate(w / 2, h / 2);
ctx.rotate(degreesRad);
ctx.drawImage(canvasClon, -canvasClon.width / 2, -canvasClon.height / 2);
// Update min scale
this._updateMinScale(canvas);
this._updateMaxScale();
// set the minimum scale, only if necessary
if (this.scale! < this.minScale!) {
this.setScale(0, true);
} // ↑ no AutoCrop
const rootRect = this._rootRect();
this._setStylesForContImg({
x: (left - rootRect.left),
y: (top - rootRect.top)
});
// keep image inside the frame
const originPosition = {...this._imgRect};
this.offset = {
x: originPosition.x,
y: originPosition.y,
left: originPosition.xc,
top: originPosition.yc
};
this._setStylesForContImg({});
this._simulatePointerMove();
this._cropIfAutoCrop();
}
_updateMinScale(canvas?: HTMLCanvasElement) {
if (!canvas) {
canvas = this._imgCanvas.nativeElement;
}
const config = this.config;
const minScale = (config.extraZoomOut ? Math.min : Math.max)(
config.width / canvas.width,
config.height / canvas.height);
this._minScale = minScale;
this.minScaleChange.emit(minScale!);
}
private _updateMaxScale() {
const maxScale = (this.config.width / this._primaryAreaWidth);
this._maxScale = maxScale;
this.maxScaleChange.emit(maxScale);
}
/**
* Resize & crop image
*/
crop(config?: ImgCropperConfig): ImgCropperEvent {
const newConfig = config
? mergeDeep({ }, this.config || new ImgCropperConfig(), config) : this.config;
const cropEvent = this._imgCrop(newConfig);
this.cd.markForCheck();
return cropEvent;
}
/**
* @docs-private
*/
private _imgCrop(myConfig: ImgCropperConfig) {
const canvasElement: HTMLCanvasElement = document.createElement('canvas');
const areaRect = this._areaCropperRect();
const canvasRect = this._canvasRect();
const scaleFix = this._scal3Fix!;
const left = (areaRect.left - canvasRect.left) / scaleFix;
const top = (areaRect.top - canvasRect.top) / scaleFix;
const { output } = myConfig;
const currentImageLoadConfig = this._currentLoadConfig!;
const area = {
width: myConfig.width,
height: myConfig.height
};
canvasElement.width = area.width / scaleFix;
canvasElement.height = area.height / scaleFix;
const ctx = canvasElement.getContext('2d')!;
if (myConfig.fill) {
ctx.fillStyle = myConfig.fill;
ctx.fillRect(0, 0, canvasElement.width, canvasElement.height);
}
ctx.drawImage(this._imgCanvas.nativeElement,
-(left), -(top),
);
const result = canvasElement;
if (myConfig.output === ImgResolution.Default) {
resizeCanvas(
result,
this._configPrimary.width,
this._configPrimary.height);
} else if (typeof output === 'object') {
if (output.width && output.height) {
resizeCanvas(result, output.width, output.height);
} else if (output.width) {
const newHeight = area.height * output.width / area.width;
resizeCanvas(result, output.width, newHeight);
} else if (output.height) {
const newWidth = area.width * output.height / area.height;
resizeCanvas(result, newWidth, output.height);
}
}
const type = currentImageLoadConfig.originalDataURL.startsWith('http')
? currentImageLoadConfig.type || myConfig.type
: myConfig.type || currentImageLoadConfig.type!;
const dataURL = result.toDataURL(type);
const cropEvent: ImgCropperEvent = {
dataURL,
type,
name: currentImageLoadConfig.name!,
areaWidth: this._primaryAreaWidth,
areaHeight: this._primaryAreaHeight,
width: result.width,
height: result.height,
originalDataURL: currentImageLoadConfig.originalDataURL,
scale: this._absoluteScale!,
rotation: this._rotation,
left: (areaRect.left - canvasRect.left) / this._scal3Fix!,
top: (areaRect.top - canvasRect.top) / this._scal3Fix!,
size: currentImageLoadConfig.size!,
xOrigin: this._imgRect.xc,
yOrigin: this._imgRect.yc,
position: {
x: this._imgRect.xc,
y: this._imgRect.yc
}
};
this.isCropped = true;
this.cropped.emit(cropEvent);
return cropEvent;
}
_rootRect(): DOMRect {
return this._elementRef.nativeElement.getBoundingClientRect() as DOMRect;
}
_areaCropperRect(): DOMRect {
return this._areaRef.nativeElement.getBoundingClientRect() as DOMRect;
}
_canvasRect(): DOMRect {
return this._imgCanvas.nativeElement.getBoundingClientRect();
}
/** Called when the user has lifted their pointer. */
private _pointerUp = (event: TouchEvent | MouseEvent) => {
if (this._isSliding) {
event.preventDefault();
this._removeGlobalEvents();
this._isSliding = false;
this._startPointerEvent = null;
this._cropIfAutoCrop();
}
}
/** Called when the window has lost focus. */
private _windowBlur = () => {
// If the window is blurred while dragging we need to stop dragging because the
// browser won't dispatch the `mouseup` and `touchend` events anymore.
if (this._lastPointerEvent) {
this._pointerUp(this._lastPointerEvent);
}
}
private _bindGlobalEvents(triggerEvent: TouchEvent | MouseEvent) {
const element = this._document;
const isTouch = isTouchEvent(triggerEvent);
const moveEventName = isTouch ? 'touchmove' : 'mousemove';
const endEventName = isTouch ? 'touchend' : 'mouseup';
element.addEventListener(moveEventName, this._pointerMove, activeEventOptions);
element.addEventListener(endEventName, this._pointerUp, activeEventOptions);
if (isTouch) {
element.addEventListener('touchcancel', this._pointerUp, activeEventOptions);
}
const window = this._getWindow();
if (typeof window !== 'undefined' && window) {
window.addEventListener('blur', this._windowBlur);
}
}
/** Removes any global event listeners that we may have added. */
private _removeGlobalEvents() {
const element = this._document;
element.removeEventListener('mousemove', this._pointerMove, activeEventOptions);
element.removeEventListener('mouseup', this._pointerUp, activeEventOptions);
element.removeEventListener('touchmove', this._pointerMove, activeEventOptions);
element.removeEventListener('touchend', this._pointerUp, activeEventOptions);
element.removeEventListener('touchcancel', this._pointerUp, activeEventOptions);
const window = this._getWindow();
if (typeof window !== 'undefined' && window) {
window.removeEventListener('blur', this._windowBlur);
}
}
/** Use defaultView of injected document if available or fallback to global window reference */
private _getWindow(): Window {
return this._document.defaultView || window;
}
}
/**
* Normalize degrees for cropper rotation
* @docs-private
*/
export function _normalizeDegrees(n: number) {
const de = n % 360;
if (de % 90) {
throw new Error(`LyCropper: Invalid \`${n}\` degree, only accepted values: 0, 90, 180, 270 & 360.`);
}
return de;
}
/**
* @docs-private
*/
function createCanvasImg(img: HTMLCanvasElement | HTMLImageElement) {
// create a new canvas
const newCanvas = document.createElement('canvas');
const context = newCanvas.getContext('2d')!;
// set dimensions
newCanvas.width = img.width;
newCanvas.height = img.height;
// apply the old canvas to the new one
context.drawImage(img, 0, 0);
// return the new canvas
return newCanvas;
}
const DATA_IMAGE_SVG_PREFIX = 'data:image/svg+xml;base64,';
function normalizeSVG(dataURL: string) {
if (window.atob && isSvgImage(dataURL)) {
const len = dataURL.length / 5;
const text = window.atob(dataURL.replace(DATA_IMAGE_SVG_PREFIX, ''));
const span = document.createElement('span');
span.innerHTML = text;
const svg = span.querySelector('svg')!;
span.setAttribute('style', 'display:none');
document.body.appendChild(span);
const width = parseFloat(getComputedStyle(svg).width!) || 1;
const height = parseFloat(getComputedStyle(svg).height!) || 1;
const max = Math.max(width, height);
svg.setAttribute('width', `${len / (width / max)}px`);
svg.setAttribute('height', `${len / (height / max)}px`);
const result = DATA_IMAGE_SVG_PREFIX + window.btoa(span.innerHTML);
document.body.removeChild(span);
return result;
}
return dataURL;
}
function isSvgImage(dataUrl: string) {
return dataUrl.startsWith(DATA_IMAGE_SVG_PREFIX);
}
function createHtmlImg(src: string) {
const img = new Image();
img.crossOrigin = 'anonymous';
img.src = src;
return img;
}
function getGesturePointFromEvent(event: TouchEvent | MouseEvent) {
// `touches` will be empty for start/end events so we have to fall back to `changedTouches`.
const point = isTouchEvent(event)
? (event.touches[0] || event.changedTouches[0])
: event;
return {
x: point.clientX,
y: point.clientY
};
}
/** Returns whether an event is a touch event. */
function isTouchEvent(event: MouseEvent | TouchEvent): event is TouchEvent {
return event.type[0] === 't';
}
export function round(n: number) {
return Math.round(n);
} | the_stack |
import { KeySet } from '../ojkeyset';
import { DataProvider } from '../ojdataprovider';
import { dvtBaseComponent, dvtBaseComponentEventMap, dvtBaseComponentSettableProperties } from '../ojdvt-base';
import { JetElement, JetSettableProperties, JetElementCustomEvent, JetSetPropertyType } from '..';
export interface ojLegend<K, D> extends dvtBaseComponent<ojLegendSettableProperties<K, D>> {
as: string;
data: DataProvider<K, D> | null;
drilling: 'on' | 'off';
expanded: KeySet<K> | null;
halign: 'center' | 'end' | 'start';
hiddenCategories: string[];
hideAndShowBehavior: 'on' | 'off';
highlightedCategories: string[];
hoverBehavior: 'dim' | 'none';
hoverBehaviorDelay: number;
orientation: 'horizontal' | 'vertical';
scrolling: 'off' | 'asNeeded';
symbolHeight: number;
symbolWidth: number;
textStyle?: object;
valign: 'middle' | 'bottom' | 'top';
translations: {
componentName?: string;
labelAndValue?: string;
labelClearSelection?: string;
labelCountWithTotal?: string;
labelDataVisualization?: string;
labelInvalidData?: string;
labelNoData?: string;
stateCollapsed?: string;
stateDrillable?: string;
stateExpanded?: string;
stateHidden?: string;
stateIsolated?: string;
stateMaximized?: string;
stateMinimized?: string;
stateSelected?: string;
stateUnselected?: string;
stateVisible?: string;
};
onAsChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["as"]>) => any) | null;
onDataChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["data"]>) => any) | null;
onDrillingChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["drilling"]>) => any) | null;
onExpandedChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["expanded"]>) => any) | null;
onHalignChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["halign"]>) => any) | null;
onHiddenCategoriesChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["hiddenCategories"]>) => any) | null;
onHideAndShowBehaviorChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["hideAndShowBehavior"]>) => any) | null;
onHighlightedCategoriesChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["highlightedCategories"]>) => any) | null;
onHoverBehaviorChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["hoverBehavior"]>) => any) | null;
onHoverBehaviorDelayChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["hoverBehaviorDelay"]>) => any) | null;
onOrientationChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["orientation"]>) => any) | null;
onScrollingChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["scrolling"]>) => any) | null;
onSymbolHeightChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["symbolHeight"]>) => any) | null;
onSymbolWidthChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["symbolWidth"]>) => any) | null;
onTextStyleChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["textStyle"]>) => any) | null;
onValignChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["valign"]>) => any) | null;
onOjDrill: ((event: ojLegend.ojDrill) => any) | null;
addEventListener<T extends keyof ojLegendEventMap<K, D>>(type: T, listener: (this: HTMLElement, ev: ojLegendEventMap<K, D>[T]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
getProperty<T extends keyof ojLegendSettableProperties<K, D>>(property: T): ojLegend<K, D>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojLegendSettableProperties<K, D>>(property: T, value: ojLegendSettableProperties<K, D>[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojLegendSettableProperties<K, D>>): void;
setProperties(properties: ojLegendSettablePropertiesLenient<K, D>): void;
getContextByNode(node: Element): ojLegend.NodeContext | null;
getItem(subIdPath: any[]): ojLegend.ItemContext | null;
getPreferredSize(): ojLegend.PreferredSize | null;
getSection(subIdPath: any[]): ojLegend.SectionContext | null;
}
export namespace ojLegend {
interface ojDrill extends CustomEvent<{
id: any;
[propName: string]: any;
}> {
}
// tslint:disable-next-line interface-over-type-literal
type ItemContext = {
text: string;
};
// tslint:disable-next-line interface-over-type-literal
type NodeContext = {
itemIndex: number;
sectionIndexPath: number[];
subId: string;
};
// tslint:disable-next-line interface-over-type-literal
type PreferredSize = {
width: number;
height: number;
};
// tslint:disable-next-line interface-over-type-literal
type SectionContext = {
title: string;
sections: object[];
items: object[];
getSection: {
title: string;
sections: string;
items: boolean;
};
getItems: {
text: string;
};
};
}
export interface ojLegendEventMap<K, D> extends dvtBaseComponentEventMap<ojLegendSettableProperties<K, D>> {
'ojDrill': ojLegend.ojDrill;
'asChanged': JetElementCustomEvent<ojLegend<K, D>["as"]>;
'dataChanged': JetElementCustomEvent<ojLegend<K, D>["data"]>;
'drillingChanged': JetElementCustomEvent<ojLegend<K, D>["drilling"]>;
'expandedChanged': JetElementCustomEvent<ojLegend<K, D>["expanded"]>;
'halignChanged': JetElementCustomEvent<ojLegend<K, D>["halign"]>;
'hiddenCategoriesChanged': JetElementCustomEvent<ojLegend<K, D>["hiddenCategories"]>;
'hideAndShowBehaviorChanged': JetElementCustomEvent<ojLegend<K, D>["hideAndShowBehavior"]>;
'highlightedCategoriesChanged': JetElementCustomEvent<ojLegend<K, D>["highlightedCategories"]>;
'hoverBehaviorChanged': JetElementCustomEvent<ojLegend<K, D>["hoverBehavior"]>;
'hoverBehaviorDelayChanged': JetElementCustomEvent<ojLegend<K, D>["hoverBehaviorDelay"]>;
'orientationChanged': JetElementCustomEvent<ojLegend<K, D>["orientation"]>;
'scrollingChanged': JetElementCustomEvent<ojLegend<K, D>["scrolling"]>;
'symbolHeightChanged': JetElementCustomEvent<ojLegend<K, D>["symbolHeight"]>;
'symbolWidthChanged': JetElementCustomEvent<ojLegend<K, D>["symbolWidth"]>;
'textStyleChanged': JetElementCustomEvent<ojLegend<K, D>["textStyle"]>;
'valignChanged': JetElementCustomEvent<ojLegend<K, D>["valign"]>;
}
export interface ojLegendSettableProperties<K, D> extends dvtBaseComponentSettableProperties {
as: string;
data: DataProvider<K, D> | null;
drilling: 'on' | 'off';
expanded: KeySet<K> | null;
halign: 'center' | 'end' | 'start';
hiddenCategories: string[];
hideAndShowBehavior: 'on' | 'off';
highlightedCategories: string[];
hoverBehavior: 'dim' | 'none';
hoverBehaviorDelay: number;
orientation: 'horizontal' | 'vertical';
scrolling: 'off' | 'asNeeded';
symbolHeight: number;
symbolWidth: number;
textStyle?: object;
valign: 'middle' | 'bottom' | 'top';
translations: {
componentName?: string;
labelAndValue?: string;
labelClearSelection?: string;
labelCountWithTotal?: string;
labelDataVisualization?: string;
labelInvalidData?: string;
labelNoData?: string;
stateCollapsed?: string;
stateDrillable?: string;
stateExpanded?: string;
stateHidden?: string;
stateIsolated?: string;
stateMaximized?: string;
stateMinimized?: string;
stateSelected?: string;
stateUnselected?: string;
stateVisible?: string;
};
}
export interface ojLegendSettablePropertiesLenient<K, D> extends Partial<ojLegendSettableProperties<K, D>> {
[key: string]: any;
}
export interface ojLegendItem extends JetElement<ojLegendItemSettableProperties> {
borderColor?: string;
categories?: string[];
categoryVisibility?: 'hidden' | 'visible';
color?: string;
drilling?: 'on' | 'off' | 'inherit';
lineStyle?: 'dotted' | 'dashed' | 'solid';
lineWidth?: number;
markerColor?: string;
markerShape: 'circle' | 'diamond' | 'ellipse' | 'human' | 'plus' | 'rectangle' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | string;
markerSvgClassName?: string;
markerSvgStyle?: object;
pattern?: 'smallChecker' | 'smallCrosshatch' | 'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle' | 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' |
'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none';
shortDesc?: string;
source?: string;
svgClassName?: string;
svgStyle?: object;
symbolType?: 'line' | 'lineWithMarker' | 'image' | 'marker';
text: string;
onBorderColorChanged: ((event: JetElementCustomEvent<ojLegendItem["borderColor"]>) => any) | null;
onCategoriesChanged: ((event: JetElementCustomEvent<ojLegendItem["categories"]>) => any) | null;
onCategoryVisibilityChanged: ((event: JetElementCustomEvent<ojLegendItem["categoryVisibility"]>) => any) | null;
onColorChanged: ((event: JetElementCustomEvent<ojLegendItem["color"]>) => any) | null;
onDrillingChanged: ((event: JetElementCustomEvent<ojLegendItem["drilling"]>) => any) | null;
onLineStyleChanged: ((event: JetElementCustomEvent<ojLegendItem["lineStyle"]>) => any) | null;
onLineWidthChanged: ((event: JetElementCustomEvent<ojLegendItem["lineWidth"]>) => any) | null;
onMarkerColorChanged: ((event: JetElementCustomEvent<ojLegendItem["markerColor"]>) => any) | null;
onMarkerShapeChanged: ((event: JetElementCustomEvent<ojLegendItem["markerShape"]>) => any) | null;
onMarkerSvgClassNameChanged: ((event: JetElementCustomEvent<ojLegendItem["markerSvgClassName"]>) => any) | null;
onMarkerSvgStyleChanged: ((event: JetElementCustomEvent<ojLegendItem["markerSvgStyle"]>) => any) | null;
onPatternChanged: ((event: JetElementCustomEvent<ojLegendItem["pattern"]>) => any) | null;
onShortDescChanged: ((event: JetElementCustomEvent<ojLegendItem["shortDesc"]>) => any) | null;
onSourceChanged: ((event: JetElementCustomEvent<ojLegendItem["source"]>) => any) | null;
onSvgClassNameChanged: ((event: JetElementCustomEvent<ojLegendItem["svgClassName"]>) => any) | null;
onSvgStyleChanged: ((event: JetElementCustomEvent<ojLegendItem["svgStyle"]>) => any) | null;
onSymbolTypeChanged: ((event: JetElementCustomEvent<ojLegendItem["symbolType"]>) => any) | null;
onTextChanged: ((event: JetElementCustomEvent<ojLegendItem["text"]>) => any) | null;
addEventListener<T extends keyof ojLegendItemEventMap>(type: T, listener: (this: HTMLElement, ev: ojLegendItemEventMap[T]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
getProperty<T extends keyof ojLegendItemSettableProperties>(property: T): ojLegendItem[T];
getProperty(property: string): any;
setProperty<T extends keyof ojLegendItemSettableProperties>(property: T, value: ojLegendItemSettableProperties[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojLegendItemSettableProperties>): void;
setProperties(properties: ojLegendItemSettablePropertiesLenient): void;
}
export interface ojLegendItemEventMap extends HTMLElementEventMap {
'borderColorChanged': JetElementCustomEvent<ojLegendItem["borderColor"]>;
'categoriesChanged': JetElementCustomEvent<ojLegendItem["categories"]>;
'categoryVisibilityChanged': JetElementCustomEvent<ojLegendItem["categoryVisibility"]>;
'colorChanged': JetElementCustomEvent<ojLegendItem["color"]>;
'drillingChanged': JetElementCustomEvent<ojLegendItem["drilling"]>;
'lineStyleChanged': JetElementCustomEvent<ojLegendItem["lineStyle"]>;
'lineWidthChanged': JetElementCustomEvent<ojLegendItem["lineWidth"]>;
'markerColorChanged': JetElementCustomEvent<ojLegendItem["markerColor"]>;
'markerShapeChanged': JetElementCustomEvent<ojLegendItem["markerShape"]>;
'markerSvgClassNameChanged': JetElementCustomEvent<ojLegendItem["markerSvgClassName"]>;
'markerSvgStyleChanged': JetElementCustomEvent<ojLegendItem["markerSvgStyle"]>;
'patternChanged': JetElementCustomEvent<ojLegendItem["pattern"]>;
'shortDescChanged': JetElementCustomEvent<ojLegendItem["shortDesc"]>;
'sourceChanged': JetElementCustomEvent<ojLegendItem["source"]>;
'svgClassNameChanged': JetElementCustomEvent<ojLegendItem["svgClassName"]>;
'svgStyleChanged': JetElementCustomEvent<ojLegendItem["svgStyle"]>;
'symbolTypeChanged': JetElementCustomEvent<ojLegendItem["symbolType"]>;
'textChanged': JetElementCustomEvent<ojLegendItem["text"]>;
}
export interface ojLegendItemSettableProperties extends JetSettableProperties {
borderColor?: string;
categories?: string[];
categoryVisibility?: 'hidden' | 'visible';
color?: string;
drilling?: 'on' | 'off' | 'inherit';
lineStyle?: 'dotted' | 'dashed' | 'solid';
lineWidth?: number;
markerColor?: string;
markerShape: 'circle' | 'diamond' | 'ellipse' | 'human' | 'plus' | 'rectangle' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | string;
markerSvgClassName?: string;
markerSvgStyle?: object;
pattern?: 'smallChecker' | 'smallCrosshatch' | 'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle' | 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' |
'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none';
shortDesc?: string;
source?: string;
svgClassName?: string;
svgStyle?: object;
symbolType?: 'line' | 'lineWithMarker' | 'image' | 'marker';
text: string;
}
export interface ojLegendItemSettablePropertiesLenient extends Partial<ojLegendItemSettableProperties> {
[key: string]: any;
}
export interface ojLegendSection extends JetElement<ojLegendSectionSettableProperties> {
collapsible?: 'on' | 'off';
text?: string;
textHalign?: 'center' | 'end' | 'start';
textStyle?: object;
onCollapsibleChanged: ((event: JetElementCustomEvent<ojLegendSection["collapsible"]>) => any) | null;
onTextChanged: ((event: JetElementCustomEvent<ojLegendSection["text"]>) => any) | null;
onTextHalignChanged: ((event: JetElementCustomEvent<ojLegendSection["textHalign"]>) => any) | null;
onTextStyleChanged: ((event: JetElementCustomEvent<ojLegendSection["textStyle"]>) => any) | null;
addEventListener<T extends keyof ojLegendSectionEventMap>(type: T, listener: (this: HTMLElement, ev: ojLegendSectionEventMap[T]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
getProperty<T extends keyof ojLegendSectionSettableProperties>(property: T): ojLegendSection[T];
getProperty(property: string): any;
setProperty<T extends keyof ojLegendSectionSettableProperties>(property: T, value: ojLegendSectionSettableProperties[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojLegendSectionSettableProperties>): void;
setProperties(properties: ojLegendSectionSettablePropertiesLenient): void;
}
export interface ojLegendSectionEventMap extends HTMLElementEventMap {
'collapsibleChanged': JetElementCustomEvent<ojLegendSection["collapsible"]>;
'textChanged': JetElementCustomEvent<ojLegendSection["text"]>;
'textHalignChanged': JetElementCustomEvent<ojLegendSection["textHalign"]>;
'textStyleChanged': JetElementCustomEvent<ojLegendSection["textStyle"]>;
}
export interface ojLegendSectionSettableProperties extends JetSettableProperties {
collapsible?: 'on' | 'off';
text?: string;
textHalign?: 'center' | 'end' | 'start';
textStyle?: object;
}
export interface ojLegendSectionSettablePropertiesLenient extends Partial<ojLegendSectionSettableProperties> {
[key: string]: any;
} | the_stack |
import { remove, set } from "mobx"
import {
detach,
findChildren,
findParent,
findParentPath,
fromSnapshot,
getChildrenObjects,
getParentPath,
getParentToChildPath,
getRootPath,
isChildOfParent,
isParentOfChild,
model,
Model,
modelSnapshotInWithMetadata,
prop,
runUnprotected,
} from "../../src"
import "../commonSetup"
const $errorMessage = "must be the model object instance instead of the '$' sub-object"
@model("P2")
export class P2 extends Model({
y: prop(() => 10),
}) {}
@model("P")
export class P extends Model({
x: prop(() => 5),
arr: prop<P2[]>(() => []),
p2: prop<P2 | undefined>(),
}) {}
test("parent", () => {
const p = fromSnapshot<P>(
modelSnapshotInWithMetadata(P, {
arr: [
modelSnapshotInWithMetadata(P2, { y: 1 }),
modelSnapshotInWithMetadata(P2, { y: 2 }),
modelSnapshotInWithMetadata(P2, { y: 3 }),
],
p2: modelSnapshotInWithMetadata(P2, { y: 12 }),
})
)
expect(p instanceof P).toBeTruthy()
expect(isChildOfParent(p, p)).toBeFalsy()
expect(isParentOfChild(p, p)).toBeFalsy()
expect(() => isChildOfParent(p.$, p)).toThrow($errorMessage)
expect(() => isParentOfChild(p, p.$)).toThrow($errorMessage)
expect(() => isChildOfParent(p, p.$)).toThrow($errorMessage)
expect(() => isParentOfChild(p.$, p)).toThrow($errorMessage)
expect(isChildOfParent(p.p2!, p)).toBeTruthy()
expect(isParentOfChild(p, p.p2!)).toBeTruthy()
expect(isChildOfParent(p, p.p2!)).toBeFalsy()
expect(isParentOfChild(p.p2!, p)).toBeFalsy()
expect(findParent(p.p2!, (parent) => parent instanceof P)).toBe(p)
expect(findParent(p.p2!, (parent) => parent instanceof P, 0)).toBe(p)
expect(findParent(p.p2!, (parent) => parent instanceof P, 1)).toBe(p)
expect(findParent(p.p2!, (parent) => parent instanceof P, 2)).toBe(p)
expect(findParent(p.p2!, (parent) => parent instanceof P, 3)).toBe(p)
expect(findParent(p.p2!, (parent) => parent instanceof P2)).toBe(undefined)
expect(findParentPath(p.p2!, (parent) => parent instanceof P)).toEqual({
parent: p,
path: ["p2"],
})
expect(findParentPath(p.p2!, (parent) => parent instanceof P, 0)).toEqual({
parent: p,
path: ["p2"],
})
expect(findParentPath(p.p2!, (parent) => parent instanceof P, 1)).toEqual({
parent: p,
path: ["p2"],
})
expect(findParentPath(p.p2!, (parent) => parent instanceof P, 2)).toEqual({
parent: p,
path: ["p2"],
})
expect(findParentPath(p.p2!, (parent) => parent instanceof P, 3)).toEqual({
parent: p,
path: ["p2"],
})
expect(findParentPath(p.p2!, (parent) => parent instanceof P2)).toBe(undefined)
expect(getParentPath(p)).toBeUndefined()
expect(() => getParentPath(p.$)).toThrow($errorMessage)
expect(() => getParentPath(p.x as any)).toThrow("must be a tree node") // not an object
expect(getParentPath(p.arr)).toEqual({ parent: p, path: "arr" })
expect(getParentPath(p.p2!)).toEqual({ parent: p, path: "p2" })
expect(() => getParentPath(p.p2!.$)).toThrow($errorMessage)
p.arr.forEach((p2, i) => {
expect(getParentPath(p2)).toStrictEqual({ parent: p.arr, path: i })
})
expect(getRootPath(p.arr[0])).toEqual({
root: p,
path: ["arr", 0],
pathObjects: [p, p.arr, p.arr[0]],
})
expect(Array.from(getChildrenObjects(p).values())).toEqual([p.arr, p.p2])
expect(() => Array.from(getChildrenObjects(p.$).values())).toThrow($errorMessage)
expect(Array.from(getChildrenObjects(p.arr).values())).toEqual(p.arr)
expect(Array.from(getChildrenObjects(p.p2!).values())).toEqual([])
expect(Array.from(findChildren(p, () => true).values())).toEqual([p.arr, p.p2])
expect(Array.from(findChildren(p, () => true, { deep: true }).values())).toEqual([
p.arr,
p.arr[0],
p.arr[1],
p.arr[2],
p.p2,
])
expect(Array.from(findChildren(p, (node) => node instanceof P2).values())).toEqual([p.p2])
expect(
Array.from(findChildren(p, (node) => node instanceof P2, { deep: true }).values())
).toEqual([p.arr[0], p.arr[1], p.arr[2], p.p2])
expect(getParentToChildPath(p, p)).toEqual([])
expect(getParentToChildPath(p, p.p2!)).toEqual(["p2"])
expect(getParentToChildPath(p.p2!, p)).toEqual(undefined) // p is not a child of p.p2
const p2 = p.p2!
// delete prop (unsupported for this.x but supported for this.$ since they require proxies and would be slower)
runUnprotected(() => {
// this is valid in mobx5 but not mobx4
// delete p.$.p2
remove(p.$, "p2")
})
expect(p.p2).toBeUndefined()
expect("p2" in p.$).toBeFalsy()
expect(getParentPath(p2)).toBeUndefined()
expect(Array.from(getChildrenObjects(p).values())).toEqual([p.arr])
expect(Array.from(findChildren(p, (node) => node instanceof P2).values())).toEqual([])
expect(
Array.from(findChildren(p, (node) => node instanceof P2, { deep: true }).values())
).toEqual([p.arr[0], p.arr[1], p.arr[2]])
// readd prop
runUnprotected(() => {
// this is valid in mobx5 but not mobx4
// p.p2 = p2
set(p.$, "p2", p2)
})
expect(getParentPath(p2)).toEqual({ parent: p, path: "p2" })
expect(Array.from(getChildrenObjects(p).values())).toEqual([p.arr, p.p2])
expect(Array.from(findChildren(p, (node) => node instanceof P2).values())).toEqual([p.p2])
expect(
Array.from(findChildren(p, (node) => node instanceof P2, { deep: true }).values())
).toEqual([p.arr[0], p.arr[1], p.arr[2], p.p2])
// reassign prop
runUnprotected(() => {
p.p2 = undefined
})
expect(getParentPath(p2)).toBeUndefined()
expect(Array.from(getChildrenObjects(p).values())).toEqual([p.arr])
expect(Array.from(findChildren(p, (node) => node instanceof P2).values())).toEqual([])
expect(
Array.from(findChildren(p, (node) => node instanceof P2, { deep: true }).values())
).toEqual([p.arr[0], p.arr[1], p.arr[2]])
// readd prop
runUnprotected(() => {
p.p2 = p2
})
expect(getParentPath(p2)).toEqual({ parent: p, path: "p2" })
expect(Array.from(getChildrenObjects(p).values())).toEqual([p.arr, p.p2])
expect(Array.from(findChildren(p, (node) => node instanceof P2).values())).toEqual([p.p2])
expect(
Array.from(findChildren(p, (node) => node instanceof P2, { deep: true }).values())
).toEqual([p.arr[0], p.arr[1], p.arr[2], p.p2])
// detach
runUnprotected(() => {
detach(p2)
})
expect(getParentPath(p2)).toBeUndefined()
expect(p.p2).toBeUndefined()
expect(Array.from(getChildrenObjects(p).values())).toEqual([p.arr])
expect(Array.from(findChildren(p, (node) => node instanceof P2).values())).toEqual([])
expect(
Array.from(findChildren(p, (node) => node instanceof P2, { deep: true }).values())
).toEqual([p.arr[0], p.arr[1], p.arr[2]])
// readd prop
runUnprotected(() => {
// this is valid in mobx5 but not in mobx4
// p.p2 = p2
set(p.$, "p2", p2)
})
expect(getParentPath(p2)).toEqual({ parent: p, path: "p2" })
expect(Array.from(getChildrenObjects(p).values())).toEqual([p.arr, p.p2])
expect(Array.from(findChildren(p, (node) => node instanceof P2).values())).toEqual([p.p2])
expect(
Array.from(findChildren(p, (node) => node instanceof P2, { deep: true }).values())
).toEqual([p.arr[0], p.arr[1], p.arr[2], p.p2])
// detach once more
runUnprotected(() => {
detach(p2)
})
const p2arr = [p.arr[0], p.arr[1], p.arr[2]]
// pop
const popped = runUnprotected(() => {
return p.arr.pop()!
})
expect(p.arr.length).toBe(2)
expect(popped).toBe(p2arr[2])
expect(getParentPath(popped)).toBeUndefined()
for (let i = 0; i < p.arr.length; i++) {
expect(getParentPath(p.arr[i])!.path).toBe(i)
}
// push back
runUnprotected(() => {
p.arr.push(popped)
})
expect(p.arr.length).toBe(3)
expect(getParentPath(popped)).toBeDefined()
expect(Array.from(getChildrenObjects(p).values())).toEqual([p.arr])
expect(Array.from(findChildren(p, (node) => node instanceof P2).values())).toEqual([])
expect(
Array.from(findChildren(p, (node) => node instanceof P2, { deep: true }).values())
).toEqual([p.arr[0], p.arr[1], p.arr[2]])
for (let i = 0; i < p.arr.length; i++) {
expect(getParentPath(p.arr[i])!.path).toBe(i)
}
// splice
const spliced = runUnprotected(() => {
return p.arr.splice(1, 1)
})[0]
expect(p.arr.length).toBe(2)
expect(spliced).toBe(p2arr[1])
expect(getParentPath(spliced)).toBeUndefined()
for (let i = 0; i < p.arr.length; i++) {
expect(getParentPath(p.arr[i])!.path).toBe(i)
}
// splice back
runUnprotected(() => {
return p.arr.splice(1, 0, spliced)
})
expect(p.arr.length).toBe(3)
expect(getParentPath(spliced)).toBeDefined()
for (let i = 0; i < p.arr.length; i++) {
expect(getParentPath(p.arr[i])!.path).toBe(i)
}
// delete array prop
// TODO: support this? mobx array interceptor/update is not emitted
/*
runUnprotected(() => {
delete p.data.arr[2]
})
expect(getParentPath(p2arr[0])).toBeDefined()
expect(getParentPath(p2arr[1])).toBeDefined()
expect(getParentPath(p2arr[2])).toBeUndefined()
expect(Array.from(getChildrenObjects(p.data).values())).toEqual([p.data.arr])
*/
// assign index
runUnprotected(() => {
p.arr[2] = null as any
})
expect(getParentPath(p2arr[0])).toBeDefined()
expect(getParentPath(p2arr[1])).toBeDefined()
expect(getParentPath(p2arr[2])).toBeUndefined()
expect(Array.from(getChildrenObjects(p).values())).toEqual([p.arr])
expect(Array.from(findChildren(p, (node) => node instanceof P2).values())).toEqual([])
expect(
Array.from(findChildren(p, (node) => node instanceof P2, { deep: true }).values())
).toEqual([p.arr[0], p.arr[1]])
runUnprotected(() => {
p.arr[2] = p2arr[2]
})
expect(getParentPath(p2arr[0])).toBeDefined()
expect(getParentPath(p2arr[1])).toBeDefined()
expect(getParentPath(p2arr[2])).toBeDefined()
expect(Array.from(getChildrenObjects(p).values())).toEqual([p.arr])
expect(Array.from(findChildren(p, (node) => node instanceof P2).values())).toEqual([])
expect(
Array.from(findChildren(p, (node) => node instanceof P2, { deep: true }).values())
).toEqual([p.arr[0], p.arr[1], p.arr[2]])
// detach
runUnprotected(() => {
detach(p2arr[1])
})
expect(p.arr).toEqual([p2arr[0], p2arr[2]])
expect(getParentPath(p2arr[0])).toBeDefined()
expect(getParentPath(p2arr[1])).toBeUndefined()
expect(getParentPath(p2arr[2])).toBeDefined()
expect(Array.from(getChildrenObjects(p).values())).toEqual([p.arr])
expect(Array.from(findChildren(p, (node) => node instanceof P2).values())).toEqual([])
expect(
Array.from(findChildren(p, (node) => node instanceof P2, { deep: true }).values())
).toEqual([p.arr[0], p.arr[1]])
// set length
runUnprotected(() => {
p.arr.length = 1
})
expect(getParentPath(p2arr[0])).toBeDefined()
expect(getParentPath(p2arr[1])).toBeUndefined()
expect(getParentPath(p2arr[2])).toBeUndefined()
expect(Array.from(getChildrenObjects(p).values())).toEqual([p.arr])
expect(Array.from(findChildren(p, (node) => node instanceof P2).values())).toEqual([])
expect(
Array.from(findChildren(p, (node) => node instanceof P2, { deep: true }).values())
).toEqual([p.arr[0]])
// adding to the array something that is already attached should fail
const oldArrayLength = p.arr.length
expect(() => {
runUnprotected(() => {
p.arr.push(p.arr[0])
})
}).toThrow("an object cannot be assigned a new parent when it already has one")
expect(p.arr.length).toBe(oldArrayLength)
expect(() => {
runUnprotected(() => {
// this is valid in mobx5 but not in mobx4
// ;(p.$ as any).z = p.arr[0]
set(p.$, "z", p.arr[0])
})
}).toThrow("an object cannot be assigned a new parent when it already has one")
expect((p.$ as any).z).toBe(undefined)
expect("z" in p.$).toBeFalsy()
}) | the_stack |
import { isNotNull } from '@vuedx/shared'
import type { SourceLocation } from '@vuedx/template-ast-types'
import type {
TextDocument,
TransformerError,
} from '@vuedx/vue-virtual-textdocument'
import { inject, injectable } from 'inversify'
import type Typescript from 'typescript/lib/tsserverlibrary'
import type {
Diagnostic,
DiagnosticRelatedInformation,
DiagnosticSeverity,
DiagnosticTag,
Range,
} from 'vscode-languageserver-types'
import { INJECTABLE_TS_SERVICE } from '../constants'
import type { TSLanguageService } from '../contracts/Typescript'
import { CacheService } from '../services/CacheService'
import { FilesystemService } from '../services/FilesystemService'
import { LanguageServiceProvider } from '../services/LanguageServiceProvider'
import { LoggerService } from '../services/LoggerService'
import { TypescriptService } from '../services/TypescriptService'
import { ScriptSetupDiagnosticsProvider } from './diagnostics/ScriptSetupDiagnosticsProvider'
import { TemplateGlobals } from './helpers'
@injectable()
export class DiagnosticsService {
private readonly logger = LoggerService.getLogger('Diagnostics')
private readonly caches = {
semantic: new CacheService<Typescript.Diagnostic[]>((fileName) =>
this.getVersion(fileName),
),
syntax: new CacheService<Typescript.DiagnosticWithLocation[]>((fileName) =>
this.getVersion(fileName),
),
suggestion: new CacheService<Typescript.DiagnosticWithLocation[]>(
(fileName) => this.getVersion(fileName),
),
extra: new CacheService<Typescript.Diagnostic[]>((fileName) =>
this.getVersion(fileName),
),
all: new CacheService<Diagnostic[]>((fileName) =>
this.getVersion(fileName),
),
}
constructor(
@inject(TypescriptService)
private readonly ts: TypescriptService,
@inject(FilesystemService)
private readonly fs: FilesystemService,
@inject(LanguageServiceProvider)
private readonly lang: LanguageServiceProvider,
@inject(INJECTABLE_TS_SERVICE)
private readonly service: TSLanguageService,
@inject(ScriptSetupDiagnosticsProvider)
private readonly scriptSetup: ScriptSetupDiagnosticsProvider,
) {}
private readonly TS_CATEGORY_TO_SEVERITY: Record<
Typescript.DiagnosticCategory,
DiagnosticSeverity
> = {
0: 2,
1: 1,
2: 4,
3: 3,
}
private readonly SEVERITY_TO_TS_CATEGORY: Record<
DiagnosticSeverity,
Typescript.DiagnosticCategory
> = {
1: 1,
2: 0,
3: 3,
4: 2,
}
private readonly NAMED_SEVERITY_TO_SEVERITY: Record<
TransformerError['severity'],
DiagnosticSeverity
> = {
error: 1,
warning: 2,
info: 3,
hint: 4,
unused: 4,
deprecated: 4,
}
private readonly getVersion = (fileName: string): string => {
return (
this.ts
.getProjectFor(fileName)
?.getScriptInfo(fileName)
?.getLatestVersion() ?? '0'
)
}
public getDiagnostics(fileName: string): Diagnostic[] {
return this.caches.all.withCache(fileName, (prevResult) => {
if (prevResult != null) return prevResult
return [
this.getSemanticDiagnostics(fileName).map((diagnostic) =>
this.toDiagnostic(diagnostic),
),
this.getSyntacticDiagnostics(fileName).map((diagnostic) =>
this.toDiagnostic(diagnostic),
),
this.getSuggestionDiagnostics(fileName).map((diagnostic) =>
this.toDiagnostic(diagnostic),
),
this.getDiagnosticsFromEmbeddedLanguageServices(fileName),
]
.flat()
.filter(isNotNull)
})
}
public getExtraDiagnostics(fileName: string): Typescript.Diagnostic[] {
return this.caches.extra.withCache(fileName, (result) => {
if (result != null) return result
this.logger.debug(`ExtraDiagnonstics in ${fileName}`)
const diagnostics: Typescript.Diagnostic[] = []
const vueFile = this.fs.getVueFile(fileName)
if (vueFile?.descriptor.scriptSetup != null) {
const virtualFileName = vueFile.getBlockId(
vueFile.descriptor.scriptSetup,
)
diagnostics.push(
...this.normalizeVirtualFileDiagnostics(
virtualFileName,
this.scriptSetup
.getDiagnostics(virtualFileName)
.map((diagnostic) =>
this.toTSDiagnostic(virtualFileName, diagnostic),
),
),
)
}
diagnostics.push(
...this.getDiagnosticsFromEmbeddedLanguageServices(
fileName,
).map((diagnostic) => this.toTSDiagnostic(fileName, diagnostic)),
)
return diagnostics
})
}
public getSemanticDiagnostics(fileName: string): Typescript.Diagnostic[] {
return this.caches.semantic.withCache(fileName, (result) => {
if (result != null) return result
this.logger.debug(`SemanticDiagnonstics in ${fileName}`)
return this.getDiagnosticsFromTS(fileName, (fileName) => {
this.logger.debug(`SemanticDiagnonstics in ${fileName}`)
return this.service.getSemanticDiagnostics(fileName)
})
})
}
public getSyntacticDiagnostics(
fileName: string,
): Typescript.DiagnosticWithLocation[] {
return this.caches.syntax.withCache(fileName, (result) => {
if (result != null) return result
this.logger.debug(`SyntacticcDiagnonstics in ${fileName}`)
return this.getDiagnosticsFromTS(fileName, (fileName) => {
this.logger.debug(`SyntacticcDiagnonstics in ${fileName}`)
return this.service.getSyntacticDiagnostics(fileName)
}) as Typescript.DiagnosticWithLocation[]
})
}
public getSuggestionDiagnostics(
fileName: string,
): Typescript.DiagnosticWithLocation[] {
return this.caches.suggestion.withCache(fileName, (result) => {
if (result != null) return result
this.logger.debug(`SuggestionDiagnonstics in ${fileName}`)
return this.getDiagnosticsFromTS(fileName, (fileName) => {
this.logger.debug(`SuggestionDiagnonstics in ${fileName}`)
return this.service.getSuggestionDiagnostics(fileName)
}) as Typescript.DiagnosticWithLocation[]
})
}
private getDiagnosticsFromEmbeddedLanguageServices(
fileName: string,
): Diagnostic[] {
const file = this.fs.getVueFile(fileName)
if (file == null) return []
const diagnostics: Diagnostic[] = []
// Collect SFC parse errors
file.errors.forEach((error) => {
if (error.message === '') return
diagnostics.push({
message: error.message,
range: this.getRangeFromLoc(file, error),
code: 'code' in error ? error.code : undefined,
severity: this.NAMED_SEVERITY_TO_SEVERITY['error'],
source: 'VueDX/SFC parser',
})
})
// Collect errors from transformed TS virtual files
file.getActiveTSDocIDs().forEach((id) => {
const doc = file.getDocById(id)
if (doc == null) return
doc.errors.forEach((error) => {
if (error.message === '') return
diagnostics.push({
message: error.message,
range: this.fs.getAbsoluteRange(
file,
doc,
this.fs.toRange(doc.source, error),
),
code: error.code,
codeDescription: error.codeDescription,
source: this.getSourceName(
error.source ?? doc.block.type + ' parser',
),
severity: this.NAMED_SEVERITY_TO_SEVERITY[error.severity],
tags: [
error.severity === 'unused' ? (1 as DiagnosticTag) : null,
error.severity === 'deprecated' ? (2 as DiagnosticTag) : null,
].filter(isNotNull),
})
})
})
// Collect diagnostics from embedded language services
file.blocks.forEach((block) => {
const fileName = file.getBlockId(block)
const doc = file.getDoc(block)
if (doc == null) return
this.lang
.getLanguageService(fileName)
?.getDiagnositcs(fileName)
.forEach((diagnostic) => {
diagnostic.range = this.fs.getAbsoluteRange(
file,
doc,
diagnostic.range,
)
diagnostic.relatedInformation = diagnostic.relatedInformation?.map(
(relatedInfo) => {
// Only virtual files from current .vue file should be supported.
if (this.fs.isVueVirtualFile(relatedInfo.location.uri)) {
relatedInfo.location.range = this.fs.getAbsoluteRange(
file,
doc,
relatedInfo.location.range,
)
}
return relatedInfo
},
)
diagnostics.push(diagnostic)
})
})
return diagnostics
}
/**
* Collect diagnostics from internal virtual files.
* @param fileName entry filename
* @param getter diagnostics getter funciton
* @returns combined diagnostics for Vue virtual files
*/
private getDiagnosticsFromTS(
fileName: string,
getter: (fileName: string) => Typescript.Diagnostic[],
): Typescript.Diagnostic[] {
if (this.fs.isVueFile(fileName)) {
const vueFile = this.fs.getVueFile(fileName)
if (vueFile == null) {
this.logger.debug(`File not found: ${fileName}`)
return []
}
const diagnostics: Typescript.Diagnostic[] = []
this.logger.debug(
`${vueFile.version} = ${vueFile.fileName}`,
vueFile.getActiveTSDocIDs(),
)
vueFile.getActiveTSDocIDs().forEach((id) => {
try {
diagnostics.push(
...this.normalizeVirtualFileDiagnostics(id, getter(id)),
)
} catch (error) {
// Ignore for now.
this.logger.error(error)
}
})
return diagnostics
} else if (this.fs.isVueVirtualSchemeFile(fileName)) {
const filePath = this.fs.removeVirtualFileScheme(fileName)
return getter(filePath).map((diagnostic) =>
this.normalizeTSDiagnostic(diagnostic),
)
} else {
return getter(fileName).map((diagnostic) =>
this.normalizeTSDiagnostic(diagnostic, fileName),
)
}
}
private normalizeVirtualFileDiagnostics(
fileName: string,
diagnostics: Typescript.Diagnostic[],
): Typescript.Diagnostic[] {
const vueFile = this.fs.getVueFile(fileName)
if (vueFile == null) return []
const blockFile = vueFile.getDocById(fileName)
if (blockFile == null) return []
const tsFile = blockFile.generated
if (tsFile == null) return []
const isScriptSetup =
blockFile.block.type === 'script' &&
blockFile.block.attrs['setup'] != null
return diagnostics
.flatMap((diagnostic) => {
if (isScriptSetup && diagnostic.code === 2528) {
this.logger.debug(
`Ignoring ${diagnostic.code} because export default in script setup is handled.`,
)
return null
}
if (diagnostic.start == null) {
this.logger.debug(`Ignoring ${diagnostic.code} without location`)
return null
}
this.logger.debug(
`${diagnostic.code} at ${diagnostic.start}: ${this.toDisplayMessage(
diagnostic.messageText,
)}`,
)
if (blockFile.isOffsetInTemplateGlobals(diagnostic.start)) {
const range = TemplateGlobals.findLHS(blockFile, diagnostic.start)
if (range == null) return null
const references = this.service.getReferencesAtPosition(
fileName,
range.start,
)
return references?.map((reference) => {
if (
reference.fileName === fileName &&
!blockFile.isOffsetInIgonredZone(reference.textSpan.start)
) {
return this.normalizeTSDiagnostic({
...diagnostic,
...reference.textSpan,
})
}
return null
})
}
if (blockFile.isOffsetInIgonredZone(diagnostic.start)) {
this.logger.debug(
`Ignoring ${diagnostic.code} at ${diagnostic.start}`,
)
return null
}
return this.normalizeTSDiagnostic(diagnostic)
})
.filter(isNotNull)
}
private toDiagnostic(diagnostic: Typescript.Diagnostic): Diagnostic | null {
if (diagnostic.file == null) return null
const file = this.fs.getFile(diagnostic.file.fileName)
if (file == null) return null
const transformed: Diagnostic = {
message: this.toDisplayMessage(diagnostic.messageText),
range: this.fs.toRange(file, diagnostic),
code: diagnostic.code,
severity: this.TS_CATEGORY_TO_SEVERITY[diagnostic.category],
source: this.getSourceName(diagnostic.source),
tags: [
diagnostic.reportsUnnecessary != null ? (1 as DiagnosticTag) : null,
diagnostic.reportsDeprecated != null ? (2 as DiagnosticTag) : null,
].filter(isNotNull),
}
transformed.relatedInformation = diagnostic.relatedInformation
?.map((diagnostic) => this.toDiagnosticRelatedInformation(diagnostic))
.filter(isNotNull)
return transformed
}
private toTSDiagnostic(
fileName: string,
diagnostic: Diagnostic,
): Typescript.Diagnostic {
const file = this.fs.getFile(fileName)
const range =
file != null
? this.fs.toOffsets(file, diagnostic.range)
: { start: undefined, length: undefined }
const sourceFile = this.ts.getSourceFile(fileName) ?? undefined
return {
source: this.getSourceName(diagnostic.source),
messageText: diagnostic.message,
category: this.SEVERITY_TO_TS_CATEGORY[diagnostic.severity ?? 1],
code: diagnostic.code != null ? Number(diagnostic.code) : 0,
reportsUnnecessary: diagnostic.tags?.includes(1 as DiagnosticTag),
reportsDeprecated: diagnostic.tags?.includes(2 as DiagnosticTag),
file: sourceFile,
start: range.start,
length: range.length,
relatedInformation: diagnostic.relatedInformation?.map((diagnostic) =>
this.toTSDiagnosticRelatedInformation(diagnostic),
),
}
}
private toDiagnosticRelatedInformation(
diagnostic: Typescript.DiagnosticRelatedInformation,
): DiagnosticRelatedInformation | null {
if (diagnostic.file == null) return null
const file = this.fs.getFile(diagnostic.file.fileName)
if (file == null) return null
return {
message: this.toDisplayMessage(diagnostic.messageText),
location: {
range: this.fs.toRange(file, diagnostic),
uri: file.uri,
},
}
}
private toTSDiagnosticRelatedInformation(
diagnostic: DiagnosticRelatedInformation,
): Typescript.DiagnosticRelatedInformation {
const file = this.fs.getFile(this.fs.toFileName(diagnostic.location.uri))
const range =
file != null
? this.fs.toOffsets(file, diagnostic.location.range)
: { start: undefined, length: undefined }
return {
messageText: diagnostic.message,
category: 1 as Typescript.DiagnosticCategory,
file: this.ts.getSourceFile(diagnostic.location.uri) ?? undefined,
code: 0,
start: range.start,
length: range.length,
}
}
private getRangeFromLoc<T extends {} | { loc?: SourceLocation }>(
file: TextDocument,
node: T,
): Range {
return this.fs.toRange(
file,
'loc' in node && node.loc != null
? {
start: node.loc.start.offset,
length: Math.max(1, node.loc.end.offset - node.loc.start.offset),
}
: { start: undefined, length: undefined },
)
}
public toDisplayMessage(
message: string | Typescript.DiagnosticMessageChain,
): string {
if (typeof message === 'string') return message
return this.ts.lib.flattenDiagnosticMessageText(message, '\n')
}
private lastSourceFile: [string, Typescript.SourceFile] | null = null
private getSourceFile(fileName: string): Typescript.SourceFile {
if (this.lastSourceFile?.[0] === fileName) return this.lastSourceFile[1]
let sourceFile: Typescript.SourceFile | null = null
if (
this.fs.isVueFile(fileName) ||
this.fs.isVueVirtualFile(fileName) ||
this.fs.isVueTsFile(fileName)
) {
sourceFile = this.fs.getVueFile(fileName) as any // VueSFCFile implements minimal required syntax.
} else if (this.fs.isVueVirtualSchemeFile(fileName)) {
const file = this.ts.getSourceFile(
this.fs.removeVirtualFileScheme(fileName),
)
if (file != null) {
sourceFile = {
fileName,
text: file.getFullText(),
} as any
}
}
this.lastSourceFile = [
fileName,
sourceFile ?? ({ fileName, text: '' } as any),
]
return this.lastSourceFile[1]
}
private normalizeTSDiagnostic(
diagnostic: Typescript.Diagnostic,
/**
* Only pass to force file on normalized diagnostics.
*/
expectedFileName?: string,
): Typescript.Diagnostic {
const file = diagnostic.file
diagnostic = { ...diagnostic }
if (diagnostic.relatedInformation != null) {
diagnostic.relatedInformation = diagnostic.relatedInformation.map(
(diagnostic) => {
if (diagnostic.file == null) {
diagnostic.file = file
}
return this.normalizeTSDiagnosticRelatedInformation(diagnostic)
},
)
}
// Serve virtual files.
if (
expectedFileName != null &&
this.fs.isVueVirtualSchemeFile(expectedFileName)
) {
diagnostic.source = this.getSourceName(diagnostic.source ?? 'TS')
diagnostic.file = this.getSourceFile(expectedFileName)
return diagnostic
}
const fileName = diagnostic.file?.fileName
if (expectedFileName != null) {
diagnostic.file = this.getSourceFile(expectedFileName)
}
if (fileName == null) {
return diagnostic
}
if (this.fs.isVueVirtualFile(fileName)) {
const range = this.fs.getAbsoluteOffsets(
this.fs.getVueFile(fileName)?.getDocById(fileName) ?? undefined,
diagnostic,
)
diagnostic.source = this.getSourceName(diagnostic.source ?? 'TS')
diagnostic.file = this.getSourceFile(expectedFileName ?? fileName)
diagnostic.start = range.start
diagnostic.length = range.length
} else if (this.fs.isVueFile(fileName) || this.fs.isVueTsFile(fileName)) {
diagnostic.source = this.getSourceName(diagnostic.source ?? 'TS')
diagnostic.file = this.getSourceFile(expectedFileName ?? fileName)
}
return diagnostic
}
private normalizeTSDiagnosticRelatedInformation(
diagnostic: Typescript.DiagnosticRelatedInformation,
): Typescript.DiagnosticRelatedInformation {
if (diagnostic.file == null) return diagnostic
return this.normalizeTSDiagnostic(diagnostic)
}
private getSourceName(source?: string): string {
if (source == null) return 'VueDX/Unknown'
else if (source.startsWith('VueDX')) return source
else return `VueDX/${source}`
}
} | the_stack |
namespace Linqer {
export interface Enumerable extends Iterable<any> {
/**
* Sorts the elements of a sequence in ascending order.
*
* @param {ISelector} keySelector
* @returns {OrderedEnumerable}
* @memberof Enumerable
*/
orderBy(keySelector: ISelector): OrderedEnumerable;
/**
* Sorts the elements of a sequence in descending order.
*
* @param {ISelector} keySelector
* @returns {OrderedEnumerable}
* @memberof Enumerable
*/
orderByDescending(keySelector: ISelector): OrderedEnumerable;
/**
* use QuickSort for ordering (default). Recommended when take, skip, takeLast, skipLast are used after orderBy
*
* @returns {Enumerable}
* @memberof Enumerable
*/
useQuickSort(): Enumerable;
/**
* use the default browser sort implementation for ordering at all times
*
* @returns {Enumerable}
* @memberof Enumerable
*/
useBrowserSort(): Enumerable;
}
/// Sorts the elements of a sequence in ascending order.
Enumerable.prototype.orderBy = function (keySelector: ISelector): OrderedEnumerable {
if (keySelector) {
_ensureFunction(keySelector);
} else {
keySelector = item => item;
}
return new OrderedEnumerable(this, keySelector, true);
};
/// Sorts the elements of a sequence in descending order.
Enumerable.prototype.orderByDescending = function (keySelector: ISelector): OrderedEnumerable {
if (keySelector) {
_ensureFunction(keySelector);
} else {
keySelector = item => item;
}
return new OrderedEnumerable(this, keySelector, false);
};
/// use QuickSort for ordering (default). Recommended when take, skip, takeLast, skipLast are used after orderBy
Enumerable.prototype.useQuickSort = function (): Enumerable {
this._useQuickSort = true;
return this;
};
/// use the default browser sort implementation for ordering at all times
Enumerable.prototype.useBrowserSort = function (): Enumerable {
this._useQuickSort = false;
return this;
};
//static sort: (arr: any[], comparer?: IComparer) => void;
Enumerable.sort = function (arr: any[], comparer: IComparer = _defaultComparer): any[] {
_quickSort(arr, 0, arr.length - 1, comparer, 0, Number.MAX_SAFE_INTEGER);
return arr;
}
enum RestrictionType {
skip,
skipLast,
take,
takeLast
}
/**
* An Enumerable yielding ordered items
*
* @export
* @class OrderedEnumerable
* @extends {Enumerable}
*/
export class OrderedEnumerable extends Enumerable {
_keySelectors: { keySelector: ISelector, ascending: boolean }[];
_restrictions: { type: RestrictionType, nr: number }[];
/**
*Creates an instance of OrderedEnumerable.
* @param {IterableType} src
* @param {ISelector} [keySelector]
* @param {boolean} [ascending=true]
* @memberof OrderedEnumerable
*/
constructor(src: IterableType,
keySelector?: ISelector,
ascending: boolean = true) {
super(src);
this._keySelectors = [];
this._restrictions = [];
if (keySelector) {
this._keySelectors.push({ keySelector: keySelector, ascending: ascending });
}
const self: OrderedEnumerable = this;
// generator gets an array of the original,
// sorted inside the interval determined by functions such as skip, take, skipLast, takeLast
this._generator = function* () {
let { startIndex, endIndex, arr } = this.getSortedArray();
if (arr) {
for (let index = startIndex; index < endIndex; index++) {
yield arr[index];
}
}
};
// the count is the difference between the end and start indexes
// if no skip/take functions were used, this will be the original count
this._count = () => {
const totalCount = Enumerable.from(self._src).count();
const { startIndex, endIndex } = this.getStartAndEndIndexes(self._restrictions, totalCount);
return endIndex - startIndex;
};
// an ordered enumerable cannot seek
this._canSeek=false;
this._tryGetAt = ()=>{ throw new Error('Ordered enumerables cannot seek'); };
}
private getSortedArray() {
const self = this;
let startIndex: number;
let endIndex: number;
let arr: any[] | null = null;
const innerEnumerable = self._src as Enumerable;
_ensureInternalTryGetAt(innerEnumerable);
// try to avoid enumerating the entire original into an array
if (innerEnumerable._canSeek) {
({ startIndex, endIndex } = self.getStartAndEndIndexes(self._restrictions, innerEnumerable.count()));
} else {
arr = Array.from(self._src);
({ startIndex, endIndex } = self.getStartAndEndIndexes(self._restrictions, arr.length));
}
if (startIndex < endIndex) {
if (!arr) {
arr = Array.from(self._src);
}
// only quicksort supports partial ordering inside an interval
const sort: (item1: any, item2: any) => void = self._useQuickSort
? (a, c) => _quickSort(a, 0, a.length - 1, c, startIndex, endIndex)
: (a, c) => a.sort(c);
const sortFunc = self.generateSortFunc(self._keySelectors);
sort(arr, sortFunc);
return {
startIndex,
endIndex,
arr
};
} else {
return {
startIndex,
endIndex,
arr: null
};
}
}
private generateSortFunc(selectors: { keySelector: ISelector, ascending: boolean }[]): (i1: any, i2: any) => number {
// simplify the selectors into an array of comparers
const comparers = selectors.map(s => {
const f = s.keySelector;
const comparer = (i1: any, i2: any) => {
const k1 = f(i1);
const k2 = f(i2);
if (k1 > k2) return 1;
if (k1 < k2) return -1;
return 0;
};
return s.ascending
? comparer
: (i1: any, i2: any) => -comparer(i1, i2);
});
// optimize the resulting sort function in the most common case
// (ordered by a single criterion)
return comparers.length == 1
? comparers[0]
: (i1: any, i2: any) => {
for (let i = 0; i < comparers.length; i++) {
const v = comparers[i](i1, i2);
if (v) return v;
}
return 0;
};
}
/// calculate the interval in which an array needs to have ordered items for this ordered enumerable
private getStartAndEndIndexes(restrictions: { type: RestrictionType, nr: number }[], arrLength: number) {
let startIndex = 0;
let endIndex = arrLength;
for (const restriction of restrictions) {
switch (restriction.type) {
case RestrictionType.take:
endIndex = Math.min(endIndex, startIndex + restriction.nr);
break;
case RestrictionType.skip:
startIndex = Math.min(endIndex, startIndex + restriction.nr);
break;
case RestrictionType.takeLast:
startIndex = Math.max(startIndex, endIndex - restriction.nr);
break;
case RestrictionType.skipLast:
endIndex = Math.max(startIndex, endIndex - restriction.nr);
break;
}
}
return { startIndex, endIndex };
}
/**
* Performs a subsequent ordering of the elements in a sequence in ascending order.
*
* @param {ISelector} keySelector
* @returns {OrderedEnumerable}
* @memberof OrderedEnumerable
*/
thenBy(keySelector: ISelector): OrderedEnumerable {
this._keySelectors.push({ keySelector: keySelector, ascending: true });
return this;
}
/**
* Performs a subsequent ordering of the elements in a sequence in descending order.
*
* @param {ISelector} keySelector
* @returns {OrderedEnumerable}
* @memberof OrderedEnumerable
*/
thenByDescending(keySelector: ISelector): OrderedEnumerable {
this._keySelectors.push({ keySelector: keySelector, ascending: false });
return this;
}
/**
* Deferred and optimized implementation of take
*
* @param {number} nr
* @returns {OrderedEnumerable}
* @memberof OrderedEnumerable
*/
take(nr: number): OrderedEnumerable {
this._restrictions.push({ type: RestrictionType.take, nr: nr });
return this;
}
/**
* Deferred and optimized implementation of takeLast
*
* @param {number} nr
* @returns {OrderedEnumerable}
* @memberof OrderedEnumerable
*/
takeLast(nr: number): OrderedEnumerable {
this._restrictions.push({ type: RestrictionType.takeLast, nr: nr });
return this;
}
/**
* Deferred and optimized implementation of skip
*
* @param {number} nr
* @returns {OrderedEnumerable}
* @memberof OrderedEnumerable
*/
skip(nr: number): OrderedEnumerable {
this._restrictions.push({ type: RestrictionType.skip, nr: nr });
return this;
}
/**
* Deferred and optimized implementation of skipLast
*
* @param {number} nr
* @returns {OrderedEnumerable}
* @memberof OrderedEnumerable
*/
skipLast(nr: number): OrderedEnumerable {
this._restrictions.push({ type: RestrictionType.skipLast, nr: nr });
return this;
}
/**
* An optimized implementation of toArray
*
* @returns {any[]}
* @memberof OrderedEnumerable
*/
toArray(): any[] {
const { startIndex, endIndex, arr } = this.getSortedArray();
return arr
? arr.slice(startIndex, endIndex)
: [];
}
/**
* An optimized implementation of toMap
*
* @param {ISelector} keySelector
* @param {ISelector} [valueSelector=x => x]
* @returns {Map<any, any>}
* @memberof OrderedEnumerable
*/
toMap(keySelector: ISelector, valueSelector: ISelector = x => x): Map<any, any> {
_ensureFunction(keySelector);
_ensureFunction(valueSelector);
const result = new Map<any, any>();
const arr = this.toArray();
for (let i = 0; i < arr.length; i++) {
result.set(keySelector(arr[i], i), valueSelector(arr[i], i));
}
return result;
}
/**
* An optimized implementation of toObject
*
* @param {ISelector} keySelector
* @param {ISelector} [valueSelector=x => x]
* @returns {{ [key: string]: any }}
* @memberof OrderedEnumerable
*/
toObject(keySelector: ISelector, valueSelector: ISelector = x => x): { [key: string]: any } {
_ensureFunction(keySelector);
_ensureFunction(valueSelector);
const result: { [key: string]: any } = {};
const arr = this.toArray();
for (let i = 0; i < arr.length; i++) {
result[keySelector(arr[i], i)] = valueSelector(arr[i], i);
}
return result;
}
/**
* An optimized implementation of to Set
*
* @returns {Set<any>}
* @memberof OrderedEnumerable
*/
toSet(): Set<any> {
const result = new Set<any>();
const arr = this.toArray();
for (let i = 0; i < arr.length; i++) {
result.add(arr[i]);
}
return result;
}
}
const _insertionSortThreshold = 64;
/// insertion sort is used for small intervals
function _insertionsort(arr: any[], leftIndex: number, rightIndex: number, comparer: IComparer) {
for (let j = leftIndex; j <= rightIndex; j++) {
const key = arr[j];
let i = j - 1;
while (i >= leftIndex && comparer(arr[i], key) > 0) {
arr[i + 1] = arr[i];
i--;
}
arr[i + 1] = key;
}
}
/// swap two items in an array by index
function _swapArrayItems(array: any[], leftIndex: number, rightIndex: number): void {
const temp = array[leftIndex];
array[leftIndex] = array[rightIndex];
array[rightIndex] = temp;
}
// Quicksort partition by center value coming from both sides
function _partition(items: any[], left: number, right: number, comparer: IComparer) {
const pivot = items[(right + left) >> 1];
while (left <= right) {
while (comparer(items[left], pivot) < 0) {
left++;
}
while (comparer(items[right], pivot) > 0) {
right--;
}
if (left < right) {
_swapArrayItems(items, left, right);
left++;
right--;
} else {
if (left === right) return left + 1;
}
}
return left;
}
/// optimized Quicksort algorithm
function _quickSort(items: any[], left: number, right: number, comparer: IComparer = _defaultComparer, minIndex: number = 0, maxIndex: number = Number.MAX_SAFE_INTEGER) {
if (!items.length) return items;
// store partition indexes to be processed in here
const partitions: { left: number, right: number }[] = [];
partitions.push({ left, right });
let size = 1;
// the actual size of the partitions array never decreases
// but we keep score of the number of partitions in 'size'
// and we reuse slots whenever possible
while (size) {
const partition = { left, right } = partitions[size-1];
if (right - left < _insertionSortThreshold) {
_insertionsort(items, left, right, comparer);
size--;
continue;
}
const index = _partition(items, left, right, comparer);
if (left < index - 1 && index - 1 >= minIndex) {
partition.right = index - 1;
if (index < right && index < maxIndex) {
partitions[size]={ left: index, right };
size++;
}
} else {
if (index < right && index < maxIndex) {
partition.left = index;
} else {
size--;
}
}
}
return items;
}
} | the_stack |
import * as BaseUtil from '../common/base_util';
import * as DomUtil from '../common/dom_util';
import SystemExternal from '../common/system_external';
import XpathUtil from '../common/xpath_util';
import {LOCALE} from '../l10n/locale';
import {SpeechRuleStore} from '../rule_engine/speech_rule_store';
import * as Semantic from '../semantic_tree/semantic';
import {SemanticFont, SemanticRole, SemanticType} from '../semantic_tree/semantic_attr';
import {SemanticNode} from '../semantic_tree/semantic_node';
import SemanticProcessor from '../semantic_tree/semantic_processor';
import * as NumbersUtil from './numbers_util';
/**
* Dictionary to store the nesting depth of each node.
*/
let nestingDepth: {[k1: string]: {[k2: string]: number}} = {};
/**
* String function to separate text into single characters by adding
* intermittent spaces.
* @param node The node to be processed.
* @return The spaced out text.
*/
export function spaceoutText(node: Element): string {
return Array.from(node.textContent).join(' ');
}
/**
* Spaces out content of the given node into new elements with single character
* content.
* @param node The node to be processed.
* @param correction A correction function applied
* to the newly created semantic node with single characters.
* @return List of single nodes.
*/
export function spaceoutNodes(
node: Element, correction: (p1: SemanticNode) => any): Element[] {
let content = Array.from(node.textContent);
let result = [];
let processor = SemanticProcessor.getInstance();
let doc = node.ownerDocument;
for (let i = 0, chr; chr = content[i]; i++) {
let leaf =
processor.getNodeFactory().makeLeafNode(chr, SemanticFont.UNKNOWN);
let sn = processor.identifierNode(leaf, SemanticFont.UNKNOWN, '');
correction(sn);
result.push(sn.xml(doc));
}
return result as Element[];
}
/**
* Query function that splits into number nodes and content nodes.
* @param node The node to be processed.
* @return List of single number nodes.
*/
export function spaceoutNumber(node: Element): Element[] {
return spaceoutNodes(node, function(sn) {
if (!sn.textContent.match(/\W/)) {
sn.type = SemanticType.NUMBER;
}
});
}
/**
* Query function that splits into number nodes and content nodes.
* @param node The node to be processed.
* @return List of single identifier nodes.
*/
export function spaceoutIdentifier(node: Element): Element[] {
return spaceoutNodes(node, function(sn) {
sn.font = SemanticFont.UNKNOWN;
sn.type = SemanticType.IDENTIFIER;
});
}
/**
* Tags that serve as a nesting barrier by default.
*/
export const nestingBarriers: SemanticType[] = [
SemanticType.CASES, SemanticType.CELL, SemanticType.INTEGRAL,
SemanticType.LINE, SemanticType.MATRIX, SemanticType.MULTILINE,
SemanticType.OVERSCORE, SemanticType.ROOT, SemanticType.ROW,
SemanticType.SQRT, SemanticType.SUBSCRIPT, SemanticType.SUPERSCRIPT,
SemanticType.TABLE, SemanticType.UNDERSCORE, SemanticType.VECTOR
];
/**
* Resets the nesting depth parameters. Method should be used on every new
* expression.
* @param node The node to translate.
* @return Array containing the original node only.
*/
export function resetNestingDepth(node: Element): Element[] {
nestingDepth = {};
return [node];
}
/**
* Computes the depth of nested descendants of a particular set of tags for a
* node.
* @param type The type of nesting depth.
* @param node The XML node to check.
* @param tags The tags to be considered for the nesting depth.
* @param opt_barrierTags Optional list of tags
* that serve as barrier.
* @param opt_barrierAttrs Attribute value pairs that
* serve as barrier.
* @param opt_func A function that overrides both
* tags and attribute barriers, i.e., if function returns true it will be
* considered as barrier, otherwise tags and attributes will be considered.
* @return The nesting depth.
*/
export function getNestingDepth(
type: string, node: Element, tags: string[],
opt_barrierTags?: Semantic.Attr[],
opt_barrierAttrs?: {[key: string]: string},
opt_func?: (p1: Element) => boolean): number {
opt_barrierTags = opt_barrierTags || nestingBarriers;
opt_barrierAttrs = opt_barrierAttrs || {};
opt_func = opt_func || function(_node) {
return false;
};
let xmlText =
(new SystemExternal.xmldom.XMLSerializer()).serializeToString(node);
if (!nestingDepth[type]) {
nestingDepth[type] = {};
}
if (nestingDepth[type][xmlText]) {
return nestingDepth[type][xmlText];
}
if (opt_func(node) || tags.indexOf(node.tagName) < 0) {
return 0;
}
let depth = computeNestingDepth_(
node, tags, BaseUtil.setdifference(opt_barrierTags, tags),
opt_barrierAttrs, opt_func, 0);
nestingDepth[type][xmlText] = depth;
return depth;
}
/**
* Checks if a node contains given attribute value pairs.
* @param node The XML node to check.
* @param attrs Attribute value pairs.
* @return True if all attributes are contained and have the given
* values.
*/
export function containsAttr(
node: Element, attrs: {[key: string]: string}): boolean {
if (!node.attributes) {
return false;
}
let attributes = DomUtil.toArray(node.attributes);
for (let i = 0, attr; attr = attributes[i]; i++) {
if (attrs[attr.nodeName] === attr.nodeValue) {
return true;
}
}
return false;
}
/**
* Computes the depth of nested descendants of a particular set of tags for a
* node recursively.
* @param node The XML node to process.
* @param tags The tags to be considered for the nesting depth.
* @param barriers List of tags that serve as barrier.
* @param attrs Attribute value pairs that serve as
* barrier.
* @param func A function that overrides both tags
* and attribute barriers, i.e., if function returns true it will be
* considered as barrier, otherwise tags and attributes will be considered.
* @param depth Accumulator for the nesting depth that is computed.
* @return The nesting depth.
*/
export function computeNestingDepth_(
node: Element, tags: string[], barriers: string[],
attrs: {[key: string]: string},
func: (p1: Element) => boolean, depth: number): number {
if (func(node) || barriers.indexOf(node.tagName) > -1 ||
containsAttr(node, attrs)) {
return depth;
}
if (tags.indexOf(node.tagName) > -1) {
depth++;
}
if (!node.childNodes || node.childNodes.length === 0) {
return depth;
}
let children = DomUtil.toArray(node.childNodes);
return Math.max.apply(null, children.map(function(subNode) {
return computeNestingDepth_(subNode, tags, barriers, attrs, func, depth);
}));
}
// TODO (sorge) Refactor the following to functions wrt. style attribute.
/**
* Computes and returns the nesting depth of fraction nodes.
* @param node The fraction node.
* @return The nesting depth. 0 if the node is not a fraction.
*/
export function fractionNestingDepth(node: Element): number {
return getNestingDepth(
'fraction', node, ['fraction'], nestingBarriers, {},
// TODO (TS): Make this a proper type.
LOCALE.FUNCTIONS.fracNestDepth as (n: Element) => boolean);
}
/**
* Computes disambiguations for nested fractions.
* @param node The fraction node.
* @param expr The disambiguating expression.
* @param opt_end Optional end expression.
* @return The disambiguating string.
*/
export function nestedFraction(
node: Element, expr: string, opt_end?: string): string {
let depth = fractionNestingDepth(node);
let annotation = Array.apply(null, Array(depth)).map((_x: string) => expr);
if (opt_end) {
annotation.push(opt_end);
}
return annotation.join(LOCALE.MESSAGES.regexp.JOINER_FRAC);
}
/**
* Opening string for fractions in Mathspeak verbose mode.
* @param node The fraction node.
* @return The opening string.
*/
export function openingFractionVerbose(node: Element): string {
return nestedFraction(
node, LOCALE.MESSAGES.MS.START, LOCALE.MESSAGES.MS.FRAC_V);
}
/**
* Closing string for fractions in Mathspeak verbose mode.
* @param node The fraction node.
* @return The closing string.
*/
export function closingFractionVerbose(node: Element): string {
return nestedFraction(
node, LOCALE.MESSAGES.MS.END, LOCALE.MESSAGES.MS.FRAC_V);
}
/**
* Middle string for fractions in Mathspeak verbose mode.
* @param node The fraction node.
* @return The middle string.
*/
export function overFractionVerbose(node: Element): string {
return nestedFraction(node, LOCALE.MESSAGES.MS.FRAC_OVER);
}
/**
* Opening string for fractions in Mathspeak brief mode.
* @param node The fraction node.
* @return The opening string.
*/
export function openingFractionBrief(node: Element): string {
return nestedFraction(
node, LOCALE.MESSAGES.MS.START, LOCALE.MESSAGES.MS.FRAC_B);
}
/**
* Closing string for fractions in Mathspeak brief mode.
* @param node The fraction node.
* @return The closing string.
*/
export function closingFractionBrief(node: Element): string {
return nestedFraction(
node, LOCALE.MESSAGES.MS.END, LOCALE.MESSAGES.MS.FRAC_B);
}
/**
* Opening string for fractions in Mathspeak superbrief mode.
* @param node The fraction node.
* @return The opening string.
*/
export function openingFractionSbrief(node: Element): string {
let depth = fractionNestingDepth(node);
if (depth === 1) {
return LOCALE.MESSAGES.MS.FRAC_S;
}
return LOCALE.FUNCTIONS.combineNestedFraction(
LOCALE.MESSAGES.MS.NEST_FRAC,
LOCALE.FUNCTIONS.radicalNestDepth(depth - 1),
LOCALE.MESSAGES.MS.FRAC_S);
}
/**
* Closing string for fractions in Mathspeak superbrief mode.
* @param node The fraction node.
* @return The closing string.
*/
export function closingFractionSbrief(node: Element): string {
let depth = fractionNestingDepth(node);
if (depth === 1) {
return LOCALE.MESSAGES.MS.ENDFRAC;
}
return LOCALE.FUNCTIONS.combineNestedFraction(
LOCALE.MESSAGES.MS.NEST_FRAC,
LOCALE.FUNCTIONS.radicalNestDepth(depth - 1),
LOCALE.MESSAGES.MS.ENDFRAC);
}
/**
* Middle string for fractions in Mathspeak superbrief mode.
* @param node The fraction node.
* @return The middle string.
*/
export function overFractionSbrief(node: Element): string {
let depth = fractionNestingDepth(node);
if (depth === 1) {
return LOCALE.MESSAGES.MS.FRAC_OVER;
}
return LOCALE.FUNCTIONS.combineNestedFraction(
LOCALE.MESSAGES.MS.NEST_FRAC,
LOCALE.FUNCTIONS.radicalNestDepth(depth - 1),
LOCALE.MESSAGES.MS.FRAC_OVER);
}
/**
* Custom query function to check if a vulgar fraction is small enough to be
* spoken as numbers in MathSpeak.
* @param node Fraction node to be tested.
* @return List containing the node if it is eligible. Otherwise
* empty.
*/
export function isSmallVulgarFraction(node: Element): Element[] {
return NumbersUtil.vulgarFractionSmall(node, 10, 100) ? [node] : [];
}
/**
* Computes prefix for sub and superscript nodes.
* @param node Subscript node.
* @param init Initial prefix string.
* @param replace Prefix strings for sub and
* superscript.
* @return The complete prefix string.
*/
export function nestedSubSuper(
node: Element, init: string, replace: {sup: string, sub: string}): string {
while (node.parentNode) {
let children = node.parentNode;
let parent = children.parentNode as Element;
if (!parent) {
break;
}
let nodeRole = node.getAttribute && node.getAttribute('role');
if (parent.tagName === SemanticType.SUBSCRIPT &&
node === children.childNodes[1] ||
parent.tagName === SemanticType.TENSOR && nodeRole &&
(nodeRole === SemanticRole.LEFTSUB ||
nodeRole === SemanticRole.RIGHTSUB)) {
init = replace.sub + LOCALE.MESSAGES.regexp.JOINER_SUBSUPER + init;
}
if (parent.tagName === SemanticType.SUPERSCRIPT &&
node === children.childNodes[1] ||
parent.tagName === SemanticType.TENSOR && nodeRole &&
(nodeRole === SemanticRole.LEFTSUPER ||
nodeRole === SemanticRole.RIGHTSUPER)) {
init = replace.sup + LOCALE.MESSAGES.regexp.JOINER_SUBSUPER + init;
}
node = parent;
}
return init.trim();
}
/**
* Computes subscript prefix in verbose mode.
* @param node Subscript node.
* @return The prefix string.
*/
export function subscriptVerbose(node: Element): string {
return nestedSubSuper(
node, LOCALE.MESSAGES.MS.SUBSCRIPT,
{sup: LOCALE.MESSAGES.MS.SUPER, sub: LOCALE.MESSAGES.MS.SUB});
}
/**
* Computes subscript prefix in brief mode.
* @param node Subscript node.
* @return The prefix string.
*/
export function subscriptBrief(node: Element): string {
return nestedSubSuper(
node, LOCALE.MESSAGES.MS.SUB,
{sup: LOCALE.MESSAGES.MS.SUP, sub: LOCALE.MESSAGES.MS.SUB});
}
/**
* Computes subscript prefix in verbose mode.
* @param node Subscript node.
* @return The prefix string.
*/
export function superscriptVerbose(node: Element): string {
return nestedSubSuper(
node, LOCALE.MESSAGES.MS.SUPERSCRIPT,
{sup: LOCALE.MESSAGES.MS.SUPER, sub: LOCALE.MESSAGES.MS.SUB});
}
/**
* Computes subscript prefix in brief mode.
* @param node Subscript node.
* @return The prefix string.
*/
export function superscriptBrief(node: Element): string {
return nestedSubSuper(
node, LOCALE.MESSAGES.MS.SUP,
{sup: LOCALE.MESSAGES.MS.SUP, sub: LOCALE.MESSAGES.MS.SUB});
}
/**
* Computes subscript prefix in verbose mode.
* @param node Subscript node.
* @return The prefix string.
*/
export function baselineVerbose(node: Element): string {
let baseline = nestedSubSuper(
node, '', {sup: LOCALE.MESSAGES.MS.SUPER, sub: LOCALE.MESSAGES.MS.SUB});
if (!baseline) {
return LOCALE.MESSAGES.MS.BASELINE;
}
return baseline.replace(
new RegExp(LOCALE.MESSAGES.MS.SUB + '$'), LOCALE.MESSAGES.MS.SUBSCRIPT)
.replace(new RegExp(LOCALE.MESSAGES.MS.SUPER + '$'),
LOCALE.MESSAGES.MS.SUPERSCRIPT);
}
/**
* Computes subscript prefix in brief mode.
* @param node Subscript node.
* @return The prefix string.
*/
export function baselineBrief(node: Element): string {
let baseline = nestedSubSuper(
node, '', {sup: LOCALE.MESSAGES.MS.SUP, sub: LOCALE.MESSAGES.MS.SUB});
return baseline || LOCALE.MESSAGES.MS.BASE;
}
// TODO (sorge) Refactor the following to functions wrt. style attribute.
/**
* Computes and returns the nesting depth of radical nodes.
* @param node The radical node.
* @return The nesting depth. 0 if the node is not a radical.
*/
export function radicalNestingDepth(node: Element): number {
return getNestingDepth(
'radical', node, ['sqrt', 'root'], nestingBarriers, {});
}
/**
* Nested string for radicals in Mathspeak mode putting together the nesting
* depth with a pre- and postfix string that depends on the speech style.
* @param node The radical node.
* @param prefix A prefix string.
* @param postfix A postfix string.
* @return The opening string.
*/
export function nestedRadical(
node: Element, prefix: string, postfix: string): string {
let depth = radicalNestingDepth(node);
let index = getRootIndex(node);
postfix = index ? LOCALE.FUNCTIONS.combineRootIndex(postfix, index) : postfix;
if (depth === 1) {
return postfix;
}
return LOCALE.FUNCTIONS.combineNestedRadical(
prefix, LOCALE.FUNCTIONS.radicalNestDepth(depth - 1), postfix);
}
/**
* A string indexing the root.
* @param node The radical node.
* @return The localised indexing string if it exists.
*/
export function getRootIndex(node: Element): string {
let content = node.tagName === 'sqrt' ? '2' :
// TODO (sorge): Make that safer?
XpathUtil.evalXPath('children/*[1]', node)[0].textContent.trim();
return LOCALE.MESSAGES.MSroots[content] || '';
}
/**
* Opening string for radicals in Mathspeak verbose mode.
* @param node The radical node.
* @return The opening string.
*/
export function openingRadicalVerbose(node: Element): string {
return nestedRadical(
node, LOCALE.MESSAGES.MS.NESTED, LOCALE.MESSAGES.MS.STARTROOT);
}
/**
* Closing string for radicals in Mathspeak verbose mode.
* @param node The radical node.
* @return The closing string.
*/
export function closingRadicalVerbose(node: Element): string {
return nestedRadical(
node, LOCALE.MESSAGES.MS.NESTED, LOCALE.MESSAGES.MS.ENDROOT);
}
/**
* Middle string for radicals in Mathspeak verbose mode.
* @param node The radical node.
* @return The middle string.
*/
export function indexRadicalVerbose(node: Element): string {
return nestedRadical(
node, LOCALE.MESSAGES.MS.NESTED, LOCALE.MESSAGES.MS.ROOTINDEX);
}
/**
* Opening string for radicals in Mathspeak brief mode.
* @param node The radical node.
* @return The opening string.
*/
export function openingRadicalBrief(node: Element): string {
return nestedRadical(
node, LOCALE.MESSAGES.MS.NEST_ROOT, LOCALE.MESSAGES.MS.STARTROOT);
}
/**
* Closing string for radicals in Mathspeak brief mode.
* @param node The radical node.
* @return The closing string.
*/
export function closingRadicalBrief(node: Element): string {
return nestedRadical(
node, LOCALE.MESSAGES.MS.NEST_ROOT, LOCALE.MESSAGES.MS.ENDROOT);
}
/**
* Middle string for radicals in Mathspeak superbrief mode.
* @param node The radical node.
* @return The middle string.
*/
export function indexRadicalBrief(node: Element): string {
return nestedRadical(
node, LOCALE.MESSAGES.MS.NEST_ROOT, LOCALE.MESSAGES.MS.ROOTINDEX);
}
/**
* Opening string for radicals in Mathspeak superbrief mode.
* @param node The radical node.
* @return The opening string.
*/
export function openingRadicalSbrief(node: Element): string {
return nestedRadical(
node, LOCALE.MESSAGES.MS.NEST_ROOT, LOCALE.MESSAGES.MS.ROOT);
}
/**
* Middle string for radicals in Mathspeak superbrief mode.
* @param node The radical node.
* @return The middle string.
*/
export function indexRadicalSbrief(node: Element): string {
return nestedRadical(
node, LOCALE.MESSAGES.MS.NEST_ROOT, LOCALE.MESSAGES.MS.INDEX);
}
/**
* Computes and returns the nesting depth of underscore nodes.
* @param node The underscore node.
* @return The nesting depth. 0 if the node is not an underscore.
*/
export function underscoreNestingDepth(node: Element): number {
return getNestingDepth(
'underscore', node, ['underscore'], nestingBarriers, {}, function(node) {
return node.tagName && node.tagName === SemanticType.UNDERSCORE &&
(node.childNodes[0].childNodes[1] as Element).
getAttribute('role') === SemanticRole.UNDERACCENT;
});
}
/**
* String function to construct and underscript prefix.
* @param node The underscore node.
* @return The correct prefix string.
*/
export function nestedUnderscript(node: Element): string {
let depth = underscoreNestingDepth(node);
return Array(depth).join(LOCALE.MESSAGES.MS.UNDER) +
LOCALE.MESSAGES.MS.UNDERSCRIPT;
}
/**
* Computes and returns the nesting depth of overscore nodes.
* @param node The overscore node.
* @return The nesting depth. 0 if the node is not an overscore.
*/
export function overscoreNestingDepth(node: Element): number {
return getNestingDepth(
'overscore', node, ['overscore'], nestingBarriers, {}, function(node) {
return node.tagName && node.tagName === SemanticType.OVERSCORE &&
(node.childNodes[0].childNodes[1] as Element).getAttribute('role') ===
SemanticRole.OVERACCENT;
});
}
export function endscripts(_node: Element) {
return LOCALE.MESSAGES.MS.ENDSCRIPTS;
}
/**
* String function to construct and overscript prefix.
* @param node The overscore node.
* @return The correct prefix string.
*/
export function nestedOverscript(node: Element): string {
let depth = overscoreNestingDepth(node);
return Array(depth).join(LOCALE.MESSAGES.MS.OVER) +
LOCALE.MESSAGES.MS.OVERSCRIPT;
}
/**
* Query function that Checks if we have a simple determinant in the sense that
* every cell only contains single letters or numbers.
* @param node The determinant node.
* @return List containing input node if true.
*/
export function determinantIsSimple(node: Element): Element[] {
if (node.tagName !== SemanticType.MATRIX ||
node.getAttribute('role') !== SemanticRole.DETERMINANT) {
return [];
}
let cells = XpathUtil.evalXPath(
'children/row/children/cell/children/*', node) as Element[];
for (let i = 0, cell; cell = cells[i]; i++) {
if (cell.tagName === SemanticType.NUMBER) {
continue;
}
if (cell.tagName === SemanticType.IDENTIFIER) {
let role = cell.getAttribute('role');
if (role === SemanticRole.LATINLETTER ||
role === SemanticRole.GREEKLETTER ||
role === SemanticRole.OTHERLETTER) {
continue;
}
}
return [];
}
return [node];
}
/**
* Generate constraints for the specialized baseline rules of relation
* sequences.
* @return The constraint strings.
*/
export function generateBaselineConstraint(): string[] {
let ignoreElems = ['subscript', 'superscript', 'tensor'];
let mainElems = ['relseq', 'multrel'];
let breakElems = ['fraction', 'punctuation', 'fenced', 'sqrt', 'root'];
let ancestrify = (elemList: string[]) =>
elemList.map(elem => 'ancestor::' + elem);
let notify = (elem: string) => 'not(' + elem + ')';
let prefix = 'ancestor::*/following-sibling::*';
let middle = notify(ancestrify(ignoreElems).join(' or '));
let mainList = ancestrify(mainElems);
let breakList = ancestrify(breakElems);
let breakCstrs: string[] = [];
for (let i = 0, brk: string; brk = breakList[i]; i++) {
breakCstrs = breakCstrs.concat(mainList.map(function(elem) {
return brk + '/' + elem;
}));
}
let postfix = notify(breakCstrs.join(' | '));
return [[prefix, middle, postfix].join(' and ')];
}
/**
* Removes parentheses around a label.
* @param node The label to be processed.
* @return The text of the label.
*/
export function removeParens(node: Element): string {
if (!node.childNodes.length || !node.childNodes[0].childNodes.length ||
!node.childNodes[0].childNodes[0].childNodes.length) {
return '';
}
let content = node.childNodes[0].childNodes[0].childNodes[0].textContent;
return content.match(/^\(.+\)$/) ? content.slice(1, -1) : content;
}
// Generating rules for tensors.
/**
* Component strings for tensor speech rules.
*/
const componentString: Map<number, string> = new Map([
[3, 'CSFleftsuperscript'],
[4, 'CSFleftsubscript'],
[2, 'CSFbaseline'],
[1, 'CSFrightsubscript'],
[0, 'CSFrightsuperscript']
]);
/**
* Child number translation for tensor speech rules.
*/
const childNumber: Map<number, number> = new Map([
[4, 2],
[3, 3],
[2, 1],
[1, 4],
[0, 5]
]);
/**
* Generates the rule strings and constraints for tensor rules.
* @param constellation Bitvector representing of possible tensor
* constellation.
* @return A list consisting of additional constraints for the
* tensor rule, plus the strings for the verbose and brief rule, in that
* order.
*/
function generateTensorRuleStrings_(constellation: string): [string[], string, string] {
let constraints = [];
let verbString = '';
let briefString = '';
let constel = parseInt(constellation, 2);
for (let i = 0; i < 5; i++) {
let childString = 'children/*[' + childNumber.get(i) + ']';
if (constel & 1) {
let compString = componentString.get(i % 5);
verbString = '[t] ' + compString + 'Verbose; [n] ' + childString + ';' +
verbString;
briefString =
'[t] ' + compString + 'Brief; [n] ' + childString + ';' + briefString;
} else {
constraints.unshift('name(' + childString + ')="empty"');
}
constel >>= 1;
}
return [constraints, verbString, briefString];
}
/**
* Generator for tensor speech rules.
* @param store The mathstore to which the rules are added.
*/
export function generateTensorRules(store: SpeechRuleStore,
brief: boolean = true) {
// Constellations are built as bitvectors with the meaning:
// lsub lsuper base rsub rsuper
let constellations = [
'11111', '11110', '11101', '11100', '10111', '10110', '10101', '10100',
'01111', '01110', '01101', '01100'
];
for (let i = 0, constel; constel = constellations[i]; i++) {
let name = 'tensor' + constel;
let [components, verbStr, briefStr] = generateTensorRuleStrings_(constel);
let verbList =
[name, 'default', verbStr, 'self::tensor'].concat(components);
// Rules without neighbour.
store.defineRule.apply(store, verbList);
if (brief) {
let briefList =
[name, 'brief', briefStr, 'self::tensor'].concat(components);
store.defineRule.apply(store, briefList);
briefList[1] = 'sbrief';
store.defineRule.apply(store, briefList);
}
// Rules with baseline.
let baselineStr = componentString.get(2);
verbStr += '; [t]' + baselineStr + 'Verbose';
briefStr += '; [t]' + baselineStr + 'Brief';
name = name + '-baseline';
let cstr = '((.//*[not(*)])[last()]/@id)!=(((.//ancestor::fraction|' +
'ancestor::root|ancestor::sqrt|ancestor::cell|ancestor::line|' +
'ancestor::stree)[1]//*[not(*)])[last()]/@id)';
verbList =
[name, 'default', verbStr, 'self::tensor', cstr].concat(components);
store.defineRule.apply(store, verbList);
if (brief) {
let briefList =
[name, 'brief', briefStr, 'self::tensor', cstr].concat(components);
store.defineRule.apply(store, briefList);
briefList[1] = 'sbrief';
store.defineRule.apply(store, briefList);
}
}
}
/**
* Predicate to decide if a root has a small index, i.e., between 1 and 10.
* @param node The root node.
* @return The list with the given node, if it is a root with a
* small index.
*/
export function smallRoot(node: Element): Element[] {
let max = Object.keys(LOCALE.MESSAGES.MSroots).length;
if (!max) {
return [];
} else {
max++;
}
if (!node.childNodes || node.childNodes.length === 0 ||
!node.childNodes[0].childNodes) {
return [];
}
let index = node.childNodes[0].childNodes[0].textContent;
if (!/^\d+$/.test(index)) {
return [];
}
let num = parseInt(index, 10);
return num > 1 && num <= max ? [node] : [];
} | the_stack |
import {
getLeoRC,
getCorePackageJSON,
getProjectPackageJSON,
runInstall,
extendsProcessEnv,
getRemotePkgTagVersion,
} from './utils';
import { IRC } from './defaultRC';
import fs from 'fs-extra';
import semver from 'semver';
import set from 'lodash.set';
import unset from 'lodash.unset';
import merge from 'lodash.merge';
import simpleGit from 'simple-git';
import inquirer from 'inquirer';
import axios from 'axios';
import { loadPkg, log as leoLog } from '@jdfed/leo-utils';
import { getDefaultConfig, IConfig, IActionArgs, localStaticConfig, configStore } from './config';
import { IBuilder, IVirtualPath, ICommonParams, ILeoCaller } from './interface';
export interface IHooks {
beforeStart?: (this: Core) => any;
afterCommandExecute?: (this: Core) => any;
}
const log = leoLog.scope('core');
class Core {
leoRC: IRC;
leoConfig: IConfig;
cli: ILeoCaller = null;
generator: ILeoCaller = null;
builder: IBuilder = null;
rootName: string;
hooks: IHooks = {};
virtualPath: IVirtualPath;
constructor({ config, hooks = {} }: { config?: IConfig; hooks?: IHooks } = {}) {
this.hooks = hooks;
this.leoConfig = configStore.init(getDefaultConfig(config)).getConfig() as IConfig;
// 初始化一些环境变量供leo-utils使用
extendsProcessEnv(this.leoConfig);
// 初始化本地 config
this.initLocalConfig();
}
async start() {
try {
this?.hooks?.beforeStart?.call(this);
this.leoRC = getLeoRC(this.leoConfig.rcFileName);
log.debug(`${this.leoConfig.rcFileName}`, JSON.stringify(this.leoRC, null, 2));
log.debug('config', JSON.stringify(this.leoConfig, null, 2));
await this.initCLI();
await this.cli.start();
} catch (e) {
log.error(this.leoConfig.isDev ? e : ((e as unknown) as Error)?.message);
process.exit(-1);
}
}
cliActionHandler = async (
command: string,
args: IActionArgs,
extendsCommandAction?: (params: {
args: IActionArgs;
subCommandName: string;
[key: string]: any;
}) => void,
) => {
log.debug('cliActionHandler', 'commandName:', command, 'args:', args);
try {
const [commandName, subCommandName] = command.split('.');
await this.doStartCheck();
// 约定必须要实现的
switch (commandName) {
case 'init':
await this.commandInitAction(args);
break;
case 'dev':
await this.commandDevAction(args);
break;
case 'build':
await this.commandBuildAction(args);
break;
case 'test':
await this.commandTestAction(args);
break;
case 'lint':
await this.commandLintAction(args);
break;
case 'clear':
await this.commandClearAction(args);
break;
case 'config':
await this.commandConfigAction(subCommandName, args);
break;
default:
await this.extendsCommandAction(commandName, subCommandName, args, extendsCommandAction);
break;
}
this?.hooks?.afterCommandExecute?.call(this);
} catch (error) {
log.error(this.leoConfig.isDev ? error : ((error as unknown) as Error)?.message);
process.exit(-1);
}
};
// 以下命令回调
// init 指令回调
async commandInitAction(args: IActionArgs) {
let {
arguments: [templateName],
} = args;
const { options, unexpectedOptions } = args;
// 模糊查询需要登录,如果直接使用如 leo init ifloor,也会提示,所以设置了配置项控制
if (templateName) {
const projectList = await this.getProjectsLikeName(templateName);
if (projectList.length <= 0) {
throw new Error(`未找到对应的模板,请校对模板名是否正确(${templateName})`);
}
// 当模板为 aa-bb 时,输出 leo init aa,也应当有提示
if (
(projectList.length === 1 && projectList[0].value !== templateName) ||
projectList.length > 1
) {
log.info('如需关闭模板模糊查询功能,可使用 leo config set fuzzyTemp=false');
const res = await this.askQuestions([
{
name: 'templateName',
type: 'list',
message: `查询到与 ${templateName} 相关的模板,请选择:`,
choices: projectList,
},
]);
templateName = res.templateName;
}
}
if (!templateName) {
const res = await this.askQuestions(this.leoConfig.questions.chooseTemplate);
templateName = res.templateName;
}
const { useInstall, projectName } = await this.askQuestions(this.leoConfig.questions.init);
log.debug('commandInitAction', templateName, options);
log.info('开始创建项目');
await this.initGenerator(templateName, { ...options, ...unexpectedOptions }, projectName);
if (useInstall !== 'custom') {
log.await('开始安装依赖');
await runInstall(useInstall === 'yarn', projectName);
log.success('安装完成!');
}
log.info(
`初始化成功!\n 使用以下指令来开始项目:\n cd ${projectName}\n ${this.leoConfig.rootName} dev\n`,
);
this.leoConfig.helpTexts.forEach((helpInfo) => {
log.info(helpInfo.text);
});
}
async commandDevAction(args: IActionArgs) {
log.debug('commandDevAction', args);
const { options, unexpectedOptions } = args;
log.info('启动调试');
await this.initBuilder({ ...options, ...unexpectedOptions });
// hook: beforeDev
await this.leoRC?.builder?.hooks?.beforeDev?.(this.builder);
await this.builder.start();
// hook: afterDev
await this.leoRC?.builder?.hooks?.afterDev?.(this.builder);
}
async commandBuildAction(args: IActionArgs) {
log.debug('commandBuildAction', args);
const { options, unexpectedOptions } = args;
log.info('开始构建');
await this.initBuilder({ ...options, ...unexpectedOptions });
// hook: beforeBuild
await this.leoRC?.builder?.hooks?.beforeBuild?.(this.builder);
await this.builder.build();
// hook: beforeBuild
await this.leoRC?.builder?.hooks?.afterBuild?.(this.builder);
}
async commandTestAction(args: IActionArgs) {
log.debug('commandTestAction', args);
const { options, unexpectedOptions } = args;
log.info('开始测试');
return await this.doTestAction({ ...options, ...unexpectedOptions });
}
async doTestAction(options: { [key: string]: any } = {}) {
if (this.leoRC.testAction) {
// 外部传入优先级更高
const testRes = await this.leoRC.testAction(options);
if (testRes !== true) {
throw new Error('test 失败');
}
return testRes;
} else {
log.warn('未找到 leorc 中 testAction 配置');
}
// true 为正常执行
return true;
}
async commandLintAction(args: IActionArgs) {
log.debug('commandLintAction', args);
const { options, unexpectedOptions } = args;
log.info('开始Lint');
return await this.doLintAction({ ...options, ...unexpectedOptions });
}
async doLintAction(options: { [key: string]: any } = {}) {
if (this.leoRC.lintAction) {
// 外部传入优先级更高
const lintRes = await this.leoRC.lintAction(options);
// 由于 leorc 是 js 编写,必须强制校验 lintAction 的返回,
// 同理 test action 也添加相同逻辑
if (lintRes !== true) {
throw new Error('lint 失败');
}
return lintRes;
} else {
log.warn('未找到 leorc 中 lintAction 配置');
}
// true 为正常执行
return true;
}
async commandClearAction(args: IActionArgs) {
const { options } = args;
log.info('开始清理');
// 如果未填参数则显示帮助信息
if (Object.values(options).every((v) => v === false)) {
return this.doClearAction();
}
await Promise.all(
Object.entries(options)
.filter((keyValue) => keyValue[1] === true)
.map((keyValue) => this.doClearAction(keyValue[0])),
);
}
async prePublishAction(args: IActionArgs) {
log.debug('prePublishAction', this.leoRC.isPrePublishParallel);
if (this.leoRC.isPrePublishParallel) {
return Promise.all([
this.commandLintAction(args),
this.commandTestAction(args),
this.commandBuildAction(args),
]);
}
const lintResult = await this.commandLintAction(args);
if (lintResult !== true) return;
const testResult = await this.commandTestAction(args);
if (testResult !== true) return;
await this.commandBuildAction(args);
}
async doClearAction(clearName?: string) {
const { virtualPath } = this.leoConfig;
switch (clearName) {
case 'config':
await fs.remove(virtualPath.configPath);
log.success('清除 leoConfig 缓存成功');
break;
case 'template':
await fs.remove(virtualPath.templatePath);
log.success('清除模板缓存成功');
break;
case 'node_modules':
await fs.remove(virtualPath.nodeModulesPath);
log.success('清除 npm 包缓存成功');
break;
case 'all':
default:
await fs.remove(virtualPath.entry);
log.success('清除所有缓存成功');
}
}
async commandConfigAction(subCommandName: string, args: IActionArgs) {
// 确保 config 文件存在
const {
virtualPath: { configPath },
} = this.leoConfig;
await fs.ensureFile(configPath);
const localConfig = (await fs.readJson(configPath)) || {};
const {
arguments: [key],
} = args;
switch (subCommandName) {
case 'set':
await this.doSetConfigAction(args, localConfig);
break;
case 'get':
log.info(localConfig[key]);
break;
case 'delete':
unset(localConfig, key);
await fs.writeJson(this.leoConfig.virtualPath.configPath, localConfig);
log.success('删除成功');
break;
case 'list':
log.info(localConfig);
break;
default:
// 不存在无值的情况,未传指令commander会拦截
break;
}
}
async doSetConfigAction(args: IActionArgs, localConfig: { [key: string]: any }) {
// args.arguments 为 ['key=value','key=value'] 格式
const keyValueMap = args.arguments.reduce((map, keyValue) => {
// 命令行空格会出现 undefined
if (keyValue) {
const [key, value] = keyValue.split('=');
const v = value === 'true' || value === 'false' ? value === 'true' : value;
set(map, key, v);
}
return map;
}, {});
await fs.writeJson(this.leoConfig.virtualPath.configPath, merge({}, localConfig, keyValueMap));
log.success('设置成功');
}
async extendsCommandAction(
commandName: string,
subCommandName: string,
args: IActionArgs,
extendsCommandAction: (params: {
args: IActionArgs;
subCommandName: string;
[key: string]: any;
}) => void,
) {
await extendsCommandAction?.({
args,
subCommandName,
...this.getCommonParams(),
});
}
askQuestions(questions: any[]): Promise<{ [key: string]: any }> {
return inquirer.prompt(questions);
}
/**
* 执行检查
* @returns {Promise}
*/
async doStartCheck(): Promise<any> {
// 云构建某些情况无法连接内网
const checkList = [this.checkNodeVersion(), this.checkVersion()];
return Promise.all(checkList);
}
private async initBuilder(options: { [key: string]: any } = {}): Promise<void> {
log.debug('initBuilder', 'before builder create');
const { leoRC } = this;
const Builder = (await loadPkg(leoRC.builder.name, {
version: leoRC.builder.version,
private: true,
})) as any;
this.builder = new Builder({
options,
...this.getCommonParams(),
});
}
private async initCLI(): Promise<void> {
log.debug('initCLI', 'before CLI create');
const { leoConfig } = this;
const { version } = getCorePackageJSON();
const CLI = (await loadPkg(leoConfig.cli.name, leoConfig.cli.version)) as any;
this.cli = new CLI({
commands: this.leoConfig.commands,
actionHandler: this.cliActionHandler,
version,
helpTexts: this.leoConfig.helpTexts,
...this.getCommonParams(),
});
}
private async initGenerator(
templateName: string,
options: { [key: string]: any },
projectName: string,
): Promise<void> {
log.debug('initGenerator', 'start init generator');
const { leoConfig } = this;
const Generator = (await loadPkg(leoConfig.generator.name, leoConfig.generator.version)) as any;
this.generator = new Generator({
templateName,
projectName,
options,
cachePath: this.leoConfig.virtualPath.templatePath,
...this.getCommonParams(),
});
await this.generator.start();
}
/**
* 检查node版本
* @private
* @returns {Promise}
*/
private checkNodeVersion(): Promise<any> {
// 检查 node 版本
const { engines } = getCorePackageJSON();
const nodeVersionSatisfy = semver.satisfies(process.version, engines.node);
if (nodeVersionSatisfy) return Promise.resolve(0);
return Promise.reject(new Error(`请使用${engines.node}版本的 node`));
}
/**
* 检查当前版本与最新版本是否一致并提示
* @private
* @returns {Promise}
*/
private async checkVersion(): Promise<any> {
// 默认提示升级,如开启强制升级,则中断后续操作
const pkg = getCorePackageJSON();
const pkgTagVersion = await getRemotePkgTagVersion(pkg.name);
const { latest } = pkgTagVersion;
// 检查正式版本
if (semver.gt(latest, pkg.version) && this.leoConfig.forceUpdate) {
return Promise.reject(new Error('当前版本过旧,请升级后使用'));
}
}
private async checkPublishStatus(): Promise<string> {
const git = simpleGit();
// 检查 git 是否全部提交
// 检查当前登录状态(是否过期)
const [{ files }] = await Promise.all([git.status()]);
if (files.length) {
return 'git 全部提交后才能进行发布';
}
return '';
}
/**
* @description 模糊查询leo-templates下的模板
* @private
* @memberof Core
*/
private getProjectsLikeName = async (name: string): Promise<[{ [key: string]: any }]> => {
const { data: templateList } = await axios
.get(`${this.leoConfig.gitTemplateGroupQueryURL}`, {
headers: this.leoConfig.gitQueryHeader,
})
.catch(() => {
return { data: [] };
});
return templateList
.map((item: { [key: string]: any }) => {
const templateName = item.path.replace(/-template$/, '');
return {
name: `${templateName}(${item.name})`,
value: templateName,
};
})
.filter((item: { [key: string]: any }) => {
return this.leoConfig.fuzzyTemp ? item.value.indexOf(name) !== -1 : item.value === name;
})
.sort((item: { [key: string]: any }) => (item.value === name ? -1 : 0));
};
/**
* @description 初始化本地 config,如果本地不存在,则创建
* @private
* @memberof Core
*/
private initLocalConfig = () => {
const {
virtualPath: { configPath },
} = this.leoConfig;
if (fs.existsSync(configPath)) {
return;
}
fs.outputJsonSync(configPath, localStaticConfig);
};
/**
* @description 提供需要为插件提供的公共参数
* @private
*/
private getCommonParams(): ICommonParams {
return {
leoConfig: this.leoConfig,
leoRC: this.leoRC,
leoUtils: {},
pkg: getProjectPackageJSON(),
};
}
}
export default Core; | the_stack |
import { Matrix2, Matrix3, Matrix4, Vector2, Vector3, Vector4 } from './matrix';
import glEnum from './glEnum';
//const glEnum = {};
let gl;
let screenTextureCount = 31;
export const clearColor = [0, 0, 0, 1];
export function getTextureIndex() {
screenTextureCount--;
return screenTextureCount;
}
export const textureEnum = {
baseColorTexture: 0,
metallicRoughnessTexture: 1,
normalTexture: 2,
occlusionTexture: 3,
emissiveTexture: 4,
irradianceTexture: 5,
prefilterTexture: 6,
brdfLUTTexture: 7,
clearcoatTexture: 8,
clearcoatRoughnessTexture: 9,
clearcoatNormalTexture: 10,
sheenColorTexture: 11,
sheenRoughnessTexture: 12,
Sheen_E: 13,
transmissionTexture: 14,
specularTexture: 15,
thicknessTexture: 16
};
export function setGl(_gl) {
gl = _gl;
// for (const k in gl) {
// const v = gl[k];
// if (typeof v === 'number') {
// glEnum[v] = k;
// }
// }
}
export function isMatrix(type) {
return glEnum[type] === 'FLOAT_MAT4' || glEnum[type] === 'FLOAT_MAT3' || glEnum[type] === 'FLOAT_MAT2';
}
export function random(min, max) {
return Math.random() * (max - min) + min;
}
export function lerp(a, b, f) {
return a + f * (b - a);
}
export function getMatrixType(type) {
if (glEnum[type] === 'FLOAT_MAT4') {
return Matrix4;
}
if (glEnum[type] === 'FLOAT_MAT3') {
return Matrix3;
}
if (glEnum[type] === 'FLOAT_MAT2') {
return Matrix2;
}
}
export function getDataType(type) {
let count;
switch (type) {
case 'MAT2':
count = 4;
break;
case 'MAT3':
count = 9;
break;
case 'MAT4':
count = 16;
break;
case 'VEC4':
count = 4;
break;
case 'VEC3':
count = 3;
break;
case 'VEC2':
count = 2;
break;
case 'SCALAR':
count = 1;
break;
}
return count;
}
export function getComponentType(type) {
let count;
switch (glEnum[type]) {
case 'FLOAT_VEC4':
count = 4;
break;
case 'FLOAT_VEC3':
count = 3;
break;
case 'FLOAT_VEC2':
count = 2;
break;
}
return count;
}
export function getMethod(type) {
let method;
switch (glEnum[type]) {
case 'FLOAT_VEC2':
method = 'uniform2f';
break;
case 'FLOAT_VEC4':
method = 'uniform4f';
break;
case 'FLOAT':
method = 'uniform1f';
break;
case 'FLOAT_VEC3':
method = 'uniform3f';
break;
case 'FLOAT_MAT4':
method = 'uniformMatrix4fv';
break;
case 'FLOAT_MAT3':
method = 'uniformMatrix3fv';
break;
case 'FLOAT_MAT2':
method = 'uniformMatrix2fv';
break;
case 'SAMPLER_2D':
method = 'uniform1i';
break;
}
return method;
}
export function getAnimationComponent(type) {
if (type === 'rotation') {
return 4;
} else if (type === 'translation' || type === 'scale') {
return 3;
}
}
export function range(min, max, value) {
return (value - min) / (max - min);
}
export function interpolation(time, frames) {
if (frames.length === 0) {
return [-1, -1, 0];
}
let prev = -1;
for (let i = frames.length - 1; i >= 0; i--) {
if (time >= frames[i].time) {
prev = i;
break;
}
}
if (prev === -1 || prev === frames.length - 1) {
if (prev < 0) {
prev = 0;
}
return [prev, prev, 0];
} else {
const startFrame = frames[prev];
const endFrame = frames[prev + 1];
time = Math.max(startFrame.time, Math.min(time, endFrame.time));
const t = range(startFrame.time, endFrame.time, time);
return [prev, prev + 1, t];
}
}
function getCount(type) {
let arr;
switch (glEnum[type]) {
case 'BYTE':
case 'UNSIGNED_BYTE':
arr = 1;
break;
case 'SHORT':
case 'UNSIGNED_SHORT':
arr = 2;
break;
case 'UNSIGNED_INT':
case 'FLOAT':
arr = 4;
break;
}
return arr;
}
export const ArrayBufferMap = new Map();
ArrayBufferMap.set(Int8Array, 'BYTE');
ArrayBufferMap.set(Uint8Array, 'UNSIGNED_BYTE');
ArrayBufferMap.set(Int16Array, 'SHORT');
ArrayBufferMap.set(Uint16Array, 'UNSIGNED_SHORT');
ArrayBufferMap.set(Uint32Array, 'UNSIGNED_INT');
ArrayBufferMap.set(Float32Array, 'FLOAT');
export function buildArrayWithStride(arrayBuffer, accessor, bufferView) {
const sizeofComponent = getCount(accessor.componentType);
const typeofComponent = getDataType(accessor.type);
const offset = (bufferView.byteOffset || 0) + (accessor.byteOffset || 0);
const stride = bufferView.byteStride;
const lengthByStride = (stride * accessor.count) / sizeofComponent;
const requiredLength = accessor.count * typeofComponent;
let length = lengthByStride || requiredLength;
if (arrayBuffer.byteLength < length * sizeofComponent + offset) {
length -= accessor.byteOffset;
}
let arr;
switch (glEnum[accessor.componentType]) {
case 'BYTE':
arr = new Int8Array(arrayBuffer, offset, length);
break;
case 'UNSIGNED_BYTE':
arr = new Uint8Array(arrayBuffer, offset, length);
break;
case 'SHORT':
arr = new Int16Array(arrayBuffer, offset, length);
break;
case 'UNSIGNED_SHORT':
arr = new Uint16Array(arrayBuffer, offset, length);
break;
case 'UNSIGNED_INT':
arr = new Uint32Array(arrayBuffer, offset, length);
break;
case 'FLOAT':
arr = new Float32Array(arrayBuffer, offset, length);
break;
}
if (length !== requiredLength) {
// buffer is too big need to stride it
const stridedArr = new arr.constructor(requiredLength);
let j = 0;
for (let i = 0; i < stridedArr.length; i += typeofComponent) {
for (let k = 0; k < typeofComponent; k++) {
stridedArr[i + k] = arr[j + k];
}
j += stride / sizeofComponent;
}
return stridedArr;
} else {
return arr;
}
}
export function buildArray(arrayBuffer, type, offset, length) {
let arr;
switch (glEnum[type]) {
case 'BYTE':
arr = new Int8Array(arrayBuffer, offset, length);
break;
case 'UNSIGNED_BYTE':
arr = new Uint8Array(arrayBuffer, offset, length);
break;
case 'SHORT':
arr = new Int16Array(arrayBuffer, offset, length);
break;
case 'UNSIGNED_SHORT':
arr = new Uint16Array(arrayBuffer, offset, length);
break;
case 'UNSIGNED_INT':
arr = new Uint32Array(arrayBuffer, offset, length);
break;
case 'FLOAT':
arr = new Float32Array(arrayBuffer, offset, length);
break;
}
return arr;
}
export function compileShader(type, shaderSource, program) {
const shader = gl.createShader(type);
gl.shaderSource(shader, shaderSource);
gl.compileShader(shader);
gl.attachShader(program, shader);
const log = gl.getShaderInfoLog(shader);
if (log) {
throw new Error(log);
}
}
export function createProgram(vertex, fragment) {
const program = gl.createProgram();
compileShader(gl.VERTEX_SHADER, vertex, program);
compileShader(gl.FRAGMENT_SHADER, fragment, program);
gl.linkProgram(program);
gl.validateProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
const info = gl.getProgramInfoLog(program);
throw new Error(`Could not compile WebGL program. ${info}`);
}
return program;
}
export function createTexture(type = gl.TEXTURE_2D, index = getTextureIndex()) {
const texture = gl.createTexture();
gl.activeTexture(gl[`TEXTURE${index}`]);
gl.bindTexture(type, texture);
texture.index = index;
return texture;
}
export function walk(node, callback) {
function _walk(node) {
callback(node);
if (node.children) {
node.children.forEach(_walk);
}
}
_walk(node);
}
export function sceneToArcBall(pos) {
let len = pos[0] * pos[0] + pos[1] * pos[1];
const sz = 0.04 * 0.04 - len;
if (sz > 0) {
return [pos[0], pos[1], Math.sqrt(sz)];
} else {
len = Math.sqrt(len);
return [(0.04 * pos[0]) / len, (0.04 * pos[1]) / len, 0];
}
}
export function canvasToWorld(vec2, projection, width, height) {
const [x, y] = vec2;
const newM = new Matrix4();
newM.setTranslate(new Vector3([0, 0, 0.05]));
const m = new Matrix4(projection);
m.multiply(newM);
const mp = m.multiplyVector4(new Vector4([0, 0, 0, 1]));
mp.elements[0] = ((2 * x) / width - 1) * mp.elements[3];
mp.elements[1] = ((-2 * y) / height + 1) * mp.elements[3];
const v = m.invert().multiplyVector4(mp);
return [v.elements[0], v.elements[1]];
}
export function calculateProjection(cam) {
const { aspect, zoom } = cam;
let proj;
if (cam.type === 'perspective' && cam.perspective) {
const { yfov } = cam.perspective;
proj = new Matrix4().setPerspective(yfov, aspect, cam.perspective.znear || 1, cam.perspective.zfar || 2e6);
} else if (cam.type === 'orthographic' && cam.orthographic) {
proj = new Matrix4().setOrtho(
cam.orthographic.xmag * zoom,
cam.orthographic.ymag * zoom,
cam.orthographic.znear,
cam.orthographic.zfar
);
}
return proj;
}
export function calculateOffset(a = 0, b = 0) {
return a + b;
}
export function calculateUVs(vertex, normal) {
const UVS = new Float32Array((vertex.length / 3) * 2);
const Min = new Vector2([Infinity, Infinity]);
const Max = new Vector2([-Infinity, -Infinity]);
for (let i = 0; i < vertex.length / 3; ++i) {
const coords = [];
const norm = [];
for (let c = 0; c < 3; ++c) {
coords.push(vertex[3 * i + c]);
norm.push(normal[3 * i + c]);
}
const N = new Vector3(norm);
const components = ['x', 'y', 'z'].sort((a, b) => {
return Math.abs(N[a]) - Math.abs(N[b]);
});
const pos = new Vector3(coords);
const u = pos[components[0]];
const v = pos[components[1]];
UVS[i * 2] = u;
UVS[i * 2 + 1] = v;
Max.x = Math.max(Max.x, u);
Max.y = Math.max(Max.y, v);
Min.x = Math.min(Min.x, u);
Min.y = Math.min(Min.y, v);
}
const diff = new Vector2(Max.elements).subtract(Min);
for (let i = 0; i < vertex.length / 3; ++i) {
const ix = i * 2;
UVS[ix] = (UVS[ix] - Min.x) / diff.x;
UVS[ix + 1] = (UVS[ix + 1] - Min.y) / diff.y;
}
return UVS;
}
export function calculateNormals2(vertex) {
const ns = new Float32Array(vertex.length);
for (let i = 0; i < vertex.length; i += 9) {
const faceVertices = [
new Vector3([vertex[i], vertex[i + 1], vertex[i + 2]]),
new Vector3([vertex[i + 3], vertex[i + 4], vertex[i + 5]]),
new Vector3([vertex[i + 6], vertex[i + 7], vertex[i + 8]])
];
const dv1 = faceVertices[1].subtract(faceVertices[0]);
const dv2 = faceVertices[2].subtract(faceVertices[0]);
const n = Vector3.cross(dv1.normalize(), dv2.normalize());
const [x, y, z] = n.elements;
ns[i] = x;
ns[i + 1] = y;
ns[i + 2] = z;
ns[i + 3] = x;
ns[i + 4] = y;
ns[i + 5] = z;
ns[i + 6] = x;
ns[i + 7] = y;
ns[i + 8] = z;
}
return ns;
}
export function calculateNormals(index, vertex) {
const ns = new Float32Array((vertex.length / 3) * 3);
for (let i = 0; i < index.length; i += 3) {
const faceIndexes = [index[i], index[i + 1], index[i + 2]];
const faceVertices = faceIndexes.map(ix => vectorFromArray(vertex, ix));
const dv1 = faceVertices[1].subtract(faceVertices[0]);
const dv2 = faceVertices[2].subtract(faceVertices[0]);
const n = Vector3.cross(dv1.normalize(), dv2.normalize());
const [x, y, z] = n.elements;
for (let j = 0; j < 3; j++) {
ns[3 * index[i + j] + 0] = ns[3 * index[i + j] + 0] + x;
ns[3 * index[i + j] + 1] = ns[3 * index[i + j] + 1] + y;
ns[3 * index[i + j] + 2] = ns[3 * index[i + j] + 2] + z;
}
}
return ns;
function vectorFromArray(array, index, elements = 3) {
index = index * elements;
return new Vector3([array[index], array[index + 1], array[index + 2]]);
}
}
export function calculateBinormals(index, vertex, normal, uv) {
const tangent = new Float32Array((normal.length / 3) * 4);
for (let i = 0; i < index.length; i += 3) {
const faceIndexes = [index[i], index[i + 1], index[i + 2]];
const faceVertices = faceIndexes.map(ix => vectorFromArray(vertex, ix));
const faceUVs = faceIndexes.map(ix => vectorFromArray(uv, ix, 2));
const dv1 = faceVertices[1].subtract(faceVertices[0]);
const dv2 = faceVertices[2].subtract(faceVertices[0]);
const duv1 = faceUVs[1].subtract(faceUVs[0]);
const duv2 = faceUVs[2].subtract(faceUVs[0]);
let r = duv1.elements[0] * duv2.elements[1] - duv1.elements[1] * duv2.elements[0];
const sign = r > 0 ? 1 : -1;
r = r !== 0 ? 1.0 / r : 1.0;
const udir = new Vector3([
(duv2.elements[1] * dv1.elements[0] - duv1.elements[1] * dv2.elements[0]) * r,
(duv2.elements[1] * dv1.elements[1] - duv1.elements[1] * dv2.elements[1]) * r,
(duv2.elements[1] * dv1.elements[2] - duv1.elements[1] * dv2.elements[2]) * r
]);
udir.normalize();
faceIndexes.forEach(ix => {
accumulateVectorInArray(tangent, ix, udir, sign);
});
}
return tangent;
function vectorFromArray(array, index, elements = 3) {
index = index * elements;
if (elements === 3) {
return new Vector3([array[index], array[index + 1], array[index + 2]]);
}
if (elements === 2) {
return new Vector2([array[index], array[index + 1]]);
}
}
function accumulateVectorInArray(array, index, vector, sign, elements = 4, accumulator = (acc, x) => acc + x) {
index = index * elements;
for (let i = 0; i < elements; ++i) {
if (i === 3) {
array[index + i] = sign;
} else {
array[index + i] = accumulator(array[index + i], vector.elements[i]);
}
}
}
}
export function measureGPU() {
const ext = gl.getExtension('EXT_disjoint_timer_query');
const query = ext.createQueryEXT();
ext.beginQueryEXT(ext.TIME_ELAPSED_EXT, query);
ext.endQueryEXT(ext.TIME_ELAPSED_EXT);
const available = ext.getQueryObjectEXT(query, ext.QUERY_RESULT_AVAILABLE_EXT);
const disjoint = gl.getParameter(ext.GPU_DISJOINT_EXT);
if (available && !disjoint) {
const timeElapsed = ext.getQueryObjectEXT(query, ext.QUERY_RESULT_EXT);
console.log(timeElapsed / 1000000);
}
}
export function getGlEnum(name) {
return glEnum[name];
}
export function normalize(array) {
let fn;
switch (true) {
case array instanceof Uint8Array:
fn = c => c / 255;
break;
case array instanceof Int8Array:
fn = c => Math.max(c / 127.0, -1.0);
break;
case array instanceof Uint16Array:
fn = c => c / 65535;
break;
case array instanceof Int16Array:
fn = c => Math.max(c / 32767.0, -1.0);
break;
}
if (fn) {
const normalizedArray = new Float32Array(array.length);
for (let i = 0; i < array.length; i++) {
normalizedArray[i] = fn(array[i]);
}
return normalizedArray;
} else {
return array;
}
} | the_stack |
export namespace Terminal {
// Default Application
export interface Application {}
// Class
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* The application‘s top-level scripting object.
*/
export interface Application {
/**
* The name of the application.
*/
name(): string;
/**
* Is this the frontmost (active) application?
*/
frontmost(): boolean;
/**
* The version of the application.
*/
version(): string;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* A window.
*/
export interface Window {
/**
* The full title of the window.
*/
name(): string;
/**
* The unique identifier of the window.
*/
id(): number;
/**
* The index of the window, ordered front to back.
*/
index(): number;
/**
* The bounding rectangle of the window.
*/
bounds(): any;
/**
* Whether the window has a close box.
*/
closeable(): boolean;
/**
* Whether the window can be minimized.
*/
miniaturizable(): boolean;
/**
* Whether the window is currently minimized.
*/
miniaturized(): boolean;
/**
* Whether the window can be resized.
*/
resizable(): boolean;
/**
* Whether the window is currently visible.
*/
visible(): boolean;
/**
* Whether the window can be zoomed.
*/
zoomable(): boolean;
/**
* Whether the window is currently zoomed.
*/
zoomed(): boolean;
/**
* Whether the window is currently the frontmost Terminal window.
*/
frontmost(): boolean;
/**
* The position of the window, relative to the upper left corner of the screen.
*/
position(): any;
/**
* The position of the window, relative to the lower left corner of the screen.
*/
origin(): any;
/**
* The width and height of the window
*/
size(): any;
/**
* The bounding rectangle, relative to the lower left corner of the screen.
*/
frame(): any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* A set of settings.
*/
export interface SettingsSet {
/**
* The unique identifier of the settings set.
*/
id(): number;
/**
* The name of the settings set.
*/
name(): string;
/**
* The number of rows displayed in the tab.
*/
numberOfRows(): number;
/**
* The number of columns displayed in the tab.
*/
numberOfColumns(): number;
/**
* The cursor color for the tab.
*/
cursorColor(): any;
/**
* The background color for the tab.
*/
backgroundColor(): any;
/**
* The normal text color for the tab.
*/
normalTextColor(): any;
/**
* The bold text color for the tab.
*/
boldTextColor(): any;
/**
* The name of the font used to display the tab’s contents.
*/
fontName(): string;
/**
* The size of the font used to display the tab’s contents.
*/
fontSize(): number;
/**
* Whether the font used to display the tab’s contents is antialiased.
*/
fontAntialiasing(): boolean;
/**
* The processes which will be ignored when checking whether a tab can be closed without showing a prompt.
*/
cleanCommands(): any;
/**
* Whether the title contains the device name.
*/
titleDisplaysDeviceName(): boolean;
/**
* Whether the title contains the shell path.
*/
titleDisplaysShellPath(): boolean;
/**
* Whether the title contains the tab’s size, in rows and columns.
*/
titleDisplaysWindowSize(): boolean;
/**
* Whether the title contains the settings name.
*/
titleDisplaysSettingsName(): boolean;
/**
* Whether the title contains a custom title.
*/
titleDisplaysCustomTitle(): boolean;
/**
* The tab’s custom title.
*/
customTitle(): string;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* A tab.
*/
export interface Tab {
/**
* The number of rows displayed in the tab.
*/
numberOfRows(): number;
/**
* The number of columns displayed in the tab.
*/
numberOfColumns(): number;
/**
* The currently visible contents of the tab.
*/
contents(): string;
/**
* The contents of the entire scrolling buffer of the tab.
*/
history(): string;
/**
* Whether the tab is busy running a process.
*/
busy(): boolean;
/**
* The processes currently running in the tab.
*/
processes(): any;
/**
* Whether the tab is selected.
*/
selected(): boolean;
/**
* Whether the title contains a custom title.
*/
titleDisplaysCustomTitle(): boolean;
/**
* The tab’s custom title.
*/
customTitle(): string;
/**
* The tab’s TTY device.
*/
tty(): string;
/**
* The set of settings which control the tab’s behavior and appearance.
*/
currentSettings(): any;
/**
* The cursor color for the tab.
*/
cursorColor(): any;
/**
* The background color for the tab.
*/
backgroundColor(): any;
/**
* The normal text color for the tab.
*/
normalTextColor(): any;
/**
* The bold text color for the tab.
*/
boldTextColor(): any;
/**
* The processes which will be ignored when checking whether a tab can be closed without showing a prompt.
*/
cleanCommands(): any;
/**
* Whether the title contains the device name.
*/
titleDisplaysDeviceName(): boolean;
/**
* Whether the title contains the shell path.
*/
titleDisplaysShellPath(): boolean;
/**
* Whether the title contains the tab’s size, in rows and columns.
*/
titleDisplaysWindowSize(): boolean;
/**
* Whether the title contains the file name.
*/
titleDisplaysFileName(): boolean;
/**
* The name of the font used to display the tab’s contents.
*/
fontName(): string;
/**
* The size of the font used to display the tab’s contents.
*/
fontSize(): number;
/**
* Whether the font used to display the tab’s contents is antialiased.
*/
fontAntialiasing(): boolean;
}
// CLass Extension
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export interface Application {
/**
* The settings set used for new windows.
*/
defaultSettings(): any;
/**
* The settings set used for the window created on application startup.
*/
startupSettings(): any;
}
// Records
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export interface PrintSettings {
/**
* the number of copies of a document to be printed
*/
copies(): number;
/**
* Should printed copies be collated?
*/
collating(): boolean;
/**
* the first page of the document to be printed
*/
startingPage(): number;
/**
* the last page of the document to be printed
*/
endingPage(): number;
/**
* number of logical pages laid across a physical page
*/
pagesAcross(): number;
/**
* number of logical pages laid out down a physical page
*/
pagesDown(): number;
/**
* how errors are handled
*/
errorHandling(): any;
/**
* for fax number
*/
faxNumber(): string;
/**
* for target printer
*/
targetPrinter(): string;
}
// Function options
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export interface CloseOptionalParameter {
/**
* Whether or not changes should be saved before closing.
*/
saving?: any;
/**
* The file in which to save the document.
*/
savingIn?: any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export interface SaveOptionalParameter {
/**
* The file in which to save the document.
*/
in?: any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export interface PrintOptionalParameter {
/**
* The print settings to use.
*/
withProperties?: any;
/**
* Should the application show the print dialog?
*/
printDialog?: boolean;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export interface QuitOptionalParameter {
/**
* Whether or not changed documents should be saved before closing.
*/
saving?: any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export interface CountOptionalParameter {
/**
* The class of objects to be counted.
*/
each?: any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export interface DuplicateOptionalParameter {
/**
* The location for the new object(s).
*/
to: any;
/**
* Properties to be set in the new duplicated object(s).
*/
withProperties?: any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export interface MakeOptionalParameter {
/**
* The class of the new object.
*/
new: any;
/**
* The location at which to insert the object.
*/
at?: any;
/**
* The initial contents of the object.
*/
withData?: any;
/**
* The initial values for properties of the object.
*/
withProperties?: any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export interface MoveOptionalParameter {
/**
* The new location for the object(s).
*/
to: any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export interface DoScriptOptionalParameter {
/**
* Data to be passed to the Terminal application as the command line. Deprecated; use direct parameter instead.
*/
withCommand?: any;
/**
* The tab in which to execute the command
*/
in?: any;
}
}
export interface Terminal extends Terminal.Application {
// Functions
/**
* Open a document.
* @param directParameter The file(s) to be opened.
*
*/
open(directParameter: {}, ): void;
/**
* Close a document.
* @param directParameter the document(s) or window(s) to close.
* @param option
*
*/
close(directParameter: any, option?: Terminal.CloseOptionalParameter): void;
/**
* Save a document.
* @param directParameter The document(s) or window(s) to save.
* @param option
*
*/
save(directParameter: any, option?: Terminal.SaveOptionalParameter): void;
/**
* Print a document.
* @param directParameter The file(s), document(s), or window(s) to be printed.
* @param option
*
*/
print(directParameter: {}, option?: Terminal.PrintOptionalParameter): void;
/**
* Quit the application.
* @param option
*
*/
quit(option?: Terminal.QuitOptionalParameter): void;
/**
* Return the number of elements of a particular class within an object.
* @param directParameter the object whose elements are to be counted
* @param option
* @return the number of elements
*/
count(directParameter: any, option?: Terminal.CountOptionalParameter): number;
/**
* Delete an object.
* @param directParameter the object to delete
*
*/
delete(directParameter: any, ): void;
/**
* Copy object(s) and put the copies at a new location.
* @param directParameter the object(s) to duplicate
* @param option
*
*/
duplicate(directParameter: any, option?: Terminal.DuplicateOptionalParameter): void;
/**
* Verify if an object exists.
* @param directParameter the object in question
* @return true if it exists, false if not
*/
exists(directParameter: any, ): boolean;
/**
* Make a new object.
* @param option
* @return to the new object
*/
make(option?: Terminal.MakeOptionalParameter): any;
/**
* Move object(s) to a new location.
* @param directParameter the object(s) to move
* @param option
*
*/
move(directParameter: any, option?: Terminal.MoveOptionalParameter): void;
/**
* Runs a UNIX shell script or command.
* @param directParameter The command to execute.
* @param option
* @return The tab the command was executed in.
*/
doScript(directParameter?: string, option?: Terminal.DoScriptOptionalParameter): Terminal.Tab;
/**
* Open a command an ssh, telnet, or x-man-page URL.
* @param directParameter The URL to open.
*
*/
getURL(directParameter: string, ): void;
} | the_stack |
import { Smithchart, ISmithchartLoadedEventArgs, TooltipRender } from '../../../src/smithchart/index';
import { createElement, remove, isNullOrUndefined } from '@syncfusion/ej2-base';
import { Tooltip} from '@syncfusion/ej2-svg-base';
import { MouseEvents } from '../base/events.spec';
import {profile , inMB, getMemoryProfile} from '../../common.spec';
import { SmithchartRect} from '../../../src/smithchart/utils/utils';
Smithchart.Inject(TooltipRender);
/**
* Title spec
*/
describe('Smithchart tooltip spec', () => {
beforeAll(() => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
});
describe('Tooltip spec', () => {
let id: string = 'container';
let smithchart: Smithchart;
let ele: HTMLDivElement;
let trigger: MouseEvents = new MouseEvents();
let spec: Element;
beforeAll(() => {
ele = <HTMLDivElement>createElement('div', { id: id, styles: 'height: 512px; width: 512px;' });
document.body.appendChild(ele);
smithchart = new Smithchart({
series: [{
points: [
{ resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 },
{ resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 },
{ resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 },
{ resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 },
{ resistance: 0, reactance: 0.05 }, { resistance: 0.3, reactance: 0.1 },
{ resistance: 0.3, reactance: 0.1 }, { resistance: 0.3, reactance: 0.1 },
{ resistance: 0.3, reactance: 0.1 }, { resistance: 0.5, reactance: 0.2 },
{ resistance: 1.0, reactance: 0.4 },
{ resistance: 1.5, reactance: 0.5 }, { resistance: 2.0, reactance: 0.5 },
{ resistance: 2.5, reactance: 0.4 }, { resistance: 3.5, reactance: 0.0 },
{ resistance: 4.5, reactance: -0.5 }, { resistance: 5.0, reactance: -1.0 }
],
fill: 'red',
tooltip: { visible: true},
marker: {
visible: true,
dataLabel: {
visible: true,
fill: 'red'
},
width: 10,
height: 10
}
},
],
}, '#' + id);
});
afterAll(() => {
remove(ele);
smithchart.destroy();
});
it('tooltip checking with mouse move', (done: Function) => {
smithchart.loaded = (args: ISmithchartLoadedEventArgs) => {
let element: Element = document.getElementById(smithchart.element.id + '_series0_points');
trigger.mousemoveEvent(element, 0, 0, 50, 255);
element = document.getElementById(id + '_smithchart_tooltip_div_text');
expect(element.firstChild.textContent).toBe('0 ');
expect(element.lastChild.textContent).toBe('0.05');
trigger.mousemoveEvent(element, 0, 0, 35, 255);
done();
};
smithchart.refresh();
});
it('tooltip template checking with mouse move', (done: Function) => {
smithchart.loaded = (args: ISmithchartLoadedEventArgs) => {
let element: Element = document.getElementById(smithchart.element.id + '_series0_points');
trigger.mousemoveEvent(element, 0, 0, 156, 250);
element = document.getElementById(id + '_smithchart_tooltip_divparent_template');
expect(element.firstChild.textContent).toBe('0.1');
trigger.mousemoveEvent(element, 0, 0, 35, 255);
done();
};
smithchart.series[0].tooltip.template = '<div style="border: 2px solid green;background: #a0e99680">${reactance}</div>';
smithchart.refresh();
});
it('tooltip checking with mouse up on touchend', (done: Function) => {
smithchart.loaded = (args: ISmithchartLoadedEventArgs) => {
let element: Element = document.getElementById(smithchart.element.id + '_series0_points');
smithchart.mouseEnd(<PointerEvent>trigger.onTouchEnd(element, 0, 0, 0, 0, 50, 255));
element = document.getElementById(id + '_smithchart_tooltip_div_text');
expect(element.firstChild.textContent).toBe('0 ');
expect(element.lastChild.textContent).toBe('0.05');
smithchart.mouseEnd(<PointerEvent>trigger.onTouchEnd(element, 0, 0, 0, 0, 35, 255));
//done();
};
smithchart.animationComplete = (args: Object): void => {
let tooltip: HTMLElement = document.getElementById(smithchart.element.id + '_smithchart_tooltip_div_text');
expect(tooltip == null).toBe(false);
done();
};
smithchart.series[0].tooltip.template = '';
smithchart.series[0].enableAnimation = true;
smithchart.series[0].animationDuration = '2000ms';
smithchart.refresh();
});
it('tooltip checking with mouse up on touchmove', (done: Function) => {
smithchart.loaded = (args: ISmithchartLoadedEventArgs) => {
let element: Element = document.getElementById(smithchart.element.id + '_series0_points');
smithchart.mouseEnd(<PointerEvent>trigger.onTouchMove(element, 0, 0, 0, 0, 156, 250));
//trigger.mouseupEvent(element, 0, 0, 65, 255);
element = document.getElementById(id + '_smithchart_tooltip_div_text');
// expect(element.firstChild.textContent).toBe('0.3 : ');
// expect(element.lastChild.textContent).toBe('0.1');
//smithchart.mouseEnd(<PointerEvent>trigger.onTouchMove(element, 0, 0, 0, 0, 35, 255));
done();
};
smithchart.refresh();
});
it('tooltip checking with mouse move on touchmove', (done: Function) => {
smithchart.loaded = (args: ISmithchartLoadedEventArgs) => {
let element: Element = document.getElementById(smithchart.element.id + '_series0_points');
smithchart.mouseMove(<PointerEvent>trigger.onTouchMove(element, 0, 0, 0, 0, 50, 255));
//trigger.mouseupEvent(element, 0, 0, 65, 255);
element = document.getElementById(id + '_smithchart_tooltip_div_text');
// expect(element.firstChild.textContent).toBe('0 : ');
// expect(element.lastChild.textContent).toBe('0.05');
//smithchart.mouseMove(<PointerEvent>trigger.onTouchMove(element, 0, 0, 0, 0, 35, 255));
done();
};
smithchart.refresh();
});
it('tooltip checking with template', (done: Function) => {
smithchart.loaded = (args: ISmithchartLoadedEventArgs) => {
let element: Element = document.getElementById('container_Series0_Points8_Marker8');
trigger.mousemoveEvent(element, 0, 0, 50, 255);
done();
};
smithchart.series[0].tooltipMappingName = 'reactance';
smithchart.refresh();
});
// it('tooltip checking with mouse up on touchmove', (done: Function) => {
// smithchart.loaded = (args: ISmithchartLoadedEventArgs) => {
// let element: Element = document.getElementById(smithchart.element.id + '_series0_points');
// smithchart.mouseEnd(<PointerEvent>trigger.onTouchEnd(element, 0, 0, 0, 0, 156, 250));
// //trigger.mouseupEvent(element, 0, 0, 65, 255);
// element = document.getElementById(id + '_smithchart_tooltip_div_text');
// expect(element.firstChild.textContent).toBe('0.3 : ');
// expect(element.lastChild.textContent).toBe('0.1');
// smithchart.mouseEnd(<PointerEvent>trigger.onTouchEnd(element, 0, 0, 0, 0, 35, 255));
// done();
// };
// smithchart.refresh();
// });
/* it('tooltip checking with mouse move on touchmove', (done: Function) => {
smithchart.loaded = (args: ISmithchartLoadedEventArgs) => {
let element: Element = document.getElementById(smithchart.element.id + '_series0_points');
smithchart.mouseMove(<PointerEvent>trigger.onTouchEnd(element, 0, 0, 0, 0, 50, 255));
//trigger.mouseupEvent(element, 0, 0, 65, 255);
element = document.getElementById(id + '_smithchart_tooltip_div_text');
expect(element.firstChild.textContent).toBe('0 : ');
expect(element.lastChild.textContent).toBe('0.05');
smithchart.mouseMove(<PointerEvent>trigger.onTouchEnd(element, 0, 0, 0, 0, 35, 255));
done();
};
smithchart.refresh();
});*/
it('legend checking with mouse click as togglevisibility set to true', (done: Function) => {
smithchart.loaded = (args: ISmithchartLoadedEventArgs) => {
let element: Element = document.getElementById(smithchart.element.id + '_LegendItemText0');
trigger.clickEvent(element);
done();
};
smithchart.legendSettings.visible = true;
smithchart.legendSettings.toggleVisibility = true;
smithchart.refresh();
});
it(' Second time legend checking with mouse click as togglevisibility set to true', (done: Function) => {
smithchart.loaded = (args: ISmithchartLoadedEventArgs) => {
let element: Element = document.getElementById(smithchart.element.id + '_LegendItemText0');
trigger.clickEvent(element);
done();
};
smithchart.legendSettings.visible = true;
smithchart.series[0].visibility = 'hidden';
smithchart.legendSettings.toggleVisibility = true;
smithchart.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);
});
}); | the_stack |
function path2module(path: any[]): string {
return path.map(p => p.name ? `${p.type}[${p.name}]` : p.type).join('/');
}
function opName(rawName: string): string {
if (rawName.includes('::')) {
return rawName.split('::')[1];
} else {
return rawName;
}
}
export class NodeTs {
readonly id: string;
readonly tail: string;
parent: NodeTs | undefined;
children: NodeTs[];
op: string;
attributes: string;
constructor(id: string, tail: string, op: string, attributes: string) {
this.children = [];
this.id = id;
this.tail = tail;
this.parent = undefined;
this.op = op;
this.attributes = attributes;
}
descendants(leafOnly: boolean): NodeTs[] {
// return all descendants includinng itself
const result: NodeTs[] = [];
if (!leafOnly || this.isChildless())
result.push(this);
for (const child of this.children) {
const childDesc = child.descendants(leafOnly);
if (childDesc.length > 0)
result.push(...childDesc);
}
return result;
}
isChildless(): boolean {
return this.children.length === 0;
}
isParent(): boolean {
return this.children.length > 0;
}
};
export class Edge {
readonly source: NodeTs;
readonly target: NodeTs;
readonly id: string;
constructor(source: NodeTs, target: NodeTs) {
this.source = source;
this.target = target;
this.id = JSON.stringify([this.source.id, this.target.id]);
}
};
interface NodeSummary {
name: string,
nodeCount: number,
edgeCount: number,
inputs: string[],
outputs: string[],
attributes: string,
op: string
};
export class Graph {
root: NodeTs;
nodes: NodeTs[];
edges: Edge[];
defaultExpandSet: Set<string>;
private id2idx: Map<string, number>;
private edgeId2idx: Map<string, number>;
private forwardGraph: Map<string, string[]>;
private backwardGraph: Map<string, string[]>;
private node2edge: Map<string, Edge[]>;
private mutableEdges: Map<string, Edge[][]>;
private build() {
this.id2idx.clear();
this.nodes.forEach((node, i) => {
this.id2idx.set(node.id, i);
});
this.edgeId2idx.clear();
this.edges.forEach((edge, i) => {
this.edgeId2idx.set(edge.id, i);
});
this.forwardGraph.clear();
this.backwardGraph.clear();
this.node2edge.clear();
this.edges.forEach(edge => {
if (!this.forwardGraph.has(edge.source.id))
this.forwardGraph.set(edge.source.id, []);
this.forwardGraph.get(edge.source.id)!.push(edge.target.id);
if (!this.backwardGraph.has(edge.target.id))
this.backwardGraph.set(edge.target.id, []);
this.backwardGraph.get(edge.target.id)!.push(edge.source.id);
if (!this.node2edge.has(edge.source.id))
this.node2edge.set(edge.source.id, []);
if (!this.node2edge.has(edge.target.id))
this.node2edge.set(edge.target.id, []);
this.node2edge.get(edge.source.id)!.push(edge);
this.node2edge.get(edge.target.id)!.push(edge);
});
this.root.children = this.nodes.filter(node => node.parent === undefined);
// won't set parent for these nodes, leave them as undefined
this.nodes.forEach(node => {
node.children = node.children.filter(child => this.getNodeById(child.id) !== undefined);
});
}
getNodeById(id: string): NodeTs | undefined {
const idx = this.id2idx.get(id);
if (idx === undefined) return undefined;
return this.nodes[idx];
}
getEdgeById(source: string, target: string): Edge | undefined {
const idx = this.edgeId2idx.get(JSON.stringify([source, target]));
if (idx === undefined) return undefined;
return this.edges[idx];
}
constructor(graphData: any, eliminateSidechains: boolean) {
this.id2idx = new Map<string, number>();
this.edgeId2idx = new Map<string, number>();
this.forwardGraph = new Map<string, string[]>();
this.backwardGraph = new Map<string, string[]>();
this.node2edge = new Map<string, Edge[]>();
this.root = new NodeTs('', '', '', '');
const cluster = new Map<string, NodeTs>();
const parentMap = new Map<string, string>();
this.nodes = graphData.node.map((node: any): NodeTs => {
const split = node.name.split('/');
const attr = node.hasOwnProperty('attr') ? atob(node.attr.attr.s) : '';
if (split.length === 1) {
return new NodeTs(node.name, node.name, opName(node.op), attr);
} else {
parentMap.set(node.name, split.slice(0, -1).join('/'));
// create clusters
for (let i = 1; i < split.length; ++i) {
const name = split.slice(0, i).join('/');
if (!cluster.has(name)) {
const parent = i > 1 ? split.slice(0, i - 1).join('/') : '';
const tail = split[i - 1];
cluster.set(name, new NodeTs(name, tail, '', ''));
parentMap.set(name, parent);
}
}
return new NodeTs(node.name, split.slice(-1)[0], opName(node.op), attr);
}
});
cluster.forEach(node => this.nodes.push(node));
this.nodes.forEach((node, i) => {
this.id2idx.set(node.id, i);
});
parentMap.forEach((parent, child) => {
const [childNode, parentNode] = [child, parent].map(this.getNodeById.bind(this));
if (childNode !== undefined && parentNode !== undefined) {
childNode.parent = parentNode;
parentNode.children.push(childNode);
}
});
// build edges
this.edges = [];
graphData.node.forEach((node: any) => {
if (!node.hasOwnProperty('input')) return;
const target = this.getNodeById(node.name);
if (target === undefined) return;
node.input.forEach((input: string) => {
const source = this.getNodeById(input);
if (source !== undefined) {
this.edges.push(new Edge(source, target));
}
})
})
this.build();
if (eliminateSidechains) {
this.eliminateSidechains();
}
this.defaultExpandSet = this.getDefaultExpandSet(graphData.mutable);
this.mutableEdges = this.inferMutableEdges(graphData.mutable);
}
private eliminateSidechains(): void {
const sources = this.nodes
.map(node => node.id)
.filter(id => id.startsWith('input'));
const visitedNodes = new Set(sources);
const dfsStack = sources;
while (dfsStack.length > 0) {
const u = dfsStack.pop()!;
if (this.forwardGraph.has(u)) {
this.forwardGraph.get(u)!.forEach((v: string) => {
if (!visitedNodes.has(v)) {
visitedNodes.add(v);
dfsStack.push(v);
}
});
}
}
const compoundCheck = (node: NodeTs) => {
if (node.isChildless())
return visitedNodes.has(node.id);
for (const child of node.children)
if (compoundCheck(child))
visitedNodes.add(node.id);
return visitedNodes.has(node.id);
}
compoundCheck(this.root);
this.nodes = this.nodes.filter(node => visitedNodes.has(node.id));
this.edges = this.edges.filter(edge =>
visitedNodes.has(edge.source.id) && visitedNodes.has(edge.target.id));
this.build();
}
private getDefaultExpandSet(graphDataMutable: any): Set<string> {
// if multiple, only expand first
const whitelistModuleList = Object.values(graphDataMutable)
.filter(Boolean)
.map((paths: any) => path2module(paths[0]));
const whitelistModule = new Set(whitelistModuleList);
const result = new Set<string>();
const dfs = (node: NodeTs): number => {
// node with mutableCount greater than 0 won't be collapsed
let mutableCount = 0;
if (node.id === '') {
// root node
mutableCount++;
} else if (whitelistModule.has(node.id)) {
mutableCount++;
} else if (node.parent !== undefined && whitelistModule.has(node.parent.id)) {
mutableCount++;
}
mutableCount += node.children.map(child => dfs(child)).reduce((a, b) => a + b, 0);
if (mutableCount > 0 && node.isParent())
result.add(node.id);
return mutableCount;
};
dfs(this.root);
return result;
}
private inferMutableModule(moduleName: string): Edge[][] {
let inputs: string[] | undefined = undefined;
let listConstructNode: string | undefined = undefined;
const moduleNode = this.getNodeById(moduleName);
if (moduleNode === undefined) return [];
for (const node of moduleNode.children)
if (node.op === 'ListConstruct') {
inputs = this.backwardGraph.get(node.id);
listConstructNode = node.id;
break;
}
if (inputs === undefined || listConstructNode === undefined)
return [];
return inputs.map((input: string): Edge[] => {
const visitedNodes = new Set<string>();
const edgeSet: Edge[] = [];
const dfs = (node: string, backward: boolean) => {
const nodeData = this.getNodeById(node)!;
if (visitedNodes.has(node)) return;
visitedNodes.add(node);
if (nodeData.parent === undefined || !nodeData.parent.id.startsWith(moduleName)) {
// in another module now
return;
}
const g = backward ? this.backwardGraph : this.forwardGraph;
const glist = g.get(node);
if (glist !== undefined) {
glist
.forEach((to: string) => {
edgeSet.push(backward ?
this.getEdgeById(to, node)! :
this.getEdgeById(node, to)!);
dfs(to, backward);
});
}
};
edgeSet.push(this.getEdgeById(input, listConstructNode!)!);
dfs(input, true);
visitedNodes.clear();
dfs(listConstructNode!, false);
return edgeSet;
});
}
private inferMutableEdges(graphDataMutable: any): Map<string, Edge[][]> {
const result = new Map<string, Edge[][]>();
Object.entries(graphDataMutable).forEach(obj => {
const [key, paths] = obj;
const modules = (paths as any[]).map(path2module);
const moduleEdge = modules.map(this.inferMutableModule.bind(this));
const edges: Edge[][] = [];
for (let i = 0; ; ++i) {
if (moduleEdge.filter(me => i < me.length).length === 0)
break;
edges.push([]);
moduleEdge
.filter(me => i < me.length)
.forEach(me => edges[i].push(...me[i]));
}
result.set(key, edges);
});
return result;
}
private connectedEdges(node: string): Edge[] {
const result = this.node2edge.get(node);
if (result === undefined)
return [];
return result;
}
nodeSummary(node: NodeTs | string): NodeSummary | undefined {
if (typeof node === 'string') {
const nodeData = this.getNodeById(node);
if (nodeData === undefined) return undefined;
return this.nodeSummary(nodeData);
}
const descendants = node.descendants(false);
const descendantSet = new Set(descendants.map(node => node.id));
const inputs = new Set<string>();
const outputs = new Set<string>();
let domesticEdges = 0;
for (const edge of this.edges) {
const [source, target] = [edge.source.id, edge.target.id];
if (descendantSet.has(target) && !descendantSet.has(source))
inputs.add(source);
if (descendantSet.has(source) && !descendantSet.has(target))
outputs.add(target);
if (descendantSet.has(source) && descendantSet.has(target))
domesticEdges++;
}
return {
name: node.id,
nodeCount: descendants.length,
edgeCount: domesticEdges,
inputs: Array.from(inputs),
outputs: Array.from(outputs),
attributes: node.attributes,
op: node.op
}
}
weightFromMutables(mutable: any): Map<string, number> {
const elemWeight = new Map<string, number>();
Object.entries(mutable).forEach(entry => {
const key = entry[0];
const weights = entry[1] as number[];
this.mutableEdges.get(key)!.forEach((edges: any, i: number) => {
edges.forEach((edge: any) => {
if (elemWeight.has(edge.id)) {
elemWeight.set(edge.id, elemWeight.get(edge.id)! + weights[i]);
} else {
elemWeight.set(edge.id, weights[i]);
}
})
});
});
this.nodes.forEach(node => {
const edges = this.connectedEdges(node.id);
const relatedEdges = edges.filter(edge => elemWeight.has(edge.id));
if (relatedEdges.length > 0) {
if (relatedEdges.length < edges.length) {
elemWeight.set(node.id, 1.);
} else {
// all related edge
const nw = edges.map(edge => elemWeight.get(edge.id)!)
.reduce((a, b) => Math.max(a, b));
elemWeight.set(node.id, nw);
}
}
});
elemWeight.forEach((v, k) => elemWeight.set(k, Math.min(v, 1.)));
// set compound weight
const gatherWeightsFromChildren = (node: NodeTs): number | undefined => {
if (node.isParent()) {
const childrenWeights =
node.children.map(gatherWeightsFromChildren)
.filter(val => val !== undefined);
if (childrenWeights.length > 0) {
const nw = childrenWeights.reduce((a, b) => Math.max(a!, b!));
elemWeight.set(node.id, nw!);
return nw;
} else {
return undefined;
}
} else {
return elemWeight.get(node.id);
}
};
gatherWeightsFromChildren(this.root);
return elemWeight;
}
}; | the_stack |
namespace LiteMol.Plugin.Views.Transform.Density {
"use strict";
import Transformer = Bootstrap.Entity.Transformer
const IsoValue = (props: { view: Transform.ControllerBase<any>, onChangeValue: (v: number)=> void, onChangeType: (v: Bootstrap.Visualization.Density.IsoValueType)=> void, min: number, max: number, value: number, isSigma: boolean }) =>
<Controls.ExpandableGroup
select={<Controls.Slider label={props.isSigma ? 'Iso Value (\u03C3)' : 'Iso Value'} onChange={props.onChangeValue} min={props.min} max={props.max} value={props.value} step={0.001} />}
expander={<Controls.ControlGroupExpander isExpanded={props.view.getPersistentState('showIsoValueType', false)} onChange={e => props.view.setPersistentState('showIsoValueType', e) } />}
options={[<Controls.Toggle onChange={v => props.onChangeType(v ? Bootstrap.Visualization.Density.IsoValueType.Sigma : Bootstrap.Visualization.Density.IsoValueType.Absolute) } value={props.isSigma} label='Relative (\u03C3)' />]}
isExpanded={ props.view.getPersistentState('showIsoValueType', false) }
/>
function isoValueAbsoluteToSigma(data: Core.Formats.Density.Data, value: number, min: number, max: number) {
let ret = (value - data.valuesInfo.mean) / data.valuesInfo.sigma;
if (ret > max) return max;
if (ret < min) return min;
return ret;
}
function isoValueSigmaToAbsolute(data: Core.Formats.Density.Data, value: number) {
let ret = data.valuesInfo.mean + value * data.valuesInfo.sigma;
if (ret > data.valuesInfo.max) return data.valuesInfo.max;
if (ret < data.valuesInfo.min) return data.valuesInfo.min;
return ret;
}
export class ParseData extends Transform.ControllerBase<Bootstrap.Components.Transform.Controller<Transformer.Density.ParseDataParams>> {
protected renderControls() {
let params = this.params;
let round = Bootstrap.Utils.round;
if (this.isUpdate) {
let data = (this.controller.entity as Bootstrap.Entity.Density.Data).props.data;
return <div>
<Controls.RowText label='Format' value={params.format!.name} />
<Controls.RowText label='Sigma' value={round(data.valuesInfo.sigma, 3)} />
<Controls.RowText label='Mean' value={round(data.valuesInfo.mean, 3)} />
<Controls.RowText label='Value Range' value={`[${round(data.valuesInfo.min, 3)}, ${round(data.valuesInfo.max, 3)}]`} />
</div>;
}
return <div>
<Controls.OptionsGroup options={LiteMol.Core.Formats.Density.SupportedFormats.All} caption={s => s.name} current={params.format}
onChange={(o) => this.updateParams({ format: o }) } label='Format' />
</div>
}
}
export class CreateVisual extends Transform.ControllerBase<Bootstrap.Components.Transform.DensityVisual<Transformer.Density.CreateVisualParams, 'style'>> {
private surface() {
const data = Bootstrap.Tree.Node.findClosestNodeOfType(this.transformSourceEntity, [Bootstrap.Entity.Density.Data]) as Bootstrap.Entity.Density.Data;
const params = this.params.style.params as Bootstrap.Visualization.Density.Params;
const isSigma = params.isoValueType !== Bootstrap.Visualization.Density.IsoValueType.Absolute;
const values = data.props.data.valuesInfo;
const min = isSigma
? (values.min - values.mean) / values.sigma
: values.min;
const max = isSigma
? (values.max - values.mean) / values.sigma
: values.max;
return <IsoValue
view={this}
onChangeValue={v => this.controller.updateStyleParams({ isoValue: v })}
onChangeType={v => {
if (v === params.isoValueType) return;
if (v === Bootstrap.Visualization.Density.IsoValueType.Absolute) {
this.controller.updateStyleParams({ isoValue: isoValueSigmaToAbsolute(data.props.data, params.isoValue), isoValueType: v });
} else {
this.controller.updateStyleParams({ isoValue: isoValueAbsoluteToSigma(data.props.data, params.isoValue, -5, 5), isoValueType: v });
}
}}
min={min} max={max} isSigma={isSigma} value={params.isoValue} />;
}
private colors() {
let params = this.params.style!.params as Bootstrap.Visualization.Density.Params;
let theme = this.params.style!.theme!;
let uc = theme.colors!.get('Uniform');
let uniform = <Controls.ToggleColorPicker key={'Uniform'} label='Color' color={uc} onChange={c => this.controller.updateThemeColor('Uniform', c) } />
let controls: JSX.Element[] = [];
// theme.colors!
// .filter((c, n) => n !== 'Uniform')
// .map((c, n) => <Controls.ToggleColorPicker key={n} label={n!} color={c!} onChange={c => this.controller.updateThemeColor(n!, c) } />).toArray();
controls.push(<TransparencyControl definition={theme.transparency!} onChange={d => this.controller.updateThemeTransparency(d) } />);
//controls.push(<Controls.Slider label='Smoothing' onChange={v => this.controller.updateStyleParams({ smoothing: v })} min={0} max={10} step={1} value={visualParams.smoothing!} title='Number of laplacian smoothing itrations.' />);
controls.push(<Controls.Toggle onChange={v => this.controller.updateStyleParams({ isWireframe: v }) } value={params.isWireframe!} label='Wireframe' />)
let showThemeOptions = this.getPersistentState('showThemeOptions', false);
return <Controls.ExpandableGroup
select={uniform}
expander={<Controls.ControlGroupExpander isExpanded={showThemeOptions} onChange={e => this.setPersistentState('showThemeOptions', e) } />}
options={controls}
isExpanded={showThemeOptions} />;
}
protected renderControls() {
return <div>
{this.surface()}
{this.colors()}
</div>
}
}
export class CreateVisualBehaviour extends Transform.ControllerBase<Bootstrap.Components.Transform.DensityVisual<Transformer.Density.CreateVisualBehaviourParams, 'style'>> {
private surface() {
let data = Bootstrap.Tree.Node.findClosestNodeOfType(this.transformSourceEntity, [Bootstrap.Entity.Density.Data]) as Bootstrap.Entity.Density.Data;
let params = this.params as Transformer.Density.CreateVisualBehaviourParams;
let visualParams = params.style.params;
let isSigma = visualParams.isoValueType !== Bootstrap.Visualization.Density.IsoValueType.Absolute;
return <IsoValue
view={this}
onChangeValue={v => this.controller.updateStyleParams({ isoValue: v })}
onChangeType={v => {
if (v === visualParams.isoValueType) return;
if (v === Bootstrap.Visualization.Density.IsoValueType.Absolute) {
this.controller.updateStyleParams({ isoValue: isoValueSigmaToAbsolute(data.props.data, visualParams.isoValue), isoValueType: v });
} else {
this.controller.updateStyleParams({ isoValue: isoValueAbsoluteToSigma(data.props.data, visualParams.isoValue, params.isoSigmaMin, params.isoSigmaMax), isoValueType: v });
}
}}
min={isSigma ? params.isoSigmaMin : data.props.data.valuesInfo.min}
max={isSigma ? params.isoSigmaMax : data.props.data.valuesInfo.max}
isSigma={isSigma}
value={visualParams.isoValue} />;
}
private colors() {
let params = this.params.style.params;
let theme = this.params.style.theme;
let uc = theme.colors!.get('Uniform');
let uniform = <Controls.ToggleColorPicker key={'Uniform'} label='Color' color={uc} onChange={c => this.controller.updateThemeColor('Uniform', c) } />
let controls = [];
// theme.colors!
// .filter((c, n) => n !== 'Uniform')
// .map((c, n) => <Controls.ToggleColorPicker key={n} label={n!} color={c!} onChange={c => this.controller.updateThemeColor(n!, c) } />).toArray();
controls.push(<TransparencyControl definition={theme.transparency!} onChange={d => this.controller.updateThemeTransparency(d) } />);
//controls.push(<Controls.Slider label='Smoothing' onChange={v => this.controller.updateStyleParams({ smoothing: v })} min={0} max={10} step={1} value={visualParams.smoothing!} title='Number of laplacian smoothing itrations.' />);
controls.push(<Controls.Toggle onChange={v => this.controller.updateStyleParams({ isWireframe: v }) } value={params.isWireframe!} label='Wireframe' />)
let showThemeOptions = this.getPersistentState('showThemeOptions', false);
return <Controls.ExpandableGroup
select={uniform}
expander={<Controls.ControlGroupExpander isExpanded={showThemeOptions} onChange={e => this.setPersistentState('showThemeOptions', e) } />}
options={controls}
isExpanded={showThemeOptions} />;
}
private show() {
const selLabel = 'Around Selection';
const allLabel = 'Everything';
let params = this.params as Transformer.Density.CreateVisualBehaviourParams;
return <Controls.OptionsGroup
options={[selLabel, allLabel]}
caption={s => s}
current={params.showFull ? allLabel : selLabel }
onChange={(o) => this.autoUpdateParams({ showFull: o === allLabel }) }
label='Show' />
}
protected renderControls() {
let params = this.params as Transformer.Density.CreateVisualBehaviourParams;
return <div>
{this.surface()}
{this.colors()}
{this.show()}
{!params.showFull
? <Controls.Slider label='Radius' onChange={v => this.autoUpdateParams({ radius: v })}
min={params.minRadius !== void 0 ? params.minRadius : 0} max={params.maxRadius !== void 0 ? params.maxRadius : 10} step={0.005} value={params.radius} />
: void 0 }
</div>
}
}
} | the_stack |
namespace correction {
type EditOperation = 'insert' | 'delete' | 'match' | 'substitute' | 'transpose-start' | 'transpose-end' | 'transpose-insert' | 'transpose-delete';
/**
* Represents the lowest-level unit for comparison during edit-distance calculations.
*/
export interface EditToken<TUnit> {
key: TUnit;
}
// A semi-optimized 'online'/iterative Damerau-Levenshtein calculator with the following features:
// - may add new character to the 'input' string or to the 'match' string, reusing all old calculations efficiently.
// - allows a 'focused' evaluation that seeks if the edit distance is within a specific range. Designed for use in match-searching,
// where we want to find the 'closest' matching strings in a lexicon.
// - towards such a match-searching algorithm/heuristic: should nothing be found within that range, all prior calculations may be reused
// to search across the lexicon with an incremented edit distance.
// - minimized memory footprint: O(m) memory footprint (where m = length of 'input' string), rather than O(mn) (where n = length of 'match' string)
// - guaranteed to use a smaller footprint than DiagonalizedIterativeDamerauLevenshteinCalculation.
//
// In short: Used to optimize calculations for low edit-distance checks, then expanded if/as necessary
// if a greater edit distance is requested.
//
// Reference: https://en.wikipedia.org/wiki/Wagner%E2%80%93Fischer_algorithm#Possible_modifications
// - Motivating statement: "if we are only interested in the distance if it is smaller than a threshold..."
export class ClassicalDistanceCalculation<TUnit = string, TInput extends EditToken<TUnit> = EditToken<TUnit>, TMatch extends EditToken<TUnit> = EditToken<TUnit>> {
/**
* Stores ONLY the computed diagonal elements, nothing else.
*
* Mapped as seen in the example below (with a diagonal of width 1):
* ```
* MAX | MAX | MAX | MAX | MAX | ...
* MAX | 0 | 1 | 2 | 3 | ... >
* MAX | 1 | a | b | - | ... ====>> | - | a | b |
* MAX | 2 | c | d | e | ... > | c | d | e |
* MAX | 3 | - | f | g | ... | f | g | ... |
* ... | ... | ... | ... | ... | ... | ... | ... | ... |
* ```
*
* Any "`-`" entries are undefined, as they lie outside of the diagonal under consideration.
*
* Things of note:
* - The entry where row index = col index will always lie at the center of the row's array.
* - For each +1 increase in row index, the row's entries are (logically) shifted by -1 in order to make this happen.
* - As all of the MAX entries and numerical entries above are fixed, known values, they are not represented here.
*/
resolvedDistances: number[][];
/**
* Specifies how far off-diagonal calculations should be performed. A value of 0 only evaluates cells with matching
* row and column indicies.
*
* The resulting value from .getFinalCost() is only guaranteed correct if it is less than or equal to this value.
* Otherwise, this object represents a heuristic that _may_ overestimate the true edit distance. Note that it will
* never underestimate.
*/
diagonalWidth: number = 2; // TODO: Ideally, should start at 1... but we'll start at 2 for now
// as a naive workaround for multi-char transform limitations.
// The sequence of characters input so far.
inputSequence: TInput[] = [];
matchSequence: TMatch[] = [];
constructor();
constructor(other: ClassicalDistanceCalculation<TUnit, TInput, TMatch>);
constructor(other?: ClassicalDistanceCalculation<TUnit, TInput, TMatch>) {
if(other) {
// Clone class properties.
let rowCount = other.resolvedDistances.length;
this.resolvedDistances = Array(rowCount);
for(let r = 0; r < rowCount; r++) {
this.resolvedDistances[r] = Array.from(other.resolvedDistances[r]);
}
this.inputSequence = Array.from(other.inputSequence);
this.matchSequence = Array.from(other.matchSequence);
this.diagonalWidth = other.diagonalWidth;
} else {
this.resolvedDistances = [];
}
}
private getTrueIndex(r: number, c: number, width: number): {row: number, col: number, sparse: boolean} {
let retVal = {
row: r,
col: c - r + width,
sparse: false
}
if(retVal.col < 0 || retVal.col > 2 * width) {
retVal.sparse = true;
}
return retVal;
}
private getCostAt(i: number, j: number, width: number = this.diagonalWidth): number {
// Check for and handle the set of fixed-value virtualized indices.
if(i < 0 || j < 0) {
if(i == -1 && j >= -1) {
return j+1;
} else if(j == -1 && i >= -1) {
return i+1;
}
return Number.MAX_VALUE;
}
let index = this.getTrueIndex(i, j, width);
return index.sparse ? Number.MAX_VALUE : this.resolvedDistances[index.row][index.col];
}
/**
* Noting the above link's statement prefixed "By examining diagonals instead of rows, and by using lazy evaluation...",
* this function will return the actual edit distance between the strings, temporarily increasing the computed
* diagonal's size if necessary.
*
* Does not actually mutate the instance.
*/
getFinalCost(): number {
let buffer = this as ClassicalDistanceCalculation<TUnit, TInput, TMatch>;
let val = buffer.getHeuristicFinalCost();
while(val > buffer.diagonalWidth) {
// A consequence of treating this class as immutable.
buffer = buffer.increaseMaxDistance();
val = buffer.getHeuristicFinalCost();
}
return val;
}
/**
* Returns this instance's computed edit distance. If greater than the diagonal's width value, note that it may be an overestimate.
*/
getHeuristicFinalCost(): number {
return this.getCostAt(this.inputSequence.length-1, this.matchSequence.length-1);
}
/**
* Returns `true` if the represented edit distance is less than or equal to the specified threshold, minimizing the amount of calculations
* needed to meet the specified limit.
*
* Does not mutate the instance.
* @param threshold
*/
hasFinalCostWithin(threshold: number): boolean {
let buffer = this as ClassicalDistanceCalculation<TUnit, TInput, TMatch>;
let val = buffer.getHeuristicFinalCost();
let guaranteedBound = this.diagonalWidth;
do {
// val will never exceed the length of the longer string, no matter how large the threshold.
if(val <= threshold) {
return true;
} else if(guaranteedBound < threshold) {
buffer = buffer.increaseMaxDistance();
guaranteedBound++;
val = buffer.getHeuristicFinalCost();
} else {
break;
}
} while(true);
return false;
}
/**
* Determines the edit path used to obtain the optimal cost, distinguishing between zero-cost
* substitutions ('match' operations) and actual substitutions.
* @param row
* @param col
*/
public editPath(row: number = this.inputSequence.length - 1, col: number = this.matchSequence.length - 1): EditOperation[] {
let currentCost = this.getCostAt(row, col);
let ops: EditOperation[] = null;
let parent: [number, number] = null;
let insertParentCost = this.getCostAt(row, col-1);
let deleteParentCost = this.getCostAt(row-1, col);
let substitutionParentCost = this.getCostAt(row-1, col-1);
let [lastInputIndex, lastMatchIndex] = ClassicalDistanceCalculation.getTransposeParent(this, row, col);
if(lastInputIndex >= 0 && lastMatchIndex >= 0) {
// OK, a transposition source is quite possible. Still need to do more vetting, to be sure.
let expectedCost = 1;
// This transposition includes either 'transpose-insert' or 'transpose-delete' operations.
ops = ['transpose-start']; // always needs a 'start'.
if(lastInputIndex != row-1) {
let count = row - lastInputIndex - 1;
ops = ops.concat( Array(count).fill('transpose-delete') );
expectedCost += count;
} else {
let count = col - lastMatchIndex - 1;
ops = ops.concat( Array(count).fill('transpose-insert') );
expectedCost += count;
}
ops.push('transpose-end');
// Double-check our expectations.
if(this.getCostAt(lastInputIndex-1, lastMatchIndex-1) != currentCost - expectedCost) {
ops = null;
}
parent = [lastInputIndex-1, lastMatchIndex-1];
}
if(ops) {
// bypass the ladder.
} else if(substitutionParentCost == currentCost - 1) {
ops = ['substitute'];
parent = [row-1, col-1];
} else if(insertParentCost == currentCost - 1) {
ops = ['insert'];
parent = [row, col-1];
} else if(deleteParentCost == currentCost - 1) {
ops = ['delete'];
parent = [row-1, col];
} else { //if(substitutionParentCost == currentCost) {
ops = ['match'];
parent = [row-1, col-1];
}
// Recursively build the edit path.
if(parent[0] >= 0 && parent[1] >= 0) {
return this.editPath(parent[0], parent[1]).concat(ops);
} else {
if(parent[0] > -1) {
// There are initial deletions.
return Array(parent[0]+1).fill('delete').concat(ops);
} else if(parent[1] > -1) {
// There are initial insertions.
return Array(parent[1]+1).fill('insert').concat(ops);
} else {
return ops;
}
}
}
private static getTransposeParent<TUnit, TInput extends EditToken<TUnit>, TMatch extends EditToken<TUnit>>(
buffer: ClassicalDistanceCalculation<TUnit, TInput, TMatch>,
r: number,
c: number
): [number, number] {
// Block any transpositions where the tokens are identical.
// Other operations will be cheaper. Also, block cases where 'parents' are impossible.
if(r < 0 || c < 0 || buffer.inputSequence[r].key == buffer.matchSequence[c].key) {
return [-1, -1];
}
// Transposition checks
let lastInputIndex = -1;
for(let i = r-1; i >= 0; i--) {
if(buffer.inputSequence[i].key == buffer.matchSequence[c].key) {
lastInputIndex = i;
break;
}
}
let lastMatchIndex = -1;
for(let i = c-1; i >= 0; i--) {
if(buffer.matchSequence[i].key == buffer.inputSequence[r].key) {
lastMatchIndex = i;
break;
}
}
return [lastInputIndex, lastMatchIndex];
}
private static initialCostAt<TUnit, TInput extends EditToken<TUnit>, TMatch extends EditToken<TUnit>>(
buffer: ClassicalDistanceCalculation<TUnit, TInput, TMatch>,
r: number,
c: number,
insertCost?: number,
deleteCost?: number) {
var baseSubstitutionCost = buffer.inputSequence[r].key == buffer.matchSequence[c].key ? 0 : 1;
var substitutionCost: number = buffer.getCostAt(r-1, c-1) + baseSubstitutionCost;
var insertionCost: number = insertCost || buffer.getCostAt(r, c-1) + 1; // If set meaningfully, will never equal zero.
var deletionCost: number = deleteCost || buffer.getCostAt(r-1, c) + 1; // If set meaningfully, will never equal zero.
var transpositionCost: number = Number.MAX_VALUE
if(r > 0 && c > 0) { // bypass when transpositions are known to be impossible.
let [lastInputIndex, lastMatchIndex] = ClassicalDistanceCalculation.getTransposeParent(buffer, r, c);
transpositionCost = buffer.getCostAt(lastInputIndex-1, lastMatchIndex-1) + (r - lastInputIndex - 1) + 1 + (c - lastMatchIndex - 1);
}
return Math.min(substitutionCost, deletionCost, insertionCost, transpositionCost);
}
getSubset(inputLength: number, matchLength: number): ClassicalDistanceCalculation<TUnit, TInput, TMatch> {
let trimmedInstance = new ClassicalDistanceCalculation(this);
if(inputLength > this.inputSequence.length || matchLength > this.matchSequence.length) {
throw "Invalid dimensions specified for trim operation";
}
// Trim our tracked input & match sequences.
trimmedInstance.inputSequence.splice(inputLength);
trimmedInstance.matchSequence.splice(matchLength);
// Major index corresponds to input length.
trimmedInstance.resolvedDistances.splice(inputLength);
// The real fun: trimming off columns. (Minor index, corresponds to match length)
let finalTrueIndex = this.getTrueIndex(inputLength-1, matchLength-1, this.diagonalWidth);
// The diagonal index increases as the row index decreases.
for(let diagonalIndex = finalTrueIndex.col; diagonalIndex <= 2 * this.diagonalWidth; diagonalIndex++) {
let row = finalTrueIndex.row - (diagonalIndex - finalTrueIndex.col);
if(row < 0) {
break;
}
if(diagonalIndex < 0) {
trimmedInstance.resolvedDistances[row] = Array(2 * trimmedInstance.diagonalWidth + 1).fill(Number.MAX_VALUE);
} else {
let newCount = 2 * this.diagonalWidth - diagonalIndex;
let keptEntries = trimmedInstance.resolvedDistances[row].splice(0, diagonalIndex+1);
let newEntries = Array(newCount).fill(Number.MAX_VALUE);
trimmedInstance.resolvedDistances[row] = keptEntries.concat(newEntries);
}
}
return trimmedInstance;
}
private static forDiagonalOfAxis(diagonalWidth: number, centerIndex: number, axisCap: number, closure: (axisIndex: number, diagIndex: number) => void) {
let diagonalCap = axisCap - centerIndex < diagonalWidth ? axisCap - centerIndex + diagonalWidth : 2 * diagonalWidth;
let startOffset = centerIndex - diagonalWidth; // The axis's index for diagonal entry 0. May be negative.
let diagonalStart = startOffset < 0 ? 0 : startOffset;
for(let diagonalIndex = diagonalStart - startOffset; diagonalIndex <= diagonalCap; diagonalIndex++) {
closure(startOffset + diagonalIndex, diagonalIndex);
}
}
// Inputs add an extra row / first index entry.
addInputChar(token: TInput): ClassicalDistanceCalculation<TUnit, TInput, TMatch> {
let returnBuffer = new ClassicalDistanceCalculation(this);
let r = returnBuffer.inputSequence.length;
returnBuffer.inputSequence.push(token);
// Insert a row, even if we don't actually do anything with it yet.
// Initialize all entries with Number.MAX_VALUE, as `undefined` use leads to JS math issues.
let row = Array(2 * returnBuffer.diagonalWidth + 1).fill(Number.MAX_VALUE);
returnBuffer.resolvedDistances[r] = row;
// If there isn't a 'match' entry yet, there are no values to compute. Exit immediately.
if(returnBuffer.matchSequence.length == 0) {
return returnBuffer;
}
ClassicalDistanceCalculation.forDiagonalOfAxis(returnBuffer.diagonalWidth, r, returnBuffer.matchSequence.length - 1, function(c, diagIndex) {
row[diagIndex] = ClassicalDistanceCalculation.initialCostAt(returnBuffer, r, c);
});
return returnBuffer;
}
addMatchChar(token: TMatch): ClassicalDistanceCalculation<TUnit, TInput, TMatch> {
let returnBuffer = new ClassicalDistanceCalculation(this);
let c = returnBuffer.matchSequence.length;
returnBuffer.matchSequence.push(token);
// If there isn't a 'match' entry yet, there are no values to compute. Exit immediately.
if(returnBuffer.inputSequence.length == 0) {
return returnBuffer;
}
ClassicalDistanceCalculation.forDiagonalOfAxis(returnBuffer.diagonalWidth, c, returnBuffer.inputSequence.length - 1, function(r, diagIndex) {
var row = returnBuffer.resolvedDistances[r];
// Since diagIndex is from the perspective of the row, it must be inverted to properly index the column.
row[2 * returnBuffer.diagonalWidth - diagIndex] = ClassicalDistanceCalculation.initialCostAt(returnBuffer, r, c);
});
return returnBuffer;
}
public increaseMaxDistance(): ClassicalDistanceCalculation<TUnit, TInput, TMatch> {
let returnBuffer = new ClassicalDistanceCalculation(this);
returnBuffer.diagonalWidth++;
if(returnBuffer.inputSequence.length < 1 || returnBuffer.matchSequence.length < 1) {
return returnBuffer;
}
// An abstraction of the common aspects of transposition handling during diagonal extensions.
function forPossibleTranspositionsInDiagonal(startPos: number, fixedChar: TUnit, lookupString: EditToken<TUnit>[], closure: (axisIndex: number, diagIndex: number) => void) {
let diagonalCap = 2 * (returnBuffer.diagonalWidth - 1); // The maximum diagonal index permitted
let axisCap = lookupString.length - 1; // The maximum index supported by the axis of iteration
// Ensures that diagonal iteration only occurs within the axis's supported range
diagonalCap = diagonalCap < axisCap - startPos ? diagonalCap : axisCap - startPos;
// Iterate within the diagonal and call our closure for any potential transpositions.
for(let diagonalIndex = 0; diagonalIndex <= diagonalCap; diagonalIndex++) {
if(fixedChar == lookupString[startPos + diagonalIndex].key) {
closure(startPos + diagonalIndex, diagonalIndex);
}
}
}
for(let r = 0; r < returnBuffer.inputSequence.length; r++) {
let leftCell = Number.MAX_VALUE;
let c = r - returnBuffer.diagonalWidth // External index of the left-most entry, which we will now calculate.
if(c >= 0) {
// If c == 0, cell is at edge, thus a known value for insertions exists.
// Base cost: r+1, +1 for inserting.
let insertionCost = c == 0 ? r + 2 : Number.MAX_VALUE;
// compute new left cell
leftCell = ClassicalDistanceCalculation.initialCostAt(returnBuffer, r, c, insertionCost, undefined);
let addedCost = leftCell;
// daisy-chain possible updates
// cell (r, c+1): new insertion source
if(c < returnBuffer.matchSequence.length-1) {
// We propagate the new added cost (via insertion) to the old left-most cell, which is one to our right.
ClassicalDistanceCalculation.propagateUpdateFrom(returnBuffer, r, c+1, addedCost+1, 0);
// Only possible if insertions are also possible AND more conditions are met.
// cells (r+2, * > c+2): new transposition source
let transposeRow = r+2;
if(r+2 < this.inputSequence.length) { // Row to check for transposes must exist.
let rowChar = returnBuffer.inputSequence[r+1].key;
// First possible match in input could be at index c + 2, which adjusts col c+2's cost. Except that entry in r+2
// doesn't exist yet - so we start with c+3 instead.
forPossibleTranspositionsInDiagonal(c + 3, rowChar, returnBuffer.matchSequence, function(axisIndex, diagIndex) {
// Because (r+2, c+3) is root, not (r+2, c+2). Min cost of 2.
ClassicalDistanceCalculation.propagateUpdateFrom(returnBuffer, transposeRow, axisIndex, addedCost + diagIndex + 2, diagIndex);
});
}
}
}
let rightCell = Number.MAX_VALUE;
c = r + returnBuffer.diagonalWidth;
if(c < returnBuffer.matchSequence.length) {
// If r == 0, cell is at edge, thus a known value for insertions exists.
// Base cost: c+1, +1 for inserting.
let deletionCost = r == 0 ? c + 2 : Number.MAX_VALUE;
// the current row wants to use adjusted diagonal width; we must specify use of the old width & its mapping instead.
var insertionCost: number = returnBuffer.getCostAt(r, c-1, this.diagonalWidth) + 1;
// compute new right cell
rightCell = ClassicalDistanceCalculation.initialCostAt(returnBuffer, r, c, insertionCost, deletionCost);
let addedCost = rightCell;
// daisy-chain possible updates
// cell (r+1, c): new deletion source
if(r < returnBuffer.inputSequence.length - 1) {
// We propagate the new added cost (via deletion) to the old right-most cell, which is one to our right.
ClassicalDistanceCalculation.propagateUpdateFrom(returnBuffer, r+1, c, addedCost + 1, 2 * this.diagonalWidth);
// Only possible if deletions are also possible AND more conditions are met.
// cells(* > r+2, c+2): new transposition source
let transposeCol = c+2;
if(c+2 < this.matchSequence.length) { // Row to check for transposes must exist.
let colChar = returnBuffer.matchSequence[r+1].key;
// First possible match in input could be at index r + 2, which adjusts row r+2's cost. Except that entry in c+2
// doesn't exist yet - so we start with r+3 instead.
forPossibleTranspositionsInDiagonal(r+3, colChar, returnBuffer.inputSequence, function(axisIndex, diagIndex) {
let diagColIndex = 2 * (returnBuffer.diagonalWidth - 1) - diagIndex;
// Because (r+3, c+2) is root, not (r+2, c+2). Min cost of 2.
ClassicalDistanceCalculation.propagateUpdateFrom(returnBuffer, axisIndex, transposeCol, addedCost + diagIndex + 2, diagColIndex);
});
}
}
}
// Constructs the final expanded diagonal for the row.
returnBuffer.resolvedDistances[r] = [leftCell].concat(returnBuffer.resolvedDistances[r], rightCell);
}
return returnBuffer;
}
private static propagateUpdateFrom<TUnit, TInput extends EditToken<TUnit>, TMatch extends EditToken<TUnit>>(
buffer: ClassicalDistanceCalculation<TUnit, TInput, TMatch>,
r: number,
c: number,
value: number,
diagonalIndex: number) {
// Note: this function does not actually need the `c` parameter!
// That said, it's very useful when tracing stack traces & debugging.
if(value < buffer.resolvedDistances[r][diagonalIndex]) {
buffer.resolvedDistances[r][diagonalIndex] = value;
} else {
return
}
let internalRow = r < buffer.inputSequence.length - 1;
let internalCol = c < buffer.matchSequence.length - 1;
// We have to compensate for the current & following rows not having been expanded yet.
if(diagonalIndex < 2 * (buffer.diagonalWidth - 1) && internalCol) {
// We've inserted to the left of an existing calculation - check for propagation via insertion.
let updateCost = value + 1;
this.propagateUpdateFrom(buffer, r, c+1, updateCost, diagonalIndex+1);
}
if(diagonalIndex > 0 && internalRow) {
// We've inserted above an existing calculation - check for propagation via deletion
let updateCost = value + 1
this.propagateUpdateFrom(buffer, r+1, c, updateCost, diagonalIndex-1);
}
// If both, check for propagation via substitution and possible transpositions
if(internalRow && internalCol) {
let updateCost = value + (buffer.inputSequence[r+1].key == buffer.matchSequence[c+1].key ? 0 : 1);
this.propagateUpdateFrom(buffer, r+1, c+1, updateCost, diagonalIndex);
// Propagating transpositions (only possible if 'internal'.)
let nextInputIndex = -1;
for(let i = r+2; i < buffer.inputSequence.length; i++) {
if(buffer.inputSequence[i].key == buffer.matchSequence[c+1].key) {
nextInputIndex = i;
break;
}
}
let nextMatchIndex = -1;
for(let i = c+2; i < buffer.matchSequence.length; i++) {
if(buffer.matchSequence[i].key == buffer.inputSequence[r+1].key) {
nextMatchIndex = i;
break;
}
}
if(nextInputIndex > 0 && nextMatchIndex > 0) {
let transpositionCost = value + (nextInputIndex - r - 2) + 1 + (nextMatchIndex - c - 2);
this.propagateUpdateFrom(buffer, nextInputIndex, nextMatchIndex, transpositionCost, (buffer.diagonalWidth - 1) + nextMatchIndex - nextInputIndex);
}
}
}
get mapKey(): string {
let inputString = this.inputSequence.map((value) => value.key).join('');
let matchString = this.matchSequence.map((value) => value.key).join('');
return inputString + models.SENTINEL_CODE_UNIT + matchString + models.SENTINEL_CODE_UNIT + this.diagonalWidth;
}
get lastInputEntry(): TInput {
return this.inputSequence[this.inputSequence.length-1];
}
get lastMatchEntry(): TMatch {
return this.matchSequence[this.matchSequence.length-1];
}
static computeDistance<TUnit, TInput extends EditToken<TUnit>, TMatch extends EditToken<TUnit>>(
input: TInput[],
match: TMatch[],
bandSize: number = 1) {
// Initialize the calculation buffer, setting the diagonal width (as appropriate) in advance.
let buffer = new ClassicalDistanceCalculation<TUnit, TInput, TMatch>();
bandSize = bandSize || 1;
buffer.diagonalWidth = bandSize;
for(let i = 0; i < input.length; i++) {
buffer = buffer.addInputChar(input[i]);
}
for(let j = 0; j < match.length; j++) {
buffer = buffer.addMatchChar(match[j]);
}
return buffer;
}
}
} | the_stack |
import { MailActions, MailActionTypes } from '../actions';
import { FolderState, MailState, PGPEncryptionType, SecureContent } from '../datatypes';
import { Attachment, EmailDisplay, Mail, MailFolderType, OrderBy } from '../models';
import { FilenamePipe } from '../../shared/pipes/filename.pipe';
/**
---Start Reducer Utilities---
* */
function transformFilename(attachments: Attachment[]) {
if (attachments && attachments.length > 0) {
attachments = attachments.map(attachment => {
if (!attachment.name) {
attachment.name = FilenamePipe.tranformToFilename(attachment.document);
}
return attachment;
});
}
return attachments;
}
function sortByDueDateWithID(sortArray: Array<number>, mailMap: any): any[] {
const mails = sortArray
.map(mailID => {
if (Object.prototype.hasOwnProperty.call(mailMap, mailID)) {
return mailMap[mailID];
}
return null;
})
.filter(mail => !!mail);
const sorted = mails
.sort((previous: any, next: any) => {
const nextUpdated = next.updated || 0;
const previousUpdated = previous.updated || 0;
return <any>new Date(nextUpdated) - <any>new Date(previousUpdated);
})
.map(mail => mail.id);
return sorted;
}
function getTotalUnreadCount(data: any): number {
if (data) {
let totalCount = 0;
for (const key of Object.keys(data)) {
if (
key !== MailFolderType.SENT &&
key !== MailFolderType.TRASH &&
key !== MailFolderType.DRAFT &&
key !== MailFolderType.OUTBOX &&
key !== MailFolderType.SPAM &&
key !== 'total_unread_count' &&
key !== MailFolderType.STARRED &&
key !== 'updateUnreadCount' &&
key !== 'outbox_dead_man_counter' &&
key !== 'outbox_delayed_delivery_counter' &&
key !== 'outbox_self_destruct_counter' &&
!Number.isNaN(data[`${key}`])
) {
totalCount += data[`${key}`];
}
}
return totalCount;
}
return 0;
}
function updateMailMap(currentMap: any, mails: Mail[]): any {
if (mails && mails.length > 0) {
let temporaryMailMap = {};
for (const mail of mails) {
temporaryMailMap = { ...temporaryMailMap, [mail.id]: mail };
}
return { ...currentMap, ...temporaryMailMap };
}
return currentMap;
}
function filterAndMergeMailIDs(
newMails: Array<Mail>,
originalMailIDs: Array<number>,
limit: number,
checkUnread = false,
): Array<number> {
let mailIDs = newMails.filter(mail => (checkUnread ? !mail.read : true)).map(mail => mail.id);
const newMailsMap: any = {};
for (const mail of newMails) {
newMailsMap[mail.id] = mail;
}
if (originalMailIDs && originalMailIDs.length > 0) {
originalMailIDs = originalMailIDs.filter(id => !mailIDs.includes(id));
mailIDs = mailIDs.map(mailID => {
const newMail = newMailsMap[mailID];
if (newMail.parent && originalMailIDs.includes(newMail.parent)) {
originalMailIDs = originalMailIDs.filter(originMailID => originMailID !== newMail.parent);
return newMail.parent;
}
return mailID;
});
originalMailIDs = [...mailIDs, ...originalMailIDs];
if (originalMailIDs.length > limit) {
originalMailIDs = originalMailIDs.slice(0, limit);
}
return originalMailIDs;
}
return mailIDs;
}
function getUpdatesFolderMap(
newMails: Array<Mail>,
originalFolderState: FolderState,
limit: number,
checkUnread = false,
isConversationViewMode = true,
): any {
let originalMailIDs = originalFolderState.mails;
let mailIDs = newMails.filter(mail => (checkUnread ? !mail.read : true)).map(mail => mail.id);
const newMailsMap: any = {};
for (const mail of newMails) {
newMailsMap[mail.id] = mail;
}
if (originalMailIDs && originalMailIDs.length > 0) {
// Remove duplicated mails
let duplicatedMailIDS: any = [];
originalMailIDs = originalMailIDs.filter(id => {
if (!mailIDs.includes(id)) {
return true;
}
duplicatedMailIDS = [...duplicatedMailIDS, id];
return false;
});
// Check children mails
// If new's parent is same with any original mail
// Replace it with original mail on new mail array
let parentWithChild: any = [];
if (isConversationViewMode) {
mailIDs = mailIDs.map(mailID => {
const newMail = newMailsMap[mailID];
if (newMail.parent && originalMailIDs.includes(newMail.parent)) {
originalMailIDs = originalMailIDs.filter(originMailID => originMailID !== newMail.parent);
parentWithChild = [...parentWithChild.filter((item: any) => newMail.parent !== item), newMail.parent];
return newMail.parent;
}
return mailID;
});
}
// Merge new with old
originalMailIDs = [...mailIDs, ...originalMailIDs];
// Check overflow
if (originalMailIDs.length > limit) {
originalMailIDs = originalMailIDs.slice(0, limit);
}
const totalMailCount =
(originalFolderState.total_mail_count ? originalFolderState.total_mail_count : 0) +
mailIDs.length -
parentWithChild.length -
duplicatedMailIDS.length >=
0
? (originalFolderState.total_mail_count ? originalFolderState.total_mail_count : 0) +
mailIDs.length -
parentWithChild.length -
duplicatedMailIDS.length
: 0;
return {
mails: originalMailIDs,
total_mail_count: totalMailCount,
};
}
return {
mails: mailIDs,
total_mail_count: mailIDs.length,
};
}
function prepareMails(folderName: MailFolderType, folders: Map<string, FolderState>, mailMap: any): Array<Mail> {
if (folders.has(folderName)) {
const folderInfo = folders.get(folderName);
const mails = folderInfo.mails
.map(mailID => {
const mail = mailMap[mailID] ? mailMap[mailID] : null;
if (mail) {
mail.receiver_list = mail.receiver_display.map((item: EmailDisplay) => item.name).join(', ');
if (mail.children_folder_info) {
if (folderName === MailFolderType.TRASH && mail.folder === MailFolderType.TRASH) {
mail.thread_count = mail.children_folder_info ? mail.children_folder_info.trash_children_count + 1 : 0;
} else if (folderName === MailFolderType.TRASH && mail.folder !== MailFolderType.TRASH) {
mail.thread_count = mail.children_folder_info ? mail.children_folder_info.trash_children_count : 0;
} else if (folderName !== MailFolderType.TRASH && mail.folder !== MailFolderType.TRASH) {
mail.thread_count = mail.children_folder_info
? mail.children_folder_info.non_trash_children_count + 1
: 0;
} else if (folderName !== MailFolderType.TRASH && mail.folder === MailFolderType.TRASH) {
mail.thread_count = mail.children_folder_info ? mail.children_folder_info.non_trash_children_count : 0;
}
}
}
return mail;
})
.filter(mail => mail !== null);
return mails;
}
return [];
}
/**
---End Reducer Utilities---
* */
export function reducer(
// eslint-disable-next-line unicorn/no-object-as-default-parameter
state: MailState = {
mails: [],
total_mail_count: 0,
mailDetail: undefined,
starredFolderCount: 0,
loaded: false,
decryptedContents: {},
unreadMailsCount: { inbox: 0 },
noUnreadCountChange: true,
canGetUnreadCount: true,
decryptedSubjects: {},
isMailsMoved: false,
customFolderMessageCount: [],
isComposerPopUp: false,
mailMap: {},
folderMap: new Map(),
pageLimit: 20,
decryptedAttachmentsMap: new Map(),
orderBy: OrderBy.ASC,
},
action: MailActions,
): MailState {
switch (action.type) {
case MailActionTypes.GET_MAILS: {
let mails = prepareMails(action.payload.folder, state.folderMap, state.mailMap);
if (mails && mails.length === 0) {
mails = undefined;
}
return {
...state,
loaded: !!(mails && !action.payload.forceReload),
inProgress: !!action.payload.inProgress,
currentFolder: action.payload.folder as MailFolderType,
mails: mails || [],
noUnreadCountChange: true,
};
}
case MailActionTypes.GET_MAILS_SUCCESS: {
const payloadMails = action.payload.mails;
const mailMap = updateMailMap(state.mailMap, payloadMails);
const folderMap = new Map(state.folderMap);
// Update Folder Map for ###TARGET FOLDER###
if (!action.payload.is_from_socket || (action.payload.is_from_socket && folderMap.has(action.payload.folder))) {
const oldFolderInfo = folderMap.get(action.payload.folder);
const mailIDS = action.payload.is_from_socket
? oldFolderInfo && !oldFolderInfo.is_not_first_page
? filterAndMergeMailIDs(payloadMails, oldFolderInfo.mails, action.payload.limit)
: oldFolderInfo.mails
: payloadMails.map((mail: any) => mail.id);
const folderState = {
mails: mailIDS,
total_mail_count: action.payload.total_mail_count ? action.payload.total_mail_count : 0,
is_not_first_page: action.payload.is_from_socket
? oldFolderInfo && oldFolderInfo.is_not_first_page
: action.payload.is_not_first_page,
offset: action.payload.offset,
is_dirty: false,
};
folderMap.set(`${action.payload.folder}`, folderState);
}
// Update Folder Map for ###UNREAD FOLDER###
if (
action.payload.is_from_socket &&
action.payload.folder !== MailFolderType.UNREAD &&
action.payload.folder !== MailFolderType.SPAM &&
folderMap.has(MailFolderType.UNREAD)
) {
const oldFolderInfo = folderMap.get(MailFolderType.UNREAD);
const basicFolderState = getUpdatesFolderMap(payloadMails, oldFolderInfo, action.payload.limit, true);
const folderState = {
...oldFolderInfo,
mails: basicFolderState.mails,
total_mail_count: basicFolderState.total_mail_count ? basicFolderState.total_mail_count : 0,
};
folderMap.set(MailFolderType.UNREAD, folderState);
}
// Update Folder Map for ###ALL EMAILS FOLDER###
if (
action.payload.is_from_socket &&
action.payload.folder !== MailFolderType.ALL_EMAILS &&
action.payload.folder !== MailFolderType.SPAM &&
folderMap.has(MailFolderType.ALL_EMAILS)
) {
const oldFolderInfo = folderMap.get(MailFolderType.ALL_EMAILS);
const basicFolderState = getUpdatesFolderMap(payloadMails, oldFolderInfo, action.payload.limit);
const folderState = {
...oldFolderInfo,
mails: basicFolderState.mails,
total_mail_count: basicFolderState.total_mail_count ? basicFolderState.total_mail_count : 0,
};
folderMap.set(MailFolderType.ALL_EMAILS, folderState);
}
// Update Current Viewing Folder
const mails = prepareMails(state.currentFolder, folderMap, mailMap);
const currentFolderMap = folderMap.get(state.currentFolder);
state.total_mail_count = currentFolderMap?.total_mail_count ? currentFolderMap?.total_mail_count : 0;
mails.forEach((mail: Mail) => {
mail.receiver_list = mail.receiver_display.map((item: EmailDisplay) => item.name).join(', ');
if (mail.is_subject_encrypted && state.decryptedSubjects[mail.id]) {
mail.subject = state.decryptedSubjects[mail.id];
mail.is_subject_encrypted = false;
}
});
state.pageLimit = action.payload.limit;
return {
...state,
mails,
loaded: true,
inProgress: false,
noUnreadCountChange: true,
mailMap,
folderMap,
};
}
case MailActionTypes.STOP_GETTING_UNREAD_MAILS_COUNT: {
return {
...state,
canGetUnreadCount: false,
};
}
case MailActionTypes.REVERT_CHILD_MAIL_ORDER: {
return {
...state,
orderBy: action.payload.orderBy,
};
}
case MailActionTypes.STARRED_FOLDER_COUNT_UPDATE: {
return { ...state, starredFolderCount: action.payload.starred_count };
}
case MailActionTypes.GET_UNREAD_MAILS_COUNT: {
return { ...state, noUnreadCountChange: false };
}
case MailActionTypes.GET_UNREAD_MAILS_COUNT_SUCCESS: {
if (action.payload.updateUnreadCount) {
const totalUnreadMailCount = getTotalUnreadCount({ ...state.unreadMailsCount, ...action.payload });
const unreadMailData = {
...state.unreadMailsCount,
...action.payload,
total_unread_count: totalUnreadMailCount,
};
return {
...state,
unreadMailsCount: unreadMailData,
noUnreadCountChange: false,
};
}
return {
...state,
unreadMailsCount: { ...action.payload, total_unread_count: getTotalUnreadCount(action.payload) },
noUnreadCountChange: false,
};
}
case MailActionTypes.GET_CUSTOMFOLDER_MESSAGE_COUNT_SUCCESS: {
return { ...state, customFolderMessageCount: action.payload };
}
case MailActionTypes.SET_IS_COMPOSER_POPUP: {
state.isComposerPopUp = action.payload;
return {
...state,
};
}
case MailActionTypes.MOVE_MAIL: {
return { ...state, inProgress: true, noUnreadCountChange: true, isMailsMoved: false };
}
case MailActionTypes.REVERT_MAILS_MOVED: {
return { ...state, isMailsMoved: false };
}
case MailActionTypes.MOVE_MAIL_SUCCESS: {
const listOfIDs = action.payload.ids.toString().split(',');
const { folderMap } = state;
const { mailMap, pageLimit, currentFolder, mailDetail } = state;
// Update source folder's mails
const sourceFolderName = action.payload.sourceFolder;
if (sourceFolderName && folderMap.has(sourceFolderName)) {
const sourceFolderState = folderMap.get(sourceFolderName);
sourceFolderState.mails = sourceFolderState.mails.filter(mail => !listOfIDs.includes(mail.toString()));
sourceFolderState.total_mail_count =
sourceFolderState.total_mail_count >= listOfIDs.length
? sourceFolderState.total_mail_count - listOfIDs.length
: 0;
folderMap.set(sourceFolderName, sourceFolderState);
}
// Update target folder's mails
const targetFolderName = action.payload.folder;
if (targetFolderName && folderMap.has(targetFolderName)) {
const targetFolderState = folderMap.get(targetFolderName);
const movedMails = listOfIDs
.map((movedID: any) => (mailMap[movedID] ? mailMap[movedID] : null))
.filter((mail: any) => !!mail);
const basicFolderState = getUpdatesFolderMap(movedMails, targetFolderState, pageLimit);
const folderState = {
...targetFolderState,
mails: sortByDueDateWithID(basicFolderState.mails, mailMap),
total_mail_count: basicFolderState.total_mail_count,
};
folderMap.set(targetFolderName, folderState);
}
// Update other folders
const folderKeys = [...folderMap.keys()].filter(
key => key !== sourceFolderName && key !== targetFolderName && key !== currentFolder,
);
for (const key of folderKeys) {
const folderInfo = folderMap.get(key);
folderInfo.is_dirty = true;
folderInfo.mails = [];
folderMap.set(key, folderInfo);
}
// Update mail map
const mailMapKeys = Object.keys(mailMap);
for (const key of mailMapKeys) {
if (listOfIDs.includes(mailMap[key].id.toString())) {
mailMap[key] = { ...mailMap[key], folder: action.payload.folder };
if (
action.payload.folder === MailFolderType.TRASH &&
mailMap[key].has_children &&
mailMap[key].children_count > 0 &&
action.payload.withChildren !== false
) {
// If moving parent to trash, children would be moved to trash as well
mailMap[key].children_folder_info = {
trash_children_count: mailMap[key].children_count,
non_trash_children_count: 0,
};
} else if (
action.payload.sourceFolder === MailFolderType.TRASH &&
mailMap[key].has_children &&
mailMap[key].children_count > 0
) {
// If moving parent from trash, children would be moved as well
mailMap[key].children_folder_info = {
trash_children_count: 0,
non_trash_children_count: mailMap[key].children_count,
};
}
}
}
// This is to move to trash only child from any folder
// should update children_folder_info as well
const incomeMails = Array.isArray(action.payload.mail) ? action.payload.mail : [action.payload.mail];
incomeMails.forEach((mail: any) => {
if (action.payload.folder === MailFolderType.TRASH && mail.parent) {
const parentID = mail.parent;
if (mailMap[parentID] && mailMap[parentID].children_folder_info) {
mailMap[parentID].children_folder_info = {
trash_children_count: mailMap[parentID].children_folder_info.trash_children_count + 1,
non_trash_children_count:
mailMap[parentID].children_folder_info.non_trash_children_count > 0
? mailMap[parentID].children_folder_info.non_trash_children_count - 1
: 0,
};
}
}
});
const mails = prepareMails(currentFolder, folderMap, mailMap);
const currentMailFolder = folderMap.get(currentFolder);
state.total_mail_count = currentMailFolder ? currentMailFolder.total_mail_count : 0;
if (
mailDetail &&
mailDetail.children &&
mailDetail.children.some(child => listOfIDs.includes(child.id.toString()))
) {
for (const [index, child] of mailDetail.children.entries()) {
if (listOfIDs.includes(child.id.toString())) {
mailDetail.children[index] = { ...mailDetail.children[index], folder: action.payload.folder };
mailDetail.children_count = mailDetail.children.length;
}
}
const sourceFolderChildren = mailDetail.children.filter(child => child.folder === sourceFolderName);
if (sourceFolderName && folderMap.has(sourceFolderName)) {
const sourceFolderState = folderMap.get(sourceFolderName);
sourceFolderState.mails = sourceFolderState.mails.filter(mailID => {
if (mailID === mailDetail.id && sourceFolderChildren.length === 0) {
return false;
}
return true;
});
folderMap.set(sourceFolderName, sourceFolderState);
}
}
if (mailDetail && listOfIDs.includes(mailDetail.id.toString())) {
state.mailDetail = { ...mailDetail, folder: action.payload.folder };
}
return {
...state,
mails,
mailMap,
folderMap,
inProgress: false,
noUnreadCountChange: true,
isMailsMoved: true,
};
}
case MailActionTypes.UNDO_DELETE_MAIL_SUCCESS: {
let { mails } = state;
const { mailMap } = state;
const undoMails = Array.isArray(action.payload.mail) ? action.payload.mail : [action.payload.mail];
const { folderMap, pageLimit, currentFolder, mailDetail } = state;
// Destination folder map
if (folderMap.has(action.payload.sourceFolder)) {
const oldFolderMap = folderMap.get(action.payload.sourceFolder);
const basicFolderState = getUpdatesFolderMap(undoMails, oldFolderMap, pageLimit);
basicFolderState.mails = sortByDueDateWithID(basicFolderState.mails, mailMap);
folderMap.set(action.payload.sourceFolder, basicFolderState);
}
// Source folder map
if (folderMap.has(action.payload.folder)) {
const oldFolderMap = folderMap.get(action.payload.folder);
oldFolderMap.mails = [];
oldFolderMap.is_dirty = true;
folderMap.set(action.payload.folder, oldFolderMap);
}
// Update mail children info
undoMails.forEach((mail: any) => {
if (
action.payload.sourceFolder === MailFolderType.TRASH &&
mail.has_children &&
mail.children_count > 0 && // Action from the other to Trash folder (undo from trash to the other folder)
// All children would be set with Trash again
// TODO, needs to get which chilren are needed to undo exactly
mailMap[mail.id]
) {
mailMap[mail.id].children_folder_info = {
trash_children_count: mailMap[mail.id].children_count,
non_trash_children_count: 0,
};
}
});
// Update current folder map
if (action.payload.sourceFolder === currentFolder) {
mails = prepareMails(action.payload.sourceFolder, folderMap, state.mailMap);
const currentMailFolder = folderMap.get(currentFolder);
state.total_mail_count = currentMailFolder ? currentMailFolder.total_mail_count : 0;
}
const listOfIDs = action.payload.ids.toString().split(',');
if (
mailDetail &&
mailDetail.children &&
mailDetail.children.some(child => listOfIDs.includes(child.id.toString()))
) {
for (const [index, child] of mailDetail.children.entries()) {
if (listOfIDs.includes(child.id.toString())) {
mailDetail.children[index] = {
...mailDetail.children[index],
folder: action.payload.sourceFolder,
};
}
}
}
if (mailDetail && listOfIDs.includes(mailDetail.id.toString())) {
state.mailDetail = { ...mailDetail, folder: action.payload.sourceFolder };
}
return {
...state,
mails,
folderMap,
noUnreadCountChange: true,
};
}
case MailActionTypes.READ_MAIL_SUCCESS: {
const listOfIDs = action.payload.ids.split(',');
const { folderMap } = state;
const { mailMap, currentFolder, mailDetail } = state;
const allIDS = Object.keys(mailMap);
for (const mailID of allIDS) {
if (listOfIDs.includes(mailID.toString())) {
mailMap[mailID] = { ...mailMap[mailID], read: action.payload.read };
}
}
// Update Unread folder
if (currentFolder !== MailFolderType.UNREAD) {
if (folderMap.has(MailFolderType.UNREAD)) {
// TODO should update manually
const unreadFolderMap = folderMap.get(MailFolderType.UNREAD);
unreadFolderMap.is_dirty = true;
folderMap.set(MailFolderType.UNREAD, unreadFolderMap);
}
} else {
const currentFolderInfo = folderMap.get(MailFolderType.UNREAD);
let updatedMailCount = 0;
const updatedCurrentFolderMails = currentFolderInfo.mails.filter(mailID => {
if (listOfIDs.includes(mailID.toString()) && action.payload.read) {
updatedMailCount += 1;
return false;
}
return true;
});
currentFolderInfo.mails = updatedCurrentFolderMails;
if (action.payload.read) {
currentFolderInfo.total_mail_count =
currentFolderInfo.total_mail_count >= updatedMailCount
? currentFolderInfo.total_mail_count - updatedMailCount
: 0;
}
folderMap.set(MailFolderType.UNREAD, currentFolderInfo);
}
const mails = prepareMails(currentFolder, folderMap, mailMap);
const currentMailFolder = folderMap.get(currentFolder);
state.total_mail_count = currentMailFolder ? currentMailFolder.total_mail_count : 0;
if (mailDetail && listOfIDs.includes(mailDetail.id.toString())) {
state.mailDetail = { ...mailDetail, read: action.payload.read };
}
return {
...state,
mails,
mailMap,
folderMap,
inProgress: false,
noUnreadCountChange: true,
};
}
case MailActionTypes.STAR_MAIL_SUCCESS: {
const listOfIDs = action.payload.ids.split(',');
const { folderMap } = state;
const { mailMap, currentFolder } = state;
let { mailDetail } = state;
const allIDS = Object.keys(mailMap);
for (const mailID of allIDS) {
if (listOfIDs.includes(mailID.toString())) {
const hasStarredChildren = !(!action.payload.starred && action.payload.withChildren);
mailMap[mailID] = {
...mailMap[mailID],
starred: action.payload.starred,
has_starred_children: hasStarredChildren,
};
}
}
// Update Star folder
if (currentFolder !== MailFolderType.STARRED) {
if (folderMap.has(MailFolderType.STARRED)) {
// TODO should update manually
const starredFolderMap = folderMap.get(MailFolderType.STARRED);
starredFolderMap.is_dirty = true;
folderMap.set(MailFolderType.STARRED, starredFolderMap);
}
} else {
const currentFolderInfo = folderMap.get(MailFolderType.STARRED);
let updatedMailCount = 0;
const updatedCurrentFolderMails = currentFolderInfo.mails.filter(mailID => {
if (listOfIDs.includes(mailID.toString()) && !action.payload.starred) {
updatedMailCount += 1;
return false;
}
if (mailDetail && mailID === mailDetail.id) {
const { children } = mailDetail;
if (children && children.length > 0) {
for (const [index, child] of children.entries()) {
if (listOfIDs.includes(child.id.toString())) {
children[index] = { ...child, starred: action.payload.starred };
}
}
return children.some(child => child.starred);
}
}
return true;
});
if (!action.payload.starred) {
currentFolderInfo.total_mail_count =
currentFolderInfo.total_mail_count >= updatedMailCount
? currentFolderInfo.total_mail_count - updatedMailCount
: 0;
}
currentFolderInfo.mails = updatedCurrentFolderMails;
folderMap.set(MailFolderType.STARRED, currentFolderInfo);
}
if (mailDetail) {
const { children, starred } = mailDetail;
// eslint-disable-next-line unicorn/consistent-destructuring
if (listOfIDs.includes(mailDetail.id.toString())) {
if (action.payload.withChildren && children && children.length > 0) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
for (const [index, child] of children.entries()) children[index].starred = action.payload.starred;
}
const hasStarredChildren =
children && children.length > 0
? children.some(child => child.starred) || action.payload.starred
: action.payload.starred;
state.mailDetail = {
...mailDetail,
starred: action.payload.starred,
children,
has_starred_children: hasStarredChildren,
};
} else if (children && children.length > 0) {
for (const [index, child] of children.entries()) {
if (listOfIDs.includes(child.id.toString())) {
children[index] = { ...child, starred: action.payload.starred };
}
}
const hasStarredChildren = children.some(child => child.starred) || starred;
mailDetail = { ...mailDetail, children, has_starred_children: hasStarredChildren };
// eslint-disable-next-line unicorn/consistent-destructuring
if (mailDetail.id in mailMap) {
// eslint-disable-next-line unicorn/consistent-destructuring
mailMap[mailDetail.id] = { ...mailMap[mailDetail.id], has_starred_children: hasStarredChildren };
}
}
}
const mails = prepareMails(state.currentFolder, folderMap, mailMap);
const currentMailFolder = folderMap.get(state.currentFolder);
state.total_mail_count = currentMailFolder ? currentMailFolder.total_mail_count : 0;
return {
...state,
mails,
mailMap,
folderMap,
inProgress: false,
noUnreadCountChange: true,
};
}
case MailActionTypes.DELETE_MAIL_FOR_ALL_SUCCESS:
case MailActionTypes.DELETE_MAIL_SUCCESS: {
const listOfIDs = action.payload.ids.split(',');
const folderMap = new Map(state.folderMap);
const mailMap = { ...state.mailMap };
const folderKeys = [MailFolderType.DRAFT, MailFolderType.TRASH, MailFolderType.SPAM];
for (const key of folderKeys) {
if (folderMap.has(key)) {
const folderInfo = folderMap.get(key);
folderInfo.mails = folderInfo.mails.filter(mailID => !listOfIDs.includes(mailID.toString()));
folderInfo.total_mail_count = folderInfo.total_mail_count > 0 ? folderInfo.total_mail_count - 1 : 0;
folderInfo.is_dirty = true;
folderMap.set(key, folderInfo);
}
}
const mails = prepareMails(state.currentFolder, folderMap, mailMap);
const currentMailFolder = folderMap.get(state.currentFolder);
state.total_mail_count = currentMailFolder ? currentMailFolder.total_mail_count : 0;
if (
!action.payload.isDraft &&
state.mailDetail &&
state.mailDetail.children &&
state.mailDetail.children.some(child => listOfIDs.includes(child.id.toString()))
) {
state.mailDetail.children = state.mailDetail.children.filter(child => !listOfIDs.includes(child.id.toString()));
state.mailDetail.children_count = state.mailDetail.children.length;
}
return {
...state,
mails,
folderMap,
mailMap,
inProgress: false,
noUnreadCountChange: true,
};
}
case MailActionTypes.GET_MAIL_DETAIL_SUCCESS: {
const { decryptedAttachmentsMap, decryptedSubjects } = state;
const mail: Mail = action.payload;
if (mail) {
if (mail.is_subject_encrypted && decryptedSubjects[mail.id]) {
mail.is_subject_encrypted = false;
mail.subject = decryptedSubjects[mail.id];
}
mail.attachments =
mail.encryption_type === PGPEncryptionType.PGP_MIME &&
decryptedAttachmentsMap.has(mail.id) &&
decryptedAttachmentsMap.get(mail.id).length > 0
? decryptedAttachmentsMap.get(mail.id)
: transformFilename(mail.attachments);
if (mail.children && mail.children.length > 0) {
for (const item of mail.children) {
item.attachments =
item.encryption_type === PGPEncryptionType.PGP_MIME &&
decryptedAttachmentsMap.has(item.id) &&
decryptedAttachmentsMap.get(item.id).length > 0
? decryptedAttachmentsMap.get(item.id)
: transformFilename(item.attachments);
}
}
}
return {
...state,
mailDetail: action.payload,
mailDetailLoaded: true,
noUnreadCountChange: true,
};
}
case MailActionTypes.GET_MAIL_DETAIL_FAILURE: {
return {
...state,
mailDetailLoaded: true,
};
}
case MailActionTypes.GET_MAIL_DETAIL: {
return {
...state,
mailDetail: null,
noUnreadCountChange: true,
};
}
case MailActionTypes.CLEAR_MAILS_ON_CONVERSATION_MODE_CHANGE: {
return {
...state,
mails: [],
total_mail_count: 0,
mailDetail: null,
loaded: false,
unreadMailsCount: { inbox: 0 },
noUnreadCountChange: true,
canGetUnreadCount: true,
mailMap: {},
folderMap: new Map(),
};
}
case MailActionTypes.CLEAR_MAILS_ON_LOGOUT: {
return {
mails: [],
total_mail_count: 0,
mailDetail: null,
loaded: false,
starredFolderCount: 0,
decryptedContents: {},
unreadMailsCount: { inbox: 0 },
noUnreadCountChange: true,
canGetUnreadCount: true,
decryptedSubjects: {},
customFolderMessageCount: [],
mailMap: {},
folderMap: new Map(),
};
}
case MailActionTypes.CLEAR_MAIL_DETAIL: {
return {
...state,
mailDetail: null,
noUnreadCountChange: true,
};
}
case MailActionTypes.UPDATE_MAIL_DETAIL_CHILDREN: {
const { mailDetail } = state;
if (mailDetail) {
if (action.payload.last_action_data?.last_action) {
if (mailDetail.id === action.payload.last_action_data.last_action_parent_id) {
mailDetail.last_action = action.payload.last_action_data.last_action;
} else {
mailDetail.children = mailDetail.children.map(mail => {
if (mail.id === action.payload.last_action_data.last_action_parent_id) {
mail.last_action = action.payload.last_action_data.last_action;
}
return mail;
});
}
}
if (action.payload.parent === mailDetail.id) {
mailDetail.children = mailDetail.children || [];
mailDetail.children = mailDetail.children.filter(child => !(child.id === action.payload.id));
mailDetail.children = [...mailDetail.children, action.payload];
mailDetail.children_count = mailDetail.children.length;
}
}
return { ...state, mailDetail, noUnreadCountChange: true };
}
case MailActionTypes.SET_CURRENT_FOLDER: {
const { folderMap, mailMap, decryptedSubjects } = state;
const mails = prepareMails(action.payload, folderMap, mailMap);
const totalMailCount = folderMap.has(action.payload) ? folderMap.get(action.payload).total_mail_count : 0;
for (const key of Object.keys(mailMap)) {
const mail = mailMap[key];
mail.marked = false;
mailMap[key] = { ...mail };
}
for (const mail of mails) {
if (decryptedSubjects[mail.id]) {
mail.subject = decryptedSubjects[mail.id];
mail.is_subject_encrypted = false;
}
}
return {
...state,
mails,
mailMap,
total_mail_count: totalMailCount,
currentFolder: action.payload,
};
}
case MailActionTypes.UPDATE_PGP_DECRYPTED_CONTENT: {
if (action.payload.isDecryptingAllSubjects) {
if (!action.payload.isPGPInProgress) {
state.mails = state.mails.map(mail => {
if (mail.id === action.payload.id) {
mail.subject = action.payload.decryptedContent.subject;
mail.is_subject_encrypted = false;
}
return mail;
});
state.decryptedSubjects[action.payload.id] = action.payload.decryptedContent.subject;
}
return { ...state };
}
const { decryptedContents } = state;
let decryptedContent: SecureContent = decryptedContents[action.payload.id] || {};
decryptedContent = {
...decryptedContent,
id: action.payload.id,
content: action.payload.decryptedContent.content,
content_plain: action.payload.decryptedContent.content_plain,
subject: action.payload.decryptedContent.subject,
inProgress: action.payload.isPGPInProgress,
incomingHeaders: action.payload.decryptedContent.incomingHeaders,
decryptError: action.payload.decryptError,
};
decryptedContents[action.payload.id] = decryptedContent;
return { ...state, decryptedContents, noUnreadCountChange: true };
}
case MailActionTypes.UPDATE_CURRENT_FOLDER: {
let mailMap = { ...state.mailMap };
const folderMap = new Map(state.folderMap);
const newMail = { ...action.payload };
// Update mail map
mailMap = updateMailMap(mailMap, [newMail]);
if (newMail.parent) {
const mailIDs = Object.keys(mailMap);
for (const mailID of mailIDs) {
if (mailMap[mailID].id === newMail.parent && !newMail.isUpdate) {
mailMap[mailID].has_children = true;
mailMap[mailID].children_count += 1;
if (mailMap[mailID].children_folder_info) {
mailMap[mailID].children_folder_info = {
...mailMap[mailID].children_folder_info,
non_trash_children_count: mailMap[mailID].children_folder_info.non_trash_children_count + 1,
};
} else {
mailMap[mailID].children_folder_info = {
trash_children_count: 0,
non_trash_children_count: 1,
};
}
}
}
}
// update target folder map
if (folderMap.has(newMail.folder) && folderMap.get(newMail.folder).mails?.length > 0) {
const targetFolderMap = folderMap.get(newMail.folder);
const basicFolderState = getUpdatesFolderMap([newMail], targetFolderMap, state.pageLimit);
folderMap.set(newMail.folder, basicFolderState);
}
const mails = prepareMails(state.currentFolder, folderMap, mailMap);
if (state.currentFolder) {
const currentMailFolder = folderMap.get(state.currentFolder);
state.total_mail_count = currentMailFolder ? currentMailFolder.total_mail_count : 0;
}
return {
...state,
mails,
mailMap,
folderMap,
noUnreadCountChange: true,
};
}
case MailActionTypes.EMPTY_FOLDER: {
return { ...state, inProgress: true, noUnreadCountChange: true };
}
case MailActionTypes.EMPTY_FOLDER_SUCCESS: {
if (state.folderMap.has(action.payload.folder)) {
state.folderMap.delete(action.payload.folder);
}
return { ...state, mails: [], inProgress: false };
}
case MailActionTypes.EMPTY_FOLDER_FAILURE: {
return { ...state, inProgress: false };
}
case MailActionTypes.MOVE_TAB: {
return { ...state, currentSettingsTab: action.payload };
}
case MailActionTypes.EMPTY_ONLY_FOLDER: {
if (state.folderMap.has(action.payload.folder)) {
state.folderMap.delete(action.payload.folder);
}
return { ...state, inProgress: false };
}
case MailActionTypes.SET_ATTACHMENTS_FOR_PGP_MIME: {
const { mailDetail, mailMap, decryptedAttachmentsMap } = state;
const { attachments, messageID } = action.payload;
if (mailDetail) {
if (messageID === mailDetail.id) {
mailDetail.attachments = attachments;
} else if (mailDetail.children?.length > 0) {
for (const child of mailDetail.children) {
if (child.id === messageID) {
child.attachments = attachments;
}
}
}
}
for (const mailID of Object.keys(mailMap)) {
if (mailID === messageID.toString()) {
mailMap[mailID].attachments = attachments;
}
}
decryptedAttachmentsMap.set(messageID, attachments);
return { ...state, mailDetail, mailMap, decryptedAttachmentsMap };
}
default: {
return state;
}
}
} | the_stack |
import {
isAttributeInstance,
isIdentifierAttributeInstance,
isComponentValueTypeInstance,
isObjectValueTypeInstance
} from '@layr/component';
import {assertIsPlainObject, assertNoUnknownOptions} from 'core-helpers';
import type {StorableComponent, SortDirection} from './storable';
import {isStorableAttributeInstance} from './properties/storable-attribute';
import {assertIsStorableInstance} from './utilities';
export type IndexAttributes = {[name: string]: SortDirection};
export type IndexOptions = {isUnique?: boolean};
/**
* Represents an index for one or several [attributes](https://layrjs.com/docs/v2/reference/attribute) of a [storable component](https://layrjs.com/docs/v2/reference/storable#storable-component-class).
*
* Once an index is defined for an attribute, all queries involving this attribute (through the [`find()`](https://layrjs.com/docs/v2/reference/storable#find-class-method) or the [`count()`](https://layrjs.com/docs/v2/reference/storable#count-class-method) methods) can be greatly optimized by the storable component's [store](https://layrjs.com/docs/v2/reference/store) and its underlying database.
*
* #### Usage
*
* ##### Single Attribute Indexes
*
* Typically, you create an `Index` for a storable component's attribute by using the [`@index()`](https://layrjs.com/docs/v2/reference/storable#index-decorator) decorator. Then, you call the [`migrateStorables()`](https://layrjs.com/docs/v2/reference/store#migrate-storables-instance-method) method on the storable component's store to effectively create the index in the underlying database.
*
* For example, here is how you would define a `Movie` class with some indexes:
*
* ```js
* // JS
*
* import {Component} from '@layr/component';
* import {Storable, primaryIdentifier, attribute, index} from '@layr/storable';
* import {MongoDBStore} from '@layr/mongodb-store';
*
* export class Movie extends Storable(Component) {
* // Primary and secondary identifier attributes are automatically indexed,
* // so there is no need to define an index for these types of attributes
* @primaryIdentifier() id;
*
* // Let's define an index for the `title` attribute
* @index() @attribute('string') title;
* }
*
* const store = new MongoDBStore('mongodb://user:pass@host:port/db');
*
* store.registerStorable(Movie);
* ```
*
* ```ts
* // TS
*
* import {Component} from '@layr/component';
* import {Storable, primaryIdentifier, attribute, index} from '@layr/storable';
* import {MongoDBStore} from '@layr/mongodb-store';
*
* export class Movie extends Storable(Component) {
* // Primary and secondary identifier attributes are automatically indexed,
* // so there is no need to define an index for these types of attributes
* @primaryIdentifier() id!: string;
*
* // Let's define an index for the `title` attribute
* @index() @attribute('string') title!: string;
* }
*
* const store = new MongoDBStore('mongodb://user:pass@host:port/db');
*
* store.registerStorable(Movie);
* ```
*
* Then you can call the [`migrateStorables()`](https://layrjs.com/docs/v2/reference/store#migrate-storables-instance-method) method on the store to create the indexes in the MongoDB database:
*
* ```
* await store.migrateStorables();
* ```
*
* And now that the `title` attribute is indexed, you can make any query on this attribute in a very performant way:
*
* ```
* const movies = await Movie.find({title: 'Inception'});
* ```
*
* ##### Compound Attribute Indexes
*
* You can create a compound attribute index to optimize some queries that involve a combination of attributes. To do so, you use the [`@index()`](https://layrjs.com/docs/v2/reference/storable#index-decorator) decorator on the storable component itself:
*
* ```js
* // JS
*
* import {Component} from '@layr/component';
* import {Storable, primaryIdentifier, attribute, index} from '@layr/storable';
* import {MongoDBStore} from '@layr/mongodb-store';
*
* // Let's define a compound attribute index for the combination of the `year`
* // attribute (descending order) and the `title` attribute (ascending order)
* ﹫index({year: 'desc', title: 'asc'})
* export class Movie extends Storable(Component) {
* @primaryIdentifier() id;
*
* @attribute('string') title;
*
* @attribute('number') year;
* }
*
* const store = new MongoDBStore('mongodb://user:pass@host:port/db');
*
* store.registerStorable(Movie);
* ```
*
* ```ts
* // TS
*
* import {Component} from '@layr/component';
* import {Storable, primaryIdentifier, attribute, index} from '@layr/storable';
* import {MongoDBStore} from '@layr/mongodb-store';
*
* // Let's define a compound attribute index for the combination of the `year`
* // attribute (descending order) and the `title` attribute (ascending order)
* ﹫index({year: 'desc', title: 'asc'})
* export class Movie extends Storable(Component) {
* @primaryIdentifier() id!: string;
*
* @attribute('string') title!: string;
*
* @attribute('number') year!: number;
* }
*
* const store = new MongoDBStore('mongodb://user:pass@host:port/db');
*
* store.registerStorable(Movie);
* ```
*
* Then you can call the [`migrateStorables()`](https://layrjs.com/docs/v2/reference/store#migrate-storables-instance-method) method on the store to create the compound attribute index in the MongoDB database:
*
* ```
* await store.migrateStorables();
* ```
*
* And now you can make any query involving a combination of `year` and `title` in a very performant way:
*
* ```
* const movies = await Movie.find(
* {year: {$greaterThan: 2010}},
* true,
* {sort: {year: 'desc', title: 'asc'}}
* );
* ```
*/
export class Index {
_attributes: IndexAttributes;
_parent: StorableComponent;
_options!: IndexOptions;
/**
* Creates an instance of [`Index`](https://layrjs.com/docs/v2/reference/index).
*
* @param attributes An object specifying the attributes to be indexed. The shape of the object should be `{attributeName: direction, ...}` where `attributeName` is a string representing the name of an attribute and `direction` is a string representing the sort direction (possible values: `'asc'` or `'desc'`).
* @param parent The storable component prototype that owns the index.
* @param [options.isUnique] A boolean specifying whether the index should hold unique values or not (default: `false`). When set to `true`, the underlying database will prevent you to store an attribute with the same value in multiple storable components.
*
* @returns The [`Index`](https://layrjs.com/docs/v2/reference/index) instance that was created.
*
* @category Creation
*/
constructor(attributes: IndexAttributes, parent: StorableComponent, options: IndexOptions = {}) {
assertIsPlainObject(attributes);
assertIsStorableInstance(parent);
for (const [name, direction] of Object.entries(attributes)) {
if (!parent.hasProperty(name)) {
throw new Error(
`Cannot create an index for an attribute that doesn't exist (${parent.describeComponent()}, attribute: '${name}')`
);
}
const property = parent.getProperty(name, {autoFork: false});
if (!isAttributeInstance(property)) {
throw new Error(
`Cannot create an index for a property that is not an attribute (${parent.describeComponent()}, property: '${name}')`
);
}
if (isStorableAttributeInstance(property) && property.isComputed()) {
throw new Error(
`Cannot create an index for a computed attribute (${parent.describeComponent()}, attribute: '${name}')`
);
}
const scalarType = property.getValueType().getScalarType();
if (isObjectValueTypeInstance(scalarType)) {
throw new Error(
`Cannot create an index for an attribute of type 'object' (${parent.describeComponent()}, attribute: '${name}')`
);
}
if (!(direction === 'asc' || direction === 'desc')) {
throw new Error(
`Cannot create an index with an invalid sort direction (${parent.describeComponent()}, attribute: '${name}', sort direction: '${direction}')`
);
}
}
if (Object.keys(attributes).length === 0) {
throw new Error(
`Cannot create an index for an empty 'attributes' parameter (${parent.describeComponent()})`
);
}
if (Object.keys(attributes).length === 1) {
const name = Object.keys(attributes)[0];
const attribute = parent.getAttribute(name, {autoFork: false});
if (isIdentifierAttributeInstance(attribute)) {
throw new Error(
`Cannot explicitly create an index for an identifier attribute (${parent.describeComponent()}, attribute: '${name}'). Note that this type of attribute is automatically indexed.`
);
}
const scalarType = attribute.getValueType().getScalarType();
if (isComponentValueTypeInstance(scalarType)) {
throw new Error(
`Cannot create an index for an attribute of type 'Component' (${parent.describeComponent()}, attribute: '${name}'). Note that primary identifier attributes of referenced components are automatically indexed.`
);
}
}
this._attributes = attributes;
this._parent = parent;
this.setOptions(options);
}
/**
* Returns the indexed attributes.
*
* @returns An object of the shape `{attributeName: direction, ...}`.
*
* @category Basic Methods
*/
getAttributes() {
return this._attributes;
}
/**
* Returns the parent of the index.
*
* @returns A storable component prototype.
*
* @category Basic Methods
*/
getParent() {
return this._parent;
}
// === Options ===
getOptions() {
return this._options;
}
setOptions(options: IndexOptions = {}) {
const {isUnique, ...unknownOptions} = options;
assertNoUnknownOptions(unknownOptions);
this._options = {isUnique};
}
// === Forking ===
fork(parent: StorableComponent) {
const forkedIndex = Object.create(this) as Index;
forkedIndex._parent = parent;
return forkedIndex;
}
// === Utilities ===
static isIndex(value: any): value is Index {
return isIndexInstance(value);
}
static _buildIndexKey(attributes: IndexAttributes) {
return JSON.stringify(attributes);
}
}
/**
* Returns whether the specified value is an `Index` class.
*
* @param value A value of any type.
*
* @returns A boolean.
*
* @category Utilities
*/
export function isIndexClass(value: any): value is typeof Index {
return typeof value?.isIndex === 'function';
}
/**
* Returns whether the specified value is an `Index` instance.
*
* @param value A value of any type.
*
* @returns A boolean.
*
* @category Utilities
*/
export function isIndexInstance(value: any): value is Index {
return isIndexClass(value?.constructor) === true;
} | the_stack |
import * as should from "should";
import * as sinon from "sinon";
import { BrowseDirection } from "node-opcua-data-model";
import { NodeId, resolveNodeId } from "node-opcua-nodeid";
import { AddressSpace, Namespace, UARootFolder, UAObjectType, UAReferenceType } from "..";
import { getMiniAddressSpace } from "../testHelpers";
// tslint:disable-next-line:no-var-requires
const describe = require("node-opcua-leak-detector").describeWithLeakDetector;
describe("Testing UAObject", () => {
let addressSpace: AddressSpace;
let namespace: Namespace;
let rootFolder: UARootFolder;
let organizesReferenceType: UAReferenceType;
let hasTypeDefinitionReferenceType: UAReferenceType;
let baseObjectType: UAObjectType;
before(async () => {
addressSpace = await getMiniAddressSpace();
namespace = addressSpace.getOwnNamespace();
rootFolder = addressSpace.findNode("RootFolder")! as UARootFolder;
organizesReferenceType = addressSpace.findReferenceType("Organizes")!;
hasTypeDefinitionReferenceType = addressSpace.findReferenceType("HasTypeDefinition")!;
baseObjectType = addressSpace.findObjectType("BaseObjectType")!;
});
after(async () => {
addressSpace.dispose();
});
function dump(e: any) {
console.log(e.toString({ addressSpace }));
}
it("AddressSpace#addObject should create a 'hasTypeDefinition' reference on node", () => {
const nbReferencesBefore = baseObjectType.findReferencesEx("HasTypeDefinition", BrowseDirection.Inverse).length;
const node1 = namespace.addObject({
browseName: "Node1",
typeDefinition: "BaseObjectType"
});
// xx node1.findReferencesEx("References", BrowseDirection.Forward).forEach(dump);
const forwardReferences = node1.findReferencesEx("References", BrowseDirection.Forward);
forwardReferences.length.should.eql(1);
forwardReferences[0].referenceType.should.eql(resolveNodeId("HasTypeDefinition"));
forwardReferences[0].isForward.should.eql(true);
forwardReferences[0].nodeId.should.eql(baseObjectType.nodeId);
const inverseReferences = node1.findReferencesEx("References", BrowseDirection.Inverse);
inverseReferences.length.should.eql(0);
const nbReferencesAfter = baseObjectType.findReferencesEx("HasTypeDefinition", BrowseDirection.Inverse).length;
// xx console.log("",nbReferencesBefore,nbReferencesAfter);
nbReferencesAfter.should.eql(
nbReferencesBefore,
"we should have no more inverse references on the BaseObjectType because we " +
"do not add backward reference when reference is HasTypeDefinition"
);
should(node1.parent).eql(null, "node1 should have no parent");
});
function _test_with_custom_referenceType(referenceType: string | NodeId | UAReferenceType) {
const node1 = namespace.addObject({
browseName: "Node1"
});
const nodeDest = namespace.addObject({
browseName: "nodeDest"
});
node1.addReference({
isForward: true,
nodeId: nodeDest.nodeId,
referenceType
});
const forwardReferences1 = node1.findReferencesEx("References", BrowseDirection.Forward);
const inverseReferences1 = node1.findReferencesEx("References", BrowseDirection.Inverse);
forwardReferences1.length.should.eql(2);
inverseReferences1.length.should.eql(0);
forwardReferences1[1].nodeId.toString().should.eql(nodeDest.nodeId.toString());
// xx console.log(node1._references[0].toString({addressSpace: addressSpace}));
// xx console.log(node1._references[1].toString({addressSpace: addressSpace}));
}
it("BaseNode#addReference - referenceType as ReferenceType BrowseName", () => {
_test_with_custom_referenceType("Organizes");
});
it("BaseNode#addReference - referenceType as nodeId String", () => {
const referenceType = addressSpace.findReferenceType("Organizes")!;
_test_with_custom_referenceType(referenceType.nodeId.toString());
});
it("BaseNode#addReference - referenceType as NodeId", () => {
const referenceType = addressSpace.findReferenceType("Organizes")!;
_test_with_custom_referenceType(referenceType.nodeId);
});
it("BaseNode#addReference - nodeId as NodeId", () => {
const node1 = namespace.addObject({ browseName: "Node1" });
const nodeDest = namespace.addObject({ browseName: "nodeDest" });
node1.addReference({
nodeId: nodeDest,
referenceType: "Organizes"
});
node1.getFolderElementByName("nodeDest")!.browseName.should.eql(nodeDest.browseName);
});
it("BaseNode#addReference - nodeId as Node", () => {
const node1 = namespace.addObject({ browseName: "Node1" });
const nodeDest = namespace.addObject({ browseName: "nodeDest" });
node1.addReference({
nodeId: nodeDest.nodeId,
referenceType: "Organizes"
});
node1.getFolderElementByName("nodeDest")!.browseName.should.eql(nodeDest.browseName);
});
it("BaseNode#addReference - nodeId as String", () => {
const node1 = namespace.addObject({ browseName: "Node1" });
const nodeDest = namespace.addObject({ browseName: "nodeDest" });
node1.addReference({
nodeId: nodeDest.nodeId.toString(),
referenceType: "Organizes"
});
node1.getFolderElementByName("nodeDest")!.browseName.should.eql(nodeDest.browseName);
});
it("BaseNode#addReference with invalid referenceType should raise an exception", () => {
const node1 = namespace.addObject({
browseName: "Node1"
});
const nodeDest = namespace.addObject({
browseName: "nodeDest"
});
should(() => {
node1.addReference({
isForward: true,
nodeId: nodeDest.nodeId,
referenceType: "INVALID TYPE"
});
}).throwError();
});
it("BaseNode#addReference - four equivalent cases", () => {
const view = namespace.addObject({ browseName: "View" });
const node1 = namespace.addObject({ browseName: "Node1" });
const node2 = namespace.addObject({ browseName: "Node2" });
const node3 = namespace.addObject({ browseName: "Node3" });
const node4 = namespace.addObject({ browseName: "Node4" });
const node5 = namespace.addObject({ browseName: "Node5" });
// the following addReference usages produce the same relationship
node1.addReference({ referenceType: "OrganizedBy", nodeId: view.nodeId });
node2.addReference({ referenceType: "OrganizedBy", nodeId: view });
node3.addReference({ referenceType: "Organizes", isForward: false, nodeId: view.nodeId });
view.addReference({ referenceType: "Organizes", nodeId: node4 });
view.addReference({ referenceType: "OrganizedBy", isForward: false, nodeId: node5 });
view.getFolderElementByName("Node1")!.browseName.toString().should.eql(node1.browseName.toString());
view.getFolderElementByName("Node2")!.browseName.toString().should.eql(node2.browseName.toString());
view.getFolderElementByName("Node3")!.browseName.toString().should.eql(node3.browseName.toString());
view.getFolderElementByName("Node4")!.browseName.toString().should.eql(node4.browseName.toString());
view.getFolderElementByName("Node5")!.browseName.toString().should.eql(node5.browseName.toString());
});
it("BaseNode#addReference - 2 nodes - should properly update backward references on referenced nodes", () => {
const node1 = namespace.addObject({
browseName: "Node1"
});
const nodeDest = namespace.addObject({
browseName: "nodeDest"
});
node1.addReference({
isForward: true,
nodeId: nodeDest.nodeId,
referenceType: "Organizes"
});
const forwardReferences1 = node1.findReferencesEx("References", BrowseDirection.Forward);
const inverseReferences1 = node1.findReferencesEx("References", BrowseDirection.Inverse);
forwardReferences1.length.should.eql(2);
inverseReferences1.length.should.eql(0);
forwardReferences1[1].nodeId.toString().should.eql(nodeDest.nodeId.toString());
const forwardReferencesDest = nodeDest.findReferencesEx("References", BrowseDirection.Forward);
const inverseReferencesDest = nodeDest.findReferencesEx("References", BrowseDirection.Inverse);
forwardReferencesDest.length.should.eql(1);
inverseReferencesDest.length.should.eql(1);
inverseReferencesDest[0].nodeId.toString().should.eql(node1.nodeId.toString());
});
it("BaseNode#addReference - 3 nodes - should properly update backward references on referenced nodes", () => {
const node1 = namespace.addObject({
browseName: "Node1"
});
const node2 = namespace.addObject({
browseName: "Node2"
});
const nodeDest = namespace.addObject({
browseName: "NodeDest"
});
node1.addReference({
isForward: true,
nodeId: nodeDest.nodeId,
referenceType: "Organizes"
});
node2.addReference({
isForward: true,
nodeId: nodeDest.nodeId,
referenceType: "Organizes"
});
const forwardReferences1 = node1.findReferencesEx("References", BrowseDirection.Forward);
const inverseReferences1 = node1.findReferencesEx("References", BrowseDirection.Inverse);
forwardReferences1.length.should.eql(2);
inverseReferences1.length.should.eql(0);
forwardReferences1[1].nodeId.toString().should.eql(nodeDest.nodeId.toString());
const forwardReferences2 = node1.findReferencesEx("References", BrowseDirection.Forward);
const inverseReferences2 = node1.findReferencesEx("References", BrowseDirection.Inverse);
forwardReferences2.length.should.eql(2);
inverseReferences2.length.should.eql(0);
forwardReferences2[1].nodeId.toString().should.eql(nodeDest.nodeId.toString());
const forwardReferencesDest = nodeDest.findReferencesEx("References", BrowseDirection.Forward);
const inverseReferencesDest = nodeDest.findReferencesEx("References", BrowseDirection.Inverse);
forwardReferencesDest.length.should.eql(1);
inverseReferencesDest.length.should.eql(2);
inverseReferencesDest[0].nodeId.toString().should.eql(node1.nodeId.toString());
inverseReferencesDest[1].nodeId.toString().should.eql(node2.nodeId.toString());
});
it("BaseNode#addReference should throw if the same reference is added twice", () => {
const node1 = namespace.addObject({
browseName: "Node1"
});
const node2 = namespace.addObject({
browseName: "Node2"
});
node1.addReference({
isForward: true,
nodeId: node2.nodeId,
referenceType: "Organizes"
});
should(function adding_the_same_reference_again() {
node1.addReference({
isForward: true,
nodeId: node2.nodeId,
referenceType: "Organizes"
});
}).throwError();
});
it("BaseNode#addReference internal cache must be invalidated", () => {
const node1 = namespace.addObject({
browseName: "Node1"
});
// let call a method that caches results
node1.getComponents().length.should.eql(0);
const node2 = namespace.addObject({
browseName: "Node2"
});
// let call a method that caches results
node2.getComponents().length.should.eql(0);
sinon.spy(node1 as any, "_clear_caches");
node1.addReference({
isForward: true,
nodeId: node2.nodeId,
referenceType: "HasComponent"
});
(node1 as any)._clear_caches.callCount.should.eql(1);
(node1 as any)._clear_caches.restore();
// let verify that cache has been cleared by calling method that caches results
// and verifying that results has changed as expected
node1.getComponents().length.should.eql(1);
node2.getComponents().length.should.eql(0);
(node1 as any).node2.browseName.toString().should.eql("1:Node2");
});
it("BaseNode#addReference (Inverse) internal cache must be invalidated", () => {
const node1 = namespace.addObject({
browseName: "Node1"
});
node1.getComponents().length.should.eql(0);
const node2 = namespace.addObject({
browseName: "Node2"
});
node2.getComponents().length.should.eql(0);
node2.addReference({
isForward: false,
nodeId: node1.nodeId,
referenceType: "HasComponent"
});
node1.getComponents().length.should.eql(1);
node2.getComponents().length.should.eql(0);
(node1 as any).node2.browseName.toString().should.eql("1:Node2");
});
it("BaseNode#namespaceIndex", () => {
const node1 = namespace.addObject({
browseName: "Node1"
});
node1.namespaceIndex.should.eql(1);
addressSpace.rootFolder.namespaceIndex.should.eql(0);
});
it("BaseNode#namespaceUri", () => {
const node1 = namespace.addObject({
browseName: "Node2"
});
node1.namespaceUri.should.eql("http://MYNAMESPACE");
addressSpace.rootFolder.namespaceUri.should.eql("http://opcfoundation.org/UA/");
});
it("AddressSpace#parent should provide a parent property to access parent node", () => {
const parentNode = namespace.addObject({
browseName: "ParentNode"
});
const child1 = namespace.addObject({ componentOf: parentNode, browseName: "Child1" });
child1.parent!.should.eql(parentNode);
const child2 = namespace.addObject({ propertyOf: parentNode, browseName: "Child2" });
child2.parent!.should.eql(parentNode);
const child3 = namespace.addObject({ organizedBy: parentNode, browseName: "Child3" });
should(child3.parent).eql(null, "OrganizedBy is not a Parent/Child relation");
});
}); | the_stack |
import {
DictionaryGetNullOptionalParams,
DictionaryGetNullResponse,
DictionaryGetEmptyOptionalParams,
DictionaryGetEmptyResponse,
DictionaryPutEmptyOptionalParams,
DictionaryGetNullValueOptionalParams,
DictionaryGetNullValueResponse,
DictionaryGetNullKeyOptionalParams,
DictionaryGetNullKeyResponse,
DictionaryGetEmptyStringKeyOptionalParams,
DictionaryGetEmptyStringKeyResponse,
DictionaryGetInvalidOptionalParams,
DictionaryGetInvalidResponse,
DictionaryGetBooleanTfftOptionalParams,
DictionaryGetBooleanTfftResponse,
DictionaryPutBooleanTfftOptionalParams,
DictionaryGetBooleanInvalidNullOptionalParams,
DictionaryGetBooleanInvalidNullResponse,
DictionaryGetBooleanInvalidStringOptionalParams,
DictionaryGetBooleanInvalidStringResponse,
DictionaryGetIntegerValidOptionalParams,
DictionaryGetIntegerValidResponse,
DictionaryPutIntegerValidOptionalParams,
DictionaryGetIntInvalidNullOptionalParams,
DictionaryGetIntInvalidNullResponse,
DictionaryGetIntInvalidStringOptionalParams,
DictionaryGetIntInvalidStringResponse,
DictionaryGetLongValidOptionalParams,
DictionaryGetLongValidResponse,
DictionaryPutLongValidOptionalParams,
DictionaryGetLongInvalidNullOptionalParams,
DictionaryGetLongInvalidNullResponse,
DictionaryGetLongInvalidStringOptionalParams,
DictionaryGetLongInvalidStringResponse,
DictionaryGetFloatValidOptionalParams,
DictionaryGetFloatValidResponse,
DictionaryPutFloatValidOptionalParams,
DictionaryGetFloatInvalidNullOptionalParams,
DictionaryGetFloatInvalidNullResponse,
DictionaryGetFloatInvalidStringOptionalParams,
DictionaryGetFloatInvalidStringResponse,
DictionaryGetDoubleValidOptionalParams,
DictionaryGetDoubleValidResponse,
DictionaryPutDoubleValidOptionalParams,
DictionaryGetDoubleInvalidNullOptionalParams,
DictionaryGetDoubleInvalidNullResponse,
DictionaryGetDoubleInvalidStringOptionalParams,
DictionaryGetDoubleInvalidStringResponse,
DictionaryGetStringValidOptionalParams,
DictionaryGetStringValidResponse,
DictionaryPutStringValidOptionalParams,
DictionaryGetStringWithNullOptionalParams,
DictionaryGetStringWithNullResponse,
DictionaryGetStringWithInvalidOptionalParams,
DictionaryGetStringWithInvalidResponse,
DictionaryGetDateValidOptionalParams,
DictionaryGetDateValidResponse,
DictionaryPutDateValidOptionalParams,
DictionaryGetDateInvalidNullOptionalParams,
DictionaryGetDateInvalidNullResponse,
DictionaryGetDateInvalidCharsOptionalParams,
DictionaryGetDateInvalidCharsResponse,
DictionaryGetDateTimeValidOptionalParams,
DictionaryGetDateTimeValidResponse,
DictionaryPutDateTimeValidOptionalParams,
DictionaryGetDateTimeInvalidNullOptionalParams,
DictionaryGetDateTimeInvalidNullResponse,
DictionaryGetDateTimeInvalidCharsOptionalParams,
DictionaryGetDateTimeInvalidCharsResponse,
DictionaryGetDateTimeRfc1123ValidOptionalParams,
DictionaryGetDateTimeRfc1123ValidResponse,
DictionaryPutDateTimeRfc1123ValidOptionalParams,
DictionaryGetDurationValidOptionalParams,
DictionaryGetDurationValidResponse,
DictionaryPutDurationValidOptionalParams,
DictionaryGetByteValidOptionalParams,
DictionaryGetByteValidResponse,
DictionaryPutByteValidOptionalParams,
DictionaryGetByteInvalidNullOptionalParams,
DictionaryGetByteInvalidNullResponse,
DictionaryGetBase64UrlOptionalParams,
DictionaryGetBase64UrlResponse,
DictionaryGetComplexNullOptionalParams,
DictionaryGetComplexNullResponse,
DictionaryGetComplexEmptyOptionalParams,
DictionaryGetComplexEmptyResponse,
DictionaryGetComplexItemNullOptionalParams,
DictionaryGetComplexItemNullResponse,
DictionaryGetComplexItemEmptyOptionalParams,
DictionaryGetComplexItemEmptyResponse,
DictionaryGetComplexValidOptionalParams,
DictionaryGetComplexValidResponse,
Widget,
DictionaryPutComplexValidOptionalParams,
DictionaryGetArrayNullOptionalParams,
DictionaryGetArrayNullResponse,
DictionaryGetArrayEmptyOptionalParams,
DictionaryGetArrayEmptyResponse,
DictionaryGetArrayItemNullOptionalParams,
DictionaryGetArrayItemNullResponse,
DictionaryGetArrayItemEmptyOptionalParams,
DictionaryGetArrayItemEmptyResponse,
DictionaryGetArrayValidOptionalParams,
DictionaryGetArrayValidResponse,
DictionaryPutArrayValidOptionalParams,
DictionaryGetDictionaryNullOptionalParams,
DictionaryGetDictionaryNullResponse,
DictionaryGetDictionaryEmptyOptionalParams,
DictionaryGetDictionaryEmptyResponse,
DictionaryGetDictionaryItemNullOptionalParams,
DictionaryGetDictionaryItemNullResponse,
DictionaryGetDictionaryItemEmptyOptionalParams,
DictionaryGetDictionaryItemEmptyResponse,
DictionaryGetDictionaryValidOptionalParams,
DictionaryGetDictionaryValidResponse,
DictionaryPutDictionaryValidOptionalParams
} from "../models";
/** Interface representing a Dictionary. */
export interface Dictionary {
/**
* Get null dictionary value
* @param options The options parameters.
*/
getNull(
options?: DictionaryGetNullOptionalParams
): Promise<DictionaryGetNullResponse>;
/**
* Get empty dictionary value {}
* @param options The options parameters.
*/
getEmpty(
options?: DictionaryGetEmptyOptionalParams
): Promise<DictionaryGetEmptyResponse>;
/**
* Set dictionary value empty {}
* @param arrayBody The empty dictionary value {}
* @param options The options parameters.
*/
putEmpty(
arrayBody: { [propertyName: string]: string },
options?: DictionaryPutEmptyOptionalParams
): Promise<void>;
/**
* Get Dictionary with null value
* @param options The options parameters.
*/
getNullValue(
options?: DictionaryGetNullValueOptionalParams
): Promise<DictionaryGetNullValueResponse>;
/**
* Get Dictionary with null key
* @param options The options parameters.
*/
getNullKey(
options?: DictionaryGetNullKeyOptionalParams
): Promise<DictionaryGetNullKeyResponse>;
/**
* Get Dictionary with key as empty string
* @param options The options parameters.
*/
getEmptyStringKey(
options?: DictionaryGetEmptyStringKeyOptionalParams
): Promise<DictionaryGetEmptyStringKeyResponse>;
/**
* Get invalid Dictionary value
* @param options The options parameters.
*/
getInvalid(
options?: DictionaryGetInvalidOptionalParams
): Promise<DictionaryGetInvalidResponse>;
/**
* Get boolean dictionary value {"0": true, "1": false, "2": false, "3": true }
* @param options The options parameters.
*/
getBooleanTfft(
options?: DictionaryGetBooleanTfftOptionalParams
): Promise<DictionaryGetBooleanTfftResponse>;
/**
* Set dictionary value empty {"0": true, "1": false, "2": false, "3": true }
* @param arrayBody The dictionary value {"0": true, "1": false, "2": false, "3": true }
* @param options The options parameters.
*/
putBooleanTfft(
arrayBody: { [propertyName: string]: boolean },
options?: DictionaryPutBooleanTfftOptionalParams
): Promise<void>;
/**
* Get boolean dictionary value {"0": true, "1": null, "2": false }
* @param options The options parameters.
*/
getBooleanInvalidNull(
options?: DictionaryGetBooleanInvalidNullOptionalParams
): Promise<DictionaryGetBooleanInvalidNullResponse>;
/**
* Get boolean dictionary value '{"0": true, "1": "boolean", "2": false}'
* @param options The options parameters.
*/
getBooleanInvalidString(
options?: DictionaryGetBooleanInvalidStringOptionalParams
): Promise<DictionaryGetBooleanInvalidStringResponse>;
/**
* Get integer dictionary value {"0": 1, "1": -1, "2": 3, "3": 300}
* @param options The options parameters.
*/
getIntegerValid(
options?: DictionaryGetIntegerValidOptionalParams
): Promise<DictionaryGetIntegerValidResponse>;
/**
* Set dictionary value empty {"0": 1, "1": -1, "2": 3, "3": 300}
* @param arrayBody The dictionary value {"0": 1, "1": -1, "2": 3, "3": 300}
* @param options The options parameters.
*/
putIntegerValid(
arrayBody: { [propertyName: string]: number },
options?: DictionaryPutIntegerValidOptionalParams
): Promise<void>;
/**
* Get integer dictionary value {"0": 1, "1": null, "2": 0}
* @param options The options parameters.
*/
getIntInvalidNull(
options?: DictionaryGetIntInvalidNullOptionalParams
): Promise<DictionaryGetIntInvalidNullResponse>;
/**
* Get integer dictionary value {"0": 1, "1": "integer", "2": 0}
* @param options The options parameters.
*/
getIntInvalidString(
options?: DictionaryGetIntInvalidStringOptionalParams
): Promise<DictionaryGetIntInvalidStringResponse>;
/**
* Get integer dictionary value {"0": 1, "1": -1, "2": 3, "3": 300}
* @param options The options parameters.
*/
getLongValid(
options?: DictionaryGetLongValidOptionalParams
): Promise<DictionaryGetLongValidResponse>;
/**
* Set dictionary value empty {"0": 1, "1": -1, "2": 3, "3": 300}
* @param arrayBody The dictionary value {"0": 1, "1": -1, "2": 3, "3": 300}
* @param options The options parameters.
*/
putLongValid(
arrayBody: { [propertyName: string]: number },
options?: DictionaryPutLongValidOptionalParams
): Promise<void>;
/**
* Get long dictionary value {"0": 1, "1": null, "2": 0}
* @param options The options parameters.
*/
getLongInvalidNull(
options?: DictionaryGetLongInvalidNullOptionalParams
): Promise<DictionaryGetLongInvalidNullResponse>;
/**
* Get long dictionary value {"0": 1, "1": "integer", "2": 0}
* @param options The options parameters.
*/
getLongInvalidString(
options?: DictionaryGetLongInvalidStringOptionalParams
): Promise<DictionaryGetLongInvalidStringResponse>;
/**
* Get float dictionary value {"0": 0, "1": -0.01, "2": 1.2e20}
* @param options The options parameters.
*/
getFloatValid(
options?: DictionaryGetFloatValidOptionalParams
): Promise<DictionaryGetFloatValidResponse>;
/**
* Set dictionary value {"0": 0, "1": -0.01, "2": 1.2e20}
* @param arrayBody The dictionary value {"0": 0, "1": -0.01, "2": 1.2e20}
* @param options The options parameters.
*/
putFloatValid(
arrayBody: { [propertyName: string]: number },
options?: DictionaryPutFloatValidOptionalParams
): Promise<void>;
/**
* Get float dictionary value {"0": 0.0, "1": null, "2": 1.2e20}
* @param options The options parameters.
*/
getFloatInvalidNull(
options?: DictionaryGetFloatInvalidNullOptionalParams
): Promise<DictionaryGetFloatInvalidNullResponse>;
/**
* Get boolean dictionary value {"0": 1.0, "1": "number", "2": 0.0}
* @param options The options parameters.
*/
getFloatInvalidString(
options?: DictionaryGetFloatInvalidStringOptionalParams
): Promise<DictionaryGetFloatInvalidStringResponse>;
/**
* Get float dictionary value {"0": 0, "1": -0.01, "2": 1.2e20}
* @param options The options parameters.
*/
getDoubleValid(
options?: DictionaryGetDoubleValidOptionalParams
): Promise<DictionaryGetDoubleValidResponse>;
/**
* Set dictionary value {"0": 0, "1": -0.01, "2": 1.2e20}
* @param arrayBody The dictionary value {"0": 0, "1": -0.01, "2": 1.2e20}
* @param options The options parameters.
*/
putDoubleValid(
arrayBody: { [propertyName: string]: number },
options?: DictionaryPutDoubleValidOptionalParams
): Promise<void>;
/**
* Get float dictionary value {"0": 0.0, "1": null, "2": 1.2e20}
* @param options The options parameters.
*/
getDoubleInvalidNull(
options?: DictionaryGetDoubleInvalidNullOptionalParams
): Promise<DictionaryGetDoubleInvalidNullResponse>;
/**
* Get boolean dictionary value {"0": 1.0, "1": "number", "2": 0.0}
* @param options The options parameters.
*/
getDoubleInvalidString(
options?: DictionaryGetDoubleInvalidStringOptionalParams
): Promise<DictionaryGetDoubleInvalidStringResponse>;
/**
* Get string dictionary value {"0": "foo1", "1": "foo2", "2": "foo3"}
* @param options The options parameters.
*/
getStringValid(
options?: DictionaryGetStringValidOptionalParams
): Promise<DictionaryGetStringValidResponse>;
/**
* Set dictionary value {"0": "foo1", "1": "foo2", "2": "foo3"}
* @param arrayBody The dictionary value {"0": "foo1", "1": "foo2", "2": "foo3"}
* @param options The options parameters.
*/
putStringValid(
arrayBody: { [propertyName: string]: string },
options?: DictionaryPutStringValidOptionalParams
): Promise<void>;
/**
* Get string dictionary value {"0": "foo", "1": null, "2": "foo2"}
* @param options The options parameters.
*/
getStringWithNull(
options?: DictionaryGetStringWithNullOptionalParams
): Promise<DictionaryGetStringWithNullResponse>;
/**
* Get string dictionary value {"0": "foo", "1": 123, "2": "foo2"}
* @param options The options parameters.
*/
getStringWithInvalid(
options?: DictionaryGetStringWithInvalidOptionalParams
): Promise<DictionaryGetStringWithInvalidResponse>;
/**
* Get integer dictionary value {"0": "2000-12-01", "1": "1980-01-02", "2": "1492-10-12"}
* @param options The options parameters.
*/
getDateValid(
options?: DictionaryGetDateValidOptionalParams
): Promise<DictionaryGetDateValidResponse>;
/**
* Set dictionary value {"0": "2000-12-01", "1": "1980-01-02", "2": "1492-10-12"}
* @param arrayBody The dictionary value {"0": "2000-12-01", "1": "1980-01-02", "2": "1492-10-12"}
* @param options The options parameters.
*/
putDateValid(
arrayBody: { [propertyName: string]: Date },
options?: DictionaryPutDateValidOptionalParams
): Promise<void>;
/**
* Get date dictionary value {"0": "2012-01-01", "1": null, "2": "1776-07-04"}
* @param options The options parameters.
*/
getDateInvalidNull(
options?: DictionaryGetDateInvalidNullOptionalParams
): Promise<DictionaryGetDateInvalidNullResponse>;
/**
* Get date dictionary value {"0": "2011-03-22", "1": "date"}
* @param options The options parameters.
*/
getDateInvalidChars(
options?: DictionaryGetDateInvalidCharsOptionalParams
): Promise<DictionaryGetDateInvalidCharsResponse>;
/**
* Get date-time dictionary value {"0": "2000-12-01t00:00:01z", "1": "1980-01-02T00:11:35+01:00", "2":
* "1492-10-12T10:15:01-08:00"}
* @param options The options parameters.
*/
getDateTimeValid(
options?: DictionaryGetDateTimeValidOptionalParams
): Promise<DictionaryGetDateTimeValidResponse>;
/**
* Set dictionary value {"0": "2000-12-01t00:00:01z", "1": "1980-01-02T00:11:35+01:00", "2":
* "1492-10-12T10:15:01-08:00"}
* @param arrayBody The dictionary value {"0": "2000-12-01t00:00:01z", "1":
* "1980-01-02T00:11:35+01:00", "2": "1492-10-12T10:15:01-08:00"}
* @param options The options parameters.
*/
putDateTimeValid(
arrayBody: { [propertyName: string]: Date },
options?: DictionaryPutDateTimeValidOptionalParams
): Promise<void>;
/**
* Get date dictionary value {"0": "2000-12-01t00:00:01z", "1": null}
* @param options The options parameters.
*/
getDateTimeInvalidNull(
options?: DictionaryGetDateTimeInvalidNullOptionalParams
): Promise<DictionaryGetDateTimeInvalidNullResponse>;
/**
* Get date dictionary value {"0": "2000-12-01t00:00:01z", "1": "date-time"}
* @param options The options parameters.
*/
getDateTimeInvalidChars(
options?: DictionaryGetDateTimeInvalidCharsOptionalParams
): Promise<DictionaryGetDateTimeInvalidCharsResponse>;
/**
* Get date-time-rfc1123 dictionary value {"0": "Fri, 01 Dec 2000 00:00:01 GMT", "1": "Wed, 02 Jan 1980
* 00:11:35 GMT", "2": "Wed, 12 Oct 1492 10:15:01 GMT"}
* @param options The options parameters.
*/
getDateTimeRfc1123Valid(
options?: DictionaryGetDateTimeRfc1123ValidOptionalParams
): Promise<DictionaryGetDateTimeRfc1123ValidResponse>;
/**
* Set dictionary value empty {"0": "Fri, 01 Dec 2000 00:00:01 GMT", "1": "Wed, 02 Jan 1980 00:11:35
* GMT", "2": "Wed, 12 Oct 1492 10:15:01 GMT"}
* @param arrayBody The dictionary value {"0": "Fri, 01 Dec 2000 00:00:01 GMT", "1": "Wed, 02 Jan 1980
* 00:11:35 GMT", "2": "Wed, 12 Oct 1492 10:15:01 GMT"}
* @param options The options parameters.
*/
putDateTimeRfc1123Valid(
arrayBody: { [propertyName: string]: Date },
options?: DictionaryPutDateTimeRfc1123ValidOptionalParams
): Promise<void>;
/**
* Get duration dictionary value {"0": "P123DT22H14M12.011S", "1": "P5DT1H0M0S"}
* @param options The options parameters.
*/
getDurationValid(
options?: DictionaryGetDurationValidOptionalParams
): Promise<DictionaryGetDurationValidResponse>;
/**
* Set dictionary value {"0": "P123DT22H14M12.011S", "1": "P5DT1H0M0S"}
* @param arrayBody The dictionary value {"0": "P123DT22H14M12.011S", "1": "P5DT1H0M0S"}
* @param options The options parameters.
*/
putDurationValid(
arrayBody: { [propertyName: string]: string },
options?: DictionaryPutDurationValidOptionalParams
): Promise<void>;
/**
* Get byte dictionary value {"0": hex(FF FF FF FA), "1": hex(01 02 03), "2": hex (25, 29, 43)} with
* each item encoded in base64
* @param options The options parameters.
*/
getByteValid(
options?: DictionaryGetByteValidOptionalParams
): Promise<DictionaryGetByteValidResponse>;
/**
* Put the dictionary value {"0": hex(FF FF FF FA), "1": hex(01 02 03), "2": hex (25, 29, 43)} with
* each elementencoded in base 64
* @param arrayBody The dictionary value {"0": hex(FF FF FF FA), "1": hex(01 02 03), "2": hex (25, 29,
* 43)} with each elementencoded in base 64
* @param options The options parameters.
*/
putByteValid(
arrayBody: { [propertyName: string]: Uint8Array },
options?: DictionaryPutByteValidOptionalParams
): Promise<void>;
/**
* Get byte dictionary value {"0": hex(FF FF FF FA), "1": null} with the first item base64 encoded
* @param options The options parameters.
*/
getByteInvalidNull(
options?: DictionaryGetByteInvalidNullOptionalParams
): Promise<DictionaryGetByteInvalidNullResponse>;
/**
* Get base64url dictionary value {"0": "a string that gets encoded with base64url", "1": "test
* string", "2": "Lorem ipsum"}
* @param options The options parameters.
*/
getBase64Url(
options?: DictionaryGetBase64UrlOptionalParams
): Promise<DictionaryGetBase64UrlResponse>;
/**
* Get dictionary of complex type null value
* @param options The options parameters.
*/
getComplexNull(
options?: DictionaryGetComplexNullOptionalParams
): Promise<DictionaryGetComplexNullResponse>;
/**
* Get empty dictionary of complex type {}
* @param options The options parameters.
*/
getComplexEmpty(
options?: DictionaryGetComplexEmptyOptionalParams
): Promise<DictionaryGetComplexEmptyResponse>;
/**
* Get dictionary of complex type with null item {"0": {"integer": 1, "string": "2"}, "1": null, "2":
* {"integer": 5, "string": "6"}}
* @param options The options parameters.
*/
getComplexItemNull(
options?: DictionaryGetComplexItemNullOptionalParams
): Promise<DictionaryGetComplexItemNullResponse>;
/**
* Get dictionary of complex type with empty item {"0": {"integer": 1, "string": "2"}, "1:" {}, "2":
* {"integer": 5, "string": "6"}}
* @param options The options parameters.
*/
getComplexItemEmpty(
options?: DictionaryGetComplexItemEmptyOptionalParams
): Promise<DictionaryGetComplexItemEmptyResponse>;
/**
* Get dictionary of complex type with {"0": {"integer": 1, "string": "2"}, "1": {"integer": 3,
* "string": "4"}, "2": {"integer": 5, "string": "6"}}
* @param options The options parameters.
*/
getComplexValid(
options?: DictionaryGetComplexValidOptionalParams
): Promise<DictionaryGetComplexValidResponse>;
/**
* Put an dictionary of complex type with values {"0": {"integer": 1, "string": "2"}, "1": {"integer":
* 3, "string": "4"}, "2": {"integer": 5, "string": "6"}}
* @param arrayBody Dictionary of complex type with {"0": {"integer": 1, "string": "2"}, "1":
* {"integer": 3, "string": "4"}, "2": {"integer": 5, "string": "6"}}
* @param options The options parameters.
*/
putComplexValid(
arrayBody: { [propertyName: string]: Widget },
options?: DictionaryPutComplexValidOptionalParams
): Promise<void>;
/**
* Get a null array
* @param options The options parameters.
*/
getArrayNull(
options?: DictionaryGetArrayNullOptionalParams
): Promise<DictionaryGetArrayNullResponse>;
/**
* Get an empty dictionary {}
* @param options The options parameters.
*/
getArrayEmpty(
options?: DictionaryGetArrayEmptyOptionalParams
): Promise<DictionaryGetArrayEmptyResponse>;
/**
* Get an dictionary of array of strings {"0": ["1", "2", "3"], "1": null, "2": ["7", "8", "9"]}
* @param options The options parameters.
*/
getArrayItemNull(
options?: DictionaryGetArrayItemNullOptionalParams
): Promise<DictionaryGetArrayItemNullResponse>;
/**
* Get an array of array of strings [{"0": ["1", "2", "3"], "1": [], "2": ["7", "8", "9"]}
* @param options The options parameters.
*/
getArrayItemEmpty(
options?: DictionaryGetArrayItemEmptyOptionalParams
): Promise<DictionaryGetArrayItemEmptyResponse>;
/**
* Get an array of array of strings {"0": ["1", "2", "3"], "1": ["4", "5", "6"], "2": ["7", "8", "9"]}
* @param options The options parameters.
*/
getArrayValid(
options?: DictionaryGetArrayValidOptionalParams
): Promise<DictionaryGetArrayValidResponse>;
/**
* Put An array of array of strings {"0": ["1", "2", "3"], "1": ["4", "5", "6"], "2": ["7", "8", "9"]}
* @param arrayBody An array of array of strings {"0": ["1", "2", "3"], "1": ["4", "5", "6"], "2":
* ["7", "8", "9"]}
* @param options The options parameters.
*/
putArrayValid(
arrayBody: { [propertyName: string]: string[] },
options?: DictionaryPutArrayValidOptionalParams
): Promise<void>;
/**
* Get an dictionaries of dictionaries with value null
* @param options The options parameters.
*/
getDictionaryNull(
options?: DictionaryGetDictionaryNullOptionalParams
): Promise<DictionaryGetDictionaryNullResponse>;
/**
* Get an dictionaries of dictionaries of type <string, string> with value {}
* @param options The options parameters.
*/
getDictionaryEmpty(
options?: DictionaryGetDictionaryEmptyOptionalParams
): Promise<DictionaryGetDictionaryEmptyResponse>;
/**
* Get an dictionaries of dictionaries of type <string, string> with value {"0": {"1": "one", "2":
* "two", "3": "three"}, "1": null, "2": {"7": "seven", "8": "eight", "9": "nine"}}
* @param options The options parameters.
*/
getDictionaryItemNull(
options?: DictionaryGetDictionaryItemNullOptionalParams
): Promise<DictionaryGetDictionaryItemNullResponse>;
/**
* Get an dictionaries of dictionaries of type <string, string> with value {"0": {"1": "one", "2":
* "two", "3": "three"}, "1": {}, "2": {"7": "seven", "8": "eight", "9": "nine"}}
* @param options The options parameters.
*/
getDictionaryItemEmpty(
options?: DictionaryGetDictionaryItemEmptyOptionalParams
): Promise<DictionaryGetDictionaryItemEmptyResponse>;
/**
* Get an dictionaries of dictionaries of type <string, string> with value {"0": {"1": "one", "2":
* "two", "3": "three"}, "1": {"4": "four", "5": "five", "6": "six"}, "2": {"7": "seven", "8": "eight",
* "9": "nine"}}
* @param options The options parameters.
*/
getDictionaryValid(
options?: DictionaryGetDictionaryValidOptionalParams
): Promise<DictionaryGetDictionaryValidResponse>;
/**
* Get an dictionaries of dictionaries of type <string, string> with value {"0": {"1": "one", "2":
* "two", "3": "three"}, "1": {"4": "four", "5": "five", "6": "six"}, "2": {"7": "seven", "8": "eight",
* "9": "nine"}}
* @param arrayBody An dictionaries of dictionaries of type <string, string> with value {"0": {"1":
* "one", "2": "two", "3": "three"}, "1": {"4": "four", "5": "five", "6": "six"}, "2": {"7": "seven",
* "8": "eight", "9": "nine"}}
* @param options The options parameters.
*/
putDictionaryValid(
arrayBody: { [propertyName: string]: { [propertyName: string]: string } },
options?: DictionaryPutDictionaryValidOptionalParams
): Promise<void>;
} | the_stack |
/*
utils.js
========
*/
/* Copyright 2017 Yahoo Inc.
* Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
*/
var utils = {
URL: window.URL || window.webkitURL || window.mozURL || window.msURL,
getUserMedia: (function () {
const getUserMedia =
navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
return getUserMedia ? getUserMedia.bind(navigator) : getUserMedia;
})(),
requestAnimFrame:
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame,
requestTimeout: function requestTimeout(callback, delay) {
callback = callback || utils.noop;
delay = delay || 0;
if (!utils.requestAnimFrame) {
return setTimeout(callback, delay);
}
const start = new Date().getTime();
const handle = new Object();
const requestAnimFrame = utils.requestAnimFrame;
const loop = function loop() {
const current = new Date().getTime();
const delta = current - start;
delta >= delay ? callback.call() : (handle.value = requestAnimFrame(loop));
};
handle.value = requestAnimFrame(loop);
return handle;
},
Blob:
window.Blob ||
window.BlobBuilder ||
window.WebKitBlobBuilder ||
window.MozBlobBuilder ||
window.MSBlobBuilder,
btoa: (function () {
const btoa =
window.btoa ||
function (input) {
let output = '';
let i = 0;
const l = input.length;
const key = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
let chr1 = void 0;
let chr2 = void 0;
let chr3 = void 0;
let enc1 = void 0;
let enc2 = void 0;
let enc3 = void 0;
let enc4 = void 0;
while (i < l) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output =
output + key.charAt(enc1) + key.charAt(enc2) + key.charAt(enc3) + key.charAt(enc4);
}
return output;
};
return btoa ? btoa.bind(window) : utils.noop;
})(),
isObject: function isObject(obj) {
return obj && Object.prototype.toString.call(obj) === '[object Object]';
},
isEmptyObject: function isEmptyObject(obj) {
return utils.isObject(obj) && !Object.keys(obj).length;
},
isArray: function isArray(arr) {
return arr && Array.isArray(arr);
},
isFunction: function isFunction(func) {
return func && typeof func === 'function';
},
isElement: function isElement(elem) {
return elem && elem.nodeType === 1;
},
isString: function isString(value) {
return typeof value === 'string' || Object.prototype.toString.call(value) === '[object String]';
},
isSupported: {
canvas: function canvas() {
const el = document.createElement('canvas');
return el && el.getContext && el.getContext('2d');
},
webworkers: function webworkers() {
return window.Worker;
},
blob: function blob() {
return utils.Blob;
},
Uint8Array: function Uint8Array() {
return window.Uint8Array;
},
Uint32Array: function Uint32Array() {
return window.Uint32Array;
},
videoCodecs: (function () {
const testEl = document.createElement('video');
const supportObj = {
mp4: false,
h264: false,
ogv: false,
ogg: false,
webm: false
};
try {
if (testEl && testEl.canPlayType) {
// Check for MPEG-4 support
supportObj.mp4 = testEl.canPlayType('video/mp4; codecs="mp4v.20.8"') !== '';
// Check for h264 support
supportObj.h264 =
(testEl.canPlayType('video/mp4; codecs="avc1.42E01E"') ||
testEl.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"')) !== '';
// Check for Ogv support
supportObj.ogv = testEl.canPlayType('video/ogg; codecs="theora"') !== '';
// Check for Ogg support
supportObj.ogg = testEl.canPlayType('video/ogg; codecs="theora"') !== '';
// Check for Webm support
supportObj.webm = testEl.canPlayType('video/webm; codecs="vp8, vorbis"') !== -1;
}
} catch (e) {}
return supportObj;
})()
},
noop: function noop() {},
each: function each(collection, callback) {
let x = void 0;
let len = void 0;
if (utils.isArray(collection)) {
x = -1;
len = collection.length;
while (++x < len) {
if (callback(x, collection[x]) === false) {
break;
}
}
} else if (utils.isObject(collection)) {
for (x in collection) {
if (collection.hasOwnProperty(x)) {
if (callback(x, collection[x]) === false) {
break;
}
}
}
}
},
normalizeOptions: function normalizeOptions(defaultOptions, userOptions) {
if (!utils.isObject(defaultOptions) || !utils.isObject(userOptions) || !Object.keys) {
return;
}
const newObj = {};
utils.each(defaultOptions, function (key, val) {
newObj[key] = defaultOptions[key];
});
utils.each(userOptions, function (key, val) {
const currentUserOption = userOptions[key];
if (!utils.isObject(currentUserOption)) {
newObj[key] = currentUserOption;
} else if (!defaultOptions[key]) {
newObj[key] = currentUserOption;
} else {
newObj[key] = utils.normalizeOptions(defaultOptions[key], currentUserOption);
}
});
return newObj;
},
setCSSAttr: function setCSSAttr(elem, attr, val) {
if (!utils.isElement(elem)) {
return;
}
if (utils.isString(attr) && utils.isString(val)) {
elem.style[attr] = val;
} else if (utils.isObject(attr)) {
utils.each(attr, function (key, val) {
elem.style[key] = val;
});
}
},
removeElement: function removeElement(node) {
if (!utils.isElement(node)) {
return;
}
if (node.parentNode) {
node.parentNode.removeChild(node);
}
},
createWebWorker: function createWebWorker(content) {
if (!utils.isString(content)) {
return {};
}
try {
const blob = new utils.Blob([content], {
type: 'text/javascript'
});
const objectUrl = utils.URL.createObjectURL(blob);
const worker = new Worker(objectUrl);
return {
objectUrl,
worker
};
} catch (e) {
return `${e}`;
}
},
getExtension: function getExtension(src) {
return src.substr(src.lastIndexOf('.') + 1, src.length);
},
getFontSize: function getFontSize() {
const options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
if (!document.body || options.resizeFont === false) {
return options.fontSize;
}
const text = options.text;
const containerWidth = options.gifWidth;
let fontSize = parseInt(options.fontSize, 10);
const minFontSize = parseInt(options.minFontSize, 10);
const div = document.createElement('div');
const span = document.createElement('span');
div.setAttribute('width', containerWidth);
div.appendChild(span);
span.innerHTML = text;
span.style.fontSize = `${fontSize}px`;
span.style.textIndent = '-9999px';
span.style.visibility = 'hidden';
document.body.appendChild(span);
while (span.offsetWidth > containerWidth && fontSize >= minFontSize) {
span.style.fontSize = `${--fontSize}px`;
}
document.body.removeChild(span);
return `${fontSize}px`;
},
webWorkerError: false
};
const utils$2 = Object.freeze({
default: utils
});
/*
error.js
========
*/
/* Copyright 2017 Yahoo Inc.
* Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
*/
// Dependencies
var error = {
validate: function validate(skipObj) {
skipObj = utils.isObject(skipObj) ? skipObj : {};
let errorObj = {};
utils.each(error.validators, function (indece, currentValidator) {
const errorCode = currentValidator.errorCode;
if (!skipObj[errorCode] && !currentValidator.condition) {
errorObj = currentValidator;
errorObj.error = true;
return false;
}
});
delete errorObj.condition;
return errorObj;
},
isValid: function isValid(skipObj) {
const errorObj = error.validate(skipObj);
const isValid = errorObj.error !== true;
return isValid;
},
validators: [
{
condition: utils.isFunction(utils.getUserMedia),
errorCode: 'getUserMedia',
errorMsg: 'The getUserMedia API is not supported in your browser'
},
{
condition: utils.isSupported.canvas(),
errorCode: 'canvas',
errorMsg: 'Canvas elements are not supported in your browser'
},
{
condition: utils.isSupported.webworkers(),
errorCode: 'webworkers',
errorMsg: 'The Web Workers API is not supported in your browser'
},
{
condition: utils.isFunction(utils.URL),
errorCode: 'window.URL',
errorMsg: 'The window.URL API is not supported in your browser'
},
{
condition: utils.isSupported.blob(),
errorCode: 'window.Blob',
errorMsg: 'The window.Blob File API is not supported in your browser'
},
{
condition: utils.isSupported.Uint8Array(),
errorCode: 'window.Uint8Array',
errorMsg: 'The window.Uint8Array function constructor is not supported in your browser'
},
{
condition: utils.isSupported.Uint32Array(),
errorCode: 'window.Uint32Array',
errorMsg: 'The window.Uint32Array function constructor is not supported in your browser'
}
],
messages: {
videoCodecs: {
errorCode: 'videocodec',
errorMsg: 'The video codec you are trying to use is not supported in your browser'
}
}
};
const error$2 = Object.freeze({
default: error
});
/*
defaultOptions.js
=================
*/
/* Copyright 2017 Yahoo Inc.
* Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
*/
// Helpers
const noop = function noop() {};
const defaultOptions = {
sampleInterval: 10,
numWorkers: 2,
filter: '',
gifWidth: 200,
gifHeight: 200,
interval: 0.1,
numFrames: 10,
frameDuration: 1,
keepCameraOn: false,
images: [],
video: null,
webcamVideoElement: null,
cameraStream: null,
text: '',
fontWeight: 'normal',
fontSize: '16px',
minFontSize: '10px',
resizeFont: false,
fontFamily: 'sans-serif',
fontColor: '#ffffff',
textAlign: 'center',
textBaseline: 'bottom',
textXCoordinate: null,
textYCoordinate: null,
progressCallback: noop,
completeCallback: noop,
saveRenderingContexts: false,
savedRenderingContexts: [],
crossOrigin: 'Anonymous'
};
const defaultOptions$2 = Object.freeze({
default: defaultOptions
});
/*
isSupported.js
==============
*/
/* Copyright 2017 Yahoo Inc.
* Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
*/
// Dependencies
function isSupported() {
return error.isValid();
}
/*
isWebCamGIFSupported.js
=======================
*/
/* Copyright 2017 Yahoo Inc.
* Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
*/
function isWebCamGIFSupported() {
return error.isValid();
}
/*
isSupported.js
==============
*/
/* Copyright 2017 Yahoo Inc.
* Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
*/
// Dependencies
function isSupported$1() {
const options = {
getUserMedia: true
};
return error.isValid(options);
}
/*
isExistingVideoGIFSupported.js
==============================
*/
/* Copyright 2017 Yahoo Inc.
* Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
*/
// Dependencies
function isExistingVideoGIFSupported(codecs) {
let hasValidCodec = false;
if (utils.isArray(codecs) && codecs.length) {
utils.each(codecs, function (indece, currentCodec) {
if (utils.isSupported.videoCodecs[currentCodec]) {
hasValidCodec = true;
}
});
if (!hasValidCodec) {
return false;
}
} else if (utils.isString(codecs) && codecs.length) {
if (!utils.isSupported.videoCodecs[codecs]) {
return false;
}
}
return error.isValid({
getUserMedia: true
});
}
/*
NeuQuant.js
===========
*/
/*
* NeuQuant Neural-Net Quantization Algorithm
* ------------------------------------------
*
* Copyright (c) 1994 Anthony Dekker
*
* NEUQUANT Neural-Net quantization algorithm by Anthony Dekker, 1994. See
* "Kohonen neural networks for optimal colour quantization" in "Network:
* Computation in Neural Systems" Vol. 5 (1994) pp 351-367. for a discussion of
* the algorithm.
*
* Any party obtaining a copy of these files from the author, directly or
* indirectly, is granted, free of charge, a full and unrestricted irrevocable,
* world-wide, paid up, royalty-free, nonexclusive right and license to deal in
* this software and documentation files (the "Software"), including without
* limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons who
* receive copies from any such party to do so, with the only requirement being
* that this copyright notice remain intact.
*/
/*
* This class handles Neural-Net quantization algorithm
* @author Kevin Weiner (original Java version - kweiner@fmsware.com)
* @author Thibault Imbert (AS3 version - bytearray.org)
* @version 0.1 AS3 implementation
* @version 0.2 JS->AS3 "translation" by antimatter15
* @version 0.3 JS clean up + using modern JS idioms by sole - http://soledadpenades.com
* Also implement fix in color conversion described at http://stackoverflow.com/questions/16371712/neuquant-js-javascript-color-quantization-hidden-bug-in-js-conversion
*/
function NeuQuant() {
const netsize = 256; // number of colours used
// four primes near 500 - assume no image has a length so large
// that it is divisible by all four primes
const prime1 = 499;
const prime2 = 491;
const prime3 = 487;
const prime4 = 503;
// minimum size for input image
const minpicturebytes = 3 * prime4;
// Network Definitions
const maxnetpos = netsize - 1;
const netbiasshift = 4; // bias for colour values
const ncycles = 100; // no. of learning cycles
// defs for freq and bias
const intbiasshift = 16; // bias for fractions
const intbias = 1 << intbiasshift;
const gammashift = 10; // gamma = 1024
const gamma = 1 << gammashift;
const betashift = 10;
const beta = intbias >> betashift; // beta = 1/1024
const betagamma = intbias << (gammashift - betashift);
// defs for decreasing radius factor
// For 256 colors, radius starts at 32.0 biased by 6 bits
// and decreases by a factor of 1/30 each cycle
const initrad = netsize >> 3;
const radiusbiasshift = 6;
const radiusbias = 1 << radiusbiasshift;
const initradius = initrad * radiusbias;
const radiusdec = 30;
// defs for decreasing alpha factor
// Alpha starts at 1.0 biased by 10 bits
const alphabiasshift = 10;
const initalpha = 1 << alphabiasshift;
let alphadec;
// radbias and alpharadbias used for radpower calculation
const radbiasshift = 8;
const radbias = 1 << radbiasshift;
const alpharadbshift = alphabiasshift + radbiasshift;
const alpharadbias = 1 << alpharadbshift;
// Input image
let thepicture;
// Height * Width * 3
let lengthcount;
// Sampling factor 1..30
let samplefac;
// The network itself
let network;
const netindex = [];
// for network lookup - really 256
const bias = [];
// bias and freq arrays for learning
const freq = [];
const radpower = [];
function NeuQuantConstructor(thepic, len, sample) {
let i;
let p;
thepicture = thepic;
lengthcount = len;
samplefac = sample;
network = new Array(netsize);
for (i = 0; i < netsize; i++) {
network[i] = new Array(4);
p = network[i];
p[0] = p[1] = p[2] = ((i << (netbiasshift + 8)) / netsize) | 0;
freq[i] = (intbias / netsize) | 0; // 1 / netsize
bias[i] = 0;
}
}
function colorMap() {
const map = [];
const index = new Array(netsize);
for (let i = 0; i < netsize; i++) {
index[network[i][3]] = i;
}
let k = 0;
for (let l = 0; l < netsize; l++) {
const j = index[l];
map[k++] = network[j][0];
map[k++] = network[j][1];
map[k++] = network[j][2];
}
return map;
}
// Insertion sort of network and building of netindex[0..255]
// (to do after unbias)
function inxbuild() {
let i;
let j;
let smallpos;
let smallval;
let p;
let q;
let previouscol;
let startpos;
previouscol = 0;
startpos = 0;
for (i = 0; i < netsize; i++) {
p = network[i];
smallpos = i;
smallval = p[1]; // index on g
// find smallest in i..netsize-1
for (j = i + 1; j < netsize; j++) {
q = network[j];
if (q[1] < smallval) {
// index on g
smallpos = j;
smallval = q[1]; // index on g
}
}
q = network[smallpos];
// swap p (i) and q (smallpos) entries
if (i != smallpos) {
j = q[0];
q[0] = p[0];
p[0] = j;
j = q[1];
q[1] = p[1];
p[1] = j;
j = q[2];
q[2] = p[2];
p[2] = j;
j = q[3];
q[3] = p[3];
p[3] = j;
}
// smallval entry is now in position i
if (smallval != previouscol) {
netindex[previouscol] = (startpos + i) >> 1;
for (j = previouscol + 1; j < smallval; j++) {
netindex[j] = i;
}
previouscol = smallval;
startpos = i;
}
}
netindex[previouscol] = (startpos + maxnetpos) >> 1;
for (j = previouscol + 1; j < 256; j++) {
netindex[j] = maxnetpos; // really 256
}
}
// Main Learning Loop
function learn() {
let i;
let j;
let b;
let g;
let r;
let radius;
let rad;
let alpha;
let step;
let delta;
let samplepixels;
let p;
let pix;
let lim;
if (lengthcount < minpicturebytes) {
samplefac = 1;
}
alphadec = 30 + (samplefac - 1) / 3;
p = thepicture;
pix = 0;
lim = lengthcount;
samplepixels = lengthcount / (3 * samplefac);
delta = (samplepixels / ncycles) | 0;
alpha = initalpha;
radius = initradius;
rad = radius >> radiusbiasshift;
if (rad <= 1) {
rad = 0;
}
for (i = 0; i < rad; i++) {
radpower[i] = alpha * (((rad * rad - i * i) * radbias) / (rad * rad));
}
if (lengthcount < minpicturebytes) {
step = 3;
} else if (lengthcount % prime1 !== 0) {
step = 3 * prime1;
} else if (lengthcount % prime2 !== 0) {
step = 3 * prime2;
} else if (lengthcount % prime3 !== 0) {
step = 3 * prime3;
} else {
step = 3 * prime4;
}
i = 0;
while (i < samplepixels) {
b = (p[pix + 0] & 0xff) << netbiasshift;
g = (p[pix + 1] & 0xff) << netbiasshift;
r = (p[pix + 2] & 0xff) << netbiasshift;
j = contest(b, g, r);
altersingle(alpha, j, b, g, r);
if (rad !== 0) {
// Alter neighbours
alterneigh(rad, j, b, g, r);
}
pix += step;
if (pix >= lim) {
pix -= lengthcount;
}
i++;
if (delta === 0) {
delta = 1;
}
if (i % delta === 0) {
alpha -= alpha / alphadec;
radius -= radius / radiusdec;
rad = radius >> radiusbiasshift;
if (rad <= 1) {
rad = 0;
}
for (j = 0; j < rad; j++) {
radpower[j] = alpha * (((rad * rad - j * j) * radbias) / (rad * rad));
}
}
}
}
// Search for BGR values 0..255 (after net is unbiased) and return colour index
function map(b, g, r) {
let i;
let j;
let dist;
let a;
let bestd;
let p;
let best;
// Biggest possible distance is 256 * 3
bestd = 1000;
best = -1;
i = netindex[g]; // index on g
j = i - 1; // start at netindex[g] and work outwards
while (i < netsize || j >= 0) {
if (i < netsize) {
p = network[i];
dist = p[1] - g; // inx key
if (dist >= bestd) {
i = netsize; // stop iter
} else {
i++;
if (dist < 0) {
dist = -dist;
}
a = p[0] - b;
if (a < 0) {
a = -a;
}
dist += a;
if (dist < bestd) {
a = p[2] - r;
if (a < 0) {
a = -a;
}
dist += a;
if (dist < bestd) {
bestd = dist;
best = p[3];
}
}
}
}
if (j >= 0) {
p = network[j];
dist = g - p[1]; // inx key - reverse dif
if (dist >= bestd) {
j = -1; // stop iter
} else {
j--;
if (dist < 0) {
dist = -dist;
}
a = p[0] - b;
if (a < 0) {
a = -a;
}
dist += a;
if (dist < bestd) {
a = p[2] - r;
if (a < 0) {
a = -a;
}
dist += a;
if (dist < bestd) {
bestd = dist;
best = p[3];
}
}
}
}
}
return best;
}
function process() {
learn();
unbiasnet();
inxbuild();
return colorMap();
}
// Unbias network to give byte values 0..255 and record position i
// to prepare for sort
function unbiasnet() {
let i;
let j;
for (i = 0; i < netsize; i++) {
network[i][0] >>= netbiasshift;
network[i][1] >>= netbiasshift;
network[i][2] >>= netbiasshift;
network[i][3] = i; // record colour no
}
}
// Move adjacent neurons by precomputed alpha*(1-((i-j)^2/[r]^2))
// in radpower[|i-j|]
function alterneigh(rad, i, b, g, r) {
let j;
let k;
let lo;
let hi;
let a;
let m;
let p;
lo = i - rad;
if (lo < -1) {
lo = -1;
}
hi = i + rad;
if (hi > netsize) {
hi = netsize;
}
j = i + 1;
k = i - 1;
m = 1;
while (j < hi || k > lo) {
a = radpower[m++];
if (j < hi) {
p = network[j++];
try {
p[0] -= ((a * (p[0] - b)) / alpharadbias) | 0;
p[1] -= ((a * (p[1] - g)) / alpharadbias) | 0;
p[2] -= ((a * (p[2] - r)) / alpharadbias) | 0;
} catch (e) {}
}
if (k > lo) {
p = network[k--];
try {
p[0] -= ((a * (p[0] - b)) / alpharadbias) | 0;
p[1] -= ((a * (p[1] - g)) / alpharadbias) | 0;
p[2] -= ((a * (p[2] - r)) / alpharadbias) | 0;
} catch (e) {}
}
}
}
// Move neuron i towards biased (b,g,r) by factor alpha
function altersingle(alpha, i, b, g, r) {
// alter hit neuron
const n = network[i];
const alphaMult = alpha / initalpha;
n[0] -= (alphaMult * (n[0] - b)) | 0;
n[1] -= (alphaMult * (n[1] - g)) | 0;
n[2] -= (alphaMult * (n[2] - r)) | 0;
}
// Search for biased BGR values
function contest(b, g, r) {
// finds closest neuron (min dist) and updates freq
// finds best neuron (min dist-bias) and returns position
// for frequently chosen neurons, freq[i] is high and bias[i] is negative
// bias[i] = gamma*((1/netsize)-freq[i])
let i;
let dist;
let a;
let biasdist;
let betafreq;
let bestpos;
let bestbiaspos;
let bestd;
let bestbiasd;
let n;
bestd = ~(1 << 31);
bestbiasd = bestd;
bestpos = -1;
bestbiaspos = bestpos;
for (i = 0; i < netsize; i++) {
n = network[i];
dist = n[0] - b;
if (dist < 0) {
dist = -dist;
}
a = n[1] - g;
if (a < 0) {
a = -a;
}
dist += a;
a = n[2] - r;
if (a < 0) {
a = -a;
}
dist += a;
if (dist < bestd) {
bestd = dist;
bestpos = i;
}
biasdist = dist - (bias[i] >> (intbiasshift - netbiasshift));
if (biasdist < bestbiasd) {
bestbiasd = biasdist;
bestbiaspos = i;
}
betafreq = freq[i] >> betashift;
freq[i] -= betafreq;
bias[i] += betafreq << gammashift;
}
freq[bestpos] += beta;
bias[bestpos] -= betagamma;
return bestbiaspos;
}
NeuQuantConstructor.apply(this, arguments);
const exports = {};
exports.map = map;
exports.process = process;
return exports;
}
/*
processFrameWorker.js
=====================
*/
/* Copyright 2017 Yahoo Inc.
* Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
*/
function workerCode() {
const self = this;
try {
globalThis.onmessage = function (ev) {
const data = ev.data || {};
let response;
if (data.gifshot) {
response = workerMethods.run(data);
postMessage(response);
}
};
} catch (e) {}
var workerMethods = {
dataToRGB: function dataToRGB(data, width, height) {
const length = width * height * 4;
let i = 0;
const rgb = [];
while (i < length) {
rgb.push(data[i++]);
rgb.push(data[i++]);
rgb.push(data[i++]);
i++; // for the alpha channel which we don't care about
}
return rgb;
},
componentizedPaletteToArray: function componentizedPaletteToArray(paletteRGB) {
paletteRGB = paletteRGB || [];
const paletteArray = [];
for (let i = 0; i < paletteRGB.length; i += 3) {
const r = paletteRGB[i];
const g = paletteRGB[i + 1];
const b = paletteRGB[i + 2];
paletteArray.push((r << 16) | (g << 8) | b);
}
return paletteArray;
},
// This is the "traditional" Animated_GIF style of going from RGBA to indexed color frames
processFrameWithQuantizer: function processFrameWithQuantizer(
imageData,
width,
height,
sampleInterval
) {
const rgbComponents = this.dataToRGB(imageData, width, height);
const nq = new NeuQuant(rgbComponents, rgbComponents.length, sampleInterval);
const paletteRGB = nq.process();
const paletteArray = new Uint32Array(this.componentizedPaletteToArray(paletteRGB));
const numberPixels = width * height;
const indexedPixels = new Uint8Array(numberPixels);
let k = 0;
for (let i = 0; i < numberPixels; i++) {
const r = rgbComponents[k++];
const g = rgbComponents[k++];
const b = rgbComponents[k++];
indexedPixels[i] = nq.map(r, g, b);
}
return {
pixels: indexedPixels,
palette: paletteArray
};
},
run: function run(frame) {
frame = frame || {};
const _frame = frame;
const height = _frame.height;
const palette = _frame.palette;
const sampleInterval = _frame.sampleInterval;
const width = _frame.width;
const imageData = frame.data;
return this.processFrameWithQuantizer(imageData, width, height, sampleInterval);
}
};
return workerMethods;
}
/*
gifWriter.js
============
*/
// (c) Dean McNamee <dean@gmail.com>, 2013.
//
// https://github.com/deanm/omggif
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
// omggif is a JavaScript implementation of a GIF 89a encoder and decoder,
// including animation and compression. It does not rely on any specific
// underlying system, so should run in the browser, Node, or Plask.
function gifWriter(buf, width, height, gopts) {
let p = 0;
gopts = gopts === undefined ? {} : gopts;
const loop_count = gopts.loop === undefined ? null : gopts.loop;
const global_palette = gopts.palette === undefined ? null : gopts.palette;
if (width <= 0 || height <= 0 || width > 65535 || height > 65535) throw 'Width/Height invalid.';
function check_palette_and_num_colors(palette) {
const num_colors = palette.length;
if (num_colors < 2 || num_colors > 256 || num_colors & (num_colors - 1))
throw 'Invalid code/color length, must be power of 2 and 2 .. 256.';
return num_colors;
}
// - Header.
buf[p++] = 0x47;
buf[p++] = 0x49;
buf[p++] = 0x46; // GIF
buf[p++] = 0x38;
buf[p++] = 0x39;
buf[p++] = 0x61; // 89a
// Handling of Global Color Table (palette) and background index.
const gp_num_colors_pow2 = 0;
const background = 0;
// - Logical Screen Descriptor.
// NOTE(deanm): w/h apparently ignored by implementations, but set anyway.
buf[p++] = width & 0xff;
buf[p++] = (width >> 8) & 0xff;
buf[p++] = height & 0xff;
buf[p++] = (height >> 8) & 0xff;
// NOTE: Indicates 0-bpp original color resolution (unused?).
buf[p++] =
(global_palette !== null ? 0x80 : 0) | // Global Color Table Flag.
gp_num_colors_pow2; // NOTE: No sort flag (unused?).
buf[p++] = background; // Background Color Index.
buf[p++] = 0; // Pixel aspect ratio (unused?).
if (loop_count !== null) {
// Netscape block for looping.
if (loop_count < 0 || loop_count > 65535) throw 'Loop count invalid.';
// Extension code, label, and length.
buf[p++] = 0x21;
buf[p++] = 0xff;
buf[p++] = 0x0b;
// NETSCAPE2.0
buf[p++] = 0x4e;
buf[p++] = 0x45;
buf[p++] = 0x54;
buf[p++] = 0x53;
buf[p++] = 0x43;
buf[p++] = 0x41;
buf[p++] = 0x50;
buf[p++] = 0x45;
buf[p++] = 0x32;
buf[p++] = 0x2e;
buf[p++] = 0x30;
// Sub-block
buf[p++] = 0x03;
buf[p++] = 0x01;
buf[p++] = loop_count & 0xff;
buf[p++] = (loop_count >> 8) & 0xff;
buf[p++] = 0x00; // Terminator.
}
let ended = false;
this.addFrame = function (x, y, w, h, indexed_pixels, opts) {
if (ended === true) {
--p;
ended = false;
} // Un-end.
opts = opts === undefined ? {} : opts;
// TODO(deanm): Bounds check x, y. Do they need to be within the virtual
// canvas width/height, I imagine?
if (x < 0 || y < 0 || x > 65535 || y > 65535) throw 'x/y invalid.';
if (w <= 0 || h <= 0 || w > 65535 || h > 65535) throw 'Width/Height invalid.';
if (indexed_pixels.length < w * h) throw 'Not enough pixels for the frame size.';
let using_local_palette = true;
let palette = opts.palette;
if (palette === undefined || palette === null) {
using_local_palette = false;
palette = global_palette;
}
if (palette === undefined || palette === null)
throw 'Must supply either a local or global palette.';
let num_colors = check_palette_and_num_colors(palette);
// Compute the min_code_size (power of 2), destroying num_colors.
let min_code_size = 0;
while ((num_colors >>= 1)) {
++min_code_size;
}
num_colors = 1 << min_code_size; // Now we can easily get it back.
const delay = opts.delay === undefined ? 0 : opts.delay;
// From the spec:
// 0 - No disposal specified. The decoder is
// not required to take any action.
// 1 - Do not dispose. The graphic is to be left
// in place.
// 2 - Restore to background color. The area used by the
// graphic must be restored to the background color.
// 3 - Restore to previous. The decoder is required to
// restore the area overwritten by the graphic with
// what was there prior to rendering the graphic.
// 4-7 - To be defined.
// NOTE(deanm): Dispose background doesn't really work, apparently most
// browsers ignore the background palette index and clear to transparency.
const disposal = opts.disposal === undefined ? 0 : opts.disposal;
if (disposal < 0 || disposal > 3)
// 4-7 is reserved.
throw 'Disposal out of range.';
let use_transparency = false;
let transparent_index = 0;
if (opts.transparent !== undefined && opts.transparent !== null) {
use_transparency = true;
transparent_index = opts.transparent;
if (transparent_index < 0 || transparent_index >= num_colors)
throw 'Transparent color index.';
}
if (disposal !== 0 || use_transparency || delay !== 0) {
// - Graphics Control Extension
buf[p++] = 0x21;
buf[p++] = 0xf9; // Extension / Label.
buf[p++] = 4; // Byte size.
buf[p++] = (disposal << 2) | (use_transparency === true ? 1 : 0);
buf[p++] = delay & 0xff;
buf[p++] = (delay >> 8) & 0xff;
buf[p++] = transparent_index; // Transparent color index.
buf[p++] = 0; // Block Terminator.
}
// - Image Descriptor
buf[p++] = 0x2c; // Image Seperator.
buf[p++] = x & 0xff;
buf[p++] = (x >> 8) & 0xff; // Left.
buf[p++] = y & 0xff;
buf[p++] = (y >> 8) & 0xff; // Top.
buf[p++] = w & 0xff;
buf[p++] = (w >> 8) & 0xff;
buf[p++] = h & 0xff;
buf[p++] = (h >> 8) & 0xff;
// NOTE: No sort flag (unused?).
// TODO(deanm): Support interlace.
buf[p++] = using_local_palette === true ? 0x80 | (min_code_size - 1) : 0;
// - Local Color Table
if (using_local_palette === true) {
for (let i = 0, il = palette.length; i < il; ++i) {
const rgb = palette[i];
buf[p++] = (rgb >> 16) & 0xff;
buf[p++] = (rgb >> 8) & 0xff;
buf[p++] = rgb & 0xff;
}
}
p = GifWriterOutputLZWCodeStream(buf, p, min_code_size < 2 ? 2 : min_code_size, indexed_pixels);
};
this.end = function () {
if (ended === false) {
buf[p++] = 0x3b; // Trailer.
ended = true;
}
return p;
};
// Main compression routine, palette indexes -> LZW code stream.
// |index_stream| must have at least one entry.
function GifWriterOutputLZWCodeStream(buf, p, min_code_size, index_stream) {
buf[p++] = min_code_size;
let cur_subblock = p++; // Pointing at the length field.
const clear_code = 1 << min_code_size;
const code_mask = clear_code - 1;
const eoi_code = clear_code + 1;
let next_code = eoi_code + 1;
let cur_code_size = min_code_size + 1; // Number of bits per code.
let cur_shift = 0;
// We have at most 12-bit codes, so we should have to hold a max of 19
// bits here (and then we would write out).
let cur = 0;
function emit_bytes_to_buffer(bit_block_size) {
while (cur_shift >= bit_block_size) {
buf[p++] = cur & 0xff;
cur >>= 8;
cur_shift -= 8;
if (p === cur_subblock + 256) {
// Finished a subblock.
buf[cur_subblock] = 255;
cur_subblock = p++;
}
}
}
function emit_code(c) {
cur |= c << cur_shift;
cur_shift += cur_code_size;
emit_bytes_to_buffer(8);
}
// I am not an expert on the topic, and I don't want to write a thesis.
// However, it is good to outline here the basic algorithm and the few data
// structures and optimizations here that make this implementation fast.
// The basic idea behind LZW is to build a table of previously seen runs
// addressed by a short id (herein called output code). All data is
// referenced by a code, which represents one or more values from the
// original input stream. All input bytes can be referenced as the same
// value as an output code. So if you didn't want any compression, you
// could more or less just output the original bytes as codes (there are
// some details to this, but it is the idea). In order to achieve
// compression, values greater then the input range (codes can be up to
// 12-bit while input only 8-bit) represent a sequence of previously seen
// inputs. The decompressor is able to build the same mapping while
// decoding, so there is always a shared common knowledge between the
// encoding and decoder, which is also important for "timing" aspects like
// how to handle variable bit width code encoding.
//
// One obvious but very important consequence of the table system is there
// is always a unique id (at most 12-bits) to map the runs. 'A' might be
// 4, then 'AA' might be 10, 'AAA' 11, 'AAAA' 12, etc. This relationship
// can be used for an effecient lookup strategy for the code mapping. We
// need to know if a run has been seen before, and be able to map that run
// to the output code. Since we start with known unique ids (input bytes),
// and then from those build more unique ids (table entries), we can
// continue this chain (almost like a linked list) to always have small
// integer values that represent the current byte chains in the encoder.
// This means instead of tracking the input bytes (AAAABCD) to know our
// current state, we can track the table entry for AAAABC (it is guaranteed
// to exist by the nature of the algorithm) and the next character D.
// Therefor the tuple of (table_entry, byte) is guaranteed to also be
// unique. This allows us to create a simple lookup key for mapping input
// sequences to codes (table indices) without having to store or search
// any of the code sequences. So if 'AAAA' has a table entry of 12, the
// tuple of ('AAAA', K) for any input byte K will be unique, and can be our
// key. This leads to a integer value at most 20-bits, which can always
// fit in an SMI value and be used as a fast sparse array / object key.
// Output code for the current contents of the index buffer.
let ib_code = index_stream[0] & code_mask; // Load first input index.
let code_table = {}; // Key'd on our 20-bit "tuple".
emit_code(clear_code); // Spec says first code should be a clear code.
// First index already loaded, process the rest of the stream.
for (let i = 1, il = index_stream.length; i < il; ++i) {
const k = index_stream[i] & code_mask;
const cur_key = (ib_code << 8) | k; // (prev, k) unique tuple.
const cur_code = code_table[cur_key]; // buffer + k.
// Check if we have to create a new code table entry.
if (cur_code === undefined) {
// We don't have buffer + k.
// Emit index buffer (without k).
// This is an inline version of emit_code, because this is the core
// writing routine of the compressor (and V8 cannot inline emit_code
// because it is a closure here in a different context). Additionally
// we can call emit_byte_to_buffer less often, because we can have
// 30-bits (from our 31-bit signed SMI), and we know our codes will only
// be 12-bits, so can safely have 18-bits there without overflow.
// emit_code(ib_code);
cur |= ib_code << cur_shift;
cur_shift += cur_code_size;
while (cur_shift >= 8) {
buf[p++] = cur & 0xff;
cur >>= 8;
cur_shift -= 8;
if (p === cur_subblock + 256) {
// Finished a subblock.
buf[cur_subblock] = 255;
cur_subblock = p++;
}
}
if (next_code === 4096) {
// Table full, need a clear.
emit_code(clear_code);
next_code = eoi_code + 1;
cur_code_size = min_code_size + 1;
code_table = {};
} else {
// Table not full, insert a new entry.
// Increase our variable bit code sizes if necessary. This is a bit
// tricky as it is based on "timing" between the encoding and
// decoder. From the encoders perspective this should happen after
// we've already emitted the index buffer and are about to create the
// first table entry that would overflow our current code bit size.
if (next_code >= 1 << cur_code_size) ++cur_code_size;
code_table[cur_key] = next_code++; // Insert into code table.
}
ib_code = k; // Index buffer to single input k.
} else {
ib_code = cur_code; // Index buffer to sequence in code table.
}
}
emit_code(ib_code); // There will still be something in the index buffer.
emit_code(eoi_code); // End Of Information.
// Flush / finalize the sub-blocks stream to the buffer.
emit_bytes_to_buffer(1);
// Finish the sub-blocks, writing out any unfinished lengths and
// terminating with a sub-block of length 0. If we have already started
// but not yet used a sub-block it can just become the terminator.
if (cur_subblock + 1 === p) {
// Started but unused.
buf[cur_subblock] = 0;
} else {
// Started and used, write length and additional terminator block.
buf[cur_subblock] = p - cur_subblock - 1;
buf[p++] = 0;
}
return p;
}
}
/*
animatedGIF.js
==============
*/
/* Copyright 2017 Yahoo Inc.
* Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
*/
// Dependencies
// Helpers
const noop$2 = function noop() {};
const AnimatedGIF = function AnimatedGIF(options) {
this.canvas = null;
this.ctx = null;
this.repeat = 0;
this.frames = [];
this.numRenderedFrames = 0;
this.onRenderCompleteCallback = noop$2;
this.onRenderProgressCallback = noop$2;
this.workers = [];
this.availableWorkers = [];
this.generatingGIF = false;
this.options = options;
// Constructs and initializes the the web workers appropriately
this.initializeWebWorkers(options);
};
AnimatedGIF.prototype = {
workerMethods: workerCode(),
initializeWebWorkers: function initializeWebWorkers(options) {
const self = this;
const processFrameWorkerCode = `${NeuQuant.toString()}(${workerCode.toString()}());`;
let webWorkerObj = void 0;
let objectUrl = void 0;
let webWorker = void 0;
let numWorkers = void 0;
let x = -1;
let workerError = '';
numWorkers = options.numWorkers;
while (++x < numWorkers) {
webWorkerObj = utils.createWebWorker(processFrameWorkerCode);
if (utils.isObject(webWorkerObj)) {
objectUrl = webWorkerObj.objectUrl;
webWorker = webWorkerObj.worker;
self.workers.push({
worker: webWorker,
objectUrl
});
self.availableWorkers.push(webWorker);
} else {
workerError = webWorkerObj;
utils.webWorkerError = Boolean(webWorkerObj);
}
}
this.workerError = workerError;
this.canvas = document.createElement('canvas');
this.canvas.width = options.gifWidth;
this.canvas.height = options.gifHeight;
this.ctx = this.canvas.getContext('2d');
this.frames = [];
},
// Return a worker for processing a frame
getWorker: function getWorker() {
return this.availableWorkers.pop();
},
// Restores a worker to the pool
freeWorker: function freeWorker(worker) {
this.availableWorkers.push(worker);
},
byteMap: (function () {
const byteMap = [];
for (let i = 0; i < 256; i++) {
byteMap[i] = String.fromCharCode(i);
}
return byteMap;
})(),
bufferToString: function bufferToString(buffer) {
const numberValues = buffer.length;
let str = '';
let x = -1;
while (++x < numberValues) {
str += this.byteMap[buffer[x]];
}
return str;
},
onFrameFinished: function onFrameFinished(progressCallback) {
// The GIF is not written until we're done with all the frames
// because they might not be processed in the same order
const self = this;
const frames = self.frames;
const options = self.options;
const hasExistingImages = Boolean((options.images || []).length);
const allDone = frames.every(function (frame) {
return !frame.beingProcessed && frame.done;
});
self.numRenderedFrames++;
if (hasExistingImages) {
progressCallback(self.numRenderedFrames / frames.length);
}
self.onRenderProgressCallback((self.numRenderedFrames * 0.75) / frames.length);
if (allDone) {
if (!self.generatingGIF) {
self.generateGIF(frames, self.onRenderCompleteCallback);
}
} else {
utils.requestTimeout(function () {
self.processNextFrame();
}, 1);
}
},
processFrame: function processFrame(position) {
const AnimatedGifContext = this;
const options = this.options;
const _options = this.options;
const progressCallback = _options.progressCallback;
const sampleInterval = _options.sampleInterval;
const frames = this.frames;
let frame = void 0;
let worker = void 0;
const done = function done() {
const ev = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const data = ev.data;
// Delete original data, and free memory
delete frame.data;
frame.pixels = Array.prototype.slice.call(data.pixels);
frame.palette = Array.prototype.slice.call(data.palette);
frame.done = true;
frame.beingProcessed = false;
AnimatedGifContext.freeWorker(worker);
AnimatedGifContext.onFrameFinished(progressCallback);
};
frame = frames[position];
if (frame.beingProcessed || frame.done) {
this.onFrameFinished();
return;
}
frame.sampleInterval = sampleInterval;
frame.beingProcessed = true;
frame.gifshot = true;
worker = this.getWorker();
if (worker) {
// Process the frame in a web worker
worker.onmessage = done;
worker.postMessage(frame);
} else {
// Process the frame in the current thread
done({
data: AnimatedGifContext.workerMethods.run(frame)
});
}
},
startRendering: function startRendering(completeCallback) {
this.onRenderCompleteCallback = completeCallback;
for (let i = 0; i < this.options.numWorkers && i < this.frames.length; i++) {
this.processFrame(i);
}
},
processNextFrame: function processNextFrame() {
let position = -1;
for (let i = 0; i < this.frames.length; i++) {
const frame = this.frames[i];
if (!frame.done && !frame.beingProcessed) {
position = i;
break;
}
}
if (position >= 0) {
this.processFrame(position);
}
},
// Takes the already processed data in frames and feeds it to a new
// GifWriter instance in order to get the binary GIF file
generateGIF: function generateGIF(frames, callback) {
// TODO: Weird: using a simple JS array instead of a typed array,
// the files are WAY smaller o_o. Patches/explanations welcome!
const buffer = []; // new Uint8Array(width * height * frames.length * 5);
const gifOptions = {
loop: this.repeat
};
const options = this.options;
const interval = options.interval;
const frameDuration = options.frameDuration;
const existingImages = options.images;
const hasExistingImages = Boolean(existingImages.length);
const height = options.gifHeight;
const width = options.gifWidth;
const gifWriter$$1 = new gifWriter(buffer, width, height, gifOptions);
const onRenderProgressCallback = this.onRenderProgressCallback;
const delay = hasExistingImages ? interval * 100 : 0;
let bufferToString = void 0;
let gif = void 0;
this.generatingGIF = true;
utils.each(frames, function (iterator, frame) {
const framePalette = frame.palette;
onRenderProgressCallback(0.75 + (0.25 * frame.position * 1.0) / frames.length);
for (let i = 0; i < frameDuration; i++) {
gifWriter$$1.addFrame(0, 0, width, height, frame.pixels, {
palette: framePalette,
delay
});
}
});
gifWriter$$1.end();
onRenderProgressCallback(1.0);
this.frames = [];
this.generatingGIF = false;
if (utils.isFunction(callback)) {
bufferToString = this.bufferToString(buffer);
gif = `data:image/gif;base64,${utils.btoa(bufferToString)}`;
callback(gif);
}
},
// From GIF: 0 = loop forever, null = not looping, n > 0 = loop n times and stop
setRepeat: function setRepeat(r) {
this.repeat = r;
},
addFrame: function addFrame(element, gifshotOptions) {
gifshotOptions = utils.isObject(gifshotOptions) ? gifshotOptions : {};
const self = this;
const ctx = self.ctx;
const options = self.options;
const width = options.gifWidth;
const height = options.gifHeight;
const fontSize = utils.getFontSize(gifshotOptions);
const _gifshotOptions = gifshotOptions;
const filter = _gifshotOptions.filter;
const fontColor = _gifshotOptions.fontColor;
const fontFamily = _gifshotOptions.fontFamily;
const fontWeight = _gifshotOptions.fontWeight;
const gifHeight = _gifshotOptions.gifHeight;
const gifWidth = _gifshotOptions.gifWidth;
const text = _gifshotOptions.text;
const textAlign = _gifshotOptions.textAlign;
const textBaseline = _gifshotOptions.textBaseline;
const textXCoordinate = gifshotOptions.textXCoordinate
? gifshotOptions.textXCoordinate
: textAlign === 'left'
? 1
: textAlign === 'right'
? width
: width / 2;
const textYCoordinate = gifshotOptions.textYCoordinate
? gifshotOptions.textYCoordinate
: textBaseline === 'top'
? 1
: textBaseline === 'center'
? height / 2
: height;
const font = `${fontWeight} ${fontSize} ${fontFamily}`;
let imageData = void 0;
try {
ctx.filter = filter;
ctx.drawImage(element, 0, 0, width, height);
if (text) {
ctx.font = font;
ctx.fillStyle = fontColor;
ctx.textAlign = textAlign;
ctx.textBaseline = textBaseline;
ctx.fillText(text, textXCoordinate, textYCoordinate);
}
imageData = ctx.getImageData(0, 0, width, height);
self.addFrameImageData(imageData);
} catch (e) {
return `${e}`;
}
},
addFrameImageData: function addFrameImageData() {
const imageData = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const frames = this.frames;
const imageDataArray = imageData.data;
this.frames.push({
data: imageDataArray,
width: imageData.width,
height: imageData.height,
palette: null,
dithering: null,
done: false,
beingProcessed: false,
position: frames.length
});
},
onRenderProgress: function onRenderProgress(callback) {
this.onRenderProgressCallback = callback;
},
isRendering: function isRendering() {
return this.generatingGIF;
},
getBase64GIF: function getBase64GIF(completeCallback) {
const self = this;
const onRenderComplete = function onRenderComplete(gif) {
self.destroyWorkers();
utils.requestTimeout(function () {
completeCallback(gif);
}, 0);
};
self.startRendering(onRenderComplete);
},
destroyWorkers: function destroyWorkers() {
if (this.workerError) {
return;
}
const workers = this.workers;
// Explicitly ask web workers to die so they are explicitly GC'ed
utils.each(workers, function (iterator, workerObj) {
const worker = workerObj.worker;
const objectUrl = workerObj.objectUrl;
worker.terminate();
utils.URL.revokeObjectURL(objectUrl);
});
}
};
/*
getBase64GIF.js
===============
*/
/* Copyright 2017 Yahoo Inc.
* Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
*/
function getBase64GIF(animatedGifInstance, callback) {
// This is asynchronous, rendered with WebWorkers
animatedGifInstance.getBase64GIF(function (image) {
callback({
error: false,
errorCode: '',
errorMsg: '',
image
});
});
}
/*
existingImages.js
=================
*/
/* Copyright 2017 Yahoo Inc.
* Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
*/
function existingImages() {
const obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const self = this;
const callback = obj.callback;
const images = obj.images;
const options = obj.options;
let imagesLength = obj.imagesLength;
const skipObj = {
getUserMedia: true,
'window.URL': true
};
const errorObj = error.validate(skipObj);
const loadedImages = [];
let loadedImagesLength = 0;
let tempImage = void 0;
let ag = void 0;
if (errorObj.error) {
return callback(errorObj);
}
// change workerPath to point to where Animated_GIF.worker.js is
ag = new AnimatedGIF(options);
utils.each(images, function (index, image) {
const currentImage = image;
// if (image.src) {
// currentImage = currentImage.src;
// }
if (utils.isElement(currentImage)) {
if (options.crossOrigin) {
currentImage.crossOrigin = options.crossOrigin;
}
loadedImages[index] = currentImage;
loadedImagesLength += 1;
if (loadedImagesLength === imagesLength) {
addLoadedImagesToGif();
}
} else if (utils.isString(currentImage)) {
tempImage = new Image();
if (options.crossOrigin) {
tempImage.crossOrigin = options.crossOrigin;
}
(function (tempImage) {
if (image.text) {
tempImage.text = image.text;
}
tempImage.onerror = function (e) {
let obj = void 0;
--imagesLength; // skips over images that error out
if (imagesLength === 0) {
obj = {};
obj.error = 'None of the requested images was capable of being retrieved';
return callback(obj);
}
};
tempImage.onload = function (e) {
if (image.text) {
loadedImages[index] = {
img: tempImage,
text: tempImage.text
};
} else {
loadedImages[index] = tempImage;
}
loadedImagesLength += 1;
if (loadedImagesLength === imagesLength) {
addLoadedImagesToGif();
}
utils.removeElement(tempImage);
};
tempImage.src = currentImage;
})(tempImage);
utils.setCSSAttr(tempImage, {
position: 'fixed',
opacity: '0'
});
document.body.appendChild(tempImage);
}
});
function addLoadedImagesToGif() {
utils.each(loadedImages, function (index, loadedImage) {
if (loadedImage) {
if (loadedImage.text) {
ag.addFrame(loadedImage.img, options, loadedImage.text);
} else {
ag.addFrame(loadedImage, options);
}
}
});
getBase64GIF(ag, callback);
}
}
/*
screenShot.js
=============
*/
/* Copyright 2017 Yahoo Inc.
* Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
*/
// Dependencies
// Helpers
const noop$3 = function noop() {};
const screenShot = {
getGIF: function getGIF() {
const options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let callback = arguments[1];
callback = utils.isFunction(callback) ? callback : noop$3;
const canvas = document.createElement('canvas');
let context = void 0;
const existingImages = options.images;
const hasExistingImages = Boolean(existingImages.length);
const cameraStream = options.cameraStream;
const crop = options.crop;
const filter = options.filter;
const fontColor = options.fontColor;
const fontFamily = options.fontFamily;
const fontWeight = options.fontWeight;
const keepCameraOn = options.keepCameraOn;
const numWorkers = options.numWorkers;
const progressCallback = options.progressCallback;
const saveRenderingContexts = options.saveRenderingContexts;
const savedRenderingContexts = options.savedRenderingContexts;
const text = options.text;
const textAlign = options.textAlign;
const textBaseline = options.textBaseline;
const videoElement = options.videoElement;
const videoHeight = options.videoHeight;
const videoWidth = options.videoWidth;
const webcamVideoElement = options.webcamVideoElement;
const gifWidth = Number(options.gifWidth);
const gifHeight = Number(options.gifHeight);
let interval = Number(options.interval);
const sampleInterval = Number(options.sampleInterval);
const waitBetweenFrames = hasExistingImages ? 0 : interval * 1000;
const renderingContextsToSave = [];
let numFrames = savedRenderingContexts.length
? savedRenderingContexts.length
: options.numFrames;
let pendingFrames = numFrames;
const ag = new AnimatedGIF(options);
const fontSize = utils.getFontSize(options);
const textXCoordinate = options.textXCoordinate
? options.textXCoordinate
: textAlign === 'left'
? 1
: textAlign === 'right'
? gifWidth
: gifWidth / 2;
const textYCoordinate = options.textYCoordinate
? options.textYCoordinate
: textBaseline === 'top'
? 1
: textBaseline === 'center'
? gifHeight / 2
: gifHeight;
const font = `${fontWeight} ${fontSize} ${fontFamily}`;
let sourceX = crop ? Math.floor(crop.scaledWidth / 2) : 0;
let sourceWidth = crop ? videoWidth - crop.scaledWidth : 0;
let sourceY = crop ? Math.floor(crop.scaledHeight / 2) : 0;
let sourceHeight = crop ? videoHeight - crop.scaledHeight : 0;
const captureFrames = function captureSingleFrame() {
const framesLeft = pendingFrames - 1;
if (savedRenderingContexts.length) {
context.putImageData(savedRenderingContexts[numFrames - pendingFrames], 0, 0);
finishCapture();
} else {
drawVideo();
}
function drawVideo() {
try {
// Makes sure the canvas video heights/widths are in bounds
if (sourceWidth > videoWidth) {
sourceWidth = videoWidth;
}
if (sourceHeight > videoHeight) {
sourceHeight = videoHeight;
}
if (sourceX < 0) {
sourceX = 0;
}
if (sourceY < 0) {
sourceY = 0;
}
context.filter = filter;
context.drawImage(
videoElement,
sourceX,
sourceY,
sourceWidth,
sourceHeight,
0,
0,
gifWidth,
gifHeight
);
finishCapture();
} catch (e) {
// There is a Firefox bug that sometimes throws NS_ERROR_NOT_AVAILABLE and
// and IndexSizeError errors when drawing a video element to the canvas
if (e.name === 'NS_ERROR_NOT_AVAILABLE') {
// Wait 100ms before trying again
utils.requestTimeout(drawVideo, 100);
} else {
throw e;
}
}
}
function finishCapture() {
let imageData = void 0;
if (saveRenderingContexts) {
renderingContextsToSave.push(context.getImageData(0, 0, gifWidth, gifHeight));
}
// If there is text to display, make sure to display it on the canvas after the image is drawn
if (text) {
context.font = font;
context.fillStyle = fontColor;
context.textAlign = textAlign;
context.textBaseline = textBaseline;
context.fillText(text, textXCoordinate, textYCoordinate);
}
imageData = context.getImageData(0, 0, gifWidth, gifHeight);
ag.addFrameImageData(imageData);
pendingFrames = framesLeft;
// Call back with an r value indicating how far along we are in capture
progressCallback((numFrames - pendingFrames) / numFrames);
if (framesLeft > 0) {
// test
utils.requestTimeout(captureSingleFrame, waitBetweenFrames);
}
if (!pendingFrames) {
ag.getBase64GIF(function (image) {
callback({
error: false,
errorCode: '',
errorMsg: '',
image,
cameraStream,
videoElement,
webcamVideoElement,
savedRenderingContexts: renderingContextsToSave,
keepCameraOn
});
});
}
}
};
numFrames = numFrames !== undefined ? numFrames : 10;
interval = interval !== undefined ? interval : 0.1; // In seconds
canvas.width = gifWidth;
canvas.height = gifHeight;
context = canvas.getContext('2d');
(function capture() {
if (!savedRenderingContexts.length && videoElement.currentTime === 0) {
utils.requestTimeout(capture, 100);
return;
}
captureFrames();
})();
},
getCropDimensions: function getCropDimensions() {
const obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const width = obj.videoWidth;
const height = obj.videoHeight;
const gifWidth = obj.gifWidth;
const gifHeight = obj.gifHeight;
const result = {
width: 0,
height: 0,
scaledWidth: 0,
scaledHeight: 0
};
if (width > height) {
result.width = Math.round(width * (gifHeight / height)) - gifWidth;
result.scaledWidth = Math.round(result.width * (height / gifHeight));
} else {
result.height = Math.round(height * (gifWidth / width)) - gifHeight;
result.scaledHeight = Math.round(result.height * (width / gifWidth));
}
return result;
}
};
/*
videoStream.js
==============
*/
/* Copyright 2017 Yahoo Inc.
* Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
*/
// Dependencies
var videoStream = {
loadedData: false,
defaultVideoDimensions: {
width: 640,
height: 480
},
findVideoSize: function findVideoSizeMethod(obj) {
findVideoSizeMethod.attempts = findVideoSizeMethod.attempts || 0;
const cameraStream = obj.cameraStream;
const completedCallback = obj.completedCallback;
const videoElement = obj.videoElement;
if (!videoElement) {
return;
}
if (videoElement.videoWidth > 0 && videoElement.videoHeight > 0) {
videoElement.removeEventListener('loadeddata', videoStream.findVideoSize);
completedCallback({
videoElement,
cameraStream,
videoWidth: videoElement.videoWidth,
videoHeight: videoElement.videoHeight
});
} else if (findVideoSizeMethod.attempts < 10) {
findVideoSizeMethod.attempts += 1;
utils.requestTimeout(function () {
videoStream.findVideoSize(obj);
}, 400);
} else {
completedCallback({
videoElement,
cameraStream,
videoWidth: videoStream.defaultVideoDimensions.width,
videoHeight: videoStream.defaultVideoDimensions.height
});
}
},
onStreamingTimeout: function onStreamingTimeout(callback) {
if (utils.isFunction(callback)) {
callback({
error: true,
errorCode: 'getUserMedia',
errorMsg:
'There was an issue with the getUserMedia API - Timed out while trying to start streaming',
image: null,
cameraStream: {}
});
}
},
stream: function stream(obj) {
const existingVideo = utils.isArray(obj.existingVideo)
? obj.existingVideo[0]
: obj.existingVideo;
const cameraStream = obj.cameraStream;
const completedCallback = obj.completedCallback;
const streamedCallback = obj.streamedCallback;
const videoElement = obj.videoElement;
if (utils.isFunction(streamedCallback)) {
streamedCallback();
}
if (existingVideo) {
if (utils.isString(existingVideo)) {
videoElement.src = existingVideo;
videoElement.innerHTML = `<source src="${existingVideo}" type="video/${utils.getExtension(
existingVideo
)}" />`;
} else if (existingVideo instanceof Blob) {
try {
videoElement.src = utils.URL.createObjectURL(existingVideo);
} catch (e) {}
videoElement.innerHTML = `<source src="${existingVideo}" type="${existingVideo.type}" />`;
}
} else if (videoElement.mozSrcObject) {
videoElement.mozSrcObject = cameraStream;
} else if (utils.URL) {
try {
videoElement.srcObject = cameraStream;
videoElement.src = utils.URL.createObjectURL(cameraStream);
} catch (e) {
videoElement.srcObject = cameraStream;
}
}
videoElement.play();
utils.requestTimeout(function checkLoadedData() {
checkLoadedData.count = checkLoadedData.count || 0;
if (videoStream.loadedData === true) {
videoStream.findVideoSize({
videoElement,
cameraStream,
completedCallback
});
videoStream.loadedData = false;
} else {
checkLoadedData.count += 1;
if (checkLoadedData.count > 10) {
videoStream.findVideoSize({
videoElement,
cameraStream,
completedCallback
});
} else {
checkLoadedData();
}
}
}, 0);
},
startStreaming: function startStreaming(obj) {
const errorCallback = utils.isFunction(obj.error) ? obj.error : utils.noop;
const streamedCallback = utils.isFunction(obj.streamed) ? obj.streamed : utils.noop;
const completedCallback = utils.isFunction(obj.completed) ? obj.completed : utils.noop;
const crossOrigin = obj.crossOrigin;
const existingVideo = obj.existingVideo;
const lastCameraStream = obj.lastCameraStream;
const options = obj.options;
const webcamVideoElement = obj.webcamVideoElement;
const videoElement = utils.isElement(existingVideo)
? existingVideo
: webcamVideoElement
? webcamVideoElement
: document.createElement('video');
const cameraStream = void 0;
if (crossOrigin) {
videoElement.crossOrigin = options.crossOrigin;
}
videoElement.autoplay = true;
videoElement.loop = true;
videoElement.muted = true;
videoElement.addEventListener('loadeddata', function (event) {
videoStream.loadedData = true;
if (options.offset) {
videoElement.currentTime = options.offset;
}
});
if (existingVideo) {
videoStream.stream({
videoElement,
existingVideo,
completedCallback
});
} else if (lastCameraStream) {
videoStream.stream({
videoElement,
cameraStream: lastCameraStream,
streamedCallback,
completedCallback
});
} else {
utils.getUserMedia(
{
video: true
},
function (stream) {
videoStream.stream({
videoElement,
cameraStream: stream,
streamedCallback,
completedCallback
});
},
errorCallback
);
}
},
startVideoStreaming: function startVideoStreaming(callback) {
const options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
const timeoutLength = options.timeout !== undefined ? options.timeout : 0;
const originalCallback = options.callback;
const webcamVideoElement = options.webcamVideoElement;
let noGetUserMediaSupportTimeout = void 0;
// Some browsers apparently have support for video streaming because of the
// presence of the getUserMedia function, but then do not answer our
// calls for streaming.
// So we'll set up this timeout and if nothing happens after a while, we'll
// conclude that there's no actual getUserMedia support.
if (timeoutLength > 0) {
noGetUserMediaSupportTimeout = utils.requestTimeout(function () {
videoStream.onStreamingTimeout(originalCallback);
}, 10000);
}
videoStream.startStreaming({
error: function error() {
originalCallback({
error: true,
errorCode: 'getUserMedia',
errorMsg:
'There was an issue with the getUserMedia API - the user probably denied permission',
image: null,
cameraStream: {}
});
},
streamed: function streamed() {
// The streaming started somehow, so we can assume there is getUserMedia support
clearTimeout(noGetUserMediaSupportTimeout);
},
completed: function completed() {
const obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const cameraStream = obj.cameraStream;
const videoElement = obj.videoElement;
const videoHeight = obj.videoHeight;
const videoWidth = obj.videoWidth;
callback({
cameraStream,
videoElement,
videoHeight,
videoWidth
});
},
lastCameraStream: options.lastCameraStream,
webcamVideoElement,
crossOrigin: options.crossOrigin,
options
});
},
stopVideoStreaming: function stopVideoStreaming(obj) {
obj = utils.isObject(obj) ? obj : {};
const _obj = obj;
const keepCameraOn = _obj.keepCameraOn;
const videoElement = _obj.videoElement;
const webcamVideoElement = _obj.webcamVideoElement;
const cameraStream = obj.cameraStream || {};
const cameraStreamTracks = cameraStream.getTracks ? cameraStream.getTracks() || [] : [];
const hasCameraStreamTracks = Boolean(cameraStreamTracks.length);
const firstCameraStreamTrack = cameraStreamTracks[0];
if (!keepCameraOn && hasCameraStreamTracks) {
if (utils.isFunction(firstCameraStreamTrack.stop)) {
// Stops the camera stream
firstCameraStreamTrack.stop();
}
}
if (utils.isElement(videoElement) && !webcamVideoElement) {
// Pauses the video, revokes the object URL (freeing up memory), and remove the video element
videoElement.pause();
// Destroys the object url
if (utils.isFunction(utils.URL.revokeObjectURL) && !utils.webWorkerError) {
if (videoElement.src) {
utils.URL.revokeObjectURL(videoElement.src);
}
}
// Removes the video element from the DOM
utils.removeElement(videoElement);
}
}
};
/*
stopVideoStreaming.js
=====================
*/
/* Copyright 2017 Yahoo Inc.
* Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
*/
function stopVideoStreaming(options) {
options = utils.isObject(options) ? options : {};
videoStream.stopVideoStreaming(options);
}
/*
createAndGetGIF.js
==================
*/
/* Copyright 2017 Yahoo Inc.
* Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
*/
// Dependencies
function createAndGetGIF(obj, callback) {
const options = obj.options || {};
const images = options.images;
const video = options.video;
const gifWidth = Number(options.gifWidth);
const gifHeight = Number(options.gifHeight);
const numFrames = Number(options.numFrames);
const cameraStream = obj.cameraStream;
const videoElement = obj.videoElement;
const videoWidth = obj.videoWidth;
const videoHeight = obj.videoHeight;
const cropDimensions = screenShot.getCropDimensions({
videoWidth,
videoHeight,
gifHeight,
gifWidth
});
const completeCallback = callback;
options.crop = cropDimensions;
options.videoElement = videoElement;
options.videoWidth = videoWidth;
options.videoHeight = videoHeight;
options.cameraStream = cameraStream;
if (!utils.isElement(videoElement)) {
return;
}
videoElement.width = gifWidth + cropDimensions.width;
videoElement.height = gifHeight + cropDimensions.height;
if (!options.webcamVideoElement) {
utils.setCSSAttr(videoElement, {
position: 'fixed',
opacity: '0'
});
document.body.appendChild(videoElement);
}
// Firefox doesn't seem to obey autoplay if the element is not in the DOM when the content
// is loaded, so we must manually trigger play after adding it, or the video will be frozen
videoElement.play();
screenShot.getGIF(options, function (obj) {
if ((!images || !images.length) && (!video || !video.length)) {
stopVideoStreaming(obj);
}
completeCallback(obj);
});
}
/*
existingVideo.js
================
*/
/* Copyright 2017 Yahoo Inc.
* Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
*/
// Dependencies
function existingVideo() {
const obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const callback = obj.callback;
let existingVideo = obj.existingVideo;
const options = obj.options;
const skipObj = {
getUserMedia: true,
'window.URL': true
};
const errorObj = error.validate(skipObj);
const loadedImages = 0;
let videoType = void 0;
let videoSrc = void 0;
const tempImage = void 0;
const ag = void 0;
if (errorObj.error) {
return callback(errorObj);
}
if (utils.isElement(existingVideo) && existingVideo.src) {
videoSrc = existingVideo.src;
videoType = utils.getExtension(videoSrc);
if (!utils.isSupported.videoCodecs[videoType]) {
return callback(error.messages.videoCodecs);
}
} else if (utils.isArray(existingVideo)) {
utils.each(existingVideo, function (iterator, videoSrc) {
if (videoSrc instanceof Blob) {
videoType = videoSrc.type.substr(videoSrc.type.lastIndexOf('/') + 1, videoSrc.length);
} else {
videoType = videoSrc.substr(videoSrc.lastIndexOf('.') + 1, videoSrc.length);
}
if (utils.isSupported.videoCodecs[videoType]) {
existingVideo = videoSrc;
return false;
}
});
}
videoStream.startStreaming({
completed: function completed(obj) {
obj.options = options || {};
createAndGetGIF(obj, callback);
},
existingVideo,
crossOrigin: options.crossOrigin,
options
});
}
/*
existingWebcam.js
=================
*/
/* Copyright 2017 Yahoo Inc.
* Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
*/
// Dependencies
function existingWebcam() {
const obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const callback = obj.callback;
const lastCameraStream = obj.lastCameraStream;
const options = obj.options;
const webcamVideoElement = obj.webcamVideoElement;
if (!isWebCamGIFSupported()) {
return callback(error.validate());
}
if (options.savedRenderingContexts.length) {
screenShot.getGIF(options, function (obj) {
callback(obj);
});
return;
}
videoStream.startVideoStreaming(
function () {
const obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
obj.options = options || {};
createAndGetGIF(obj, callback);
},
{
lastCameraStream,
callback,
webcamVideoElement,
crossOrigin: options.crossOrigin
}
);
}
/*
createGIF.js
============
*/
/* Copyright 2017 Yahoo Inc.
* Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
*/
// Dependencies
function createGIF(userOptions, callback) {
callback = utils.isFunction(userOptions) ? userOptions : callback;
userOptions = utils.isObject(userOptions) ? userOptions : {};
if (!utils.isFunction(callback)) {
return;
}
let options = utils.normalizeOptions(defaultOptions, userOptions) || {};
const lastCameraStream = userOptions.cameraStream;
const images = options.images;
const imagesLength = images ? images.length : 0;
const video = options.video;
const webcamVideoElement = options.webcamVideoElement;
options = utils.normalizeOptions(options, {
gifWidth: Math.floor(options.gifWidth),
gifHeight: Math.floor(options.gifHeight)
});
// If the user would like to create a GIF from an existing image(s)
if (imagesLength) {
existingImages({
images,
imagesLength,
callback,
options
});
} else if (video) {
// If the user would like to create a GIF from an existing HTML5 video
existingVideo({
existingVideo: video,
callback,
options
});
} else {
// If the user would like to create a GIF from a webcam stream
existingWebcam({
lastCameraStream,
callback,
webcamVideoElement,
options
});
}
}
/*
takeSnapShot.js
===============
*/
/* Copyright 2017 Yahoo Inc.
* Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
*/
function takeSnapShot(userOptions, callback) {
callback = utils.isFunction(userOptions) ? userOptions : callback;
userOptions = utils.isObject(userOptions) ? userOptions : {};
if (!utils.isFunction(callback)) {
return;
}
const mergedOptions = utils.normalizeOptions(defaultOptions, userOptions);
const options = utils.normalizeOptions(mergedOptions, {
interval: 0.1,
numFrames: 1,
gifWidth: Math.floor(mergedOptions.gifWidth),
gifHeight: Math.floor(mergedOptions.gifHeight)
});
createGIF(options, callback);
}
/*
API.js
======
*/
/* Copyright 2017 Yahoo Inc.
* Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
*/
// Dependencies
const API = {
utils: utils$2,
error: error$2,
defaultOptions: defaultOptions$2,
createGIF,
takeSnapShot,
stopVideoStreaming,
isSupported,
isWebCamGIFSupported,
isExistingVideoGIFSupported,
isExistingImagesGIFSupported: isSupported$1,
VERSION: '0.4.5'
};
export default API; | the_stack |
import {assert} from 'chrome://resources/js/assert.m.js';
import {FilePath} from 'chrome://resources/mojo/mojo/public/mojom/base/file_path.mojom-webui.js';
import {Actions} from '../personalization_actions.js';
import {WallpaperCollection, WallpaperImage} from '../personalization_app.mojom-webui.js';
import {ReducerFunction} from '../personalization_reducers.js';
import {PersonalizationState} from '../personalization_state.js';
import {WallpaperActionName} from './wallpaper_actions.js';
import {WallpaperState} from './wallpaper_state.js';
export type DisplayableImage = FilePath|WallpaperImage;
function backdropReducer(
state: WallpaperState['backdrop'], action: Actions,
_: PersonalizationState): WallpaperState['backdrop'] {
switch (action.name) {
case WallpaperActionName.SET_COLLECTIONS:
return {collections: action.collections, images: {}};
case WallpaperActionName.SET_IMAGES_FOR_COLLECTION:
if (!state.collections) {
console.warn('Cannot set images when collections is null');
return state;
}
if (!state.collections.some(({id}) => id === action.collectionId)) {
console.warn(
'Cannot store images for unknown collection', action.collectionId);
return state;
}
return {
...state,
images: {...state.images, [action.collectionId]: action.images}
};
default:
return state;
}
}
function loadingReducer(
state: WallpaperState['loading'], action: Actions,
_: PersonalizationState): WallpaperState['loading'] {
switch (action.name) {
case WallpaperActionName.BEGIN_LOAD_IMAGES_FOR_COLLECTIONS:
return {
...state,
images: action.collections.reduce(
(result, {id}) => {
result[id] = true;
return result;
},
{} as Record<WallpaperCollection['id'], boolean>)
};
case WallpaperActionName.BEGIN_LOAD_LOCAL_IMAGE_DATA:
return {
...state,
local: {...state.local, data: {...state.local.data, [action.id]: true}}
};
case WallpaperActionName.BEGIN_LOAD_SELECTED_IMAGE:
return {...state, selected: true};
case WallpaperActionName.BEGIN_SELECT_IMAGE:
return {...state, setImage: state.setImage + 1};
case WallpaperActionName.END_SELECT_IMAGE:
if (state.setImage <= 0) {
console.error('Impossible state for loading.setImage');
// Reset to 0.
return {...state, setImage: 0};
}
return {...state, setImage: state.setImage - 1};
case WallpaperActionName.SET_COLLECTIONS:
return {...state, collections: false};
case WallpaperActionName.SET_IMAGES_FOR_COLLECTION:
return {
...state,
images: {...state.images, [action.collectionId]: false},
};
case WallpaperActionName.BEGIN_LOAD_LOCAL_IMAGES:
return {
...state,
local: {
...state.local,
images: true,
},
};
case WallpaperActionName.SET_LOCAL_IMAGES:
return {
...state,
local: {
// Only keep loading state for most recent local images.
data: (action.images || [])
.reduce(
(result, {path}) => {
if (state.local.data.hasOwnProperty(path)) {
result[path] = state.local.data[path];
}
return result;
},
{} as Record<FilePath['path'], boolean>),
// Image list is done loading.
images: false,
},
};
case WallpaperActionName.SET_LOCAL_IMAGE_DATA:
return {
...state,
local: {
...state.local,
data: {
...state.local.data,
[action.id]: false,
},
},
};
case WallpaperActionName.SET_SELECTED_IMAGE:
if (state.setImage === 0) {
return {...state, selected: false};
}
return state;
case WallpaperActionName.BEGIN_UPDATE_DAILY_REFRESH_IMAGE:
return {...state, refreshWallpaper: true};
case WallpaperActionName.SET_UPDATED_DAILY_REFRESH_IMAGE:
return {...state, refreshWallpaper: false};
case WallpaperActionName.BEGIN_LOAD_GOOGLE_PHOTOS_ALBUM:
assert(state.googlePhotos.photosByAlbumId[action.albumId] === undefined);
return {
...state,
googlePhotos: {
...state.googlePhotos,
photosByAlbumId: {
...state.googlePhotos.photosByAlbumId,
[action.albumId]: true,
},
},
};
case WallpaperActionName.SET_GOOGLE_PHOTOS_ALBUM:
assert(state.googlePhotos.photosByAlbumId[action.albumId] === true);
return {
...state,
googlePhotos: {
...state.googlePhotos,
photosByAlbumId: {
...state.googlePhotos.photosByAlbumId,
[action.albumId]: false,
},
},
};
case WallpaperActionName.BEGIN_LOAD_GOOGLE_PHOTOS_ALBUMS:
assert(state.googlePhotos.albums === false);
return {
...state,
googlePhotos: {
...state.googlePhotos,
albums: true,
},
};
case WallpaperActionName.SET_GOOGLE_PHOTOS_ALBUMS:
assert(state.googlePhotos.albums === true);
return {
...state,
googlePhotos: {
...state.googlePhotos,
albums: false,
},
};
case WallpaperActionName.BEGIN_LOAD_GOOGLE_PHOTOS_COUNT:
assert(state.googlePhotos.count === false);
return {
...state,
googlePhotos: {
...state.googlePhotos,
count: true,
},
};
case WallpaperActionName.SET_GOOGLE_PHOTOS_COUNT:
assert(state.googlePhotos.count === true);
return {
...state,
googlePhotos: {
...state.googlePhotos,
count: false,
},
};
case WallpaperActionName.BEGIN_LOAD_GOOGLE_PHOTOS_PHOTOS:
assert(state.googlePhotos.photos === false);
return {
...state,
googlePhotos: {
...state.googlePhotos,
photos: true,
},
};
case WallpaperActionName.SET_GOOGLE_PHOTOS_PHOTOS:
assert(state.googlePhotos.photos === true);
return {
...state,
googlePhotos: {
...state.googlePhotos,
photos: false,
},
};
default:
return state;
}
}
function localReducer(
state: WallpaperState['local'], action: Actions,
_: PersonalizationState): WallpaperState['local'] {
switch (action.name) {
case WallpaperActionName.SET_LOCAL_IMAGES:
return {
...state,
images: action.images,
// Only keep image thumbnails if the image is still in |images|.
data: (action.images || [])
.reduce(
(result, {path}) => {
if (state.data.hasOwnProperty(path)) {
result[path] = state.data[path];
}
return result;
},
{} as Record<FilePath['path'], string>),
};
case WallpaperActionName.SET_LOCAL_IMAGE_DATA:
return {
...state,
data: {
...state.data,
[action.id]: action.data,
}
};
default:
return state;
}
}
function currentSelectedReducer(
state: WallpaperState['currentSelected'], action: Actions,
_: PersonalizationState): WallpaperState['currentSelected'] {
switch (action.name) {
case WallpaperActionName.SET_SELECTED_IMAGE:
return action.image;
default:
return state;
}
}
/**
* Reducer for the pending selected image. The pendingSelected state is set when
* a user clicks on an image and before the client code is reached.
*
* Note: We allow multiple concurrent requests of selecting images while only
* keeping the latest pending image and failing others occurred in between.
* The pendingSelected state should not be cleared in this scenario (of multiple
* concurrent requests). Otherwise, it results in a unwanted jumpy motion of
* selected state.
*/
function pendingSelectedReducer(
state: WallpaperState['pendingSelected'], action: Actions,
globalState: PersonalizationState): WallpaperState['pendingSelected'] {
switch (action.name) {
case WallpaperActionName.BEGIN_SELECT_IMAGE:
return action.image;
case WallpaperActionName.BEGIN_UPDATE_DAILY_REFRESH_IMAGE:
return null;
case WallpaperActionName.SET_SELECTED_IMAGE:
const {image} = action;
if (!image) {
console.warn('pendingSelectedReducer: Failed to get selected image.');
return null;
} else if (globalState.wallpaper.loading.setImage == 0) {
// Clear the pending state when there are no more requests.
return null;
}
return state;
case WallpaperActionName.SET_FULLSCREEN_ENABLED:
if (!(/** @type {{enabled: boolean}} */ (action)).enabled) {
// Clear the pending selected state after full screen is dismissed.
return null;
}
return state;
case WallpaperActionName.END_SELECT_IMAGE:
const {success} = action;
if (!success && globalState.wallpaper.loading.setImage <= 1) {
// Clear the pending selected state if an error occurs and
// there are no multiple concurrent requests of selecting images.
return null;
}
return state;
default:
return state;
}
}
function dailyRefreshReducer(
state: WallpaperState['dailyRefresh'], action: Actions,
_: PersonalizationState): WallpaperState['dailyRefresh'] {
switch (action.name) {
case WallpaperActionName.SET_DAILY_REFRESH_COLLECTION_ID:
return {
...state,
collectionId: action.collectionId,
};
default:
return state;
}
}
function fullscreenReducer(
state: WallpaperState['fullscreen'], action: Actions,
_: PersonalizationState): WallpaperState['fullscreen'] {
switch (action.name) {
case WallpaperActionName.SET_FULLSCREEN_ENABLED:
return action.enabled;
default:
return state;
}
}
function googlePhotosReducer(
state: WallpaperState['googlePhotos'], action: Actions,
_: PersonalizationState): WallpaperState['googlePhotos'] {
switch (action.name) {
case WallpaperActionName.BEGIN_LOAD_GOOGLE_PHOTOS_ALBUM:
// The list of photos for an album should be loaded only once.
assert(state.albums?.some(album => album.id === action.albumId));
assert(state.photosByAlbumId[action.albumId] === undefined);
return state;
case WallpaperActionName.SET_GOOGLE_PHOTOS_ALBUM:
assert(state.albums?.some(album => album.id === action.albumId));
assert(action.albumId !== undefined);
assert(action.photos !== undefined);
return {
...state,
photosByAlbumId: {
...state.photosByAlbumId,
[action.albumId]: action.photos,
},
};
case WallpaperActionName.BEGIN_LOAD_GOOGLE_PHOTOS_ALBUMS:
// The list of albums should be loaded only once.
assert(state.albums === undefined);
return state;
case WallpaperActionName.SET_GOOGLE_PHOTOS_ALBUMS:
assert(action.albums !== undefined);
return {
...state,
albums: action.albums,
};
case WallpaperActionName.BEGIN_LOAD_GOOGLE_PHOTOS_COUNT:
// The total count of photos should be loaded only once.
assert(state.count === undefined);
return state;
case WallpaperActionName.SET_GOOGLE_PHOTOS_COUNT:
assert(action.count !== undefined);
return {
...state,
count: action.count,
};
case WallpaperActionName.BEGIN_LOAD_GOOGLE_PHOTOS_PHOTOS:
// The list of photos should be loaded only once.
assert(state.photos === undefined);
return state;
case WallpaperActionName.SET_GOOGLE_PHOTOS_PHOTOS:
assert(action.photos !== undefined);
return {
...state,
photos: action.photos,
};
default:
return state;
}
}
export const wallpaperReducers:
{[K in keyof WallpaperState]: ReducerFunction<WallpaperState[K]>} = {
backdrop: backdropReducer,
loading: loadingReducer,
local: localReducer,
currentSelected: currentSelectedReducer,
pendingSelected: pendingSelectedReducer,
dailyRefresh: dailyRefreshReducer,
fullscreen: fullscreenReducer,
googlePhotos: googlePhotosReducer,
}; | the_stack |
* Transforms Doxygen descriptions to markdown.
*/
import {DoxDescription, DoxDescriptionElement} from './doxygen-model';
import {DocCompound, DocMemberOverload} from './doc-model';
import {log} from './logger';
export interface TypeLinks {
linkPrefix: string;
linkMap: Map<string, string>;
operatorMap: Map<string, string>;
}
export interface LinkResolver {
stdTypeLinks: TypeLinks;
idlTypeLinks: TypeLinks;
resolveCompoundId(doxCompoundId: string): DocCompound | undefined;
resolveMemberId(
doxMemberId: string,
): [DocCompound | undefined, DocMemberOverload | undefined];
}
export function toMarkdown(
desc: DoxDescription,
linkResolver?: LinkResolver,
): string {
const context: DoxDescriptionElement[] = [];
let indent = 0;
type AutoLinkerState = 'Start' | 'InTemplateArgs' | 'InMember';
let linkerState: AutoLinkerState = 'Start';
let linkerTemplateDepth = 0;
let linkerTypeLink: string | undefined;
const sb = new StringBuilder();
write(desc);
return sb.toString().trim();
// eslint-disable-next-line complexity
function transformElement(
element: DoxDescriptionElement,
index: number,
): void {
switch (element['#name']) {
case '__text__':
return writeText(element._);
case 'sp':
return write(' ');
case 'nonbreakablespace':
return write(' ');
case 'ensp':
return write(' ');
case 'emsp':
return write(' ');
case 'thinsp':
return write(' ');
case 'emphasis':
return write('*', element.$$, '*');
case 'bold':
return write('**', element.$$, '**');
case 'mdash':
return write('—');
case 'ndash':
return write('–');
case 'linebreak':
return write('<br/>');
case 'para':
return writeBlock(
index ? '\n\n' : '',
' '.repeat(index ? indent : 0),
element.$$,
);
case 'orderedlist':
case 'itemizedlist':
return writeWithContext(element, index ? '\n' : '', element.$$);
case 'listitem':
const itemBullet =
last(context)?.['#name'] === 'orderedlist' ? '1. ' : '* ';
return writeWithIndent(
itemBullet.length,
index ? '\n' : '',
' '.repeat(indent),
itemBullet,
element.$$,
);
case 'parameterlist':
if (element.$.kind === 'param') {
return write(index ? '\n\n' : '', '### Parameters\n', element.$$);
} else if (element.$.kind === 'retval') {
return write(index ? '\n\n' : '', '### Return values\n', element.$$);
} else {
return log.warning(`Unknown parameterlist kind {${element.$.kind}}.`);
}
case 'parameteritem':
return write('\n* ', element.$$);
case 'parametername':
return writeCode('`', element.$$, '` ');
case 'computeroutput':
return writeCode('`', element.$$, '`');
case 'programlisting':
return writeCode('\n```cpp\n', element.$$, '```\n');
case 'codeline':
return write(element.$$, '\n');
case 'xrefsect':
return write('\n> ', element.$$);
case 'simplesect':
if (element.$.kind === 'attention') {
return write('> ', element.$$);
} else if (element.$.kind === 'return') {
return write(index ? '\n\n' : '', '### Returns\n\n', element.$$);
} else if (element.$.kind === 'see') {
return write('**See also**: ', element.$$);
} else {
log.warning(`[element.$.kind=${element.$.kind}]: not supported.`);
return;
}
case 'formula':
let s = (element._ || '').trim();
if (s.startsWith('$') && s.endsWith('$')) {
return write(s);
}
if (s.startsWith('\\[') && s.endsWith('\\]')) {
s = s.substring(2, s.length - 2).trim();
}
return write('\n$$\n' + s + '\n$$\n');
case 'preformatted':
return writeCode('\n<pre>', element.$$, '</pre>\n');
case 'sect1':
case 'sect2':
case 'sect3':
case 'sect4':
return writeWithContext(element, index ? '\n\n' : '', element.$$);
case 'title':
const level = Number((last(context)?.['#name'] || '0').slice(-1));
return write('#'.repeat(level), ' ', element._);
case 'heading':
sb.removeLastIf(' ');
return write('#'.repeat(Number(element.$.level || 0)), ' ', element.$$);
case 'hruler':
return write('---');
case 'ref':
return refLink(element);
case 'ulink':
return link(toMarkdown(element.$$), element.$.url);
case 'xreftitle':
return write('**', element.$$, ':** ');
case 'row':
write('\n', escapeRow(toMarkdown(element.$$, linkResolver)));
if ((element.$$[0] as DoxDescriptionElement).$.thead === 'yes') {
element.$$.forEach((_, i) => {
write(i ? ' | ' : '\n', '---------');
});
}
break;
case 'entry':
return write(escapeCell(toMarkdown(element.$$, linkResolver)), '|');
case 'anchor':
case 'highlight':
case 'table':
case 'parameterdescription':
case 'parameternamelist':
case 'xrefdescription':
case 'verbatim':
case undefined:
return write(element.$$);
default:
log.warning(`[element[['#name'=${element['#name']}]]]: not supported.`);
}
}
function refLink(element: DoxDescriptionElement): void {
const text = toMarkdown(element.$$);
if (!linkResolver) {
return write(text);
}
if (element.$.kindref === 'compound') {
const compound = linkResolver.resolveCompoundId(element.$.refid);
if (compound) {
return linkCode(text, compound.docId);
} else {
return write('`', text, '`');
}
} else if (element.$.kindref === 'member') {
const [compound, memberOverload] = linkResolver.resolveMemberId(
element.$.refid,
);
if (compound) {
return linkCode(text, compound.docId + memberOverload?.anchor);
} else {
return write('`', text, '`');
}
} else {
log.warning(`Unknown kindref={${element.$.kindref}}`);
}
write(text);
}
function link(text: string, href: string) {
if (linkResolver) {
write('[', text, '](', href, ')');
} else {
write(text);
}
}
function linkCode(text: string, href: string) {
if (linkResolver) {
write('[`', text, '`](', href, ')');
} else {
write(text);
}
}
function writeBlock(...items: DoxDescription[]) {
write(...items);
linkerState = 'Start';
linkerTemplateDepth = 0;
}
function writeText(text?: string) {
if (text) {
if (text.trim() === '') {
if (text.includes(' ')) {
write(' ');
}
} else {
// Do auto-linking for known types
if (linkResolver) {
applyAutoLinks(
text,
linkResolver.stdTypeLinks,
linkResolver.idlTypeLinks,
);
} else {
write(text);
}
}
}
}
// We support the following syntax for standard library types and functions:
// - Standard types must start with 'std::' and follow by a type name.
// - Then they may have template arguments in < >
// - Then they may have '::' followed by method name or an operator.
// - It also recognizes types generated from IDL.
// They must start with an upper case letter.
// eslint-disable-next-line complexity
function applyAutoLinks(
text: string,
stdTypeLinks: TypeLinks,
idlTypeLinks: TypeLinks,
) {
const tokenExpr = regex('g')`
(?<stdType>std::\w+) // standard lib type name
|(?<idlType>[A-Z]\w*)(::\w+(\(\))?)? // idl generated type
|(?<ltBracket><) // start template args
|(?<gtBracket>>) // end template args
|::(?<member>
(?<operator>operator // list of all member operators
(\[\]
|\(\)
|,
|->\*
|-[-=>]?
|\+[+=]?
|\*=?
|/=?
|%=?
|\^=?
|~=?
|<<?=?>?
|>>?=?
|&&?=?
|\|\|?=?
|==?
|!=?
)
)
|(?<method>\w+)(\(\))? // method to match
)`;
let index = 0;
let startCode = false;
while (tokenExpr.lastIndex < text.length) {
const match = tokenExpr.exec(text);
const token = match?.groups;
if (!match || !token) break;
switch (linkerState) {
case 'Start': {
if (token.stdType) {
linkerTypeLink = writeTypeLink(stdTypeLinks, match, token.stdType);
if (linkerTypeLink) {
if (text.startsWith('<', index)) {
linkerState = 'InTemplateArgs';
} else if (text.startsWith('::', index)) {
linkerState = 'InMember';
} else {
linkerState = 'Start';
linkerTypeLink = undefined;
}
}
} else if (token.idlType) {
writeTypeLink(idlTypeLinks, match, token.idlType);
}
break;
}
case 'InTemplateArgs': {
startCode = true;
if (token.stdType) {
if (writeTypeLink(stdTypeLinks, match, token.stdType)) {
startCode = true;
}
} else if (token.idlType) {
if (writeTypeLink(idlTypeLinks, match, token.idlType)) {
startCode = true;
}
} else if (token.ltBracket) {
++linkerTemplateDepth;
} else if (token.gtBracket) {
if (--linkerTemplateDepth === 0) {
if (text.startsWith('::', tokenExpr.lastIndex)) {
linkerState = 'InMember';
} else {
completeText(tokenExpr.lastIndex);
linkerState = 'Start';
}
}
}
break;
}
case 'InMember': {
startCode = true;
if (token.method) {
writeMemberLink(match.index + 2, token.member, token.method);
} else if (token.operator) {
const operatorLink = stdTypeLinks.operatorMap.get(token.operator);
if (operatorLink) {
writeMemberLink(match.index + 2, token.operator, operatorLink);
} else {
completeText(tokenExpr.lastIndex);
}
}
linkerTypeLink = undefined;
linkerState = 'Start';
break;
}
}
}
completeText(text.length);
function completeText(endIndex: number) {
const str = text.substring(index, endIndex);
const delimiter = startCode && str ? '`' : '';
startCode = false;
write(delimiter, str, delimiter);
index = endIndex;
}
function writeCodeLink(
startIndex: number,
label: string,
...linkParts: string[]
) {
completeText(startIndex);
write('[`', label, '`](', ...linkParts, ')');
index = tokenExpr.lastIndex;
}
function writeTypeLink(
typeLinks: TypeLinks,
match: RegExpExecArray,
type: string,
) {
const typeLink = typeLinks.linkMap.get(type);
if (typeLink) {
writeCodeLink(match.index, match[0], typeLinks.linkPrefix, typeLink);
}
return typeLink;
}
function writeMemberLink(
startIndex: number,
member: string,
memberLink: string,
) {
writeCodeLink(
startIndex,
member,
stdTypeLinks.linkPrefix,
linkerTypeLink!,
'/',
memberLink,
);
}
}
function escapeRow(text: string): string {
return text.replace(/\s*\|\s*$/, '');
}
function escapeCell(text: string): string {
return text
.replace(/^[\n]+|[\n]+$/g, '') // trim CRLF
.replace('/|/g', '\\|') // escape the pipe
.replace(/\n/g, '<br/>'); // escape CRLF
}
function writeCode(...items: DoxDescription[]) {
const oldLinkResolver = linkResolver;
linkResolver = undefined;
write(...items);
linkResolver = oldLinkResolver;
}
function writeWithContext(
element: DoxDescriptionElement,
...items: DoxDescription[]
) {
context.push(element);
write(...items);
context.pop();
}
function writeWithIndent(indentBy: number, ...items: DoxDescription[]) {
indent += indentBy;
write(...items);
indent -= indentBy;
}
function write(...items: DoxDescription[]): void {
for (const item of items) {
if (typeof item === 'string') {
sb.write(item);
} else if (typeof item === 'object') {
if (Array.isArray(item)) {
(item as DoxDescriptionElement[])
// Remove all non-meaningful white spaces
.filter(
element =>
typeof element !== 'object' ||
element['#name'] !== '__text__' ||
(element._ && (element._.trim() || element._.includes(' '))),
)
.forEach((element, index) => {
transformElement(element, index);
});
} else {
transformElement(item as DoxDescriptionElement, 0);
}
} else if (typeof item !== 'undefined') {
throw new Error(`Unexpected object type: ${typeof item}`);
}
}
}
}
export class StringBuilder {
private readonly parts: string[] = [];
write(...args: string[]) {
for (const arg of args) {
this.parts.push(arg);
}
}
writeIf(arg: string, condition: boolean) {
if (condition) {
this.parts.push(arg);
}
}
removeLastIf(text: string) {
if (last(this.parts) === text) {
this.parts.pop();
}
}
toString() {
return this.parts.join('');
}
}
function last<T>(arr?: T[]): T | undefined {
return arr ? arr[arr.length - 1] : undefined;
}
// Converted to TypeScript from https://stackoverflow.com/a/62153852
// It allows to write RegExp with comments.
interface TaggedTemplate {
(strings: TemplateStringsArray, ...values: string[]): RegExp;
}
function regex(arg0: string): TaggedTemplate;
function regex(strings: TemplateStringsArray, ...values: string[]): RegExp;
function regex(
arg0: string | TemplateStringsArray,
...args: string[]
): RegExp | TaggedTemplate {
function cleanup(str: string) {
// remove whitespace, single and multi-line comments
return str.replace(/\s+|\/\/.*|\/\*[\s\S]*?\*\//g, '');
}
function escape(str: string) {
// escape regular expression
return str.replace(/[-.*+?^${}()|[\]\\]/g, '\\$&');
}
function create(
flags: string,
strings: TemplateStringsArray,
...values: string[]
) {
let pattern = '';
for (let i = 0; i < values.length; ++i) {
pattern += cleanup(strings.raw[i]); // strings are cleaned up
pattern += escape(values[i]); // values are escaped
}
pattern += cleanup(strings.raw[values.length]);
return RegExp(pattern, flags);
}
if (Array.isArray(arg0)) {
// used as a template tag (no flags)
return create('', arg0 as TemplateStringsArray, ...args);
}
// used as a function (with flags)
return create.bind(void 0, arg0 as string);
} | the_stack |
import {serial as testAny, TestInterface} from 'ava';
import fs from 'fs';
import path from 'path';
import sinon from 'sinon';
import uniqueString from 'unique-string';
const test = testAny as TestInterface<{outputPath: string}>;
import {getVideoMetadata} from './helpers/video-utils';
import {almostEquals} from './helpers/assertions';
import {getFormatExtension} from '../main/common/constants';
import {Except, SetOptional} from 'type-fest';
import {mockImport} from './helpers/mocks';
import {Format} from '../main/common/types';
const getRandomFileName = (ext: Format = Format.mp4) => `${uniqueString()}.${getFormatExtension(ext)}`;
const input = path.resolve(__dirname, 'fixtures', 'input.mp4');
const retinaInput = path.resolve(__dirname, 'fixtures', 'input@2x.mp4');
mockImport('../common/analytics', 'analytics');
mockImport('../plugins/service-context', 'service-context');
mockImport('../plugins', 'plugins');
const {settings} = mockImport('../common/settings', 'settings');
import {convertTo} from '../main/converters';
import {ConvertOptions} from '../main/converters/utils';
test.afterEach.always(t => {
if (t.context.outputPath && fs.existsSync(t.context.outputPath)) {
fs.unlinkSync(t.context.outputPath);
}
});
const convert = async (format: Format, options: SetOptional<Except<ConvertOptions, 'outputPath'>, 'onCancel' | 'onProgress' | 'shouldMute'>) => {
return convertTo(format, {
defaultFileName: getRandomFileName(format),
onProgress: sinon.fake(),
onCancel: sinon.fake(),
shouldMute: true,
...options
});
};
// MP4
test('mp4: retina with sound', async t => {
const onProgress = sinon.fake();
t.context.outputPath = await convert(Format.mp4, {
shouldMute: false,
inputPath: retinaInput,
fps: 39,
width: 469,
height: 839,
startTime: 30,
endTime: 43.5,
shouldCrop: true,
onProgress
});
const meta = await getVideoMetadata(t.context.outputPath);
// Makes dimensions even
t.is(meta.size.width, 470);
t.is(meta.size.height, 840);
t.is(meta.fps, 39);
t.true(almostEquals(meta.duration, 13.5));
t.is(meta.encoding, 'h264');
t.true(meta.hasAudio);
t.true(onProgress.calledWithMatch(sinon.match.string, sinon.match.number));
t.true(onProgress.calledWithMatch(sinon.match.string, sinon.match.number, sinon.match.string));
});
test('mp4: retina without sound', async t => {
t.context.outputPath = await convert(Format.mp4, {
shouldMute: true,
inputPath: retinaInput,
fps: 10,
width: 46,
height: 83,
startTime: 0,
endTime: 5,
shouldCrop: true
});
const meta = await getVideoMetadata(t.context.outputPath);
t.false(meta.hasAudio);
});
test('mp4: non-retina', async t => {
t.context.outputPath = await convert(Format.mp4, {
shouldMute: false,
inputPath: input,
fps: 30,
width: 255,
height: 143,
startTime: 11.5,
endTime: 27,
// Should resize even though this is false, because dimensions are odd
shouldCrop: false
});
const meta = await getVideoMetadata(t.context.outputPath);
// Makes dimensions even
t.is(meta.size.width, 256);
t.is(meta.size.height, 144);
t.is(meta.fps, 30);
t.true(almostEquals(meta.duration, 15.5));
t.is(meta.encoding, 'h264');
t.false(meta.hasAudio);
});
// WEBM
test('webm: retina with sound', async t => {
const onProgress = sinon.fake();
t.context.outputPath = await convert(Format.webm, {
shouldMute: false,
inputPath: retinaInput,
fps: 39,
width: 469,
height: 839,
startTime: 30,
endTime: 43.5,
shouldCrop: true,
onProgress
});
const meta = await getVideoMetadata(t.context.outputPath);
t.is(meta.size.width, 470);
t.is(meta.size.height, 840);
t.is(meta.fps, 39);
t.true(almostEquals(meta.duration, 13.5));
t.is(meta.encoding, 'vp9');
t.true(meta.hasAudio);
t.true(onProgress.calledWithMatch(sinon.match.string, sinon.match.number));
t.true(onProgress.calledWithMatch(sinon.match.string, sinon.match.number, sinon.match.string));
});
test('webm: retina without sound', async t => {
t.context.outputPath = await convert(Format.webm, {
shouldMute: true,
inputPath: retinaInput,
fps: 10,
width: 46,
height: 83,
startTime: 0,
endTime: 5,
shouldCrop: true
});
const meta = await getVideoMetadata(t.context.outputPath);
t.false(meta.hasAudio);
});
test('webm: non-retina', async t => {
t.context.outputPath = await convert(Format.webm, {
shouldMute: false,
inputPath: input,
fps: 30,
width: 255,
height: 143,
startTime: 11.5,
endTime: 27,
shouldCrop: true
});
const meta = await getVideoMetadata(t.context.outputPath);
t.is(meta.size.width, 256);
t.is(meta.size.height, 144);
t.is(meta.fps, 30);
t.true(almostEquals(meta.duration, 15.5));
t.is(meta.encoding, 'vp9');
t.false(meta.hasAudio);
});
// APNG
test('apng: retina', async t => {
const onProgress = sinon.fake();
t.context.outputPath = await convert(Format.apng, {
shouldMute: false,
inputPath: retinaInput,
fps: 15,
width: 469,
height: 839,
startTime: 30,
endTime: 43.5,
shouldCrop: true,
onProgress
});
const meta = await getVideoMetadata(t.context.outputPath);
t.is(meta.size.width, 469);
t.is(meta.size.height, 839);
t.is(meta.fps, 15);
t.is(meta.encoding, 'apng');
t.false(meta.hasAudio);
t.true(onProgress.calledWithMatch(sinon.match.string, sinon.match.number));
t.true(onProgress.calledWithMatch(sinon.match.string, sinon.match.number, sinon.match.string));
});
test('apng: non-retina', async t => {
t.context.outputPath = await convert(Format.apng, {
shouldMute: false,
inputPath: input,
fps: 15,
width: 255,
height: 143,
startTime: 11.5,
endTime: 27,
shouldCrop: true
});
const meta = await getVideoMetadata(t.context.outputPath);
t.is(meta.size.width, 255);
t.is(meta.size.height, 143);
t.is(meta.fps, 15);
t.is(meta.encoding, 'apng');
t.false(meta.hasAudio);
});
// GIF
test('gif: retina', async t => {
const onProgress = sinon.fake();
t.context.outputPath = await convert(Format.gif, {
shouldMute: false,
inputPath: retinaInput,
fps: 10,
width: 236,
height: 420,
startTime: 0,
endTime: 8.5,
shouldCrop: true,
onProgress
});
const meta = await getVideoMetadata(t.context.outputPath);
t.is(meta.size.width, 236);
t.is(meta.size.height, 420);
t.is(meta.fps, 10);
t.true(almostEquals(meta.duration, 8.5));
t.is(meta.encoding, 'gif');
t.false(meta.hasAudio);
t.true(onProgress.calledWithMatch(sinon.match.string, sinon.match.number));
t.true(onProgress.calledWithMatch(sinon.match.string, sinon.match.number, sinon.match.string));
});
test('gif: non-retina', async t => {
t.context.outputPath = await convert(Format.gif, {
shouldMute: false,
inputPath: input,
fps: 15,
width: 255,
height: 143,
startTime: 11.5,
endTime: 27,
shouldCrop: true
});
const meta = await getVideoMetadata(t.context.outputPath);
t.is(meta.size.width, 255);
t.is(meta.size.height, 143);
t.is(meta.fps, 15);
t.true(almostEquals(meta.duration, 15.5));
t.is(meta.encoding, 'gif');
t.false(meta.hasAudio);
});
test('gif: lossy', async t => {
settings.setMock('lossyCompression', false);
const regular = await convert(Format.gif, {
inputPath: input,
fps: 20,
width: 510,
height: 286,
startTime: 1,
endTime: 10,
shouldCrop: true
});
settings.setMock('lossyCompression', true);
const lossy = await convert(Format.gif, {
inputPath: input,
fps: 20,
width: 510,
height: 286,
startTime: 1,
endTime: 10,
shouldCrop: true
});
t.true(
fs.statSync(regular).size >=
fs.statSync(lossy).size
);
});
// AV1
test('av1: retina with sound', async t => {
const onProgress = sinon.fake();
t.context.outputPath = await convert(Format.av1, {
shouldMute: false,
inputPath: retinaInput,
fps: 15,
width: 235,
height: 420,
startTime: 30,
endTime: 35.5,
shouldCrop: true,
onProgress
});
const meta = await getVideoMetadata(t.context.outputPath);
// Makes dimensions even
t.is(meta.size.width, 236);
t.is(meta.size.height, 420);
t.is(meta.fps, 15);
t.true(almostEquals(meta.duration, 5.5));
t.is(meta.encoding, 'av1');
t.true(meta.hasAudio);
t.true(onProgress.calledWithMatch(sinon.match.string, sinon.match.number));
t.true(onProgress.calledWithMatch(sinon.match.string, sinon.match.number, sinon.match.string));
});
test('av1: retina without sound', async t => {
t.context.outputPath = await convert(Format.av1, {
shouldMute: true,
inputPath: retinaInput,
fps: 10,
width: 100,
height: 200,
startTime: 0,
endTime: 4,
shouldCrop: true
});
const meta = await getVideoMetadata(t.context.outputPath);
t.false(meta.hasAudio);
});
test('av1: non-retina', async t => {
t.context.outputPath = await convert(Format.av1, {
shouldMute: false,
inputPath: input,
fps: 10,
width: 255,
height: 143,
startTime: 11.5,
endTime: 16,
shouldCrop: true
});
const meta = await getVideoMetadata(t.context.outputPath);
// Makes dimensions even
t.is(meta.size.width, 256);
t.is(meta.size.height, 144);
t.is(meta.fps, 10);
t.true(almostEquals(meta.duration, 4.5));
t.is(meta.encoding, 'av1');
t.false(meta.hasAudio);
});
// HEVC
test('HEVC: retina', async t => {
const onProgress = sinon.fake();
t.context.outputPath = await convert(Format.hevc, {
shouldMute: true,
inputPath: retinaInput,
fps: 15,
width: 469,
height: 839,
startTime: 30,
endTime: 43.5,
shouldCrop: true,
onProgress
});
const meta = await getVideoMetadata(t.context.outputPath);
// Makes dimensions even
t.is(meta.size.width, 470);
t.is(meta.size.height, 840);
t.is(meta.fps, 15);
t.is(meta.encoding, 'hevc');
t.false(meta.hasAudio);
t.true(onProgress.calledWithMatch(sinon.match.string, sinon.match.number));
t.true(onProgress.calledWithMatch(sinon.match.string, sinon.match.number, sinon.match.string));
});
test('HEVC: non-retina', async t => {
t.context.outputPath = await convert(Format.hevc, {
shouldMute: true,
inputPath: input,
fps: 15,
width: 255,
height: 143,
startTime: 11.5,
endTime: 27,
shouldCrop: true
});
const meta = await getVideoMetadata(t.context.outputPath);
// Makes dimensions even
t.is(meta.size.width, 256);
t.is(meta.size.height, 144);
t.is(meta.fps, 15);
t.is(meta.encoding, 'hevc');
t.false(meta.hasAudio);
}); | the_stack |
import edgeSourceUndefined from './constants/negative/json/08-edge-source-undefined.json';
import edgeTargetUndefined from './constants/negative/json/07-edge-target-undefined.json';
import duplicateNodeEdgeID from './constants/negative/json/01-duplicate-node-edge-key.json';
import invalidEdgeSource from './constants/negative/json/05-invalid-edge-source.json';
import invalidEdgeTarget from './constants/negative/json/12-invalid-edge-target.json';
import duplicateNodeID from './constants/negative/json/06-duplicate-node-id.json';
import duplicateEdgeID from './constants/negative/json/13-duplicate-edge-id.json';
import * as edgeListCsv from './constants/negative/edgeListCsv';
import * as nodeEdgeCsv from './constants/negative/nodeEdgeCsv';
import {
importEdgeListCsv,
importJson,
importNodeEdgeCsv,
} from '../processors/import';
import { MotifImportError } from '../../../components/ImportErrorMessage';
import * as T from '../types';
describe('Import Errors', () => {
describe('JSON', () => {
// edge source attribute is missing in the data.
it('Missing Edge Source Attributes', (done) => {
const input = edgeSourceUndefined.data as never as T.GraphList;
const groupEdge = false;
const accessors = {
nodeID: 'id',
edgeID: 'id',
edgeSource: 'source',
edgeTarget: 'target',
};
importJson(input, accessors, groupEdge).catch((err) => {
expect(err).toBeInstanceOf(MotifImportError);
expect(err.name).toEqual('edge-source-value-undefined');
expect(err.message).toEqual('');
done();
});
});
// edge target attribute is missing in the data.
it('Missing Edge Target Attributes', (done) => {
const input = edgeTargetUndefined.data as never as T.GraphList;
const groupEdge = false;
const accessors = {
nodeID: 'id',
edgeID: 'id',
edgeSource: 'source',
edgeTarget: 'target',
};
importJson(input, accessors, groupEdge).catch((err) => {
expect(err).toBeInstanceOf(MotifImportError);
expect(err.name).toEqual('edge-target-value-undefined');
expect(err.message).toEqual('');
done();
});
});
// node id and edge id are found conflicting with each others.
it('Conflicting ID between Nodes and Edges', (done) => {
const input = duplicateNodeEdgeID.data as never as T.GraphList;
const groupEdge = false;
const accessors = {
nodeID: 'id',
edgeID: 'id',
edgeSource: 'source',
edgeTarget: 'target',
};
importJson(input, accessors, groupEdge).catch((err) => {
const conflictId = JSON.stringify(['two']);
expect(err).toBeInstanceOf(MotifImportError);
expect(err.name).toEqual('node-edge-id-conflicts');
expect(err.message).toEqual(conflictId);
done();
});
});
// edge source pointing to non-existence node id.
it('Invalid Edge Source', (done) => {
const input = invalidEdgeSource.data as never as T.GraphList;
const groupEdge = false;
const accessors = {
nodeID: 'id',
edgeID: 'id',
edgeSource: 'source',
edgeTarget: 'target',
};
importJson(input, accessors, groupEdge).catch((err) => {
const invalidEdgeSource = 'two';
expect(err).toBeInstanceOf(MotifImportError);
expect(err.name).toEqual('edge-source-not-exist');
expect(err.message).toEqual(invalidEdgeSource);
done();
});
});
// edge target pointing to non-existence node id.
it('Invalid Edge Target', (done) => {
const input = invalidEdgeTarget.data as never as T.GraphList;
const groupEdge = false;
const accessors = {
nodeID: 'id',
edgeID: 'id',
edgeSource: 'source',
edgeTarget: 'target',
};
importJson(input, accessors, groupEdge).catch((err) => {
const invalidEdgeSource = 'two';
expect(err).toBeInstanceOf(MotifImportError);
expect(err.name).toEqual('edge-target-not-exist');
expect(err.message).toEqual(invalidEdgeSource);
done();
});
});
// Node ID are conflicting with each others.
it('Duplicate Node ID', (done) => {
const input = duplicateNodeID.data as never as T.GraphList;
const groupEdge = false;
const accessors = {
nodeID: 'id',
edgeID: 'id',
edgeSource: 'source',
edgeTarget: 'target',
};
importJson(input, accessors, groupEdge).catch((err) => {
const invalidIds = JSON.stringify(['node-two']);
expect(err).toBeInstanceOf(MotifImportError);
expect(err.name).toEqual('conflict-node-id');
expect(err.message).toEqual(invalidIds);
done();
});
});
// Node ID are conflicting with each others.
it('Duplicate Edge ID', (done) => {
const input = duplicateEdgeID.data as never as T.GraphList;
const groupEdge = false;
const accessors = {
nodeID: 'id',
edgeID: 'id',
edgeSource: 'source',
edgeTarget: 'target',
};
importJson(input, accessors, groupEdge).catch((err) => {
const invalidIds = JSON.stringify(['edge-two']);
expect(err).toBeInstanceOf(MotifImportError);
expect(err.name).toEqual('conflict-edge-id');
expect(err.message).toEqual(invalidIds);
done();
});
});
});
describe('Edge List CSV', () => {
// edge source attribute is missing in the data.
it('Missing Edge Source Attributes', (done) => {
const input = edgeListCsv.missingSource as string;
const accessors = {
nodeID: 'auto-generate',
edgeID: 'id',
edgeSource: 'custom-source',
edgeTarget: 'custom-target',
};
importEdgeListCsv(input, accessors, false).catch((err) => {
expect(err).toBeInstanceOf(MotifImportError);
expect(err.name).toEqual('edge-source-value-undefined');
expect(err.message).toEqual('');
done();
});
});
// edge target attribute is missing in the data.
it('Missing Edge Target Attributes', (done) => {
const input = edgeListCsv.missingTarget as string;
const accessors = {
nodeID: 'auto-generate',
edgeID: 'id',
edgeSource: 'custom-source',
edgeTarget: 'custom-target',
};
importEdgeListCsv(input, accessors, false).catch((err) => {
expect(err).toBeInstanceOf(MotifImportError);
expect(err.name).toEqual('edge-target-value-undefined');
expect(err.message).toEqual('');
done();
});
});
// node id and edge id are found conflicting with each others.
it('Conflicting ID between Nodes and Edges', (done) => {
const input = edgeListCsv.conflictIds as string;
const accessors = {
nodeID: 'auto-generate',
edgeID: 'id',
edgeSource: 'custom-source',
edgeTarget: 'custom-target',
};
importEdgeListCsv(input, accessors, false).catch((err) => {
const conflictIds = JSON.stringify(['two', 'three']);
expect(err).toBeInstanceOf(MotifImportError);
expect(err.name).toEqual('node-edge-id-conflicts');
expect(err.message).toEqual(conflictIds);
done();
});
});
});
describe('Node Edge CSV', () => {
// edge source attribute is missing in the data.
it('Missing Edge Source Attributes', (done) => {
const nodeCsvs = [nodeEdgeCsv.conflictNodeId.one];
const edgeCsvs = [nodeEdgeCsv.conflictEdgeId.one];
const accessors = {
nodeID: 'id',
edgeID: 'id',
edgeSource: 'source',
edgeTarget: 'target',
};
importNodeEdgeCsv(nodeCsvs, edgeCsvs, accessors, false).catch((err) => {
expect(err).toBeInstanceOf(MotifImportError);
expect(err.name).toEqual('edge-source-not-exist');
expect(err.message).toEqual('three');
done();
});
});
// edge target attribute is missing in the data.
it('Missing Edge Target Attributes', (done) => {
const nodeCsvs = [nodeEdgeCsv.sampleNode];
const edgeCsvs = [nodeEdgeCsv.edgeTargetInvalidNode];
const accessors = {
nodeID: 'id',
edgeID: 'id',
edgeSource: 'source',
edgeTarget: 'target',
};
importNodeEdgeCsv(nodeCsvs, edgeCsvs, accessors, false).catch((err) => {
expect(err).toBeInstanceOf(MotifImportError);
expect(err.name).toEqual('edge-target-not-exist');
expect(err.message).toEqual('d');
done();
});
});
// node id and edge id are found conflicting with each others.
it('Conflicting ID between Nodes and Edges', (done) => {
const nodeCsvs = [
nodeEdgeCsv.conflictNodeId.one,
nodeEdgeCsv.conflictNodeId.two,
];
const edgeCsvs = [nodeEdgeCsv.conflictEdgeId.one];
const accessors = {
nodeID: 'id',
edgeID: 'id',
edgeSource: 'source',
edgeTarget: 'target',
};
importNodeEdgeCsv(nodeCsvs, edgeCsvs, accessors, false).catch((err) => {
const conflictingId = JSON.stringify(['three', 'four']);
expect(err).toBeInstanceOf(MotifImportError);
expect(err.name).toEqual('node-edge-id-conflicts');
expect(err.message).toEqual(conflictingId);
done();
});
});
// conflict node id
it('Conflict Node ID', (done) => {
const nodeCsvs = [
nodeEdgeCsv.conflictNodeId.one,
nodeEdgeCsv.conflictNodeId.one,
];
const edgeCsvs = [nodeEdgeCsv.conflictEdgeId.two];
const accessors = {
nodeID: 'id',
edgeID: 'id',
edgeSource: 'source',
edgeTarget: 'target',
};
importNodeEdgeCsv(nodeCsvs, edgeCsvs, accessors, false).catch((err) => {
const conflictNodeId = JSON.stringify(['one', 'two']);
expect(err).toBeInstanceOf(MotifImportError);
expect(err.name).toEqual('conflict-node-id');
expect(err.message).toEqual(conflictNodeId);
done();
});
});
// conflict edge id
it('Conflict Edge ID', (done) => {
const nodeCsvs = [nodeEdgeCsv.conflictNodeId.one];
const edgeCsvs = [
nodeEdgeCsv.conflictEdgeId.two,
nodeEdgeCsv.conflictEdgeId.two,
];
const accessors = {
nodeID: 'id',
edgeID: 'id',
edgeSource: 'source',
edgeTarget: 'target',
};
importNodeEdgeCsv(nodeCsvs, edgeCsvs, accessors, false).catch((err) => {
const conflictEdgeID = JSON.stringify(['one', 'two']);
expect(err).toBeInstanceOf(MotifImportError);
expect(err.name).toEqual('conflict-edge-id');
expect(err.message).toEqual(conflictEdgeID);
done();
});
});
// edge source pointing to non-existence node id.
it('Invalid Edge Source', (done) => {
const nodeCsvs = [nodeEdgeCsv.conflictNodeId.one];
const edgeCsvs = [
nodeEdgeCsv.conflictEdgeId.two,
nodeEdgeCsv.conflictNodeId.two,
];
const accessors = {
nodeID: 'id',
edgeID: 'id',
edgeSource: 'source',
edgeTarget: 'target',
};
importNodeEdgeCsv(nodeCsvs, edgeCsvs, accessors, false).catch((err) => {
expect(err).toBeInstanceOf(MotifImportError);
expect(err.name).toEqual('edge-source-not-exist');
expect(err.message).toEqual('');
done();
});
});
// edge target pointing to non-existence node id.
it('Invalid Edge Target', (done) => {
const nodeCsvs = [nodeEdgeCsv.conflictNodeId.one];
const edgeCsvs = [nodeEdgeCsv.sampleEdge];
const accessors = {
nodeID: 'id',
edgeID: 'id',
edgeSource: 'source',
edgeTarget: 'target',
};
importNodeEdgeCsv(nodeCsvs, edgeCsvs, accessors, false).catch((err) => {
expect(err).toBeInstanceOf(MotifImportError);
expect(err.name).toEqual('edge-target-not-exist');
expect(err.message).toEqual('three');
done();
});
});
});
}); | the_stack |
import {postMessage, randInt, DelayNotify, LocalStorage} from '../utils'
import md5 from '../md5'
const storage = new LocalStorage('h5plr')
const PUREMODE = 'pureMode'
export function isPureMode () {
return storage.getItem(PUREMODE, '0') === '1'
}
export function setPureMode (val: boolean) {
storage.setItem(PUREMODE, val ? '1' : '0')
}
declare var window: {
_ACJ_ (args: any[]): void,
[key: string]: any
} & Window
declare function escape(s:string): string;
export const getACF = (key: string) => {
try {
return new RegExp(`acf_${key}=(.*?)(;|$)`).exec(document.cookie)[1]
} catch (e) {
return ''
}
}
interface DouyuPackage {
type: string,
[key: string]: any
}
function filterEnc (s: string) {
s = s.toString()
s = s.replace(/@/g, '@A')
return s.replace(/\//g, '@S')
}
function filterDec (s: string) {
s = s.toString()
s = s.replace(/@S/g, '/')
return s.replace(/@A/g, '@')
}
function douyuEncode (data: DouyuPackage) {
return Object.keys(data).map(key => `${key}@=${filterEnc(data[key])}`).join('/') + '/'
}
function douyuDecode (data: string) {
let out: DouyuPackage = {
type: '!!missing!!'
}
try {
data.split('/').filter(i => i.length > 2).forEach(i => {
let e = i.split('@=')
out[e[0]] = filterDec(e[1])
})
} catch (e) {
console.error(e)
console.log(data)
}
return out
}
function douyuDecodeList (list: string) {
return list.split('/').filter(i => i.length > 2).map(filterDec).map(douyuDecode)
}
export function ACJ (id: string, data: any | string) {
if (typeof data == 'object') {
data = douyuEncode(data)
}
try {
window._ACJ_([id, data])
} catch (e) {
console.error(id, data, e)
}
}
function abConcat(buffer1: ArrayBuffer, buffer2: ArrayBuffer) {
let tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength)
tmp.set(new Uint8Array(buffer1), 0)
tmp.set(new Uint8Array(buffer2), buffer1.byteLength)
return tmp.buffer
};
interface DouyuListener {
onReconnect (): void
onPackage (pkg: DouyuPackage, pkgStr: string): void
onClose (): void
onError (e: string): void
}
class DouyuProtocol {
buffer: ArrayBuffer
connectHandler: () => void = () => null
ws: WebSocket
decoder = new TextDecoder('utf-8')
encoder = new TextEncoder()
constructor (public listener: DouyuListener) {
this.buffer = new ArrayBuffer(0)
}
connectAsync (url: string) {
return new Promise<void>((res, rej) => {
const ws = new WebSocket(url)
ws.binaryType = 'arraybuffer'
ws.onopen = () => {
this.ws = ws
ws.onmessage = e => {
const buf: ArrayBuffer = e.data
this.dataHandler(buf)
}
ws.onclose = () => this.closeHandler()
ws.onerror = (e) => this.errorHandler('Connection error(ws)')
res()
}
ws.onerror = () => rej()
})
}
dataHandler (data: ArrayBuffer) {
this.buffer = abConcat(this.buffer, data)
while (this.buffer.byteLength >= 4) {
const buffer = this.buffer
const view = new DataView(buffer)
let size = view.getUint32(0, true)
if (buffer.byteLength - 4 >= size) {
const u8 = new Uint8Array(buffer)
let pkgStr = ''
try {
pkgStr = this.decoder.decode(u8.slice(12, 4 + size - 1))
// pkgStr = ascii_to_utf8(buffer.substr(12, size-8))
} catch (e) {
console.log('decode fail', u8)
}
this.buffer = u8.slice(size + 4).buffer
if (pkgStr.length === 0) continue
try {
let pkg = douyuDecode(pkgStr)
this.listener && this.listener.onPackage(pkg, pkgStr)
} catch (e) {
console.error('call map', e)
}
} else {
break
}
}
}
closeHandler () {
console.error('lost connection')
this.listener && this.listener.onClose()
}
errorHandler (err: string) {
console.error(err)
this.listener && this.listener.onError(err)
}
send (data: DouyuPackage) {
let msg = douyuEncode(data)
let msgu8 = this.encoder.encode(msg)
msgu8 = new Uint8Array(abConcat(msgu8.buffer, new ArrayBuffer(1)))
let buf = new ArrayBuffer(msgu8.length + 12)
const headerView = new DataView(buf)
const hLen = msgu8.length + 8
headerView.setUint32(0, hLen, true)
headerView.setUint32(4, hLen, true)
headerView.setUint32(8, 689, true)
new Uint8Array(buf).set(msgu8, 12)
this.ws.send(buf)
}
}
function Type (type: string) {
return (target: {
map: { [key: string]: Function },
[key: string]: any
}, propertyKey: string, descriptor: PropertyDescriptor) => {
if (!target.map) {
target.map = {}
}
target.map[type] = target[propertyKey]
}
}
abstract class DouyuBaseClient implements DouyuListener {
private prot: DouyuProtocol
private lastIP: string = null
private lastPort: string = null
private keepaliveId: number = null
private reconnectDelay: number = 1000
private queue = Promise.resolve()
redirect: {
[key: string]: string
} = {}
map: {
[key: string]: Function
}
static getRoomArgs () {
if (window._room_args) return window._room_args
if (window.room_args) {
return window.room_args
} else {
return window.$ROOM.args
}
}
async reconnect () {
console.log('reconnect')
this.prot.listener = null
this.prot = new DouyuProtocol(this)
try {
await this.connectAsync(this.lastIP, this.lastPort)
this.onReconnect()
} catch (e) {
// 连接失败
this.onError()
}
}
onClose () {
setTimeout(() => this.reconnect(), this.reconnectDelay)
if (this.reconnectDelay < 16000) {
this.reconnectDelay *= 2
}
}
onError () {
this.onClose()
}
onPackage (pkg: DouyuPackage, pkgStr: string) {
const type = pkg.type
if (this.redirect[type]) {
ACJ(this.redirect[type], pkg)
return
}
if (this.map[type]) {
this.queue = this.queue.then(() => this.map[type].call(this, pkg, pkgStr))
return
}
this.onDefault(pkg)
}
abstract onDefault (pkg: DouyuPackage): void
abstract onReconnect (): void
send (pkg: DouyuPackage) {
this.prot.send(pkg)
}
async connectAsync (ip: string, port: string) {
this.lastIP = ip
this.lastPort = port
const url = `wss://${ip}:${port}/`
await this.prot.connectAsync(url)
this.send(this.loginreq())
}
keepalivePkg (): DouyuPackage {
return {
type: 'keeplive',
tick: Math.round(new Date().getTime() / 1000).toString()
}
}
loginreq () {
const rt = Math.round(new Date().getTime() / 1000)
const devid = getACF('did') // md5(Math.random()).toUpperCase()
const username = getACF('username')
console.log('username', username, devid)
return {
type: 'loginreq',
username: username,
ct: 0,
password: '',
roomid: this.roomId,
devid: devid,
rt: rt,
pt: 2,
vk: md5(`${rt}r5*^5;}2#\${XF[h+;'./.Q'1;,-]f'p[${devid}`),
ver: '20150929',
aver: 'H5_2018021001beta',
biz: getACF('biz'),
stk: getACF('stk'),
ltkid: getACF('ltkid')
}
}
startKeepalive () {
this.send(this.keepalivePkg())
if (this.keepaliveId) {
window.clearInterval(this.keepaliveId)
}
this.keepaliveId = window.setInterval(() => this.send(this.keepalivePkg()), 30 * 1000)
}
constructor (public roomId: string) {
this.prot = new DouyuProtocol(this)
}
}
let blacklist: string[] = []
function onChatMsg (data: DouyuPackage) {
if (blacklist.indexOf(data.uid) !== -1) {
console.log('black')
return
}
try {
postMessage('DANMU', data)
} catch (e) {
console.error('wtf', e)
}
ACJ('room_data_chat2', data)
if (window.BarrageReturn) {
window.BarrageReturn(douyuEncode(data))
}
}
class DouyuClient extends DouyuBaseClient {
uid: string
rg: number
pg: number
danmuClient: DouyuDanmuClient
serverList: {
ip: string,
port: string,
nr: string
}[]
constructor (roomId: string) {
super(roomId)
this.redirect = {
qtlr: 'room_data_tasklis',
initcl: 'room_data_chatinit',
memberinfores: 'room_data_info',
ranklist: 'room_data_cqrank',
rsm: 'room_data_brocast',
qausrespond: 'data_rank_score',
frank: 'room_data_handler',
online_noble_list: 'room_data_handler',
}
}
reqOnlineGift (loginres: DouyuPackage) {
return {
type: 'reqog',
uid: loginres.userid
}
}
@Type('chatmsg')
chatmsg (data: DouyuPackage) {
if (this.rg > 1 || this.pg > 1) {
return
}
onChatMsg(data)
}
@Type('resog')
resog (data: DouyuPackage) {
ACJ('room_data_chest', {
lev: data.lv,
lack_time: data.t,
dl: data.dl
})
}
@Type('loginres')
loginres (data: DouyuPackage) {
console.log('loginres ms', data)
this.uid = data.userid
this.rg = data.roomgroup
this.pg = data.pg
this.send(this.reqOnlineGift(data))
this.startKeepalive()
ACJ('room_data_login', data)
ACJ('room_data_getdid', {
devid: getACF('devid')
})
}
@Type('msgrepeaterproxylist')
async msgrepeaterproxylist (data: DouyuPackage) {
this.serverList = douyuDecodeList(data.list) as any
if (this.danmuClient !== undefined) {
console.warn('skip connect dm')
return
}
const list = this.serverList
const serverAddr = list[randInt(0, list.length)]
this.danmuClient = new DouyuDanmuClient(this.roomId)
window.dm = this.danmuClient
await this.danmuClient.connectAsync(serverAddr.ip, serverAddr.port)
}
@Type('keeplive')
keeplive (data: DouyuPackage, rawString: string) {
ACJ('room_data_userc', data.uc)
ACJ('room_data_tbredpacket', rawString)
}
@Type('setmsggroup')
setmsggroup (data: DouyuPackage) {
console.log('joingroup', data)
this.danmuClient.joingroup(data.rid, data.gid)
}
onDefault (data: DouyuPackage) {
ACJ('room_data_handler', data)
console.log('ms', data.type, data)
}
onReconnect () {
}
}
class DouyuDanmuClient extends DouyuBaseClient {
gid: string
rid: string
hasReconnect: boolean = false
constructor (roomId: string) {
super(roomId)
this.redirect = {
chatres: 'room_data_chat2',
initcl: 'room_data_chatinit',
dgb: 'room_data_giftbat1',
dgn: 'room_data_giftbat1',
spbc: 'room_data_giftbat1',
uenter: 'room_data_nstip2',
upgrade: 'room_data_ulgrow',
newblackres: 'room_data_sys',
ranklist: 'room_data_cqrank',
rankup: 'room_data_ulgrow',
gift_title: 'room_data_schat',
rss: 'room_data_state',
srres: 'room_data_wbsharesuc',
onlinegift: 'room_data_olyw',
gpbc: 'room_data_handler',
synexp: 'room_data_handler',
frank: 'room_data_handler',
ggbb: 'room_data_sabonusget',
online_noble_list: 'room_data_handler',
}
}
joingroup (rid: string, gid: string) {
this.rid = rid
this.gid = gid
this.send({
type: 'joingroup',
rid: rid,
gid: gid
})
}
@Type('chatmsg')
chatmsg (pkg: DouyuPackage) {
onChatMsg(pkg)
}
@Type('loginres')
loginres (data: DouyuPackage) {
console.log('loginres dm', data)
this.startKeepalive()
if (this.hasReconnect) {
this.hasReconnect = false
if (this.rid && this.gid) {
this.joingroup(this.rid, this.gid)
}
}
}
onDefault (data: DouyuPackage) {
ACJ('room_data_handler', data)
console.log('dm', data.type, data)
}
onReconnect () {
this.hasReconnect = true
}
}
function hookDouyu (roomId: string, miscClient: DouyuClient, loginNotify: DelayNotify<void>) {
let oldExe: Function
const repeatPacket = (text: string) => douyuDecode(text)
const jsMap: any = {
js_getRankScore: repeatPacket,
js_getnoble: repeatPacket,
js_rewardList: {
type: 'qrl',
rid: roomId
},
js_queryTask: {
type: 'qtlnq'
},
js_newQueryTask: {
type: 'qtlq'
},
js_sendmsg (msg: string) {
let pkg = douyuDecode(msg)
pkg.type = 'chatmessage'
return pkg
},
js_giveGift (gift: string) {
let pkg = douyuDecode(gift)
if (pkg.type === 'dn_s_gf') {
pkg.type = 'sgq'
pkg.bat = 0
}
console.log('giveGift', gift)
return gift
},
js_GetHongbao: repeatPacket,
js_UserHaveHandle () {},
js_myblacklist (list: string) {
console.log('add blacklist', list)
blacklist = list.split('|')
},
js_medal_opera (opt: string) {
let pkg = douyuDecode(opt)
return pkg
}
}
const api: any = window['require']('douyu/page/room/base/api')
const hookd = function hookd (...args: any[]) {
let req = jsMap[args[0]]
if (args[0] == 'js_userlogin') {
console.log('user login')
loginNotify.notify(undefined)
}
if (req) {
if (typeof req == 'function') {
req = req.apply(null, args.slice(1))
}
req && miscClient.send(req)
} else {
console.log('exe', args)
try {
return oldExe.apply(api, args)
} catch (e) {}
}
}
if (api) {
if (api.exe !== hookd) {
oldExe = api.exe
api.exe = hookd
}
} else if (window.thisMovie) {
window.thisMovie = () => new Proxy({}, {
get (target: any, key: PropertyKey, receiver: any) {
return (...args: any[]) => hookd.apply(null, [key].concat(args))
}
})
}
}
export interface DouyuAPI {
sendDanmu (content: string): void
serverSend (pkg: DouyuPackage): void
}
export async function douyuApi (roomId: string): Promise<DouyuAPI> {
ACJ('room_bus_login', '')
const res = await fetch('/swf_api/getProxyServer')
const args = await res.json()
const servers = args.servers
const mserver = servers[Math.floor(Math.random() * servers.length)]
let miscClient = new DouyuClient(roomId)
const df = new DelayNotify<void>(undefined)
hookDouyu(roomId, miscClient, df)
await df.wait()
await miscClient.connectAsync(mserver.ip, mserver.port)
return {
sendDanmu (content: string) {
// type@=chatmessage/receiver@=0/content@=${内容}/scope@=/col@=0/pid@=/p2p@=0/nc@=0/rev@=0/hg@=0/ifs@=0/sid@=/lid@=0/
miscClient.send({
nc: '0',
rev: '0',
hg: '0',
ifs: '0',
lid: '0',
col: '0',
p2p: '0',
receiver: '0',
content: content,
sid: '',
pid: '',
scope: '',
type: 'chatmessage'
})
},
serverSend (pkg: DouyuPackage) {
return miscClient.send(pkg)
}
}
} | the_stack |
'use strict';
import platform = require('vs/platform/platform');
import { IJSONSchema } from 'vs/base/common/jsonSchema';
import { Color, RGBA } from 'vs/base/common/color';
import { ITheme } from 'vs/platform/theme/common/themeService';
import nls = require('vs/nls');
// ------ API types
export type ColorIdentifier = string;
export interface ColorContribution {
readonly id: ColorIdentifier;
readonly description: string;
readonly defaults: ColorDefaults;
}
export interface ColorFunction {
(theme: ITheme): Color;
}
export interface ColorDefaults {
light: ColorValue;
dark: ColorValue;
hc: ColorValue;
}
/**
* A Color Value is either a color literal, a refence to other color or a derived color
*/
export type ColorValue = Color | string | ColorIdentifier | ColorFunction;
// color registry
export const Extensions = {
ColorContribution: 'base.contributions.colors'
};
export interface IColorRegistry {
/**
* Register a color to the registry.
* @param id The color id as used in theme descrition files
* @param defaults The default values
* @description the description
*/
registerColor(id: string, defaults: ColorDefaults, description: string): ColorIdentifier;
/**
* Get all color contributions
*/
getColors(): ColorContribution[];
/**
* Gets the default color of the given id
*/
resolveDefaultColor(id: ColorIdentifier, theme: ITheme): Color;
/**
* JSON schema of all colors
*/
getColorSchema(): IJSONSchema;
}
const colorPattern = '^#([0-9A-Fa-f]{3,4}|([0-9A-Fa-f]{2}){3,4})$';
const colorPatternErrorMessage = nls.localize('invalid.color', 'Invalid color format. Use #RGB, #RGBA, #RRGGBB or #RRGGBBAA');
class ColorRegistry implements IColorRegistry {
private colorsById: { [key: string]: ColorContribution };
private colorSchema: IJSONSchema = { type: 'object', description: nls.localize('schema.colors', "Colors used in the workbench."), properties: {}, additionalProperties: false };
constructor() {
this.colorsById = {};
}
public registerColor(id: string, defaults: ColorDefaults, description: string): ColorIdentifier {
let colorContribution = { id, description, defaults };
this.colorsById[id] = colorContribution;
this.colorSchema.properties[id] = { type: 'string', description, format: 'color', pattern: colorPattern, patternErrorMessage: colorPatternErrorMessage };
return id;
}
public getColors(): ColorContribution[] {
return Object.keys(this.colorsById).map(id => this.colorsById[id]);
}
public resolveDefaultColor(id: ColorIdentifier, theme: ITheme): Color {
let colorDesc = this.colorsById[id];
if (colorDesc && colorDesc.defaults) {
let colorValue = colorDesc.defaults[theme.type];
return resolveColorValue(colorValue, theme);
}
return null;
}
public getColorSchema(): IJSONSchema {
return this.colorSchema;
}
public toString() {
return Object.keys(this.colorsById).sort().map(k => `- \`${k}\`: ${this.colorsById[k].description}`).join('\n');
}
}
const colorRegistry = new ColorRegistry();
platform.Registry.add(Extensions.ColorContribution, colorRegistry);
export function registerColor(id: string, defaults: ColorDefaults, description: string): ColorIdentifier {
return colorRegistry.registerColor(id, defaults, description);
}
// ----- base colors
export const foreground = registerColor('foreground', { dark: '#CCCCCC', light: '#6C6C6C', hc: '#FFFFFF' }, nls.localize('foreground', "Overall foreground color. This color is only used if not overridden by a component."));
export const focusBorder = registerColor('focusBorder', { dark: Color.fromRGBA(new RGBA(14, 99, 156)).transparent(0.6), light: Color.fromRGBA(new RGBA(0, 122, 204)).transparent(0.4), hc: '#F38518' }, nls.localize('focusBorder', "Overall border color for focused elements. This color is only used if not overridden by a component."));
export const contrastBorder = registerColor('contrastBorder', { light: null, dark: null, hc: '#6FC3DF' }, nls.localize('contrastBorder', "An extra border around elements to separate them from others for greater contrast."));
export const activeContrastBorder = registerColor('contrastActiveBorder', { light: null, dark: null, hc: focusBorder }, nls.localize('activeContrastBorder', "An extra border around active elements to separate them from others for greater contrast."));
// ----- widgets
export const widgetShadow = registerColor('widget.shadow', { dark: '#000000', light: '#A8A8A8', hc: null }, nls.localize('widgetShadow', 'Shadow color of widgets such as find/replace inside the editor.'));
export const inputBackground = registerColor('input.background', { dark: '#3C3C3C', light: Color.white, hc: Color.black }, nls.localize('inputBoxBackground', "Input box background."));
export const inputForeground = registerColor('input.foreground', { dark: foreground, light: foreground, hc: foreground }, nls.localize('inputBoxForeground', "Input box foreground."));
export const inputBorder = registerColor('input.border', { dark: null, light: null, hc: contrastBorder }, nls.localize('inputBoxBorder', "Input box border."));
export const inputActiveOptionBorder = registerColor('inputOption.activeBorder', { dark: '#007ACC', light: '#007ACC', hc: activeContrastBorder }, nls.localize('inputBoxActiveOptionBorder', "Border color of activated options in input fields."));
export const inputValidationInfoBackground = registerColor('inputValidation.infoBackground', { dark: '#063B49', light: '#D6ECF2', hc: Color.black }, nls.localize('inputValidationInfoBackground', "Input validation background color for information severity."));
export const inputValidationInfoBorder = registerColor('inputValidation.infoBorder', { dark: '#55AAFF', light: '#009CCC', hc: '#6FC3DF' }, nls.localize('inputValidationInfoBorder', "Input validation border color for information severity."));
export const inputValidationWarningBackground = registerColor('inputValidation.warningBackground', { dark: '#352A05', light: '#F6F5D2', hc: Color.black }, nls.localize('inputValidationWarningBackground', "Input validation background color for information warning."));
export const inputValidationWarningBorder = registerColor('inputValidation.warningBorder', { dark: '#B89500', light: '#F2CB1D', hc: '#B89500' }, nls.localize('inputValidationWarningBorder', "Input validation border color for warning severity."));
export const inputValidationErrorBackground = registerColor('inputValidation.errorBackground', { dark: '#5A1D1D', light: '#F2DEDE', hc: Color.black }, nls.localize('inputValidationErrorBackground', "Input validation background color for error severity."));
export const inputValidationErrorBorder = registerColor('inputValidation.errorBorder', { dark: '#BE1100', light: '#E51400', hc: '#BE1100' }, nls.localize('inputValidationErrorBorder', "Input validation border color for error severity."));
export const selectBackground = registerColor('dropdown.background', { dark: '#3C3C3C', light: Color.white, hc: Color.black }, nls.localize('dropdownBackground', "Dropdown background."));
export const selectForeground = registerColor('dropdown.foreground', { dark: '#F0F0F0', light: null, hc: Color.white }, nls.localize('dropdownForeground', "Dropdown foreground."));
export const selectBorder = registerColor('dropdown.border', { dark: selectBackground, light: '#CECECE', hc: contrastBorder }, nls.localize('dropdownBorder', "Dropdown border."));
export const listFocusBackground = registerColor('list.focusBackground', { dark: '#073655', light: '#DCEBFC', hc: null }, nls.localize('listFocusBackground', "List/Tree background color for the focused item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not."));
export const listActiveSelectionBackground = registerColor('list.activeSelectionBackground', { dark: '#094771', light: '#3399FF', hc: null }, nls.localize('listActiveSelectionBackground', "List/Tree background color for the selected item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not."));
export const listInactiveSelectionBackground = registerColor('list.inactiveSelectionBackground', { dark: '#3F3F46', light: '#CCCEDB', hc: null }, nls.localize('listInactiveSelectionBackground', "List/Tree background color for the selected item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not."));
export const listActiveSelectionForeground = registerColor('list.activeSelectionForeground', { dark: Color.white, light: Color.white, hc: Color.white }, nls.localize('listActiveSelectionForeground', "List/Tree foreground color for the selected item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not."));
export const listHoverBackground = registerColor('list.hoverBackground', { dark: '#2A2D2E', light: '#F0F0F0', hc: null }, nls.localize('listHoverBackground', "List/Tree background when hovering over items using the mouse."));
export const listDropBackground = registerColor('list.dropBackground', { dark: listFocusBackground, light: listFocusBackground, hc: null }, nls.localize('listDropBackground', "List/Tree drag and drop background when moving items around using the mouse."));
export const listHighlightForeground = registerColor('list.highlightForeground', { dark: '#219AE4', light: '#186B9E', hc: '#219AE4' }, nls.localize('highlight', 'List/Tree foreground color of the match highlights when searching inside the list/tree.'));
export const pickerGroupForeground = registerColor('pickerGroup.foreground', { dark: Color.fromHex('#0097FB').transparent(0.6), light: Color.fromHex('#007ACC').transparent(0.6), hc: Color.white }, nls.localize('pickerGroupForeground', "Quick picker color for grouping labels."));
export const pickerGroupBorder = registerColor('pickerGroup.border', { dark: '#3F3F46', light: '#CCCEDB', hc: Color.white }, nls.localize('pickerGroupBorder', "Quick picker color for grouping borders."));
export const buttonForeground = registerColor('button.foreground', { dark: Color.white, light: Color.white, hc: Color.white }, nls.localize('buttonForeground', "Button foreground color."));
export const buttonBackground = registerColor('button.background', { dark: '#0E639C', light: '#007ACC', hc: null }, nls.localize('buttonBackground', "Button background color."));
export const buttonHoverBackground = registerColor('button.hoverBackground', { dark: lighten(buttonBackground, 0.2), light: darken(buttonBackground, 0.2), hc: null }, nls.localize('buttonHoverBackground', "Button background color when hovering."));
export const scrollbarShadow = registerColor('scrollbar.shadow', { dark: '#000000', light: '#DDDDDD', hc: null }, nls.localize('scrollbarShadow', "Scrollbar shadow to indicate that the view is scrolled."));
export const scrollbarSliderBackground = registerColor('scrollbarSlider.background', { dark: Color.fromHex('#797979').transparent(0.4), light: Color.fromHex('#646464').transparent(0.4), hc: transparent(contrastBorder, 0.6) }, nls.localize('scrollbarSliderBackground', "Slider background color."));
export const scrollbarSliderHoverBackground = registerColor('scrollbarSlider.hoverBackground', { dark: Color.fromHex('#646464').transparent(0.7), light: Color.fromHex('#646464').transparent(0.7), hc: transparent(contrastBorder, 0.8) }, nls.localize('scrollbarSliderHoverBackground', "Slider background color when hovering."));
export const scrollbarSliderActiveBackground = registerColor('scrollbarSlider.activeBackground', { dark: Color.fromHex('#BFBFBF').transparent(0.4), light: Color.fromHex('#000000').transparent(0.6), hc: contrastBorder }, nls.localize('scrollbarSliderActiveBackground', "Slider background color when active."));
/**
* Editor background color.
* Because of bug https://monacotools.visualstudio.com/DefaultCollection/Monaco/_workitems/edit/13254
* we are *not* using the color white (or #ffffff, rgba(255,255,255)) but something very close to white.
*/
export const editorBackground = registerColor('editor.background', { light: '#fffffe', dark: '#1E1E1E', hc: Color.black }, nls.localize('editorBackground', "Editor background color."));
/**
* Editor foreground color.
*/
export const editorForeground = registerColor('editor.foreground', { light: '#333333', dark: '#BBBBBB', hc: Color.white }, nls.localize('editorForeground', "Editor default foreground color."));
/**
* Editor selection colors.
*/
export const editorSelection = registerColor('editor.selectionBackground', { light: '#ADD6FF', dark: '#264F78', hc: '#f3f518' }, nls.localize('editorSelection', "Color of the editor selection."));
export const editorInactiveSelection = registerColor('editor.inactiveSelectionBackground', { light: transparent(editorSelection, 0.5), dark: transparent(editorSelection, 0.5), hc: null }, nls.localize('editorInactiveSelection', "Color of the selection in an inactive editor."));
export const editorSelectionHighlight = registerColor('editor.selectionHighlightBackground', { light: lessProminent(editorSelection, editorBackground, 0.3, 0.6), dark: lessProminent(editorSelection, editorBackground, 0.3, 0.6), hc: null }, nls.localize('editorSelectionHighlight', 'Color for regions with the same content as the selection.'));
/**
* Editor find match colors.
*/
export const editorFindMatch = registerColor('editor.findMatchBackground', { light: '#A8AC94', dark: '#515C6A', hc: null }, nls.localize('editorFindMatch', "Color of the current search match."));
export const editorFindMatchHighlight = registerColor('editor.findMatchHighlightBackground', { light: '#EA5C0055', dark: '#EA5C0055', hc: null }, nls.localize('findMatchHighlight', "Color of the other search matches."));
export const editorFindRangeHighlight = registerColor('editor.findRangeHighlightBackground', { dark: '#3a3d4166', light: '#b4b4b44d', hc: null }, nls.localize('findRangeHighlight', "Color the range limiting the search."));
/**
* Editor link colors
*/
export const editorActiveLinkForeground = registerColor('editorLink.activeForeground', { dark: '#4E94CE', light: Color.black, hc: Color.cyan }, nls.localize('activeLinkForeground', 'Color of active links.'));
/**
* Find widget
*/
export const editorWidgetBackground = registerColor('editorWidget.background', { dark: '#2D2D30', light: '#EFEFF2', hc: '#0C141F' }, nls.localize('editorWidgetBackground', 'Background color of editor widgets, such as find/replace.'));
// ----- color functions
export function darken(colorValue: ColorValue, factor: number): ColorFunction {
return (theme) => {
let color = resolveColorValue(colorValue, theme);
if (color) {
return color.darken(factor);
}
return null;
};
}
export function lighten(colorValue: ColorValue, factor: number): ColorFunction {
return (theme) => {
let color = resolveColorValue(colorValue, theme);
if (color) {
return color.lighten(factor);
}
return null;
};
}
export function transparent(colorValue: ColorValue, factor: number): ColorFunction {
return (theme) => {
let color = resolveColorValue(colorValue, theme);
if (color) {
return color.transparent(factor);
}
return null;
};
}
function lessProminent(colorValue: ColorValue, backgroundColorValue: ColorValue, factor: number, transparency: number): ColorFunction {
return (theme) => {
let from = resolveColorValue(colorValue, theme);
if (from) {
let backgroundColor = resolveColorValue(backgroundColorValue, theme);
if (backgroundColor) {
if (from.isDarkerThan(backgroundColor)) {
return Color.getLighterColor(from, backgroundColor, factor).transparent(transparency);
}
return Color.getDarkerColor(from, backgroundColor, factor).transparent(transparency);
}
return from.transparent(factor * transparency);
}
return null;
};
}
// ----- implementation
/**
* @param colorValue Resolve a color value in the context of a theme
*/
function resolveColorValue(colorValue: ColorValue, theme: ITheme): Color {
if (colorValue === null) {
return null;
} else if (typeof colorValue === 'string') {
if (colorValue[0] === '#') {
return Color.fromHex(colorValue);
}
return theme.getColor(colorValue);
} else if (colorValue instanceof Color) {
return colorValue;
} else if (typeof colorValue === 'function') {
return colorValue(theme);
}
return null;
}
//setTimeout(_ => console.log(colorRegistry.toString()), 5000); | the_stack |
import { REQUEST } from '@nestjs/core'
import { Injectable, Scope, Inject } from '@nestjs/common'
import { QueryService } from '@nestjs-query/core'
import { getConnection } from 'typeorm'
import { BaseService } from '../../utilities/base.service'
import { PlanEntity } from '../entities/plan.entity'
import { Plan } from '../entities/plan.model'
import { PaymentEntity } from '../entities/payment.entity'
import { SettingsService } from '../../settings/settings.service'
import { ProvidersService } from './providers.service'
@QueryService(PlanEntity)
@Injectable({ scope: Scope.REQUEST })
export class PlansService extends BaseService<PlanEntity> {
private readonly planRepository = getConnection().getRepository(PlanEntity)
// private readonly paymentIntegration: string
constructor (
@Inject(REQUEST) private readonly req,
private readonly settingsService: SettingsService,
private readonly providersService: ProvidersService
) {
super(
req,
'PlanEntity'
)
}
/**
* Return a plan object from a string handle
* If plan is not found, or plan is external, but extenal it not allowed, the default plan is returned
* @param handle the handle to the plan. It is in the format 'm-plus' there m stands from monthly or yearly and plus is the immutable name of the plan within Saasform
*/
async getPlanFromHandle (handle: string, allowExternalPlan: boolean): Promise<any> { // TODO: make an entity
const chunks = (handle ?? '').split('_')
let intervalHandle
let ref
if (chunks.length >= 2) {
ref = chunks[1]
intervalHandle = chunks[0] === 'm' ? 'month' : 'year'
} else {
ref = handle
intervalHandle = 'year'
}
const plans = await this.getPlans()
// 1. search exact match
let plan = plans.filter(p => p.hasRef(ref))[0]
// 2. if plan is null, or plan is external, but extenal it not allowed, return default plan
if (
plan == null ||
(plan.data.provider === 'external' && !allowExternalPlan)
) {
plan = plans.filter(p => p.isPrimary())[0]
}
const provider = plan?.getProvider()
const interval = plan?.getInterval(intervalHandle)
const chosenPlan = {
name: plan?.getName(),
freeTrial: plan?.data?.free_trial,
price: plan?.getIntervalPrice(interval),
interval,
ref: plan?.getRef(),
provider
}
chosenPlan[provider] = plan?.getProviderData()
return chosenPlan
// Inkstinct
// return {
// freeTrial: 0, // if 0, no trial, if > 0 days of trial
// price: 4900, // if 0, free tier, if > 0 price
// interval: 'month', // month or year
// ref: 'pro', // internal plan name, immutable
// provider: 'stripe', // stripe/killbill (free tier, trial, full), external (enterprise)
// stripe: { prices: { month: { id: 'price_1JHr1gBZGgCe7OWGGed4jbe7' } } }
// }
// Free trial
// return {
// freeTrial: 4, // if 0, no trial, if > 0 days of trial
// price: 4900, // if 0, free tier, if > 0 price
// interval: 'month', // month or year
// ref: 'pro', // internal plan name, immutable
// provider: 'stripe', // stripe/killbill (free tier, trial, full), external (enterprise)
// stripe: { prices: { month: { id: 'price_1JHr1gBZGgCe7OWGGed4jbe7' } } }
// }
// Enterprise
// return {
// ref: 'pro', // internal plan name, immutable
// provider: 'external' // stripe/killbill (free tier, trial, full), external (enterprise)
// }
// Free tier
// return {
// freeTrial: 0, // if 0, no trial, if > 0 days of trial
// price: 0, // if 0, free tier, if > 0 price
// interval: 'month', // month or year
// ref: 'pro', // internal plan name, immutable
// provider: 'stripe' // stripe/killbill (free tier, trial, full), external (enterprise)
// }
// Free tier with trial
// return {
// freeTrial: 4, // if 0, no trial, if > 0 days of trial
// price: 0, // if 0, free tier, if > 0 price
// interval: 'month', // month or year
// ref: 'pro', // internal plan name, immutable
// provider: 'stripe', // stripe/killbill (free tier, trial, full), external (enterprise)
// stripe: { prices: { month: { id: 'price_1JHr1gBZGgCe7OWGGed4jbe7' } } }
// }
}
// OLD
// createPlan (id, name, description, _prices, features, extra): any {
// if (features == null) { features = [] }
// const prices = _prices.reduce((prices, price) => {
// const { id, currency, unit_amount, unit_amount_decimal, recurring, product } = price // eslint-disable-line
// prices[recurring.interval] = {
// id,
// unit_amount_decimal,
// recurring,
// product,
// currency,
// unit_amount_hr: unit_amount / 100
// }
// return prices
// }, {})
// const plan = {
// id,
// description,
// name,
// features,
// ...extra,
// prices
// }
// return plan
// }
async addPlan (name, description, monthAmount, yearAmount, features, extra): Promise<any> { // TODO: return a proper type
// call payment provider
/*
if (this.paymentIntegration === 'killbill') {
await this.addKillBillPlan(name, description, monthAmount, yearAmount, features, extra)
} else {
await this.addStripePlan(name, description, monthAmount, yearAmount, features, extra)
}
*/
}
async addKillBillPlan (name, description, monthAmount, yearAmount, features, extra): Promise<any> {
/*
try {
let planData: SimplePlan
planData = {
planId: `${String(name)}-monthly`,
productName: name,
productCategory: SimplePlanProductCategoryEnum.BASE,
currency: SimplePlanCurrencyEnum.USD,
amount: monthAmount,
billingPeriod: SimplePlanBillingPeriodEnum.MONTHLY,
trialLength: 0
}
await this.killBillService.catalogApi.addSimplePlan(planData, 'saasform')
planData = {
planId: `${String(name)}-yearly`,
productName: name,
productCategory: SimplePlanProductCategoryEnum.BASE,
currency: SimplePlanCurrencyEnum.USD,
amount: yearAmount,
billingPeriod: SimplePlanBillingPeriodEnum.ANNUAL,
trialLength: 0
}
await this.killBillService.catalogApi.addSimplePlan(planData, 'saasform')
// For now, make it look like a Stripe plan (the Kill Bill data model is quite different though)
const product = { id: name, description: description, killbill: true }
const monthPrice = { type: 'recurring', unit_amount: monthAmount, recurring: { interval: 'month', interval_count: 1 }, killbill: true }
const yearPrice = { type: 'recurring', unit_amount: monthAmount, recurring: { interval: 'year', interval_count: 1 }, killbill: true }
const _plan = this.createPlan(
product.id, name, description,
[monthPrice, yearPrice],
features,
extra
)
const plan = new PlanEntity()
// plan.product = JSON.stringify(product)
// plan.prices = JSON.stringify([monthPrice, yearPrice])
// plan.plan = JSON.stringify(_plan)
await this.createOne(plan)
} catch (err) {
console.error('Error while creating plan', name, description, monthAmount, yearAmount, features, err)
return null
}
*/
}
// TODO: Refactor
async createFirstBilling (): Promise<any> { // TODO: return a proper type
/*
// should we move the API call outside?
await this.addPlan(
'Starter',
'Starter plan',
3500, 2900 * 12,
[
{ name: '3 sites' },
{ name: '1,000 shares' },
{ name: 'Email support' }
],
{
button: 'Choose'
}
)
await this.addPlan(
'Pro',
'Pro plan',
11900, 9900 * 12,
[
{ name: '100 sites' },
{ name: 'Unlimited shares' },
{ name: 'Premium support' }
],
{
button: 'Choose',
primary: true
}
)
await this.addPlan(
'Enterprise',
'Enterprise plan',
0, 0,
[
{ name: 'All features' },
{ name: 'Cloud or on-prem' },
{ name: 'Premium support' }
],
{
button: 'Contact us',
priceText: 'Let\'s talk'
}
)
*/
}
validatePlan (p): any {
/*
const plan = JSON.parse(p.plan)
plan.prices.year.unit_amount_hr = (plan.price_decimals > 0) ? plan.prices.year.unit_amount_hr / 12 : Math.round(plan.prices.year.unit_amount_hr / 12)
plan.uid = p.id // MySql ID used to update the plan
return {
...plan,
button: plan.button ?? 'Choose',
price_year: plan.prices.year.unit_amount_hr,
price_month: plan.prices.month.unit_amount_hr,
price_decimals: plan.price_decimals ?? 0,
price_text: plan.priceText,
free_trial: plan.freeTrial
}
*/
}
/**
* Return the plan list.
* The list is returned from the db, table plans.
* If the db table is empty, plans are generated from website.yml.
* When a payment processor is configured, plans are created in the db from website.yml.
*
* Said in another way, one can:
* - launch saasform and see default plans (from website.yml)
* - change website.yml, see updated plans
* - configure Stripe (or Killbill) - at this point plans are stored in the db (with ref to, e.g., Stripe products)
* - any further change must be done inside the db (or clearing the db first)
* @returns Plan list
*/
async getPlans (): Promise<any[]> {
// 1. get the plan list
let plans = await this.query({})
// 2. if plan list if empty, create from setting.yaml
if (plans == null || plans.length === 0) {
const settings = await this.settingsService.getWebsiteRenderingVariables()
const plansFromSettings = settings.pricing_plans ?? []
plans = plansFromSettings.map(planData => {
const plan = new PlanEntity()
plan.data = { ...planData }
const priceYear = planData.price_year ?? null
const priceMonth = planData.price_month ?? null
const priceText = planData.price_text ?? null
// Check plan type: 1. enterprise 2. free tier 3. free trial 4. full
if (priceText != null && priceYear == null && priceMonth == null) {
// enterprise
plan.data.provider = 'external'
} else if (priceYear === 0 && priceMonth === 0) {
// free tier, pass
} else {
// free trial and full subscription
plan.data.free_trial = settings.pricing_free_trial
}
plan.setValuesFromJson()
return plan
})
const config = await this.providersService.getPaymentsConfig()
const provider = config.payment_processor_enabled === true ? config.payment_processor : null
// 3. If payment processor is configured, sync the newly created plans (TODO)
if (plans != null && plans.length > 0 && provider != null) {
let shouldPersistData = true
for (let i = 0; i < plans.length; i++) {
try {
// a. sync with payment processor, if not enterprise or free tier
const p = plans[i]
if (!p.isExternal() && !p.isFreeTier()) {
const providerData = await this.providersService.createPlan(p)
if (providerData == null) {
shouldPersistData = false
}
p.data[provider] = providerData
}
} catch (err) {
console.error('plansService - getPlans - exception while creating payment provider plans', err)
}
}
// todo: check provider sync was successful
if (shouldPersistData) {
for (let i = 0; i < plans.length; i++) {
try {
// b. persist on DB. Make sure to set the ref if ref is not set!
const newPlan = await this.createOne(plans[i])
if (newPlan == null) {
console.error('plansService - getPlans - error while persisting plan', plans[i])
}
} catch (err) {
console.error('plansService - getPlans - exception while persisting plans', err)
}
}
}
}
}
return plans
}
async getPricingAndPlans (): Promise<any> {
const plans = await this.getPlans()
return {
free_trial: plans?.[0]?.free_trial ?? 0,
plans
}
}
async getPlanForPayment (payment: PaymentEntity): Promise<any> { // TODO: use a better type
if (payment == null) { return null }
const plans = await this.getPlans()
const plan =
payment && payment.data && payment.data.plan // eslint-disable-line
? plans.filter(p => p.id === payment.data.plan.product)[0]
: null
return plan
}
// This will update both the month and year prices for a plan
/**
* Updates a single plan. It requires both the month and year prices
* If a price has changes, a new price is created on Stripe and updated
* on the DB.
* @param plan
*/
async updatePlan (plan: Plan): Promise<PlanEntity | null> {
return null
/*
// 1. get plan from DB
const savedPlan = await this.findById(plan.uid)
if (savedPlan == null) {
console.error('plansService - updatePlan - savedPlan not found', plan)
return null
}
// TODO: replace this with actual JSON values on the DB. See users and account for example
let monthPrice = JSON.parse(savedPlan.prices)[0]
let yearPrice = JSON.parse(savedPlan.prices)[1]
let toUpdate = false
// Create a new Stripe pricing for month price if necessary
if (monthPrice.unit_amount_decimal !== plan.prices.month.unit_amount_decimal) {
toUpdate = true
monthPrice = await this.stripeService.client.prices.create({
unit_amount: plan.prices.month.unit_amount_decimal,
currency: 'usd',
recurring: { interval: 'month' },
product: plan.id
}, this.stripeService.apiOptions)
}
// Create a new Stripe pricing for year price if necessary
if (yearPrice.unit_amount_decimal !== plan.prices.year.unit_amount_decimal) {
toUpdate = true
yearPrice = await this.stripeService.client.prices.create({
unit_amount: plan.prices.year.unit_amount_decimal,
currency: 'usd',
recurring: { interval: 'year' },
product: plan.id
}, this.stripeService.apiOptions)
}
const FIELDS = ['name', 'limitUsers', 'freeTrial', 'priceText']
const savedPlanData = JSON.parse(savedPlan.plan)
for (const key of FIELDS) {
if (plan[key] !== savedPlanData[key]) {
toUpdate = true
}
}
// Update plan on the DB, if necessary
if (toUpdate) {
// TODO: replace this with actual JSON values on the DB. See users and account for example
const { id, name, description, features, ...extra } = savedPlanData
const newExtra = {
...extra,
limitUsers: plan.limitUsers,
freeTrial: plan.freeTrial,
priceText: plan.priceText
}
const _plan = this.createPlan(
id, plan.name, description,
[monthPrice, yearPrice],
plan?.features ?? [],
newExtra
)
// TODO: replace this with actual JSON values on the DB. See users and account for example
savedPlan.prices = JSON.stringify([monthPrice, yearPrice])
savedPlan.plan = JSON.stringify(_plan)
const { id: plan_id, ...update } = savedPlan // eslint-disable-line
await this.updateOne(plan.uid, update)
}
const ret = await this.findById(plan.uid)
if (ret == null) {
console.error('plansService - error')
return null
}
return ret
*/
}
/**
* Get a price given a plan and the indication if it is annual or monthly payment
*
* @param product
* @param annual
*/
async getPriceByProductAndAnnual (product: any, monthly: any): Promise<any> {
const plans = await this.getPlans()
const res = plans.filter(p => p.id === product)[0]
return monthly != null ? res.prices.month : res.prices.year
}
} | the_stack |
var typeMapping: { [s: string]: any } = {
"RC:TxtMsg": "TextMessage",
"RC:ImgMsg": "ImageMessage",
"RC:VcMsg": "VoiceMessage",
"RC:ImgTextMsg": "RichContentMessage",
"RC:FileMsg": "FileMessage",
"RC:HQVCMsg": "HQVoiceMessage",
"RC:LBSMsg": "LocationMessage",
"RC:InfoNtf": "InformationNotificationMessage",
"RC:ContactNtf": "ContactNotificationMessage",
"RC:ProfileNtf": "ProfileNotificationMessage",
"RC:CmdNtf": "CommandNotificationMessage",
"RC:DizNtf": "DiscussionNotificationMessage",
"RC:CmdMsg": "CommandMessage",
"RC:TypSts": "TypingStatusMessage",
"RC:CsChaR": "ChangeModeResponseMessage",
"RC:CsHsR": "HandShakeResponseMessage",
"RC:CsEnd": "TerminateMessage",
"RC:CsSp": "SuspendMessage",
"RC:CsUpdate": "CustomerStatusUpdateMessage",
"RC:ReadNtf": "ReadReceiptMessage",
"RC:VCAccept": "AcceptMessage",
"RC:VCRinging": "RingingMessage",
"RC:VCSummary": "SummaryMessage",
"RC:VCHangup": "HungupMessage",
"RC:VCInvite": "InviteMessage",
"RC:VCModifyMedia": "MediaModifyMessage",
"RC:VCModifyMem": "MemberModifyMessage",
"RC:CsContact": "CustomerContact",
"RC:PSImgTxtMsg": "PublicServiceRichContentMessage",
"RC:PSMultiImgTxtMsg": "PublicServiceMultiRichContentMessage",
"RC:GrpNtf": "GroupNotificationMessage",
"RC:PSCmd": "PublicServiceCommandMessage",
"RC:RcCmd": "RecallCommandMessage",
"RC:SRSMsg": "SyncReadStatusMessage",
"RC:RRReqMsg": "ReadReceiptRequestMessage",
"RC:RRRspMsg": "ReadReceiptResponseMessage",
"RCJrmf:RpMsg": "JrmfRedPacketMessage",
"RCJrmf:RpOpendMsg": "JrmfRedPacketOpenedMessage",
"RC:CombineMsg":"RCCombineMessage",
"RC:chrmKVNotiMsg": "ChrmKVNotificationMessage"
},
//自定义消息类型
registerMessageTypeMapping: { [s: string]: any } = {},
HistoryMsgType: { [s: number]: any } = {
4: "qryCMsg",
2: "qryDMsg",
3: "qryGMsg",
1: "qryPMsg",
6: "qrySMsg",
7: "qryPMsg",
8: "qryPMsg",
5: "qryCMsg"
}, disconnectStatus: { [s: number]: any } = { 1: 6 };
module RongIMLib {
/**
* 通道标识类
*/
export class Transportations {
static _TransportType: string = Socket.WEBSOCKET;
}
export class SyncTimeUtil {
static $getKey(message: any){
var client = Bridge._client;
var userId = client.userId;
var direction = (message.messageDirection == 1 ? 'send' : 'receive');
var appkey = RongIMClient._memoryStore.appKey;
var tpl = '{appkey}_{userId}_{direction}box';
return RongUtil.tplEngine(tpl, {
appkey: appkey,
userId: userId,
direction: direction
});
}
static set(message: any){
var key = SyncTimeUtil.$getKey(message)
var sentTime = message.sentTime;
var storage = RongIMClient._storageProvider;
storage.setItem(key, sentTime);
}
static get(){
var sent = SyncTimeUtil.$getKey({
messageDirection: MessageDirection.SEND
});
var received = SyncTimeUtil.$getKey({
messageDirection: MessageDirection.RECEIVE
});
var storage = RongIMClient._storageProvider;
return {
sent: Number(storage.getItem(sent) || 0),
received: Number(storage.getItem(received) || 0)
};
}
}
export class MessageUtil {
//适配SSL
// static schemeArrs: Array<any> = [["http", "ws"], ["https", "wss"]];
static sign: any = { converNum: 1, msgNum: 1, isMsgStart: true, isConvStart: true };
/**
*4680000 为localstorage最小容量5200000字节的90%,超过90%将删除之前过早的存储
*/
static checkStorageSize(): boolean {
return JSON.stringify(localStorage).length < 4680000;
}
static getFirstKey(obj: any): string {
var str: string = "";
for (var key in obj) {
str = key;
break;
}
return str;
}
static isEmpty(obj: any): boolean {
var empty: boolean = true;
for (var key in obj) {
empty = false;
break;
}
return empty;
}
static ArrayForm(typearray: any): Array<any> {
if (Object.prototype.toString.call(typearray) == "[object ArrayBuffer]") {
var arr = new Int8Array(typearray);
return [].slice.call(arr);
}
return typearray;
}
static ArrayFormInput(typearray: any): Uint8Array {
if (Object.prototype.toString.call(typearray) == "[object ArrayBuffer]") {
var arr = new Uint8Array(typearray);
return arr;
}
return typearray;
}
static indexOf(arr?: any, item?: any, from?: any): number {
for (var l = arr.length, i = (from < 0) ? Math.max(0, +from) : from || 0; i < l; i++) {
if (arr[i] == item) {
return i;
}
}
return -1;
}
static isArray(obj: any) {
return Object.prototype.toString.call(obj) == "[object Array]";
}
//遍历,只能遍历数组
static forEach(arr: any, func: any) {
if ([].forEach) {
return function(arr: any, func: any) {
[].forEach.call(arr, func);
};
} else {
return function(arr: any, func: any) {
for (var i = 0; i < arr.length; i++) {
func.call(arr, arr[i], i, arr);
}
};
}
}
static remove(array: any, func: any): void {
for (var i = 0, len = array.length; i < len; i++) {
if (func(array[i])) {
return array.splice(i, 1)[0];
}
}
return null;
}
static int64ToTimestamp(obj: any, isDate?: boolean) {
if (obj.low === undefined) {
return obj;
}
var low = obj.low;
if (low < 0) {
low += 0xffffffff + 1;
}
low = low.toString(16);
var timestamp = parseInt(obj.high.toString(16) + "00000000".replace(new RegExp("0{" + low.length + "}$"), low), 16);
if (isDate) {
return new Date(timestamp);
}
return timestamp;
}
//消息转换方法
static messageParser(entity: any, onReceived?: any, offlineMsg?: boolean): any {
var message: Message = new Message(), content: any = entity.content, de: any, objectName: string = entity.classname, val: any, isUseDef = false;
try {
if (RongIMClient._memoryStore.depend.isPolling) {
val = new BinaryHelper().readUTF(content.offset ? MessageUtil.ArrayForm(content.buffer).slice(content.offset, content.limit) : content);
de = JSON.parse(val);
} else {
val = new BinaryHelper().readUTF(content.offset ? MessageUtil.ArrayFormInput(content.buffer).subarray(content.offset, content.limit) : content);
de = JSON.parse(val);
}
} catch (ex) {
de = val;
isUseDef = true;
}
var IMLib: any = RongIMLib;
//映射为具体消息对象
if (objectName in typeMapping) {
var typeName = typeMapping[objectName];
message.content = new IMLib[typeName](de);
message.messageType = typeMapping[objectName];
} else if (objectName in registerMessageTypeMapping) {
var typeName = registerMessageTypeMapping[objectName];
var regMsg = new IMLib.RongIMClient.RegisterMessage[typeName](de);
if (isUseDef) {
message.content = regMsg.decode(de);
} else {
message.content = regMsg;
}
message.messageType = registerMessageTypeMapping[objectName];
} else {
message.content = new UnknownMessage({ content: de, objectName: objectName });
message.messageType = "UnknownMessage";
}
//根据实体对象设置message对象]
var dateTime = MessageUtil.int64ToTimestamp(entity.dataTime);
if (dateTime > 0) {
message.sentTime = dateTime;
} else {
message.sentTime = +new Date;
}
message.senderUserId = entity.fromUserId;
message.conversationType = entity.type;
if (entity.fromUserId == Bridge._client.userId) {
message.targetId = entity.groupId;
} else {
message.targetId = (/^[234]$/.test(entity.type || entity.getType()) ? entity.groupId : message.senderUserId);
}
var selfUserId = Bridge._client.userId;
// 解决多端在线收自己发的消息时, messageDirection 为 2(接收), 导致未读数增加
var isSelfSend = entity.direction == 1 || message.senderUserId === selfUserId;
if (isSelfSend) {
message.messageDirection = MessageDirection.SEND;
message.senderUserId = Bridge._client.userId;
} else {
message.messageDirection = MessageDirection.RECEIVE;
}
// 自己给自己发的消息, messageDirection 为 2(接收)
var isSelfToSelf = message.senderUserId === selfUserId && message.targetId === selfUserId;
if (isSelfToSelf) {
message.messageDirection = MessageDirection.RECEIVE;
}
message.messageUId = entity.msgId;
message.receivedTime = new Date().getTime();
message.messageId = (message.conversationType + "_" + ~~(Math.random() * 0xffffff));
message.objectName = objectName;
message.receivedStatus = ReceivedStatus.READ;
if ((entity.status & 2) == 2) {
message.receivedStatus = ReceivedStatus.RETRIEVED;
}
message.offLineMessage = offlineMsg ? true : false;
if (!offlineMsg) {
if (RongIMLib.RongIMClient._memoryStore.connectAckTime > message.sentTime) {
message.offLineMessage = true;
}
}
return message;
}
static detectCMP(options: any){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4){
var status = xhr.status;
if(status == 200){
options.success();
}else{
options.fail(xhr.status);
}
}
};
var method = options.url;
var url = options.url;
var method = options.method || 'GET';
xhr.open(method, url);
var headers = options.headers;
for (var key in headers) {
var value = headers[key];
xhr.setRequestHeader(key, value);
}
var body = JSON.stringify(options.body || {});
xhr.send(body);
return xhr;
}
}
/**
* 工具类
*/
export class MessageIdHandler {
static messageId: number = 0;
static init() {
this.messageId = +(RongIMClient._storageProvider.getItem(Navigation.Endpoint.userId + "msgId") || RongIMClient._storageProvider.setItem(Navigation.Endpoint.userId + "msgId", 0) || 0);
}
static messageIdPlus(method: any): any {
RongIMClient._memoryStore.depend.isPolling && this.init();
if (this.messageId >= 65535) {
this.messageId = 0;
}
this.messageId++;
RongIMClient._memoryStore.depend.isPolling && RongIMClient._storageProvider.setItem(Navigation.Endpoint.userId + "msgId", this.messageId);
return this.messageId;
}
static clearMessageId() {
this.messageId = 0;
RongIMClient._memoryStore.depend.isPolling && RongIMClient._storageProvider.setItem(Navigation.Endpoint.userId + "msgId", this.messageId);
}
static getMessageId() {
RongIMClient._memoryStore.depend.isPolling && this.init();
return this.messageId;
}
}
class ChrmKVCaches {
time: number = 0;
cache: any = {};
setTime(time: number) {
this.time = time;
}
getTime(): number {
return this.time;
}
setValue(kvContent: ChrmKVCacheContent) {
var key = kvContent.key, timestamp = kvContent.timestamp;
this.cache[key] = this.cache[key] || {};
this.cache[key] = {
value: kvContent.value,
userId: kvContent.userId,
isDeleted: false,
timestamp: timestamp
};
}
removeValue(kvContent: ChrmKVCacheContent) {
var key = kvContent.key, timestamp = kvContent.timestamp;
this.cache[key] = this.cache[key] || {};
var cache = this.cache[key];
this.cache[key] = RongUtil.extend(cache, {
isDeleted: true,
userId: kvContent.userId,
timestamp: timestamp
});
}
getValue(key: string): string {
this.cache[key] = this.cache[key] || {};
var cache = this.cache[key];
return cache.isDeleted ? null : cache.value;
}
getAllKV() {
var kv: any = {};
RongUtil.forEach(this.cache, function (item: any, key: string) {
if (!item.isDeleted) {
kv[key] = item.value;
}
});
return kv;
}
getSetUserId(key: string): string {
this.cache[key] = this.cache[key] || {};
return this.cache[key].userId;
}
isKeyExisted(key: string) {
this.cache[key] = this.cache[key] || {};
var cache = this.cache[key];
var hasValue = !RongUtil.isEmpty(cache.value);
return hasValue && !cache.isDeleted;
}
clear() {
this.cache = {};
}
}
var chrmKVCaches: any = {};
var chrmKVProsumerCaches: any = {};
var getKVCache = (chrmId: string) => {
var chrmKVCache = chrmKVCaches[chrmId];
if (!chrmKVCache) {
chrmKVCache = chrmKVCaches[chrmId] = new ChrmKVCaches();
}
return chrmKVCache;
};
var getKVProsumer = (chrmId: string) => {
var kvProsumer = chrmKVProsumerCaches[chrmId];
if (!kvProsumer) {
kvProsumer = chrmKVProsumerCaches[chrmId] = new RongUtil.Prosumer();
}
return kvProsumer;
};
export class ChrmKVHandler {
static pull(chrmId: string, time: number) {
var prosumer = getKVProsumer(chrmId);
var event = RongIMClient._dataAccessProvider.pullChatroomEntry;
prosumer.produce({ event, chrmId, time });
prosumer.consume(function (params: any, next: any) {
var { event, chrmId, time } = params;
var kvCache = getKVCache(chrmId);
var currentTime = kvCache.getTime();
var isKVNeedUpdated = currentTime < time;
if (isKVNeedUpdated) {
event(chrmId, currentTime, {
onSuccess: function (result: any) {
ChrmKVHandler.setEntries(chrmId, result);
next();
},
onError: next
});
} else {
next();
}
});
}
static setEntries(chrmId: string, entity: any) {
var entries: Array<any> = entity.entries, isFullUpdate: boolean = entity.bFullUpdate, syncTime = entity.syncTime;
var event = isFullUpdate ? ChrmKVHandler.setFullEntries : ChrmKVHandler.setIncreEntries;
var kvCache = getKVCache(chrmId);
syncTime = MessageUtil.int64ToTimestamp(syncTime);
if (RongUtil.isArray(entries)) {
RongUtil.forEach(entries, (item: any) => {
var setTime = item.timestamp;
if (!RongUtil.isNumber(setTime)) {
item.timestamp = MessageUtil.int64ToTimestamp(setTime);
}
});
}
kvCache.setTime(syncTime); // 更新拉取时间
event(chrmId, entries); // 更新 kv 值
}
static setEntry(chrmId: string, chatroomEntry: ChatroomEntry, status: number, userId: string) {
var kvCache = getKVCache(chrmId);
var timestamp = chatroomEntry.timestamp || +new Date();
var isDelete = RongInnerTools.getChrmEntityByStatus(status).isDelete;
var eventName = isDelete ? 'removeValue' : 'setValue';
kvCache[eventName]({
key: chatroomEntry.key,
value: chatroomEntry.value,
userId: userId,
timestamp: timestamp
});
}
static setFullEntries(chrmId: string, entries: Array<any>) { // 全量更新
var kvCache = getKVCache(chrmId);
kvCache.clear();
RongUtil.forEach(entries, function (entity:any) {
entity.timestamp = MessageUtil.int64ToTimestamp(entity.timestamp);
kvCache.setValue({
key: entity.key,
value: entity.value,
userId: entity.uid,
timestamp: entity.timestamp
});
});
}
static setIncreEntries(chrmId: string, entries: Array<any>) {
var kvCache = getKVCache(chrmId);
var currentUserId = RongIMClient.getInstance().getCurrentUserId();
var optEvent = function (entity:any, isOverwrite: boolean, eventName: string) {
var key = entity.key, value = entity.value;
var isLatestedKeySetBySelf = kvCache.getSetUserId(key) === currentUserId;
var isKeyNotExist = !kvCache.isKeyExisted(key);
/*
1. 需覆盖时, 不管 key 是否已存在, 都直接设置
2. 不覆盖时, 必须最后一次 key 为自己设置的或此 key 还未设置过, 才能继续
*/
if (isOverwrite || isLatestedKeySetBySelf || isKeyNotExist) {
kvCache[eventName]({
key: key,
value: value,
userId: entity.uid,
timestamp: entity.timestamp
});
}
};
RongUtil.forEach(entries, function (entity: any) {
var entityContent = RongInnerTools.getChrmEntityByStatus(entity.status);
var eventName = entityContent.isDelete ? 'removeValue' : 'setValue';
optEvent(entity, entityContent.isOverwrite, eventName);
});
}
static getEntityValue(chrmId: string, key: string) {
var kvCache = getKVCache(chrmId);
return kvCache.getValue(key);
}
static getAllEntityValue(chrmId: string) {
var kvCache = getKVCache(chrmId);
return kvCache.getAllKV();
}
static isKeyValid(key: string) {
return /^[A-Za-z0-9_=+-]+$/.test(key);
}
}
var AutoDeleteCode = 0x0001;
var OverwriteCode = 0x0002;
var DeleteOperationCode = 0x0004;
export class RongInnerTools {
static convertUserStatus(entity: any): any{
entity = RongUtil.rename(entity, {subUserId: 'userId'});
var status = JSON.parse(entity.status);
var us = status.us;
if (!us) {
return entity;
}
entity.status = RongUtil.rename(us, {o: 'online', 'p': 'platform', s: 'status'});
return entity;
}
static getChrmEntityStatus(entity: ChatroomEntry, chatroomOpt: ChatroomEntityOpt): number {
var status = 0;
// 是否自动清理
if (entity.isAutoDelete) {
status = status | AutoDeleteCode;
}
// 是否覆盖
if (entity.isOverwrite) {
status = status | OverwriteCode;
}
// 操作类型
switch (chatroomOpt) {
case ChatroomEntityOpt.DELETE:
status = status | DeleteOperationCode;
break;
default:
break;
}
return status;
}
static getChrmEntityByStatus(status: number): any {
var isDelete = !!(status & DeleteOperationCode);
var entityOpt = isDelete ? ChatroomEntityOpt.DELETE : ChatroomEntityOpt.UPDATE;
return {
isAutoDelete: !!(status & AutoDeleteCode),
isOverwrite: !!(status & OverwriteCode),
entityOpt: entityOpt,
isDelete: isDelete
};
}
}
export class UnreadCountHandler {
static KeyTemp: string = 'cu{selfId}{type}{targetId}';
static ValueTemp: string = '{count}_{sentTime}';
static getKey(type: ConversationType|string, targetId: string): string {
var selfId = RongIMClient.getInstance().getCurrentUserId();
return RongUtil.tplEngine(UnreadCountHandler.KeyTemp, {
selfId,
type,
targetId
});
}
static getDetailByKey(key: string): any {
var detail = { count: 0, sentTime: 0 };
var value = RongIMClient._storageProvider.getItem(key) + '';
if (!value) {
return detail;
}
var unreadItems = value.split('_');
var hasUnderline = unreadItems.length > 1;
detail.count = Number(unreadItems[0]);
if (hasUnderline) {
detail.sentTime = Number(unreadItems[1]);
}
return detail;
}
static getDetail(type: ConversationType, targetId: string): any {
var key = UnreadCountHandler.getKey(type, targetId);
var detail = UnreadCountHandler.getDetailByKey(key);
return detail;
}
static set(type: ConversationType, id: string, count: number, sentTime?: number) {
var key = UnreadCountHandler.getKey(type, id);
var value = sentTime ? RongUtil.tplEngine(UnreadCountHandler.ValueTemp, {
count,
sentTime
}) : count;
RongIMClient._storageProvider.setItem(key, value);
return count;
}
static add(type: ConversationType, id: string, plusCount: number, sentTime?: number) {
var detail = UnreadCountHandler.getDetail(type, id),
count = detail.count,
oldSentTime = detail.sentTime;
if (sentTime && sentTime > oldSentTime) {
count = count + plusCount;
UnreadCountHandler.set(type, id, count, sentTime);
}
return count;
}
static get(type: ConversationType, id: string): number {
var detail = UnreadCountHandler.getDetail(type, id);
return detail.count;
}
static getAll(types?: Array<ConversationType>) {
var total = 0;
var selfId = RongIMClient.getInstance().getCurrentUserId();
var setTotal = (keyList: Array<string>) => {
RongUtil.forEach(keyList, (key: string) => {
var detail = UnreadCountHandler.getDetailByKey(key);
total += detail.count;
});
};
if (types) {
RongUtil.forEach(types, (type: number) => {
var key = UnreadCountHandler.getKey(type, '');
var unreadKeys = RongIMClient._storageProvider.getItemKeyList(key);
setTotal(unreadKeys);
});
} else {
var key = UnreadCountHandler.getKey('', '');
var unreadKeys = RongIMClient._storageProvider.getItemKeyList(key);
setTotal(unreadKeys);
}
return total;
}
static remove(type: ConversationType, targetId: string) {
var key = UnreadCountHandler.getKey(type, targetId);
RongIMClient._storageProvider.removeItem(key);
}
static clear() {
var key = UnreadCountHandler.getKey('', '');
var keyList = RongIMClient._storageProvider.getItemKeyList(key);
RongUtil.forEach(keyList, (key: string) => {
RongIMClient._storageProvider.removeItem(key);
});
}
}
} | the_stack |
export interface ProductColor {
light: string;
lightHover: string;
lightActive: string;
normal: string;
normalHover: string;
normalActive: string;
dark: string;
darkHover: string;
darkActive: string;
darker: string;
}
export interface StatusColor {
light: string;
lightHover: string;
lightActive: string;
normal: string;
normalHover: string;
normalActive: string;
dark: string;
darkHover: string;
darkActive: string;
darker: string;
}
export interface WhiteColor {
normal: string;
normalHover: string;
normalActive: string;
}
export interface CloudColor {
light: string;
lightHover: string;
lightActive: string;
normal: string;
normalHover: string;
normalActive: string;
dark: string;
}
export interface InkColor {
lighter: string;
lighterHover: string;
lighterActive: string;
light: string;
lightHover: string;
lightActive: string;
normal: string;
normalHover: string;
normalActive: string;
}
export interface SocialColor {
facebook: string;
facebookHover: string;
facebookActive: string;
}
export interface Palette {
product: ProductColor;
white: WhiteColor;
cloud: CloudColor;
ink: InkColor;
orange: StatusColor;
red: StatusColor;
green: StatusColor;
blue: StatusColor;
social: SocialColor;
}
export interface Base {
fontFamily: string;
fontSizeSm: string;
fontSizeMd: string;
fontSizeLg: string;
borderRadius: string;
sizeSm: string;
sizeMd: string;
sizeLg: string;
sizeXl: string;
size2xl: string;
opacitySmall: string;
opacityMedium: string;
opacityLarge: string;
fontWeightNormal: string;
fontWeightMedium: string;
fontWeightBold: string;
space2xs: string;
spaceXs: string;
spaceSm: string;
spaceMd: string;
spaceLg: string;
spaceXl: string;
space2xl: string;
space3xl: string;
durationFast: string;
durationNormal: string;
durationSlow: string;
transitionDefault: string;
lineHeight: string;
boxShadowStatic: string;
boxShadowActionable: string;
boxShadowElevated: string;
boxShadowModal: string;
boxShadowColorStatic: string;
boxShadowColorActionable: string;
boxShadowColorElevated: string;
boxShadowColorModal: string;
}
export interface Foundation {
palette: Palette;
base: Base;
}
export interface CustomPalette {
product?: Partial<ProductColor> | undefined;
white?: Partial<WhiteColor> | undefined;
cloud?: Partial<CloudColor> | undefined;
ink?: Partial<InkColor> | undefined;
orange?: Partial<StatusColor> | undefined;
red?: Partial<StatusColor> | undefined;
green?: Partial<StatusColor> | undefined;
blue?: Partial<StatusColor> | undefined;
social?: Partial<SocialColor> | undefined;
}
export type CustomBase = Partial<Base>;
export type CustomFoundation = Partial<{
palette: CustomPalette;
base: CustomBase;
}>;
export interface Tokens {
colorTextPrimary: string;
colorTextSecondary: string;
colorTextAttention: string;
colorTextError: string;
colorTextInfo: string;
colorTextSuccess: string;
colorTextWarning: string;
colorTextCritical: string;
colorTextWhite: string;
colorIconPrimary: string;
colorIconSecondary: string;
colorIconAttention: string;
colorIconTertiary: string;
colorIconInfo: string;
colorIconSuccess: string;
colorIconWarning: string;
colorIconCritical: string;
colorHeading: string;
colorHeadingInverted: string;
colorTextLinkPrimary: string;
colorTextLinkPrimaryHover: string;
colorTextLinkSecondary: string;
colorTextLinkSecondaryHover: string;
colorAlertIconSuccess: string;
colorTextAlertSuccess: string;
colorAlertIconInfo: string;
colorTextAlertInfo: string;
colorAlertIconWarning: string;
colorTextAlertWarning: string;
colorAlertIconCritical: string;
colorTextAlertCritical: string;
colorTextAlertLink: string;
colorTextButtonFilled: string;
colorTextButtonFilledHover: string;
colorTextButtonFilledActive: string;
colorTextButtonPrimary: string;
colorTextButtonPrimaryHover: string;
colorTextButtonPrimaryActive: string;
colorTextButtonSecondary: string;
colorTextButtonSecondaryHover: string;
colorTextButtonSecondaryActive: string;
colorTextButtonInfo: string;
colorTextButtonInfoHover: string;
colorTextButtonInfoActive: string;
colorTextButtonSuccess: string;
colorTextButtonSuccessHover: string;
colorTextButtonSuccessActive: string;
colorTextButtonWarning: string;
colorTextButtonWarningHover: string;
colorTextButtonWarningActive: string;
colorTextButtonCritical: string;
colorTextButtonCriticalHover: string;
colorTextButtonCriticalActive: string;
colorTextButtonFacebook: string;
colorTextButtonFacebookHover: string;
colorTextButtonFacebookActive: string;
colorTextButtonGoogle: string;
colorTextButtonGoogleHover: string;
colorTextButtonGoogleActive: string;
colorTextButtonWhite: string;
colorTextButtonWhiteHover: string;
colorTextButtonWhiteActive: string;
colorTextButtonPrimaryBordered: string;
colorTextButtonPrimaryBorderedHover: string;
colorTextButtonPrimaryBorderedActive: string;
colorTextButtonSecondaryBordered: string;
colorTextButtonSecondaryBorderedHover: string;
colorTextButtonSecondaryBorderedActive: string;
colorTextButtonInfoBordered: string;
colorTextButtonInfoBorderedHover: string;
colorTextButtonInfoBorderedActive: string;
colorTextButtonSuccessBordered: string;
colorTextButtonSuccessBorderedHover: string;
colorTextButtonSuccessBorderedActive: string;
colorTextButtonWarningBordered: string;
colorTextButtonWarningBorderedHover: string;
colorTextButtonWarningBorderedActive: string;
colorTextButtonCriticalBordered: string;
colorTextButtonCriticalBorderedHover: string;
colorTextButtonCriticalBorderedActive: string;
colorTextButtonFacebookBordered: string;
colorTextButtonFacebookBorderedHover: string;
colorTextButtonFacebookBorderedActive: string;
colorTextButtonGoogleBordered: string;
colorTextButtonGoogleBorderedHover: string;
colorTextButtonGoogleBorderedActive: string;
colorTextButtonWhiteBordered: string;
colorTextButtonWhiteBorderedHover: string;
colorTextButtonWhiteBorderedActive: string;
colorTextButtonLinkPrimary: string;
colorTextButtonLinkPrimaryHover: string;
colorTextButtonLinkPrimaryActive: string;
colorTextButtonLinkSecondary: string;
colorTextButtonLinkSecondaryHover: string;
colorTextButtonLinkSecondaryActive: string;
colorTextInput: string;
colorTextInputPrefix: string;
colorTextInputDisabled: string;
colorTextBadgeNeutral: string;
colorTextBadgeInfo: string;
colorTextBadgeSuccess: string;
colorTextBadgeWarning: string;
colorTextBadgeCritical: string;
colorTextBadgeDark: string;
colorTextBadgeWhite: string;
colorTextLoading: string;
colorTextTable: string;
colorTextTag: string;
colorTextTagSelected: string;
colorIconInput: string;
colorPlaceholderInput: string;
colorPlaceholderInputError: string;
colorPlaceholderInputFile: string;
colorPlaceholderInputFileError: string;
colorFormLabel: string;
colorFormLabelFilled: string;
colorInfoCheckBoxRadio: string;
colorIconCheckboxRadio: string;
colorIconCheckboxRadioDisabled: string;
colorIconRadioButton: string;
colorIconRadioButtonDisabled: string;
colorStopoverArrow: string;
fontFamily: string;
backgroundBody: string;
backgroundModal: string;
backgroundCard: string;
backgroundCarrierLogo: string;
backgroundCountryFlag: string;
backgroundButtonPrimary: string;
backgroundButtonPrimaryHover: string;
backgroundButtonPrimaryActive: string;
backgroundButtonSecondary: string;
backgroundButtonSecondaryHover: string;
backgroundButtonSecondaryActive: string;
backgroundButtonFacebook: string;
backgroundButtonFacebookHover: string;
backgroundButtonFacebookActive: string;
backgroundButtonGoogle: string;
backgroundButtonGoogleHover: string;
backgroundButtonGoogleActive: string;
backgroundButtonInfo: string;
backgroundButtonInfoHover: string;
backgroundButtonInfoActive: string;
backgroundButtonSuccess: string;
backgroundButtonSuccessHover: string;
backgroundButtonSuccessActive: string;
backgroundButtonWarning: string;
backgroundButtonWarningHover: string;
backgroundButtonWarningActive: string;
backgroundButtonCritical: string;
backgroundButtonCriticalHover: string;
backgroundButtonCriticalActive: string;
backgroundButtonWhite: string;
backgroundButtonWhiteHover: string;
backgroundButtonWhiteActive: string;
backgroundButtonBordered: string;
backgroundButtonBorderedHover: string;
backgroundButtonBorderedActive: string;
backgroundButtonWhiteBordered: string;
backgroundButtonWhiteBorderedHover: string;
backgroundButtonWhiteBorderedActive: string;
backgroundButtonLinkPrimary: string;
backgroundButtonLinkPrimaryHover: string;
backgroundButtonLinkPrimaryActive: string;
backgroundButtonLinkSecondary: string;
backgroundButtonLinkSecondaryHover: string;
backgroundButtonLinkSecondaryActive: string;
backgroundInput: string;
backgroundInputDisabled: string;
backgroundAlertSuccess: string;
backgroundAlertInfo: string;
backgroundAlertWarning: string;
backgroundAlertCritical: string;
backgroundBadgeNeutral: string;
backgroundBadgeInfo: string;
backgroundBadgeSuccess: string;
backgroundBadgeWarning: string;
backgroundBadgeCritical: string;
backgroundBadgeDark: string;
backgroundBadgeWhite: string;
backgroundServiceLogo: string;
backgroundIllustration: string;
backgroundSeparator: string;
backgroundTableShadowLeft: string;
backgroundTableShadowRight: string;
backgroundTable: string;
backgroundTableEven: string;
backgroundTableHover: string;
backgroundTag: string;
backgroundTagSelected: string;
backgroundTagHover: string;
backgroundTagSelectedHover: string;
backgroundTagActive: string;
backgroundTagSelectedActive: string;
fontSizeHeadingDisplay: string;
fontSizeHeadingDisplaySubtitle: string;
fontSizeHeadingTitle1: string;
fontSizeHeadingTitle2: string;
fontSizeHeadingTitle3: string;
fontSizeHeadingTitle4: string;
fontSizeHeadingTitle5: string;
fontSizeTextNormal: string;
fontSizeTextLarge: string;
fontSizeTextSmall: string;
fontSizeMessage: string;
fontSizeButtonLarge: string;
fontSizeButtonNormal: string;
fontSizeButtonSmall: string;
fontSizeInputNormal: string;
fontSizeInputSmall: string;
fontSizeFormLabel: string;
fontSizeFormFeedback: string;
borderRadiusCircle: string;
borderRadiusNormal: string;
borderRadiusLarge: string;
borderRadiusSmall: string;
borderRadiusBadge: string;
zIndexDefault: string;
zIndexSticky: string;
zIndexModalOverlay: string;
zIndexModal: string;
zIndexOnTheTop: string;
widthIconSmall: string;
heightIconSmall: string;
widthIconMedium: string;
heightIconMedium: string;
widthIconLarge: string;
heightIconLarge: string;
heightInputNormal: string;
heightInputLarge: string;
heightInputSmall: string;
heightButtonNormal: string;
heightButtonLarge: string;
heightButtonSmall: string;
heightRadioButton: string;
widthRadioButton: string;
heightCheckbox: string;
widthCheckbox: string;
heightCountryFlag: string;
widthCountryFlag: string;
heightBadge: string;
widthBadgeCircled: string;
heightIllustrationSmall: string;
heightIllustrationMedium: string;
heightServiceLogoSmall: string;
heightServiceLogoMedium: string;
heightServiceLogoLarge: string;
heightSeparator: string;
heightInputGroupSeparatorSmall: string;
heightInputGroupSeparatorNormal: string;
widthModalSmall: string;
widthModalNormal: string;
widthModalLarge: string;
widthStopoverArrow: string;
heightStopoverArrow: string;
widthBreakpointMediumMobile: number;
widthBreakpointLargeMobile: number;
widthBreakpointTablet: number;
widthBreakpointDesktop: number;
widthBreakpointLargeDesktop: number;
borderColorInput: string;
borderColorInputHover: string;
borderColorInputActive: string;
borderColorInputFocus: string;
borderColorInputError: string;
borderColorInputErrorHover: string;
borderColorInputErrorFocus: string;
borderColorTableCell: string;
borderColorCard: string;
borderColorModal: string;
borderColorButtonPrimaryBordered: string;
borderColorButtonPrimaryBorderedHover: string;
borderColorButtonPrimaryBorderedActive: string;
borderColorButtonSecondaryBordered: string;
borderColorButtonSecondaryBorderedHover: string;
borderColorButtonSecondaryBorderedActive: string;
borderColorButtonFacebookBordered: string;
borderColorButtonFacebookBorderedHover: string;
borderColorButtonFacebookBorderedActive: string;
borderColorButtonGoogleBordered: string;
borderColorButtonGoogleBorderedHover: string;
borderColorButtonGoogleBorderedActive: string;
borderColorButtonInfoBordered: string;
borderColorButtonInfoBorderedHover: string;
borderColorButtonInfoBorderedActive: string;
borderColorButtonSuccessBordered: string;
borderColorButtonSuccessBorderedHover: string;
borderColorButtonSuccessBorderedActive: string;
borderColorButtonWarningBordered: string;
borderColorButtonWarningBorderedHover: string;
borderColorButtonWarningBorderedActive: string;
borderColorButtonCriticalBordered: string;
borderColorButtonCriticalBorderedHover: string;
borderColorButtonCriticalBorderedActive: string;
borderColorButtonWhiteBordered: string;
borderColorButtonWhiteBorderedHover: string;
borderColorButtonWhiteBorderedActive: string;
borderColorCheckboxRadio: string;
borderColorCheckboxRadioError: string;
borderColorCheckboxRadioHover: string;
borderColorCheckboxRadioActive: string;
borderColorCheckboxRadioFocus: string;
borderColorTable: string;
borderColorTableHead: string;
borderColorTag: string;
borderColorTagFocus: string;
borderStyleCard: string;
borderWidthCard: string;
borderStyleInput: string;
borderWidthInput: string;
borderWidthInputFocus: string;
opacityOverlay: string;
opacityButtonDisabled: string;
opacityRadioButtonDisabled: string;
opacityCheckboxDisabled: string;
fontWeightNormal: string;
fontWeightMedium: string;
fontWeightBold: string;
fontWeightLinks: string;
fontWeightHeadingDisplay: string;
fontWeightHeadingDisplaySubtitle: string;
fontWeightHeadingTitle1: string;
fontWeightHeadingTitle2: string;
fontWeightHeadingTitle3: string;
fontWeightHeadingTitle4: string;
fontWeightHeadingTitle5: string;
fontWeightTableHead: string;
paddingAlert: string;
paddingAlertWithIcon: string;
paddingBadge: string;
paddingButtonWithoutText: string;
paddingButtonSmall: string;
paddingButtonNormal: string;
paddingButtonLarge: string;
paddingButtonSmallWithIcons: string;
paddingButtonNormalWithIcons: string;
paddingButtonLargeWithIcons: string;
paddingButtonSmallWithLeftIcon: string;
paddingButtonNormalWithLeftIcon: string;
paddingButtonLargeWithLeftIcon: string;
paddingButtonSmallWithRightIcon: string;
paddingButtonNormalWithRightIcon: string;
paddingButtonLargeWithRightIcon: string;
paddingTextareaSmall: string;
paddingTextareaNormal: string;
paddingInputSmall: string;
paddingInputNormal: string;
marginButtonIconSmall: string;
marginButtonIconNormal: string;
marginButtonIconLarge: string;
marginButtonGroupConnected: string;
marginButtonGroup: string;
marginTopFormFeedback: string;
marginBottomSelectSuffix: string;
paddingInputFile: string;
paddingLeftSelectPrefix: string;
paddingLoading: string;
paddingTable: string;
paddingTableCompact: string;
paddingTag: string;
paddingTagWithIcon: string;
paddingTagRemovable: string;
paddingTagRemovableWithIcon: string;
marginBadgeIcon: string;
spaceXXXSmall: string;
spaceXXSmall: string;
spaceXSmall: string;
spaceSmall: string;
spaceMedium: string;
spaceLarge: string;
spaceXLarge: string;
spaceXXLarge: string;
spaceXXXLarge: string;
durationFast: string;
durationNormal: string;
durationSlow: string;
modifierScaleButtonActive: number;
modifierScaleCheckboxRadioActive: number;
lineHeightText: string;
lineHeightHeading: string;
lineHeightHeadingDisplay: string;
lineHeightHeadingDisplaySubtitle: string;
lineHeightHeadingTitle1: string;
lineHeightHeadingTitle2: string;
lineHeightHeadingTitle3: string;
lineHeightHeadingTitle4: string;
lineHeightHeadingTitle5: string;
textDecorationTextLinkPrimary: string;
textDecorationTextLinkPrimaryHover: string;
textDecorationTextLinkSecondary: string;
textDecorationTextLinkSecondaryHover: string;
boxShadowButtonFocus: string;
boxShadowActionable: string;
boxShadowElevatedLevel1: string;
boxShadowModal: string;
paletteProductLight: string;
paletteProductLightHover: string;
paletteProductLightActive: string;
paletteProductNormal: string;
paletteProductNormalHover: string;
paletteProductNormalActive: string;
paletteProductDark: string;
paletteProductDarkHover: string;
paletteProductDarkActive: string;
paletteProductDarker: string;
paletteWhite: string;
paletteWhiteHover: string;
paletteWhiteActive: string;
paletteCloudLight: string;
paletteCloudLightHover: string;
paletteCloudLightActive: string;
paletteCloudNormal: string;
paletteCloudNormalHover: string;
paletteCloudNormalActive: string;
paletteCloudDark: string;
paletteInkLighter: string;
paletteInkLighterHover: string;
paletteInkLighterActive: string;
paletteInkLight: string;
paletteInkLightHover: string;
paletteInkLightActive: string;
paletteInkNormal: string;
paletteInkNormalHover: string;
paletteInkNormalActive: string;
paletteOrangeLight: string;
paletteOrangeLightHover: string;
paletteOrangeLightActive: string;
paletteOrangeNormal: string;
paletteOrangeNormalHover: string;
paletteOrangeNormalActive: string;
paletteOrangeDark: string;
paletteOrangeDarkHover: string;
paletteOrangeDarkActive: string;
paletteOrangeDarker: string;
paletteRedLight: string;
paletteRedLightHover: string;
paletteRedLightActive: string;
paletteRedNormal: string;
paletteRedNormalHover: string;
paletteRedNormalActive: string;
paletteRedDark: string;
paletteRedDarkHover: string;
paletteRedDarkActive: string;
paletteRedDarker: string;
paletteGreenLight: string;
paletteGreenLightHover: string;
paletteGreenLightActive: string;
paletteGreenNormal: string;
paletteGreenNormalHover: string;
paletteGreenNormalActive: string;
paletteGreenDark: string;
paletteGreenDarkHover: string;
paletteGreenDarkActive: string;
paletteGreenDarker: string;
paletteBlueLight: string;
paletteBlueLightHover: string;
paletteBlueLightActive: string;
paletteBlueNormal: string;
paletteBlueNormalHover: string;
paletteBlueNormalActive: string;
paletteBlueDark: string;
paletteBlueDarkHover: string;
paletteBlueDarkActive: string;
paletteBlueDarker: string;
paletteSocialFacebook: string;
paletteSocialFacebookHover: string;
paletteSocialFacebookActive: string;
}
export interface ThemePaletteColors {
productLight: string;
productLightHover: string;
productLightActive: string;
productNormal: string;
productNormalHover: string;
productNormalActive: string;
productDark: string;
productDarkHover?: string | undefined;
productDarkActive?: string | undefined;
productDarker?: string | undefined;
}
export function fromPlainObject(themePaletteColors: ThemePaletteColors): Tokens;
export function getTokens(customFoundation?: CustomFoundation): Tokens; | the_stack |
import { RoundedRectangle } from "../render/RoundedRectangle";
import { Container, IContainerPrivate, IContainerSettings, IContainerEvents } from "./Container";
import * as $type from "../util/Type";
import { Graphics } from "./Graphics";
import { Button } from "./Button";
import type { Time } from "../util/Animation";
import * as $utils from "../util/Utils";
import type { Animation } from "../util/Entity";
export interface IScrollbarSettings extends IContainerSettings {
/**
* Orientation of the scrollbar.
*/
orientation: "horizontal" | "vertical";
/**
* Relative start of the selected range, with 0 meaning beginning, and 1 the
* end.
*/
start?: number;
/**
* Relative end of the selected range, with 0 meaning beginning, and 1 the
* end.
*/
end?: number;
/**
* Number of milliseconds to play scroll animations for.
*/
animationDuration?: number;
/**
* Easing function to use for animations.
*
* @see {@link https://www.amcharts.com/docs/v5/concepts/animations/#Easing_functions} for more info
*/
animationEasing?: (t: Time) => Time;
}
export interface IScrollbarPrivate extends IContainerPrivate {
/**
* @ignore
*/
isBusy?: boolean;
/**
* @ignore
*/
positionTextFunction?: (position: number) => string;
}
export interface IScrollbarEvents extends IContainerEvents {
/**
* Invoked when range of the selection changes.
*/
rangechanged: { start: number, end: number };
}
/**
* A control that allows zooming chart's axes, or other uses requiring range
* selection.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/scrollbars/} for more info
*/
export class Scrollbar extends Container {
public _addOrientationClass() {
this._settings.themeTags = $utils.mergeTags(this._settings.themeTags, ["scrollbar", this._settings.orientation]);
if (!this._settings.background) {
this._settings.background = RoundedRectangle.new(this._root, {
themeTags: $utils.mergeTags(this._settings.themeTags, ["main", "background"])
});
}
}
declare public _settings: IScrollbarSettings;
declare public _privateSettings: IScrollbarPrivate;
declare public _events: IScrollbarEvents;
public static className: string = "Scrollbar";
public static classNames: Array<string> = Container.classNames.concat([Scrollbar.className]);
/**
* A thumb elment - a draggable square between the grips, used for panning
* the selection.
*/
public thumb: RoundedRectangle = this._makeThumb();
/**
* Start grip button.
*/
public startGrip: Button = this._makeButton();
/**
* End grip button.
*/
public endGrip: Button = this._makeButton();
protected _thumbBusy: boolean = false;
protected _startDown: boolean = false;
protected _endDown: boolean = false;
protected _thumbDown: boolean = false;
protected _makeButton(): Button {
return this.children.push(Button.new(this._root, {
themeTags: ["resize", "button", this.get("orientation")], icon: Graphics.new(this._root, {
themeTags: ["icon"]
})
}));
}
protected _makeThumb(): RoundedRectangle {
return this.children.push(RoundedRectangle.new(this._root, {
themeTags: ["thumb", this.get("orientation")]
}));
}
protected _handleAnimation(animation: Animation<any>) {
if (animation) {
this._disposers.push(
animation.events.on("stopped", () => {
this.setPrivateRaw("isBusy", false);
this._thumbBusy = false;
})
)
}
}
protected _afterNew() {
this._addOrientationClass();
super._afterNew();
const startGrip = this.startGrip;
const endGrip = this.endGrip;
const thumb = this.thumb;
const background = this.get("background");
if (background) {
this._disposers.push(
background.events.on("click", (event) => {
this.setPrivateRaw("isBusy", true);
const point = this._display.toLocal(event.point);
const w = this.width();
const h = this.height();
const orientation = this.get("orientation");
let newMiddle: number;
if (orientation == "vertical") {
newMiddle = (point.y - thumb.height() / 2) / h;
}
else {
newMiddle = (point.x - thumb.width() / 2) / w;
}
let newCoordinate: number;
let key: "x" | "y";
if (orientation == "vertical") {
newCoordinate = newMiddle * h;
key = "y";
}
else {
newCoordinate = newMiddle * w;
key = "x";
}
const duration = this.get("animationDuration", 0);
if (duration > 0) {
this._thumbBusy = true;
this._handleAnimation(this.thumb.animate({ key: key, to: newCoordinate, duration: duration, easing: this.get("animationEasing") }));
}
else {
this.thumb.set(key, newCoordinate);
}
})
)
}
this._disposers.push(thumb.events.on("dblclick", () => {
const duration = this.get("animationDuration", 0);
const easing = this.get("animationEasing");
this.animate({ key: "start", to: 0, duration: duration, easing: easing });
this.animate({ key: "end", to: 1, duration: duration, easing: easing });
}));
this._disposers.push(startGrip.events.on("pointerdown", () => {
this.setPrivateRaw("isBusy", true);
this._startDown = true;
}))
this._disposers.push(endGrip.events.on("pointerdown", () => {
this.setPrivateRaw("isBusy", true);
this._endDown = true;
}))
this._disposers.push(thumb.events.on("pointerdown", () => {
this.setPrivateRaw("isBusy", true);
this._thumbDown = true;
}))
this._disposers.push(startGrip.events.on("globalpointerup", () => {
if (this._startDown) {
this.setPrivateRaw("isBusy", false);
}
this._startDown = false;
}))
this._disposers.push(endGrip.events.on("globalpointerup", () => {
if (this._endDown) {
this.setPrivateRaw("isBusy", false);
}
this._endDown = false;
}))
this._disposers.push(thumb.events.on("globalpointerup", () => {
if (this._thumbDown) {
this.setPrivateRaw("isBusy", false);
}
this._thumbDown = false;
}))
this._disposers.push(startGrip.on("x", () => {
this._updateThumb();
}));
this._disposers.push(endGrip.on("x", () => {
this._updateThumb();
}));
this._disposers.push(startGrip.on("y", () => {
this._updateThumb();
}));
this._disposers.push(endGrip.on("y", () => {
this._updateThumb();
}));
this._disposers.push(thumb.events.on("positionchanged", () => {
this._updateGripsByThumb();
}));
if (this.get("orientation") == "vertical") {
startGrip.set("x", 0);
endGrip.set("x", 0);
this._disposers.push(thumb.adapters.add("y", (value) => {
return Math.max(Math.min(Number(value), this.height() - thumb.height()), 0);
}))
this._disposers.push(thumb.adapters.add("x", (_value) => {
return this.width() / 2;
}))
this._disposers.push(startGrip.adapters.add("x", (_value) => {
return this.width() / 2;
}))
this._disposers.push(endGrip.adapters.add("x", (_value) => {
return this.width() / 2;
}))
this._disposers.push(startGrip.adapters.add("y", (value) => {
return Math.max(Math.min(Number(value), this.height()), 0);
}))
this._disposers.push(endGrip.adapters.add("y", (value) => {
return Math.max(Math.min(Number(value), this.height()), 0);
}))
}
else {
startGrip.set("y", 0);
endGrip.set("y", 0);
this._disposers.push(thumb.adapters.add("x", (value) => {
return Math.max(Math.min(Number(value), this.width() - thumb.width()), 0);
}))
this._disposers.push(thumb.adapters.add("y", (_value) => {
return this.height() / 2;
}))
this._disposers.push(startGrip.adapters.add("y", (_value) => {
return this.height() / 2;
}))
this._disposers.push(endGrip.adapters.add("y", (_value) => {
return this.height() / 2;
}))
this._disposers.push(startGrip.adapters.add("x", (value) => {
return Math.max(Math.min(Number(value), this.width()), 0);
}))
this._disposers.push(endGrip.adapters.add("x", (value) => {
return Math.max(Math.min(Number(value), this.width()), 0);
}))
}
}
public _updateChildren() {
super._updateChildren();
if (this.isDirty("end") || this.isDirty("start") || this._sizeDirty) {
this.updateGrips();
}
}
public _changed() {
super._changed();
if (this.isDirty("start") || this.isDirty("end")) {
const eventType = "rangechanged";
if (this.events.isEnabled(eventType)) {
this.events.dispatch(eventType, { type: eventType, target: this, start: this.get("start", 0), end: this.get("end", 1) });
}
}
}
/**
* @ignore
*/
public updateGrips() {
const startGrip = this.startGrip;
const endGrip = this.endGrip;
const orientation = this.get("orientation");
const height = this.height();
const width = this.width();
if (orientation == "vertical") {
startGrip.set("y", height * this.get("start", 0));
endGrip.set("y", height * this.get("end", 1));
}
else {
startGrip.set("x", width * this.get("start", 0));
endGrip.set("x", width * this.get("end", 1));
}
const valueFunction = this.getPrivate("positionTextFunction");
const from = Math.round(this.get("start", 0) * 100);
const to = Math.round(this.get("end", 0) * 100);
let fromValue: string;
let toValue: string;
if (valueFunction) {
fromValue = valueFunction.call(this, this.get("start", 0));
toValue = valueFunction.call(this, this.get("end", 0));
}
else {
fromValue = from + "%";
toValue = to + "%";
}
startGrip.set("ariaLabel", this._t("From %1", undefined, fromValue));
startGrip.set("ariaValueNow", "" + from);
startGrip.set("ariaValueText", from + "%");
startGrip.set("ariaValueMin", "0");
startGrip.set("ariaValueMax", "100");
endGrip.set("ariaLabel", this._t("To %1", undefined, toValue));
endGrip.set("ariaValueNow", "" + to);
endGrip.set("ariaValueText", to + "%");
endGrip.set("ariaValueMin", "0");
endGrip.set("ariaValueMax", "100");
}
protected _updateThumb() {
const thumb = this.thumb;
const startGrip = this.startGrip;
const endGrip = this.endGrip;
const height = this.height();
const width = this.width();
let x0 = startGrip.x();
let x1 = endGrip.x();
let y0 = startGrip.y();
let y1 = endGrip.y();
let start: number = 0;
let end: number = 1;
if (this.get("orientation") == "vertical") {
if ($type.isNumber(y0) && $type.isNumber(y1)) {
if (!this._thumbBusy && !thumb.isDragging()) {
thumb.set("height", y1 - y0);
thumb.set("y", y0);
}
start = y0 / height;
end = y1 / height;
}
}
else {
if ($type.isNumber(x0) && $type.isNumber(x1)) {
if (!this._thumbBusy && !thumb.isDragging()) {
thumb.set("width", x1 - x0);
thumb.set("x", x0);
}
start = x0 / width;
end = x1 / width;
}
}
if (this.getPrivate("isBusy") && (this.get("start") != start || this.get("end") != end)) {
this.set("start", start);
this.set("end", end);
}
const valueFunction = this.getPrivate("positionTextFunction");
const from = Math.round(this.get("start", 0) * 100);
const to = Math.round(this.get("end", 0) * 100);
let fromValue: string;
let toValue: string;
if (valueFunction) {
fromValue = valueFunction.call(this, this.get("start", 0));
toValue = valueFunction.call(this, this.get("end", 0));
}
else {
fromValue = from + "%";
toValue = to + "%";
}
thumb.set("ariaLabel", this._t("From %1 to %2", undefined, fromValue, toValue));
thumb.set("ariaValueNow", "" + from);
thumb.set("ariaValueText", from + "%");
}
protected _updateGripsByThumb() {
const thumb = this.thumb;
const startGrip = this.startGrip;
const endGrip = this.endGrip;
if (this.get("orientation") == "vertical") {
const thumbSize = thumb.height();
startGrip.set("y", thumb.y());
endGrip.set("y", thumb.y() + thumbSize);
}
else {
const thumbSize = thumb.width();
startGrip.set("x", thumb.x());
endGrip.set("x", thumb.x() + thumbSize);
}
}
} | the_stack |
'use strict';
import * as DebuggerExtension from './Debugger/extension';
import * as LanguageServer from './LanguageServer/extension';
import * as os from 'os';
import * as path from 'path';
import * as Telemetry from './telemetry';
import * as util from './common';
import * as vscode from 'vscode';
import { CppToolsApi, CppToolsExtension } from 'vscode-cpptools';
import { PlatformInformation } from './platform';
import { CppTools1 } from './cppTools1';
import { CppSettings } from './LanguageServer/settings';
import { PersistentState } from './LanguageServer/persistentState';
import { TargetPopulation } from 'vscode-tas-client';
import * as semver from 'semver';
import * as nls from 'vscode-nls';
import { cppBuildTaskProvider, CppBuildTaskProvider } from './LanguageServer/cppBuildTaskProvider';
nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })();
const localize: nls.LocalizeFunc = nls.loadMessageBundle();
const cppTools: CppTools1 = new CppTools1();
let languageServiceDisabled: boolean = false;
let reloadMessageShown: boolean = false;
const disposables: vscode.Disposable[] = [];
export async function activate(context: vscode.ExtensionContext): Promise<CppToolsApi & CppToolsExtension> {
util.setExtensionContext(context);
Telemetry.activate();
util.setProgress(0);
// Register a protocol handler to serve localized versions of the schema for c_cpp_properties.json
class SchemaProvider implements vscode.TextDocumentContentProvider {
public async provideTextDocumentContent(uri: vscode.Uri): Promise<string> {
console.assert(uri.path[0] === '/', "A preceeding slash is expected on schema uri path");
const fileName: string = uri.path.substring(1);
const locale: string = util.getLocaleId();
let localizedFilePath: string = util.getExtensionFilePath(path.join("dist/schema/", locale, fileName));
const fileExists: boolean = await util.checkFileExists(localizedFilePath);
if (!fileExists) {
localizedFilePath = util.getExtensionFilePath(fileName);
}
return util.readFileText(localizedFilePath);
}
}
vscode.workspace.registerTextDocumentContentProvider('cpptools-schema', new SchemaProvider());
// Initialize the DebuggerExtension and register the related commands and providers.
DebuggerExtension.initialize(context);
const info: PlatformInformation = await PlatformInformation.GetPlatformInformation();
sendTelemetry(info);
// Always attempt to make the binaries executable, not just when installedVersion changes.
// The user may have uninstalled and reinstalled the same version.
await makeBinariesExecutable();
// Notify users if debugging may not be supported on their OS.
util.checkDistro(info);
await checkVsixCompatibility();
UpdateInsidersAccess();
const settings: CppSettings = new CppSettings((vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 0) ? vscode.workspace.workspaceFolders[0]?.uri : undefined);
let isOldMacOs: boolean = false;
if (info.platform === 'darwin') {
const releaseParts: string[] = os.release().split(".");
if (releaseParts.length >= 1) {
isOldMacOs = parseInt(releaseParts[0]) < 16;
}
}
// Read the setting and determine whether we should activate the language server prior to installing callbacks,
// to ensure there is no potential race condition. LanguageServer.activate() is called near the end of this
// function, to allow any further setup to occur here, prior to activation.
const shouldActivateLanguageServer: boolean = (settings.intelliSenseEngine !== "Disabled" && !isOldMacOs);
if (isOldMacOs) {
languageServiceDisabled = true;
vscode.window.showErrorMessage(localize("macos.version.deprecated", "Versions of the C/C++ extension more recent than {0} require at least macOS version {1}.", "1.9.8", "10.12"));
} else {
if (settings.intelliSenseEngine === "Disabled") {
languageServiceDisabled = true;
}
let currentIntelliSenseEngineValue: string | undefined = settings.intelliSenseEngine;
disposables.push(vscode.workspace.onDidChangeConfiguration(() => {
const settings: CppSettings = new CppSettings((vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 0) ? vscode.workspace.workspaceFolders[0]?.uri : undefined);
if (!reloadMessageShown && settings.intelliSenseEngine !== currentIntelliSenseEngineValue) {
if (currentIntelliSenseEngineValue === "Disabled") {
// If switching from disabled to enabled, we can continue activation.
currentIntelliSenseEngineValue = settings.intelliSenseEngine;
languageServiceDisabled = false;
LanguageServer.activate();
} else {
// We can't deactivate or change engines on the fly, so prompt for window reload.
reloadMessageShown = true;
util.promptForReloadWindowDueToSettingsChange();
}
}
}));
}
if (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 0) {
for (let i: number = 0; i < vscode.workspace.workspaceFolders.length; ++i) {
const config: string = path.join(vscode.workspace.workspaceFolders[i].uri.fsPath, ".vscode/c_cpp_properties.json");
if (await util.checkFileExists(config)) {
const doc: vscode.TextDocument = await vscode.workspace.openTextDocument(config);
vscode.languages.setTextDocumentLanguage(doc, "jsonc");
}
}
}
disposables.push(vscode.tasks.registerTaskProvider(CppBuildTaskProvider.CppBuildScriptType, cppBuildTaskProvider));
vscode.tasks.onDidStartTask(event => {
if (event.execution.task.definition.type === CppBuildTaskProvider.CppBuildScriptType
|| event.execution.task.name.startsWith(LanguageServer.configPrefix)) {
Telemetry.logLanguageServerEvent('buildTaskStarted');
}
});
vscode.tasks.onDidEndTask(event => {
if (event.execution.task.definition.type === CppBuildTaskProvider.CppBuildScriptType
|| event.execution.task.name.startsWith(LanguageServer.configPrefix)) {
Telemetry.logLanguageServerEvent('buildTaskFinished');
}
});
if (shouldActivateLanguageServer) {
await LanguageServer.activate();
}
return cppTools;
}
export function deactivate(): Thenable<void> {
DebuggerExtension.dispose();
Telemetry.deactivate();
disposables.forEach(d => d.dispose());
if (languageServiceDisabled) {
return Promise.resolve();
}
return LanguageServer.deactivate();
}
async function makeBinariesExecutable(): Promise<void> {
const promises: Thenable<void>[] = [];
if (process.platform !== 'win32') {
const commonBinaries: string[] = [
"./bin/cpptools",
"./bin/cpptools-srv",
"./bin/cpptools-wordexp",
"./LLVM/bin/clang-format",
"./LLVM/bin/clang-tidy",
"./debugAdapters/bin/OpenDebugAD7"
];
commonBinaries.forEach(binary => promises.push(util.allowExecution(util.getExtensionFilePath(binary))));
if (process.platform === "darwin") {
const macBinaries: string[] = [
"./debugAdapters/lldb-mi/bin/lldb-mi"
];
macBinaries.forEach(binary => promises.push(util.allowExecution(util.getExtensionFilePath(binary))));
if (os.arch() === "x64") {
const oldMacBinaries: string[] = [
"./debugAdapters/lldb/bin/debugserver",
"./debugAdapters/lldb/bin/lldb-mi",
"./debugAdapters/lldb/bin/lldb-argdumper",
"./debugAdapters/lldb/bin/lldb-launcher"
];
oldMacBinaries.forEach(binary => promises.push(util.allowExecution(util.getExtensionFilePath(binary))));
}
}
}
await Promise.all(promises);
}
function sendTelemetry(info: PlatformInformation): void {
const telemetryProperties: { [key: string]: string } = {};
if (info.distribution) {
telemetryProperties['linuxDistroName'] = info.distribution.name;
telemetryProperties['linuxDistroVersion'] = info.distribution.version;
}
telemetryProperties['osArchitecture'] = os.arch();
telemetryProperties['infoArchitecture'] = info.architecture;
const targetPopulation: TargetPopulation = util.getCppToolsTargetPopulation();
switch (targetPopulation) {
case TargetPopulation.Public:
telemetryProperties['targetPopulation'] = "Public";
break;
case TargetPopulation.Internal:
telemetryProperties['targetPopulation'] = "Internal";
break;
case TargetPopulation.Insiders:
telemetryProperties['targetPopulation'] = "Insiders";
break;
default:
break;
}
Telemetry.logDebuggerEvent("acquisition", telemetryProperties);
}
export function UpdateInsidersAccess(): void {
let installPrerelease: boolean = false;
// Only move them to the new prerelease mechanism if using updateChannel of Insiders.
const settings: CppSettings = new CppSettings();
const migratedInsiders: PersistentState<boolean> = new PersistentState<boolean>("CPP.migratedInsiders", false);
if (settings.updateChannel === "Insiders") {
// Don't do anything while the user has autoUpdate disabled, so we do not cause the extension to be updated.
if (!migratedInsiders.Value && vscode.workspace.getConfiguration("extensions", null).get<boolean>("autoUpdate")) {
installPrerelease = true;
migratedInsiders.Value = true;
}
} else {
// Reset persistent value, so we register again if they switch to "Insiders" again.
if (migratedInsiders.Value) {
migratedInsiders.Value = false;
}
}
// Mitigate an issue with VS Code not recognizing a programmatically installed VSIX as Prerelease.
// If using VS Code Insiders, and updateChannel is not explicitly set, default to Prerelease.
// Only do this once. If the user manually switches to Release, we don't want to switch them back to Prerelease again.
if (util.isVsCodeInsiders()) {
const insidersMitigationDone: PersistentState<boolean> = new PersistentState<boolean>("CPP.insidersMitigationDone", false);
if (!insidersMitigationDone.Value) {
if (vscode.workspace.getConfiguration("extensions", null).get<boolean>("autoUpdate")) {
if (settings.getWithUndefinedDefault<string>("updateChannel") === undefined) {
installPrerelease = true;
}
}
insidersMitigationDone.Value = true;
}
}
if (installPrerelease) {
vscode.commands.executeCommand("workbench.extensions.installExtension", "ms-vscode.cpptools", { installPreReleaseVersion: true });
}
}
async function checkVsixCompatibility(): Promise<void> {
const ignoreMismatchedCompatibleVsix: PersistentState<boolean> = new PersistentState<boolean>("CPP." + util.packageJson.version + ".ignoreMismatchedCompatibleVsix", false);
let resetIgnoreMismatchedCompatibleVsix: boolean = true;
// Check to ensure the correct platform-specific VSIX was installed.
const vsixManifestPath: string = path.join(util.extensionPath, ".vsixmanifest");
// Skip the check if the file does not exist, such as when debugging cpptools.
if (await util.checkFileExists(vsixManifestPath)) {
const content: string = await util.readFileText(vsixManifestPath);
const matches: RegExpMatchArray | null = content.match(/TargetPlatform="(?<platform>[^"]*)"/);
if (matches && matches.length > 0 && matches.groups) {
const vsixTargetPlatform: string = matches.groups['platform'];
const platformInfo: PlatformInformation = await PlatformInformation.GetPlatformInformation();
let isPlatformCompatible: boolean = true;
let isPlatformMatching: boolean = true;
switch (vsixTargetPlatform) {
case "win32-x64":
isPlatformMatching = platformInfo.platform === "win32" && platformInfo.architecture === "x64";
// x64 binaries can also be run on arm64 Windows 11.
isPlatformCompatible = platformInfo.platform === "win32" && (platformInfo.architecture === "x64" || (platformInfo.architecture === "arm64" && semver.gte(os.release(), "10.0.22000")));
break;
case "win32-ia32":
isPlatformMatching = platformInfo.platform === "win32" && platformInfo.architecture === "x86";
// x86 binaries can also be run on x64 and arm64 Windows.
isPlatformCompatible = platformInfo.platform === "win32" && (platformInfo.architecture === "x86" || platformInfo.architecture === "x64" || platformInfo.architecture === "arm64");
break;
case "win32-arm64":
isPlatformMatching = platformInfo.platform === "win32" && platformInfo.architecture === "arm64";
isPlatformCompatible = isPlatformMatching;
break;
case "linux-x64":
isPlatformMatching = platformInfo.platform === "linux" && platformInfo.architecture === "x64" && platformInfo.distribution?.name !== "alpine";
isPlatformCompatible = isPlatformMatching;
break;
case "linux-arm64":
isPlatformMatching = platformInfo.platform === "linux" && platformInfo.architecture === "arm64" && platformInfo.distribution?.name !== "alpine";
isPlatformCompatible = isPlatformMatching;
break;
case "linux-armhf":
isPlatformMatching = platformInfo.platform === "linux" && platformInfo.architecture === "arm" && platformInfo.distribution?.name !== "alpine";
// armhf binaries can also be run on aarch64 linux.
isPlatformCompatible = platformInfo.platform === "linux" && (platformInfo.architecture === "arm" || platformInfo.architecture === "arm64") && platformInfo.distribution?.name !== "alpine";
break;
case "alpine-x64":
isPlatformMatching = platformInfo.platform === "linux" && platformInfo.architecture === "x64" && platformInfo.distribution?.name === "alpine";
isPlatformCompatible = isPlatformMatching;
break;
case "alpine-arm64":
isPlatformMatching = platformInfo.platform === "linux" && platformInfo.architecture === "arm64" && platformInfo.distribution?.name === "alpine";
isPlatformCompatible = isPlatformMatching;
break;
case "darwin-x64":
isPlatformMatching = platformInfo.platform === "darwin" && platformInfo.architecture === "x64";
isPlatformCompatible = isPlatformMatching;
break;
case "darwin-arm64":
isPlatformMatching = platformInfo.platform === "darwin" && platformInfo.architecture === "arm64";
// x64 binaries can also be run on arm64 macOS.
isPlatformCompatible = platformInfo.platform === "darwin" && (platformInfo.architecture === "x64" || platformInfo.architecture === "arm64");
break;
default:
console.log("Unrecognized TargetPlatform in .vsixmanifest");
break;
}
const moreInfoButton: string = localize("more.info.button", "More Info");
const ignoreButton: string = localize("ignore.button", "Ignore");
let promise: Thenable<string | undefined> | undefined;
if (!isPlatformCompatible) {
promise = vscode.window.showErrorMessage(localize("vsix.platform.incompatible", "The C/C++ extension installed does not match your system.", vsixTargetPlatform), moreInfoButton);
} else if (!isPlatformMatching) {
if (!ignoreMismatchedCompatibleVsix.Value) {
resetIgnoreMismatchedCompatibleVsix = false;
promise = vscode.window.showWarningMessage(localize("vsix.platform.mismatching", "The C/C++ extension installed is compatible with but does not match your system.", vsixTargetPlatform), moreInfoButton, ignoreButton);
}
}
if (promise) {
promise.then(async (value) => {
if (value === moreInfoButton) {
await vscode.commands.executeCommand("markdown.showPreview", vscode.Uri.file(util.getLocalizedHtmlPath("Reinstalling the Extension.md")));
} else if (value === ignoreButton) {
ignoreMismatchedCompatibleVsix.Value = true;
}
});
}
} else {
console.log("Unable to find TargetPlatform in .vsixmanifest");
}
}
if (resetIgnoreMismatchedCompatibleVsix) {
ignoreMismatchedCompatibleVsix.Value = false;
}
} | the_stack |
import * as assert from "assert";
import * as FS from "fs";
import * as Path from "path";
import * as Commander from "commander";
import chalk from "chalk";
import { enqueueSMTTestEvaluate, enqueueSMTTestRefute, enqueueSMTTestWitness } from "./smt_runner";
import { runCompilerTest } from "./compile_runner";
import { enqueueICPPTest } from "./icpp_runner";
const testroot = Path.normalize(Path.join(__dirname, "tests"));
abstract class IndividualTestInfo {
readonly name: string;
readonly fullname: string;
readonly code: string;
readonly extraSrc: string | undefined;
constructor(name: string, fullname: string, code: string, extraSrc: string | undefined) {
this.name = name;
this.fullname = fullname;
this.code = code;
this.extraSrc = extraSrc;
}
generateTestPlan(restriction: string, tests: IndividualTestInfo[]) {
if(restriction === "compile") {
if(this instanceof IndividualCompileWarnTest) {
tests.push(this);
}
}
else if(restriction === "check") {
if((this instanceof IndividualInfeasibleTestInfo) || (this instanceof IndividualWitnessTestInfo)) {
tests.push(this);
}
}
else if(restriction === "evaluate") {
if((this instanceof IndividualEvaluateTestInfo)) {
tests.push(this);
}
}
else if(restriction === "smt") {
if((this instanceof IndividualInfeasibleTestInfo) || (this instanceof IndividualWitnessTestInfo) || (this instanceof IndividualEvaluateTestInfo)) {
tests.push(this);
}
}
else if(restriction === "execute") {
if(this instanceof IndividualICPPTestInfo) {
tests.push(this);
}
}
else {
if(restriction === "*" || this.fullname.startsWith(restriction)) {
tests.push(this);
}
}
}
}
class IndividualCompileWarnTest extends IndividualTestInfo {
private static ctemplate =
"namespace NSMain;\n\
\n\
%%SIG%% {\n\
return %%ACTION%%;\n\
}\n\
\n\
%%CODE%%\n\
";
constructor(name: string, fullname: string, code: string, extraSrc: string | undefined) {
super(name, fullname, code, extraSrc);
}
static create(name: string, fullname: string, sig: string, action: string, code: string, extraSrc: string | undefined): IndividualCompileWarnTest {
const rcode = IndividualCompileWarnTest.ctemplate
.replace("%%SIG%%", sig)
.replace("%%ACTION%%", action)
.replace("%%CODE%%", code);
return new IndividualCompileWarnTest(name, fullname, rcode, extraSrc);
}
}
class IndividualInfeasibleTestInfo extends IndividualTestInfo {
readonly line: number;
private static ctemplate =
"namespace NSMain;\n\
\n\
%%SIG%% {\n\
let res = %%ACTION%%;\n\
assert %%CHECK%%;\n\
return res;\n\
}\n\
\n\
%%CODE%%\n\
";
constructor(name: string, fullname: string, code: string, line: number, extraSrc: string | undefined) {
super(name, fullname, code, extraSrc);
this.line = line;
}
static create(name: string, fullname: string, sig: string, action: string, check: string, code: string, extraSrc: string | undefined): IndividualInfeasibleTestInfo {
const rcode = IndividualInfeasibleTestInfo.ctemplate
.replace("%%SIG%%", sig)
.replace("%%ACTION%%", action)
.replace("%%CHECK%%", check)
.replace("%%CODE%%", code);
return new IndividualInfeasibleTestInfo(name, fullname, rcode, 5, extraSrc);
}
}
class IndividualWitnessTestInfo extends IndividualTestInfo {
readonly line: number;
readonly dosmall: boolean;
private static ctemplate =
"namespace NSMain;\n\
\n\
%%SIG%% {\n\
let res = %%ACTION%%;\n\
assert %%CHECK%%;\n\
return res;\n\
}\n\
\n\
%%CODE%%\n\
";
constructor(name: string, fullname: string, code: string, line: number, dosmall: boolean, extraSrc: string | undefined) {
super(name, fullname, code, extraSrc);
this.line = line;
this.dosmall = dosmall;
}
static create(name: string, dosmall: boolean, fullname: string, sig: string, action: string, check: string, code: string, extraSrc: string | undefined): IndividualWitnessTestInfo {
const rcode = IndividualWitnessTestInfo.ctemplate
.replace("%%SIG%%", sig)
.replace("%%ACTION%%", action)
.replace("%%CHECK%%", check)
.replace("%%CODE%%", code);
return new IndividualWitnessTestInfo(name, fullname, rcode, 5, dosmall, extraSrc);
}
}
class IndividualEvaluateTestInfo extends IndividualTestInfo {
readonly jargs: any[];
readonly expected: any; //undefined is infeasible
private static ctemplate =
"namespace NSMain;\n\
\n\
%%SIG%% {\n\
return %%ACTION%%;\n\
}\n\
\n\
%%CODE%%\n\
";
constructor(name: string, fullname: string, code: string, jargs: any[], expected: any, extraSrc: string | undefined) {
super(name, fullname, code, extraSrc);
this.jargs = jargs;
this.expected = expected;
}
static create(name: string, fullname: string, sig: string, action: string, code: string, jargs: any[], expected: any, extraSrc: string | undefined): IndividualEvaluateTestInfo {
const rcode = IndividualEvaluateTestInfo.ctemplate
.replace("%%SIG%%", sig)
.replace("%%ACTION%%", action)
.replace("%%CODE%%", code);
return new IndividualEvaluateTestInfo(name, fullname, rcode, jargs, expected, extraSrc);
}
}
class IndividualICPPTestInfo extends IndividualTestInfo {
readonly jargs: any[];
readonly expected: string | undefined; //undefined is exception
private static ctemplate =
"namespace NSMain;\n\
\n\
%%SIG%% {\n\
return %%ACTION%%;\n\
}\n\
\n\
%%CODE%%\n\
";
constructor(name: string, fullname: string, code: string, jargs: any[], expected: string | undefined, extraSrc: string | undefined) {
super(name, fullname, code, extraSrc);
this.jargs = jargs;
this.expected = expected;
}
static create(name: string, fullname: string, sig: string, action: string, code: string, jargs: any[], expected: string | undefined, extraSrc: string | undefined): IndividualICPPTestInfo {
const rcode = IndividualICPPTestInfo.ctemplate
.replace("%%SIG%%", sig)
.replace("%%ACTION%%", action)
.replace("%%CODE%%", code);
return new IndividualICPPTestInfo(name, fullname, rcode, jargs, expected, extraSrc);
}
}
type APICheckTestBundle = {
action: string,
check: string
dosmall?: boolean
};
type APIExecTestBundle = {
action: string,
args: any[],
result: any
};
type APITestGroupJSON = {
test: string,
src: string | null,
sig: string,
code: string,
typechk: string[],
infeasible: APICheckTestBundle[],
witness: APICheckTestBundle[],
evaluates: APIExecTestBundle[],
icpp: APIExecTestBundle[]
};
class APITestGroup {
readonly groupname: string;
readonly tests: IndividualTestInfo[];
constructor(groupname: string, tests: IndividualTestInfo[]) {
this.groupname = groupname;
this.tests = tests;
}
static create(scopename: string, spec: APITestGroupJSON): APITestGroup {
const groupname = `${scopename}.${spec.test}`;
const compiles = (spec.typechk || []).map((tt, i) => IndividualCompileWarnTest.create(`compiler#${i}`, `${groupname}.compiler#${i}`, spec.sig, tt, spec.code, spec.src || undefined));
const infeasible = (spec.infeasible || []).map((tt, i) => IndividualInfeasibleTestInfo.create(`infeasible#${i}`, `${groupname}.infeasible#${i}`, spec.sig, tt.action, tt.check, spec.code, spec.src || undefined));
const witness = (spec.witness || []).map((tt, i) => IndividualWitnessTestInfo.create(`witness#${i}`, tt.dosmall || false, `${groupname}.witness#${i}`, spec.sig, tt.action, tt.check, spec.code, spec.src || undefined));
const evaluate = (spec.evaluates || []).map((tt, i) => IndividualEvaluateTestInfo.create(`evaluate#${i}`, `${groupname}.evaluate#${i}`, spec.sig, tt.action, spec.code, tt.args, tt.result, spec.src || undefined));
//
//TODO: ICPP TESTS
//
//const icpp = (spec.icpp || []).map((tt, i) => IndividualICPPTestInfo.create(`icpp#${i}`, `${groupname}.icpp#${i}`, spec.sig, tt.action, spec.code, tt.args, tt.result, spec.src || undefined));
const icpp: IndividualICPPTestInfo[] = [];
return new APITestGroup(groupname, [...compiles, ...infeasible, ...witness, ...evaluate, ...icpp]);
}
generateTestPlan(restriction: string, tests: IndividualTestInfo[]) {
this.tests.forEach((tt) => tt.generateTestPlan(restriction, tests));
}
}
type CategoryTestGroupJSON = {
suite: string,
tests: APITestGroupJSON[]
};
class CategoryTestGroup {
readonly categoryname: string;
readonly apitests: APITestGroup[];
constructor(categoryname: string, apitests: APITestGroup[]) {
this.categoryname = categoryname;
this.apitests = apitests;
}
static create(scopename: string, spec: CategoryTestGroupJSON) {
const categoryname = `${scopename}.${spec.suite}`;
const apitests = spec.tests.map((tt) => APITestGroup.create(categoryname, tt));
return new CategoryTestGroup(categoryname, apitests);
}
generateTestPlan(restriction: string, tests: IndividualTestInfo[]) {
this.apitests.forEach((tt) => tt.generateTestPlan(restriction, tests));
}
}
class TestFolder {
readonly path: string;
readonly testname: string;
readonly tests: CategoryTestGroup[];
constructor(path: string, testname: string, tests: CategoryTestGroup[]) {
this.path = path;
this.testname = testname;
this.tests = tests;
}
generateTestPlan(restriction: string, tests: IndividualTestInfo[]) {
this.tests.forEach((tt) => tt.generateTestPlan(restriction, tests));
}
}
class TestSuite {
readonly tests: TestFolder[];
constructor(tests: TestFolder[]) {
this.tests = tests;
}
generateTestPlan(restriction: string): TestPlan {
let tests: IndividualTestInfo[] = [];
this.tests.forEach((tt) => tt.generateTestPlan(restriction, tests));
return new TestPlan(this, tests);
}
}
class TestPlan {
readonly suite: TestSuite;
readonly tests: IndividualTestInfo[];
constructor(suite: TestSuite, tests: IndividualTestInfo[]) {
this.suite = suite;
this.tests = tests;
}
}
class TestResult {
readonly test: IndividualTestInfo;
readonly start: Date;
readonly end: Date;
readonly status: "pass" | "fail" | "error";
readonly info: string | undefined;
constructor(test: IndividualTestInfo, start: Date, end: Date, status: "pass" | "fail" | "error", info: string | undefined) {
this.test = test;
this.start = start;
this.end = end;
this.status = status;
this.info = info;
}
}
class TestRunResults {
readonly suite: TestSuite;
start: Date = new Date(0);
end: Date = new Date(0);
passed: TestResult[] = [];
failed: TestResult[] = [];
errors: TestResult[] = [];
constructor(suite: TestSuite) {
this.suite = suite;
}
getOverallResults(): {total: number, elapsed: number, passed: number, failed: number, errors: number} {
return {
total: this.passed.length + this.failed.length + this.errors.length,
elapsed: (this.end.getTime() - this.start.getTime()) / 1000,
passed: this.passed.length,
failed: this.failed.length,
errors: this.errors.length
}
}
}
function loadTestSuite(): TestSuite {
const tdirs = FS.readdirSync(testroot, {withFileTypes: true}).filter((de) => de.isDirectory());
let tfa: TestFolder[] = [];
for(let i = 0; i < tdirs.length; ++i) {
const dpath = Path.join(testroot, tdirs[i].name);
const tfiles = FS.readdirSync(dpath).filter((fp) => fp.endsWith(".json"));
let ctgs: CategoryTestGroup[] = [];
for (let j = 0; j < tfiles.length; ++j) {
const fpath = Path.join(dpath, tfiles[j]);
const fcontents = JSON.parse(FS.readFileSync(fpath, "utf8")) as CategoryTestGroupJSON;
ctgs.push(CategoryTestGroup.create(`${tdirs[i].name}.${tfiles[j].replace(".json", "")}`, fcontents));
}
tfa.push(new TestFolder(dpath, tdirs[i].name, ctgs));
}
return new TestSuite(tfa);
}
type SMTTestAssets = {
extras: Map<string, string>
};
function loadSMTTestAssets(suite: TestSuite): SMTTestAssets {
let extras = new Map<string, string>();
for(let i = 0; i < suite.tests.length; ++i) {
const tf = suite.tests[i];
for (let j = 0; j < tf.tests.length; ++j) {
const ctg = tf.tests[j];
for (let k = 0; k < ctg.apitests.length; ++k) {
const stg = ctg.apitests[k];
stg.tests.filter((iti) => iti.extraSrc !== undefined).forEach((iti) => {
const cc = Path.join(testroot, iti.extraSrc as string);
const contents = FS.readFileSync(cc, "utf8");
extras.set(iti.extraSrc as string, contents);
});
}
}
}
return {
extras: extras
};
}
type ICPPTestAssets = {
extras: Map<string, string>
};
function loadICPPTestAssets(suite: TestSuite): ICPPTestAssets {
let extras = new Map<string, string>();
for(let i = 0; i < suite.tests.length; ++i) {
const tf = suite.tests[i];
for (let j = 0; j < tf.tests.length; ++j) {
const ctg = tf.tests[j];
for (let k = 0; k < ctg.apitests.length; ++k) {
const stg = ctg.apitests[k];
stg.tests.filter((iti) => iti.extraSrc !== undefined).forEach((iti) => {
const cc = Path.join(testroot, iti.extraSrc as string);
const contents = FS.readFileSync(cc, "utf8");
extras.set(iti.extraSrc as string, contents);
});
}
}
}
return {
extras: extras
};
}
class TestRunner {
readonly suite: TestSuite;
readonly plan: TestPlan;
pending: IndividualTestInfo[];
queued: string[];
results: TestRunResults;
maxpar: number;
ppos: number = 0;
inccb: (msg: string) => void = (m: string) => {;};
done: (results: TestRunResults) => void = (r: TestRunResults) => {;};
smt_assets: SMTTestAssets;
icpp_assets: ICPPTestAssets;
private testCompleteActionProcess(test: IndividualTestInfo, result: "pass" | "fail" | "unknown/timeout" | "error", start: Date, end: Date, info?: string) {
if (result === "pass") {
this.results.passed.push(new TestResult(test, start, end, "pass", undefined));
this.inccb(test.fullname + ": " + chalk.green("pass") + "\n");
}
else if (result === "fail" || result === "error") {
this.results.failed.push(new TestResult(test, start, end, "fail", info));
const failinfo = info !== undefined ? ` with: \n${info.slice(0, 80)}${info.length > 80 ? "..." : ""}` : "";
this.inccb(test.fullname + ": " + chalk.red("fail") + failinfo + "\n");
}
else {
this.results.errors.push(new TestResult(test, start, end, "error", info));
const errinfo = info !== undefined ? ` with ${info.slice(0, 80)}${info.length > 80 ? "..." : ""}` : "";
this.inccb(test.fullname + ": " + chalk.magenta("error") + errinfo + "\n");
}
}
private testCompleteActionQueued(test: IndividualTestInfo, result: "pass" | "fail" | "unknown/timeout" | "error", start: Date, end: Date, info?: string) {
const qidx = this.queued.findIndex((vv) => vv === test.fullname);
assert(qidx !== -1);
this.queued.splice(qidx, 1);
this.testCompleteActionProcess(test, result, start, end, info);
}
private testCompleteActionInline(test: IndividualTestInfo, result: "pass" | "fail" | "unknown/timeout" | "error", start: Date, end: Date, info?: string) {
this.testCompleteActionProcess(test, result, start, end, info);
}
private generateTestResultCallback(test: IndividualTestInfo) {
return (result: "pass" | "fail" | "unknown/timeout" | "error", start: Date, end: Date, info?: string) => {
this.testCompleteActionQueued(test, result, start, end, info);
this.checkAndEnqueueTests();
if(this.ppos === this.pending.length && this.queued.length === 0) {
this.done(this.results);
}
};
}
private checkAndEnqueueTests() {
while(this.queued.length < this.maxpar && this.ppos < this.pending.length) {
const tt = this.pending[this.ppos++];
if (tt instanceof IndividualCompileWarnTest) {
let code = tt.code;
if(tt.extraSrc !== undefined) {
code = code + "\n\n" + this.smt_assets.extras.get(tt.extraSrc) as string;
}
const tinfo = runCompilerTest(code);
this.testCompleteActionInline(tt, tinfo.result, tinfo.start, tinfo.end, tinfo.info);
}
else if (tt instanceof IndividualInfeasibleTestInfo) {
let code = tt.code;
if(tt.extraSrc !== undefined) {
code = code + "\n\n" + this.smt_assets.extras.get(tt.extraSrc) as string;
}
const handler = this.generateTestResultCallback(tt);
this.queued.push(tt.fullname);
try {
enqueueSMTTestRefute(code, tt.line, handler);
}
catch (ex) {
handler("error", new Date(), new Date(), `${ex}`);
}
}
else if (tt instanceof IndividualWitnessTestInfo) {
let code = tt.code;
if(tt.extraSrc !== undefined) {
code = code + "\n\n" + this.smt_assets.extras.get(tt.extraSrc) as string;
}
const handler = this.generateTestResultCallback(tt);
this.queued.push(tt.fullname);
try {
enqueueSMTTestWitness(code, tt.line, tt.dosmall, handler);
}
catch (ex) {
handler("error", new Date(), new Date(), `${ex}`);
}
}
else if(tt instanceof IndividualEvaluateTestInfo) {
let code = tt.code;
if(tt.extraSrc !== undefined) {
code = code + "\n\n" + this.smt_assets.extras.get(tt.extraSrc) as string;
}
const handler = this.generateTestResultCallback(tt);
this.queued.push(tt.fullname);
try {
enqueueSMTTestEvaluate(code, tt.jargs, tt.expected, handler);
}
catch (ex) {
handler("error", new Date(), new Date(), `${ex}`);
}
}
else if(tt instanceof IndividualICPPTestInfo) {
let code = tt.code;
if(tt.extraSrc !== undefined) {
code = code + "\n\n" + this.icpp_assets.extras.get(tt.extraSrc) as string;
}
const handler = this.generateTestResultCallback(tt);
this.queued.push(tt.fullname);
try {
enqueueICPPTest(code, tt.jargs, tt.expected, handler);
}
catch (ex) {
handler("error", new Date(), new Date(), `${ex}`);
}
}
else {
assert(false);
break;
}
}
}
constructor(suite: TestSuite, smtassets: SMTTestAssets, icppassets: ICPPTestAssets, plan: TestPlan, maxpar?: number) {
this.suite = suite;
this.plan = plan;
this.smt_assets = smtassets;
this.icpp_assets = icppassets;
this.pending = [...this.plan.tests];
this.queued = [];
this.results = new TestRunResults(suite);
this.maxpar = maxpar || 8;
}
run(inccb: (msg: string) => void, oncomplete: (results: TestRunResults) => void) {
this.results.start = new Date();
this.inccb = inccb;
this.done = oncomplete;
this.checkAndEnqueueTests();
}
}
////
//Application
let paralleldefault = 4;
if(process.platform === "win32") {
//
//TODO: see a super weird EPIPE error if we run in parallel on win32 -- so just run serial as a workaround for now
//
paralleldefault = 1;
}
Commander
.option("-m --parallel [parallel]", "Number of parallel tests to run simultaniously", paralleldefault)
.option("-r --restriction [spec]", "Limit the test run to a specific set of tests", "*")
//
//TODO: maybe want to run only SMT or only compiler tests too
//
;
Commander.parse(process.argv);
const suite = loadTestSuite();
const plan = suite.generateTestPlan(Commander.restriction)
const smt_assets = loadSMTTestAssets(suite);
const icpp_assets = loadICPPTestAssets(suite);
const runner = new TestRunner(suite, smt_assets, icpp_assets, plan, Commander.parallel);
runner.run(
(msg: string) => process.stdout.write(msg),
(results: TestRunResults) => {
const gresults = results.getOverallResults();
process.stdout.write(`Completed ${gresults.total} tests...\n`);
if(gresults.failed === 0) {
process.stdout.write(chalk.bold(`${gresults.passed}`) + " " + chalk.green("ok") + "\n");
if(gresults.errors !== 0) {
process.stdout.write(chalk.bold(`${gresults.errors}`) + " " + chalk.magenta("errors") + "\n");
}
process.exit(0);
}
else {
process.stdout.write(chalk.bold(`${gresults.failed}`) + " " + chalk.red("failures") + "\n");
process.stdout.write(chalk.bold(`${gresults.errors}`) + " " + chalk.magenta("errors") + "\n");
process.exit(1);
}
}
); | the_stack |
import type { RegExpVisitor } from "regexpp/visitor"
import type { Alternative, Element, Pattern } from "regexpp/ast"
import type { RegExpContext } from "../utils"
import {
CP_MINUS,
CP_PLUS,
CP_STAR,
CP_QUESTION,
CP_SLASH,
CP_SPACE,
CP_APOSTROPHE,
createRule,
defineRegexpVisitor,
} from "../utils"
import type { ReadonlyFlags } from "regexp-ast-analysis"
import {
Chars,
getFirstConsumedChar,
hasSomeDescendant,
} from "regexp-ast-analysis"
import type { CharSet } from "refa"
import { JS } from "refa"
import { canReorder } from "../utils/reorder-alternatives"
import { getPossiblyConsumedChar } from "../utils/regexp-ast"
import { getLongestPrefix } from "../utils/regexp-ast/alternative-prefix"
interface AllowedChars {
allowed: CharSet
required: CharSet
}
const cache = new Map<string, Readonly<AllowedChars>>()
/** */
function getAllowedChars(flags: ReadonlyFlags) {
const cacheKey = (flags.ignoreCase ? "i" : "") + (flags.unicode ? "u" : "")
let result = cache.get(cacheKey)
if (result === undefined) {
result = {
allowed: JS.createCharSet(
[
{ kind: "word", negate: false },
{ min: CP_SPACE, max: CP_SPACE },
// common punctuation and operators
{ min: CP_PLUS, max: CP_PLUS },
{ min: CP_MINUS, max: CP_MINUS },
{ min: CP_STAR, max: CP_STAR },
{ min: CP_SLASH, max: CP_SLASH },
{ min: CP_APOSTROPHE, max: CP_APOSTROPHE },
{ min: CP_QUESTION, max: CP_QUESTION },
],
flags,
),
required: Chars.word(flags),
}
cache.set(cacheKey, result)
}
return result
}
/**
* Returns whether the given element contains only literal characters and
* groups/other elements containing literal characters.
*/
function containsOnlyLiterals(
element: Element | Pattern | Alternative,
): boolean {
return !hasSomeDescendant(
element,
(d) => {
return (
d.type === "Backreference" ||
d.type === "CharacterSet" ||
(d.type === "Quantifier" && d.max === Infinity) ||
(d.type === "CharacterClass" && d.negate)
)
},
(d) => d.type !== "Assertion",
)
}
/**
* Compare two string independent of the current locale by byte order.
*/
function compareByteOrder(a: string, b: string): number {
if (a === b) {
return 0
}
return a < b ? -1 : +1
}
/**
* Compare two char sets by byte order.
*/
function compareCharSets(a: CharSet, b: CharSet): number {
// empty char set > everything else
if (a.isEmpty) {
return 1
} else if (b.isEmpty) {
return -1
}
// the first character is different
if (a.ranges[0].min !== b.ranges[0].min) {
return a.ranges[0].min - b.ranges[0].min
}
// Now for the difficult part: We want to compare them by byte-order but
// what does that mean for a set of characters?
// We will define it as such: Let x be the smallest character in the
// symmetric difference of a and b. If x is in a then a < b. Otherwise
// b < a. If the symmetric difference is empty, then a == b.
const symDiff = a.union(b).without(a.intersect(b))
if (symDiff.isEmpty) {
// a == b
return 0
}
const min = symDiff.ranges[0].min
if (a.has(min)) {
// a < b
return -1
}
// b < a
return 1
}
/**
* Compare two strings of char sets by byte order.
*/
function compareCharSetStrings(
a: readonly CharSet[],
b: readonly CharSet[],
): number {
const l = Math.min(a.length, b.length)
for (let i = 0; i < l; i++) {
const diff = compareCharSets(a[i], b[i])
if (diff !== 0) {
return diff
}
}
return a.length - b.length
}
/**
* Sorts the given alternatives.
*/
function sortAlternatives(
alternatives: Alternative[],
flags: ReadonlyFlags,
): void {
const firstChars = new Map<Alternative, number>()
for (const a of alternatives) {
const chars = getFirstConsumedChar(a, "ltr", flags)
const char =
chars.empty || chars.char.isEmpty
? Infinity
: chars.char.ranges[0].min
firstChars.set(a, char)
}
alternatives.sort((a, b) => {
const prefixDiff = compareCharSetStrings(
getLongestPrefix(a, "ltr", flags),
getLongestPrefix(b, "ltr", flags),
)
if (prefixDiff !== 0) {
return prefixDiff
}
if (flags.ignoreCase) {
return (
compareByteOrder(a.raw.toUpperCase(), b.raw.toUpperCase()) ||
compareByteOrder(a.raw, b.raw)
)
}
return compareByteOrder(a.raw, b.raw)
})
}
/**
* Returns whether the given string is a valid integer.
* @param str
* @returns
*/
function isIntegerString(str: string): boolean {
return /^(?:0|[1-9]\d*)$/u.test(str)
}
/**
* This tries to sort the given alternatives by assuming that all alternatives
* are a number.
*/
function trySortNumberAlternatives(alternatives: Alternative[]): void {
const runs = getRuns(alternatives, (a) => isIntegerString(a.raw))
for (const { startIndex, elements } of runs) {
elements.sort((a, b) => {
return Number(a.raw) - Number(b.raw)
})
alternatives.splice(startIndex, elements.length, ...elements)
}
}
/**
* Returns the indexes of the first and last of original array that is changed
* when compared with the reordered one.
*/
function getReorderingBounds<T>(
original: readonly T[],
reorder: readonly T[],
): [number, number] | undefined {
if (original.length !== reorder.length) {
return undefined
}
const len = original.length
let first = 0
for (; first < len && original[first] === reorder[first]; first++);
if (first === len) {
return undefined
}
let last = len - 1
for (; last >= 0 && original[last] === reorder[last]; last--);
return [first, last]
}
interface Run<T> {
startIndex: number
elements: T[]
}
/**
* Returns an array of runs of elements that fulfill the given condition.
*/
function getRuns<T>(iter: Iterable<T>, condFn: (item: T) => boolean): Run<T>[] {
const runs: Run<T>[] = []
let elements: T[] = []
let index = 0
for (const item of iter) {
if (condFn(item)) {
elements.push(item)
} else {
if (elements.length > 0) {
runs.push({ startIndex: index - elements.length, elements })
elements = []
}
}
index++
}
if (elements.length > 0) {
runs.push({ startIndex: index - elements.length, elements })
elements = []
}
return runs
}
export default createRule("sort-alternatives", {
meta: {
docs: {
description: "sort alternatives if order doesn't matter",
category: "Best Practices",
recommended: false,
},
fixable: "code",
schema: [],
messages: {
sort: "The alternatives of this group can be sorted without affecting the regex.",
},
type: "suggestion", // "problem",
},
create(context) {
const sliceMinLength = 3
/**
* Create visitor
*/
function createVisitor(
regexpContext: RegExpContext,
): RegExpVisitor.Handlers {
const { node, getRegexpLocation, fixReplaceNode, flags } =
regexpContext
const allowedChars = getAllowedChars(flags)
const possibleCharsCache = new Map<Alternative, CharSet>()
/** A cached version of getPossiblyConsumedChar */
function getPossibleChars(a: Alternative): CharSet {
let chars = possibleCharsCache.get(a)
if (chars === undefined) {
chars = getPossiblyConsumedChar(a, flags).char
possibleCharsCache.set(a, chars)
}
return chars
}
/** Tries to sort the given alternatives. */
function trySortRun(run: Run<Alternative>): void {
const alternatives = run.elements
if (canReorder(alternatives, flags)) {
// alternatives can be reordered freely
sortAlternatives(alternatives, flags)
trySortNumberAlternatives(alternatives)
} else {
const consumedChars = Chars.empty(flags).union(
...alternatives.map(getPossibleChars),
)
if (!consumedChars.isDisjointWith(Chars.digit(flags))) {
// let's try to at least sort numbers
const runs = getRuns(alternatives, (a) =>
isIntegerString(a.raw),
)
for (const { startIndex: index, elements } of runs) {
if (
elements.length > 1 &&
canReorder(elements, flags)
) {
trySortNumberAlternatives(elements)
alternatives.splice(
index,
elements.length,
...elements,
)
}
}
}
}
enforceSorted(run)
}
/**
* Creates a report if the sorted alternatives are different from
* the unsorted ones.
*/
function enforceSorted(run: Run<Alternative>): void {
const sorted = run.elements
const parent = sorted[0].parent
const unsorted = parent.alternatives.slice(
run.startIndex,
run.startIndex + sorted.length,
)
const bounds = getReorderingBounds(unsorted, sorted)
if (!bounds) {
return
}
const loc = getRegexpLocation({
start: unsorted[bounds[0]].start,
end: unsorted[bounds[1]].end,
})
context.report({
node,
loc,
messageId: "sort",
fix: fixReplaceNode(parent, () => {
const prefix = parent.raw.slice(
0,
unsorted[0].start - parent.start,
)
const suffix = parent.raw.slice(
unsorted[unsorted.length - 1].end - parent.start,
)
return (
prefix + sorted.map((a) => a.raw).join("|") + suffix
)
}),
})
}
/** The handler for parents */
function onParent(parent: Alternative["parent"]): void {
if (parent.alternatives.length < 2) {
return
}
const runs = getRuns(parent.alternatives, (a) => {
if (!containsOnlyLiterals(a)) {
return false
}
const consumedChars = getPossibleChars(a)
if (consumedChars.isEmpty) {
// the alternative is either empty or only contains
// assertions
return false
}
if (!consumedChars.isSubsetOf(allowedChars.allowed)) {
// contains some chars that are not allowed
return false
}
if (consumedChars.isDisjointWith(allowedChars.required)) {
// doesn't contain required chars
return false
}
return true
})
if (
runs.length === 1 &&
runs[0].elements.length === parent.alternatives.length
) {
// All alternatives are to be sorted
trySortRun(runs[0])
} else {
// Some slices are to be sorted
for (const run of runs) {
if (
run.elements.length >= sliceMinLength &&
run.elements.length >= 2
) {
trySortRun(run)
}
}
}
}
return {
onGroupEnter: onParent,
onPatternEnter: onParent,
onCapturingGroupEnter: onParent,
}
}
return defineRegexpVisitor(context, {
createVisitor,
})
},
}) | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.