text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import * as url from 'url';
import { urlUtil, validation } from ".";
import auth from '../Auth';
import { Logger } from "../cli";
import config from "../config";
import { BasePermissions } from '../m365/spo/base-permissions';
import request from "../request";
export interface ContextInfo {
FormDigestTimeoutSeconds: number;
FormDigestValue: string;
WebFullUrl: string;
}
export interface FormDigestInfo extends ContextInfo {
FormDigestExpiresAt: Date;
}
export type ClientSvcResponse = Array<any | ClientSvcResponseContents>;
export interface ClientSvcResponseContents {
SchemaVersion: string;
LibraryVersion: string;
ErrorInfo?: {
ErrorMessage: string;
ErrorValue?: string;
TraceCorrelationId: string;
ErrorCode: number;
ErrorTypeName?: string;
};
TraceCorrelationId: string;
}
export interface SearchResponse {
PrimaryQueryResult: {
RelevantResults: {
RowCount: number;
Table: {
Rows: {
Cells: {
Key: string;
Value: string;
ValueType: string;
}[];
}[];
};
}
}
}
export interface SpoOperation {
_ObjectIdentity_: string;
IsComplete: boolean;
PollingInterval: number;
}
export interface IdentityResponse {
objectIdentity: string;
serverRelativeUrl: string;
}
export const spo = {
getRequestDigest(siteUrl: string): Promise<FormDigestInfo> {
const requestOptions: any = {
url: `${siteUrl}/_api/contextinfo`,
headers: {
accept: 'application/json;odata=nometadata'
},
responseType: 'json'
};
return request.post(requestOptions);
},
ensureFormDigest(siteUrl: string, logger: Logger, context: FormDigestInfo | undefined, debug: boolean): Promise<FormDigestInfo> {
return new Promise<FormDigestInfo>((resolve: (context: FormDigestInfo) => void, reject: (error: any) => void): void => {
if (validation.isValidFormDigest(context)) {
if (debug) {
logger.logToStderr('Existing form digest still valid');
}
resolve(context as FormDigestInfo);
return;
}
spo
.getRequestDigest(siteUrl)
.then((res: FormDigestInfo): void => {
const now: Date = new Date();
now.setSeconds(now.getSeconds() + res.FormDigestTimeoutSeconds - 5);
context = {
FormDigestValue: res.FormDigestValue,
FormDigestTimeoutSeconds: res.FormDigestTimeoutSeconds,
FormDigestExpiresAt: now,
WebFullUrl: res.WebFullUrl
};
resolve(context);
}, (error: any): void => {
reject(error);
});
});
},
waitUntilFinished({ operationId, siteUrl, resolve, reject, logger, currentContext, dots, debug, verbose }: { operationId: string, siteUrl: string, resolve: () => void, reject: (error: any) => void, logger: Logger, currentContext: FormDigestInfo, dots?: string, debug: boolean, verbose: boolean }): void {
spo
.ensureFormDigest(siteUrl, logger, currentContext, debug)
.then((res: FormDigestInfo): Promise<string> => {
currentContext = res;
if (debug) {
logger.logToStderr(`Checking if operation ${operationId} completed...`);
}
if (!debug && verbose) {
dots += '.';
process.stdout.write(`\r${dots}`);
}
const requestOptions: any = {
url: `${siteUrl}/_vti_bin/client.svc/ProcessQuery`,
headers: {
'X-RequestDigest': currentContext.FormDigestValue
},
data: `<Request AddExpandoFieldTypeSuffix="true" SchemaVersion="15.0.0.0" LibraryVersion="16.0.0.0" ApplicationName="${config.applicationName}" xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009"><Actions><Query Id="188" ObjectPathId="184"><Query SelectAllProperties="false"><Properties><Property Name="IsComplete" ScalarProperty="true" /><Property Name="PollingInterval" ScalarProperty="true" /></Properties></Query></Query></Actions><ObjectPaths><Identity Id="184" Name="${operationId.replace(/\\n/g, '
').replace(/"/g, '')}" /></ObjectPaths></Request>`
};
return request.post(requestOptions);
})
.then((res: string): void => {
const json: ClientSvcResponse = JSON.parse(res);
const response: ClientSvcResponseContents = json[0];
if (response.ErrorInfo) {
reject(response.ErrorInfo.ErrorMessage);
}
else {
const operation: SpoOperation = json[json.length - 1];
const isComplete: boolean = operation.IsComplete;
if (isComplete) {
if (!debug && verbose) {
process.stdout.write('\n');
}
resolve();
return;
}
setTimeout(() => {
spo.waitUntilFinished({
operationId: JSON.stringify(operation._ObjectIdentity_),
siteUrl,
resolve,
reject,
logger,
currentContext,
dots,
debug,
verbose
});
}, operation.PollingInterval);
}
});
},
waitUntilCopyJobFinished({ copyJobInfo, siteUrl, pollingInterval, resolve, reject, logger, dots, debug, verbose }: { copyJobInfo: any, siteUrl: string, pollingInterval: number, resolve: () => void, reject: (error: any) => void, logger: Logger, dots?: string, debug: boolean, verbose: boolean }): void {
const requestUrl: string = `${siteUrl}/_api/site/GetCopyJobProgress`;
const requestOptions: any = {
url: requestUrl,
headers: {
'accept': 'application/json;odata=nometadata'
},
data: { "copyJobInfo": copyJobInfo },
responseType: 'json'
};
if (!debug && verbose) {
dots += '.';
process.stdout.write(`\r${dots}`);
}
request
.post<{ JobState?: number, Logs: string[] }>(requestOptions)
.then((resp: { JobState?: number, Logs: string[] }): void => {
if (debug) {
logger.logToStderr('getCopyJobProgress response...');
logger.logToStderr(resp);
}
for (const item of resp.Logs) {
const log: { Event: string; Message: string } = JSON.parse(item);
// reject if progress error
if (log.Event === "JobError" || log.Event === "JobFatalError") {
return reject(log.Message);
}
}
// two possible scenarios
// job done = success promise returned
// job in progress = recursive call using setTimeout returned
if (resp.JobState === 0) {
// job done
if (verbose) {
process.stdout.write('\n');
}
resolve();
}
else {
setTimeout(() => {
spo.waitUntilCopyJobFinished({ copyJobInfo, siteUrl, pollingInterval, resolve, reject, logger, dots, debug, verbose });
}, pollingInterval);
}
});
},
getSpoUrl(logger: Logger, debug: boolean): Promise<string> {
if (auth.service.spoUrl) {
if (debug) {
logger.logToStderr(`SPO URL previously retrieved ${auth.service.spoUrl}. Returning...`);
}
return Promise.resolve(auth.service.spoUrl);
}
return new Promise<string>((resolve: (spoUrl: string) => void, reject: (error: any) => void): void => {
if (debug) {
logger.logToStderr(`No SPO URL available. Retrieving from MS Graph...`);
}
const requestOptions: any = {
url: `https://graph.microsoft.com/v1.0/sites/root?$select=webUrl`,
headers: {
'accept': 'application/json;odata.metadata=none'
},
responseType: 'json'
};
request
.get<{ webUrl: string }>(requestOptions)
.then((res: { webUrl: string }): Promise<void> => {
auth.service.spoUrl = res.webUrl;
return auth.storeConnectionInfo();
})
.then((): void => {
resolve(auth.service.spoUrl as string);
}, (err: any): void => {
if (auth.service.spoUrl) {
resolve(auth.service.spoUrl);
}
else {
reject(err);
}
});
});
},
getSpoAdminUrl(logger: Logger, debug: boolean): Promise<string> {
return new Promise<string>((resolve: (spoAdminUrl: string) => void, reject: (error: any) => void): void => {
spo
.getSpoUrl(logger, debug)
.then((spoUrl: string): void => {
resolve(spoUrl.replace(/(https:\/\/)([^\.]+)(.*)/, '$1$2-admin$3'));
}, (error: any): void => {
reject(error);
});
});
},
getTenantId(logger: Logger, debug: boolean): Promise<string> {
if (auth.service.tenantId) {
if (debug) {
logger.logToStderr(`SPO Tenant ID previously retrieved ${auth.service.tenantId}. Returning...`);
}
return Promise.resolve(auth.service.tenantId);
}
return new Promise<string>((resolve: (spoUrl: string) => void, reject: (error: any) => void): void => {
if (debug) {
logger.logToStderr(`No SPO Tenant ID available. Retrieving...`);
}
let spoAdminUrl: string = '';
spo
.getSpoAdminUrl(logger, debug)
.then((_spoAdminUrl: string): Promise<ContextInfo> => {
spoAdminUrl = _spoAdminUrl;
return spo.getRequestDigest(spoAdminUrl);
})
.then((contextInfo: ContextInfo): Promise<string> => {
const tenantInfoRequestOptions = {
url: `${spoAdminUrl}/_vti_bin/client.svc/ProcessQuery`,
headers: {
'X-RequestDigest': contextInfo.FormDigestValue,
accept: 'application/json;odata=nometadata'
},
data: `<Request AddExpandoFieldTypeSuffix="true" SchemaVersion="15.0.0.0" LibraryVersion="16.0.0.0" ApplicationName="${config.applicationName}" xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009"><Actions><ObjectPath Id="4" ObjectPathId="3" /><Query Id="5" ObjectPathId="3"><Query SelectAllProperties="true"><Properties /></Query></Query></Actions><ObjectPaths><Constructor Id="3" TypeId="{268004ae-ef6b-4e9b-8425-127220d84719}" /></ObjectPaths></Request>`
};
return request.post(tenantInfoRequestOptions);
})
.then((res: string): Promise<void> => {
const json: string[] = JSON.parse(res);
auth.service.tenantId = (json[json.length - 1] as any)._ObjectIdentity_.replace('\n', '
');
return auth.storeConnectionInfo();
})
.then((): void => {
resolve(auth.service.tenantId as string);
}, (err: any): void => {
if (auth.service.tenantId) {
resolve(auth.service.tenantId);
}
else {
reject(err);
}
});
});
},
/**
* Ensures the folder path exists
* @param webFullUrl web full url e.g. https://contoso.sharepoint.com/sites/site1
* @param folderToEnsure web relative or server relative folder path e.g. /Documents/MyFolder or /sites/site1/Documents/MyFolder
* @param siteAccessToken a valid access token for the site specified in the webFullUrl param
*/
ensureFolder(webFullUrl: string, folderToEnsure: string, logger: Logger, debug: boolean): Promise<void> {
const webUrl = url.parse(webFullUrl);
if (!webUrl.protocol || !webUrl.hostname) {
return Promise.reject('webFullUrl is not a valid URL');
}
if (!folderToEnsure) {
return Promise.reject('folderToEnsure cannot be empty');
}
// remove last '/' of webFullUrl if exists
const webFullUrlLastCharPos: number = webFullUrl.length - 1;
if (webFullUrl.length > 1 &&
webFullUrl[webFullUrlLastCharPos] === '/') {
webFullUrl = webFullUrl.substring(0, webFullUrlLastCharPos);
}
folderToEnsure = urlUtil.getWebRelativePath(webFullUrl, folderToEnsure);
if (debug) {
logger.log(`folderToEnsure`);
logger.log(folderToEnsure);
logger.log('');
}
let nextFolder: string = '';
let prevFolder: string = '';
let folderIndex: number = 0;
// build array of folders e.g. ["Shared%20Documents","22","54","55"]
const folders: string[] = folderToEnsure.substring(1).split('/');
if (debug) {
logger.log('folders to process');
logger.log(JSON.stringify(folders));
logger.log('');
}
// recursive function
const checkOrAddFolder = (resolve: () => void, reject: (error: any) => void): void => {
if (folderIndex === folders.length) {
if (debug) {
logger.log(`All sub-folders exist`);
}
return resolve();
}
// append the next sub-folder to the folder path and check if it exists
prevFolder = nextFolder;
nextFolder += `/${folders[folderIndex]}`;
const folderServerRelativeUrl = urlUtil.getServerRelativePath(webFullUrl, nextFolder);
const requestOptions: any = {
url: `${webFullUrl}/_api/web/GetFolderByServerRelativeUrl('${encodeURIComponent(folderServerRelativeUrl)}')`,
headers: {
'accept': 'application/json;odata=nometadata'
}
};
request
.get(requestOptions)
.then(() => {
folderIndex++;
checkOrAddFolder(resolve, reject);
})
.catch(() => {
const prevFolderServerRelativeUrl: string = urlUtil.getServerRelativePath(webFullUrl, prevFolder);
const requestOptions: any = {
url: `${webFullUrl}/_api/web/GetFolderByServerRelativePath(DecodedUrl=@a1)/AddSubFolderUsingPath(DecodedUrl=@a2)?@a1=%27${encodeURIComponent(prevFolderServerRelativeUrl)}%27&@a2=%27${encodeURIComponent(folders[folderIndex])}%27`,
headers: {
'accept': 'application/json;odata=nometadata'
},
responseType: 'json'
};
return request.post(requestOptions)
.then(() => {
folderIndex++;
checkOrAddFolder(resolve, reject);
})
.catch((err: any) => {
if (debug) {
logger.log(`Could not create sub-folder ${folderServerRelativeUrl}`);
}
reject(err);
});
});
};
return new Promise<void>(checkOrAddFolder);
},
/**
* Requests web object identity for the current web.
* That request is something similar to _contextinfo in REST.
* The response data looks like:
* _ObjectIdentity_=<GUID>|<GUID>:site:<GUID>:web:<GUID>
* _ObjectType_=SP.Web
* ServerRelativeUrl=/sites/contoso
* @param webUrl web url
* @param formDigestValue formDigestValue
*/
getCurrentWebIdentity(webUrl: string, formDigestValue: string): Promise<IdentityResponse> {
const requestOptions: any = {
url: `${webUrl}/_vti_bin/client.svc/ProcessQuery`,
headers: {
'X-RequestDigest': formDigestValue
},
data: `<Request AddExpandoFieldTypeSuffix="true" SchemaVersion="15.0.0.0" LibraryVersion="16.0.0.0" ApplicationName="${config.applicationName}" xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009"><Actions><Query Id="1" ObjectPathId="5"><Query SelectAllProperties="false"><Properties><Property Name="ServerRelativeUrl" ScalarProperty="true" /></Properties></Query></Query></Actions><ObjectPaths><Property Id="5" ParentId="3" Name="Web" /><StaticProperty Id="3" TypeId="{3747adcd-a3c3-41b9-bfab-4a64dd2f1e0a}" Name="Current" /></ObjectPaths></Request>`
};
return new Promise<IdentityResponse>((resolve: (identity: IdentityResponse) => void, reject: (error: any) => void): void => {
request.post<string>(requestOptions).then((res: string): void => {
const json: ClientSvcResponse = JSON.parse(res);
const contents: ClientSvcResponseContents = json.find(x => { return x.ErrorInfo; });
if (contents && contents.ErrorInfo) {
return reject(contents.ErrorInfo.ErrorMessage || 'ClientSvc unknown error');
}
const identityObject: { _ObjectIdentity_: string; ServerRelativeUrl: string } = json.find(x => { return x._ObjectIdentity_; });
if (identityObject) {
return resolve({
objectIdentity: identityObject._ObjectIdentity_,
serverRelativeUrl: identityObject.ServerRelativeUrl
});
}
reject('Cannot proceed. _ObjectIdentity_ not found'); // this is not supposed to happen
}, (err: any): void => { reject(err); });
});
},
/**
* Gets EffectiveBasePermissions for web return type is "_ObjectType_\":\"SP.Web\".
* @param webObjectIdentity ObjectIdentity. Has format _ObjectIdentity_=<GUID>|<GUID>:site:<GUID>:web:<GUID>
* @param webUrl web url
* @param siteAccessToken site access token
* @param formDigestValue formDigestValue
*/
getEffectiveBasePermissions(webObjectIdentity: string, webUrl: string, formDigestValue: string, logger: Logger, debug: boolean): Promise<BasePermissions> {
const basePermissionsResult: BasePermissions = new BasePermissions();
const requestOptions: any = {
url: `${webUrl}/_vti_bin/client.svc/ProcessQuery`,
headers: {
'X-RequestDigest': formDigestValue
},
data: `<Request AddExpandoFieldTypeSuffix="true" SchemaVersion="15.0.0.0" LibraryVersion="16.0.0.0" ApplicationName="${config.applicationName}" xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009"><Actions><Query Id="11" ObjectPathId="5"><Query SelectAllProperties="false"><Properties><Property Name="EffectiveBasePermissions" ScalarProperty="true" /></Properties></Query></Query></Actions><ObjectPaths><Identity Id="5" Name="${webObjectIdentity}" /></ObjectPaths></Request>`
};
return new Promise<BasePermissions>((resolve: (permissions: BasePermissions) => void, reject: (error: any) => void): void => {
request.post<string>(requestOptions).then((res: string): void => {
if (debug) {
logger.log('Attempt to get the web EffectiveBasePermissions');
}
const json: ClientSvcResponse = JSON.parse(res);
const contents: ClientSvcResponseContents = json.find(x => { return x.ErrorInfo; });
if (contents && contents.ErrorInfo) {
return reject(contents.ErrorInfo.ErrorMessage || 'ClientSvc unknown error');
}
const permissionsObj = json.find(x => { return x.EffectiveBasePermissions; });
if (permissionsObj) {
basePermissionsResult.high = permissionsObj.EffectiveBasePermissions.High;
basePermissionsResult.low = permissionsObj.EffectiveBasePermissions.Low;
return resolve(basePermissionsResult);
}
reject('Cannot proceed. EffectiveBasePermissions not found'); // this is not supposed to happen
}, (err: any): void => { reject(err); });
});
},
/**
* Gets folder by server relative url (GetFolderByServerRelativeUrl in REST)
* The response data looks like:
* _ObjectIdentity_=<GUID>|<GUID>:site:<GUID>:web:<GUID>:folder:<GUID>
* _ObjectType_=SP.Folder
* @param webObjectIdentity ObjectIdentity. Has format _ObjectIdentity_=<GUID>|<GUID>:site:<GUID>:web:<GUID>
* @param webUrl web url
* @param siteRelativeUrl site relative url e.g. /Shared Documents/Folder1
* @param formDigestValue formDigestValue
*/
getFolderIdentity(webObjectIdentity: string, webUrl: string, siteRelativeUrl: string, formDigestValue: string): Promise<IdentityResponse> {
const serverRelativePath: string = urlUtil.getServerRelativePath(webUrl, siteRelativeUrl);
const requestOptions: any = {
url: `${webUrl}/_vti_bin/client.svc/ProcessQuery`,
headers: {
'X-RequestDigest': formDigestValue
},
data: `<Request AddExpandoFieldTypeSuffix="true" SchemaVersion="15.0.0.0" LibraryVersion="16.0.0.0" ApplicationName="${config.applicationName}" xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009"><Actions><ObjectPath Id="10" ObjectPathId="9" /><ObjectIdentityQuery Id="11" ObjectPathId="9" /><Query Id="12" ObjectPathId="9"><Query SelectAllProperties="false"><Properties><Property Name="Properties" SelectAll="true"><Query SelectAllProperties="false"><Properties /></Query></Property></Properties></Query></Query></Actions><ObjectPaths><Method Id="9" ParentId="5" Name="GetFolderByServerRelativeUrl"><Parameters><Parameter Type="String">${serverRelativePath}</Parameter></Parameters></Method><Identity Id="5" Name="${webObjectIdentity}" /></ObjectPaths></Request>`
};
return new Promise<IdentityResponse>((resolve: (identity: IdentityResponse) => void, reject: (error: any) => void) => {
return request.post<string>(requestOptions).then((res: string): void => {
const json: ClientSvcResponse = JSON.parse(res);
const contents: ClientSvcResponseContents = json.find(x => { return x.ErrorInfo; });
if (contents && contents.ErrorInfo) {
return reject(contents.ErrorInfo.ErrorMessage || 'ClientSvc unknown error');
}
const objectIdentity: { _ObjectIdentity_: string; } = json.find(x => { return x._ObjectIdentity_; });
if (objectIdentity) {
return resolve({
objectIdentity: objectIdentity._ObjectIdentity_,
serverRelativeUrl: serverRelativePath
});
}
reject('Cannot proceed. Folder _ObjectIdentity_ not found'); // this is not suppose to happen
}, (err: any): void => { reject(err); });
});
}
}; | the_stack |
import { expect } from "chai";
import { BasicTests } from "test/helper/Basic";
import { IntervalTimeline, IntervalTimelineEvent } from "./IntervalTimeline";
describe("IntervalTimeline", () => {
BasicTests(IntervalTimeline);
context("inserting/deleting events", () => {
it("accepts events into the timeline", () => {
const sched = new IntervalTimeline();
sched.add({
duration: 0.2,
state: "A",
time: 0,
});
sched.add({
duration: 0.4,
state: "B",
time: 1,
});
sched.add({
duration: 12,
state: "C",
time: 2,
});
sched.dispose();
});
it("computes the lenght of the timeline correctly after adding events", () => {
const sched = new IntervalTimeline();
sched.add({
duration: 0.2,
state: "A",
time: 0,
});
sched.add({
duration: 0.4,
state: "B",
time: 1,
});
sched.add({
duration: 12,
state: "C",
time: 2,
});
expect(sched.length).to.equal(3);
sched.dispose();
});
it("can remove events from the timeline", () => {
const sched = new IntervalTimeline();
const ev0 = {
duration: 0.2,
time: 0,
};
const ev1 = {
duration: 0.2,
time: 0.2,
};
const ev2 = {
duration: 0.2,
time: 0.1,
};
sched.add(ev0);
sched.add(ev1);
sched.add(ev2);
expect(sched.length).to.equal(3);
sched.remove(ev0);
sched.remove(ev1);
expect(sched.length).to.equal(1);
sched.remove(ev2);
expect(sched.length).to.equal(0);
sched.dispose();
});
it("removing on a null set does nothing", () => {
const sched = new IntervalTimeline();
expect(sched.length).to.equal(0);
// @ts-ignore
sched.remove({});
expect(sched.length).to.equal(0);
sched.dispose();
});
it("can add and remove and add again events from the timeline", () => {
const sched = new IntervalTimeline();
const ev0 = {
duration: 0.2,
time: 0,
};
const ev1 = {
duration: 0.2,
time: 0.2,
};
const ev2 = {
duration: 0.2,
time: 0.1,
};
sched.add(ev0);
sched.add(ev1);
sched.add(ev2);
expect(sched.length).to.equal(3);
sched.remove(ev0);
sched.remove(ev1);
expect(sched.length).to.equal(1);
sched.add(ev0);
sched.add(ev1);
expect(sched.length).to.equal(3);
sched.dispose();
});
it("throws an error if events do not have both time and duration attributes", () => {
const sched = new IntervalTimeline();
expect(() => {
// @ts-ignore
sched.add({
time: 0,
});
}).to.throw(Error);
expect(() => {
// @ts-ignore
sched.add({
duration: 0,
});
}).to.throw(Error);
sched.dispose();
});
});
context("getting events", () => {
it("returns null when no events are in the timeline", () => {
const sched = new IntervalTimeline();
expect(sched.get(3)).to.equal(null);
sched.dispose();
});
it("returns the event which overlaps the given time", () => {
const sched = new IntervalTimeline();
sched.add({
duration: Infinity,
state: "A",
time: 0,
});
sched.add({
duration: 0.4,
state: "B",
time: 1,
});
sched.add({
duration: 12,
state: "C",
time: 2,
});
// @ts-ignore
expect(sched.get(0.2).state).to.equal("A");
sched.dispose();
});
it("returns events exclusive of the end time", () => {
const sched = new IntervalTimeline();
sched.add({
duration: 1,
state: "A",
time: 0,
});
// @ts-ignore
expect(sched.get(0.99).state).to.equal("A");
expect(sched.get(1)).to.equal(null);
sched.dispose();
});
it("factors in start position and duration when checking for overlaps", () => {
const sched = new IntervalTimeline();
sched.add({
duration: 0.4,
time: 0,
});
expect(sched.get(0.5)).to.equal(null);
expect(sched.get(-1)).to.equal(null);
expect(sched.get(0)).to.not.equal(null);
expect(sched.get(0.39)).to.not.equal(null);
sched.dispose();
});
it("returns the event whose start is closest to the given time", () => {
const sched = new IntervalTimeline();
sched.add({
duration: Infinity,
state: "A",
time: 0,
});
sched.add({
duration: 0.4,
state: "B",
time: 0.2,
});
sched.add({
duration: 12,
state: "C",
time: 2,
});
// @ts-ignore
expect(sched.get(0.2).state).to.equal("B");
sched.dispose();
});
it("returns the events correctly after some events are removed", () => {
const sched = new IntervalTimeline();
const ev0 = {
duration: 0.2,
state: "A",
time: 0.1,
};
const ev1 = {
duration: 0.3,
state: "B",
time: 0.2,
};
const ev2 = {
duration: Infinity,
state: "C",
time: 0,
};
sched.add(ev0);
sched.add(ev1);
sched.add(ev2);
sched.remove(ev0);
sched.remove(ev1);
// @ts-ignore
expect(sched.get(0.2)).to.not.equal(null);
// @ts-ignore
expect(sched.get(0.2).state).to.equal("C");
sched.dispose();
});
it("can handle many items", () => {
const sched = new IntervalTimeline();
const len = 5000;
const events: IntervalTimelineEvent[] = [];
let duration = 1;
let time = 0;
for (let i = 0; i < len; i++) {
const event = {
duration,
time,
};
time = (time + 3.1) % 109;
duration = (duration + 5.7) % 19;
sched.add(event);
events.push(event);
}
for (let j = 0; j < events.length; j++) {
const event = events[j];
const eventVal = sched.get(event.time);
if (eventVal) {
expect(eventVal.time).to.equal(event.time);
}
}
for (let k = 0; k < events.length; k++) {
sched.remove(events[k]);
expect(sched.length).to.equal(events.length - k - 1);
}
sched.dispose();
});
});
context("cancelling", () => {
it("can cancel items after the given time", () => {
const sched = new IntervalTimeline();
for (let i = 5; i < 100; i++) {
sched.add({
duration: 10,
time: i,
});
}
sched.cancel(10);
expect(sched.length).to.equal(5);
sched.cancel(0);
expect(sched.length).to.equal(0);
sched.dispose();
});
it("can cancel items at the given time", () => {
const sched = new IntervalTimeline();
sched.add({
duration: 10,
time: 0,
});
sched.cancel(1);
expect(sched.length).to.equal(1);
sched.cancel(0);
expect(sched.length).to.equal(0);
sched.dispose();
});
});
context("Iterators", () => {
it("iterates over all items and returns and item", () => {
const sched = new IntervalTimeline();
sched.add({ time: 0, duration: 5 });
sched.add({ time: 0.1, duration: 5 });
sched.add({ time: 0.2, duration: 5 });
sched.add({ time: 0.3, duration: 5 });
sched.add({ time: 0.4, duration: 5 });
let count = 0;
sched.forEach((event) => {
expect(event).to.be.an("object");
count++;
});
expect(count).to.equal(5);
sched.dispose();
});
it("iterate over null set", () => {
const sched = new IntervalTimeline();
let count = 0;
sched.forEach(() => {
count++;
});
expect(count).to.equal(0);
sched.dispose();
});
it("iterates over all items overlapping the given time", () => {
const sched = new IntervalTimeline();
sched.add({ time: 0, duration: 5 });
sched.add({ time: 0.1, duration: 5 });
sched.add({ time: 0.2, duration: 5 });
sched.add({ time: 0.3, duration: 5 });
sched.add({ time: 0.4, duration: 5 });
let count = 0;
sched.forEachAtTime(0.3, (event) => {
expect(event).to.be.an("object");
expect(event.time).to.be.at.most(0.3);
count++;
});
expect(count).to.equal(4);
sched.dispose();
});
it("handles time ranges before the available objects", () => {
const sched = new IntervalTimeline();
sched.add({ time: 0.1, duration: 5 });
sched.add({ time: 0.2, duration: 5 });
sched.add({ time: 0.3, duration: 5 });
sched.add({ time: 0.4, duration: 5 });
let count = 0;
sched.forEachAtTime(0, () => {
count++;
});
expect(count).to.equal(0);
sched.dispose();
});
it("handles time ranges after the available objects", () => {
const sched = new IntervalTimeline();
sched.add({ time: 0.1, duration: 5 });
sched.add({ time: 0.2, duration: 5 });
sched.add({ time: 0.3, duration: 5 });
sched.add({ time: 0.4, duration: 5 });
let count = 0;
sched.forEachAtTime(5.5, () => {
count++;
});
expect(count).to.equal(0);
sched.dispose();
});
it("iterates over all items after the given time", () => {
const sched = new IntervalTimeline();
sched.add({ time: 0.1, duration: 5 });
sched.add({ time: 0.2, duration: 5 });
sched.add({ time: 0.3, duration: 5 });
sched.add({ time: 0.4, duration: 5 });
let count = 0;
sched.forEachFrom(0.2, (event) => {
expect(event).to.be.an("object");
expect(event.time).to.be.gte(0.2);
count++;
});
expect(count).to.equal(3);
count = 0;
sched.forEachFrom(0.35, (event) => {
expect(event.time).to.be.gte(0.35);
count++;
});
expect(count).to.equal(1);
sched.dispose();
});
it("handles time ranges after the available objects", () => {
const sched = new IntervalTimeline();
sched.add({ time: 0.1, duration: 5 });
sched.add({ time: 0.2, duration: 5 });
sched.add({ time: 0.3, duration: 5 });
sched.add({ time: 0.4, duration: 5 });
let count = 0;
sched.forEachFrom(0.5, () => {
count++;
});
expect(count).to.equal(0);
sched.dispose();
});
it("iterates over all items", () => {
const sched = new IntervalTimeline();
sched.add({ time: 0.1, duration: 5 });
sched.add({ time: 0.2, duration: 5 });
sched.add({ time: 0.3, duration: 5 });
sched.add({ time: 0.4, duration: 5 });
let count = 0;
sched.forEach(() => {
count++;
});
expect(count).to.equal(4);
sched.dispose();
});
it("can remove items during forEach iterations", () => {
const sched = new IntervalTimeline();
for (let i = 0; i < 1000; i++) {
sched.add({ time: i, duration: 0.01 });
}
sched.forEach((event) => {
sched.cancel(event.time);
});
expect(sched.length).to.equal(0);
sched.dispose();
});
it("can remove items during forEachAtTime iterations", () => {
const sched = new IntervalTimeline();
for (let i = 0; i < 1000; i++) {
sched.add({ time: i, duration: Infinity });
}
sched.forEachAtTime(1000, (event) => {
sched.cancel(event.time);
});
expect(sched.length).to.equal(0);
sched.dispose();
});
it("can remove items during forEachFrom iterations", () => {
const sched = new IntervalTimeline();
for (let i = 0; i < 1000; i++) {
sched.add({ time: i, duration: Infinity });
}
sched.forEachFrom(0, (event) => {
sched.remove(event);
});
expect(sched.length).to.equal(0);
sched.dispose();
});
});
}); | the_stack |
import { Hash, HashedObject, HashedSet, Literal, LiteralUtils, MutationOp } from 'data/model';
import { AgentPod } from 'mesh/service/AgentPod';
import { Store } from 'storage/store';
import { Logger, LogLevel } from 'util/logging';
import { Endpoint } from '../network/NetworkAgent';
import { PeerGroupAgent } from '../peer/PeerGroupAgent';
import { PeeringAgentBase } from '../peer/PeeringAgentBase';
import { HeaderBasedState } from './history/HeaderBasedState';
import { AgentStateUpdateEvent, GossipEventTypes } from './StateGossipAgent';
import { StateSyncAgent } from './StateSyncAgent';
import { HistorySynchronizer } from './history/HistorySynchronizer';
import { HistoryProvider, MessageType, SyncMsg } from './history/HistoryProvider';
import { OpHeader, OpHeaderLiteral } from 'data/history/OpHeader';
import { Resources } from 'spaces/Resources';
type StateFilter = (state: HeaderBasedState, store: Store, isLocal: boolean, localState?: HeaderBasedState) => Promise<HeaderBasedState>;
class HeaderBasedSyncAgent extends PeeringAgentBase implements StateSyncAgent {
static controlLog = new Logger(HeaderBasedSyncAgent.name, LogLevel.INFO);
static messageLog = new Logger(HeaderBasedSyncAgent.name, LogLevel.INFO);
static syncAgentIdFor(objHash: Hash, peerGroupId: string) {
return 'causal-sync-for-' + objHash + '-in-peer-group-' + peerGroupId;
}
static MaxRequestsPerRemote = 2;
mutableObj: Hash;
acceptedMutationOpClasses: string[];
stateOpFilter?: StateFilter;
resources: Resources;
store: Store;
pod?: AgentPod;
state?: HeaderBasedState;
stateHash?: Hash;
stateOpHeadersByOpHash?: Map<Hash, OpHeader>;
remoteStates: Map<Endpoint, HashedSet<Hash>>;
synchronizer : HistorySynchronizer;
provider : HistoryProvider;
terminated = false;
controlLog: Logger;
messageLog: Logger;
constructor(peerGroupAgent: PeerGroupAgent, mutableObj: Hash, resources: Resources, acceptedMutationOpClasses : string[], stateOpFilter?: StateFilter) {
super(peerGroupAgent);
this.mutableObj = mutableObj;
this.acceptedMutationOpClasses = acceptedMutationOpClasses;
this.stateOpFilter = stateOpFilter;
this.resources = resources;
this.store = resources.store;
this.remoteStates = new Map();
this.synchronizer = new HistorySynchronizer(this);
this.provider = new HistoryProvider(this);
this.opCallback = this.opCallback.bind(this);
this.controlLog = HeaderBasedSyncAgent.controlLog;
this.messageLog = HeaderBasedSyncAgent.messageLog;
}
getAgentId(): string {
return HeaderBasedSyncAgent.syncAgentIdFor(this.mutableObj, this.peerGroupAgent.peerGroupId);
}
ready(pod: AgentPod): void {
this.pod = pod;
this.updateStateFromStore().then(async () => {
if (this.stateOpHeadersByOpHash !== undefined) {
for (const opHistory of this.stateOpHeadersByOpHash.values()) {
const op = await this.store.load(opHistory?.opHash) as MutationOp;
await this.synchronizer.onNewLocalOp(op);
}
}
}
);
this.watchStoreForOps();
}
shutdown(): void {
this.terminated = true;
this.synchronizer.shutdown();
}
// Reactive logic:
// - Gossip agent informing us of the reception of remote state updates
// - Messages from peers with requests, replies, literals, etc.
async receiveRemoteState(sender: string, stateHash: string, state: HashedObject): Promise<boolean> {
if (this.terminated) return false;
let isNew = false;
if (state instanceof HeaderBasedState && state.mutableObj === this.mutableObj) {
this.remoteStates.set(sender, new HashedSet<Hash>(state.terminalOpHeaderHashes?.values()))
if (this.stateHash !== stateHash) {
const filteredState = this.stateOpFilter === undefined? state : await this.stateOpFilter(state, this.store, false, this.state);
const unknown = new Set<OpHeader>();
for (const opHistoryLiteral of (filteredState.terminalOpHeaders as HashedSet<OpHeaderLiteral>).values()) {
if ((await this.store.loadOpHeaderByHeaderHash(opHistoryLiteral.headerHash)) === undefined) {
unknown.add(new OpHeader(opHistoryLiteral));
}
}
isNew = unknown.size > 0;
if (isNew) {
this.synchronizer.onNewHistory(sender, unknown);
}
}
}
return isNew;
}
receivePeerMessage(source: Endpoint, sender: Hash, recipient: Hash, content: any): void {
if (this.terminated) return;
sender; recipient;
const msg: SyncMsg = content as SyncMsg;
if (this.messageLog.level <= LogLevel.DEBUG) {
this.messageLog.debug('Msg received from: ' + source + ' to: ' + this.peerGroupAgent.getLocalPeer().endpoint, msg);
}
if (msg.type === MessageType.Request) {
this.provider.onReceivingRequest(source, msg);
} else if (msg.type === MessageType.Response) {
this.synchronizer.onReceivingResponse(source, msg);
} else if (msg.type === MessageType.SendLiteral) {
this.synchronizer.onReceivingLiteral(source, msg);
} else if (msg.type === MessageType.RejectRequest) {
this.synchronizer.onReceivingRequestRejection(source, msg);
} else if (msg.type === MessageType.CancelRequest) {
this.provider.onReceivingRequestCancellation(source, msg);
}
}
// Monitoring local state for changes:
watchStoreForOps() {
this.store.watchReferences('targetObject', this.mutableObj, this.opCallback);
}
unwatchStoreForOps() {
this.store.removeReferencesWatch('targetObject', this.mutableObj, this.opCallback);
}
async opCallback(opHash: Hash): Promise<void> {
if (this.terminated) return;
this.controlLog.trace('Op ' + opHash + ' found for object ' + this.mutableObj + ' in peer ' + this.peerGroupAgent.getLocalPeer().endpoint);
let op = await this.store.load(opHash) as MutationOp;
if (this.shouldAcceptMutationOp(op)) {
await this.synchronizer.onNewLocalOp(op);
await this.updateStateFromStore();
}
};
literalIsValidOp(literal?: Literal): boolean {
let valid = false;
if (this.acceptedMutationOpClasses !== undefined && literal !== undefined) {
const fields = LiteralUtils.getFields(literal);
const className = LiteralUtils.getClassName(literal);
if (fields['targetObject'] !== undefined && fields['targetObject']._hash === this.mutableObj &&
this.acceptedMutationOpClasses.indexOf(className) >= 0) {
valid = true;
}
}
return valid;
}
// Loading local state:
private async updateStateFromStore(): Promise<void> {
const state = await this.loadStateFromStore();
this.updateState(state);
}
/*private async loadSynchronizerState(): Promise<HeaderBasedState> {
this.synchronizer.localState.getTerminalOps();
}*/
private async loadStateFromStore(): Promise<HeaderBasedState> {
let terminalOpsInfo = await this.store.loadTerminalOpsForMutable(this.mutableObj);
if (terminalOpsInfo === undefined) {
terminalOpsInfo = {terminalOps: []};
}
const terminalOpHeaders: Array<OpHeader> = [];
for (const terminalOpHash of terminalOpsInfo.terminalOps) {
let terminalOpHeader = this.stateOpHeadersByOpHash?.get(terminalOpHash);
if (terminalOpHeader === undefined) {
terminalOpHeader = await this.store.loadOpHeader(terminalOpHash);
}
terminalOpHeaders.push(terminalOpHeader as OpHeader)
}
const state = HeaderBasedState.create(this.mutableObj, terminalOpHeaders);
if (this.stateOpFilter === undefined) {
return state;
} else {
return this.stateOpFilter(state, this.store, true);
}
}
private updateState(state: HeaderBasedState): void {
const stateHash = state.hash();
if (this.stateHash === undefined || this.stateHash !== stateHash) {
HeaderBasedSyncAgent.controlLog.trace('Found new state ' + stateHash + ' for ' + this.mutableObj + ' in ' + this.peerGroupAgent.getLocalPeer().endpoint);
this.state = state;
this.stateHash = stateHash;
this.stateOpHeadersByOpHash = new Map();
if (this.state?.terminalOpHeaders !== undefined) {
for (const opHeader of this.state?.terminalOpHeaders?.values()) {
this.stateOpHeadersByOpHash.set(opHeader.opHash, new OpHeader(opHeader));
}
}
let stateUpdate: AgentStateUpdateEvent = {
type: GossipEventTypes.AgentStateUpdate,
content: { agentId: this.getAgentId(), state }
}
this.pod?.broadcastEvent(stateUpdate);
}
}
private shouldAcceptMutationOp(op: MutationOp): boolean {
return this.mutableObj === op.targetObject?.hash() &&
this.acceptedMutationOpClasses.indexOf(op.getClassName()) >= 0;
}
async lastStoredOpsDescription(limit=25) {
const load = await this.store.loadByReference('targetObject', this.mutableObj, { order: 'desc', limit: limit});
const last = load.objects.length === limit? 'last ' : '';
let contents = 'Showing ' + last + load.objects.length + ' ops in store for ' + this.mutableObj + '\n';
let idx=0;
for (const op of load.objects) {
const opHistory = await this.store.loadOpHeader(op.getLastHash()) as OpHeader;
contents = contents + idx + ': ' + opHistory.opHash + ' causal: ' + opHistory.headerHash + ' -> [' + Array.from(opHistory.prevOpHeaders) + ']\n';
idx=idx+1;
}
return contents;
}
}
export { SyncMsg as HistoryMsg, HeaderBasedSyncAgent, StateFilter } | the_stack |
import { normalize } from 'path';
import {
BotConfigWithPath,
BotConfigWithPathImpl,
CommandServiceImpl,
CommandServiceInstance,
} from '@bfemulator/sdk-shared';
import { BotConfiguration } from 'botframework-config';
import { load } from '@bfemulator/app-shared/built/state/actions/botActions';
import { CredentialManager } from './credentialManager';
import { BotHelpers } from './botHelpers';
jest.mock('electron', () => ({
app: {
getPath: () => '/downloads',
},
ipcMain: new Proxy(
{},
{
get(): any {
return () => ({});
},
has() {
return true;
},
}
),
ipcRenderer: new Proxy(
{},
{
get(): any {
return () => ({});
},
has() {
return true;
},
}
),
}));
const mockDispatch = jest.fn(_action => null);
jest.mock('./state/store', () => ({
store: {
getState: () => ({
bot: {
activeBot: {
name: 'someBot',
description: '',
padlock: '',
path: 'somePath',
services: [],
},
botFiles: [
{ path: 'path1', displayName: 'name1', secret: '' },
{ path: 'path2', displayName: 'name2', secret: '' },
{ path: 'path3', displayName: 'name3', secret: '' },
{ path: 'path4', displayName: 'name4', secret: 'ffsafsdfdsa' },
],
},
}),
dispatch: action => mockDispatch(action),
},
}));
describe('The botHelpers', () => {
let commandService: CommandServiceImpl;
beforeAll(() => {
const decorator = CommandServiceInstance();
const descriptor = decorator({ descriptor: {} }, 'none') as any;
commandService = descriptor.descriptor.get();
});
beforeEach(() => {
mockDispatch.mockClear();
});
it('getActiveBot() should retrieve the active bot', () => {
const activeBot = BotHelpers.getActiveBot();
expect(activeBot).toEqual({
name: 'someBot',
description: '',
padlock: '',
path: 'somePath',
services: [],
});
});
it('getBotInfoByPath() should get the bot info matching the specified path', () => {
const info = BotHelpers.getBotInfoByPath('path2');
expect(info).toEqual({ path: 'path2', displayName: 'name2', secret: '' });
});
it('pathExistsInRecentBots() should determine if the specified path exists in the recent bot list', () => {
const pathExists = BotHelpers.pathExistsInRecentBots('path1');
expect(pathExists).toBe(true);
});
it(`removeBotFromList() should remove the bot from the list based on the specified path`, async () => {
await BotHelpers.removeBotFromList('path4');
const newBotsList = [
{ path: 'path1', displayName: 'name1', secret: '' },
{ path: 'path2', displayName: 'name2', secret: '' },
{ path: 'path3', displayName: 'name3', secret: '' },
];
expect(mockDispatch).toHaveBeenCalledWith(load(newBotsList));
});
it('cloneBot() should clone the specified bot as expected', () => {
const bot1 = null;
expect(BotHelpers.cloneBot(bot1)).toBe(null);
const bot2: BotConfigWithPath = BotConfigWithPathImpl.fromJSON({
version: '',
name: 'someName',
description: 'someDescription',
padlock: 'somePadlock',
services: [],
path: 'somePath',
overrides: null,
});
expect(BotHelpers.cloneBot(bot2)).toEqual(bot2);
});
it('toSavableBot() should convert the specified bot to a savable instance', () => {
const bot1 = null;
expect(() => BotHelpers.toSavableBot(bot1)).toThrowError('Cannot convert null bot to savable bot.');
const bot2: BotConfigWithPath = BotConfigWithPathImpl.fromJSON({
version: '',
name: 'someName',
description: 'someDescription',
services: [],
path: 'somePath',
overrides: null,
});
const secret = 'lgCbJPXnfOlatjbBDKMbh0ie6bc8PD/cjqA/2tPgMS0=';
const savableBot = BotHelpers.toSavableBot(bot2, secret);
const expectedBot = new BotConfiguration();
expectedBot.name = 'someName';
expectedBot.description = 'someDescription';
expectedBot.services = [];
expect(savableBot.name).toEqual(expectedBot.name);
expect(savableBot.description).toEqual(expectedBot.description);
expect(savableBot.services).toEqual(expectedBot.services);
// secret key should've been refreshed
expect(savableBot.padlock).not.toEqual(secret);
});
it('promptForSecretAndRetry() should prompt the user for the bot secret', async () => {
commandService.remoteCall = jest
.fn()
.mockImplementationOnce(() => Promise.resolve(null))
.mockImplementation(() => Promise.resolve('secret'));
// if prompt for secret is dismissed, this should return null
expect(await BotHelpers.promptForSecretAndRetry('somePath')).toBe(null);
// should throw because it will get to the end of the function and try
// to load a .bot file at 'somePath'
try {
await BotHelpers.promptForSecretAndRetry('somePath');
} catch (e) {
expect(e.code).toBe('ENOENT');
}
});
describe('saveBot()', () => {
it('should save a bot using the provided secret', async () => {
const mockSave = jest.fn().mockResolvedValueOnce(true);
const mockValidateSecret = jest.fn(() => null);
jest
.spyOn(BotHelpers, 'toSavableBot')
.mockReturnValueOnce({ save: mockSave, validateSecret: mockValidateSecret });
const result = await BotHelpers.saveBot({ path: 'path' } as any, 'secret');
expect(result).toBe(true);
expect(mockValidateSecret).toHaveBeenCalledWith('secret');
expect(mockSave).toHaveBeenCalledWith('secret');
});
it('should save a bot using the secret from the store', async () => {
const mockSave = jest.fn().mockResolvedValueOnce(true);
const mockValidateSecret = jest.fn(() => null);
jest
.spyOn(BotHelpers, 'toSavableBot')
.mockReturnValueOnce({ save: mockSave, validateSecret: mockValidateSecret });
jest.spyOn(CredentialManager, 'getPassword').mockResolvedValueOnce('secret');
const result = await BotHelpers.saveBot({ path: 'path' } as any, undefined);
expect(result).toBe(true);
expect(mockValidateSecret).toHaveBeenCalledWith('secret');
expect(mockSave).toHaveBeenCalledWith('secret');
});
});
describe('loadBotWithRetry()', () => {
it('should load the bot if the correct secret is provided (happy path)', async () => {
const botConfigLoadSpy = jest
.spyOn(BotConfiguration, 'load')
.mockResolvedValueOnce({ path: 'path', name: 'boticus' });
const getPasswordSpy = jest.spyOn(CredentialManager, 'getPassword').mockResolvedValueOnce('secret');
const setPasswordSpy = jest.spyOn(CredentialManager, 'setPassword');
jest.spyOn(BotHelpers, 'pathExistsInRecentBots').mockReturnValueOnce(false);
const patchBotsSpy = jest.spyOn(BotHelpers, 'patchBotsJson').mockResolvedValueOnce(true);
const result = await BotHelpers.loadBotWithRetry('path', 'secret');
expect(botConfigLoadSpy).toHaveBeenCalledWith('path', 'secret');
expect(patchBotsSpy).toHaveBeenCalledWith('path', { path: 'path', displayName: 'boticus' });
expect(getPasswordSpy).toHaveBeenCalledWith('path');
expect(setPasswordSpy).not.toHaveBeenCalled();
expect(result).toEqual({
description: '',
name: 'boticus',
overrides: null,
padlock: '',
path: 'path',
services: [],
version: '2.0',
});
});
it('should update the secret in the store if there is no secret in the store', async () => {
jest.spyOn(BotConfiguration, 'load').mockResolvedValueOnce({ path: 'path', name: 'boticus' });
jest.spyOn(CredentialManager, 'getPassword').mockResolvedValueOnce(undefined);
const setPasswordSpy = jest.spyOn(CredentialManager, 'setPassword');
jest.spyOn(BotHelpers, 'pathExistsInRecentBots').mockReturnValueOnce(false);
jest.spyOn(BotHelpers, 'patchBotsJson').mockResolvedValueOnce(true);
const result = await BotHelpers.loadBotWithRetry('path', 'secret');
expect(setPasswordSpy).toHaveBeenCalledWith('path', 'secret');
expect(result).toEqual({
description: '',
name: 'boticus',
overrides: null,
padlock: '',
path: 'path',
services: [],
version: '2.0',
});
});
it('should update the secret in the store if it does not match the supplied secret', async () => {
jest.spyOn(BotConfiguration, 'load').mockResolvedValueOnce({ path: 'path', name: 'boticus' });
jest.spyOn(CredentialManager, 'getPassword').mockResolvedValueOnce('otherSecret');
const setPasswordSpy = jest.spyOn(CredentialManager, 'setPassword');
jest.spyOn(BotHelpers, 'pathExistsInRecentBots').mockReturnValueOnce(false);
jest.spyOn(BotHelpers, 'patchBotsJson').mockResolvedValueOnce(true);
const result = await BotHelpers.loadBotWithRetry('path', 'secret');
expect(setPasswordSpy).toHaveBeenCalledWith('path', 'secret');
expect(result).toEqual({
description: '',
name: 'boticus',
overrides: null,
padlock: '',
path: 'path',
services: [],
version: '2.0',
});
});
it('should try loading the bot again if a secret was found in the store', async () => {
jest
.spyOn(BotConfiguration, 'load')
// enter catch block on first attempt
.mockRejectedValueOnce(new Error('provided secret was wrong'))
// return a bot on second attempt
.mockResolvedValueOnce({ path: 'path' });
const loadBotWithRetrySpy = jest.spyOn(BotHelpers, 'loadBotWithRetry');
jest.spyOn(BotHelpers, 'pathExistsInRecentBots').mockReturnValue(true);
jest.spyOn(CredentialManager, 'getPassword').mockResolvedValue('secret');
const result = await BotHelpers.loadBotWithRetry('path', 'secret');
expect(result).toEqual({
description: '',
name: '',
overrides: null,
padlock: '',
path: 'path',
services: [],
version: '2.0',
});
expect(loadBotWithRetrySpy).toHaveBeenCalledTimes(2);
});
it('should prompt the user for a secret if there is no secret in the credential store', async () => {
jest.spyOn(BotConfiguration, 'load').mockRejectedValueOnce(new Error('provided secret was wrong'));
jest.spyOn(CredentialManager, 'getPassword').mockResolvedValue(undefined);
const promptForSecretSpy = jest.spyOn(BotHelpers, 'promptForSecretAndRetry').mockResolvedValueOnce(null);
const result = await BotHelpers.loadBotWithRetry('path', undefined);
expect(result).toBe(null);
expect(promptForSecretSpy).toHaveBeenCalled();
});
it('should throw if it catches an error not related to loading a bot without a secret', async () => {
try {
jest.spyOn(BotConfiguration, 'load').mockRejectedValue(new Error('something went wrong'));
await BotHelpers.loadBotWithRetry('path', undefined);
} catch (e) {
expect(e).toEqual(new Error('something went wrong'));
}
});
});
describe('getTranscriptsPath()', () => {
it('should return a value directory path with an active bot', async () => {
const result = BotHelpers.getTranscriptsPath({ path: '/foo/bar' } as any, { mode: 'livechat' } as any);
expect(result).toBe(normalize('/foo/transcripts'));
});
it('should return a value directory path with a bot opened via url', async () => {
const result = BotHelpers.getTranscriptsPath({ path: '/foo/bar' } as any, { mode: 'livechat-url' } as any);
expect(result).toBe(normalize('/downloads/transcripts'));
});
});
}); | the_stack |
import { EventEmitter, Injectable } from '@angular/core';
import { arrayRemoveItem, empty, isObject } from '@deepkit/core';
import { DatabaseCommit, DatabaseInfo, EntityPropertySeed, EntitySeed, FakerTypes, findFaker } from '@deepkit/orm-browser-api';
import { Changes, changeSetSymbol, ClassSchema, getChangeDetector, getConverterForSnapshot, PropertySchema, PropertyValidatorError } from '@deepkit/type';
import { ControllerClient } from './client';
import { Progress } from '@deepkit/rpc';
import { getInstanceStateFromItem } from '@deepkit/orm';
export type ChangesStore = { [pkHash: string]: { pk: { [name: string]: any }, changes: Changes<any> } };
export type ValidationErrors = { [fieldName: string]: PropertyValidatorError };
export type ValidationErrorStore = Map<any, ValidationErrors>;
export type IdWrapper = { $___newId: any };
const storeKeySeparator = '\0t\0';
export type FilterItem = { name: string, comparator: string, value: any };
export class BrowserQuery {
id: number = 0;
javascript: string = '';
placeholder: string = '';
tab: string = 'result';
loading: boolean = false;
progress?: Progress;
executionTime: number = 0;
downloadTime: number = 0;
downloadBytes: number = 0;
result: any;
sort: any = {};
error?: string;
log: string[] = [];
executed: boolean = false;
inputHeight: number = 40;
javascriptError: string = '';
protected lastJson?: string;
setValue(v: any) {
this.result = v;
}
eval() {
this.javascriptError = '';
try {
const a = new Function(this.javascript);
} catch (error) {
//new Function does not return helpful error message on syntax errors, but eval does.
//we can not use eval at the beginning since it tries to actually execute the code.
try {
eval(this.javascript);
} catch (error) {
this.javascriptError = error;
}
}
}
}
export class BrowserEntityState {
properties: PropertySchema[] = [];
queryId: number = 0;
error?: string;
loading: boolean = false;
filter: FilterItem[] = [];
activeQuery: number = -1;
queries: BrowserQuery[] = [];
progress?: Progress;
executionTime: number = 0;
downloadTime: number = 0;
downloadBytes: number = 0;
count: number = 0;
page: number = 1;
get totalPages(): number {
return Math.ceil(this.count / this.itemsPerPage);
}
itemsPerPage: number = 100;
dbItems: any[] = []; //items from the db
items: any[] = []; //items visible in table
selection: any[] = [];
changes?: ChangesStore;
validationStore?: ValidationErrorStore;
deletions: { [pkHash: string]: any } = {};
constructor(public schema: ClassSchema) {
}
addQuery() {
const query = new BrowserQuery();
query.placeholder = query.javascript = `database.query(${this.schema.getClassName()}).find()`;
query.id = ++this.queryId;
this.queries.push(query);
this.activeQuery = this.queries.length - 1;
}
removeQuery(query: BrowserQuery) {
const index = this.queries.indexOf(query);
if (this.activeQuery >= index) this.activeQuery--;
arrayRemoveItem(this.queries, query);
this.queries = this.queries.slice(0);
}
}
@Injectable()
export class BrowserState {
databases: DatabaseInfo[] = [];
seedSettings: { [storeKey: string]: EntitySeed } = {};
database?: DatabaseInfo;
newId: number = 0;
newItems = new Map<any, number>();
newItemsMap = new Map<number, any>();
browserEntityState: { [storeKey: string]: BrowserEntityState } = {};
addedItems: { [storeKey: string]: any[] } = {};
deletions: { [storeKey: string]: { [pkHash: string]: { [name: string]: any } } } = {};
changes: { [storeKey: string]: ChangesStore } = {};
validationErrors: { [storeKey: string]: ValidationErrorStore } = {};
connectedNewItems = new Map<any, { row: any, property: PropertySchema }[]>();
onDataChange = new EventEmitter();
constructor(protected controllerClient: ControllerClient) {
(window as any).state = this;
}
getSeedSettings(fakerTypes: FakerTypes, db: string, entity: string): EntitySeed {
const key = this.getStoreKey(db, entity);
let settings = this.seedSettings[key];
if (!settings) {
const storage = localStorage.getItem('orm-browser/seed-properties/' + db + '/' + entity);
const predefined: { [name: string]: { fake: boolean, faker: string } } = storage ? JSON.parse(storage) : { properties: {} };
const properties: EntitySeed['properties'] = {};
for (const property of this.getEntity(db, entity).getProperties()) {
if (property.backReference) continue;
if (property.isParentReference) continue;
const propertyPredefined = predefined[property.name];
const seed = properties[property.name] = new EntityPropertySeed(property.name);
seed.fake = propertyPredefined?.fake || false;
seed.faker = propertyPredefined?.faker || findFaker(fakerTypes, property);
}
settings = this.seedSettings[key] = new EntitySeed();
settings.properties = properties;
}
return settings;
}
storeSeedSettings(db: string, entity: string) {
const key = this.getStoreKey(db, entity);
const seedSettings = this.seedSettings[key];
if (!seedSettings) return;
const properties: { [name: string]: { fake: boolean, faker: string } } = {};
for (const [name, seed] of Object.entries(seedSettings.properties)) {
properties[name] = { fake: seed.fake, faker: seed.faker };
}
localStorage.setItem('orm-browser/seed-properties/' + db + '/' + entity, JSON.stringify(properties));
}
resetAll() {
this.changes = {};
this.addedItems = {};
this.validationErrors = {};
this.deletions = {};
this.connectedNewItems.clear();
this.newId = 0;
this.newItems.clear();
this.newItemsMap.clear();
}
getBrowserEntityState(dbName: string, entityName: string) {
const storeKey = this.getStoreKey(dbName, entityName);
return this.browserEntityState[storeKey] ||= new BrowserEntityState(this.getEntity(dbName, entityName));
}
getDeletions(dbName: string, entityName: string) {
const storeKey = this.getStoreKey(dbName, entityName);
return this.deletions[storeKey] ||= {};
}
getDatabase(name: string): DatabaseInfo {
for (const db of this.databases) if (db.name === name) return db;
throw new Error(`Database ${name} not loaded`);
}
scheduleForDeletion(dbName: string, entityName: string, item: any) {
const deletions = this.getDeletions(dbName, entityName);
const state = getInstanceStateFromItem(item);
deletions[state.getLastKnownPKHash()] = state.getLastKnownPK();
}
unscheduleForDeletion(dbName: string, entityName: string, item: any) {
const storeKey = this.getStoreKey(dbName, entityName);
const deletions = this.deletions[storeKey] ||= {};
const state = getInstanceStateFromItem(item);
delete deletions[state.getLastKnownPKHash()];
}
hasChanges(): boolean {
for (const i in this.changes) {
if (!this.changes.hasOwnProperty(i)) continue;
if (!empty(this.changes[i])) return true;
if (!empty(this.deletions[i])) return true;
}
return this.newItems.size > 0;
}
hasAddedItems(dbName: string, entityName: string): boolean {
const items = this.addedItems[this.getStoreKey(dbName, entityName)];
return items && items.length > 0;
}
getAddedItems(dbName: string, entityName: string): any[] {
const key = this.getStoreKey(dbName, entityName);
let items = this.addedItems[key];
if (!items) items = this.addedItems[key] = [];
return items;
}
getStoreKey(dbName: string, entityName: string): string {
return dbName + storeKeySeparator + entityName;
}
async commit() {
const commit: DatabaseCommit = {};
for (const db of this.databases) {
commit[db.name] = { added: {}, removed: {}, changed: {}, addedIds: {} };
}
for (const storeKey in this.deletions) {
if (!this.deletions.hasOwnProperty(storeKey)) continue;
const [dbName, entityName] = storeKey.split(storeKeySeparator) as [string, string];
commit[dbName].removed[entityName] = Object.values(this.deletions[storeKey]);
}
for (const storeKey in this.changes) {
if (!this.changes.hasOwnProperty(storeKey)) continue;
const [dbName, entityName] = storeKey.split(storeKeySeparator) as [string, string];
const database = commit[dbName];
const changed = database.changed[entityName] ||= [];
for (const changes of Object.values(this.changes[storeKey])) {
changed.push({
pk: changes.pk,
changes: { $inc: changes.changes.$inc, $set: changes.changes.$set, $unset: changes.changes.$unset },
});
}
}
for (const storeKey in this.addedItems) {
if (!this.addedItems.hasOwnProperty(storeKey)) continue;
const [dbName, entityName] = storeKey.split(storeKeySeparator) as [string, string];
const database = commit[dbName];
// const entity = this.getEntity(dbName, entityName);
database.added[entityName] = this.addedItems[storeKey];
database.addedIds[entityName] = this.addedItems[storeKey].map(v => this.newItems.get(v) || -1);
}
await this.controllerClient.browser.commit(commit);
this.onDataChange.emit();
}
getEntityFromCacheKey(key: string): ClassSchema {
const [dbName, entityName] = key.split(storeKeySeparator);
return this.getEntity(dbName, entityName);
}
getEntity(dbName: string, name: string): ClassSchema {
for (const db of this.databases) {
for (const entity of db.getClassSchemas()) {
if (entity.name === name) return entity;
}
}
throw new Error(`No entity ${name} in db ${dbName} found`);
}
connectNewItem(newItem: any, row: any, property: PropertySchema) {
let connections = this.connectedNewItems.get(newItem);
if (!connections) {
connections = [];
this.connectedNewItems.set(newItem, connections);
}
connections.push({ row, property });
return connections;
}
disconnectForNewItem(newItem: any) {
const connections = this.connectedNewItems.get(newItem);
if (!connections) return;
for (const connection of connections) {
connection.row[connection.property.name] = undefined;
}
}
registerNewItem(item: any) {
const id = ++this.newId;
this.newItems.set(item, id);
this.newItemsMap.set(id, item);
}
getNewItemId(item: any): number {
const id = this.newItems.get(item);
if (!id) throw new Error('Item is not registered as new');
return id;
}
getNewItemIdWrapper(item: any): IdWrapper {
const id = this.newItems.get(item);
if (!id) throw new Error('Item is not registered as new');
return { $___newId: id };
}
extractIdWrapper(value: IdWrapper): any {
return value.$___newId;
}
extractHashFromNewItem(item: any): any {
const id = this.newItems.get(item);
return 'h\0' + id;
}
extractHashFromIdWrapper(value: IdWrapper): any {
return 'h\0' + value.$___newId;
}
isIdWrapper(value: any): value is IdWrapper {
return isObject(value) && '$___newId' in value;
}
isNew(item: any): boolean {
return this.newItems.has(item);
}
getChangeStore(dbName: string, entityName: string): ChangesStore {
return this.changes[this.getStoreKey(dbName, entityName)] ||= {};
}
getValidationStore(dbName: string, entityName: string): ValidationErrorStore {
let store = this.validationErrors[this.getStoreKey(dbName, entityName)];
if (!store) store = this.validationErrors[this.getStoreKey(dbName, entityName)] = new Map();
return store;
}
changed(dbName: string, entityName: string, item: any) {
const entity = this.getEntity(dbName, entityName);
const changes = this.getChangeStore(dbName, entityName);
const state = getInstanceStateFromItem(item);
const lastSnapshot = state.getSnapshot();
const changeDetector = getChangeDetector(entity);
const doSnapshot = getConverterForSnapshot(entity);
const currentSnapshot = doSnapshot(item);
delete item[changeSetSymbol]; //we want to start over. We don't use $inc for the moment, so thats ok
const changeSet = changeDetector(lastSnapshot, currentSnapshot, item);
const pkHash = state.getLastKnownPKHash();
if (changeSet) {
// console.log('changed', lastSnapshot, currentSnapshot, changeSet);
changes[pkHash] = { changes: changeSet, pk: state.getLastKnownPK() };
} else if (changes[pkHash]) {
delete changes[pkHash];
}
}
} | the_stack |
import { Subscription } from 'rxjs';
import cloneDeep from 'lodash/cloneDeep';
import { RevertExplorationModalComponent } from './modal-templates/revert-exploration-modal.component';
require(
'components/version-diff-visualization/' +
'version-diff-visualization.component.ts');
require('domain/utilities/url-interpolation.service.ts');
require('pages/exploration-editor-page/services/exploration-data.service.ts');
require(
'pages/exploration-editor-page/history-tab/services/' +
'compare-versions.service.ts');
require(
'pages/exploration-editor-page/history-tab/services/version-tree.service.ts');
require('services/date-time-format.service.ts');
require('services/editability.service.ts');
require('pages/exploration-editor-page/services/router.service.ts');
require(
'pages/exploration-editor-page/services/' +
'history-tab-backend-api.service.ts'
);
require('services/ngb-modal.service.ts');
angular.module('oppia').component('historyTab', {
template: require('./history-tab.component.html'),
controller: [
'$log', '$rootScope', 'CompareVersionsService',
'DateTimeFormatService', 'EditabilityService', 'ExplorationDataService',
'HistoryTabBackendApiService', 'LoaderService', 'NgbModal',
'RouterService', 'VersionTreeService', 'WindowRef',
function(
$log, $rootScope, CompareVersionsService,
DateTimeFormatService, EditabilityService, ExplorationDataService,
HistoryTabBackendApiService, LoaderService, NgbModal,
RouterService, VersionTreeService, WindowRef) {
var ctrl = this;
ctrl.directiveSubscriptions = new Subscription();
// Variable explorationSnapshots is a list of all snapshots for the
// exploration in ascending order.
var explorationSnapshots = null;
var currentPage = 0;
// Compares the two selected versions and displays the comparison
// results.
ctrl.compareSelectedVersions = function() {
if (ctrl.selectedVersionsArray.length === 2) {
ctrl.changeCompareVersion();
ctrl.hideHistoryGraph = false;
}
};
// Changes the checkbox selection and provides an appropriate user
// prompt.
ctrl.changeSelectedVersions = function(snapshot, item) {
if (item === 1 && snapshot && !ctrl.selectedVersionsArray.includes(
snapshot.versionNumber)) {
ctrl.selectedVersionsArray[0] = snapshot.versionNumber;
}
if (item === 2 && snapshot && !ctrl.selectedVersionsArray.includes(
snapshot.versionNumber)) {
ctrl.selectedVersionsArray[1] = snapshot.versionNumber;
}
if (ctrl.selectedVersionsArray.length === 2) {
ctrl.compareSelectedVersions();
} else if (!ctrl.comparisonsAreDisabled) {
ctrl.hideHistoryGraph = true;
ctrl.compareVersionsButtonIsHidden = false;
}
};
// Refreshes the displayed version history log.
ctrl.refreshVersionHistory = function() {
LoaderService.showLoadingScreen('Loading');
ExplorationDataService.getDataAsync().then(function(data) {
var currentVersion = data.version;
ctrl.currentVersion = currentVersion;
// The ctrl.compareVersionMetadata is an object with keys
// 'earlierVersion' and 'laterVersion' whose values are the
// metadata of the compared versions, containing 'committerId',
// 'createdOnMsecs', 'commitMessage', and 'versionNumber'.
ctrl.compareVersions = {};
ctrl.compareVersionMetadata = {};
// Contains the IDs of the versions selected for comparison.
// Should contain a maximum of two elements.
ctrl.selectedVersionsArray = [];
ctrl.hideHistoryGraph = true;
// Disable all comparisons if there are less than two revisions in
// total.
ctrl.comparisonsAreDisabled = (currentVersion < 2);
ctrl.compareVersionsButtonIsHidden = ctrl.comparisonsAreDisabled;
HistoryTabBackendApiService
.getData(ctrl.explorationAllSnapshotsUrl).then(
function(response) {
explorationSnapshots = response.snapshots;
VersionTreeService.init(explorationSnapshots);
// Re-populate versionCheckboxArray and
// explorationVersionMetadata when history is refreshed.
ctrl.versionCheckboxArray = [];
ctrl.explorationVersionMetadata = [];
var lowestVersionIndex = 0;
for (
var i = currentVersion - 1; i >= lowestVersionIndex; i--) {
var versionNumber = explorationSnapshots[i].version_number;
ctrl.explorationVersionMetadata[versionNumber - 1] = {
committerId: explorationSnapshots[i].committer_id,
createdOnMsecsStr: (
DateTimeFormatService
.getLocaleDateTimeHourString(
explorationSnapshots[i].created_on_ms)),
tooltipText: DateTimeFormatService.getDateTimeInWords(
explorationSnapshots[i].created_on_ms),
commitMessage: explorationSnapshots[i].commit_message,
versionNumber: explorationSnapshots[i].version_number
};
ctrl.versionCheckboxArray.push({
vnum: explorationSnapshots[i].version_number,
selected: false
});
}
ctrl.totalExplorationVersionMetadata = cloneDeep(
ctrl.explorationVersionMetadata);
ctrl.totalExplorationVersionMetadata.reverse();
LoaderService.hideLoadingScreen();
ctrl.changeItemsPerPage();
$rootScope.$applyAsync();
}
);
$rootScope.$applyAsync();
});
};
var getVersionHeader = function(versionMetadata) {
return (
'Revision #' + versionMetadata.versionNumber +
' by ' + versionMetadata.committerId +
' (' + versionMetadata.createdOnMsecsStr +
')' + (
versionMetadata.commitMessage ?
': ' + versionMetadata.commitMessage : ''));
};
ctrl.filterByUsername = function() {
if (!ctrl.username) {
ctrl.explorationVersionMetadata = cloneDeep(
ctrl.totalExplorationVersionMetadata);
ctrl.versionNumbersToDisplay = ctrl.explorationVersionMetadata.length;
return;
}
ctrl.explorationVersionMetadata = (
ctrl.totalExplorationVersionMetadata.filter((metadata) => {
return (
metadata && metadata.committerId.trim().toLowerCase().includes(
ctrl.username.trim().toLowerCase()));
}));
ctrl.versionNumbersToDisplay = ctrl.explorationVersionMetadata.length;
};
// Function to set compared version metadata, download YAML and
// generate diff graph and legend when selection is changed.
ctrl.changeCompareVersion = function() {
ctrl.diffData = null;
var earlierComparedVersion = Math.min(
ctrl.selectedVersionsArray[0], ctrl.selectedVersionsArray[1]);
var laterComparedVersion = Math.max(
ctrl.selectedVersionsArray[0], ctrl.selectedVersionsArray[1]);
let earlierIndex = null, laterIndex = null;
for (let i = 0; i < ctrl.totalExplorationVersionMetadata.length; i++) {
if (ctrl.totalExplorationVersionMetadata[i].versionNumber ===
earlierComparedVersion) {
earlierIndex = i;
} else if (ctrl.totalExplorationVersionMetadata[i].versionNumber ===
laterComparedVersion) {
laterIndex = i;
}
if (earlierIndex !== null && laterIndex !== null) {
break;
}
}
ctrl.compareVersionMetadata.earlierVersion = (
ctrl.totalExplorationVersionMetadata[earlierIndex]);
ctrl.compareVersionMetadata.laterVersion = (
ctrl.totalExplorationVersionMetadata[laterIndex]);
CompareVersionsService.getDiffGraphData(
earlierComparedVersion, laterComparedVersion).then(
function(response) {
$log.info('Retrieved version comparison data');
$log.info(response);
ctrl.diffData = response;
ctrl.earlierVersionHeader = getVersionHeader(
ctrl.compareVersionMetadata.earlierVersion);
ctrl.laterVersionHeader = getVersionHeader(
ctrl.compareVersionMetadata.laterVersion);
}
);
};
// Downloads the zip file for an exploration.
ctrl.downloadExplorationWithVersion = function(versionNumber) {
// Note that this opens (and then immediately closes) a new tab. If
// we do this in the same tab, the beforeunload handler is
// triggered.
WindowRef.nativeWindow.open(
ctrl.explorationDownloadUrl + '?v=' + versionNumber,
'&output_format=zip');
};
ctrl.showRevertExplorationModal = function(version) {
const modalRef = NgbModal.open(RevertExplorationModalComponent, {
backdrop: true,
});
modalRef.componentInstance.version = version;
modalRef.result.then(function(version) {
var data = {
revertExplorationUrl: ctrl.revertExplorationUrl,
currentVersion: ExplorationDataService.data.version,
revertToVersion: version
};
HistoryTabBackendApiService.postData(data).then(
function() {
WindowRef.nativeWindow.location.reload();
},
function() {
// Note to developers:
// This callback is triggered when the Post Request is failed.
}
);
}, function(error) {
// Note to developers:
// This callback is triggered when the Cancel button is clicked.
// No further action is needed.
});
};
ctrl.changeItemsPerPage = function() {
ctrl.explorationVersionMetadata =
ctrl.totalExplorationVersionMetadata.slice(
(ctrl.displayedCurrentPageNumber - 1) * ctrl.VERSIONS_PER_PAGE,
(ctrl.displayedCurrentPageNumber) * ctrl.VERSIONS_PER_PAGE);
ctrl.startingIndex = (
(ctrl.displayedCurrentPageNumber - 1) * ctrl.VERSIONS_PER_PAGE + 1);
ctrl.endIndex = (
(ctrl.displayedCurrentPageNumber) * ctrl.VERSIONS_PER_PAGE);
ctrl.versionNumbersToDisplay = ctrl.explorationVersionMetadata.length;
};
ctrl.isEditable = function() {
return ctrl.EditabilityService.isEditable();
};
ctrl.resetGraph = function() {
ctrl.firstVersion = null;
ctrl.secondVersion = null;
ctrl.hideHistoryGraph = true;
ctrl.selectedVersionsArray = [];
};
ctrl.reverseDateOrder = function() {
ctrl.explorationVersionMetadata.reverse();
};
ctrl.$onInit = function() {
ctrl.directiveSubscriptions.add(
RouterService.onRefreshVersionHistory.subscribe((data) => {
if (
data.forceRefresh || ctrl.explorationVersionMetadata === null) {
ctrl.refreshVersionHistory();
}
})
);
ctrl.EditabilityService = EditabilityService;
ctrl.explorationId = ExplorationDataService.explorationId;
ctrl.explorationAllSnapshotsUrl =
'/createhandler/snapshots/' + ctrl.explorationId;
ctrl.revertExplorationUrl =
'/createhandler/revert/' + ctrl.explorationId;
ctrl.explorationDownloadUrl =
'/createhandler/download/' + ctrl.explorationId;
/* Variable definitions:
*
* explorationVersionMetadata is an object whose keys are version
* numbers and whose values are objects containing data of that
* revision (that is to be displayed) with the keys 'committerId',
* 'createdOnMsecs', 'commitMessage', and 'versionNumber'. It
* contains a maximum of 30 versions.
*
* versionCheckboxArray is an array of the version numbers of the
* revisions to be displayed on the page, in the order they are
* displayed in.
*
*/
ctrl.explorationVersionMetadata = null;
ctrl.versionCheckboxArray = [];
ctrl.username = '';
ctrl.firstVersion = '';
ctrl.secondVersion = '';
ctrl.displayedCurrentPageNumber = currentPage + 1;
ctrl.versionNumbersToDisplay = [];
ctrl.VERSIONS_PER_PAGE = 10;
ctrl.startingIndex = 1;
ctrl.endIndex = 10;
ctrl.versionChoices = [10, 15, 20];
};
ctrl.$onDestroy = function() {
ctrl.directiveSubscriptions.unsubscribe();
};
}
]
}); | the_stack |
import type BN from 'bn.js';
import type { ApiPromise } from '@polkadot/api';
import type { SubmittableExtrinsic } from '@polkadot/api/types';
import type { AccountId } from '@polkadot/types/interfaces';
import type { NodeRuntimeProxyType, PalletProxyProxyDefinition } from '@polkadot/types/lookup';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import styled from 'styled-components';
import { BatchWarning, Button, Dropdown, InputAddress, InputBalance, MarkError, Modal, TxButton } from '@polkadot/react-components';
import { useApi, useTxBatch } from '@polkadot/react-hooks';
import { BN_ZERO } from '@polkadot/util';
import { useTranslation } from '../translate';
type PrevProxy = [AccountId, NodeRuntimeProxyType];
interface Props {
className?: string;
onClose: () => void;
previousProxy?: [PalletProxyProxyDefinition[], BN];
proxiedAccount: string;
}
interface ValueProps {
index: number;
typeOpts: { text: string; value: number }[];
value: PrevProxy;
}
interface NewProxyProps extends ValueProps {
onChangeAccount: (index: number, value: string | null) => void;
onChangeType: (index: number, value: number | undefined) => void;
onRemove: (index: number) => void;
proxiedAccount: string;
}
interface PrevProxyProps extends ValueProps {
onRemove: (accountId: AccountId, type: NodeRuntimeProxyType, index: number) => void;
}
const optTxBatch = { isBatchAll: true };
const EMPTY_EXISTING: [PalletProxyProxyDefinition[], BN] = [[], BN_ZERO];
function createAddProxy (api: ApiPromise, account: AccountId, type: NodeRuntimeProxyType, delay = 0): SubmittableExtrinsic<'promise'> {
return api.tx.proxy.addProxy.meta.args.length === 2
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore old version
? api.tx.proxy.addProxy(account, type)
: api.tx.proxy.addProxy(account, type, delay);
}
function createRmProxy (api: ApiPromise, account: AccountId, type: NodeRuntimeProxyType, delay = 0): SubmittableExtrinsic<'promise'> {
return api.tx.proxy.removeProxy.meta.args.length === 2
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore old version
? api.tx.proxy.removeProxy(account, type)
: api.tx.proxy.removeProxy(account, type, delay);
}
function PrevProxy ({ index, onRemove, typeOpts, value: [accountId, type] }: PrevProxyProps): React.ReactElement<PrevProxyProps> {
const { t } = useTranslation();
const _onRemove = useCallback(
() => onRemove(accountId, type, index),
[accountId, index, onRemove, type]
);
return (
<div className='proxy-container'>
<div className='input-column'>
<InputAddress
defaultValue={accountId}
isDisabled
label={t<string>('proxy account')}
/>
<Dropdown
help={'Type of proxy'}
isDisabled
label={'type'}
options={typeOpts}
value={type.toNumber()}
/>
</div>
<div className='buttons-column'>
<Button
icon='times'
onClick={_onRemove}
/>
</div>
</div>
);
}
function NewProxy ({ index, onChangeAccount, onChangeType, onRemove, proxiedAccount, typeOpts, value: [accountId, type] }: NewProxyProps): React.ReactElement<NewProxyProps> {
const { t } = useTranslation();
const _onChangeAccount = useCallback(
(value: string | null) => onChangeAccount(index, value),
[index, onChangeAccount]
);
const _onChangeType = useCallback(
(value?: number) => onChangeType(index, value),
[index, onChangeType]
);
const _onRemove = useCallback(
() => onRemove(index),
[index, onRemove]
);
return (
<div
className='proxy-container'
key={`addedProxy-${index}`}
>
<div className='input-column'>
<InputAddress
label={t<string>('proxy account')}
onChange={_onChangeAccount}
type='account'
value={accountId}
/>
{accountId.eq(proxiedAccount) && (
<MarkError content={t<string>('You should not setup proxies to act as a self-proxy.')} />
)}
<Dropdown
help={'Type of proxy'}
label={'type'}
onChange={_onChangeType}
options={typeOpts}
value={type.toNumber()}
/>
</div>
<div className='buttons-column'>
<Button
icon='times'
onClick={_onRemove}
/>
</div>
</div>
);
}
function getProxyTypeInstance (api: ApiPromise, index = 0): NodeRuntimeProxyType {
// This is not perfect, but should work for `{Kusama, Node, Polkadot}RuntimeProxyType`
const proxyNames = api.registry.lookup.names.filter((name) => name.endsWith('RuntimeProxyType'));
// fallback to previous version (may be Substrate default), when not found
return api.createType<NodeRuntimeProxyType>(proxyNames.length ? proxyNames[0] : 'ProxyType', index);
}
function getProxyOptions (api: ApiPromise): { text: string; value: number; }[] {
return getProxyTypeInstance(api).defKeys
.map((text, value) => ({ text, value }))
// Filter the empty entries added in v14
.filter(({ text }) => !text.startsWith('__Unused'));
}
function ProxyOverview ({ className, onClose, previousProxy: [existing] = EMPTY_EXISTING, proxiedAccount }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api } = useApi();
const [batchPrevious, setBatchPrevious] = useState<SubmittableExtrinsic<'promise'>[]>([]);
const [batchAdded, setBatchAdded] = useState<SubmittableExtrinsic<'promise'>[]>([]);
const [txs, setTxs] = useState<SubmittableExtrinsic<'promise'>[] | null>(null);
const [previous, setPrevious] = useState<PrevProxy[]>(() => existing.map(({ delegate, proxyType }) => [delegate, proxyType]));
const [added, setAdded] = useState<PrevProxy[]>([]);
const extrinsics = useTxBatch(txs, optTxBatch);
const reservedAmount = useMemo(
() => api.consts.proxy.proxyDepositFactor
.muln(batchPrevious.length + batchAdded.length)
.iadd(api.consts.proxy.proxyDepositBase),
[api, batchPrevious, batchAdded]
);
const typeOpts = useRef(getProxyOptions(api));
useEffect((): void => {
setBatchAdded(
added.map(([newAccount, newType]) => createAddProxy(api, newAccount, newType))
);
}, [api, added]);
useEffect((): void => {
setTxs(() => [...batchPrevious, ...batchAdded]);
}, [batchPrevious, batchAdded]);
const _addProxy = useCallback(
() => setAdded((added) =>
[...added, [
added.length
? added[added.length - 1][0]
: previous.length
? previous[previous.length - 1][0]
: api.createType('AccountId', proxiedAccount),
getProxyTypeInstance(api)
]]
),
[api, previous, proxiedAccount]
);
const _delProxy = useCallback(
(index: number) => setAdded((added) => added.filter((_, i) => i !== index)),
[]
);
const _delPrev = useCallback(
(accountId: AccountId, type: NodeRuntimeProxyType, index: number): void => {
setPrevious((previous) => previous.filter((_, i) => i !== index));
setBatchPrevious((previous) => [...previous, createRmProxy(api, accountId, type)]);
},
[api]
);
const _changeProxyAccount = useCallback(
(index: number, address: string | null) => setAdded((prevState) => {
const newState = [...prevState];
newState[index][0] = api.createType('AccountId', address);
return newState;
}),
[api]
);
const _changeProxyType = useCallback(
(index: number, newTypeNumber: number | undefined): void =>
setAdded((added) => {
const newState = [...added];
newState[index][1] = getProxyTypeInstance(api, newTypeNumber);
return newState;
}),
[api]
);
const isSameAdd = added.some(([accountId]) => accountId.eq(proxiedAccount));
return (
<Modal
className={className}
header={t<string>('Proxy overview')}
onClose={onClose}
size='large'
>
<Modal.Content>
<Modal.Columns hint={t<string>('Any account set as proxy will be able to perform actions in place of the proxied account')}>
<InputAddress
isDisabled={true}
label={t<string>('proxied account')}
type='account'
value={proxiedAccount}
/>
</Modal.Columns>
<Modal.Columns hint={t<string>('If you add several proxy accounts for the same proxy type (e.g 2 accounts set as proxy for Governance), then any of those 2 accounts will be able to perfom governance actions on behalf of the proxied account')}>
{previous.map((value, index) => (
<PrevProxy
index={index}
key={`${value.toString()}-${index}`}
onRemove={_delPrev}
typeOpts={typeOpts.current}
value={value}
/>
))}
{added.map((value, index) => (
<NewProxy
index={index}
key={`${value.toString()}-${index}`}
onChangeAccount={_changeProxyAccount}
onChangeType={_changeProxyType}
onRemove={_delProxy}
proxiedAccount={proxiedAccount}
typeOpts={typeOpts.current}
value={value}
/>
))}
<Button.Group>
<Button
icon='plus'
label={t<string>('Add proxy')}
onClick={_addProxy}
/>
</Button.Group>
</Modal.Columns>
<Modal.Columns hint={t<string>('The amount that is reserved for the proxy based on the base deposit and number of proxies')}>
<InputBalance
defaultValue={reservedAmount}
isDisabled
label={t<string>('reserved balance')}
/>
</Modal.Columns>
<Modal.Columns>
<BatchWarning />
</Modal.Columns>
</Modal.Content>
<Modal.Actions>
{existing.length !== 0 && (
<TxButton
accountId={proxiedAccount}
icon='trash-alt'
label={t<string>('Clear all')}
onStart={onClose}
tx={api.tx.proxy.removeProxies}
/>
)}
<TxButton
accountId={proxiedAccount}
extrinsic={extrinsics}
icon='sign-in-alt'
isDisabled={isSameAdd || (!batchPrevious.length && !batchAdded.length)}
onStart={onClose}
/>
</Modal.Actions>
</Modal>
);
}
export default React.memo(styled(ProxyOverview)`
.proxy-container {
display: grid;
grid-column-gap: 0.5rem;
grid-template-columns: minmax(0, 1fr) auto;
margin-bottom: 1rem;
.input-column {
grid-column: 1;
}
.buttons-column {
grid-column: 2;
padding-top: 0.3rem;
}
}
`); | the_stack |
import Debug from '@prisma/debug'
import { fixBinaryTargets, getOriginalBinaryTargetsValue, printGeneratorConfig } from '@prisma/engine-core'
import { enginesVersion, getCliQueryEngineBinaryType } from '@prisma/engines'
import type { DownloadOptions } from '@prisma/fetch-engine'
import { download } from '@prisma/fetch-engine'
import type { BinaryTargetsEnvValue, EngineType, GeneratorConfig, GeneratorOptions } from '@prisma/generator-helper'
import type { Platform } from '@prisma/get-platform'
import { getPlatform, platforms } from '@prisma/get-platform'
import chalk from 'chalk'
import fs from 'fs'
import pMap from 'p-map'
import path from 'path'
import { getConfig, getDMMF } from '..'
import { Generator } from '../Generator'
import { pick } from '../pick'
import type { GeneratorPaths } from '../predefinedGeneratorResolvers'
import { predefinedGeneratorResolvers } from '../predefinedGeneratorResolvers'
import { resolveOutput } from '../resolveOutput'
import { extractPreviewFeatures } from '../utils/extractPreviewFeatures'
import { mapPreviewFeatures } from '../utils/mapPreviewFeatures'
import { missingDatasource } from '../utils/missingDatasource'
import { missingModelMessage, missingModelMessageMongoDB } from '../utils/missingGeneratorMessage'
import { parseBinaryTargetsEnvValue, parseEnvValue } from '../utils/parseEnvValue'
import { printConfigWarnings } from '../utils/printConfigWarnings'
import { getEngineVersionForGenerator } from './utils/getEngineVersionForGenerator'
import { binaryTypeToEngineType } from './utils/binaryTypeToEngineType'
import { getBinaryPathsByVersion } from './utils/getBinaryPathsByVersion'
import { checkFeatureFlags } from './utils/check-feature-flags/checkFeatureFlags'
const debug = Debug('prisma:getGenerators')
export type ProviderAliases = { [alias: string]: GeneratorPaths }
type BinaryPathsOverride = {
[P in EngineType]?: string
}
// From https://github.com/prisma/prisma/blob/eb4563aea6fb6e593ae48106a74f716ce3dc6752/packages/cli/src/Generate.ts#L167-L172
// versions are set like:
// version: enginesVersion,
// cliVersion: pkg.version,
export type GetGeneratorOptions = {
schemaPath: string
providerAliases?: ProviderAliases
cliVersion?: string
version?: string
printDownloadProgress?: boolean
baseDir?: string // useful in tests to resolve the base dir from which `output` is resolved
overrideGenerators?: GeneratorConfig[]
skipDownload?: boolean
binaryPathsOverride?: BinaryPathsOverride
}
/**
* Makes sure that all generators have the binaries they deserve and returns a
* `Generator` class per generator defined in the schema.prisma file.
* In other words, this is basically a generator factory function.
* @param schemaPath Path to schema.prisma
* @param aliases Aliases like `prisma-client-js` -> `node_modules/@prisma/client/generator-build/index.js`
*/
export async function getGenerators({
schemaPath,
providerAliases: aliases, // do you get the pun?
version,
cliVersion,
printDownloadProgress,
baseDir = path.dirname(schemaPath),
overrideGenerators,
skipDownload,
binaryPathsOverride,
}: GetGeneratorOptions): Promise<Generator[]> {
if (!schemaPath) {
throw new Error(`schemaPath for getGenerators got invalid value ${schemaPath}`)
}
if (!fs.existsSync(schemaPath)) {
throw new Error(`${schemaPath} does not exist`)
}
const platform = await getPlatform()
const queryEngineBinaryType = getCliQueryEngineBinaryType()
const queryEngineType = binaryTypeToEngineType(queryEngineBinaryType)
let prismaPath: string | undefined = binaryPathsOverride?.[queryEngineType]
// overwrite query engine if the version is provided
if (version && !prismaPath) {
const potentialPath = eval(`require('path').join(__dirname, '..')`)
// for pkg we need to make an exception
if (!potentialPath.startsWith('/snapshot/')) {
const downloadParams: DownloadOptions = {
binaries: {
[queryEngineBinaryType]: potentialPath,
},
binaryTargets: [platform],
showProgress: false,
version,
skipDownload,
}
const binaryPathsWithEngineType = await download(downloadParams)
prismaPath = binaryPathsWithEngineType[queryEngineBinaryType]![platform]
}
}
const datamodel = fs.readFileSync(schemaPath, 'utf-8')
const config = await getConfig({
datamodel,
datamodelPath: schemaPath,
prismaPath,
ignoreEnvVarErrors: true,
})
if (config.datasources.length === 0) {
throw new Error(missingDatasource)
}
printConfigWarnings(config.warnings)
// TODO: This needs a better abstraction, but we don't have any better right now
const previewFeatures = mapPreviewFeatures(extractPreviewFeatures(config))
const dmmf = await getDMMF({
datamodel,
datamodelPath: schemaPath,
prismaPath,
previewFeatures,
})
if (dmmf.datamodel.models.length === 0) {
// MongoDB needs extras for @id: @map("_id") @db.ObjectId
if (config.datasources.some((d) => d.provider === 'mongodb')) {
throw new Error(missingModelMessageMongoDB)
}
throw new Error(missingModelMessage)
}
checkFeatureFlags(config)
const generatorConfigs = overrideGenerators || config.generators
await validateGenerators(generatorConfigs)
const runningGenerators: Generator[] = []
try {
// 1. Get all generators
const generators = await pMap(
generatorConfigs,
async (generator, index) => {
let generatorPath = parseEnvValue(generator.provider)
let paths: GeneratorPaths | undefined
// as of now mostly used by studio
const providerValue = parseEnvValue(generator.provider)
if (aliases && aliases[providerValue]) {
generatorPath = aliases[providerValue].generatorPath
paths = aliases[providerValue]
} else if (predefinedGeneratorResolvers[providerValue]) {
paths = await predefinedGeneratorResolvers[providerValue](baseDir, cliVersion)
generatorPath = paths.generatorPath
}
const generatorInstance = new Generator(generatorPath, generator, paths?.isNode)
await generatorInstance.init()
// resolve output path
if (generator.output) {
generator.output = {
value: path.resolve(baseDir, parseEnvValue(generator.output)),
fromEnvVar: null,
}
generator.isCustomOutput = true
} else if (paths) {
generator.output = {
value: paths.outputPath,
fromEnvVar: null,
}
} else {
if (!generatorInstance.manifest || !generatorInstance.manifest.defaultOutput) {
throw new Error(
`Can't resolve output dir for generator ${chalk.bold(generator.name)} with provider ${chalk.bold(
generator.provider,
)}.
The generator needs to either define the \`defaultOutput\` path in the manifest or you need to define \`output\` in the datamodel.prisma file.`,
)
}
generator.output = {
value: await resolveOutput({
defaultOutput: generatorInstance.manifest.defaultOutput,
baseDir,
}),
fromEnvVar: 'null',
}
}
const options: GeneratorOptions = {
datamodel,
datasources: config.datasources,
generator,
dmmf,
otherGenerators: skipIndex(generatorConfigs, index),
schemaPath,
version: version || enginesVersion, // this version makes no sense anymore and should be ignored
}
// we set the options here a bit later after instantiating the Generator,
// as we need the generator manifest to resolve the `output` dir
generatorInstance.setOptions(options)
runningGenerators.push(generatorInstance)
return generatorInstance
},
{
stopOnError: false, // needed so we can first make sure all generators are created properly, then cleaned up properly
},
)
// 2. Check, if all required generators are there.
// Generators can say in their "requiresGenerators" property in the manifest, which other generators they depend on
// This has mostly been introduced for 3rd party generators, which rely on `prisma-client-js`.
const generatorProviders: string[] = generatorConfigs.map((g) => parseEnvValue(g.provider))
for (const g of generators) {
if (g?.manifest?.requiresGenerators && g?.manifest?.requiresGenerators.length > 0) {
for (const neededGenerator of g?.manifest?.requiresGenerators) {
if (!generatorProviders.includes(neededGenerator)) {
throw new Error(
`Generator "${g.manifest.prettyName}" requires generator "${neededGenerator}", but it is missing in your schema.prisma.
Please add it to your schema.prisma:
generator gen {
provider = "${neededGenerator}"
}
`,
)
}
}
}
}
// 3. Download all binaries and binary targets needed
const neededVersions = Object.create(null)
for (const g of generators) {
if (
g.manifest?.requiresEngines &&
Array.isArray(g.manifest?.requiresEngines) &&
g.manifest.requiresEngines.length > 0
) {
const neededVersion = getEngineVersionForGenerator(g.manifest, version)
if (!neededVersions[neededVersion]) {
neededVersions[neededVersion] = { engines: [], binaryTargets: [] }
}
for (const engine of g.manifest?.requiresEngines) {
if (!neededVersions[neededVersion].engines.includes(engine)) {
neededVersions[neededVersion].engines.push(engine)
}
}
const generatorBinaryTargets = g.options?.generator?.binaryTargets
if (generatorBinaryTargets && generatorBinaryTargets.length > 0) {
const binaryTarget0 = generatorBinaryTargets[0]
// If set from env var, there is only one item
// and we need to read the env var
if (binaryTarget0.fromEnvVar !== null) {
const parsedBinaryTargetsEnvValue = parseBinaryTargetsEnvValue(binaryTarget0)
// remove item and replace with parsed values
// value is an array
// so we create one new iteam for each element in the array
generatorBinaryTargets.shift()
if (Array.isArray(parsedBinaryTargetsEnvValue)) {
for (const platformName of parsedBinaryTargetsEnvValue) {
generatorBinaryTargets.push({
fromEnvVar: binaryTarget0.fromEnvVar,
value: platformName,
})
}
} else {
generatorBinaryTargets.push({
fromEnvVar: binaryTarget0.fromEnvVar,
value: parsedBinaryTargetsEnvValue,
})
}
}
for (const binaryTarget of generatorBinaryTargets) {
if (binaryTarget.value === 'native') {
binaryTarget.value = platform
}
if (!neededVersions[neededVersion].binaryTargets.find((object) => object.value === binaryTarget.value)) {
neededVersions[neededVersion].binaryTargets.push(binaryTarget)
}
}
}
}
}
debug('neededVersions', JSON.stringify(neededVersions, null, 2))
const binaryPathsByVersion = await getBinaryPathsByVersion({
neededVersions,
platform,
version,
printDownloadProgress,
skipDownload,
binaryPathsOverride,
})
for (const generator of generators) {
if (generator.manifest && generator.manifest.requiresEngines) {
const engineVersion = getEngineVersionForGenerator(generator.manifest, version)
const binaryPaths = binaryPathsByVersion[engineVersion]
// pick only the engines that we need for this generator
const generatorBinaryPaths = pick(binaryPaths, generator.manifest.requiresEngines)
debug({ generatorBinaryPaths })
generator.setBinaryPaths(generatorBinaryPaths)
// in case cli engine version !== client engine version
// we need to re-generate the dmmf and pass it in to the generator
if (
engineVersion !== version &&
generator.options &&
generator.manifest.requiresEngines.includes(queryEngineType) &&
generatorBinaryPaths[queryEngineType] &&
generatorBinaryPaths[queryEngineType]?.[platform]
) {
const customDmmf = await getDMMF({
datamodel,
datamodelPath: schemaPath,
prismaPath: generatorBinaryPaths[queryEngineType]?.[platform],
previewFeatures,
})
const options = { ...generator.options, dmmf: customDmmf }
debug('generator.manifest.prettyName', generator.manifest.prettyName)
debug('options', options)
debug('options.generator.binaryTargets', options.generator.binaryTargets)
generator.setOptions(options)
}
}
}
return generators
} catch (e) {
// make sure all generators that are already running are being stopped
runningGenerators.forEach((g) => g.stop())
throw e
}
}
type NeededVersions = {
[key: string]: {
engines: EngineType[]
binaryTargets: BinaryTargetsEnvValue[]
}
}
export type GetBinaryPathsByVersionInput = {
neededVersions: NeededVersions
platform: Platform
version?: string
printDownloadProgress?: boolean
skipDownload?: boolean
binaryPathsOverride?: BinaryPathsOverride
}
/**
* Shortcut for getGenerators, if there is only one generator defined. Useful for testing.
* @param schemaPath path to schema.prisma
* @param aliases Aliases like `photonjs` -> `node_modules/photonjs/gen.js`
* @param version Version of the binary, commit hash of https://github.com/prisma/prisma-engine/commits/master
* @param printDownloadProgress `boolean` to print download progress or not
*/
export async function getGenerator(options: GetGeneratorOptions): Promise<Generator> {
const generators = await getGenerators(options)
return generators[0]
}
export function skipIndex<T = any>(arr: T[], index: number): T[] {
return [...arr.slice(0, index), ...arr.slice(index + 1)]
}
export const knownBinaryTargets: Platform[] = [...platforms, 'native']
const oldToNewBinaryTargetsMapping = {
'linux-glibc-libssl1.0.1': 'debian-openssl-1.0.x',
'linux-glibc-libssl1.0.2': 'debian-openssl-1.0.x',
'linux-glibc-libssl1.1.0': 'debian-openssl1.1.x',
}
async function validateGenerators(generators: GeneratorConfig[]): Promise<void> {
const platform = await getPlatform()
for (const generator of generators) {
if (parseEnvValue(generator.provider) === 'photonjs') {
throw new Error(`Oops! Photon has been renamed to Prisma Client. Please make the following adjustments:
1. Rename ${chalk.red('provider = "photonjs"')} to ${chalk.green(
'provider = "prisma-client-js"',
)} in your ${chalk.bold('schema.prisma')} file.
2. Replace your ${chalk.bold('package.json')}'s ${chalk.red('@prisma/photon')} dependency to ${chalk.green(
'@prisma/client',
)}
3. Replace ${chalk.red("import { Photon } from '@prisma/photon'")} with ${chalk.green(
"import { PrismaClient } from '@prisma/client'",
)} in your code.
4. Run ${chalk.green('prisma generate')} again.
`)
}
if (generator.config.platforms) {
throw new Error(
`The \`platforms\` field on the generator definition is deprecated. Please rename it to \`binaryTargets\`.`,
)
}
if (generator.config.pinnedBinaryTargets) {
throw new Error(
`The \`pinnedBinaryTargets\` field on the generator definition is deprecated.
Please use the PRISMA_QUERY_ENGINE_BINARY env var instead to pin the binary target.`,
)
}
if (generator.binaryTargets) {
const binaryTargets =
generator.binaryTargets && generator.binaryTargets.length > 0
? generator.binaryTargets
: [{ fromEnvVar: null, value: 'native' }]
const resolvedBinaryTargets: string[] = binaryTargets
.flatMap((object) => parseBinaryTargetsEnvValue(object))
.map((p) => (p === 'native' ? platform : p))
for (const resolvedBinaryTarget of resolvedBinaryTargets) {
if (oldToNewBinaryTargetsMapping[resolvedBinaryTarget]) {
throw new Error(
`Binary target ${chalk.red.bold(resolvedBinaryTarget)} is deprecated. Please use ${chalk.green.bold(
oldToNewBinaryTargetsMapping[resolvedBinaryTarget],
)} instead.`,
)
}
if (!knownBinaryTargets.includes(resolvedBinaryTarget as Platform)) {
throw new Error(
`Unknown binary target ${chalk.red(resolvedBinaryTarget)} in generator ${chalk.bold(generator.name)}.
Possible binaryTargets: ${chalk.greenBright(knownBinaryTargets.join(', '))}`,
)
}
}
// Only show warning if resolvedBinaryTargets
// is missing current platform
if (!resolvedBinaryTargets.includes(platform)) {
const originalBinaryTargetsConfig = getOriginalBinaryTargetsValue(generator.binaryTargets)
if (generator) {
console.log(`${chalk.yellow('Warning:')} Your current platform \`${chalk.bold(
platform,
)}\` is not included in your generator's \`binaryTargets\` configuration ${JSON.stringify(
originalBinaryTargetsConfig,
)}.
To fix it, use this generator config in your ${chalk.bold('schema.prisma')}:
${chalk.greenBright(
printGeneratorConfig({
...generator,
binaryTargets: fixBinaryTargets(generator.binaryTargets, platform),
}),
)}
${chalk.gray(
`Note, that by providing \`native\`, Prisma Client automatically resolves \`${platform}\`.
Read more about deploying Prisma Client: ${chalk.underline(
'https://github.com/prisma/prisma/blob/main/docs/core/generators/prisma-client-js.md',
)}`,
)}\n`)
} else {
console.log(
`${chalk.yellow('Warning')} The binaryTargets ${JSON.stringify(
originalBinaryTargetsConfig,
)} don't include your local platform ${platform}, which you can also point to with \`native\`.
In case you want to fix this, you can provide ${chalk.greenBright(
`binaryTargets: ${JSON.stringify(['native', ...(binaryTargets || [])])}`,
)} in the schema.prisma file.`,
)
}
}
}
}
} | the_stack |
import React from 'react';
import { ConfigProvider, Table, Button, DatePicker, Form, Icon, Switch, Pagination, Dialog, Input, Select } from '@alicloud/console-components';
import Actions, { LinkButton } from '@alicloud/console-components-actions';
import { withRouter } from 'react-router-dom';
import Page from '@/components/Page';
import { GlobalProps } from '@/module';
import styled, { css } from 'styled-components';
import getData, { GlobalSessionParam } from '@/service/transactionInfo';
import PropTypes from 'prop-types';
import moment from 'moment';
import './index.scss';
const { RangePicker } = DatePicker;
const FormItem = Form.Item;
type StatusType = {
label: string,
value: number,
iconType: string,
iconColor: string,
}
type TransactionInfoState = {
list: Array<any>;
total: number;
loading: boolean;
branchSessionDialogVisible: boolean;
currentBranchSession: Array<any>;
globalSessionParam : GlobalSessionParam;
}
const statusList:Array<StatusType> = [
{
label: 'AsyncCommitting',
value: 8,
iconType: 'ellipsis',
iconColor: 'rgb(3, 193, 253)',
},
{
label: 'Begin',
value: 1,
iconType: 'ellipsis',
iconColor: 'rgb(3, 193, 253)',
},
{
label: 'Committing',
value: 2,
iconType: 'ellipsis',
iconColor: 'rgb(3, 193, 253)',
},
{
label: 'CommitRetrying',
value: 3,
iconType: 'ellipsis',
iconColor: 'rgb(3, 193, 253)',
},
{
label: 'Committed',
value: 9,
iconType: 'success',
iconColor: '#1DC11D',
},
{
label: 'CommitFailed',
value: 10,
iconType: 'error',
iconColor: '#FF3333',
},
{
label: 'CommitRetryTimeout',
value: 16,
iconType: 'error',
iconColor: '#FF3333',
},
{
label: 'Finished',
value: 15,
iconType: 'success',
iconColor: '#1DC11D',
},
{
label: 'Rollbacking',
value: 4,
iconType: 'ellipsis',
iconColor: 'rgb(3, 193, 253)',
},
{
label: 'RollbackRetrying',
value: 5,
iconType: 'ellipsis',
iconColor: 'rgb(3, 193, 253)',
},
{
label: 'Rollbacked',
value: 11,
iconType: 'error',
iconColor: '#FF3333',
},
{
label: 'RollbackFailed',
value: 12,
iconType: 'error',
iconColor: '#FF3333',
},
{
label: 'RollbackRetryTimeout',
value: 17,
iconType: 'error',
iconColor: '#FF3333',
},
{
label: 'TimeoutRollbacking',
value: 6,
iconType: 'ellipsis',
iconColor: 'rgb(3, 193, 253)',
},
{
label: 'TimeoutRollbackRetrying',
value: 7,
iconType: 'ellipsis',
iconColor: 'rgb(3, 193, 253)',
},
{
label: 'TimeoutRollbacked',
value: 13,
iconType: 'error',
iconColor: '#FF3333',
},
{
label: 'TimeoutRollbackFailed',
value: 14,
iconType: 'error',
iconColor: '#FF3333',
},
{
label: 'UnKnown',
value: 0,
iconType: 'warning',
iconColor: '#FFA003',
},
];
const branchSessionStatusList:Array<StatusType> = [
{
label: 'UnKnown',
value: 0,
iconType: 'warning',
iconColor: '#FFA003',
},
{
label: 'Registered',
value: 1,
iconType: 'ellipsis',
iconColor: 'rgb(3, 193, 253)',
},
{
label: 'PhaseOne_Done',
value: 2,
iconType: 'ellipsis',
iconColor: 'rgb(3, 193, 253)',
},
{
label: 'PhaseOne_Failed',
value: 3,
iconType: 'error',
iconColor: '#FF3333',
},
{
label: 'PhaseOne_Timeout',
value: 4,
iconType: 'error',
iconColor: '#FF3333',
},
{
label: 'PhaseTwo_Committed',
value: 5,
iconType: 'success',
iconColor: '#1DC11D',
},
{
label: 'PhaseTwo_CommitFailed_Retryable',
value: 6,
iconType: 'ellipsis',
iconColor: 'rgb(3, 193, 253)',
},
{
label: 'PhaseTwo_CommitFailed_Unretryable',
value: 7,
iconType: 'error',
iconColor: '#FF3333',
},
{
label: 'PhaseTwo_Rollbacked',
value: 8,
iconType: 'error',
iconColor: '#FF3333',
},
{
label: 'PhaseTwo_RollbackFailed_Retryable',
value: 9,
iconType: 'ellipsis',
iconColor: 'rgb(3, 193, 253)',
},
{
label: 'PhaseTwo_RollbackFailed_Unretryable',
value: 10,
iconType: 'error',
iconColor: '#FF3333',
},
];
class TransactionInfo extends React.Component<GlobalProps, TransactionInfoState> {
static displayName = 'TransactionInfo';
static propTypes = {
locale: PropTypes.object,
history: PropTypes.object,
};
state: TransactionInfoState = {
list: [],
total: 0,
loading: false,
branchSessionDialogVisible: false,
currentBranchSession: [],
globalSessionParam: {
withBranch: false,
pageSize: 10,
pageNum: 1,
},
};
componentDidMount = () => {
// search once by default
this.search();
}
resetSearchFilter = () => {
this.setState({
globalSessionParam: {
withBranch: false,
// pagination info don`t reset
pageSize: this.state.globalSessionParam.pageSize,
pageNum: this.state.globalSessionParam.pageNum,
},
});
}
search = () => {
this.setState({ loading: true });
getData(this.state.globalSessionParam).then(data => {
// if the result set is empty, set the page number to go back to the first page
if (data.total === 0) {
this.setState({
list: [],
total: 0,
loading: false,
globalSessionParam: Object.assign(this.state.globalSessionParam,
{ pageNum: 1 }),
});
return;
}
// format time
data.data.forEach((element: any) => {
element.beginTime = (element.beginTime == null || element.beginTime === '') ? null : moment(Number(element.beginTime)).format('YYYY-MM-DD HH:mm:ss');
});
this.setState({
list: data.data,
total: data.total,
loading: false,
});
}).catch(err => {
this.setState({ loading: false });
});
}
searchFilterOnChange = (key:string, val:string) => {
this.setState({
globalSessionParam: Object.assign(this.state.globalSessionParam,
{ [key]: val }),
});
}
branchSessionSwitchOnChange = (checked: boolean, e: any) => {
this.setState({
globalSessionParam: Object.assign(this.state.globalSessionParam,
{ withBranch: checked }),
});
if (checked) {
// if checked, do search for load branch sessions
this.search();
}
}
createTimeOnChange = (value: Array<any>) => {
// timestamp(milliseconds)
const timeStart = value[0] == null ? null : moment(value[0]).unix() * 1000;
const timeEnd = value[1] == null ? null : moment(value[1]).unix() * 1000;
this.setState({
globalSessionParam: Object.assign(this.state.globalSessionParam,
{ timeStart, timeEnd }),
});
}
statusCell = (val: number, index: number, record: any) => {
let icon;
statusList.forEach((status: StatusType) => {
if (status.value === val) {
icon = (
<span><Icon type={status.iconType} style={{ color: status.iconColor, marginRight: '10px' }} />{status.label}</span>
);
}
});
// Unmatched
if (icon === undefined) {
icon = (<span>{val}</span>);
}
return icon;
}
branchSessionStatusCell = (val: number, index: number, record: any) => {
let icon;
branchSessionStatusList.forEach((status: StatusType) => {
if (status.value === val) {
icon = (
<span><Icon type={status.iconType} style={{ color: status.iconColor, marginRight: '10px' }} />{status.label}</span>
);
}
});
// Unmatched
if (icon === undefined) {
icon = (<span>{val}</span>);
}
return icon;
}
operateCell = (val: string, index: number, record: any) => {
const { locale = {}, history } = this.props;
const {
showBranchSessionTitle,
showGlobalLockTitle,
} = locale;
return (
<Actions style={{ width: '200px' }}>
{/* {when withBranch false, hide 'View branch session' button} */}
{this.state.globalSessionParam.withBranch ? (
<LinkButton
onClick={this.showBranchSessionDialog(val, index, record)}
>
{showBranchSessionTitle}
</LinkButton>
) : null}
<LinkButton
onClick={() => {
history.push({
pathname: '/GlobalLockInfo',
// @ts-ignore
query: { xid: record.xid },
});
}}
>
{showGlobalLockTitle}
</LinkButton>
</Actions>);
}
branchSessionDialogOperateCell = (val: string, index: number, record: any) => {
const { locale = {}, history } = this.props;
const {
showGlobalLockTitle,
} = locale;
return (
<Actions style={{ width: '80px' }}>
<LinkButton
onClick={() => {
history.push({
pathname: '/GlobalLockInfo',
// @ts-ignore
query: { xid: record.xid },
});
}}
>
{showGlobalLockTitle}
</LinkButton>
</Actions>);
}
paginationOnChange = (current: number, e: {}) => {
this.setState({
globalSessionParam: Object.assign(this.state.globalSessionParam,
{ pageNum: current }),
});
this.search();
}
paginationOnPageSizeChange = (pageSize: number) => {
this.setState({
globalSessionParam: Object.assign(this.state.globalSessionParam,
{ pageSize }),
});
this.search();
}
showBranchSessionDialog = (val: string, index: number, record: any) => () => {
this.setState({
branchSessionDialogVisible: true,
currentBranchSession: record.branchSessionVOs,
});
}
closeBranchSessionDialog = () => {
this.setState({
branchSessionDialogVisible: false,
currentBranchSession: [],
});
}
render() {
const { locale = {} } = this.props;
const { title, subTitle, createTimeLabel,
selectFilerPlaceholder,
inputFilterPlaceholder,
branchSessionSwitchLabel,
resetButtonLabel,
searchButtonLabel,
operateTitle,
branchSessionDialogTitle,
} = locale;
return (
<Page
title={title}
breadcrumbs={[
{
link: '/',
text: title,
},
{
text: subTitle,
},
]}
>
{/* search form */}
<Form inline labelAlign="left">
{/* {create time picker} */}
<FormItem name="createTime" label={createTimeLabel}>
<RangePicker
onChange={this.createTimeOnChange}
onOk={this.createTimeOnChange}
showTime
format="YYYY-MM-DD"
/>
</FormItem>
{/* {search filters} */}
<FormItem name="xid" label="xid">
<Input
placeholder={inputFilterPlaceholder}
onChange={(value: string) => { this.searchFilterOnChange('xid', value); }}
/>
</FormItem>
<FormItem name="applicationId" label="applicationId">
<Input
placeholder={inputFilterPlaceholder}
onChange={(value: string) => { this.searchFilterOnChange('applicationId', value); }}
/>
</FormItem>
<FormItem name="status" label="status">
<Select
hasClear
placeholder={selectFilerPlaceholder}
onChange={(value: string) => { this.searchFilterOnChange('status', value); }}
dataSource={statusList}
/>
</FormItem>
{/* {branch session switch} */}
<FormItem name="withBranch" label={branchSessionSwitchLabel}>
<Switch
onChange={this.branchSessionSwitchOnChange}
checked={this.state.globalSessionParam.withBranch}
/>
</FormItem>
{/* {reset search filter button} */}
<FormItem>
<Form.Reset onClick={this.resetSearchFilter}>
<Icon type="redo" />{resetButtonLabel}
</Form.Reset>
</FormItem>
{/* {search button} */}
<FormItem>
<Form.Submit onClick={this.search}>
<Icon type="search" />{searchButtonLabel}
</Form.Submit>
</FormItem>
</Form>
{/* global session table */}
<div>
<Table dataSource={this.state.list} loading={this.state.loading}>
<Table.Column title="xid" dataIndex="xid" />
<Table.Column title="transactionId" dataIndex="transactionId" />
<Table.Column title="applicationId" dataIndex="applicationId" />
<Table.Column title="transactionServiceGroup" dataIndex="transactionServiceGroup" />
<Table.Column title="transactionName" dataIndex="transactionName" />
<Table.Column
title="status"
dataIndex="status"
cell={this.statusCell}
/>
<Table.Column title="timeout" dataIndex="timeout" />
<Table.Column title="beginTime" dataIndex="beginTime" />
<Table.Column title="applicationData" dataIndex="applicationData" />
<Table.Column
title={operateTitle}
cell={this.operateCell}
/>
</Table>
<Pagination
total={this.state.total}
defaultCurrent={1}
current={this.state.globalSessionParam.pageNum}
onChange={this.paginationOnChange}
pageSize={this.state.globalSessionParam.pageSize}
pageSizeSelector="dropdown"
pageSizeList={[10, 20, 30, 40, 50]}
onPageSizeChange={this.paginationOnPageSizeChange}
/>
</div>
{/* branch session dialog */}
<Dialog visible={this.state.branchSessionDialogVisible} title={branchSessionDialogTitle} footer={false} onClose={this.closeBranchSessionDialog} style={{ overflowX: 'auto' }}>
<Table dataSource={this.state.currentBranchSession}>
<Table.Column title="transactionId" dataIndex="transactionId" />
<Table.Column title="branchId" dataIndex="branchId" />
<Table.Column title="resourceGroupId" dataIndex="resourceGroupId" />
<Table.Column title="branchType" dataIndex="branchType" />
<Table.Column
title="status"
dataIndex="status"
cell={this.branchSessionStatusCell}
/>
<Table.Column title="resourceId" dataIndex="resourceId" />
<Table.Column title="clientId" dataIndex="clientId" />
<Table.Column title="applicationData" dataIndex="applicationData" />
<Table.Column
title={operateTitle}
cell={this.branchSessionDialogOperateCell}
/>
</Table>
</Dialog>
</Page>
);
}
}
export default withRouter(ConfigProvider.config(TransactionInfo, {})); | the_stack |
import { ERRORS } from "@algo-builder/web";
import { assert } from "chai";
import * as path from "path";
import * as sinon from "sinon";
import { types } from "../../../src/config";
import { BuilderContext } from "../../../src/internal/context";
import { Environment } from "../../../src/internal/core/runtime-environment";
import { TasksDSL } from "../../../src/internal/core/tasks/dsl";
import { resetBuilderContext } from "../../../src/internal/reset";
import {
ParamDefinition,
ResolvedConfig,
RuntimeArgs,
RuntimeEnv,
TasksMap
} from "../../../src/types";
import {
expectBuilderError,
expectBuilderErrorAsync
} from "../../helpers/errors";
import { useFixtureProject } from "../../helpers/project";
describe("Environment", () => {
const config: ResolvedConfig = {
networks: {
localNet: {
accounts: [],
chainName: "local-chain-name",
host: "local-net",
port: 8080
},
default: {
accounts: [],
chainName: "default-chain-name",
host: "default-net:8080",
port: 8080
}
}
};
const args: RuntimeArgs = {
network: "localNet",
showStackTraces: false,
version: false,
help: false,
verbose: false
};
let tasks: TasksMap;
let env: RuntimeEnv;
let dsl: TasksDSL;
beforeEach(() => {
const ctx = BuilderContext.createBuilderContext();
dsl = ctx.tasksDSL;
dsl.task("example", async (_ret) => {
return 27;
});
dsl
.task("complexExampleTask", "a complex example task")
.addPositionalParam(
"positionalRequiredStringParam",
"a positional required type 'string' param",
undefined,
types.string,
false
)
.addOptionalPositionalParam(
"posOptJsonParamWithDefault",
"a positional optional type 'json' param",
{ a: 1 },
types.json
)
.setAction(async () => 42);
dsl
.task("taskWithMultipleTypesParams", "a task with many types params")
.addFlag("flagParam", "some flag")
.addOptionalParam("optIntParam", "an opt int param", 123, types.int)
.addOptionalParam("optFloatParam", "an opt float param", 2.5, types.float)
.addOptionalParam(
"optFileParam",
"an opt file param",
undefined,
types.inputFile
)
.addOptionalParam(
"optStringParam",
"an opt string param",
"some default",
types.string
)
.addOptionalVariadicPositionalParam(
"variadicOptStrParam",
"an opt variadic 'str' param",
[],
types.string
)
.setAction(async () => 42);
tasks = ctx.tasksDSL.getTaskDefinitions();
env = new Environment(config, args, tasks, [], true);
ctx.setRuntimeEnv(env);
});
afterEach(() => resetBuilderContext());
describe("Environment", () => {
it("should create an environment", () => {
assert.deepEqual(env.config, config);
assert.isDefined(env.tasks);
assert.isDefined(env.network);
});
it("should run a task correctly", async () => {
const ret = await env.run("example");
assert.equal(ret, 27);
});
describe("run task arguments validation", () => {
it("should throw on missing required argument", async () => {
const taskName = "complexExampleTask";
const requiredParamName = "positionalRequiredStringParam";
const task = env.tasks[taskName];
const param = task.positionalParamDefinitions.find(
({ name }) => name === requiredParamName
);
assert.isDefined(param);
// task runs with required param present
const taskResult = await env.run(taskName, {
[requiredParamName]: "some value"
});
assert.isDefined(taskResult);
// same task throws with required param missing
await expectBuilderErrorAsync(async () => {
await env.run("complexExampleTask", {});
}, ERRORS.ARGUMENTS.MISSING_TASK_ARGUMENT);
});
it("should use default value on missing optional argument with default param", async () => {
const taskName = "complexExampleTask";
const optParamName = "posOptJsonParamWithDefault";
const task = env.tasks[taskName];
const param = task.positionalParamDefinitions.find(
({ name }) => name === optParamName
) as ParamDefinition<any>;
assert.isDefined(param);
// specified arg value, should be different from the default for this test
const paramValue = { value: 20 };
const { defaultValue } = param;
assert.notEqual(defaultValue, paramValue);
const taskMinimalArgs = {
positionalRequiredStringParam: "a string value"
};
const taskArgumentsSpecified = {
...taskMinimalArgs,
[optParamName]: paramValue
};
// setup task action spy
const taskActionSpy = sinon.spy(task, "action");
// task should run with *specified* value on defined param argument
await env.run(taskName, taskArgumentsSpecified);
// task should run with *default* value on empty param argument
await env.run(taskName, taskMinimalArgs);
// assertions
const [
taskWithSpecifiedArgsCall,
taskWithDefaultArgsCall
] = taskActionSpy.getCalls();
assert.equal(
taskWithSpecifiedArgsCall.args[0][optParamName],
paramValue,
"should include specified param value in task action call"
);
assert.equal(
taskWithDefaultArgsCall.args[0][optParamName],
defaultValue,
"should include default param value in task action call"
);
});
it("should validate argument type matches the param type", async () => {
const taskName = "taskWithMultipleTypesParams";
const typesValidationTestCases = {
flagParam: { valid: true, invalid: 1 },
optIntParam: { valid: 10, invalid: 1.2 },
optFloatParam: { valid: 1.2, invalid: NaN },
optStringParam: { valid: "a string", invalid: 123 },
optFileParam: { valid: __filename, invalid: __dirname },
variadicOptStrParam: { valid: ["a", "b"], invalid: ["a", 1] }
};
const expectTaskRunsSuccesfully = async (
taskNameToRun: string,
taskArguments: any
): Promise<void> => {
const argsString = JSON.stringify(taskArguments);
try {
await env.run(taskNameToRun, taskArguments);
} catch (error) {
if (error instanceof Error) {
assert.fail(
error,
undefined,
`Should not throw error task ${taskNameToRun} with args ${argsString}. Error message: ${
String(error.message || error)
}`
);
}
console.error("An unexpected error occurred:", error);
}
};
const expectTaskRunsWithError = async (
taskNameToRun: string,
taskArguments: any
): Promise<void> => {
await expectBuilderErrorAsync(async () => {
await env.run(taskNameToRun, taskArguments);
console.error(
`should have thrown task run: '${taskNameToRun}' with arguments: `,
taskArguments
);
}, ERRORS.ARGUMENTS.INVALID_VALUE_FOR_TYPE);
};
for (const [paramName, { valid, invalid }] of Object.entries(
typesValidationTestCases
)) {
// should run task successfully with valid type arguments
const validTaskArguments = { [paramName]: valid };
await expectTaskRunsSuccesfully(taskName, validTaskArguments);
// should throw error with argument of type not same type as the param type
const invalidTaskArguments = { [paramName]: invalid };
await expectTaskRunsWithError(taskName, invalidTaskArguments);
}
});
});
it("should fail trying to run a non existent task", () => {
env.run("invalid").catch((err) => {
assert.equal(err.number, ERRORS.ARGUMENTS.UNRECOGNIZED_TASK.number);
});
});
it("should clean global state after task execution", async () => {
assert.equal(await env.run("example"), 27);
const globalAsAny = global as any;
assert.isUndefined(globalAsAny.runSuper);
assert.isUndefined(globalAsAny.env);
});
it("should run overridden task correctly", async () => {
dsl.task("example", "description", async (_ret) => {
return 28;
});
tasks = dsl.getTaskDefinitions();
const localEnv = new Environment(config, args, tasks, [], true);
assert.equal(await localEnv.run("example"), 28);
});
it("Should preserve the injected env after running a sub-task", async () => {
dsl.task(
"with-subtask",
"description",
async (taskName, { run, config: theConfig, network }, runSuper: any): Promise<void> => {
const globalAsAny = global as any;
assert.equal(globalAsAny.config, theConfig);
assert.isDefined(globalAsAny.config);
assert.equal(globalAsAny.runSuper, runSuper);
assert.isDefined(globalAsAny.network);
await run("example");
assert.equal(globalAsAny.config, theConfig);
assert.equal(globalAsAny.runSuper, runSuper);
assert.equal(globalAsAny.network, network);
}
);
await env.run("with-subtask");
});
it("Should define the network field correctly", () => {
assert.isDefined(env.network);
assert.equal(env.network.name, "localNet");
assert.equal(env.network.config, config.networks.localNet);
});
it("Should throw if the chosen network doesn't exist", () => {
expectBuilderError(() => {
const ctx = BuilderContext.getBuilderContext();
env = new Environment(
config,
{ ...args, network: "NOPE" },
tasks,
ctx.extendersManager.getExtenders(),
true
);
}, ERRORS.NETWORK.CONFIG_NOT_FOUND);
});
});
describe("Plugin system", () => {
useFixtureProject("plugin-project");
it("environment should contain plugin extensions", async () => {
require(path.join(process.cwd(), "plugins", "example"));
const ctx = BuilderContext.getBuilderContext();
env = new Environment(
config,
args,
tasks,
ctx.extendersManager.getExtenders(),
true
);
assert.equal((env as any).__test_key, "a value");
assert.equal((env as any).__test_bleep(2), 4);
});
});
}); | the_stack |
import commander from "commander";
import { build as viteBuild } from "vite";
import { loadConfig } from "../lib/config";
import { makeViteConfig } from "../lib/vite-config";
import cheerio from "cheerio";
import fs from "fs";
import path from "path";
import micromatch from "micromatch";
import chalk from "chalk";
import { RakkasDeploymentTarget, FullConfig } from "../..";
import rimraf from "rimraf";
import { build as esbuild, BuildOptions as ESBuildOptions } from "esbuild";
import { builtinModules } from "module";
import type {
handleRequest as HandleRequest,
Route,
} from "rakkasjs/dist/server";
import { installNodeFetch } from "../runtime/install-node-fetch";
import { spawn } from "child_process";
import { Headers } from "node-fetch";
import { RakkasResponse } from "rakkasjs";
const { createCommand, Option } = commander;
const TARGETS: RakkasDeploymentTarget[] = [
"node",
"static",
"vercel",
"netlify",
"cloudflare-workers",
];
interface BuildCommandOptions {
deploymentTarget: RakkasDeploymentTarget;
}
export default function buildCommand() {
const cmd = createCommand("build")
.description("Build for production")
.addOption(
new Option("-d, --deployment-target <target>", "Deployment target")
.choices(TARGETS)
.default("node"),
)
.action(async (options: BuildCommandOptions) => {
const { config } = await loadConfig({
command: "build",
deploymentTarget: options.deploymentTarget,
});
// eslint-disable-next-line no-console
console.log(
chalk.whiteBright("Building for deployment target"),
chalk.yellowBright(options.deploymentTarget),
);
const result = await build(config, options.deploymentTarget);
return result;
});
return cmd;
}
export async function build(
config: FullConfig,
deploymentTarget: RakkasDeploymentTarget,
) {
let outDir: string;
let clientOutDir: string;
let serverOutDir: string;
let entry: string | undefined;
switch (deploymentTarget) {
case "node":
outDir = path.resolve("dist");
clientOutDir = path.join(outDir, "client");
serverOutDir = path.join(outDir, "server");
entry = path.resolve(__dirname, "./entries/entry-node.js");
break;
case "static":
outDir = path.resolve("node_modules/.rakkas/static");
clientOutDir = path.join(outDir, "client");
serverOutDir = path.join(outDir, "server");
break;
case "vercel":
outDir = path.resolve(".vercel_build_output");
clientOutDir = path.join(outDir, "static");
serverOutDir = path.resolve("./node_modules/.rakkas/vercel");
entry = path.resolve(__dirname, "./entries/entry-vercel.js");
await fs.promises.mkdir(path.join(outDir, "config"), {
recursive: true,
});
await fs.promises.writeFile(
path.join(outDir, "config", "routes.json"),
JSON.stringify([
{ handle: "filesystem" },
{
src: "/(.*)",
dest: "/.vercel/functions/render",
},
]),
);
break;
case "netlify":
outDir = path.resolve("netlify");
clientOutDir = path.join(outDir, "static");
serverOutDir = path.resolve("./node_modules/.rakkas/netlify");
entry = path.resolve(__dirname, "./entries/entry-netlify.js");
break;
case "cloudflare-workers":
outDir = path.resolve("cloudflare");
clientOutDir = path.join(outDir, "static");
serverOutDir = path.resolve("./node_modules/.rakkas/cloudflare");
entry = path.resolve(__dirname, "./entries/entry-cloudflare-workers.js");
break;
default:
throw new Error(`Build target ${deploymentTarget} is not supported yet`);
}
await fs.promises.mkdir(clientOutDir, { recursive: true });
await fs.promises.mkdir(serverOutDir, { recursive: true });
// eslint-disable-next-line no-console
console.log(chalk.blue("Building client"));
const buildId = await getBuildId();
const clientConfig = await makeViteConfig(config, deploymentTarget, buildId, {
ssr: false,
});
await viteBuild({
...clientConfig,
build: {
outDir: clientOutDir,
emptyOutDir: true,
ssrManifest: true,
target: "es2020",
},
});
const ssrConfig = await makeViteConfig(config, deploymentTarget, buildId, {
ssr: true,
});
// Fix index.html
const htmlTemplate = await fs.promises.readFile(
path.join(clientOutDir, "index.html"),
"utf-8",
);
const dom = cheerio.load(htmlTemplate);
await fs.promises.unlink(path.join(clientOutDir, "index.html"));
// Fix manifest
const rawManifest = JSON.parse(
await fs.promises.readFile(
path.join(clientOutDir, "ssr-manifest.json"),
"utf-8",
),
) as Record<string, string[]>;
const importManifest = JSON.parse(
await fs.promises.readFile(
path.join(clientOutDir, "import-manifest.json"),
"utf-8",
),
) as Record<string, string[]>;
const pagesDir = path.resolve(`./src/${config.pagesDir}`);
const pageExtensions = config.pageExtensions.join("|");
const pageMatcher = micromatch.matcher(`**/(*.)?page.(${pageExtensions})`);
const layoutMatcher = micromatch.matcher(
`**/(*/)?layout.(${pageExtensions})`,
);
const manifest = Object.fromEntries(
Object.entries(rawManifest)
.map(([name, value]) => {
const relative = path.relative(pagesDir, path.resolve("src", name));
if (
relative &&
!relative.startsWith("..") &&
!path.isAbsolute(relative) &&
(pageMatcher(relative) || layoutMatcher(relative))
) {
const fullName = path.join(config.pagesDir, relative);
const assetSet = new Set<string>(value);
const deps = importManifest[fullName] || [];
for (const dep of deps) {
const assets = rawManifest[dep];
if (!assets) continue;
assets.forEach((x) => assetSet.add(x));
}
return [path.join("/", config.pagesDir, relative), [...assetSet]];
}
})
.filter(Boolean) as Array<[string, string[]]>,
);
if (deploymentTarget !== "static") {
await fs.promises.unlink(path.join(clientOutDir, "ssr-manifest.json"));
await fs.promises.unlink(path.join(clientOutDir, "import-manifest.json"));
}
// eslint-disable-next-line no-console
console.log(chalk.blue("Building server"));
if (deploymentTarget === "cloudflare-workers") {
ssrConfig.ssr.target = "webworker";
ssrConfig.resolve = ssrConfig.resolve || {};
ssrConfig.resolve.mainFields = ["module", "main", "browser"];
ssrConfig.resolve.conditions = ssrConfig.resolve.conditions || [];
ssrConfig.resolve.conditions.push("worker");
}
await viteBuild({
...ssrConfig,
build: {
ssr: true,
target: "node12",
outDir: serverOutDir,
rollupOptions: {
input: [
"virtual:rakkasjs:page-routes",
"virtual:rakkasjs:api-routes",
"virtual:rakkasjs:server",
"virtual:rakkasjs:placeholder-loader",
],
output: undefined,
},
emptyOutDir: true,
},
publicDir: false,
});
if (deploymentTarget !== "static") {
await fs.promises.writeFile(
path.join(serverOutDir, "rakkas-manifest.json"),
JSON.stringify(manifest),
"utf8",
);
await fs.promises.writeFile(
path.join(serverOutDir, "html-template.js"),
`module.exports=${JSON.stringify(dom.html())}`,
"utf8",
);
await fs.promises.copyFile(entry!, path.join(serverOutDir, "index.js"));
}
const pageRoutes: Route[] = (
await (0, eval)(
`import(${JSON.stringify(
path.join(serverOutDir, "virtual_rakkasjs_page-routes.js"),
)})`,
)
).default.default;
installNodeFetch();
const htmlContents = dom.html();
const placeholderLoader = path.join(serverOutDir, "placeholder-loader.js");
const htmlPlaceholder = await (
await (0, eval)(`import(${JSON.stringify(placeholderLoader)})`)
).default.default(htmlContents, pageRoutes);
await fs.promises.unlink(placeholderLoader);
fs.promises.writeFile(
path.join(serverOutDir, "placeholder.js"),
`module.exports=${JSON.stringify(htmlPlaceholder)}`,
"utf8",
);
await prerender(
config,
serverOutDir,
clientOutDir,
htmlContents,
htmlPlaceholder,
manifest,
config.prerender,
pageRoutes,
deploymentTarget,
);
if (deploymentTarget === "vercel") {
// eslint-disable-next-line no-console
console.log(chalk.blue("Bundling serverless fuction"));
await fs.promises.mkdir(path.join(outDir, "functions/node/render"), {
recursive: true,
});
const esbuilfOptions: ESBuildOptions = {
bundle: true,
entryPoints: [path.join(serverOutDir, "index.js")],
outfile: path.join(outDir, "functions/node/render/index.js"),
platform: "node",
target: "node12",
format: "cjs",
};
config.modifyEsbuildOptions?.(esbuilfOptions);
await esbuild(esbuilfOptions);
} else if (deploymentTarget === "netlify") {
// eslint-disable-next-line no-console
console.log(chalk.blue("Bundling serverless fuction"));
await fs.promises.mkdir(path.join(outDir, "functions"), {
recursive: true,
});
const esbuilfOptions: ESBuildOptions = {
bundle: true,
entryPoints: [path.join(serverOutDir, "index.js")],
outfile: path.join(outDir, "functions/render.js"),
platform: "node",
target: "node12",
format: "cjs",
};
config.modifyEsbuildOptions?.(esbuilfOptions);
await esbuild(esbuilfOptions);
await fs.promises.writeFile(
path.join(clientOutDir, "_redirects"),
"/* /.netlify/functions/render 200",
);
} else if (deploymentTarget === "cloudflare-workers") {
// eslint-disable-next-line no-console
console.log(chalk.blue("Bundling serverless fuction"));
await fs.promises.mkdir(path.join(outDir, "functions"), {
recursive: true,
});
const esbuilfOptions: ESBuildOptions = {
bundle: true,
minify: true,
entryPoints: [path.join(serverOutDir, "index.js")],
outfile: path.join(outDir, "index.js"),
platform: "browser",
target: "node12",
format: "esm",
mainFields: ["module", "main", "browser"],
external: builtinModules,
};
config.modifyEsbuildOptions?.(esbuilfOptions);
await esbuild(esbuilfOptions);
await fs.promises.writeFile(
path.join(outDir, "package.json"),
`{"main":"index.js"}`,
);
}
if (deploymentTarget === "static") {
await fs.promises.mkdir("dist", { recursive: true });
await new Promise<void>((resolve, reject) =>
rimraf("dist", (error) => {
if (error) {
reject(error);
} else {
resolve();
}
}),
);
await fs.promises.rename(path.join(outDir, "client"), "dist");
await fs.promises.copyFile(
path.resolve(__dirname, "./entries/entry-language-detect.js"),
"dist/lang-redir.js",
);
await new Promise<void>((resolve, reject) =>
rimraf(outDir, (error) => {
if (error) {
reject(error);
} else {
resolve();
}
}),
);
outDir = path.resolve("dist");
}
// eslint-disable-next-line no-console
console.log(chalk.whiteBright("Application built in "), chalk.green(outDir));
}
async function prerender(
config: FullConfig,
serverOutDir: string,
clientOutDir: string,
htmlTemplate: string,
htmlPlaceholder: string,
manifest: Record<string, string[]>,
prerender: string[],
pageRoutes: Route[],
deploymentTarget: RakkasDeploymentTarget,
) {
if (!prerender.length) return;
// eslint-disable-next-line no-console
console.log(chalk.blue("Pre-rendering static routes"));
const server = await (0, eval)(
`import(${JSON.stringify(path.join(serverOutDir, "server.js"))})`,
);
const handleRequest: typeof HandleRequest = server.handleRequest;
const apiRoutes: Route[] = (
await (0, eval)(
`import(${JSON.stringify(
path.join(serverOutDir, "virtual_rakkasjs_api-routes.js"),
)})`,
)
).default.default;
const roots = new Set(prerender);
const origin = `http://localhost`;
const prerendered: Record<
string,
{
content: RakkasResponse;
filename: string;
}
> = {};
const decoder = new TextDecoder("utf-8");
for (const root of roots) {
const currentUrl = new URL(origin + root);
const response = await handleRequest({
prerendering: true,
htmlTemplate,
htmlPlaceholder,
pageRoutes,
apiRoutes,
manifest,
async saveResponse(name, response) {
try {
const fullname = clientOutDir + name;
const dir = path.parse(fullname).dir;
const { body, ...bodiless } = response;
let content = body;
if (content === undefined || content === null) {
content = "";
} else if (
typeof content !== "string" &&
!(content instanceof Uint8Array)
) {
content = JSON.stringify(content);
}
// eslint-disable-next-line no-console
console.log(chalk.gray(name));
await fs.promises.mkdir(dir, { recursive: true });
await fs.promises.writeFile(fullname, content as any);
prerendered[name] = {
content: bodiless,
filename: fullname,
};
} catch (error) {
// eslint-disable-next-line no-console
console.error(error);
}
},
async getCachedResponse(name) {
const response =
prerendered[name] ||
prerendered[
name.endsWith("/") ? name + "index.html" : name + "/index.html"
];
if (!response) {
return undefined;
}
const body = await fs.promises.readFile(response.filename);
return {
response: {
...response.content,
body,
},
expired: false,
};
},
request: {
url: currentUrl,
ip: "",
method: "GET",
headers: new Headers() as any,
originalIp: "",
originalUrl: currentUrl,
type: "empty",
},
});
let replyHeaders = response.headers || [];
if (!Array.isArray(replyHeaders)) {
replyHeaders = Object.entries(replyHeaders);
}
if ((response.status || 200) > 399) {
// eslint-disable-next-line no-console
console.log(
chalk.yellowBright(
`Request to ${root} returned status ${response.status}.`,
),
);
}
// eslint-disable-next-line no-inner-declarations
function addPath(path: string) {
const url = new URL(path, currentUrl);
if (url.origin === origin) {
roots.add(url.pathname);
}
}
const location = replyHeaders.find(
(x) => x[0].toLowerCase() === "location",
)?.[1];
if (typeof location === "string") addPath(location);
const contentType = replyHeaders.find(
(x) => x[0].toLowerCase() === "content-type",
)?.[1];
const prerenderHeader = replyHeaders.find(
(x) => x[0].toLowerCase() === "x-rakkas-prerender",
)?.[1];
if (prerenderHeader === "language-redirect") {
const redirects: Record<string, string> = response.body as any;
for (const [, path] of Object.entries(redirects)) {
addPath(path);
}
if (deploymentTarget === "static" && config.locales?.detect) {
const content = renderLanguageRedirectPage(
redirects,
config.locales?.default || "en",
config.locales?.cookieName,
);
let name = currentUrl.pathname;
if (!name.endsWith("/")) name += "/";
name += "/index.html";
const fullname = clientOutDir + name;
const dir = path.parse(fullname).dir;
// eslint-disable-next-line no-console
console.log(chalk.gray(name));
await fs.promises.mkdir(dir, { recursive: true });
await fs.promises.writeFile(fullname, content);
prerendered[name] = {
content: { headers: response.headers, status: response.status },
filename: fullname,
};
}
} else if (contentType === "text/html") {
const noCrawl = prerenderHeader === "no-crawl";
if (!noCrawl) {
if (response.body === undefined || response.body === null) {
response.body = "";
} else if (typeof response.body !== "string") {
if (response.body instanceof Uint8Array) {
response.body = decoder.decode(response.body);
} else {
response.body = JSON.stringify(response.body);
}
}
const dom = cheerio.load(response.body as string);
dom("a[href]").each((_, el) => addPath(el.attribs.href));
dom("area[href]").each((_, el) => addPath(el.attribs.href));
}
}
}
}
async function getBuildId(): Promise<string> {
return await new Promise<string>((resolve) => {
const git = spawn("git", ["rev-parse", "HEAD"], {
stdio: ["ignore", "pipe", "ignore"],
});
git.stdout.setEncoding("utf8");
let output = "";
git.stdout.on("data", (data) => {
output += data;
});
git.on("close", (code) => {
if (code === 0) {
resolve(output.trim().slice(0, 11));
} else {
// Return a random hash if git fails
resolve(Math.random().toString(36).substring(2, 15));
}
});
});
}
function renderLanguageRedirectPage(
redirects: Record<string, string>,
defaultLocale: string,
coookieName?: string,
): string {
let anchors = "";
let links = "";
for (const [lang, url] of Object.entries(redirects)) {
let displayName = lang;
try {
displayName = new (Intl as any).DisplayNames(lang, {
type: "language",
})
.of(lang)
.toLocaleUpperCase(lang);
} catch {
// Do nothing
}
anchors += `<li><a href="${escapeHtml(
url,
)}" hreflang="${lang}" lang="${lang}">${escapeHtml(displayName)}</a></li>`;
links += `<link rel="alternate" hreflang="${lang}" href="${escapeHtml(
url,
)}" />`;
}
return `<!DOCTYPE html><html><head><meta charset="utf-8">${links}</head><body><noscript><ul>${anchors}</ul></noscript><script>RAKKAS_DEFAULT_LOCALE=${JSON.stringify(
defaultLocale,
)};RAKKAS_LOCALE_COOKIE_NAME=${JSON.stringify(
coookieName,
)}</script><script src="/lang-redir.js"></script></body></html>`;
}
function escapeHtml(text: string): string {
return text
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
} | the_stack |
import * as Common from '../../core/common/common.js';
import * as i18n from '../../core/i18n/i18n.js';
import * as Platform from '../../core/platform/platform.js';
import * as Root from '../../core/root/root.js';
import * as Persistence from '../../models/persistence/persistence.js';
import * as Workspace from '../../models/workspace/workspace.js';
import * as QuickOpen from '../../ui/legacy/components/quick_open/quick_open.js';
import * as SourceFrame from '../../ui/legacy/components/source_frame/source_frame.js';
import * as UI from '../../ui/legacy/legacy.js';
import {EditingLocationHistoryManager} from './EditingLocationHistoryManager.js';
import sourcesViewStyles from './sourcesView.css.js';
import type {EditorSelectedEvent, TabbedEditorContainerDelegate} from './TabbedEditorContainer.js';
import {Events as TabbedEditorContainerEvents, TabbedEditorContainer} from './TabbedEditorContainer.js';
import {Events as UISourceCodeFrameEvents, UISourceCodeFrame} from './UISourceCodeFrame.js';
const UIStrings = {
/**
*@description Text to open a file
*/
openFile: 'Open file',
/**
*@description Text to run commands
*/
runCommand: 'Run command',
/**
*@description Text in Sources View of the Sources panel
*/
dropInAFolderToAddToWorkspace: 'Drop in a folder to add to workspace',
/**
*@description Accessible label for Sources placeholder view actions list
*/
sourceViewActions: 'Source View Actions',
};
const str_ = i18n.i18n.registerUIStrings('panels/sources/SourcesView.ts', UIStrings);
const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);
export class SourcesView extends Common.ObjectWrapper.eventMixin<EventTypes, typeof UI.Widget.VBox>(UI.Widget.VBox)
implements TabbedEditorContainerDelegate, UI.SearchableView.Searchable, UI.SearchableView.Replaceable {
private placeholderOptionArray: {
element: HTMLElement,
handler: Function,
}[];
private selectedIndex: number;
private readonly searchableViewInternal: UI.SearchableView.SearchableView;
private readonly sourceViewByUISourceCode: Map<Workspace.UISourceCode.UISourceCode, UI.Widget.Widget>;
editorContainer: TabbedEditorContainer;
private readonly historyManager: EditingLocationHistoryManager;
private readonly toolbarContainerElementInternal: HTMLElement;
private readonly scriptViewToolbar: UI.Toolbar.Toolbar;
private readonly bottomToolbarInternal: UI.Toolbar.Toolbar;
private toolbarChangedListener: Common.EventTarget.EventDescriptor|null;
private readonly shortcuts: Map<number, () => boolean>;
private readonly focusedPlaceholderElement?: HTMLElement;
private searchView?: UISourceCodeFrame;
private searchConfig?: UI.SearchableView.SearchConfig;
constructor() {
super();
this.element.id = 'sources-panel-sources-view';
this.setMinimumAndPreferredSizes(250, 52, 250, 100);
this.placeholderOptionArray = [];
this.selectedIndex = 0;
const workspace = Workspace.Workspace.WorkspaceImpl.instance();
this.searchableViewInternal = new UI.SearchableView.SearchableView(this, this, 'sourcesViewSearchConfig');
this.searchableViewInternal.setMinimalSearchQuerySize(0);
this.searchableViewInternal.show(this.element);
this.sourceViewByUISourceCode = new Map();
this.editorContainer = new TabbedEditorContainer(
this, Common.Settings.Settings.instance().createLocalSetting('previouslyViewedFiles', []),
this.placeholderElement(), this.focusedPlaceholderElement);
this.editorContainer.show(this.searchableViewInternal.element);
this.editorContainer.addEventListener(TabbedEditorContainerEvents.EditorSelected, this.editorSelected, this);
this.editorContainer.addEventListener(TabbedEditorContainerEvents.EditorClosed, this.editorClosed, this);
this.historyManager = new EditingLocationHistoryManager(this, this.currentSourceFrame.bind(this));
this.toolbarContainerElementInternal = this.element.createChild('div', 'sources-toolbar');
if (!Root.Runtime.experiments.isEnabled('sourcesPrettyPrint')) {
const toolbarEditorActions = new UI.Toolbar.Toolbar('', this.toolbarContainerElementInternal);
for (const action of getRegisteredEditorActions()) {
toolbarEditorActions.appendToolbarItem(action.getOrCreateButton(this));
}
}
this.scriptViewToolbar = new UI.Toolbar.Toolbar('', this.toolbarContainerElementInternal);
this.scriptViewToolbar.element.style.flex = 'auto';
this.bottomToolbarInternal = new UI.Toolbar.Toolbar('', this.toolbarContainerElementInternal);
this.toolbarChangedListener = null;
UI.UIUtils.startBatchUpdate();
workspace.uiSourceCodes().forEach(this.addUISourceCode.bind(this));
UI.UIUtils.endBatchUpdate();
workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeAdded, this.uiSourceCodeAdded, this);
workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeRemoved, this.uiSourceCodeRemoved, this);
workspace.addEventListener(Workspace.Workspace.Events.ProjectRemoved, this.projectRemoved.bind(this), this);
function handleBeforeUnload(event: Event): void {
if (event.returnValue) {
return;
}
const unsavedSourceCodes: Workspace.UISourceCode.UISourceCode[] = [];
const projects =
Workspace.Workspace.WorkspaceImpl.instance().projectsForType(Workspace.Workspace.projectTypes.FileSystem);
for (const project of projects) {
unsavedSourceCodes.push(...project.uiSourceCodes().filter(sourceCode => sourceCode.isDirty()));
}
if (!unsavedSourceCodes.length) {
return;
}
event.returnValue = true;
UI.ViewManager.ViewManager.instance().showView('sources');
for (const sourceCode of unsavedSourceCodes) {
Common.Revealer.reveal(sourceCode);
}
}
if (!window.opener) {
window.addEventListener('beforeunload', handleBeforeUnload, true);
}
this.shortcuts = new Map();
this.element.addEventListener('keydown', this.handleKeyDown.bind(this), false);
}
private placeholderElement(): Element {
this.placeholderOptionArray = [];
const shortcuts = [
{actionId: 'quickOpen.show', description: i18nString(UIStrings.openFile)},
{actionId: 'commandMenu.show', description: i18nString(UIStrings.runCommand)},
{actionId: 'sources.add-folder-to-workspace', description: i18nString(UIStrings.dropInAFolderToAddToWorkspace)},
];
const element = document.createElement('div');
const list = element.createChild('div', 'tabbed-pane-placeholder');
list.addEventListener('keydown', this.placeholderOnKeyDown.bind(this), false);
UI.ARIAUtils.markAsList(list);
UI.ARIAUtils.setAccessibleName(list, i18nString(UIStrings.sourceViewActions));
for (let i = 0; i < shortcuts.length; i++) {
const shortcut = shortcuts[i];
const shortcutKeyText = UI.ShortcutRegistry.ShortcutRegistry.instance().shortcutTitleForAction(shortcut.actionId);
const listItemElement = list.createChild('div');
UI.ARIAUtils.markAsListitem(listItemElement);
const row = (listItemElement.createChild('div', 'tabbed-pane-placeholder-row') as HTMLElement);
row.tabIndex = -1;
UI.ARIAUtils.markAsButton(row);
if (shortcutKeyText) {
row.createChild('div', 'tabbed-pane-placeholder-key').textContent = shortcutKeyText;
row.createChild('div', 'tabbed-pane-placeholder-value').textContent = shortcut.description;
} else {
row.createChild('div', 'tabbed-pane-no-shortcut').textContent = shortcut.description;
}
const action = UI.ActionRegistry.ActionRegistry.instance().action(shortcut.actionId);
if (action) {
this.placeholderOptionArray.push({
element: row,
handler(): void {
action.execute();
},
});
}
}
element.appendChild(
UI.XLink.XLink.create('https://developer.chrome.com/docs/devtools/workspaces/', 'Learn more about Workspaces'));
return element;
}
private placeholderOnKeyDown(event: Event): void {
const keyboardEvent = (event as KeyboardEvent);
if (isEnterOrSpaceKey(keyboardEvent)) {
this.placeholderOptionArray[this.selectedIndex].handler();
return;
}
let offset = 0;
if (keyboardEvent.key === 'ArrowDown') {
offset = 1;
} else if (keyboardEvent.key === 'ArrowUp') {
offset = -1;
}
const newIndex = Math.max(Math.min(this.placeholderOptionArray.length - 1, this.selectedIndex + offset), 0);
const newElement = this.placeholderOptionArray[newIndex].element;
const oldElement = this.placeholderOptionArray[this.selectedIndex].element;
if (newElement !== oldElement) {
oldElement.tabIndex = -1;
newElement.tabIndex = 0;
UI.ARIAUtils.setSelected(oldElement, false);
UI.ARIAUtils.setSelected(newElement, true);
this.selectedIndex = newIndex;
newElement.focus();
}
}
static defaultUISourceCodeScores(): Map<Workspace.UISourceCode.UISourceCode, number> {
const defaultScores = new Map<Workspace.UISourceCode.UISourceCode, number>();
const sourcesView = UI.Context.Context.instance().flavor(SourcesView);
if (sourcesView) {
const uiSourceCodes = sourcesView.editorContainer.historyUISourceCodes();
for (let i = 1; i < uiSourceCodes.length; ++i) // Skip current element
{
defaultScores.set(uiSourceCodes[i], uiSourceCodes.length - i);
}
}
return defaultScores;
}
leftToolbar(): UI.Toolbar.Toolbar {
return this.editorContainer.leftToolbar();
}
rightToolbar(): UI.Toolbar.Toolbar {
return this.editorContainer.rightToolbar();
}
bottomToolbar(): UI.Toolbar.Toolbar {
return this.bottomToolbarInternal;
}
private registerShortcuts(keys: UI.KeyboardShortcut.Descriptor[], handler: (arg0?: Event|undefined) => boolean):
void {
for (let i = 0; i < keys.length; ++i) {
this.shortcuts.set(keys[i].key, handler);
}
}
private handleKeyDown(event: Event): void {
const shortcutKey = UI.KeyboardShortcut.KeyboardShortcut.makeKeyFromEvent((event as KeyboardEvent));
const handler = this.shortcuts.get(shortcutKey);
if (handler && handler()) {
event.consume(true);
}
}
wasShown(): void {
super.wasShown();
this.registerCSSFiles([sourcesViewStyles]);
UI.Context.Context.instance().setFlavor(SourcesView, this);
}
willHide(): void {
UI.Context.Context.instance().setFlavor(SourcesView, null);
super.willHide();
}
toolbarContainerElement(): Element {
return this.toolbarContainerElementInternal;
}
searchableView(): UI.SearchableView.SearchableView {
return this.searchableViewInternal;
}
visibleView(): UI.Widget.Widget|null {
return this.editorContainer.visibleView;
}
currentSourceFrame(): UISourceCodeFrame|null {
const view = this.visibleView();
if (!(view instanceof UISourceCodeFrame)) {
return null;
}
return (view as UISourceCodeFrame);
}
currentUISourceCode(): Workspace.UISourceCode.UISourceCode|null {
return this.editorContainer.currentFile();
}
onCloseEditorTab(): boolean {
const uiSourceCode = this.editorContainer.currentFile();
if (!uiSourceCode) {
return false;
}
this.editorContainer.closeFile(uiSourceCode);
return true;
}
onJumpToPreviousLocation(): void {
this.historyManager.rollback();
}
onJumpToNextLocation(): void {
this.historyManager.rollover();
}
private uiSourceCodeAdded(event: Common.EventTarget.EventTargetEvent<Workspace.UISourceCode.UISourceCode>): void {
const uiSourceCode = event.data;
this.addUISourceCode(uiSourceCode);
}
private addUISourceCode(uiSourceCode: Workspace.UISourceCode.UISourceCode): void {
if (uiSourceCode.project().isServiceProject()) {
return;
}
if (uiSourceCode.project().type() === Workspace.Workspace.projectTypes.FileSystem &&
Persistence.FileSystemWorkspaceBinding.FileSystemWorkspaceBinding.fileSystemType(uiSourceCode.project()) ===
'overrides') {
return;
}
this.editorContainer.addUISourceCode(uiSourceCode);
}
private uiSourceCodeRemoved(event: Common.EventTarget.EventTargetEvent<Workspace.UISourceCode.UISourceCode>): void {
const uiSourceCode = event.data;
this.removeUISourceCodes([uiSourceCode]);
}
private removeUISourceCodes(uiSourceCodes: Workspace.UISourceCode.UISourceCode[]): void {
this.editorContainer.removeUISourceCodes(uiSourceCodes);
for (let i = 0; i < uiSourceCodes.length; ++i) {
this.removeSourceFrame(uiSourceCodes[i]);
this.historyManager.removeHistoryForSourceCode(uiSourceCodes[i]);
}
}
private projectRemoved(event: Common.EventTarget.EventTargetEvent<Workspace.Workspace.Project>): void {
const project = event.data;
const uiSourceCodes = project.uiSourceCodes();
this.removeUISourceCodes(uiSourceCodes);
}
private updateScriptViewToolbarItems(): void {
const view = this.visibleView();
if (view instanceof UI.View.SimpleView) {
view.toolbarItems().then(items => {
this.scriptViewToolbar.removeToolbarItems();
items.map(item => this.scriptViewToolbar.appendToolbarItem(item));
});
}
}
showSourceLocation(
uiSourceCode: Workspace.UISourceCode.UISourceCode, lineNumber?: number, columnNumber?: number,
omitFocus?: boolean, omitHighlight?: boolean): void {
this.historyManager.updateCurrentState();
this.editorContainer.showFile(uiSourceCode);
const currentSourceFrame = this.currentSourceFrame();
if (currentSourceFrame && typeof lineNumber === 'number') {
currentSourceFrame.revealPosition(lineNumber, columnNumber, !omitHighlight);
}
this.historyManager.pushNewState();
const visibleView = this.visibleView();
if (!omitFocus && visibleView) {
visibleView.focus();
}
}
private createSourceView(uiSourceCode: Workspace.UISourceCode.UISourceCode): UI.Widget.Widget {
let sourceFrame;
let sourceView;
const contentType = uiSourceCode.contentType();
if (contentType === Common.ResourceType.resourceTypes.Image) {
sourceView = new SourceFrame.ImageView.ImageView(uiSourceCode.mimeType(), uiSourceCode);
} else if (contentType === Common.ResourceType.resourceTypes.Font) {
sourceView = new SourceFrame.FontView.FontView(uiSourceCode.mimeType(), uiSourceCode);
} else {
sourceFrame = new UISourceCodeFrame(uiSourceCode);
}
if (sourceFrame) {
this.historyManager.trackSourceFrameCursorJumps(sourceFrame);
}
const widget = (sourceFrame || sourceView as UI.Widget.Widget);
this.sourceViewByUISourceCode.set(uiSourceCode, widget);
return widget;
}
private getOrCreateSourceView(uiSourceCode: Workspace.UISourceCode.UISourceCode): UI.Widget.Widget {
return this.sourceViewByUISourceCode.get(uiSourceCode) || this.createSourceView(uiSourceCode);
}
recycleUISourceCodeFrame(sourceFrame: UISourceCodeFrame, uiSourceCode: Workspace.UISourceCode.UISourceCode): void {
this.sourceViewByUISourceCode.delete(sourceFrame.uiSourceCode());
sourceFrame.setUISourceCode(uiSourceCode);
this.sourceViewByUISourceCode.set(uiSourceCode, sourceFrame);
}
viewForFile(uiSourceCode: Workspace.UISourceCode.UISourceCode): UI.Widget.Widget {
return this.getOrCreateSourceView(uiSourceCode);
}
private removeSourceFrame(uiSourceCode: Workspace.UISourceCode.UISourceCode): void {
const sourceView = this.sourceViewByUISourceCode.get(uiSourceCode);
this.sourceViewByUISourceCode.delete(uiSourceCode);
if (sourceView && sourceView instanceof UISourceCodeFrame) {
(sourceView as UISourceCodeFrame).dispose();
}
}
private editorClosed(event: Common.EventTarget.EventTargetEvent<Workspace.UISourceCode.UISourceCode>): void {
const uiSourceCode = event.data;
this.historyManager.removeHistoryForSourceCode(uiSourceCode);
let wasSelected = false;
if (!this.editorContainer.currentFile()) {
wasSelected = true;
}
// SourcesNavigator does not need to update on EditorClosed.
this.removeToolbarChangedListener();
this.updateScriptViewToolbarItems();
this.searchableViewInternal.resetSearch();
const data = {
uiSourceCode: uiSourceCode,
wasSelected: wasSelected,
};
this.dispatchEventToListeners(Events.EditorClosed, data);
}
private editorSelected(event: Common.EventTarget.EventTargetEvent<EditorSelectedEvent>): void {
const previousSourceFrame = event.data.previousView instanceof UISourceCodeFrame ? event.data.previousView : null;
if (previousSourceFrame) {
previousSourceFrame.setSearchableView(null);
}
const currentSourceFrame = event.data.currentView instanceof UISourceCodeFrame ? event.data.currentView : null;
if (currentSourceFrame) {
currentSourceFrame.setSearchableView(this.searchableViewInternal);
}
this.searchableViewInternal.setReplaceable(
Boolean(currentSourceFrame) && (currentSourceFrame ? currentSourceFrame.canEditSource() : false));
this.searchableViewInternal.refreshSearch();
this.updateToolbarChangedListener();
this.updateScriptViewToolbarItems();
const currentFile = this.editorContainer.currentFile();
if (currentFile) {
this.dispatchEventToListeners(Events.EditorSelected, currentFile);
}
}
private removeToolbarChangedListener(): void {
if (this.toolbarChangedListener) {
Common.EventTarget.removeEventListeners([this.toolbarChangedListener]);
}
this.toolbarChangedListener = null;
}
private updateToolbarChangedListener(): void {
this.removeToolbarChangedListener();
const sourceFrame = this.currentSourceFrame();
if (!sourceFrame) {
return;
}
this.toolbarChangedListener = sourceFrame.addEventListener(
UISourceCodeFrameEvents.ToolbarItemsChanged, this.updateScriptViewToolbarItems, this);
}
searchCanceled(): void {
if (this.searchView) {
this.searchView.searchCanceled();
}
delete this.searchView;
delete this.searchConfig;
}
performSearch(searchConfig: UI.SearchableView.SearchConfig, shouldJump: boolean, jumpBackwards?: boolean): void {
const sourceFrame = this.currentSourceFrame();
if (!sourceFrame) {
return;
}
this.searchView = sourceFrame;
this.searchConfig = searchConfig;
this.searchView.performSearch(this.searchConfig, shouldJump, jumpBackwards);
}
jumpToNextSearchResult(): void {
if (!this.searchView) {
return;
}
if (this.searchConfig && this.searchView !== this.currentSourceFrame()) {
this.performSearch(this.searchConfig, true);
return;
}
this.searchView.jumpToNextSearchResult();
}
jumpToPreviousSearchResult(): void {
if (!this.searchView) {
return;
}
if (this.searchConfig && this.searchView !== this.currentSourceFrame()) {
this.performSearch(this.searchConfig, true);
if (this.searchView) {
this.searchView.jumpToLastSearchResult();
}
return;
}
this.searchView.jumpToPreviousSearchResult();
}
supportsCaseSensitiveSearch(): boolean {
return true;
}
supportsRegexSearch(): boolean {
return true;
}
replaceSelectionWith(searchConfig: UI.SearchableView.SearchConfig, replacement: string): void {
const sourceFrame = this.currentSourceFrame();
if (!sourceFrame) {
console.assert(Boolean(sourceFrame));
return;
}
sourceFrame.replaceSelectionWith(searchConfig, replacement);
}
replaceAllWith(searchConfig: UI.SearchableView.SearchConfig, replacement: string): void {
const sourceFrame = this.currentSourceFrame();
if (!sourceFrame) {
console.assert(Boolean(sourceFrame));
return;
}
sourceFrame.replaceAllWith(searchConfig, replacement);
}
showOutlineQuickOpen(): void {
QuickOpen.QuickOpen.QuickOpenImpl.show('@');
}
showGoToLineQuickOpen(): void {
if (this.editorContainer.currentFile()) {
QuickOpen.QuickOpen.QuickOpenImpl.show(':');
}
}
save(): void {
this.saveSourceFrame(this.currentSourceFrame());
}
saveAll(): void {
const sourceFrames = this.editorContainer.fileViews();
sourceFrames.forEach(this.saveSourceFrame.bind(this));
}
private saveSourceFrame(sourceFrame: UI.Widget.Widget|null): void {
if (!(sourceFrame instanceof UISourceCodeFrame)) {
return;
}
const uiSourceCodeFrame = (sourceFrame as UISourceCodeFrame);
uiSourceCodeFrame.commitEditing();
}
toggleBreakpointsActiveState(active: boolean): void {
this.editorContainer.view.element.classList.toggle('breakpoints-deactivated', !active);
}
}
export // TODO(crbug.com/1167717): Make this a const enum again
// eslint-disable-next-line rulesdir/const_enum
enum Events {
EditorClosed = 'EditorClosed',
EditorSelected = 'EditorSelected',
}
export interface EditorClosedEvent {
uiSourceCode: Workspace.UISourceCode.UISourceCode;
wasSelected: boolean;
}
export type EventTypes = {
[Events.EditorClosed]: EditorClosedEvent,
[Events.EditorSelected]: Workspace.UISourceCode.UISourceCode,
};
/**
* @interface
*/
export interface EditorAction {
getOrCreateButton(sourcesView: SourcesView): UI.Toolbar.ToolbarButton;
}
const registeredEditorActions: (() => EditorAction)[] = [];
export function registerEditorAction(editorAction: () => EditorAction): void {
registeredEditorActions.push(editorAction);
}
export function getRegisteredEditorActions(): EditorAction[] {
return registeredEditorActions.map(editorAction => editorAction());
}
let switchFileActionDelegateInstance: SwitchFileActionDelegate;
export class SwitchFileActionDelegate implements UI.ActionRegistration.ActionDelegate {
static instance(opts: {
forceNew: boolean|null,
} = {forceNew: null}): SwitchFileActionDelegate {
const {forceNew} = opts;
if (!switchFileActionDelegateInstance || forceNew) {
switchFileActionDelegateInstance = new SwitchFileActionDelegate();
}
return switchFileActionDelegateInstance;
}
private static nextFile(currentUISourceCode: Workspace.UISourceCode.UISourceCode): Workspace.UISourceCode.UISourceCode
|null {
function fileNamePrefix(name: string): string {
const lastDotIndex = name.lastIndexOf('.');
const namePrefix = name.substr(0, lastDotIndex !== -1 ? lastDotIndex : name.length);
return namePrefix.toLowerCase();
}
const uiSourceCodes = currentUISourceCode.project().uiSourceCodes();
const candidates = [];
const url = currentUISourceCode.parentURL();
const name = currentUISourceCode.name();
const namePrefix = fileNamePrefix(name);
for (let i = 0; i < uiSourceCodes.length; ++i) {
const uiSourceCode = uiSourceCodes[i];
if (url !== uiSourceCode.parentURL()) {
continue;
}
if (fileNamePrefix(uiSourceCode.name()) === namePrefix) {
candidates.push(uiSourceCode.name());
}
}
candidates.sort(Platform.StringUtilities.naturalOrderComparator);
const index = Platform.NumberUtilities.mod(candidates.indexOf(name) + 1, candidates.length);
const fullURL = (url ? url + '/' : '') + candidates[index];
const nextUISourceCode = currentUISourceCode.project().uiSourceCodeForURL(fullURL);
return nextUISourceCode !== currentUISourceCode ? nextUISourceCode : null;
}
handleAction(_context: UI.Context.Context, _actionId: string): boolean {
const sourcesView = UI.Context.Context.instance().flavor(SourcesView);
if (!sourcesView) {
return false;
}
const currentUISourceCode = sourcesView.currentUISourceCode();
if (!currentUISourceCode) {
return false;
}
const nextUISourceCode = SwitchFileActionDelegate.nextFile(currentUISourceCode);
if (!nextUISourceCode) {
return false;
}
sourcesView.showSourceLocation(nextUISourceCode);
return true;
}
}
let actionDelegateInstance: ActionDelegate;
export class ActionDelegate implements UI.ActionRegistration.ActionDelegate {
static instance(opts: {
forceNew: boolean|null,
}|undefined = {forceNew: null}): ActionDelegate {
const {forceNew} = opts;
if (!actionDelegateInstance || forceNew) {
actionDelegateInstance = new ActionDelegate();
}
return actionDelegateInstance;
}
handleAction(context: UI.Context.Context, actionId: string): boolean {
const sourcesView = UI.Context.Context.instance().flavor(SourcesView);
if (!sourcesView) {
return false;
}
switch (actionId) {
case 'sources.close-all':
sourcesView.editorContainer.closeAllFiles();
return true;
case 'sources.jump-to-previous-location':
sourcesView.onJumpToPreviousLocation();
return true;
case 'sources.jump-to-next-location':
sourcesView.onJumpToNextLocation();
return true;
case 'sources.close-editor-tab':
return sourcesView.onCloseEditorTab();
case 'sources.go-to-line':
sourcesView.showGoToLineQuickOpen();
return true;
case 'sources.go-to-member':
sourcesView.showOutlineQuickOpen();
return true;
case 'sources.save':
sourcesView.save();
return true;
case 'sources.save-all':
sourcesView.saveAll();
return true;
}
return false;
}
} | the_stack |
import { css } from '@emotion/core'
import styled from '@emotion/styled'
import { giphyBlue, giphyGreen, giphyPurple, giphyRed, giphyYellow } from '@giphy/js-brand'
import { IGif, ImageAllTypes, IUser } from '@giphy/js-types'
import { getAltText, getBestRendition, getGifHeight, Logger } from '@giphy/js-util'
import React, { ElementType, HTMLProps, SyntheticEvent, useContext, useEffect, useRef, useState } from 'react'
import * as pingback from '../util/pingback'
import AttributionOverlay from './attribution/overlay'
import VerifiedBadge from './attribution/verified-badge'
import { PingbackContext } from './pingback-context-manager'
import { GifOverlayProps } from './types'
const GifContainer = styled.div<{ borderRadius?: number }>`
display: block;
&:focus {
outline: unset;
}
${(props) =>
props.borderRadius &&
css`
border-radius: ${props.borderRadius}px;
overflow: hidden;
`}
img {
display: block;
}
.${VerifiedBadge.className} {
g {
fill: white;
}
}
.${VerifiedBadge.checkMarkClassName} {
opacity: 0;
}
`
export const GRID_COLORS = [giphyBlue, giphyGreen, giphyPurple, giphyRed, giphyYellow]
export const getColor = () => GRID_COLORS[Math.round(Math.random() * (GRID_COLORS.length - 1))]
const hoverTimeoutDelay = 200
type ContainerProps = HTMLProps<HTMLElement> & { href?: string; borderRadius: number }
const Container = (props: ContainerProps) => (
<GifContainer as={props.href ? 'a' : 'div'} {...(props as HTMLProps<HTMLDivElement>)} />
)
export type EventProps = {
// fired every time the gif is show
onGifVisible?: (gif: IGif, e?: SyntheticEvent<HTMLElement, Event>) => void
// fired once after the gif loads and when it's completely in view
onGifSeen?: (gif: IGif, boundingClientRect: ClientRect | DOMRect) => void
// fired when the gif is clicked
onGifClick?: (gif: IGif, e: SyntheticEvent<HTMLElement, Event>) => void
// fired when the gif is right clicked
onGifRightClick?: (gif: IGif, e: SyntheticEvent<HTMLElement, Event>) => void
}
type GifProps = {
gif: IGif
width: number
height?: number
backgroundColor?: string
className?: string
user?: Partial<IUser>
overlay?: ElementType<GifOverlayProps>
hideAttribution?: boolean
noLink?: boolean
borderRadius?: number
tabIndex?: number
style?: any
}
type Props = GifProps & EventProps
const placeholder = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
// used to detect if we're on the server or client
const canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement)
const noop = () => {}
const Gif = ({
gif,
width,
height: forcedHeight,
onGifRightClick = noop,
className = '',
onGifClick = noop,
onGifSeen = noop,
onGifVisible = noop,
user = {},
backgroundColor,
overlay,
hideAttribution = false,
noLink = false,
borderRadius = 4,
style,
tabIndex,
}: Props) => {
// only fire seen once per gif id
const [hasFiredSeen, setHasFiredSeen] = useState(false)
// hovered is for the gif overlay
const [isHovered, setHovered] = useState(false)
// only show the gif if it's on the screen
// if we can't use the dom (SSR), then we show the gif by default
const [showGif, setShowGif] = useState(!canUseDOM)
// classname to target animations on image load
const [loadedClassname, setLoadedClassName] = useState('')
// the background color shouldn't change unless it comes from a prop or we have a sticker
const defaultBgColor = useRef(getColor())
// the a tag the media is rendered into
const container = useRef<HTMLDivElement | null>(null)
// to play it safe when using SSR, we check image.complete after mount
const image = useRef<HTMLImageElement | null>(null)
// intersection observer with no threshold
const showGifObserver = useRef<IntersectionObserver>()
// intersection observer with a threshold of 1 (full element is on screen)
const fullGifObserver = useRef<IntersectionObserver>()
// fire hover pingback after this timeout
const hoverTimeout = useRef<number>()
// fire onseen ref (changes per gif, so need a ref)
const sendOnSeen = useRef<(_: IntersectionObserverEntry) => void>(noop)
// custom pingback
const { attributes } = useContext(PingbackContext)
// user's overlay
let Overlay = overlay
if (!Overlay && !hideAttribution) {
// no user overlay, and no force hide of the attribution
Overlay = AttributionOverlay
}
const onMouseOver = (e: SyntheticEvent<HTMLElement, Event>) => {
clearTimeout(hoverTimeout.current!)
e.persist()
setHovered(true)
hoverTimeout.current = window.setTimeout(() => {
pingback.onGifHover(gif, user?.id, e.target as HTMLElement, attributes)
}, hoverTimeoutDelay)
}
const onMouseLeave = () => {
clearTimeout(hoverTimeout.current!)
setHovered(false)
}
const onClick = (e: SyntheticEvent<HTMLElement, Event>) => {
// fire pingback
pingback.onGifClick(gif, user?.id, e.target as HTMLElement, attributes)
onGifClick(gif, e)
}
// using a ref in case `gif` changes
sendOnSeen.current = (entry: IntersectionObserverEntry) => {
// flag so we don't observe any more
setHasFiredSeen(true)
Logger.debug(`GIF ${gif.id} seen. ${gif.title}`)
// fire pingback
pingback.onGifSeen(gif, user?.id, entry.boundingClientRect, attributes)
// fire custom onGifSeen
onGifSeen?.(gif, entry.boundingClientRect)
// disconnect
if (fullGifObserver.current) {
fullGifObserver.current.disconnect()
}
}
const watchGif = () => {
if (!fullGifObserver.current) {
fullGifObserver.current = new IntersectionObserver(
([entry]: IntersectionObserverEntry[]) => {
if (entry.isIntersecting) {
sendOnSeen.current(entry)
}
},
{ threshold: [0.99] }
)
}
if (!hasFiredSeen && container.current && fullGifObserver.current) {
// observe img for full gif view
fullGifObserver.current.observe(container.current)
}
}
const onImageLoad = (e: SyntheticEvent<HTMLElement, Event>) => {
watchGif()
onGifVisible(gif, e) // gif is visible, perhaps just partially
setLoadedClassName(Gif.imgLoadedClassName)
}
useEffect(() => {
// the id has changed, maybe the image has loaded
if (image.current?.complete) {
watchGif()
onGifVisible(gif) // gif is visible, perhaps just partially
}
fullGifObserver.current?.disconnect()
setHasFiredSeen(false)
// We only want to fire this when gif id changes
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [gif.id])
useEffect(() => {
showGifObserver.current = new IntersectionObserver(([entry]: IntersectionObserverEntry[]) => {
const { isIntersecting } = entry
// show the gif if the container is on the screen
setShowGif(isIntersecting)
// remove the fullGifObserver if we go off the screen
// we may have already disconnected if the hasFiredSeen happened
if (!isIntersecting && fullGifObserver.current) {
fullGifObserver.current.disconnect()
}
})
showGifObserver.current.observe(container.current!)
return () => {
if (showGifObserver.current) showGifObserver.current.disconnect()
if (fullGifObserver.current) fullGifObserver.current.disconnect()
if (hoverTimeout.current) clearTimeout(hoverTimeout.current)
}
}, [])
const height = forcedHeight || getGifHeight(gif, width)
const bestRendition = getBestRendition(gif.images, width, height)
const rendition = gif.images[bestRendition.renditionName] as ImageAllTypes
const background =
backgroundColor || // <- specified background prop
// sticker has black if no backgroundColor is specified
(gif.is_sticker
? `url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADgAAAA4AQMAAACSSKldAAAABlBMVEUhIiIWFhYoSqvJAAAAGElEQVQY02MAAv7///8PWxqIPwDZw5UGABtgwz2xhFKxAAAAAElFTkSuQmCC') 0 0`
: defaultBgColor.current)
return (
<Container
href={noLink ? undefined : gif.url}
style={{
width,
height,
...style,
}}
borderRadius={borderRadius}
className={[Gif.className, className].join(' ')}
onMouseOver={onMouseOver}
onMouseLeave={onMouseLeave}
onClick={onClick}
onContextMenu={(e: SyntheticEvent<HTMLElement, Event>) => onGifRightClick(gif, e)}
tabIndex={tabIndex}
>
<div style={{ width, height, position: 'relative' }} ref={container}>
<picture>
<source type="image/webp" srcSet={rendition.webp} />
<img
ref={image}
suppressHydrationWarning
className={[Gif.imgClassName, loadedClassname].join(' ')}
src={showGif ? rendition.url : placeholder}
style={{ background }}
width={width}
height={height}
alt={getAltText(gif)}
onLoad={showGif ? onImageLoad : () => {}}
/>
</picture>
{showGif ? Overlay && <Overlay gif={gif} isHovered={isHovered} width={width} height={height} /> : null}
</div>
</Container>
)
}
Gif.className = 'giphy-gif'
Gif.imgClassName = 'giphy-gif-img'
Gif.imgLoadedClassName = 'giphy-img-loaded'
export default Gif | the_stack |
import { Component, Inject, InjectionToken, OnInit, ViewContainerRef } from '@angular/core';
import {
aggregationTranslations,
AggregationType,
DAY,
HistoryWindowType,
quickTimeIntervalPeriod,
RealtimeWindowType,
Timewindow,
TimewindowType
} from '@shared/models/time/time.models';
import { OverlayRef } from '@angular/cdk/overlay';
import { PageComponent } from '@shared/components/page.component';
import { Store } from '@ngrx/store';
import { AppState } from '@core/core.state';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { TimeService } from '@core/services/time.service';
export const TIMEWINDOW_PANEL_DATA = new InjectionToken<any>('TimewindowPanelData');
export interface TimewindowPanelData {
historyOnly: boolean;
timewindow: Timewindow;
aggregation: boolean;
timezone: boolean;
isEdit: boolean;
}
@Component({
selector: 'tb-timewindow-panel',
templateUrl: './timewindow-panel.component.html',
styleUrls: ['./timewindow-panel.component.scss']
})
export class TimewindowPanelComponent extends PageComponent implements OnInit {
historyOnly = false;
aggregation = false;
timezone = false;
isEdit = false;
timewindow: Timewindow;
result: Timewindow;
timewindowForm: FormGroup;
historyTypes = HistoryWindowType;
realtimeTypes = RealtimeWindowType;
timewindowTypes = TimewindowType;
aggregationTypes = AggregationType;
aggregations = Object.keys(AggregationType);
aggregationTypesTranslations = aggregationTranslations;
constructor(@Inject(TIMEWINDOW_PANEL_DATA) public data: TimewindowPanelData,
public overlayRef: OverlayRef,
protected store: Store<AppState>,
public fb: FormBuilder,
private timeService: TimeService,
public viewContainerRef: ViewContainerRef) {
super(store);
this.historyOnly = data.historyOnly;
this.timewindow = data.timewindow;
this.aggregation = data.aggregation;
this.timezone = data.timezone;
this.isEdit = data.isEdit;
}
ngOnInit(): void {
const hideInterval = this.timewindow.hideInterval || false;
const hideAggregation = this.timewindow.hideAggregation || false;
const hideAggInterval = this.timewindow.hideAggInterval || false;
const hideTimezone = this.timewindow.hideTimezone || false;
this.timewindowForm = this.fb.group({
realtime: this.fb.group(
{
realtimeType: this.fb.control({
value: this.timewindow.realtime && typeof this.timewindow.realtime.realtimeType !== 'undefined'
? this.timewindow.realtime.realtimeType : RealtimeWindowType.LAST_INTERVAL,
disabled: hideInterval
}),
timewindowMs: [
this.timewindow.realtime && typeof this.timewindow.realtime.timewindowMs !== 'undefined'
? this.timewindow.realtime.timewindowMs : null
],
interval: [
this.timewindow.realtime && typeof this.timewindow.realtime.interval !== 'undefined'
? this.timewindow.realtime.interval : null
],
quickInterval: this.fb.control({
value: this.timewindow.realtime && typeof this.timewindow.realtime.quickInterval !== 'undefined'
? this.timewindow.realtime.quickInterval : null,
disabled: hideInterval
})
}
),
history: this.fb.group(
{
historyType: this.fb.control({
value: this.timewindow.history && typeof this.timewindow.history.historyType !== 'undefined'
? this.timewindow.history.historyType : HistoryWindowType.LAST_INTERVAL,
disabled: hideInterval
}),
timewindowMs: this.fb.control({
value: this.timewindow.history && typeof this.timewindow.history.timewindowMs !== 'undefined'
? this.timewindow.history.timewindowMs : null,
disabled: hideInterval
}),
interval: [
this.timewindow.history && typeof this.timewindow.history.interval !== 'undefined'
? this.timewindow.history.interval : null
],
fixedTimewindow: this.fb.control({
value: this.timewindow.history && typeof this.timewindow.history.fixedTimewindow !== 'undefined'
? this.timewindow.history.fixedTimewindow : null,
disabled: hideInterval
}),
quickInterval: this.fb.control({
value: this.timewindow.history && typeof this.timewindow.history.quickInterval !== 'undefined'
? this.timewindow.history.quickInterval : null,
disabled: hideInterval
})
}
),
aggregation: this.fb.group(
{
type: this.fb.control({
value: this.timewindow.aggregation && typeof this.timewindow.aggregation.type !== 'undefined'
? this.timewindow.aggregation.type : null,
disabled: hideAggregation
}),
limit: this.fb.control({
value: this.timewindow.aggregation && typeof this.timewindow.aggregation.limit !== 'undefined'
? this.timewindow.aggregation.limit : null,
disabled: hideAggInterval
}, [Validators.min(this.minDatapointsLimit()), Validators.max(this.maxDatapointsLimit())])
}
),
timezone: this.fb.control({
value: this.timewindow.timezone !== 'undefined'
? this.timewindow.timezone : null,
disabled: hideTimezone
})
});
}
update() {
const timewindowFormValue = this.timewindowForm.getRawValue();
this.timewindow.realtime = {
realtimeType: timewindowFormValue.realtime.realtimeType,
timewindowMs: timewindowFormValue.realtime.timewindowMs,
quickInterval: timewindowFormValue.realtime.quickInterval,
interval: timewindowFormValue.realtime.interval
};
this.timewindow.history = {
historyType: timewindowFormValue.history.historyType,
timewindowMs: timewindowFormValue.history.timewindowMs,
interval: timewindowFormValue.history.interval,
fixedTimewindow: timewindowFormValue.history.fixedTimewindow,
quickInterval: timewindowFormValue.history.quickInterval,
};
if (this.aggregation) {
this.timewindow.aggregation = {
type: timewindowFormValue.aggregation.type,
limit: timewindowFormValue.aggregation.limit
};
}
if (this.timezone) {
this.timewindow.timezone = timewindowFormValue.timezone;
}
this.result = this.timewindow;
this.overlayRef.dispose();
}
cancel() {
this.overlayRef.dispose();
}
minDatapointsLimit() {
return this.timeService.getMinDatapointsLimit();
}
maxDatapointsLimit() {
return this.timeService.getMaxDatapointsLimit();
}
minRealtimeAggInterval() {
return this.timeService.minIntervalLimit(this.currentRealtimeTimewindow());
}
maxRealtimeAggInterval() {
return this.timeService.maxIntervalLimit(this.currentRealtimeTimewindow());
}
currentRealtimeTimewindow(): number {
const timeWindowFormValue = this.timewindowForm.getRawValue();
switch (timeWindowFormValue.realtime.realtimeType) {
case RealtimeWindowType.LAST_INTERVAL:
return timeWindowFormValue.realtime.timewindowMs;
case RealtimeWindowType.INTERVAL:
return quickTimeIntervalPeriod(timeWindowFormValue.realtime.quickInterval);
default:
return DAY;
}
}
minHistoryAggInterval() {
return this.timeService.minIntervalLimit(this.currentHistoryTimewindow());
}
maxHistoryAggInterval() {
return this.timeService.maxIntervalLimit(this.currentHistoryTimewindow());
}
currentHistoryTimewindow() {
const timewindowFormValue = this.timewindowForm.getRawValue();
if (timewindowFormValue.history.historyType === HistoryWindowType.LAST_INTERVAL) {
return timewindowFormValue.history.timewindowMs;
} else if (timewindowFormValue.history.historyType === HistoryWindowType.INTERVAL) {
return quickTimeIntervalPeriod(timewindowFormValue.history.quickInterval);
} else if (timewindowFormValue.history.fixedTimewindow) {
return timewindowFormValue.history.fixedTimewindow.endTimeMs -
timewindowFormValue.history.fixedTimewindow.startTimeMs;
} else {
return DAY;
}
}
onHideIntervalChanged() {
if (this.timewindow.hideInterval) {
this.timewindowForm.get('history.historyType').disable({emitEvent: false});
this.timewindowForm.get('history.timewindowMs').disable({emitEvent: false});
this.timewindowForm.get('history.fixedTimewindow').disable({emitEvent: false});
this.timewindowForm.get('history.quickInterval').disable({emitEvent: false});
this.timewindowForm.get('realtime.realtimeType').disable({emitEvent: false});
this.timewindowForm.get('realtime.timewindowMs').disable({emitEvent: false});
this.timewindowForm.get('realtime.quickInterval').disable({emitEvent: false});
} else {
this.timewindowForm.get('history.historyType').enable({emitEvent: false});
this.timewindowForm.get('history.timewindowMs').enable({emitEvent: false});
this.timewindowForm.get('history.fixedTimewindow').enable({emitEvent: false});
this.timewindowForm.get('history.quickInterval').enable({emitEvent: false});
this.timewindowForm.get('realtime.realtimeType').enable({emitEvent: false});
this.timewindowForm.get('realtime.timewindowMs').enable({emitEvent: false});
this.timewindowForm.get('realtime.quickInterval').enable({emitEvent: false});
}
this.timewindowForm.markAsDirty();
}
onHideAggregationChanged() {
if (this.timewindow.hideAggregation) {
this.timewindowForm.get('aggregation.type').disable({emitEvent: false});
} else {
this.timewindowForm.get('aggregation.type').enable({emitEvent: false});
}
this.timewindowForm.markAsDirty();
}
onHideAggIntervalChanged() {
if (this.timewindow.hideAggInterval) {
this.timewindowForm.get('aggregation.limit').disable({emitEvent: false});
} else {
this.timewindowForm.get('aggregation.limit').enable({emitEvent: false});
}
this.timewindowForm.markAsDirty();
}
onHideTimezoneChanged() {
if (this.timewindow.hideTimezone) {
this.timewindowForm.get('timezone').disable({emitEvent: false});
} else {
this.timewindowForm.get('timezone').enable({emitEvent: false});
}
this.timewindowForm.markAsDirty();
}
} | the_stack |
import { fireEvent, render } from "@testing-library/react";
import { expect } from "chai";
import * as enzyme from "enzyme";
import * as React from "react";
import * as sinon from "sinon";
import { Key } from "ts-key-enum";
import { FilteringInput, FilteringInputStatus } from "../../components-react/filtering/FilteringInput";
import { ResultSelector } from "../../components-react/filtering/ResultSelector";
import TestUtils from "../TestUtils";
describe("FilteringInput", () => {
before(async () => {
await TestUtils.initializeUiComponents();
});
it("renders correctly", () => {
const filteringInput = enzyme.mount(
<FilteringInput
status={FilteringInputStatus.ReadyToFilter}
onFilterCancel={() => { }}
onFilterClear={() => { }}
onFilterStart={() => { }}
resultSelectorProps={{ onSelectedChanged: () => { }, resultCount: 0 }} />);
expect(filteringInput.find("input[type=\"text\"]").first().exists()).to.be.true;
const actionIcon = filteringInput.find(".components-filtering-input-input-components").childAt(0);
expect(actionIcon.render().hasClass("icon-search"));
});
it("shows 'Cancel' button when filtering status is `FilteringInProgress`", () => {
const filteringInput = enzyme.mount(
<FilteringInput
status={FilteringInputStatus.FilteringInProgress}
onFilterCancel={() => { }}
onFilterClear={() => { }}
onFilterStart={() => { }}
resultSelectorProps={{ onSelectedChanged: () => { }, resultCount: 0 }} />);
const actionIcon = filteringInput.find(".components-filtering-input-input-components").childAt(0);
expect(actionIcon.render().hasClass("icon-close"));
});
it("shows `ResultSelector` and 'X' button when filtering status is `FilteringFinished` and stepping is enabled", () => {
const filteringInput = enzyme.mount(
<FilteringInput
status={FilteringInputStatus.FilteringFinished}
onFilterCancel={() => { }}
onFilterClear={() => { }}
onFilterStart={() => { }}
resultSelectorProps={{ onSelectedChanged: () => { }, resultCount: 0 }} />);
expect(filteringInput.find(ResultSelector).first().exists(), "No ResultSelector found").to.be.true;
expect(filteringInput.find(".components-filtering-input-clear").first().hasClass("icon-close"), "No X button found").to.be.true;
});
it("doesn't show `ResultSelector` when filtering status is `FilteringFinished` and stepping is disabled", () => {
const filteringInput = enzyme.mount(
<FilteringInput
status={FilteringInputStatus.FilteringFinished}
onFilterCancel={() => { }}
onFilterClear={() => { }}
onFilterStart={() => { }} />);
expect(filteringInput.find(ResultSelector).first().exists()).to.be.false;
expect(filteringInput.find(".components-filtering-input-clear").first().hasClass("icon-close"), "No X button found").to.be.true;
});
it("starts search when input is edited and 'Enter' key is pressed", () => {
const startCallback = sinon.spy();
const filteringInput = enzyme.mount(
<FilteringInput
status={FilteringInputStatus.ReadyToFilter}
onFilterCancel={() => { }}
onFilterClear={() => { }}
onFilterStart={startCallback}
resultSelectorProps={{ onSelectedChanged: () => { }, resultCount: 0 }} />);
const inputField = filteringInput.find("input[type=\"text\"]").first();
inputField.simulate("change", { target: { value: "test" } });
inputField.simulate("keyDown", { key: Key.Backspace });
expect(startCallback).to.not.be.called;
inputField.simulate("keyDown", { key: Key.Enter });
expect(startCallback).to.be.calledOnce;
});
it("doesn't start search when input is empty", () => {
const startCallback = sinon.spy();
const filteringInput = enzyme.mount(
<FilteringInput
status={FilteringInputStatus.ReadyToFilter}
onFilterCancel={() => { }}
onFilterClear={() => { }}
onFilterStart={startCallback} />);
const inputField = filteringInput.find("input[type=\"text\"]").first();
expect(inputField.props().value).to.be.empty;
inputField.simulate("keyDown", { key: Key.Enter });
expect(startCallback).to.not.be.called;
const searchButton = filteringInput.find(".components-filtering-input-input-components>.icon-search");
searchButton.simulate("click");
expect(startCallback).to.not.be.called;
});
it("calls appropriate callbacks to different button clicks", () => {
const cancelCallback = sinon.spy();
const clearCallback = sinon.spy();
const startCallback = sinon.spy();
const filteringInput = enzyme.mount(
<FilteringInput
status={FilteringInputStatus.ReadyToFilter}
onFilterCancel={cancelCallback}
onFilterClear={clearCallback}
onFilterStart={startCallback} />);
const inputField = filteringInput.find("input[type=\"text\"]").first();
inputField.simulate("change", { target: { value: "test" } });
filteringInput.find(".components-filtering-input-input-components>.icon-search").simulate("click");
expect(startCallback).to.be.calledOnce;
filteringInput.setProps({ status: FilteringInputStatus.FilteringInProgress });
filteringInput.find(".components-filtering-input-input-components>.icon-close").simulate("click");
expect(cancelCallback).to.be.calledOnce;
filteringInput.setProps({ status: FilteringInputStatus.ReadyToFilter });
inputField.simulate("change", { target: { value: "test" } });
filteringInput.find(".components-filtering-input-input-components>.icon-search").simulate("click");
filteringInput.setProps({ status: FilteringInputStatus.FilteringInProgress });
filteringInput.setProps({ status: FilteringInputStatus.FilteringFinished, resultSelectorProps: { onSelectedChanged: () => { }, resultCount: 0 } });
filteringInput.find(".components-filtering-input-clear").simulate("click");
expect(clearCallback).to.be.calledOnce;
});
it("calls onFilterCancel when input text is changed after starting the search", () => {
const cancelCallback = sinon.spy();
const filteringInput = render(
<FilteringInput
onFilterCancel={cancelCallback}
onFilterClear={() => { }}
onFilterStart={() => { }}
status={FilteringInputStatus.ReadyToFilter} />);
const searchBar = filteringInput.container.querySelector('[class="components-filtering-input-input"]')?.firstChild;
const searchIcon = filteringInput.container.querySelector('[class="icon icon-search"]');
expect(searchBar).to.exist;
expect(searchIcon).to.exist;
fireEvent.change(searchBar as Element, { target: { value: "test" } });
fireEvent.click(searchIcon as Element);
fireEvent.change(searchBar as Element, { target: { value: "testing" } });
expect(cancelCallback).to.be.calledOnce;
});
it("does not render `ResultSelector` but renders `search` button when status is set to `ReadyToFilter`", () => {
const filteringInput = render(
<FilteringInput
onFilterCancel={() => { }}
onFilterClear={() => { }}
onFilterStart={() => { }}
status={FilteringInputStatus.ReadyToFilter} />);
expect(filteringInput.container.querySelector('[class="components-result-selector"]'), "ResultSelector found").to.not.exist;
expect(filteringInput.container.querySelector('[class="icon icon-search"]'), "Search icon found").to.exist;
});
it("does not render `ResultSelector` but renders `X` button when status is set to `FilteringInProgress`", () => {
const filteringInput = render(
<FilteringInput
onFilterCancel={() => { }}
onFilterClear={() => { }}
onFilterStart={() => { }}
status={FilteringInputStatus.FilteringInProgress} />);
expect(filteringInput.container.querySelector('[class="components-result-selector"]'), "ResultSelector found").to.not.exist;
expect(filteringInput.container.querySelector('[class="icon icon-close"]'), "X button found").to.exist;
});
it("renders `ResultSelector` and 'X' button when status is set to `FilteringFinished` and `resultSelectorProps` are provided ", () => {
const filteringInput = render(
<FilteringInput
onFilterCancel={() => { }}
onFilterClear={() => { }}
onFilterStart={() => { }}
status={FilteringInputStatus.FilteringFinished}
resultSelectorProps={{ onSelectedChanged: () => { }, resultCount: 0 }} />);
expect(filteringInput.container.querySelector('[class="components-result-selector"]'), "ResultSelector found").to.exist;
expect(filteringInput.container.querySelector('[class="components-filtering-input-clear icon icon-close"]'), "X button found").to.exist;
});
it("doesn't render `ResultSelector` but renders 'X' button when status is set to `FilteringFinished` and `resultSelectorProps` are not provided ", () => {
const filteringInput = render(
<FilteringInput
onFilterCancel={() => { }}
onFilterClear={() => { }}
onFilterStart={() => { }}
status={FilteringInputStatus.FilteringFinished} />);
expect(filteringInput.container.querySelector('[class="components-result-selector"]'), "ResultSelector found").to.not.exist;
expect(filteringInput.container.querySelector('[class="components-filtering-input-clear icon icon-close"]'), "X button found").to.exist;
});
it("re-renders ResultSelector(sets activeMatchIndex to 1) when resultSelectorProps are updated when using status property", () => {
const filteringInput = render(
<FilteringInput
onFilterCancel={() => { }}
onFilterClear={() => { }}
onFilterStart={() => { }}
resultSelectorProps={{ onSelectedChanged: () => { }, resultCount: 5 }}
status={FilteringInputStatus.FilteringFinished} />);
expect(filteringInput.getByText("1")).to.exist;
const nextButton = filteringInput.container.querySelector('[class="components-result-selector-button icon icon-chevron-right"]');
expect(nextButton).to.exist;
fireEvent.click(nextButton as Element);
expect(filteringInput.getByText("2")).to.exist;
filteringInput.rerender(
<FilteringInput
onFilterCancel={() => { }}
onFilterClear={() => { }}
onFilterStart={() => { }}
resultSelectorProps={{ onSelectedChanged: () => { }, resultCount: 5 }}
status={FilteringInputStatus.FilteringFinished} />);
expect(filteringInput.getByText("1")).to.exist;
});
}); | the_stack |
import {
AnyFunction,
Cartesian2Option,
Cartesian3Option,
Cartesian4Option,
PolygonHierarchyOption,
CartographicInDegreeOption,
NearFarScalarOption,
DistanceDisplayConditionOption,
ColorInByteOption,
MaterialOption,
VcComponentInternalInstance,
RectangleInDegreeOption,
BoundingRectangleOption,
PlaneOption,
TranslationRotationScaleOption,
CameraOption,
HeadingPitchRollOption
} from './types'
import { hasOwn, isFunction, isArray, isString, isPlainObject, isEmptyObj, getObjClassName } from './util'
/**
* 将对象或数组转换为 Cesium.Cartesian2
* @param {Object} val
* @returns {Cartesian2 | CallbackProperty} 返回 Cartesian2 或者 CallbackProperty
* @example
* const options = [100, 100]
* // const options = [x: 100, y: 100]
* const position = makeCartesian2(options)
*/
export function makeCartesian2(
val: Cesium.CallbackProperty | Cesium.Cartesian2 | Cartesian2Option | Array<number> | AnyFunction<any>,
isConstant = false
): Cesium.Cartesian2 | Cesium.CallbackProperty | undefined {
const { Cartesian2, CallbackProperty } = Cesium
if (val instanceof Cesium.Cartesian2 || val instanceof CallbackProperty) {
return val
}
if (isPlainObject(val)) {
if (hasOwn(val, 'x') && hasOwn(val, 'y')) {
const value = val as Cartesian2Option
return new Cartesian2(value.x, value.y)
}
}
if (isArray(val)) {
return new Cartesian2(val[0], val[1])
}
if (isFunction(val)) {
return new CallbackProperty(val, isConstant)
}
return undefined
}
/**
* 将对象或者数组转换为 Cesium.Cartesian3
* @param {Object} val 传入的对象或数组
* @param {Boolean} isConstant 传入function时生效,true 代表回调 function 每时每刻都返回值, false 代表改变才会返回值。默认false。
* @returns 返回 Cartesian3 或者 CallbackProperty
* @example
* const options = {
* lng: 108,
* lat: 35,
* height: 1000
* }
* // const options = [108, 35, 1000]
* const position = makeCartesian3 (options) // return Cesium.Cartesian3
*/
export function makeCartesian3(
val: Cesium.CallbackProperty | Cesium.Cartesian3 | Cartesian3Option | CartographicInDegreeOption | Array<number> | AnyFunction<any>,
ellipsoid?: Cesium.Ellipsoid,
isConstant = false
):
| Cesium.Cartesian3
| Cesium.CallbackProperty
| Cesium.SampledPositionProperty
| Cesium.CompositePositionProperty
| Cesium.ConstantPositionProperty
| Cesium.TimeIntervalCollectionPositionProperty
| undefined {
const {
CallbackProperty,
Cartesian3,
Ellipsoid,
SampledPositionProperty,
CompositePositionProperty,
ConstantPositionProperty,
TimeIntervalCollectionPositionProperty
} = Cesium
if (
val instanceof Cartesian3 ||
val instanceof CallbackProperty ||
val instanceof SampledPositionProperty ||
val instanceof CompositePositionProperty ||
val instanceof ConstantPositionProperty ||
val instanceof TimeIntervalCollectionPositionProperty
) {
return val
}
ellipsoid = ellipsoid || Ellipsoid.WGS84
if (isPlainObject(val)) {
if (hasOwn(val, 'x') && hasOwn(val, 'y') && hasOwn(val, 'z')) {
const value = val as Cartesian3Option
return new Cartesian3(value.x, value.y, value.z)
} else if (hasOwn(val, 'lng') && hasOwn(val, 'lat')) {
const value = val as CartographicInDegreeOption
return Cartesian3.fromDegrees(value.lng!, value.lat!, value.height || 0, ellipsoid)
}
}
// 经纬度数组
if (isArray(val)) {
return Cartesian3.fromDegrees(val[0], val[1], val[2] || 0, ellipsoid)
}
if (isFunction(val)) {
return new CallbackProperty(val, isConstant)
}
return undefined
}
/**
* 将数组 [lng, lat, height, ……,lng, lat, height] 转换为 Cesium.Cartesian3 数组
* @param {Array} val
* @returns {Array<Cartesian3>}
*/
export function makeCartesian3Array(
vals:
| Cesium.CallbackProperty
| Array<Cesium.Cartesian3>
| Array<Cartesian3Option>
| Array<CartographicInDegreeOption>
| Array<number>
| Array<Array<number>>
| AnyFunction<any>,
ellipsoid?: Cesium.Ellipsoid,
isConstant = false
): Array<Cesium.Cartesian3> | Cesium.CallbackProperty | undefined {
const { CallbackProperty, Cartesian3, Ellipsoid } = Cesium
if (vals instanceof CallbackProperty) {
return vals
}
if (isFunction(vals)) {
return new CallbackProperty(vals, isConstant)
}
ellipsoid = ellipsoid || Ellipsoid.WGS84
if (isArray(vals)) {
if (isArray(vals[0]) || isPlainObject(vals[0])) {
const results: Array<any> = []
vals.forEach(val => {
results.push(makeCartesian3(val, ellipsoid))
})
return results
}
return Cartesian3.fromDegreesArrayHeights(vals as Array<number>, ellipsoid)
}
return undefined
}
/**
* 将形如 [lng, lat, ……,lng, lat] 数组转换为 Cesium.Cartesian2 数组
* @param {Array} vals
* @returns {Array<Cartesian2>}
*/
export function makeCartesian2Array(
vals: Cesium.CallbackProperty | Array<Cesium.Cartesian2> | Array<Cartesian2Option> | Array<Array<number>> | Array<number> | AnyFunction<any>,
isConstant
): Cesium.CallbackProperty | Array<Cesium.Cartesian2> | undefined {
const { CallbackProperty, Cartesian2 } = Cesium
if (vals instanceof CallbackProperty) {
return vals
}
if (isFunction(vals)) {
return new CallbackProperty(vals, isConstant)
}
if (isArray(vals)) {
const points: Array<Cesium.Cartesian2> = []
vals.forEach(val => {
points.push(makeCartesian2(val) as Cesium.Cartesian2)
})
return points
}
return undefined
}
/**
* 将对象或数组 转换为 Cesium.Quaternion
* @param {Object} val
* @example
* const options = {x: 0, y: 0, z: 0, w: 0}
* // const options = [0, 0, 0, 0]
* const orientation = makeQuaternion(options) // returns Cesium.Quaternion
*/
export function makeQuaternion(
val: Cesium.CallbackProperty | Cesium.Quaternion | Cartesian4Option | Array<number> | AnyFunction<any>,
isConstant = false
): Cesium.CallbackProperty | Cesium.Quaternion | Cesium.VelocityOrientationProperty | undefined {
const { CallbackProperty, Quaternion, VelocityOrientationProperty } = Cesium
if (val instanceof Quaternion || val instanceof CallbackProperty || val instanceof VelocityOrientationProperty) {
return val
}
if (isPlainObject(val) && hasOwn(val, 'x') && hasOwn(val, 'y')) {
const value = val as Cartesian4Option
return new Quaternion(value.x, value.y, value.z, value.w)
}
if (isArray(val)) {
return new Quaternion(val[0], val[1], val[2], val[3])
}
if (isFunction(val)) {
return new CallbackProperty(val, isConstant)
}
return undefined
}
/**
* 解析 HierarchyJson
* @param {Object} val
*/
function parsePolygonHierarchyJson(val: Array<PolygonHierarchyOption>, ellipsoid?: Cesium.Ellipsoid) {
val.forEach(item => {
item.positions = makeCartesian3Array(item.positions, ellipsoid) as Array<Cesium.Cartesian3>
if (item.holes) {
parsePolygonHierarchyJson(item.holes, ellipsoid)
}
})
}
/**
* 普通数组或对象转 Cesium.PolygonHierarchy 对象。
* @param {Object|Array} val
*/
export function makePolygonHierarchy(
val:
| Cesium.CallbackProperty
| Cesium.PolygonHierarchy
| PolygonHierarchyOption
| Array<Cesium.Cartesian3>
| Array<Cartesian3Option>
| Array<Array<number>>
| AnyFunction<any>,
ellipsoid?: Cesium.Ellipsoid,
isConstant = false
): Cesium.CallbackProperty | Cesium.PolygonHierarchy | PolygonHierarchyOption | undefined {
const { PolygonHierarchy, CallbackProperty } = Cesium
if (val instanceof PolygonHierarchy || val instanceof CallbackProperty) {
return val
}
if (isFunction(val)) {
return new CallbackProperty(val, isConstant)
}
if (isArray(val) && val.length >= 3) {
const points = makeCartesian3Array(val, ellipsoid) as Array<Cesium.Cartesian3>
return new PolygonHierarchy(points)
}
if (isPlainObject(val) && hasOwn(val, 'positions')) {
const value = val as PolygonHierarchyOption
value.positions = makeCartesian3Array(value.positions, ellipsoid) as Array<Cesium.Cartesian3>
parsePolygonHierarchyJson(value.holes!, ellipsoid)
return value
}
return undefined
}
/**
* 对象或数组转 Cesium.NearFarScalar。
* @param {Object} val
* @returns {NearFarScalar}
* @example
* const options = {near: 1000, nearValue: 1.0, far: 10000, farValue: 0.5}
* // const options = [1000, 1.0, 10000, 1.5]
* const nearFarScalar = makeNearFarScalar(options)
*/
export function makeNearFarScalar(
val: Cesium.NearFarScalar | Cesium.CallbackProperty | NearFarScalarOption | Array<number> | AnyFunction<any>,
isConstant = false
): Cesium.NearFarScalar | Cesium.CallbackProperty | undefined {
const { NearFarScalar, CallbackProperty } = Cesium
if (val instanceof NearFarScalar || val instanceof CallbackProperty) {
return val
}
if (isPlainObject(val) && hasOwn(val, 'near') && hasOwn(val, 'far')) {
const value = val as NearFarScalarOption
return new NearFarScalar(value.near, value.nearValue || 0.0, value.far, value.farValue || 1.0)
}
if (isArray(val)) {
return new NearFarScalar(val[0], val[1], val[2], val[3])
}
if (isFunction(val)) {
return new CallbackProperty(val, isConstant)
}
return undefined
}
/**
* 对象或数组转 Cesium.DistanceDisplayCondition。
* @param {Object} val
* @returns {DistanceDisplayCondition}
* @example
* const options = [0, 1000]
* // const options = {near: 0, far: 1000}
* const distanceDisplayCondition = makeDistanceDisplayCondition(options) // return Cesium.DistanceDisplayCondition
*/
export function makeDistanceDisplayCondition(
val: Cesium.DistanceDisplayCondition | Cesium.CallbackProperty | DistanceDisplayConditionOption | Array<number> | AnyFunction<any>,
isConstant = false
): Cesium.DistanceDisplayCondition | Cesium.CallbackProperty | undefined {
const { DistanceDisplayCondition, CallbackProperty } = Cesium
if (val instanceof DistanceDisplayCondition || val instanceof CallbackProperty) {
return val
}
if (isPlainObject(val) && hasOwn(val, 'near') && hasOwn(val, 'far')) {
const value = val as DistanceDisplayConditionOption
return new DistanceDisplayCondition(value.near, value.far)
}
if (isArray(val)) {
return new DistanceDisplayCondition(val[0], val[1])
}
if (isFunction(val)) {
return new CallbackProperty(val, isConstant)
}
return undefined
}
/**
* 普通对象、数组或字符串转 Cesium.Color。
* @param {String|Array|Object|Function} val
* @returns {Color}
* @example
* const options = 'red'
* // const options = [1, 0, 0, 1.0] // r g b a
* // const options = {red: 255, green: 0, bule: 0, alpha: 255}
* const color = makeColor(options) // return Cesium.Color
*/
export function makeColor(
val: Cesium.Color | Cesium.CallbackProperty | string | Array<number> | ColorInByteOption | Cartesian4Option | AnyFunction<any>,
isConstant = false
): Cesium.Color | Cesium.CallbackProperty | undefined {
const { Color, CallbackProperty } = Cesium
if (val instanceof Color || val instanceof CallbackProperty) {
return val
}
if (isString(val)) {
return Color.fromCssColorString(val)
}
if (isPlainObject(val)) {
if (hasOwn(val, 'red')) {
const value = val as ColorInByteOption
return Color.fromBytes(value.red, value.green || 255, value.blue || 255, value.alpha || 255)
} else if (hasOwn(val, 'x')) {
const value = val as Cartesian4Option
return new Color(value.x, value.y || 1, value.z || 1, value.w || 1)
}
}
if (isArray(val)) {
return Color.fromBytes(val[0], val[1], val[2], val[3] || 255)
}
if (isFunction(val)) {
return new CallbackProperty(val, isConstant)
}
return undefined
}
export function makeColors(vals: Cesium.Color[] | string[] | number[][] | ColorInByteOption[] | Cartesian4Option[]): Cesium.Color[] {
if (isArray(vals)) {
const results: Cesium.Color[] = []
vals.forEach(val => {
results.push(makeColor(val) as Cesium.Color)
})
return results
} else {
return vals
}
}
/**
* 普通对象或数组 [r, g, b, a] 或字符串转 MaterialProperty
* @param {String|Array|Object} val
*/
export function makeMaterialProperty(
val:
| Cesium.CallbackProperty
| Cesium.Color
| Cesium.CheckerboardMaterialProperty
| Cesium.ColorMaterialProperty
| Cesium.GridMaterialProperty
| Cesium.ImageMaterialProperty
| Cesium.PolylineArrowMaterialProperty
| Cesium.PolylineDashMaterialProperty
| Cesium.PolylineGlowMaterialProperty
| Cesium.PolylineOutlineMaterialProperty
| Cesium.StripeMaterialProperty
| MaterialOption
| string
| Array<number>
| HTMLImageElement
| HTMLCanvasElement
| HTMLVideoElement
| AnyFunction<any>,
isConstant = false
) {
const {
CallbackProperty,
Color,
CheckerboardMaterialProperty,
ColorMaterialProperty,
GridMaterialProperty,
ImageMaterialProperty,
PolylineArrowMaterialProperty,
PolylineDashMaterialProperty,
PolylineGlowMaterialProperty,
PolylineOutlineMaterialProperty,
StripeMaterialProperty,
StripeOrientation
} = Cesium
if (
val instanceof CallbackProperty ||
val instanceof Color ||
val instanceof CheckerboardMaterialProperty ||
val instanceof ColorMaterialProperty ||
val instanceof ImageMaterialProperty ||
val instanceof PolylineArrowMaterialProperty ||
val instanceof PolylineDashMaterialProperty ||
val instanceof PolylineGlowMaterialProperty ||
val instanceof PolylineOutlineMaterialProperty ||
val instanceof StripeMaterialProperty ||
getObjClassName(val as any).indexOf('MaterialProperty') !== -1
) {
return val
}
if (
(isString(val) && /(.*)\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)$/.test(val)) ||
val instanceof HTMLImageElement ||
val instanceof HTMLCanvasElement ||
val instanceof HTMLVideoElement
) {
return new ImageMaterialProperty({
image: val,
repeat: makeCartesian2({ x: 1.0, y: 1.0 }),
color: Color.WHITE,
transparent: true
})
}
if (isArray(val) || isString(val)) {
return new ColorMaterialProperty(makeColor(val))
}
if (isPlainObject(val) && hasOwn(val, 'fabric')) {
const value = val as MaterialOption
switch (value.fabric.type) {
case 'Image':
return new ImageMaterialProperty({
image: value.fabric.uniforms.image,
repeat: makeCartesian2((value.fabric.uniforms.repeat as Cartesian2Option) || { x: 1.0, y: 1.0 }),
color: makeColor(value.fabric.uniforms.color!) || Color.WHITE,
transparent: value.fabric.uniforms.transparent || false
})
case 'Color':
return new ColorMaterialProperty(makeColor(value.fabric.uniforms.color || Color.WHITE))
case 'PolylineArrow':
return new PolylineArrowMaterialProperty(makeColor(value.fabric.uniforms.color || Color.WHITE))
case 'PolylineDash':
return new PolylineDashMaterialProperty({
color: makeColor(value.fabric.uniforms.color || 'white') || Color.WHITE,
gapColor: makeColor(value.fabric.uniforms.gapColor!) || Color.TRANSPARENT,
dashLength: value.fabric.uniforms.taperPower || 16.0,
dashPattern: value.fabric.uniforms.taperPower || 255.0
})
case 'PolylineGlow':
return new PolylineGlowMaterialProperty({
color: makeColor(value.fabric.uniforms.color!) || Color.WHITE,
glowPower: value.fabric.uniforms.glowPower || 0.25,
taperPower: value.fabric.uniforms.taperPower || 1.0
})
case 'PolylineOutline':
return new PolylineOutlineMaterialProperty({
color: makeColor(value.fabric.uniforms.color!) || Color.WHITE,
outlineColor: makeColor(value.fabric.uniforms.outlineColor!) || Color.BLACK,
outlineWidth: value.fabric.uniforms.outlineWidth || 1.0
})
case 'Checkerboard':
return new CheckerboardMaterialProperty({
evenColor: makeColor(value.fabric.uniforms.evenColor!) || Color.WHITE,
oddColor: makeColor(value.fabric.uniforms.oddColor!) || Color.BLACK,
repeat: makeCartesian2((value.fabric.uniforms.repeat as Cartesian2Option) || { x: 2, y: 2 })
})
case 'Grid':
return new GridMaterialProperty({
color: makeColor(value.fabric.uniforms.color!) || Color.WHITE,
cellAlpha: value.fabric.uniforms.cellAlpha || 0.1,
lineCount: makeCartesian2((value.fabric.uniforms.lineCount as Cartesian2Option) || { x: 8, y: 8 }),
lineThickness: makeCartesian2((value.fabric.uniforms.lineThickness as Cartesian2Option) || { x: 1, y: 1 }),
lineOffset: makeCartesian2((value.fabric.uniforms.lineOffset as Cartesian2Option) || { x: 0, y: 0 })
})
case 'Stripe':
return new StripeMaterialProperty({
orientation: value.fabric.uniforms.orientation || StripeOrientation.HORIZONTAL,
evenColor: makeColor(value.fabric.uniforms.evenColor || 'white'),
oddColor: makeColor(value.fabric.uniforms.oddColor || 'black'),
offset: value.fabric.uniforms.offset || 0,
repeat: (value.fabric.uniforms.repeat as number) || 1
})
}
}
if (isFunction(val)) {
return new CallbackProperty(val, isConstant)
}
return val
}
/**
* 转 Material
* @param {String|Array|Object} val
*/
export function makeMaterial(this, val: string | Array<number> | MaterialOption) {
const vcInstance = this as VcComponentInternalInstance
const cmpName = vcInstance.proxy?.$options.name
if (cmpName && (cmpName.indexOf('Graphics') || cmpName.indexOf('Datasource')) !== -1) {
return makeMaterialProperty(val)
}
const { Material, combine } = Cesium
if (val instanceof Material) {
return val
}
if (isPlainObject(val) && hasOwn(val, 'fabric')) {
const f = obj => {
for (const i in obj) {
if (!isArray(obj[i]) && isPlainObject(obj[i])) {
f(obj[i])
} else {
if (i.toLocaleLowerCase().indexOf('color') !== -1 && !isEmptyObj(obj[i])) {
const result = makeColor(obj[i])
// Cesium 通过对象属性个数判断具体材质类型的,通过 Cesium.combine 移除 vue 传的一些属性
obj[i] = combine(result, result, true)
}
}
}
}
f(val)
return new Material(val as MaterialOption)
}
if (isArray(val) || isString(val)) {
const material = Material.fromType('Color')
material.uniforms.color = makeColor(val)
return material
}
return undefined
}
/**
* 将对象 {west: number, south: number, east: number, north: number} 或者[west, south, east, north]数组 转 Cesium.Rectangle 对象。
* @param {Object} val
* @returns {Rectangle}
*/
export function makeRectangle(
val: Cesium.Rectangle | Cesium.CallbackProperty | RectangleInDegreeOption | Cartesian4Option | Array<number> | AnyFunction<any>,
isConstant = false
): Cesium.Rectangle | Cesium.CallbackProperty | Cesium.RectangleGraphics | undefined {
const { Rectangle, RectangleGraphics, CallbackProperty } = Cesium
// Entiy 的 rectangle 属性不能调用这个方法
if (val instanceof RectangleGraphics || val instanceof Rectangle || val instanceof CallbackProperty) {
return val
}
if (isArray(val)) {
return Rectangle.fromDegrees(val[0], val[1], val[2], val[3])
}
if (isPlainObject(val)) {
if (hasOwn(val, 'west')) {
const value = val as RectangleInDegreeOption
return Rectangle.fromDegrees(value.west, value.south, value.east, value.north)
} else if (hasOwn(val, 'x')) {
const value = val as Cartesian4Option
return new Rectangle(value.x, value.y, value.z, value.w)
}
}
if (isFunction(val)) {
return new CallbackProperty(val, isConstant)
}
return undefined
}
/**
* 对象或数组转 Cesium.BoundingRectangle。
* @param {Object} val
* @returns {Cesium.BoundingRectangle}
* @example
* const options = [0, 0, 100, 100]
* // const options = {x: 0, y: 0, width: 100, height: 100}
* const boundingRectangle = makeBoundingRectangle(options)
*/
export function makeBoundingRectangle(
val: Cesium.BoundingRectangle | Cesium.CallbackProperty | BoundingRectangleOption | Array<number> | AnyFunction<any>,
isConstant = false
): Cesium.BoundingRectangle | Cesium.CallbackProperty | undefined {
const { BoundingRectangle, CallbackProperty } = Cesium
if (val instanceof BoundingRectangle || val instanceof CallbackProperty) {
return val
}
if (isPlainObject(val) && hasOwn(val, 'x')) {
const value = val as BoundingRectangleOption
return new BoundingRectangle(value.x, value.y, value.width, value.height)
}
if (isArray(val)) {
return new BoundingRectangle(val[0], val[1], val[2], val[3])
}
if (isFunction(val)) {
return new CallbackProperty(val, isConstant)
}
return undefined
}
/**
* 普通对象 {normal: number, distance: number} 转 Cesium.Plane 对象。
* @param {Object} val
* @returns {Plane}
*/
export function makePlane(
val: Cesium.CallbackProperty | Cesium.Plane | PlaneOption | Array<any> | AnyFunction<any>,
isConstant = false
): Cesium.CallbackProperty | Cesium.Plane | Cesium.PlaneGraphics | undefined {
const { Cartesian3, Plane, PlaneGraphics, CallbackProperty } = Cesium
// Entiy 和 PlaneGraphics 都有个 plane 属性 要区别一下
if (val instanceof PlaneGraphics || val instanceof Plane || val instanceof CallbackProperty) {
return val
}
if (isPlainObject(val) && hasOwn(val, 'normal')) {
const value = val as PlaneOption
// normal 法向量 需要写成 {x: number, y: number, z: number} 形式
Cartesian3.normalize(makeCartesian3(value.normal) as Cesium.Cartesian3, value.normal as Cesium.Cartesian3)
return new Plane(value.normal as Cesium.Cartesian3, value.distance)
}
if (isArray(val)) {
const point3D = makeCartesian3(val[0]) as Cesium.Cartesian3
const normalizePoint3D = Cartesian3.normalize(point3D, new Cartesian3())
return new Plane(normalizePoint3D, val[1])
}
if (isFunction(val)) {
return new CallbackProperty(val, isConstant)
}
return undefined
}
/**
* 普通对象转平移、旋转、缩放变换对象。
* @param {*} val
*/
export function makeTranslationRotationScale(
val: Cesium.TranslationRotationScale | Cesium.CallbackProperty | TranslationRotationScaleOption | AnyFunction<any> | Array<any>,
isConstant = false
) {
const { TranslationRotationScale, CallbackProperty } = Cesium
if (val instanceof CallbackProperty || val instanceof TranslationRotationScale) {
return val
}
if (isPlainObject(val) && hasOwn(val, 'translation')) {
const value = val as TranslationRotationScaleOption
// note
// translation scale需要写成 { x: number, y: number, z: number } 的形式
return new TranslationRotationScale(
makeCartesian3(value.translation) as Cesium.Cartesian3,
makeQuaternion(value.rotation) as Cesium.Quaternion,
makeCartesian3(value.scale) as Cesium.Cartesian3
)
}
if (isArray(val)) {
return new TranslationRotationScale(
makeCartesian3(val[0]) as Cesium.Cartesian3,
makeQuaternion(val[1]) as Cesium.Quaternion,
makeCartesian3(val[2]) as Cesium.Cartesian3
)
}
if (isFunction(val)) {
return new CallbackProperty(val, isConstant)
}
return undefined
}
export function makeOptions(this, val) {
const vcInstance = this as VcComponentInternalInstance
const cmpName = vcInstance.proxy?.$options.name
const result: any = {}
switch (cmpName) {
case 'VcDatasourceGeojson':
Object.assign(result, val)
result && result.markerColor && (result.markerColor = makeColor(result.markerColor))
result && result.stroke && (result.stroke = makeColor(result.stroke))
result && result.fill && (result.fill = makeColor(result.fill))
return result
}
return val
}
export function captureScreenshot(viewer: Cesium.Viewer) {
const scene = viewer.scene
const promise: Promise<string> = new Promise((resolve, reject) => {
const removeCallback = viewer.scene.postRender.addEventListener(() => {
removeCallback()
try {
const cesiumCanvas = viewer.scene.canvas
const canvas = cesiumCanvas
resolve(canvas.toDataURL('image/png'))
} catch (e) {
reject(e)
}
})
})
scene.render(viewer.clock.currentTime)
return promise
}
export function makeCameraOptions(camera: CameraOption, ellipsoid?: Cesium.Ellipsoid) {
const { Math: CesiumMath, Rectangle } = Cesium
let destination: Cesium.Cartesian3 | Cesium.Rectangle | undefined = undefined
let orientation: HeadingPitchRollOption = {}
if (hasOwn(camera, 'position')) {
const position = camera.position
destination = makeCartesian3(position!, ellipsoid) as Cesium.Cartesian3
if ((hasOwn(position!, 'lng') && hasOwn(position!, 'lat')) || isArray(position)) {
orientation = {
heading: CesiumMath.toRadians(camera.heading || 360),
pitch: CesiumMath.toRadians(camera.pitch || -90),
roll: CesiumMath.toRadians(camera.roll || 0)
}
} else {
orientation = {
heading: camera.heading || 2 * Math.PI,
pitch: camera.pitch || -Math.PI / 2,
roll: camera.roll || 0
}
}
} else if (hasOwn(camera, 'rectangle')) {
const rectangle = camera.retangle
destination = makeRectangle(rectangle!) as Cesium.Rectangle
Rectangle.validate(destination)
if (
(hasOwn(rectangle!, 'west') && hasOwn(rectangle!, 'south') && hasOwn(rectangle!, 'east') && hasOwn(rectangle!, 'north')) ||
isArray(rectangle)
) {
orientation = {
heading: CesiumMath.toRadians(camera.heading || 360),
pitch: CesiumMath.toRadians(camera.pitch || -90),
roll: CesiumMath.toRadians(camera.roll || 0)
}
} else {
orientation = {
heading: camera.heading || 2 * Math.PI,
pitch: camera.pitch || -Math.PI / 2,
roll: camera.roll || 0
}
}
}
return {
destination,
orientation
}
}
export function setViewerCamera(viewer: Cesium.Viewer, camera: CameraOption) {
const { destination, orientation } = makeCameraOptions(camera, viewer.scene.globe.ellipsoid)
viewer.camera.setView({
destination: destination,
orientation: orientation
})
}
export function flyToCamera(viewer: Cesium.Viewer, camera: CameraOption, options?) {
const { destination, orientation } = makeCameraOptions(camera, viewer.scene.globe.ellipsoid)
viewer.camera.flyTo({
destination: options.destination || destination,
orientation: options.orientation || orientation,
duration: options.duration,
complete: options.complete,
cancel: options.cancel
})
}
export function getGeodesicDistance(start: Cesium.Cartesian3, end: Cesium.Cartesian3, ellipsoid: Cesium.Ellipsoid) {
const { EllipsoidGeodesic, Ellipsoid } = Cesium
ellipsoid = ellipsoid || Ellipsoid.WGS84
const pickedPointCartographic = ellipsoid.cartesianToCartographic(start)
const lastPointCartographic = ellipsoid.cartesianToCartographic(end)
const geodesic = new EllipsoidGeodesic(pickedPointCartographic, lastPointCartographic)
return geodesic.surfaceDistance
}
export function getHeadingPitchRoll(start: Cesium.Cartesian3, end: Cesium.Cartesian3, scene: Cesium.Scene, result?: Array<number>) {
const { Camera, Cartesian3, Math: CesiumMath } = Cesium
const camera = new Camera(scene)
if (Cartesian3.equals(start, end)) {
return undefined
}
let direction = Cartesian3.subtract(end, start, {} as any)
direction = Cartesian3.normalize(direction, direction)
let up = Cartesian3.subtract(start, new Cartesian3(), {} as any)
up = Cartesian3.normalize(up, up)
camera.setView({
destination: start,
orientation: {
direction,
up
}
})
result = result || [0, 0, 0]
let heading = camera.heading
heading -= CesiumMath.PI_OVER_TWO
if (heading < 0) {
heading += CesiumMath.TWO_PI
}
result.splice(0, result.length, heading, camera.pitch, camera.roll)
return result
}
export function getPolylineSegmentEndpoint(start: Cesium.Cartesian3, heading: number, distance: number, ellipsoid: Cesium.Ellipsoid) {
const { HeadingPitchRoll, Transforms, Matrix4, Cartesian3, Cartesian4, Quaternion, Cartographic, Ellipsoid } = Cesium
ellipsoid = ellipsoid || Ellipsoid.WGS84
const hpr = new HeadingPitchRoll(heading, 0, 0)
const scale = new Cartesian3(1, 1, 1)
const matrix = Transforms.headingPitchRollToFixedFrame(start, hpr)
const translation = Matrix4.getColumn(matrix, 1, new Cartesian4())
const axis = new Cartesian3(translation.x, translation.y, translation.z)
const quaternion = Quaternion.fromAxisAngle(axis, distance * ellipsoid.oneOverRadii.x)
const hprMatrix = Matrix4.fromTranslationQuaternionRotationScale(Cartesian3.ZERO, quaternion, scale)
const position = Matrix4.multiplyByPoint(hprMatrix, start, new Cartesian3())
const startCartographic = Cartographic.fromCartesian(start, ellipsoid)
const positionCartographic = Cartographic.fromCartesian(position, ellipsoid)
positionCartographic.height = startCartographic.height
return Cartographic.toCartesian(positionCartographic, ellipsoid)
}
const restoreCursors: Array<string> = []
export function setViewerCursor(viewer: Cesium.Viewer, cursor: string) {
const restoreCursor = getComputedStyle(viewer.canvas).cursor
restoreCursors[restoreCursors.length - 1] !== restoreCursor && restoreCursors.push(restoreCursor)
viewer.canvas.setAttribute('style', `cursor: ${cursor}`)
}
export function restoreViewerCursor(viewer: Cesium.Viewer, count = 1) {
for (let i = 0; i < count; i++) {
const cursor = restoreCursors.pop()
viewer.canvas.setAttribute('style', `cursor: ${cursor}`)
}
} | the_stack |
import {
addHeaders,
getAWSEnvironment,
getEdgeHost,
getEventEntitySize,
getPatchedTraceId,
getRandomId,
isAwsService,
isEmptyString,
isKeepHeadersOn,
isTimeoutTimerEnabled,
isValidAlias,
lowerCaseObjectKeys,
} from '../utils';
import {
extractBodyFromEmitSocketEvent,
extractBodyFromEndFunc,
extractBodyFromWriteFunc,
} from './httpUtils';
import { getCurrentTransactionId, getHttpInfo, getHttpSpan } from '../spans/awsSpan';
import { URL } from 'url';
import { SpansContainer, TracerGlobals } from '../globals';
import * as logger from '../logger';
import * as extender from '../extender';
import * as http from 'http';
import * as https from 'https';
import { GlobalDurationTimer } from '../utils/globalDurationTimer';
import { runOneTimeWrapper } from '../utils/functionUtils';
export const hostBlaclist = new Set(['127.0.0.1']);
export type Agent = {
defaultPort: number;
};
export type ParseHttpRequestOptions = {
agent?: Agent;
_defaultAgent?: Agent;
// eslint-disable-next-line no-undef
headers?: Record<string, string>;
method?: 'GET' | 'POST';
protocol?: string;
path?: string;
port?: number;
defaultPort?: number;
};
export class Http {
static httpRequestEndWrapper(requestData, currentSpan) {
return function (args) {
GlobalDurationTimer.start();
if (isEmptyString(requestData.body)) {
const body = extractBodyFromEndFunc(args);
if (body) {
requestData.body += body.substr(0, getEventEntitySize(false));
}
if (currentSpan) currentSpan.info.httpInfo = getHttpInfo(requestData, {});
}
GlobalDurationTimer.stop();
};
}
@GlobalDurationTimer.timedSync()
static httpRequestArguments(args) {
if (args.length === 0) {
throw new Error('http/s.request(...) was called without any arguments.');
}
let url = undefined;
let options = undefined;
let callback = undefined;
if (typeof args[0] === 'string' || args[0] instanceof URL) {
url = args[0];
if (args[1]) {
if (typeof args[1] === 'function') {
callback = args[1];
} else {
options = args[1];
if (typeof args[2] === 'function') {
callback = args[2];
}
}
}
} else {
options = args[0];
if (typeof args[1] === 'function') {
callback = args[1];
}
}
return { url, options, callback };
}
@GlobalDurationTimer.timedSync()
static getHostFromOptionsOrUrl(options, url) {
if (url) {
return new URL(url).hostname;
}
return options.hostname || options.host || (options.uri && options.uri.hostname) || 'localhost';
}
static isBlacklisted(host) {
return host === getEdgeHost() || hostBlaclist.has(host);
}
@GlobalDurationTimer.timedSync()
static parseHttpRequestOptions(options: ParseHttpRequestOptions = {}, url) {
const host = Http.getHostFromOptionsOrUrl(options, url);
const agent = options.agent || options._defaultAgent;
let path = null;
let port = null;
let protocol = null;
let { headers, method = 'GET' } = options;
const sendTime = new Date().getTime();
if (url) {
const myUrl = new URL(url);
({ pathname: path, port, protocol } = myUrl);
} else {
path = options.path || '/';
port = options.port || options.defaultPort || (agent && agent.defaultPort) || 80;
protocol = options.protocol || (port === 443 && 'https:') || 'http:';
}
if (headers && !headers.host) {
headers = addHeaders(headers, { host });
}
const uri = `${host}${path}`;
return {
path,
port,
uri,
host,
body: '', // XXX Filled by the httpRequestEndWrapper or httpRequestEmitBeforeHookWrapper ( / Write)
method,
headers: lowerCaseObjectKeys(headers),
protocol,
sendTime,
};
}
@GlobalDurationTimer.timedSync()
static httpBeforeRequestWrapper(args, extenderContext) {
// @ts-ignore
const { awsRequestId } = TracerGlobals.getHandlerInputs().context;
const transactionId = getCurrentTransactionId();
extenderContext.isTracedDisabled = true;
extenderContext.awsRequestId = awsRequestId;
extenderContext.transactionId = transactionId;
const { url, options } = Http.httpRequestArguments(args);
const { headers } = options || {};
const host = Http.getHostFromOptionsOrUrl(options, url);
extenderContext.isTracedDisabled =
Http.isBlacklisted(host) || !isValidAlias() || GlobalDurationTimer.isTimePassed();
if (!extenderContext.isTracedDisabled) {
logger.debug('Starting hook', { host, url, headers });
const isRequestToAwsService = isAwsService(host);
if (isRequestToAwsService && !isKeepHeadersOn()) {
const { awsXAmznTraceId } = getAWSEnvironment();
const traceId = getPatchedTraceId(awsXAmznTraceId);
options.headers['X-Amzn-Trace-Id'] = traceId;
}
const requestData = Http.parseHttpRequestOptions(options, url);
const requestRandomId = getRandomId();
extenderContext.requestRandomId = requestRandomId;
extenderContext.requestData = requestData;
if (isTimeoutTimerEnabled()) {
const httpSpan = getHttpSpan(transactionId, awsRequestId, requestRandomId, requestData);
SpansContainer.addSpan(httpSpan);
extenderContext.currentSpan = httpSpan;
}
}
}
@GlobalDurationTimer.timedSync()
static httpAfterRequestWrapper(args, originalFnResult, extenderContext) {
const clientRequest = originalFnResult;
const {
requestData,
requestRandomId,
isTracedDisabled,
awsRequestId,
transactionId,
currentSpan,
} = extenderContext;
if (!isTracedDisabled) {
const endWrapper = Http.httpRequestEndWrapper(requestData, currentSpan);
const emitWrapper = Http.httpRequestEmitBeforeHookWrapper(
transactionId,
awsRequestId,
requestData,
requestRandomId,
currentSpan
);
const writeWrapper = Http.httpRequestWriteBeforeHookWrapper(requestData, currentSpan);
extender.hook(clientRequest, 'end', { beforeHook: endWrapper });
extender.hook(clientRequest, 'emit', { beforeHook: emitWrapper });
extender.hook(clientRequest, 'write', { beforeHook: writeWrapper });
}
}
static httpRequestWriteBeforeHookWrapper(requestData, currentSpan) {
return function (args) {
GlobalDurationTimer.start();
if (isEmptyString(requestData.body)) {
const body = extractBodyFromWriteFunc(args);
if (body) {
requestData.body += body;
if (currentSpan) currentSpan.info.httpInfo = getHttpInfo(requestData, {});
}
}
GlobalDurationTimer.stop();
};
}
@GlobalDurationTimer.timedSync()
static addStepFunctionEvent(messageId) {
// @ts-ignore
const awsRequestId = TracerGlobals.getHandlerInputs().context.awsRequestId;
const transactionId = getCurrentTransactionId();
const httpSpan = getHttpSpan(transactionId, awsRequestId, messageId, { sendTime: Date.now() });
const stepInfo = Object.assign(httpSpan.info, {
resourceName: 'StepFunction',
httpInfo: { host: 'StepFunction' },
messageId: messageId,
});
const stepSpan = Object.assign(httpSpan, { info: stepInfo });
SpansContainer.addSpan(stepSpan);
}
static wrapHttpLib(httpLib) {
extender.hook(httpLib, 'get', {
beforeHook: Http.httpBeforeRequestWrapper,
afterHook: Http.httpAfterRequestWrapper,
});
extender.hook(httpLib, 'request', {
beforeHook: Http.httpBeforeRequestWrapper,
afterHook: Http.httpAfterRequestWrapper,
});
}
static hookHttp() {
Http.wrapHttpLib(http);
Http.wrapHttpLib(https);
}
static createEmitResponseOnEmitBeforeHookHandler(
transactionId,
awsRequestId,
requestData,
requestRandomId,
response
) {
let body = '';
let maxPayloadSize = getEventEntitySize(true);
return function (args) {
GlobalDurationTimer.start();
const receivedTime = new Date().getTime();
let truncated = false;
const { headers, statusCode } = response;
// add to body only if we didnt pass the max size
if (args[0] === 'data' && body.length < maxPayloadSize) {
let chunk = args[1].toString();
const allowedLengthToAdd = maxPayloadSize - body.length;
//if we reached or close to limit get only substring of the part to reach the limit
if (chunk.length > allowedLengthToAdd) {
truncated = true;
chunk = chunk.substr(0, allowedLengthToAdd);
}
body += chunk;
}
if (args[0] === 'end') {
let maxSizeNoErrors = getEventEntitySize();
const responseData = {
statusCode,
receivedTime,
body:
statusCode < 400 && body.length > maxSizeNoErrors // if there are no errors cut the size to max allowed with no errors
? body.substr(0, maxSizeNoErrors)
: body,
headers: lowerCaseObjectKeys(headers),
};
const httpSpan = getHttpSpan(
transactionId,
awsRequestId,
requestRandomId,
requestData,
responseData,
truncated
);
if (httpSpan.id !== requestRandomId) {
// In Http case, one of our parser decide to change the spanId for async connection
SpansContainer.changeSpanId(requestRandomId, httpSpan.id);
}
SpansContainer.addSpan(httpSpan);
}
GlobalDurationTimer.stop();
};
}
static createEmitResponseHandler(transactionId, awsRequestId, requestData, requestRandomId) {
return (response) => {
const onHandler = Http.createEmitResponseOnEmitBeforeHookHandler(
transactionId,
awsRequestId,
requestData,
requestRandomId,
response
);
extender.hook(response, 'emit', {
beforeHook: onHandler,
});
};
}
static httpRequestEmitBeforeHookWrapper(
transactionId,
awsRequestId,
requestData,
requestRandomId,
currentSpan
) {
const emitResponseHandler = Http.createEmitResponseHandler(
transactionId,
awsRequestId,
requestData,
requestRandomId
);
const oneTimerEmitResponseHandler = runOneTimeWrapper(emitResponseHandler, {});
return function (args) {
GlobalDurationTimer.start();
if (args[0] === 'response') {
oneTimerEmitResponseHandler(args[1]);
}
if (args[0] === 'socket') {
if (isEmptyString(requestData.body)) {
const body = extractBodyFromEmitSocketEvent(args[1]);
if (body) {
requestData.body += body.substr(0, getEventEntitySize(false));
if (currentSpan) currentSpan.info.httpInfo = getHttpInfo(requestData, {});
}
}
}
GlobalDurationTimer.stop();
};
}
} | the_stack |
import {
CancellationToken,
CompletionItemKind,
DocumentSymbol,
Location,
SymbolInformation,
SymbolKind,
} from 'vscode-languageserver';
import { URI } from 'vscode-uri';
import { resolveAliasDeclaration } from '../analyzer/aliasDeclarationUtils';
import { AnalyzerFileInfo, ImportLookup } from '../analyzer/analyzerFileInfo';
import * as AnalyzerNodeInfo from '../analyzer/analyzerNodeInfo';
import { AliasDeclaration, Declaration, DeclarationType } from '../analyzer/declaration';
import { getNameFromDeclaration } from '../analyzer/declarationUtils';
import { getLastTypedDeclaredForSymbol } from '../analyzer/symbolUtils';
import { TypeEvaluator } from '../analyzer/typeEvaluatorTypes';
import { isProperty } from '../analyzer/typeUtils';
import { throwIfCancellationRequested } from '../common/cancellationUtils';
import { convertOffsetsToRange } from '../common/positionUtils';
import * as StringUtils from '../common/stringUtils';
import { Range } from '../common/textRange';
import { ParseResults } from '../parser/parser';
import { convertSymbolKindToCompletionItemKind } from './autoImporter';
export interface IndexAliasData {
readonly originalName: string;
readonly modulePath: string;
readonly kind: SymbolKind;
readonly itemKind?: CompletionItemKind | undefined;
}
export interface IndexSymbolData {
readonly name: string;
readonly externallyVisible: boolean;
readonly kind: SymbolKind;
readonly itemKind?: CompletionItemKind | undefined;
readonly alias?: IndexAliasData | undefined;
readonly range?: Range | undefined;
readonly selectionRange?: Range | undefined;
readonly children?: IndexSymbolData[] | undefined;
}
export interface IndexResults {
readonly privateOrProtected: boolean;
readonly symbols: IndexSymbolData[];
}
export interface IndexOptions {
indexingForAutoImportMode: boolean;
forceIndexing?: boolean;
}
export type WorkspaceSymbolCallback = (symbols: SymbolInformation[]) => void;
export function getIndexAliasData(
importLookup: ImportLookup,
declaration: AliasDeclaration
): IndexAliasData | undefined {
if (!declaration.symbolName) {
return undefined;
}
const resolvedInfo = resolveAliasDeclaration(
importLookup,
declaration,
/* resolveLocalNames */ true,
/* allowExternallyHiddenAccess */ false
);
if (!resolvedInfo || !resolvedInfo.declaration) {
return undefined;
}
if (resolvedInfo.isPrivate) {
return undefined;
}
const nameValue = getNameFromDeclaration(resolvedInfo.declaration);
if (!nameValue || resolvedInfo.declaration.path.length <= 0) {
return undefined;
}
const symbolKind = getSymbolKind(nameValue, resolvedInfo.declaration) ?? SymbolKind.Module;
return {
originalName: nameValue,
modulePath: resolvedInfo.declaration.path,
kind: symbolKind,
itemKind: convertSymbolKindToCompletionItemKind(symbolKind),
};
}
export function convertToFlatSymbols(documentUri: string, symbolList: DocumentSymbol[]): SymbolInformation[] {
const flatSymbols: SymbolInformation[] = [];
for (const symbol of symbolList) {
appendToFlatSymbolsRecursive(flatSymbols, documentUri, symbol);
}
return flatSymbols;
}
export class DocumentSymbolProvider {
static getSymbolsForDocument(
fileInfo: AnalyzerFileInfo | undefined,
indexResults: IndexResults | undefined,
parseResults: ParseResults | undefined,
filePath: string,
query: string,
token: CancellationToken
): SymbolInformation[] {
const symbolList: SymbolInformation[] = [];
if (!indexResults && !parseResults) {
return symbolList;
}
const indexSymbolData =
(indexResults?.symbols as IndexSymbolData[]) ??
DocumentSymbolProvider.indexSymbols(fileInfo!, parseResults!, { indexingForAutoImportMode: false }, token);
appendWorkspaceSymbolsRecursive(indexSymbolData, filePath, query, '', symbolList, token);
return symbolList;
}
static addHierarchicalSymbolsForDocument(
fileInfo: AnalyzerFileInfo | undefined,
indexResults: IndexResults | undefined,
parseResults: ParseResults | undefined,
symbolList: DocumentSymbol[],
token: CancellationToken
) {
if (!indexResults && !parseResults) {
return;
}
const indexSymbolData =
(indexResults?.symbols as IndexSymbolData[]) ??
DocumentSymbolProvider.indexSymbols(fileInfo!, parseResults!, { indexingForAutoImportMode: false }, token);
appendDocumentSymbolsRecursive(indexSymbolData, symbolList, token);
}
static indexSymbols(
fileInfo: AnalyzerFileInfo,
parseResults: ParseResults,
options: IndexOptions,
token: CancellationToken
): IndexSymbolData[] {
// Here are the rule of what symbols are indexed for a file.
// 1. If it is a stub file, we index every public symbols defined by "https://www.python.org/dev/peps/pep-0484/#stub-files"
// 2. If it is a py file and it is py.typed package, we index public symbols
// defined by "https://github.com/microsoft/pyright/blob/main/docs/typed-libraries.md#library-interface"
// 3. If it is a py file and it is not py.typed package, we index only symbols that appear in
// __all__ to make sure we don't include too many symbols in the index.
const indexSymbolData: IndexSymbolData[] = [];
collectSymbolIndexData(fileInfo, parseResults, parseResults.parseTree, options, indexSymbolData, token);
return indexSymbolData;
}
}
function getSymbolKind(name: string, declaration: Declaration, evaluator?: TypeEvaluator): SymbolKind | undefined {
let symbolKind: SymbolKind;
switch (declaration.type) {
case DeclarationType.Class:
case DeclarationType.SpecialBuiltInClass:
symbolKind = SymbolKind.Class;
break;
case DeclarationType.Function:
if (declaration.isMethod) {
const declType = evaluator?.getTypeForDeclaration(declaration);
if (declType && isProperty(declType)) {
symbolKind = SymbolKind.Property;
} else {
symbolKind = SymbolKind.Method;
}
} else {
symbolKind = SymbolKind.Function;
}
break;
case DeclarationType.Alias:
symbolKind = SymbolKind.Module;
break;
case DeclarationType.Parameter:
if (name === 'self' || name === 'cls' || name === '_') {
return;
}
symbolKind = SymbolKind.Variable;
break;
case DeclarationType.Variable:
if (name === '_') {
return;
}
symbolKind = declaration.isConstant || declaration.isFinal ? SymbolKind.Constant : SymbolKind.Variable;
break;
default:
symbolKind = SymbolKind.Variable;
break;
}
return symbolKind;
}
function appendWorkspaceSymbolsRecursive(
indexSymbolData: IndexSymbolData[] | undefined,
filePath: string,
query: string,
container: string,
symbolList: SymbolInformation[],
token: CancellationToken
) {
throwIfCancellationRequested(token);
if (!indexSymbolData) {
return;
}
for (const symbolData of indexSymbolData) {
if (symbolData.alias) {
continue;
}
if (StringUtils.isPatternInSymbol(query, symbolData.name)) {
const location: Location = {
uri: URI.file(filePath).toString(),
range: symbolData.selectionRange!,
};
const symbolInfo: SymbolInformation = {
name: symbolData.name,
kind: symbolData.kind,
location,
};
if (container.length) {
symbolInfo.containerName = container;
}
symbolList.push(symbolInfo);
}
appendWorkspaceSymbolsRecursive(
symbolData.children,
filePath,
query,
getContainerName(container, symbolData.name),
symbolList,
token
);
}
function getContainerName(container: string, name: string) {
if (container.length > 0) {
return `${container}.${name}`;
}
return name;
}
}
function appendDocumentSymbolsRecursive(
indexSymbolData: IndexSymbolData[] | undefined,
symbolList: DocumentSymbol[],
token: CancellationToken
) {
throwIfCancellationRequested(token);
if (!indexSymbolData) {
return;
}
for (const symbolData of indexSymbolData) {
if (symbolData.alias) {
continue;
}
const children: DocumentSymbol[] = [];
appendDocumentSymbolsRecursive(symbolData.children, children, token);
const symbolInfo: DocumentSymbol = {
name: symbolData.name,
kind: symbolData.kind,
range: symbolData.range!,
selectionRange: symbolData.selectionRange!,
children: children!,
};
symbolList.push(symbolInfo);
}
}
function collectSymbolIndexData(
fileInfo: AnalyzerFileInfo,
parseResults: ParseResults,
node: AnalyzerNodeInfo.ScopedNode,
options: IndexOptions,
indexSymbolData: IndexSymbolData[],
token: CancellationToken
) {
throwIfCancellationRequested(token);
const scope = AnalyzerNodeInfo.getScope(node);
if (!scope) {
return;
}
const symbolTable = scope.symbolTable;
symbolTable.forEach((symbol, name) => {
if (symbol.isIgnoredForProtocolMatch()) {
return;
}
// If we are not py.typed package, symbol must exist in __all__ for auto import mode.
if (
options.indexingForAutoImportMode &&
!options.forceIndexing &&
!fileInfo.isStubFile &&
!fileInfo.isInPyTypedPackage &&
!symbol.isInDunderAll()
) {
return;
}
// Prefer declarations with a defined type.
let declaration = getLastTypedDeclaredForSymbol(symbol);
// Fall back to declarations without a type.
if (!declaration && symbol.hasDeclarations()) {
declaration = symbol.getDeclarations()[0];
}
if (!declaration) {
return;
}
if (DeclarationType.Alias === declaration.type) {
if (!options.indexingForAutoImportMode) {
// We don't include import alias for workspace files.
return;
}
if (!declaration.loadSymbolsFromPath || declaration.path.length <= 0) {
// If alias doesn't have a path to the original file, we can't do dedup
// so ignore those aliases.
// ex) asyncio.futures, asyncio.base_futures.futures and many will dedup
// to asyncio.futures
return;
}
}
// We rely on ExternallyHidden flag to determine what
// symbols should be public (included in the index)
collectSymbolIndexDataForName(
fileInfo,
parseResults,
declaration,
options,
!symbol.isExternallyHidden(),
name,
indexSymbolData,
token
);
});
}
function collectSymbolIndexDataForName(
fileInfo: AnalyzerFileInfo,
parseResults: ParseResults,
declaration: Declaration,
options: IndexOptions,
externallyVisible: boolean,
name: string,
indexSymbolData: IndexSymbolData[],
token: CancellationToken
) {
if (options.indexingForAutoImportMode && !externallyVisible) {
return;
}
const symbolKind = getSymbolKind(name, declaration);
if (symbolKind === undefined) {
return;
}
const selectionRange = declaration.range;
let range = selectionRange;
const children: IndexSymbolData[] = [];
if (declaration.type === DeclarationType.Class || declaration.type === DeclarationType.Function) {
if (!options.indexingForAutoImportMode) {
collectSymbolIndexData(fileInfo, parseResults, declaration.node, options, children, token);
}
range = convertOffsetsToRange(
declaration.node.start,
declaration.node.start + declaration.node.length,
parseResults.tokenizerOutput.lines
);
}
let aliasData: IndexAliasData | undefined = undefined;
if (DeclarationType.Alias === declaration.type) {
aliasData = getIndexAliasData(AnalyzerNodeInfo.getFileInfo(parseResults.parseTree)!.importLookup, declaration);
// If we can't create alias data for import alias, then don't include it in index.
if (!aliasData) {
return;
}
}
const data: IndexSymbolData = {
name,
externallyVisible,
kind: symbolKind,
itemKind: convertSymbolKindToCompletionItemKind(symbolKind),
alias: aliasData,
range: options.indexingForAutoImportMode ? undefined : range,
selectionRange: options.indexingForAutoImportMode ? undefined : selectionRange,
children: options.indexingForAutoImportMode ? undefined : children,
};
indexSymbolData.push(data);
}
function appendToFlatSymbolsRecursive(
flatSymbols: SymbolInformation[],
documentUri: string,
symbol: DocumentSymbol,
parent?: DocumentSymbol
) {
const flatSymbol: SymbolInformation = {
name: symbol.name,
kind: symbol.kind,
location: Location.create(documentUri, symbol.range),
};
if (symbol.tags) {
flatSymbol.tags = symbol.tags;
}
if (parent) {
flatSymbol.containerName = parent.name;
}
flatSymbols.push(flatSymbol);
if (symbol.children) {
for (const child of symbol.children) {
appendToFlatSymbolsRecursive(flatSymbols, documentUri, child, symbol);
}
}
} | the_stack |
import { IComponent, ComponentList, TComAndDir, DirectiveList } from '../types';
import { utils } from '../utils';
import { Compile } from './compile';
import { buildComponentScope } from './compiler-utils';
import { Vnode, parseTemplateToVnode, isTagName } from '../vnode';
import { mountDirective } from './directive-compiler';
import { buildViewChildandChildren, buildContentChildandChildren, ChangeDetectionStrategy } from '../component';
import { lifecycleCaller } from '../lifecycle';
/**
* use lifecycle nvDestory for @Directive
*
* @param {DirectiveList[]} directiveList
*/
function emitDirectiveDestory(directiveList: DirectiveList[]): void {
directiveList.forEach(directive => {
lifecycleCaller(directive.instanceScope, 'nvOnDestory');
});
}
/**
* use lifecycle nvDestory for @Component
*
* @param {ComponentList[]} componentList
*/
function emitComponentDestory(componentList: ComponentList[]): void {
componentList.forEach(component => {
emitDirectiveDestory(component.instanceScope.$directiveList);
emitComponentDestory(component.instanceScope.$componentList);
lifecycleCaller(component.instanceScope, 'nvOnDestory');
});
}
/**
* mountComponent for Components in Component
*
* @export
* @param {IComponent} componentInstance
* @param {TComAndDir} componentAndDirectives
*/
export async function mountComponent(componentInstance: IComponent, componentAndDirectives: TComAndDir): Promise<void> {
const cacheComponentList: ComponentList[] = [...componentInstance.$componentList];
const foundCacheComponentList: ComponentList[] = [];
componentsConstructor(componentInstance, componentAndDirectives);
const componentListLength = componentInstance.$componentList.length;
for (let i = 0; i < componentListLength; i++) {
const component = componentInstance.$componentList[i];
// find Component from cache
const cacheComponentIndex = cacheComponentList.findIndex(cache => cache.nativeElement === component.nativeElement);
const cacheComponent = cacheComponentList[cacheComponentIndex];
// clear cache, the rest need to be destoried, and push cacheComponent to foundCacheComponentList
if (cacheComponentIndex !== -1) {
cacheComponentList.splice(cacheComponentIndex, 1);
foundCacheComponentList.push(cacheComponent);
}
if (cacheComponent) {
component.instanceScope = cacheComponent.instanceScope;
// old inputs: component.instanceScope.$saveInputs
// new inputs: component.inputs
if (!utils.isEqual(component.instanceScope.$saveInputs, component.inputs)) {
if (component.instanceScope.nvReceiveInputs) component.instanceScope.nvReceiveInputs({ ...component.inputs });
component.instanceScope.$saveInputs = component.inputs;
for (const key in component.inputs) {
if (component.instanceScope.$inputsList) {
component.instanceScope.$inputsList.forEach(({ propertyName, inputName }) => {
if (inputName === key) (component.instanceScope as any)[propertyName] = component.inputs[key];
});
}
}
// 标记组件为脏组件
component.isDirty = true;
}
} else {
component.instanceScope = buildComponentScope(component.constructorFunction, component.inputs, component.nativeElement, componentInstance);
}
component.instanceScope.$indivInstance = componentInstance.$indivInstance;
// 赋值 <nv-content>的 Vnode[] 给组件实 $nvContent
component.instanceScope.$nvContent = component.content;
if (!cacheComponent) {
lifecycleCaller(component.instanceScope, 'nvOnInit');
lifecycleCaller(component.instanceScope, 'watchData');
lifecycleCaller(component.instanceScope, 'nvBeforeMount');
}
}
// the rest should use nvOnDestory to destory
const cacheComponentListLength = cacheComponentList.length;
for (let i = 0; i < cacheComponentListLength; i++) {
const cache = cacheComponentList[i];
emitDirectiveDestory(cache.instanceScope.$directiveList);
emitComponentDestory(cache.instanceScope.$componentList);
lifecycleCaller(cache.instanceScope, 'nvOnDestory');
}
// render, only component which isn't rendered will be rendered and called
for (let i = 0; i < componentListLength; i++) {
const component = componentInstance.$componentList[i];
// 如果没找到该组件
if (!foundCacheComponentList.find(cache => cache.nativeElement === component.nativeElement)) {
await component.instanceScope.render();
// in ssr env indiv won't call nvAfterMount
if (!component.instanceScope.$indivInstance.getIndivEnv.isServerRendering) lifecycleCaller(component.instanceScope, 'nvAfterMount');
} else {
// 如果找到该组件 并且为脏组件
if (component.isDirty) {
// 如果是 OnPush 模式的话,则需要触发一次更新
if (component.instanceScope.$nvChangeDetection === ChangeDetectionStrategy.OnPush) {
if (component.instanceScope.nvDoCheck) component.instanceScope.nvDoCheck();
await component.instanceScope.render();
}
component.isDirty = false;
}
}
}
// build @ViewChild @ViewChildren
buildViewChildandChildren(componentInstance);
// build @ContentChild @ContentChildren
buildContentChildandChildren(componentInstance);
}
/**
* construct Components in Component
*
* @export
* @param {IComponent} componentInstance
* @param {TComAndDir} componentAndDirectives
*/
export function componentsConstructor(componentInstance: IComponent, componentAndDirectives: TComAndDir): void {
componentInstance.$componentList = [];
componentAndDirectives.components.forEach(component => {
const declaration = componentInstance.$declarationMap.get(component.name);
componentInstance.$componentList.push({
nativeElement: component.nativeElement,
inputs: component.inputs,
instanceScope: null,
constructorFunction: declaration,
content: component.content,
isFromContent: component.isFromContent,
isDirty: false,
});
});
}
/**
* build list for build @Component and @Directive
*
* @export
* @param {Vnode} vnode
* @param {TComAndDir} componentAndDirectives
* @param {Vnode[]} contentComponentStack
*/
export function buildComponentsAndDirectives(vnode: Vnode, componentAndDirectives: TComAndDir, contentComponentStack: Vnode[]): void {
if (vnode.type === 'text') return;
const componentInputs: any = {};
// 判断栈是否为空,如果没空则证明是 <nv-content> 的子作用域的组件
const fromContent = contentComponentStack.length ? true : false;
let hasPushStack = false;
if (isTagName(vnode, 'nv-content') && vnode.childNodes && vnode.childNodes.length > 0) {
contentComponentStack.push(vnode);
hasPushStack = true;
}
if (vnode.childNodes && vnode.childNodes.length > 0) vnode.childNodes.forEach(child => {
buildComponentsAndDirectives(child, componentAndDirectives, contentComponentStack);
});
if (vnode.attributes && vnode.attributes.length > 0) {
vnode.attributes.forEach(attr => {
if (attr.type === 'directive') {
componentAndDirectives.directives.push({
nativeElement: vnode.nativeElement,
inputs: attr.nvValue,
name: attr.name,
isFromContent: fromContent,
});
}
if (attr.type === 'prop') componentInputs[attr.name] = attr.nvValue;
});
}
if (vnode.type === 'component') {
componentAndDirectives.components.push({
nativeElement: vnode.nativeElement,
inputs: componentInputs,
name: vnode.tagName,
content: vnode.childNodes,
isFromContent: fromContent,
});
}
// 深度优先遍历后,出栈
if (hasPushStack) contentComponentStack.pop();
}
/**
* render Component with using nativeElement and RenderTask instance
*
* @export
* @param {*} nativeElement
* @param {IComponent} componentInstance
* @returns {Promise<IComponent>}
*/
export async function componentCompiler(nativeElement: any, componentInstance: IComponent): Promise<IComponent> {
// for compile, @Component must init $parseVnodeOptions, templateVnode and $compileInstance
if (!componentInstance.$parseVnodeOptions) {
componentInstance.$parseVnodeOptions = {
components: [],
directives: [],
};
componentInstance.$declarationMap.forEach((value, key) => {
if (componentInstance.$parseVnodeOptions.components.indexOf(key) === -1 && (value as any).nvType === 'nvComponent') componentInstance.$parseVnodeOptions.components.push(key);
if (componentInstance.$parseVnodeOptions.directives.indexOf(key) === -1 && (value as any).nvType === 'nvDirective') componentInstance.$parseVnodeOptions.directives.push(key);
});
}
if (!componentInstance.$templateVnode) componentInstance.$templateVnode = parseTemplateToVnode(componentInstance.$template, componentInstance.$parseVnodeOptions);
if (!componentInstance.$compileInstance) componentInstance.$compileInstance = new Compile(nativeElement, componentInstance);
let saveVnode: Vnode[] = [];
try {
saveVnode = componentInstance.$compileInstance.startCompile();
} catch (error) {
throw new Error(`Error: ${error}, compoent ${(componentInstance.constructor as any).selector} was compiled failed!`);
}
// for save saveVnode in componentInstance
componentInstance.$saveVnode = [...saveVnode];
let componentAndDirectives: TComAndDir = { components: [], directives: [] };
// 定义一个来自 <nv-content> 的 Vnode 栈
let contentComponentStack: Vnode[] = [];
saveVnode.forEach(vnode => buildComponentsAndDirectives(vnode, componentAndDirectives, contentComponentStack));
// firstly mount directive
try {
mountDirective(componentInstance, componentAndDirectives);
} catch (error) {
throw new Error(`Error: ${error}, directives of compoent ${(componentInstance.constructor as any).selector} were compiled failed!`);
}
// then mount component
try {
await mountComponent(componentInstance, componentAndDirectives);
lifecycleCaller(componentInstance, 'nvHasRender');
} catch (error) {
throw new Error(`Error: ${error}, components of compoent ${(componentInstance.constructor as any).selector} were compiled failed!`);
}
componentAndDirectives = null;
contentComponentStack = null;
return componentInstance;
} | the_stack |
import * as cp from 'child_process';
import ChildProcess = cp.ChildProcess;
import { TextDocumentChangeEvent, TextDocument, Disposable, OutputChannel, FileSystemWatcher as VFileSystemWatcher, DiagnosticCollection, ProviderResult, CancellationToken, Position as VPosition, Location as VLocation, Range as VRange, CompletionItem as VCompletionItem, CompletionList as VCompletionList, SignatureHelp as VSignatureHelp, Definition as VDefinition, DocumentHighlight as VDocumentHighlight, SymbolInformation as VSymbolInformation, CodeActionContext as VCodeActionContext, Command as VCommand, CodeLens as VCodeLens, FormattingOptions as VFormattingOptions, TextEdit as VTextEdit, WorkspaceEdit as VWorkspaceEdit, Hover as VHover, DocumentLink as VDocumentLink, TextDocumentWillSaveEvent } from 'vscode';
import { Message, MessageType as RPCMessageType, ErrorCodes, ResponseError, RequestType, RequestType0, RequestHandler, RequestHandler0, GenericRequestHandler, NotificationType, NotificationType0, NotificationHandler, NotificationHandler0, GenericNotificationHandler, MessageReader, MessageWriter, Trace, Event } from 'vscode-jsonrpc';
import { InitializeError, DocumentSelector } from './protocol';
import * as c2p from './codeConverter';
import * as p2c from './protocolConverter';
export { ResponseError, InitializeError, ErrorCodes, RequestType, RequestType0, RequestHandler, RequestHandler0, GenericRequestHandler, NotificationType, NotificationType0, NotificationHandler, NotificationHandler0, GenericNotificationHandler };
export { Converter as Code2ProtocolConverter } from './codeConverter';
export { Converter as Protocol2CodeConverter } from './protocolConverter';
export * from 'vscode-languageserver-types';
export * from './protocol';
export interface StreamInfo {
writer: NodeJS.WritableStream;
reader: NodeJS.ReadableStream;
}
export interface ExecutableOptions {
cwd?: string;
stdio?: string | string[];
env?: any;
detached?: boolean;
}
export interface Executable {
command: string;
args?: string[];
options?: ExecutableOptions;
}
export interface ForkOptions {
cwd?: string;
env?: any;
encoding?: string;
execArgv?: string[];
}
export declare enum TransportKind {
stdio = 0,
ipc = 1,
pipe = 2,
}
export interface NodeModule {
module: string;
transport?: TransportKind;
args?: string[];
runtime?: string;
options?: ForkOptions;
}
export declare type ServerOptions = Executable | {
run: Executable;
debug: Executable;
} | {
run: NodeModule;
debug: NodeModule;
} | NodeModule | (() => Thenable<ChildProcess | StreamInfo>);
/**
* An action to be performed when the connection is producing errors.
*/
export declare enum ErrorAction {
/**
* Continue running the server.
*/
Continue = 1,
/**
* Shutdown the server.
*/
Shutdown = 2,
}
/**
* An action to be performed when the connection to a server got closed.
*/
export declare enum CloseAction {
/**
* Don't restart the server. The connection stays closed.
*/
DoNotRestart = 1,
/**
* Restart the server.
*/
Restart = 2,
}
/**
* A pluggable error handler that is invoked when the connection is either
* producing errors or got closed.
*/
export interface ErrorHandler {
/**
* An error has occurred while writing or reading from the connection.
*
* @param error - the error received
* @param message - the message to be delivered to the server if know.
* @param count - a count indicating how often an error is received. Will
* be reset if a message got successfully send or received.
*/
error(error: Error, message: Message, count: number): ErrorAction;
/**
* The connection to the server got closed.
*/
closed(): CloseAction;
}
export interface InitializationFailedHandler {
(error: ResponseError<InitializeError> | Error | any): boolean;
}
export interface SynchronizeOptions {
configurationSection?: string | string[];
fileEvents?: VFileSystemWatcher | VFileSystemWatcher[];
}
export declare enum RevealOutputChannelOn {
Info = 1,
Warn = 2,
Error = 3,
Never = 4,
}
export interface ProvideCompletionItemsSignature {
(document: TextDocument, position: VPosition, token: CancellationToken): ProviderResult<VCompletionItem[] | VCompletionList>;
}
export interface ResolveCompletionItemSignature {
(item: VCompletionItem, token: CancellationToken): ProviderResult<VCompletionItem>;
}
export interface ProvideHoverSignature {
(document: TextDocument, position: VPosition, token: CancellationToken): ProviderResult<VHover>;
}
export interface ProvideSignatureHelpSignature {
(document: TextDocument, position: VPosition, token: CancellationToken): ProviderResult<VSignatureHelp>;
}
export interface ProvideDefinitionSignature {
(document: TextDocument, position: VPosition, token: CancellationToken): ProviderResult<VDefinition>;
}
export interface ProvideReferencesSignature {
(document: TextDocument, position: VPosition, options: {
includeDeclaration: boolean;
}, token: CancellationToken): ProviderResult<VLocation[]>;
}
export interface ProvideDocumentHighlightsSignature {
(document: TextDocument, position: VPosition, token: CancellationToken): ProviderResult<VDocumentHighlight[]>;
}
export interface ProvideDocumentSymbolsSignature {
(document: TextDocument, token: CancellationToken): ProviderResult<VSymbolInformation[]>;
}
export interface ProvideWorkspaceSymbolsSignature {
(query: string, token: CancellationToken): ProviderResult<VSymbolInformation[]>;
}
export interface ProvideCodeActionsSignature {
(document: TextDocument, range: VRange, context: VCodeActionContext, token: CancellationToken): ProviderResult<VCommand[]>;
}
export interface ProvideCodeLensesSignature {
(document: TextDocument, token: CancellationToken): ProviderResult<VCodeLens[]>;
}
export interface ResolveCodeLensSignature {
(codeLens: VCodeLens, token: CancellationToken): ProviderResult<VCodeLens>;
}
export interface ProvideDocumentFormattingEditsSignature {
(document: TextDocument, options: VFormattingOptions, token: CancellationToken): ProviderResult<VTextEdit[]>;
}
export interface ProvideDocumentRangeFormattingEditsSignature {
(document: TextDocument, range: VRange, options: VFormattingOptions, token: CancellationToken): ProviderResult<VTextEdit[]>;
}
export interface ProvideOnTypeFormattingEditsSignature {
(document: TextDocument, position: VPosition, ch: string, options: VFormattingOptions, token: CancellationToken): ProviderResult<VTextEdit[]>;
}
export interface ProvideRenameEditsSignature {
(document: TextDocument, position: VPosition, newName: string, token: CancellationToken): ProviderResult<VWorkspaceEdit>;
}
export interface ProvideDocumentLinksSignature {
(document: TextDocument, token: CancellationToken): ProviderResult<VDocumentLink[]>;
}
export interface ResolveDocumentLinkSignature {
(link: VDocumentLink, token: CancellationToken): ProviderResult<VDocumentLink>;
}
export interface NextSignature<P, R> {
(data: P, next: (data: P) => R): R;
}
export interface Middleware {
didOpen?: NextSignature<TextDocument, void>;
didChange?: NextSignature<TextDocumentChangeEvent, void>;
willSave?: NextSignature<TextDocumentWillSaveEvent, void>;
willSaveWaitUntil?: NextSignature<TextDocumentWillSaveEvent, Thenable<VTextEdit[]>>;
didSave?: NextSignature<TextDocument, void>;
didClose?: NextSignature<TextDocument, void>;
provideCompletionItem?: (document: TextDocument, position: VPosition, token: CancellationToken, next: ProvideCompletionItemsSignature) => ProviderResult<VCompletionItem[] | VCompletionList>;
resolveCompletionItem?: (item: VCompletionItem, token: CancellationToken, next: ResolveCompletionItemSignature) => ProviderResult<VCompletionItem>;
provideHover?: (document: TextDocument, position: VPosition, token: CancellationToken, next: ProvideHoverSignature) => ProviderResult<VHover>;
provideSignatureHelp?: (document: TextDocument, position: VPosition, token: CancellationToken, next: ProvideSignatureHelpSignature) => ProviderResult<VSignatureHelp>;
provideDefinition?: (document: TextDocument, position: VPosition, token: CancellationToken, next: ProvideDefinitionSignature) => ProviderResult<VDefinition>;
provideReferences?: (document: TextDocument, position: VPosition, options: {
includeDeclaration: boolean;
}, token: CancellationToken, next: ProvideReferencesSignature) => ProviderResult<VLocation[]>;
provideDocumentHighlights?: (document: TextDocument, position: VPosition, token: CancellationToken, next: ProvideDocumentHighlightsSignature) => ProviderResult<VDocumentHighlight[]>;
provideDocumentSymbols?: (document: TextDocument, token: CancellationToken, next: ProvideDocumentSymbolsSignature) => ProviderResult<VSymbolInformation[]>;
provideWorkspaceSymbols?: (query: string, token: CancellationToken, next: ProvideWorkspaceSymbolsSignature) => ProviderResult<VSymbolInformation[]>;
provideCodeActions?: (document: TextDocument, range: VRange, context: VCodeActionContext, token: CancellationToken, next: ProvideCodeActionsSignature) => ProviderResult<VCommand[]>;
provideCodeLenses?: (document: TextDocument, token: CancellationToken, next: ProvideCodeLensesSignature) => ProviderResult<VCodeLens[]>;
resolveCodeLens?: (codeLens: VCodeLens, token: CancellationToken, next: ResolveCodeLensSignature) => ProviderResult<VCodeLens>;
provideDocumentFormattingEdits?: (document: TextDocument, options: VFormattingOptions, token: CancellationToken, next: ProvideDocumentFormattingEditsSignature) => ProviderResult<VTextEdit[]>;
provideDocumentRangeFormattingEdits?: (document: TextDocument, range: VRange, options: VFormattingOptions, token: CancellationToken, next: ProvideDocumentRangeFormattingEditsSignature) => ProviderResult<VTextEdit[]>;
provideOnTypeFormattingEdits?: (document: TextDocument, position: VPosition, ch: string, options: VFormattingOptions, token: CancellationToken, next: ProvideOnTypeFormattingEditsSignature) => ProviderResult<VTextEdit[]>;
provideRenameEdits?: (document: TextDocument, position: VPosition, newName: string, token: CancellationToken, next: ProvideRenameEditsSignature) => ProviderResult<VWorkspaceEdit>;
provideDocumentLinks?: (document: TextDocument, token: CancellationToken, next: ProvideDocumentLinksSignature) => ProviderResult<VDocumentLink[]>;
resolveDocumentLink?: (link: VDocumentLink, token: CancellationToken, next: ResolveDocumentLinkSignature) => ProviderResult<VDocumentLink>;
}
export interface LanguageClientOptions {
documentSelector?: DocumentSelector | string[];
synchronize?: SynchronizeOptions;
diagnosticCollectionName?: string;
outputChannelName?: string;
revealOutputChannelOn?: RevealOutputChannelOn;
/**
* The encoding use to read stdout and stderr. Defaults
* to 'utf8' if ommitted.
*/
stdioEncoding?: string;
initializationOptions?: any | (() => any);
initializationFailedHandler?: InitializationFailedHandler;
errorHandler?: ErrorHandler;
middleware?: Middleware;
uriConverters?: {
code2Protocol: c2p.URIConverter;
protocol2Code: p2c.URIConverter;
};
}
export declare enum State {
Stopped = 1,
Running = 2,
}
export interface StateChangeEvent {
oldState: State;
newState: State;
}
export interface MessageTransports {
reader: MessageReader;
writer: MessageWriter;
}
export declare abstract class BaseLanguageClient {
private _id;
private _name;
private _clientOptions;
private _state;
private _onReady;
private _onReadyCallbacks;
private _connectionPromise;
private _resolvedConnection;
private _outputChannel;
private _capabilites;
private _listeners;
private _providers;
private _diagnostics;
private _fileEvents;
private _fileEventDelayer;
private _telemetryEmitter;
private _stateChangeEmitter;
private _trace;
private _tracer;
private _c2p;
private _p2c;
constructor(id: string, name: string, clientOptions: LanguageClientOptions);
private state;
private getPublicState();
sendRequest<R, E, RO>(type: RequestType0<R, E, RO>, token?: CancellationToken): Thenable<R>;
sendRequest<P, R, E, RO>(type: RequestType<P, R, E, RO>, params: P, token?: CancellationToken): Thenable<R>;
sendRequest<R>(method: string, token?: CancellationToken): Thenable<R>;
sendRequest<R>(method: string, param: any, token?: CancellationToken): Thenable<R>;
onRequest<R, E, RO>(type: RequestType0<R, E, RO>, handler: RequestHandler0<R, E>): void;
onRequest<P, R, E, RO>(type: RequestType<P, R, E, RO>, handler: RequestHandler<P, R, E>): void;
onRequest<R, E>(method: string, handler: GenericRequestHandler<R, E>): void;
sendNotification<RO>(type: NotificationType0<RO>): void;
sendNotification<P, RO>(type: NotificationType<P, RO>, params?: P): void;
sendNotification(method: string): void;
sendNotification(method: string, params: any): void;
onNotification<RO>(type: NotificationType0<RO>, handler: NotificationHandler0): void;
onNotification<P, RO>(type: NotificationType<P, RO>, handler: NotificationHandler<P>): void;
onNotification(method: string, handler: GenericNotificationHandler): void;
readonly clientOptions: LanguageClientOptions;
readonly protocol2CodeConverter: p2c.Converter;
readonly code2ProtocolConverter: c2p.Converter;
readonly onTelemetry: Event<any>;
readonly onDidChangeState: Event<StateChangeEvent>;
readonly outputChannel: OutputChannel;
readonly diagnostics: DiagnosticCollection | undefined;
createDefaultErrorHandler(): ErrorHandler;
trace: Trace;
private data2String(data);
info(message: string, data?: any): void;
warn(message: string, data?: any): void;
error(message: string, data?: any): void;
private logTrace(message, data?);
needsStart(): boolean;
needsStop(): boolean;
onReady(): Promise<void>;
private isConnectionActive();
start(): Disposable;
private resolveConnection();
private initialize(connection);
stop(): Thenable<void>;
private cleanUp(diagnostics?);
private notifyFileEvent(event);
private forceDocumentSync();
private handleDiagnostics(params);
protected abstract createMessageTransports(encoding: string): Thenable<MessageTransports>;
private createConnection();
protected handleConnectionClosed(): void;
private handleConnectionError(error, message, count);
private hookConfigurationChanged(connection);
private refreshTrace(connection, sendNotification?);
private onDidChangeConfiguration(connection);
private extractSettingsInformation(keys);
private hookFileEvents(_connection);
private readonly _registeredHandlers;
private initRegistrationHandlers(_connection);
private handleRegistrationRequest(params);
private handleUnregistrationRequest(params);
private handleApplyWorkspaceEdit(params);
private hookCapabilities(_connection);
protected logFailedRequest(type: RPCMessageType, error: any): void;
private createCompletionProvider(options);
private createHoverProvider(options);
private createSignatureHelpProvider(options);
private createDefinitionProvider(options);
private createReferencesProvider(options);
private createDocumentHighlightProvider(options);
private createDocumentSymbolProvider(options);
private createWorkspaceSymbolProvider(_options);
private createCodeActionsProvider(options);
private createCodeLensProvider(options);
private createDocumentFormattingProvider(options);
private createDocumentRangeFormattingProvider(options);
private createDocumentOnTypeFormattingProvider(options);
private createRenameProvider(options);
private createDocumentLinkProvider(options);
} | the_stack |
import { ScrollView, View } from "@tarojs/components"
import { ViewProps } from "@tarojs/components/types/View"
import { nextTick } from "@tarojs/taro"
import classNames from "classnames"
import * as _ from "lodash"
import * as React from "react"
import {
Children,
isValidElement,
ReactElement,
ReactNode,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react"
import useMounted from "../hooks/use-mounted"
import { prefixClassname } from "../styles"
import { getRect } from "../utils/dom/rect"
import { getScrollTop } from "../utils/dom/scroll"
import { useRefs, useValue } from "../utils/state"
import CalendarFooter from "./calendar-footer"
import CalendarHeader from "./calendar-header"
import CalendarMonth, { CalendarMonthInstance } from "./calendar-month"
import CalendarContext from "./calendar.context"
import {
CalendarDayObject,
CalendarType,
CalendarValueType,
compareDate,
compareYearMonth,
createNextDay,
createPreviousDay,
createToday,
MAX_DATE,
MIN_DATE,
} from "./calendar.shared"
type CalendarSubtitleRender = (date: Date) => ReactNode
function defaultSubtitleRender(date: Date) {
return `${date.getFullYear()}年${date.getMonth() + 1}月`
}
function useSubtitleRender(subtitle?: ReactNode | CalendarSubtitleRender): CalendarSubtitleRender {
const renderRef = useRef<CalendarSubtitleRender>()
const getRender = useCallback(() => {
if (_.isBoolean(subtitle) && subtitle) {
return defaultSubtitleRender
} else if (_.isBoolean(subtitle) && !subtitle) {
return () => undefined
} else if (_.isFunction(subtitle)) {
return subtitle
}
return () => subtitle
}, [subtitle])
useEffect(() => {
renderRef.current = getRender()
}, [getRender, subtitle])
return useCallback((date: Date) => renderRef.current?.(date), [])
}
function defaultFormatter(day: CalendarDayObject) {
return day
}
interface CalendarChildren {
footer?: ReactNode
}
function useCalendarChildren(children?: ReactNode): CalendarChildren {
const __children__: CalendarChildren = {}
Children.forEach(children, (child: ReactNode) => {
if (isValidElement(child)) {
const element = child as ReactElement
const { type: elementType } = element
if (elementType === CalendarFooter) {
__children__.footer = element
}
}
})
return __children__
}
export interface CalendarProps extends ViewProps {
type?: CalendarType
title?: ReactNode
subtitle?: ReactNode | CalendarSubtitleRender
defaultValue?: CalendarValueType
value?: CalendarValueType
min?: Date
max?: Date
firstDayOfWeek?: number
watermark?: boolean
readonly?: boolean
children?: ReactNode
formatter?(day: CalendarDayObject): CalendarDayObject
onChange?(value: any): void
onConfirm?(value: any): void
}
function Calendar(props: CalendarProps) {
const {
className,
style,
title = true,
subtitle: subtitleProp = true,
type = "single",
defaultValue,
value: valueProp,
min: minValue = MIN_DATE,
max: maxValue = MAX_DATE,
firstDayOfWeek,
readonly = false,
watermark = true,
formatter = defaultFormatter,
children: childrenProp,
onChange: onChangeProp,
onConfirm,
} = props
const { value, setValue } = useValue({ defaultValue, value: valueProp, onChange: onChangeProp })
const { footer } = useCalendarChildren(childrenProp)
const bodyRef = useRef()
const hasConfirmRef = useRef(false)
const subtitleRender = useSubtitleRender(subtitleProp)
const [subtitle, setSubtitle] = useState<ReactNode>()
const changeValueRef = useRef<CalendarValueType>()
const [bodyScrollTop, setBodyScrollTop] = useState(0)
const bodyScrollTopRef = useRef(0)
const [monthRefs, setMonthRefs] = useRefs<CalendarMonthInstance>()
const dayOffset = useMemo(() => (firstDayOfWeek ? +firstDayOfWeek % 7 : 0), [firstDayOfWeek])
const months = useMemo<Date[]>(() => {
const months: Date[] = []
const cursor = new Date(minValue)
cursor.setDate(1)
do {
months.push(new Date(cursor))
cursor.setMonth(cursor.getMonth() + 1)
} while (compareYearMonth(cursor, maxValue) !== 1)
return months
}, [maxValue, minValue])
function limitDateRange(date: Date, minDate = minValue, maxDate = maxValue) {
if (compareDate(date, minDate) === -1) {
return minDate
}
if (compareDate(date, maxDate) === 1) {
return maxDate
}
return date
}
function getInitialDate(defaultDate?: CalendarValueType) {
if (defaultDate === null) {
return defaultDate
}
const now = createToday()
if (type === "range") {
if (!Array.isArray(defaultDate)) {
defaultDate = []
}
const start = limitDateRange(defaultDate[0] || now, minValue, createPreviousDay(maxValue))
const end = limitDateRange(defaultDate[1] || now, createNextDay(minValue))
return [start, end]
}
if (type === "multiple") {
if (Array.isArray(defaultDate)) {
return defaultDate.map((date) => limitDateRange(date))
}
return [limitDateRange(now)]
}
if (!defaultDate || Array.isArray(defaultDate)) {
defaultDate = now
}
return limitDateRange(defaultDate)
}
// get first disabled calendarDay between date range
function getDisabledDate(
disabledDays: CalendarDayObject[],
startDay: Date,
date: Date,
): Date | undefined {
return disabledDays.find(
(day) => compareDate(startDay, day.value!) === -1 && compareDate(day.value!, date) === -1,
)?.value
}
// disabled calendarDay
function getDisabledDays() {
return monthRefs.reduce((arr, ref) => {
arr.push(...(ref.current?.disabledDays ?? []))
return arr
}, [] as CalendarDayObject[])
}
function change(dateValue: CalendarValueType, complete?: boolean) {
changeValueRef.current = dateValue
setValue?.(dateValue)
if (complete && !hasConfirmRef.current) {
onConfirm?.(dateValue)
}
}
function onDayClick(day: CalendarDayObject) {
const { value: date } = day
if (readonly || !date) {
return
}
if (type === "range") {
const disabledDays = getDisabledDays()
if (!value) {
change([date])
return
}
const [startDay, endDay] = value as [Date, Date]
if (startDay && !endDay) {
const compareToStart = compareDate(date, startDay)
if (compareToStart === 1) {
const disabledDay = getDisabledDate(disabledDays, startDay, date)
if (disabledDay) {
change([startDay, createPreviousDay(disabledDay)])
} else {
change([startDay, date], true)
}
} else if (compareToStart === -1) {
change([date])
} else {
change([date, date], true)
}
} else {
change([date])
}
} else if (type === "multiple") {
if (!value) {
change([date])
return
}
const dates = value as Date[]
const newDates = _.filter(dates, (dateItem) => compareDate(dateItem, date) !== 0)
if (_.size(newDates) !== _.size(dates)) {
change(newDates)
} else {
change([...dates, date])
}
} else {
change(date, true)
}
}
async function onScroll() {
const top = await getScrollTop(bodyRef)
const bodyHeight = (await getRect(bodyRef)).height
const bottom = top + bodyHeight
const heights = months.map((item, index) => monthRefs[index].current.getHeight())
const heightSum = heights.reduce((a, b) => a + b, 0)
// iOS scroll bounce may exceed the range
if (bottom > heightSum && top > 0) {
return
}
let height = 0
let currentMonth
for (let i = 0; i < months.length; i++) {
const month = monthRefs[i]
const visible = height <= bottom && height + heights[i] >= top
if (visible && !currentMonth) {
currentMonth = month
break
}
height += heights[i]
}
if (currentMonth) {
const subtitle = subtitleRender(currentMonth.current.getValue())
setMonthSubtitle(currentMonth.current, subtitle)
}
}
function setMonthSubtitle(currentMonth: CalendarMonthInstance, subtitle: ReactNode) {
/* istanbul ignore else */
if (currentMonth) {
setSubtitle(subtitle)
}
}
async function scrollToDate(targetDate?: Date) {
months.some((month, index) => {
if (compareYearMonth(month, targetDate as Date) === 0) {
const currentMonth = monthRefs[index].current
const subtitle = subtitleRender(currentMonth.getValue())
setMonthSubtitle(currentMonth, subtitle)
nextTick(() => {
if (bodyRef.current) {
Promise.all([
getRect(bodyRef), //
getScrollTop(bodyRef),
currentMonth?.getScrollTop(subtitle),
]).then(([{ top: bodyTop }, bodyScrollTop, monthScrollTop]) => {
const newBodyScrollTop = monthScrollTop - bodyTop + bodyScrollTop
if (bodyScrollTopRef.current !== newBodyScrollTop) {
setBodyScrollTop(bodyScrollTopRef.current)
setBodyScrollTop(newBodyScrollTop)
} else {
setBodyScrollTop(newBodyScrollTop)
}
})
}
})
return true
}
return false
})
}
// scroll to current month
async function scrollIntoView(newValue?: CalendarValueType) {
if (newValue) {
const targetDate = (() => {
if (type === "single" && _.isDate(newValue)) {
return newValue as Date
} else if (_.isArray(newValue)) {
return newValue[0] as Date
}
})()
await scrollToDate(targetDate)
} else {
await onScroll()
}
}
const reset = (date?: CalendarValueType) => nextTick(() => scrollIntoView(date).then())
const init = () => reset(value)
useEffect(() => {
if (value !== changeValueRef.current) {
reset(getInitialDate(value))
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [value])
useEffect(() => {
reset(getInitialDate(value))
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [type, subtitleRender, minValue, maxValue])
useMounted(init)
const monthsRender = useMemo(() => {
return _.map(months, (month, index) => (
<CalendarMonth
ref={setMonthRefs(index)}
key={month.getTime()}
value={month}
top={index === 0}
watermark={watermark}
/>
))
}, [months, setMonthRefs, watermark])
function notifyConfirm(hasConfirm: boolean) {
hasConfirmRef.current = hasConfirm
}
function handleConfirm() {
onConfirm?.(value as CalendarValueType)
}
return (
<CalendarContext.Provider
value={{
type,
subtitle,
firstDayOfWeek: dayOffset,
min: minValue,
max: maxValue,
value,
formatter,
onDayClick,
notifyConfirm,
onConfirm: handleConfirm,
}}
>
<View
className={classNames(
prefixClassname("calendar"),
prefixClassname(`calendar--${type}`),
className,
)}
style={style}
>
{(title || subtitle) && <CalendarHeader title={title} subtitle={subtitle} />}
<ScrollView
ref={bodyRef}
className={prefixClassname("calendar__body")}
scrollY
scrollTop={bodyScrollTop}
onScroll={async ({ detail }) => {
bodyScrollTopRef.current = detail.scrollTop
await onScroll()
}}
>
{monthsRender}
</ScrollView>
{footer}
</View>
</CalendarContext.Provider>
)
}
export default Calendar | the_stack |
import * as Generator from 'yeoman-generator';
import * as lodash from 'lodash';
import * as chalk from 'chalk';
import { GeneratorTeamsAppOptions } from './../app/GeneratorTeamsAppOptions';
import { Yotilities } from './../app/Yotilities';
import { Project, Scope, Decorator, ClassDeclaration } from "ts-morph";
import * as ts from 'typescript';
import * as path from 'path';
import EmptyGuid = require('../app/EmptyGuid');
import validate = require('uuid-validate');
import { ManifestGeneratorFactory } from '../app/manifestGeneration/ManifestGeneratorFactory';
export class MessageExtensionGenerator extends Generator {
options: GeneratorTeamsAppOptions;
public constructor(args: any, opts: any) {
super(args, opts);
opts.force = true;
this.options = opts.options;
this.desc('Adds a Message Extension to a Microsoft Teams Apps project');
}
public prompting() {
if (this.options.messageExtension) {
return this.prompt(
[
{
type: 'list',
name: 'messageExtensionHost',
message: 'Where is your message extension hosted?',
default: (answers: any) => {
if (this.options.botType == 'botframework') {
return 'existing';
} else {
return 'new';
}
},
choices: (answers: any) => {
var choices: any[] = [];
if (this.options.botType == 'botframework' ||
this.options.existingManifest && this.options.existingManifest.bots && this.options.existingManifest.bots.length > 0 ||
this.options.existingManifest && this.options.existingManifest.composeExtensions && this.options.existingManifest.composeExtensions.length > 0) {
choices.push({
name: 'In a bot or Messaging Extension already defined in this project',
value: 'existing',
});
} else {
choices.push({
name: 'In a new bot',
value: 'new'
});
}
choices.push({
name: 'In a bot hosted somewhere else',
value: 'external'
});
return choices;
}
},
{
// this is when we are running on an already existin project
type: 'list',
name: 'botId',
message: 'Choose which bot',
choices: (answers: any) => {
let choices: any[] = [];
if (this.options.existingManifest.bots) {
// TODO: use AST to find the bot classes as well
// Check existing bots
choices = this.options.existingManifest.bots.map((b: any) => {
return b.botId;
});
// check existing compose extensions
choices = choices.concat(this.options.existingManifest.composeExtensions.map((b: any) => {
return b.botId;
}));
}
if (this.options.bot) {
choices.push(this.options.botid);
}
return choices.filter((value, index, self) => self.indexOf(value) === index); // only return unique
},
when: (answers: any) => {
return answers.messageExtensionHost == 'existing' && this.options.existingManifest !== undefined
}
},
{
type: 'input',
name: 'messageExtensionId',
message: (answers: any) => {
var message = 'What is the Microsoft App ID for the bot used by the Message Extension? ';
return message;
},
default: (answers: any) => {
return EmptyGuid.empty;
},
validate: (input: string) => {
return validate(input) || input == EmptyGuid.empty;
},
when: (answers: any) => {
return answers.messageExtensionHost !== 'existing';
},
},
{
type: 'list',
name: 'messagingExtensionType',
message: 'What type of messaging extension command?',
choices: [
{
name: "Search based messaging extension",
value: "query"
},
{
name: "Action based messaging extension",
value: "action"
},
{
name: "Link unfurling messaging extension",
value: "queryLink"
}
]
},
{
type: 'checkbox',
name: 'messagingExtensionActionContext',
message: "What context do you want your action to work from?",
choices: [
{
name: "The compose box",
value: "compose",
checked: true
},
{
name: "The command box",
value: "commandBox",
checked: true
},
{
name: "Conversation messages",
value: "message"
}
],
when: (answers: any) => {
return answers.messagingExtensionType == "action"
}
},
{
type: 'list',
name: 'messagingExtensionActionInputType',
message: "How would you like to collect information from the user for your action?",
choices: [
{
name: "Using an Adaptive Card",
value: "adaptiveCard",
},
{
name: "Using static properties",
value: "static",
},
{
name: "Using a Task Module",
value: "taskModule"
}
],
when: (answers: any) => {
return answers.messagingExtensionType == "action";
}
},
{
type: 'confirm',
name: 'messagingExtensionActionResponseTypeConfig',
message: "Do you need configuration or authorization when collecting information?",
when: (answers: any) => {
return answers.messagingExtensionType == "action" && answers.messagingExtensionActionInputType != "static";
},
default: false
},
{
type: 'confirm',
name: 'messagingExtensionCanUpdateConfiguration',
message: 'Would you like a Settings option for the messaging extension?',
default: (answers: any) => {
if (this.options.existingManifest && answers.messageExtensionHost == 'existing') {
return false; // if you haven't added it already, we assume you don't want it this time either
}
return true; // always return true if it's a new project
},
when: (answers) => {
if (this.options.existingManifest && answers.messageExtensionHost == 'existing') {
if (this.options.existingManifest.composeExtensions) {
const composeExtension = this.options.existingManifest.composeExtensions.find((c: { botId: any; }) => c.botId == answers.botId);
if (composeExtension && composeExtension.canUpdateConfiguration == false) {
return true; // if we already have not added a config, then it's ok now
}
}
return false; // there's already some ME with config in the project
}
return true; // always return true if it's a new project or a new bot
}
},
{
type: 'input',
name: 'messageExtensionName',
message: 'What is the name of your Message Extension command?',
default: this.options.title + ' Message Extension',
validate: (input: string, answers: any) => {
if (!(/^[a-zA-Z].*/.test(input))) {
return "Must start with an alphabetical character";
}
if (answers && answers.messageExtensionHost !== 'external') {
let name = lodash.camelCase(input);
if (!name.endsWith(`MessageExtension`)) {
name += `MessageExtension`;
}
let className = name.charAt(0).toUpperCase() + name.slice(1);
if (this.fs.exists(`src/server/${name}/${className}.ts`)) {
return `There's already a file with the name of ${name}/${className}.ts`;
}
}
return input.length > 0 && input.length <= 32;
},
},
{
type: 'input',
name: 'messageExtensionDescription',
message: 'Describe your Message Extension command?',
default: (answers: any) => {
return `Description of ${answers.messageExtensionName}`
},
validate: (input: string) => {
return input.length > 0;
}
},
{
type: 'input',
name: 'messageExtensionLinkDomains',
message: 'Provide a comma separated list of domains for your Message Extension Link Unfurling:',
default: '*.contoso.com',
validate: (input: string, answers: any) => {
if (!(/[\*]?.[\w]*[.[\w]*]*[,]?/gm.test(input))) {
return "Must contain a comma separated list of domains";
}
return input.length > 0;
},
when: (answers: any) => {
return answers.messagingExtensionType == "queryLink"
}
},
]
).then((answers: any) => {
this.options.messageExtensionHost = answers.messageExtensionHost;
this.options.messageExtensionTitle = answers.messageExtensionName;
this.options.messageExtensionDescription = answers.messageExtensionDescription;
this.options.messagingExtensionCanUpdateConfiguration = answers.messagingExtensionCanUpdateConfiguration;
this.options.messagingExtensionActionResponseTypeConfig = answers.messagingExtensionActionResponseTypeConfig;
this.options.messageExtensionName = lodash.camelCase(answers.messageExtensionName);
if (answers.messagingExtensionType) {
this.options.messagingExtensionType = answers.messagingExtensionType;
}
if (this.options.messagingExtensionType === "action") {
this.options.messagingExtensionActionContext = answers.messagingExtensionActionContext;
this.options.messagingExtensionActionInputType = answers.messagingExtensionActionInputType;
this.options.messagingExtensionActionResponseType = "adaptiveCard";
}
if (!this.options.messageExtensionName.endsWith(`MessageExtension`)) {
this.options.messageExtensionName += `MessageExtension`;
}
if (answers.messageExtensionLinkDomains) {
this.options.messageExtensionLinkDomains = answers.messageExtensionLinkDomains.split(",");
}
this.options.messageExtensionClassName = this.options.messageExtensionName.charAt(0).toUpperCase() + this.options.messageExtensionName.slice(1);
if (answers.messageExtensionHost == 'new') {
// we need to add the bot, even though the users did not choose to create one
this.options.messagingExtensionBot = true;
this.options.botid = answers.messageExtensionId;
this.options.messageExtensionId = `{{${this.options.botidEnv}}}`;
this.options.botType = 'botframework';
this.options.botTitle = answers.messageExtensionName + ' Bot';
this.options.botName = lodash.camelCase(this.options.botTitle); // TODO: check valid file name here
this.options.botClassName = this.options.botName.charAt(0).toUpperCase() + this.options.botName.slice(1);
} else if (answers.messageExtensionHost == 'existing') {
// reuse the bot id
if (this.options.existingManifest) {
// load local environment variable
require('dotenv').config({
path: `${this.destinationRoot()}${path.sep}.env`
});
this.options.messageExtensionId = answers.botId;
// if we already have a project, let's find the bot implementation class
const project = new Project();
project.addSourceFilesAtPaths(`${this.destinationRoot()}/src/server/**/*.ts`);
// get all classes that has bots
const botClasses = project.getSourceFiles().map(s => {
return s.getClasses().map<{ c: ClassDeclaration, id: string } | undefined>(c => {
const dec: Decorator | undefined = c.getDecorator('BotDeclaration');
if (dec) {
// arg 2 is the id
const idarg = dec.getArguments()[2];
let idargval = idarg.getText();
// check if the idargval has "-characters
if (idargval.startsWith("\"") && idargval.endsWith("\"")) {
idargval = idargval.substr(1, idargval.length - 2);
}
if (validate(idargval) || idargval == EmptyGuid.empty) {
return { c: c, id: idargval };
} else {
if (idargval.startsWith("process.env.")) {
return { c: c, id: `{{${idargval.substring(12)}}}` };
}
if (idargval.startsWith("{") && idargval.endsWith("}")) {
this.log(chalk.red("Please update your bot ID references to use a Guids that are not encapsulated in { and }."))
}
this.log(chalk.red('Unable to continue, as I cannot correlate the bot ID and the TypeScript class'));
this.log(chalk.red('Please verify that you have a valid Guid or a valid environment variable in your BotDeclaration.'));
process.exit(1);
}
}
}).filter(x => {
return x !== undefined;
});
})
let botId: string = answers.botId;
const botClass = lodash.flatten(botClasses).find(c => {
return c !== undefined && c.id == botId;
});
if (botClass) {
// we need the file name here, because that is what we use and not the actual class name (normally they should be the same though)
this.options.botClassName = botClass.c.getSourceFile().getBaseNameWithoutExtension() as string;
// we need the directory here and not the actual bot name
this.options.botName = botClass.c.getSourceFile().getDirectory().getBaseName() as string;
} else {
this.log(chalk.red('Unable to continue, as I could not locate the bot implementation'));
this.log(chalk.red('Please verify that you have a valid Guid or a valid environment variable in your BotDeclaration.'));
process.exit(1);
}
} else {
// we're adding a bot AND an extension
this.options.messageExtensionId = `{{${this.options.botidEnv}}}`;
}
}
this.options.reactComponents = true;
});
}
}
public writing() {
if (this.options.messageExtension) {
const manifestGeneratorFactory = new ManifestGeneratorFactory();
const manifestGenerator = manifestGeneratorFactory.createManifestGenerator(this.options.manifestVersion);
let manifestPath = "src/manifest/manifest.json";
var manifest: any = this.fs.readJSON(manifestPath);
manifestGenerator.updateMessageExtensionManifest(manifest, this.options);
this.fs.writeJSON(manifestPath, manifest);
// Externally hosted bots does not have an implementation
if (this.options.messageExtensionHost !== "external") {
let templateFiles = [];
templateFiles.push(
"src/server/{messageExtensionName}/{messageExtensionClassName}.ts",
);
if (this.options.messagingExtensionCanUpdateConfiguration || this.options.messagingExtensionActionResponseTypeConfig) {
templateFiles.push(
"src/client/{messageExtensionName}/{messageExtensionClassName}Config.tsx",
"src/public/{messageExtensionName}/config.html",
);
}
// add the task module
if (this.options.messagingExtensionType == "action" && this.options.messagingExtensionActionInputType === "taskModule") {
templateFiles.push(
"src/client/{messageExtensionName}/{messageExtensionClassName}Action.tsx",
"src/public/{messageExtensionName}/action.html",
);
}
if (this.options.unitTestsEnabled &&
(this.options.messagingExtensionCanUpdateConfiguration || this.options.messagingExtensionActionResponseTypeConfig)) {
templateFiles.push(
"src/client/{messageExtensionName}/__tests__/{messageExtensionClassName}Config.spec.tsx"
);
}
if (this.options.unitTestsEnabled) {
templateFiles.push(
"src/server/{messageExtensionName}/__tests__/{messageExtensionClassName}.spec.ts"
);
}
templateFiles.forEach(t => {
this.fs.copyTpl(
this.templatePath(t),
Yotilities.fixFileNames(t, this.options),
this.options);
});
Yotilities.addAdditionalDeps([
["botbuilder-teams-messagingextensions", "1.8.0-preview2"]
], this.fs);
if (this.options.messagingExtensionCanUpdateConfiguration || this.options.messagingExtensionActionResponseTypeConfig) {
Yotilities.insertTsExportDeclaration(
"src/client/client.ts",
`./${this.options.messageExtensionName}/${this.options.messageExtensionClassName}Config`,
`Automatically added for the ${this.options.messageExtensionName} message extension`,
this.fs
);
}
if (this.options.messagingExtensionType == "action" && this.options.messagingExtensionActionInputType == "taskModule") {
Yotilities.insertTsExportDeclaration(
"src/client/client.ts",
`./${this.options.messageExtensionName}/${this.options.messageExtensionClassName}Action`,
`Automatically added for the ${this.options.messageExtensionName} message extension action`,
this.fs
);
}
// Dynamically insert the reference and hook it up to the bot
const project = new Project();
const file = project.createSourceFile(
`src/server/${this.options.botName}/${this.options.botClassName}.ts`,
this.fs.read(`src/server/${this.options.botName}/${this.options.botClassName}.ts`), {
overwrite: true
});
const classes = file.getClasses();
const cl = classes.find(x => {
return x.getDecorator('BotDeclaration') != undefined;
});
// insert the import statement
const imports = file.getImportDeclarations();
const lastImport = imports.length > 0 ? imports[imports.length - 1] : undefined;
const pos = lastImport !== undefined ? lastImport.getChildIndex() : 0;
const importDecl = file.insertImportDeclaration(pos, {
defaultImport: this.options.messageExtensionClassName,
moduleSpecifier: `../${this.options.messageExtensionName}/${this.options.messageExtensionClassName}`,
});
let hostimports = imports.filter(i => {
return i.getModuleSpecifier().getLiteralText() == 'express-msteams-host'
});
if (hostimports.length >= 1) {
let alreadyImported = hostimports.filter(i => {
return i.getNamedImports().map(n => { return n.getText(); }).indexOf('MessageExtensionDeclaration') != -1;
});
if (alreadyImported.length == 0) {
hostimports[0].addNamedImport(`MessageExtensionDeclaration`);
}
} else {
const importDecl = file.insertImportDeclaration(pos, {
namedImports: [`MessageExtensionDeclaration`],
moduleSpecifier: `express-msteams-host`,
});
}
if (cl) {
// add the property
const prop = cl.insertProperty(1, {
scope: Scope.Private,
name: `_${this.options.messageExtensionName}`,
type: this.options.messageExtensionClassName,
docs: [`Local property for ${this.options.messageExtensionClassName}`]
});
// add the decorator
prop.addDecorator({
name: 'MessageExtensionDeclaration',
arguments: [`"${this.options.messageExtensionName}"`]
});
// add a new line after the property to avoid eslint issue
prop.appendWhitespace("\n");
const children = prop.getChildren();
if (children && children.length > 0) {
const declaration = children.find(c => { return c.getKind() == ts.SyntaxKind.PropertyDeclaration; });
if (declaration) {
cl.insertText(declaration.getPos(), "// eslint:disable-next-line: variable-name\n");
}
}
// hook up the logic in the constructor
const constructors = cl.getConstructors();
if (constructors.length > 0) {
const c = constructors[0];
// use index 1, as we need to insert it after the super();
c.insertStatements(1, `// Message extension ${this.options.messageExtensionClassName}
this._${this.options.messageExtensionName} = new ${this.options.messageExtensionClassName}();`);
} else {
// TODO: log
}
} else {
// TODO: log
}
file.formatText();
this.fs.write(`src/server/${this.options.botName}/${this.options.botClassName}.ts`, file.getFullText());
}
}
}
} | the_stack |
declare module 'http' {
import * as stream from 'node:stream';
import { URL } from 'node:url';
import { Socket, Server as NetServer } from 'node:net';
// incoming headers will never contain number
interface IncomingHttpHeaders extends NodeJS.Dict<string | string[]> {
accept?: string | undefined;
'accept-language'?: string | undefined;
'accept-patch'?: string | undefined;
'accept-ranges'?: string | undefined;
'access-control-allow-credentials'?: string | undefined;
'access-control-allow-headers'?: string | undefined;
'access-control-allow-methods'?: string | undefined;
'access-control-allow-origin'?: string | undefined;
'access-control-expose-headers'?: string | undefined;
'access-control-max-age'?: string | undefined;
'access-control-request-headers'?: string | undefined;
'access-control-request-method'?: string | undefined;
age?: string | undefined;
allow?: string | undefined;
'alt-svc'?: string | undefined;
authorization?: string | undefined;
'cache-control'?: string | undefined;
connection?: string | undefined;
'content-disposition'?: string | undefined;
'content-encoding'?: string | undefined;
'content-language'?: string | undefined;
'content-length'?: string | undefined;
'content-location'?: string | undefined;
'content-range'?: string | undefined;
'content-type'?: string | undefined;
cookie?: string | undefined;
date?: string | undefined;
etag?: string | undefined;
expect?: string | undefined;
expires?: string | undefined;
forwarded?: string | undefined;
from?: string | undefined;
host?: string | undefined;
'if-match'?: string | undefined;
'if-modified-since'?: string | undefined;
'if-none-match'?: string | undefined;
'if-unmodified-since'?: string | undefined;
'last-modified'?: string | undefined;
location?: string | undefined;
origin?: string | undefined;
pragma?: string | undefined;
'proxy-authenticate'?: string | undefined;
'proxy-authorization'?: string | undefined;
'public-key-pins'?: string | undefined;
range?: string | undefined;
referer?: string | undefined;
'retry-after'?: string | undefined;
'sec-websocket-accept'?: string | undefined;
'sec-websocket-extensions'?: string | undefined;
'sec-websocket-key'?: string | undefined;
'sec-websocket-protocol'?: string | undefined;
'sec-websocket-version'?: string | undefined;
'set-cookie'?: string[] | undefined;
'strict-transport-security'?: string | undefined;
tk?: string | undefined;
trailer?: string | undefined;
'transfer-encoding'?: string | undefined;
upgrade?: string | undefined;
'user-agent'?: string | undefined;
vary?: string | undefined;
via?: string | undefined;
warning?: string | undefined;
'www-authenticate'?: string | undefined;
}
// outgoing headers allows numbers (as they are converted internally to strings)
type OutgoingHttpHeader = number | string | string[];
interface OutgoingHttpHeaders extends NodeJS.Dict<OutgoingHttpHeader> {}
interface ClientRequestArgs {
abort?: AbortSignal | undefined;
protocol?: string | null | undefined;
host?: string | null | undefined;
hostname?: string | null | undefined;
family?: number | undefined;
port?: number | string | null | undefined;
defaultPort?: number | string | undefined;
localAddress?: string | undefined;
socketPath?: string | undefined;
/**
* @default 8192
*/
maxHeaderSize?: number | undefined;
method?: string | undefined;
path?: string | null | undefined;
headers?: OutgoingHttpHeaders | undefined;
auth?: string | null | undefined;
agent?: Agent | boolean | undefined;
_defaultAgent?: Agent | undefined;
timeout?: number | undefined;
setHost?: boolean | undefined;
// https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278
createConnection?: ((options: ClientRequestArgs, oncreate: (err: Error, socket: Socket) => void) => Socket) | undefined;
}
interface ServerOptions {
IncomingMessage?: typeof IncomingMessage | undefined;
ServerResponse?: typeof ServerResponse | undefined;
/**
* Optionally overrides the value of
* `--max-http-header-size` for requests received by this server, i.e.
* the maximum length of request headers in bytes.
* @default 8192
*/
maxHeaderSize?: number | undefined;
/**
* Use an insecure HTTP parser that accepts invalid HTTP headers when true.
* Using the insecure parser should be avoided.
* See --insecure-http-parser for more information.
* @default false
*/
insecureHTTPParser?: boolean | undefined;
}
type RequestListener = (req: IncomingMessage, res: ServerResponse) => void;
/**
* @since v0.1.17
*/
class Server extends NetServer {
constructor(requestListener?: RequestListener);
constructor(options: ServerOptions, requestListener?: RequestListener);
setTimeout(msecs?: number, callback?: () => void): this;
setTimeout(callback: () => void): this;
/**
* Limits maximum incoming headers count. If set to 0, no limit will be applied.
* @default 2000
* {@link https://nodejs.org/api/http.html#http_server_maxheaderscount}
*/
maxHeadersCount: number | null;
timeout: number;
/**
* Limit the amount of time the parser will wait to receive the complete HTTP headers.
* @default 60000
* {@link https://nodejs.org/api/http.html#http_server_headerstimeout}
*/
headersTimeout: number;
keepAliveTimeout: number;
/**
* Sets the timeout value in milliseconds for receiving the entire request from the client.
* @default 0
* {@link https://nodejs.org/api/http.html#http_server_requesttimeout}
*/
requestTimeout: number;
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: 'close', listener: () => void): this;
addListener(event: 'connection', listener: (socket: Socket) => void): this;
addListener(event: 'error', listener: (err: Error) => void): this;
addListener(event: 'listening', listener: () => void): this;
addListener(event: 'checkContinue', listener: RequestListener): this;
addListener(event: 'checkExpectation', listener: RequestListener): this;
addListener(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this;
addListener(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this;
addListener(event: 'request', listener: RequestListener): this;
addListener(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this;
emit(event: string, ...args: any[]): boolean;
emit(event: 'close'): boolean;
emit(event: 'connection', socket: Socket): boolean;
emit(event: 'error', err: Error): boolean;
emit(event: 'listening'): boolean;
emit(event: 'checkContinue', req: IncomingMessage, res: ServerResponse): boolean;
emit(event: 'checkExpectation', req: IncomingMessage, res: ServerResponse): boolean;
emit(event: 'clientError', err: Error, socket: stream.Duplex): boolean;
emit(event: 'connect', req: IncomingMessage, socket: stream.Duplex, head: Buffer): boolean;
emit(event: 'request', req: IncomingMessage, res: ServerResponse): boolean;
emit(event: 'upgrade', req: IncomingMessage, socket: stream.Duplex, head: Buffer): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: 'close', listener: () => void): this;
on(event: 'connection', listener: (socket: Socket) => void): this;
on(event: 'error', listener: (err: Error) => void): this;
on(event: 'listening', listener: () => void): this;
on(event: 'checkContinue', listener: RequestListener): this;
on(event: 'checkExpectation', listener: RequestListener): this;
on(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this;
on(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this;
on(event: 'request', listener: RequestListener): this;
on(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: 'close', listener: () => void): this;
once(event: 'connection', listener: (socket: Socket) => void): this;
once(event: 'error', listener: (err: Error) => void): this;
once(event: 'listening', listener: () => void): this;
once(event: 'checkContinue', listener: RequestListener): this;
once(event: 'checkExpectation', listener: RequestListener): this;
once(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this;
once(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this;
once(event: 'request', listener: RequestListener): this;
once(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: 'close', listener: () => void): this;
prependListener(event: 'connection', listener: (socket: Socket) => void): this;
prependListener(event: 'error', listener: (err: Error) => void): this;
prependListener(event: 'listening', listener: () => void): this;
prependListener(event: 'checkContinue', listener: RequestListener): this;
prependListener(event: 'checkExpectation', listener: RequestListener): this;
prependListener(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this;
prependListener(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this;
prependListener(event: 'request', listener: RequestListener): this;
prependListener(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: 'close', listener: () => void): this;
prependOnceListener(event: 'connection', listener: (socket: Socket) => void): this;
prependOnceListener(event: 'error', listener: (err: Error) => void): this;
prependOnceListener(event: 'listening', listener: () => void): this;
prependOnceListener(event: 'checkContinue', listener: RequestListener): this;
prependOnceListener(event: 'checkExpectation', listener: RequestListener): this;
prependOnceListener(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this;
prependOnceListener(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this;
prependOnceListener(event: 'request', listener: RequestListener): this;
prependOnceListener(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this;
}
/**
* This class serves as the parent class of {@link ClientRequest} and {@link ServerResponse}. It is an abstract of outgoing message from
* the perspective of the participants of HTTP transaction.
* @since v0.1.17
*/
class OutgoingMessage extends stream.Writable {
readonly req: IncomingMessage;
chunkedEncoding: boolean;
shouldKeepAlive: boolean;
useChunkedEncodingByDefault: boolean;
sendDate: boolean;
/**
* @deprecated Use `writableEnded` instead.
*/
finished: boolean;
/**
* Read-only. `true` if the headers were sent, otherwise `false`.
* @since v0.9.3
*/
readonly headersSent: boolean;
/**
* Aliases of `outgoingMessage.socket`
* @since v0.3.0
* @deprecated Since v15.12.0 - Use `socket` instead.
*/
readonly connection: Socket | null;
/**
* Reference to the underlying socket. Usually, users will not want to access
* this property.
*
* After calling `outgoingMessage.end()`, this property will be nulled.
* @since v0.3.0
*/
readonly socket: Socket | null;
constructor();
/**
* occurs, Same as binding to the `timeout` event.
*
* Once a socket is associated with the message and is connected,`socket.setTimeout()` will be called with `msecs` as the first parameter.
* @since v0.9.12
* @param callback Optional function to be called when a timeout
*/
setTimeout(msecs: number, callback?: () => void): this;
/**
* Sets a single header value for the header object.
* @since v0.4.0
* @param name Header name
* @param value Header value
*/
setHeader(name: string, value: number | string | ReadonlyArray<string>): this;
/**
* Gets the value of HTTP header with the given name. If such a name doesn't
* exist in message, it will be `undefined`.
* @since v0.4.0
* @param name Name of header
*/
getHeader(name: string): number | string | string[] | undefined;
/**
* Returns a shallow copy of the current outgoing headers. Since a shallow
* copy is used, array values may be mutated without additional calls to
* various header-related HTTP module methods. The keys of the returned
* object are the header names and the values are the respective header
* values. All header names are lowercase.
*
* The object returned by the `outgoingMessage.getHeaders()` method does
* not prototypically inherit from the JavaScript Object. This means that
* typical Object methods such as `obj.toString()`, `obj.hasOwnProperty()`,
* and others are not defined and will not work.
*
* ```js
* outgoingMessage.setHeader('Foo', 'bar');
* outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
*
* const headers = outgoingMessage.getHeaders();
* // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }
* ```
* @since v8.0.0
*/
getHeaders(): OutgoingHttpHeaders;
/**
* Returns an array of names of headers of the outgoing outgoingMessage. All
* names are lowercase.
* @since v8.0.0
*/
getHeaderNames(): string[];
/**
* Returns `true` if the header identified by `name` is currently set in the
* outgoing headers. The header name is case-insensitive.
*
* ```js
* const hasContentType = outgoingMessage.hasHeader('content-type');
* ```
* @since v8.0.0
*/
hasHeader(name: string): boolean;
/**
* Removes a header that is queued for implicit sending.
*
* ```js
* outgoingMessage.removeHeader('Content-Encoding');
* ```
* @since v0.4.0
*/
removeHeader(name: string): void;
/**
* Adds HTTP trailers (headers but at the end of the message) to the message.
*
* Trailers are **only** be emitted if the message is chunked encoded. If not,
* the trailer will be silently discarded.
*
* HTTP requires the `Trailer` header to be sent to emit trailers,
* with a list of header fields in its value, e.g.
*
* ```js
* message.writeHead(200, { 'Content-Type': 'text/plain',
* 'Trailer': 'Content-MD5' });
* message.write(fileData);
* message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' });
* message.end();
* ```
*
* Attempting to set a header field name or value that contains invalid characters
* will result in a `TypeError` being thrown.
* @since v0.3.0
*/
addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void;
/**
* Compulsorily flushes the message headers
*
* For efficiency reason, Node.js normally buffers the message headers
* until `outgoingMessage.end()` is called or the first chunk of message data
* is written. It then tries to pack the headers and data into a single TCP
* packet.
*
* It is usually desired (it saves a TCP round-trip), but not when the first
* data is not sent until possibly much later. `outgoingMessage.flushHeaders()`bypasses the optimization and kickstarts the request.
* @since v1.6.0
*/
flushHeaders(): void;
}
/**
* This object is created internally by an HTTP server, not by the user. It is
* passed as the second parameter to the `'request'` event.
* @since v0.1.17
*/
class ServerResponse extends OutgoingMessage {
/**
* When using implicit headers (not calling `response.writeHead()` explicitly),
* this property controls the status code that will be sent to the client when
* the headers get flushed.
*
* ```js
* response.statusCode = 404;
* ```
*
* After response header was sent to the client, this property indicates the
* status code which was sent out.
* @since v0.4.0
*/
statusCode: number;
/**
* When using implicit headers (not calling `response.writeHead()` explicitly),
* this property controls the status message that will be sent to the client when
* the headers get flushed. If this is left as `undefined` then the standard
* message for the status code will be used.
*
* ```js
* response.statusMessage = 'Not found';
* ```
*
* After response header was sent to the client, this property indicates the
* status message which was sent out.
* @since v0.11.8
*/
statusMessage: string;
constructor(req: IncomingMessage);
assignSocket(socket: Socket): void;
detachSocket(socket: Socket): void;
/**
* Sends a HTTP/1.1 100 Continue message to the client, indicating that
* the request body should be sent. See the `'checkContinue'` event on`Server`.
* @since v0.3.0
*/
writeContinue(callback?: () => void): void;
/**
* Sends a response header to the request. The status code is a 3-digit HTTP
* status code, like `404`. The last argument, `headers`, are the response headers.
* Optionally one can give a human-readable `statusMessage` as the second
* argument.
*
* `headers` may be an `Array` where the keys and values are in the same list.
* It is _not_ a list of tuples. So, the even-numbered offsets are key values,
* and the odd-numbered offsets are the associated values. The array is in the same
* format as `request.rawHeaders`.
*
* Returns a reference to the `ServerResponse`, so that calls can be chained.
*
* ```js
* const body = 'hello world';
* response
* .writeHead(200, {
* 'Content-Length': Buffer.byteLength(body),
* 'Content-Type': 'text/plain'
* })
* .end(body);
* ```
*
* This method must only be called once on a message and it must
* be called before `response.end()` is called.
*
* If `response.write()` or `response.end()` are called before calling
* this, the implicit/mutable headers will be calculated and call this function.
*
* When headers have been set with `response.setHeader()`, they will be merged
* with any headers passed to `response.writeHead()`, with the headers passed
* to `response.writeHead()` given precedence.
*
* If this method is called and `response.setHeader()` has not been called,
* it will directly write the supplied header values onto the network channel
* without caching internally, and the `response.getHeader()` on the header
* will not yield the expected result. If progressive population of headers is
* desired with potential future retrieval and modification, use `response.setHeader()` instead.
*
* ```js
* // Returns content-type = text/plain
* const server = http.createServer((req, res) => {
* res.setHeader('Content-Type', 'text/html');
* res.setHeader('X-Foo', 'bar');
* res.writeHead(200, { 'Content-Type': 'text/plain' });
* res.end('ok');
* });
* ```
*
* `Content-Length` is given in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js
* does not check whether `Content-Length` and the length of the body which has
* been transmitted are equal or not.
*
* Attempting to set a header field name or value that contains invalid characters
* will result in a `TypeError` being thrown.
* @since v0.1.30
*/
writeHead(statusCode: number, statusMessage?: string, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this;
writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this;
/**
* Sends a HTTP/1.1 102 Processing message to the client, indicating that
* the request body should be sent.
* @since v10.0.0
*/
writeProcessing(): void;
}
interface InformationEvent {
statusCode: number;
statusMessage: string;
httpVersion: string;
httpVersionMajor: number;
httpVersionMinor: number;
headers: IncomingHttpHeaders;
rawHeaders: string[];
}
/**
* This object is created internally and returned from {@link request}. It
* represents an _in-progress_ request whose header has already been queued. The
* header is still mutable using the `setHeader(name, value)`,`getHeader(name)`, `removeHeader(name)` API. The actual header will
* be sent along with the first data chunk or when calling `request.end()`.
*
* To get the response, add a listener for `'response'` to the request object.`'response'` will be emitted from the request object when the response
* headers have been received. The `'response'` event is executed with one
* argument which is an instance of {@link IncomingMessage}.
*
* During the `'response'` event, one can add listeners to the
* response object; particularly to listen for the `'data'` event.
*
* If no `'response'` handler is added, then the response will be
* entirely discarded. However, if a `'response'` event handler is added,
* then the data from the response object **must** be consumed, either by
* calling `response.read()` whenever there is a `'readable'` event, or
* by adding a `'data'` handler, or by calling the `.resume()` method.
* Until the data is consumed, the `'end'` event will not fire. Also, until
* the data is read it will consume memory that can eventually lead to a
* 'process out of memory' error.
*
* For backward compatibility, `res` will only emit `'error'` if there is an`'error'` listener registered.
*
* Node.js does not check whether Content-Length and the length of the
* body which has been transmitted are equal or not.
* @since v0.1.17
*/
class ClientRequest extends OutgoingMessage {
/**
* The `request.aborted` property will be `true` if the request has
* been aborted.
* @since v0.11.14
*/
aborted: boolean;
/**
* The request host.
* @since v14.5.0, v12.19.0
*/
host: string;
/**
* The request protocol.
* @since v14.5.0, v12.19.0
*/
protocol: string;
constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void);
/**
* The request method.
* @since v0.1.97
*/
method: string;
/**
* The request path.
* @since v0.4.0
*/
path: string;
/**
* Marks the request as aborting. Calling this will cause remaining data
* in the response to be dropped and the socket to be destroyed.
* @since v0.3.8
* @deprecated Since v14.1.0,v13.14.0 - Use `destroy` instead.
*/
abort(): void;
onSocket(socket: Socket): void;
/**
* Once a socket is assigned to this request and is connected `socket.setTimeout()` will be called.
* @since v0.5.9
* @param timeout Milliseconds before a request times out.
* @param callback Optional function to be called when a timeout occurs. Same as binding to the `'timeout'` event.
*/
setTimeout(timeout: number, callback?: () => void): this;
/**
* Once a socket is assigned to this request and is connected `socket.setNoDelay()` will be called.
* @since v0.5.9
*/
setNoDelay(noDelay?: boolean): void;
/**
* Once a socket is assigned to this request and is connected `socket.setKeepAlive()` will be called.
* @since v0.5.9
*/
setSocketKeepAlive(enable?: boolean, initialDelay?: number): void;
/**
* Returns an array containing the unique names of the current outgoing raw
* headers. Header names are returned with their exact casing being set.
*
* ```js
* request.setHeader('Foo', 'bar');
* request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
*
* const headerNames = request.getRawHeaderNames();
* // headerNames === ['Foo', 'Set-Cookie']
* ```
* @since v15.13.0
*/
getRawHeaderNames(): string[];
addListener(event: 'abort', listener: () => void): this;
addListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
addListener(event: 'continue', listener: () => void): this;
addListener(event: 'information', listener: (info: InformationEvent) => void): this;
addListener(event: 'response', listener: (response: IncomingMessage) => void): this;
addListener(event: 'socket', listener: (socket: Socket) => void): this;
addListener(event: 'timeout', listener: () => void): this;
addListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
addListener(event: 'close', listener: () => void): this;
addListener(event: 'drain', listener: () => void): this;
addListener(event: 'error', listener: (err: Error) => void): this;
addListener(event: 'finish', listener: () => void): this;
addListener(event: 'pipe', listener: (src: stream.Readable) => void): this;
addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
on(event: 'abort', listener: () => void): this;
on(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
on(event: 'continue', listener: () => void): this;
on(event: 'information', listener: (info: InformationEvent) => void): this;
on(event: 'response', listener: (response: IncomingMessage) => void): this;
on(event: 'socket', listener: (socket: Socket) => void): this;
on(event: 'timeout', listener: () => void): this;
on(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
on(event: 'close', listener: () => void): this;
on(event: 'drain', listener: () => void): this;
on(event: 'error', listener: (err: Error) => void): this;
on(event: 'finish', listener: () => void): this;
on(event: 'pipe', listener: (src: stream.Readable) => void): this;
on(event: 'unpipe', listener: (src: stream.Readable) => void): this;
on(event: string | symbol, listener: (...args: any[]) => void): this;
once(event: 'abort', listener: () => void): this;
once(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
once(event: 'continue', listener: () => void): this;
once(event: 'information', listener: (info: InformationEvent) => void): this;
once(event: 'response', listener: (response: IncomingMessage) => void): this;
once(event: 'socket', listener: (socket: Socket) => void): this;
once(event: 'timeout', listener: () => void): this;
once(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
once(event: 'close', listener: () => void): this;
once(event: 'drain', listener: () => void): this;
once(event: 'error', listener: (err: Error) => void): this;
once(event: 'finish', listener: () => void): this;
once(event: 'pipe', listener: (src: stream.Readable) => void): this;
once(event: 'unpipe', listener: (src: stream.Readable) => void): this;
once(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener(event: 'abort', listener: () => void): this;
prependListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
prependListener(event: 'continue', listener: () => void): this;
prependListener(event: 'information', listener: (info: InformationEvent) => void): this;
prependListener(event: 'response', listener: (response: IncomingMessage) => void): this;
prependListener(event: 'socket', listener: (socket: Socket) => void): this;
prependListener(event: 'timeout', listener: () => void): this;
prependListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
prependListener(event: 'close', listener: () => void): this;
prependListener(event: 'drain', listener: () => void): this;
prependListener(event: 'error', listener: (err: Error) => void): this;
prependListener(event: 'finish', listener: () => void): this;
prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this;
prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this;
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener(event: 'abort', listener: () => void): this;
prependOnceListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
prependOnceListener(event: 'continue', listener: () => void): this;
prependOnceListener(event: 'information', listener: (info: InformationEvent) => void): this;
prependOnceListener(event: 'response', listener: (response: IncomingMessage) => void): this;
prependOnceListener(event: 'socket', listener: (socket: Socket) => void): this;
prependOnceListener(event: 'timeout', listener: () => void): this;
prependOnceListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
prependOnceListener(event: 'close', listener: () => void): this;
prependOnceListener(event: 'drain', listener: () => void): this;
prependOnceListener(event: 'error', listener: (err: Error) => void): this;
prependOnceListener(event: 'finish', listener: () => void): this;
prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this;
prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this;
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
}
/**
* An `IncomingMessage` object is created by {@link Server} or {@link ClientRequest} and passed as the first argument to the `'request'` and `'response'` event respectively. It may be used to
* access response
* status, headers and data.
*
* Different from its `socket` value which is a subclass of `<stream.Duplex>`, the`IncomingMessage` itself extends `<stream.Readable>` and is created separately to
* parse and emit the incoming HTTP headers and payload, as the underlying socket
* may be reused multiple times in case of keep-alive.
* @since v0.1.17
*/
class IncomingMessage extends stream.Readable {
constructor(socket: Socket);
/**
* The `message.aborted` property will be `true` if the request has
* been aborted.
* @since v10.1.0
*/
aborted: boolean;
/**
* In case of server request, the HTTP version sent by the client. In the case of
* client response, the HTTP version of the connected-to server.
* Probably either `'1.1'` or `'1.0'`.
*
* Also `message.httpVersionMajor` is the first integer and`message.httpVersionMinor` is the second.
* @since v0.1.1
*/
httpVersion: string;
httpVersionMajor: number;
httpVersionMinor: number;
/**
* The `message.complete` property will be `true` if a complete HTTP message has
* been received and successfully parsed.
*
* This property is particularly useful as a means of determining if a client or
* server fully transmitted a message before a connection was terminated:
*
* ```js
* const req = http.request({
* host: '127.0.0.1',
* port: 8080,
* method: 'POST'
* }, (res) => {
* res.resume();
* res.on('end', () => {
* if (!res.complete)
* console.error(
* 'The connection was terminated while the message was still being sent');
* });
* });
* ```
* @since v0.3.0
*/
complete: boolean;
/**
* Alias for `message.socket`.
* @since v0.1.90
* @deprecated Since v16.0.0 - Use `socket`.
*/
connection: Socket;
/**
* The `net.Socket` object associated with the connection.
*
* With HTTPS support, use `request.socket.getPeerCertificate()` to obtain the
* client's authentication details.
*
* This property is guaranteed to be an instance of the `<net.Socket>` class,
* a subclass of `<stream.Duplex>`, unless the user specified a socket
* type other than `<net.Socket>`.
* @since v0.3.0
*/
socket: Socket;
/**
* The request/response headers object.
*
* Key-value pairs of header names and values. Header names are lower-cased.
*
* ```js
* // Prints something like:
* //
* // { 'user-agent': 'curl/7.22.0',
* // host: '127.0.0.1:8000',
* // accept: '*' }
* console.log(request.headers);
* ```
*
* Duplicates in raw headers are handled in the following ways, depending on the
* header name:
*
* * Duplicates of `age`, `authorization`, `content-length`, `content-type`,`etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`,`last-modified`, `location`,
* `max-forwards`, `proxy-authorization`, `referer`,`retry-after`, `server`, or `user-agent` are discarded.
* * `set-cookie` is always an array. Duplicates are added to the array.
* * For duplicate `cookie` headers, the values are joined together with '; '.
* * For all other headers, the values are joined together with ', '.
* @since v0.1.5
*/
headers: IncomingHttpHeaders;
/**
* The raw request/response headers list exactly as they were received.
*
* The keys and values are in the same list. It is _not_ a
* list of tuples. So, the even-numbered offsets are key values, and the
* odd-numbered offsets are the associated values.
*
* Header names are not lowercased, and duplicates are not merged.
*
* ```js
* // Prints something like:
* //
* // [ 'user-agent',
* // 'this is invalid because there can be only one',
* // 'User-Agent',
* // 'curl/7.22.0',
* // 'Host',
* // '127.0.0.1:8000',
* // 'ACCEPT',
* // '*' ]
* console.log(request.rawHeaders);
* ```
* @since v0.11.6
*/
rawHeaders: string[];
/**
* The request/response trailers object. Only populated at the `'end'` event.
* @since v0.3.0
*/
trailers: NodeJS.Dict<string>;
/**
* The raw request/response trailer keys and values exactly as they were
* received. Only populated at the `'end'` event.
* @since v0.11.6
*/
rawTrailers: string[];
/**
* Calls `message.socket.setTimeout(msecs, callback)`.
* @since v0.5.9
*/
setTimeout(msecs: number, callback?: () => void): this;
/**
* **Only valid for request obtained from {@link Server}.**
*
* The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`.
* @since v0.1.1
*/
method?: string | undefined;
/**
* **Only valid for request obtained from {@link Server}.**
*
* Request URL string. This contains only the URL that is present in the actual
* HTTP request. Take the following request:
*
* ```http
* GET /status?name=ryan HTTP/1.1
* Accept: text/plain
* ```
*
* To parse the URL into its parts:
*
* ```js
* new URL(request.url, `http://${request.headers.host}`);
* ```
*
* When `request.url` is `'/status?name=ryan'` and`request.headers.host` is `'localhost:3000'`:
*
* ```console
* $ node
* > new URL(request.url, `http://${request.headers.host}`)
* URL {
* href: 'http://localhost:3000/status?name=ryan',
* origin: 'http://localhost:3000',
* protocol: 'http:',
* username: '',
* password: '',
* host: 'localhost:3000',
* hostname: 'localhost',
* port: '3000',
* pathname: '/status',
* search: '?name=ryan',
* searchParams: URLSearchParams { 'name' => 'ryan' },
* hash: ''
* }
* ```
* @since v0.1.90
*/
url?: string | undefined;
/**
* **Only valid for response obtained from {@link ClientRequest}.**
*
* The 3-digit HTTP response status code. E.G. `404`.
* @since v0.1.1
*/
statusCode?: number | undefined;
/**
* **Only valid for response obtained from {@link ClientRequest}.**
*
* The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`.
* @since v0.11.10
*/
statusMessage?: string | undefined;
/**
* Calls `destroy()` on the socket that received the `IncomingMessage`. If `error`is provided, an `'error'` event is emitted on the socket and `error` is passed
* as an argument to any listeners on the event.
* @since v0.3.0
*/
destroy(error?: Error): void;
}
interface AgentOptions {
/**
* Keep sockets around in a pool to be used by other requests in the future. Default = false
*/
keepAlive?: boolean | undefined;
/**
* When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000.
* Only relevant if keepAlive is set to true.
*/
keepAliveMsecs?: number | undefined;
/**
* Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity
*/
maxSockets?: number | undefined;
/**
* Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default: Infinity.
*/
maxTotalSockets?: number | undefined;
/**
* Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256.
*/
maxFreeSockets?: number | undefined;
/**
* Socket timeout in milliseconds. This will set the timeout after the socket is connected.
*/
timeout?: number | undefined;
/**
* Scheduling strategy to apply when picking the next free socket to use.
* @default `lifo`
*/
scheduling?: 'fifo' | 'lifo' | undefined;
}
/**
* An `Agent` is responsible for managing connection persistence
* and reuse for HTTP clients. It maintains a queue of pending requests
* for a given host and port, reusing a single socket connection for each
* until the queue is empty, at which time the socket is either destroyed
* or put into a pool where it is kept to be used again for requests to the
* same host and port. Whether it is destroyed or pooled depends on the`keepAlive` `option`.
*
* Pooled connections have TCP Keep-Alive enabled for them, but servers may
* still close idle connections, in which case they will be removed from the
* pool and a new connection will be made when a new HTTP request is made for
* that host and port. Servers may also refuse to allow multiple requests
* over the same connection, in which case the connection will have to be
* remade for every request and cannot be pooled. The `Agent` will still make
* the requests to that server, but each one will occur over a new connection.
*
* When a connection is closed by the client or the server, it is removed
* from the pool. Any unused sockets in the pool will be unrefed so as not
* to keep the Node.js process running when there are no outstanding requests.
* (see `socket.unref()`).
*
* It is good practice, to `destroy()` an `Agent` instance when it is no
* longer in use, because unused sockets consume OS resources.
*
* Sockets are removed from an agent when the socket emits either
* a `'close'` event or an `'agentRemove'` event. When intending to keep one
* HTTP request open for a long time without keeping it in the agent, something
* like the following may be done:
*
* ```js
* http.get(options, (res) => {
* // Do stuff
* }).on('socket', (socket) => {
* socket.emit('agentRemove');
* });
* ```
*
* An agent may also be used for an individual request. By providing`{agent: false}` as an option to the `http.get()` or `http.request()`functions, a one-time use `Agent` with default options
* will be used
* for the client connection.
*
* `agent:false`:
*
* ```js
* http.get({
* hostname: 'localhost',
* port: 80,
* path: '/',
* agent: false // Create a new agent just for this one request
* }, (res) => {
* // Do stuff with response
* });
* ```
* @since v0.3.4
*/
class Agent {
/**
* By default set to 256\. For agents with `keepAlive` enabled, this
* sets the maximum number of sockets that will be left open in the free
* state.
* @since v0.11.7
*/
maxFreeSockets: number;
/**
* By default set to `Infinity`. Determines how many concurrent sockets the agent
* can have open per origin. Origin is the returned value of `agent.getName()`.
* @since v0.3.6
*/
maxSockets: number;
/**
* By default set to `Infinity`. Determines how many concurrent sockets the agent
* can have open. Unlike `maxSockets`, this parameter applies across all origins.
* @since v14.5.0, v12.19.0
*/
maxTotalSockets: number;
/**
* An object which contains arrays of sockets currently awaiting use by
* the agent when `keepAlive` is enabled. Do not modify.
*
* Sockets in the `freeSockets` list will be automatically destroyed and
* removed from the array on `'timeout'`.
* @since v0.11.4
*/
readonly freeSockets: NodeJS.ReadOnlyDict<Socket[]>;
/**
* An object which contains arrays of sockets currently in use by the
* agent. Do not modify.
* @since v0.3.6
*/
readonly sockets: NodeJS.ReadOnlyDict<Socket[]>;
/**
* An object which contains queues of requests that have not yet been assigned to
* sockets. Do not modify.
* @since v0.5.9
*/
readonly requests: NodeJS.ReadOnlyDict<IncomingMessage[]>;
constructor(opts?: AgentOptions);
/**
* Destroy any sockets that are currently in use by the agent.
*
* It is usually not necessary to do this. However, if using an
* agent with `keepAlive` enabled, then it is best to explicitly shut down
* the agent when it is no longer needed. Otherwise,
* sockets might stay open for quite a long time before the server
* terminates them.
* @since v0.11.4
*/
destroy(): void;
}
const METHODS: string[];
const STATUS_CODES: {
[errorCode: number]: string | undefined;
[errorCode: string]: string | undefined;
};
/**
* Returns a new instance of {@link Server}.
*
* The `requestListener` is a function which is automatically
* added to the `'request'` event.
* @since v0.1.13
*/
function createServer(requestListener?: RequestListener): Server;
function createServer(options: ServerOptions, requestListener?: RequestListener): Server;
// although RequestOptions are passed as ClientRequestArgs to ClientRequest directly,
// create interface RequestOptions would make the naming more clear to developers
interface RequestOptions extends ClientRequestArgs {}
/**
* Node.js maintains several connections per server to make HTTP requests.
* This function allows one to transparently issue requests.
*
* `url` can be a string or a `URL` object. If `url` is a
* string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object.
*
* If both `url` and `options` are specified, the objects are merged, with the`options` properties taking precedence.
*
* The optional `callback` parameter will be added as a one-time listener for
* the `'response'` event.
*
* `http.request()` returns an instance of the {@link ClientRequest} class. The `ClientRequest` instance is a writable stream. If one needs to
* upload a file with a POST request, then write to the `ClientRequest` object.
*
* ```js
* const http = require('http');
*
* const postData = JSON.stringify({
* 'msg': 'Hello World!'
* });
*
* const options = {
* hostname: 'www.google.com',
* port: 80,
* path: '/upload',
* method: 'POST',
* headers: {
* 'Content-Type': 'application/json',
* 'Content-Length': Buffer.byteLength(postData)
* }
* };
*
* const req = http.request(options, (res) => {
* console.log(`STATUS: ${res.statusCode}`);
* console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
* res.setEncoding('utf8');
* res.on('data', (chunk) => {
* console.log(`BODY: ${chunk}`);
* });
* res.on('end', () => {
* console.log('No more data in response.');
* });
* });
*
* req.on('error', (e) => {
* console.error(`problem with request: ${e.message}`);
* });
*
* // Write data to request body
* req.write(postData);
* req.end();
* ```
*
* In the example `req.end()` was called. With `http.request()` one
* must always call `req.end()` to signify the end of the request -
* even if there is no data being written to the request body.
*
* If any error is encountered during the request (be that with DNS resolution,
* TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted
* on the returned request object. As with all `'error'` events, if no listeners
* are registered the error will be thrown.
*
* There are a few special headers that should be noted.
*
* * Sending a 'Connection: keep-alive' will notify Node.js that the connection to
* the server should be persisted until the next request.
* * Sending a 'Content-Length' header will disable the default chunked encoding.
* * Sending an 'Expect' header will immediately send the request headers.
* Usually, when sending 'Expect: 100-continue', both a timeout and a listener
* for the `'continue'` event should be set. See RFC 2616 Section 8.2.3 for more
* information.
* * Sending an Authorization header will override using the `auth` option
* to compute basic authentication.
*
* Example using a `URL` as `options`:
*
* ```js
* const options = new URL('http://abc:xyz@example.com');
*
* const req = http.request(options, (res) => {
* // ...
* });
* ```
*
* In a successful request, the following events will be emitted in the following
* order:
*
* * `'socket'`
* * `'response'`
* * `'data'` any number of times, on the `res` object
* (`'data'` will not be emitted at all if the response body is empty, for
* instance, in most redirects)
* * `'end'` on the `res` object
* * `'close'`
*
* In the case of a connection error, the following events will be emitted:
*
* * `'socket'`
* * `'error'`
* * `'close'`
*
* In the case of a premature connection close before the response is received,
* the following events will be emitted in the following order:
*
* * `'socket'`
* * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'`
* * `'close'`
*
* In the case of a premature connection close after the response is received,
* the following events will be emitted in the following order:
*
* * `'socket'`
* * `'response'`
* * `'data'` any number of times, on the `res` object
* * (connection closed here)
* * `'aborted'` on the `res` object
* * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`.
* * `'close'`
* * `'close'` on the `res` object
*
* If `req.destroy()` is called before a socket is assigned, the following
* events will be emitted in the following order:
*
* * (`req.destroy()` called here)
* * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'`
* * `'close'`
*
* If `req.destroy()` is called before the connection succeeds, the following
* events will be emitted in the following order:
*
* * `'socket'`
* * (`req.destroy()` called here)
* * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'`
* * `'close'`
*
* If `req.destroy()` is called after the response is received, the following
* events will be emitted in the following order:
*
* * `'socket'`
* * `'response'`
* * `'data'` any number of times, on the `res` object
* * (`req.destroy()` called here)
* * `'aborted'` on the `res` object
* * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`.
* * `'close'`
* * `'close'` on the `res` object
*
* If `req.abort()` is called before a socket is assigned, the following
* events will be emitted in the following order:
*
* * (`req.abort()` called here)
* * `'abort'`
* * `'close'`
*
* If `req.abort()` is called before the connection succeeds, the following
* events will be emitted in the following order:
*
* * `'socket'`
* * (`req.abort()` called here)
* * `'abort'`
* * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'`
* * `'close'`
*
* If `req.abort()` is called after the response is received, the following
* events will be emitted in the following order:
*
* * `'socket'`
* * `'response'`
* * `'data'` any number of times, on the `res` object
* * (`req.abort()` called here)
* * `'abort'`
* * `'aborted'` on the `res` object
* * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`.
* * `'close'`
* * `'close'` on the `res` object
*
* Setting the `timeout` option or using the `setTimeout()` function will
* not abort the request or do anything besides add a `'timeout'` event.
*
* Passing an `AbortSignal` and then calling `abort` on the corresponding`AbortController` will behave the same way as calling `.destroy()` on the
* request itself.
* @since v0.3.6
*/
function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest;
function request(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest;
/**
* Since most requests are GET requests without bodies, Node.js provides this
* convenience method. The only difference between this method and {@link request} is that it sets the method to GET and calls `req.end()`automatically. The callback must take care to consume the
* response
* data for reasons stated in {@link ClientRequest} section.
*
* The `callback` is invoked with a single argument that is an instance of {@link IncomingMessage}.
*
* JSON fetching example:
*
* ```js
* http.get('http://localhost:8000/', (res) => {
* const { statusCode } = res;
* const contentType = res.headers['content-type'];
*
* let error;
* // Any 2xx status code signals a successful response but
* // here we're only checking for 200.
* if (statusCode !== 200) {
* error = new Error('Request Failed.\n' +
* `Status Code: ${statusCode}`);
* } else if (!/^application\/json/.test(contentType)) {
* error = new Error('Invalid content-type.\n' +
* `Expected application/json but received ${contentType}`);
* }
* if (error) {
* console.error(error.message);
* // Consume response data to free up memory
* res.resume();
* return;
* }
*
* res.setEncoding('utf8');
* let rawData = '';
* res.on('data', (chunk) => { rawData += chunk; });
* res.on('end', () => {
* try {
* const parsedData = JSON.parse(rawData);
* console.log(parsedData);
* } catch (e) {
* console.error(e.message);
* }
* });
* }).on('error', (e) => {
* console.error(`Got error: ${e.message}`);
* });
*
* // Create a local server to receive data from
* const server = http.createServer((req, res) => {
* res.writeHead(200, { 'Content-Type': 'application/json' });
* res.end(JSON.stringify({
* data: 'Hello World!'
* }));
* });
*
* server.listen(8000);
* ```
* @since v0.3.6
* @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. Properties that are inherited from the prototype are ignored.
*/
function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest;
function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest;
let globalAgent: Agent;
/**
* Read-only property specifying the maximum allowed size of HTTP headers in bytes.
* Defaults to 16KB. Configurable using the `--max-http-header-size` CLI option.
*/
const maxHeaderSize: number;
}
declare module 'node:http' {
export * from 'http';
} | the_stack |
import * as assert from 'assert';
import { ITextFileService, snapshotToString, TextFileOperationError, TextFileOperationResult, stringToSnapshot } from 'vs/workbench/services/textfile/common/textfiles';
import { URI } from 'vs/base/common/uri';
import { join, basename } from 'vs/base/common/path';
import { UTF16le, UTF8_with_bom, UTF16be, UTF8, UTF16le_BOM, UTF16be_BOM, UTF8_BOM } from 'vs/workbench/services/textfile/common/encoding';
import { bufferToStream, VSBuffer } from 'vs/base/common/buffer';
import { createTextModel } from 'vs/editor/test/common/testTextModel';
import { ITextSnapshot, DefaultEndOfLine } from 'vs/editor/common/model';
import { isWindows } from 'vs/base/common/platform';
import { createTextBufferFactoryFromStream } from 'vs/editor/common/model/textModel';
export interface Params {
setup(): Promise<{
service: ITextFileService;
testDir: string;
}>;
teardown(): Promise<void>;
exists(fsPath: string): Promise<boolean>;
stat(fsPath: string): Promise<{ size: number }>;
readFile(fsPath: string): Promise<VSBuffer | Buffer>;
readFile(fsPath: string, encoding: string): Promise<string>;
readFile(fsPath: string, encoding?: string): Promise<VSBuffer | Buffer | string>;
detectEncodingByBOM(fsPath: string): Promise<typeof UTF16be | typeof UTF16le | typeof UTF8_with_bom | null>;
}
/**
* Allows us to reuse test suite across different environments.
*
* It introduces a bit of complexity with setup and teardown, however
* it helps us to ensure that tests are added for all environments at once,
* hence helps us catch bugs better.
*/
export default function createSuite(params: Params) {
let service: ITextFileService;
let testDir = '';
const { exists, stat, readFile, detectEncodingByBOM } = params;
setup(async () => {
const result = await params.setup();
service = result.service;
testDir = result.testDir;
});
teardown(async () => {
await params.teardown();
});
test('create - no encoding - content empty', async () => {
const resource = URI.file(join(testDir, 'small_new.txt'));
await service.create([{ resource }]);
const res = await readFile(resource.fsPath);
assert.strictEqual(res.byteLength, 0 /* no BOM */);
});
test('create - no encoding - content provided (string)', async () => {
const resource = URI.file(join(testDir, 'small_new.txt'));
await service.create([{ resource, value: 'Hello World' }]);
const res = await readFile(resource.fsPath);
assert.strictEqual(res.toString(), 'Hello World');
assert.strictEqual(res.byteLength, 'Hello World'.length);
});
test('create - no encoding - content provided (snapshot)', async () => {
const resource = URI.file(join(testDir, 'small_new.txt'));
await service.create([{ resource, value: stringToSnapshot('Hello World') }]);
const res = await readFile(resource.fsPath);
assert.strictEqual(res.toString(), 'Hello World');
assert.strictEqual(res.byteLength, 'Hello World'.length);
});
test('create - UTF 16 LE - no content', async () => {
const resource = URI.file(join(testDir, 'small_new.utf16le'));
await service.create([{ resource }]);
assert.strictEqual(await exists(resource.fsPath), true);
const detectedEncoding = await detectEncodingByBOM(resource.fsPath);
assert.strictEqual(detectedEncoding, UTF16le);
const res = await readFile(resource.fsPath);
assert.strictEqual(res.byteLength, UTF16le_BOM.length);
});
test('create - UTF 16 LE - content provided', async () => {
const resource = URI.file(join(testDir, 'small_new.utf16le'));
await service.create([{ resource, value: 'Hello World' }]);
assert.strictEqual(await exists(resource.fsPath), true);
const detectedEncoding = await detectEncodingByBOM(resource.fsPath);
assert.strictEqual(detectedEncoding, UTF16le);
const res = await readFile(resource.fsPath);
assert.strictEqual(res.byteLength, 'Hello World'.length * 2 /* UTF16 2bytes per char */ + UTF16le_BOM.length);
});
test('create - UTF 16 BE - no content', async () => {
const resource = URI.file(join(testDir, 'small_new.utf16be'));
await service.create([{ resource }]);
assert.strictEqual(await exists(resource.fsPath), true);
const detectedEncoding = await detectEncodingByBOM(resource.fsPath);
assert.strictEqual(detectedEncoding, UTF16be);
const res = await readFile(resource.fsPath);
assert.strictEqual(res.byteLength, UTF16le_BOM.length);
});
test('create - UTF 16 BE - content provided', async () => {
const resource = URI.file(join(testDir, 'small_new.utf16be'));
await service.create([{ resource, value: 'Hello World' }]);
assert.strictEqual(await exists(resource.fsPath), true);
const detectedEncoding = await detectEncodingByBOM(resource.fsPath);
assert.strictEqual(detectedEncoding, UTF16be);
const res = await readFile(resource.fsPath);
assert.strictEqual(res.byteLength, 'Hello World'.length * 2 /* UTF16 2bytes per char */ + UTF16be_BOM.length);
});
test('create - UTF 8 BOM - no content', async () => {
const resource = URI.file(join(testDir, 'small_new.utf8bom'));
await service.create([{ resource }]);
assert.strictEqual(await exists(resource.fsPath), true);
const detectedEncoding = await detectEncodingByBOM(resource.fsPath);
assert.strictEqual(detectedEncoding, UTF8_with_bom);
const res = await readFile(resource.fsPath);
assert.strictEqual(res.byteLength, UTF8_BOM.length);
});
test('create - UTF 8 BOM - content provided', async () => {
const resource = URI.file(join(testDir, 'small_new.utf8bom'));
await service.create([{ resource, value: 'Hello World' }]);
assert.strictEqual(await exists(resource.fsPath), true);
const detectedEncoding = await detectEncodingByBOM(resource.fsPath);
assert.strictEqual(detectedEncoding, UTF8_with_bom);
const res = await readFile(resource.fsPath);
assert.strictEqual(res.byteLength, 'Hello World'.length + UTF8_BOM.length);
});
function createTextModelSnapshot(text: string, preserveBOM?: boolean): ITextSnapshot {
const textModel = createTextModel(text);
const snapshot = textModel.createSnapshot(preserveBOM);
textModel.dispose();
return snapshot;
}
test('create - UTF 8 BOM - empty content - snapshot', async () => {
const resource = URI.file(join(testDir, 'small_new.utf8bom'));
await service.create([{ resource, value: createTextModelSnapshot('') }]);
assert.strictEqual(await exists(resource.fsPath), true);
const detectedEncoding = await detectEncodingByBOM(resource.fsPath);
assert.strictEqual(detectedEncoding, UTF8_with_bom);
const res = await readFile(resource.fsPath);
assert.strictEqual(res.byteLength, UTF8_BOM.length);
});
test('create - UTF 8 BOM - content provided - snapshot', async () => {
const resource = URI.file(join(testDir, 'small_new.utf8bom'));
await service.create([{ resource, value: createTextModelSnapshot('Hello World') }]);
assert.strictEqual(await exists(resource.fsPath), true);
const detectedEncoding = await detectEncodingByBOM(resource.fsPath);
assert.strictEqual(detectedEncoding, UTF8_with_bom);
const res = await readFile(resource.fsPath);
assert.strictEqual(res.byteLength, 'Hello World'.length + UTF8_BOM.length);
});
test('write - use encoding (UTF 16 BE) - small content as string', async () => {
await testEncoding(URI.file(join(testDir, 'small.txt')), UTF16be, 'Hello\nWorld', 'Hello\nWorld');
});
test('write - use encoding (UTF 16 BE) - small content as snapshot', async () => {
await testEncoding(URI.file(join(testDir, 'small.txt')), UTF16be, createTextModelSnapshot('Hello\nWorld'), 'Hello\nWorld');
});
test('write - use encoding (UTF 16 BE) - large content as string', async () => {
await testEncoding(URI.file(join(testDir, 'lorem.txt')), UTF16be, 'Hello\nWorld', 'Hello\nWorld');
});
test('write - use encoding (UTF 16 BE) - large content as snapshot', async () => {
await testEncoding(URI.file(join(testDir, 'lorem.txt')), UTF16be, createTextModelSnapshot('Hello\nWorld'), 'Hello\nWorld');
});
async function testEncoding(resource: URI, encoding: string, content: string | ITextSnapshot, expectedContent: string) {
await service.write(resource, content, { encoding });
const detectedEncoding = await detectEncodingByBOM(resource.fsPath);
assert.strictEqual(detectedEncoding, encoding);
const resolved = await service.readStream(resource);
assert.strictEqual(resolved.encoding, encoding);
assert.strictEqual(snapshotToString(resolved.value.create(isWindows ? DefaultEndOfLine.CRLF : DefaultEndOfLine.LF).textBuffer.createSnapshot(false)), expectedContent);
}
test('write - use encoding (cp1252)', async () => {
const filePath = join(testDir, 'some_cp1252.txt');
const contents = await readFile(filePath, 'utf8');
const eol = /\r\n/.test(contents) ? '\r\n' : '\n';
await testEncodingKeepsData(URI.file(filePath), 'cp1252', ['ObjectCount = LoadObjects("Öffentlicher Ordner");', '', 'Private = "Persönliche Information"', ''].join(eol));
});
test('write - use encoding (shiftjis)', async () => {
await testEncodingKeepsData(URI.file(join(testDir, 'some_shiftjis.txt')), 'shiftjis', '中文abc');
});
test('write - use encoding (gbk)', async () => {
await testEncodingKeepsData(URI.file(join(testDir, 'some_gbk.txt')), 'gbk', '中国abc');
});
test('write - use encoding (cyrillic)', async () => {
await testEncodingKeepsData(URI.file(join(testDir, 'some_cyrillic.txt')), 'cp866', 'АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя');
});
test('write - use encoding (big5)', async () => {
await testEncodingKeepsData(URI.file(join(testDir, 'some_big5.txt')), 'cp950', '中文abc');
});
async function testEncodingKeepsData(resource: URI, encoding: string, expected: string) {
let resolved = await service.readStream(resource, { encoding });
const content = snapshotToString(resolved.value.create(isWindows ? DefaultEndOfLine.CRLF : DefaultEndOfLine.LF).textBuffer.createSnapshot(false));
assert.strictEqual(content, expected);
await service.write(resource, content, { encoding });
resolved = await service.readStream(resource, { encoding });
assert.strictEqual(snapshotToString(resolved.value.create(DefaultEndOfLine.CRLF).textBuffer.createSnapshot(false)), content);
await service.write(resource, createTextModelSnapshot(content), { encoding });
resolved = await service.readStream(resource, { encoding });
assert.strictEqual(snapshotToString(resolved.value.create(DefaultEndOfLine.CRLF).textBuffer.createSnapshot(false)), content);
}
test('write - no encoding - content as string', async () => {
const resource = URI.file(join(testDir, 'small.txt'));
const content = (await readFile(resource.fsPath)).toString();
await service.write(resource, content);
const resolved = await service.readStream(resource);
assert.strictEqual(resolved.value.getFirstLineText(999999), content);
});
test('write - no encoding - content as snapshot', async () => {
const resource = URI.file(join(testDir, 'small.txt'));
const content = (await readFile(resource.fsPath)).toString();
await service.write(resource, createTextModelSnapshot(content));
const resolved = await service.readStream(resource);
assert.strictEqual(resolved.value.getFirstLineText(999999), content);
});
test('write - encoding preserved (UTF 16 LE) - content as string', async () => {
const resource = URI.file(join(testDir, 'some_utf16le.css'));
const resolved = await service.readStream(resource);
assert.strictEqual(resolved.encoding, UTF16le);
await testEncoding(URI.file(join(testDir, 'some_utf16le.css')), UTF16le, 'Hello\nWorld', 'Hello\nWorld');
});
test('write - encoding preserved (UTF 16 LE) - content as snapshot', async () => {
const resource = URI.file(join(testDir, 'some_utf16le.css'));
const resolved = await service.readStream(resource);
assert.strictEqual(resolved.encoding, UTF16le);
await testEncoding(URI.file(join(testDir, 'some_utf16le.css')), UTF16le, createTextModelSnapshot('Hello\nWorld'), 'Hello\nWorld');
});
test('write - UTF8 variations - content as string', async () => {
const resource = URI.file(join(testDir, 'index.html'));
let detectedEncoding = await detectEncodingByBOM(resource.fsPath);
assert.strictEqual(detectedEncoding, null);
const content = (await readFile(resource.fsPath)).toString() + 'updates';
await service.write(resource, content, { encoding: UTF8_with_bom });
detectedEncoding = await detectEncodingByBOM(resource.fsPath);
assert.strictEqual(detectedEncoding, UTF8_with_bom);
// ensure BOM preserved if enforced
await service.write(resource, content, { encoding: UTF8_with_bom });
detectedEncoding = await detectEncodingByBOM(resource.fsPath);
assert.strictEqual(detectedEncoding, UTF8_with_bom);
// allow to remove BOM
await service.write(resource, content, { encoding: UTF8 });
detectedEncoding = await detectEncodingByBOM(resource.fsPath);
assert.strictEqual(detectedEncoding, null);
// BOM does not come back
await service.write(resource, content, { encoding: UTF8 });
detectedEncoding = await detectEncodingByBOM(resource.fsPath);
assert.strictEqual(detectedEncoding, null);
});
test('write - UTF8 variations - content as snapshot', async () => {
const resource = URI.file(join(testDir, 'index.html'));
let detectedEncoding = await detectEncodingByBOM(resource.fsPath);
assert.strictEqual(detectedEncoding, null);
const model = createTextModel((await readFile(resource.fsPath)).toString() + 'updates');
await service.write(resource, model.createSnapshot(), { encoding: UTF8_with_bom });
detectedEncoding = await detectEncodingByBOM(resource.fsPath);
assert.strictEqual(detectedEncoding, UTF8_with_bom);
// ensure BOM preserved if enforced
await service.write(resource, model.createSnapshot(), { encoding: UTF8_with_bom });
detectedEncoding = await detectEncodingByBOM(resource.fsPath);
assert.strictEqual(detectedEncoding, UTF8_with_bom);
// allow to remove BOM
await service.write(resource, model.createSnapshot(), { encoding: UTF8 });
detectedEncoding = await detectEncodingByBOM(resource.fsPath);
assert.strictEqual(detectedEncoding, null);
// BOM does not come back
await service.write(resource, model.createSnapshot(), { encoding: UTF8 });
detectedEncoding = await detectEncodingByBOM(resource.fsPath);
assert.strictEqual(detectedEncoding, null);
model.dispose();
});
test('write - preserve UTF8 BOM - content as string', async () => {
const resource = URI.file(join(testDir, 'some_utf8_bom.txt'));
let detectedEncoding = await detectEncodingByBOM(resource.fsPath);
assert.strictEqual(detectedEncoding, UTF8_with_bom);
await service.write(resource, 'Hello World', { encoding: detectedEncoding! });
detectedEncoding = await detectEncodingByBOM(resource.fsPath);
assert.strictEqual(detectedEncoding, UTF8_with_bom);
});
test('write - ensure BOM in empty file - content as string', async () => {
const resource = URI.file(join(testDir, 'small.txt'));
await service.write(resource, '', { encoding: UTF8_with_bom });
const detectedEncoding = await detectEncodingByBOM(resource.fsPath);
assert.strictEqual(detectedEncoding, UTF8_with_bom);
});
test('write - ensure BOM in empty file - content as snapshot', async () => {
const resource = URI.file(join(testDir, 'small.txt'));
await service.write(resource, createTextModelSnapshot(''), { encoding: UTF8_with_bom });
const detectedEncoding = await detectEncodingByBOM(resource.fsPath);
assert.strictEqual(detectedEncoding, UTF8_with_bom);
});
test('readStream - small text', async () => {
const resource = URI.file(join(testDir, 'small.txt'));
await testReadStream(resource);
});
test('readStream - large text', async () => {
const resource = URI.file(join(testDir, 'lorem.txt'));
await testReadStream(resource);
});
async function testReadStream(resource: URI): Promise<void> {
const result = await service.readStream(resource);
assert.strictEqual(result.name, basename(resource.fsPath));
assert.strictEqual(result.size, (await stat(resource.fsPath)).size);
const content = (await readFile(resource.fsPath)).toString();
assert.strictEqual(
snapshotToString(result.value.create(DefaultEndOfLine.LF).textBuffer.createSnapshot(false)),
snapshotToString(createTextModelSnapshot(content, false)));
}
test('read - small text', async () => {
const resource = URI.file(join(testDir, 'small.txt'));
await testRead(resource);
});
test('read - large text', async () => {
const resource = URI.file(join(testDir, 'lorem.txt'));
await testRead(resource);
});
async function testRead(resource: URI): Promise<void> {
const result = await service.read(resource);
assert.strictEqual(result.name, basename(resource.fsPath));
assert.strictEqual(result.size, (await stat(resource.fsPath)).size);
assert.strictEqual(result.value, (await readFile(resource.fsPath)).toString());
}
test('readStream - encoding picked up (CP1252)', async () => {
const resource = URI.file(join(testDir, 'some_small_cp1252.txt'));
const encoding = 'windows1252';
const result = await service.readStream(resource, { encoding });
assert.strictEqual(result.encoding, encoding);
assert.strictEqual(result.value.getFirstLineText(999999), 'Private = "Persönlicheß Information"');
});
test('read - encoding picked up (CP1252)', async () => {
const resource = URI.file(join(testDir, 'some_small_cp1252.txt'));
const encoding = 'windows1252';
const result = await service.read(resource, { encoding });
assert.strictEqual(result.encoding, encoding);
assert.strictEqual(result.value, 'Private = "Persönlicheß Information"');
});
test('read - encoding picked up (binary)', async () => {
const resource = URI.file(join(testDir, 'some_small_cp1252.txt'));
const encoding = 'binary';
const result = await service.read(resource, { encoding });
assert.strictEqual(result.encoding, encoding);
assert.strictEqual(result.value, 'Private = "Persönlicheß Information"');
});
test('read - encoding picked up (base64)', async () => {
const resource = URI.file(join(testDir, 'some_small_cp1252.txt'));
const encoding = 'base64';
const result = await service.read(resource, { encoding });
assert.strictEqual(result.encoding, encoding);
assert.strictEqual(result.value, btoa('Private = "Persönlicheß Information"'));
});
test('readStream - user overrides BOM', async () => {
const resource = URI.file(join(testDir, 'some_utf16le.css'));
const result = await service.readStream(resource, { encoding: 'windows1252' });
assert.strictEqual(result.encoding, 'windows1252');
});
test('readStream - BOM removed', async () => {
const resource = URI.file(join(testDir, 'some_utf8_bom.txt'));
const result = await service.readStream(resource);
assert.strictEqual(result.value.getFirstLineText(999999), 'This is some UTF 8 with BOM file.');
});
test('readStream - invalid encoding', async () => {
const resource = URI.file(join(testDir, 'index.html'));
const result = await service.readStream(resource, { encoding: 'superduper' });
assert.strictEqual(result.encoding, 'utf8');
});
test('readStream - encoding override', async () => {
const resource = URI.file(join(testDir, 'some.utf16le'));
const result = await service.readStream(resource, { encoding: 'windows1252' });
assert.strictEqual(result.encoding, 'utf16le');
assert.strictEqual(result.value.getFirstLineText(999999), 'This is some UTF 16 with BOM file.');
});
test('readStream - large Big5', async () => {
await testLargeEncoding('big5', '中文abc');
});
test('readStream - large CP1252', async () => {
await testLargeEncoding('cp1252', 'öäüß');
});
test('readStream - large Cyrillic', async () => {
await testLargeEncoding('cp866', 'АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя');
});
test('readStream - large GBK', async () => {
await testLargeEncoding('gbk', '中国abc');
});
test('readStream - large ShiftJIS', async () => {
await testLargeEncoding('shiftjis', '中文abc');
});
test('readStream - large UTF8 BOM', async () => {
await testLargeEncoding('utf8bom', 'öäüß');
});
test('readStream - large UTF16 LE', async () => {
await testLargeEncoding('utf16le', 'öäüß');
});
test('readStream - large UTF16 BE', async () => {
await testLargeEncoding('utf16be', 'öäüß');
});
async function testLargeEncoding(encoding: string, needle: string): Promise<void> {
const resource = URI.file(join(testDir, `lorem_${encoding}.txt`));
// Verify via `ITextFileService.readStream`
const result = await service.readStream(resource, { encoding });
assert.strictEqual(result.encoding, encoding);
let contents = snapshotToString(result.value.create(DefaultEndOfLine.LF).textBuffer.createSnapshot(false));
assert.strictEqual(contents.indexOf(needle), 0);
assert.ok(contents.indexOf(needle, 10) > 0);
// Verify via `ITextFileService.getDecodedTextFactory`
const rawFile = await params.readFile(resource.fsPath);
let rawFileVSBuffer: VSBuffer;
if (rawFile instanceof VSBuffer) {
rawFileVSBuffer = rawFile;
} else {
rawFileVSBuffer = VSBuffer.wrap(rawFile);
}
const factory = await createTextBufferFactoryFromStream(await service.getDecodedStream(resource, bufferToStream(rawFileVSBuffer), { encoding }));
contents = snapshotToString(factory.create(DefaultEndOfLine.LF).textBuffer.createSnapshot(false));
assert.strictEqual(contents.indexOf(needle), 0);
assert.ok(contents.indexOf(needle, 10) > 0);
}
test('readStream - UTF16 LE (no BOM)', async () => {
const resource = URI.file(join(testDir, 'utf16_le_nobom.txt'));
const result = await service.readStream(resource);
assert.strictEqual(result.encoding, 'utf16le');
});
test('readStream - UTF16 BE (no BOM)', async () => {
const resource = URI.file(join(testDir, 'utf16_be_nobom.txt'));
const result = await service.readStream(resource);
assert.strictEqual(result.encoding, 'utf16be');
});
test('readStream - autoguessEncoding', async () => {
const resource = URI.file(join(testDir, 'some_cp1252.txt'));
const result = await service.readStream(resource, { autoGuessEncoding: true });
assert.strictEqual(result.encoding, 'windows1252');
});
test('readStream - FILE_IS_BINARY', async () => {
const resource = URI.file(join(testDir, 'binary.txt'));
let error: TextFileOperationError | undefined = undefined;
try {
await service.readStream(resource, { acceptTextOnly: true });
} catch (err) {
error = err;
}
assert.ok(error);
assert.strictEqual(error!.textFileOperationResult, TextFileOperationResult.FILE_IS_BINARY);
const result = await service.readStream(URI.file(join(testDir, 'small.txt')), { acceptTextOnly: true });
assert.strictEqual(result.name, 'small.txt');
});
test('read - FILE_IS_BINARY', async () => {
const resource = URI.file(join(testDir, 'binary.txt'));
let error: TextFileOperationError | undefined = undefined;
try {
await service.read(resource, { acceptTextOnly: true });
} catch (err) {
error = err;
}
assert.ok(error);
assert.strictEqual(error!.textFileOperationResult, TextFileOperationResult.FILE_IS_BINARY);
const result = await service.read(URI.file(join(testDir, 'small.txt')), { acceptTextOnly: true });
assert.strictEqual(result.name, 'small.txt');
});
} | the_stack |
'use strict';
import { Agent } from 'https';
import { endpoint } from 'azure-iot-common';
import * as ConnectionString from './connection_string';
import * as SharedAccessSignature from './shared_access_signature';
import { RestApiClient } from 'azure-iot-http-base';
import { DeviceMethod } from './device_method';
import { Query } from './query';
import { DeviceMethodParams } from './interfaces';
import { TripleValueCallback, tripleValueCallbackToPromise } from 'azure-iot-common';
import { TokenCredential } from '@azure/core-http';
// tslint:disable-next-line:no-var-requires
const packageJson = require('../package.json');
const defaultMaxExecutionTimeInSeconds = 3600;
export type JobType = 'scheduleUpdateTwin' | 'scheduleDeviceMethod';
export type JobStatus = 'queued' | 'scheduled' | 'running' | 'cancelled' | 'finished';
/**
* @private
*/
export interface JobDescription {
jobId: string | number;
type: JobType;
queryCondition?: string;
updateTwin?: any;
cloudToDeviceMethod?: DeviceMethodParams;
startTime: string;
maxExecutionTimeInSeconds: number;
}
/**
* Provides methods to create, update, monitor and cancel long-running jobs on an IoT Hub instance, as well as query existing jobs.
* The Jobs API in Azure IoT Hub allows to schedule direct method calls and twin updates on multiple devices.
*
* SDK users are expected to create {@link azure-iothub.JobClient} instances using the factory methods {@link azure-iothub.JobClient.fromConnectionString} and {@link azure-iothub.JobClient.fromSharedAccessSignature}.
*/
export class JobClient {
private _restApiClient: RestApiClient;
/**
* @private
* @constructor
* @param {RestApiClient} restApiClient The HTTP registry client used to execute REST API calls.@constructor
* @throws {ReferenceError} If the restApiClient argument is falsy.
*/
constructor(restApiClient: RestApiClient) {
/*Codes_SRS_NODE_JOB_CLIENT_16_001: [The `JobClient` constructor shall throw a `ReferenceError` if `restApiClient` is falsy.]*/
if (!restApiClient) throw new ReferenceError('restApiClient cannot be \'' + restApiClient + '\'');
this._restApiClient = restApiClient;
if (this._restApiClient.setOptions) {
this._restApiClient.setOptions({ http: { agent: new Agent({ keepAlive: true }) } });
}
}
/**
* @method module:azure-iothub.JobClient#getJob
* @description Requests information about an existing job.
*
* @param {String} jobId The identifier of an existing job.
* @param {Function} [done] The optional function to call when the operation is
* complete. `done` will be called with three
* arguments: an Error object (can be null), a
* job object, and a transport-specific response
* object useful for logging or debugging.
* @returns {Promise<JobStatusResponse>> | void} Promise if no callback function was passed, void otherwise.
*/
getJob(jobId: string | number, done: TripleValueCallback<any, any>): void;
getJob(jobId: string | number): Promise<JobStatusResponse>;
getJob(jobId: string | number, done?: TripleValueCallback<any, any>): Promise<JobStatusResponse> | void {
/*Codes_SRS_NODE_JOB_CLIENT_16_006: [The `getJob` method shall throw a `ReferenceError` if `jobId` is `null`, `undefined` or an empty string.]*/
return tripleValueCallbackToPromise((_callback) => {
if (jobId === undefined || jobId === null || jobId === '') throw new ReferenceError('jobId cannot be \'' + jobId + '\'');
/*Codes_SRS_NODE_JOB_CLIENT_16_007: [The `getJob` method shall construct the HTTP request as follows:
```
GET /jobs/v2/<jobId>?api-version=<version>
Authorization: <config.sharedAccessSignature>
Content-Type: application/json; charset=utf-8
Request-Id: <guid>
User-Agent: <sdk-name>/<sdk-version>
```]*/
const path = '/jobs/v2/' + jobId + endpoint.versionQueryString();
this._restApiClient.executeApiCall('GET', path, null, null, _callback);
}, createJobStatusResponse, done);
}
/**
* @method module:azure-iothub.JobClient#createQuery
* @description Creates a query that can be used to return pages of existing job based on type and status.
*
* @param {String} jobType The type that should be used to filter results.
* @param {String} jobStatus The status that should be used to filter results.
* @param {Number} pageSize The number of elements to return per page.
*/
createQuery(jobType?: JobType, jobStatus?: JobStatus, pageSize?: number): Query {
return new Query(this._getJobsFunc(jobType, jobStatus, pageSize));
}
/**
* @method module:azure-iothub.JobClient#cancelJob
* @description Cancels an existing job.
*
* @param {String} jobId The identifier of an existing job.
* @param {Function} [done] The optional function to call when the operation is
* complete. `done` will be called with three
* arguments: an Error object (can be null), a
* job object, and a transport-specific response
* object useful for logging or debugging.
* @returns {Promise<JobStatusResponse>> | void} Promise if no callback function was passed, void otherwise.
*/
cancelJob(jobId: string | number, done: TripleValueCallback<any, any>): void;
cancelJob(jobId: string | number): Promise<JobStatusResponse>;
cancelJob(jobId: string | number, done?: TripleValueCallback<any, any>): Promise<JobStatusResponse> | void {
/*Codes_SRS_NODE_JOB_CLIENT_16_008: [The `cancelJob` method shall throw a `ReferenceError` if `jobId` is `null`, `undefined` or an empty string.]*/
return tripleValueCallbackToPromise((_callback) => {
if (jobId === undefined || jobId === null || jobId === '') throw new ReferenceError('jobId cannot be \'' + jobId + '\'');
/*Codes_SRS_NODE_JOB_CLIENT_16_009: [The `cancelJob` method shall construct the HTTP request as follows:
```
POST /jobs/v2/<jobId>/cancel?api-version=<version>
Authorization: <config.sharedAccessSignature>
Content-Type: application/json; charset=utf-8
Request-Id: <guid>
User-Agent: <sdk-name>/<sdk-version>
```]*/
const path = '/jobs/v2/' + jobId + '/cancel' + endpoint.versionQueryString();
this._restApiClient.executeApiCall('POST', path, null, null, _callback);
}, createJobStatusResponse, done);
}
/**
* @method module:azure-iothub.JobClient#scheduleDeviceMethod
* @description Schedules a job that will execute a device method on a set of devices.
*
* @param {String} jobId The unique identifier that should be used for this job.
* @param {String} queryCondition A SQL query WHERE clause used to compute the list of devices
* on which this job should be run.
* @param {Object} methodParams An object describing the method and shall have the following properties:
* - methodName The name of the method that shall be invoked.
* - payload [optional] The payload to use for the method call.
* - responseTimeoutInSeconds [optional] The number of seconds IoT Hub shall wait for the device
* @param {Date} [jobStartTime] Time time at which the job should start
* @param {Number} [maxExecutionTimeInSeconds] The maximum time alloted for this job to run in seconds.
* @param {Function} [done] The optional function to call when the operation is
* complete. `done` will be called with three
* arguments: an Error object (can be null), a
* job object, and a transport-specific response
* object useful for logging or debugging.
* @returns {Promise<JobStatusResponse>> | void} Promise if no callback function was passed, void otherwise.
*
* @throws {ReferenceError} If one or more of the jobId, queryCondition or methodParams arguments are falsy.
* @throws {ReferenceError} If methodParams.methodName is falsy.
* @throws {TypeError} If the callback is not the last parameter
*/
scheduleDeviceMethod(jobId: string | number, queryCondition: string, methodParams: DeviceMethodParams, jobStartTime: Date, maxExecutionTimeInSeconds: number, done: TripleValueCallback<any, any>): void;
scheduleDeviceMethod(jobId: string | number, queryCondition: string, methodParams: DeviceMethodParams, jobStartTime: Date, done: TripleValueCallback<any, any>): void;
scheduleDeviceMethod(jobId: string | number, queryCondition: string, methodParams: DeviceMethodParams, done: TripleValueCallback<any, any>): void;
scheduleDeviceMethod(jobId: string | number, queryCondition: string, methodParams: DeviceMethodParams, jobStartTime: Date, maxExecutionTimeInSeconds: number): Promise<JobStatusResponse>;
scheduleDeviceMethod(jobId: string | number, queryCondition: string, methodParams: DeviceMethodParams, jobStartTime: Date): Promise<JobStatusResponse>;
scheduleDeviceMethod(jobId: string | number, queryCondition: string, methodParams: DeviceMethodParams): Promise<JobStatusResponse>;
scheduleDeviceMethod(jobId: string | number, queryCondition: string, methodParams: DeviceMethodParams, jobStartTime?: Date | TripleValueCallback<any, any>, maxExecutionTimeInSeconds?: number | TripleValueCallback<any, any>, done?: TripleValueCallback<any, any>): Promise<JobStatusResponse> | void {
const callback = (typeof jobStartTime === 'function') ? jobStartTime as TripleValueCallback<any, any> : ((typeof maxExecutionTimeInSeconds === 'function') ? maxExecutionTimeInSeconds as TripleValueCallback<any, any> : done);
return tripleValueCallbackToPromise((_callback) => {
/*Codes_SRS_NODE_JOB_CLIENT_16_013: [The `scheduleDeviceMethod` method shall throw a `ReferenceError` if `jobId` is `null`, `undefined` or an empty string.]*/
if (jobId === undefined || jobId === null || jobId === '') throw new ReferenceError('jobId cannot be \'' + jobId + '\'');
/*Codes_SRS_NODE_JOB_CLIENT_16_014: [The `scheduleDeviceMethod` method shall throw a `ReferenceError` if `queryCondition` is falsy.]*/
if (!queryCondition) throw new ReferenceError('queryCondition cannot be \'' + queryCondition + '\'');
/*Codes_SRS_NODE_JOB_CLIENT_16_029: [The `scheduleDeviceMethod` method shall throw a `ReferenceError` if `methodParams` is falsy.*/
if (!methodParams) throw new ReferenceError('methodParams cannot be \'' + methodParams + '\'');
/*Codes_SRS_NODE_JOB_CLIENT_16_015: [The `scheduleDeviceMethod` method shall throw a `ReferenceError` if `methodParams.methodName` is `null`, `undefined` or an empty string.]*/
if (methodParams.methodName === undefined || methodParams.methodName === null || methodParams.methodName === '') throw new ReferenceError('methodParams.methodName cannot be \'' + methodParams.methodName + '\'');
/*Codes_SRS_NODE_JOB_CLIENT_16_018: [If `jobStartTime` is a function, `jobStartTime` shall be considered the callback and a `TypeError` shall be thrown if `maxExecutionTimeInSeconds` and/or `_callback` are not `undefined`.]*/
if (typeof jobStartTime === 'function') {
if (maxExecutionTimeInSeconds || done) {
throw new TypeError('The callback must be the last parameter');
} else {
_callback = jobStartTime;
jobStartTime = new Date();
maxExecutionTimeInSeconds = defaultMaxExecutionTimeInSeconds;
}
/*Codes_SRS_NODE_JOB_CLIENT_16_019: [If `maxExecutionTimeInSeconds` is a function, `maxExecutionTimeInSeconds` shall be considered the callback and a `TypeError` shall be thrown if `_callback` is not `undefined`.]*/
} else if (typeof maxExecutionTimeInSeconds === 'function') {
if (done) {
throw new TypeError('The callback must be the last parameter');
} else {
_callback = maxExecutionTimeInSeconds;
maxExecutionTimeInSeconds = defaultMaxExecutionTimeInSeconds;
}
}
/*Codes_SRS_NODE_JOB_CLIENT_16_030: [The `scheduleDeviceMethod` method shall use the `DeviceMethod.defaultPayload` value if `methodParams.payload` is `undefined`.]*/
/*Codes_SRS_NODE_JOB_CLIENT_16_031: [The `scheduleDeviceMethod` method shall use the `DeviceMethod.defaultTimeout` value if `methodParams.responseTimeoutInSeconds` is falsy.]*/
const fullMethodParams: DeviceMethodParams = {
methodName: methodParams.methodName,
payload: methodParams.payload || DeviceMethod.defaultPayload,
responseTimeoutInSeconds: methodParams.responseTimeoutInSeconds || DeviceMethod.defaultResponseTimeout
};
/*Codes_SRS_NODE_JOB_CLIENT_16_020: [The `scheduleDeviceMethod` method shall construct the HTTP request as follows:
```
PUT /jobs/v2/<jobId>?api-version=<version>
Authorization: <config.sharedAccessSignature>
Content-Type: application/json; charset=utf-8
Request-Id: <guid>
User-Agent: <sdk-name>/<sdk-version>
{
jobId: '<jobId>',
type: 'scheduleDirectRequest', // TBC
cloudToDeviceMethod: {
methodName: '<methodName>',
payload: <payload>, // valid JSON object
timeoutInSeconds: methodTimeoutInSeconds // Number
},
queryCondition: '<queryCondition>', // if the query parameter is a string
startTime: <jobStartTime>, // as an ISO-8601 date string
maxExecutionTimeInSeconds: <maxExecutionTimeInSeconds> // format TBD
}
```]*/
let jobDesc: JobDescription = {
jobId: jobId,
type: 'scheduleDeviceMethod',
cloudToDeviceMethod: fullMethodParams,
startTime: jobStartTime ? (jobStartTime as Date).toISOString() : null,
maxExecutionTimeInSeconds: maxExecutionTimeInSeconds as number
};
if (typeof queryCondition === 'string') {
jobDesc.queryCondition = queryCondition;
} else {
throw new TypeError('queryCondition must be a sql WHERE clause string');
}
this._scheduleJob(jobDesc, _callback);
}, createJobStatusResponse, callback);
}
/**
* @method module:azure-iothub.JobClient#scheduleTwinUpdate
* @description Schedule a job that will update a set of twins with the patch provided as a parameter.
*
* @param {String} jobId The unique identifier that should be used for this job.
* @param {String} queryCondition A SQL query WHERE clause used to compute the list of devices
* on which this job should be run.
* @param {Object} patch The twin patch that should be applied to the twins.
* @param {Date} [jobStartTime] Time time at which the job should start
* @param {Number} [maxExecutionTimeInSeconds] The maximum time alloted for this job to run in seconds.
* @param {Function} [done] The optional function to call when the operation is
* complete. `done` will be called with three
* arguments: an Error object (can be null), a
* job object, and a transport-specific response
* object useful for logging or debugging.
* @returns {Promise<JobStatusResponse>> | void} Promise if no callback function was passed, void otherwise.
*
* @throws {ReferenceError} If one or more of the jobId, queryCondition or patch arguments are falsy.
* @throws {TypeError} If the callback is not the last parameter
*/
scheduleTwinUpdate(jobId: string | number, queryCondition: string, patch: any, jobStartTime: Date, maxExecutionTimeInSeconds: number, done: TripleValueCallback<any, any>): void;
scheduleTwinUpdate(jobId: string | number, queryCondition: string, patch: any, jobStartTime: Date, done: TripleValueCallback<any, any>): void;
scheduleTwinUpdate(jobId: string | number, queryCondition: string, patch: any, done: TripleValueCallback<any, any>): void;
scheduleTwinUpdate(jobId: string | number, queryCondition: string, patch: any, jobStartTime: Date, maxExecutionTimeInSeconds?: number): Promise<JobStatusResponse>;
scheduleTwinUpdate(jobId: string | number, queryCondition: string, patch: any, jobStartTime: Date): Promise<JobStatusResponse>;
scheduleTwinUpdate(jobId: string | number, queryCondition: string, patch: any): Promise<JobStatusResponse>;
scheduleTwinUpdate(jobId: string | number, queryCondition: string, patch: any, jobStartTime?: Date | TripleValueCallback<any, any>, maxExecutionTimeInSeconds?: number | TripleValueCallback<any, any>, done?: TripleValueCallback<any, any>): Promise<JobStatusResponse> | void {
const callback = (typeof jobStartTime === 'function') ? jobStartTime as TripleValueCallback<any, any> : ((typeof maxExecutionTimeInSeconds === 'function') ? maxExecutionTimeInSeconds as TripleValueCallback<any, any> : done);
return tripleValueCallbackToPromise((_callback) => {
/*Codes_SRS_NODE_JOB_CLIENT_16_021: [The `scheduleTwinUpdate` method shall throw a `ReferenceError` if `jobId` is `null`, `undefined` or an empty string.]*/
if (jobId === undefined || jobId === null || jobId === '') throw new ReferenceError('jobId cannot be \'' + jobId + '\'');
/*Codes_SRS_NODE_JOB_CLIENT_16_022: [The `scheduleTwinUpdate` method shall throw a `ReferenceError` if `query` is falsy.]*/
if (!queryCondition) throw new ReferenceError('queryCondition cannot be \'' + queryCondition + '\'');
/*Codes_SRS_NODE_JOB_CLIENT_16_023: [The `scheduleTwinUpdate` method shall throw a `ReferenceError` if `patch` is falsy.]*/
if (!patch) throw new ReferenceError('patch cannot be \'' + patch + '\'');
/*Codes_SRS_NODE_JOB_CLIENT_16_024: [If `jobStartTime` is a function, `jobStartTime` shall be considered the callback and a `TypeError` shall be thrown if `maxExecutionTimeInSeconds` and/or `_callback` are not `undefined`.]*/
if (typeof jobStartTime === 'function') {
if (maxExecutionTimeInSeconds || done) {
throw new TypeError('The callback must be the last parameter');
} else {
_callback = jobStartTime;
jobStartTime = new Date();
maxExecutionTimeInSeconds = defaultMaxExecutionTimeInSeconds;
}
/*Codes_SRS_NODE_JOB_CLIENT_16_025: [If `maxExecutionTimeInSeconds` is a function, `maxExecutionTimeInSeconds` shall be considered the callback and a `TypeError` shall be thrown if `_callback` is not `undefined`.]*/
} else if (typeof maxExecutionTimeInSeconds === 'function') {
if (done) {
throw new TypeError('The callback must be the last parameter');
} else {
_callback = maxExecutionTimeInSeconds;
maxExecutionTimeInSeconds = defaultMaxExecutionTimeInSeconds;
}
}
let jobDesc: JobDescription = {
jobId: jobId,
type: 'scheduleUpdateTwin',
updateTwin: patch,
startTime: jobStartTime ? (jobStartTime as Date).toISOString() : null,
maxExecutionTimeInSeconds: maxExecutionTimeInSeconds as number
};
if (typeof queryCondition === 'string') {
jobDesc.queryCondition = queryCondition;
} else {
throw new TypeError('queryCondition must be a sql WHERE clause string');
}
/*Codes_SRS_NODE_JOB_CLIENT_16_026: [The `scheduleTwinUpdate` method shall construct the HTTP request as follows:
```
PUT /jobs/v2/<jobId>?api-version=<version>
Authorization: <config.sharedAccessSignature>
Content-Type: application/json; charset=utf-8
Request-Id: <guid>
User-Agent: <sdk-name>/<sdk-version>
{
jobId: '<jobId>',
type: 'scheduleTwinUpdate', // TBC
updateTwin: <patch> // Valid JSON object
queryCondition: '<queryCondition>', // if the query parameter is a string
startTime: <jobStartTime>, // as an ISO-8601 date string
maxExecutionTimeInSeconds: <maxExecutionTimeInSeconds> // format TBD
}
```]*/
this._scheduleJob(jobDesc, _callback);
}, createJobStatusResponse, callback);
}
private _getJobsFunc(jobType: JobType, jobStatus: JobStatus, pageSize: number): (continuationToken: string, done: TripleValueCallback<any, any>) => void {
/*Codes_SRS_NODE_JOB_CLIENT_16_035: [The `_getJobsFunc` function shall return a function that can be used by the `Query` object to get a new page of results]*/
return (continuationToken, done) => {
/*Codes_SRS_NODE_JOB_CLIENT_16_012: [The `_getJobsFunc` method shall construct the HTTP request as follows:
```
GET /jobs/v2/query?api-version=<version>[&jobType=<jobType>][&jobStatus=<jobStatus>][&pageSize=<pageSize>][&continuationToken=<continuationToken>]
Authorization: <config.sharedAccessSignature>
Content-Type: application/json; charset=utf-8
Request-Id: <guid>
User-Agent: <sdk-name>/<sdk-version>
```]*/
const jobStatusQueryParam = jobStatus ? '&jobStatus=' + encodeURIComponent(jobStatus) : '';
const jobTypeQueryParam = jobType ? '&jobType=' + encodeURIComponent(jobType) : '';
const path = '/jobs/v2/query' + endpoint.versionQueryString() + jobStatusQueryParam + jobTypeQueryParam;
let headers = {};
if (continuationToken) {
headers['x-ms-continuation'] = continuationToken;
}
if (pageSize) {
headers['x-ms-max-item-count'] = pageSize;
}
this._restApiClient.executeApiCall('GET', path, headers, null, done);
};
}
private _scheduleJob(jobDesc: JobDescription, done: TripleValueCallback<any, any>): void {
const path = '/jobs/v2/' + encodeURIComponent(jobDesc.jobId.toString()) + endpoint.versionQueryString();
const headers = {
'Content-Type': 'application/json; charset=utf-8'
};
/*Codes_SRS_NODE_JOB_CLIENT_16_027: [The method shall call the `done` callback with a single argument that is a standard Javascript `Error` object if the request failed.]*/
/*Codes_SRS_NODE_JOB_CLIENT_16_028: [The method shall call the `done` callback with a `null` error argument, a result and a transport-specific response object if the request was successful.]*/
this._restApiClient.executeApiCall('PUT', path, headers, jobDesc, done);
}
/**
* @method module:azure-iothub.JobClient.fromConnectionString
* @description Constructs a JobClient object from the given connection string.
* @static
*
* @param {String} connectionString A connection string which encapsulates the
* appropriate (read and/or write) Registry
* permissions.
*
* @throws {ReferenceError} If the connectionString argument is falsy.
*
* @returns {module:azure-iothub.JobClient}
*/
static fromConnectionString(connectionString: string): JobClient {
/*Codes_SRS_NODE_JOB_CLIENT_16_002: [The `fromConnectionString` method shall throw a `ReferenceError` if `connectionString` is falsy.]*/
if (!connectionString) throw new ReferenceError('connectionString cannot be \'' + connectionString + '\'');
const cn = ConnectionString.parse(connectionString);
const config = {
host: cn.HostName,
sharedAccessSignature: SharedAccessSignature.create(cn.HostName, cn.SharedAccessKeyName, cn.SharedAccessKey, Date.now()),
tokenCredential: undefined
};
/*Codes_SRS_NODE_JOB_CLIENT_16_003: [The `fromConnectionString` method shall return a new `JobClient` instance.]*/
return new JobClient(new RestApiClient(config, packageJson.name + '/' + packageJson.version));
}
/**
* @method module:azure-iothub.JobClient.fromSharedAccessSignature
* @description Constructs a JobClient object from the given shared access signature.
* @static
*
* @param {String} sharedAccessSignature A shared access signature which encapsulates
* the appropriate (read and/or write) Registry
* permissions.
*
* @throws {ReferenceError} If the sharedAccessSignature argument is falsy.
*
* @returns {module:azure-iothub.JobClient}
*/
static fromSharedAccessSignature(sharedAccessSignature: string): JobClient {
/*Codes_SRS_NODE_JOB_CLIENT_16_004: [The `fromSharedAccessSignature` method shall throw a `ReferenceError` if `sharedAccessSignature` is falsy.]*/
if (!sharedAccessSignature) throw new ReferenceError('sharedAccessSignature cannot be \'' + sharedAccessSignature + '\'');
const sas = SharedAccessSignature.parse(sharedAccessSignature);
const config = {
host: sas.sr,
sharedAccessSignature: sharedAccessSignature,
tokenCredential: undefined
};
/*Codes_SRS_NODE_JOB_CLIENT_16_005: [The `fromSharedAccessSignature` method shall return a new `JobClient` instance.]*/
return new JobClient(new RestApiClient(config, packageJson.name + '/' + packageJson.version));
}
/**
* @method module:azure-iothub.JobClient.fromTokenCredential
* @description Constructs a JobClient object from the given shared Azure TokenCredential.
* @static
*
* @param {String} hostName Host name of the Azure service.
* @param {String} tokenCredential An Azure TokenCredential used to authenticate
* with the Azure service
*
* @throws {ReferenceError} If the tokenCredential argument is falsy.
*
* @returns {module:azure-iothub.JobClient}
*/
static fromTokenCredential(hostName: string, tokenCredential: TokenCredential): JobClient {
const config = {
host: hostName,
tokenCredential,
tokenScope: 'https://iothubs.azure.net/.default'
};
return new JobClient(new RestApiClient(config, packageJson.name + '/' + packageJson.version));
}
}
export namespace JobClient {
export type JobCallback = TripleValueCallback<any, any>; // (err: Error, jobStatus?: any, response?: any) => void;
}
export type JobStatusResponse = {
jobStatus: any;
response: any;
};
export function createJobStatusResponse(jobStatus: any, response: any): JobStatusResponse {
return { jobStatus: jobStatus, response: response };
} | the_stack |
import Conditions from '../../../../../resources/conditions';
import NetRegexes from '../../../../../resources/netregexes';
import Outputs from '../../../../../resources/outputs';
import { Responses } from '../../../../../resources/responses';
import ZoneId from '../../../../../resources/zone_id';
import { RaidbossData } from '../../../../../types/data';
import { TriggerSet } from '../../../../../types/trigger';
export interface Data extends RaidbossData {
charges: string[];
seenBrighteyes?: boolean;
}
// Notes:
// Ignoring Gobsway Rumblerocks (1AA0) aoe trigger, as it is small and frequent.
const chargeOutputStrings = {
getIn: Outputs.in,
getOut: {
en: 'Out',
de: 'Raus',
fr: 'Exterieur',
ja: '外へ',
cn: '远离',
ko: '밖으로',
},
spread: Outputs.spread,
stackMarker: Outputs.stackMarker,
unknown: Outputs.unknown,
};
const triggerSet: TriggerSet<Data> = {
zoneId: ZoneId.AlexanderTheBreathOfTheCreatorSavage,
timelineFile: 'a10s.txt',
initData: () => {
return {
charges: [],
};
},
timelineTriggers: [
{
id: 'A10S Goblin Rush',
regex: /Goblin Rush/,
beforeSeconds: 5,
suppressSeconds: 1,
response: Responses.miniBuster(),
},
{
id: 'A10S Gobbie Adds',
regex: /Gobbie Adds/,
beforeSeconds: 0,
suppressSeconds: 1,
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Hit Adds With Weight Trap',
de: 'Adds mit Gewichtsfalle treffen',
fr: 'Frappez les Adds avec le Piège à poids',
ja: '鉄球ギミックを使って雑魚を倒す',
cn: '使用铁锤陷阱击中小怪',
ko: '철퇴 함정으로 쫄 맞추기',
},
},
},
],
triggers: [
{
id: 'A10S Floor Spike Trap',
type: 'Ability',
netRegex: NetRegexes.ability({ source: 'Lamebrix Strikebocks', id: '1AB2', capture: false }),
netRegexDe: NetRegexes.ability({ source: 'Wüterix (?:der|die|das) Söldner', id: '1AB2', capture: false }),
netRegexFr: NetRegexes.ability({ source: 'Lamebrix Le Mercenaire', id: '1AB2', capture: false }),
netRegexJa: NetRegexes.ability({ source: '傭兵のレイムプリクス', id: '1AB2', capture: false }),
netRegexCn: NetRegexes.ability({ source: '佣兵雷姆普里克斯', id: '1AB2', capture: false }),
netRegexKo: NetRegexes.ability({ source: '용병 레임브릭스', id: '1AB2', capture: false }),
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Floor Spikes',
de: 'Boden-Stachel',
fr: 'Pics au sol',
ja: '罠: 棘',
cn: '地刺陷阱',
ko: '가시 함정',
},
},
},
{
id: 'A10S Frost Laser Trap',
type: 'Ability',
netRegex: NetRegexes.ability({ source: 'Lamebrix Strikebocks', id: '1AB1', capture: false }),
netRegexDe: NetRegexes.ability({ source: 'Wüterix (?:der|die|das) Söldner', id: '1AB1', capture: false }),
netRegexFr: NetRegexes.ability({ source: 'Lamebrix Le Mercenaire', id: '1AB1', capture: false }),
netRegexJa: NetRegexes.ability({ source: '傭兵のレイムプリクス', id: '1AB1', capture: false }),
netRegexCn: NetRegexes.ability({ source: '佣兵雷姆普里克斯', id: '1AB1', capture: false }),
netRegexKo: NetRegexes.ability({ source: '용병 레임브릭스', id: '1AB1', capture: false }),
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Frost Lasers',
de: 'Eislaser',
fr: 'Lasers de glace',
ja: '罠: 氷',
cn: '冰晶陷阱',
ko: '얼음화살 함정',
},
},
},
{
id: 'A10S Ceiling Weight Trap',
type: 'Ability',
netRegex: NetRegexes.ability({ source: 'Lamebrix Strikebocks', id: '1AB0', capture: false }),
netRegexDe: NetRegexes.ability({ source: 'Wüterix (?:der|die|das) Söldner', id: '1AB0', capture: false }),
netRegexFr: NetRegexes.ability({ source: 'Lamebrix Le Mercenaire', id: '1AB0', capture: false }),
netRegexJa: NetRegexes.ability({ source: '傭兵のレイムプリクス', id: '1AB0', capture: false }),
netRegexCn: NetRegexes.ability({ source: '佣兵雷姆普里克斯', id: '1AB0', capture: false }),
netRegexKo: NetRegexes.ability({ source: '용병 레임브릭스', id: '1AB0', capture: false }),
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Ceiling Weight',
de: 'Gewichte von der Decke',
fr: 'Poids du plafond',
ja: '罠: 鉄球',
cn: '铁球陷阱',
ko: '철퇴 함정',
},
},
},
{
id: 'A10S Charge Marker',
type: 'Ability',
// This also handles the "single charge" call.
netRegex: NetRegexes.ability({ source: 'Lamebrix Strikebocks', id: '1AB[89AB]' }),
netRegexDe: NetRegexes.ability({ source: 'Wüterix (?:der|die|das) Söldner', id: '1AB[89AB]' }),
netRegexFr: NetRegexes.ability({ source: 'Lamebrix Le Mercenaire', id: '1AB[89AB]' }),
netRegexJa: NetRegexes.ability({ source: '傭兵のレイムプリクス', id: '1AB[89AB]' }),
netRegexCn: NetRegexes.ability({ source: '佣兵雷姆普里克斯', id: '1AB[89AB]' }),
netRegexKo: NetRegexes.ability({ source: '용병 레임브릭스', id: '1AB[89AB]' }),
preRun: (data, matches) => {
const chargeMap: { [abilityId: string]: string } = {
'1AB8': 'getIn',
'1AB9': 'getOut',
'1ABA': 'spread',
'1ABB': 'stackMarker',
};
data.charges.push(chargeMap[matches.id] ?? 'unknown');
},
response: (data, _matches, output) => {
// cactbot-builtin-response
output.responseOutputStrings = chargeOutputStrings;
// Call the first one out with alert, the other two with info.
const severity = data.charges.length > 1 ? 'infoText' : 'alertText';
const charge = data.charges[data.charges.length - 1] ?? 'unknown';
return { [severity]: output[charge]!() };
},
},
{
id: 'A10S Charge 1',
type: 'Ability',
netRegex: NetRegexes.ability({ source: 'Lamebrix Strikebocks', id: '1A9[789]', capture: false }),
netRegexDe: NetRegexes.ability({ source: 'Wüterix (?:der|die|das) Söldner', id: '1A9[789]', capture: false }),
netRegexFr: NetRegexes.ability({ source: 'Lamebrix Le Mercenaire', id: '1A9[789]', capture: false }),
netRegexJa: NetRegexes.ability({ source: '傭兵のレイムプリクス', id: '1A9[789]', capture: false }),
netRegexCn: NetRegexes.ability({ source: '佣兵雷姆普里克斯', id: '1A9[789]', capture: false }),
netRegexKo: NetRegexes.ability({ source: '용병 레임브릭스', id: '1A9[789]', capture: false }),
run: (data) => data.charges.shift(),
},
{
id: 'A10S Charge Double Triple',
type: 'Ability',
netRegex: NetRegexes.ability({ source: 'Lamebrix Strikebocks', id: '1A9[ABCE]', capture: false }),
netRegexDe: NetRegexes.ability({ source: 'Wüterix (?:der|die|das) Söldner', id: '1A9[ABCE]', capture: false }),
netRegexFr: NetRegexes.ability({ source: 'Lamebrix Le Mercenaire', id: '1A9[ABCE]', capture: false }),
netRegexJa: NetRegexes.ability({ source: '傭兵のレイムプリクス', id: '1A9[ABCE]', capture: false }),
netRegexCn: NetRegexes.ability({ source: '佣兵雷姆普里克斯', id: '1A9[ABCE]', capture: false }),
netRegexKo: NetRegexes.ability({ source: '용병 레임브릭스', id: '1A9[ABCE]', capture: false }),
suppressSeconds: 0.5,
response: (data, _matches, output) => {
// cactbot-builtin-response
output.responseOutputStrings = chargeOutputStrings;
if (data.charges.length === 0)
return;
const charge = data.charges.shift();
if (charge)
return { alertText: output[charge]!() };
},
},
{
id: 'A10S Charge Clear',
type: 'Ability',
netRegex: NetRegexes.ability({ source: 'Lamebrix Strikebocks', id: '1A9[789]', capture: false }),
netRegexDe: NetRegexes.ability({ source: 'Wüterix (?:der|die|das) Söldner', id: '1A9[789]', capture: false }),
netRegexFr: NetRegexes.ability({ source: 'Lamebrix Le Mercenaire', id: '1A9[789]', capture: false }),
netRegexJa: NetRegexes.ability({ source: '傭兵のレイムプリクス', id: '1A9[789]', capture: false }),
netRegexCn: NetRegexes.ability({ source: '佣兵雷姆普里克斯', id: '1A9[789]', capture: false }),
netRegexKo: NetRegexes.ability({ source: '용병 레임브릭스', id: '1A9[789]', capture: false }),
delaySeconds: 10,
run: (data) => {
// Cleanup just in case.
data.charges = [];
},
},
{
id: 'A10S Gobrush Rushgob',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: 'Lamebrix Strikebocks', id: '1A9F' }),
netRegexDe: NetRegexes.startsUsing({ source: 'Wüterix (?:der|die|das) Söldner', id: '1A9F' }),
netRegexFr: NetRegexes.startsUsing({ source: 'Lamebrix Le Mercenaire', id: '1A9F' }),
netRegexJa: NetRegexes.startsUsing({ source: '傭兵のレイムプリクス', id: '1A9F' }),
netRegexCn: NetRegexes.startsUsing({ source: '佣兵雷姆普里克斯', id: '1A9F' }),
netRegexKo: NetRegexes.startsUsing({ source: '용병 레임브릭스', id: '1A9F' }),
response: Responses.tankBuster(),
},
{
id: 'A10S Slicetops Tether',
type: 'Tether',
netRegex: NetRegexes.tether({ source: 'Lamebrix Strikebocks', id: '0039' }),
netRegexDe: NetRegexes.tether({ source: 'Wüterix (?:der|die|das) Söldner', id: '0039' }),
netRegexFr: NetRegexes.tether({ source: 'Lamebrix Le Mercenaire', id: '0039' }),
netRegexJa: NetRegexes.tether({ source: '傭兵のレイムプリクス', id: '0039' }),
netRegexCn: NetRegexes.tether({ source: '佣兵雷姆普里克斯', id: '0039' }),
netRegexKo: NetRegexes.tether({ source: '용병 레임브릭스', id: '0039' }),
alarmText: (data, matches, output) => {
if (data.me !== matches.target)
return;
return output.tankSwapGetAway!();
},
alertText: (data, matches, output) => {
if (data.me === matches.target)
return;
if (data.role === 'tank')
return output.tankSwap!();
if (data.role === 'healer' || data.job === 'BLU')
return output.shieldPlayer!({ player: data.ShortName(matches.target) });
},
outputStrings: {
tankSwap: Outputs.tankSwap,
shieldPlayer: {
en: 'Shield ${player}',
de: 'Schild ${player}',
fr: 'Bouclier ${player}',
ja: '${player}にバリア',
cn: '单盾${player}',
ko: '"${player}" 보호막',
},
tankSwapGetAway: {
en: 'Tank Swap, Get Away',
de: 'Tankwechsel, geh weg',
fr: 'Tank swap, éloignez-vous',
ja: 'タンクスイッチ、離れる',
cn: '换T并且远离',
ko: '탱 교대, 멀리가기',
},
},
},
{
id: 'A10S Gobsnick Leghops',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: 'Lamebrix Strikebocks', id: '1AA4', capture: false }),
netRegexDe: NetRegexes.startsUsing({ source: 'Wüterix (?:der|die|das) Söldner', id: '1AA4', capture: false }),
netRegexFr: NetRegexes.startsUsing({ source: 'Lamebrix Le Mercenaire', id: '1AA4', capture: false }),
netRegexJa: NetRegexes.startsUsing({ source: '傭兵のレイムプリクス', id: '1AA4', capture: false }),
netRegexCn: NetRegexes.startsUsing({ source: '佣兵雷姆普里克斯', id: '1AA4', capture: false }),
netRegexKo: NetRegexes.startsUsing({ source: '용병 레임브릭스', id: '1AA4', capture: false }),
response: Responses.stopEverything(),
},
{
id: 'A10S Brighteyes Tracker',
type: 'Ability',
netRegex: NetRegexes.ability({ source: 'Lamebrix Strikebocks', id: '1AA9', capture: false }),
netRegexDe: NetRegexes.ability({ source: 'Wüterix (?:der|die|das) Söldner', id: '1AA9', capture: false }),
netRegexFr: NetRegexes.ability({ source: 'Lamebrix Le Mercenaire', id: '1AA9', capture: false }),
netRegexJa: NetRegexes.ability({ source: '傭兵のレイムプリクス', id: '1AA9', capture: false }),
netRegexCn: NetRegexes.ability({ source: '佣兵雷姆普里克斯', id: '1AA9', capture: false }),
netRegexKo: NetRegexes.ability({ source: '용병 레임브릭스', id: '1AA9', capture: false }),
run: (data) => {
// This comes out 0.1s before every '0029' prey marker.
data.seenBrighteyes = true;
},
},
{
id: 'A10S Brighteyes Cleanup',
type: 'Ability',
netRegex: NetRegexes.ability({ source: 'Lamebrix Strikebocks', id: '1AA9', capture: false }),
netRegexDe: NetRegexes.ability({ source: 'Wüterix (?:der|die|das) Söldner', id: '1AA9', capture: false }),
netRegexFr: NetRegexes.ability({ source: 'Lamebrix Le Mercenaire', id: '1AA9', capture: false }),
netRegexJa: NetRegexes.ability({ source: '傭兵のレイムプリクス', id: '1AA9', capture: false }),
netRegexCn: NetRegexes.ability({ source: '佣兵雷姆普里克斯', id: '1AA9', capture: false }),
netRegexKo: NetRegexes.ability({ source: '용병 레임브릭스', id: '1AA9', capture: false }),
delaySeconds: 20,
suppressSeconds: 20,
run: (data) => delete data.seenBrighteyes,
},
{
id: 'A10S Brighteyes Prey Marker',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '0029' }),
condition: Conditions.targetIsYou(),
alertText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Prey on YOU',
de: 'Makierung auf DIR',
fr: 'Marquage sur VOUS',
ja: '自分に狙い目',
cn: '火圈点名',
ko: '징 대상자',
},
},
},
{
id: 'A10S Brighteyes Prey Marker Pass',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '0029' }),
condition: (data, matches) => {
// Only need to pass on the first one.
return data.me === matches.target && !data.seenBrighteyes;
},
delaySeconds: 5,
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Pass Prey',
de: 'Makierung weitergeben',
fr: 'Passez la marque',
ja: '狙い目を渡す',
cn: '传递点名',
ko: '징 넘김',
},
},
},
{
id: 'A10S Gobslice Mooncrops',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: 'Lamebrix Strikebocks', id: '1A92', capture: false }),
netRegexDe: NetRegexes.startsUsing({ source: 'Wüterix (?:der|die|das) Söldner', id: '1A92', capture: false }),
netRegexFr: NetRegexes.startsUsing({ source: 'Lamebrix Le Mercenaire', id: '1A92', capture: false }),
netRegexJa: NetRegexes.startsUsing({ source: '傭兵のレイムプリクス', id: '1A92', capture: false }),
netRegexCn: NetRegexes.startsUsing({ source: '佣兵雷姆普里克斯', id: '1A92', capture: false }),
netRegexKo: NetRegexes.startsUsing({ source: '용병 레임브릭스', id: '1A92', capture: false }),
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Hit Floor Trap',
de: 'Aktiviere Bodenfalle',
fr: 'Activez le Piège au sol',
ja: '棘を踏む',
cn: '踩地刺陷阱',
ko: '가시함정 밟기',
},
},
},
{
id: 'A10S Gobslice Mooncrops Cast',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: 'Lamebrix Strikebocks', id: '1A8F', capture: false }),
netRegexDe: NetRegexes.startsUsing({ source: 'Wüterix (?:der|die|das) Söldner', id: '1A8F', capture: false }),
netRegexFr: NetRegexes.startsUsing({ source: 'Lamebrix Le Mercenaire', id: '1A8F', capture: false }),
netRegexJa: NetRegexes.startsUsing({ source: '傭兵のレイムプリクス', id: '1A8F', capture: false }),
netRegexCn: NetRegexes.startsUsing({ source: '佣兵雷姆普里克斯', id: '1A8F', capture: false }),
netRegexKo: NetRegexes.startsUsing({ source: '용병 레임브릭스', id: '1A8F', capture: false }),
response: Responses.getOut('info'),
},
{
id: 'A10S Gobspin Zoomdrops',
type: 'Ability',
netRegex: NetRegexes.ability({ source: 'Lamebrix Strikebocks', id: '1A8F', capture: false }),
netRegexDe: NetRegexes.ability({ source: 'Wüterix (?:der|die|das) Söldner', id: '1A8F', capture: false }),
netRegexFr: NetRegexes.ability({ source: 'Lamebrix Le Mercenaire', id: '1A8F', capture: false }),
netRegexJa: NetRegexes.ability({ source: '傭兵のレイムプリクス', id: '1A8F', capture: false }),
netRegexCn: NetRegexes.ability({ source: '佣兵雷姆普里克斯', id: '1A8F', capture: false }),
netRegexKo: NetRegexes.ability({ source: '용병 레임브릭스', id: '1A8F', capture: false }),
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Hit Boss With Ice',
de: 'Boss mit Eis treffen',
fr: 'Frappez le boss avec la Glace',
ja: '氷を踏む',
cn: '踩冰晶陷阱',
ko: '보스에게 얼음함정 맞히기',
},
},
},
],
timelineReplace: [
{
'locale': 'de',
'replaceSync': {
'Buzzsaw': 'Rotorsäge',
'Gobpress R-VI': 'Gob-Roller VI',
'Lamebrix Strikebocks': 'Wüterix (?:der|die|das) Söldner',
'Lameprix Strikedocks': 'Wüterix (?:der|die|das) Trickser',
'The Excruciationator': 'Multi-Martyrium',
'Weight Of The World': 'Schwere der Erde',
},
'replaceText': {
'(?!--)mechanic': 'Mechanik',
'--in/out--': '--Rein/Raus--',
'--out/in--': '--Raus/Rein--',
'--spread/stack--': '--Verteilen/Sammeln--',
'--stack/spread--': '--Sammeln/Verteilen--',
'\\(Stack/Spread\\)': '(Sammeln/Verteilen)',
'Brighteyes(?! Markers)': 'Zielheften Auge',
'Brighteyes Markers': 'Zielheften Auge Markierungen',
'Clone Add': 'Klon Add',
'Discharge': 'Abfeuern',
'Double Charge': 'Doppelaufladung',
'Floor Trap': 'Boden-Falle',
'Frost Trap': 'Eisstrahl-Falle',
'Frostbite': 'Abfrieren',
'Gobbie Adds': 'Gobbie Adds',
'Goblin Rush': 'Goblin-Rausch',
'Gobrush Rushgob': 'Indigoblin-Rausch ',
'Gobslash Slicetops': 'Indigo-Vakuumhieb',
'Gobslice Mooncrops': 'Schlitzensichel',
'Gobsnick Leghops': 'Gob am Berg',
'Gobspin Zoomdrops': 'Große Gobwirbel',
'Gobsway Rumblerocks': 'Riesengroße Schüttern',
'Gobswish Spraymops': 'Fährliche Fächer',
'Illuminati Hand Cannon': 'Indigohandkanone',
'Impact': 'Impakt',
'Laceration': 'Zerreißen',
'Single Charge': 'Einzelaufladung',
'Steam Roller': 'Dampfwalze',
'Stoneskin': 'Steinhaut',
'Triple Charge': 'Dreifachaufladung',
'Weight Trap': 'Gewichts-Falle',
'Leghops\\?/Charge': 'Gob am Berg?/Aufladung',
},
},
{
'locale': 'fr',
'replaceSync': {
'Buzzsaw': 'Scie mécanique',
'Gobpress R-VI': 'Gobrouleau compresseur G-VI',
'Lamebrix Strikebocks': 'Lamebrix le Mercenaire',
'Lameprix Strikedocks': 'Lamebrix le Diversif',
'The Excruciationator': 'la plate-forme de torture polyvalente',
'Weight Of The World': 'Poids du monde',
},
'replaceText': {
'(?!--)mechanic': 'Mécanique',
'--in/out--': '--intérieur/extérieur--',
'--out/in--': '--extérieur/intérieur--',
'--spread/stack--': '--dispersion/package--',
'--stack/spread--': '--package/dispersion--',
'\\(Stack/Spread\\)': '(Package/Dispersion)',
'Brighteyes Markers': 'Marquage Œil vif',
'Brighteyes(?! Markers)': 'Œil vif',
'Clone Add': 'Add Clone',
'Discharge': 'Mitraillage',
'Double Charge': 'Rechargement double',
'Floor Trap': 'Piège au sol',
'Frost Trap': 'Piège de glace',
'Frostbite': 'Gelure',
'Gobbie Adds x3': 'Adds x3 Gob',
'Goblin Rush': 'Charge gobeline',
'Gobrush Rushgob': 'Gobcharge gobeline',
'Gobslash Slicetops': 'Gobtranchant du vide',
'Gobslice Mooncrops': 'Gobcroissant lacérant',
'Gobsnick Leghops': 'Gobfeinte mortelle',
'Gobspin Zoomdrops': 'Gobtoupie mégatranchante',
'Gobsway Rumblerocks': 'Gobbouleversement',
'Gobswish Spraymops': 'Gobdécoupage brutal',
'Illuminati Hand Cannon': 'Main-canon indigo',
'Impact': 'Impact',
'Laceration': 'Lacération',
'Leghops\\?/Charge': 'Mortelle ?/Charge',
'Single Charge': 'Rechargement simple',
'Steam Roller': 'Compression',
'Stoneskin': 'Cuirasse',
'Triple Charge': 'Rechargement triple',
'Weight Trap': 'Piège à poids',
},
},
{
'locale': 'ja',
'replaceSync': {
'Buzzsaw': '回転ノコギリ',
'Gobpress R-VI': 'VI号ゴブリローラー',
'Lamebrix Strikebocks': '傭兵のレイムプリクス',
'Lameprix Strikedocks': '偽兵のレイムプリクス',
'The Excruciationator': '科学的万能処刑場',
'Weight Of The World': '大陸の重み',
},
'replaceText': {
'(?!--)mechanic': 'ギミック',
'--in/out--': '--中/外--',
'--out/in--': '--外/中--',
'--spread/stack--': '--散開/集合--',
'--stack/spread--': '--集合/散開--',
'\\(Stack/Spread\\)': '(集合/散開)',
'\\)\\?': ') ?',
'Brighteyes Markers': '狙い目マーキング',
'Brighteyes(?! Markers)': '狙い目',
'Clone Add': '雑魚: ミラージュ',
'Discharge': '銃撃',
'Double Charge': '二連充填',
'Floor Trap': '罠ギミック',
'Frost Trap': '罠: 氷',
'Frostbite': 'フロストバイト',
'Gobbie Adds x3': '雑魚: 3 ゴブ',
'Goblin Rush': 'ゴブリンラッシュ',
'Gobrush Rushgob': 'ゴブ流ゴブリンラッシュ',
'Gobslash Slicetops': 'ゴブ流真空斬り',
'Gobslice Mooncrops': 'ゴブ流三日月斬り',
'Gobsnick Leghops': 'ゴブ流後の先',
'Gobspin Zoomdrops': 'ゴブ流大回転斬り',
'Gobsway Rumblerocks': 'ゴブ流大激震',
'Gobswish Spraymops': 'ゴブ流飛水断ち',
'Illuminati Hand Cannon': 'イルミナティ・ハンドカノン',
'Impact': '衝撃',
'Laceration': '斬撃',
'Leghops\\?/Charge': 'ゴブ流後の先?/充填',
'Single Charge': '単発充填',
'Steam Roller': 'ローラープレス',
'Stoneskin': 'ストンスキン',
'Triple Charge': '三連充填',
'Weight Trap': '罠: 鉄球',
},
},
{
'locale': 'cn',
'replaceSync': {
'Buzzsaw': '旋转链锯',
'Gobpress R-VI': '6号哥布林压路机',
'Lamebrix Strikebocks': '佣兵雷姆普里克斯',
'Lameprix Strikedocks': '虚兵雷姆普里克斯',
'The Excruciationator': '科学万能处刑场',
'Weight Of The World': '大陆之重',
},
'replaceText': {
'(?!--)mechanic': '机制',
'--in/out--': '--内/外--',
'--out/in--': '--外/内--',
'--spread/stack--': '--分散/集合--',
'--stack/spread--': '--集合/分散--',
'\\)\\?': ') ?',
'Brighteyes': '目标',
'Clone Add': '分身出现',
'Discharge': '枪击',
'Double Charge': '二连填充',
'Floor Trap': '地刺陷阱',
'Frost Trap': '冰晶陷阱',
'Frostbite': '寒冰箭',
'Gobbie Adds': '哥布林出现',
'Goblin Rush': '哥布林冲锋',
'Gobrush Rushgob': '哥布流哥布林冲锋',
'Gobslash Slicetops': '哥布流真空斩',
'Gobslice Mooncrops': '哥布流月牙斩',
'Gobsnick Leghops': '哥布流后之先',
'Gobspin Zoomdrops': '哥布流大回旋斩',
'Gobsway Rumblerocks': '哥布流大怒震',
'Gobswish Spraymops': '哥布流断瀑斩',
'Illuminati Hand Cannon': '青蓝手炮',
'Impact': '锤击',
'Laceration': '斩击',
'Single Charge': '单发填充',
'Steam Roller': '蒸汽滚轮',
'Stoneskin': '石肤',
'Triple Charge': '三连填充',
'Weight Trap': '铁球陷阱',
'Leghops\\?/Charge': '哥布流后之先?/冲锋',
},
},
{
'locale': 'ko',
'replaceSync': {
'Buzzsaw': '회전톱',
'Gobpress R-VI': 'VI호 고블린롤러',
'Lamebrix Strikebocks': '용병 레임브릭스',
'Lameprix Strikedocks': '가짜 용병 레임프릭스',
'The Excruciationator': '과학적 만능처형장',
'Weight Of The World': '쇠구슬',
},
'replaceText': {
'(?!--)mechanic': '기믹',
'--in/out--': '--안/밖--',
'--out/in--': '--밖/안--',
'--spread/stack--': '--산개/쉐어--',
'--stack/spread--': '--쉐어/산개--',
'Brighteyes': '표적',
'Clone Add': '분신 등장',
'Discharge': '총격',
'Double Charge': '2연속 충전',
'Floor Trap': '가시 함정',
'Frost Trap': '얼음화살 함정',
'Frostbite': '동상',
'Gobbie Adds': '고블린 등장',
'Goblin Rush': '고블린 돌진',
'Gobrush Rushgob': '고브류 고블린 돌진',
'Gobslash Slicetops': '고브류 진공베기',
'Gobslice Mooncrops': '고브류 초승달베기',
'Gobsnick Leghops': '고브류 되받아치기',
'Gobspin Zoomdrops': '고브류 대회전베기',
'Gobsway Rumblerocks': '고브류 대격진',
'Gobswish Spraymops': '고브류 물보라베기',
'Illuminati Hand Cannon': '푸른손 화포',
'Impact': '충격',
'Laceration': '참격',
'Single Charge': '단발 충전',
'Steam Roller': '롤러 프레스',
'Stoneskin': '스톤스킨',
'Triple Charge': '3연속 충전',
'Weight Trap': '철퇴 함정',
'Leghops\\?/Charge': '되받아치기?/충전',
},
},
],
};
export default triggerSet; | the_stack |
import 'mocha';
import { expect } from '@integration/testing-tools';
import { StageManager } from '@serenity-js/core';
import { SceneFinished, SceneParametersDetected, SceneSequenceDetected, SceneStarts, SceneTagged, SceneTemplateDetected, TestRunFinishes } from '@serenity-js/core/lib/events';
import { FileSystemLocation, Path } from '@serenity-js/core/lib/io';
import {
BrowserTag,
Category,
CorrelationId,
Description,
ExecutionFailedWithError,
ExecutionSuccessful,
Name,
PlatformTag,
ScenarioDetails,
ScenarioParameters,
} from '@serenity-js/core/lib/model';
import * as sinon from 'sinon';
import { SerenityBDDReporter } from '../../../../../src/stage';
import { SerenityBDDReport } from '../../../../../src/stage/crew/serenity-bdd-reporter/SerenityBDDJsonSchema';
import { given } from '../../given';
import { create } from '../create';
describe('SerenityBDDReporter', () => {
let stageManager: sinon.SinonStubbedInstance<StageManager>,
reporter: SerenityBDDReporter;
beforeEach(() => {
const env = create();
stageManager = env.stageManager;
reporter = env.reporter;
});
// see examples/cucumber/features/reporting_results/reports_scenario_outlines.feature for more context
const
sceneIds = [ new CorrelationId('scene-0'), new CorrelationId('scene-1') ],
category = new Category('Reporting results'),
name = new Name('Reports scenario outlines'),
path = new Path(`reporting_results/reports_scenario_outlines.feature`),
template = new Description(`
When <Developer> makes a contribution of:
| value |
| time |
| talent |
| great code |
Then they help bring serenity to fellow devs
`),
sequence = new ScenarioDetails(name, category, new FileSystemLocation(
path,
7,
)),
scenarios = [
new ScenarioDetails(name, category, new FileSystemLocation(path, 25)),
new ScenarioDetails(name, category, new FileSystemLocation(path, 26)),
]
;
/**
* @test {SerenityBDDReporter}
*/
it('captures information about a sequence of scenes (2 scenes in a sequence)', () => {
given(reporter).isNotifiedOfFollowingEvents(
new SceneSequenceDetected(sceneIds[0], sequence),
new SceneTemplateDetected(sceneIds[0], template),
new SceneParametersDetected(
sceneIds[0],
scenarios[0],
new ScenarioParameters(
new Name('Serenity/JS contributors'),
new Description(`Some of the people who have contributed their time and talent to the Serenity/JS project`),
{ Developer: 'jan-molak', Twitter_Handle: '@JanMolak' },
),
),
new SceneStarts(sceneIds[0], scenarios[0]),
new SceneFinished(sceneIds[0], scenarios[0], new ExecutionSuccessful()),
new SceneSequenceDetected(sceneIds[1], sequence),
new SceneTemplateDetected(sceneIds[1], template),
new SceneParametersDetected(
sceneIds[1],
scenarios[1],
new ScenarioParameters(
new Name('Serenity/JS contributors'),
new Description(`Some of the people who have contributed their time and talent to the Serenity/JS project`),
{ Developer: 'wakaleo', Twitter_Handle: '@wakaleo' },
),
),
new SceneStarts(sceneIds[1], scenarios[1]),
new SceneFinished(sceneIds[1], scenarios[1], new ExecutionSuccessful()),
new TestRunFinishes(),
);
const report: SerenityBDDReport = stageManager.notifyOf.firstCall.lastArg.artifact.map(_ => _);
expect(report.name).to.equal(name.value);
expect(report.dataTable).to.exist;
expect(report.dataTable.scenarioOutline).to.equal(template.value);
expect(report.dataTable.headers).to.deep.equal([
'Developer',
'Twitter_Handle',
]);
expect(report.dataTable.dataSetDescriptors).to.deep.equal([{
startRow: 0,
rowCount: 2,
name: 'Serenity/JS contributors',
description: 'Some of the people who have contributed their time and talent to the Serenity/JS project',
}]);
expect(report.dataTable.rows).to.deep.equal([
{ values: [ 'jan-molak', '@JanMolak' ], result: 'SUCCESS' },
{ values: [ 'wakaleo', '@wakaleo' ], result: 'SUCCESS' },
]);
expect(report.testSteps).to.have.lengthOf(2);
expect(report.testSteps[0].description)
.to.equal(`${name.value} #1 - Developer: jan-molak, Twitter_Handle: @JanMolak`);
expect(report.testSteps[1].description)
.to.equal(`${name.value} #2 - Developer: wakaleo, Twitter_Handle: @wakaleo`);
});
/**
* @test {SerenityBDDReporter}
*/
it('determines the result of the sequence based on the worst result of the contributing scenarios', () => {
given(reporter).isNotifiedOfFollowingEvents(
new SceneSequenceDetected(sceneIds[0], sequence),
new SceneTemplateDetected(sceneIds[0], template),
new SceneParametersDetected(
sceneIds[0],
scenarios[0],
new ScenarioParameters(
new Name('Serenity/JS contributors'),
new Description(`Some of the people who have contributed their time and talent to the Serenity/JS project`),
{ Developer: 'jan-molak', Twitter_Handle: '@JanMolak' },
),
),
new SceneStarts(sceneIds[0], scenarios[0]),
new SceneFinished(sceneIds[0], scenarios[0], new ExecutionFailedWithError(new Error('Something happened'))),
new SceneSequenceDetected(sceneIds[1], sequence),
new SceneTemplateDetected(sceneIds[1], template),
new SceneParametersDetected(
sceneIds[1],
scenarios[1],
new ScenarioParameters(
new Name('Serenity/JS contributors'),
new Description(`Some of the people who have contributed their time and talent to the Serenity/JS project`),
{ Developer: 'wakaleo', Twitter_Handle: '@wakaleo' },
),
),
new SceneStarts(sceneIds[1], scenarios[1]),
new SceneFinished(sceneIds[1], scenarios[1], new ExecutionSuccessful()),
new TestRunFinishes(),
);
const report: SerenityBDDReport = stageManager.notifyOf.firstCall.lastArg.artifact.map(_ => _);
expect(report.dataTable.rows).to.deep.equal([
{ values: [ 'jan-molak', '@JanMolak' ], result: 'ERROR' },
{ values: [ 'wakaleo', '@wakaleo' ], result: 'SUCCESS' },
]);
expect(report.testSteps).to.have.lengthOf(2);
expect(report.testSteps[0].description)
.to.equal(`${name.value} #1 - Developer: jan-molak, Twitter_Handle: @JanMolak`);
// todo: check for error somewhere here
// todo: map well map the main report
expect(report.testSteps[1].description)
.to.equal(`${name.value} #2 - Developer: wakaleo, Twitter_Handle: @wakaleo`);
});
/**
* @test {SerenityBDDReporter}
*/
it('ensures that context and tags are not duplicated despite having multiple scenarios in a sequence', () => {
given(reporter).isNotifiedOfFollowingEvents(
new SceneSequenceDetected(sceneIds[0], sequence),
new SceneTemplateDetected(sceneIds[0], template),
new SceneParametersDetected(
sceneIds[0],
scenarios[0],
new ScenarioParameters(
new Name('Serenity/JS contributors'),
new Description(`Some of the people who have contributed their time and talent to the Serenity/JS project`),
{ Developer: 'jan-molak', Twitter_Handle: '@JanMolak' },
),
),
new SceneStarts(sceneIds[0], scenarios[0]),
new SceneTagged(
sceneIds[0],
new BrowserTag('chrome', '83.0.4103.106'),
),
new SceneTagged(
sceneIds[0],
new PlatformTag('Mac OS X'),
),
new SceneFinished(sceneIds[0], scenarios[0], new ExecutionFailedWithError(new Error('Something happened'))),
new SceneSequenceDetected(sceneIds[1], sequence),
new SceneTemplateDetected(sceneIds[1], template),
new SceneParametersDetected(
sceneIds[1],
scenarios[1],
new ScenarioParameters(
new Name('Serenity/JS contributors'),
new Description(`Some of the people who have contributed their time and talent to the Serenity/JS project`),
{ Developer: 'wakaleo', Twitter_Handle: '@wakaleo' },
),
),
new SceneStarts(sceneIds[1], scenarios[1]),
new SceneTagged(
sceneIds[1],
new BrowserTag('chrome', '83.0.4103.106'),
),
new SceneTagged(
sceneIds[1],
new PlatformTag('Mac OS X'),
),
new SceneFinished(sceneIds[1], scenarios[1], new ExecutionSuccessful()),
new TestRunFinishes(),
);
const report: SerenityBDDReport = stageManager.notifyOf.firstCall.lastArg.artifact.map(_ => _);
expect(report.id).to.equal('reporting-results;reports-scenario-outlines;chrome-83-0-4103-106;mac-os-x');
expect(report.context).to.equal('chrome,mac');
expect(report.tags).to.deep.equal([{
browserName: 'chrome',
browserVersion: '83.0.4103.106',
displayName: 'chrome 83.0.4103.106',
name: 'chrome 83.0.4103.106',
type: 'browser',
}, {
displayName: 'Mac OS X',
name: 'Mac OS X',
platformName: 'Mac OS X',
platformVersion: '',
type: 'platform',
}]);
});
}); | the_stack |
import { IResource, Resource, Duration } from '@aws-cdk/core';
import { Construct } from 'constructs';
import { CfnUserPoolClient } from './cognito.generated';
import { IUserPool } from './user-pool';
import { ClientAttributes } from './user-pool-attr';
import { IUserPoolResourceServer, ResourceServerScope } from './user-pool-resource-server';
/**
* Types of authentication flow
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html
*/
export interface AuthFlow {
/**
* Enable admin based user password authentication flow
* @default false
*/
readonly adminUserPassword?: boolean;
/**
* Enable custom authentication flow
* @default false
*/
readonly custom?: boolean;
/**
* Enable auth using username & password
* @default false
*/
readonly userPassword?: boolean;
/**
* Enable SRP based authentication
* @default false
*/
readonly userSrp?: boolean;
}
/**
* OAuth settings to configure the interaction between the app and this client.
*/
export interface OAuthSettings {
/**
* OAuth flows that are allowed with this client.
* @see - the 'Allowed OAuth Flows' section at https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-app-idp-settings.html
* @default {authorizationCodeGrant:true,implicitCodeGrant:true}
*/
readonly flows?: OAuthFlows;
/**
* List of allowed redirect URLs for the identity providers.
* @default - ['https://example.com'] if either authorizationCodeGrant or implicitCodeGrant flows are enabled, no callback URLs otherwise.
*/
readonly callbackUrls?: string[];
/**
* List of allowed logout URLs for the identity providers.
* @default - no logout URLs
*/
readonly logoutUrls?: string[];
/**
* OAuth scopes that are allowed with this client.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-app-idp-settings.html
* @default [OAuthScope.PHONE,OAuthScope.EMAIL,OAuthScope.OPENID,OAuthScope.PROFILE,OAuthScope.COGNITO_ADMIN]
*/
readonly scopes?: OAuthScope[];
}
/**
* Types of OAuth grant flows
* @see - the 'Allowed OAuth Flows' section at https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-app-idp-settings.html
*/
export interface OAuthFlows {
/**
* Initiate an authorization code grant flow, which provides an authorization code as the response.
* @default false
*/
readonly authorizationCodeGrant?: boolean;
/**
* The client should get the access token and ID token directly.
* @default false
*/
readonly implicitCodeGrant?: boolean;
/**
* Client should get the access token and ID token from the token endpoint
* using a combination of client and client_secret.
* @default false
*/
readonly clientCredentials?: boolean;
}
/**
* OAuth scopes that are allowed with this client.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-app-idp-settings.html
*/
export class OAuthScope {
/**
* Grants access to the 'phone_number' and 'phone_number_verified' claims.
* Automatically includes access to `OAuthScope.OPENID`.
*/
public static readonly PHONE = new OAuthScope('phone');
/**
* Grants access to the 'email' and 'email_verified' claims.
* Automatically includes access to `OAuthScope.OPENID`.
*/
public static readonly EMAIL = new OAuthScope('email');
/**
* Returns all user attributes in the ID token that are readable by the client
*/
public static readonly OPENID = new OAuthScope('openid');
/**
* Grants access to all user attributes that are readable by the client
* Automatically includes access to `OAuthScope.OPENID`.
*/
public static readonly PROFILE = new OAuthScope('profile');
/**
* Grants access to Amazon Cognito User Pool API operations that require access tokens,
* such as UpdateUserAttributes and VerifyUserAttribute.
*/
public static readonly COGNITO_ADMIN = new OAuthScope('aws.cognito.signin.user.admin');
/**
* Custom scope is one that you define for your own resource server in the Resource Servers.
* The format is 'resource-server-identifier/scope'.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-define-resource-servers.html
*/
public static custom(name: string) {
return new OAuthScope(name);
}
/**
* Adds a custom scope that's tied to a resource server in your stack
*/
public static resourceServer(server: IUserPoolResourceServer, scope: ResourceServerScope) {
return new OAuthScope(`${server.userPoolResourceServerId}/${scope.scopeName}`);
}
/**
* The name of this scope as recognized by CloudFormation.
* @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpoolclient.html#cfn-cognito-userpoolclient-allowedoauthscopes
*/
public readonly scopeName: string;
private constructor(scopeName: string) {
this.scopeName = scopeName;
}
}
/**
* Identity providers supported by the UserPoolClient
*/
export class UserPoolClientIdentityProvider {
/**
* Allow users to sign in using 'Sign In With Apple'.
* A `UserPoolIdentityProviderApple` must be attached to the user pool.
*/
public static readonly APPLE = new UserPoolClientIdentityProvider('SignInWithApple');
/**
* Allow users to sign in using 'Facebook Login'.
* A `UserPoolIdentityProviderFacebook` must be attached to the user pool.
*/
public static readonly FACEBOOK = new UserPoolClientIdentityProvider('Facebook');
/**
* Allow users to sign in using 'Google Login'.
* A `UserPoolIdentityProviderGoogle` must be attached to the user pool.
*/
public static readonly GOOGLE = new UserPoolClientIdentityProvider('Google');
/**
* Allow users to sign in using 'Login With Amazon'.
* A `UserPoolIdentityProviderAmazon` must be attached to the user pool.
*/
public static readonly AMAZON = new UserPoolClientIdentityProvider('LoginWithAmazon');
/**
* Allow users to sign in directly as a user of the User Pool
*/
public static readonly COGNITO = new UserPoolClientIdentityProvider('COGNITO');
/**
* Specify a provider not yet supported by the CDK.
* @param name name of the identity provider as recognized by CloudFormation property `SupportedIdentityProviders`
*/
public static custom(name: string) {
return new UserPoolClientIdentityProvider(name);
}
/** The name of the identity provider as recognized by CloudFormation property `SupportedIdentityProviders` */
public readonly name: string;
private constructor(name: string) {
this.name = name;
}
}
/**
* Options to create a UserPoolClient
*/
export interface UserPoolClientOptions {
/**
* Name of the application client
* @default - cloudformation generated name
*/
readonly userPoolClientName?: string;
/**
* Whether to generate a client secret
* @default false
*/
readonly generateSecret?: boolean;
/**
* The set of OAuth authentication flows to enable on the client
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html
* @default - all auth flows disabled
*/
readonly authFlows?: AuthFlow;
/**
* Turns off all OAuth interactions for this client.
* @default false
*/
readonly disableOAuth?: boolean;
/**
* OAuth settings for this client to interact with the app.
* An error is thrown when this is specified and `disableOAuth` is set.
* @default - see defaults in `OAuthSettings`. meaningless if `disableOAuth` is set.
*/
readonly oAuth?: OAuthSettings;
/**
* Whether Cognito returns a UserNotFoundException exception when the
* user does not exist in the user pool (false), or whether it returns
* another type of error that doesn't reveal the user's absence.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-managing-errors.html
* @default false
*/
readonly preventUserExistenceErrors?: boolean;
/**
* The list of identity providers that users should be able to use to sign in using this client.
*
* @default - supports all identity providers that are registered with the user pool. If the user pool and/or
* identity providers are imported, either specify this option explicitly or ensure that the identity providers are
* registered with the user pool using the `UserPool.registerIdentityProvider()` API.
*/
readonly supportedIdentityProviders?: UserPoolClientIdentityProvider[];
/**
* Validity of the ID token.
* Values between 5 minutes and 1 day are valid. The duration can not be longer than the refresh token validity.
* @see https://docs.aws.amazon.com/en_us/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html#amazon-cognito-user-pools-using-the-id-token
* @default Duration.minutes(60)
*/
readonly idTokenValidity?: Duration;
/**
* Validity of the refresh token.
* Values between 60 minutes and 10 years are valid.
* @see https://docs.aws.amazon.com/en_us/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html#amazon-cognito-user-pools-using-the-refresh-token
* @default Duration.days(30)
*/
readonly refreshTokenValidity?: Duration;
/**
* Validity of the access token.
* Values between 5 minutes and 1 day are valid. The duration can not be longer than the refresh token validity.
* @see https://docs.aws.amazon.com/en_us/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html#amazon-cognito-user-pools-using-the-access-token
* @default Duration.minutes(60)
*/
readonly accessTokenValidity?: Duration;
/**
* The set of attributes this client will be able to read.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html#user-pool-settings-attribute-permissions-and-scopes
* @default - all standard and custom attributes
*/
readonly readAttributes?: ClientAttributes;
/**
* The set of attributes this client will be able to write.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html#user-pool-settings-attribute-permissions-and-scopes
* @default - all standard and custom attributes
*/
readonly writeAttributes?: ClientAttributes;
/**
* Enable token revocation for this client.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/token-revocation.html#enable-token-revocation
* @default true for new user pool clients
*/
readonly enableTokenRevocation?: boolean;
}
/**
* Properties for the UserPoolClient construct
*/
export interface UserPoolClientProps extends UserPoolClientOptions {
/**
* The UserPool resource this client will have access to
*/
readonly userPool: IUserPool;
}
/**
* Represents a Cognito user pool client.
*/
export interface IUserPoolClient extends IResource {
/**
* Name of the application client
* @attribute
*/
readonly userPoolClientId: string;
}
/**
* Define a UserPool App Client
*/
export class UserPoolClient extends Resource implements IUserPoolClient {
/**
* Import a user pool client given its id.
*/
public static fromUserPoolClientId(scope: Construct, id: string, userPoolClientId: string): IUserPoolClient {
class Import extends Resource implements IUserPoolClient {
public readonly userPoolClientId = userPoolClientId;
}
return new Import(scope, id);
}
public readonly userPoolClientId: string;
/**
* The OAuth flows enabled for this client.
*/
public readonly oAuthFlows: OAuthFlows;
private readonly _userPoolClientName?: string;
/*
* Note to implementers: Two CloudFormation return values Name and ClientSecret are part of the spec.
* However, they have been explicity not implemented here. They are not documented in CloudFormation, and
* CloudFormation returns the following the string when these two attributes are 'GetAtt' - "attribute not supported
* at this time, please use the CLI or Console to retrieve this value".
* Awaiting updates from CloudFormation.
*/
constructor(scope: Construct, id: string, props: UserPoolClientProps) {
super(scope, id);
if (props.disableOAuth && props.oAuth) {
throw new Error('OAuth settings cannot be specified when disableOAuth is set.');
}
this.oAuthFlows = props.oAuth?.flows ?? {
implicitCodeGrant: true,
authorizationCodeGrant: true,
};
let callbackUrls: string[] | undefined = props.oAuth?.callbackUrls;
if (this.oAuthFlows.authorizationCodeGrant || this.oAuthFlows.implicitCodeGrant) {
if (callbackUrls === undefined) {
callbackUrls = ['https://example.com'];
} else if (callbackUrls.length === 0) {
throw new Error('callbackUrl must not be empty when codeGrant or implicitGrant OAuth flows are enabled.');
}
}
const resource = new CfnUserPoolClient(this, 'Resource', {
clientName: props.userPoolClientName,
generateSecret: props.generateSecret,
userPoolId: props.userPool.userPoolId,
explicitAuthFlows: this.configureAuthFlows(props),
allowedOAuthFlows: props.disableOAuth ? undefined : this.configureOAuthFlows(),
allowedOAuthScopes: props.disableOAuth ? undefined : this.configureOAuthScopes(props.oAuth),
callbackUrLs: callbackUrls && callbackUrls.length > 0 && !props.disableOAuth ? callbackUrls : undefined,
logoutUrLs: props.oAuth?.logoutUrls,
allowedOAuthFlowsUserPoolClient: !props.disableOAuth,
preventUserExistenceErrors: this.configurePreventUserExistenceErrors(props.preventUserExistenceErrors),
supportedIdentityProviders: this.configureIdentityProviders(props),
readAttributes: props.readAttributes?.attributes(),
writeAttributes: props.writeAttributes?.attributes(),
enableTokenRevocation: props.enableTokenRevocation,
});
this.configureTokenValidity(resource, props);
this.userPoolClientId = resource.ref;
this._userPoolClientName = props.userPoolClientName;
}
/**
* The client name that was specified via the `userPoolClientName` property during initialization,
* throws an error otherwise.
*/
public get userPoolClientName(): string {
if (this._userPoolClientName === undefined) {
throw new Error('userPoolClientName is available only if specified on the UserPoolClient during initialization');
}
return this._userPoolClientName;
}
private configureAuthFlows(props: UserPoolClientProps): string[] | undefined {
if (!props.authFlows) return undefined;
const authFlows: string[] = [];
if (props.authFlows.userPassword) { authFlows.push('ALLOW_USER_PASSWORD_AUTH'); }
if (props.authFlows.adminUserPassword) { authFlows.push('ALLOW_ADMIN_USER_PASSWORD_AUTH'); }
if (props.authFlows.custom) { authFlows.push('ALLOW_CUSTOM_AUTH'); }
if (props.authFlows.userSrp) { authFlows.push('ALLOW_USER_SRP_AUTH'); }
// refreshToken should always be allowed if authFlows are present
if (authFlows.length > 0) {
authFlows.push('ALLOW_REFRESH_TOKEN_AUTH');
}
if (authFlows.length === 0) {
return undefined;
}
return authFlows;
}
private configureOAuthFlows(): string[] | undefined {
if ((this.oAuthFlows.authorizationCodeGrant || this.oAuthFlows.implicitCodeGrant) && this.oAuthFlows.clientCredentials) {
throw new Error('clientCredentials OAuth flow cannot be selected along with codeGrant or implicitGrant.');
}
const oAuthFlows: string[] = [];
if (this.oAuthFlows.clientCredentials) { oAuthFlows.push('client_credentials'); }
if (this.oAuthFlows.implicitCodeGrant) { oAuthFlows.push('implicit'); }
if (this.oAuthFlows.authorizationCodeGrant) { oAuthFlows.push('code'); }
if (oAuthFlows.length === 0) {
return undefined;
}
return oAuthFlows;
}
private configureOAuthScopes(oAuth?: OAuthSettings): string[] {
const scopes = oAuth?.scopes ?? [OAuthScope.PROFILE, OAuthScope.PHONE, OAuthScope.EMAIL, OAuthScope.OPENID,
OAuthScope.COGNITO_ADMIN];
const scopeNames = new Set(scopes.map((x) => x.scopeName));
const autoOpenIdScopes = [OAuthScope.PHONE, OAuthScope.EMAIL, OAuthScope.PROFILE];
if (autoOpenIdScopes.reduce((agg, s) => agg || scopeNames.has(s.scopeName), false)) {
scopeNames.add(OAuthScope.OPENID.scopeName);
}
return Array.from(scopeNames);
}
private configurePreventUserExistenceErrors(prevent?: boolean): string | undefined {
if (prevent === undefined) {
return undefined;
}
return prevent ? 'ENABLED' : 'LEGACY';
}
private configureIdentityProviders(props: UserPoolClientProps): string[] | undefined {
let providers: string[];
if (!props.supportedIdentityProviders) {
const providerSet = new Set(props.userPool.identityProviders.map((p) => p.providerName));
providerSet.add('COGNITO');
providers = Array.from(providerSet);
} else {
providers = props.supportedIdentityProviders.map((p) => p.name);
}
if (providers.length === 0) { return undefined; }
return Array.from(providers);
}
private configureTokenValidity(resource: CfnUserPoolClient, props: UserPoolClientProps) {
this.validateDuration('idTokenValidity', Duration.minutes(5), Duration.days(1), props.idTokenValidity);
this.validateDuration('accessTokenValidity', Duration.minutes(5), Duration.days(1), props.accessTokenValidity);
this.validateDuration('refreshTokenValidity', Duration.minutes(60), Duration.days(10 * 365), props.refreshTokenValidity);
if (props.refreshTokenValidity) {
this.validateDuration('idTokenValidity', Duration.minutes(5), props.refreshTokenValidity, props.idTokenValidity);
this.validateDuration('accessTokenValidity', Duration.minutes(5), props.refreshTokenValidity, props.accessTokenValidity);
}
if (props.accessTokenValidity || props.idTokenValidity || props.refreshTokenValidity) {
resource.tokenValidityUnits = {
idToken: props.idTokenValidity ? 'minutes' : undefined,
accessToken: props.accessTokenValidity ? 'minutes' : undefined,
refreshToken: props.refreshTokenValidity ? 'minutes' : undefined,
};
};
resource.idTokenValidity = props.idTokenValidity ? props.idTokenValidity.toMinutes() : undefined;
resource.refreshTokenValidity = props.refreshTokenValidity ? props.refreshTokenValidity.toMinutes() : undefined;
resource.accessTokenValidity = props.accessTokenValidity ? props.accessTokenValidity.toMinutes() : undefined;
}
private validateDuration(name: string, min: Duration, max: Duration, value?: Duration) {
if (value === undefined) { return; }
if (value.toMilliseconds() < min.toMilliseconds() || value.toMilliseconds() > max.toMilliseconds()) {
throw new Error(`${name}: Must be a duration between ${min.toHumanString()} and ${max.toHumanString()} (inclusive); received ${value.toHumanString()}.`);
}
}
} | the_stack |
import {
ExportInfo,
Link,
Namespace,
Paths,
Repository,
RepositoryCollection,
RepositoryCreation,
RepositoryTypeCollection,
} from "@scm-manager/ui-types";
import { useMutation, useQuery, useQueryClient } from "react-query";
import { apiClient } from "./apiclient";
import { ApiResult, ApiResultWithFetching, useIndexJsonResource, useRequiredIndexLink } from "./base";
import { createQueryString } from "./utils";
import { objectLink, requiredLink } from "./links";
import { repoQueryKey } from "./keys";
import { concat } from "./urls";
import { useEffect, useState } from "react";
import { MissingLinkError, NotFoundError } from "./errors";
export type UseRepositoriesRequest = {
namespace?: Namespace;
search?: string;
page?: number | string;
disabled?: boolean;
};
export const useRepositories = (request?: UseRepositoriesRequest): ApiResult<RepositoryCollection> => {
const queryClient = useQueryClient();
const indexLink = useRequiredIndexLink("repositories");
const namespaceLink = (request?.namespace?._links.repositories as Link)?.href;
const link = namespaceLink || indexLink;
const queryParams: Record<string, string> = {
sortBy: "namespaceAndName",
};
if (request?.search) {
queryParams.q = request.search;
}
if (request?.page) {
queryParams.page = request.page.toString();
}
return useQuery<RepositoryCollection, Error>(
["repositories", request?.namespace?.namespace, request?.search || "", request?.page || 0],
() => apiClient.get(`${link}?${createQueryString(queryParams)}`).then((response) => response.json()),
{
enabled: !request?.disabled,
onSuccess: (repositories: RepositoryCollection) => {
// prepare single repository cache
repositories._embedded?.repositories.forEach((repository: Repository) => {
queryClient.setQueryData(["repository", repository.namespace, repository.name], repository);
});
},
}
);
};
type CreateRepositoryRequest = {
repository: RepositoryCreation;
initialize: boolean;
};
const createRepository = (link: string) => {
return (request: CreateRepositoryRequest) => {
let createLink = link;
if (request.initialize) {
createLink += "?initialize=true";
}
return apiClient
.post(createLink, request.repository, "application/vnd.scmm-repository+json;v=2")
.then((response) => {
const location = response.headers.get("Location");
if (!location) {
throw new Error("Server does not return required Location header");
}
return apiClient.get(location);
})
.then((response) => response.json());
};
};
export const useCreateRepository = () => {
const queryClient = useQueryClient();
// not really the index link,
// but a post to the collection is create by convention
const link = useRequiredIndexLink("repositories");
const { mutate, data, isLoading, error } = useMutation<Repository, Error, CreateRepositoryRequest>(
createRepository(link),
{
onSuccess: (repository) => {
queryClient.setQueryData(["repository", repository.namespace, repository.name], repository);
return queryClient.invalidateQueries(["repositories"]);
},
}
);
return {
create: (repository: RepositoryCreation, initialize: boolean) => {
mutate({ repository, initialize });
},
isLoading,
error,
repository: data,
};
};
// TODO increase staleTime, infinite?
export const useRepositoryTypes = () => useIndexJsonResource<RepositoryTypeCollection>("repositoryTypes");
export const useRepository = (namespace: string, name: string): ApiResult<Repository> => {
const link = useRequiredIndexLink("repositories");
return useQuery<Repository, Error>(["repository", namespace, name], () =>
apiClient.get(concat(link, namespace, name)).then((response) => response.json())
);
};
export type UseDeleteRepositoryOptions = {
onSuccess: (repository: Repository) => void;
};
export const useDeleteRepository = (options?: UseDeleteRepositoryOptions) => {
const queryClient = useQueryClient();
const { mutate, isLoading, error, data } = useMutation<unknown, Error, Repository>(
(repository) => {
const link = requiredLink(repository, "delete");
return apiClient.delete(link);
},
{
onSuccess: async (_, repository) => {
if (options?.onSuccess) {
options.onSuccess(repository);
}
await queryClient.removeQueries(repoQueryKey(repository));
await queryClient.invalidateQueries(["repositories"]);
},
}
);
return {
remove: (repository: Repository) => mutate(repository),
isLoading,
error,
isDeleted: !!data,
};
};
export const useUpdateRepository = () => {
const queryClient = useQueryClient();
const { mutate, isLoading, error, data } = useMutation<unknown, Error, Repository>(
(repository) => {
const link = requiredLink(repository, "update");
return apiClient.put(link, repository, "application/vnd.scmm-repository+json;v=2");
},
{
onSuccess: async (_, repository) => {
await queryClient.invalidateQueries(repoQueryKey(repository));
await queryClient.invalidateQueries(["repositories"]);
},
}
);
return {
update: (repository: Repository) => mutate(repository),
isLoading,
error,
isUpdated: !!data,
};
};
export const useArchiveRepository = () => {
const queryClient = useQueryClient();
const { mutate, isLoading, error, data } = useMutation<unknown, Error, Repository>(
(repository) => {
const link = requiredLink(repository, "archive");
return apiClient.post(link);
},
{
onSuccess: async (_, repository) => {
await queryClient.invalidateQueries(repoQueryKey(repository));
await queryClient.invalidateQueries(["repositories"]);
},
}
);
return {
archive: (repository: Repository) => mutate(repository),
isLoading,
error,
isArchived: !!data,
};
};
export const useUnarchiveRepository = () => {
const queryClient = useQueryClient();
const { mutate, isLoading, error, data } = useMutation<unknown, Error, Repository>(
(repository) => {
const link = requiredLink(repository, "unarchive");
return apiClient.post(link);
},
{
onSuccess: async (_, repository) => {
await queryClient.invalidateQueries(repoQueryKey(repository));
await queryClient.invalidateQueries(["repositories"]);
},
}
);
return {
unarchive: (repository: Repository) => mutate(repository),
isLoading,
error,
isUnarchived: !!data,
};
};
export const useRunHealthCheck = () => {
const queryClient = useQueryClient();
const { mutate, isLoading, error, data } = useMutation<unknown, Error, Repository>(
(repository) => {
const link = requiredLink(repository, "runHealthCheck");
return apiClient.post(link);
},
{
onSuccess: async (_, repository) => {
await queryClient.invalidateQueries(repoQueryKey(repository));
},
}
);
return {
runHealthCheck: (repository: Repository) => mutate(repository),
isLoading,
error,
isRunning: !!data,
};
};
export const useExportInfo = (repository: Repository): ApiResultWithFetching<ExportInfo> => {
const link = requiredLink(repository, "exportInfo");
//TODO Refetch while exporting to update the page
const { isLoading, isFetching, error, data } = useQuery<ExportInfo, Error>(
["repository", repository.namespace, repository.name, "exportInfo"],
() => apiClient.get(link).then((response) => response.json()),
{}
);
return {
isLoading,
isFetching,
error: error instanceof NotFoundError ? null : error,
data,
};
};
type ExportOptions = {
compressed: boolean;
withMetadata: boolean;
password?: string;
};
type ExportRepositoryMutateOptions = {
repository: Repository;
options: ExportOptions;
};
const EXPORT_MEDIA_TYPE = "application/vnd.scmm-repositoryExport+json;v=2";
export const useExportRepository = () => {
const queryClient = useQueryClient();
const [intervalId, setIntervalId] = useState<ReturnType<typeof setTimeout>>();
useEffect(() => {
return () => {
if (intervalId) {
clearInterval(intervalId);
}
};
}, [intervalId]);
const { mutate, isLoading, error, data } = useMutation<ExportInfo, Error, ExportRepositoryMutateOptions>(
({ repository, options }) => {
const infolink = requiredLink(repository, "exportInfo");
let link = requiredLink(repository, options.withMetadata ? "fullExport" : "export");
if (options.compressed) {
link += "?compressed=true";
}
return apiClient
.post(link, { password: options.password, async: true }, EXPORT_MEDIA_TYPE)
.then(() => queryClient.invalidateQueries(repoQueryKey(repository)))
.then(() => queryClient.invalidateQueries(["repositories"]))
.then(() => {
return new Promise<ExportInfo>((resolve, reject) => {
const id = setInterval(() => {
apiClient
.get(infolink)
.then((r) => r.json())
.then((info: ExportInfo) => {
if (info._links.download) {
clearInterval(id);
resolve(info);
}
})
.catch((e) => {
clearInterval(id);
reject(e);
});
}, 1000);
setIntervalId(id);
});
});
},
{
onSuccess: async (_, { repository }) => {
await queryClient.invalidateQueries(repoQueryKey(repository));
await queryClient.invalidateQueries(["repositories"]);
},
}
);
return {
exportRepository: (repository: Repository, options: ExportOptions) => mutate({ repository, options }),
isLoading,
error,
data,
};
};
export const usePaths = (repository: Repository, revision: string): ApiResult<Paths> => {
const link = requiredLink(repository, "paths").replace("{revision}", revision);
return useQuery<Paths, Error>(repoQueryKey(repository, "paths", revision), () =>
apiClient.get(link).then((response) => response.json())
);
};
type RenameRepositoryRequest = {
name: string;
namespace: string;
};
export const useRenameRepository = (repository: Repository) => {
const queryClient = useQueryClient();
const url = objectLink(repository, "renameWithNamespace") || objectLink(repository, "rename");
if (!url) {
throw new MissingLinkError(`could not find rename link on repository ${repository.namespace}/${repository.name}`);
}
const { mutate, isLoading, error, data } = useMutation<unknown, Error, RenameRepositoryRequest>(
({ name, namespace }) => apiClient.post(url, { namespace, name }, "application/vnd.scmm-repository+json;v=2"),
{
onSuccess: () => queryClient.removeQueries(repoQueryKey(repository)),
}
);
return {
renameRepository: (namespace: string, name: string) => mutate({ namespace, name }),
isLoading,
error,
isRenamed: !!data,
};
}; | the_stack |
import React, { useCallback, memo } from 'react'
import { Button, ButtonSize, ButtonType, IconArrowWhite } from '@audius/stems'
import { useHistory } from 'react-router'
import { ReactComponent as IconAlbum } from 'assets/img/iconAlbum.svg'
import { ReactComponent as IconCollectibles } from 'assets/img/iconCollectibles.svg'
import { ReactComponent as IconNote } from 'assets/img/iconNote.svg'
import { ReactComponent as IconPlaylists } from 'assets/img/iconPlaylists.svg'
import { ReactComponent as IconReposts } from 'assets/img/iconRepost.svg'
import { Name } from 'common/models/Analytics'
import { Collection } from 'common/models/Collection'
import { ID, UID } from 'common/models/Identifiers'
import { CoverPhotoSizes, ProfilePictureSizes } from 'common/models/ImageSizes'
import Status from 'common/models/Status'
import { User } from 'common/models/User'
import Card from 'components/card/desktop/Card'
import CoverPhoto from 'components/general/CoverPhoto'
import Mask from 'components/general/Mask'
import NavBanner from 'components/general/NavBanner'
import Page from 'components/general/Page'
import StatBanner from 'components/general/StatBanner'
import UploadChip from 'components/upload/UploadChip'
import CollectiblesPage from 'containers/collectibles/components/CollectiblesPage'
import CardLineup from 'containers/lineup/CardLineup'
import Lineup from 'containers/lineup/Lineup'
import { MIN_COLLECTIBLES_TIER } from 'containers/profile-page/ProfilePageProvider'
import EmptyTab from 'containers/profile-page/components/EmptyTab'
import { feedActions } from 'containers/profile-page/store/lineups/feed/actions'
import { tracksActions } from 'containers/profile-page/store/lineups/tracks/actions'
import { ProfileUser, Tabs } from 'containers/profile-page/store/types'
import ConnectedProfileCompletionHeroCard from 'containers/profile-progress/ConnectedProfileCompletionHeroCard'
import { useSelectTierInfo } from 'containers/user-badges/hooks'
import { badgeTiers } from 'containers/user-badges/utils'
import useTabs, { useTabRecalculator } from 'hooks/useTabs/useTabs'
import { LineupState } from 'models/common/Lineup'
import { make, useRecord } from 'store/analytics/actions'
import {
albumPage,
playlistPage,
profilePage,
fullProfilePage,
UPLOAD_PAGE,
UPLOAD_ALBUM_PAGE,
UPLOAD_PLAYLIST_PAGE
} from 'utils/route'
import { DeactivatedProfileTombstone } from '../DeactivatedProfileTombstone'
import styles from './ProfilePage.module.css'
import ProfileWrapping from './ProfileWrapping'
export type ProfilePageProps = {
// State
editMode: boolean
shouldMaskContent: boolean
areArtistRecommendationsVisible: boolean
mostUsedTags: string[]
// Computed
accountUserId: ID | null
isArtist: boolean
isOwner: boolean
userId: ID | null
handle: string
verified: boolean
created: string
name: string
bio: string
location: string
twitterHandle: string
instagramHandle: string
tikTokHandle: string
twitterVerified?: boolean
instagramVerified?: boolean
website: string
donation: string
coverPhotoSizes: CoverPhotoSizes | null
updatedCoverPhoto: { error: boolean; url: string }
profilePictureSizes: ProfilePictureSizes | null
updatedProfilePicture: { error: boolean; url: string }
hasProfilePicture: boolean
followers: User[]
followersLoading: boolean
followees: User[]
followeesLoading: boolean
followeeFollows: User[]
activeTab: Tabs | null
followeeFollowsCount: number
followeeFollowsLoading: boolean
dropdownDisabled: boolean
following: boolean
isSubscribed: boolean
mode: string
stats: Array<{ number: number; title: string; key: string }>
profile: ProfileUser | null
albums: Collection[] | null
playlists: Collection[] | null
status: Status
goToRoute: (route: string) => void
artistTracks: LineupState<{ id: ID }>
playArtistTrack: (uid: UID) => void
pauseArtistTrack: () => void
// Feed
userFeed: LineupState<{ id: ID }>
playUserFeedTrack: (uid: UID) => void
pauseUserFeedTrack: () => void
// Methods
onFollow: () => void
onUnfollow: () => void
updateName: (name: string) => void
updateBio: (bio: string) => void
updateLocation: (location: string) => void
updateTwitterHandle: (handle: string) => void
updateInstagramHandle: (handle: string) => void
updateTikTokHandle: (handle: string) => void
updateWebsite: (website: string) => void
updateDonation: (donation: string) => void
changeTab: (tab: Tabs) => void
getLineupProps: (lineup: any) => any
onEdit: () => void
onSave: () => void
onShare: () => void
onCancel: () => void
onSortByRecent: () => void
onSortByPopular: () => void
loadMoreArtistTracks: (offset: number, limit: number) => void
loadMoreUserFeed: (offset: number, limit: number) => void
formatCardSecondaryText: (
saves: number,
tracks: number,
isPrivate?: boolean
) => string
fetchFollowers: () => void
fetchFollowees: () => void
fetchFolloweeFollows: () => void
openCreatePlaylistModal: () => void
updateProfile: (metadata: any) => void
updateProfilePicture: (
selectedFiles: any,
source: 'original' | 'unsplash' | 'url'
) => Promise<void>
updateCoverPhoto: (
selectedFiles: any,
source: 'original' | 'unsplash' | 'url'
) => Promise<void>
setNotificationSubscription: (userId: ID, isSubscribed: boolean) => void
didChangeTabsFrom: (prevLabel: string, currentLabel: string) => void
onCloseArtistRecommendations: () => void
}
const ProfilePage = ({
isOwner,
profile,
albums,
playlists,
status,
goToRoute,
// Tracks
artistTracks,
playArtistTrack,
pauseArtistTrack,
getLineupProps,
// Feed
userFeed,
playUserFeedTrack,
pauseUserFeedTrack,
formatCardSecondaryText,
loadMoreUserFeed,
loadMoreArtistTracks,
openCreatePlaylistModal,
updateProfile,
mostUsedTags,
onFollow,
onUnfollow,
updateName,
updateBio,
updateLocation,
updateTwitterHandle,
updateInstagramHandle,
updateTikTokHandle,
updateWebsite,
updateDonation,
updateProfilePicture,
updateCoverPhoto,
changeTab,
mode,
stats,
onEdit,
onSave,
onShare,
onCancel,
onSortByRecent,
onSortByPopular,
fetchFollowers,
fetchFollowees,
fetchFolloweeFollows,
isArtist,
status: profileLoadingStatus,
activeTab,
shouldMaskContent,
editMode,
areArtistRecommendationsVisible,
onCloseArtistRecommendations,
accountUserId,
userId,
handle,
verified,
created,
name,
bio,
location,
twitterHandle,
instagramHandle,
tikTokHandle,
twitterVerified,
instagramVerified,
website,
donation,
coverPhotoSizes,
updatedCoverPhoto,
profilePictureSizes,
updatedProfilePicture,
hasProfilePicture,
followers,
followersLoading,
followees,
followeesLoading,
followeeFollows,
followeeFollowsCount,
followeeFollowsLoading,
dropdownDisabled,
following,
isSubscribed,
setNotificationSubscription,
didChangeTabsFrom
}: ProfilePageProps) => {
const renderProfileCompletionCard = () => {
return isOwner ? <ConnectedProfileCompletionHeroCard /> : null
}
const record = useRecord()
const onClickUploadAlbum = useCallback(() => {
goToRoute(UPLOAD_ALBUM_PAGE)
record(make(Name.TRACK_UPLOAD_OPEN, { source: 'profile' }))
}, [goToRoute, record])
const onClickUploadPlaylist = useCallback(() => {
goToRoute(UPLOAD_PLAYLIST_PAGE)
record(make(Name.TRACK_UPLOAD_OPEN, { source: 'profile' }))
}, [goToRoute, record])
const onClickUploadTrack = useCallback(() => {
goToRoute(UPLOAD_PAGE)
record(make(Name.TRACK_UPLOAD_OPEN, { source: 'profile' }))
}, [goToRoute, record])
const { tierNumber } = useSelectTierInfo(userId ?? 0)
const profileHasCollectiblesTierRequirement =
tierNumber >= badgeTiers.findIndex(t => t.tier === MIN_COLLECTIBLES_TIER)
const profileHasCollectibles =
profile?.collectibleList?.length || profile?.solanaCollectibleList?.length
const profileNeverSetCollectiblesOrder = !profile?.collectibles
const profileHasNonEmptyCollectiblesOrder =
profile?.collectibles?.order?.length ?? false
const profileHasVisibleImageOrVideoCollectibles =
profileHasCollectibles &&
(profileNeverSetCollectiblesOrder || profileHasNonEmptyCollectiblesOrder)
const didCollectiblesLoadAndWasEmpty =
profileHasCollectibles && !profileHasNonEmptyCollectiblesOrder
const isUserOnTheirProfile = accountUserId === userId
const tabRecalculator = useTabRecalculator()
const recalculate = useCallback(() => {
tabRecalculator.recalculate()
}, [tabRecalculator])
const getArtistProfileContent = () => {
if (!profile || !albums || !playlists) return { headers: [], elements: [] }
const albumCards = albums.map((album, index) => (
<Card
key={index}
size='medium'
handle={profile.handle}
playlistName={album.playlist_name}
playlistId={album.playlist_id}
id={album.playlist_id}
userId={album.playlist_owner_id}
isPublic={!album.is_private}
imageSize={album._cover_art_sizes}
isPlaylist={!album.is_album}
primaryText={album.playlist_name}
// link={fullAlbumPage(profile.handle, album.playlist_name, album.playlist_id)}
secondaryText={formatCardSecondaryText(
album.save_count,
album.playlist_contents.track_ids.length
)}
cardCoverImageSizes={album._cover_art_sizes}
isReposted={album.has_current_user_reposted}
isSaved={album.has_current_user_saved}
onClick={() =>
goToRoute(
albumPage(profile.handle, album.playlist_name, album.playlist_id)
)
}
/>
))
if (isOwner) {
albumCards.unshift(
<UploadChip
key='upload-chip'
type='album'
variant='card'
onClick={onClickUploadAlbum}
isFirst={albumCards.length === 0}
/>
)
}
const playlistCards = playlists.map((playlist, index) => (
<Card
key={index}
size='medium'
handle={profile.handle}
playlistName={playlist.playlist_name}
playlistId={playlist.playlist_id}
id={playlist.playlist_id}
imageSize={playlist._cover_art_sizes}
userId={playlist.playlist_owner_id}
isPublic={!playlist.is_private}
// isAlbum={playlist.is_album}
primaryText={playlist.playlist_name}
// link={fullPlaylistPage(profile.handle, playlist.playlist_name, playlist.playlist_id)}
secondaryText={formatCardSecondaryText(
playlist.save_count,
playlist.playlist_contents.track_ids.length,
playlist.is_private
)}
cardCoverImageSizes={playlist._cover_art_sizes}
isReposted={playlist.has_current_user_reposted}
isSaved={playlist.has_current_user_saved}
onClick={() =>
goToRoute(
playlistPage(
profile.handle,
playlist.playlist_name,
playlist.playlist_id
)
)
}
/>
))
if (isOwner) {
playlistCards.unshift(
<UploadChip
key='upload-chip'
type='playlist'
variant='card'
onClick={onClickUploadPlaylist}
isArtist
isFirst={playlistCards.length === 0}
/>
)
}
const trackUploadChip = isOwner ? (
<UploadChip
key='upload-chip'
type='track'
variant='tile'
onClick={onClickUploadTrack}
/>
) : null
const headers = [
{ icon: <IconNote />, text: Tabs.TRACKS, label: Tabs.TRACKS },
{ icon: <IconAlbum />, text: Tabs.ALBUMS, label: Tabs.ALBUMS },
{
icon: <IconPlaylists />,
text: Tabs.PLAYLISTS,
label: Tabs.PLAYLISTS
},
{ icon: <IconReposts />, text: Tabs.REPOSTS, label: Tabs.REPOSTS }
]
const elements = [
<div key={Tabs.TRACKS} className={styles.tiles}>
{renderProfileCompletionCard()}
{status !== Status.LOADING ? (
artistTracks.status !== Status.LOADING &&
artistTracks.entries.length === 0 ? (
<EmptyTab
isOwner={isOwner}
name={profile.name}
text={'uploaded any tracks'}
/>
) : (
<Lineup
{...getLineupProps(artistTracks)}
extraPrecedingElement={trackUploadChip}
animateLeadingElement
leadingElementId={profile._artist_pick}
loadMore={loadMoreArtistTracks}
playTrack={playArtistTrack}
pauseTrack={pauseArtistTrack}
actions={tracksActions}
/>
)
) : null}
</div>,
<div key={Tabs.ALBUMS} className={styles.cards}>
{albums.length === 0 && !isOwner ? (
<EmptyTab
isOwner={isOwner}
name={profile.name}
text={'created any albums'}
/>
) : (
<CardLineup cardsClassName={styles.cardLineup} cards={albumCards} />
)}
</div>,
<div key={Tabs.PLAYLISTS} className={styles.cards}>
{playlists.length === 0 && !isOwner ? (
<EmptyTab
isOwner={isOwner}
name={profile.name}
text={'created any playlists'}
/>
) : (
<CardLineup
cardsClassName={styles.cardLineup}
cards={playlistCards}
/>
)}
</div>,
<div key={Tabs.REPOSTS} className={styles.tiles}>
{status !== Status.LOADING ? (
(userFeed.status !== Status.LOADING &&
userFeed.entries.length === 0) ||
profile.repost_count === 0 ? (
<EmptyTab
isOwner={isOwner}
name={profile.name}
text={'reposted anything'}
/>
) : (
<Lineup
{...getLineupProps(userFeed)}
loadMore={loadMoreUserFeed}
playTrack={playUserFeedTrack}
pauseTrack={pauseUserFeedTrack}
actions={feedActions}
/>
)
) : null}
</div>
]
if (
// `has_collectibles` is a shortcut that is only true iff the user has a modified collectibles state
(profile?.has_collectibles &&
profileHasCollectiblesTierRequirement &&
!didCollectiblesLoadAndWasEmpty) ||
(profileHasCollectiblesTierRequirement &&
(profileHasVisibleImageOrVideoCollectibles ||
(profileHasCollectibles && isUserOnTheirProfile)))
) {
headers.push({
icon: <IconCollectibles />,
text: Tabs.COLLECTIBLES,
label: Tabs.COLLECTIBLES
})
elements.push(
<div key={Tabs.COLLECTIBLES} className={styles.tiles}>
<CollectiblesPage
userId={userId}
name={name}
isMobile={false}
isUserOnTheirProfile={isUserOnTheirProfile}
profile={profile}
updateProfile={updateProfile}
updateProfilePicture={updateProfilePicture}
onLoad={recalculate}
onSave={onSave}
/>
</div>
)
}
return { headers, elements }
}
const toggleNotificationSubscription = () => {
if (!userId) return
setNotificationSubscription(userId, !isSubscribed)
}
const getUserProfileContent = () => {
if (!profile || !playlists) return { headers: [], elements: [] }
const playlistCards = playlists.map((playlist, index) => (
<Card
key={index}
size='medium'
id={playlist.playlist_id}
userId={playlist.playlist_owner_id}
imageSize={playlist._cover_art_sizes}
handle={profile.handle}
playlistId={playlist.playlist_id}
isPublic={!playlist.is_private}
playlistName={playlist.playlist_name}
// isAlbum={playlist.is_album}
primaryText={playlist.playlist_name}
secondaryText={formatCardSecondaryText(
playlist.save_count,
playlist.playlist_contents.track_ids.length,
playlist.is_private
)}
// link={fullPlaylistPage(profile.handle, playlist.playlist_name, playlist.playlist_id)}
isReposted={playlist.has_current_user_reposted}
isSaved={playlist.has_current_user_saved}
cardCoverImageSizes={playlist._cover_art_sizes}
onClick={() =>
goToRoute(
playlistPage(
profile.handle,
playlist.playlist_name,
playlist.playlist_id
)
)
}
/>
))
playlistCards.unshift(
<UploadChip
type='playlist'
variant='card'
onClick={openCreatePlaylistModal}
isFirst={playlistCards.length === 0}
/>
)
const headers = [
{ icon: <IconReposts />, text: Tabs.REPOSTS, label: Tabs.REPOSTS },
{ icon: <IconPlaylists />, text: Tabs.PLAYLISTS, label: Tabs.PLAYLISTS }
]
const elements = [
<div key={Tabs.REPOSTS} className={styles.tiles}>
{renderProfileCompletionCard()}
{(userFeed.status !== Status.LOADING &&
userFeed.entries.length === 0) ||
profile.repost_count === 0 ? (
<EmptyTab
isOwner={isOwner}
name={profile.name}
text={'reposted anything'}
/>
) : (
<Lineup
{...getLineupProps(userFeed)}
count={profile.repost_count}
loadMore={loadMoreUserFeed}
playTrack={playUserFeedTrack}
pauseTrack={pauseUserFeedTrack}
actions={feedActions}
/>
)}
</div>,
<div key={Tabs.PLAYLISTS} className={styles.cards}>
{playlists.length === 0 && !isOwner ? (
<EmptyTab
isOwner={isOwner}
name={profile.name}
text={'created any playlists'}
/>
) : (
<CardLineup
cardsClassName={styles.cardLineup}
cards={playlistCards}
/>
)}
</div>
]
if (
(profile?.has_collectibles &&
profileHasCollectiblesTierRequirement &&
!didCollectiblesLoadAndWasEmpty) ||
(profileHasCollectiblesTierRequirement &&
(profileHasVisibleImageOrVideoCollectibles ||
(profileHasCollectibles && isUserOnTheirProfile)))
) {
headers.push({
icon: <IconCollectibles />,
text: Tabs.COLLECTIBLES,
label: Tabs.COLLECTIBLES
})
elements.push(
<div key={Tabs.COLLECTIBLES} className={styles.tiles}>
<CollectiblesPage
userId={userId}
name={name}
isMobile={false}
isUserOnTheirProfile={isUserOnTheirProfile}
profile={profile}
updateProfile={updateProfile}
updateProfilePicture={updateProfilePicture}
onLoad={recalculate}
onSave={onSave}
/>
</div>
)
}
return { headers, elements }
}
const { headers, elements } = profile
? isArtist
? getArtistProfileContent()
: getUserProfileContent()
: { headers: [], elements: [] }
const { tabs, body } = useTabs({
didChangeTabsFrom,
isMobile: false,
tabs: headers,
tabRecalculator,
bodyClassName: styles.tabBody,
initialTab: activeTab || undefined,
elements
})
return (
<Page
title={name && handle ? `${name} (${handle})` : ''}
description={bio}
canonicalUrl={fullProfilePage(handle)}
variant='flush'
contentClassName={styles.profilePageWrapper}
scrollableSearch
>
<div className={styles.headerWrapper}>
<ProfileWrapping
userId={userId}
isDeactivated={profile?.is_deactivated}
loading={status === Status.LOADING}
verified={verified}
profilePictureSizes={profilePictureSizes}
updatedProfilePicture={updatedProfilePicture}
hasProfilePicture={hasProfilePicture}
followeeFollows={followeeFollows}
followeeFollowsCount={followeeFollowsCount}
followeeFollowsLoading={followeeFollowsLoading}
loadMoreFolloweeFollows={fetchFolloweeFollows}
isOwner={isOwner}
isArtist={isArtist}
editMode={editMode}
name={name}
handle={handle}
bio={bio}
location={location}
twitterHandle={twitterHandle}
instagramHandle={instagramHandle}
tikTokHandle={tikTokHandle}
twitterVerified={twitterVerified}
instagramVerified={instagramVerified}
website={website}
donation={donation}
created={created}
tags={mostUsedTags || []}
onUpdateName={updateName}
onUpdateProfilePicture={updateProfilePicture}
onUpdateBio={updateBio}
onUpdateLocation={updateLocation}
onUpdateTwitterHandle={updateTwitterHandle}
onUpdateInstagramHandle={updateInstagramHandle}
onUpdateTikTokHandle={updateTikTokHandle}
onUpdateWebsite={updateWebsite}
onUpdateDonation={updateDonation}
goToRoute={goToRoute}
/>
<CoverPhoto
userId={userId}
coverPhotoSizes={
profile && profile.is_deactivated ? null : coverPhotoSizes
}
updatedCoverPhoto={updatedCoverPhoto ? updatedCoverPhoto.url : ''}
error={updatedCoverPhoto ? updatedCoverPhoto.error : false}
loading={profileLoadingStatus === Status.LOADING}
onDrop={updateCoverPhoto}
edit={editMode}
darken={editMode}
/>
<Mask show={editMode} zIndex={2}>
<StatBanner
empty={!profile || profile.is_deactivated}
mode={mode}
stats={stats}
userId={accountUserId}
handle={handle}
profileId={profile?.user_id}
areArtistRecommendationsVisible={areArtistRecommendationsVisible}
onCloseArtistRecommendations={onCloseArtistRecommendations}
onClickArtistName={(handle: string) => {
goToRoute(profilePage(handle))
}}
onEdit={onEdit}
onSave={onSave}
onShare={onShare}
onCancel={onCancel}
following={following}
followers={followers}
followees={followees}
followersLoading={followersLoading}
followeesLoading={followeesLoading}
loadMoreFollowers={fetchFollowers}
loadMoreFollowees={fetchFollowees}
isSubscribed={isSubscribed}
onToggleSubscribe={toggleNotificationSubscription}
onFollow={onFollow}
onUnfollow={onUnfollow}
/>
<div className={styles.inset}>
<NavBanner
empty={!profile || profile.is_deactivated}
tabs={tabs}
dropdownDisabled={dropdownDisabled}
onChange={changeTab}
activeTab={activeTab}
isArtist={isArtist}
onSortByRecent={onSortByRecent}
onSortByPopular={onSortByPopular}
shouldMaskContent={shouldMaskContent}
/>
<div className={styles.content}>
{profile && profile.is_deactivated ? (
<DeactivatedProfileTombstone goToRoute={goToRoute} />
) : (
body
)}
</div>
</div>
</Mask>
</div>
</Page>
)
}
export default memo(ProfilePage) | the_stack |
import * as React from "react";
import "./AddItemPanel.scss";
import { Project } from "../../Models/PortfolioPlanningQueryModels";
import {
IProject,
IAddItems,
IAddItemPanelProjectItems,
LoadingStatus,
IAddItem,
IProjectConfiguration
} from "../../Contracts";
import { PortfolioPlanningDataService } from "../../Common/Services/PortfolioPlanningDataService";
import { Panel } from "azure-devops-ui/Panel";
import { Dropdown, DropdownCallout } from "azure-devops-ui/Dropdown";
import { Location } from "azure-devops-ui/Utilities/Position";
import { IListBoxItem } from "azure-devops-ui/ListBox";
import {
DetailsList,
DetailsListLayoutMode,
Selection,
IColumn,
CheckboxVisibility
} from "office-ui-fabric-react/lib/DetailsList";
import { FormItem } from "azure-devops-ui/FormItem";
import { Spinner, SpinnerSize } from "azure-devops-ui/Spinner";
import { CollapsiblePanel } from "../../Common/Components/CollapsiblePanel";
import { MessageBar, MessageBarType } from "office-ui-fabric-react/lib/MessageBar";
import { ProjectConfigurationDataService } from "../../Common/Services/ProjectConfigurationDataService";
import { Image, IImageProps, ImageFit } from "office-ui-fabric-react/lib/Image";
import { PortfolioTelemetry } from "../../Common/Utilities/Telemetry";
import { Tooltip } from "azure-devops-ui/TooltipEx";
import { TextField, TextFieldWidth, TextFieldStyle } from "azure-devops-ui/TextField";
export interface IAddItemPanelProps {
planId: string;
epicsInPlan: { [epicId: number]: number };
onCloseAddItemPanel: () => void;
onAddItems: (itemsToAdd: IAddItems) => void;
}
interface IAddItemPanelState {
projects: IListBoxItem[];
selectedProject: IProject;
selectedProjectBacklogConfiguration: IProjectConfiguration;
/**
* Map of work items to display, grouped by work item type.
*/
workItemsByLevel: IAddItemPanelProjectItems;
selectedWorkItems: { [workItemTypeKey: string]: { [workItemId: number]: IAddItem } };
loadingProjects: boolean;
loadingProjectConfiguration: boolean;
errorMessage: string;
}
export class AddItemPanel extends React.Component<IAddItemPanelProps, IAddItemPanelState> {
private _selectionByWorkItemType: { [workItemTypeKey: string]: Selection } = {};
private _projectConfigurationsCache: { [projectIdKey: string]: IProjectConfiguration } = {};
/**
* Number of work items over which search is available for a work item type section.
*/
private static readonly WORKITEMTYPE_SEARCH_THRESHOLD: number = 20;
constructor(props) {
super(props);
this.state = {
projects: [],
selectedProject: null,
selectedProjectBacklogConfiguration: null,
workItemsByLevel: {},
selectedWorkItems: {},
loadingProjects: true,
loadingProjectConfiguration: false,
errorMessage: ""
};
this._getAllProjects().then(
projects => {
const allProjects = [...this.state.projects];
projects.forEach(project => {
allProjects.push({
id: project.ProjectSK,
text: project.ProjectName
});
});
this.setState({
projects: allProjects,
loadingProjects: false
});
},
error =>
this.setState({
errorMessage: JSON.stringify(error),
loadingProjects: false
})
);
}
public render() {
return (
<Panel
onDismiss={() => this.props.onCloseAddItemPanel()}
showSeparator={true}
titleProps={{ text: "Add items" }}
footerButtonProps={[
{
text: "Cancel",
onClick: () => this.props.onCloseAddItemPanel()
},
{
text: "Add",
primary: true,
onClick: () => this._onAddEpics(),
disabled: Object.keys(this.state.selectedWorkItems).length === 0
}
]}
>
<div className="add-item-panel-container">
{this._renderProjectPicker()}
<div>{this._renderEpics()}</div>
</div>
</Panel>
);
}
private _renderProjectPicker = () => {
const { loadingProjects } = this.state;
if (loadingProjects) {
return <Spinner label="Loading Projects..." size={SpinnerSize.large} className="loading-projects" />;
} else {
return (
<FormItem message={this.state.errorMessage} error={!!this.state.errorMessage}>
<div className="projects-label">Projects</div>
<Dropdown
className="project-picker"
placeholder="Select a project"
items={this.state.projects}
disabled={this.state.loadingProjectConfiguration}
onSelect={this._onProjectSelected}
renderCallout={props => (
<DropdownCallout
{...props}
dropdownOrigin={{
horizontal: Location.start,
vertical: Location.start
}}
anchorOrigin={{
horizontal: Location.start,
vertical: Location.start
}}
/>
)}
/>
</FormItem>
);
}
};
private _onProjectSelected = async (event: React.SyntheticEvent<HTMLElement>, item: IListBoxItem<{}>) => {
// Clear selection objects for DetailsList.
this._selectionByWorkItemType = {};
this.setState({
selectedProject: {
id: item.id,
title: item.text,
configuration: null
},
loadingProjectConfiguration: true
});
let errorMessage: string = null;
try {
const projectConfiguration = await this._getProjectConfiguration(item.id);
PortfolioTelemetry.getInstance().TrackAddItemPanelProjectSelected(item.id, projectConfiguration);
const firstWorkItemType = projectConfiguration.orderedWorkItemTypes[0];
const firstWorkItemTypeKey = firstWorkItemType.toLowerCase();
const workItemsOfType = await PortfolioPlanningDataService.getInstance().getAllWorkItemsOfTypeInProject(
item.id,
firstWorkItemType
);
PortfolioTelemetry.getInstance().TrackAddItemPanelWorkItemsOfTypeCount(
item.id,
firstWorkItemType,
workItemsOfType.workItems!.length || 0
);
const projectItems: IAddItemPanelProjectItems = {};
// Adding all work item types in project.
projectConfiguration.orderedWorkItemTypes.forEach(wiType => {
const wiTypeKey = wiType.toLowerCase();
projectItems[wiTypeKey] = {
workItemTypeDisplayName: wiType,
loadingStatus: LoadingStatus.NotLoaded,
loadingErrorMessage: null,
items: null,
workItemsFoundInProject: 0,
searchKeyword: null
};
});
// Populating work items for first type.
const items: { [workItemId: number]: IAddItem } = {};
if (workItemsOfType.exceptionMessage && workItemsOfType.exceptionMessage.length > 0) {
projectItems[firstWorkItemTypeKey] = {
workItemTypeDisplayName: firstWorkItemType,
loadingStatus: LoadingStatus.Loaded,
loadingErrorMessage: workItemsOfType.exceptionMessage,
items: null,
workItemsFoundInProject: 0,
searchKeyword: null
};
} else {
workItemsOfType.workItems.forEach(workItem => {
// Only show work items not yet included in the plan.
if (!this.props.epicsInPlan[workItem.WorkItemId]) {
items[workItem.WorkItemId] = {
id: workItem.WorkItemId,
key: workItem.WorkItemId,
text: workItem.Title,
workItemType: workItem.WorkItemType,
hide: false
};
}
});
projectItems[firstWorkItemTypeKey] = {
workItemTypeDisplayName: firstWorkItemType,
loadingStatus: LoadingStatus.Loaded,
loadingErrorMessage: null,
items,
workItemsFoundInProject: workItemsOfType.workItems.length,
searchKeyword: null
};
}
this.setState({
workItemsByLevel: projectItems,
loadingProjectConfiguration: false,
selectedProjectBacklogConfiguration: projectConfiguration,
errorMessage: null
});
} catch (error) {
errorMessage = JSON.stringify(error, null, " ");
console.log(errorMessage);
} finally {
this.setState({
errorMessage,
loadingProjectConfiguration: false
});
}
};
private _renderItemsForType = (workItemType: string): JSX.Element => {
const { workItemsByLevel } = this.state;
const workItemTypeKey = workItemType.toLowerCase();
const content = workItemsByLevel[workItemTypeKey];
// No-op when LoadingStatus.NotLoaded, which means users has not clicked on the section yet to expand it.
if (content.loadingStatus === LoadingStatus.Loading) {
return <Spinner label="Loading work items..." size={SpinnerSize.large} className="loading-workitems" />;
} else {
if (content.loadingErrorMessage && content.loadingErrorMessage.length > 0) {
return (
<MessageBar messageBarType={MessageBarType.error} isMultiline={true}>
{content.loadingErrorMessage}
</MessageBar>
);
} else if (content.workItemsFoundInProject === 0) {
return (
<div className="workItemTypeEmptyMessage">
No work items of this type were found in the project.
</div>
);
} else if (Object.keys(content.items).length === 0) {
return <div className="workItemTypeEmptyMessage">All work items were already added to the plan.</div>;
} else {
if (!this._selectionByWorkItemType[workItemTypeKey]) {
const selection = new Selection({
onSelectionChanged: () => this._onWorkItemSelectionChanged(workItemTypeKey)
});
this._selectionByWorkItemType[workItemTypeKey] = selection;
}
let allItemsCount: number = 0;
const listItems: IAddItem[] = [];
Object.keys(content.items).forEach(workItemId => {
const item = content.items[workItemId];
allItemsCount++;
if (item.hide === false) {
listItems.push(item);
}
});
const columns: IColumn[] = [
{
key: "titleColumn",
name: "Title",
fieldName: "text",
minWidth: 100,
isResizable: false,
isIconOnly: true
}
];
const list: JSX.Element = (
<DetailsList
isHeaderVisible={false}
checkboxVisibility={CheckboxVisibility.hidden}
items={listItems}
columns={columns}
setKey="set"
onRenderItemColumn={this._onRenderItemColumn}
layoutMode={DetailsListLayoutMode.justified}
selection={this._selectionByWorkItemType[workItemTypeKey]}
selectionPreservedOnEmptyClick={true}
ariaLabelForSelectionColumn="Toggle selection"
ariaLabelForSelectAllCheckbox="Toggle selection for all items"
checkButtonAriaLabel="Row checkbox"
/>
);
const searchFilter =
allItemsCount > AddItemPanel.WORKITEMTYPE_SEARCH_THRESHOLD
? this._renderWorkItemTypeSectionFilter(workItemType)
: null;
return (
<div className={"workItemTypeSectionBody"}>
{searchFilter}
{list}
</div>
);
}
}
};
private _onRenderItemColumn = (item: IAddItem, index: number, column: IColumn): JSX.Element => {
const workItemTypeKey = item.workItemType.toLowerCase();
const iconProps = this.state.selectedProjectBacklogConfiguration.iconInfoByWorkItemType[workItemTypeKey];
const imageProps: IImageProps = {
src: iconProps.url,
className: "workItemIconClass",
imageFit: ImageFit.center,
maximizeFrame: true
};
return (
<div className="item-list-row">
<Image {...imageProps as any} />
<Tooltip overflowOnly={true}>
<span className="item-list-row-text">
{item.id} - {item.text}
</span>
</Tooltip>
</div>
);
};
private _onWorkItemSelectionChanged = (workItemTypeKey: string) => {
const { selectedWorkItems, workItemsByLevel } = this.state;
const selection = this._selectionByWorkItemType[workItemTypeKey];
const newSelectedWorkItems: { [workItemId: number]: IAddItem } = [];
const workItemsInlevel = workItemsByLevel[workItemTypeKey];
selection.getSelection().forEach(selectedWorkItem => {
const workItemId: number = selectedWorkItem.key as number;
newSelectedWorkItems[workItemId] = workItemsInlevel.items[workItemId];
});
if (Object.keys(newSelectedWorkItems).length === 0) {
delete selectedWorkItems[workItemTypeKey];
} else {
selectedWorkItems[workItemTypeKey] = newSelectedWorkItems;
}
this.setState({
selectedWorkItems
});
};
private _renderWorkItemTypeSectionFilter = (workItemType: string): JSX.Element => {
const searchKeyword = this.state.workItemsByLevel[workItemType].searchKeyword || "";
return (
<TextField
value={searchKeyword}
onChange={(e, value) => this._onChangeSearchKeywordTextField(e, value, workItemType)}
placeholder={"Search keyword"}
width={TextFieldWidth.auto}
style={TextFieldStyle.inline}
className={"searchTextField"}
/>
);
};
private _onChangeSearchKeywordTextField = (
ev: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>,
value: string,
workItemType: string
): void => {
const { workItemsByLevel } = this.state;
const filterEnabled = value && value.length > 0;
const valueLowerCase = value!.toLowerCase() || "";
Object.keys(workItemsByLevel[workItemType].items).forEach(itemKey => {
const item = workItemsByLevel[workItemType].items[itemKey] as IAddItem;
item.hide = filterEnabled === true && !this._matchesSearchKeywordFilter(valueLowerCase, item);
});
workItemsByLevel[workItemType].searchKeyword = value;
this.setState({
workItemsByLevel: workItemsByLevel
});
};
private _matchesSearchKeywordFilter = (keywordLowerCase: string, item: IAddItem): boolean => {
// prettier-ignore
return (
// Matches work item id?
item.id.toString().indexOf(keywordLowerCase) >= 0
||
// Matches work item text?
item.text.toLowerCase().indexOf(keywordLowerCase) >= 0
);
};
private _renderEpics = () => {
const { loadingProjectConfiguration, workItemsByLevel } = this.state;
if (loadingProjectConfiguration) {
return (
<Spinner label="Loading Project Data..." size={SpinnerSize.large} className="loading-project-data" />
);
} else {
const workItemTypeSections = Object.keys(workItemsByLevel).map(workItemTypeKey => {
const content = workItemsByLevel[workItemTypeKey];
return (
<CollapsiblePanel
contentKey={workItemTypeKey}
animate={false}
headerLabel={content.workItemTypeDisplayName}
headerClassName={"workItemTypeHeader"}
renderContent={this._renderItemsForType}
isCollapsible={true}
// Initially expand sections loaded or currently loading.
initialIsExpanded={
content.loadingStatus === LoadingStatus.Loaded ||
content.loadingStatus === LoadingStatus.Loading
}
forceContentUpdate={content.loadingStatus === LoadingStatus.Loaded}
alwaysRenderContents={false}
onToggle={this._onWorkItemTypeToggle}
/>
);
});
return (
<FormItem
message={this.state.errorMessage}
error={this.state.errorMessage && this.state.errorMessage !== ""}
>
{workItemTypeSections}
</FormItem>
);
}
};
private _onWorkItemTypeToggle = async (workItemTypeKey: string, isExpanded: boolean) => {
PortfolioTelemetry.getInstance().TrackAction("AddItemPanel/WorkItemTypeToggle", {
["IsExpanded"]: isExpanded
});
const { selectedProject, workItemsByLevel } = this.state;
const content = workItemsByLevel[workItemTypeKey];
if (isExpanded && content.loadingStatus === LoadingStatus.NotLoaded) {
// Expanding for the first time, need to load work items.
content.loadingStatus = LoadingStatus.Loading;
this.setState({
workItemsByLevel
});
// Load work items for this type.
let errorMessage: string = null;
const items: { [workItemId: number]: IAddItem } = {};
let workItemsFoundInProject = 0;
try {
const workItemsOfType = await PortfolioPlanningDataService.getInstance().getAllWorkItemsOfTypeInProject(
selectedProject.id,
content.workItemTypeDisplayName
);
if (workItemsOfType.exceptionMessage && workItemsOfType.exceptionMessage.length > 0) {
errorMessage = workItemsOfType.exceptionMessage;
} else {
workItemsFoundInProject = workItemsOfType.workItems.length;
PortfolioTelemetry.getInstance().TrackAddItemPanelWorkItemsOfTypeCount(
selectedProject.id,
content.workItemTypeDisplayName,
workItemsFoundInProject
);
workItemsOfType.workItems.forEach(workItem => {
// Only show work items not yet included in the plan.
if (!this.props.epicsInPlan[workItem.WorkItemId]) {
items[workItem.WorkItemId] = {
id: workItem.WorkItemId,
key: workItem.WorkItemId,
text: workItem.Title,
workItemType: workItemTypeKey,
hide: false
};
}
});
}
} catch (error) {
errorMessage = JSON.stringify(error, null, " ");
console.log(errorMessage);
} finally {
content.loadingErrorMessage = errorMessage;
content.items = items;
content.workItemsFoundInProject = workItemsFoundInProject;
content.loadingStatus = LoadingStatus.Loaded;
this.setState({
workItemsByLevel
});
}
}
};
private _onAddEpics = (): void => {
const items: IAddItem[] = [];
Object.keys(this.state.selectedWorkItems).forEach(wiTypeKey => {
const workItemsInType = this.state.selectedWorkItems[wiTypeKey];
Object.keys(workItemsInType).forEach(workItem => {
items.push(workItemsInType[workItem]);
});
});
this.props.onAddItems({
planId: this.props.planId,
projectId: this.state.selectedProject.id,
items,
projectConfiguration: this.state.selectedProjectBacklogConfiguration
});
this.props.onCloseAddItemPanel();
};
private _getAllProjects = async (): Promise<Project[]> => {
const projects = await PortfolioPlanningDataService.getInstance().getAllProjects();
return projects.projects;
};
private _getProjectConfiguration = async (projectId: string): Promise<IProjectConfiguration> => {
const projectIdKey = projectId.toLowerCase();
let result: IProjectConfiguration = this._projectConfigurationsCache[projectIdKey];
if (!result) {
result = await ProjectConfigurationDataService.getInstance().getProjectConfiguration(projectId);
this._projectConfigurationsCache[projectIdKey] = result;
}
return result;
};
} | the_stack |
import { ContractAddresses } from '@0x/contract-addresses';
import { assetDataUtils, ERC20AssetData, generatePseudoRandomSalt, orderCalculationUtils } from '@0x/order-utils';
import { RFQTIndicativeQuote } from '@0x/quote-server';
import { SignedOrder } from '@0x/types';
import { AbiEncoder, BigNumber } from '@0x/utils';
import { MarketOperation, SignedOrderWithFillableAmounts } from '../../types';
import {
ERC20_PROXY_ID,
MAX_UINT256,
NULL_ADDRESS,
NULL_BYTES,
ONE_HOUR_IN_SECONDS,
ONE_SECOND_MS,
WALLET_SIGNATURE,
ZERO_AMOUNT,
} from './constants';
import { getMultiBridgeIntermediateToken } from './multibridge_utils';
import {
AggregationError,
BalancerFillData,
BancorFillData,
CollapsedFill,
CurveFillData,
DexSample,
DODOFillData,
ERC20BridgeSource,
KyberFillData,
LiquidityProviderFillData,
MooniswapFillData,
MultiBridgeFillData,
MultiHopFillData,
NativeCollapsedFill,
OptimizedMarketOrder,
OrderDomain,
SnowSwapFillData,
SushiSwapFillData,
SwerveFillData,
UniswapV2FillData,
} from './types';
// tslint:disable completed-docs no-unnecessary-type-assertion
export function createDummyOrderForSampler(
makerAssetData: string,
takerAssetData: string,
makerAddress: string,
): SignedOrder {
return {
makerAddress,
takerAddress: NULL_ADDRESS,
senderAddress: NULL_ADDRESS,
feeRecipientAddress: NULL_ADDRESS,
salt: ZERO_AMOUNT,
expirationTimeSeconds: ZERO_AMOUNT,
makerAssetData,
takerAssetData,
makerFeeAssetData: NULL_BYTES,
takerFeeAssetData: NULL_BYTES,
makerFee: ZERO_AMOUNT,
takerFee: ZERO_AMOUNT,
makerAssetAmount: ZERO_AMOUNT,
takerAssetAmount: ZERO_AMOUNT,
signature: NULL_BYTES,
chainId: 1,
exchangeAddress: NULL_ADDRESS,
};
}
export function getNativeOrderTokens(order: SignedOrder): [string, string] {
const assets = [order.makerAssetData, order.takerAssetData].map(a => assetDataUtils.decodeAssetDataOrThrow(a)) as [
ERC20AssetData,
ERC20AssetData
];
if (assets.some(a => a.assetProxyId !== ERC20_PROXY_ID)) {
throw new Error(AggregationError.NotERC20AssetData);
}
return assets.map(a => a.tokenAddress.toLowerCase()) as [string, string];
}
export function convertNativeOrderToFullyFillableOptimizedOrders(order: SignedOrder): OptimizedMarketOrder {
return {
...order,
fillableMakerAssetAmount: order.makerAssetAmount,
fillableTakerAssetAmount: order.takerAssetAmount,
fillableTakerFeeAmount: order.takerFee,
fills: [],
};
}
/**
* Augments native orders with fillable amounts and filters out unfillable orders.
*/
export function createSignedOrdersWithFillableAmounts(
side: MarketOperation,
orders: SignedOrder[],
fillableAmounts: BigNumber[],
): SignedOrderWithFillableAmounts[] {
// Quick safety check: ensures that orders maps perfectly to fillable amounts.
if (orders.length !== fillableAmounts.length) {
throw new Error(
`Number of orders was ${orders.length} but fillable amounts was ${
fillableAmounts.length
}. This should never happen`,
);
}
return orders
.map((order: SignedOrder, i: number) => {
const fillableAmount = fillableAmounts[i];
const fillableMakerAssetAmount =
side === MarketOperation.Buy
? fillableAmount
: orderCalculationUtils.getMakerFillAmount(order, fillableAmount);
const fillableTakerAssetAmount =
side === MarketOperation.Sell
? fillableAmount
: orderCalculationUtils.getTakerFillAmount(order, fillableAmount);
const fillableTakerFeeAmount = orderCalculationUtils.getTakerFeeAmount(order, fillableTakerAssetAmount);
return {
...order,
fillableMakerAssetAmount,
fillableTakerAssetAmount,
fillableTakerFeeAmount,
};
})
.filter(order => {
return !order.fillableMakerAssetAmount.isZero() && !order.fillableTakerAssetAmount.isZero();
});
}
export interface CreateOrderFromPathOpts {
side: MarketOperation;
inputToken: string;
outputToken: string;
orderDomain: OrderDomain;
contractAddresses: ContractAddresses;
bridgeSlippage: number;
}
export function createOrdersFromTwoHopSample(
sample: DexSample<MultiHopFillData>,
opts: CreateOrderFromPathOpts,
): OptimizedMarketOrder[] {
const [makerToken, takerToken] = getMakerTakerTokens(opts);
const { firstHopSource, secondHopSource, intermediateToken } = sample.fillData!;
const firstHopFill: CollapsedFill = {
sourcePathId: '',
source: firstHopSource.source,
input: opts.side === MarketOperation.Sell ? sample.input : ZERO_AMOUNT,
output: opts.side === MarketOperation.Sell ? ZERO_AMOUNT : sample.output,
subFills: [],
fillData: firstHopSource.fillData,
};
const secondHopFill: CollapsedFill = {
sourcePathId: '',
source: secondHopSource.source,
input: opts.side === MarketOperation.Sell ? MAX_UINT256 : sample.input,
output: opts.side === MarketOperation.Sell ? sample.output : MAX_UINT256,
subFills: [],
fillData: secondHopSource.fillData,
};
return [
createBridgeOrder(firstHopFill, intermediateToken, takerToken, opts),
createBridgeOrder(secondHopFill, makerToken, intermediateToken, opts),
];
}
function getBridgeAddressFromFill(fill: CollapsedFill, opts: CreateOrderFromPathOpts): string {
switch (fill.source) {
case ERC20BridgeSource.Eth2Dai:
return opts.contractAddresses.eth2DaiBridge;
case ERC20BridgeSource.Kyber:
return opts.contractAddresses.kyberBridge;
case ERC20BridgeSource.Uniswap:
return opts.contractAddresses.uniswapBridge;
case ERC20BridgeSource.UniswapV2:
return opts.contractAddresses.uniswapV2Bridge;
case ERC20BridgeSource.SushiSwap:
return opts.contractAddresses.sushiswapBridge;
case ERC20BridgeSource.Curve:
return opts.contractAddresses.curveBridge;
case ERC20BridgeSource.Swerve:
return opts.contractAddresses.curveBridge;
case ERC20BridgeSource.SnowSwap:
return opts.contractAddresses.curveBridge;
case ERC20BridgeSource.Bancor:
return opts.contractAddresses.bancorBridge;
case ERC20BridgeSource.Balancer:
return opts.contractAddresses.balancerBridge;
case ERC20BridgeSource.Cream:
return opts.contractAddresses.creamBridge;
case ERC20BridgeSource.LiquidityProvider:
return (fill.fillData as LiquidityProviderFillData).poolAddress;
case ERC20BridgeSource.MultiBridge:
return (fill.fillData as MultiBridgeFillData).poolAddress;
case ERC20BridgeSource.MStable:
return opts.contractAddresses.mStableBridge;
case ERC20BridgeSource.Mooniswap:
return opts.contractAddresses.mooniswapBridge;
case ERC20BridgeSource.Shell:
return opts.contractAddresses.shellBridge;
case ERC20BridgeSource.Dodo:
return opts.contractAddresses.dodoBridge;
default:
break;
}
throw new Error(AggregationError.NoBridgeForSource);
}
export function createBridgeOrder(
fill: CollapsedFill,
makerToken: string,
takerToken: string,
opts: CreateOrderFromPathOpts,
): OptimizedMarketOrder {
const bridgeAddress = getBridgeAddressFromFill(fill, opts);
let makerAssetData;
switch (fill.source) {
case ERC20BridgeSource.Curve:
const curveFillData = (fill as CollapsedFill<CurveFillData>).fillData!; // tslint:disable-line:no-non-null-assertion
makerAssetData = assetDataUtils.encodeERC20BridgeAssetData(
makerToken,
bridgeAddress,
createCurveBridgeData(
curveFillData.pool.poolAddress,
curveFillData.pool.exchangeFunctionSelector,
takerToken,
curveFillData.fromTokenIdx,
curveFillData.toTokenIdx,
),
);
break;
case ERC20BridgeSource.Swerve:
const swerveFillData = (fill as CollapsedFill<SwerveFillData>).fillData!; // tslint:disable-line:no-non-null-assertion
makerAssetData = assetDataUtils.encodeERC20BridgeAssetData(
makerToken,
bridgeAddress,
createCurveBridgeData(
swerveFillData.pool.poolAddress,
swerveFillData.pool.exchangeFunctionSelector,
takerToken,
swerveFillData.fromTokenIdx,
swerveFillData.toTokenIdx,
),
);
break;
case ERC20BridgeSource.SnowSwap:
const snowSwapFillData = (fill as CollapsedFill<SnowSwapFillData>).fillData!; // tslint:disable-line:no-non-null-assertion
makerAssetData = assetDataUtils.encodeERC20BridgeAssetData(
makerToken,
bridgeAddress,
createCurveBridgeData(
snowSwapFillData.pool.poolAddress,
snowSwapFillData.pool.exchangeFunctionSelector,
takerToken,
snowSwapFillData.fromTokenIdx,
snowSwapFillData.toTokenIdx,
),
);
break;
case ERC20BridgeSource.Balancer:
const balancerFillData = (fill as CollapsedFill<BalancerFillData>).fillData!; // tslint:disable-line:no-non-null-assertion
makerAssetData = assetDataUtils.encodeERC20BridgeAssetData(
makerToken,
bridgeAddress,
createBalancerBridgeData(takerToken, balancerFillData.poolAddress),
);
break;
case ERC20BridgeSource.Cream:
const creamFillData = (fill as CollapsedFill<BalancerFillData>).fillData!; // tslint:disable-line:no-non-null-assertion
makerAssetData = assetDataUtils.encodeERC20BridgeAssetData(
makerToken,
bridgeAddress,
createBalancerBridgeData(takerToken, creamFillData.poolAddress),
);
break;
case ERC20BridgeSource.Bancor:
const bancorFillData = (fill as CollapsedFill<BancorFillData>).fillData!; // tslint:disable-line:no-non-null-assertion
makerAssetData = assetDataUtils.encodeERC20BridgeAssetData(
makerToken,
bridgeAddress,
createBancorBridgeData(bancorFillData.path, bancorFillData.networkAddress),
);
break;
case ERC20BridgeSource.UniswapV2:
const uniswapV2FillData = (fill as CollapsedFill<UniswapV2FillData>).fillData!; // tslint:disable-line:no-non-null-assertion
makerAssetData = assetDataUtils.encodeERC20BridgeAssetData(
makerToken,
bridgeAddress,
createUniswapV2BridgeData(uniswapV2FillData.tokenAddressPath),
);
break;
case ERC20BridgeSource.SushiSwap:
const sushiSwapFillData = (fill as CollapsedFill<SushiSwapFillData>).fillData!; // tslint:disable-line:no-non-null-assertion
makerAssetData = assetDataUtils.encodeERC20BridgeAssetData(
makerToken,
bridgeAddress,
createSushiSwapBridgeData(sushiSwapFillData.tokenAddressPath, sushiSwapFillData.router),
);
break;
case ERC20BridgeSource.MultiBridge:
makerAssetData = assetDataUtils.encodeERC20BridgeAssetData(
makerToken,
bridgeAddress,
createMultiBridgeData(takerToken, makerToken),
);
break;
case ERC20BridgeSource.Kyber:
const kyberFillData = (fill as CollapsedFill<KyberFillData>).fillData!; // tslint:disable-line:no-non-null-assertion
makerAssetData = assetDataUtils.encodeERC20BridgeAssetData(
makerToken,
bridgeAddress,
createKyberBridgeData(takerToken, kyberFillData.hint),
);
break;
case ERC20BridgeSource.Mooniswap:
const mooniswapFillData = (fill as CollapsedFill<MooniswapFillData>).fillData!; // tslint:disable-line:no-non-null-assertion
makerAssetData = assetDataUtils.encodeERC20BridgeAssetData(
makerToken,
bridgeAddress,
createMooniswapBridgeData(takerToken, mooniswapFillData.poolAddress),
);
break;
case ERC20BridgeSource.Dodo:
const dodoFillData = (fill as CollapsedFill<DODOFillData>).fillData!; // tslint:disable-line:no-non-null-assertion
makerAssetData = assetDataUtils.encodeERC20BridgeAssetData(
makerToken,
bridgeAddress,
createDODOBridgeData(takerToken, dodoFillData.poolAddress, dodoFillData.isSellBase),
);
break;
default:
makerAssetData = assetDataUtils.encodeERC20BridgeAssetData(
makerToken,
bridgeAddress,
createBridgeData(takerToken),
);
}
const [slippedMakerAssetAmount, slippedTakerAssetAmount] = getSlippedBridgeAssetAmounts(fill, opts);
return {
fills: [fill],
makerAssetData,
takerAssetData: assetDataUtils.encodeERC20AssetData(takerToken),
makerAddress: bridgeAddress,
makerAssetAmount: slippedMakerAssetAmount,
takerAssetAmount: slippedTakerAssetAmount,
fillableMakerAssetAmount: slippedMakerAssetAmount,
fillableTakerAssetAmount: slippedTakerAssetAmount,
...createCommonBridgeOrderFields(opts.orderDomain),
};
}
export function getMakerTakerTokens(opts: CreateOrderFromPathOpts): [string, string] {
const makerToken = opts.side === MarketOperation.Sell ? opts.outputToken : opts.inputToken;
const takerToken = opts.side === MarketOperation.Sell ? opts.inputToken : opts.outputToken;
return [makerToken, takerToken];
}
function createBridgeData(tokenAddress: string): string {
const encoder = AbiEncoder.create([{ name: 'tokenAddress', type: 'address' }]);
return encoder.encode({ tokenAddress });
}
function createMultiBridgeData(takerToken: string, makerToken: string): string {
const intermediateToken = getMultiBridgeIntermediateToken(takerToken, makerToken);
const encoder = AbiEncoder.create([
{ name: 'takerToken', type: 'address' },
{ name: 'intermediateToken', type: 'address' },
]);
return encoder.encode({ takerToken, intermediateToken });
}
function createBalancerBridgeData(takerToken: string, poolAddress: string): string {
const encoder = AbiEncoder.create([
{ name: 'takerToken', type: 'address' },
{ name: 'poolAddress', type: 'address' },
]);
return encoder.encode({ takerToken, poolAddress });
}
function createBancorBridgeData(path: string[], networkAddress: string): string {
const encoder = AbiEncoder.create([
{ name: 'path', type: 'address[]' },
{ name: 'networkAddress', type: 'address' },
]);
return encoder.encode({ path, networkAddress });
}
function createKyberBridgeData(fromTokenAddress: string, hint: string): string {
const encoder = AbiEncoder.create([{ name: 'fromTokenAddress', type: 'address' }, { name: 'hint', type: 'bytes' }]);
return encoder.encode({ fromTokenAddress, hint });
}
function createMooniswapBridgeData(takerToken: string, poolAddress: string): string {
const encoder = AbiEncoder.create([
{ name: 'takerToken', type: 'address' },
{ name: 'poolAddress', type: 'address' },
]);
return encoder.encode({ takerToken, poolAddress });
}
function createDODOBridgeData(takerToken: string, poolAddress: string, isSellBase: boolean): string {
const encoder = AbiEncoder.create([
{ name: 'takerToken', type: 'address' },
{ name: 'poolAddress', type: 'address' },
{ name: 'isSellBase', type: 'bool' },
]);
return encoder.encode({ takerToken, poolAddress, isSellBase });
}
function createCurveBridgeData(
curveAddress: string,
exchangeFunctionSelector: string,
takerToken: string,
fromTokenIdx: number,
toTokenIdx: number,
): string {
const encoder = AbiEncoder.create([
{ name: 'curveAddress', type: 'address' },
{ name: 'exchangeFunctionSelector', type: 'bytes4' },
{ name: 'fromTokenAddress', type: 'address' },
{ name: 'fromTokenIdx', type: 'int128' },
{ name: 'toTokenIdx', type: 'int128' },
]);
return encoder.encode([curveAddress, exchangeFunctionSelector, takerToken, fromTokenIdx, toTokenIdx]);
}
function createUniswapV2BridgeData(tokenAddressPath: string[]): string {
const encoder = AbiEncoder.create('(address[])');
return encoder.encode([tokenAddressPath]);
}
function createSushiSwapBridgeData(tokenAddressPath: string[], router: string): string {
const encoder = AbiEncoder.create('(address[],address)');
return encoder.encode([tokenAddressPath, router]);
}
function getSlippedBridgeAssetAmounts(fill: CollapsedFill, opts: CreateOrderFromPathOpts): [BigNumber, BigNumber] {
return [
// Maker asset amount.
opts.side === MarketOperation.Sell
? fill.output.times(1 - opts.bridgeSlippage).integerValue(BigNumber.ROUND_DOWN)
: fill.input,
// Taker asset amount.
opts.side === MarketOperation.Sell
? fill.input
: BigNumber.min(fill.output.times(opts.bridgeSlippage + 1).integerValue(BigNumber.ROUND_UP), MAX_UINT256),
];
}
type CommonBridgeOrderFields = Pick<
OptimizedMarketOrder,
Exclude<
keyof OptimizedMarketOrder,
| 'fills'
| 'makerAddress'
| 'makerAssetData'
| 'takerAssetData'
| 'makerAssetAmount'
| 'takerAssetAmount'
| 'fillableMakerAssetAmount'
| 'fillableTakerAssetAmount'
>
>;
function createCommonBridgeOrderFields(orderDomain: OrderDomain): CommonBridgeOrderFields {
return {
takerAddress: NULL_ADDRESS,
senderAddress: NULL_ADDRESS,
feeRecipientAddress: NULL_ADDRESS,
salt: generatePseudoRandomSalt(),
// 2 hours from now
expirationTimeSeconds: new BigNumber(Math.floor(Date.now() / ONE_SECOND_MS) + ONE_HOUR_IN_SECONDS * 2),
makerFeeAssetData: NULL_BYTES,
takerFeeAssetData: NULL_BYTES,
makerFee: ZERO_AMOUNT,
takerFee: ZERO_AMOUNT,
fillableTakerFeeAmount: ZERO_AMOUNT,
signature: WALLET_SIGNATURE,
...orderDomain,
};
}
export function createNativeOrder(fill: NativeCollapsedFill): OptimizedMarketOrder {
return {
fills: [fill],
...fill.fillData!.order, // tslint:disable-line:no-non-null-assertion
};
}
export function createSignedOrdersFromRfqtIndicativeQuotes(
quotes: RFQTIndicativeQuote[],
): SignedOrderWithFillableAmounts[] {
return quotes.map(quote => {
return {
fillableMakerAssetAmount: quote.makerAssetAmount,
fillableTakerAssetAmount: quote.takerAssetAmount,
makerAssetAmount: quote.makerAssetAmount,
takerAssetAmount: quote.takerAssetAmount,
makerAssetData: quote.makerAssetData,
takerAssetData: quote.takerAssetData,
takerAddress: NULL_ADDRESS,
makerAddress: NULL_ADDRESS,
senderAddress: NULL_ADDRESS,
feeRecipientAddress: NULL_ADDRESS,
salt: ZERO_AMOUNT,
expirationTimeSeconds: quote.expirationTimeSeconds,
makerFeeAssetData: NULL_BYTES,
takerFeeAssetData: NULL_BYTES,
makerFee: ZERO_AMOUNT,
takerFee: ZERO_AMOUNT,
fillableTakerFeeAmount: ZERO_AMOUNT,
signature: WALLET_SIGNATURE,
chainId: 0,
exchangeAddress: NULL_ADDRESS,
};
});
} | the_stack |
import { Icon } from "@hpcc-js/common";
import { BaseScope, ScopeEdge, ScopeGraph, ScopeSubgraph, ScopeVertex } from "@hpcc-js/comms";
import { Edge, IGraphData, Lineage, Subgraph, Vertex } from "@hpcc-js/graph";
import { Edge as UtilEdge, Subgraph as UtilSubgraph, Vertex as UtilVertex } from "@hpcc-js/util";
import { WUGraphLegendData } from "./WUGraphLegend";
export type VertexType = Vertex | Icon;
export interface MyGraphData {
subgraphs: Subgraph[];
vertices: VertexType[];
edges: Edge[];
hierarchy: Lineage[];
}
function faCharFactory(kind): string {
switch (kind) {
case "2": return "\uf0c7"; // Disk Write
case "3": return "\uf15d"; // sort
case "5": return "\uf0b0"; // Filter
case "6": return "\uf1e0"; // Split
case "12": return "\uf039"; // First N
case "15": return "\uf126"; // Lightweight Join
case "17": return "\uf126"; // Lookup Join
case "22": return "\uf1e6"; // Pipe Output
case "23": return "\uf078"; // Funnel
case "25": return "\uf0ce"; // Inline Dataset
case "26": return "\uf074"; // distribute
case "29": return "\uf005"; // Store Internal Result
case "36": return "\uf128"; // If
case "44": return "\uf0c7"; // write csv
case "47": return "\uf0c7"; // write
case "54": return "\uf013"; // Workunit Read
case "56": return "\uf0c7"; // Spill
case "59": return "\uf126"; // Merge
case "61": return "\uf0c7"; // write xml
case "82": return "\uf1c0"; // Projected Disk Read Spill
case "88": return "\uf1c0"; // Projected Disk Read Spill
case "92": return "\uf129"; // Limted Index Read
case "93": return "\uf129"; // Limted Index Read
case "99": return "\uf1c0"; // CSV Read
case "105": return "\uf1c0"; // CSV Read
case "7": return "\uf090"; // Project
case "9": return "\uf0e2"; // Local Iterate
case "16": return "\uf005"; // Output Internal
case "19": return "\uf074"; // Hash Distribute
case "21": return "\uf275"; // Normalize
case "35": return "\uf0c7"; // CSV Write
case "37": return "\uf0c7"; // Index Write
case "71": return "\uf1c0"; // Disk Read Spill
case "133": return "\uf0ce"; // Inline Dataset
case "148": return "\uf0ce"; // Inline Dataset
case "168": return "\uf275"; // Local Denormalize
}
return "\uf063";
}
export class WUScopeController {
private graphDB: ScopeGraph;
private subgraphsMap: { [id: string]: Subgraph } = {};
private rSubgraphsMap: { [id: string]: ScopeSubgraph } = {};
private verticesMap: { [id: string]: VertexType } = {};
private rVerticesMap: { [id: string]: ScopeVertex } = {};
private edgesMap: { [id: string]: Edge } = {};
private rEdgesMap: { [id: string]: ScopeEdge } = {};
private kindMap: { [id: string]: ScopeVertex[] } = {};
protected _disabled: { [kind: number]: boolean } = {};
constructor() {
}
clear() {
this.subgraphsMap = {};
this.rSubgraphsMap = {};
this.verticesMap = {};
this.rVerticesMap = {};
this.edgesMap = {};
this.rEdgesMap = {};
}
set(masterGraph: ScopeGraph) {
this.graphDB = masterGraph;
this.graphGui(this.graphDB);
this.kindMap = {};
this.graphDB.walk(item => {
if (item instanceof UtilSubgraph) {
} else if (item instanceof UtilVertex) {
const kind = item._.attr("Kind").RawValue;
if (!this.kindMap[kind]) {
this.kindMap[kind] = [];
}
this.kindMap[kind].push(item);
} else if (item instanceof UtilEdge) {
}
});
}
disabled(): number[];
disabled(_: number[]): this;
disabled(_?: number[]): number[] | this {
if (!arguments.length) {
const retVal = [];
for (const key in this._disabled) {
if (this._disabled[key]) {
retVal.push(key);
}
}
return retVal;
}
this._disabled = {};
_.forEach(kind => this._disabled[kind] = true);
return this;
}
graphGui(graphDB: ScopeGraph): IGraphData {
const graphGui: MyGraphData = {
subgraphs: [],
vertices: [],
edges: [],
hierarchy: []
};
graphDB.walk((item) => {
if (item instanceof UtilSubgraph) {
const subgraph = this.appendSubgraph(item, graphGui.hierarchy, graphGui.subgraphs);
subgraph.showMinMax(item.vertices.length > 3 || subgraph.minState() !== "normal");
} else if (item instanceof UtilVertex) {
this.appendVertex(item, graphGui.hierarchy, graphGui.vertices);
} else if (item instanceof UtilEdge) {
this.appendEdge(item, graphGui.edges);
}
});
return graphGui;
}
format(labelTpl, obj) {
let retVal = "";
let lpos = labelTpl.indexOf("%");
let rpos = -1;
while (lpos >= 0) {
retVal += labelTpl.substring(rpos + 1, lpos);
rpos = labelTpl.indexOf("%", lpos + 1);
if (rpos < 0) {
console.log("Invalid Label Template");
break;
}
const key = labelTpl.substring(lpos + 1, rpos);
retVal += !key ? "%" : (obj[labelTpl.substring(lpos + 1, rpos)] || "");
lpos = labelTpl.indexOf("%", rpos + 1);
}
retVal += labelTpl.substring(rpos + 1, labelTpl.length);
return retVal.split("\\n").join("\n");
}
createSubgraph(subgraph: ScopeSubgraph): Subgraph {
let sg = this.subgraphsMap[subgraph._.Id];
if (!sg) {
sg = new Subgraph()
.title(subgraph._.Id)
.on("minClick", () => {
this.minClick(sg);
})
;
this.subgraphsMap[subgraph._.Id] = sg;
this.rSubgraphsMap[sg.id()] = subgraph;
}
return sg;
}
createVertex(vertex: ScopeVertex): VertexType {
let v = this.verticesMap[vertex._.Id];
if (!v) {
const attrs = vertex._.rawAttrs();
if (vertex._.ScopeType === "dummy") {
const parent = this.subgraphsMap[vertex.parent._.Id];
v = new Icon()
.shape_colorFill("darkred")
.shape_colorStroke("darkred")
.image_colorFill("white")
.faChar("\uf067")
.on("click", () => {
parent.minState("normal");
this.minClick(parent);
})
;
} else {
v = new Vertex()
.icon_shape_colorFill("#1f77b4")
.icon_image_colorFill("white")
.faChar(faCharFactory(attrs["Kind"]))
.text(attrs["Label"])
;
const annotations = [];
if (vertex._.hasAttr("Definition")) {
annotations.push({
faChar: "\uf036",
tooltip: "Definition",
shape_colorFill: "lightgray",
shape_colorStroke: "lightgray",
image_colorFill: "black"
});
}
if (vertex._.hasAttr("IsInternal")) {
annotations.push({
faChar: "\uf085",
tooltip: "IsInternal",
shape_colorFill: "red",
shape_colorStroke: "red",
image_colorFill: "white"
});
}
v.annotationIcons(annotations);
}
this.verticesMap[vertex._.Id] = v;
this.rVerticesMap[v.id()] = vertex;
}
return v;
}
isSpill(edge: ScopeEdge): boolean {
const sourceKind = edge.source._.attr("Kind").RawValue;
const targetKind = edge.target._.attr("Kind").RawValue;
return sourceKind === "2" || targetKind === "71";
}
spansSubgraph(edge: ScopeEdge): boolean {
return edge.source.parent._.Id !== edge.target.parent._.Id;
}
createEdge(edge: ScopeEdge): Edge | undefined {
let e = this.edgesMap[edge._.Id];
if (!e) {
const attrs = edge._.rawAttrs();
const sourceV = this.verticesMap[edge.source._.Id];
const targetV = this.verticesMap[edge.target._.Id];
if (sourceV && targetV) {
const isSpill = this.isSpill(edge);
const spansSubgraph = this.spansSubgraph(edge);
const label = this.format("%Label%\n%NumRowsProcessed%", attrs);
/* TODO: Add extra annotations once WUDetails is fixed...
const numSlaves = parseInt(attrs["NumSlaves"]);
const numStarts = parseInt(attrs["NumStarts"]);
const numStops = parseInt(attrs["NumStops"]);
const started = numStarts > 0;
const finished = numStops === numSlaves;
const active = started && !finished;
*/
let strokeDasharray = null;
let weight = 100;
if (attrs["IsDependency"]) {
weight = 10;
strokeDasharray = "1,5";
} else if (attrs["_childGraph"]) {
strokeDasharray = "5,5";
} else if (isSpill) {
weight = 25;
strokeDasharray = "5,5,10,5";
} else if (spansSubgraph) {
weight = 5;
strokeDasharray = "5,5";
}
e = new Edge()
.sourceVertex(sourceV)
.targetVertex(targetV)
.sourceMarker("circle")
.targetMarker("arrow")
.weight(weight)
.strokeDasharray(strokeDasharray)
.text(label)
;
this.edgesMap[edge._.Id] = e;
this.rEdgesMap[e.id()] = edge;
}
}
return e;
}
appendSubgraph(subgraph: ScopeSubgraph, hierarchy: Lineage[], subgraphs: Subgraph[]): Subgraph {
const sg = this.createSubgraph(subgraph);
subgraphs.push(sg);
const parent = this.subgraphsMap[subgraph.parent._.Id];
if (parent) {
hierarchy.push({ parent, child: sg });
}
return sg;
}
appendVertex(vertex: ScopeVertex, hierarchy: Lineage[], vertices: VertexType[]): VertexType {
const v = this.createVertex(vertex);
vertices.push(v);
const parent = this.subgraphsMap[vertex.parent._.Id];
if (parent) {
hierarchy.push({ parent, child: v });
}
return v;
}
appendEdge(edge: ScopeEdge, edges: Edge[]): Edge {
const e = this.createEdge(edge);
if (e) {
edges.push(e);
}
return e;
}
filterLegend(graphDB: ScopeGraph) {
for (let i = graphDB.vertices.length - 1; i >= 0; --i) {
const vertex = graphDB.vertices[i];
const kind = vertex._.attr("Kind").RawValue;
if (this._disabled[kind]) {
vertex.remove(false, (source: BaseScope, target: BaseScope) => {
return new BaseScope({
ScopeName: vertex._.ScopeName + ":in",
Id: source.Id + "->" + target.Id,
ScopeType: "dummy-edge",
Properties: {
Property: [vertex._.attr("Label")]
},
Notes: {
Note: []
}
});
});
}
}
}
filterPartial(graphDB: ScopeGraph) {
for (const subgraph of graphDB.subgraphs) {
const sg = this.subgraphsMap[subgraph._.Id];
switch (sg.minState()) {
case "partial":
const childVertices: ReadonlyArray<ScopeVertex> = subgraph.vertices;
const vShow: ScopeVertex[] = [];
const vHide: ScopeVertex[] = [];
for (const vertex of childVertices) {
if (vertex.inEdges.length === 0 || vertex.inEdges.some(edge => edge.source.parent !== edge.target.parent) ||
vertex.outEdges.length === 0 || vertex.outEdges.some(edge => edge.source.parent !== edge.target.parent)) {
vShow.push(vertex);
} else {
vHide.push(vertex);
}
}
if (vHide.length > 1) {
const dummyDetails = {
ScopeName: subgraph._.ScopeName,
Id: subgraph._.Id + ":dummy",
ScopeType: "dummy",
Properties: {
Property: [{
Name: "Activities",
RawValue: "" + vHide.length,
Formatted: "" + vHide.length,
Measure: "count",
Creator: "",
CreatorType: ""
}]
},
Notes: {
Note: []
}
};
const dummyScope = new BaseScope(dummyDetails);
const dummyVertex = subgraph.createVertex(dummyScope);
for (const vertex of vHide) {
for (const edge of vertex.inEdges) {
if (vShow.indexOf(edge.source) >= 0) {
const dummyEdgeScope = new BaseScope({
ScopeName: edge.source._.ScopeName,
Id: edge.source._.Id + "->" + dummyVertex._.Id,
ScopeType: "dummy-in",
Properties: {
Property: []
},
Notes: {
Note: []
}
});
console.log(dummyEdgeScope.Id);
subgraph.createEdge(edge.source, dummyVertex, dummyEdgeScope);
}
}
for (const edge of vertex.outEdges) {
if (vShow.indexOf(edge.target) >= 0) {
const dummyEdgeScope = new BaseScope({
ScopeName: edge.target._.ScopeName,
Id: dummyVertex._.Id + "->" + edge.target._.Id,
ScopeType: "dummy-out",
Properties: {
Property: []
},
Notes: {
Note: []
}
});
console.log(dummyEdgeScope.Id);
subgraph.createEdge(dummyVertex, edge.target, dummyEdgeScope);
}
}
}
vHide.forEach(vertex => vertex.remove(true));
}
break;
}
}
}
filterEmptySubgraphs(graphDB: ScopeGraph) {
while (true) {
const emptySubgraphs = graphDB.subgraphs.filter(subgraph => subgraph.subgraphs.length === 0 && subgraph.vertices.length === 0);
if (emptySubgraphs.length === 0) break;
emptySubgraphs.forEach(subgraph => subgraph.remove(true));
}
}
removeObsoleteSubgraphs(graphDB: ScopeGraph) {
for (const subgraph of [...graphDB.subgraphs]) {
if (subgraph.vertices.length === 0) {
subgraph.remove(false);
}
}
}
graphData(): IGraphData {
const graphDB = this.graphDB.clone();
this.filterLegend(graphDB);
this.filterPartial(graphDB);
this.filterEmptySubgraphs(graphDB);
this.removeObsoleteSubgraphs(graphDB);
return this.graphGui(graphDB);
}
calcLegend(): WUGraphLegendData[] {
const retVal: WUGraphLegendData[] = [];
for (const kind in this.kindMap) {
retVal.push({
kind: parseInt(kind),
faChar: faCharFactory(kind),
label: this.kindMap[kind][0]._.attr("Label").RawValue.split("\n")[0],
count: this.kindMap[kind].length
});
}
return retVal;
}
vertices(kind: number): VertexType[] {
const retVal: VertexType[] = [];
for (const v of this.kindMap[kind]) {
retVal.push(this.verticesMap[v._.Id]);
}
return retVal;
}
formatRow(item: ScopeEdge | ScopeSubgraph | ScopeVertex, columns, row) {
const attrs = item._.formattedAttrs();
for (const key in attrs) {
const idx = columns.indexOf(key);
if (idx === -1) {
columns.push(key);
row.push(attrs[key]);
} else {
row[idx] = attrs[key];
}
}
for (let i = 0; i < 100; ++i) {
if (row[i] === undefined) {
row[i] = "";
}
}
return row;
}
activityData(): { columns: string[], data: any[][] } {
const columns = ["Id", "Kind", "Label"];
const data = this.graphDB.vertices.map(v => {
const row = [parseInt(v._.Id.split("a")[1])];
return this.formatRow(v, columns, row);
});
return { columns, data };
}
edgeData(): { columns: string[], data: any[][] } {
const columns = ["Id", "Label"];
const data = this.graphDB.edges.map(e => {
const row = [e._.Id];
return this.formatRow(e, columns, row);
});
return { columns, data };
}
subgraphData(): { columns: string[], data: any[][] } {
const columns = ["Id", "Label"];
const data = this.graphDB.subgraphs.map(sg => {
const row = [sg._.Id];
return this.formatRow(sg, columns, row);
});
return { columns, data };
}
calcGraphTooltip(item: VertexType | Edge) {
let scope;
let parentScope;
if (item instanceof Subgraph) {
const subgraph = this.rSubgraphsMap[item.id()];
scope = subgraph._;
parentScope = subgraph.parent._;
} else if (item instanceof Vertex || item instanceof Icon) {
const vertex = this.rVerticesMap[item.id()];
scope = vertex._;
parentScope = vertex.parent._;
} else if (item instanceof Edge) {
const edge = this.rEdgesMap[item.id()];
scope = edge._;
parentScope = edge.parent._;
}
if (scope) {
return scope.calcTooltip(parentScope);
}
return "";
}
subgraph(id: string): Subgraph | undefined {
return this.subgraphsMap[id];
}
vertex(id: string): VertexType | undefined {
return this.verticesMap[id];
}
edge(id: string): Edge {
return this.edgesMap[id];
}
// Events ---
minClick(sg: Subgraph) {
}
} | the_stack |
import test from 'tape-promise/tape';
import {Device} from '@luma.gl/api';
import {webgl1TestDevice, webgl2TestDevice} from '@luma.gl/test-utils';
import {assembleShaders, picking, fp64, pbr} from '@luma.gl/shadertools';
import type {WebGLDevice} from '@luma.gl/webgl';
function getInfo(device: Device) {
return {
gpu: device.info.gpu,
features: device.features
};
}
const VS_GLSL_300 = `\
#version 300 es
in vec4 positions;
void main(void) {
gl_Position = positions;
}
`;
const FS_GLSL_300 = `\
#version 300 es
precision highp float;
out vec4 fragmentColor;
void main(void) {
fragmentColor = vec4(1.0, 1.0, 1.0, 1.0);
}
`;
const VS_GLSL_300_2 = `\
#version 300 es
in vec4 positions;
in vec2 uvs;
in vec3 normals;
out vec2 vUV;
out vec3 vNormal;
// Make sure in and out args don't get transpiled
void setPosition1(in vec4 inPosition, out vec4 outPosition) {
outPosition = inPosition;
}
void setPosition2(
in vec4 inPosition,
out vec4 outPosition
) {
outPosition = inPosition;
}
void main(void) {
vUV = uvs;
vNormal = normals;
setPosition1(positions, gl_Position);
setPosition2(positions, gl_Position);
}
`;
const FS_GLSL_300_2 = `\
#version 300 es
precision highp float;
uniform sampler2D tex;
in vec2 vUV;
in vec3 vNormal;
out vec4 fragmentColor;
void main(void) {
fragmentColor = texture(tex, vUV) * vec4(vNormal, 1.0);
}
`;
// deck.gl mesh layer shaders
// TODO - broken tests
/*
const VS_GLSL_300_DECK = `#version 300 es
#define SHADER_NAME simple-mesh-layer-vs
// Scale the model
uniform float sizeScale;
uniform bool composeModelMatrix;
// Primitive attributes
in vec3 positions;
in vec3 normals;
in vec2 texCoords;
// Instance attributes
in vec3 instancePositions;
in vec3 instancePositions64Low;
in vec4 instanceColors;
in vec3 instancePickingColors;
in mat3 instanceModelMatrix;
in vec3 instanceTranslation;
// Outputs to fragment shader
out vec2 vTexCoord;
out vec3 cameraPosition;
out vec3 normals_commonspace;
out vec4 position_commonspace;
out vec4 vColor;
void main(void) {
vTexCoord = texCoords;
cameraPosition = vec3(1.0);
normals_commonspace = vec3(1.0);
vColor = instanceColors;
vec3 pos = (instanceModelMatrix * positions) * sizeScale + instanceTranslation;
if (composeModelMatrix) {
gl_Position = vec4(1.0);
}
else {
gl_Position = vec4(1.0);
}
}
`;
const FS_GLSL_300_DECK = `#version 300 es
#define SHADER_NAME simple-mesh-layer-fs
precision highp float;
uniform bool hasTexture;
uniform sampler2D sampler;
uniform bool flatShading;
uniform float opacity;
in vec2 vTexCoord;
in vec3 cameraPosition;
in vec3 normals_commonspace;
in vec4 position_commonspace;
in vec4 vColor;
out vec4 fragColor;
void main(void) {
vec3 normal;
if (flatShading) {
normal = normalize(cross(dFdx(position_commonspace.xyz), dFdy(position_commonspace.xyz)));
} else {
normal = normals_commonspace;
}
vec4 color = hasTexture ? texture(sampler, vTexCoord) : vColor;
vec3 lightColor = vec3(1.0);
fragColor = vec4(lightColor, color.a * opacity);
}
`;
*/
const VS_GLSL_300_GLTF = `#version 300 es
#if (__VERSION__ < 300)
#define _attr attribute
#else
#define _attr in
#endif
_attr vec4 POSITION;
#ifdef HAS_NORMALS
_attr vec4 NORMAL;
#endif
#ifdef HAS_TANGENTS
_attr vec4 TANGENT;
#endif
#ifdef HAS_UV
_attr vec2 TEXCOORD_0;
#endif
void main(void) {
vec4 _NORMAL = vec4(0.);
vec4 _TANGENT = vec4(0.);
vec2 _TEXCOORD_0 = vec2(0.);
#ifdef HAS_NORMALS
_NORMAL = NORMAL;
#endif
#ifdef HAS_TANGENTS
_TANGENT = TANGENT;
#endif
#ifdef HAS_UV
_TEXCOORD_0 = TEXCOORD_0;
#endif
pbr_setPositionNormalTangentUV(POSITION, _NORMAL, _TANGENT, _TEXCOORD_0);
gl_Position = u_MVPMatrix * POSITION;
}
`;
const FS_GLSL_300_GLTF = `#version 300 es
out vec4 fragmentColor;
void main(void) {
fragmentColor = pbr_filterColor(vec4(0));
}
`;
const TEST_MODULE = {
name: 'TEST_MODULE',
inject: {
'vs:#decl': `uniform float vsFloat;`,
// Hook function has access to injected variable
'vs:HOOK_FUNCTION': 'value = vsFloat;',
'fs:#decl': `uniform vec4 fsVec4;`,
// Hook function has access to injected variable
'fs:HOOK_FUNCTION': 'value = fsVec4;'
}
};
const VS_GLSL_300_MODULES = `\
#version 300 es
in float floatAttribute;
out float floatVarying;
void main(void) {
HOOK_FUNCTION(floatVarying);
}
`;
const FS_GLSL_300_MODULES = `\
#version 300 es
precision highp float;
in float floatVarying;
out vec4 fragmentColor;
void main(void) {
HOOK_FUNCTION(fragmentColor);
}
`;
test('assembleShaders#import', (t) => {
t.ok(assembleShaders !== undefined, 'assembleShaders import successful');
t.end();
});
test('assembleShaders#version_directive', (t) => {
const assembleResult = assembleShaders(getInfo(webgl1TestDevice), {
vs: VS_GLSL_300,
fs: FS_GLSL_300,
modules: [picking]
});
// Verify version directive remains as first line.
t.equal(
assembleResult.vs.indexOf('#version 300 es'),
0,
'version directive should be first statement'
);
t.equal(
assembleResult.fs.indexOf('#version 300 es'),
0,
'version directive should be first statement'
);
t.end();
});
test('assembleShaders#getUniforms', (t) => {
// inject spy into the picking module's getUniforms
// const module = getShaderModule(picking);
// const getUniformsSpy = makeSpy(module, 'getUniforms');
let assembleResult;
// Without shader modules
assembleResult = assembleShaders(getInfo(webgl1TestDevice), {
vs: VS_GLSL_300,
fs: FS_GLSL_300
});
// Verify getUniforms is function
t.is(typeof assembleResult.getUniforms, 'function', 'getUniforms should be function');
// With shader modules
const testModule = {
name: 'test-module',
vs: '',
fs: '',
getUniforms: (opts, context) => {
// Check a uniform generated by its dependency
t.ok(context.picking_uActive, 'module getUniforms is called with correct context');
return {};
},
dependencies: [picking]
};
assembleResult = assembleShaders(getInfo(webgl1TestDevice), {
vs: VS_GLSL_300,
fs: FS_GLSL_300,
modules: [picking, testModule, fp64]
});
// Verify getUniforms is function
t.is(typeof assembleResult.getUniforms, 'function', 'getUniforms should be function');
t.end();
});
test('assembleShaders#defines', (t) => {
const assembleResult = assembleShaders(getInfo(webgl1TestDevice), {
vs: VS_GLSL_300,
fs: FS_GLSL_300,
defines: {IS_TEST: true}
});
t.ok(assembleResult.vs.indexOf('#define IS_TEST true') > 0, 'has application defines');
t.ok(assembleResult.fs.indexOf('#define IS_TEST true') > 0, 'has application defines');
t.end();
});
test('assembleShaders#shaderhooks', (t) => {
const hookFunctions = [
'vs:LUMAGL_pickColor(inout vec4 color)',
{
hook: 'fs:LUMAGL_fragmentColor(inout vec4 color)',
header: 'if (color.a == 0.0) discard;\n',
footer: 'color.a *= 1.2;\n'
}
];
const pickingInject = Object.assign(
{
inject: {
'vs:LUMAGL_pickColor': 'picking_setPickingColor(color.rgb);',
'fs:LUMAGL_fragmentColor': {
injection: 'color = picking_filterColor(color);',
order: Number.POSITIVE_INFINITY
},
'fs:#main-end': 'gl_FragColor = picking_filterColor(gl_FragColor);'
}
},
picking
);
const testInject = {
name: 'test-injection',
inject: {
'fs:LUMAGL_fragmentColor': 'color.r = 1.0;'
}
};
let assembleResult = assembleShaders(getInfo(webgl1TestDevice), {
vs: VS_GLSL_300,
fs: FS_GLSL_300,
hookFunctions
});
// Verify version directive remains as first line.
t.ok(
assembleResult.vs.indexOf('LUMAGL_pickColor') > -1,
'hook function injected into vertex shader'
);
t.ok(
assembleResult.fs.indexOf('LUMAGL_fragmentColor') > -1,
'hook function injected into fragment shader'
);
t.ok(
assembleResult.fs.indexOf('if (color.a == 0.0) discard;') > -1,
'hook header injected into fragment shader'
);
t.ok(
assembleResult.vs.indexOf('picking_setPickingColor(color.rgb)') === -1,
'injection code not included in vertex shader without module'
);
t.ok(
assembleResult.fs.indexOf('color = picking_filterColor(color)') === -1,
'injection code not included in fragment shader without module'
);
t.ok(
assembleResult.fs.indexOf('fragmentColor = picking_filterColor(fragmentColor)') === -1,
'regex injection code not included in fragment shader without module'
);
assembleResult = assembleShaders(getInfo(webgl1TestDevice), {
vs: VS_GLSL_300,
fs: FS_GLSL_300,
modules: [pickingInject],
hookFunctions
});
// Verify version directive remains as first line.
t.ok(
assembleResult.vs.indexOf('LUMAGL_pickColor') > -1,
'hook function injected into vertex shader'
);
t.ok(
assembleResult.fs.indexOf('LUMAGL_fragmentColor') > -1,
'hook function injected into fragment shader'
);
t.ok(
assembleResult.vs.indexOf('picking_setPickingColor(color.rgb)') > -1,
'injection code included in vertex shader with module'
);
t.ok(
assembleResult.fs.indexOf('color = picking_filterColor(color)') > -1,
'injection code included in fragment shader with module'
);
t.ok(
assembleResult.fs.indexOf('color.a *= 1.2;') >
assembleResult.fs.indexOf('color = picking_filterColor(color)'),
'hook footer injected after injection code'
);
t.ok(
assembleResult.fs.indexOf('fragmentColor = picking_filterColor(fragmentColor)') > -1,
'regex injection code included in fragment shader with module'
);
assembleResult = assembleShaders(getInfo(webgl1TestDevice), {
vs: VS_GLSL_300,
fs: FS_GLSL_300,
inject: {
'vs:LUMAGL_pickColor': 'color *= 0.1;',
'fs:LUMAGL_fragmentColor': 'color += 0.1;'
},
modules: [pickingInject],
hookFunctions
});
t.ok(
assembleResult.vs.indexOf('color *= 0.1') > -1,
'argument injection code included in shader hook'
);
t.ok(
assembleResult.fs.indexOf('color += 0.1') > -1,
'argument injection code included in shader hook'
);
t.ok(
assembleResult.fs.indexOf('color += 0.1') <
assembleResult.fs.indexOf('color = picking_filterColor(color)'),
'argument injection code injected in the correct order'
);
assembleResult = assembleShaders(getInfo(webgl1TestDevice), {
vs: VS_GLSL_300,
fs: FS_GLSL_300,
modules: [pickingInject, testInject],
hookFunctions
});
t.ok(
assembleResult.fs.indexOf('color.r = 1.0') > -1,
'module injection code included in shader hook'
);
t.ok(
assembleResult.fs.indexOf('color.r = 1.0') <
assembleResult.fs.indexOf('color = picking_filterColor(color)'),
'module injection code injected in the correct order'
);
assembleResult = assembleShaders(getInfo(webgl1TestDevice), {
vs: VS_GLSL_300,
fs: FS_GLSL_300,
inject: {
'fragmentColor = vec4(1.0, 1.0, 1.0, 1.0);': 'fragmentColor -= 0.1;'
},
hookFunctions
});
t.ok(
assembleResult.fs.indexOf('fragmentColor -= 0.1;') > -1,
'regex injection code included in shader hook'
);
t.end();
});
test('assembleShaders#injection order', (t) => {
let assembleResult = assembleShaders(getInfo(webgl1TestDevice), {
vs: VS_GLSL_300_MODULES,
fs: FS_GLSL_300_MODULES,
inject: {
'vs:#decl': `uniform float vsFloat;`,
// Hook function has access to injected variable
'vs:HOOK_FUNCTION': 'value = vsFloat;',
'fs:#decl': `uniform vec4 fsVec4;`,
// Hook function has access to injected variable
'fs:HOOK_FUNCTION': 'value = fsVec4;'
},
transpileToGLSL100: true,
hookFunctions: ['vs:HOOK_FUNCTION(inout float value)', 'fs:HOOK_FUNCTION(inout vec4 value)']
});
t.ok(
compileAndLinkShaders(t, webgl1TestDevice, assembleResult),
'Hook functions have access to injected variables.'
);
assembleResult = assembleShaders(getInfo(webgl1TestDevice), {
vs: VS_GLSL_300_MODULES,
fs: FS_GLSL_300_MODULES,
modules: [TEST_MODULE],
transpileToGLSL100: true,
hookFunctions: ['vs:HOOK_FUNCTION(inout float value)', 'fs:HOOK_FUNCTION(inout vec4 value)']
});
t.ok(
compileAndLinkShaders(t, webgl1TestDevice, assembleResult),
'Hook functions have access to injected variables through modules.'
);
t.end();
});
test('assembleShaders#transpilation', (t) => {
let assembleResult = assembleShaders(getInfo(webgl1TestDevice), {
vs: VS_GLSL_300,
fs: FS_GLSL_300,
modules: [picking],
transpileToGLSL100: true
});
t.ok(assembleResult.vs.indexOf('#version 300 es') === -1, 'es 3.0 version directive removed');
t.ok(!assembleResult.vs.match(/\bin vec4\b/), '"in" keyword removed');
t.ok(assembleResult.fs.indexOf('#version 300 es') === -1, 'es 3.0 version directive removed');
t.ok(!assembleResult.fs.match(/\bout vec4\b/), '"out" keyword removed');
t.ok(compileAndLinkShaders(t, webgl1TestDevice, assembleResult), 'assemble GLSL300 + picking and transpile to GLSL100');
assembleResult = assembleShaders(getInfo(webgl1TestDevice), {
vs: VS_GLSL_300_2,
fs: FS_GLSL_300_2,
modules: [picking],
transpileToGLSL100: true
});
t.ok(compileAndLinkShaders(t, webgl1TestDevice, assembleResult), 'assemble GLSL300 + picking and transpile to GLSL100');
/* TODO - broken test, common_space varying broken
if (gl.getExtension('OES_standard_derivatives')) {
assembleResult = assembleShaders(getInfo(webgl1TestDevice), {
vs: VS_GLSL_300_DECK,
fs: FS_GLSL_300_DECK,
transpileToGLSL100: true
});
t.ok(
compileAndLinkShaders(t, webgl1TestDevice, assembleResult),
'Deck shaders transpile 300 to 100 valid program'
);
}
*/
assembleResult = assembleShaders(getInfo(webgl1TestDevice), {
vs: VS_GLSL_300_GLTF,
fs: FS_GLSL_300_GLTF,
modules: [pbr],
transpileToGLSL100: true
});
t.ok(
compileAndLinkShaders(t, webgl1TestDevice, assembleResult),
'assemble GLSL300 + PBR assemble to 100'
);
if (webgl2TestDevice) {
assembleResult = assembleShaders(getInfo(webgl2TestDevice), {
vs: VS_GLSL_300_GLTF,
fs: FS_GLSL_300_GLTF,
modules: [pbr],
transpileToGLSL100: false
});
t.ok(
compileAndLinkShaders(t, webgl2TestDevice, assembleResult),
'assemble GLSL300 + PBR assemble to 100, WebGL2'
);
}
t.end();
});
// HELPERS
function compileAndLinkShaders(t, device: WebGLDevice, assembleResult) {
const gl = device.gl;
let vShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vShader, assembleResult.vs);
gl.compileShader(vShader);
let compileStatus = gl.getShaderParameter(vShader, gl.COMPILE_STATUS);
if (!compileStatus) {
const infoLog = gl.getShaderInfoLog(vShader);
t.comment(`VS COMPILATION LOG: ${infoLog}`);
return false;
}
let fShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fShader, assembleResult.fs);
gl.compileShader(fShader);
compileStatus = gl.getShaderParameter(fShader, gl.COMPILE_STATUS);
if (!compileStatus) {
const infoLog = gl.getShaderInfoLog(fShader);
t.comment(`FS COMPLIATION LOG: ${infoLog}`);
return false;
}
let program = gl.createProgram();
gl.attachShader(program, vShader);
gl.attachShader(program, fShader);
gl.linkProgram(program);
const linkStatus = gl.getProgramParameter(program, gl.LINK_STATUS);
if (!linkStatus) {
const infoLog = gl.getProgramInfoLog(program);
t.comment(`LINKLOG ${infoLog}`);
}
gl.deleteShader(vShader);
gl.deleteShader(fShader);
gl.deleteProgram(program);
return linkStatus;
} | the_stack |
import * as tf from '../index';
import {ALL_ENVS, describeWithFlags} from '../jasmine_util';
import {expectArraysClose, expectArraysEqual} from '../test_util';
describeWithFlags('greaterEqual', ALL_ENVS, () => {
// Tensor1D:
it('Tensor1D - int32', async () => {
let a = tf.tensor1d([1, 4, 5], 'int32');
let b = tf.tensor1d([2, 3, 5], 'int32');
let res = tf.greaterEqual(a, b);
expect(res.dtype).toBe('bool');
expectArraysClose(await res.data(), [0, 1, 1]);
a = tf.tensor1d([2, 2, 2], 'int32');
b = tf.tensor1d([2, 2, 2], 'int32');
res = tf.greaterEqual(a, b);
expect(res.dtype).toBe('bool');
expectArraysClose(await res.data(), [1, 1, 1]);
a = tf.tensor1d([0, 0], 'int32');
b = tf.tensor1d([3, 3], 'int32');
res = tf.greaterEqual(a, b);
expect(res.dtype).toBe('bool');
expectArraysClose(await res.data(), [0, 0]);
});
it('Tensor1D - float32', async () => {
let a = tf.tensor1d([1.1, 4.1, 5.1], 'float32');
let b = tf.tensor1d([2.2, 3.2, 5.1], 'float32');
let res = tf.greaterEqual(a, b);
expect(res.dtype).toBe('bool');
expectArraysClose(await res.data(), [0, 1, 1]);
a = tf.tensor1d([2.31, 2.31, 2.31], 'float32');
b = tf.tensor1d([2.31, 2.31, 2.31], 'float32');
res = tf.greaterEqual(a, b);
expect(res.dtype).toBe('bool');
expectArraysClose(await res.data(), [1, 1, 1]);
a = tf.tensor1d([0.45, 0.123], 'float32');
b = tf.tensor1d([3.123, 3.321], 'float32');
res = tf.greaterEqual(a, b);
expect(res.dtype).toBe('bool');
expectArraysClose(await res.data(), [0, 0]);
});
it('upcasts when dtypes dont match', async () => {
const a = [1.1, 4.1, 5];
const b = [2.2, 3.2, 5];
let res = tf.greaterEqual(
tf.tensor(a, [3], 'float32'), tf.tensor(b, [3], 'int32'));
expect(res.dtype).toBe('bool');
expect(res.shape).toEqual([3]);
expectArraysClose(await res.data(), [0, 1, 1]);
res =
tf.greaterEqual(tf.tensor(a, [3], 'int32'), tf.tensor(b, [3], 'bool'));
expect(res.dtype).toBe('bool');
expect(res.shape).toEqual([3]);
expectArraysClose(await res.data(), [1, 1, 1]);
});
it('mismatched Tensor1D shapes - int32', () => {
const a = tf.tensor1d([1, 2], 'int32');
const b = tf.tensor1d([1, 2, 3], 'int32');
const f = () => {
tf.greaterEqual(a, b);
};
expect(f).toThrowError();
});
it('mismatched Tensor1D shapes - float32', () => {
const a = tf.tensor1d([1.1, 2.1], 'float32');
const b = tf.tensor1d([1.1, 2.1, 3.1], 'float32');
const f = () => {
tf.greaterEqual(a, b);
};
expect(f).toThrowError();
});
it('NaNs in Tensor1D - float32', async () => {
const a = tf.tensor1d([1.1, NaN, 2.1], 'float32');
const b = tf.tensor1d([2.1, 3.1, NaN], 'float32');
const res = tf.greaterEqual(a, b);
expect(res.dtype).toBe('bool');
expectArraysClose(await res.data(), [0, 0, 0]);
});
// Tensor2D:
it('Tensor2D - int32', async () => {
let a = tf.tensor2d([[1, 4, 5], [8, 9, 12]], [2, 3], 'int32');
let b = tf.tensor2d([[2, 3, 6], [7, 10, 11]], [2, 3], 'int32');
let res = tf.greaterEqual(a, b);
expect(res.dtype).toBe('bool');
expectArraysClose(await res.data(), [0, 1, 0, 1, 0, 1]);
a = tf.tensor2d([[0, 0], [1, 1]], [2, 2], 'int32');
b = tf.tensor2d([[0, 0], [1, 1]], [2, 2], 'int32');
res = tf.greaterEqual(a, b);
expect(res.dtype).toBe('bool');
expectArraysClose(await res.data(), [1, 1, 1, 1]);
});
it('Tensor2D - float32', async () => {
let a = tf.tensor2d([[1.1, 4.1, 5.1], [8.1, 9.1, 12.1]], [2, 3], 'float32');
let b =
tf.tensor2d([[2.1, 3.1, 6.1], [7.1, 10.1, 11.1]], [2, 3], 'float32');
let res = tf.greaterEqual(a, b);
expect(res.dtype).toBe('bool');
expectArraysClose(await res.data(), [0, 1, 0, 1, 0, 1]);
a = tf.tensor2d([[0.2, 0.2], [1.2, 1.2]], [2, 2], 'float32');
b = tf.tensor2d([[0.2, 0.2], [1.2, 1.2]], [2, 2], 'float32');
res = tf.greaterEqual(a, b);
expect(res.dtype).toBe('bool');
expectArraysClose(await res.data(), [1, 1, 1, 1]);
});
it('broadcasting Tensor2D shapes - int32', async () => {
const a = tf.tensor2d([[3], [7]], [2, 1], 'int32');
const b = tf.tensor2d([[2, 3, 4], [7, 8, 9]], [2, 3], 'int32');
const res = tf.greaterEqual(a, b);
expect(res.dtype).toBe('bool');
expectArraysClose(await res.data(), [1, 1, 0, 1, 0, 0]);
});
it('broadcasting Tensor2D shapes - float32', async () => {
const a = tf.tensor2d([[1.1], [7.1]], [2, 1], 'float32');
const b =
tf.tensor2d([[0.1, 1.1, 2.1], [7.1, 8.1, 9.1]], [2, 3], 'float32');
const res = tf.greaterEqual(a, b);
expect(res.dtype).toBe('bool');
expectArraysClose(await res.data(), [1, 1, 0, 1, 0, 0]);
});
it('NaNs in Tensor2D - float32', async () => {
const a = tf.tensor2d([[1.1, NaN], [0.1, NaN]], [2, 2], 'float32');
const b = tf.tensor2d([[0.1, NaN], [1.1, NaN]], [2, 2], 'float32');
const res = tf.greaterEqual(a, b);
expect(res.dtype).toBe('bool');
expectArraysClose(await res.data(), [1, 0, 0, 0]);
});
// Tensor3D:
it('Tensor3D - int32', async () => {
let a =
tf.tensor3d([[[1], [4], [5]], [[8], [9], [12]]], [2, 3, 1], 'int32');
let b =
tf.tensor3d([[[2], [3], [6]], [[7], [10], [11]]], [2, 3, 1], 'int32');
let res = tf.greaterEqual(a, b);
expect(res.dtype).toBe('bool');
expectArraysClose(await res.data(), [0, 1, 0, 1, 0, 1]);
a = tf.tensor3d([[[0], [0], [0]], [[1], [1], [1]]], [2, 3, 1], 'int32');
b = tf.tensor3d([[[0], [0], [0]], [[1], [1], [1]]], [2, 3, 1], 'int32');
res = tf.greaterEqual(a, b);
expect(res.dtype).toBe('bool');
expectArraysClose(await res.data(), [1, 1, 1, 1, 1, 1]);
});
it('Tensor3D - float32', async () => {
let a = tf.tensor3d(
[[[1.1], [4.1], [5.1]], [[8.1], [9.1], [12.1]]], [2, 3, 1], 'float32');
let b = tf.tensor3d(
[[[2.1], [3.1], [6.1]], [[7.1], [10.1], [11.1]]], [2, 3, 1], 'float32');
let res = tf.greaterEqual(a, b);
expect(res.dtype).toBe('bool');
expectArraysClose(await res.data(), [0, 1, 0, 1, 0, 1]);
a = tf.tensor3d(
[[[0.1], [0.1], [0.1]], [[1.1], [1.1], [1.2]]], [2, 3, 1], 'float32');
b = tf.tensor3d(
[[[0.1], [0.1], [0.1]], [[1.1], [1.1], [1.1]]], [2, 3, 1], 'float32');
res = tf.greaterEqual(a, b);
expect(res.dtype).toBe('bool');
expectArraysClose(await res.data(), [1, 1, 1, 1, 1, 1]);
});
it('broadcasting Tensor3D shapes - int32', async () => {
const a = tf.tensor3d(
[[[1, 0], [2, 3], [4, 5]], [[6, 7], [9, 8], [10, 11]]], [2, 3, 2],
'int32');
const b =
tf.tensor3d([[[1], [2], [3]], [[7], [10], [9]]], [2, 3, 1], 'int32');
const res = tf.greaterEqual(a, b);
expect(res.dtype).toBe('bool');
expectArraysClose(await res.data(), [1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1]);
});
it('broadcasting Tensor3D shapes - float32', async () => {
const a = tf.tensor3d(
[
[[1.1, 0.1], [2.1, 3.1], [4.1, 5.1]],
[[6.1, 7.1], [9.1, 8.1], [10.1, 11.1]]
],
[2, 3, 2], 'float32');
const b = tf.tensor3d(
[[[1.1], [2.1], [3.1]], [[7.1], [10.1], [9.1]]], [2, 3, 1], 'float32');
const res = tf.greaterEqual(a, b);
expect(res.dtype).toBe('bool');
expectArraysClose(await res.data(), [1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1]);
});
it('NaNs in Tensor3D - float32', async () => {
const a = tf.tensor3d(
[[[1.1], [NaN], [1.1]], [[0.1], [0.1], [0.1]]], [2, 3, 1], 'float32');
const b = tf.tensor3d(
[[[0.1], [0.1], [1.1]], [[1.1], [0.1], [NaN]]], [2, 3, 1], 'float32');
const res = tf.greaterEqual(a, b);
expect(res.dtype).toBe('bool');
expectArraysClose(await res.data(), [1, 0, 1, 0, 1, 0]);
});
// Tensor4D:
it('Tensor4D - int32', async () => {
let a = tf.tensor4d([1, 4, 5, 8], [2, 2, 1, 1], 'int32');
let b = tf.tensor4d([2, 3, 6, 7], [2, 2, 1, 1], 'int32');
let res = tf.greaterEqual(a, b);
expect(res.dtype).toBe('bool');
expectArraysClose(await res.data(), [0, 1, 0, 1]);
a = tf.tensor4d([0, 1, 2, 3], [2, 2, 1, 1], 'int32');
b = tf.tensor4d([0, 1, 2, 3], [2, 2, 1, 1], 'int32');
res = tf.greaterEqual(a, b);
expect(res.dtype).toBe('bool');
expectArraysClose(await res.data(), [1, 1, 1, 1]);
a = tf.tensor4d([1, 1, 1, 1], [2, 2, 1, 1], 'int32');
b = tf.tensor4d([2, 2, 2, 2], [2, 2, 1, 1], 'int32');
res = tf.greaterEqual(a, b);
expect(res.dtype).toBe('bool');
expectArraysClose(await res.data(), [0, 0, 0, 0]);
});
it('Tensor4D - float32', async () => {
let a = tf.tensor4d([1.1, 4.1, 5.1, 8.1], [2, 2, 1, 1], 'float32');
let b = tf.tensor4d([2.1, 3.1, 6.1, 7.1], [2, 2, 1, 1], 'float32');
let res = tf.greaterEqual(a, b);
expect(res.dtype).toBe('bool');
expectArraysClose(await res.data(), [0, 1, 0, 1]);
a = tf.tensor4d([0.1, 1.1, 2.2, 3.3], [2, 2, 1, 1], 'float32');
b = tf.tensor4d([0.1, 1.1, 2.2, 3.3], [2, 2, 1, 1], 'float32');
res = tf.greaterEqual(a, b);
expect(res.dtype).toBe('bool');
expectArraysClose(await res.data(), [1, 1, 1, 1]);
a = tf.tensor4d([0.1, 0.1, 0.1, 0.1], [2, 2, 1, 1], 'float32');
b = tf.tensor4d([1.1, 1.1, 1.1, 1.1], [2, 2, 1, 1], 'float32');
res = tf.greaterEqual(a, b);
expect(res.dtype).toBe('bool');
expectArraysClose(await res.data(), [0, 0, 0, 0]);
});
it('broadcasting Tensor4D shapes - int32', async () => {
const a = tf.tensor4d([1, 2, 5, 9], [2, 2, 1, 1], 'int32');
const b = tf.tensor4d(
[[[[1, 2]], [[3, 4]]], [[[5, 6]], [[7, 8]]]], [2, 2, 1, 2], 'int32');
const res = tf.greaterEqual(a, b);
expect(res.dtype).toBe('bool');
expectArraysClose(await res.data(), [1, 0, 0, 0, 1, 0, 1, 1]);
});
it('broadcasting Tensor4D shapes - float32', async () => {
const a = tf.tensor4d([1.1, 2.1, 5.1, 9.1], [2, 2, 1, 1], 'float32');
const b = tf.tensor4d(
[[[[1.1, 2.1]], [[3.1, 4.1]]], [[[5.1, 6.1]], [[7.1, 8.1]]]],
[2, 2, 1, 2], 'float32');
const res = tf.greaterEqual(a, b);
expect(res.dtype).toBe('bool');
expectArraysClose(await res.data(), [1, 0, 0, 0, 1, 0, 1, 1]);
});
it('NaNs in Tensor4D - float32', async () => {
const a = tf.tensor4d([1.1, NaN, 0.1, 0.1], [2, 2, 1, 1], 'float32');
const b = tf.tensor4d([0.1, 1.1, 1.1, NaN], [2, 2, 1, 1], 'float32');
const res = tf.greaterEqual(a, b);
expect(res.dtype).toBe('bool');
expectArraysClose(await res.data(), [1, 0, 0, 0]);
});
it('throws when passed a as a non-tensor', () => {
expect(() => tf.greaterEqual({} as tf.Tensor, tf.scalar(1)))
.toThrowError(/Argument 'a' passed to 'greaterEqual' must be a Tensor/);
});
it('throws when passed b as a non-tensor', () => {
expect(() => tf.greaterEqual(tf.scalar(1), {} as tf.Tensor))
.toThrowError(/Argument 'b' passed to 'greaterEqual' must be a Tensor/);
});
it('accepts a tensor-like object', async () => {
const a = [1, 4, 5];
const b = [2, 3, 5];
const res = tf.greaterEqual(a, b);
expect(res.dtype).toBe('bool');
expectArraysClose(await res.data(), [0, 1, 1]);
});
it('has gradient', async () => {
const a = tf.tensor1d([3, 2, 5]);
const b = tf.tensor1d([4, 1, 5]);
const dy = tf.ones([3], 'float32');
const da = tf.grad((a: tf.Tensor1D) => tf.greaterEqual(a, b))(a, dy);
expect(da.dtype).toBe('float32');
expect(da.shape).toEqual([3]);
expectArraysClose(await da.data(), [0, 0, 0]);
});
it('gradient with clones', async () => {
const a = tf.tensor1d([3, 2, 5]);
const b = tf.tensor1d([4, 1, 5]);
const dy = tf.ones([3], 'float32');
const da = tf.grad(
(a: tf.Tensor1D) => tf.greaterEqual(a.clone(), b.clone()).clone())(
a, dy);
expect(da.dtype).toBe('float32');
expect(da.shape).toEqual([3]);
expectArraysClose(await da.data(), [0, 0, 0]);
});
it('should support string comparison', async () => {
const tensorA = tf.tensor('a', [], 'string');
const tensorB = tf.tensor(['a', 'b', ''], [3], 'string');
const result = await tf.greaterEqual(tensorA, tensorB);
expectArraysEqual(result.shape, [3]);
expectArraysEqual(await result.data(), [1, 0, 1]);
});
}); | the_stack |
import { CloudErrorMapper, BaseResourceMapper } from "@azure/ms-rest-azure-js";
import * as msRest from "@azure/ms-rest-js";
export const CloudError = CloudErrorMapper;
export const BaseResource = BaseResourceMapper;
export const RoleDefinitionFilter: msRest.CompositeMapper = {
serializedName: "RoleDefinitionFilter",
type: {
name: "Composite",
className: "RoleDefinitionFilter",
modelProperties: {
roleName: {
serializedName: "roleName",
type: {
name: "String"
}
}
}
}
};
export const Permission: msRest.CompositeMapper = {
serializedName: "Permission",
type: {
name: "Composite",
className: "Permission",
modelProperties: {
actions: {
serializedName: "actions",
type: {
name: "Sequence",
element: {
type: {
name: "String"
}
}
}
},
notActions: {
serializedName: "notActions",
type: {
name: "Sequence",
element: {
type: {
name: "String"
}
}
}
}
}
}
};
export const RoleDefinition: msRest.CompositeMapper = {
serializedName: "RoleDefinition",
type: {
name: "Composite",
className: "RoleDefinition",
modelProperties: {
id: {
readOnly: true,
serializedName: "id",
type: {
name: "String"
}
},
name: {
readOnly: true,
serializedName: "name",
type: {
name: "String"
}
},
type: {
readOnly: true,
serializedName: "type",
type: {
name: "String"
}
},
roleName: {
serializedName: "properties.roleName",
type: {
name: "String"
}
},
description: {
serializedName: "properties.description",
type: {
name: "String"
}
},
roleType: {
serializedName: "properties.type",
type: {
name: "String"
}
},
permissions: {
serializedName: "properties.permissions",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "Permission"
}
}
}
},
assignableScopes: {
serializedName: "properties.assignableScopes",
type: {
name: "Sequence",
element: {
type: {
name: "String"
}
}
}
}
}
}
};
export const ProviderOperation: msRest.CompositeMapper = {
serializedName: "ProviderOperation",
type: {
name: "Composite",
className: "ProviderOperation",
modelProperties: {
name: {
serializedName: "name",
type: {
name: "String"
}
},
displayName: {
serializedName: "displayName",
type: {
name: "String"
}
},
description: {
serializedName: "description",
type: {
name: "String"
}
},
origin: {
serializedName: "origin",
type: {
name: "String"
}
},
properties: {
serializedName: "properties",
type: {
name: "Object"
}
}
}
}
};
export const ResourceType: msRest.CompositeMapper = {
serializedName: "ResourceType",
type: {
name: "Composite",
className: "ResourceType",
modelProperties: {
name: {
serializedName: "name",
type: {
name: "String"
}
},
displayName: {
serializedName: "displayName",
type: {
name: "String"
}
},
operations: {
serializedName: "operations",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ProviderOperation"
}
}
}
}
}
}
};
export const ProviderOperationsMetadata: msRest.CompositeMapper = {
serializedName: "ProviderOperationsMetadata",
type: {
name: "Composite",
className: "ProviderOperationsMetadata",
modelProperties: {
id: {
serializedName: "id",
type: {
name: "String"
}
},
name: {
serializedName: "name",
type: {
name: "String"
}
},
type: {
serializedName: "type",
type: {
name: "String"
}
},
displayName: {
serializedName: "displayName",
type: {
name: "String"
}
},
resourceTypes: {
serializedName: "resourceTypes",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ResourceType"
}
}
}
},
operations: {
serializedName: "operations",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ProviderOperation"
}
}
}
}
}
}
};
export const RoleAssignmentFilter: msRest.CompositeMapper = {
serializedName: "RoleAssignmentFilter",
type: {
name: "Composite",
className: "RoleAssignmentFilter",
modelProperties: {
principalId: {
serializedName: "principalId",
type: {
name: "String"
}
}
}
}
};
export const RoleAssignmentPropertiesWithScope: msRest.CompositeMapper = {
serializedName: "RoleAssignmentPropertiesWithScope",
type: {
name: "Composite",
className: "RoleAssignmentPropertiesWithScope",
modelProperties: {
scope: {
serializedName: "scope",
type: {
name: "String"
}
},
roleDefinitionId: {
serializedName: "roleDefinitionId",
type: {
name: "String"
}
},
principalId: {
serializedName: "principalId",
type: {
name: "String"
}
}
}
}
};
export const RoleAssignment: msRest.CompositeMapper = {
serializedName: "RoleAssignment",
type: {
name: "Composite",
className: "RoleAssignment",
modelProperties: {
id: {
readOnly: true,
serializedName: "id",
type: {
name: "String"
}
},
name: {
readOnly: true,
serializedName: "name",
type: {
name: "String"
}
},
type: {
readOnly: true,
serializedName: "type",
type: {
name: "String"
}
},
properties: {
serializedName: "properties",
type: {
name: "Composite",
className: "RoleAssignmentPropertiesWithScope"
}
}
}
}
};
export const RoleAssignmentProperties: msRest.CompositeMapper = {
serializedName: "RoleAssignmentProperties",
type: {
name: "Composite",
className: "RoleAssignmentProperties",
modelProperties: {
roleDefinitionId: {
required: true,
serializedName: "roleDefinitionId",
type: {
name: "String"
}
},
principalId: {
required: true,
serializedName: "principalId",
type: {
name: "String"
}
}
}
}
};
export const RoleAssignmentCreateParameters: msRest.CompositeMapper = {
serializedName: "RoleAssignmentCreateParameters",
type: {
name: "Composite",
className: "RoleAssignmentCreateParameters",
modelProperties: {
properties: {
required: true,
serializedName: "properties",
type: {
name: "Composite",
className: "RoleAssignmentProperties"
}
}
}
}
};
export const PermissionGetResult: msRest.CompositeMapper = {
serializedName: "PermissionGetResult",
type: {
name: "Composite",
className: "PermissionGetResult",
modelProperties: {
value: {
serializedName: "",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "Permission"
}
}
}
},
nextLink: {
serializedName: "nextLink",
type: {
name: "String"
}
}
}
}
};
export const RoleDefinitionListResult: msRest.CompositeMapper = {
serializedName: "RoleDefinitionListResult",
type: {
name: "Composite",
className: "RoleDefinitionListResult",
modelProperties: {
value: {
serializedName: "",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "RoleDefinition"
}
}
}
},
nextLink: {
serializedName: "nextLink",
type: {
name: "String"
}
}
}
}
};
export const ProviderOperationsMetadataListResult: msRest.CompositeMapper = {
serializedName: "ProviderOperationsMetadataListResult",
type: {
name: "Composite",
className: "ProviderOperationsMetadataListResult",
modelProperties: {
value: {
serializedName: "",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ProviderOperationsMetadata"
}
}
}
},
nextLink: {
serializedName: "nextLink",
type: {
name: "String"
}
}
}
}
};
export const RoleAssignmentListResult: msRest.CompositeMapper = {
serializedName: "RoleAssignmentListResult",
type: {
name: "Composite",
className: "RoleAssignmentListResult",
modelProperties: {
value: {
serializedName: "",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "RoleAssignment"
}
}
}
},
nextLink: {
serializedName: "nextLink",
type: {
name: "String"
}
}
}
}
}; | the_stack |
import { default as substitutions, IMatrixToSlackResult } from "../../src/substitutions";
import { FakeMain } from "../utils/fakeMain";
import { expect } from "chai";
import { Main } from "../../src/Main";
import { BridgedRoom } from "../../src/BridgedRoom";
describe("Substitutions", () => {
const fakeMain = new FakeMain({
oauth2: false,
usersInTeam: [
{
display_name: "Stranger",
slack_id: "12345",
id: "@_slack_12345:localhost",
avatar_url: "",
},
{
display_name: "Alice",
slack_id: "12346",
id: "@_slack_12346:localhost",
avatar_url: "",
},
{
display_name: "Alice Bob",
slack_id: "12347",
id: "@_slack_12347:localhost",
avatar_url: "",
},
],
}) as unknown as Main;
fakeMain.rooms.upsertRoom(new BridgedRoom(fakeMain, {
matrix_room_id: "!working:localhost",
slack_channel_id: "workingslackchannel",
slack_team_id: "footeam",
inbound_id: "foo",
slack_type: "unknown",
}));
fakeMain.rooms.upsertRoom(new BridgedRoom(fakeMain, {
matrix_room_id: "!alsoworking:localhost",
slack_channel_id: "alsoworkingslackchannel",
slack_team_id: "footeam",
inbound_id: "foo",
slack_type: "unknown",
}));
describe("matrixToSlack", () => {
it ("should reject a message with no content", async () => {
const res = await substitutions.matrixToSlack({ }, fakeMain, "");
expect(res).to.be.null;
});
it ("should reject a message with invalid content", async () => {
let res: IMatrixToSlackResult | null;
res = await substitutions.matrixToSlack({ content: { } }, fakeMain, "");
expect(res).to.be.null;
res = await substitutions.matrixToSlack({ content: { body: "" } }, fakeMain, "");
expect(res).to.be.null;
res = await substitutions.matrixToSlack({ content: { body: 0 } }, fakeMain, "");
expect(res).to.be.null;
res = await substitutions.matrixToSlack({ content: { body: true } }, fakeMain, "");
expect(res).to.be.null;
res = await substitutions.matrixToSlack({ content: { body: { foo: "bar"} } }, fakeMain, "");
expect(res).to.be.null;
// No sender
res = await substitutions.matrixToSlack({ content: { body: "bar" } }, fakeMain, "");
expect(res).to.be.null;
});
it ("should allow a simple text message with no msgtype", async () => {
const res = await substitutions.matrixToSlack({
content: {
body: "Hello world!",
},
sender: "@alice:localhost",
}, fakeMain, "");
expect(res).to.deep.equal({
link_names: true,
text: "Hello world!",
username: "@alice:localhost",
});
});
it ("should allow a simple m.text message", async () => {
const res = await substitutions.matrixToSlack({
content: {
body: "Hello world!",
msgtype: "m.text",
},
sender: "@alice:localhost",
}, fakeMain, "");
expect(res).to.deep.equal({
link_names: true,
text: "Hello world!",
username: "@alice:localhost",
});
});
it ("should allow a simple message with any other type", async () => {
const res = await substitutions.matrixToSlack({
content: {
body: "Hello world!",
msgtype: "org.matrix.fake.message.type",
},
sender: "@alice:localhost",
}, fakeMain, "");
expect(res).to.deep.equal({
link_names: true,
text: "Hello world!",
username: "@alice:localhost",
});
});
it ("should handle m.emote", async () => {
const res = await substitutions.matrixToSlack({
content: {
body: "This is not sarcasm",
msgtype: "m.emote",
},
sender: "@alice:localhost",
}, fakeMain, "");
expect(res).to.deep.equal({
link_names: true,
text: "_This is not sarcasm_",
username: "@alice:localhost",
});
});
it ("should replace <, > and & with HTML codes", async () => {
const res = await substitutions.matrixToSlack({
content: {
body: "Let's talk about <html> and the & character",
},
sender: "@alice:localhost",
}, fakeMain, "");
expect(res).to.deep.equal({
link_names: true,
text: "Let's talk about <html> and the & character",
username: "@alice:localhost",
});
});
it ("should replace @room with @channel", async () => {
const res = await substitutions.matrixToSlack({
content: {
body: "@room Hello everyone!",
},
sender: "@alice:localhost",
}, fakeMain, "");
expect(res).to.deep.equal({
link_names: true,
text: "@channel Hello everyone!",
username: "@alice:localhost",
});
});
it ("should replace room pills with Slack mentions", async () => {
const res = await substitutions.matrixToSlack({
content: {
body: "You should join my room #working:localhost",
format: "org.matrix.custom.html",
formatted_body: "You should join my room <a href=\"https://matrix.to/#/#working:localhost\">#working:localhost</a>.",
},
sender: "@alice:localhost",
}, fakeMain, "footeam");
expect(res).to.deep.equal({
link_names: true,
text: "You should join my room <#workingslackchannel>",
username: "@alice:localhost",
});
});
it ("should replace multiple room pills with Slack mentions", async () => {
const res = await substitutions.matrixToSlack({
content: {
body: "You should join my room #working:localhost, or perhaps #working2:localhost",
format: "org.matrix.custom.html",
formatted_body: "You should join my room <a href=\"https://matrix.to/#/#working:localhost\">#working:localhost</a>, " +
"or perhaps <a href=\"https://matrix.to/#/#working2:localhost\">#working2:localhost</a>",
},
sender: "@alice:localhost",
}, fakeMain, "footeam");
expect(res).to.deep.equal({
link_names: true,
text: "You should join my room <#workingslackchannel>, or perhaps <#alsoworkingslackchannel>",
username: "@alice:localhost",
});
});
it ("should replace user pills with Slack mentions", async () => {
const res = await substitutions.matrixToSlack({
content: {
body: "Hello! Stranger",
format: "org.matrix.custom.html",
formatted_body: "Hello! <a href=\"https://matrix.to/#/@stranger:localhost\">Stranger</a>.",
},
sender: "@alice:localhost",
}, fakeMain, "footeam");
expect(res).to.deep.equal({
link_names: true,
text: "Hello! <@12345>",
username: "@alice:localhost",
});
});
it ("should replace multiple user pills with Slack mentions", async () => {
const res = await substitutions.matrixToSlack({
content: {
body: "Hello! Stranger Thing",
format: "org.matrix.custom.html",
formatted_body: "Hello! <a href=\"https://matrix.to/#/@stranger:localhost\">Stranger</a> " +
"<a href=\"https://matrix.to/#/@thing:localhost\">Thing</a>",
},
sender: "@alice:localhost",
}, fakeMain, "footeam");
expect(res).to.deep.equal({
link_names: true,
text: "Hello! <@12345> <@54321>",
username: "@alice:localhost",
});
});
it ("should replace non-pilled @user mentions", async () => {
const res = await substitutions.matrixToSlack({
content: {
body: "Hello! @Stranger",
},
sender: "@alice:localhost",
}, fakeMain, "footeam");
expect(res).to.deep.equal({
link_names: true,
text: "Hello! <@12345>",
username: "@alice:localhost",
});
});
it ("should replace non-pilled @user mentions with the most obvious match", async () => {
const res = await substitutions.matrixToSlack({
content: {
body: "Hello! @Alice Bob",
},
sender: "@alice:localhost",
}, fakeMain, "footeam");
expect(res).to.deep.equal({
link_names: true,
text: "Hello! <@12347>",
username: "@alice:localhost",
});
});
it ("should replace matrix links with Slack links", async () => {
const res = await substitutions.matrixToSlack({
content: {
body: "This bridge is built on the [Matrix](https://matrix.org) protocol.",
},
sender: "@alice:localhost",
}, fakeMain, "footeam");
expect(res).to.deep.equal({
link_names: true,
text: "This bridge is built on the <https://matrix.org|Matrix> protocol.",
username: "@alice:localhost",
});
});
it ("should replace multiple matrix links with Slack links", async () => {
const res = await substitutions.matrixToSlack({
content: {
body: "[a](http://example.com) b [c](http://example.net)",
},
sender: "@alice:localhost",
}, fakeMain, "footeam");
expect(res).to.deep.equal({
link_names: true,
text: "<http://example.com|a> b <http://example.net|c>",
username: "@alice:localhost",
});
});
it ("should return an attachment for an m.image message", async () => {
const res = await substitutions.matrixToSlack({
content: {
body: "image.png",
msgtype: "m.image",
url: "mxc://localhost/fake",
},
sender: "@alice:localhost",
}, fakeMain, "footeam");
expect(res).to.deep.equal({
link_names: false,
username: "@alice:localhost",
attachments: [
{
fallback: "image.png",
image_url: "fake-mxc://localhost/fake",
},
],
});
});
});
// describe("slackTextToMatrixHTML", () => {
// it("should repeat a plain string", async () => {
// const res = await substitutions.slackTextToMatrixHTML("Hello World!");
// expect(res).to.equal("Hello World!");
// });
// it("should convert < and >", async () => {
// const res = await substitutions.slackTextToMatrixHTML("<html>Hello</html>");
// expect(res).to.equal("<html>Hello</html>");
// });
// it("should convert a single new line to a <br />", async () => {
// const res = substitutions.slackTextToMatrixHTML("line 1\nline 2");
// expect(res).to.equal("line 1<br />line 2");
// });
// it("should convert two new lines to paragraphs", async () => {
// const res = substitutions.slackTextToMatrixHTML("line 1\n\nline 3");
// expect(res).to.equal("<p>line 1</p><p>line 3</p>");
// });
// it("should convert bold formatting", async () => {
// const res = substitutions.slackTextToMatrixHTML("This is *bold*!");
// expect(res).to.equal("This is <strong>bold</strong>!");
// });
// it("should convert italic formatting", async () => {
// const res = substitutions.slackTextToMatrixHTML("This is /italics/!");
// expect(res).to.equal("This is <em>italics</em>!");
// });
// it("should convert strikethrough formatting", async () => {
// const res = substitutions.slackTextToMatrixHTML("This is ~strikethrough~!");
// expect(res).to.equal("This is <del>strikethrough</del>");
// });
// });
}); | the_stack |
import express from "express";
import _ from "lodash";
import {
getUser,
mustBeAdmin
} from "magda-typescript-common/src/authorization-api/authMiddleware";
import buildJwt from "magda-typescript-common/src/session/buildJwt";
import GenericError from "magda-typescript-common/src/authorization-api/GenericError";
import Database, { Query } from "./Database";
import { Maybe } from "tsmonad";
import { Content } from "./model";
import {
content,
ContentEncoding,
ContentItem,
findContentItemById
} from "./content";
import {
installStatusRouter,
createServiceProbe
} from "magda-typescript-common/src/express/status";
import AccessControlError from "magda-typescript-common/src/authorization-api/AccessControlError";
import { User } from "magda-typescript-common/src/authorization-api/model";
export interface ApiRouterOptions {
database: Database;
jwtSecret: string;
authApiUrl: string;
}
export default function createApiRouter(options: ApiRouterOptions) {
const database = options.database;
const router: express.Router = express.Router();
const status = {
probes: {
database: database.check.bind(database),
auth: createServiceProbe(options.authApiUrl)
}
};
installStatusRouter(router, status);
const USER = getUser(options.authApiUrl, options.jwtSecret);
const ADMIN = mustBeAdmin(options.authApiUrl, options.jwtSecret);
/**
* @apiGroup Content
* @api {post} /v0/content/all Get All
* @apiDescription Get a list of content items and their type.
*
* @apiParam (Query) {string} id filter content id by this wildcard pattern. For example: "id=header/*&id=footer/*". Can specify multiple.
* @apiParam (Query) {string} type filter content mime type by this wildcard pattern. For example: "type=application/*". Can specify multiple.
* @apiParam (Query) {boolean} inline flag to specify if content should be inlined. Only application/json mime type content is supported now.
*
* @apiSuccess {string} result=SUCCESS
*
* @apiSuccessExample {json} 200
* [
* {
* "id": ...
* "type": ...
* "length": ...
* "content": ...
* },
* ...
* ]
*/
router.get("/all", USER, async function (req, res) {
try {
const idQuery: Query = {
field: "id",
patterns: coerceToArray(req.query.id as string)
};
const typeQuery: Query = {
field: "type",
patterns: coerceToArray(req.query.type as string)
};
const inline =
req.query.inline &&
(req.query.inline as string).toLowerCase() === "true";
const inlineContentIfType: string[] = inline
? ["application/json", "text/plain"]
: [];
// get summary
let all: any[] = await database.getContentSummary(
[idQuery, typeQuery],
inlineContentIfType,
req.header("X-Magda-Session")
);
// filter out privates and non-configurable
all = all.filter((item: any) => {
const contentItem = findContentItemById(item.id);
if (contentItem && contentItem.private) {
return (req.user as User)?.isAdmin;
} else {
return true;
}
});
// inline
if (inline) {
for (const item of all.filter((item) => item.content)) {
try {
switch (item.type) {
case "application/json":
item.content = JSON.parse(item.content);
break;
}
} catch (e) {
item.error = e.message;
console.error(e.stack);
}
}
}
res.json(all);
} catch (e) {
console.error(e);
res.sendStatus(500);
}
});
function coerceToArray<T>(thing: T | T[]): T[] {
if (_.isArray(thing)) {
return thing;
} else if (thing) {
return [thing];
} else {
return [];
}
}
/**
* @apiGroup Content
* @api {get} /v0/content/:contentId.:format Get Content
* @apiDescription Returns content by content id.
*
* @apiParam {string} contentId id of content item
* @apiParam {string} format The format to return result with.
* * If specified format is text, will return content as text/plain
* * If specified format is json, will return content as application/json.
* * If specified format is anything else, will return content as saved mime type.
*
* @apiSuccessExample {any} 200
* Content in format requested
*
* @apiError {string} result=FAILED
*
* @apiErrorExample {json} 404
* {
* "result": "FAILED"
* }
*
* @apiErrorExample {json} 500
* {
* "result": "FAILED"
* }
*/
router.get("/*", getContent);
async function getContent(req: any, res: any) {
const requestContentId = req.path.substr(
1,
req.path.lastIndexOf(".") - 1
);
const requestFormat = req.path.substr(req.path.lastIndexOf(".") + 1);
try {
const contentPromise = await database.getContentById(
requestContentId,
req.header("X-Magda-Session")
);
const { content, format } = (
await contentPromise.caseOf({
just: (content) =>
Promise.resolve(
Maybe.just({
format: requestFormat,
content
})
),
nothing: async () => {
const tempContentId = req.path.substr(1);
const tempContentMaybe = await database.getContentById(
tempContentId
);
return tempContentMaybe.map((content) => ({
format: tempContentId.substr(
tempContentId.lastIndexOf(".") + 1
),
content
}));
}
})
).valueOrThrow(
new GenericError(
`Unsupported configuration item requested: ${requestContentId}.${requestFormat}`,
404
)
);
switch (format) {
case "json":
JSON.parse(content.content);
return returnText(res, content, "application/json");
case "js":
return returnText(res, content, "application/javascript");
case "text":
return returnText(res, content, "text/plain");
case "md":
return returnText(res, content, "text/markdown");
case "css":
case "html":
return returnText(res, content, `text/${format}`);
default:
return returnBinary(res, content);
}
} catch (e) {
res.status(e.statusCode || 500).json({
result: "FAILED"
});
if (e instanceof AccessControlError) {
console.log(e);
} else {
console.error(e);
}
}
}
Object.entries(content).forEach(function (config: [string, ContentItem]) {
const [contentId, configurationItem] = config;
const route = configurationItem.route || `/${contentId}`;
const body = configurationItem.body || null;
const verify = configurationItem.verify || null;
/**
* @apiGroup Content
* @api {put} /v0/content/:contentId Update Content
* @apiDescription Update content by id
*
* @apiParam {string} contentId id of content item
* @apiHeader {string} Content-Type=text/plain mime type of posted content.
*
* @apiSuccess {string} result=SUCCESS
*
* @apiSuccessExample {json} 200
* {
* "result": "SUCCESS"
* }
*
* @apiError {string} result=FAILED
*
* @apiErrorExample {json} 400
* {
* "result": "FAILED"
* }
*/
async function put(req: any, res: any) {
try {
let content = req.body;
switch (configurationItem.encode) {
case ContentEncoding.base64:
if (!(content instanceof Buffer)) {
throw new GenericError(
"Can not base64 encode non-raw"
);
}
content = content.toString("base64");
break;
case ContentEncoding.json:
if (
typeof content !== "object" &&
typeof content !== "string" &&
typeof content !== "number" &&
typeof content !== "boolean" &&
content !== null
) {
throw new GenericError(
"Can not stringify encode non-json"
);
}
content = JSON.stringify(content);
break;
}
if (typeof content !== "string") {
// if this error is being thrown, also check if body parser is configured with right type
throw new GenericError(
`Config value is not string yet (${typeof content}). You'll got some work to do.`
);
}
const contentType =
configurationItem.contentType ||
req.headers["content-type"] ||
"text/plain";
const finalContentId = req.path.substr(1);
await database.setContentById(
finalContentId,
contentType,
content
);
res.status(201).json({
result: "SUCCESS"
});
} catch (e) {
res.status(e.statusCode || 500).json({
result: "FAILED"
});
console.error(e);
}
}
router.put.apply(
router,
([route, ADMIN, body, verify, put] as any).filter((i: any) => i)
);
/**
* @apiGroup Content
* @api {delete} /v0/content/:contentId Delete Content
* @apiDescription Delete content by content id. Must be an admin.
* Only available for contents with wildcard ids.
*
* @apiParam {string} contentId id of content item
*
* @apiSuccessExample {any} 200
* {
* "result": "SUCCESS"
* }
*
*/
router.delete(route, ADMIN, async function (req, res) {
const finalContentId = req.path.substr(1);
await database.deleteContentById(finalContentId);
res.status(200).json({
result: "SUCCESS"
});
});
});
// This is for getting a JWT in development so you can do fake authenticated requests to a local server.
if (process.env.NODE_ENV !== "production") {
router.get("/public/jwt", function (req, res) {
res.status(200);
res.write(
"X-Magda-Session: " +
buildJwt(
options.jwtSecret,
"00000000-0000-4000-8000-000000000000"
)
);
res.send();
});
}
return router;
}
function returnBinary(res: any, content: Content) {
const buffer = Buffer.from(content.content, "base64");
res.header("Content-Type", content.type).send(buffer);
}
function returnText(res: any, content: Content, mime: string) {
res.header("Content-Type", mime).send(content.content);
} | the_stack |
import * as am5 from "@amcharts/amcharts5";
import * as am5map from "@amcharts/amcharts5/map";
import am5geodata_worldLow from "@amcharts/amcharts5/geodata/worldLow";
import am5themes_Animated from "@amcharts/amcharts5/themes/Animated";
/**
* ---------------------------------------
* This demo was created using amCharts 5.
*
* For more information visit:
* https://www.amcharts.com/
*
* Documentation is available at:
* https://www.amcharts.com/docs/v5/
* ---------------------------------------
*/
// Create root element
// https://www.amcharts.com/docs/v5/getting-started/#Root_element
const root = am5.Root.new("chartdiv");
// Set themes
// https://www.amcharts.com/docs/v5/concepts/themes/
root.setThemes([am5themes_Animated.new(root)]);
// Create the map chart
// https://www.amcharts.com/docs/v5/charts/map-chart/
const chart = root.container.children.push(
am5map.MapChart.new(root, {
panX: "rotateX",
panY: "rotateY",
projection: am5map.geoMercator()
})
);
// Create series for background fill
// https://www.amcharts.com/docs/v5/charts/map-chart/map-polygon-series/#Background_polygon
const backgroundSeries = chart.series.push(am5map.MapPolygonSeries.new(root, {}));
backgroundSeries.mapPolygons.template.setAll({
fill: root.interfaceColors.get("alternativeBackground"),
fillOpacity: 0,
strokeOpacity: 0
});
// Add background polygo
// https://www.amcharts.com/docs/v5/charts/map-chart/map-polygon-series/#Background_polygon
backgroundSeries.data.push({
geometry: am5map.getGeoRectangle(90, 180, -90, -180)
});
// Create main polygon series for countries
// https://www.amcharts.com/docs/v5/charts/map-chart/map-polygon-series/
const polygonSeries = chart.series.push(
am5map.MapPolygonSeries.new(root, {
geoJSON: am5geodata_worldLow
})
);
polygonSeries.mapPolygons.template.setAll({
fill: root.interfaceColors.get("alternativeBackground"),
fillOpacity: 0.15,
strokeWidth: 0.5,
stroke: root.interfaceColors.get("background")
});
// Create polygon series for circles
// https://www.amcharts.com/docs/v5/charts/map-chart/map-polygon-series/
const circleTemplate = am5.Template.new({
tooltipText: "{name}: {value}"
});
const bubbleSeries = chart.series.push(
am5map.MapPointSeries.new(root, {
calculateAggregates: true,
valueField: "value",
polygonIdField: "id"
})
);
bubbleSeries.bullets.push(function () {
return am5.Bullet.new(root, {
sprite: am5.Circle.new(
root,
{
radius: 10,
templateField: "circleTemplate"
},
circleTemplate
)
});
});
bubbleSeries.set("heatRules", [
{
target: circleTemplate,
min: 3,
max: 30,
key: "radius",
dataField: "value"
}
]);
const colors = am5.ColorSet.new(root, {});
bubbleSeries.data.setAll([
{
id: "AF",
name: "Afghanistan",
value: 32358260,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "AL",
name: "Albania",
value: 3215988,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "DZ",
name: "Algeria",
value: 35980193,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "AO",
name: "Angola",
value: 19618432,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "AR",
name: "Argentina",
value: 40764561,
circleTemplate: { fill: colors.getIndex(3) }
},
{
id: "AM",
name: "Armenia",
value: 3100236,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "AU",
name: "Australia",
value: 22605732,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "AT",
name: "Austria",
value: 8413429,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "AZ",
name: "Azerbaijan",
value: 9306023,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "BH",
name: "Bahrain",
value: 1323535,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "BD",
name: "Bangladesh",
value: 150493658,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "BY",
name: "Belarus",
value: 9559441,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "BE",
name: "Belgium",
value: 10754056,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "BJ",
name: "Benin",
value: 9099922,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "BT",
name: "Bhutan",
value: 738267,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "BO",
name: "Bolivia",
value: 10088108,
circleTemplate: { fill: colors.getIndex(3) }
},
{
id: "BA",
name: "Bosnia and Herzegovina",
value: 3752228,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "BW",
name: "Botswana",
value: 2030738,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "BR",
name: "Brazil",
value: 196655014,
circleTemplate: { fill: colors.getIndex(3) }
},
{
id: "BN",
name: "Brunei",
value: 405938,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "BG",
name: "Bulgaria",
value: 7446135,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "BF",
name: "Burkina Faso",
value: 16967845,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "BI",
name: "Burundi",
value: 8575172,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "KH",
name: "Cambodia",
value: 14305183,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "CM",
name: "Cameroon",
value: 20030362,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "CA",
name: "Canada",
value: 34349561,
circleTemplate: { fill: colors.getIndex(4) }
},
{
id: "CV",
name: "Cape Verde",
value: 500585,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "CF",
name: "Central African Rep.",
value: 4486837,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "TD",
name: "Chad",
value: 11525496,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "CL",
name: "Chile",
value: 17269525,
circleTemplate: { fill: colors.getIndex(3) }
},
{
id: "CN",
name: "China",
value: 1347565324,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "CO",
name: "Colombia",
value: 46927125,
circleTemplate: { fill: colors.getIndex(3) }
},
{
id: "KM",
name: "Comoros",
value: 753943,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "CD",
name: "Congo, Dem. Rep.",
value: 67757577,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "CG",
name: "Congo, Rep.",
value: 4139748,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "CR",
name: "Costa Rica",
value: 4726575,
circleTemplate: { fill: colors.getIndex(4) }
},
{
id: "CI",
name: "Cote d'Ivoire",
value: 20152894,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "HR",
name: "Croatia",
value: 4395560,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "CU",
name: "Cuba",
value: 11253665,
circleTemplate: { fill: colors.getIndex(4) }
},
{
id: "CY",
name: "Cyprus",
value: 1116564,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "CZ",
name: "Czech Rep.",
value: 10534293,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "DK",
name: "Denmark",
value: 5572594,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "DJ",
name: "Djibouti",
value: 905564,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "DO",
name: "Dominican Rep.",
value: 10056181,
circleTemplate: { fill: colors.getIndex(4) }
},
{
id: "EC",
name: "Ecuador",
value: 14666055,
circleTemplate: { fill: colors.getIndex(3) }
},
{
id: "EG",
name: "Egypt",
value: 82536770,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "SV",
name: "El Salvador",
value: 6227491,
circleTemplate: { fill: colors.getIndex(4) }
},
{
id: "GQ",
name: "Equatorial Guinea",
value: 720213,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "ER",
name: "Eritrea",
value: 5415280,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "EE",
name: "Estonia",
value: 1340537,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "ET",
name: "Ethiopia",
value: 84734262,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "FJ",
name: "Fiji",
value: 868406,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "FI",
name: "Finland",
value: 5384770,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "FR",
name: "France",
value: 63125894,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "GA",
name: "Gabon",
value: 1534262,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "GM",
name: "Gambia",
value: 1776103,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "GE",
name: "Georgia",
value: 4329026,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "DE",
name: "Germany",
value: 82162512,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "GH",
name: "Ghana",
value: 24965816,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "GR",
name: "Greece",
value: 11390031,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "GT",
name: "Guatemala",
value: 14757316,
circleTemplate: { fill: colors.getIndex(4) }
},
{
id: "GN",
name: "Guinea",
value: 10221808,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "GW",
name: "Guinea-Bissau",
value: 1547061,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "GY",
name: "Guyana",
value: 756040,
circleTemplate: { fill: colors.getIndex(3) }
},
{
id: "HT",
name: "Haiti",
value: 10123787,
circleTemplate: { fill: colors.getIndex(4) }
},
{
id: "HN",
name: "Honduras",
value: 7754687,
circleTemplate: { fill: colors.getIndex(4) }
},
{
id: "HK",
name: "Hong Kong, China",
value: 7122187,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "HU",
name: "Hungary",
value: 9966116,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "IS",
name: "Iceland",
value: 324366,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "IN",
name: "India",
value: 1241491960,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "ID",
name: "Indonesia",
value: 242325638,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "IR",
name: "Iran",
value: 74798599,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "IQ",
name: "Iraq",
value: 32664942,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "IE",
name: "Ireland",
value: 4525802,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "IL",
name: "Israel",
value: 7562194,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "IT",
name: "Italy",
value: 60788694,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "JM",
name: "Jamaica",
value: 2751273,
circleTemplate: { fill: colors.getIndex(4) }
},
{
id: "JP",
name: "Japan",
value: 126497241,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "JO",
name: "Jordan",
value: 6330169,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "KZ",
name: "Kazakhstan",
value: 16206750,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "KE",
name: "Kenya",
value: 41609728,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "KP",
name: "Korea, Dem. Rep.",
value: 24451285,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "KR",
name: "Korea, Rep.",
value: 48391343,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "KW",
name: "Kuwait",
value: 2818042,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "KG",
name: "Kyrgyzstan",
value: 5392580,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "LA",
name: "Laos",
value: 6288037,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "LV",
name: "Latvia",
value: 2243142,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "LB",
name: "Lebanon",
value: 4259405,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "LS",
name: "Lesotho",
value: 2193843,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "LR",
name: "Liberia",
value: 4128572,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "LY",
name: "Libya",
value: 6422772,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "LT",
name: "Lithuania",
value: 3307481,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "LU",
name: "Luxembourg",
value: 515941,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "MK",
name: "Macedonia, FYR",
value: 2063893,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "MG",
name: "Madagascar",
value: 21315135,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "MW",
name: "Malawi",
value: 15380888,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "MY",
name: "Malaysia",
value: 28859154,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "ML",
name: "Mali",
value: 15839538,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "MR",
name: "Mauritania",
value: 3541540,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "MU",
name: "Mauritius",
value: 1306593,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "MX",
name: "Mexico",
value: 114793341,
circleTemplate: { fill: colors.getIndex(4) }
},
{
id: "MD",
name: "Moldova",
value: 3544864,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "MN",
name: "Mongolia",
value: 2800114,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "ME",
name: "Montenegro",
value: 632261,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "MA",
name: "Morocco",
value: 32272974,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "MZ",
name: "Mozambique",
value: 23929708,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "MM",
name: "Myanmar",
value: 48336763,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "NA",
name: "Namibia",
value: 2324004,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "NP",
name: "Nepal",
value: 30485798,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "NL",
name: "Netherlands",
value: 16664746,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "NZ",
name: "New Zealand",
value: 4414509,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "NI",
name: "Nicaragua",
value: 5869859,
circleTemplate: { fill: colors.getIndex(4) }
},
{
id: "NE",
name: "Niger",
value: 16068994,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "NG",
name: "Nigeria",
value: 162470737,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "NO",
name: "Norway",
value: 4924848,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "OM",
name: "Oman",
value: 2846145,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "PK",
name: "Pakistan",
value: 176745364,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "PA",
name: "Panama",
value: 3571185,
circleTemplate: { fill: colors.getIndex(4) }
},
{
id: "PG",
name: "Papua New Guinea",
value: 7013829,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "PY",
name: "Paraguay",
value: 6568290,
circleTemplate: { fill: colors.getIndex(3) }
},
{
id: "PE",
name: "Peru",
value: 29399817,
circleTemplate: { fill: colors.getIndex(3) }
},
{
id: "PH",
name: "Philippines",
value: 94852030,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "PL",
name: "Poland",
value: 38298949,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "PT",
name: "Portugal",
value: 10689663,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "PR",
name: "Puerto Rico",
value: 3745526,
circleTemplate: { fill: colors.getIndex(4) }
},
{
id: "QA",
name: "Qatar",
value: 1870041,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "RO",
name: "Romania",
value: 21436495,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "RU",
name: "Russia",
value: 142835555,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "RW",
name: "Rwanda",
value: 10942950,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "SA",
name: "Saudi Arabia",
value: 28082541,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "SN",
name: "Senegal",
value: 12767556,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "RS",
name: "Serbia",
value: 9853969,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "SL",
name: "Sierra Leone",
value: 5997486,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "SG",
name: "Singapore",
value: 5187933,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "SK",
name: "Slovak Republic",
value: 5471502,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "SI",
name: "Slovenia",
value: 2035012,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "SB",
name: "Solomon Islands",
value: 552267,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "SO",
name: "Somalia",
value: 9556873,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "ZA",
name: "South Africa",
value: 50459978,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "ES",
name: "Spain",
value: 46454895,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "LK",
name: "Sri Lanka",
value: 21045394,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "SD",
name: "Sudan",
value: 34735288,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "SR",
name: "Suriname",
value: 529419,
circleTemplate: { fill: colors.getIndex(3) }
},
{
id: "SZ",
name: "Swaziland",
value: 1203330,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "SE",
name: "Sweden",
value: 9440747,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "CH",
name: "Switzerland",
value: 7701690,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "SY",
name: "Syria",
value: 20766037,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "TW",
name: "Taiwan",
value: 23072000,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "TJ",
name: "Tajikistan",
value: 6976958,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "TZ",
name: "Tanzania",
value: 46218486,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "TH",
name: "Thailand",
value: 69518555,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "TG",
name: "Togo",
value: 6154813,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "TT",
name: "Trinidad and Tobago",
value: 1346350,
circleTemplate: { fill: colors.getIndex(4) }
},
{
id: "TN",
name: "Tunisia",
value: 10594057,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "TR",
name: "Turkey",
value: 73639596,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "TM",
name: "Turkmenistan",
value: 5105301,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "UG",
name: "Uganda",
value: 34509205,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "UA",
name: "Ukraine",
value: 45190180,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "AE",
name: "United Arab Emirates",
value: 7890924,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "GB",
name: "United Kingdom",
value: 62417431,
circleTemplate: { fill: colors.getIndex(8) }
},
{
id: "US",
name: "United States",
value: 313085380,
circleTemplate: { fill: colors.getIndex(4) }
},
{
id: "UY",
name: "Uruguay",
value: 3380008,
circleTemplate: { fill: colors.getIndex(3) }
},
{
id: "UZ",
name: "Uzbekistan",
value: 27760267,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "VE",
name: "Venezuela",
value: 29436891,
circleTemplate: { fill: colors.getIndex(3) }
},
{
id: "PS",
name: "West Bank and Gaza",
value: 4152369,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "VN",
name: "Vietnam",
value: 88791996,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "YE",
name: "Yemen, Rep.",
value: 24799880,
circleTemplate: { fill: colors.getIndex(0) }
},
{
id: "ZM",
name: "Zambia",
value: 13474959,
circleTemplate: { fill: colors.getIndex(2) }
},
{
id: "ZW",
name: "Zimbabwe",
value: 12754378,
circleTemplate: { fill: colors.getIndex(2) }
}
]);
// Add globe/map switch
const cont = chart.children.push(
am5.Container.new(root, {
layout: root.horizontalLayout,
x: 20,
y: 40
})
);
cont.children.push(
am5.Label.new(root, {
centerY: am5.p50,
text: "Map"
})
);
const switchButton = cont.children.push(
am5.Button.new(root, {
themeTags: ["switch"],
centerY: am5.p50,
icon: am5.Circle.new(root, {
themeTags: ["icon"]
})
})
);
switchButton.on("active", function () {
if (!switchButton.get("active")) {
chart.set("projection", am5map.geoMercator());
backgroundSeries.mapPolygons.template.set("fillOpacity", 0);
} else {
chart.set("projection", am5map.geoOrthographic());
backgroundSeries.mapPolygons.template.set("fillOpacity", 0.1);
}
});
cont.children.push(
am5.Label.new(root, {
centerY: am5.p50,
text: "Globe"
})
);
// Make stuff animate on load
chart.appear(1000, 100); | the_stack |
//inconsistent namespace: this is a helper funtion from tables.js and should not pollute the global namespace!
declare function sanitizeDuration(duration: string): string;
declare namespace Vex {
function L(block: string, args: any[]): void;
function Merge<T extends Object>(destination: T, source: Object): T;
function Min(a: number, b: number): number;
function Max(a: number, b: number): number;
function RoundN(x: number, n: number): number;
function MidLine(a: number, b: number): number;
function SortAndUnique<T extends any[]>(arr: T, cmp: Function, eq: Function): T;
function Contains(a: any[], obj: any): boolean;
function getCanvasContext(canvas_sel: string): CanvasRenderingContext2D;
function drawDot(ctx: IRenderContext, x: number, y: number, color?: string): void;
function BM(s: number, f: Function): void;
function Inherit<T extends Object>(child: T, parent: Object, object: Object): T;
class RuntimeError {
constructor(code: string, message: string);
}
class RERR {
constructor(code: string, message: string);
}
/**
* Helper interface for handling the different rendering contexts (i.e. CanvasContext, RaphaelContext, SVGContext). Not part of VexFlow!
*/
interface IRenderContext {
clear(): void;
setFont(family: string, size: number, weight?: number): IRenderContext;
setRawFont(font: string): IRenderContext;
setFillStyle(style: string): IRenderContext;
setBackgroundFillStyle(style: string): IRenderContext;
setStrokeStyle(style: string): IRenderContext;
setShadowColor(color: string): IRenderContext;
setShadowBlur(blur: string): IRenderContext;
setLineWidth(width: number): IRenderContext;
setLineCap(cap_type: string): IRenderContext;
setLineDash(dash: string): IRenderContext;
scale(x: number, y: number): IRenderContext;
resize(width: number, height: number): IRenderContext;
fillRect(x: number, y: number, width: number, height: number): IRenderContext;
clearRect(x: number, y: number, width: number, height: number): IRenderContext;
beginPath(): IRenderContext;
moveTo(x: number, y: number): IRenderContext;
lineTo(x: number, y: number): IRenderContext;
bezierCurveTo(x1: number, y1: number, x2: number, y2: number, x: number, y: number): IRenderContext;
quadraticCurveTo(x1: number, y1: number, x2: number, y2: number): IRenderContext;
arc(
x: number,
y: number,
radius: number,
startAngle: number,
endAngle: number,
antiClockwise: boolean,
): IRenderContext;
glow(): IRenderContext;
fill(): IRenderContext;
stroke(): IRenderContext;
closePath(): IRenderContext;
fillText(text: string, x: number, y: number): IRenderContext;
save(): IRenderContext;
restore(): IRenderContext;
openGroup(): Node | undefined;
closeGroup(): void;
/**
* canvas returns TextMetrics, SVG returns SVGRect, Raphael returns {width : number, height : number}. Only width is used throughout VexFlow.
*/
measureText(text: string): { width: number };
}
/**
* Helper interface for handling the Vex.Flow.Font object in Vex.Flow.Glyph. Not part of VexFlow!
*/
interface IFont {
glyphs: { x_min: number; x_max: number; ha: number; o: string[] }[];
cssFontWeight: string;
ascender: number;
underlinePosition: number;
cssFontStyle: string;
boundingBox: { yMin: number; xMin: number; yMax: number; xMax: number };
resolution: number;
descender: number;
familyName: string;
lineHeight: number;
underlineThickness: number;
/**
* This property is missing in vexflow_font.js, but present in gonville_original.js and gonville_all.js.
*/
original_font_information?: {
postscript_name: string;
version_string: string;
vendor_url: string;
full_font_name: string;
font_family_name: string;
copyright: string;
description: string;
trademark: string;
designer: string;
designer_url: string;
unique_font_identifier: string;
license_url: string;
license_description: string;
manufacturer_name: string;
font_sub_family_name: string;
} | undefined;
}
namespace Flow {
const RESOLUTION: number;
// from tables.js:
const STEM_WIDTH: number;
const STEM_HEIGHT: number;
const STAVE_LINE_THICKNESS: number;
const TIME4_4: { num_beats: number; beat_value: number; resolution: number };
const unicode: { [name: string]: string }; //inconsistent API: this should be private and have a wrapper function like the other tables
const DEFAULT_NOTATION_FONT_SCALE: number;
function clefProperties(clef: string): { line_shift: number };
function keyProperties(
key: string,
clef: string,
params: { octave_shift?: number | undefined },
): {
key: string;
octave: number;
line: number;
int_value: number;
accidental: string;
code: number;
stroke: number;
shift_right: number;
displaced: boolean;
};
function integerToNote(integer: number): string;
function tabToGlyph(fret: string): { text: string; code: number; width: number; shift_y: number };
function textWidth(text: string): number;
function articulationCodes(
artic: string,
): {
code: string;
width: number;
shift_right: number;
shift_up: number;
shift_down: number;
between_lines: boolean;
};
function accidentalCodes(
acc: string,
): { code: string; width: number; gracenote_width: number; shift_right: number; shift_down: number };
function ornamentCodes(
acc: string,
): { code: string; shift_right: number; shift_up: number; shift_down: number; width: number };
function keySignature(spec: string): { type: string; line: number }[];
function parseNoteDurationString(durationString: string): { duration: string; dots: number; type: string };
function parseNoteData(noteData: {
duration: string;
dots: number;
type: string;
}): { duration: string; type: string; dots: number; ticks: number };
function durationToFraction(duration: string): Fraction;
function durationToNumber(duration: string): number;
function durationToTicks(duration: string): number;
function durationToGlyph(
duration: string,
type: string,
): {
head_width: number;
stem: boolean;
stem_offset: number;
flag: boolean;
stem_up_extension: number;
stem_down_extension: number;
gracenote_stem_up_extension: number;
gracenote_stem_down_extension: number;
tabnote_stem_up_extension: number;
tabnote_stem_down_extension: number;
dot_shiftY: number;
line_above: number;
line_below: number;
code_head?: string | undefined;
rest?: boolean | undefined;
position?: string | undefined;
};
// from glyph.js:
function renderGlyph(
ctx: IRenderContext,
x_pos: number,
y_pos: number,
point: number,
val: string,
nocache: boolean,
): void;
// from vexflow_font.js / gonville_original.js / gonville_all.js
var Font: {
glyphs: { x_min: number; x_max: number; ha: number; o: string[] }[];
cssFontWeight: string;
ascender: number;
underlinePosition: number;
cssFontStyle: string;
boundingBox: { yMin: number; xMin: number; yMax: number; xMax: number };
resolution: number;
descender: number;
familyName: string;
lineHeight: number;
underlineThickness: number;
//inconsistent member : this is missing in vexflow_font.js, but present in gonville_original.js and gonville_all.js
original_font_information: {
postscript_name: string;
version_string: string;
vendor_url: string;
full_font_name: string;
font_family_name: string;
copyright: string;
description: string;
trademark: string;
designer: string;
designer_url: string;
unique_font_identifier: string;
license_url: string;
license_description: string;
manufacturer_name: string;
font_sub_family_name: string;
};
};
class Accidental extends Modifier {
//TODO remove the following lines once TypeScript allows subclass overrides with type changes
setNote(note: Note): Modifier;
constructor(type: string);
static DEBUG: boolean;
static format(
accidentals: Accidental[],
state: { left_shift: number; right_shift: number; text_line: number },
): void;
setNote(note: StaveNote): void;
setAsCautionary(): Accidental;
draw(): void;
static applyAccidentals(voices: Voice[], keySignature?: string): void;
}
namespace Accidental {
const CATEGORY: string;
}
class Annotation extends Modifier {
constructor(text: string);
static DEBUG: boolean;
static format(
annotations: Annotation[],
state: { left_shift: number; right_shift: number; text_line: number },
): boolean;
setTextLine(line: number): Annotation;
setFont(family: string, size: number, weight: string): Annotation;
setVerticalJustification(just: Annotation.VerticalJustify): Annotation;
getJustification(): Annotation.Justify;
setJustification(justification: Annotation.Justify): Annotation;
draw(): void;
}
namespace Annotation {
enum Justify {
LEFT = 1,
CENTER,
RIGHT,
CENTER_STEM,
}
enum VerticalJustify {
TOP = 1,
CENTER,
BOTTOM,
CENTER_STEM,
}
const CATEGORY: string;
}
class Articulation extends Modifier {
constructor(type: string);
static DEBUG: boolean;
static format(
articulations: Articulation[],
state: { left_shift: number; right_shift: number; text_line: number },
): boolean;
draw(): void;
}
namespace Articulation {
const CATEGORY: string;
}
class BarNote extends Note {
static DEBUG: boolean;
constructor();
getType(): Barline.type;
setType(type: Barline.type): BarNote;
getBoundingBox(): BoundingBox;
addToModifierContext(): BarNote;
preFormat(): BarNote;
draw(): void;
}
namespace Barline {
enum type {
SINGLE = 1,
DOUBLE,
END,
REPEAT_BEGIN,
REPEAT_END,
REPEAT_BOTH,
NONE,
}
}
class Barline extends StaveModifier {
constructor(type: Barline.type, x: number);
getCategory(): string;
setX(x: number): Barline;
draw(stave: Stave, x_shift?: number): void;
drawVerticalBar(stave: Stave, x: number, double_bar?: boolean): void;
drawVerticalEndBar(stave: Stave, x: number): void;
drawRepeatBar(stave: Stave, x: number, begin: boolean): void;
}
class Beam {
constructor(notes: StemmableNote[], auto_stem?: boolean);
setStyle(style: {
shadowColor?: string | undefined;
shadowBlur?: string | undefined;
fillStyle?: string | undefined;
strokeStyle?: string | undefined;
}): Beam;
setContext(context: IRenderContext): Beam;
getNotes(): StemmableNote[];
getBeamCount(): number;
breakSecondaryAt(indices: number[]): Beam;
getSlopeY(): number;
calculateSlope(): void;
applyStemExtensions(): void;
getBeamLines(duration: string): { start: number; end: number }[];
drawStems(): void;
drawBeamLines(): void;
preFormat(): Beam;
postFormat(): Beam;
draw(): boolean;
calculateStemDirection(notes: Note): number;
static getDefaultBeamGroups(time_sig: string): Fraction[];
static applyAndGetBeams(voice: Voice, stem_direction: number, groups: Fraction[]): Beam[];
static generateBeams(
notes: StemmableNote[],
config?: {
groups?: Fraction[] | undefined;
stem_direction?: number | undefined;
beam_rests?: boolean | undefined;
beam_middle_only?: boolean | undefined;
show_stemlets?: boolean | undefined;
maintain_stem_directions?: boolean | undefined;
},
): Beam[];
}
class Bend extends Modifier {
constructor(text: string, release?: boolean, phrase?: { type: number; text: string; width: number }[]);
static UP: number;
static DOWN: number;
static format(
bends: Bend[],
state: { left_shift: number; right_shift: number; text_line: number },
): boolean;
setXShift(value: number): void;
setFont(font: string): Bend;
getText(): string;
updateWidth(): Bend;
draw(): void;
}
namespace Bend {
const CATEGORY: string;
}
class BoundingBox {
constructor(x: number, y: number, w: number, h: number);
static copy(that: BoundingBox): BoundingBox;
getX(): number;
getY(): number;
getW(): number;
getH(): number;
setX(x: number): BoundingBox;
setY(y: number): BoundingBox;
setW(w: number): BoundingBox;
setH(h: number): BoundingBox;
move(x: number, y: number): void;
clone(): BoundingBox;
mergeWith(boundingBox: BoundingBox, ctx?: IRenderContext): BoundingBox;
draw(ctx: IRenderContext, x: number, y: number): void;
}
class CanvasContext implements IRenderContext {
//TODO remove the following lines once TypeScript allows subclass overrides with type changes or type inconsistencies mentioned below are fixed
setLineDash(dash: string): CanvasContext;
scale(x: number, y: number): CanvasContext;
resize(width: number, height: number): CanvasContext;
fillRect(x: number, y: number, width: number, height: number): CanvasContext;
clearRect(x: number, y: number, width: number, height: number): CanvasContext;
beginPath(): CanvasContext;
moveTo(x: number, y: number): CanvasContext;
lineTo(x: number, y: number): CanvasContext;
bezierCurveTo(x1: number, y1: number, x2: number, y2: number, x: number, y: number): CanvasContext;
quadraticCurveTo(x1: number, y1: number, x2: number, y2: number): CanvasContext;
arc(
x: number,
y: number,
radius: number,
startAngle: number,
endAngle: number,
antiClockwise: boolean,
): CanvasContext;
glow(): CanvasContext;
fill(): CanvasContext;
stroke(): CanvasContext;
closePath(): CanvasContext;
fillText(text: string, x: number, y: number): CanvasContext;
save(): CanvasContext;
restore(): CanvasContext;
constructor(context: CanvasRenderingContext2D);
static WIDTH: number;
static HEIGHT: number;
clear(): void;
setFont(family: string, size: number, weight?: number): CanvasContext;
setRawFont(font: string): CanvasContext;
setFillStyle(style: string): CanvasContext;
setBackgroundFillStyle(style: string): CanvasContext;
setStrokeStyle(style: string): CanvasContext;
setShadowColor(style: string): CanvasContext; //inconsistent name: style -> color
setShadowBlur(blur: string): CanvasContext;
setLineWidth(width: number): CanvasContext;
setLineCap(cap_type: string): CanvasContext;
//inconsistent type: void -> CanvasContext
setLineDash(dash: string): void;
scale(x: number, y: number): void;
resize(width: number, height: number): void;
fillRect(x: number, y: number, width: number, height: number): void;
clearRect(x: number, y: number, width: number, height: number): void;
beginPath(): void;
moveTo(x: number, y: number): void;
lineTo(x: number, y: number): void;
bezierCurveToTo(x1: number, y1: number, x2: number, y2: number, x: number, y: number): void;
quadraticCurveToTo(x1: number, y1: number, x: number, y: number): void; //inconsistent name: x -> x2, y -> y2
arc(
x: number,
y: number,
radius: number,
startAngle: number,
endAngle: number,
antiClockwise: boolean,
): void;
glow(): void;
fill(): void;
stroke(): void;
closePath(): void;
measureText(text: string): TextMetrics;
fillText(text: string, x: number, y: number): void;
save(): void;
restore(): void;
openGroup(): undefined;
closeGroup(): void;
}
class Clef extends StaveModifier {
//TODO remove the following lines once TypeScript allows subclass overrides with type changes
addModifier(): void;
addEndModifier(): void;
constructor(clef: string, size?: string, annotation?: string);
static DEBUG: boolean;
addModifier(stave: Stave): void;
addEndModifier(stave: Stave): void;
}
class ClefNote extends Note {
//TODO remove the following lines once TypeScript allows subclass overrides with type changes
setStave(stave: Stave): Note;
constructor(clef: string, size?: string, annotation?: string);
setClef(clef: string, size?: string, annotation?: string): ClefNote;
getClef(): string;
setStave(stave: Stave): void;
getBoundingBox(): BoundingBox;
addToModifierContext(): ClefNote;
getCategory(): string;
preFormat(): ClefNote;
draw(): void;
}
class Crescendo extends Note {
constructor(note_struct: { duration: number; line?: number | undefined });
static DEBUG: boolean;
setLine(line: number): Crescendo;
setHeight(height: number): Crescendo;
setDecrescendo(decresc: boolean): Crescendo;
preFormat(): Crescendo;
draw(): void;
}
class Curve {
constructor(
from: Note,
to: Note,
options?: {
spacing?: number | undefined;
thickness?: number | undefined;
x_shift?: number | undefined;
y_shift: number;
position: Curve.Position;
invert: boolean;
cps?: { x: number; y: number }[] | undefined;
},
);
static DEBUG: boolean;
setContext(context: IRenderContext): Curve;
setNotes(from: Note, to: Note): Curve;
isPartial(): boolean;
renderCurve(params: {
first_x: number;
first_y: number;
last_x: number;
last_y: number;
direction: number;
}): void;
draw(): boolean;
}
namespace Curve {
enum Position {
NEAR_HEAD = 1,
NEAR_TOP,
}
}
class Dot extends Modifier {
//TODO remove the following lines once TypeScript allows subclass overrides with type changes or type inconsistencies mentioned below are fixed
setNote(note: Note): Dot;
static format(dots: number, state: { left_shift: number; right_shift: number; text_line: number }): void;
setNote(note: Note): void; //inconsistent type: void -> Dot
setDotShiftY(y: number): Dot;
draw(): void;
}
namespace Dot {
const CATEGORY: string;
}
class Formatter {
static DEBUG: boolean;
constructor(options?: {
softmaxFactor?: number | undefined,
maxIterations?: number | undefined
});
static FormatAndDraw(
ctx: IRenderContext,
stave: Stave,
notes: Note[],
params?: { auto_beam: boolean; align_rests: boolean },
): BoundingBox;
static FormatAndDraw(ctx: IRenderContext, stave: Stave, notes: Note[], params?: boolean): BoundingBox;
static FormatAndDrawTab(
ctx: IRenderContext,
tabstave: TabStave,
stave: Stave,
tabnotes: TabNote[],
notes: Note[],
autobeam?: boolean,
params?: { auto_beam: boolean; align_rests: boolean },
): void;
static FormatAndDrawTab(
ctx: IRenderContext,
tabstave: TabStave,
stave: Stave,
tabnotes: TabNote[],
notes: Note[],
autobeam?: boolean,
params?: boolean,
): void;
static AlignRestsToNotes(notes: Note[], align_all_notes?: boolean, align_tuplets?: boolean): Formatter;
alignRests(voices: Voice[], align_all_notes: boolean): void;
preCalculateMinTotalWidth(voices: Voice[]): number;
getMinTotalWidth(): number;
createModifierContexts(voices: Voice[]): ModifierContext[];
createTickContexts(voices: Voice[]): TickContext[];
preFormat(justifyWidth?: number, rendering_context?: IRenderContext, voices?: Voice[], stave?: Stave): void;
postFormat(): Formatter;
joinVoices(voices: Voice[]): Formatter;
format(
voices: Voice[],
justifyWidth: number,
options?: { align_rests?: boolean | undefined; context: IRenderContext },
): Formatter;
formatToStave(
voices: Voice[],
stave: Stave,
options?: { align_rests?: boolean | undefined; context: IRenderContext },
): Formatter;
}
class Fraction {
constructor(numerator: number, denominator: number);
static GCD(a: number, b: number): number;
static LCM(a: number, b: number): number;
static LCMM(a: number, b: number): number;
set(numerator: number, denominator: number): Fraction;
value(): number;
simplify(): Fraction;
add(param1: Fraction, param2: Fraction): Fraction;
add(param1: number, param2: number): Fraction;
subtract(param1: Fraction, param2: Fraction): Fraction;
subtract(param1: number, param2: number): Fraction;
multiply(param1: Fraction, param2: Fraction): Fraction;
multiply(param1: number, param2: number): Fraction;
divide(param1: Fraction, param2: Fraction): Fraction;
divide(param1: number, param2: number): Fraction;
equals(compare: Fraction): boolean;
greaterThan(compare: Fraction): boolean;
greaterThanEquals(compare: Fraction): boolean;
lessThan(compare: Fraction): boolean;
lessThanEquals(compare: Fraction): boolean;
clone(): Fraction;
copy(copy: Fraction): Fraction;
quotient(): number;
fraction(): number;
abs(): Fraction;
toString(): string;
toSimplifiedString(): string;
toMixedString(): string;
parse(str: string): Fraction;
}
class FretHandFinger extends Modifier {
constructor(number: number | string);
static format(
nums: FretHandFinger[],
state: { left_shift: number; right_shift: number; text_line: number },
): void;
finger: number | string;
getNote(): Note;
setNote(note: Note): FretHandFinger;
getIndex(): number;
setIndex(index: number): FretHandFinger;
getPosition(): Modifier.Position;
setPosition(position: Modifier.Position): FretHandFinger;
setFretHandFinger(number: number): FretHandFinger;
setOffsetX(x: number): FretHandFinger;
setOffsetY(y: number): FretHandFinger;
draw(): void;
}
namespace FretHandFinger {
const CATEGORY: string;
}
class GhostNote extends StemmableNote {
//TODO remove the following lines once TypeScript allows subclass overrides with type changes or type inconsistencies mentioned below are fixed
setStave(stave: Stave): Note;
constructor(duration: string);
constructor(note_struct: {
type?: string | undefined;
dots?: number | undefined;
duration: string
}); //inconsistent name : init struct is called 'duration', should be 'params'/'options' (may be string or Object)
isRest(): boolean;
setStave(stave: Stave): void; //inconsistent type: void -> GhostNote
addToModifierContext(): GhostNote;
preFormat(): GhostNote;
draw(): void;
}
class Glyph {
constructor(code: string, point: number, options?: { cache?: boolean | undefined; font?: IFont | undefined });
setOptions(options: { cache?: boolean | undefined; font?: IFont | undefined }): void;
setStave(stave: Stave): Glyph;
setXShift(x_shift: number): Glyph;
setYShift(y_shift: number): Glyph;
setContext(context: IRenderContext): Glyph;
getContext(): IRenderContext;
reset(): void;
setWidth(width: number): Glyph;
getMetrics(): { x_min: number; x_max: number; width: number; height: number };
render(ctx: IRenderContext, x_pos: number, y_pos: number): void;
renderToStave(x: number): void;
static loadMetrics(
font: IFont,
code: string,
cache: boolean,
): { x_min: number; x_max: number; ha: number; outline: number[] };
static renderOutline(
ctx: IRenderContext,
outline: number[],
scale: number,
x_pos: number,
y_pos: number,
): void;
}
class GraceNote extends StaveNote {
constructor(note_struct: {
slash?: boolean | undefined;
type?: string | undefined;
dots?: number | undefined;
duration: string;
clef?: string | undefined;
keys: string[];
octave_shift?: number | undefined;
auto_stem?: boolean | undefined;
stem_direction?: number | undefined;
});
static LEDGER_LINE_OFFSET: number;
getStemExtension(): number;
getCategory(): string;
draw(): void;
}
namespace GraceNote {
const SCALE: number;
}
class GraceNoteGroup extends Modifier {
//TODO remove the following lines once TypeScript allows subclass overrides with type changes or type inconsistencies mentioned below are fixed
setWidth(width: number): Modifier;
setNote(note: StaveNote): Modifier;
constructor(grace_notes: GraceNote[], show_slur?: boolean); //inconsistent name: 'show_slur' is called 'config', suggesting object (is boolean)
static DEBUG: boolean;
static format(
gracenote_groups: GraceNoteGroup[],
state: { left_shift: number; right_shift: number; text_line: number },
): boolean;
preFormat(): void;
beamNotes(): GraceNoteGroup;
setNote(note: Note): void; //inconsistent type: void -> GraceNoteGroup
setWidth(width: number): void; //inconsistent type: void -> GraceNoteGroup
getWidth(): number;
setXShift(x_shift: number): void;
draw(): void;
}
namespace GraceNoteGroup {
const CATEGORY: string;
}
class KeyManager {
constructor(key: string);
setKey(key: string): KeyManager;
getKey(): string;
reset(): KeyManager;
getAccidental(key: string): { note: string; accidental: string };
selectNote(note: string): { note: string; accidental: string; change: boolean };
}
class KeySignature extends StaveModifier {
//TODO remove the following lines once TypeScript allows subclass overrides with type changes
addModifier(): void;
constructor(key_spec: string);
addAccToStave(
stave: Stave,
acc: { type: string; line: number },
next?: { type: string; line: number },
): void;
cancelKey(spec: string): KeySignature;
addModifier(stave: Stave): KeySignature;
addToStave(stave: Stave, firstGlyph?: boolean): KeySignature;
convertAccLines(clef: string, type: string): void;
}
class Modifier {
static DEBUG: boolean;
getCategory(): string;
getWidth(): number;
setWidth(width: number): Modifier;
getNote(): Note;
setNote(note: Note): Modifier;
getIndex(): number;
setIndex(index: number): Modifier;
getContext(): IRenderContext;
setContext(context: IRenderContext): Modifier;
getModifierContext(): ModifierContext;
setModifierContext(c: ModifierContext): Modifier;
getPosition(): Modifier.Position;
setPosition(position: Modifier.Position): Modifier;
setTextLine(line: number): Modifier;
setYShift(y: number): Modifier;
setXShift(x: number): void; //inconsistent type: void -> Modifier
draw(): void;
alignSubNotesWithNote(subNotes: Note[], note: Note): void;
}
namespace Modifier {
enum Position {
LEFT = 1,
RIGHT,
ABOVE,
BELOW,
}
const CATEGORY: string;
}
class ModifierContext {
static DEBUG: boolean;
addModifier(modifier: Modifier): ModifierContext;
getModifiers(type: string): Modifier[];
getWidth(): number;
getExtraLeftPx(): number;
getExtraRightPx(): number;
getState(): { left_shift: number; right_shift: number; text_line: number };
getMetrics(): { width: number; spacing: number; extra_left_px: number; extra_right_px: number };
preFormat(): void;
postFormat(): void;
}
class Music {
isValidNoteValue(note: number): boolean;
isValidIntervalValue(interval: number): boolean;
getNoteParts(noteString: string): { root: string; accidental: string };
getKeyParts(noteString: string): { root: string; accidental: string; type: string };
getNoteValue(noteString: string): number;
getIntervalValue(intervalString: string): number;
getCanonicalNoteName(noteValue: number): string;
getCanonicalIntervalName(intervalValue: number): string;
getRelativeNoteValue(noteValue: number, intervalValue: number, direction?: number): number;
getRelativeNoteName(root: string, noteValue: number): string;
getScaleTones(key: string, intervals: number[]): number;
getIntervalBetween(note1: number, note2: number, direction?: number): number;
createScaleMap(keySignature: string): { [rootName: string]: string };
}
namespace Music {
const NUM_TONES: number;
const roots: string[];
const root_values: number[];
const root_indices: { [root: string]: number };
const canonical_notes: string[];
const diatonic_intervals: string[];
const diatonic_accidentals: { [diatonic_interval: string]: { note: number; accidental: number } };
const intervals: { [interval: string]: number };
const scales: { [scale: string]: number[] };
const accidentals: string[];
const noteValues: { [value: string]: { root_index: number; int_val: number } };
}
class Note implements Tickable {
//from tickable interface:
getTicks(): Fraction;
getCenterXShift(): number;
isCenterAligned(): boolean;
setCenterAlignment(align_center: boolean): Note;
getTuplet(): Tuplet;
setTuplet(tuplet: Tuplet): Note;
addToModifierContext(mc: ModifierContext): void;
preFormat(): void;
postFormat(): Note;
getIntrinsicTicks(): Fraction;
setIntrinsicTicks(intrinsicTicks: Fraction): void;
getTickMultiplier(): Fraction;
applyTickMultiplier(numerator: number, denominator: number): void;
setDuration(duration: Fraction): void;
preFormatted: boolean;
constructor(note_struct: { type?: string | undefined; dots?: number | undefined; duration: string });
getPlayNote(): any;
setPlayNote(note: any): Note;
isRest(): boolean;
addStroke(index: number, stroke: Stroke): Note;
getStave(): Stave;
setStave(stave: Stave): Note;
getCategory(): string;
setContext(context: IRenderContext): Note;
getExtraLeftPx(): number;
getExtraRightPx(): number;
setExtraLeftPx(x: number): Note;
setExtraRightPx(x: number): Note;
shouldIgnoreTicks(): boolean;
getLineNumber(): number;
getLineForRest(): number;
getGlyph(): Glyph;
setYs(ys: number[]): Note;
getYs(): number[];
getYForTopText(text_line: number): number;
getBoundingBox(): BoundingBox;
getVoice(): Voice;
setVoice(voice: Voice): Note;
getTickContext(): TickContext;
setTickContext(tc: TickContext): Note;
getDuration(): string;
isDotted(): boolean;
hasStem(): boolean;
getDots(): number;
getNoteType(): string;
setBeam(): Note;
setModifierContext(mc: ModifierContext): Note;
addModifier(modifier: Modifier, index?: number): Note;
getModifierStartXY(): { x: number; y: number };
getMetrics(): {
width: number;
noteWidth: number;
left_shift: number;
modLeftPx: number;
modRightPx: number;
extraLeftPx: number;
extraRightPx: number;
};
setWidth(width: number): void;
getWidth(): number;
setXShift(x: number): Note;
getX(): number;
getAbsoluteX(): number;
setPreFormatted(value: boolean): void;
}
namespace Note {
const CATEGORY: string;
}
class NoteHead extends Note {
constructor(head_options: {
x?: number | undefined;
y?: number | undefined;
note_type?: string | undefined;
duration: string;
displaced?: boolean | undefined;
stem_direction?: number | undefined;
line: number;
x_shift: number;
custom_glyph_code?: string | undefined;
style?: string | undefined;
slashed?: boolean | undefined;
glyph_font_scale?: number | undefined;
});
static DEBUG: boolean;
getCategory(): string;
setContext(context: IRenderContext): NoteHead;
getWidth(): number;
isDisplaced(): boolean;
getStyle(): { shadowColor?: string | undefined; shadowBlur?: string | undefined; fillStyle?: string | undefined; strokeStyle?: string | undefined };
setStyle(style: {
shadowColor?: string | undefined;
shadowBlur?: string | undefined;
fillStyle?: string | undefined;
strokeStyle?: string | undefined;
}): NoteHead;
getGlyph(): Glyph;
setX(x: number): NoteHead;
getY(): number;
setY(y: number): NoteHead;
getLine(): number;
setLine(line: number): NoteHead;
getAbsoluteX(): number;
getBoundingBox(): BoundingBox;
applyStyle(context: IRenderContext): NoteHead;
setStave(stave: Stave): NoteHead;
preFormat(): NoteHead;
draw(): void;
}
class NoteSubGroup extends Modifier {
constructor(subnotes: Note[]);
preFormat(): void;
}
class Ornament extends Modifier {
constructor(type: string);
static DEBUG: boolean;
static format(
ornaments: Ornament[],
state: { left_shift: number; right_shift: number; text_line: number },
): boolean;
setDelayed(delayed: boolean): Ornament;
setUpperAccidental(acc: string): Ornament;
setLowerAccidental(acc: string): Ornament;
draw(): void;
}
namespace Ornament {
const CATEGORY: string;
}
class PedalMarking {
constructor(notes: Note[]); //inconsistent name: 'notes' is called 'type', suggesting string (is Note[])
static DEBUG: boolean;
static createSustain(notes: Note[]): PedalMarking;
static createSostenuto(notes: Note[]): PedalMarking;
static createUnaCorda(notes: Note[]): PedalMarking;
setCustomText(depress?: string, release?: string): PedalMarking;
setStyle(style: PedalMarking.Styles): PedalMarking;
setLine(line: number): PedalMarking;
setContext(context: IRenderContext): PedalMarking;
drawBracketed(): void;
drawText(): void;
draw(): void;
}
namespace PedalMarking {
enum Styles {
TEXT = 1,
BRACKET,
MIXED,
}
const GLYPHS: { [name: string]: { code: string; x_shift: number; y_shift: number } };
}
class RaphaelContext implements IRenderContext {
//TODO remove the following lines once TypeScript allows subclass overrides with type changes or type inconsistencies mentioned below are fixed
setLineWidth(width: number): RaphaelContext;
glow(): RaphaelContext;
constructor(element: HTMLElement);
setFont(family: string, size: number, weight?: number): RaphaelContext;
setRawFont(font: string): RaphaelContext;
setFillStyle(style: string): RaphaelContext;
setBackgroundFillStyle(style: string): RaphaelContext;
setStrokeStyle(style: string): RaphaelContext;
setShadowColor(style: string): RaphaelContext; //inconsistent name: style -> color
setShadowBlur(blur: string): RaphaelContext;
setLineWidth(width: number): void; //inconsistent type: void -> RaphaelContext
setLineDash(dash: string): RaphaelContext;
setLineCap(cap_type: string): RaphaelContext;
scale(x: number, y: number): RaphaelContext;
clear(): void;
resize(width: number, height: number): RaphaelContext;
setViewBox(viewBox: string): void;
rect(x: number, y: number, width: number, height: number): void;
fillRect(x: number, y: number, width: number, height: number): RaphaelContext;
clearRect(x: number, y: number, width: number, height: number): RaphaelContext;
beginPath(): RaphaelContext;
moveTo(x: number, y: number): RaphaelContext;
lineTo(x: number, y: number): RaphaelContext;
bezierCurveTo(x1: number, y1: number, x2: number, y2: number, x: number, y: number): RaphaelContext;
quadraticCurveTo(x1: number, y1: number, x: number, y: number): RaphaelContext; //inconsistent name: x, y -> x2, y2
arc(
x: number,
y: number,
radius: number,
startAngle: number,
endAngle: number,
antiClockwise: boolean,
): RaphaelContext;
glow(): { width: number; fill: boolean; opacity: number; offsetx: number; offsety: number; color: string }; //inconsistent type : Object -> RaphaelContext
fill(): RaphaelContext;
stroke(): RaphaelContext;
closePath(): RaphaelContext;
measureText(text: string): { width: number; height: number };
fillText(text: string, x: number, y: number): RaphaelContext;
save(): RaphaelContext;
restore(): RaphaelContext;
openGroup(): undefined;
closeGroup(): void;
}
class Renderer {
constructor(sel: HTMLElement, backend: Renderer.Backends);
static USE_CANVAS_PROXY: boolean;
static buildContext(
sel: HTMLElement,
backend: Renderer.Backends,
width?: number,
height?: number,
background?: string,
): IRenderContext;
static getCanvasContext(
sel: HTMLElement,
backend: Renderer.Backends,
width?: number,
height?: number,
background?: string,
): CanvasContext;
static getRaphaelContext(
sel: HTMLElement,
backend: Renderer.Backends,
width?: number,
height?: number,
background?: string,
): RaphaelContext;
static getSVGContext(
sel: HTMLElement,
backend: Renderer.Backends,
width?: number,
height?: number,
background?: string,
): SVGContext;
static bolsterCanvasContext(ctx: CanvasRenderingContext2D): CanvasContext;
static drawDashedLine(
context: IRenderContext,
fromX: number,
fromY: number,
toX: number,
toY: number,
dashPattern: number[],
): void;
resize(width: number, height: number): Renderer;
getContext(): IRenderContext;
}
namespace Renderer {
enum Backends {
CANVAS = 1,
RAPHAEL,
SVG,
VML,
}
enum LineEndType {
NONE = 1,
UP,
DOWN,
}
}
class Repetition extends StaveModifier {
constructor(type: Repetition.type, x: number, y_shift: number);
getCategory(): string;
setShiftX(x: number): Repetition;
setShiftY(y: number): Repetition;
draw(stave: Stave, x: number): Repetition;
drawCodaFixed(stave: Stave, x: number): Repetition;
drawSignoFixed(stave: Stave, x: number): Repetition; //inconsistent name: drawSignoFixed -> drawSegnoFixed
drawSymbolText(stave: Stave, x: number, text: string, draw_coda: boolean): Repetition;
}
namespace Repetition {
enum type {
NONE = 1,
CODA_LEFT,
CODA_RIGHT,
SEGNO_LEFT,
SEGNO_RIGHT,
DC,
DC_AL_CODA,
DC_AL_FINE,
DS,
DS_AL_CODA,
DS_AL_FINE,
FINE,
}
}
class Stave {
constructor(
x: number,
y: number,
width: number,
options?: {
vertical_bar_width?: number | undefined;
glyph_spacing_px?: number | undefined;
num_lines?: number | undefined;
fill_style?: string | undefined;
spacing_between_lines_px?: number | undefined;
space_above_staff_ln?: number | undefined;
space_below_staff_ln?: number | undefined;
top_text_position?: number | undefined;
},
);
options: {
vertical_bar_width?: number | undefined;
glyph_spacing_px?: number | undefined;
num_lines?: number | undefined;
fill_style?: string | undefined;
left_bar?: boolean | undefined;
right_bar?: boolean | undefined;
spacing_between_lines_px?: number | undefined;
space_above_staff_ln?: number | undefined;
space_below_staff_ln?: number | undefined;
top_text_position?: number | undefined;
};
resetLines(): void;
setNoteStartX(x: number): Stave;
getNoteStartX(): number;
getNoteEndX(): number;
getTieStartX(): number;
getTieEndX(): number;
setContext(context: IRenderContext): Stave;
getContext(): IRenderContext;
getX(): number;
getNumLines(): number;
setX(x: number): Stave;
setY(y: number): Stave;
setWidth(width: number): Stave;
getWidth(): number;
setMeasure(measure: number): Stave;
setBegBarType(type: Barline.type): Stave;
setEndBarType(type: Barline.type): Stave;
getModifierXShift(index: number): number;
setRepetitionTypeLeft(type: Repetition.type, y: number): Stave;
setRepetitionTypeRight(type: Repetition.type, y: number): Stave;
setVoltaType(type: Volta.type, number_t: number, y: number): Stave;
setSection(section: string, y: number): Stave;
setTempo(tempo: { name?: string | undefined; duration: string; dots: boolean; bpm: number }, y: number): Stave;
setText(
text: string,
position: Modifier.Position,
options?: { shift_x?: number | undefined; shift_y?: number | undefined; justification?: TextNote.Justification | undefined },
): Stave;
getHeight(): number;
getSpacingBetweenLines(): number;
getBoundingBix(): BoundingBox;
getBottomY(): number;
getBottomLineY(): number;
getYForLine(line: number): number;
getYForTopText(line?: number): number;
getYForBottomText(line?: number): number;
getYForNote(line?: number): number;
getYForGlyphs(): number;
addGlyph(glypg: Glyph): Stave;
addEndGlyph(glypg: Glyph): Stave;
addModifier(modifier: StaveModifier, position?: StaveModifier.Position): Stave;
addEndModifier(modifier: StaveModifier): Stave;
addKeySignature(keySpec: string): Stave;
setKeySignature(keySpec: string, cancelKeySpec: string, position?: StaveModifier.Position): Stave;
addClef(clef: string, size?: string, annotation?: string, position?: StaveModifier.Position): Stave;
addEndClef(clef: string, size?: string, annotation?: string): Stave;
setEndClef(clef: string, size?: string, annotation?: string): Stave;
addTimeSignature(timeSpec: string, customPadding?: number): void; //inconsistent type: void -> Stave
addTrebleGlyph(): Stave;
draw(): void;
drawVertical(x: number, isDouble: boolean): void;
drawVerticalFixed(x: number, isDouble: boolean): void;
drawVerticalBar(x: number): void;
drawVerticalBarFixed(x: number): void;
getConfigForLines(): { visible: boolean }[];
setConfigForLine(line_number: number, line_config: { visible: boolean }): Stave;
setConfigForLines(lines_configuration: { visible: boolean }[]): Stave;
getModifiers(position?: number, category?: string): StaveModifier[];
}
class StaveConnector {
constructor(top_stave: Stave, bottom_stave: Stave);
top_stave: Stave;
bottom_stave: Stave;
thickness: number;
x_shift: number;
setContext(ctx: IRenderContext): StaveConnector;
setType(type: StaveConnector.type): StaveConnector;
setText(text: string, text_options?: { shift_x?: number | undefined; shift_y?: number | undefined }): StaveConnector;
setFont(font: { family?: string | undefined; size?: number | undefined; weight?: string | undefined }): void; //inconsistent type: void -> StaveConnector
setXShift(x_shift: number): StaveConnector;
draw(): void;
drawBoldDoubleLine(ctx: Object, type: StaveConnector.type, topX: number, topY: number, botY: number): void;
}
namespace StaveConnector {
enum type {
SINGLE_RIGHT = 0,
SINGLE_LEFT = 1,
SINGLE = 1,
DOUBLE = 2,
BRACE = 3,
BRACKET = 4,
BOLD_DOUBLE_LEFT = 5,
BOLD_DOUBLE_RIGHT = 6,
THIN_DOUBLE = 7,
NONE = 8,
}
}
class StaveHairpin {
constructor(notes: { first_note: Note; last_note: Note }, type: StaveHairpin.type);
static FormatByTicksAndDraw(
ctx: IRenderContext,
formatter: Formatter,
notes: { first_note: Note; last_note: Note },
type: StaveHairpin.type,
position: Modifier.Position,
options?: { height: number; y_shift: number; left_shift_ticks: number; right_shift_ticks: number },
): void;
setContext(context: IRenderContext): StaveHairpin;
setPosition(position: Modifier.Position): StaveHairpin;
setRenderOptions(options: {
height?: number | undefined;
y_shift: number;
left_shift_px: number;
right_shift_px: number;
}): StaveHairpin;
setNotes(notes: { first_note: Note; last_note: Note }): StaveHairpin;
renderHairpin(params: {
first_x: number;
last_x: number;
first_y: number;
last_y: number;
staff_height: number;
}): void;
draw(): boolean;
}
namespace StaveHairpin {
enum type {
CRESC = 1,
DECRESC,
}
}
class StaveLine {
constructor(notes: { first_note: Note; last_note: Note; first_indices: number[]; last_indices: number[] });
setContext(context: Object): StaveLine;
setFont(font: { family: string; size: number; weight: string }): StaveLine;
setText(text: string): StaveLine;
setNotes(notes: {
first_note: Note;
last_note: Note;
first_indices?: number[] | undefined;
last_indices?: number[] | undefined;
}): StaveLine;
applyLineStyle(): void;
applyFontStyle(): void;
draw(): StaveLine;
//inconsistent API: this should be set via an options object in the constructor
render_options: {
padding_left: number;
padding_right: number;
line_width: number;
line_dash: number[];
rounded_end: boolean;
color: string;
draw_start_arrow: boolean;
draw_end_arrow: boolean;
arrowhead_length: number;
arrowhead_angle: number;
text_position_vertical: StaveLine.TextVerticalPosition;
text_justification: StaveLine.TextJustification;
};
}
namespace StaveLine {
enum TextVerticalPosition {
TOP = 1,
BOTTOM,
}
enum TextJustification {
LEFT = 1,
CENTER,
RIGHT,
}
}
class StaveModifier {
getCategory(): string;
makeSpacer(
padding: number,
): { getContext: Function; setStave: Function; renderToStave: Function; getMetrics: Function };
placeGlyphOnLine(glyph: Glyph, stave: Stave, line: number): void;
setPadding(padding: number): void;
addToStave(stave: Stave, firstGlyph: boolean): StaveModifier;
addToStaveEnd(stave: Stave, firstGlyph: boolean): StaveModifier;
addModifier(): void;
addEndModifier(): void;
getPosition(): number;
getWidth(): number;
getPadding(index: number): number;
}
namespace StaveModifier {
// @see https://github.com/0xfe/vexflow/blob/master/src/stavemodifier.js#L9
enum Position {
LEFT = 1,
RIGHT = 2,
ABOVE = 3,
BELOW = 4,
BEGIN = 5,
END = 6,
}
}
class StaveNote extends StemmableNote {
//TODO remove the following lines once TypeScript allows subclass overrides with type changes and/or inconsistencies mentioned below are fixed
buildStem(): StemmableNote;
setStave(stave: Stave): Note;
//TODO: vexflow actualy managed to have Note use modifier, index and stavenote index,modifier. To use the function in
// Typescript we need to allow both. The name is the correct type :(
addModifier(index: any, modifier?: any): Note;
getModifierStartXY(): { x: number; y: number };
getDots(): number;
x_shift: number;
constructor(note_struct: {
type?: string | undefined;
dots?: number | undefined;
duration: string;
clef?: string | undefined;
keys: string[];
octave_shift?: number | undefined;
auto_stem?: boolean | undefined;
stem_direction?: number | undefined;
});
static DEBUG: boolean;
static format(
notes: StaveNote[],
state: { left_shift: number; right_shift: number; text_line: number },
): boolean;
static formatByY(
notes: StaveNote[],
state: { left_shift: number; right_shift: number; text_line: number },
): void;
static postFormat(notes: StaveNote[]): boolean;
buildStem(): void; //inconsistent type: void -> StaveNote
buildNoteHeads(): void;
autoStem(): void;
calculateKeyProps(): void;
getBoundingBox(): BoundingBox;
getLineNumber(): number;
isRest(): boolean;
isChord(): boolean;
hasStem(): boolean;
getYForTopText(text_line: number): number;
getYForBottomText(text_line: number): number;
setStave(stave: Stave): StaveNote;
getKeys(): string[];
getKeyProps(): {
key: string;
octave: number;
line: number;
int_value: number;
accidental: string;
code: number;
stroke: number;
shift_right: number;
displaced: boolean;
}[];
isDisplaced(): boolean;
setNoteDisplaced(displaced: boolean): StaveNote;
getTieRightX(): number;
getTieLeftX(): number;
getLineForRest(): number;
getModifierStartXY(position: Modifier.Position, index: number): { x: number; y: number };
setStyle(style: {
shadowColor?: string | undefined;
shadowBlur?: string | undefined;
fillStyle?: string | undefined;
strokeStyle?: string | undefined;
}): void; // inconsistent type: void -> StaveNote
setStemStyle(style: {
shadowColor?: string | undefined;
shadowBlur?: string | undefined;
fillStyle?: string | undefined;
strokeStyle?: string | undefined;
}): void;
setKeyStyle(
index: number,
style: { shadowColor?: string | undefined; shadowBlur?: string | undefined; fillStyle?: string | undefined; strokeStyle?: string | undefined },
): StaveNote;
setKeyLine(index: number, line: number): StaveNote;
getKeyLine(index: number): number;
addToModifierContext(mContext: ModifierContext): StaveNote;
addAccidental(index: number, accidental: Accidental): StaveNote;
addArticulation(index: number, articulation: Articulation): StaveNote;
addAnnotation(index: number, annotation: Annotation): StaveNote;
addDot(index: number): StaveNote;
addDotToAll(): StaveNote;
getAccidentals(): Accidental[];
getDots(): Dot[];
getVoiceShiftWidth(): number;
calcExtraPx(): void;
preFormat(): void;
getNoteHeadBounds(): { y_top: number; y_bottom: number; highest_line: number; lowest_line: number };
getNoteHeadBeginX(): number;
getNoteHeadEndX(): number;
drawLedgerLines(): void;
drawModifiers(): void;
drawFlag(): void;
drawNoteHeads(): void;
drawStem(struct: {
x_begin?: number | undefined;
x_end?: number | undefined;
y_top?: number | undefined;
y_bottom?: number | undefined;
y_extend?: number | undefined;
stem_extension?: number | undefined;
stem_direction?: number | undefined;
}): void;
draw(): void;
}
namespace StaveNote {
const STEM_UP: number;
const STEM_DOWN: number;
const CATEGORY: string;
}
class StaveSection extends Modifier {
//TODO remove the following lines once TypeScript allows subclass overrides with type changes
draw(): void;
constructor(section: string, x: number, shift_y: number);
getCategory(): string;
setStaveSection(section: string): StaveSection;
setShiftX(x: number): StaveSection;
setShiftY(y: number): StaveSection;
draw(stave: Stave, shift_x: number): StaveSection;
}
class StaveTempo extends StaveModifier {
constructor(
tempo: { name?: string | undefined; duration: string; dots: number; bpm: number },
x: number,
shift_y: number,
);
getCategory(): string;
setTempo(tempo: { name?: string | undefined; duration: string; dots: number; bpm: number }): StaveTempo;
setShiftX(x: number): StaveTempo;
setShiftY(y: number): StaveTempo;
draw(stave: Stave, shift_x: number): StaveTempo;
}
class StaveText extends Modifier {
//TODO remove the following lines once TypeScript allows subclass overrides with type changes
draw(): void;
constructor(
text: string,
position: Modifier.Position,
options?: { shift_x?: number | undefined; shift_y?: number | undefined; justification?: TextNote.Justification | undefined },
);
getCategory(): string;
setStaveText(text: string): StaveText;
setShiftX(x: number): StaveText;
setShiftY(y: number): StaveText;
setFont(font: { family?: string | undefined; size?: number | undefined; weight?: number | undefined }): void;
setText(text: string): void;
draw(stave: Stave): StaveText;
}
class StaveTie {
/**
* @see https://github.com/0xfe/vexflow/blob/master/src/stavetie.js#L12
*
* Notes is a struct that has:
*
* {
* first_note: Note,
* last_note: Note,
* first_indices: [n1, n2, n3],
* last_indices: [n1, n2, n3]
* }
* All properties are optional, since ties can span line breaks in which case
* two ties can be used, each with either "first_note" or "last_note" missing.
*
**/
constructor(
notes: { first_note?: Note | undefined; last_note?: Note | undefined; first_indices?: number[] | undefined; last_indices?: number[] | undefined },
text?: string,
);
setContext(context: IRenderContext): StaveTie;
setFont(font: { family: string; size: number; weight: string }): StaveTie;
setNotes(notes: {
first_note?: Note | undefined;
last_note?: Note | undefined;
first_indices?: number[] | undefined;
last_indices?: number[] | undefined;
}): StaveTie;
isPartial(): boolean;
renderTie(params: {
first_ys: number[];
last_ys: number[];
last_x_px: number;
first_x_px: number;
direction: number;
}): void;
renderText(first_x_px: number, last_x_px: number): void;
draw(): boolean;
}
class Stem {
constructor(options: {
x_begin?: number | undefined;
x_end?: number | undefined;
y_top?: number | undefined;
y_bottom?: number | undefined;
y_extend?: number | undefined;
stem_extension?: number | undefined;
stem_direction?: number | undefined;
});
static DEBUG: boolean;
setNoteHeadXBounds(x_begin: number, x_end: number): Stem;
setDirection(direction: number): void;
setExtension(extension: number): void;
setYBounds(y_top: number, y_bottom: number): void;
getCategory(): string;
setContext(context: IRenderContext): Stem;
getHeight(): number;
getBoundingBox(): BoundingBox;
getExtents(): { topY: number; baseY: number };
setStyle(style: {
shadowColor?: string | undefined;
shadowBlur?: string | undefined;
fillStyle?: string | undefined;
strokeStyle?: string | undefined;
}): void;
getStyle(): { shadowColor?: string | undefined; shadowBlur?: string | undefined; fillStyle?: string | undefined; strokeStyle?: string | undefined };
applyStyle(context: IRenderContext): Stem;
draw(): void;
//inconsistent API: this should be set via the options object in the constructor
hide: boolean;
}
namespace Stem {
const UP: number;
const DOWN: number;
}
class StemmableNote extends Note {
//TODO remove the following lines once TypeScript allows subclass overrides with type changes
setBeam(): Note;
constructor(note_struct: { type?: string | undefined; dots?: number | undefined; duration: string });
static DEBUG: boolean;
flag: Glyph;
getAttribute(attr: string): any;
setFlagStyle(style_struct: {
shadowColor?: string | undefined;
shadowBlur?: string | undefined;
fillStyle?: string | undefined;
strokeStyle?: string | undefined;
}): void;
getStem(): Stem;
setStem(stem: Stem): StemmableNote;
buildStem(): StemmableNote;
getStemLength(): number;
getBeamCount(): number;
getStemMinumumLength(): number; //inconsistent name: getStemMinumumLength -> getStemMinimumLength
getStemDirection(): number;
setStemDirection(direction: number): StemmableNote;
getStemX(): number;
getCenterGlyphX(): number;
getStemExtension(): number;
setStemLength(): number;
getStemExtents(): { topY: number; baseY: number };
setBeam(beam: Beam): StemmableNote;
getYForTopText(text_line: number): number;
getYForBottomText(text_line: number): number;
postFormat(): StemmableNote;
drawStem(stem_struct: {
x_begin?: number | undefined;
x_end?: number | undefined;
y_top?: number | undefined;
y_bottom?: number | undefined;
y_extend?: number | undefined;
stem_extension?: number | undefined;
stem_direction?: number | undefined;
}): void;
}
class StringNumber extends Modifier {
//TODO remove the following lines once TypeScript allows subclass overrides with type changes
setNote(note: Note): StringNumber;
// actually this is not really consistent in the vexflow code "ctx.measureText(this.string_number).width" looks
// like it is a string. But from the use of it it might be a number ?!
constructor(number: number | string);
static format(
nums: StringNumber[],
state: { left_shift: number; right_shift: number; text_line: number },
): boolean;
string_number: number | string;
getNote(): Note;
setNote(note: StemmableNote): StringNumber;
getIndex(): number;
setIndex(index: number): StringNumber;
setLineEndType(leg: Renderer.LineEndType): StringNumber;
getPosition(): Modifier.Position;
setPosition(position: Modifier.Position): StringNumber;
setStringNumber(number: number): StringNumber;
setOffsetX(x: number): StringNumber;
setOffsetY(y: number): StringNumber;
setLastNote(note: StemmableNote): StringNumber;
setDashed(dashed: boolean): StringNumber;
draw(): void;
}
namespace StringNumber {
const CATEGORY: string;
}
class Stroke extends Modifier {
constructor(type: Stroke.Type, options?: { all_voices?: boolean | undefined });
static format(
strokes: Stroke[],
state: { left_shift: number; right_shift: number; text_line: number },
): boolean;
getPosition(): Modifier.Position;
addEndNote(note: Note): Stroke;
draw(): void;
}
namespace Stroke {
enum Type {
BRUSH_DOWN = 1,
BRUSH_UP,
ROLL_DOWN,
ROLL_UP,
RASQUEDO_DOWN,
RASQUEDO_UP,
ARPEGGIO_DIRECTIONLESS,
}
const CATEGORY: string;
}
class SVGContext implements IRenderContext {
constructor(element: HTMLElement);
svg: SVGElement;
state: any;
attributes: any;
lineWidth: number;
iePolyfill(): boolean;
setFont(family: string, size: number, weight?: number | string): SVGContext;
setRawFont(font: string): SVGContext;
setFillStyle(style: string): SVGContext;
setBackgroundFillStyle(style: string): SVGContext;
setStrokeStyle(style: string): SVGContext;
setShadowColor(style: string): SVGContext; //inconsistent name: style -> color
setShadowBlur(blur: string): SVGContext;
setLineWidth(width: number): SVGContext;
setLineDash(dash: string): SVGContext;
setLineCap(cap_type: string): SVGContext;
resize(width: number, height: number): SVGContext;
scale(x: number, y: number): SVGContext;
setViewBox(xMin: number, yMin: number, width: number, height: number): void;
clear(): void;
rect(x: number, y: number, width: number, height: number): SVGContext;
fillRect(x: number, y: number, width: number, height: number): SVGContext;
clearRect(x: number, y: number, width: number, height: number): SVGContext;
beginPath(): SVGContext;
moveTo(x: number, y: number): SVGContext;
lineTo(x: number, y: number): SVGContext;
bezierCurveTo(x1: number, y1: number, x2: number, y2: number, x: number, y: number): SVGContext;
quadraticCurveTo(x1: number, y1: number, x: number, y: number): SVGContext; //inconsistent: x, y -> x2, y2
arc(
x: number,
y: number,
radius: number,
startAngle: number,
endAngle: number,
antiClockwise: boolean,
): SVGContext;
closePath(): SVGContext;
glow(): SVGContext;
fill(): SVGContext;
stroke(): SVGContext;
measureText(text: string): SVGRect;
ieMeasureTextFix(bbox: SVGRect, text: string): { x: number; y: number; width: number; height: number };
fillText(text: string, x: number, y: number): SVGContext;
save(): SVGContext;
restore(): SVGContext;
openGroup(): Node;
closeGroup(): void;
}
class TabNote extends StemmableNote {
//TODO remove the following lines once TypeScript allows subclass overrides with type changes
setStave(stave: Stave): Note;
getModifierStartXY(): { x: number; y: number };
constructor(
tab_struct: {
positions: { str: number; fret: number }[];
type?: string | undefined;
dots?: number | undefined;
duration: string;
stem_direction?: number | undefined;
},
draw_stem?: boolean,
);
getCategory(): string;
setGhost(ghost: boolean): TabNote;
hasStem(): boolean;
getStemExtension(): number;
addDot(): TabNote;
updateWidth(): void;
setStave(stave: Stave): TabNote;
getPositions(): { str: number; fret: number }[];
addToModifierContext(mc: ModifierContext): TabNote;
getTieRightX(): number;
getTieLeftX(): number;
getModifierStartXY(position: Modifier.Position, index: number): { x: number; y: number };
getLineForRest(): number;
preFormat(): void;
getStemX(): number;
getStemY(): number;
getStemExtents(): { topY: number; baseY: number };
drawFlag(): void;
drawModifiers(): void;
drawStemThrough(): void;
draw(): void;
}
class TabSlide extends TabTie {
constructor(
notes: { first_note: Note; last_note: Note; first_indices: number[]; last_indices: number[] },
direction?: number,
);
static createSlideUp(notes: {
first_note: Note;
last_note: Note;
first_indices: number[];
last_indices: number[];
}): TabSlide;
static createSlideDown(notes: {
first_note: Note;
last_note: Note;
first_indices: number[];
last_indices: number[];
}): TabSlide;
renderTie(params: {
first_ys: number[];
last_ys: number[];
last_x_px: number;
first_x_px: number;
direction: number;
}): void;
}
namespace TabSlide {
const SLIDE_UP: number;
const SLIDE_DOWN: number;
}
class TabStave extends Stave {
constructor(
x: number,
y: number,
width: number,
options?: {
vertical_bar_width?: number | undefined;
glyph_spacing_px?: number | undefined;
num_lines?: number | undefined;
fill_style?: string | undefined;
spacing_between_lines_px?: number | undefined;
space_above_staff_ln?: number | undefined;
space_below_staff_ln?: number | undefined;
top_text_position?: number | undefined;
},
);
getYForGlyphs(): number;
addTabGlyph(): TabStave;
}
class TabTie extends StaveTie {
constructor(
notes: { first_note: Note; last_note: Note; first_indices: number[]; last_indices: number[] },
text?: string,
);
createHammeron(notes: {
first_note: Note;
last_note: Note;
first_indices: number[];
last_indices: number[];
}): TabTie;
createPulloff(notes: {
first_note: Note;
last_note: Note;
first_indices: number[];
last_indices: number[];
}): TabTie;
draw(): boolean;
}
class TextBracket {
constructor(bracket_data: {
start: Note;
stop: Note;
text?: string | undefined;
superscript?: string | undefined;
position?: TextBracket.Positions | undefined;
});
static DEBUG: boolean;
start: Note;
stop: Note;
position: TextBracket.Positions;
applyStyle(context: IRenderContext): TextBracket;
setDashed(dashed: boolean, dash?: number[]): TextBracket;
setFont(font: { family: string; size: number; weight: string }): TextBracket;
setContext(context: IRenderContext): TextBracket;
setLine(line: number): TextBracket;
draw(): void;
}
namespace TextBracket {
enum Positions {
TOP = 1,
BOTTOM = -1,
}
}
class TextDynamics extends Note {
constructor(text_struct: { duration: string; text: string; line?: number | undefined });
static DEBUG: boolean;
setLine(line: number): TextDynamics;
preFormat(): TextDynamics;
draw(): void;
}
class TextNote extends Note {
constructor(text_struct: {
duration: string;
text?: string | undefined;
superscript?: boolean | undefined;
subscript?: boolean | undefined;
glyph?: string | undefined;
font?: { family: string; size: number; weight: string } | undefined;
line?: number | undefined;
smooth?: boolean | undefined;
ignore_ticks?: boolean | undefined;
});
setJustification(just: TextNote.Justification): TextNote;
setLine(line: number): TextNote;
preFormat(): void;
draw(): void;
}
namespace TextNote {
enum Justification {
LEFT = 1,
CENTER,
RIGHT,
}
const GLYPHS: { [name: string]: { code: string; point: number; x_shift: number; y_shift: number } };
}
interface Tickable {
setContext(context: IRenderContext): void;
getBoundingBox(): BoundingBox;
getTicks(): Fraction;
shouldIgnoreTicks(): boolean;
getWidth(): number;
setXShift(x: number): Tickable;
getCenterXShift(): number;
isCenterAligned(): boolean;
setCenterAlignment(align_center: boolean): Tickable;
getVoice(): Voice;
setVoice(voice: Voice): void;
getTuplet(): Tuplet;
setTuplet(tuplet: Tuplet): Tickable;
addToModifierContext(mc: ModifierContext): void;
addModifier(mod: Modifier): Tickable;
setTickContext(tc: TickContext): void;
preFormat(): void;
postFormat(): Tickable;
getIntrinsicTicks(): Fraction;
setIntrinsicTicks(intrinsicTicks: Fraction): void;
getTickMultiplier(): Fraction;
applyTickMultiplier(numerator: number, denominator: number): void;
setDuration(duration: Fraction): void;
}
class TickContext {
setContext(context: IRenderContext): void;
getContext(): IRenderContext;
shouldIgnoreTicks(): boolean;
getWidth(): number;
getX(): number;
setX(x: number): TickContext;
getXBase(): number;
setXBase(xBase: number): void;
getXOffset(): number;
setXOffset(xOffset: number): void;
getPixelsUsed(): number;
setPixelsUsed(pixelsUsed: number): TickContext;
setPadding(padding: number): TickContext;
getMaxTicks(): number;
getMinTicks(): number;
getTickables(): Tickable[];
getCenterAlignedTickables(): Tickable[];
getMetrics(): { width: number; notePx: number; extraLeftPx: number; extraRightPx: number };
getCurrentTick(): Fraction;
setCurrentTick(tick: Fraction): void;
getExtraPx(): { left: number; right: number; extraLeft: number; extraRight: number };
addTickable(tickable: Tickable): TickContext;
preFormat(): TickContext;
postFormat(): TickContext;
static getNextContext(tContext: TickContext): TickContext;
}
class TimeSignature extends StaveModifier {
//TODO remove the following lines once TypeScript allows subclass overrides with type changes
addModifier(): void;
addEndModifier(): void;
constructor(timeSpec: string, customPadding?: number);
parseTimeSpec(timeSpec: string): { num: number; glyph: Glyph };
makeTimeSignatureGlyph(topNums: number[], botNums: number[]): Glyph;
getTimeSig(): { num: number; glyph: Glyph };
addModifier(stave: Stave): void;
addEndModifier(stave: Stave): void;
}
namespace TimeSignature {
const glyphs: { [name: string]: { code: string; point: number; line: number } };
}
class TimeSigNote extends Note {
//TODO remove the following lines once TypeScript allows subclass overrides with type changes or type inconsistencies mentioned below are fixed
setStave(stave: Stave): Note;
constructor(timeSpec: string, customPadding: number);
setStave(stave: Stave): void; //inconsistent type: void -> TimeSignote
getBoundingBox(): BoundingBox;
addToModifierContext(): TimeSigNote;
preFormat(): TimeSigNote;
draw(): void;
}
class Tremolo extends Modifier {
constructor(num: number);
getCategory(): string;
draw(): void;
}
class Tuning {
constructor(tuningString?: string);
noteToInteger(noteString: string): number;
setTuning(tuningString: string): void;
getValueForString(stringNum: string): number;
getValueForFret(fretNum: string, stringNum: string): number;
getNoteForFret(fretNum: string, stringNum: string): string;
}
namespace Tuning {
const names: { [name: string]: string };
}
class Tuplet {
constructor(
notes: StaveNote[],
options?: {
location?: number | undefined;
bracketed?: boolean | undefined;
ratioed: boolean;
num_notes?: number | undefined;
notes_occupied?: number | undefined;
y_offset?: number | undefined;
},
);
attach(): void;
detach(): void;
setContext(context: IRenderContext): Tuplet;
setBracketed(bracketed: boolean): Tuplet;
setRatioed(ratioed: boolean): Tuplet;
setTupletLocation(location: number): Tuplet;
getNotes(): StaveNote[];
getNoteCount(): number;
getBeatsOccupied(): number;
setBeatsOccupied(beats: number): void;
resolveGlyphs(): void;
draw(): void;
}
namespace Tuplet {
const LOCATION_TOP: number;
const LOCATION_BOTTOM: number;
}
class Vibrato extends Modifier {
static format(
vibratos: Vibrato[],
state: { left_shift: number; right_shift: number; text_line: number },
context: ModifierContext,
): boolean;
setHarsh(harsh: boolean): Vibrato;
setVibratoWidth(width: number): Vibrato;
draw(): void;
}
namespace Vibrato {
const CATEGORY: string;
}
class Voice {
constructor(time: { num_beats?: number | undefined; beat_value?: number | undefined; resolution?: number | undefined });
getTotalTicks(): Fraction;
getTicksUsed(): Fraction;
getLargestTickWidth(): number;
getSmallestTickCount(): Fraction;
getTickables(): Tickable[];
getMode(): Voice.Mode;
setMode(mode: Voice.Mode): Voice;
getResolutionMultiplier(): number;
getActualResolution(): number;
setStave(stave: Stave): Voice;
getBoundingBox(): BoundingBox;
getVoiceGroup(): VoiceGroup;
setVoiceGroup(g: VoiceGroup): Voice;
setStrict(strict: boolean): Voice;
isComplete(): boolean;
addTickable(tickable: Tickable): Voice;
addTickables(tickables: Tickable[]): Voice;
preFormat(): Voice;
draw(context: IRenderContext, stave?: Stave): void;
}
namespace Voice {
enum Mode {
STRICT = 1,
SOFT,
FULL,
}
}
class VoiceGroup {
getVoices(): Voice[];
getModifierContexts(): ModifierContext[];
addVoice(voice: Voice): void;
}
class Volta extends StaveModifier {
constructor(type: Volta.type, number: number, x: number, y_shift: number);
getCategory(): string;
setShiftY(y: number): Volta;
draw(stave: Stave, x: number): Volta;
}
namespace Volta {
enum type {
NONE = 1,
BEGIN,
MID,
END,
BEGIN_END,
}
}
class Parser {
constructor(grammar: any);
grammar: any;
parse(line: any): any;
line: any;
pos: any;
errorPos: any;
matchFail(returnPos: any): void;
matchSuccess(): void;
matchToken(
token: any,
noSpace?: boolean,
):
| {
success: boolean;
matchedString: any;
incrementPos: any;
pos: any;
}
| {
success: boolean;
pos: any;
matchedString?: undefined;
incrementPos?: undefined;
};
expectOne(rule: any, maybe?: boolean): any;
expectOneOrMore(rule: any, maybe?: boolean): any;
expectZeroOrMore(rule: any): any;
expect(rules: any): any;
}
class EasyScore {
constructor(options?: {});
defaults: {
clef: string;
time: string;
stem: string;
};
set(defaults: any): EasyScore;
setOptions(options: any): EasyScore;
options: any;
factory: any;
builder: any;
grammar: any;
parser: Parser;
setContext(context: any): EasyScore;
parse(line: any, options?: {}): any;
beam(notes: any, options?: {}): any;
tuplet(notes: any, options?: {}): any;
notes(line: any, options?: {}): any;
voice(notes: any, voiceOptions: any): any;
addCommitHook(commitHook: any): any;
}
class System {
constructor(params?: any);
setOptions(options?: any): void;
addConnector(type?: string): any;
addStave(params: any): Stave;
format(): any;
draw(): any;
}
class Factory {
static newFromElementId(elementId: any, width?: number, height?: number): Factory;
constructor(options: any);
options: {
stave: {
space: number;
};
renderer: {
context: any;
elementId: string;
backend: number;
width: number;
height: number;
background: string;
};
font: {
face: string;
point: number;
style: string;
};
};
reset(): void;
renderQ: any[];
systems: any[];
staves: any[];
voices: any[];
stave: Stave;
getOptions(): {
stave: {
space: number;
};
renderer: {
context: any;
elementId: string;
backend: number;
width: number;
height: number;
background: string;
};
font: {
face: string;
point: number;
style: string;
};
};
setOptions(options: any): void;
initRenderer(): void;
context: any;
getContext(): any;
setContext(context: any): Factory;
getStave(): Stave;
getVoices(): any[];
space(spacing: any): number;
Stave(params: any): Stave;
TabStave(params: any): TabStave;
StaveNote(noteStruct: any): StaveNote;
GlyphNote(glyph: any, noteStruct: any, options: any): GlyphNote;
RepeatNote(type: any, noteStruct: any, options: any): RepeatNote;
GhostNote(noteStruct: any): GhostNote;
TextNote(textNoteStruct: any): TextNote;
BarNote(params: any): BarNote;
ClefNote(params: any): ClefNote;
TimeSigNote(params: any): TimeSigNote;
KeySigNote(params: any): KeySigNote;
TabNote(noteStruct: any): TabNote;
GraceNote(noteStruct: any): GraceNote;
GraceNoteGroup(params: any): GraceNoteGroup;
Accidental(params: any): Accidental;
Annotation(params: any): Annotation;
Articulation(params: any): Articulation;
TextDynamics(params: any): TextDynamics;
Fingering(params: any): FretHandFinger;
StringNumber(params: any): StringNumber;
TickContext(): TickContext;
ModifierContext(): ModifierContext;
MultiMeasureRest(params: any): MultiMeasureRest;
Voice(params: any): Voice;
StaveConnector(params: any): StaveConnector;
Formatter(): Formatter;
Tuplet(params: any): Tuplet;
Beam(params: any): Beam;
Curve(params: any): Curve;
StaveTie(params: any): StaveTie;
StaveLine(params: any): StaveLine;
VibratoBracket(params: any): VibratoBracket;
TextBracket(params: any): TextBracket;
System(params?: {}): System;
EasyScore(params?: {}): EasyScore;
PedalMarking(params?: {}): PedalMarking;
NoteSubGroup(params?: {}): NoteSubGroup;
draw(): void;
}
class VibratoBracket extends Element {
constructor(bracket_data: any);
start: any;
stop: any;
line: number;
render_options: {
harsh: boolean;
wave_height: number;
wave_width: number;
wave_girth: number;
};
setLine(line: any): VibratoBracket;
setHarsh(harsh: any): VibratoBracket;
draw(): void;
}
class GlyphNote extends Note {
constructor(glyph: any, noteStruct: any, options: any);
options: any;
setGlyph(glyph: any): GlyphNote;
draw(): void;
}
class KeySigNote extends Note {
constructor(keySpec: any, cancelKeySpec: any, alterKeySpec: any);
keySignature: KeySignature;
draw(): void;
}
class MultiMeasureRest extends Element {
constructor(number_of_measures: any, options: any);
render_options: {
show_number: boolean;
number_line: number;
number_glyph_point: any;
padding_left: any;
padding_right: any;
line: number;
spacing_between_lines_px: number;
line_thickness: any;
serif_thickness: number;
use_symbols: boolean;
symbol_spacing: any;
semibrave_rest_glyph_scale: number;
};
number_of_measures: any;
xs: {
left: number;
right: number;
};
getXs(): {
left: number;
right: number;
};
setStave(stave: any): MultiMeasureRest;
stave: any;
getStave(): any;
drawLine(ctx: any, left: any, right: any, sbl: any): void;
drawSymbols(ctx: any, left: any, right: any, sbl: any): void;
draw(): void;
}
class RepeatNote extends GlyphNote {
constructor(type: any, noteStruct: any, options: any);
}
}
}
declare module 'vexflow' {
export = Vex;
} | the_stack |
import { Matrix } from './Matrix'
import { Vector3 } from './Vector3'
import { MathTmp } from './preallocatedVariables'
import { DEG2RAD, RAD2DEG } from './types'
import { Scalar } from "./Scalar"
/** @public */
export type ReadOnlyQuaternion = {
readonly x: number
readonly y: number
readonly z: number
readonly w: number
}
/**
* Class used to store quaternion data
* {@link https://en.wikipedia.org/wiki/Quaternion }
* {@link http://doc.babylonjs.com/features/position,_rotation,_scaling }
* @public
*/
export class Quaternion {
/**
* Creates a new Quaternion from the given floats
* @param x - defines the first component (0 by default)
* @param y - defines the second component (0 by default)
* @param z - defines the third component (0 by default)
* @param w - defines the fourth component (1.0 by default)
*/
constructor(
/** defines the first component (0 by default) */
public x: number = 0.0,
/** defines the second component (0 by default) */
public y: number = 0.0,
/** defines the third component (0 by default) */
public z: number = 0.0,
/** defines the fourth component (1.0 by default) */
public w: number = 1.0
) {}
// Statics
/**
* Creates a new quaternion from a rotation matrix
* @param matrix - defines the source matrix
* @returns a new quaternion created from the given rotation matrix values
*/
public static FromRotationMatrix(matrix: Matrix): Quaternion {
let result = new Quaternion()
Quaternion.FromRotationMatrixToRef(matrix, result)
return result
}
/**
* Updates the given quaternion with the given rotation matrix values
* @param matrix - defines the source matrix
* @param result - defines the target quaternion
*/
public static FromRotationMatrixToRef(matrix: Matrix, result: Quaternion): void {
let data = matrix.m
// tslint:disable:one-variable-per-declaration
let m11 = data[0],
m12 = data[4],
m13 = data[8]
let m21 = data[1],
m22 = data[5],
m23 = data[9]
let m31 = data[2],
m32 = data[6],
m33 = data[10]
// tslint:enable:one-variable-per-declaration
let trace = m11 + m22 + m33
let s
if (trace > 0) {
s = 0.5 / Math.sqrt(trace + 1.0)
result.w = 0.25 / s
result.x = (m32 - m23) * s
result.y = (m13 - m31) * s
result.z = (m21 - m12) * s
} else if (m11 > m22 && m11 > m33) {
s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33)
result.w = (m32 - m23) / s
result.x = 0.25 * s
result.y = (m12 + m21) / s
result.z = (m13 + m31) / s
} else if (m22 > m33) {
s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33)
result.w = (m13 - m31) / s
result.x = (m12 + m21) / s
result.y = 0.25 * s
result.z = (m23 + m32) / s
} else {
s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22)
result.w = (m21 - m12) / s
result.x = (m13 + m31) / s
result.y = (m23 + m32) / s
result.z = 0.25 * s
}
}
/**
* Returns the dot product (float) between the quaternions "left" and "right"
* @param left - defines the left operand
* @param right - defines the right operand
* @returns the dot product
*/
public static Dot(left: ReadOnlyQuaternion, right: ReadOnlyQuaternion): number {
return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w
}
/**
* Checks if the two quaternions are close to each other
* @param quat0 - defines the first quaternion to check
* @param quat1 - defines the second quaternion to check
* @returns true if the two quaternions are close to each other
*/
public static AreClose(quat0: ReadOnlyQuaternion, quat1: ReadOnlyQuaternion): boolean {
let dot = Quaternion.Dot(quat0, quat1)
return dot >= 0
}
/**
* Creates an empty quaternion
* @returns a new quaternion set to (0.0, 0.0, 0.0)
*/
public static Zero(): Quaternion {
return new Quaternion(0.0, 0.0, 0.0, 0.0)
}
/**
* Inverse a given quaternion
* @param q - defines the source quaternion
* @returns a new quaternion as the inverted current quaternion
*/
public static Inverse(q: Quaternion): Quaternion {
return new Quaternion(-q.x, -q.y, -q.z, q.w)
}
/**
* Gets a boolean indicating if the given quaternion is identity
* @param quaternion - defines the quaternion to check
* @returns true if the quaternion is identity
*/
public static IsIdentity(quaternion: ReadOnlyQuaternion): boolean {
return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1
}
/**
* Creates a quaternion from a rotation around an axis
* @param axis - defines the axis to use
* @param angle - defines the angle to use (in Euler degrees)
* @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
*/
public static RotationAxis(axis: Vector3, angle: number): Quaternion {
const angleRad = angle * DEG2RAD
return Quaternion.RotationAxisToRef(axis, angleRad, new Quaternion())
}
/**
* Creates a rotation around an axis and stores it into the given quaternion
* @param axis - defines the axis to use
* @param angle - defines the angle to use (in Euler degrees)
* @param result - defines the target quaternion
* @returns the target quaternion
*/
public static RotationAxisToRef(axis: Vector3, angle: number, result: Quaternion): Quaternion {
const angleRad = angle * DEG2RAD
let sin = Math.sin(angleRad / 2)
axis.normalize()
result.w = Math.cos(angleRad / 2)
result.x = axis.x * sin
result.y = axis.y * sin
result.z = axis.z * sin
return result
}
/**
* Creates a new quaternion from data stored into an array
* @param array - defines the data source
* @param offset - defines the offset in the source array where the data starts
* @returns a new quaternion
*/
public static FromArray(array: ArrayLike<number>, offset: number = 0): Quaternion {
return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3])
}
/**
* Creates a new quaternion from a set of euler angles and stores it in the target quaternion
*/
public static FromEulerAnglesRef(x: number, y: number, z: number, result: Quaternion): void {
return Quaternion.RotationYawPitchRollToRef(y * DEG2RAD, x * DEG2RAD, z * DEG2RAD, result)
}
/**
* Creates a new quaternion from the given Euler float angles (y, x, z)
* @param yaw - defines the rotation around Y axis
* @param pitch - defines the rotation around X axis
* @param roll - defines the rotation around Z axis
* @returns the new quaternion
*/
public static RotationYawPitchRoll(yaw: number, pitch: number, roll: number): Quaternion {
let q = new Quaternion()
Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q)
return q
}
/**
* Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
* @param yaw - defines the rotation around Y axis
* @param pitch - defines the rotation around X axis
* @param roll - defines the rotation around Z axis
* @param result - defines the target quaternion
*/
public static RotationYawPitchRollToRef(yaw: number, pitch: number, roll: number, result: Quaternion): void {
// Implemented unity-based calculations from: https://stackoverflow.com/a/56055813
let halfPitch = pitch * 0.5
let halfYaw = yaw * 0.5
let halfRoll = roll * 0.5
const c1 = Math.cos(halfPitch)
const c2 = Math.cos(halfYaw)
const c3 = Math.cos(halfRoll)
const s1 = Math.sin(halfPitch)
const s2 = Math.sin(halfYaw)
const s3 = Math.sin(halfRoll)
result.x = c2 * s1 * c3 + s2 * c1 * s3
result.y = s2 * c1 * c3 - c2 * s1 * s3
result.z = c2 * c1 * s3 - s2 * s1 * c3
result.w = c2 * c1 * c3 + s2 * s1 * s3
}
/**
* Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
* @param alpha - defines the rotation around first axis
* @param beta - defines the rotation around second axis
* @param gamma - defines the rotation around third axis
* @returns the new quaternion
*/
public static RotationAlphaBetaGamma(alpha: number, beta: number, gamma: number): Quaternion {
let result = new Quaternion()
Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result)
return result
}
/**
* Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
* @param alpha - defines the rotation around first axis
* @param beta - defines the rotation around second axis
* @param gamma - defines the rotation around third axis
* @param result - defines the target quaternion
*/
public static RotationAlphaBetaGammaToRef(alpha: number, beta: number, gamma: number, result: Quaternion): void {
// Produces a quaternion from Euler angles in the z-x-z orientation
let halfGammaPlusAlpha = (gamma + alpha) * 0.5
let halfGammaMinusAlpha = (gamma - alpha) * 0.5
let halfBeta = beta * 0.5
result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta)
result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta)
result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta)
result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta)
}
/**
* Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
* @param axis1 - defines the first axis
* @param axis2 - defines the second axis
* @param axis3 - defines the third axis
* @returns the new quaternion
*/
public static RotationQuaternionFromAxis(axis1: Vector3, axis2: Vector3, axis3: Vector3): Quaternion {
let quat = new Quaternion(0.0, 0.0, 0.0, 0.0)
Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat)
return quat
}
/**
* Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
* @param axis1 - defines the first axis
* @param axis2 - defines the second axis
* @param axis3 - defines the third axis
* @param ref - defines the target quaternion
*/
public static RotationQuaternionFromAxisToRef(axis1: Vector3, axis2: Vector3, axis3: Vector3, ref: Quaternion): void {
let rotMat = MathTmp.Matrix[0]
Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat)
Quaternion.FromRotationMatrixToRef(rotMat, ref)
}
/**
* Interpolates between two quaternions
* @param left - defines first quaternion
* @param right - defines second quaternion
* @param amount - defines the gradient to use
* @returns the new interpolated quaternion
*/
public static Slerp(left: ReadOnlyQuaternion, right: ReadOnlyQuaternion, amount: number): Quaternion {
let result = Quaternion.Identity
Quaternion.SlerpToRef(left, right, amount, result)
return result
}
/**
* Interpolates between two quaternions and stores it into a target quaternion
* @param left - defines first quaternion
* @param right - defines second quaternion
* @param amount - defines the gradient to use
* @param result - defines the target quaternion
*/
public static SlerpToRef(
left: ReadOnlyQuaternion,
right: ReadOnlyQuaternion,
amount: number,
result: Quaternion
): void {
let num2
let num3
let num4 = left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w
let flag = false
if (num4 < 0) {
flag = true
num4 = -num4
}
if (num4 > 0.999999) {
num3 = 1 - amount
num2 = flag ? -amount : amount
} else {
let num5 = Math.acos(num4)
let num6 = 1.0 / Math.sin(num5)
num3 = Math.sin((1.0 - amount) * num5) * num6
num2 = flag ? -Math.sin(amount * num5) * num6 : Math.sin(amount * num5) * num6
}
result.x = num3 * left.x + num2 * right.x
result.y = num3 * left.y + num2 * right.y
result.z = num3 * left.z + num2 * right.z
result.w = num3 * left.w + num2 * right.w
}
/**
* Interpolate between two quaternions using Hermite interpolation
* @param value1 - defines first quaternion
* @param tangent1 - defines the incoming tangent
* @param value2 - defines second quaternion
* @param tangent2 - defines the outgoing tangent
* @param amount - defines the target quaternion
* @returns the new interpolated quaternion
*/
public static Hermite(
value1: ReadOnlyQuaternion,
tangent1: ReadOnlyQuaternion,
value2: ReadOnlyQuaternion,
tangent2: ReadOnlyQuaternion,
amount: number
): Quaternion {
let squared = amount * amount
let cubed = amount * squared
let part1 = 2.0 * cubed - 3.0 * squared + 1.0
let part2 = -2.0 * cubed + 3.0 * squared
let part3 = cubed - 2.0 * squared + amount
let part4 = cubed - squared
let x = value1.x * part1 + value2.x * part2 + tangent1.x * part3 + tangent2.x * part4
let y = value1.y * part1 + value2.y * part2 + tangent1.y * part3 + tangent2.y * part4
let z = value1.z * part1 + value2.z * part2 + tangent1.z * part3 + tangent2.z * part4
let w = value1.w * part1 + value2.w * part2 + tangent1.w * part3 + tangent2.w * part4
return new Quaternion(x, y, z, w)
}
/**
* Creates an identity quaternion
* @returns - the identity quaternion
*/
public static get Identity(): Quaternion {
return new Quaternion(0.0, 0.0, 0.0, 1.0)
}
/**
* Returns the angle in degrees between two rotations a and b.
* @param quat1 - defines the first quaternion
* @param quat2 - defines the second quaternion
*/
public static Angle(quat1: ReadOnlyQuaternion, quat2: ReadOnlyQuaternion): number {
const dot = Quaternion.Dot(quat1, quat2)
return Math.acos(Math.min(Math.abs(dot), 1)) * 2 * RAD2DEG
}
/**
* Returns a rotation that rotates z degrees around the z axis, x degrees around the x axis, and y degrees around the y axis.
* @param x - the rotation on the x axis in euler degrees
* @param y - the rotation on the y axis in euler degrees
* @param z - the rotation on the z axis in euler degrees
*/
public static Euler(x: number, y: number, z: number): Quaternion {
return Quaternion.RotationYawPitchRoll(y * DEG2RAD, x * DEG2RAD, z * DEG2RAD)
}
/**
* Creates a rotation with the specified forward and upwards directions.
* @param forward - the direction to look in
* @param up - the vector that defines in which direction up is
*/
public static LookRotation(forward: Vector3, up: Vector3 = MathTmp.staticUp): Quaternion {
const forwardNew = Vector3.Normalize(forward)
const right: Vector3 = Vector3.Normalize(Vector3.Cross(up, forwardNew))
const upNew = Vector3.Cross(forwardNew, right)
let m00 = right.x
let m01 = right.y
let m02 = right.z
let m10 = upNew.x
let m11 = upNew.y
let m12 = upNew.z
let m20 = forwardNew.x
let m21 = forwardNew.y
let m22 = forwardNew.z
const num8 = m00 + m11 + m22
let quaternion = new Quaternion()
if (num8 > 0) {
let num = Math.sqrt(num8 + 1)
quaternion.w = num * 0.5
num = 0.5 / num
quaternion.x = (m12 - m21) * num
quaternion.y = (m20 - m02) * num
quaternion.z = (m01 - m10) * num
return quaternion
}
if (m00 >= m11 && m00 >= m22) {
let num7 = Math.sqrt(1 + m00 - m11 - m22)
let num4 = 0.5 / num7
quaternion.x = 0.5 * num7
quaternion.y = (m01 + m10) * num4
quaternion.z = (m02 + m20) * num4
quaternion.w = (m12 - m21) * num4
return quaternion
}
if (m11 > m22) {
let num6 = Math.sqrt(1 + m11 - m00 - m22)
let num3 = 0.5 / num6
quaternion.x = (m10 + m01) * num3
quaternion.y = 0.5 * num6
quaternion.z = (m21 + m12) * num3
quaternion.w = (m20 - m02) * num3
return quaternion
}
let num5 = Math.sqrt(1 + m22 - m00 - m11)
let num2 = 0.5 / num5
quaternion.x = (m20 + m02) * num2
quaternion.y = (m21 + m12) * num2
quaternion.z = 0.5 * num5
quaternion.w = (m01 - m10) * num2
return quaternion
}
/**
* The from quaternion is rotated towards to by an angular step of maxDegreesDelta.
* @param from - defines the first quaternion
* @param to - defines the second quaternion
* @param maxDegreesDelta - the interval step
*/
public static RotateTowards(from: ReadOnlyQuaternion, to: Quaternion, maxDegreesDelta: number): Quaternion {
const num: number = Quaternion.Angle(from, to)
if (num === 0) {
return to
}
const t: number = Math.min(1, maxDegreesDelta / num)
return Quaternion.Slerp(from, to, t)
}
/**
* Creates a rotation which rotates from fromDirection to toDirection.
* @param from - defines the first direction Vector
* @param to - defines the target direction Vector
*/
public static FromToRotation(from: Vector3, to: Vector3, up: Vector3 = MathTmp.staticUp): Quaternion {
// Unity-based calculations implemented from https://forum.unity.com/threads/quaternion-lookrotation-around-an-axis.608470/#post-4069888
let v0 = from.normalize()
let v1 = to.normalize()
const a = Vector3.Cross(v0, v1)
const w = Math.sqrt(v0.lengthSquared() * v1.lengthSquared()) + Vector3.Dot(v0, v1)
if (a.lengthSquared() < 0.0001) {
// the vectors are parallel, check w to find direction
// if w is 0 then values are opposite, and we sould rotate 180 degrees around the supplied axis
// otherwise the vectors in the same direction and no rotation should occur
return (Math.abs(w) < 0.0001) ? new Quaternion(up.x, up.y, up.z, 0).normalized : Quaternion.Identity
} else {
return new Quaternion(a.x, a.y, a.z, w).normalized
}
}
/**
* Converts this quaternion to one with the same orientation but with a magnitude of 1.
*/
public get normalized() {
return this.normalize()
}
/**
* Creates a rotation which rotates from fromDirection to toDirection.
* @param from - defines the first Vector
* @param to - defines the second Vector
* @param up - defines the direction
*/
public setFromToRotation(from: Vector3, to: Vector3, up: Vector3 = MathTmp.staticUp) {
const result = Quaternion.FromToRotation(from, to, up)
this.x = result.x
this.y = result.y
this.z = result.z
this.w = result.w
}
/**
* Sets the euler angle representation of the rotation.
*/
public set eulerAngles(euler: Vector3) {
this.setEuler(euler.x, euler.y, euler.z)
}
/**
* Gets the euler angle representation of the rotation.
* Implemented unity-based calculations from: https://stackoverflow.com/a/56055813
*/
public get eulerAngles() {
const out = new Vector3()
// if the input quaternion is normalized, this is exactly one. Otherwise, this acts as a correction factor for the quaternion's not-normalizedness
const unit = (this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w)
// this will have a magnitude of 0.5 or greater if and only if this is a singularity case
const test = this.x * this.w - this.y * this.z
if (test > 0.4995 * unit) { // singularity at north pole
out.x = Math.PI / 2
out.y = 2 * Math.atan2(this.y, this.x)
out.z = 0
} else if (test < -0.4995 * unit) { // singularity at south pole
out.x = -Math.PI / 2
out.y = -2 * Math.atan2(this.y, this.x)
out.z = 0
} else { // no singularity - this is the majority of cases
out.x = Math.asin(2 * (this.w * this.x - this.y * this.z))
out.y = Math.atan2(2 * this.w * this.y + 2 * this.z * this.x, 1 - 2 * (this.x * this.x + this.y * this.y))
out.z = Math.atan2(2 * this.w * this.z + 2 * this.x * this.y, 1 - 2 * (this.z * this.z + this.x * this.x))
}
out.x *= RAD2DEG
out.y *= RAD2DEG
out.z *= RAD2DEG
// ensure the degree values are between 0 and 360
out.x = Scalar.Repeat(out.x, 360)
out.y = Scalar.Repeat(out.y, 360)
out.z = Scalar.Repeat(out.z, 360)
return out
}
/**
* Gets a string representation for the current quaternion
* @returns a string with the Quaternion coordinates
*/
public toString(): string {
return `(${this.x}, ${this.y}, ${this.z}, ${this.w})`
}
/**
* Gets length of current quaternion
* @returns the quaternion length (float)
*/
public get length(): number {
return Math.sqrt(this.lengthSquared)
}
/**
* Gets length of current quaternion
* @returns the quaternion length (float)
*/
public get lengthSquared(): number {
return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w
}
/**
* Gets the class name of the quaternion
* @returns the string "Quaternion"
*/
public getClassName(): string {
return 'Quaternion'
}
/**
* Gets a hash code for this quaternion
* @returns the quaternion hash code
*/
public getHashCode(): number {
let hash = this.x || 0
hash = (hash * 397) ^ (this.y || 0)
hash = (hash * 397) ^ (this.z || 0)
hash = (hash * 397) ^ (this.w || 0)
return hash
}
/**
* Copy the quaternion to an array
* @returns a new array populated with 4 elements from the quaternion coordinates
*/
public asArray(): number[] {
return [this.x, this.y, this.z, this.w]
}
/**
* Check if two quaternions are equals
* @param otherQuaternion - defines the second operand
* @returns true if the current quaternion and the given one coordinates are strictly equals
*/
public equals(otherQuaternion: ReadOnlyQuaternion): boolean {
return (
otherQuaternion &&
this.x === otherQuaternion.x &&
this.y === otherQuaternion.y &&
this.z === otherQuaternion.z &&
this.w === otherQuaternion.w
)
}
/**
* Clone the current quaternion
* @returns a new quaternion copied from the current one
*/
public clone(): Quaternion {
return new Quaternion(this.x, this.y, this.z, this.w)
}
/**
* Copy a quaternion to the current one
* @param other - defines the other quaternion
* @returns the updated current quaternion
*/
public copyFrom(other: ReadOnlyQuaternion): Quaternion {
this.x = other.x
this.y = other.y
this.z = other.z
this.w = other.w
return this
}
/**
* Updates the current quaternion with the given float coordinates
* @param x - defines the x coordinate
* @param y - defines the y coordinate
* @param z - defines the z coordinate
* @param w - defines the w coordinate
* @returns the updated current quaternion
*/
public copyFromFloats(x: number, y: number, z: number, w: number): Quaternion {
this.x = x
this.y = y
this.z = z
this.w = w
return this
}
/**
* Updates the current quaternion from the given float coordinates
* @param x - defines the x coordinate
* @param y - defines the y coordinate
* @param z - defines the z coordinate
* @param w - defines the w coordinate
* @returns the updated current quaternion
*/
public set(x: number, y: number, z: number, w: number): Quaternion {
return this.copyFromFloats(x, y, z, w)
}
/**
* Updates the current quaternion from the given euler angles
* @returns the updated current quaternion
*/
public setEuler(x: number, y: number, z: number): Quaternion {
Quaternion.RotationYawPitchRollToRef(y * DEG2RAD, x * DEG2RAD, z * DEG2RAD, this)
return this
}
/**
* @internal
* Adds two quaternions
* @param other - defines the second operand
* @returns a new quaternion as the addition result of the given one and the current quaternion
*/
public add(other: Quaternion): Quaternion {
return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w)
}
/**
* @internal
* Add a quaternion to the current one
* @param other - defines the quaternion to add
* @returns the current quaternion
*/
public addInPlace(other: Quaternion): Quaternion {
this.x += other.x
this.y += other.y
this.z += other.z
this.w += other.w
return this
}
/**
* Subtract two quaternions
* @param other - defines the second operand
* @returns a new quaternion as the subtraction result of the given one from the current one
*/
public subtract(other: Quaternion): Quaternion {
return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w)
}
/**
* Multiplies the current quaternion by a scale factor
* @param value - defines the scale factor
* @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
*/
public scale(value: number): Quaternion {
return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value)
}
/**
* Scale the current quaternion values by a factor and stores the result to a given quaternion
* @param scale - defines the scale factor
* @param result - defines the Quaternion object where to store the result
* @returns the unmodified current quaternion
*/
public scaleToRef(scale: number, result: Quaternion): Quaternion {
result.x = this.x * scale
result.y = this.y * scale
result.z = this.z * scale
result.w = this.w * scale
return this
}
/**
* Multiplies in place the current quaternion by a scale factor
* @param value - defines the scale factor
* @returns the current modified quaternion
*/
public scaleInPlace(value: number): Quaternion {
this.x *= value
this.y *= value
this.z *= value
this.w *= value
return this
}
/**
* Scale the current quaternion values by a factor and add the result to a given quaternion
* @param scale - defines the scale factor
* @param result - defines the Quaternion object where to store the result
* @returns the unmodified current quaternion
*/
public scaleAndAddToRef(scale: number, result: Quaternion): Quaternion {
result.x += this.x * scale
result.y += this.y * scale
result.z += this.z * scale
result.w += this.w * scale
return this
}
/**
* Multiplies two quaternions
* @param q1 - defines the second operand
* @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
*/
public multiply(q1: ReadOnlyQuaternion): Quaternion {
let result = new Quaternion(0, 0, 0, 1.0)
this.multiplyToRef(q1, result)
return result
}
/**
* Sets the given "result" as the the multiplication result of the current one with the given one "q1"
* @param q1 - defines the second operand
* @param result - defines the target quaternion
* @returns the current quaternion
*/
public multiplyToRef(q1: ReadOnlyQuaternion, result: Quaternion): Quaternion {
let x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x
let y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y
let z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z
let w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w
result.copyFromFloats(x, y, z, w)
return this
}
/**
* Updates the current quaternion with the multiplication of itself with the given one "q1"
* @param q1 - defines the second operand
* @returns the currentupdated quaternion
*/
public multiplyInPlace(q1: ReadOnlyQuaternion): Quaternion {
this.multiplyToRef(q1, this)
return this
}
/**
* Conjugates (1-q) the current quaternion and stores the result in the given quaternion
* @param ref - defines the target quaternion
* @returns the current quaternion
*/
public conjugateToRef(ref: Quaternion): Quaternion {
ref.copyFromFloats(-this.x, -this.y, -this.z, this.w)
return this
}
/**
* Conjugates in place (1-q) the current quaternion
* @returns the current updated quaternion
*/
public conjugateInPlace(): Quaternion {
this.x *= -1
this.y *= -1
this.z *= -1
return this
}
/**
* Conjugates in place (1-q) the current quaternion
* @returns a new quaternion
*/
public conjugate(): Quaternion {
let result = new Quaternion(-this.x, -this.y, -this.z, this.w)
return result
}
/**
* Normalize in place the current quaternion
* @returns the current updated quaternion
*/
public normalize(): Quaternion {
let length = 1.0 / this.length
this.x *= length
this.y *= length
this.z *= length
this.w *= length
return this
}
public angleAxis(degress: number, axis: Vector3) {
if (axis.lengthSquared() === 0) {
return Quaternion.Identity
}
const result: Quaternion = Quaternion.Identity
let radians = degress * DEG2RAD
radians *= 0.5
let a2 = axis.normalize()
a2 = axis.scaleInPlace(Math.sin(radians))
result.x = a2.x
result.y = a2.y
result.z = a2.z
result.w = Math.cos(radians)
return result.normalize()
}
/**
* Updates the given rotation matrix with the current quaternion values
* @param result - defines the target matrix
* @returns the current unchanged quaternion
*/
public toRotationMatrix(result: Matrix): Quaternion {
Matrix.FromQuaternionToRef(this, result)
return this
}
/**
* Updates the current quaternion from the given rotation matrix values
* @param matrix - defines the source matrix
* @returns the current updated quaternion
*/
public fromRotationMatrix(matrix: Matrix): Quaternion {
Quaternion.FromRotationMatrixToRef(matrix, this)
return this
}
} | the_stack |
import { makeAutoObservable, runInAction, toJS, values } from 'mobx';
import { SwapResponse } from 'types/generated/loop_pb';
import { BuildSwapSteps, Quote, SwapDirection, SwapTerms } from 'types/state';
import Big from 'big.js';
import { percentage } from 'util/bigmath';
import { BalanceMode } from 'util/constants';
import { formatSats } from 'util/formatters';
import { prefixTranslation } from 'util/translate';
import { Store } from 'store';
import Channel from 'store/models/channel';
const { l } = prefixTranslation('stores.buildSwapView');
// an artificial delay to allow the user to abort a swap before it executed
export const SWAP_ABORT_DELAY = 3000;
/**
* The store to manage the state of a Loop swap being created
*/
class BuildSwapView {
_store: Store;
// the increments between swap amounts that may be chosen by the user
AMOUNT_INCREMENT = 10000;
/** determines whether to show the swap wizard */
currentStep = BuildSwapSteps.Closed;
/** the chosen direction for the loop */
direction: SwapDirection = SwapDirection.IN;
/** the channels selected */
selectedChanIds: string[] = [];
/** the amount to swap */
amount: Big = Big(0);
/** determines whether to show the swap advanced options */
addlOptionsVisible = false;
/** the confirmation target of the on-chain txn used in the swap */
confTarget?: number;
/** the on-chain address to send funds to during a loop out swap */
loopOutAddress?: string;
/** the min/max amount this node is allowed to swap */
terms: SwapTerms = {
in: { min: Big(0), max: Big(0) },
out: { min: Big(0), max: Big(0) },
};
/** the quote for the swap */
quote: Quote = {
swapFee: Big(0),
prepayAmount: Big(0),
minerFee: Big(0),
};
/** the reference to the timeout used to allow cancelling a swap */
processingTimeout?: NodeJS.Timeout;
constructor(store: Store) {
makeAutoObservable(this, {}, { deep: false, autoBind: true });
this._store = store;
}
//
// Computed properties
//
/** returns the list of all channels. filters out inactive channels when performing a swap */
get channels() {
const { channelStore } = this._store;
return this.currentStep === BuildSwapSteps.Closed
? channelStore.sortedChannels
: channelStore.activeChannels;
}
/** determines whether to show the options for Loop In or Loop Out */
get showActions(): boolean {
return this.currentStep === BuildSwapSteps.SelectDirection;
}
/** determines whether to show the swap wizard UI */
get showWizard(): boolean {
return [
BuildSwapSteps.ChooseAmount,
BuildSwapSteps.ReviewQuote,
BuildSwapSteps.Processing,
].includes(this.currentStep);
}
/** determines if the channel list should be editable */
get listEditable(): boolean {
return this.currentStep !== BuildSwapSteps.Closed;
}
/** the min/max amounts this node is allowed to swap based on the current direction */
get termsForDirection() {
return this.getTermsForDirection(this.direction);
}
/** returns the stored amount but ensures it is between the terms min & max */
get amountForSelected() {
const { min, max } = this.termsForDirection;
if (this.amount.eq(0)) {
return min.plus(max).div(2).round(0);
}
if (this.amount.lt(min)) {
return min;
}
if (this.amount.gt(max)) {
return max;
}
return this.amount;
}
/** the total quoted fee to perform the current swap */
get fee() {
return this.quote.swapFee.plus(this.quote.minerFee);
}
/** a string containing the fee as an absolute value and a percentage */
get feesLabel() {
const feesPct = percentage(this.fee, this.amount, 2);
const amount = formatSats(this.fee, { unit: this._store.settingsStore.unit });
return `${amount} (${feesPct}%)`;
}
/** the invoice total including the swap amount and fee */
get invoiceTotal() {
return this.amount.plus(this.fee);
}
/** infer a swap direction based on the selected channels */
get inferredDirection(): SwapDirection | undefined {
const mode = this._store.settingsStore.balanceMode;
switch (mode) {
case BalanceMode.routing:
// unable to infer a direction with no selection
if (this.selectedChanIds.length === 0) return undefined;
// calculate the average local balance percent
const percents = values(this._store.channelStore.channels)
.filter(c => this.selectedChanIds.includes(c.chanId))
.map(c => c.localPercent);
const sum = percents.reduce((s, p) => s + p, 0);
const avgPct = sum / percents.length;
// if the average is low, suggest Loop In. Otherwise, suggest Loop Out
return avgPct < 50 ? SwapDirection.IN : SwapDirection.OUT;
case BalanceMode.send:
// always infer Loop In when using Sending mode
return SwapDirection.IN;
case BalanceMode.receive:
default:
// always suggest Loop Out when using Receiving mode
return SwapDirection.OUT;
}
}
/**
* determines if the selected channels all use the same peer. also
* return true if no channels are selected
*/
get hasValidLoopInPeers() {
if (this.selectedChanIds.length > 0) {
return this.loopInLastHop !== undefined;
}
return true;
}
/**
* determines if the balance of selected (or all) channels are
* greater than the minimum swap allowed
*/
get isLoopInMinimumMet() {
const { min, max } = this.getTermsForDirection(SwapDirection.IN);
if (!max.gte(min)) return false;
if (this.selectedChanIds.length > 0) {
return this.loopInLastHop !== undefined;
}
return true;
}
/**
* determines if Loop Out is allowed. the balance of selected (or all)
* channels must be greater than the minimum swap allowed
*/
get isLoopOutMinimumMet() {
const { min, max } = this.getTermsForDirection(SwapDirection.OUT);
if (!max.gte(min)) return false;
return true;
}
/**
* Returns the unique peer pubkey of the selected channels. If no channels
* are selected OR the selected channels are using more than one peer, then
* undefined is returned
*/
get loopInLastHop(): string | undefined {
const channels = this.selectedChanIds
.map(id => this._store.channelStore.channels.get(id))
.filter(c => !!c) as Channel[];
const peers = channels.reduce((peers, c) => {
if (!peers.includes(c.remotePubkey)) {
peers.push(c.remotePubkey);
}
return peers;
}, [] as string[]);
return peers.length === 1 ? peers[0] : undefined;
}
//
// Actions
//
/**
* display the Loop actions bar
*/
async startSwap(): Promise<void> {
if (this._store.channelStore.activeChannels.length === 0) {
this._store.appView.notify(l('noChannelsMsg'));
return;
}
this._store.appView.tourGoToNext();
this.currentStep = BuildSwapSteps.SelectDirection;
await this.getTerms();
this._store.log.info(`updated buildSwapView.currentStep`, this.currentStep);
}
/**
* Set the direction, In or Out, for the pending swap
* @param direction the direction of the swap
*/
async setDirection(direction: SwapDirection): Promise<void> {
this.direction = direction;
this._store.log.info(`updated buildSwapView.direction`, direction);
if (this.direction === SwapDirection.IN) {
// select all channels to the selected peer for Loop In
this.autoSelectPeerChannels();
}
this.goToNextStep();
}
/**
* Toggles a selected channel to use for the pending swap
* @param channels the selected channels
*/
toggleSelectedChannel(channelId: string) {
if (this.selectedChanIds.includes(channelId)) {
this.selectedChanIds = this.selectedChanIds.filter(id => id !== channelId);
} else {
this.selectedChanIds = [...this.selectedChanIds, channelId];
}
this._store.log.info(
`updated buildSwapView.selectedChanIds`,
toJS(this.selectedChanIds),
);
}
/**
* When performing a Loop In, you can only specify the last hop of the payment,
* so all channels with the selected peer may be used. This function will ensure
* that all channels of the selected peer are selected
*/
autoSelectPeerChannels() {
// create an array of pubkeys for the selected channels
const peers = this.channels
.filter(c => this.selectedChanIds.includes(c.chanId))
.map(c => c.remotePubkey)
.filter((c, i, a) => a.indexOf(c) === i); // filter out duplicates
// create a list of all channels with this peer
const peerChannels = this.channels
.filter(c => peers.includes(c.remotePubkey))
.map(c => c.chanId);
this.selectedChanIds = peerChannels;
this._store.log.info(`automatically selected peer channels`, this.selectedChanIds);
}
/**
* Set the amount for the swap
* @param amount the amount in sats
*/
setAmount(amount: Big) {
this.amount = amount;
}
/**
* toggles the advanced options section in the swap config step
*/
toggleAddlOptions() {
this.addlOptionsVisible = !this.addlOptionsVisible;
this._store.log.info(
`updated buildSwapView.addlOptionsVisible`,
this.addlOptionsVisible,
);
}
/**
* Set the confirmation target for the swap
*/
setConfTarget(target?: number) {
// ensure the Loop Out target is between the CLTV min & max
if (
this.direction === SwapDirection.OUT &&
this.terms.out.minCltv &&
this.terms.out.maxCltv &&
target !== undefined &&
(isNaN(target) ||
this.terms.out.minCltv > target ||
this.terms.out.maxCltv < target)
) {
throw new Error(
`Confirmation target must be between ${this.terms.out.minCltv} and ${this.terms.out.maxCltv}.`,
);
}
this.confTarget = target;
this._store.log.info(`updated buildSwapView.confTarget`, this.confTarget);
}
/**
* Set the on-chain destination address for the loop out swap
*/
setLoopOutAddress(address: string) {
this.loopOutAddress = address;
this._store.log.info(`updated buildSwapView.loopOutAddress`, this.loopOutAddress);
}
/**
* Navigate to the next step in the wizard
*/
goToNextStep() {
if (this.currentStep === BuildSwapSteps.ChooseAmount) {
this.amount = this.amountForSelected;
this.getQuote();
// clear the advanced options if values were set, then hidden
if (!this.addlOptionsVisible) {
this.confTarget = undefined;
this.loopOutAddress = undefined;
}
} else if (this.currentStep === BuildSwapSteps.ReviewQuote) {
this.requestSwap();
}
this.currentStep++;
this._store.log.info(`updated buildSwapView.currentStep`, this.currentStep);
this._store.appView.tourGoToNext();
}
/**
* Navigate to the previous step in the wizard
*/
goToPrevStep() {
if (this.currentStep === BuildSwapSteps.Processing) {
// if back is clicked on the processing step
this.abortSwap();
}
this.currentStep--;
this._store.log.info(`updated buildSwapView.currentStep`, this.currentStep);
}
/**
* hide the swap wizard
*/
cancel() {
this.currentStep = BuildSwapSteps.Closed;
this.selectedChanIds = [];
this.amount = Big(0);
this.addlOptionsVisible = false;
this.confTarget = undefined;
this.loopOutAddress = undefined;
this.quote.swapFee = Big(0);
this.quote.minerFee = Big(0);
this.quote.prepayAmount = Big(0);
this._store.log.info(`reset buildSwapView`, toJS(this));
}
/**
* fetch the terms, minimum/maximum swap amount allowed, from the Loop API
*/
async getTerms(): Promise<void> {
this._store.log.info(`fetching loop terms`);
try {
const inTerms = await this._store.api.loop.getLoopInTerms();
const outTerms = await this._store.api.loop.getLoopOutTerms();
runInAction(() => {
this.terms = {
in: {
min: Big(inTerms.minSwapAmount),
max: Big(inTerms.maxSwapAmount),
},
out: {
min: Big(outTerms.minSwapAmount),
max: Big(outTerms.maxSwapAmount),
minCltv: outTerms.minCltvDelta,
maxCltv: outTerms.maxCltvDelta,
},
};
this._store.log.info('updated store.terms', toJS(this.terms));
});
} catch (error) {
this._store.appView.handleError(error, 'Unable to fetch Loop Terms');
this.goToPrevStep();
}
}
/**
* get a loop quote from the Loop RPC
*/
async getQuote(): Promise<void> {
const { amount, direction } = this;
this._store.log.info(`fetching ${direction} quote for ${amount} sats`);
try {
let quote: Quote;
if (direction === SwapDirection.IN) {
const inQuote = await this._store.api.loop.getLoopInQuote(
amount,
this.confTarget,
);
quote = {
swapFee: Big(inQuote.swapFeeSat),
minerFee: Big(inQuote.htlcPublishFeeSat),
prepayAmount: Big(0),
};
} else {
const outQuote = await this._store.api.loop.getLoopOutQuote(
amount,
this.confTarget,
);
quote = {
swapFee: Big(outQuote.swapFeeSat),
minerFee: Big(outQuote.htlcSweepFeeSat),
prepayAmount: Big(outQuote.prepayAmtSat),
};
}
runInAction(() => {
this.quote = quote;
this._store.log.info('updated buildSwapView.quote', toJS(this.quote));
});
} catch (error) {
this._store.appView.handleError(error, 'Unable to fetch Quote');
this.goToPrevStep();
}
}
/**
* submit a request to the Loop API to perform a swap. There will be a 3 second
* delay added to allow the swap to be aborted
*/
requestSwap() {
const delay =
process.env.NODE_ENV === 'test'
? 1 // use a 1 ms delay for unit tests
: this._store.appView.tourVisible
? 1500 // use a 1.5 second delay during the tour
: SWAP_ABORT_DELAY;
const { amount, direction, quote } = this;
this._store.log.info(
`executing ${direction} for ${amount} sats (delaying for ${delay}ms)`,
);
this.processingTimeout = setTimeout(async () => {
try {
let res: SwapResponse.AsObject;
if (direction === SwapDirection.IN) {
res = await this._store.api.loop.loopIn(
amount,
quote,
this.loopInLastHop,
this.confTarget,
);
// save the channels that were used in the swap. for Loop In all channels
// with the same peer will be used
this._store.swapStore.addSwappedChannels(res.id, this.selectedChanIds);
} else {
// on regtest, set the publication deadline to 0 for faster swaps, otherwise
// set it to 30 minutes in the future to reduce swap fees
const thirtyMins = 30 * 60 * 1000;
const deadline =
this._store.nodeStore.network === 'regtest' ? 0 : Date.now() + thirtyMins;
// convert the selected channel ids to numbers
res = await this._store.api.loop.loopOut(
amount,
quote,
this.selectedChanIds,
deadline,
this.confTarget,
this.loopOutAddress,
);
// save the channels that were used in the swap
this._store.swapStore.addSwappedChannels(res.id, this.selectedChanIds);
}
this._store.log.info('completed loop', toJS(res));
runInAction(() => {
// hide the swap UI after it is complete
this.cancel();
this._store.appView.toggleProcessingSwaps();
this._store.appView.tourGoToNext();
});
} catch (error) {
this._store.appView.handleError(error, `Unable to Perform ${direction}`);
this.goToPrevStep();
}
}, delay);
}
/**
* abort a swap that has been submitted
*/
abortSwap() {
if (this.processingTimeout) {
clearTimeout(this.processingTimeout);
this.processingTimeout = undefined;
}
}
/**
* Returns the swap terms after adjusting the max based on channel balances
* @param direction the swap direction
*/
getTermsForDirection(direction: SwapDirection) {
const selectors = {
[SwapDirection.IN]: {
directionTerms: { ...this.terms.in },
balanceSelector: (channel: Channel) => channel.remoteBalance,
totalBalance: this._store.channelStore.totalInbound,
},
[SwapDirection.OUT]: {
directionTerms: { ...this.terms.out },
balanceSelector: (channel: Channel) => channel.localBalance,
totalBalance: this._store.channelStore.totalOutbound,
},
};
const { directionTerms, balanceSelector, totalBalance } = selectors[direction];
// set the terms based on the chosen direction
const terms = directionTerms;
// get the total balance of the selected or all channels
let total = this.selectedChanIds.length
? this.channels
.filter(c => this.selectedChanIds.includes(c.chanId))
.map(balanceSelector)
.reduce((sum, bal) => sum.plus(bal), Big(0))
: totalBalance;
// subtract the 1% reserve balance that cannot be spent
total = total.mul(0.99);
// decrease the max amount if it is lower than the server terms
if (terms.max.gt(total)) {
terms.max = total.div(this.AMOUNT_INCREMENT).round(0, 0).mul(this.AMOUNT_INCREMENT);
}
return terms;
}
}
export default BuildSwapView; | the_stack |
import * as assert from 'power-assert';
import {dtsmake} from '../src/dtsmake';
import fs = require('fs');
describe("Parsing TernJS definition JSON file(s), ",()=>{
let dg = new dtsmake.DTSMake();
context("parseToDTS()", ()=>{
it.skip("should parse !type type to DTS",()=>{
let baseDef = {
"Fn": {
"!type": "fn(name: string, self: +tern.AVal, args: [?], argNames: [string], retval: ?)",
"name": "string",
"test": "?"
}
};
let parsedJson = dg.parseJsonNodeDTS(baseDef);
let out = dg.parseToDTS(parsedJson);
const answer3 = `"Fn":{"new ":{}}`;
assert.deepEqual(
out,answer3,
`out string ${out} is not match answer str ${answer3}.`
);
});
});
context("replaceExportNamespace()",()=>{
it("should replace module name when isOutExport ON",()=>{
const def = {
[dtsmake.TernDef.NAME]:"TEST_NAME",
[dtsmake.TernDef.DEFINE]:{
[dtsmake.TernDef.NODE]:{
"node_modules/path/to/module`js":{
"prop":{
type:dtsmake.TSObjType.BOOLEAN
}
}
}
}
};
dg.option.isOutExport = true;
dg.nodeModuleName = "node_modules/path/to/module`js";
dg.userDefinedModuleName = "TEST_NAME";
let out = dg.replaceExportNamespace(def);
//console.log(JSON.stringify(out))
let answer = {
[dtsmake.TernDef.NAME]:"TEST_NAME",
[dtsmake.TernDef.DEFINE]:{
[dtsmake.TernDef.NODE]:{
[dg.userDefinedModuleName]:{
"prop":{
type:dtsmake.TSObjType.BOOLEAN
}
}
}
}
};
assert.deepEqual(out, answer);
});
});
context("parseJsonNodeDTS()",()=>{
it("should be output !type param array type",()=>{
const def = {
"Fn":{
"!type": "fn(sParams: [string], nParams: [number])"
}
};
let out = dg.parseJsonNodeDTS(def);
let answer = {
"Fn":{
"!type":[
{"type":dtsmake.TSObjType.FUNCTION,
"params":[
{
"type":dtsmake.TSObjType.ARRAY,
"arrayType": [
{"type":dtsmake.TSObjType.STRING}
],
"name":"sParams"
},
{
"type":dtsmake.TSObjType.ARRAY,
"arrayType": [
{"type":dtsmake.TSObjType.NUMBER}
],
"name":"nParams"
}
],
"ret":[
{
"type":dtsmake.TSObjType.VOID
}
]
}
]
}
}
assert.deepEqual(
out,answer,
`out ${JSON.stringify(out)}\n, answer ${JSON.stringify(answer)}`
)
});
it.skip("should be output !proto collectly",()=>{
const def = {
"Fn":{
"!type":"fn()",
"prototype":{
"!proto": "tern.Obj.prototype"
}
}
};
const out = dg.parseJsonNodeDTS(def);
const answer = {
"Fn":{}
};
assert.deepEqual(
out, answer
);
});
})
context("parseTernDef()",()=>{
it("should parse simple array",()=>{
const def = "[string]";
const answer = [
{
"type":dtsmake.TSObjType.ARRAY,
//"name":"test",
"arrayType": [
{"type":dtsmake.TSObjType.STRING}
]
}
];
let out = dg.parseTernDef(def);
assert.deepEqual(
out, answer,
`out ${JSON.stringify(out)},\n`+
`ans ${JSON.stringify(answer)}`
);
});
it("should parse single array param fn",()=>{
const def = "fn(p1: [string])";
const answer =
[
{
"type":dtsmake.TSObjType.FUNCTION,
"ret":[
{
"type":dtsmake.TSObjType.VOID
}
],
"params":[
{
"type":dtsmake.TSObjType.ARRAY,
"name":"p1",
"arrayType": [
{"type":dtsmake.TSObjType.STRING}
]
}
]
}
];
let out = dg.parseTernDef(def);
assert.deepEqual(
out, answer,
`out ${JSON.stringify(out)},\n`+
`ans ${JSON.stringify(answer)}`
);
});
it("should parse optional param fn",()=>{
const def = "fn(p1?: [string])";
const answer =
[
{
"type":dtsmake.TSObjType.FUNCTION,
"ret":[
{
"type":dtsmake.TSObjType.VOID
}
],
"params":[
{
"type":dtsmake.TSObjType.ARRAY,
"name":"p1?",
"arrayType": [
{"type":dtsmake.TSObjType.STRING}
]
}
]
}
];
let out = dg.parseTernDef(def);
assert.deepEqual(
out, answer,
`out ${JSON.stringify(out)},\n`+
`ans ${JSON.stringify(answer)}`
);
});
it("should parse double array params fn",()=>{
const def = "fn(sParams: [string], nParams: [number])";
const answer = [
{"type":dtsmake.TSObjType.FUNCTION,
"ret":[
{
"type":dtsmake.TSObjType.VOID
}
],
"params":[
{
"type":dtsmake.TSObjType.ARRAY,
"arrayType": [
{"type":dtsmake.TSObjType.STRING}
],
"name":"sParams"
},
{
"type":dtsmake.TSObjType.ARRAY,
"arrayType": [
{"type":dtsmake.TSObjType.NUMBER}
],
"name":"nParams"
}
]
}
];
let out = dg.parseTernDef(def);
assert.deepEqual(out,answer, `\ndef out ${JSON.stringify(out)},\nanswer ${JSON.stringify(answer)}`);
});
//it("should parse ")
it("should parse union params fn",()=>{
const def = "fn(a: string|number)";
const answer = [
{"type":dtsmake.TSObjType.FUNCTION,
"ret":[
{
"type":dtsmake.TSObjType.VOID
}
],
"params":[
[
{
"name":"a",
"type":dtsmake.TSObjType.STRING
},
{
"name":"a",
"type":dtsmake.TSObjType.NUMBER
}
]
]
}
];
let out = dg.parseTernDef(def);
assert.deepEqual(out, answer);
});
it("should parse fn union params fn",()=>{
const def = "fn(a: fn(string)|fn(number))";
const answer = [
{"type":dtsmake.TSObjType.FUNCTION,
"ret":[
{
"type":dtsmake.TSObjType.VOID
}
],
"params":[
[
{
"name":"a",
"params":[{
"type":dtsmake.TSObjType.STRING
}],
"type":dtsmake.TSObjType.FUNCTION,
"ret":[{
"type":dtsmake.TSObjType.VOID
}]
},
{
"name":"a",
"params":[{
"type":dtsmake.TSObjType.NUMBER
}],
"type":dtsmake.TSObjType.FUNCTION,
"ret":[{
"type":dtsmake.TSObjType.VOID
}]
}
]
]
}
];
let out = dg.parseTernDef(def);
assert.deepEqual(out, answer);
});
});
context("parseParams()",()=>{
it("should parse fn params array",()=>{
const def = "fn(sParams:[string],nParams:[number])";
const answer =
[
{
"type":dtsmake.TSObjType.ARRAY,
"arrayType": [
{"type":dtsmake.TSObjType.STRING}
],
"name":"sParams"
},
{
"type":dtsmake.TSObjType.ARRAY,
"arrayType": [
{"type":dtsmake.TSObjType.NUMBER}
],
"name":"nParams"
}
];
let out = dg.parseParams(def);
assert.deepEqual(out,answer, `\ndef out ${JSON.stringify(out)},\nanswer ${JSON.stringify(answer)}`);
});
it("should parse fn union params", ()=>{
const def = "fn(a: fn(string)|fn(number))";
const answer = [
[
{
"name":"a",
"params":[{
"type":dtsmake.TSObjType.STRING
}],
"type":dtsmake.TSObjType.FUNCTION,
"ret":[{
"type":dtsmake.TSObjType.VOID
}]
},
{
"name":"a",
"params":[{
"type":dtsmake.TSObjType.NUMBER
}],
"type":dtsmake.TSObjType.FUNCTION,
"ret":[{
"type":dtsmake.TSObjType.VOID
}]
}
]
];
let out = dg.parseParams(def);
assert.deepEqual(out, answer);
});
});
context("splitParams()",()=>{
it("should parse fn params array",()=>{
const def = "sParams:[string],nParams:[number]";
const answer =
[
"sParams:[string]",
"nParams:[number]"
];
let out = dg.splitParams(def);
assert.deepEqual(out,answer, `\ndef out ${JSON.stringify(out)},\nanswer ${JSON.stringify(answer)}`);
});
});
context("parseTernJson()",()=>{
let loadData:JSON;
beforeEach((done)=>{
dg.loadTernJson("sample/infer.js.json",(jsonData)=>{
loadData = jsonData;
done();
})
});
let nodeDTSObj:any;
it("parseJsonNodeDTS()",(done)=>{
nodeDTSObj = dg.parseJsonNodeDTS(loadData);
done();
});
let modifiedObj;
it("preModifiedJson()", (done)=>{
modifiedObj = dg.preModifiedJson(nodeDTSObj);
done();
});
});
context("Type checking ternjs type strings",()=>{
const s =
[
{type:dtsmake.TSObjType.ANY, str:"?"},
{type:dtsmake.TSObjType.ARRAY, str:"[number]"},
{type:dtsmake.TSObjType.BOOLEAN, str:"bool"},
{type:dtsmake.TSObjType.CLASS, str:"+hoge.fuga.Class"},
{type:dtsmake.TSObjType.FUNCTION, str:"fn(?,?)->?"},
{type:dtsmake.TSObjType.NUMBER, str:"number"},
{type:dtsmake.TSObjType.OBJECT, str:"hoge"},
{type:dtsmake.TSObjType.STRING, str:"string"},
{type:dtsmake.TSObjType.UNIONS, str:"number|string"}
];
it("basic type check",()=>{
for(let i in s){
let o = s[i];
assert(dg.checkType(o.str) === o.type,`type ${dtsmake.TSObjType[o.type]} check faild.`);
}
});
const objs =
[
{type:dtsmake.TSObjType.OBJECT, str:"!this"},
{type:dtsmake.TSObjType.OBJECT, str:"!this.Obj"},
{type:dtsmake.TSObjType.OBJECT, str:"some.namespace.to.object"},
{type:dtsmake.TSObjType.OBJECT, str:"!ternjs.!internal.!refs.!0.<i>"}
];
const noObjs =
[
"number",
"string",
"+hoge.fuga",
"bool",
"?",
"?|bool",
"fn(number|?,bool|?)->+hoge.fuga",
"[bool|number]",
"[+hoge.fuga]"
];
it("object type check",()=>{
for(let i in objs){
let o = objs[i];
assert(dg.checkType(o.str) === o.type,`type ${dtsmake.TSObjType[o.type]} check faild.`);
}
for(let i in noObjs){
let o = noObjs[i];
assert(dg.checkType(o) !== dtsmake.TSObjType.OBJECT,`${o} is may object.`);
}
});
/*
const mems = [
{type:dtsmake.TSObjType.OBJ_MEMBER, str:"!this"},
{type:dtsmake.TSObjType.OBJ_MEMBER, str:"!this.member"},
{type:dtsmake.TSObjType.OBJ_MEMBER, str:"!this.member.child.child"},
{type:dtsmake.TSObjType.OBJ_MEMBER, str:"!this.member.!this.!this.!node"}
];
it("this member obj check",()=>{
for(let i in mems){
let o = mems[i];
assert(dg.checkType(o.str) === o.type,`type ${dtsmake.TSObjType[o.type]} check faild.`);
}
});
*/
});
context("checkReplaceTypes(), ", ()=>{
it("should match replace fn return type",()=>{
let path = ["Klass", "prototype", "prop", "!ret"];
let t = dg.checkReplaceType(path[path.length-1]);
assert(t == dtsmake.ReplaceType.RETURN,
`${path[path.length-1]} is not match ReplaceType.RETURN`
);
});
it("should match may be Class",()=>{
let cs = [
"A",
"Ab",
"Abc",
"ABC",
"KlassA"
];
for(let i in cs){
assert(
dg.checkReplaceType(cs[i]) === dtsmake.ReplaceType.CLASS,
`${cs[i]} may not be Class`
);
}
});
it("should match array type",()=>{
let cs = [
"<i>",
"<i>",
"<i>",
"<i>",
"<hoge>"
];
for(let i in cs){
let out = dg.checkReplaceType(cs[i]);
assert(
out === dtsmake.ReplaceType.ARRAY,
`${cs[i]} may not be Array`
);
}
})
});
context("search ternjs ref & replace dts ref, ",()=>{
let test = {
"!define":{
"Klass.prop.!ret":[
{
"type": dtsmake.TSObjType.CLASS,
"class":"+Klass"
}
]
},
"Klass":{
"prop":{
"type":dtsmake.TSObjType.FUNCTION,
"ret":[
{
"type": dtsmake.TSObjType.OBJECT,
"class": "!this"
}
],
"params": <any>null
},
"prop2":{
"type":dtsmake.TSObjType.NUMBER
}
}
};
beforeEach(()=>{
test = {
"!define":{
"Klass.prop.!ret":[
{
"type": dtsmake.TSObjType.CLASS,
"class":"+Klass"
}
]
},
"Klass":{
"prop":{
"type":dtsmake.TSObjType.FUNCTION,
"ret":[
{
"type": dtsmake.TSObjType.OBJECT,
"class": "!this"
}
],
"params": <any>null
},
"prop2":{
"type":dtsmake.TSObjType.NUMBER
}
}
};
});
it("should search prototype ref (Klass.prototype.prop.!ret)", ()=>{
let ref = dg.searchRef(
test,
["Klass","prototype","prop","!ret"],
false
);
assert(ref, "no ref");
});
it("should search prototype prop ref", ()=>{
let ref2 = dg.searchRef(
test,
["Klass","prototype","prop2"],
false
);
assert(ref2, "no ref");
});
it("should faild search non ref", ()=>{
let ref = dg.searchRef(
test,
["Klass","hoge","fuga","!0"],
false
);
assert(!ref, "no ref should be no ref");
});
it("should replace prototype ref to Class ref", ()=>{
dg.searchAndReplaceDTS(
test,
["Klass","prototype","prop"],
"PropRet",
false
);
//console.log(JSON.stringify(test));
});
it("should replace prototype ref to Class ref 2", ()=>{
dg.searchAndReplaceDTS(
test,
["Klass","prototype","prop2"],
"Prop2",
false
);
});
it.skip("should replace local !ret", ()=>{
const o = {
"scopeAt": {
"!type": [
{
"type": 5,
"ret": [
{
"type": 9,
"class": "!2"
}
],
"params": [
{
"name": "ast",
"type": 0
},
{
"name": "pos",
"type": 0
},
{
"name": "defaultScope",
"type": 0
}
]
}
]
}
};
const answer = {
"scopeAt": {
//"!type": "fn(ast: ?, pos: ?, defaultScope: ?) -> !2"
"!type":[{
"type":dtsmake.TSObjType.FUNCTION,
"params":[
{
"type":dtsmake.TSObjType.ANY,
"name":"ast"
},
{
"type":dtsmake.TSObjType.ANY,
"name":"pos"
},
{
"type":dtsmake.TSObjType.ANY,
"name":"defaultScope"
}
],
"ret":[
{
"type":dtsmake.TSObjType.ANY,
"class":"!2"
}
]
}]
}
};
let out = dg.searchRef(o,["!2"],false);
console.log("ref", JSON.stringify(out));
dg.searchAndReplaceDTS(o, ["!ret"],"",false);
assert.deepEqual(o, answer);
});
});
context("preModifiedJson()", ()=>{
let def:{};
beforeEach(()=>{
def = {
"Math":{
"prop":{
type:dtsmake.TSObjType.STRING
}
},
"NoGlobal":{}
};
dg["userDefinedModuleName"] = "MyLib";
});
it("should remove a object that same name with JS Global Object",()=>{
dg.option.globalObject = dtsmake.Option.GlobalObject.REMOVE;
let out = dg.preModifiedJson(def);
let answer = {
"NoGlobal":{}
};
assert.deepEqual(out, answer);
});
it("should wrap a object that same name with JS Global Object",()=>{
dg.option.globalObject = dtsmake.Option.GlobalObject.WRAP;
let out = dg.preModifiedJson(def);
let answer = {
"MyLib":{
"Math":{
"prop":{
type:dtsmake.TSObjType.STRING
},
"!!!dtsinterface!!!":"Math"
}
},
"NoGlobal":{}
};
assert.deepEqual(out, answer);
});
it("should rename a object that same name with JS Global Object",()=>{
dg.option.globalObject = dtsmake.Option.GlobalObject.RENAME;
let out = dg.preModifiedJson(def);
let answer = {
"MyLib$Math":{
"prop":{
type:dtsmake.TSObjType.STRING
}
},
"NoGlobal":{}
};
assert.deepEqual(out, answer);
});
it.skip("should rename & extend a object that same name with JS Global Object",()=>{
dg.option.globalObject = dtsmake.Option.GlobalObject.RENAME;
let out = dg.preModifiedJson(def);
let answer = {
"MyLib$Math":{
"prop":{
type:dtsmake.TSObjType.STRING
},
"!proto":{
type:dtsmake.TSObjType.CLASS,
class:"Math.prototype"
}
},
"NoGlobal":{}
};
assert.deepEqual(out, answer);
});
});
}); | the_stack |
import ee from 'event-emitter';
import { AlfrescoApiConfig } from './alfrescoApiConfig';
import superagent, { Response, ProgressEvent } from 'superagent';
import { Authentication } from './authentication/authentication';
import { BasicAuth } from './authentication/basicAuth';
import { Oauth2 } from './authentication/oauth2';
declare const Buffer: any;
declare const Blob: any;
export interface RequestOptions {
path: string;
httpMethod?: string;
pathParams?: any;
queryParams?: any;
headerParams?: any;
formParams?: any;
bodyParam?: any;
contentTypes?: string[];
accepts?: string[];
returnType?: any;
contextRoot?: string;
responseType?: string;
url?: string;
}
/**
* Returns a string representation for an actual parameter.
* @param param The actual parameter.
* @returns The string representation of <code>param</code>.
*/
export function paramToString(param: any): string {
if (param === undefined || param === null) {
return '';
}
if (param instanceof Date) {
return param.toJSON();
}
return param.toString();
}
/**
* Builds a string representation of an array-type actual parameter, according to the given collection format.
* @param {Array} param An array parameter.
* @param {module:ApiClient.CollectionFormatEnum} collectionFormat The array element separator strategy.
* @returns {String|Array} A string representation of the supplied collection, using the specified delimiter. Returns
* <code>param</code> as is if <code>collectionFormat</code> is <code>multi</code>.
*/
export function buildCollectionParam(param: string[], collectionFormat: string): string | any[] {
if (!param) {
return null;
}
switch (collectionFormat) {
case 'csv':
return param.map(paramToString).join(',');
case 'ssv':
return param.map(paramToString).join(' ');
case 'tsv':
return param.map(paramToString).join('\t');
case 'pipes':
return param.map(paramToString).join('|');
case 'multi':
// return the array directly as SuperAgent will handle it as expected
return param.map(paramToString);
default:
throw new Error('Unknown collection format: ' + collectionFormat);
}
}
export class AlfrescoApiClient implements ee.Emitter {
on: ee.EmitterMethod;
off: ee.EmitterMethod;
once: ee.EmitterMethod;
emit: (type: string, ...args: any[]) => void;
host: string;
className: string;
config: AlfrescoApiConfig;
url: string;
/**
* The base URL against which to resolve every API call's (relative) path.
*/
basePath: string = '';
/**
* The authentication methods to be included for all API calls.
*/
authentications: Authentication = {
basicAuth: {
ticket: ''
},
type: 'basic'
};
/**
* The default HTTP headers to be included for all API calls.
*/
defaultHeaders = {};
/**
* The default HTTP timeout for all API calls.
*/
timeout: number | { deadline?: number, response?: number } = undefined;
contentTypes = {
JSON: ['application/json']
};
constructor(host?: string) {
this.host = host;
ee(this);
}
/**
* Builds full URL by appending the given path to the base URL and replacing path parameter place-holders with parameter values.
* NOTE: query parameters are not handled here.
* @param path The path to append to the base URL.
* @param pathParams The parameter values to append.
* @returns The encoded path with parameter values substituted.
*/
buildUrl(path: string, pathParams: any): string {
if (!path.match(/^\//)) {
path = '/' + path;
}
let url = this.basePath + path;
url = url.replace(/\{([\w-]+)\}/g, function (fullMatch, key) {
let value;
if (pathParams.hasOwnProperty(key)) {
value = paramToString(pathParams[key]);
} else {
value = fullMatch;
}
return encodeURIComponent(value);
});
return url;
}
/**
* Checks whether the given content type represents JSON.<br>
* JSON content type examples:<br>
* <ul>
* <li>application/json</li>
* <li>application/json; charset=UTF8</li>
* <li>APPLICATION/JSON</li>
* </ul>
* @param contentType The MIME content type to check.
* @returns <code>true</code> if <code>contentType</code> represents JSON, otherwise <code>false</code>.
*/
isJsonMime(contentType: string): boolean {
return Boolean(contentType !== null && contentType.match(/^application\/json(;.*)?$/i));
}
/**
* Chooses a content type from the given array, with JSON preferred; i.e. return JSON if included, otherwise return the first.
* @param contentTypes
* @returns The chosen content type, preferring JSON.
*/
jsonPreferredMime(contentTypes: string[]): string {
for (let i = 0; i < contentTypes.length; i++) {
if (this.isJsonMime(contentTypes[i])) {
return contentTypes[i];
}
}
return contentTypes[0];
}
/**
* Checks whether the given parameter value represents file-like content.
* @param param The parameter to check.
* @returns <code>true</code> if <code>param</code> represents a file.
*/
isFileParam(param: any): boolean {
// Buffer in Node.js
if (typeof Buffer === 'function' && (param instanceof Buffer || param.path)) {
return true;
}
// Blob in browser
if (typeof Blob === 'function' && param instanceof Blob) {
return true;
}
// File in browser (it seems File object is also instance of Blob, but keep this for safe)
if (typeof File === 'function' && param instanceof File) {
return true;
}
// Safari fix
if (typeof File === 'object' && param instanceof File) {
return true;
}
return false;
}
/**
* Normalizes parameter values:
* <ul>
* <li>remove nils</li>
* <li>keep files and arrays</li>
* <li>format to string with `paramToString` for other cases</li>
* </ul>
* @param {Object.<String, Object>} params The parameters as object properties.
* @returns {Object.<String, Object>} normalized parameters.
*/
normalizeParams(params: { [key: string]: any; }): { [key: string]: any; } {
const newParams: { [key: string]: any; } = {};
for (const key in params) {
if (params.hasOwnProperty(key) && params[key] !== undefined && params[key] !== null) {
const value = params[key];
if (this.isFileParam(value) || Array.isArray(value)) {
newParams[key] = value;
} else {
newParams[key] = paramToString(value);
}
}
}
return newParams;
}
isWithCredentials(): boolean {
if (this.config) {
return this.config.withCredentials;
} else {
return false;
}
}
/**
* Applies authentication headers to the request.
* @param {Object} request The request object created by a <code>superagent()</code> call.
*/
applyAuthToRequest(request: any) {
if (this.authentications) {
switch (this.authentications.type) {
case 'basic': {
const basicAuth: BasicAuth = this.authentications.basicAuth;
if (basicAuth.username || basicAuth.password) {
request.auth(
basicAuth.username ? encodeURI(basicAuth.username) : '',
basicAuth.password ? encodeURI(basicAuth.password) : ''
);
}
break;
}
case 'activiti': {
if (this.authentications.basicAuth.ticket) {
request.set({ 'Authorization': this.authentications.basicAuth.ticket });
}
break;
}
case 'oauth2': {
const oauth2: Oauth2 = this.authentications.oauth2;
if (oauth2.accessToken) {
request.set({ 'Authorization': 'Bearer ' + oauth2.accessToken });
}
break;
}
default:
throw new Error('Unknown authentication type: ' + this.authentications.type);
}
}
}
/**
* Deserializes an HTTP response body into a value of the specified type.
* @param {Object} response A SuperAgent response object.
* @param {(String|string[]|Object.<String, Object>|Function)} returnType The type to return. Pass a string for simple types
* or the constructor function for a complex type. Pass an array containing the type name to return an array of that type. To
* return an object, pass an object with one property whose name is the key type and whose value is the corresponding value type:
* all properties on <code>data<code> will be converted to this type.
* @returns A value of the specified type.
*/
deserialize(response: any, returnType?: any): any {
if (response === null) {
return null;
}
let data = response.body;
if (data === null) {
data = response.text;
}
if (returnType) {
if (returnType === 'blob' && this.isBrowser()) {
data = new Blob([data], { type: response.header['content-type'] });
} else if (returnType === 'blob' && !this.isBrowser()) {
data = new Buffer.from(data, 'binary');
} else if (Array.isArray(data)) {
data = data.map((element) => {
return new returnType(element);
});
} else {
data = new returnType(data);
}
}
return data;
}
basicAuth(username: string, password: string): string {
const str: any = username + ':' + password;
let base64;
if (typeof Buffer === 'function') {
base64 = Buffer.from(str.toString(), 'binary').toString('base64');
} else {
base64 = btoa(str);
}
return 'Basic ' + base64;
}
/**
* Invokes the REST service using the supplied settings and parameters.
*
* @param {String} path The base URL to invoke.
* @param {String} httpMethod The HTTP method to use.
* @param {Object.<String, String>} pathParams A map of path parameters and their values.
* @param {Object.<String, Object>} queryParams A map of query parameters and their values.
* @param {Object.<String, Object>} headerParams A map of header parameters and their values.
* @param {Object.<String, Object>} formParams A map of form parameters and their values.
* @param {Object} bodyParam The value to pass as the request body.
* @param {String[]} contentTypes An array of request MIME types.
* @param {String[]} accepts An array of acceptable response MIME types.
* @param {(String|Array|ObjectFunction)} returnType The required type to return; can be a string for simple types or the
* @param {(String)} contextRoot alternative contextRoot
* @param {(String)} responseType is an enumerated value that returns the type of the response.
* It also lets the author change the response type to one "arraybuffer", "blob", "document",
* "json", or "text".
* If an empty string is set as the value of responseType, it is assumed as type "text".
* constructor for a complex type. * @returns {Promise} A Promise object.
*/
callApi(path: string, httpMethod: string, pathParams?: any, queryParams?: any, headerParams?: any, formParams?: any, bodyParam?: any,
contentTypes?: string[], accepts?: string[], returnType?: any, contextRoot?: string, responseType?: string, url?: string): Promise<any> {
if (!url) {
if (contextRoot) {
const basePath = `${this.host}/${contextRoot}`;
url = this.buildUrlCustomBasePath(basePath, path, pathParams);
} else {
url = this.buildUrl(path, pathParams);
}
}
return this.callHostApi(path, httpMethod, pathParams, queryParams, headerParams, formParams, bodyParam,
contentTypes, accepts, returnType, contextRoot, responseType, url);
}
request<T = any>(options: RequestOptions): Promise<T> {
return this.callApi(
options.path,
options.httpMethod,
options.pathParams,
options.queryParams,
options.headerParams,
options.formParams,
options.bodyParam,
options.contentTypes,
options.accepts,
options.returnType,
options.contextRoot,
options.responseType,
options.url
);
}
post<T = any>(options: RequestOptions): Promise<T> {
return this.request<T>({
...options,
httpMethod: 'POST',
contentTypes: options.contentTypes || this.contentTypes.JSON,
accepts: options.accepts || this.contentTypes.JSON
});
}
put<T = any>(options: RequestOptions): Promise<T> {
return this.request<T>({
...options,
httpMethod: 'PUT',
contentTypes: options.contentTypes || this.contentTypes.JSON,
accepts: options.accepts || this.contentTypes.JSON
});
}
get<T = any>(options: RequestOptions): Promise<T> {
return this.request<T>({
...options,
httpMethod: 'GET',
contentTypes: options.contentTypes || this.contentTypes.JSON,
accepts: options.accepts || this.contentTypes.JSON
});
}
delete<T = void>(options: RequestOptions): Promise<T> {
return this.request<T>({
...options,
httpMethod: 'DELETE',
contentTypes: options.contentTypes || this.contentTypes.JSON,
accepts: options.accepts || this.contentTypes.JSON
});
}
/**
* Invokes the REST service using the supplied settings and parameters but not the basepath.
*
* @param {String} path The base URL to invoke.
* @param {String} httpMethod The HTTP method to use.
* @param {Object.<String, String>} pathParams A map of path parameters and their values.
* @param {Object.<String, Object>} queryParams A map of query parameters and their values.
* @param {Object.<String, Object>} headerParams A map of header parameters and their values.
* @param {Object.<String, Object>} formParams A map of form parameters and their values.
* @param {Object} bodyParam The value to pass as the request body.
* @param {String[]} contentTypes An array of request MIME types.
* @param {String[]} accepts An array of acceptable response MIME types.
* @param {(String|Array|ObjectFunction)} returnType The required type to return; can be a string for simple types or the
* @param {(String)} contextRoot alternative contextRoot
* @param {(String)} responseType is an enumerated value that returns the type of the response.
* It also lets the author change the response type to one "arraybuffer", "blob", "document",
* "json", or "text".
* If an empty string is set as the value of responseType, it is assumed as type "text".
* constructor for a complex type. * @returns {Promise} A Promise object.
*/
callCustomApi(path: string, httpMethod: string, pathParams?: any, queryParams?: any, headerParams?: any, formParams?: any, bodyParam?: any,
contentTypes?: string[], accepts?: string[], returnType?: any, contextRoot?: string, responseType?: string): Promise<any> {
const url = this.buildUrlCustomBasePath(path, '', pathParams);
return this.callHostApi(path, httpMethod, pathParams, queryParams, headerParams, formParams, bodyParam,
contentTypes, accepts, returnType, contextRoot, responseType, url);
}
/**
* Invokes the REST service using the supplied settings and parameters.
*
* @param {String} path The base URL to invoke.
* @param {String} httpMethod The HTTP method to use.
* @param {Object.<String, String>} pathParams A map of path parameters and their values.
* @param {Object.<String, Object>} queryParams A map of query parameters and their values.
* @param {Object.<String, Object>} headerParams A map of header parameters and their values.
* @param {Object.<String, Object>} formParams A map of form parameters and their values.
* @param {Object} bodyParam The value to pass as the request body.
* @param {String[]} contentTypes An array of request MIME types.
* @param {String[]} accepts An array of acceptable response MIME types.
* @param {(String|Array|any)} returnType The required type to return; can be a string for simple types or the
* @param {(String)} contextRoot alternative contextRoot
* @param {(String)} responseType is an enumerated value that returns the type of the response.
* It also lets the author change the response type to one "arraybuffer", "blob", "document",
* "json", or "text".
* If an empty string is set as the value of responseType, it is assumed as type "text".
* constructor for a complex type. * @returns {Promise} A Promise object.
*/
callHostApi(
// @ts-ignore
path: string,
httpMethod: string,
// @ts-ignore
pathParams?: any,
queryParams?: any, headerParams?: any, formParams?: any, bodyParam?: any,
contentTypes?: string[], accepts?: string[], returnType?: any,
// @ts-ignore
contextRoot?: string,
responseType?: string, url?: string): Promise<any> {
const eventEmitter: any = ee({});
let request = this.buildRequest(httpMethod, url, queryParams, headerParams, formParams, bodyParam,
contentTypes, accepts, responseType, eventEmitter, returnType);
if (returnType === 'Binary') {
request = request.buffer(true).parse(superagent.parse['application/octet-stream']);
}
const promise: any = new Promise((resolve, reject) => {
request.on('abort', () => {
eventEmitter.emit('abort');
});
request.end((error: any, response: Response) => {
if (error) {
this.emit('error', error);
eventEmitter.emit('error', error);
if (error.status === 401) {
this.emit('unauthorized');
eventEmitter.emit('unauthorized');
}
if (response && response.text) {
error = error || {};
reject(Object.assign(error, { message: response.text }));
} else {
reject({ error: error });
}
} else {
if (this.isBpmRequest()) {
if (response.header && response.header.hasOwnProperty('set-cookie')) {
this.authentications.cookie = response.header['set-cookie'][0];
}
}
let data = {};
if (response.type === 'text/html') {
data = this.deserialize(response);
} else {
data = this.deserialize(response, returnType);
}
eventEmitter.emit('success', data);
resolve(data);
}
});
});
promise.on = function () {
eventEmitter.on.apply(eventEmitter, arguments);
return this;
};
promise.once = function () {
eventEmitter.once.apply(eventEmitter, arguments);
return this;
};
promise.emit = function () {
eventEmitter.emit.apply(eventEmitter, arguments);
return this;
};
promise.off = function () {
eventEmitter.off.apply(eventEmitter, arguments);
return this;
};
promise.abort = function () {
request.abort();
return this;
};
return promise;
}
isBpmRequest(): boolean {
return this.className === 'ProcessAuth' || this.className === 'ProcessClient';
}
isCsrfEnabled(): boolean {
if (this.config) {
return !this.config.disableCsrf;
} else {
return true;
}
}
setCsrfToken(request: any) {
const token = this.createCSRFToken();
request.set('X-CSRF-TOKEN', token);
if (!this.isBrowser()) {
request.set('Cookie', 'CSRF-TOKEN=' + token + ';path=/');
}
try {
document.cookie = 'CSRF-TOKEN=' + token + ';path=/';
} catch (err) {
/* continue regardless of error */
}
}
isBrowser(): boolean {
return (typeof window !== 'undefined' && typeof window.document !== 'undefined');
}
createCSRFToken(a?: any): string {
return a ? (a ^ Math.random() * 16 >> a / 4).toString(16) : ([1e16] + (1e16).toString()).replace(/[01]/g, this.createCSRFToken);
}
progress(event: any, eventEmitter: ee.Emitter) {
if (event.lengthComputable) {
const percent = Math.round(event.loaded / event.total * 100);
eventEmitter.emit('progress', {
total: event.total,
loaded: event.loaded,
percent: percent
});
}
}
/**
* Builds full URL by appending the given path to the base URL and replacing path parameter place-holders
* with parameter values
*/
buildUrlCustomBasePath(basePath: string, path: string, pathParams: any): string {
if (path && path !== '' && !path.match(/^\//)) {
path = '/' + path;
}
let url = basePath + path;
url = url.replace(/\{([\w-]+)\}/g, function (fullMatch, key) {
let value;
if (pathParams.hasOwnProperty(key)) {
value = paramToString(pathParams[key]);
} else {
value = fullMatch;
}
return encodeURIComponent(value);
});
return url;
}
buildRequest(
httpMethod: string,
url: string,
queryParams: { [key: string]: any },
headerParams: { [key: string]: any },
formParams: { [key: string]: any },
bodyParam: string | Object,
contentTypes: string[],
accepts: string[],
responseType: string,
eventEmitter: ee.Emitter,
returnType: string) {
const request: any = superagent(httpMethod, url);
// apply authentications
this.applyAuthToRequest(request);
// set query parameters
request.query(this.normalizeParams(queryParams));
// set header parameters
request.set(this.defaultHeaders).set(this.normalizeParams(headerParams));
if (this.isBpmRequest() && this.isCsrfEnabled()) {
this.setCsrfToken(request);
}
if (this.isWithCredentials()) {
request.withCredentials();
}
// add cookie for activiti
if (this.isBpmRequest()) {
request.withCredentials();
if (this.authentications.cookie) {
if (!this.isBrowser()) {
request.set('Cookie', this.authentications.cookie);
}
}
}
// set request timeout
request.timeout(this.timeout);
const contentType = this.jsonPreferredMime(contentTypes);
if (contentType && contentType !== 'multipart/form-data') {
request.type(contentType);
} else if (!request.header['Content-Type'] && contentType !== 'multipart/form-data') {
request.type('application/json');
}
if (contentType === 'application/x-www-form-urlencoded') {
request.send(this.normalizeParams(formParams)).on('progress', (event: any) => {
this.progress(event, eventEmitter);
});
} else if (contentType === 'multipart/form-data') {
const _formParams = this.normalizeParams(formParams);
for (const key in _formParams) {
if (_formParams.hasOwnProperty(key)) {
if (this.isFileParam(_formParams[key])) {
// file field
request.attach(key, _formParams[key]).on('progress', (event: ProgressEvent) => {// jshint ignore:line
this.progress(event, eventEmitter);
});
} else {
request.field(key, _formParams[key]).on('progress', (event: ProgressEvent) => {// jshint ignore:line
this.progress(event, eventEmitter);
});
}
}
}
} else if (bodyParam) {
request.send(bodyParam).on('progress', (event: any) => {
this.progress(event, eventEmitter);
});
}
const accept = this.jsonPreferredMime(accepts);
if (accept) {
request.accept(accept);
}
if (returnType === 'blob' || returnType === 'Blob' || responseType === 'blob' || responseType === 'Blob') {
request.responseType('blob');
} else if (returnType === 'String') {
request.responseType('string');
}
return request;
}
getAlfTicket(ticket: string): string {
let alfTicketFragment = '';
if (ticket) {
alfTicketFragment = '&alf_ticket=' + ticket;
} else if (this.config.ticketEcm) {
alfTicketFragment = '&alf_ticket=' + this.config.ticketEcm;
}
return alfTicketFragment;
}
} | the_stack |
import {
execute,
GraphQLBoolean,
GraphQLID,
GraphQLInputObjectType,
GraphQLInt,
GraphQLList,
GraphQLNonNull,
GraphQLObjectType,
GraphQLScalarType,
GraphQLSchema,
GraphQLString,
parse,
} from 'graphql';
import { ExecutionResult } from '@graphql-tools/utils';
import { stitchSchemas } from '@graphql-tools/stitch';
import { stitchingDirectives } from '@graphql-tools/stitching-directives';
import { ValidationLevel } from '../src/types';
describe('merging using type merging', () => {
const { stitchingDirectivesValidator, stitchingDirectivesTransformer } = stitchingDirectives();
const users = [
{
id: '1',
name: 'Ada Lovelace',
birthDate: '1815-12-10',
username: '@ada',
},
{
id: '2',
name: 'Alan Turing',
birthDate: '1912-06-23',
username: '@complete',
},
];
const accountsSchemaTypes = Object.create(null);
accountsSchemaTypes._Key = new GraphQLScalarType({
name: '_Key',
} as any);
accountsSchemaTypes.Query = new GraphQLObjectType({
name: 'Query',
fields: () => ({
me: {
type: accountsSchemaTypes.User,
resolve: () => users[0],
},
_users: {
type: new GraphQLList(accountsSchemaTypes.User),
args: {
_keys: {
type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(accountsSchemaTypes._Key))),
},
},
resolve: (_root, { keys }) => keys.map((key: Record<string, any>) => users.find(u => u.id === key['id'])),
extensions: {
directives: [
{
name: 'merge',
},
],
},
},
}),
});
accountsSchemaTypes.User = new GraphQLObjectType({
name: 'User',
fields: () => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
username: { type: GraphQLString },
}),
extensions: {
directives: [
{
name: 'key',
args: {
selectionSet: '{ id }',
},
},
],
},
});
const accountsSchema = stitchingDirectivesValidator(
new GraphQLSchema({
query: accountsSchemaTypes.Query,
})
);
const inventory = [
{ upc: '1', inStock: true },
{ upc: '2', inStock: false },
{ upc: '3', inStock: true },
];
const inventorySchemaTypes = Object.create(null);
inventorySchemaTypes.ProductKey = new GraphQLInputObjectType({
name: 'ProductKey',
fields: () => ({
upc: { type: new GraphQLNonNull(GraphQLString) },
price: { type: GraphQLInt },
weight: { type: GraphQLInt },
}),
});
inventorySchemaTypes.Product = new GraphQLObjectType({
name: 'Product',
fields: () => ({
upc: { type: new GraphQLNonNull(GraphQLString) },
inStock: { type: GraphQLBoolean },
shippingEstimate: {
type: GraphQLInt,
resolve: product => {
if (product.price > 1000) {
return 0; // free for expensive items
}
return Math.round(product.weight * 0.5) || null; // estimate is based on weight
},
extensions: {
directives: {
computed: {
selectionSet: '{ price weight }',
},
},
},
},
}),
extensions: {
directives: {
key: {
selectionSet: '{ upc }',
},
},
},
});
inventorySchemaTypes.Query = new GraphQLObjectType({
name: 'Query',
fields: () => ({
mostStockedProduct: {
type: inventorySchemaTypes.Product,
resolve: () => inventory.find(i => i.upc === '3'),
},
_products: {
type: new GraphQLNonNull(new GraphQLList(inventorySchemaTypes.Product)),
args: {
keys: { type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(inventorySchemaTypes.ProductKey))) },
},
resolve: (_root, { keys }) => {
return keys.map((key: Record<string, any>) => ({ ...key, ...inventory.find(i => i.upc === key['upc']) }));
},
extensions: {
directives: {
merge: {},
},
},
},
}),
});
const inventorySchema = stitchingDirectivesValidator(
new GraphQLSchema({
query: inventorySchemaTypes.Query,
})
);
const products = [
{
upc: '1',
name: 'Table',
price: 899,
weight: 100,
},
{
upc: '2',
name: 'Couch',
price: 1299,
weight: 1000,
},
{
upc: '3',
name: 'Chair',
price: 54,
weight: 50,
},
];
const productsSchemaTypes = Object.create(null);
productsSchemaTypes.Product = new GraphQLObjectType({
name: 'Product',
fields: () => ({
upc: { type: new GraphQLNonNull(GraphQLString) },
name: { type: GraphQLString },
price: { type: GraphQLInt },
weight: { type: GraphQLInt },
}),
// key is not necessary when using keyField
//
// extensions: {
// directives: {
// key: {
// selectionSet: '{ upc }',
// },
// },
// },
});
productsSchemaTypes.Query = new GraphQLObjectType({
name: 'Query',
fields: () => ({
topProducts: {
type: new GraphQLList(productsSchemaTypes.Product),
args: {
first: {
type: GraphQLInt,
defaultValue: 2,
},
},
resolve: (_root, args) => products.slice(0, args['first']),
},
_productsByUpc: {
type: new GraphQLList(productsSchemaTypes.Product),
args: {
upcs: { type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(GraphQLString))) },
},
resolve: (_root, { upcs }) => upcs.map((upc: any) => products.find(product => product.upc === upc)),
extensions: {
directives: {
merge: {
keyField: 'upc',
},
},
},
},
}),
});
const productsSchema = stitchingDirectivesValidator(
new GraphQLSchema({
query: productsSchemaTypes.Query,
})
);
const usernames = [
{ id: '1', username: '@ada' },
{ id: '2', username: '@complete' },
];
const reviews = [
{
id: '1',
authorId: '1',
product: { upc: '1' },
body: 'Love it!',
},
{
id: '2',
authorId: '1',
product: { upc: '2' },
body: 'Too expensive.',
},
{
id: '3',
authorId: '2',
product: { upc: '3' },
body: 'Could be better.',
},
{
id: '4',
authorId: '2',
product: { upc: '1' },
body: 'Prefer something else.',
},
];
const reviewsSchemaTypes = Object.create(null);
reviewsSchemaTypes.Review = new GraphQLObjectType({
name: 'Review',
fields: () => ({
id: { type: new GraphQLNonNull(GraphQLID) },
body: { type: GraphQLString },
author: {
type: reviewsSchemaTypes.User,
resolve: review => ({ __typename: 'User', id: review.authorId }),
},
product: { type: reviewsSchemaTypes.Product },
}),
});
reviewsSchemaTypes.UserKey = new GraphQLInputObjectType({
name: 'UserKey',
fields: () => ({
id: { type: new GraphQLNonNull(GraphQLID) },
}),
});
reviewsSchemaTypes.User = new GraphQLObjectType({
name: 'User',
fields: () => ({
id: { type: new GraphQLNonNull(GraphQLID) },
username: {
type: GraphQLString,
resolve: user => {
const found = usernames.find(username => username.id === user.id);
return found ? found.username : null;
},
},
numberOfReviews: {
type: GraphQLInt,
resolve: user => reviews.filter(review => review.authorId === user.id).length,
},
reviews: {
type: new GraphQLList(reviewsSchemaTypes.Review),
resolve: user => reviews.filter(review => review.authorId === user.id),
},
}),
extensions: {
directives: {
key: {
selectionSet: '{ id }',
},
},
},
});
reviewsSchemaTypes.ProductKey = new GraphQLInputObjectType({
name: 'ProductKey',
fields: () => ({
upc: { type: new GraphQLNonNull(GraphQLString) },
}),
});
reviewsSchemaTypes.ProductInput = new GraphQLInputObjectType({
name: 'ProductInput',
fields: () => ({
keys: { type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(reviewsSchemaTypes.ProductKey))) },
}),
});
reviewsSchemaTypes.Product = new GraphQLObjectType({
name: 'Product',
fields: () => ({
upc: { type: new GraphQLNonNull(GraphQLString) },
reviews: {
type: new GraphQLList(reviewsSchemaTypes.Review),
resolve: product => reviews.filter(review => review.product.upc === product.upc),
},
}),
extensions: {
directives: {
key: {
selectionSet: '{ upc }',
},
},
},
});
reviewsSchemaTypes.Query = new GraphQLObjectType({
name: 'Query',
fields: () => ({
_reviews: {
type: reviewsSchemaTypes.Review,
args: {
id: { type: new GraphQLNonNull(GraphQLID) },
},
resolve: (_root, { id }) => reviews.find(review => review.id === id),
},
_users: {
type: new GraphQLList(reviewsSchemaTypes.User),
args: {
keys: { type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(reviewsSchemaTypes.UserKey))) },
},
resolve: (_root, { keys }) => keys,
extensions: {
directives: {
merge: {},
},
},
},
_products: {
type: new GraphQLList(reviewsSchemaTypes.Product),
args: {
productInput: { type: reviewsSchemaTypes.ProductInput },
},
resolve: (_root, { input }) => input.keys,
extensions: {
directives: {
merge: {
keyArg: 'input.keys',
},
},
},
},
}),
});
const reviewsSchema = stitchingDirectivesValidator(
new GraphQLSchema({
query: reviewsSchemaTypes.Query,
})
);
const stitchedSchema = stitchSchemas({
subschemas: [
{
schema: accountsSchema,
batch: true,
},
{
schema: inventorySchema,
batch: true,
},
{
schema: productsSchema,
batch: true,
},
{
schema: reviewsSchema,
batch: true,
},
],
subschemaConfigTransforms: [stitchingDirectivesTransformer],
typeMergingOptions: {
validationSettings: { validationLevel: ValidationLevel.Off },
},
});
test('can stitch from products to inventory schema including mixture of computed and non-computed fields', async () => {
const result = await execute({
schema: stitchedSchema,
document: parse(/* GraphQL */ `
query {
topProducts {
upc
inStock
shippingEstimate
}
}
`),
});
const expectedResult: ExecutionResult = {
data: {
topProducts: [
{
upc: '1',
inStock: true,
shippingEstimate: 50,
},
{
upc: '2',
inStock: false,
shippingEstimate: 0,
},
],
},
};
expect(result).toEqual(expectedResult);
});
test('can stitch from accounts to reviews to products to inventory', async () => {
const result = await execute({
schema: stitchedSchema,
document: parse(/* GraphQL */ `
query {
me {
reviews {
product {
upc
price
weight
}
}
}
}
`),
});
const expectedResult: ExecutionResult = {
data: {
me: {
reviews: [
{ product: { price: 899, upc: '1', weight: 100 } },
{ product: { price: 1299, upc: '2', weight: 1000 } },
],
},
},
};
expect(result).toEqual(expectedResult);
});
test('can stitch from accounts to reviews to products to inventory', async () => {
const result = await execute({
schema: stitchedSchema,
document: parse(/* GraphQL */ `
query {
me {
reviews {
product {
upc
price
weight
shippingEstimate
}
}
}
}
`),
});
const expectedResult: ExecutionResult = {
data: {
me: {
reviews: [
{
product: {
price: 899,
upc: '1',
weight: 100,
shippingEstimate: 50,
},
},
{
product: {
price: 1299,
upc: '2',
weight: 1000,
shippingEstimate: 0,
},
},
],
},
},
};
expect(result).toEqual(expectedResult);
});
test('can stitch from accounts to reviews to products to inventory even when entire key not requested', async () => {
const result = await execute({
schema: stitchedSchema,
document: parse(/* GraphQL */ `
query {
me {
reviews {
product {
upc
shippingEstimate
}
}
}
}
`),
});
const expectedResult: ExecutionResult = {
data: {
me: {
reviews: [
{
product: {
upc: '1',
shippingEstimate: 50,
},
},
{
product: {
upc: '2',
shippingEstimate: 0,
},
},
],
},
},
};
expect(result).toEqual(expectedResult);
});
test('can stitch from inventory to products and then back to inventory', async () => {
const result = await execute({
schema: stitchedSchema,
document: parse(/* GraphQL */ `
query {
mostStockedProduct {
upc
inStock
shippingEstimate
}
}
`),
});
const expectedResult: ExecutionResult = {
data: {
mostStockedProduct: {
upc: '3',
inStock: true,
shippingEstimate: 25,
},
},
};
expect(result).toEqual(expectedResult);
});
}); | the_stack |
import {
computeHMACSHA256,
truncatedISO8061Date
} from "../../common/utils/utils";
import { BlobSASResourceType } from "./BlobSASResourceType";
import { SASProtocol } from "./IAccountSASSignatureValues";
import { IIPRange, ipRangeToString } from "./IIPRange";
/**
* IBlobSASSignatureValues is used to help generating Blob service SAS tokens for containers or blobs.
*
* @export
* @class IBlobSASSignatureValues
*/
export interface IBlobSASSignatureValues {
/**
* The version of the service this SAS will target. If not specified, it will default to the version targeted by the
* library.
*
* @type {string}
* @memberof IBlobSASSignatureValues
*/
version: string;
/**
* Optional. SAS protocols, HTTPS only or HTTPSandHTTP
*
* @type {SASProtocol | string}
* @memberof IBlobSASSignatureValues
*/
protocol?: SASProtocol | string;
/**
* Optional. When the SAS will take effect.
*
* @type {Date | string}
* @memberof IBlobSASSignatureValues
*/
startTime?: Date | string;
/**
* Optional only when identifier is provided. The time after which the SAS will no longer work.
*
* @type {Date | string}
* @memberof IBlobSASSignatureValues
*/
expiryTime?: Date | string;
/**
* Optional only when identifier is provided.
* Please refer to either {@link ContainerSASPermissions} or {@link BlobSASPermissions} depending on the resource
* being accessed for help constructing the permissions string.
*
* @type {string}
* @memberof IBlobSASSignatureValues
*/
permissions?: string;
/**
* Optional. IP ranges allowed in this SAS.
*
* @type {IIPRange | string}
* @memberof IBlobSASSignatureValues
*/
ipRange?: IIPRange | string;
/**
* The name of the container the SAS user may access.
*
* @type {string}
* @memberof IBlobSASSignatureValues
*/
containerName: string;
/**
* Optional. The name of the container the SAS user may access.
*
* @type {string}
* @memberof IBlobSASSignatureValues
*/
blobName?: string;
/**
* Optional. The name of the access policy on the container this SAS references if any.
*
* @see https://docs.microsoft.com/en-us/rest/api/storageservices/establishing-a-stored-access-policy
*
* @type {string}
* @memberof IBlobSASSignatureValues
*/
identifier?: string;
/**
* Optional. The cache-control header for the SAS.
*
* @type {string}
* @memberof IBlobSASSignatureValues
*/
cacheControl?: string;
/**
* Optional. The content-disposition header for the SAS.
*
* @type {string}
* @memberof IBlobSASSignatureValues
*/
contentDisposition?: string;
/**
* Optional. The content-encoding header for the SAS.
*
* @type {string}
* @memberof IBlobSASSignatureValues
*/
contentEncoding?: string;
/**
* Optional. The content-language header for the SAS.
*
* @type {string}
* @memberof IBlobSASSignatureValues
*/
contentLanguage?: string;
/**
* Optional. The content-type header for the SAS.
*
* @type {string}
* @memberof IBlobSASSignatureValues
*/
contentType?: string;
/**
* Optional. Specifies the accessible resources. Required for version 2018-11-09 and later.
*
* @type {string}
* @memberof IBlobSASSignatureValues
*/
signedResource?: string;
/**
* Optional. Specifies the snapshot time. Required for version 2018-11-09 and later.
*
* @type {string}
* @memberof IBlobSASSignatureValues
*/
snapshot?: string;
}
/**
* Creates an instance of SASQueryParameters.
*
* Only accepts required settings needed to create a SAS. For optional settings please
* set corresponding properties directly, such as permissions, startTime and identifier.
*
* WARNING: When identifier is not provided, permissions and expiryTime are required.
* You MUST assign value to identifier or expiryTime & permissions manually if you initial with
* this constructor.
*
* @export
* @param {IBlobSASSignatureValues} blobSASSignatureValues
* @param {BlobSASResourceType} resource
* @param {string} accountName
* @param {Buffer} sharedKey
* @returns {[string, string]} signature and stringToSign
*/
export function generateBlobSASSignature(
blobSASSignatureValues: IBlobSASSignatureValues,
resource: BlobSASResourceType,
accountName: string,
sharedKey: Buffer
): [string, string] {
if (blobSASSignatureValues.version >= "2018-11-09") {
return generateBlobSASSignature20181109(
blobSASSignatureValues,
resource,
accountName,
sharedKey
);
} else {
return generateBlobSASSignature20150405(
blobSASSignatureValues,
resource,
accountName,
sharedKey
);
}
}
function generateBlobSASSignature20181109(
blobSASSignatureValues: IBlobSASSignatureValues,
resource: BlobSASResourceType,
accountName: string,
sharedKey: Buffer
): [string, string] {
if (
!blobSASSignatureValues.identifier &&
(!blobSASSignatureValues.permissions && !blobSASSignatureValues.expiryTime)
) {
throw new RangeError(
// tslint:disable-next-line:max-line-length
"generateBlobSASSignature(): Must provide 'permissions' and 'expiryTime' for Blob SAS generation when 'identifier' is not provided."
);
}
const version = blobSASSignatureValues.version;
const verifiedPermissions = blobSASSignatureValues.permissions;
// Signature is generated on the un-url-encoded values.
// TODO: Check whether validating the snapshot is necessary.
const stringToSign = [
verifiedPermissions ? verifiedPermissions : "",
blobSASSignatureValues.startTime === undefined
? ""
: typeof blobSASSignatureValues.startTime === "string"
? blobSASSignatureValues.startTime
: truncatedISO8061Date(blobSASSignatureValues.startTime, false),
blobSASSignatureValues.expiryTime === undefined
? ""
: typeof blobSASSignatureValues.expiryTime === "string"
? blobSASSignatureValues.expiryTime
: truncatedISO8061Date(blobSASSignatureValues.expiryTime, false),
getCanonicalName(
accountName,
blobSASSignatureValues.containerName,
resource === BlobSASResourceType.Blob ||
resource === BlobSASResourceType.BlobSnapshot
? blobSASSignatureValues.blobName
: ""
),
blobSASSignatureValues.identifier, // TODO: ? blobSASSignatureValues.identifier : "",
blobSASSignatureValues.ipRange
? typeof blobSASSignatureValues.ipRange === "string"
? blobSASSignatureValues.ipRange
: ipRangeToString(blobSASSignatureValues.ipRange)
: "",
blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "",
version,
blobSASSignatureValues.signedResource,
blobSASSignatureValues.snapshot,
blobSASSignatureValues.cacheControl
? blobSASSignatureValues.cacheControl
: "",
blobSASSignatureValues.contentDisposition
? blobSASSignatureValues.contentDisposition
: "",
blobSASSignatureValues.contentEncoding
? blobSASSignatureValues.contentEncoding
: "",
blobSASSignatureValues.contentLanguage
? blobSASSignatureValues.contentLanguage
: "",
blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : ""
].join("\n");
const signature = computeHMACSHA256(stringToSign, sharedKey);
return [signature, stringToSign];
}
function generateBlobSASSignature20150405(
blobSASSignatureValues: IBlobSASSignatureValues,
resource: BlobSASResourceType,
accountName: string,
sharedKey: Buffer
): [string, string] {
if (
!blobSASSignatureValues.identifier &&
(!blobSASSignatureValues.permissions && !blobSASSignatureValues.expiryTime)
) {
throw new RangeError(
// tslint:disable-next-line:max-line-length
"generateBlobSASSignature(): Must provide 'permissions' and 'expiryTime' for Blob SAS generation when 'identifier' is not provided."
);
}
const version = blobSASSignatureValues.version;
const verifiedPermissions = blobSASSignatureValues.permissions;
// Signature is generated on the un-url-encoded values.
const stringToSign = [
verifiedPermissions ? verifiedPermissions : "",
blobSASSignatureValues.startTime === undefined
? ""
: typeof blobSASSignatureValues.startTime === "string"
? blobSASSignatureValues.startTime
: truncatedISO8061Date(blobSASSignatureValues.startTime, false),
blobSASSignatureValues.expiryTime === undefined
? ""
: typeof blobSASSignatureValues.expiryTime === "string"
? blobSASSignatureValues.expiryTime
: truncatedISO8061Date(blobSASSignatureValues.expiryTime, false),
getCanonicalName(
accountName,
blobSASSignatureValues.containerName,
resource === BlobSASResourceType.Blob
? blobSASSignatureValues.blobName
: ""
),
blobSASSignatureValues.identifier, // TODO: ? blobSASSignatureValues.identifier : "",
blobSASSignatureValues.ipRange
? typeof blobSASSignatureValues.ipRange === "string"
? blobSASSignatureValues.ipRange
: ipRangeToString(blobSASSignatureValues.ipRange)
: "",
blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "",
version,
blobSASSignatureValues.cacheControl
? blobSASSignatureValues.cacheControl
: "",
blobSASSignatureValues.contentDisposition
? blobSASSignatureValues.contentDisposition
: "",
blobSASSignatureValues.contentEncoding
? blobSASSignatureValues.contentEncoding
: "",
blobSASSignatureValues.contentLanguage
? blobSASSignatureValues.contentLanguage
: "",
blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : ""
].join("\n");
const signature = computeHMACSHA256(stringToSign, sharedKey);
return [signature, stringToSign];
}
function getCanonicalName(
accountName: string,
containerName: string,
blobName?: string
): string {
// Container: "/blob/account/containerName"
// Blob: "/blob/account/containerName/blobName"
const elements: string[] = [`/blob/${accountName}/${containerName}`];
if (blobName) {
elements.push(`/${blobName}`);
}
return elements.join("");
} | the_stack |
import { IAM, Lambda } from 'aws-sdk'
import { SdkUtils } from 'lib/sdkutils'
import { TaskOperations } from 'tasks/LambdaDeployFunction/TaskOperations'
import { deployCodeAndConfig, deployCodeOnly, TaskParameters } from 'tasks/LambdaDeployFunction/TaskParameters'
import { emptyConnectionParameters } from '../testCommon'
jest.mock('aws-sdk')
const baseTaskParameters: TaskParameters = {
awsConnectionParameters: emptyConnectionParameters,
deploymentMode: '',
functionName: 'undefined1',
functionHandler: '',
runtime: '',
codeLocation: '',
localZipFile: '',
s3Bucket: '',
s3ObjectKey: '',
s3ObjectVersion: undefined,
roleARN: '',
description: '',
layers: [],
memorySize: 128,
timeout: 3,
publish: false,
deadLetterARN: '',
kmsKeyARN: '',
environment: [],
tags: [],
securityGroups: [],
subnets: [],
tracingConfig: '',
outputVariable: ''
}
const getFunctionSucceeds = {
promise: function() {}
}
const getFunctionFails = {
promise: function() {
throw new Error('does not exist')
}
}
const updateFunctionFails = {
promise: function() {
throw new Error('update failed')
}
}
const updateFunctionSucceeds = {
promise: function() {
return {
FunctionArn: 'arn:yes'
}
}
}
const getIamRoleSucceeds = {
promise: function() {
return {
Role: {
Arn: 'arn:yes'
}
}
}
}
describe('Lambda Deploy Function', () => {
// TODO https://github.com/aws/aws-vsts-tools/issues/167
beforeAll(() => {
SdkUtils.readResourcesFromRelativePath('../../build/src/tasks/LambdaDeployFunction/task.json')
})
test('Creates a TaskOperation', () => {
expect(new TaskOperations(new IAM(), new Lambda(), baseTaskParameters)).not.toBeNull()
})
test('Unknown deployment mode fails', async () => {
expect.assertions(2)
const taskParameters = { ...baseTaskParameters }
taskParameters.deploymentMode = 'to the moon'
const lambda = new Lambda() as any
lambda.getFunction = jest.fn(() => getFunctionSucceeds)
const taskOperations = new TaskOperations(new IAM(), lambda, taskParameters)
await taskOperations.execute().catch(e => expect(`${e}`).toContain('Unrecognized deployment mode to the moon'))
expect(lambda.getFunction).toBeCalledTimes(1)
})
test('Fails to update fails', async () => {
expect.assertions(3)
const taskParameters = { ...baseTaskParameters }
taskParameters.deploymentMode = deployCodeOnly
taskParameters.roleARN = 'arn:yes'
const lambda = new Lambda() as any
lambda.getFunction = jest.fn(() => getFunctionSucceeds)
lambda.updateFunctionCode = jest.fn(() => updateFunctionFails)
const taskOperations = new TaskOperations(new IAM(), lambda, taskParameters)
await taskOperations.execute().catch(e => expect(`${e}`).toContain('Error while updating function code'))
expect(lambda.getFunction).toBeCalledTimes(1)
expect(lambda.updateFunctionCode).toBeCalledTimes(1)
})
test('Deploy only Function does not exist fails', async () => {
expect.assertions(2)
const taskParameters = { ...baseTaskParameters }
taskParameters.deploymentMode = deployCodeOnly
taskParameters.roleARN = 'arn:yes'
const lambda = new Lambda() as any
lambda.getFunction = jest.fn(() => getFunctionFails)
const taskOperations = new TaskOperations(new IAM(), lambda, taskParameters)
await taskOperations.execute().catch(e => expect(`${e}`).toContain('Function undefined1 does not exist'))
expect(lambda.getFunction).toBeCalledTimes(1)
})
test('Deploy only Function exists calls update', async () => {
expect.assertions(2)
const taskParameters = { ...baseTaskParameters }
taskParameters.deploymentMode = deployCodeOnly
taskParameters.roleARN = 'arn:yes'
const lambda = new Lambda() as any
lambda.getFunction = jest.fn(() => getFunctionSucceeds)
lambda.updateFunctionCode = jest.fn(() => updateFunctionSucceeds)
const taskOperations = new TaskOperations(new IAM(), lambda, taskParameters)
await taskOperations.execute()
expect(lambda.getFunction).toBeCalledTimes(1)
expect(lambda.updateFunctionCode).toBeCalledTimes(1)
})
test('Deploy and config does not exist calls create', async () => {
expect.assertions(2)
const taskParameters = { ...baseTaskParameters }
taskParameters.deploymentMode = deployCodeAndConfig
taskParameters.roleARN = 'arn:yes'
const lambda = new Lambda() as any
lambda.getFunction = jest.fn(() => getFunctionFails)
lambda.createFunction = jest.fn(() => updateFunctionSucceeds)
const taskOperations = new TaskOperations(new IAM(), lambda, taskParameters)
await taskOperations.execute()
expect(lambda.getFunction).toBeCalledTimes(1)
expect(lambda.createFunction).toBeCalledTimes(1)
})
test('Deploy and config exists calls update', async () => {
expect.assertions(3)
const taskParameters = { ...baseTaskParameters }
taskParameters.deploymentMode = deployCodeAndConfig
taskParameters.roleARN = 'arn:yes'
const lambda = new Lambda() as any
lambda.getFunction = jest.fn(() => getFunctionSucceeds)
lambda.updateFunctionCode = jest.fn(() => updateFunctionSucceeds)
lambda.updateFunctionConfiguration = jest.fn(() => updateFunctionSucceeds)
const taskOperations = new TaskOperations(new IAM(), lambda, taskParameters)
await taskOperations.execute()
expect(lambda.getFunction).toBeCalledTimes(1)
expect(lambda.updateFunctionCode).toBeCalledTimes(1)
expect(lambda.updateFunctionConfiguration).toBeCalledTimes(1)
})
test('Create function adds fields if they exist', async () => {
expect.assertions(5)
const taskParameters = { ...baseTaskParameters }
taskParameters.deploymentMode = deployCodeAndConfig
taskParameters.roleARN = 'arn:yes'
taskParameters.tracingConfig = 'XRay'
taskParameters.securityGroups = ['security']
taskParameters.tags = ['tag1=2', 'tag2=22']
taskParameters.environment = ['tag1=2', 'tag2=1']
taskParameters.layers = ['arn:thing:whatever:version']
const lambda = new Lambda() as any
lambda.getFunction = jest.fn(() => getFunctionFails)
lambda.createFunction = jest.fn((args: any) => {
expect(args.Environment.Variables).toStrictEqual({ tag1: '2', tag2: '1' })
expect(args.Tags).toStrictEqual({ tag1: '2', tag2: '22' })
expect(args.VpcConfig.SecurityGroupIds).toStrictEqual(['security'])
expect(args.TracingConfig).toBeUndefined()
expect(args.Layers.length).toBe(1)
return updateFunctionSucceeds
})
const taskOperations = new TaskOperations(new IAM(), lambda, taskParameters)
await taskOperations.execute()
})
test('Update function adds fields if they exist', async () => {
expect.assertions(4)
const taskParameters = { ...baseTaskParameters }
taskParameters.deploymentMode = deployCodeAndConfig
taskParameters.roleARN = 'arn:yes'
taskParameters.securityGroups = ['security']
taskParameters.environment = ['tag1=2', 'tag2=1']
taskParameters.tags = ['tag1=5', 'tag=abc']
taskParameters.tracingConfig = 'XRay'
const lambda = new Lambda() as any
lambda.getFunction = jest.fn(() => getFunctionSucceeds)
lambda.updateFunctionCode = jest.fn(() => updateFunctionSucceeds)
lambda.updateFunctionConfiguration = jest.fn(args => {
expect(args.Environment.Variables).toStrictEqual({ tag1: '2', tag2: '1' })
expect(args.VpcConfig.SecurityGroupIds).toStrictEqual(['security'])
expect(args.TracingConfig).toBeUndefined()
return updateFunctionSucceeds
})
lambda.tagResource = jest.fn(args => {
expect(args.Tags).toStrictEqual({ tag1: '5', tag: 'abc' })
return updateFunctionSucceeds
})
const taskOperations = new TaskOperations(new IAM(), lambda, taskParameters)
await taskOperations.execute()
})
test('Update function does not call functions when it should not', async () => {
expect.assertions(1)
const taskParameters = { ...baseTaskParameters }
taskParameters.deploymentMode = deployCodeAndConfig
taskParameters.roleARN = 'arn:yes'
taskParameters.tags = []
taskParameters.tracingConfig = 'XRay'
const lambda = new Lambda() as any
lambda.getFunction = jest.fn(() => getFunctionSucceeds)
lambda.updateFunctionCode = jest.fn(() => updateFunctionSucceeds)
lambda.updateFunctionConfiguration = jest.fn(() => updateFunctionSucceeds)
const tagResourceFunction = jest.fn()
lambda.tagResource = tagResourceFunction
const taskOperations = new TaskOperations(new IAM(), lambda, taskParameters)
await taskOperations.execute()
expect(tagResourceFunction).toHaveBeenCalledTimes(0)
})
test('IAM call when no role arn specified works', async () => {
expect.assertions(1)
const taskParameters = { ...baseTaskParameters }
taskParameters.deploymentMode = deployCodeAndConfig
taskParameters.roleARN = 'name'
const lambda = new Lambda() as any
lambda.getFunction = jest.fn(() => getFunctionFails)
const iam = new IAM() as any
iam.getRole = jest.fn(() => getIamRoleSucceeds)
const taskOperations = new TaskOperations(iam, lambda, taskParameters)
try {
await taskOperations.execute()
} catch (e) {}
expect(iam.getRole).toBeCalledTimes(1)
})
}) | the_stack |
jest.unmock("@dharmaprotocol/contracts");
// Unmock the "fs-extra" package in order to give us
// access to the deployed TokenRegistry on the
// test chain.
jest.unmock("fs-extra");
// External libraries
import * as moment from "moment";
import * as Web3 from "web3";
// Utils
import { BigNumber } from "../../../utils/bignumber";
import * as Units from "../../../utils/units";
import { Web3Utils } from "../../../utils/web3_utils";
import { ACCOUNTS } from "../../accounts";
// Wrappers
import { DebtKernelContract, RepaymentRouterContract } from "../../../src/wrappers";
// Types
import { DEBT_ORDER_DATA_DEFAULTS, DebtOrderData, DebtRegistryEntry } from "../../../src/types";
// Adapters
import {
ERC721CollateralizedSimpleInterestLoanAdapter,
ERC721CollateralizedSimpleInterestLoanOrder,
ERC721CollateralizedTermsContractParameters,
ERC721CollateralizerAdapterErrors,
} from "../../../src/adapters/erc721_collateralized_simple_interest/loan_adapter";
// Loan terms
import { ERC721CollateralizedLoanTerms } from "../../../src/adapters/erc721_collateralized_simple_interest/loan_terms";
// Loan adapters
import {
SimpleInterestAdapterErrors,
SimpleInterestLoanAdapter,
} from "../../../src/adapters/simple_interest_loan_adapter";
// Contracts API
import { ContractsAPI, ContractsError } from "../../../src/apis/contracts_api";
const provider = new Web3.providers.HttpProvider("http://localhost:8545");
const web3 = new Web3(provider);
const web3Utils = new Web3Utils(web3);
const contracts = new ContractsAPI(web3);
const collateralizedSimpleInterestLoanAdapter = new ERC721CollateralizedSimpleInterestLoanAdapter(
web3,
contracts,
);
const collateralizedLoanTerms = new ERC721CollateralizedLoanTerms(web3, contracts);
const TX_DEFAULTS = { from: ACCOUNTS[0].address, gas: 4712388 };
interface Scenario {
unpackedParams: ERC721CollateralizedTermsContractParameters;
packedParams: string;
}
describe("ERC721 Collateralized Terms Contract Interface (Unit Tests)", () => {
let snapshotId: number;
beforeEach(async () => {
snapshotId = await web3Utils.saveTestSnapshot();
});
afterEach(async () => {
await web3Utils.revertToSnapshot(snapshotId);
});
const scenario1: Scenario = {
unpackedParams: {
erc721ContractIndex: new BigNumber(0),
tokenReference: new BigNumber(0),
isEnumerable: new BigNumber(1),
},
packedParams: "0x0000000000000000000000000000000000000000000000000000000000000001",
};
const scenario2: Scenario = {
unpackedParams: {
erc721ContractIndex: new BigNumber(0),
tokenReference: new BigNumber(0),
isEnumerable: new BigNumber(0),
},
packedParams: "0x0000000000000000000000000000000000000000000000000000000000000000",
};
const scenario3: Scenario = {
unpackedParams: {
erc721ContractIndex: new BigNumber(0),
tokenReference: new BigNumber(1),
isEnumerable: new BigNumber(0),
},
packedParams: "0x0000000000000000000000000000000000000000000000000000000000000010",
};
const scenario4: Scenario = {
unpackedParams: {
erc721ContractIndex: new BigNumber(0),
tokenReference: new BigNumber(1),
isEnumerable: new BigNumber(1),
},
packedParams: "0x0000000000000000000000000000000000000000000000000000000000000011",
};
describe("#packParameters", () => {
describe("with an invalid contract index", () => {
test("should throw INVALID_TOKEN_INDEX error", async () => {
// If there is 1 token contract in the registry, its index will be 0, and so on.
const invalidERC721ContractIndex = new BigNumber(-1);
expect(() => {
collateralizedLoanTerms.packParameters({
...scenario1.unpackedParams,
erc721ContractIndex: invalidERC721ContractIndex,
});
}).toThrow(
ERC721CollateralizerAdapterErrors.INVALID_CONTRACT_INDEX(
invalidERC721ContractIndex,
),
);
});
});
describe("with an invalid isEnumerable", () => {
test("should throw INVALID_IS_ENUMERABLE_FLAG error", () => {
expect(() => {
collateralizedLoanTerms.packParameters({
...scenario1.unpackedParams,
isEnumerable: new BigNumber(2),
});
}).toThrow(ERC721CollateralizerAdapterErrors.INVALID_IS_ENUMERABLE_FLAG());
});
});
describe("...with invalid token reference", () => {
test("should throw INVALID_TOKEN_REFERENCE error", () => {
expect(() => {
collateralizedLoanTerms.packParameters({
...scenario1.unpackedParams,
tokenReference: new BigNumber(-1),
});
}).toThrow(ERC721CollateralizerAdapterErrors.INVALID_TOKEN_REFERENCE());
});
});
describe("...with valid ERC721 contract index, token reference, and isEnumerable", () => {
describe("Scenario #1", () => {
test("should return correctly packed parameters", () => {
expect(
collateralizedLoanTerms.packParameters(scenario1.unpackedParams),
).toEqual(scenario1.packedParams);
});
});
describe("Scenario #2", () => {
test("should return correctly packed parameters", () => {
expect(
collateralizedLoanTerms.packParameters(scenario2.unpackedParams),
).toEqual(scenario2.packedParams);
});
});
describe("Scenario #3", () => {
test("should return correctly packed parameters", () => {
expect(
collateralizedLoanTerms.packParameters(scenario3.unpackedParams),
).toEqual(scenario3.packedParams);
});
});
describe("Scenario #4", () => {
test("should return correctly packed parameters", () => {
expect(
collateralizedLoanTerms.packParameters(scenario4.unpackedParams),
).toEqual(scenario4.packedParams);
});
});
});
});
describe("#unpackParameters", () => {
describe("...with value that has too few bytes", () => {
const termsContractParameters = "0x" + "f".repeat(63);
test("should throw INVALID_PACKED_PARAMETERS error", () => {
expect(() => {
collateralizedLoanTerms.unpackParameters(termsContractParameters);
}).toThrowError(/Expected packedParams to conform to schema \/Bytes32/);
});
});
describe("...with value that has too many bytes", () => {
const termsContractParameters = "0x" + "f".repeat(65);
test("should throw INVALID_PACKED_PARAMETERS error", () => {
expect(() => {
collateralizedLoanTerms.unpackParameters(termsContractParameters);
}).toThrowError(/Expected packedParams to conform to schema \/Bytes32/);
});
});
describe("...with value that includes non-hexadecimal characters", () => {
const termsContractParameters = "0x" + "z".repeat(64);
test("should throw INVALID_PACKED_PARAMETERS error", () => {
expect(() => {
collateralizedLoanTerms.unpackParameters(termsContractParameters);
}).toThrowError(/Expected packedParams to conform to schema \/Bytes32/);
});
});
});
describe("...with valid termsContractParameters string", () => {
describe("Scenario #1", () => {
test("should return correctly unpacked parameters", () => {
expect(collateralizedLoanTerms.unpackParameters(scenario1.packedParams)).toEqual(
scenario1.unpackedParams,
);
});
});
});
});
describe("Collateralized Simple Interest Loan Adapter (Unit Tests)", () => {
interface AdapterScenario {
debtOrderData: DebtOrderData;
fullLoanOrder: ERC721CollateralizedSimpleInterestLoanOrder;
minimalLoanOrder: ERC721CollateralizedSimpleInterestLoanOrder;
entry: DebtRegistryEntry;
}
let scenario1: AdapterScenario;
let scenario2: AdapterScenario;
let scenario3: AdapterScenario;
beforeAll(async () => {
const debtKernel = await DebtKernelContract.deployed(web3, TX_DEFAULTS);
const repaymentRouter = await RepaymentRouterContract.deployed(web3, TX_DEFAULTS);
const termsContract = await contracts.loadERC721CollateralizedSimpleInterestTermsContract(
TX_DEFAULTS,
);
const tokenSymbols = await Promise.all(
[0, 1, 2].map((index) => contracts.getTokenSymbolByIndexAsync(new BigNumber(index))),
);
const tokenAddresses = await Promise.all(
tokenSymbols.map((symbol) => contracts.getTokenAddressBySymbolAsync(symbol)),
);
const principalAmountForScenario1 = new BigNumber(1000 * 10 ** 18);
const principalAmountForScenario2 = new BigNumber(12 * 10 ** 18);
const principalAmountForScenario3 = new BigNumber(50 * 10 ** 18);
const debtOrderDataBase = {
...DEBT_ORDER_DATA_DEFAULTS,
kernelVersion: debtKernel.address,
issuanceVersion: repaymentRouter.address,
termsContract: termsContract.address,
};
const debtOrderDataForScenario1 = {
...debtOrderDataBase,
principalAmount: principalAmountForScenario1,
principalToken: tokenAddresses[0],
termsContractParameters:
"0x000000003635c9adc5dea000000003e830002000000000000000000000000001",
};
const debtOrderDataForScenario2 = {
...debtOrderDataBase,
principalAmount: principalAmountForScenario2,
principalToken: tokenAddresses[1],
termsContractParameters:
// Token Reference is 1; isEnumerable is true.
"0x0100000000a688906bd8b000000004b040003000000000000000000000000011",
};
const debtOrderDataForScenario3 = {
...debtOrderDataBase,
principalAmount: principalAmountForScenario3,
principalToken: tokenAddresses[2],
termsContractParameters:
// Token Reference is 0; isEnumerable is false.
"0x0200000002b5e3af16b18800000007d02000a000000000000000000000000000",
};
const loanOrderParamsForScenario1 = {
principalTokenSymbol: tokenSymbols[0],
principalAmount: principalAmountForScenario1,
interestRate: new BigNumber(0.1),
amortizationUnit: SimpleInterestLoanAdapter.Installments.MONTHLY,
termLength: new BigNumber(2),
// TODO: Pull this dynamically?
erc721Symbol: "MET",
tokenReference: new BigNumber(0),
isEnumerable: true,
};
// Token reference of 1
const loanOrderParamsForScenario2 = {
principalTokenSymbol: tokenSymbols[1],
principalAmount: principalAmountForScenario2,
interestRate: new BigNumber(0.12),
amortizationUnit: SimpleInterestLoanAdapter.Installments.YEARLY,
termLength: new BigNumber(3),
erc721Symbol: "MET",
tokenReference: new BigNumber(1),
isEnumerable: true,
};
// isEnumerable is false
const loanOrderParamsForScenario3 = {
principalTokenSymbol: tokenSymbols[2],
principalAmount: principalAmountForScenario3,
interestRate: new BigNumber(0.2),
amortizationUnit: SimpleInterestLoanAdapter.Installments.WEEKLY,
termLength: new BigNumber(10),
erc721Symbol: "MET",
tokenReference: new BigNumber(0),
isEnumerable: false,
};
const debtRegistryEntryBase = {
version: repaymentRouter.address,
beneficiary: ACCOUNTS[0].address,
underwriter: ACCOUNTS[1].address,
underwriterRiskRating: Units.percent(0.1),
termsContract: termsContract.address,
issuanceBlockTimestamp: new BigNumber(moment().unix()),
};
scenario1 = {
debtOrderData: debtOrderDataForScenario1,
fullLoanOrder: {
...debtOrderDataForScenario1,
...loanOrderParamsForScenario1,
},
minimalLoanOrder: loanOrderParamsForScenario1,
entry: {
...debtRegistryEntryBase,
termsContractParameters: debtOrderDataForScenario1.termsContractParameters,
},
};
scenario2 = {
debtOrderData: debtOrderDataForScenario2,
fullLoanOrder: {
...debtOrderDataForScenario2,
...loanOrderParamsForScenario2,
},
minimalLoanOrder: loanOrderParamsForScenario2,
entry: {
...debtRegistryEntryBase,
termsContractParameters: debtOrderDataForScenario2.termsContractParameters,
},
};
scenario3 = {
debtOrderData: debtOrderDataForScenario3,
fullLoanOrder: {
...debtOrderDataForScenario3,
...loanOrderParamsForScenario3,
},
minimalLoanOrder: loanOrderParamsForScenario3,
entry: {
...debtRegistryEntryBase,
termsContractParameters: debtOrderDataForScenario3.termsContractParameters,
},
};
});
describe("#toDebtOrder", () => {
describe("collateralized simple interest loan's required parameter is missing or malformed", () => {
describe("`erc721Symbol` is missing", () => {
test("should throw DOES_NOT_CONFORM_TO_SCHEMA", async () => {
await expect(
collateralizedSimpleInterestLoanAdapter.toDebtOrder({
...scenario1.minimalLoanOrder,
erc721Symbol: undefined,
}),
).rejects.toThrow('instance requires property "erc721Symbol"');
});
});
describe("`erc721Symbol` is not tracked by Token Registry", () => {
test("should throw CANNOT_FIND_TOKEN_WITH_SYMBOL", async () => {
await expect(
collateralizedSimpleInterestLoanAdapter.toDebtOrder({
...scenario1.minimalLoanOrder,
erc721Symbol: "XXX", // XXX is not tracked in our test env's registry
}),
).rejects.toThrow(ContractsError.CANNOT_FIND_TOKEN_WITH_SYMBOL("XXX"));
});
});
describe("`tokenReference` is missing", async () => {
test("should throw DOES_NOT_CONFORM_TO_SCHEMA", async () => {
await expect(
collateralizedSimpleInterestLoanAdapter.toDebtOrder({
...scenario1.minimalLoanOrder,
tokenReference: undefined,
}),
).rejects.toThrow('instance requires property "tokenReference"');
});
});
describe("`isEnumerable` is missing", async () => {
test("should throw DOES_NOT_CONFORM_TO_SCHEMA", async () => {
await expect(
collateralizedSimpleInterestLoanAdapter.toDebtOrder({
...scenario1.minimalLoanOrder,
isEnumerable: undefined,
}),
).rejects.toThrow('instance requires property "isEnumerable"');
});
});
describe("`isEnumerable` is a BigNumber instead of a boolean", async () => {
test("should throw DOES_NOT_CONFORM_TO_SCHEMA", async () => {
await expect(
collateralizedSimpleInterestLoanAdapter.toDebtOrder({
...scenario1.minimalLoanOrder,
isEnumerable: new BigNumber(0),
}),
).rejects.toThrow("instance.isEnumerable is not of a type(s) boolean");
});
});
});
describe(
"erc721 collateralized simple interest loan's " +
"required parameters are present and well-formed ",
() => {
describe("Scenario #1", () => {
test("should return debt order with correctly packed values", async () => {
await expect(
collateralizedSimpleInterestLoanAdapter.toDebtOrder(
scenario1.minimalLoanOrder,
),
).resolves.toEqual(scenario1.debtOrderData);
});
});
describe("Scenario #2", () => {
test("should return debt order with correctly packed values", async () => {
await expect(
collateralizedSimpleInterestLoanAdapter.toDebtOrder(
scenario2.minimalLoanOrder,
),
).resolves.toEqual(scenario2.debtOrderData);
});
});
describe("Scenario #3", () => {
test("should return debt order with correctly packed values", async () => {
await expect(
collateralizedSimpleInterestLoanAdapter.toDebtOrder(
scenario3.minimalLoanOrder,
),
).resolves.toEqual(scenario3.debtOrderData);
});
});
},
);
});
describe("#fromDebtOrder()", () => {
describe("argument does not conform to the DebtOrderWithTermsSpecified schema", () => {
describe("malformed terms contract", () => {
test("should throw DOES_NOT_CONFORM_TO_SCHEMA", async () => {
await expect(
collateralizedSimpleInterestLoanAdapter.fromDebtOrder({
...scenario1.debtOrderData,
termsContract: "invalid terms contract",
}),
).rejects.toThrow("instance.termsContract does not match pattern");
});
});
describe("missing termsContract", () => {
test("should throw DOES_NOT_CONFORM_TO_SCHEMA", async () => {
await expect(
collateralizedSimpleInterestLoanAdapter.fromDebtOrder({
...scenario1.debtOrderData,
termsContract: undefined,
}),
).rejects.toThrow('instance requires property "termsContract"');
});
});
describe("missing termsContractParameters", () => {
test("should throw DOES_NOT_CONFORM_TO_SCHEMA", async () => {
await expect(
collateralizedSimpleInterestLoanAdapter.fromDebtOrder({
...scenario1.debtOrderData,
termsContractParameters: undefined,
}),
).rejects.toThrow('instance requires property "termsContractParameters"');
});
});
describe("missing principalAmount", async () => {
test("should throw DOES_NOT_CONFORM_TO_SCHEMA", async () => {
await expect(
collateralizedSimpleInterestLoanAdapter.fromDebtOrder({
...scenario1.debtOrderData,
principalAmount: undefined,
}),
).rejects.toThrow('instance requires property "principalAmount"');
});
});
describe("missing principalToken", async () => {
test("should throw DOES_NOT_CONFORM_TO_SCHEMA", async () => {
await expect(
collateralizedSimpleInterestLoanAdapter.fromDebtOrder({
...scenario1.debtOrderData,
principalToken: undefined,
}),
).rejects.toThrow('instance requires property "principalToken"');
});
});
});
describe(
"terms contract does not match principal token's " +
"associated `ERC721CollateralizedSimpleInterestTermsContract`",
() => {
test("should throw MISMATCHED_TOKEN_SYMBOL", async () => {
const principalTokenSymbol = await contracts.getTokenSymbolByIndexAsync(
new BigNumber(1),
);
await expect(
collateralizedSimpleInterestLoanAdapter.fromDebtOrder({
...scenario1.debtOrderData,
// // the principal token index is encoded as 1 instead of 0.
termsContractParameters:
"0x010000003635c9adc5dea000000003e830002000000000000000000000000001",
}),
).rejects.toThrow(
ERC721CollateralizerAdapterErrors.MISMATCHED_TOKEN_SYMBOL(
scenario1.debtOrderData.principalToken,
principalTokenSymbol,
),
);
});
},
);
describe("terms contract params contains token index out of bounds", () => {
test("should throw CANNOT_FIND_TOKEN_WITH_INDEX", async () => {
await expect(
collateralizedSimpleInterestLoanAdapter.fromDebtOrder({
...scenario1.debtOrderData,
// the principal token index is encoded as 255, which does not map to any
// token listed in our `TokenRegistry`
termsContractParameters:
"0xff0000003635c9adc5dea000000003e8300020200000008ac7230489e800005a",
}),
).rejects.toThrow(ContractsError.CANNOT_FIND_TOKEN_WITH_INDEX(255));
});
});
describe("amortization specified in termsContractParameters is of invalid type", () => {
it("should throw INVALID_AMORTIZATION_UNIT_TYPE", async () => {
await expect(
collateralizedSimpleInterestLoanAdapter.fromDebtOrder({
...scenario1.debtOrderData,
// The amortization unit is encoded as 6 (which is invalid) instead of 3.
termsContractParameters:
"0x000000003635c9adc5dea000000003e8600020200000008ac7230489e800005a",
}),
).rejects.toThrow(SimpleInterestAdapterErrors.INVALID_AMORTIZATION_UNIT_TYPE());
});
});
describe("debt order is valid and well-formed", () => {
describe("Scenario #1", () => {
test("should return `ERC721CollateralizedSimpleInterestLoanOrder` with correctly unpacked values", async () => {
await expect(
collateralizedSimpleInterestLoanAdapter.fromDebtOrder(
scenario1.debtOrderData,
),
).resolves.toEqual(scenario1.fullLoanOrder);
});
});
describe("Scenario #2", () => {
test("should return `ERC721CollateralizedSimpleInterestLoanOrder` with correctly unpacked values", async () => {
await expect(
collateralizedSimpleInterestLoanAdapter.fromDebtOrder(
scenario2.debtOrderData,
),
).resolves.toEqual(scenario2.fullLoanOrder);
});
});
describe("Scenario #3", () => {
test("should return `ERC721CollateralizedSimpleInterestLoanOrder` with correctly unpacked values", async () => {
await expect(
collateralizedSimpleInterestLoanAdapter.fromDebtOrder(
scenario3.debtOrderData,
),
).resolves.toEqual(scenario3.fullLoanOrder);
});
});
});
});
describe("#fromDebtRegistryEntry", () => {
describe("no principal token tracked at that index", () => {
it("should throw CANNOT_FIND_TOKEN_WITH_INDEX", async () => {
await expect(
collateralizedSimpleInterestLoanAdapter.fromDebtRegistryEntry({
...scenario1.entry,
// Our test environment does not track a token at index 255 (which is packed
// into the first byte of the parameters)
termsContractParameters:
"0xff000000000de0b6b3a764000000057820002000000000000000000000000000",
}),
).rejects.toThrow(ContractsError.CANNOT_FIND_TOKEN_WITH_INDEX(255));
});
});
describe("refers to incorrect terms contract", () => {
test("should throw MISMATCHED_TERMS_CONTRACT", async () => {
// We choose an arbitrary address to represent
// a different terms contract's address.
const INVALID_ADDRESS = ACCOUNTS[3].address;
await expect(
collateralizedSimpleInterestLoanAdapter.fromDebtRegistryEntry({
...scenario1.entry,
termsContract: INVALID_ADDRESS,
}),
).rejects.toThrow(
ERC721CollateralizerAdapterErrors.MISMATCHED_TERMS_CONTRACT(INVALID_ADDRESS),
);
});
});
describe("entry parameters are valid", () => {
describe("Scenario #1:", () => {
test("should return correct collateralized simple interest loan order", async () => {
await expect(
collateralizedSimpleInterestLoanAdapter.fromDebtRegistryEntry(
scenario1.entry,
),
).resolves.toEqual(scenario1.minimalLoanOrder);
});
});
describe("Scenario #2:", () => {
test("should return correct collateralized simple interest loan order", async () => {
await expect(
collateralizedSimpleInterestLoanAdapter.fromDebtRegistryEntry(
scenario2.entry,
),
).resolves.toEqual(scenario2.minimalLoanOrder);
});
});
describe("Scenario #3:", () => {
test("should return correct collateralized simple interest loan order", async () => {
await expect(
collateralizedSimpleInterestLoanAdapter.fromDebtRegistryEntry(
scenario3.entry,
),
).resolves.toEqual(scenario3.minimalLoanOrder);
});
});
});
});
}); | the_stack |
import pathlib from "path";
import semver from "semver";
import * as ts from "@tslab/typescript-for-tslab";
import { isValidModuleName } from "./util";
import { CodeMetadata } from "./metadata";
import { normalizeJoin } from "./tspath";
// TODO: Disallow accessing "module" of Node.js.
export interface SideOutput {
path: string;
data: string;
}
// This is a hack to remove readonly from AST nodes.
// TODO(yunabe): Use visit API instead of modifying AST nodes directly.
type Mutable<T> = {
-readonly [P in keyof T]: T[P];
};
function asMutable<T>(o: T): Mutable<T> {
return o as Mutable<T>;
}
export interface ConvertResult {
output?: string;
declOutput?: string;
/**
* When diagnostics is not empty, other fields are not set.
*/
diagnostics: Diagnostic[];
/**
* The variable name to store the last expression if exists.
* This is necessary to fix #11
*/
lastExpressionVar?: string;
/**
* If true, the input and the output have top-level await statements.
*/
hasToplevelAwait?: boolean;
/**
* JavaScript outputs from external files in the root dir.
*/
sideOutputs?: SideOutput[];
}
export interface DiagnosticPos {
/** Byte-offset. */
offset: number;
/** Zero-based line number. */
line: number;
/** Zero-based char offset in the line. */
character: number;
}
export interface Diagnostic {
start: DiagnosticPos;
end: DiagnosticPos;
messageText: string;
category: number;
code: number;
fileName?: string;
}
export interface CompletionInfo {
start: number;
end: number;
candidates: string[];
/**
* The original completion from TS compiler.
* It's exposed for debugging purpuse.
*/
original?: ts.CompletionInfo;
}
export interface IsCompleteResult {
completed: boolean;
indent?: string;
}
export interface ConverterOptions {
/** If true, JavaScript mode. TypeSceript mode otherwise */
isJS?: boolean;
/** If true, creates a converter for browser mode. Otherwise, Node.js */
isBrowser?: boolean;
/** Only for testing. File changes are forwarded to this handler. */
_fileWatcher?: ts.FileWatcherCallback;
}
export interface Converter {
convert(prevDecl: string, src: string): ConvertResult;
inspect(prevDecl: string, src: string, position: number): ts.QuickInfo;
complete(prevDecl: string, src: string, position: number): CompletionInfo;
/** Release internal resources to terminate the process gracefully. */
close(): void;
/** Defines a in-memory module */
addModule(name: string, content: string, meta?: CodeMetadata): Diagnostic[];
}
interface RebuildTimer {
callback: (...args: any[]) => void;
}
const cancellationToken: ts.CancellationToken = {
isCancellationRequested: (): boolean => false,
throwIfCancellationRequested: (): void => {},
};
export function createConverter(options?: ConverterOptions): Converter {
const cwd = ts.sys.getCurrentDirectory();
const srcFilename = normalizeJoin(
cwd,
options?.isJS ? "__tslab__.js" : "__tslab__.ts"
);
const declFilename = normalizeJoin(cwd, "__prev__.d.ts");
const rootFiles = new Set<string>([declFilename, srcFilename]);
const outDir = "outDir";
const dstFilename = normalizeJoin(outDir, "__tslab__.js");
const dstDeclFilename = normalizeJoin(outDir, "__tslab__.d.ts");
// c.f.
// https://github.com/microsoft/TypeScript/wiki/Node-Target-Mapping
// https://github.com/microsoft/TypeScript/issues/22306#issuecomment-412266626
const transpileTarget =
semver.major(process.version) >= 12
? ts.ScriptTarget.ES2019
: ts.ScriptTarget.ES2018;
// References:
// https://github.com/microsoft/TypeScript/blob/master/src/lib/es2019.full.d.ts
const transpileLib =
transpileTarget === ts.ScriptTarget.ES2019 ? ["es2019"] : ["es2018"];
if (options?.isBrowser) {
transpileLib.push("dom");
transpileLib.push("dom.iterable");
}
/**
* A prefix to sources to handle sources as external modules
* > any file containing a top-level import or export is considered a module.
* > https://www.typescriptlang.org/docs/handbook/modules.html#introduction
*/
const srcPrefix = "export {};" + ts.sys.newLine;
/** Used in adjustSrcFileOffset */
const srcPrefixOffsets = {
offset: srcPrefix.length,
line: (srcPrefix.match(/\n/g) || []).length,
char: srcPrefix.length - (srcPrefix.lastIndexOf("\n") + 1),
};
let srcContent: string = "";
let declContent: string = "";
/** Check if external .ts files are converted. */
const sideInputsConverted = new Set<string>();
let builder: ts.BuilderProgram = null;
const sys = Object.create(ts.sys) as ts.System;
let rebuildTimer: RebuildTimer = null;
sys.getCurrentDirectory = function () {
return cwd;
};
sys.setTimeout = (callback: (...args: any[]) => void): any => {
if (rebuildTimer) {
throw new Error("Unexpected pending rebuildTimer");
}
rebuildTimer = { callback };
return rebuildTimer;
};
sys.clearTimeout = (timeoutId: any) => {
if (rebuildTimer === timeoutId) {
rebuildTimer = null;
return;
}
throw new Error("clearing unexpected tiemr");
};
sys.readFile = function (path, encoding) {
if (path === srcFilename) {
return srcPrefix + srcContent;
}
if (path === declFilename) {
return srcPrefix + declContent;
}
if (virtualFiles.has(path)) {
return virtualFiles.get(path);
}
return ts.sys.readFile(forwardTslabPath(cwd, path), encoding);
};
sys.directoryExists = function (path: string): boolean {
if (ts.sys.directoryExists(forwardTslabPath(cwd, path))) {
return true;
}
// Fake the existence of node_modules for tslab. This is necessary
// to import `tslab` when `node_modules` does not exist in `cwd`.
// See forwardTslabPath for details.
// TODO: Test this behavior.
return normalizeJoin(cwd, "node_modules") === path;
};
sys.fileExists = function (path: string): boolean {
if (ts.sys.fileExists(forwardTslabPath(cwd, path))) {
return true;
}
return virtualFiles.has(path);
};
sys.readDirectory = function (
path: string,
extensions?: readonly string[],
exclude?: readonly string[],
include?: readonly string[],
depth?: number
): string[] {
return ts.sys.readDirectory(
forwardTslabPath(cwd, path),
extensions,
exclude,
include,
depth
);
};
sys.writeFile = function (path, data) {
throw new Error("writeFile must not be called");
};
let notifyUpdateSrc: ts.FileWatcherCallback = null;
let notifyUpdateDecls: ts.FileWatcherCallback = null;
/** files for modules in memory. `srcPrefix` is prepended to values of virtualFiles. */
const virtualFiles = new Map<string, string>();
const fileWatchers = new Map<string, ts.FileWatcherCallback>();
sys.watchFile = (path, callback, pollingInterval?: number) => {
if (path === srcFilename) {
notifyUpdateSrc = callback;
return {
close: () => {},
};
}
if (path === declFilename) {
notifyUpdateDecls = callback;
return {
close: () => {},
};
}
// Note: File watchers for real files and virtual files are mixed here.
// This implementation is not 100% precise, though it causes a minor performance issue.
const cb = (fileName, eventKind) => {
sideInputsConverted.delete(fileName);
callback(fileName, eventKind);
if (options?._fileWatcher) {
options._fileWatcher(fileName, eventKind);
}
};
fileWatchers.set(path, cb);
const watcher = ts.sys.watchFile(path, cb, pollingInterval);
return {
close: () => {
fileWatchers.delete(path);
watcher.close();
},
};
};
// This takes several hundreds millisecs.
const host = ts.createWatchCompilerHost(
Array.from(rootFiles),
{
// module is ESNext, not ES2015, to support dynamic import.
module: ts.ModuleKind.ESNext,
moduleResolution: ts.ModuleResolutionKind.NodeJs,
esModuleInterop: true,
target: transpileTarget,
// We need to wrap entries with lib.*.d.ts before passing `lib` though it's not documented clearly.
// c.f.
// https://github.com/microsoft/TypeScript/blob/master/src/testRunner/unittests/config/commandLineParsing.ts
// https://github.com/microsoft/TypeScript/blob/master/src/compiler/commandLineParser.ts
lib: transpileLib.map((lib) => `lib.${lib}.d.ts`),
declaration: true,
newLine: ts.NewLineKind.LineFeed,
// Remove 'use strict' from outputs.
noImplicitUseStrict: true,
experimentalDecorators: true,
resolveJsonModule: true,
jsx: ts.JsxEmit.React,
typeRoots: getTypeRoots(),
// allowJs, checkJs and outDir are necessary to transpile .js files.
allowJs: true,
checkJs: true,
disableTopLevelAwait: true,
// tslab does not show error messages in d.ts (e.g. files in @types).
// This may improve the compile performance slightly.
skipLibCheck: true,
// rootDir is necessary to stabilize the paths of output files.
rootDir: cwd,
outDir,
},
sys,
null,
function (d: ts.Diagnostic) {
console.log(d.messageText);
},
function (d: ts.Diagnostic) {
// Drop watch status changes.
}
);
host.afterProgramCreate = function (b: ts.BuilderProgram) {
builder = b;
};
const watch = ts.createWatchProgram(host);
if (!builder) {
throw new Error("builder is not created");
}
return {
close,
convert,
inspect,
complete,
addModule,
};
function close() {
watch.close();
}
function convert(prevDecl: string, src: string): ConvertResult {
updateContent(prevDecl, src);
let declsFile = builder.getSourceFile(declFilename);
let srcFile = builder.getSourceFile(srcFilename);
const locals: ts.SymbolTable = srcFile.locals;
const keys = new Set<string>();
if (locals) {
locals.forEach((_: any, key: any) => {
keys.add(key);
});
}
if (keys.size > 0) {
// Export all local variables.
// TODO: Disallow "export" in the input.
const suffix = "\nexport {" + Array.from(keys).join(", ") + "}";
updateContent(prevDecl, src + suffix);
declsFile = builder.getSourceFile(declFilename);
srcFile = builder.getSourceFile(srcFilename);
}
asMutable(srcFile).parent = declsFile;
const diag = convertDiagnostics(
getPreEmitDiagnosticsWithDependencies(builder, srcFile)
);
if (diag.diagnostics.length > 0) {
return {
diagnostics: diag.diagnostics,
};
}
let output: string;
let declOutput: string;
let lastExpressionVar: string;
let sideOutputs: SideOutput[];
for (const dep of getAllSrcDependencies(builder, srcFile)) {
if (sideInputsConverted.has(dep)) {
continue;
}
if (dep !== srcFilename) {
sideInputsConverted.add(dep);
}
builder.emit(
builder.getSourceFile(dep),
(fileName: string, data: string) => {
if (fileName === dstFilename) {
output = data;
return;
}
if (fileName === dstDeclFilename) {
declOutput = data;
return;
}
if (!fileName.endsWith(".js")) {
return;
}
const rel = pathlib.relative(outDir, fileName);
if (rel.startsWith("..")) {
throw new Error("unexpected emit path: " + fileName);
}
if (!sideOutputs) {
sideOutputs = [];
}
sideOutputs.push({
path: normalizeJoin(cwd, rel),
data: esModuleToCommonJSModule(data, transpileTarget),
});
},
undefined,
undefined,
getCustomTransformers(
builder.getProgram().getTypeChecker(),
declsFile,
keys,
(name: string) => {
lastExpressionVar = name;
}
)
);
}
if (sideOutputs) {
sideOutputs.sort((a, b) => a.path.localeCompare(b.path));
}
declOutput += remainingDecls(
builder.getProgram().getTypeChecker(),
srcFile,
declsFile
);
return {
output: esModuleToCommonJSModule(output, transpileTarget),
declOutput,
diagnostics: diag.diagnostics,
hasToplevelAwait: diag.hasToplevelAwait,
sideOutputs,
lastExpressionVar,
};
}
function getTypeRoots(): string[] {
// If @types/node does not exist in the default type roots,
// use @types under tslab/node_modules (bug#10).
// TODO: Integration-test for this behavior.
const typeRoots =
ts.getDefaultTypeRoots(cwd, {
directoryExists: sys.directoryExists,
}) || [];
for (const root of typeRoots) {
if (ts.sys.fileExists(normalizeJoin(root, "node", "package.json"))) {
return typeRoots;
}
}
typeRoots.push(normalizeJoin(__dirname, "..", "node_modules", "@types"));
return typeRoots;
}
function inspect(
prevDecl: string,
src: string,
position: number
): ts.QuickInfo | undefined {
// c.f.
// https://github.com/microsoft/vscode/blob/master/extensions/typescript-language-features/src/features/hover.ts
updateContent(prevDecl, src);
let declsFile = builder.getSourceFile(declFilename);
let srcFile = builder.getSourceFile(srcFilename);
asMutable(srcFile).parent = declsFile;
const info = ts.getQuickInfoAtPosition(
srcFile,
builder.getProgram().getTypeChecker(),
cancellationToken,
position + srcPrefix.length
);
if (info && info.textSpan) {
info.textSpan.start -= srcPrefix.length;
}
return info;
}
function complete(
prevDecl: string,
src: string,
position: number
): CompletionInfo {
updateContent(prevDecl, src);
let declsFile = builder.getSourceFile(declFilename);
let srcFile = builder.getSourceFile(srcFilename);
asMutable(srcFile).parent = declsFile;
const pos = position + srcPrefix.length;
const info = getCompletionsAtPosition(
builder.getProgram(),
() => {
// ignore log messages
},
srcFile,
pos,
{},
undefined
);
if (info?.optionalReplacementSpan) {
info.optionalReplacementSpan.start -= srcPrefix.length;
}
const prev: ts.Node = ts.tslab.findPrecedingToken(pos, srcFile);
// Note: In contradiction to the docstring, findPrecedingToken may return prev with
// prev.end > pos (e.g. `members with surrounding` test case).
//
// Note: Be careful. node.pos != node.getStart().
// (e.g. `globals with prefix` test case)
if (prev && ts.isIdentifier(prev) && prev.end >= pos) {
return completionWithId(info, prev, srcFile);
}
const next: ts.Node = prev
? ts.tslab.findNextToken(prev, srcFile, srcFile)
: null;
if (
next &&
ts.isIdentifier(next) &&
next.getStart(srcFile) <= pos &&
pos <= next.end
) {
return completionWithId(info, next, srcFile);
}
let entries = info && info.entries ? info.entries.slice() : [];
entries.sort((a, b) => {
const ord = a.sortText.localeCompare(b.sortText);
return ord !== 0 ? ord : a.name.localeCompare(b.name);
});
const candidates = entries.map((e) => e.name);
return {
start: pos - srcPrefix.length,
end: pos - srcPrefix.length,
candidates,
original: info,
};
}
// TODO(yunabe): Probably, replace this with optionalReplacementSpan.
function completionWithId(
info: ts.CompletionInfo | undefined,
id: ts.Identifier,
srcFile: ts.SourceFile
): CompletionInfo {
let name = id.escapedText.toString();
let lower = name.toLowerCase();
let entries = info ? info.entries : [];
const candidates = entries
.map((e, index) => {
const key = (() => {
if (e.name.startsWith(name)) {
return "0";
}
const lname = e.name.toLowerCase();
if (lname.toLowerCase().startsWith(lower)) {
return "1";
}
if (lname.indexOf(lower) >= 0) {
return "2";
}
return "";
})();
if (key === "") {
return null;
}
return {
name: e.name,
sortKey: key + e.sortText,
index,
};
})
.filter((e) => !!e);
// Sort stably by using the original index.
candidates.sort((a, b) => {
const ord = a.sortKey.localeCompare(b.sortKey);
return ord !== 0 ? ord : a.index - b.index;
});
return {
start: id.getStart(srcFile) - srcPrefix.length,
end: id.end - srcPrefix.length,
candidates: candidates.map((e) => e.name),
original: info,
};
}
function remainingDecls(
checker: ts.TypeChecker,
srcSF: ts.SourceFile,
declsSF: ts.SourceFile
): string {
const declLocals = declsSF.locals as ts.SymbolTable;
const locals = srcSF.locals as ts.SymbolTable;
let keepMap = new Map<ts.Node, Set<ts.__String>>();
function addName(node: ts.Node, name: ts.__String) {
let set = keepMap.get(node);
if (!set) {
set = new Set();
keepMap.set(node, set);
}
set.add(name);
}
let valueNames = new Set<ts.__String>();
let anyVars = new Set<ts.__String>();
declLocals.forEach((sym, key) => {
let keep = checkKeepDeclType(checker, locals.get(key));
if (!keep.type && !keep.value) {
return;
}
sym.declarations.forEach((decl) => {
let node = decl as ts.Node;
while (node.parent !== declsSF) {
node = node.parent;
}
if (node.kind === ts.SyntaxKind.VariableStatement) {
if (keep.value) {
addName(node, key);
if (anyVars.has(key)) {
anyVars.delete(key);
}
valueNames.add(key);
}
return;
}
if (ts.isTypeAliasDeclaration(node)) {
if (keep.type) {
addName(node, key);
}
return;
}
if (ts.isClassDeclaration(node) || ts.isEnumDeclaration(node)) {
if (keep.type) {
if (keep.value) {
addName(node, key);
}
// If !keep.value, forget this class.
return;
}
// keep.value === true
if (!valueNames.has(node.name.escapedText)) {
anyVars.add(node.name.escapedText);
}
return;
}
if (ts.isImportDeclaration(node)) {
if (keep.type && keep.value) {
addName(node, key);
return;
}
let aliased = checker.getAliasedSymbol(sym);
if (!keep.value) {
// Here, keep.type == true.
if (aliased.flags & ts.SymbolFlags.Value) {
// Overwritten with a new value.
return;
}
if (aliased.flags && ts.SymbolFlags.Type) {
addName(node, key);
}
return;
}
// Here, keep.value == true and keep.type == false.
if (aliased.flags & ts.SymbolFlags.Type) {
// Overwritten with a new type.
if (
aliased.flags & ts.SymbolFlags.Value &&
!valueNames.has(aliased.escapedName)
) {
anyVars.add(aliased.escapedName);
}
return;
}
addName(node, key);
return;
}
if (ts.isFunctionDeclaration(node)) {
if (keep.value) {
addName(node, key);
}
return;
}
if (ts.isInterfaceDeclaration(node)) {
if (keep.type) {
addName(node, key);
}
}
// TODO: Support more kinds.
// console.log(
// ts.SyntaxKind[node.kind],
// ts.createPrinter({newLine: ts.NewLineKind.LineFeed}).printNode(ts.EmitHint.Unspecified, node, declsSF)
// );
});
});
let statements = [];
declsSF.statements.forEach((stmt) => {
let names = keepMap.get(stmt);
if (!names) {
return;
}
statements.push(stmt);
if (ts.isVariableStatement(stmt)) {
const decls: ts.VariableDeclaration[] = [];
stmt.declarationList.declarations.forEach((decl) => {
if (!ts.isIdentifier(decl.name)) {
// This must not happen.
return;
}
if (!names.has(decl.name.escapedText)) {
return;
}
decls.push(decl);
});
//TODO(yunabe): Stop using ts.createNodeArray, which is deprecated in TypeScript 4.
asMutable(stmt.declarationList).declarations = ts.createNodeArray(
decls
);
}
if (ts.isImportDeclaration(stmt)) {
keepNamesInImport(stmt, names);
}
// Do nothing for
// - TypeAliasDeclaration (No multiple specs)
// - FunctionDeclaration (ditto)
// - InterfaceDeclaration (ditto)
});
asMutable(declsSF).statements = ts.createNodeArray(statements);
let printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
let anyVarsDecls: string[] = [];
anyVars.forEach((name) => {
anyVarsDecls.push(`let ${name}: any;\n`);
});
return printer.printFile(declsSF) + anyVarsDecls.join("");
}
function checkKeepDeclType(
checker: ts.TypeChecker,
symb: ts.Symbol
): { value: boolean; type: boolean } {
const ret = { value: true, type: true };
if (!symb) {
return ret;
}
if (symb.flags & ts.SymbolFlags.Alias) {
symb = checker.getAliasedSymbol(symb);
}
if (symb.flags & ts.SymbolFlags.Value) {
ret.value = false;
}
if (symb.flags & ts.SymbolFlags.Type) {
ret.type = false;
}
return ret;
}
function updateContent(decls: string, src: string) {
declContent = decls;
srcContent = src;
builder = null;
// TODO: Notify updates only when src is really updated,
// unless there is another cache layer in watcher API.
notifyUpdateSrc(srcFilename, ts.FileWatcherEventKind.Changed);
notifyUpdateDecls(declFilename, ts.FileWatcherEventKind.Changed);
if (!rebuildTimer) {
throw new Error("rebuildTimer is not set properly");
}
rebuildTimer.callback();
rebuildTimer = null;
if (!builder) {
throw new Error("builder is not recreated");
}
}
/**
* Check if `d` is a diagnostic from a top-level await.
* This is used to allow top-level awaits (#16).
*/
function isTopLevelAwaitDiagnostic(
srcFile: ts.SourceFile,
d: ts.Diagnostic
): boolean {
if (d.code !== 1308 || srcFile == null) {
// https://github.com/microsoft/TypeScript/search?q=await_expression_is_only_allowed_within_an_async_function_1308
return false;
}
const await: ts.Node = ts.tslab.findPrecedingToken(
d.start + d.length,
srcFile
);
if (await.kind !== ts.SyntaxKind.AwaitKeyword) {
// This must not happen, though.
return false;
}
let isTop = true;
let parent = await.parent;
while (isTop && parent && parent !== srcFile) {
switch (parent.kind) {
case ts.SyntaxKind.ArrowFunction:
case ts.SyntaxKind.FunctionExpression:
case ts.SyntaxKind.FunctionDeclaration:
case ts.SyntaxKind.ClassDeclaration:
case ts.SyntaxKind.ModuleDeclaration:
// await is not top-level. This is invalid in tslab.
return false;
}
parent = parent.parent;
}
return true;
}
function adjustSrcFileOffset(
fileName: string,
offset: number
): DiagnosticPos {
const lineChar = ts.getLineAndCharacterOfPosition(
builder.getSourceFile(fileName),
offset
);
const pos = {
offset: offset,
line: lineChar.line,
character: lineChar.character,
};
if (fileName === srcFilename || virtualFiles.has(fileName)) {
pos.offset -= srcPrefixOffsets.offset;
pos.line -= srcPrefixOffsets.line;
pos.character -= srcPrefixOffsets.char;
}
return pos;
}
function convertDiagnostics(
input: readonly ts.Diagnostic[]
): {
diagnostics: Diagnostic[];
hasToplevelAwait: boolean;
} {
let hasToplevelAwait = false;
const diagnostics: Diagnostic[] = [];
const srcFile = builder.getSourceFile(srcFilename);
for (const d of input) {
if (!d.file) {
continue;
}
if (
d.file.fileName === srcFilename &&
isTopLevelAwaitDiagnostic(srcFile, d)
) {
hasToplevelAwait = true;
continue;
}
let fileName: string;
if (d.file.fileName !== srcFilename) {
const rel = pathlib.relative(cwd, d.file.fileName);
if (rel.startsWith("..")) {
continue;
}
fileName = rel;
}
const start = adjustSrcFileOffset(d.file.fileName, d.start);
const end = adjustSrcFileOffset(d.file.fileName, d.start + d.length);
if (typeof d.messageText === "string") {
diagnostics.push({
start,
end,
messageText: d.messageText.toString(),
category: d.category,
code: d.code,
fileName,
});
continue;
}
traverseDiagnosticMessageChain(
start,
end,
d.messageText,
diagnostics,
fileName
);
}
return { diagnostics, hasToplevelAwait };
}
function traverseDiagnosticMessageChain(
start: DiagnosticPos,
end: DiagnosticPos,
msg: ts.DiagnosticMessageChain,
out: Diagnostic[],
fileName?: string
) {
out.push({
start,
end,
messageText: msg.messageText,
category: msg.category,
code: msg.code,
});
if (!msg.next) {
return;
}
for (const child of msg.next) {
traverseDiagnosticMessageChain(start, end, child, out);
}
}
/**
* @param locals A set of names of declared variables.
* @param setLastExprName A callback to store the created name.
*/
function getCustomTransformers(
checker: ts.TypeChecker,
declsFile: ts.SourceFile,
locals: Set<string>,
setLastExprName: (name: string) => void
): ts.CustomTransformers {
const nullTransformationContext = ts.getNullTransformationContext();
return {
after: [after],
afterDeclarations: [afterDeclarations],
};
function createLastExprVar() {
const prefix = "tsLastExpr";
if (!locals.has(prefix)) {
return prefix;
}
let i = 0;
while (true) {
let name = `${prefix}${i}`;
if (!locals.has(name)) {
return name;
}
i++;
}
}
// Wrap identifiers to previous variables with exports.
function wrapPrevIdentifier(node: ts.Node) {
if (!ts.isIdentifier(node)) {
return ts.visitEachChild(
node,
wrapPrevIdentifier,
nullTransformationContext
);
}
if (
node.parent &&
ts.isPropertyAccessExpression(node.parent) &&
node.parent.name === node
) {
return node;
}
let prev = false;
for (const decl of checker.getSymbolAtLocation(node)?.declarations ??
[]) {
if (decl.getSourceFile() === declsFile) {
prev = true;
break;
}
}
if (!prev) {
return node;
}
return ts.createPropertyAccess(ts.createIdentifier("exports"), node);
}
function after(): (node: ts.SourceFile) => ts.SourceFile {
// Rewrite the output to store the last expression to a variable.
return (node: ts.SourceFile) => {
node = ts.visitEachChild(
node,
wrapPrevIdentifier,
nullTransformationContext
);
for (let i = node.statements.length - 1; i >= 0; i--) {
const stmt = node.statements[i];
if (ts.isExportDeclaration(stmt)) {
continue;
}
if (!ts.isExpressionStatement(stmt)) {
break;
}
const lastName = createLastExprVar();
let statements = node.statements.slice(0, i);
statements.push(
ts.createVariableStatement(
[ts.createModifier(ts.SyntaxKind.ExportKeyword)],
ts.createVariableDeclarationList(
[
ts.createVariableDeclaration(
lastName,
undefined,
stmt.expression
),
],
ts.NodeFlags.Const
)
)
);
setLastExprName(lastName);
statements.push(...node.statements.slice(i + 1));
asMutable(node).statements = ts.createNodeArray(statements);
break;
}
return node;
};
}
function afterDeclarations(): (node: ts.SourceFile) => ts.SourceFile {
// Delete all exports { ... }
return (node: ts.SourceFile) => {
const statements = [];
for (const stmt of node.statements) {
if (ts.isExportDeclaration(stmt)) {
continue;
}
statements.push(stmt);
}
asMutable(node).statements = ts.createNodeArray(statements);
return node;
};
}
}
function getModuleFilePath(name: string, meta?: CodeMetadata): string {
if (!isValidModuleName(name)) {
throw new Error("invalid module name: " + JSON.stringify(name));
}
let ext = options?.isJS ? ".js" : ".ts";
if (meta?.jsx) {
ext += "x";
}
return normalizeJoin(cwd, name + ext);
}
function addModule(
name: string,
content: string,
meta?: CodeMetadata
): Diagnostic[] {
return addModuleWithPath(getModuleFilePath(name, meta), content);
}
function addModuleWithPath(path: string, content: string): Diagnostic[] {
content = srcPrefix + content;
virtualFiles.set(path, content);
if (fileWatchers.has(path)) {
fileWatchers.get(path)(path, ts.FileWatcherEventKind.Changed);
}
builder = null;
rootFiles.add(path);
watch.updateRootFileNames(Array.from(rootFiles));
if (!rebuildTimer) {
throw new Error("rebuildTimer is not set properly");
}
rebuildTimer.callback();
rebuildTimer = null;
const file = builder.getSourceFile(path);
const diags = ts.getPreEmitDiagnostics(builder.getProgram(), file);
return convertDiagnostics(diags).diagnostics;
}
}
export function isCompleteCode(content: string): IsCompleteResult {
if (/(^|\n)\s*\n\s*$/.test(content)) {
// Force to process src if it ends with two white-space lines.
return { completed: true };
}
const src = ts.createSourceFile(
"tmp.ts",
content,
ts.ScriptTarget.Latest,
undefined,
ts.ScriptKind.TSX
);
const diags: ts.DiagnosticWithLocation[] = (src as any).parseDiagnostics;
if (!diags) {
return { completed: true };
}
const end = content.length;
for (const diag of diags) {
if (diag.start !== end || diag.length !== 0) {
continue;
}
if (typeof diag.messageText !== "string") {
continue;
}
if (diag.messageText.endsWith(" expected.")) {
const indent = indentOnEnter(content);
return { completed: false, indent };
}
}
return { completed: true };
}
function indentOnEnter(src: string): string {
// References:
// https://code.visualstudio.com/api/language-extensions/language-configuration-guide#indentation-rules
// https://github.com/microsoft/vscode/blob/master/extensions/typescript-language-features/src/features/languageConfiguration.ts
let line = src.match(/[^\n]*$/)[0];
let current = line.match(/^\s*/)[0];
if (/^((?!.*?\/\*).*\*\/)?\s*[\}\]].*$/.test(line)) {
// decrease indent
// TODO: Look into the indent of the previous line.
if (current.endsWith(" ")) {
return current.substring(0, current.length - 2);
}
if (current.endsWith("\t") || current.endsWith(" ")) {
return current.substring(0, current.length - 1);
}
return current;
}
if (/^((?!\/\/).)*(\{[^}"'`]*|\([^)"'`]*|\[[^\]"'`]*)$/.test(line)) {
// increase indent
return current + " ";
}
return current;
}
/*@internal*/
export function esModuleToCommonJSModule(
js: string,
target: ts.ScriptTarget
): string {
let out = ts.transpileModule(js, {
fileName: "custom.js",
compilerOptions: {
module: ts.ModuleKind.CommonJS,
esModuleInterop: true,
target,
newLine: ts.NewLineKind.LineFeed,
// Remove 'use strict' from outputs.
noImplicitUseStrict: true,
},
}).outputText;
return out;
}
/*@internal*/
export function keepNamesInImport(
im: ts.ImportDeclaration,
names: Set<ts.__String>
) {
if (!names || !names.size) {
throw new Error("names is empty of null");
}
let imc = im.importClause;
if (imc.name && !names.has(imc.name.escapedText)) {
delete asMutable(imc).name;
}
if (imc.namedBindings) {
if (ts.isNamespaceImport(imc.namedBindings)) {
if (!names.has(imc.namedBindings.name.escapedText)) {
delete asMutable(imc).namedBindings;
}
} else {
let elms: ts.ImportSpecifier[] = [];
imc.namedBindings.elements.forEach((elm) => {
if (names.has(elm.name.escapedText)) {
elms.push(elm);
}
});
if (elms.length) {
asMutable(imc.namedBindings).elements = ts.createNodeArray(elms);
} else {
delete asMutable(imc).namedBindings;
}
}
}
if (!imc.name && !imc.namedBindings) {
throw new Error("no symbol is included in names");
}
}
function getCompletionsAtPosition(
program: ts.Program,
log: (message: string) => void,
sourceFile: ts.SourceFile,
position: number,
preferences: ts.UserPreferences,
triggerCharacter?: ts.CompletionsTriggerCharacter
): ts.CompletionInfo {
const host: ts.LanguageServiceHost = {} as any;
return ts.tslab.getCompletionsAtPosition(
host,
program,
log,
sourceFile,
position,
preferences,
triggerCharacter
);
}
function forwardTslabPath(cwd: string, path: string): string {
const rel = pathlib.relative(
normalizeJoin(cwd, "node_modules", "tslab"),
path
);
if (rel.startsWith("..")) {
return path;
}
return normalizeJoin(pathlib.dirname(__dirname), rel);
}
function getPreEmitDiagnosticsWithDependencies(
builder: ts.BuilderProgram,
sourceFile: ts.SourceFile
): readonly ts.Diagnostic[] {
const files = [sourceFile];
for (const dep of getAllSrcDependencies(builder, sourceFile)) {
if (dep !== sourceFile.fileName) {
files.push(builder.getSourceFile(dep));
}
}
return ts.getPreEmitDiagnosticsOfFiles(builder.getProgram(), files);
}
/**
* Get a list of all .ts and .js file dependencies (including `sourceFile`) of `sourceFile`.
*/
function getAllSrcDependencies(
builder: ts.BuilderProgram,
sourceFile: ts.SourceFile
): string[] {
return builder
.getAllDependencies(sourceFile)
.filter(
(dep) =>
dep.endsWith(".js") || (dep.endsWith(".ts") && !dep.endsWith(".d.ts"))
);
} | the_stack |
import * as dotnetInteractiveInterfaces from "../dotnet-interactive/dotnet-interactive-interfaces";
import { Kernel, IKernelCommandHandler } from "../common/interactive/kernel";
import { TokenGenerator } from "../common/interactive/tokenGenerator";
import { signalTransportFactory } from "../dotnet-interactive/signalr-client";
import * as contracts from "../common/interfaces/contracts";
import { createDefaultClientFetch } from "./clientFetch";
import { clientSideKernelFactory } from "../dotnet-interactive/kernel-factory";
export interface KernelClientImplParameteres {
clientFetch: (input: RequestInfo, init: RequestInit) => Promise<Response>;
rootUrl: string;
kernelTransport: contracts.KernelTransport,
clientSideKernel: Kernel,
configureRequire: (config: any) => any
}
class ClientEventQueueManager {
private static eventPromiseQueues: Map<string, Array<Promise<void>>> = new Map();
static addEventToClientQueue(clientFetch: dotnetInteractiveInterfaces.ClientFetch, commandToken: string, eventEnvelope: contracts.KernelEventEnvelope) {
let promiseQueue = this.eventPromiseQueues.get(commandToken);
if (!promiseQueue) {
promiseQueue = [];
this.eventPromiseQueues.set(commandToken, promiseQueue);
}
const newPromise = clientFetch("publishEvent", {
method: 'POST',
cache: 'no-cache',
mode: 'cors',
body: JSON.stringify({ commandToken, eventEnvelope }),
headers: {
'Content-Type': 'application/json'
}
}).then(() => { });
promiseQueue.push(newPromise);
}
static async waitForAllEventsToPublish(commandToken: string): Promise<void> {
const promiseQueue = this.eventPromiseQueues.get(commandToken);
if (!promiseQueue) {
return;
}
await Promise.all(promiseQueue);
}
}
class InteractiveConsoleWrapper {
private globalConsole: Console;
constructor(private clientFetch: dotnetInteractiveInterfaces.ClientFetch, private commandToken: string) {
this.globalConsole = console;
}
public error(...args: any[]) {
this.redirectAndEnqueue(this.globalConsole.error, ...args);
}
public info(...args: any[]) {
this.redirectAndEnqueue(this.globalConsole.info, ...args);
}
public log(...args: any[]) {
this.redirectAndEnqueue(this.globalConsole.log, ...args);
}
private redirectAndEnqueue(target: (...args: any[]) => void, ...args: any[]) {
target(...args);
this.enqueueArgsAsEvents(...args);
}
private enqueueArgsAsEvents(...args: any[]) {
for (const arg of args) {
let mimeType: string;
let value: string;
if (typeof arg !== 'object' && !Array.isArray(arg)) {
mimeType = 'text/plain';
value = arg.toString();
} else {
mimeType = 'application/json';
value = JSON.stringify(arg);
}
const displayedValue: contracts.DisplayedValueProduced = {
formattedValues: [
{
mimeType,
value,
}
]
};
const eventEnvelope: contracts.KernelEventEnvelope = {
eventType: contracts.DisplayedValueProducedType,
event: displayedValue,
};
ClientEventQueueManager.addEventToClientQueue(this.clientFetch, this.commandToken, eventEnvelope);
}
}
}
export class KernelClientImpl implements dotnetInteractiveInterfaces.DotnetInteractiveClient {
private _clientFetch: (input: RequestInfo, init?: RequestInit) => Promise<Response>;
private _rootUrl: string;
private _kernelTransport: contracts.KernelTransport;
private _clientSideKernel: Kernel;
private _tokenGenerator: TokenGenerator;
private _configureRequire: (confing: any) => any;
constructor(parameters: KernelClientImplParameteres) {
this._clientFetch = parameters.clientFetch;
this._rootUrl = parameters.rootUrl;
this._kernelTransport = parameters.kernelTransport;
this._tokenGenerator = new TokenGenerator();
this._configureRequire = parameters.configureRequire;
this._clientSideKernel = parameters.clientSideKernel;
}
public configureRequire(config: any) {
return this._configureRequire(config);
}
public subscribeToKernelEvents(observer: contracts.KernelEventEnvelopeObserver): contracts.DisposableSubscription {
let subscription = this._kernelTransport.subscribeToKernelEvents(observer);
return subscription;
}
public registerCommandHandler(handler: IKernelCommandHandler): void {
this._clientSideKernel.registerCommandHandler(handler);
}
public async getVariable(kernelName: string, variableName: string): Promise<any> {
let response = await this._clientFetch(`variables/${kernelName}/${variableName}`,
{
method: 'GET',
cache: 'no-cache',
mode: 'cors'
});
let variable = await response.json();
return variable;
}
public async getVariables(variableRequest: dotnetInteractiveInterfaces.VariableRequest): Promise<dotnetInteractiveInterfaces.VariableResponse> {
let response = await this._clientFetch("variables", {
method: 'POST',
cache: 'no-cache',
mode: 'cors',
body: JSON.stringify(variableRequest),
headers: {
'Content-Type': 'application/json'
}
});
let variableBundle = await response.json();
return variableBundle;
}
public getResource(resource: string): Promise<Response> {
return this._clientFetch(`resources/${resource}`);
}
public getResourceUrl(resource: string): string {
return `${this._rootUrl}resources/${resource}`;
}
public getExtensionResource(extensionName: string, resource: string): Promise<Response> {
return this._clientFetch(`extension/${extensionName}/resources/${resource}`);
}
public getExtensionResourceUrl(extensionName: string, resource: string): string {
return `${this._rootUrl}extensions/${extensionName}/resources/${resource}`;
}
public async loadKernels(): Promise<void> {
let kernels = await this._clientFetch("kernels",
{
method: "GET",
cache: 'no-cache',
mode: 'cors'
});
let kernelNames = await kernels.json();
if (Array.isArray(kernelNames)) {
for (let i = 0; i < kernelNames.length; i++) {
let kernelName: string = kernelNames[i];
let kernelClient: dotnetInteractiveInterfaces.KernelClient = {
getVariable: (variableName: string): Promise<any> => {
return this.getVariable(kernelName, variableName);
},
submitCode: (code: string): Promise<string> => {
return this.submitCode(code, kernelName);
},
submitCommand: (commandType: string, command?: any): Promise<string> => {
return this.submitCommand(commandType, command, kernelName);
}
};
(<any>this)[kernelName] = kernelClient;
}
}
}
public async submitCode(code: string, targetKernelName: string = null): Promise<string> {
let token: string = this._tokenGenerator.GetNewToken();
let command: contracts.SubmitCode = {
code: code,
targetKernelName: targetKernelName
}
await this._kernelTransport.submitCommand({ command, commandType: contracts.SubmitCodeType, token });
return token;
}
public async submitCommand(commandType: string, command?: any, targetKernelName?: string): Promise<string> {
let token: string = this._tokenGenerator.GetNewToken();
if (!command) {
command = {};
}
if (targetKernelName) {
command.targetKernelName = targetKernelName;
}
await this._kernelTransport.submitCommand({ command, commandType: <any>commandType, token });
return token;
}
public getConsole(commandToken: string): any {
const wrappedConsole = new InteractiveConsoleWrapper(this._clientFetch, commandToken);
return wrappedConsole;
}
public markExecutionComplete(commandToken: string): Promise<void> {
return this._clientFetch("markExecutionComplete", {
method: 'POST',
cache: 'no-cache',
mode: 'cors',
body: JSON.stringify({ commandToken }),
headers: {
'Content-Type': 'application/json'
}
}).then(() => { });
}
public failCommand(err: any, commandToken: string) {
const failedEvent: contracts.CommandFailed = {
message: `${err}`
};
const eventEnvelope: contracts.KernelEventEnvelope = {
eventType: contracts.CommandFailedType,
event: failedEvent,
};
ClientEventQueueManager.addEventToClientQueue(this._clientFetch, commandToken, eventEnvelope);
}
public waitForAllEventsToPublish(commandToken: string): Promise<void> {
return ClientEventQueueManager.waitForAllEventsToPublish(commandToken);
}
}
export type DotnetInteractiveClientConfiguration = {
address: string,
clientFetch?: dotnetInteractiveInterfaces.ClientFetch,
kernelTransportFactory?: (rootUrl: string) => Promise<contracts.KernelTransport>,
clientSideKernelFactory?: (kernelTransport: contracts.KernelTransport) => Promise<Kernel>
};
function isConfiguration(config: any): config is DotnetInteractiveClientConfiguration {
return typeof config !== "string";
}
export async function createDotnetInteractiveClient(configuration: string | DotnetInteractiveClientConfiguration): Promise<dotnetInteractiveInterfaces.DotnetInteractiveClient> {
let rootUrl = "";
let clientFetch: dotnetInteractiveInterfaces.ClientFetch = null;
let kernelTransportFactory: (rootUrl: string) => Promise<contracts.KernelTransport> = null;
let kernelFactory: (kernelTransport: contracts.KernelTransport) => Promise<Kernel> = null;
if (isConfiguration(configuration)) {
rootUrl = configuration.address;
clientFetch = configuration.clientFetch;
kernelTransportFactory = configuration.kernelTransportFactory;
kernelFactory = configuration.clientSideKernelFactory;
} else {
rootUrl = configuration;
}
if (!rootUrl.endsWith("/")) {
rootUrl = `${rootUrl}/`;
}
if (!clientFetch) {
clientFetch = createDefaultClientFetch(rootUrl);
}
if (!kernelTransportFactory) {
kernelTransportFactory = signalTransportFactory;
}
if (!kernelFactory) {
kernelFactory = clientSideKernelFactory;
}
let transport = await kernelTransportFactory(rootUrl);
let clientSideKernel = await kernelFactory(transport);
let client = new KernelClientImpl({
clientFetch: clientFetch,
rootUrl,
kernelTransport: transport,
clientSideKernel,
configureRequire: (config: any) => {
return (<any>require).config(config) || require;
}
});
await client.loadKernels();
return client;
} | the_stack |
import * as test from "tape";
import SVGPathProperties from "../src/svg-path-properties";
import { inDelta } from "./inDelta";
test("getPointAtLength testing lineTo", function (test) {
const paths = [
{
path: "M0,50L500,50",
xValues: [0, 100, 200, 300, 400, 500],
yValues: [50, 50, 50, 50, 50, 50]
},
{
path: "M0,50L300,300",
xValues: [0, 59.999996185302734, 119.99999237060547, 180, 239.99998474121094, 300],
yValues: [50, 100, 150, 200, 249.99998474121094, 300]
},
{
path: "M0,50H300",
xValues: [0, 50, 100, 150, 200, 250, 300],
yValues: [50, 50, 50, 50, 50, 50, 50]
},
{
path: "M50,50h300",
xValues: [50, 100, 150, 200, 250, 300, 350],
yValues: [50, 50, 50, 50, 50, 50, 50]
},
{
path: "M50,0V200",
xValues: [50, 50, 50, 50, 50, 50, 50],
yValues: [
0,
33.33333206176758,
66.66666412353516,
100,
133.3333282470703,
166.6666717529297,
200
]
},
{
path: "M50,10v200",
xValues: [50, 50, 50, 50, 50, 50, 50],
yValues: [
10,
43.33333206176758,
76.66666412353516,
110,
143.3333282470703,
176.6666717529297,
210
]
},
{
path: "M50,50H300V200H50Z",
xValues: [50, 183.3333282470703, 300, 300, 166.66668701171875, 50, 50],
yValues: [50, 50, 66.66665649414062, 200, 200, 183.33331298828125, 50]
}
];
let properties: SVGPathProperties;
for (let i = 0; i < paths.length; i++) {
for (let j = 0; j < paths[i].xValues.length; j++) {
properties = new SVGPathProperties(paths[i].path);
const position = properties.getPointAtLength(
(j * properties.getTotalLength()) / (paths[i].xValues.length - 1)
);
test.true(inDelta(position.x, paths[i].xValues[j], 0.1));
test.true(inDelta(position.y, paths[i].yValues[j], 0.1));
}
test.deepEqual(
properties.getPointAtLength(10000000),
properties.getPointAtLength(properties.getTotalLength())
);
test.deepEqual(properties.getPointAtLength(-1), properties.getPointAtLength(0));
}
test.end();
});
test("getPointAtLength testing Quadratic Bézier", function (test) {
const paths = [
{
path: "M200,300 Q400,50 600,300",
xValues: [
200,
255.24655151367188,
321.72381591796875,
400.0000305175781,
478.2762756347656,
544.75341796875,
600
],
yValues: [
300,
240.47999572753906,
194.14747619628906,
175.0000762939453,
194.1474609375,
240.47999572753906,
300
]
},
{
path: "M0,100 Q50,-50 100,100 T200,100",
xValues: [
0,
25.60834312438965,
74.3916015625,
99.99996948242188,
125.60824584960938,
174.39163208007812,
200
],
yValues: [
100,
42.84862518310547,
42.84857940673828,
99.99991607666016,
157.15122985839844,
157.15139770507812,
100
]
},
{
path: "M0,100 q50,-150 100,0 t100,0",
xValues: [
0,
25.60834312438965,
74.3916015625,
99.99996948242188,
125.60824584960938,
174.39163208007812,
200
],
yValues: [
100,
42.84862518310547,
42.84857940673828,
99.99991607666016,
157.15122985839844,
157.15139770507812,
100
]
},
{
path: "M0,100 T200,100",
xValues: [
0,
33.33333206176758,
66.66666412353516,
100,
133.3333282470703,
166.6666717529297,
200
],
yValues: [100, 100, 100, 100, 100, 100, 100]
},
{
path: "M0,100 Q50,-50 100,100 T200,100 T300,100",
xValues: [
0,
50.00000762939453,
99.99998474121094,
149.9999542236328,
200.0000457763672,
250.00059509277344,
300
],
yValues: [
100,
25.000080108642578,
99.99996185302734,
174.9999237060547,
99.99983978271484,
25.00008201599121,
100
]
}
];
let properties: SVGPathProperties;
for (let i = 0; i < paths.length; i++) {
for (let j = 0; j < paths[i].xValues.length; j++) {
properties = new SVGPathProperties(paths[i].path);
const position = properties.getPointAtLength(
(j * properties.getTotalLength()) / (paths[i].xValues.length - 1)
);
test.true(inDelta(position.x, paths[i].xValues[j], 1));
test.true(inDelta(position.y, paths[i].yValues[j], 1));
}
test.deepEqual(
properties.getPointAtLength(10000000),
properties.getPointAtLength(properties.getTotalLength())
);
test.deepEqual(properties.getPointAtLength(-1), properties.getPointAtLength(0));
}
test.end();
});
test("getPointAtLength testing Cubic Bézier", function (test) {
const paths = [
{
path: "M200,200 C275,100 575,100 500,200",
xValues: [
200,
249.48426818847656,
309.1169738769531,
371.97515869140625,
435.7851257324219,
496.41815185546875,
500.0001220703125
],
yValues: [
200,
160.3770294189453,
137.765380859375,
126.64154052734375,
126.40363311767578,
144.5059051513672,
199.99981689453125
]
},
{
path: "M100,200 C100,100 250,100 250,200 S400,300 400,200",
xValues: [
100,
136.8885955810547,
213.11134338378906,
250,
286.88836669921875,
363.11114501953125,
400
],
yValues: [
200,
134.37181091308594,
134.3717498779297,
199.99984741210938,
265.6280517578125,
265.62835693359375,
200
]
},
{
path: "M100,200 S400,300 400,200",
xValues: [
100,
152.38723754882812,
205.42906188964844,
259.1198425292969,
313.48455810546875,
367.6199951171875,
400
],
yValues: [
200,
215.58023071289062,
228.76190185546875,
238.95660400390625,
244.3085174560547,
238.78338623046875,
200
]
},
{
path:
"M240,100C290,100,240,225,290,200S290,75,340,50S515,100,390,150S215,200,90,150S90,25,140,50S140,175,190,200S190,100,240,100",
xValues: [
240,
315.0015563964844,
441.4165954589844,
240.0000762939453,
38.58317947387695,
164.99853515625,
240
],
yValues: [
100,
121.3836898803711,
111.11810302734375,
187.49990844726562,
111.11775207519531,
121.38365936279297,
100
]
},
{
path:
"m240,100c50,0,0,125,50,100s0,-125,50,-150s175,50,50,100s-175,50,-300,0s0,-125,50,-100s0,125,50,150s0,-100,50,-100",
xValues: [
240,
315.0015563964844,
441.4165954589844,
240.0000762939453,
38.58317947387695,
164.99853515625,
240
],
yValues: [
100,
121.3836898803711,
111.11810302734375,
187.49990844726562,
111.11775207519531,
121.38365936279297,
100
]
}
];
let properties: SVGPathProperties;
for (let i = 0; i < paths.length; i++) {
for (let j = 0; j < paths[i].xValues.length; j++) {
properties = new SVGPathProperties(paths[i].path);
const position = properties.getPointAtLength(
(j * properties.getTotalLength()) / (paths[i].xValues.length - 1)
);
test.true(inDelta(position.x, paths[i].xValues[j], 1));
test.true(inDelta(position.y, paths[i].yValues[j], 1));
}
test.deepEqual(
properties.getPointAtLength(10000000),
properties.getPointAtLength(properties.getTotalLength())
);
test.deepEqual(properties.getPointAtLength(-1), properties.getPointAtLength(0));
}
test.end();
});
test("getPointAtLength bug testing", function (test) {
//Testing https://github.com/rveciana/svg-path-properties/issues/1
const properties = new SVGPathProperties(
"M 211.6687111164928,312.6478542077994 C 211.6687111164928,312.6478542077994 211.6687111164928,312.6478542077994 219,293"
);
const pos1 = properties.getPointAtLength(12);
const pos2 = properties.getPointAtLength(11.95);
const pos3 = properties.getPointAtLength(12.05);
test.true(inDelta(pos1.x, pos2.x, 0.1));
test.true(inDelta(pos1.x, pos3.x, 0.1));
test.true(inDelta(pos1.y, pos2.y, 0.1));
test.true(inDelta(pos1.y, pos3.y, 0.1));
test.end();
});
test("Testing getPointAtLength with straigh line bezier curve (bug)", function (test) {
//https://github.com/rveciana/svg-path-properties/issues/4
const pathData = new SVGPathProperties("M500,300Q425,325 350,350");
const pathLen = pathData.getTotalLength();
test.true(inDelta(pathLen, 158.11, 0.1)); //Gave undefined
let pos = pathData.getPointAtLength(0);
test.true(inDelta(pos.x, 500, 0.00001));
test.true(inDelta(pos.y, 300, 0.00001));
pos = pathData.getPointAtLength(pathLen);
test.true(inDelta(pos.x, 350, 0.00001));
test.true(inDelta(pos.y, 350, 0.00001));
test.end();
});
test("Testing with multiple rings", function (test) {
let properties = new SVGPathProperties("M100,100h100v100h-100Z m200,0h1v1h-1z");
test.deepEqual(properties.getPointAtLength(0), { x: 100, y: 100 });
test.deepEqual(properties.getPointAtLength(401), { x: 301, y: 100 });
properties = new SVGPathProperties("M100,100L200,100 M300,100L400,100");
test.deepEqual(properties.getPointAtLength(0), { x: 100, y: 100 });
test.deepEqual(properties.getPointAtLength(100), { x: 200, y: 100 });
test.deepEqual(properties.getPointAtLength(200), { x: 400, y: 100 });
test.deepEqual(properties.getPointAtLength(200), properties.getPointAtLength(500));
properties = new SVGPathProperties("M100,100 L101,100 M200,0 M500,600 M0,0L1,0L1,1L0,1Z");
test.deepEqual(properties.getPointAtLength(0), { x: 100, y: 100 });
test.deepEqual(properties.getPointAtLength(1), { x: 101, y: 100 });
test.deepEqual(properties.getPointAtLength(2), { x: 1, y: 0 });
test.end();
});
test("TestingDegenerated quadratic curves, issue 9", function (test) {
let properties = new SVGPathProperties("M60,20Q60,20 150,20");
test.deepEqual(properties.getPointAtLength(2), { x: 62, y: 20 });
test.equal(properties.getTotalLength(), 90);
properties = new SVGPathProperties("M60,20q0,0 90,0");
test.deepEqual(properties.getPointAtLength(2), { x: 62, y: 20 });
test.equal(properties.getTotalLength(), 90);
test.end();
});
test("Check null path, issue 35", function (test) {
let properties = new SVGPathProperties("M0, 0");
test.deepEqual(properties.getPointAtLength(0), { x: 0, y: 0 });
test.deepEqual(properties.getTangentAtLength(0), { x: 0, y: 0 });
test.deepEqual(properties.getPropertiesAtLength(0), { x: 0, y: 0, tangentX: 0, tangentY: 0 });
properties = new SVGPathProperties(null);
test.deepEqual(properties.getPointAtLength(0), { x: 0, y: 0 });
test.deepEqual(properties.getTangentAtLength(0), { x: 0, y: 0 });
test.deepEqual(properties.getPropertiesAtLength(0), { x: 0, y: 0, tangentX: 0, tangentY: 0 });
properties = new SVGPathProperties("");
test.deepEqual(properties.getPointAtLength(0), { x: 0, y: 0 });
test.deepEqual(properties.getTangentAtLength(0), { x: 0, y: 0 });
test.deepEqual(properties.getPropertiesAtLength(0), { x: 0, y: 0, tangentX: 0, tangentY: 0 });
properties = new SVGPathProperties("M10, 10");
test.deepEqual(properties.getPointAtLength(0), { x: 10, y: 10 });
test.deepEqual(properties.getTangentAtLength(0), { x: 0, y: 0 });
test.deepEqual(properties.getPropertiesAtLength(0), { x: 10, y: 10, tangentX: 0, tangentY: 0 });
test.end();
});
test("TestingDegenerated quadratic curves, issue 43", function (test) {
let properties = new SVGPathProperties(
"M224,32C153,195,69,366,76,544C77,567,97,585,105,606C133,683,137,768,175,840C193,875,225,902,250,932"
);
test.deepEqual(properties.getPointAtLength(300), { x: 111.7377391058728, y: 310.0179550672576 });
test.deepEqual(properties.getTangentAtLength(300), {
x: -0.29770950875462776,
y: 0.9546565080682572
});
test.deepEqual(properties.getPropertiesAtLength(300), {
x: 111.7377391058728,
y: 310.0179550672576,
tangentX: -0.29770950875462776,
tangentY: 0.9546565080682572
});
test.end();
});
//https://github.com/rveciana/svg-path-properties/pull/44/files
test("Testing first point of zero length fraction", function (test) {
let properties = new SVGPathProperties("M 0,0 l 0 0 l 10 10");
test.deepEqual(properties.getPointAtLength(0), { x: 0, y: 0 });
properties = new SVGPathProperties("M 1,1 L 1 1");
test.deepEqual(properties.getPointAtLength(0), { x: 1, y: 1 });
properties = new SVGPathProperties("M 1,1 l 0 0");
test.deepEqual(properties.getPointAtLength(0), { x: 1, y: 1 });
test.end();
}); | the_stack |
import log from "../../../log";
import assert from "../../../utils/assert";
import {
be2toi,
be3toi,
be4toi,
be8toi,
concat,
itobe4,
itobe8,
} from "../../../utils/byte_parsing";
import {
hexToBytes,
readNullTerminatedString,
} from "../../../utils/string_parsing";
import { MAX_32_BIT_INT } from "./constants";
import { createBox } from "./create_box";
import { getPlayReadyKIDFromPrivateData } from "./drm";
import {
getBoxContent,
getBoxOffsets,
} from "./get_box";
import {
getEMSG,
getMDIA,
getTRAF,
} from "./read";
/** Information related to a PSSH box. */
export interface IISOBMFFPSSHInfo {
/** Corresponding DRM's system ID, as an hexadecimal string. */
systemId : string;
/** Additional data contained in the PSSH Box. */
privateData : Uint8Array;
}
/**
* Inband event data when the data was contained inside an ISOBMFF box.
* The value and their name corresponds to the same one than in the
* corresponding ISOBMFF specification.
*/
export interface IEMSG {
schemeIdUri: string;
value: string;
timescale: number;
presentationTimeDelta: number;
eventDuration: number;
id: number;
messageData: Uint8Array;
}
/** Segment information from a parsed sidx. */
export interface ISidxSegment {
/** This segment start time, timescaled. */
time : number;
/** This segment difference between its end and start time, timescaled. */
duration : number;
/** Dividing `time` or `duration` with this value allows to obtain seconds. */
timescale : number;
/**
* Start and ending bytes (included) for the segment in the whole ISOBMFF
* buffer.
*/
range : [number, number];
}
/**
* Parse the sidx part (segment index) of an ISOBMFF buffer and construct a
* corresponding Array of available segments.
*
* Returns `null` if not found.
* @param {Uint8Array} buf
* @param {Number} sidxOffsetInWholeSegment
* @returns {Object|null} {Array.<Object>} - Information about each subsegment.
*/
function getSegmentsFromSidx(
buf : Uint8Array,
sidxOffsetInWholeSegment : number
) : ISidxSegment[]|null {
const sidxOffsets = getBoxOffsets(buf, 0x73696478 /* "sidx" */);
if (sidxOffsets === null) {
return null;
}
let offset = sidxOffsetInWholeSegment;
const boxSize = sidxOffsets[2] - sidxOffsets[0];
let cursor = sidxOffsets[1];
/* version(8) */
/* flags(24) */
/* reference_ID(32); */
/* timescale(32); */
const version = buf[cursor]; cursor += 4 + 4;
const timescale = be4toi(buf, cursor); cursor += 4;
/* earliest_presentation_time(32 / 64) */
/* first_offset(32 / 64) */
let time;
if (version === 0) {
time = be4toi(buf, cursor); cursor += 4;
offset += be4toi(buf, cursor) + boxSize; cursor += 4;
}
else if (version === 1) {
time = be8toi(buf, cursor); cursor += 8;
offset += be8toi(buf, cursor) + boxSize; cursor += 8;
}
else {
return null;
}
const segments : ISidxSegment[] = [];
/* reserved(16) */
/* reference_count(16) */
cursor += 2;
let count = be2toi(buf, cursor);
cursor += 2;
while (--count >= 0) {
/* reference_type(1) */
/* reference_size(31) */
/* segment_duration(32) */
/* sap..(32) */
const refChunk = be4toi(buf, cursor);
cursor += 4;
const refType = (refChunk & 0x80000000) >>> 31;
const refSize = (refChunk & 0x7FFFFFFF);
// when set to 1 indicates that the reference is to a sidx, else to media
if (refType === 1) {
throw new Error("sidx with reference_type `1` not yet implemented");
}
const duration = be4toi(buf, cursor);
cursor += 4;
// let sapChunk = be4toi(buf, cursor + 8);
cursor += 4;
// TODO(pierre): handle sap
// let startsWithSap = (sapChunk & 0x80000000) >>> 31;
// let sapType = (sapChunk & 0x70000000) >>> 28;
// let sapDelta = sapChunk & 0x0FFFFFFF;
segments.push({ time,
duration,
timescale,
range: [offset, offset + refSize - 1] });
time += duration;
offset += refSize;
}
return segments;
}
/**
* Parse track Fragment Decode Time to get a precize initial time for this
* segment (in the media timescale).
*
* Stops at the first tfdt encountered from the beginning of the file.
* Returns this time.
* `undefined` if not found.
* @param {Uint8Array} buffer
* @returns {Number | undefined}
*/
function getTrackFragmentDecodeTime(buffer : Uint8Array) : number | undefined {
const traf = getTRAF(buffer);
if (traf === null) {
return undefined;
}
const tfdt = getBoxContent(traf, 0x74666474 /* tfdt */);
if (tfdt === null) {
return undefined;
}
const version = tfdt[0];
return version === 1 ? be8toi(tfdt, 4) :
version === 0 ? be4toi(tfdt, 4) :
undefined;
}
/**
* Returns the "default sample duration" which is the default value for duration
* of samples found in a "traf" ISOBMFF box.
*
* Returns `undefined` if no "default sample duration" has been found.
* @param {Uint8Array} traf
* @returns {number|undefined}
*/
function getDefaultDurationFromTFHDInTRAF(traf : Uint8Array) : number | undefined {
const tfhd = getBoxContent(traf, 0x74666864 /* tfhd */);
if (tfhd === null) {
return undefined;
}
let cursor = /* version */ 1;
const flags = be3toi(tfhd, cursor); cursor += 3;
const hasBaseDataOffset = (flags & 0x000001) > 0;
const hasSampleDescriptionIndex = (flags & 0x000002) > 0;
const hasDefaultSampleDuration = (flags & 0x000008) > 0;
if (!hasDefaultSampleDuration) {
return undefined;
}
cursor += 4;
if (hasBaseDataOffset) {
cursor += 8;
}
if (hasSampleDescriptionIndex) {
cursor += 4;
}
const defaultDuration = be4toi(tfhd, cursor);
return defaultDuration;
}
/**
* Calculate segment duration approximation by additioning the duration from
* every samples in a trun ISOBMFF box.
*
* Returns `undefined` if we could not parse the duration.
* @param {Uint8Array} buffer
* @returns {number | undefined}
*/
function getDurationFromTrun(buffer : Uint8Array) : number | undefined {
const traf = getTRAF(buffer);
if (traf === null) {
return undefined;
}
const trun = getBoxContent(traf, 0x7472756E /* trun */);
if (trun === null) {
return undefined;
}
let cursor = 0;
const version = trun[cursor]; cursor += 1;
if (version > 1) {
return undefined;
}
const flags = be3toi(trun, cursor); cursor += 3;
const hasSampleDuration = (flags & 0x000100) > 0;
let defaultDuration : number | undefined = 0;
if (!hasSampleDuration) {
defaultDuration = getDefaultDurationFromTFHDInTRAF(traf);
if (defaultDuration === undefined) {
return undefined;
}
}
const hasDataOffset = (flags & 0x000001) > 0;
const hasFirstSampleFlags = (flags & 0x000004) > 0;
const hasSampleSize = (flags & 0x000200) > 0;
const hasSampleFlags = (flags & 0x000400) > 0;
const hasSampleCompositionOffset = (flags & 0x000800) > 0;
const sampleCounts = be4toi(trun, cursor); cursor += 4;
if (hasDataOffset) {
cursor += 4;
}
if (hasFirstSampleFlags) {
cursor += 4;
}
let i = sampleCounts;
let duration = 0;
while (i-- > 0) {
if (hasSampleDuration) {
duration += be4toi(trun, cursor);
cursor += 4;
} else {
duration += defaultDuration;
}
if (hasSampleSize) {
cursor += 4;
}
if (hasSampleFlags) {
cursor += 4;
}
if (hasSampleCompositionOffset) {
cursor += 4;
}
}
return duration;
}
/**
* Get timescale information from a movie header box. Found in init segments.
* `undefined` if not found or not parsed.
*
* This timescale is the default timescale used for segments.
* @param {Uint8Array} buffer
* @returns {Number | undefined}
*/
function getMDHDTimescale(buffer : Uint8Array) : number | undefined {
const mdia = getMDIA(buffer);
if (mdia === null) {
return undefined;
}
const mdhd = getBoxContent(mdia, 0x6D646864 /* "mdhd" */);
if (mdhd === null) {
return undefined;
}
let cursor = 0;
const version = mdhd[cursor]; cursor += 4;
return version === 1 ? be4toi(mdhd, cursor + 16) :
version === 0 ? be4toi(mdhd, cursor + 8) :
undefined;
}
/**
* Creates a PSSH box with the given systemId and data.
* @param {Array.<Object>} psshInfo
* @returns {Uint8Array}
*/
function createPssh({ systemId, privateData } : IISOBMFFPSSHInfo) : Uint8Array {
const _systemId = systemId.replace(/-/g, "");
assert(_systemId.length === 32);
return createBox("pssh", concat(4, // 4 initial zeroed bytes
hexToBytes(_systemId),
itobe4(privateData.length),
privateData));
}
/**
* Update ISOBMFF given to add a "pssh" box in the "moov" box for every content
* protection in the psshList array given.
* @param {Uint8Array} buf - the ISOBMFF file
* @param {Array.<Object>} psshList
* @returns {Uint8Array} - The new ISOBMFF generated.
*/
function patchPssh(buf : Uint8Array, psshList : IISOBMFFPSSHInfo[]) : Uint8Array {
if (psshList == null || psshList.length === 0) {
return buf;
}
const moovOffsets = getBoxOffsets(buf, 0x6D6F6F76 /* = "moov" */);
if (moovOffsets === null) {
return buf;
}
const moov = buf.subarray(moovOffsets[0], moovOffsets[2]);
const moovArr = [moov];
for (let i = 0; i < psshList.length; i++) {
moovArr.push(createPssh(psshList[i]));
}
const newmoov = updateBoxLength(concat(...moovArr));
return concat(buf.subarray(0, moovOffsets[0]),
newmoov,
buf.subarray(moovOffsets[2]));
}
/**
* Returns a new version of the given box with the size updated
* so it reflects its actual size.
*
* You can use this function after modifying a ISOBMFF box so its size is
* updated.
*
* /!\ Please consider that this function might mutate the given Uint8Array
* in place or might create a new one, depending on the current conditions.
* @param {Uint8Array} buf - The ISOBMFF box
* @returns {Uint8Array}
*/
function updateBoxLength(buf : Uint8Array) : Uint8Array {
const newLen = buf.length;
if (newLen < 4) {
throw new Error("Cannot update box length: box too short");
}
const oldSize = be4toi(buf, 0);
if (oldSize === 0) {
if (newLen > MAX_32_BIT_INT) {
const newBox = new Uint8Array(newLen + 8);
newBox.set(itobe4(1), 0);
newBox.set(buf.subarray(4, 8), 4);
newBox.set(itobe8(newLen + 8), 8);
newBox.set(buf.subarray(8, newLen), 16);
return newBox;
} else {
buf.set(itobe4(newLen), 0);
return buf;
}
} else if (oldSize === 1) {
if (newLen < 16) {
throw new Error("Cannot update box length: box too short");
}
buf.set(itobe8(newLen), 8);
return buf;
} else if (newLen <= MAX_32_BIT_INT) {
buf.set(itobe4(newLen), 0);
return buf;
} else {
const newBox = new Uint8Array(newLen + 8);
newBox.set(itobe4(1), 0);
newBox.set(buf.subarray(4, 8), 4);
newBox.set(itobe8(newLen + 8), 8);
newBox.set(buf.subarray(8, newLen), 16);
return newBox;
}
}
/**
* Parse EMSG boxes from ISOBMFF data.
* @param {Uint8Array} buf
* @returns {Array.<Object> | undefined}
*/
function parseEmsgBoxes(buffer: Uint8Array) : IEMSG[] | undefined {
const emsgs: IEMSG[] = [];
let offset = 0;
while (offset < buffer.length) {
const emsg = getEMSG(buffer, offset);
if (emsg === null) {
break;
}
const length = emsg.length;
offset += length;
const version = emsg[0];
if (version !== 0) {
log.warn("ISOBMFF: EMSG version " + version.toString() + " not supported.");
} else {
let position = 4; // skip version + flags
const { end: schemeIdEnd, string: schemeIdUri } =
readNullTerminatedString(emsg, position);
position = schemeIdEnd; // skip schemeIdUri
const { end: valueEnd, string: value } = readNullTerminatedString(emsg, position);
position = valueEnd; // skip value
const timescale = be4toi(emsg, position);
position += 4; // skip timescale
const presentationTimeDelta = be4toi(emsg, position);
position += 4; // skip presentationTimeDelta
const eventDuration = be4toi(emsg, position);
position += 4; // skip eventDuration
const id = be4toi(emsg, position);
position += 4; // skip id
const messageData = emsg.subarray(position, length);
const emsgData = { schemeIdUri,
value,
timescale,
presentationTimeDelta,
eventDuration,
id,
messageData };
emsgs.push(emsgData);
}
}
if (emsgs.length === 0) {
return undefined;
}
return emsgs;
}
export {
getMDHDTimescale,
getPlayReadyKIDFromPrivateData,
getTrackFragmentDecodeTime,
getDurationFromTrun,
getSegmentsFromSidx,
patchPssh,
updateBoxLength,
parseEmsgBoxes,
}; | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace FormContract {
interface Header extends DevKit.Controls.IHeader {
/** Date and time when the record was created. */
CreatedOn: DevKit.Controls.DateTime;
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
/** Select the contract's status. */
StatusCode: DevKit.Controls.OptionSet;
}
interface tab_general_Sections {
billing_information: DevKit.Controls.Section;
contract_type: DevKit.Controls.Section;
contract_line: DevKit.Controls.Section;
description: DevKit.Controls.Section;
header: DevKit.Controls.Section;
history: DevKit.Controls.Section;
notes: 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;
/** Enter the date when the contract becomes active. */
ActiveOn: DevKit.Controls.Date;
/** Select the customer account or contact to which the contract should be billed to provide a quick link to address and other customer details. */
BillingCustomerId: DevKit.Controls.Lookup;
/** Enter the end date for the contract's billing period to indicate the period for which the customer must pay for a service. */
BillingEndOn: DevKit.Controls.Date;
/** Select the billing schedule of the contract to indicate how often the customer should be invoiced. */
BillingFrequencyCode: DevKit.Controls.OptionSet;
/** Enter the start date for the contract's billing period to indicate the period for which the customer must pay for a service. This defaults to the same date that is selected in the Contract Start Date field. */
BillingStartOn: DevKit.Controls.Date;
/** Choose which address to send the invoice to. */
BillToAddress: DevKit.Controls.Lookup;
/** Shows the date and time when the contract was canceled. */
CancelOn: DevKit.Controls.Date;
/** Type additional information about the contract, such as the products or services provided to the customer. */
ContractLanguage: DevKit.Controls.String;
/** Shows the number for the contract for customer reference and searching capabilities. You cannot modify this number. */
ContractNumber: DevKit.Controls.String;
/** Select the level of service that should be provided for the contract based on your company's definition of bronze, silver, or gold. */
ContractServiceLevelCode: DevKit.Controls.OptionSet;
/** Choose the contract template that should be used to determine the terms of the contract, such as allotment type, available hours, and billing frequency. */
ContractTemplateId: DevKit.Controls.Lookup;
/** Select the customer account or contact to provide a quick link to additional customer details, such as address, phone number, activities, and orders. */
CustomerId: DevKit.Controls.Lookup;
/** Shows for the duration of the contract, in days, based on the contract start and end dates. */
Duration: DevKit.Controls.Integer;
/** Enter the date when the contract expires. */
ExpiresOn: DevKit.Controls.Date;
/** Shows the total charge to the customer for the service contract, calculated as the sum of values in the Net field for each existing contract line related to the contract. */
NetPrice: DevKit.Controls.Money;
notescontrol: DevKit.Controls.Note;
/** Choose the original contract that this contract was created from. This information is used to track renewal history. */
OriginatingContract: DevKit.Controls.Lookup;
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
/** Choose the address for the customer account or contact where the services are provided. */
ServiceAddress: DevKit.Controls.Lookup;
/** Type a title or name for the contract that indicates the purpose of the contract. */
Title: DevKit.Controls.String;
/** Shows the total discount applied to the contract's service charges, calculated as the sum of values in the Discount fields for each existing contract line related to the contract. */
TotalDiscount: DevKit.Controls.Money;
/** Shows the total service charge for the contract, before any discounts are credited. This is calculated as the sum of values in the Total Price field for each existing contract line related to the contract. */
TotalPrice: DevKit.Controls.Money;
/** Choose the local currency for the record to make sure budgets are reported in the correct currency. */
TransactionCurrencyId: DevKit.Controls.Lookup;
/** Select whether the discounts entered on contract lines for this contract should be entered as a percentage or a fixed dollar value. */
UseDiscountAsPercentage: DevKit.Controls.Boolean;
}
interface Grid {
Contract_lines: DevKit.Controls.Grid;
}
}
class FormContract extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Contract
* @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 Contract */
Body: DevKit.FormContract.Body;
/** The Header section of form Contract */
Header: DevKit.FormContract.Header;
/** The Grid of form Contract */
Grid: DevKit.FormContract.Grid;
}
namespace FormContract_Information {
interface tab_details_Sections {
contract_type: DevKit.Controls.Section;
description: DevKit.Controls.Section;
history: DevKit.Controls.Section;
}
interface tab_general_Sections {
billing_information: DevKit.Controls.Section;
header: DevKit.Controls.Section;
pricing: DevKit.Controls.Section;
}
interface tab_notes_Sections {
notes: DevKit.Controls.Section;
}
interface tab_details extends DevKit.Controls.ITab {
Section: tab_details_Sections;
}
interface tab_general extends DevKit.Controls.ITab {
Section: tab_general_Sections;
}
interface tab_notes extends DevKit.Controls.ITab {
Section: tab_notes_Sections;
}
interface Tabs {
details: tab_details;
general: tab_general;
notes: tab_notes;
}
interface Body {
Tab: Tabs;
/** Enter the date when the contract becomes active. */
ActiveOn: DevKit.Controls.Date;
/** Select the customer account or contact to which the contract should be billed to provide a quick link to address and other customer details. */
BillingCustomerId: DevKit.Controls.Lookup;
/** Enter the end date for the contract's billing period to indicate the period for which the customer must pay for a service. */
BillingEndOn: DevKit.Controls.Date;
/** Select the billing schedule of the contract to indicate how often the customer should be invoiced. */
BillingFrequencyCode: DevKit.Controls.OptionSet;
/** Enter the start date for the contract's billing period to indicate the period for which the customer must pay for a service. This defaults to the same date that is selected in the Contract Start Date field. */
BillingStartOn: DevKit.Controls.Date;
/** Choose which address to send the invoice to. */
BillToAddress: DevKit.Controls.Lookup;
/** Shows the date and time when the contract was canceled. */
CancelOn: DevKit.Controls.Date;
/** Type additional information about the contract, such as the products or services provided to the customer. */
ContractLanguage: DevKit.Controls.String;
/** Shows the number for the contract for customer reference and searching capabilities. You cannot modify this number. */
ContractNumber: DevKit.Controls.String;
/** Select the level of service that should be provided for the contract based on your company's definition of bronze, silver, or gold. */
ContractServiceLevelCode: DevKit.Controls.OptionSet;
/** Choose the contract template that should be used to determine the terms of the contract, such as allotment type, available hours, and billing frequency. */
ContractTemplateId: DevKit.Controls.Lookup;
/** Select the customer account or contact to provide a quick link to additional customer details, such as address, phone number, activities, and orders. */
CustomerId: DevKit.Controls.Lookup;
/** Shows for the duration of the contract, in days, based on the contract start and end dates. */
Duration: DevKit.Controls.Integer;
/** Enter the date when the contract expires. */
ExpiresOn: DevKit.Controls.Date;
/** Shows the total charge to the customer for the service contract, calculated as the sum of values in the Net field for each existing contract line related to the contract. */
NetPrice: DevKit.Controls.Money;
notescontrol: DevKit.Controls.Note;
/** Choose the original contract that this contract was created from. This information is used to track renewal history. */
OriginatingContract: DevKit.Controls.Lookup;
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
/** Choose the address for the customer account or contact where the services are provided. */
ServiceAddress: DevKit.Controls.Lookup;
/** Type a title or name for the contract that indicates the purpose of the contract. */
Title: DevKit.Controls.String;
/** Shows the total discount applied to the contract's service charges, calculated as the sum of values in the Discount fields for each existing contract line related to the contract. */
TotalDiscount: DevKit.Controls.Money;
/** Shows the total service charge for the contract, before any discounts are credited. This is calculated as the sum of values in the Total Price field for each existing contract line related to the contract. */
TotalPrice: DevKit.Controls.Money;
/** Choose the local currency for the record to make sure budgets are reported in the correct currency. */
TransactionCurrencyId: DevKit.Controls.Lookup;
/** Select whether the discounts entered on contract lines for this contract should be entered as a percentage or a fixed dollar value. */
UseDiscountAsPercentage: DevKit.Controls.Boolean;
}
}
class FormContract_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Contract_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 Contract_Information */
Body: DevKit.FormContract_Information.Body;
}
class ContractApi {
/**
* DynamicsCrm.DevKit ContractApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Unique identifier of the account with which the contract is associated. */
AccountId: DevKit.WebApi.LookupValueReadonly;
/** Enter the date when the contract becomes active. */
ActiveOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Type of allotment that the contract supports. */
AllotmentTypeCode: DevKit.WebApi.OptionSetValue;
/** Unique identifier of the account to which the contract is to be billed. */
BillingAccountId: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the contact to whom the contract is to be billed. */
BillingContactId: DevKit.WebApi.LookupValueReadonly;
billingcustomerid_account: DevKit.WebApi.LookupValue;
billingcustomerid_contact: DevKit.WebApi.LookupValue;
/** Enter the end date for the contract's billing period to indicate the period for which the customer must pay for a service. */
BillingEndOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Select the billing schedule of the contract to indicate how often the customer should be invoiced. */
BillingFrequencyCode: DevKit.WebApi.OptionSetValue;
/** Enter the start date for the contract's billing period to indicate the period for which the customer must pay for a service. This defaults to the same date that is selected in the Contract Start Date field. */
BillingStartOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Choose which address to send the invoice to. */
BillToAddress: DevKit.WebApi.LookupValue;
/** Shows the date and time when the contract was canceled. */
CancelOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValueReadonly;
/** Unique identifier of the contact specified for the contract. */
ContactId: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the contract. */
ContractId: DevKit.WebApi.GuidValue;
/** Type additional information about the contract, such as the products or services provided to the customer. */
ContractLanguage: DevKit.WebApi.StringValue;
/** Shows the number for the contract for customer reference and searching capabilities. You cannot modify this number. */
ContractNumber: DevKit.WebApi.StringValue;
/** Select the level of service that should be provided for the contract based on your company's definition of bronze, silver, or gold. */
ContractServiceLevelCode: DevKit.WebApi.OptionSetValue;
/** Shows the abbreviation of the contract template selected when the contract is created. */
ContractTemplateAbbreviation: DevKit.WebApi.StringValueReadonly;
/** Choose the contract template that should be used to determine the terms of the contract, such as allotment type, available hours, and billing frequency. */
ContractTemplateId: DevKit.WebApi.LookupValue;
/** 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;
customerid_account: DevKit.WebApi.LookupValue;
customerid_contact: DevKit.WebApi.LookupValue;
/** Shows for the duration of the contract, in days, based on the contract start and end dates. */
Duration: DevKit.WebApi.IntegerValueReadonly;
/** Days of the week and times during which customer service support is available for the duration of the contract. */
EffectivityCalendar: DevKit.WebApi.StringValue;
/** The primary email address for the entity. */
EmailAddress: 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;
/** Enter the date when the contract expires. */
ExpiresOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Sequence number of the import that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Shows who last updated the record. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was modified. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who last updated the record on behalf of another user. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the total charge to the customer for the service contract, calculated as the sum of values in the Net field for each existing contract line related to the contract. */
NetPrice: DevKit.WebApi.MoneyValueReadonly;
/** Value of the Net Price in base currency. */
NetPrice_Base: DevKit.WebApi.MoneyValueReadonly;
/** Choose the original contract that this contract was created from. This information is used to track renewal history. */
OriginatingContract: DevKit.WebApi.LookupValue;
/** Date and time that the record was migrated. */
OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */
OwnerId_systemuser: DevKit.WebApi.LookupValue;
/** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */
OwnerId_team: DevKit.WebApi.LookupValue;
/** Unique identifier for the business unit that owns the record */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the team that owns the record. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the user that owns the record. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** Choose the address for the customer account or contact where the services are provided. */
ServiceAddress: DevKit.WebApi.LookupValue;
/** Shows whether the contract is in draft, invoiced, active, on hold, canceled, or expired. You can edit only the contracts that are in draft status. */
StateCode: DevKit.WebApi.OptionSetValue;
/** Select the contract's status. */
StatusCode: DevKit.WebApi.OptionSetValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Type a title or name for the contract that indicates the purpose of the contract. */
Title: DevKit.WebApi.StringValue;
/** Shows the total discount applied to the contract's service charges, calculated as the sum of values in the Discount fields for each existing contract line related to the contract. */
TotalDiscount: DevKit.WebApi.MoneyValueReadonly;
/** Value of the Total Discount in base currency. */
TotalDiscount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the total service charge for the contract, before any discounts are credited. This is calculated as the sum of values in the Total Price field for each existing contract line related to the contract. */
TotalPrice: DevKit.WebApi.MoneyValueReadonly;
/** Value of the Total Price in base currency. */
TotalPrice_Base: DevKit.WebApi.MoneyValueReadonly;
/** Choose the local currency for the record to make sure budgets are reported in the correct currency. */
TransactionCurrencyId: DevKit.WebApi.LookupValue;
/** Select whether the discounts entered on contract lines for this contract should be entered as a percentage or a fixed dollar value. */
UseDiscountAsPercentage: DevKit.WebApi.BooleanValue;
/** Time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
/** Version Number */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
}
}
declare namespace OptionSet {
namespace Contract {
enum AllotmentTypeCode {
/** 3 */
Coverage_Dates,
/** 1 */
Number_of_Cases,
/** 2 */
Time
}
enum BillingFrequencyCode {
/** 5 */
Annually,
/** 2 */
Bimonthly,
/** 1 */
Monthly,
/** 3 */
Quarterly,
/** 4 */
Semiannually
}
enum ContractServiceLevelCode {
/** 3 */
Bronze,
/** 1 */
Gold,
/** 2 */
Silver
}
enum StateCode {
/** 2 */
Active,
/** 4 */
Canceled,
/** 0 */
Draft,
/** 5 */
Expired,
/** 1 */
Invoiced,
/** 3 */
On_Hold
}
enum StatusCode {
/** 3 */
Active,
/** 5 */
Canceled,
/** 1 */
Draft,
/** 6 */
Expired,
/** 2 */
Invoiced,
/** 4 */
On_Hold
}
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':['Contract','Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import Stats from 'three/examples/jsm/libs/stats.module.js';
import { GUI } from 'dat.GUI';
import { SimpleDropzone } from 'simple-dropzone';
import { ThreeRenderer } from './three_renderer';
import { PathtracingRenderer, Loader } from '../lib/index';
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import * as Assets from '../../assets/asset_index';
if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
alert('The File APIs are not fully supported in this browser.');
}
class App {
_gui: any;
_stats: any | null;
canvas: HTMLCanvasElement;
canvas_three: HTMLCanvasElement;
canvas_pt: HTMLCanvasElement;
spinner: Element;
container: HTMLElement | null;
scene: string;
ibl: string;
camera: THREE.PerspectiveCamera;
controls: OrbitControls;
renderer: any;
three_renderer: ThreeRenderer;
useControls: true;
pathtracing = true;
autoScaleScene = false;
autoRotate = false;
interactionScale = 0.2;
sceneBoundingBox: THREE.Box3;
constructor() {
this.scene = Assets.getScene(0).name;
this.ibl = Assets.getIBL(0).name;
this.container = document.createElement('div');
document.body.appendChild(this.container);
this.canvas = document.createElement('canvas');
this.container.appendChild(this.canvas);
this.spinner = document.getElementsByClassName('spinner')[0];
this.canvas_pt = document.createElement('canvas');
this.canvas_three = document.createElement('canvas');
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
this.canvas_pt.width = window.innerWidth;
this.canvas_pt.height = window.innerHeight;
this.canvas_three.width = window.innerWidth;
this.canvas_three.height = window.innerHeight;
this._stats = new (Stats as any)();
this._stats.domElement.style.position = 'absolute';
this._stats.domElement.style.top = '0px';
this._stats.domElement.style.cursor = "default";
this._stats.domElement.style.webkitUserSelect = "none";
this._stats.domElement.style.MozUserSelect = "none";
this.container.appendChild(this._stats.domElement);
let aspect = window.innerWidth / window.innerHeight;
this.camera = new THREE.PerspectiveCamera(45, aspect, 0.01, 1000);
this.controls = new OrbitControls(this.camera, this.canvas);
this.controls.screenSpacePanning = true;
this.controls.addEventListener('change', () => {
this.camera.updateMatrixWorld();
this.renderer.resetAccumulation();
});
this.controls.addEventListener('start', () => {
this["pixelRatio"] = this.renderer.pixelRatio;
this.renderer.pixelRatio = this.interactionScale;
});
this.controls.addEventListener('end', () => {
this.renderer.pixelRatio = this["pixelRatio"];
});
this.controls.mouseButtons = {
LEFT: THREE.MOUSE.ROTATE,
MIDDLE: THREE.MOUSE.PAN,
RIGHT: THREE.MOUSE.DOLLY
}
this.renderer = new PathtracingRenderer({ canvas: this.canvas_pt});
this.three_renderer = new ThreeRenderer({ canvas: this.canvas_three, powerPreference: "high-performance", alpha: true });
this.renderer.pixelRatio = 0.5;
// this.renderer.iblRotation = 180.0;
this.renderer.exposure = 1.5;
this.renderer.maxBounces = 8;
window.addEventListener('resize', () => {
this.resize();
}, false);
const input = document.createElement('input');
const dropCtrl = new SimpleDropzone(this.canvas, input);
dropCtrl.on('drop', ({ files }) => this.load(files));
dropCtrl.on('dropstart', () => this.showSpinner());
dropCtrl.on('droperror', () => this.hideSpinner());
this.container.addEventListener('dragover', function (e) {
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
});
this.initUI();
this.hideSpinner();
}
private load(fileMap) {
const files : [string, File][] = Array.from(fileMap)
if (files.length == 1 && files[0][1].name.match(/\.hdr$/)) {
console.log("loading HDR...");
// const url = URL.createObjectURL(e.dataTransfer.getData('text/html'));
Loader.loadIBL(URL.createObjectURL(files[0][1])).then((ibl) => {
this.renderer.setIBL(ibl);
this.three_renderer.setIBL(ibl);
const iblNode = document.getElementById("ibl-info");
iblNode.innerHTML = '';
this.hideSpinner();
});
} else {
// this.showSpinner();
const scenePromise = Loader.loadSceneFromBlobs(files, this.autoScaleScene);
const iblPromise = Loader.loadIBL(Assets.getIBLByName(this.ibl).url);
Promise.all([scenePromise, iblPromise]).then(([gltf, ibl]) => {
this.sceneBoundingBox = new THREE.Box3().setFromObject(gltf.scene);
this.updateCameraFromBoundingBox();
this.renderer.setIBL(ibl);
this.renderer.setScene(gltf.scene, gltf).then(() => {
this.startPathtracing();
this.hideSpinner();
document.getElementById("scene-info").innerHTML = '';
});
this.three_renderer.setScene(new THREE.Scene().add(gltf.scene));
this.three_renderer.setIBL(ibl);
});
}
}
private startRasterizer() {
this.stopPathtracing();
this.three_renderer.render(this.camera, () => {
var destCtx = this.canvas.getContext("2d");
destCtx.drawImage(this.canvas_three, 0, 0);
});
}
private stopRasterizer() {
this.three_renderer.stopRendering();
}
private stopPathtracing() {
this.renderer.stopRendering();
}
private startPathtracing() {
this.stopRasterizer();
this.renderer.render(this.camera, -1, () => {
this.controls.update();
this._stats.update();
if (this.pathtracing) {
var destCtx = this.canvas.getContext("2d");
destCtx.drawImage(this.canvas_pt, 0, 0);
}
})
}
private resize() {
console.log("resizing", window.innerWidth, window.innerHeight);
let res = [window.innerWidth, window.innerHeight];
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
this.canvas_pt.width = window.innerWidth;
this.canvas_pt.height = window.innerHeight;
this.canvas_three.width = window.innerWidth;
this.canvas_three.height = window.innerHeight;
this.renderer.resize(window.innerWidth, window.innerHeight);
this.three_renderer.resize(window.innerWidth, window.innerHeight);
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
}
private updateCameraFromBoundingBox() {
this.controls.reset();
let diag = this.sceneBoundingBox.max.distanceTo(this.sceneBoundingBox.min);
let dist = diag * 2 / Math.tan(45.0 * Math.PI / 180.0);
let center = new THREE.Vector3();
this.sceneBoundingBox.getCenter(center);
let pos = center.clone();
pos.add(new THREE.Vector3(0,0, dist));
pos.add(new THREE.Vector3(0,diag, 0));
this.camera.position.set(pos.x, pos.y, pos.z);
this.camera.lookAt(center);
this.camera.updateMatrixWorld();
this.controls.update();
}
private loadScene(sceneUrl) {
const scenePromise = Loader.loadSceneFromUrl(sceneUrl, this.autoScaleScene);
const iblPromise = Loader.loadIBL(Assets.getIBLByName(this.ibl).url);
Promise.all([scenePromise, iblPromise]).then(([gltf, ibl]) => {
this.sceneBoundingBox = new THREE.Box3().setFromObject(gltf.scene);
this.updateCameraFromBoundingBox();
this.renderer.setIBL(ibl);
this.renderer.setScene(gltf.scene, gltf).then(() => {
if (this.pathtracing)
this.startPathtracing();
});
this.three_renderer.setScene(new THREE.Scene().add(gltf.scene));
this.three_renderer.setIBL(ibl);
if (!this.pathtracing) {
this.startRasterizer();
}
});
}
initUI() {
if (this._gui)
return;
this._gui = new GUI();
this._gui.domElement.classList.add("hidden");
this._gui.width = 300;
this._gui.add(this, 'pathtracing').name('Use Pathtracing').onChange((value) => {
if (value == false) {
this.startRasterizer();
} else {
this.startPathtracing();
}
});
this._gui.add(this, "scene", Assets.scene_names).name('Scene').onChange((value) => {
const sceneInfo = Assets.getSceneByName(value);
console.log(`Loading ${sceneInfo.name}`);
this.loadScene(sceneInfo.url);
this.setSceneInfo(sceneInfo);
}).setValue(Assets.getScene(0).name);
this._gui.add(this, 'autoScaleScene').name('Autoscale Scene');
this._gui.add(this, "ibl", Assets.ibl_names).name('IBL').onChange((value) => {
const iblInfo = Assets.getIBLByName(value);
console.log(`Loading ${iblInfo.name}`);
Loader.loadIBL(iblInfo.url).then((ibl) => {
this.renderer.setIBL(ibl);
this.three_renderer.setIBL(ibl);
this.setIBLInfo(iblInfo);
});
}).setValue(Assets.getIBL(0).name);
this._gui.add(this.renderer, 'iblRotation').name('IBL Rotation').min(-180.0).max(180.0).step(0.1);
// this._gui.add(_this.renderer, 'iblSampling').name('IBL Sampling');
this._gui.add(this.renderer, 'exposure').name('Display Exposure').min(0).max(3).step(0.01).onChange((value) => {
this.three_renderer.exposure = value;
});
this._gui.add(this, 'autoRotate').name('Auto Rotate').onChange((value) => {
this.controls.autoRotate = value;
this.renderer.resetAccumulation();
});
this._gui.add(this.renderer, 'debugMode', this.renderer.debugModes).name('Debug Mode');
this._gui.add(this.renderer, 'tonemapping', this.renderer.tonemappingModes).name('Tonemapping').onChange(val => {
this.three_renderer.tonemapping = val;
});
this._gui.add(this.renderer, 'enableGamma').name('Gamma');
this._gui.add(this.renderer, 'pixelRatio').name('Pixel Ratio').min(0.1).max(1.0);
this._gui.add(this, 'interactionScale').name('Interaction Ratio').min(0.1).max(1.0).step(0.1);
this._gui.add(this.renderer, 'useIBL').name('Use IBL').onChange((value) => {
this.three_renderer.useIBL(value);
});
this._gui.add(this.renderer, 'showBackground').name('Show Background').onChange((value) => {
this.three_renderer.showBackground = value;
});
this.backgroundColor = [0, 0, 0];
this._gui.addColor(this, 'backgroundColor').name('Background Color').onChange((value) => {
this.renderer.backgroundColor = [value[0]/255.0, value[1]/255.0, value[2]/255.0];
this.three_renderer.backgroundColor = [value[0]/255.0, value[1]/255.0, value[2]/255.0];
});
this._gui.add(this.renderer, 'forceIBLEval').name('Force IBL Eval');
this._gui.add(this.renderer, 'maxBounces').name('Bounce Depth').min(0).max(32).step(1);
this._gui.add(this.renderer, 'sheenG', this.renderer.sheenGModes).name('Sheen G');
this._gui.add(this.renderer, 'rayEps').name('Ray Offset');
let reload_obj = {
reload: () => {
console.log("Reload");
this.loadScene(Assets.getSceneByName(this.scene).url);
}
};
this._gui.add(reload_obj, 'reload').name('Reload');
const center_obj = {
centerView: () => {
console.log("center view");
if (this.controls) {
let center = new THREE.Vector3();
this.sceneBoundingBox.getCenter(center);
this.controls.target = center;
this.controls.update();
this.renderer.resetAccumulation();
}
}
};
this._gui.add(center_obj, 'centerView').name('Center View');
const save_img = {
save_img: () => {
console.log("Save Image");
var dataURL = this.canvas.toDataURL('image/png');
const link = document.createElement("a");
link.download = 'capture.png';
link.href = dataURL;
link.click();
}
};
this._gui.add(save_img, 'save_img').name('Save PNG');
}
showSpinner() {
this.spinner.style.display = '';
}
hideSpinner() {
this.spinner.style.display = 'none';
}
setIBLInfo(ibl: any) {
const html = `
IBL: ${ibl.name} by ${ibl.author}
from <a href="${ibl.source_url}"> ${ibl.source} </a>
<a href="${ibl.license_url}">(${ibl.license})</a>
`;
document.getElementById("ibl-info").innerHTML = html;
}
setSceneInfo(scene: any) {
const html = `
Scene: ${scene.name} by ${scene.author}
from <a href="${scene.source_url}"> ${scene.source} </a>
<a href="${scene.license_url}">(${scene.license})</a>
`;
document.getElementById("scene-info").innerHTML = html;
}
}
let app = new App(); | the_stack |
* ---------------------------------------------------------------
* ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API ##
* ## ##
* ## AUTHOR: acacode ##
* ## SOURCE: https://github.com/acacode/swagger-typescript-api ##
* ---------------------------------------------------------------
*/
/**
* A user or organization
*/
export interface Actor {
avatar_url?: string;
bio?: string;
/** The website URL from the profile page */
blog?: string;
collaborators?: number;
company?: string;
/** ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ */
created_at?: string;
disk_usage?: number;
/** Note: The returned email is the user’s publicly visible email address (or null if the user has not specified a public email address in their profile). */
email?: string;
followers?: number;
followers_url?: string;
following?: number;
following_url?: string;
gists_url?: string;
gravatar_id?: string;
hireable?: boolean;
html_url?: string;
id?: number;
location?: string;
/** The account username */
login?: string;
/** The full account name */
name?: string;
organizations_url?: string;
owned_private_repos?: number;
plan?: { collaborators?: number; name?: string; private_repos?: number; space?: number };
private_gists?: number;
public_gists?: number;
public_repos?: number;
starred_url?: string;
subscriptions_url?: string;
total_private_repos?: number;
type?: "User" | "Organization";
/** ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ */
updated_at?: string;
url?: string;
}
export interface Asset {
content_type?: string;
created_at?: string;
download_count?: number;
id?: number;
label?: string;
name?: string;
size?: number;
state?: string;
updated_at?: string;
/** A GitHub user */
uploader?: User;
url?: string;
}
export interface AssetPatch {
label?: string;
name: string;
}
export type Assets = Asset[];
export type Assignees = User[];
export interface Blob {
content?: string;
encoding?: "utf-8" | "base64";
sha?: string;
size?: number;
}
export interface Blobs {
sha?: string;
}
export interface Branch {
_links?: { html?: string; self?: string };
commit?: {
author?: User;
commit?: {
author?: { date?: string; email?: string; name?: string };
committer?: { date?: string; email?: string; name?: string };
message?: string;
tree?: { sha?: string; url?: string };
url?: string;
};
committer?: User;
parents?: { sha?: string; url?: string }[];
sha?: string;
url?: string;
};
name?: string;
}
export type Branches = { commit?: { sha?: string; url?: string }; name?: string }[];
export type CodeFrequencyStats = number[];
export interface Comment {
body?: string;
}
export interface CommentBody {
body: string;
}
export type Comments = { body?: string; created_at?: string; id?: number; url?: string; user?: User }[];
export interface Commit {
/** A GitHub user */
author?: User;
commit?: {
author?: { date?: string; email?: string; name?: string };
committer?: { date?: string; email?: string; name?: string };
message?: string;
tree?: { sha?: string; url?: string };
url?: string;
};
/** A GitHub user */
committer?: User;
files?: {
additions?: number;
blob_url?: string;
changes?: number;
deletions?: number;
filename?: string;
patch?: string;
raw_url?: string;
status?: string;
}[];
parents?: { sha?: string; url?: string }[];
sha?: string;
stats?: { additions?: number; deletions?: number; total?: number };
url?: string;
}
export type CommitActivityStats = { days?: number[]; total?: number; week?: number }[];
export interface CommitComment {
body?: string;
commit_id?: string;
/** ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ */
created_at?: string;
html_url?: string;
id?: number;
line?: number;
path?: string;
position?: number;
/** ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ */
updated_at?: string;
url?: string;
/** A GitHub user */
user?: User;
}
export interface CommitCommentBody {
body: string;
/** Deprecated - Use position parameter instead. */
line?: string;
/** Line number in the file to comment on. Defaults to null. */
number?: string;
/** Relative path of the file to comment on. */
path?: string;
/** Line index in the diff to comment on. */
position?: number;
/** SHA of the commit to comment on. */
sha: string;
}
export type Commits = {
author?: User;
commit?: {
author?: { date?: string; email?: string; name?: string };
committer?: { date?: string; email?: string; name?: string };
message?: string;
tree?: { sha?: string; url?: string };
url?: string;
};
committer?: User;
parents?: { sha?: string; url?: string }[];
sha?: string;
url?: string;
}[];
export interface CompareCommits {
ahead_by?: number;
base_commit?: {
author?: User;
commit?: {
author?: { date?: string; email?: string; name?: string };
committer?: { date?: string; email?: string; name?: string };
message?: string;
tree?: { sha?: string; url?: string };
url?: string;
};
committer?: User;
parents?: { sha?: string; url?: string }[];
sha?: string;
url?: string;
};
behind_by?: number;
commits?: {
author?: User;
commit?: {
author?: { date?: string; email?: string; name?: string };
committer?: { date?: string; email?: string; name?: string };
message?: string;
tree?: { sha?: string; url?: string };
url?: string;
};
committer?: User;
parents?: { sha?: string; url?: string }[];
sha?: string;
url?: string;
}[];
diff_url?: string;
files?: {
additions?: number;
blob_url?: string;
changes?: number;
contents_url?: string;
deletions?: number;
filename?: string;
patch?: string;
raw_url?: string;
sha?: string;
status?: string;
}[];
html_url?: string;
patch_url?: string;
permalink_url?: string;
status?: string;
total_commits?: number;
url?: string;
}
export interface ContentsPath {
_links?: { git?: string; html?: string; self?: string };
content?: string;
encoding?: string;
git_url?: string;
html_url?: string;
name?: string;
path?: string;
sha?: string;
size?: number;
type?: string;
url?: string;
}
export type ContributorsStats = {
author?: { avatar_url?: string; gravatar_id?: string; id?: number; login?: string; url?: string };
total?: number;
weeks?: { a?: number; c?: number; d?: number; w?: string }[];
}[];
export interface CreateFile {
commit?: {
author?: { date?: string; email?: string; name?: string };
committer?: { date?: string; email?: string; name?: string };
html_url?: string;
message?: string;
parents?: { html_url?: string; sha?: string; url?: string }[];
sha?: string;
tree?: { sha?: string; url?: string };
url?: string;
};
content?: {
_links?: { git?: string; html?: string; self?: string };
git_url?: string;
html_url?: string;
name?: string;
path?: string;
sha?: string;
size?: number;
type?: string;
url?: string;
};
}
export interface CreateFileBody {
committer?: { email?: string; name?: string };
content?: string;
message?: string;
}
export interface DeleteFile {
commit?: {
author?: { date?: string; email?: string; name?: string };
committer?: { date?: string; email?: string; name?: string };
html_url?: string;
message?: string;
parents?: { html_url?: string; sha?: string; url?: string };
sha?: string;
tree?: { sha?: string; url?: string };
url?: string;
};
content?: string;
}
export interface DeleteFileBody {
committer?: { email?: string; name?: string };
message?: string;
sha?: string;
}
export interface Deployment {
description?: string;
payload?: { deploy_user?: string; environment?: string; room_id?: number };
ref?: string;
}
export interface DeploymentResp {
created_at?: string;
/** A GitHub user */
creator?: User;
description?: string;
id?: number;
payload?: string;
sha?: string;
statuses_url?: string;
updated_at?: string;
url?: string;
}
export type DeploymentStatuses = {
created_at?: string;
creator?: User;
description?: string;
id?: number;
payload?: string;
state?: string;
target_url?: string;
updated_at?: string;
url?: string;
}[];
export interface DeploymentStatusesCreate {
description?: string;
state?: string;
target_url?: string;
}
export interface Download {
content_type?: string;
description?: string;
download_count?: number;
html_url?: string;
id?: number;
name?: string;
size?: number;
url?: string;
}
export type Downloads = Download[];
export interface EditTeam {
name: string;
permission?: "pull" | "push" | "admin";
}
export type EmailsPost = string[];
export type Emojis = Record<string, string>;
export interface Event {
/** A user or organization */
actor?: Actor;
created_at?: object;
id?: number;
/** A GitHub organization */
org?: Organization;
payload?: object;
public?: boolean;
repo?: { id?: number; name?: string; url?: string };
type?: string;
}
export type Events = Event[];
export interface Feeds {
_links?: {
current_user?: { href?: string; type?: string };
current_user_actor?: { href?: string; type?: string };
current_user_organization?: { href?: string; type?: string };
current_user_public?: { href?: string; type?: string };
timeline?: { href?: string; type?: string };
user?: { href?: string; type?: string };
};
current_user_actor_url?: string;
current_user_organization_url?: string;
current_user_public?: string;
current_user_url?: string;
timeline_url?: string;
user_url?: string;
}
export interface ForkBody {
organization?: string;
}
export type Forks = Repos;
export interface Gist {
comments?: number;
comments_url?: string;
/** Timestamp in ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ. */
created_at?: string;
description?: string;
files?: { "ring.erl"?: { filename?: string; raw_url?: string; size?: number } };
forks?: { created_at?: string; url?: string; user?: User }[];
git_pull_url?: string;
git_push_url?: string;
history?: {
change_status?: { additions?: number; deletions?: number; total?: number };
committed_at?: string;
url?: string;
user?: User;
version?: string;
}[];
html_url?: string;
id?: string;
public?: boolean;
url?: string;
/** A GitHub user */
user?: User;
}
export type Gists = {
comments?: number;
comments_url?: string;
created_at?: string;
description?: string;
files?: { "ring.erl"?: { filename?: string; raw_url?: string; size?: number } };
git_pull_url?: string;
git_push_url?: string;
html_url?: string;
id?: string;
public?: boolean;
url?: string;
user?: User;
}[];
export interface GitCommit {
author?: { date?: string; email?: string; name?: string };
message?: string;
parents?: string;
tree?: string;
}
export interface GitRefPatch {
force?: boolean;
sha?: string;
}
export type Gitignore = any[];
export interface GitignoreLang {
name?: string;
source?: string;
}
export interface HeadBranch {
object?: { sha?: string; type?: string; url?: string };
ref?: string;
url?: string;
}
export type Hook = {
active?: boolean;
config?: { content_type?: string; url?: string };
created_at?: string;
events?: (
| "push"
| "issues"
| "issue_comment"
| "commit_comment"
| "pull_request"
| "pull_request_review_comment"
| "gollum"
| "watch"
| "download"
| "fork"
| "fork_apply"
| "member"
| "public"
| "team_add"
| "status"
)[];
id?: number;
name?: string;
updated_at?: string;
url?: string;
}[];
export interface HookBody {
active?: boolean;
add_events?: string[];
}
export interface Issue {
assignee?: string;
body?: string;
labels?: string[];
milestone?: number;
title?: string;
}
export interface IssueEvent {
/** A user or organization */
actor?: Actor;
commit_id?: string;
/** ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ */
created_at?: string;
event?: string;
issue?: {
assignee?: User;
body?: string;
closed_at?: string;
comments?: number;
created_at?: string;
html_url?: string;
labels?: { color?: string; name?: string; url?: string }[];
milestone?: {
closed_issues?: number;
created_at?: string;
creator?: User;
description?: string;
due_on?: string;
number?: number;
open_issues?: number;
state?: "open" | "closed";
title?: string;
url?: string;
};
number?: number;
pull_request?: { diff_url?: string; html_url?: string; patch_url?: string };
state?: "open" | "closed";
title?: string;
updated_at?: string;
url?: string;
user?: User;
};
url?: string;
}
export type IssueEvents = IssueEvent[];
export type Issues = {
assignee?: User;
body?: string;
closed_at?: string;
comments?: number;
created_at?: string;
html_url?: string;
labels?: { color?: string; name?: string; url?: string }[];
milestone?: {
closed_issues?: number;
created_at?: string;
creator?: User;
description?: string;
due_on?: string;
number?: number;
open_issues?: number;
state?: "open" | "closed";
title?: string;
url?: string;
};
number?: number;
pull_request?: { diff_url?: string; html_url?: string; patch_url?: string };
state?: "open" | "closed";
title?: string;
updated_at?: string;
url?: string;
user?: User;
}[];
export interface IssuesComment {
body?: string;
/** ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ */
created_at?: string;
html_url?: string;
id?: number;
/** ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ */
updated_at?: string;
url?: string;
/** A GitHub user */
user?: User;
}
export type IssuesComments = {
_links?: { html?: { href?: string }; pull_request?: { href?: string }; self?: { href?: string } };
body?: string;
commit_id?: string;
created_at?: string;
id?: number;
path?: string;
position?: number;
updated_at?: string;
url?: string;
user?: User;
}[];
export type Keys = { id?: number; key?: string; title?: string; url?: string }[];
export interface Label {
color?: string;
name?: string;
url?: string;
}
export type Labels = { color?: string; name?: string; url?: string }[];
export type Languages = Record<string, number>;
export interface Markdown {
context?: string;
mode?: string;
text?: string;
}
export interface Merge {
merged?: boolean;
message?: string;
sha?: string;
}
export interface MergePullBody {
commit_message?: string;
}
export interface MergesBody {
base?: string;
commit_message?: string;
head?: string;
}
export interface MergesConflict {
/** Error message */
message?: string;
}
export interface MergesSuccessful {
/** A GitHub user */
author?: User;
comments_url?: string;
commit?: {
author?: { date?: string; email?: string; name?: string };
comment_count?: number;
committer?: { date?: string; email?: string; name?: string };
message?: string;
tree?: { sha?: string; url?: string };
url?: string;
};
/** A GitHub user */
committer?: User;
merged?: boolean;
message?: string;
parents?: { sha?: string; url?: string }[];
sha?: string;
url?: string;
}
export interface Meta {
git?: string[];
hooks?: string[];
}
export interface Milestone {
closed_issues?: number;
/** ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ */
created_at?: string;
/** A GitHub user */
creator?: User;
description?: string;
/** ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ */
due_on?: string;
number?: number;
open_issues?: number;
state?: "open" | "closed";
title?: string;
url?: string;
}
export interface MilestoneUpdate {
description?: string;
due_on?: string;
state?: string;
title?: string;
}
export interface NotificationMarkRead {
last_read_at?: string;
}
export interface Notifications {
id?: number;
last_read_at?: string;
reason?: string;
repository?: {
description?: string;
fork?: boolean;
full_name?: string;
html_url?: string;
id?: number;
name?: string;
owner?: Actor;
private?: boolean;
url?: string;
};
subject?: { latest_comment_url?: string; title?: string; type?: string; url?: string };
unread?: boolean;
updated_at?: string;
url?: string;
}
export interface OrgTeamsPost {
name: string;
permission?: "pull" | "push" | "admin";
repo_names?: string[];
}
/**
* A GitHub organization
*/
export type Organization = Actor;
export interface OrganizationAsTeamMember {
errors?: { code?: string; field?: string; resource?: string }[];
message?: string;
}
export interface ParticipationStats {
all?: number[];
owner?: number[];
}
export interface PatchGist {
description?: string;
files?: {
"delete_this_file.txt"?: string;
"file1.txt"?: { content?: string };
"new_file.txt"?: { content?: string };
"old_name.txt"?: { content?: string; filename?: string };
};
}
export interface PatchOrg {
/** Billing email address. This address is not publicized. */
billing_email?: string;
company?: string;
/** Publicly visible email address. */
email?: string;
location?: string;
name?: string;
}
export interface PostGist {
description?: string;
files?: { "file1.txt"?: { content?: string } };
public?: boolean;
}
export interface PostRepo {
/** True to create an initial commit with empty README. Default is false. */
auto_init?: boolean;
description?: string;
/** Desired language or platform .gitignore template to apply. Use the name of the template without the extension. For example, "Haskell" Ignored if auto_init parameter is not provided. */
gitignore_template?: string;
/** True to enable downloads for this repository, false to disable them. Default is true. */
has_downloads?: boolean;
/** True to enable issues for this repository, false to disable them. Default is true. */
has_issues?: boolean;
/** True to enable the wiki for this repository, false to disable it. Default is true. */
has_wiki?: boolean;
homepage?: string;
name: string;
/** True to create a private repository, false to create a public one. Creating private repositories requires a paid GitHub account. */
private?: boolean;
/** The id of the team that will be granted access to this repository. This is only valid when creating a repo in an organization. */
team_id?: number;
}
export interface PullRequest {
_links?: {
comments?: { href?: string };
html?: { href?: string };
review_comments?: { href?: string };
self?: { href?: string };
};
additions?: number;
base?: {
label?: string;
ref?: string;
repo?: Repo;
sha?: string;
user?: { avatar_url?: string; gravatar_id?: string; id?: number; login?: string; url?: string };
};
body?: string;
changed_files?: number;
closed_at?: string;
comments?: number;
commits?: number;
created_at?: string;
deletions?: number;
diff_url?: string;
head?: {
label?: string;
ref?: string;
repo?: Repo;
sha?: string;
user?: { avatar_url?: string; gravatar_id?: string; id?: number; login?: string; url?: string };
};
html_url?: string;
issue_url?: string;
merge_commit_sha?: string;
mergeable?: boolean;
merged?: boolean;
merged_at?: string;
merged_by?: { avatar_url?: string; gravatar_id?: string; id?: number; login?: string; url?: string };
number?: number;
patch_url?: string;
state?: string;
title?: string;
updated_at?: string;
url?: string;
user?: { avatar_url?: string; gravatar_id?: string; id?: number; login?: string; url?: string };
}
export interface PullUpdate {
body?: string;
state?: string;
title?: string;
}
export type Pulls = {
_links?: {
comments?: { href?: string };
html?: { href?: string };
review_comments?: { href?: string };
self?: { href?: string };
};
base?: {
label?: string;
ref?: string;
repo?: Repo;
sha?: string;
user?: { avatar_url?: string; gravatar_id?: string; id?: number; login?: string; url?: string };
};
body?: string;
closed_at?: string;
created_at?: string;
diff_url?: string;
head?: {
label?: string;
ref?: string;
repo?: Repo;
sha?: string;
user?: { avatar_url?: string; gravatar_id?: string; id?: number; login?: string; url?: string };
};
html_url?: string;
issue_url?: string;
merged_at?: string;
number?: number;
patch_url?: string;
state?: "open" | "closed";
title?: string;
updated_at?: string;
url?: string;
user?: { avatar_url?: string; gravatar_id?: string; id?: number; login?: string; url?: string };
}[];
export interface PullsComment {
_links?: { html?: { href?: string }; pull_request?: { href?: string }; self?: { href?: string } };
body?: string;
commit_id?: string;
/** ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ */
created_at?: string;
id?: number;
path?: string;
position?: number;
/** ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ */
updated_at?: string;
url?: string;
user?: { avatar_url?: string; gravatar_id?: string; id?: number; login?: string; url?: string };
}
export interface PullsCommentPost {
body?: string;
commit_id?: string;
path?: string;
position?: number;
}
export type PullsComments = {
_links?: { html?: { href?: string }; pull_request?: { href?: string }; self?: { href?: string } };
body?: string;
commit_id?: string;
created_at?: string;
id?: number;
path?: string;
position?: number;
updated_at?: string;
url?: string;
user?: { avatar_url?: string; gravatar_id?: string; id?: number; login?: string; url?: string };
}[];
export interface PullsPost {
base?: string;
body?: string;
head?: string;
title?: string;
}
export interface PutSubscription {
created_at?: string;
ignored?: boolean;
reason?: object;
subscribed?: boolean;
thread_url?: string;
url?: string;
}
export interface RateLimit {
rate?: { limit?: number; remaining?: number; reset?: number };
}
export type Ref = {
created_at?: string;
creator?: { avatar_url?: string; gravatar_id?: string; id?: number; login?: string; url?: string };
description?: string;
id?: number;
state?: string;
target_url?: string;
updated_at?: string;
url?: string;
}[];
export type RefStatus = {
commit_url?: string;
name?: string;
repository_url?: string;
sha?: string;
state?: string;
statuses?: {
context?: string;
created_at?: string;
description?: string;
id?: number;
state?: string;
target_url?: string;
updated_at?: string;
url?: string;
}[];
}[];
export type Refs = { object?: { sha?: string; type?: string; url?: string }; ref?: string; url?: string }[];
export interface RefsBody {
ref?: string;
sha?: string;
}
export interface Release {
assets?: {
content_type?: string;
created_at?: string;
download_count?: number;
id?: number;
label?: string;
name?: string;
size?: number;
state?: string;
updated_at?: string;
uploader?: User;
url?: string;
}[];
assets_url?: string;
/** A GitHub user */
author?: User;
body?: string;
created_at?: string;
draft?: boolean;
html_url?: string;
id?: number;
name?: string;
prerelease?: boolean;
published_at?: string;
tag_name?: string;
tarball_url?: string;
target_commitish?: string;
upload_url?: string;
url?: string;
zipball_url?: string;
}
export interface ReleaseCreate {
body?: string;
draft?: boolean;
name?: string;
prerelease?: boolean;
tag_name?: string;
target_commitish?: string;
}
export type Releases = {
assets?: {
content_type?: string;
created_at?: string;
download_count?: number;
id?: number;
label?: string;
name?: string;
size?: number;
state?: string;
updated_at?: string;
uploader?: User;
url?: string;
}[];
assets_url?: string;
author?: User;
body?: string;
created_at?: string;
draft?: boolean;
html_url?: string;
id?: number;
name?: string;
prerelease?: boolean;
published_at?: string;
tag_name?: string;
tarball_url?: string;
target_commitish?: string;
upload_url?: string;
url?: string;
zipball_url?: string;
}[];
export interface Repo {
clone_url?: string;
/** ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ */
created_at?: string;
description?: string;
fork?: boolean;
forks?: number;
forks_count?: number;
full_name?: string;
git_url?: string;
has_downloads?: boolean;
has_issues?: boolean;
has_wiki?: boolean;
homepage?: string;
html_url?: string;
id?: number;
language?: string;
master_branch?: string;
mirror_url?: string;
name?: string;
open_issues?: number;
open_issues_count?: number;
/** A GitHub organization */
organization?: Organization;
/** A user or organization */
owner?: Actor;
/** Is present when the repo is a fork. Parent is the repo this repo was forked from. */
parent?: Repo;
private?: boolean;
/** ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ */
pushed_at?: string;
size?: number;
/** Is present when the repo is a fork. Source is the ultimate source for the network. */
source?: Repo;
ssh_url?: string;
svn_url?: string;
/** ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ */
updated_at?: string;
url?: string;
watchers?: number;
watchers_count?: number;
}
export type RepoDeployments = {
created_at?: string;
creator?: User;
description?: string;
id?: number;
payload?: string;
sha?: string;
statuses_url?: string;
updated_at?: string;
url?: string;
}[];
export type RepoComments = {
body?: string;
commit_id?: string;
created_at?: string;
html_url?: string;
id?: number;
line?: number;
path?: string;
position?: number;
updated_at?: string;
url?: string;
user?: User;
}[];
export interface RepoCommit {
author?: { date?: string; email?: string; name?: string };
committer?: { date?: string; email?: string; name?: string };
message?: string;
parents?: { sha?: string; url?: string }[];
sha?: string;
tree?: { sha?: string; url?: string };
url?: string;
}
export interface RepoCommitBody {
author?: { date?: string; email?: string; name?: string };
message: string;
parents: string[];
tree: string;
}
export interface RepoEdit {
description?: string;
has_downloads?: boolean;
has_issues?: boolean;
has_wiki?: boolean;
homepage?: string;
name?: string;
private?: boolean;
}
export type Repos = Repo[];
export interface SearchCode {
items?: {
git_url?: string;
html_url?: string;
name?: string;
path?: string;
repository?: {
archive_url?: string;
assignees_url?: string;
blobs_url?: string;
branches_url?: string;
collaborators_url?: string;
comments_url?: string;
commits_url?: string;
compare_url?: string;
contents_url?: string;
contributors_url?: string;
description?: string;
downloads_url?: string;
events_url?: string;
fork?: boolean;
forks_url?: string;
full_name?: string;
git_commits_url?: string;
git_refs_url?: string;
git_tags_url?: string;
hooks_url?: string;
html_url?: string;
id?: number;
issue_comment_url?: string;
issue_events_url?: string;
issues_url?: string;
keys_url?: string;
labels_url?: string;
languages_url?: string;
merges_url?: string;
milestones_url?: string;
name?: string;
notifications_url?: string;
owner?: Actor;
private?: boolean;
pulls_url?: string;
stargazers_url?: string;
statuses_url?: string;
subscribers_url?: string;
subscription_url?: string;
tags_url?: string;
teams_url?: string;
trees_url?: string;
url?: string;
};
score?: number;
sha?: string;
url?: string;
}[];
total_count?: number;
}
export interface SearchIssues {
items?: {
assignee?: any;
body?: string;
closed_at?: any;
comments?: number;
comments_url?: string;
created_at?: string;
events_url?: string;
html_url?: string;
id?: number;
labels?: { color?: string; name?: string; url?: string }[];
labels_url?: string;
milestone?: any;
number?: number;
pull_request?: { diff_url?: any; html_url?: any; patch_url?: any };
score?: number;
state?: string;
title?: string;
updated_at?: string;
url?: string;
user?: User;
}[];
total_count?: number;
}
export interface SearchIssuesByKeyword {
issues?: {
body?: string;
comments?: number;
created_at?: string;
gravatar_id?: string;
html_url?: string;
labels?: string[];
number?: number;
position?: number;
state?: string;
title?: string;
updated_at?: string;
user?: string;
votes?: number;
}[];
}
export interface SearchRepositories {
items?: Repo[];
total_count?: number;
}
export interface SearchRepositoriesByKeyword {
repositories?: Repo[];
}
export interface SearchUserByEmail {
/** A GitHub user */
user?: User;
}
export interface SearchUsers {
items?: Users;
total_count?: number;
}
export interface SearchUsersByKeyword {
users?: Users;
}
export interface Subscription {
/** ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ */
created_at?: string;
ignored?: boolean;
reason?: string;
repository_url?: string;
subscribed?: boolean;
thread_url?: string;
url?: string;
}
export interface SubscriptionBody {
ignored?: boolean;
subscribed?: boolean;
}
export interface Tag {
/** String of the tag message. */
message?: string;
object?: { sha?: string; type?: "commit" | "tree" | "blob"; url?: string };
sha?: string;
/** The tag's name. This is typically a version (e.g., "v0.0.1"). */
tag?: string;
tagger?: { date?: string; email?: string; name?: string };
url?: string;
}
export interface TagBody {
/** String of the tag message. */
message: string;
/** String of the SHA of the git object this is tagging. */
object: string;
/** The tag's name. This is typically a version (e.g., "v0.0.1"). */
tag: string;
tagger: { date?: string; email?: string; name?: string };
/** String of the type of the object we’re tagging. Normally this is a commit but it can also be a tree or a blob. */
type: "commit" | "tree" | "blob";
}
export type Tags = Tag[];
export interface Team {
id?: number;
members_count?: number;
name?: string;
permission?: string;
repos_count?: number;
url?: string;
}
export interface TeamMembership {
state?: string;
url?: string;
}
export type TeamRepos = Repos;
export type Teams = { id?: number; name?: string; url?: string }[];
export type TeamsList = {
id?: number;
members_count?: number;
name?: string;
organization?: { avatar_url?: string; id?: number; login?: string; url?: string };
permission?: string;
repos_count?: number;
url?: string;
}[];
export interface Tree {
sha?: string;
tree?: {
mode?: "100644" | "100755" | "040000" | "160000" | "120000";
path?: string;
sha?: string;
size?: number;
type?: "blob" | "tree" | "commit";
url?: string;
}[];
url?: string;
}
export interface Trees {
base_tree?: string;
/** SHA1 checksum ID of the object in the tree. */
sha?: string;
tree?: Tree[];
url?: string;
}
/**
* A GitHub user
*/
export type User = Actor;
export type UserEmails = string[];
export interface UserKeysKeyId {
id?: number;
key?: string;
title?: string;
url?: string;
}
export interface UserKeysPost {
key?: string;
title?: string;
}
export interface UserUpdate {
bio?: string;
blog?: string;
company?: string;
email?: string;
hireable?: boolean;
location?: string;
name?: string;
}
export type Users = User[]; | the_stack |
/// <reference types="node" />
/**
* Jdenticon
* http://jdenticon.com
*
* Copyright (c) 2014-2019 Daniel Mester Pirttijärvi
*
* 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.
*
*/
declare global {
interface JdenticonConfig {
/**
* Limits the possible hues in generated icons. The hues are specified as an array of hues in degrees. If the
* option is omitted or an empty array is specified, all hues are allowed.
*/
hues?: number[],
/**
* Specifies the lightness of the generated icon.
*/
lightness?: {
/**
* Specifies the lightness range of colored shapes of an icon. The range is expressed as an array
* containing two numbers, representing the minimum and maximum lightness in the range [0.0, 1.0].
*/
color?: number[],
/**
* Specifies the lightness range of grayscale shapes of an icon. The range is expressed as an array
* containing two numbers, representing the minimum and maximum lightness in the range [0.0, 1.0].
*/
grayscale?: number[]
},
/**
* Specifies the saturation of the generated icon.
*
* For backward compatibility a single number can be specified instead of a `{ color, grayscale }`
* object. This single number refers to the saturation of colored shapes.
*/
saturation?: {
/**
* Specifies the saturation of originally colored shapes of an icon. The saturation is expressed as a
* number in the range [0.0, 1.0].
*/
color?: number,
/**
* Specifies the saturation of originally grayscale shapes of an icon. The saturation is expressed as a
* number in the range [0.0, 1.0].
*/
grayscale?: number
} | number,
/**
* Specifies the padding surrounding the icon in percents in the range [0.0, 0.5).
*/
padding?: number;
/**
* Specifies the background color to be rendered behind the icon.
*
* Supported syntaxes are:
* * `"#rgb"`
* * `"#rgba"`
* * `"#rrggbb"`
* * `"#rrggbbaa"`
*/
backColor?: string,
/**
* Specifies when icons will be rendered.
*
* * `"never"` – icons are never rendered automatically. You need to call `jdenticon.update()` manually to
* render identicons.
*
* * `"once"` – icons are rendered once the page has loaded. Any dynamically inserted or modified icons will
* not be rendered unless `jdenticon.update()` is manually called.
*
* * `"observe"` – icons are rendered upon page load, and the DOM is monitored for new icons using a
* `MutationObserver`. Use this if icons are inserted dynamically, e.g. by using Angular, React or
* VanillaJS. This option behaves as `"once"` in IE<11.
*
* @remarks
* This option has no effect in Node environments.
*/
replaceMode?: "never" | "once" | "observe"
}
interface Jdenticon {
/**
* Updates all canvas elements with the `data-jdenticon-hash` or `data-jdenticon-value` attribute.
*
* @remarks
* This method is only available in the browser. Calling this method on Node.js will throw an error.
*/
(): void;
/**
* Updates the identicon in the specified canvas or svg elements.
*
* @remarks
* This method is only available in the browser. Calling this method on Node.js will throw an error.
*
* @param elementOrSelector Specifies the container in which the icon is rendered as a DOM element of the type
* `<svg>` or `<canvas>`, or a CSS selector to such an element.
* @param hash Optional hash or value to be rendered. If not specified, the `data-jdenticon-hash` or
* `data-jdenticon-value` attribute will be evaluated.
* @param config Optional configuration. If specified, this configuration object overrides any global
* configuration in its entirety. For backward compability a padding value in the range [0.0, 0.5) can be
* specified in place of a configuration object.
*/
update(elementOrSelector: HTMLElement | string, hashOrValue?: any, config?: JdenticonConfig | number): void;
/**
* Draws an identicon to a context.
* @param ctx Canvas context on which the icon will be drawn at location (0, 0).
* @param hashOrValue A hexadecimal hash string or any value that will be hashed by Jdenticon.
* @param size Icon size in pixels.
* @param config Optional configuration. If specified, this configuration object overrides any global
* configuration in its entirety. For backward compability a padding value in the range [0.0, 0.5) can be
* specified in place of a configuration object.
*/
drawIcon(
ctx: JdenticonCompatibleCanvasRenderingContext2D,
hashOrValue: any,
size: number,
config?: JdenticonConfig | number): void;
/**
* Draws an identicon as an SVG string.
* @param hashOrValue A hexadecimal hash string or any value that will be hashed by Jdenticon.
* @param size Icon size in pixels.
* @param config Optional configuration. If specified, this configuration object overrides any global
* configuration in its entirety. For backward compability a padding value in the range [0.0, 0.5) can be
* specified in place of a configuration object.
* @returns SVG string
*/
toSvg(hashOrValue: any, size: number, config?: JdenticonConfig | number): string;
/**
* Draws an identicon as PNG.
*
* @remarks
* This method is not available in the browser.
*
* @param hashOrValue A hexadecimal hash string or any value that will be hashed by Jdenticon.
* @param size Icon size in pixels.
* @param config Optional configuration. If specified, this configuration object overrides any global
* configuration in its entirety. For backward compability a padding value in the range [0.0, 0.5) can be
* specified in place of a configuration object.
* @returns PNG data
*/
toPng(hashOrValue: any, size: number, config?: JdenticonConfig | number): Buffer;
/**
* Specifies the color options for the generated icons. This is the only supported method of setting identicon
* styles when used in a Node environment.
*
* In browsers {@link jdenticon_config} is the prefered way of setting an identicon style to avoid a race
* condition where the style is set before the Jdetnicon lib has loaded, leading to an unhandled error.
*/
config?: JdenticonConfig;
/**
* Specifies the version of the Jdenticon package in use.
*/
readonly version: string;
}
/**
* This is a subset of `HTMLCanvasElement` to allow using incomplete canvas implementations,
* like `canvas-renderer`.
*/
interface JdenticonCompatibleCanvas {
// HTMLCanvasElement
readonly height: number;
readonly width: number;
getContext(contextId: "2d"): JdenticonCompatibleCanvasRenderingContext2D | null;
}
/**
* This is a subset of `CanvasRenderingContext2D` to allow using incomplete canvas implementations,
* like `canvas-renderer`.
*/
interface JdenticonCompatibleCanvasRenderingContext2D {
// CanvasRenderingContext2D
readonly canvas: JdenticonCompatibleCanvas;
// CanvasDrawPath
beginPath(): void;
fill(): void;
// CanvasFillStrokeStyles
fillStyle: any;
// CanvasPath
arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void;
closePath(): void;
lineTo(x: number, y: number): void;
moveTo(x: number, y: number): void;
// CanvasRect
clearRect(x: number, y: number, w: number, h: number): void;
fillRect(x: number, y: number, w: number, h: number): void;
// CanvasState
restore(): void;
save(): void;
// CanvasTransform
translate(x: number, y: number): void;
}
interface JQuery {
/**
* Renders an indenticon for all matching supported elements.
*
* @param hashOrValue A hexadecimal hash string or any value that will be hashed by Jdenticon. If not
* specified the `data-jdenticon-hash` and `data-jdenticon-value` attributes of each element will be
* evaluated.
* @param config Optional configuration. If specified, this configuration object overrides any global
* configuration in its entirety. For backward compability a padding value in the range [0.0, 0.5) can be
* specified in place of a configuration object.
*/
jdenticon(hashOrValue?: any, config?: JdenticonConfig | number): void;
}
interface Window {
/**
* Specifies options for generated identicons.
*
* See also {@link jdenticon.config} for Node usage.
*/
jdenticon_config?: JdenticonConfig;
}
}
declare var jdenticon: Jdenticon;
export = jdenticon;
export as namespace jdenticon; | the_stack |
export interface DescribeSpecInfoRequest {
/**
* 可用区
*/
Zone?: string;
}
/**
* TerminateDBInstance请求参数结构体
*/
export interface TerminateDBInstanceRequest {
/**
* 实例ID,格式如:cmgo-p8vnipr5。
*/
InstanceId: string;
}
/**
* CreateDBInstance请求参数结构体
*/
export interface CreateDBInstanceRequest {
/**
* 每个副本集内从节点个数
*/
SecondaryNum: number;
/**
* 实例内存大小,单位:GB
*/
Memory: number;
/**
* 实例硬盘大小,单位:GB
*/
Volume: number;
/**
* 版本号,当前支持 MONGO_3_WT、MONGO_3_ROCKS、MONGO_36_WT
*/
MongoVersion: string;
/**
* 机器类型,GIO:高IO版;TGIO:高IO万兆
*/
MachineCode: string;
/**
* 实例数量,默认值为1, 最小值1,最大值为10
*/
GoodsNum: number;
/**
* 实例所属区域名称,格式如:ap-guangzhou-2
*/
Zone: string;
/**
* 时长,购买月数
*/
TimeSpan: number;
/**
* 实例密码
*/
Password: string;
/**
* 项目ID,不填为默认项目
*/
ProjectId?: number;
/**
* 安全组参数
*/
SecurityGroup?: Array<string>;
/**
* 私有网络ID,如果不传则默认选择基础网络
*/
UniqVpcId?: string;
/**
* 私有网络下的子网ID,如果设置了 VpcId,则 SubnetId必填
*/
UniqSubnetId?: string;
}
/**
* UpgradeDBInstanceHour请求参数结构体
*/
export interface UpgradeDBInstanceHourRequest {
/**
* 实例ID,格式如:cmgo-p8vnipr5
*/
InstanceId: string;
/**
* 升级后的内存大小,单位:GB
*/
Memory: number;
/**
* 升级后的硬盘大小,单位:GB
*/
Volume: number;
/**
* 升级后oplog的大小,单位:GB,默认为磁盘空间的10%,允许设置的最小值为磁盘的10%,最大值为磁盘的90%
*/
OplogSize?: number;
}
/**
* CreateDBInstanceHour请求参数结构体
*/
export interface CreateDBInstanceHourRequest {
/**
* 实例内存大小,单位:GB
*/
Memory: number;
/**
* 实例硬盘大小,单位:GB
*/
Volume: number;
/**
* 副本集个数,1为单副本集实例,大于1为分片集群实例,最大不超过10
*/
ReplicateSetNum: number;
/**
* 每个副本集内从节点个数,目前只支持从节点数为2
*/
SecondaryNum: number;
/**
* MongoDB引擎版本,值包括MONGO_3_WT 、MONGO_3_ROCKS和MONGO_36_WT
*/
EngineVersion: string;
/**
* 实例类型,GIO:高IO版;TGIO:高IO万兆
*/
Machine: string;
/**
* 实例数量,默认值为1, 最小值1,最大值为10
*/
GoodsNum: number;
/**
* 可用区信息,格式如:ap-guangzhou-2
*/
Zone: string;
/**
* 实例角色,支持值包括:MASTER-表示主实例,DR-表示灾备实例,RO-表示只读实例
*/
InstanceRole: string;
/**
* 实例类型,REPLSET-副本集,SHARD-分片集群
*/
InstanceType: string;
/**
* 数据是否加密,当且仅当引擎版本为MONGO_3_ROCKS,可以选择加密
*/
Encrypt?: number;
/**
* 私有网络ID,如果不传则默认选择基础网络
*/
VpcId?: string;
/**
* 私有网络下的子网ID,如果设置了 VpcId,则 SubnetId必填
*/
SubnetId?: string;
/**
* 项目ID,不填为默认项目
*/
ProjectId?: number;
/**
* 安全组参数
*/
SecurityGroup?: Array<string>;
}
/**
* AssignProject请求参数结构体
*/
export interface AssignProjectRequest {
/**
* 实例ID列表,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同
*/
InstanceIds: Array<string>;
/**
* 项目ID
*/
ProjectId: number;
}
/**
* 客户端连接信息,包括客户端IP和连接数
*/
export interface ClientConnection {
/**
* 连接的客户端IP
*/
IP: string;
/**
* 对应客户端IP的连接数
*/
Count: number;
}
/**
* DescribeDBInstances请求参数结构体
*/
export interface DescribeDBInstancesRequest {
/**
* 实例ID列表,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同
*/
InstanceIds?: Array<string>;
/**
* 实例类型,取值范围:0-所有实例,1-正式实例,2-临时实例, 3-只读实例,-1-正式实例+只读+灾备实例
*/
InstanceType?: number;
/**
* 集群类型,取值范围:0-副本集实例,1-分片实例,-1-所有实例
*/
ClusterType?: number;
/**
* 实例状态,取值范围:0-待初始化,1-流程执行中,2-实例有效,-2-实例已过期
*/
Status?: Array<number>;
/**
* 私有网络的ID,基础网络则不传该参数
*/
VpcId?: string;
/**
* 私有网络的子网ID,基础网络则不传该参数。入参设置该参数的同时,必须设置相应的VpcId
*/
SubnetId?: string;
/**
* 付费类型,取值范围:0-按量计费,1-包年包月,-1-按量计费+包年包月
*/
PayMode?: number;
/**
* 单次请求返回的数量,最小值为1,最大值为100,默认值为20
*/
Limit?: number;
/**
* 偏移量,默认值为0
*/
Offset?: number;
/**
* 返回结果集排序的字段,目前支持:"ProjectId", "InstanceName", "CreateTime",默认为升序排序
*/
OrderBy?: string;
/**
* 返回结果集排序方式,目前支持:"ASC"或者"DESC"
*/
OrderByType?: string;
}
/**
* SetPassword返回参数结构体
*/
export interface SetPasswordResponse {
/**
* 返回的异步任务ID
*/
FlowId?: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 实例规格信息
*/
export interface SpecificationInfo {
/**
* 地域信息
*/
Region: string;
/**
* 可用区信息
*/
Zone: string;
/**
* 售卖规格信息
*/
SpecItems: Array<SpecItem>;
}
/**
* 实例详情
*/
export interface MongoDBInstanceDetail {
/**
* 实例ID
*/
InstanceId: string;
/**
* 实例名称
*/
InstanceName: string;
/**
* 付费类型,可能的返回值:1-包年包月;0-按量计费
*/
PayMode: number;
/**
* 项目ID
*/
ProjectId: number;
/**
* 集群类型,可能的返回值:0-副本集实例,1-分片实例,
*/
ClusterType: number;
/**
* 地域信息
*/
Region: string;
/**
* 可用区信息
*/
Zone: string;
/**
* 网络类型,可能的返回值:0-基础网络,1-私有网络
*/
NetType: number;
/**
* 私有网络的ID
*/
VpcId: string;
/**
* 私有网络的子网ID
*/
SubnetId: string;
/**
* 实例状态,可能的返回值:0-待初始化,1-流程处理中,2-运行中,-2-实例已过期
*/
Status: number;
/**
* 实例IP
*/
Vip: string;
/**
* 端口号
*/
Vport: number;
/**
* 实例创建时间
*/
CreateTime: string;
/**
* 实例到期时间
*/
DeadLine: string;
/**
* 实例版本信息
*/
MongoVersion: string;
/**
* 实例内存规格,单位为MB
*/
Memory: number;
/**
* 实例磁盘规格,单位为MB
*/
Volume: number;
/**
* 实例CPU核心数
*/
CpuNum: number;
/**
* 实例机器类型
*/
MachineType: string;
/**
* 实例从节点数
*/
SecondaryNum: number;
/**
* 实例分片数
*/
ReplicationSetNum: number;
/**
* 实例自动续费标志,可能的返回值:0-手动续费,1-自动续费,2-确认不续费
*/
AutoRenewFlag: number;
/**
* 已用容量,单位MB
*/
UsedVolume: number;
/**
* 维护窗口起始时间
*/
MaintenanceStart: string;
/**
* 维护窗口结束时间
*/
MaintenanceEnd: string;
/**
* 分片信息
*/
ReplicaSets: Array<MongodbShardInfo>;
/**
* 只读实例信息
注意:此字段可能返回 null,表示取不到有效值。
*/
ReadonlyInstances: Array<MongoDBInstance>;
/**
* 灾备实例信息
注意:此字段可能返回 null,表示取不到有效值。
*/
StandbyInstances: Array<MongoDBInstance>;
/**
* 临时实例信息
注意:此字段可能返回 null,表示取不到有效值。
*/
CloneInstances: Array<MongoDBInstance>;
/**
* 关联实例信息,对于正式实例,该字段表示它的临时实例信息;对于临时实例,则表示它的正式实例信息;如果为只读/灾备实例,则表示他的主实例信息
注意:此字段可能返回 null,表示取不到有效值。
*/
RelatedInstance: MongoDBInstance;
/**
* 实例标签信息集合
注意:此字段可能返回 null,表示取不到有效值。
*/
Tags: Array<TagInfo>;
/**
* 实例标记
*/
InstanceVer: number;
/**
* 实例标记
*/
ClusterVer: number;
/**
* 协议信息,可能的返回值:1-mongodb,2-dynamodb
*/
Protocol: number;
/**
* 实例类型,可能的返回值,1-正式实例,2-临时实例,3-只读实例,4-灾备实例
*/
InstanceType: number;
/**
* 实例状态描述
*/
InstanceStatusDesc: string;
/**
* 实例对应的物理实例ID,回档并替换过的实例有不同的InstanceId和RealInstanceId,从barad获取监控数据等场景下需要用物理id获取
*/
RealInstanceId: string;
}
/**
* DescribeSpecInfo返回参数结构体
*/
export interface DescribeSpecInfoResponse {
/**
* 实例售卖规格信息列表
*/
SpecInfoList?: Array<SpecificationInfo>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 实例标签信息
*/
export interface TagInfo {
/**
* 标签Key值
*/
TagKey: string;
/**
* 标签值
*/
TagValue: string;
}
/**
* DescribeSlowLog返回参数结构体
*/
export interface DescribeSlowLogResponse {
/**
* 符合查询条件的慢查询日志总数。
*/
TotalCount?: number;
/**
* 符合查询条件的慢查询日志详情。
*/
SlowLogList?: Array<string>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeDBInstances返回参数结构体
*/
export interface DescribeDBInstancesResponse {
/**
* 符合查询条件的实例总数
*/
TotalCount?: number;
/**
* 实例详细信息
*/
InstanceDetails?: Array<MongoDBInstanceDetail>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateDBInstance返回参数结构体
*/
export interface CreateDBInstanceResponse {
/**
* 订单ID
*/
DealId?: string;
/**
* 创建的实例ID列表
*/
InstanceIds?: Array<string>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* SetPassword请求参数结构体
*/
export interface SetPasswordRequest {
/**
* 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同
*/
InstanceId: string;
/**
* 实例账户名称
*/
UserName: string;
/**
* 实例新密码,至少包含字母、数字和字符(!@#%^*())中的两种,长度为8-16个字符
*/
Password: string;
}
/**
* AssignProject返回参数结构体
*/
export interface AssignProjectResponse {
/**
* 返回的异步任务ID列表
*/
FlowIds?: Array<number>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeSlowLog请求参数结构体
*/
export interface DescribeSlowLogRequest {
/**
* 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同
*/
InstanceId: string;
/**
* 慢日志起始时间,格式:yyyy-mm-dd hh:mm:ss,如:2019-06-01 10:00:00。查询起止时间间隔不能超过24小时,只允许查询最近7天内慢日志。
*/
StartTime: string;
/**
* 慢日志终止时间,格式:yyyy-mm-dd hh:mm:ss,如:2019-06-02 12:00:00。查询起止时间间隔不能超过24小时,只允许查询最近7天内慢日志。
*/
EndTime: string;
/**
* 慢日志执行时间阈值,返回执行时间超过该阈值的慢日志,单位为毫秒(ms),最小为100毫秒。
*/
SlowMS: number;
/**
* 偏移量,最小值为0,最大值为10000,默认值为0。
*/
Offset?: number;
/**
* 分页大小,最小值为1,最大值为100,默认值为20。
*/
Limit?: number;
}
/**
* DescribeClientConnections请求参数结构体
*/
export interface DescribeClientConnectionsRequest {
/**
* 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同
*/
InstanceId: string;
}
/**
* SetAutoRenew返回参数结构体
*/
export interface SetAutoRenewResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 实例信息
*/
export interface MongoDBInstance {
/**
* 实例ID
*/
InstanceId: string;
/**
* 地域信息
*/
Region: string;
}
/**
* RenameInstance请求参数结构体
*/
export interface RenameInstanceRequest {
/**
* 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同
*/
InstanceId: string;
/**
* 实例名称
*/
NewName: string;
}
/**
* UpgradeDBInstance返回参数结构体
*/
export interface UpgradeDBInstanceResponse {
/**
* 订单ID
*/
DealId?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* SetAutoRenew请求参数结构体
*/
export interface SetAutoRenewRequest {
/**
* 实例ID列表,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同
*/
InstanceIds: Array<string>;
/**
* 续费选项,取值范围:0-手动续费,1-自动续费,2-确认不续费
*/
AutoRenewFlag: number;
}
/**
* RenameInstance返回参数结构体
*/
export interface RenameInstanceResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeClientConnections返回参数结构体
*/
export interface DescribeClientConnectionsResponse {
/**
* 客户端连接信息,包括客户端IP和对应IP的连接数量
注意:此字段可能返回 null,表示取不到有效值。
*/
Clients?: Array<ClientConnection>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* UpgradeDBInstanceHour返回参数结构体
*/
export interface UpgradeDBInstanceHourResponse {
/**
* 订单ID
*/
DealId?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* UpgradeDBInstance请求参数结构体
*/
export interface UpgradeDBInstanceRequest {
/**
* 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同
*/
InstanceId: string;
/**
* 升级后的内存大小,单位:GB
*/
Memory: number;
/**
* 升级后的硬盘大小,单位:GB
*/
Volume: number;
/**
* 升级后oplog的大小,单位:GB,默认为磁盘空间的10%,允许设置的最小值为磁盘的10%,最大值为磁盘的90%
*/
OplogSize?: number;
}
/**
* CreateDBInstanceHour返回参数结构体
*/
export interface CreateDBInstanceHourResponse {
/**
* 订单ID
*/
DealId?: string;
/**
* 创建的实例ID列表
*/
InstanceIds?: Array<string>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* TerminateDBInstance返回参数结构体
*/
export interface TerminateDBInstanceResponse {
/**
* 订单ID,表示注销实例成功
*/
AsyncRequestId?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 实例分片详情
*/
export interface MongodbShardInfo {
/**
* 分片已使用容量
*/
UsedVolume: number;
/**
* 分片ID
*/
ReplicaSetId: string;
/**
* 分片名
*/
ReplicaSetName: string;
/**
* 分片内存规格,单位为MB
*/
Memory: number;
/**
* 分片磁盘规格,单位为MB
*/
Volume: number;
/**
* 分片Oplog大小,单位为MB
*/
OplogSize: number;
/**
* 分片从节点数
*/
SecondaryNum: number;
/**
* 分片物理ID
*/
RealReplicaSetId: string;
}
/**
* mongodb售卖规格
*/
export interface SpecItem {
/**
* 规格信息标识
*/
SpecCode: string;
/**
* 规格有效标志,取值:0-停止售卖,1-开放售卖
*/
Status: number;
/**
* 机器类型,取值:0-HIO,4-HIO10G
*/
MachineType: string;
/**
* cpu核心数
*/
Cpu: number;
/**
* 内存规格,单位为MB
*/
Memory: number;
/**
* 默认磁盘规格,单位MB
*/
DefaultStorage: number;
/**
* 最大磁盘规格,单位MB
*/
MaxStorage: number;
/**
* 最小磁盘规格,单位MB
*/
MinStorage: number;
/**
* 可承载qps信息
*/
Qps: number;
/**
* 连接数限制
*/
Conns: number;
/**
* 实例mongodb版本信息
*/
MongoVersionCode: string;
/**
* 实例mongodb版本号
*/
MongoVersionValue: number;
/**
* 实例mongodb版本号(短)
*/
Version: string;
/**
* 存储引擎
*/
EngineName: string;
/**
* 集群类型,取值:1-分片集群,0-副本集集群
*/
ClusterType: number;
/**
* 最小副本集从节点数
*/
MinNodeNum: number;
/**
* 最大副本集从节点数
*/
MaxNodeNum: number;
/**
* 最小分片数
*/
MinReplicateSetNum: number;
/**
* 最大分片数
*/
MaxReplicateSetNum: number;
/**
* 最小分片从节点数
*/
MinReplicateSetNodeNum: number;
/**
* 最大分片从节点数
*/
MaxReplicateSetNodeNum: number;
} | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace FormCompetitor {
interface Header extends DevKit.Controls.IHeader {
/** Type the amount of revenue reported in the competitor's annual report or other source. */
ReportedRevenue: DevKit.Controls.Money;
/** Type the stock exchange symbol for the competitor to track financial performance of the company. You can click the code entered in this field to access the latest trading information from MSN Money. */
TickerSymbol: DevKit.Controls.String;
}
interface tab_COMPETITOR_Sections {
analysis: DevKit.Controls.Section;
Competitor_Information: DevKit.Controls.Section;
notes: DevKit.Controls.Section;
}
interface tab_opportunities_Sections {
OpportunitiesChart: DevKit.Controls.Section;
Opportunity: DevKit.Controls.Section;
}
interface tab_COMPETITOR extends DevKit.Controls.ITab {
Section: tab_COMPETITOR_Sections;
}
interface tab_opportunities extends DevKit.Controls.ITab {
Section: tab_opportunities_Sections;
}
interface Tabs {
COMPETITOR: tab_COMPETITOR;
opportunities: tab_opportunities;
}
interface Body {
Tab: Tabs;
/** Shows the complete primary address. */
Address1_Composite: DevKit.Controls.String;
/** Type the company or business name used to identify the competitor in data views and related records. */
Name: DevKit.Controls.String;
notescontrol: DevKit.Controls.Note;
/** Type notes or other information about the competitor's strengths, such as top-selling products and targeted industries or markets. */
Strengths: DevKit.Controls.String;
/** Choose the local currency for the record to make sure budgets are reported in the correct currency. */
TransactionCurrencyId: DevKit.Controls.Lookup;
/** Type notes or other information about the competitor's weaknesses or areas in which your organization outperforms the competitor. */
Weaknesses: DevKit.Controls.String;
/** Type the website URL for the competitor. */
WebSiteUrl: DevKit.Controls.String;
}
interface Navigation {
navAsyncOperations: DevKit.Controls.NavigationItem,
navConnections: DevKit.Controls.NavigationItem,
navOpportunities: DevKit.Controls.NavigationItem,
navProcessSessions: DevKit.Controls.NavigationItem
}
interface Grid {
OpportunityCurrentFiscalYear: DevKit.Controls.Grid;
ChartTest: DevKit.Controls.Grid;
}
}
class FormCompetitor extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Competitor
* @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 Competitor */
Body: DevKit.FormCompetitor.Body;
/** The Header section of form Competitor */
Header: DevKit.FormCompetitor.Header;
/** The Navigation of form Competitor */
Navigation: DevKit.FormCompetitor.Navigation;
/** The Grid of form Competitor */
Grid: DevKit.FormCompetitor.Grid;
}
namespace FormCompetitor_Information {
interface tab_analysis_Sections {
analysis: DevKit.Controls.Section;
}
interface tab_general_Sections {
address: DevKit.Controls.Section;
competitor_information: DevKit.Controls.Section;
}
interface tab_notes_Sections {
notes: DevKit.Controls.Section;
}
interface tab_analysis extends DevKit.Controls.ITab {
Section: tab_analysis_Sections;
}
interface tab_general extends DevKit.Controls.ITab {
Section: tab_general_Sections;
}
interface tab_notes extends DevKit.Controls.ITab {
Section: tab_notes_Sections;
}
interface Tabs {
analysis: tab_analysis;
general: tab_general;
notes: tab_notes;
}
interface Body {
Tab: Tabs;
/** Type the city for the primary address. */
Address1_City: DevKit.Controls.String;
/** Type the country or region for the primary address. */
Address1_Country: DevKit.Controls.String;
/** Type the first line of the primary address. */
Address1_Line1: DevKit.Controls.String;
/** Type the second line of the primary address. */
Address1_Line2: DevKit.Controls.String;
/** Type the third line of the primary address. */
Address1_Line3: DevKit.Controls.String;
/** Type the ZIP Code or postal code for the primary address. */
Address1_PostalCode: DevKit.Controls.String;
/** Type the state or province of the primary address. */
Address1_StateOrProvince: DevKit.Controls.String;
/** Type the competitor's primary product, service, or specialty. */
KeyProduct: DevKit.Controls.String;
/** Type the company or business name used to identify the competitor in data views and related records. */
Name: DevKit.Controls.String;
notescontrol: DevKit.Controls.Note;
/** Type notes or other information about the competitive opportunities or selling points you can make. */
Opportunities: DevKit.Controls.String;
/** Type notes or other information about the competitor's business, such as location, revenue, or distribution channel. */
Overview: DevKit.Controls.String;
/** Type the amount of revenue reported in the competitor's annual report or other source. */
ReportedRevenue: DevKit.Controls.Money;
/** Type the stock exchange at which the competitor is listed to track their stock and financial performance of the company. */
StockExchange: DevKit.Controls.String;
/** Type notes or other information about the competitor's strengths, such as top-selling products and targeted industries or markets. */
Strengths: DevKit.Controls.String;
/** Type notes or other information about the competitor's threats to your organization when you sell to the same prospect or customer. */
Threats: DevKit.Controls.String;
/** Choose the local currency for the record to make sure budgets are reported in the correct currency. */
TransactionCurrencyId: DevKit.Controls.Lookup;
/** Type notes or other information about the competitor's weaknesses or areas in which your organization outperforms the competitor. */
Weaknesses: DevKit.Controls.String;
/** Type the website URL for the competitor. */
WebSiteUrl: DevKit.Controls.String;
}
}
class FormCompetitor_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Competitor_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 Competitor_Information */
Body: DevKit.FormCompetitor_Information.Body;
}
class CompetitorApi {
/**
* DynamicsCrm.DevKit CompetitorApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Unique identifier for address 1. */
Address1_AddressId: DevKit.WebApi.GuidValue;
/** Select the primary address type. */
Address1_AddressTypeCode: DevKit.WebApi.OptionSetValue;
/** Type the city for the primary address. */
Address1_City: DevKit.WebApi.StringValue;
/** Shows the complete primary address. */
Address1_Composite: DevKit.WebApi.StringValueReadonly;
/** Type the country or region for the primary address. */
Address1_Country: DevKit.WebApi.StringValue;
/** Type the county for the primary address. */
Address1_County: DevKit.WebApi.StringValue;
/** Type the fax number associated with the primary address. */
Address1_Fax: DevKit.WebApi.StringValue;
/** Type the latitude value for the primary address for use in mapping and other applications. */
Address1_Latitude: DevKit.WebApi.DoubleValue;
/** Type the first line of the primary address. */
Address1_Line1: DevKit.WebApi.StringValue;
/** Type the second line of the primary address. */
Address1_Line2: DevKit.WebApi.StringValue;
/** Type the third line of the primary address. */
Address1_Line3: DevKit.WebApi.StringValue;
/** Type the longitude value for the primary address for use in mapping and other applications. */
Address1_Longitude: DevKit.WebApi.DoubleValue;
/** Type a descriptive name for the primary address, such as Corporate Headquarters. */
Address1_Name: DevKit.WebApi.StringValue;
/** Type the ZIP Code or postal code for the primary address. */
Address1_PostalCode: DevKit.WebApi.StringValue;
/** Type the post office box number of the primary address. */
Address1_PostOfficeBox: DevKit.WebApi.StringValue;
/** Select a shipping method for deliveries sent to this address. */
Address1_ShippingMethodCode: DevKit.WebApi.OptionSetValue;
/** Type the state or province of the primary address. */
Address1_StateOrProvince: DevKit.WebApi.StringValue;
/** Type the main phone number associated with the primary address. */
Address1_Telephone1: DevKit.WebApi.StringValue;
/** Type a second phone number associated with the primary address. */
Address1_Telephone2: DevKit.WebApi.StringValue;
/** Type a third phone number associated with the primary address. */
Address1_Telephone3: DevKit.WebApi.StringValue;
/** Type the UPS zone of the primary address to make sure shipping charges are calculated correctly and deliveries are made promptly, if shipped by UPS. */
Address1_UPSZone: DevKit.WebApi.StringValue;
/** Select the time zone, or UTC offset, for this address so that other people can reference it when they contact someone at this address. */
Address1_UTCOffset: DevKit.WebApi.IntegerValue;
/** Unique identifier for address 2. */
Address2_AddressId: DevKit.WebApi.GuidValue;
/** Select the secondary address type. */
Address2_AddressTypeCode: DevKit.WebApi.OptionSetValue;
/** Type the city for the secondary address. */
Address2_City: DevKit.WebApi.StringValue;
/** Shows the complete secondary address. */
Address2_Composite: DevKit.WebApi.StringValueReadonly;
/** Type the country or region for the secondary address. */
Address2_Country: DevKit.WebApi.StringValue;
/** Type the county for the secondary address. */
Address2_County: DevKit.WebApi.StringValue;
/** Type the fax number associated with the secondary address. */
Address2_Fax: DevKit.WebApi.StringValue;
/** Type the latitude value for the secondary address for use in mapping and other applications. */
Address2_Latitude: DevKit.WebApi.DoubleValue;
/** Type the first line of the secondary address. */
Address2_Line1: DevKit.WebApi.StringValue;
/** Type the second line of the secondary address. */
Address2_Line2: DevKit.WebApi.StringValue;
/** Type the third line of the secondary address. */
Address2_Line3: DevKit.WebApi.StringValue;
/** Type the longitude value for the secondary address for use in mapping and other applications. */
Address2_Longitude: DevKit.WebApi.DoubleValue;
/** Type a descriptive name for the secondary address, such as Corporate Headquarters. */
Address2_Name: DevKit.WebApi.StringValue;
/** Type the ZIP Code or postal code for the secondary address. */
Address2_PostalCode: DevKit.WebApi.StringValue;
/** Type the post office box number of the secondary address. */
Address2_PostOfficeBox: DevKit.WebApi.StringValue;
/** Select a shipping method for deliveries sent to this address. */
Address2_ShippingMethodCode: DevKit.WebApi.OptionSetValue;
/** Type the state or province of the secondary address. */
Address2_StateOrProvince: DevKit.WebApi.StringValue;
/** Type the main phone number associated with the secondary address. */
Address2_Telephone1: DevKit.WebApi.StringValue;
/** Type a second phone number associated with the secondary address. */
Address2_Telephone2: DevKit.WebApi.StringValue;
/** Type a third phone number associated with the secondary address. */
Address2_Telephone3: DevKit.WebApi.StringValue;
/** Type the UPS zone of the secondary address to make sure shipping charges are calculated correctly and deliveries are made promptly , if shipped by UPS. */
Address2_UPSZone: DevKit.WebApi.StringValue;
/** Select the time zone, or UTC offset, for this address so that other people can reference it when they contact someone at this address. */
Address2_UTCOffset: DevKit.WebApi.IntegerValue;
/** Unique identifier of the competitor. */
CompetitorId: DevKit.WebApi.GuidValue;
/** 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;
/** Shows the default image for the record. */
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;
/** Sequence number of the import that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Type the competitor's primary product, service, or specialty. */
KeyProduct: DevKit.WebApi.StringValue;
/** Shows who last updated the record. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was modified. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who last updated the record on behalf of another user. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Type the company or business name used to identify the competitor in data views and related records. */
Name: DevKit.WebApi.StringValue;
/** Type notes or other information about the competitive opportunities or selling points you can make. */
Opportunities: DevKit.WebApi.StringValue;
/** Unique identifier for the organization */
OrganizationId: DevKit.WebApi.LookupValueReadonly;
/** Date and time that the record was migrated. */
OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Type notes or other information about the competitor's business, such as location, revenue, or distribution channel. */
Overview: DevKit.WebApi.StringValue;
/** Contains the id of the process associated with the entity. */
ProcessId: DevKit.WebApi.GuidValue;
/** Type the URL for the website used to obtain reference information about the competitor. */
ReferenceInfoUrl: DevKit.WebApi.StringValue;
/** Type the amount of revenue reported in the competitor's annual report or other source. */
ReportedRevenue: DevKit.WebApi.MoneyValue;
/** Value of the Reported Revenue in base currency. */
ReportedRevenue_Base: DevKit.WebApi.MoneyValueReadonly;
/** Type the quarter number during which the competitor's reported revenue was recorded or announced for use in reporting and analysis. */
ReportingQuarter: DevKit.WebApi.IntegerValue;
/** Type the fiscal year during which the competitor's reported revenue was announced for use in reporting and analysis. */
ReportingYear: DevKit.WebApi.IntegerValue;
/** Contains the id of the stage where the entity is located. */
StageId: DevKit.WebApi.GuidValue;
/** Type the stock exchange at which the competitor is listed to track their stock and financial performance of the company. */
StockExchange: DevKit.WebApi.StringValue;
/** Type notes or other information about the competitor's strengths, such as top-selling products and targeted industries or markets. */
Strengths: DevKit.WebApi.StringValue;
/** Type notes or other information about the competitor's threats to your organization when you sell to the same prospect or customer. */
Threats: DevKit.WebApi.StringValue;
/** Type the stock exchange symbol for the competitor to track financial performance of the company. You can click the code entered in this field to access the latest trading information from MSN Money. */
TickerSymbol: DevKit.WebApi.StringValue;
/** 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;
/** A comma separated list of string values representing the unique identifiers of stages in a Business Process Flow Instance in the order that they occur. */
TraversedPath: DevKit.WebApi.StringValue;
/** Time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
/** Version Number */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
/** Type notes or other information about the competitor's weaknesses or areas in which your organization outperforms the competitor. */
Weaknesses: DevKit.WebApi.StringValue;
/** Type the website URL for the competitor. */
WebSiteUrl: DevKit.WebApi.StringValue;
/** Type the percentage of your organization's lost opportunities that are won by the competitor to identify your strongest competitors. */
WinPercentage: DevKit.WebApi.DoubleValue;
/** Type the phonetic spelling of the competitor's name, if specified in Japanese, to make sure the name is pronounced correctly in phone calls and other communications. */
YomiName: DevKit.WebApi.StringValue;
}
}
declare namespace OptionSet {
namespace Competitor {
enum Address1_AddressTypeCode {
/** 1 */
Default_Value
}
enum Address1_ShippingMethodCode {
/** 1 */
Default_Value
}
enum Address2_AddressTypeCode {
/** 1 */
Default_Value
}
enum Address2_ShippingMethodCode {
/** 1 */
Default_Value
}
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':['Competitor','Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest';
import * as models from '../models';
/**
* @class
* Recommendations
* __NOTE__: An instance of this class is automatically created for an
* instance of the AdvisorManagementClient.
*/
export interface Recommendations {
/**
* Initiates the recommendation generation or computation process for a
* subscription. This operation is asynchronous. The generated recommendations
* are stored in a cache in the Advisor service.
*
* @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.
*/
generateWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Initiates the recommendation generation or computation process for a
* subscription. This operation is asynchronous. The generated recommendations
* are stored in a cache in the Advisor service.
*
* @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.
*/
generate(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
generate(callback: ServiceCallback<void>): void;
generate(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Retrieves the status of the recommendation computation or generation
* process. Invoke this API after calling the generation recommendation. The
* URI of this API is returned in the Location field of the response header.
*
* @param {uuid} operationId The operation ID, which can be found from the
* Location field in the generate recommendation response header.
*
* @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.
*/
getGenerateStatusWithHttpOperationResponse(operationId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Retrieves the status of the recommendation computation or generation
* process. Invoke this API after calling the generation recommendation. The
* URI of this API is returned in the Location field of the response header.
*
* @param {uuid} operationId The operation ID, which can be found from the
* Location field in the generate recommendation response header.
*
* @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.
*/
getGenerateStatus(operationId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
getGenerateStatus(operationId: string, callback: ServiceCallback<void>): void;
getGenerateStatus(operationId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Obtains cached recommendations for a subscription. The recommendations are
* generated or computed by invoking generateRecommendations.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] The filter to apply to the recommendations.
*
* @param {number} [options.top] The number of recommendations per page if a
* paged version of this API is being used.
*
* @param {string} [options.skipToken] The page-continuation token to use with
* a paged version of this API.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ResourceRecommendationBaseListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { filter? : string, top? : number, skipToken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ResourceRecommendationBaseListResult>>;
/**
* Obtains cached recommendations for a subscription. The recommendations are
* generated or computed by invoking generateRecommendations.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] The filter to apply to the recommendations.
*
* @param {number} [options.top] The number of recommendations per page if a
* paged version of this API is being used.
*
* @param {string} [options.skipToken] The page-continuation token to use with
* a paged version of this API.
*
* @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 {ResourceRecommendationBaseListResult} - 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.
*
* {ResourceRecommendationBaseListResult} [result] - The deserialized result object if an error did not occur.
* See {@link ResourceRecommendationBaseListResult} 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.
*/
list(options?: { filter? : string, top? : number, skipToken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ResourceRecommendationBaseListResult>;
list(callback: ServiceCallback<models.ResourceRecommendationBaseListResult>): void;
list(options: { filter? : string, top? : number, skipToken? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResourceRecommendationBaseListResult>): void;
/**
* Obtains details of a cached recommendation.
*
* @param {string} resourceUri The fully qualified Azure Resource Manager
* identifier of the resource to which the recommendation applies.
*
* @param {string} recommendationId The recommendation ID.
*
* @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<ResourceRecommendationBase>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceUri: string, recommendationId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ResourceRecommendationBase>>;
/**
* Obtains details of a cached recommendation.
*
* @param {string} resourceUri The fully qualified Azure Resource Manager
* identifier of the resource to which the recommendation applies.
*
* @param {string} recommendationId The recommendation ID.
*
* @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 {ResourceRecommendationBase} - 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.
*
* {ResourceRecommendationBase} [result] - The deserialized result object if an error did not occur.
* See {@link ResourceRecommendationBase} 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(resourceUri: string, recommendationId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ResourceRecommendationBase>;
get(resourceUri: string, recommendationId: string, callback: ServiceCallback<models.ResourceRecommendationBase>): void;
get(resourceUri: string, recommendationId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResourceRecommendationBase>): void;
/**
* Obtains cached recommendations for a subscription. The recommendations are
* generated or computed by invoking generateRecommendations.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @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<ResourceRecommendationBaseListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ResourceRecommendationBaseListResult>>;
/**
* Obtains cached recommendations for a subscription. The recommendations are
* generated or computed by invoking generateRecommendations.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @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 {ResourceRecommendationBaseListResult} - 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.
*
* {ResourceRecommendationBaseListResult} [result] - The deserialized result object if an error did not occur.
* See {@link ResourceRecommendationBaseListResult} 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.
*/
listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ResourceRecommendationBaseListResult>;
listNext(nextPageLink: string, callback: ServiceCallback<models.ResourceRecommendationBaseListResult>): void;
listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResourceRecommendationBaseListResult>): void;
}
/**
* @class
* Operations
* __NOTE__: An instance of this class is automatically created for an
* instance of the AdvisorManagementClient.
*/
export interface Operations {
/**
* Lists all the available Advisor REST API operations.
*
* @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<OperationEntityListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationEntityListResult>>;
/**
* Lists all the available Advisor REST API operations.
*
* @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 {OperationEntityListResult} - 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.
*
* {OperationEntityListResult} [result] - The deserialized result object if an error did not occur.
* See {@link OperationEntityListResult} 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.
*/
list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationEntityListResult>;
list(callback: ServiceCallback<models.OperationEntityListResult>): void;
list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationEntityListResult>): void;
/**
* Lists all the available Advisor REST API operations.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @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<OperationEntityListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationEntityListResult>>;
/**
* Lists all the available Advisor REST API operations.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @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 {OperationEntityListResult} - 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.
*
* {OperationEntityListResult} [result] - The deserialized result object if an error did not occur.
* See {@link OperationEntityListResult} 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.
*/
listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationEntityListResult>;
listNext(nextPageLink: string, callback: ServiceCallback<models.OperationEntityListResult>): void;
listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationEntityListResult>): void;
}
/**
* @class
* Suppressions
* __NOTE__: An instance of this class is automatically created for an
* instance of the AdvisorManagementClient.
*/
export interface Suppressions {
/**
* Obtains the details of a suppression.
*
* @param {string} resourceUri The fully qualified Azure Resource Manager
* identifier of the resource to which the recommendation applies.
*
* @param {string} recommendationId The recommendation ID.
*
* @param {string} name The name of the suppression.
*
* @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<SuppressionContract>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceUri: string, recommendationId: string, name: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SuppressionContract>>;
/**
* Obtains the details of a suppression.
*
* @param {string} resourceUri The fully qualified Azure Resource Manager
* identifier of the resource to which the recommendation applies.
*
* @param {string} recommendationId The recommendation ID.
*
* @param {string} name The name of the suppression.
*
* @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 {SuppressionContract} - 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.
*
* {SuppressionContract} [result] - The deserialized result object if an error did not occur.
* See {@link SuppressionContract} 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(resourceUri: string, recommendationId: string, name: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SuppressionContract>;
get(resourceUri: string, recommendationId: string, name: string, callback: ServiceCallback<models.SuppressionContract>): void;
get(resourceUri: string, recommendationId: string, name: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SuppressionContract>): void;
/**
* Enables the snoozed or dismissed attribute of a recommendation. The snoozed
* or dismissed attribute is referred to as a suppression. Use this API to
* create or update the snoozed or dismissed status of a recommendation.
*
* @param {string} resourceUri The fully qualified Azure Resource Manager
* identifier of the resource to which the recommendation applies.
*
* @param {string} recommendationId The recommendation ID.
*
* @param {string} name The name of the suppression.
*
* @param {object} suppressionContract The snoozed or dismissed attribute; for
* example, the snooze duration.
*
* @param {string} [suppressionContract.suppressionId] The GUID of the
* suppression.
*
* @param {string} [suppressionContract.ttl] The duration for which the
* suppression is valid.
*
* @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<SuppressionContract>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createWithHttpOperationResponse(resourceUri: string, recommendationId: string, name: string, suppressionContract: models.SuppressionContract, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SuppressionContract>>;
/**
* Enables the snoozed or dismissed attribute of a recommendation. The snoozed
* or dismissed attribute is referred to as a suppression. Use this API to
* create or update the snoozed or dismissed status of a recommendation.
*
* @param {string} resourceUri The fully qualified Azure Resource Manager
* identifier of the resource to which the recommendation applies.
*
* @param {string} recommendationId The recommendation ID.
*
* @param {string} name The name of the suppression.
*
* @param {object} suppressionContract The snoozed or dismissed attribute; for
* example, the snooze duration.
*
* @param {string} [suppressionContract.suppressionId] The GUID of the
* suppression.
*
* @param {string} [suppressionContract.ttl] The duration for which the
* suppression is valid.
*
* @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 {SuppressionContract} - 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.
*
* {SuppressionContract} [result] - The deserialized result object if an error did not occur.
* See {@link SuppressionContract} 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.
*/
create(resourceUri: string, recommendationId: string, name: string, suppressionContract: models.SuppressionContract, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SuppressionContract>;
create(resourceUri: string, recommendationId: string, name: string, suppressionContract: models.SuppressionContract, callback: ServiceCallback<models.SuppressionContract>): void;
create(resourceUri: string, recommendationId: string, name: string, suppressionContract: models.SuppressionContract, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SuppressionContract>): void;
/**
* Enables the activation of a snoozed or dismissed recommendation. The snoozed
* or dismissed attribute of a recommendation is referred to as a suppression.
*
* @param {string} resourceUri The fully qualified Azure Resource Manager
* identifier of the resource to which the recommendation applies.
*
* @param {string} recommendationId The recommendation ID.
*
* @param {string} name The name of the suppression.
*
* @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(resourceUri: string, recommendationId: string, name: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Enables the activation of a snoozed or dismissed recommendation. The snoozed
* or dismissed attribute of a recommendation is referred to as a suppression.
*
* @param {string} resourceUri The fully qualified Azure Resource Manager
* identifier of the resource to which the recommendation applies.
*
* @param {string} recommendationId The recommendation ID.
*
* @param {string} name The name of the suppression.
*
* @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(resourceUri: string, recommendationId: string, name: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteMethod(resourceUri: string, recommendationId: string, name: string, callback: ServiceCallback<void>): void;
deleteMethod(resourceUri: string, recommendationId: string, name: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Retrieves the list of snoozed or dismissed suppressions for a subscription.
* The snoozed or dismissed attribute of a recommendation is referred to as a
* suppression.
*
* @param {object} [options] Optional Parameters.
*
* @param {number} [options.top] The number of suppressions per page if a paged
* version of this API is being used.
*
* @param {string} [options.skipToken] The page-continuation token to use with
* a paged version of this API.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<SuppressionContractListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { top? : number, skipToken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SuppressionContractListResult>>;
/**
* Retrieves the list of snoozed or dismissed suppressions for a subscription.
* The snoozed or dismissed attribute of a recommendation is referred to as a
* suppression.
*
* @param {object} [options] Optional Parameters.
*
* @param {number} [options.top] The number of suppressions per page if a paged
* version of this API is being used.
*
* @param {string} [options.skipToken] The page-continuation token to use with
* a paged version of this API.
*
* @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 {SuppressionContractListResult} - 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.
*
* {SuppressionContractListResult} [result] - The deserialized result object if an error did not occur.
* See {@link SuppressionContractListResult} 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.
*/
list(options?: { top? : number, skipToken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.SuppressionContractListResult>;
list(callback: ServiceCallback<models.SuppressionContractListResult>): void;
list(options: { top? : number, skipToken? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SuppressionContractListResult>): void;
/**
* Retrieves the list of snoozed or dismissed suppressions for a subscription.
* The snoozed or dismissed attribute of a recommendation is referred to as a
* suppression.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @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<SuppressionContractListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SuppressionContractListResult>>;
/**
* Retrieves the list of snoozed or dismissed suppressions for a subscription.
* The snoozed or dismissed attribute of a recommendation is referred to as a
* suppression.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @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 {SuppressionContractListResult} - 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.
*
* {SuppressionContractListResult} [result] - The deserialized result object if an error did not occur.
* See {@link SuppressionContractListResult} 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.
*/
listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SuppressionContractListResult>;
listNext(nextPageLink: string, callback: ServiceCallback<models.SuppressionContractListResult>): void;
listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SuppressionContractListResult>): void;
} | the_stack |
import * as Redis from 'ioredis';
import { Module, RedisModuleOptions } from '../module.base';
import { SearchCommander } from './redisearch.commander';
import {
FTAggregateParameters, FTConfig, FTCreateParameters, FTFieldOptions, FTFieldType, FTIndexType, FTInfo, FTSchemaField,
FTSearchParameters, FTSearchResponse, FTSpellCheck, FTSpellCheckResponse, FTSugAddParameters, FTSugGetParameters, FTAggregateResponse
} from './redisearch.types';
import { RedisearchHelpers } from './redisearch.helpers';
export class Redisearch extends Module {
private searchCommander = new SearchCommander();
private searchHelpers = new RedisearchHelpers();
/**
* Initializing the module object
* @param name The name of the module
* @param clusterNodes The nodes of the cluster
* @param moduleOptions The additional module options
* @param moduleOptions.isHandleError If to throw error on error
* @param moduleOptions.showDebugLogs If to print debug logs
* @param clusterOptions The options of the clusters
*/
constructor(clusterNodes: Redis.ClusterNode[], moduleOptions?: RedisModuleOptions, clusterOptions?: Redis.ClusterOptions)
/**
* Initializing the module object
* @param name The name of the module
* @param redisOptions The options of the redis database
* @param moduleOptions The additional module options
* @param moduleOptions.isHandleError If to throw error on error
* @param moduleOptions.showDebugLogs If to print debug logs
*/
constructor(redisOptions: Redis.RedisOptions, moduleOptions?: RedisModuleOptions)
constructor(options: Redis.RedisOptions & Redis.ClusterNode[], moduleOptions?: RedisModuleOptions, clusterOptions?: Redis.ClusterOptions) {
super(Redisearch.name, options, moduleOptions, clusterOptions)
}
/**
* Creating an index with a given spec
* @param index The index of the schema
* @param indexType The index type of the schema
* @param schemaFields The filter set after the 'SCHEMA' argument
* @param parameters The additional parameters of the spec
* @returns 'OK' or error
*/
async create(index: string, indexType: FTIndexType, schemaFields: FTSchemaField[], parameters?: FTCreateParameters): Promise<'OK' | string> {
const command = this.searchCommander.create(index, indexType, schemaFields, parameters);
const response = await this.sendCommand(command);
return this.handleResponse(response);
}
/**
* Searching the index with a textual query
* @param index The index
* @param query The query
* @param parameters The additional optional parameter
* @returns Array reply, where the first element is the total number of results, and then pairs of document id, and a nested array of field/value.
*/
async search(index: string, query: string, parameters?: FTSearchParameters): Promise<FTSearchResponse> {
const command = this.searchCommander.search(index, query, parameters);
const response = await this.sendCommand(command);
if(this.returnRawResponse === true) {
return this.handleResponse(response);
}
return this.searchHelpers.handleQueryResponse(response);
}
/**
* Runs a search query on an index, and performs aggregate transformations on the results, extracting statistics etc from them
* @param index The index
* @param query The query
* @param parameters The additional optional parameters
* @returns Array Response. Each row is an array and represents a single aggregate result
*/
async aggregate(index: string, query: string, parameters?: FTAggregateParameters): Promise<FTAggregateResponse> {
const command = this.searchCommander.aggregate(index, query, parameters);
const response = await this.sendCommand(command);
if(this.returnRawResponse === true) {
return this.handleResponse(response)
}
return this.searchHelpers.handleAggregateResponse(response);
}
/**
* Retrieving the execution plan for a complex query
* @param index The index
* @param query The query
* @returns Returns the execution plan for a complex query
*/
async explain(index: string, query: string): Promise<string> {
const command = this.searchCommander.explain(index, query);
const response = await this.sendCommand(command);
return this.handleResponse(response);
}
/**
* Retrieving the execution plan for a complex query but formatted for easier reading without using redis-cli --raw
* @param index The index
* @param query The query
* @returns A string representing the execution plan.
*/
async explainCLI(index: string, query: string): Promise<string[]> {
const command = this.searchCommander.explainCLI(index, query);
const response = await this.sendCommand(command);
return this.handleResponse(response.join(''));
}
/**
* Adding a new field to the index
* @param index The index
* @param field The field name
* @param fieldType The field type
* @param options The additional optional parameters
* @returns 'OK' or error
*/
async alter(index: string, field: string, fieldType: FTFieldType, options?: FTFieldOptions): Promise<'OK' | string> {
const command = this.searchCommander.alter(index, field, fieldType, options);
const response = await this.sendCommand(command);
return this.handleResponse(response);
}
/**
* Deleting the index
* @param index The index
* @param deleteHash If set, the drop operation will delete the actual document hashes.
* @returns 'OK' or error
*/
async dropindex(index: string, deleteHash = false): Promise<'OK' | string> {
const command = this.searchCommander.dropindex(index, deleteHash);
const response = await this.sendCommand(command);
return this.handleResponse(response);
}
/**
* Adding alias fron an index
* @param name The alias name
* @param index The alias index
* @returns 'OK' or error
*/
async aliasadd(name: string, index: string): Promise<'OK' | string> {
const command = this.searchCommander.aliasadd(name, index);
const response = await this.sendCommand(command);
return this.handleResponse(response);
}
/**
* Updating alias index
* @param name The alias name
* @param index The alias index
* @returns 'OK' or error
*/
async aliasupdate(name: string, index: string): Promise<'OK' | string> {
const command = this.searchCommander.aliasupdate(name, index);
const response = await this.sendCommand(command);
return this.handleResponse(response);
}
/**
* Deleting alias fron an index
* @param name The alias name
* @returns 'OK' or error
*/
async aliasdel(name: string): Promise<'OK' | string> {
const command = this.searchCommander.aliasdel(name);
const response = await this.sendCommand(command);
return this.handleResponse(response);
}
/**
* Retrieving the distinct tags indexed in a Tag field
* @param index The index
* @param field The field name
* @returns The distinct tags indexed in a Tag field
*/
async tagvals(index: string, field: string): Promise<string[]> {
const command = this.searchCommander.tagvals(index, field);
const response = await this.sendCommand(command);
return this.handleResponse(response);
}
/**
* Adds a suggestion string to an auto-complete suggestion dictionary
* @param key The key
* @param suggestion The suggestion
* @param score The score
* @param options The additional optional parameters
* @returns The current size of the suggestion dictionary
*/
async sugadd(key: string, suggestion: string, score: number, options?: FTSugAddParameters): Promise<number> {
const command = this.searchCommander.sugadd(key, suggestion, score, options);
const response = await this.sendCommand(command);
return this.handleResponse(response);
}
/**
* Retrieving completion suggestions for a prefix
* @param key The key
* @param prefix The prefix of the suggestion
* @param options The additional optional parameter
* @returns A list of the top suggestions matching the prefix, optionally with score after each entry
*/
async sugget(key: string, prefix: string, options?: FTSugGetParameters): Promise<string> {
const command = this.searchCommander.sugget(key, prefix, options);
const response = await this.sendCommand(command);
return this.handleResponse(response);
}
/**
* Deleting a string from a suggestion index
* @param key The key
* @param suggestion The suggestion
*/
async sugdel(key: string, suggestion: string): Promise<number> {
const command = this.searchCommander.sugdel(key, suggestion);
const response = await this.sendCommand(command);
return this.handleResponse(response);
}
/**
* Retrieving the size of an auto-complete suggestion dictionary
* @param key The key
*/
async suglen(key: string): Promise<number> {
const command = this.searchCommander.suglen(key);
const response = await this.sendCommand(command);
return this.handleResponse(response);
}
/**
* Updating a synonym group
* @param index The index
* @param groupId The group id
* @param terms A list of terms
* @param skipInitialScan If set, we do not scan and index.
* @returns 'OK'
*/
async synupdate(index: string, groupId: number, terms: string[], skipInitialScan = false): Promise<'OK'> {
const command = this.searchCommander.synupdate(index, groupId, terms, skipInitialScan);
const response = await this.sendCommand(command);
return this.handleResponse(response);
}
/**
* Dumps the contents of a synonym group
* @param index The index
* @returns A list of synonym terms and their synonym group ids.
*/
async syndump(index: string): Promise<{[key: string]: string | number}> {
const command = this.searchCommander.syndump(index);
const response = await this.sendCommand(command);
return this.handleResponse(response);
}
/**
* Performs spelling correction on a query
* @param index The index
* @param query The query
* @param options The additional optional parameters
* @returns An array, in which each element represents a misspelled term from the query
*/
async spellcheck(index: string, query: string, options?: FTSpellCheck): Promise<FTSpellCheckResponse[]> {
const command = this.searchCommander.spellcheck(index, query, options);
const response = await this.sendCommand(command);
return this.searchHelpers.handleSpellcheckResponse(response);
}
/**
* Adding terms to a dictionary
* @param dict The dictionary
* @param terms A list of terms
* @returns The number of new terms that were added
*/
async dictadd(dict: string, terms: string[]): Promise<number> {
const command = this.searchCommander.dictadd(dict, terms);
const response = await this.sendCommand(command);
return this.handleResponse(response);
}
/**
* Deleting terms from a dictionary
* @param dict The dictionary
* @param terms A list of terms
* @returns The number of terms that were deleted
*/
async dictdel(dict: string, terms: string[]): Promise<number> {
const command = this.searchCommander.dictdel(dict, terms);
const response = await this.sendCommand(command);
return this.handleResponse(response);
}
/**
* Dumps all terms in the given dictionary
* @param dict The dictionary
* @returns An array, where each element is term
*/
async dictdump(dict: string): Promise<string> {
const command = this.searchCommander.dictdump(dict);
const response = await this.sendCommand(command);
return this.handleResponse(response);
}
/**
* Retrieving infromation and statistics on the index
* @param index The index
* @returns A nested array of keys and values.
*/
async info(index: string): Promise<FTInfo> {
const command = this.searchCommander.info(index);
const response = await this.sendCommand(command);
return this.handleResponse(response);
}
/**
* Retrieves, describes and sets runtime configuration options
* @param commandType The command type
* @param option The option
* @param value In case of 'SET' command, a valid value to set
* @returns If 'SET' command, returns 'OK' for valid runtime-settable option names and values. If 'GET' command, returns a string with the current option's value.
*/
async config(commandType: 'GET' | 'SET' | 'HELP', option: string, value?: string): Promise<FTConfig> {
const command = this.searchCommander.config(commandType, option, value);
const response = await this.sendCommand(command);
return this.handleResponse(response);
}
} | the_stack |
import { expect, test } from '@oclif/test'
import { resolve } from 'path'
import chai from 'chai'
import spies from 'chai-spies'
import cmd from '../src'
import sinon from 'sinon'
import * as IpUtil from '../src/utils/public-ip'
chai.use(spies)
describe('monika', () => {
let getPublicIPStub: any
let getPublicNetworkInfoStub: any
beforeEach(() => {
getPublicIPStub = sinon.stub(IpUtil, 'getPublicIp' as never)
getPublicNetworkInfoStub = sinon.stub(
IpUtil,
'getPublicNetworkInfo' as never
)
})
afterEach(() => {
getPublicIPStub.restore()
getPublicNetworkInfoStub.restore()
})
// General Test
test
.stdout()
.do(() =>
cmd.run(['--config', resolve('./test/testConfigs/fullConfig.yml')])
)
.it('runs with full config', (ctx) => {
expect(ctx.stdout).to.contain('Starting Monika.')
})
test
.stdout()
.do(() =>
cmd.run([
'--config',
resolve('./test/testConfigs/fullConfig.yml'),
resolve('./test/testConfigs/manyProbes.yml'),
])
)
.it('runs multiple config override', (ctx) => {
expect(ctx.stdout).to.contain('Probes: 2.')
expect(ctx.stdout).to.contain('Notifications: 7')
})
test
.stdout()
.do(() =>
cmd.run([
'--config',
resolve('./test/testConfigs/fullConfig.yml'),
resolve('./test/testConfigs/manyNotif.yml'),
])
)
.it('runs multiple config override', (ctx) => {
expect(ctx.stdout).to.contain('Probes: 1.')
expect(ctx.stdout).to.contain('Notifications: 2')
})
test
.stdout()
.do(() => cmd.run(['--har', resolve('./test/testConfigs/harTest.har')]))
.it('runs with har file config', (ctx) => {
expect(ctx.stdout).to.contain('Starting Monika.')
})
test
.stdout()
.do(() =>
cmd.run([
'-c',
resolve('./test/testConfigs/manyNotif.yml'),
resolve('./test/testConfigs/manyProbes.yml'),
'--har',
resolve('./test/testConfigs/harTest.har'),
])
)
.it('merge har file with other config', (ctx) => {
expect(ctx.stdout).to.contain('Notifications: 2').and.contain('Probes: 1')
})
test
.stdout()
.do(() =>
cmd.run([
'--har',
resolve('./test/testConfigs/harTest.har'),
'-c',
resolve('./test/testConfigs/manyNotif.yml'),
resolve('./test/testConfigs/manyProbes.yml'),
])
)
.it('probes from har file will override regardless flag order', (ctx) => {
expect(ctx.stdout).to.contain('Notifications: 2').and.contain('Probes: 1')
})
test
.stdout()
.do(() =>
cmd.run([
'-c',
resolve('./test/testConfigs/manyNotif.yml'),
resolve('./test/testConfigs/manyProbes.yml'),
'--postman',
resolve('./test/testConfigs/simple.postman_collection.json'),
])
)
.it('merge postman file with other config', (ctx) => {
expect(ctx.stdout).to.contain('Notifications: 2').and.contain('Probes: 1')
})
test
.stdout()
.do(() =>
cmd.run([
'--postman',
resolve('./test/testConfigs/simple.postman_collection.json'),
'-c',
resolve('./test/testConfigs/manyNotif.yml'),
resolve('./test/testConfigs/manyProbes.yml'),
])
)
.it(
'probes from postman file will override regardless flag order',
(ctx) => {
expect(ctx.stdout)
.to.contain('Notifications: 2')
.and.contain('Probes: 1')
}
)
test
.stdout()
.do(() =>
cmd.run(['--config', resolve('./test/testConfigs/noInterval.yml')])
)
.it('runs with config without interval', (ctx) => {
expect(ctx.stdout).to.contain('Starting Monika.')
})
test
.stderr()
.do(() =>
cmd.run([
'--config',
resolve('./test/testConfigs/invalidNotificationType.yml'),
])
)
.catch((error) => {
expect(error.message).to.contain('Notifications type is not allowed')
})
.it('runs with config with invalid notification type')
// Probes Test
test
.stderr()
.do(() =>
cmd.run(['--config', resolve('./test/testConfigs/probes/noProbes.yml')])
)
.catch((error) => {
expect(error.message).to.contain(
'Probes object does not exists or has length lower than 1!'
)
})
.it('runs with config without probes')
test
.stdout()
.do(() =>
cmd.run([
'--config',
resolve('./test/testConfigs/probes/noProbeName.yml'),
])
)
.it('runs with config without probe name', (ctx) => {
expect(ctx.stdout).to.contain('Starting Monika.')
})
test
.stderr()
.do(() =>
cmd.run([
'--config',
resolve('./test/testConfigs/probes/noProbeRequest.yml'),
])
)
.catch((error) => {
expect(error.message).to.contain(
'Probe requests does not exists or has length lower than 1!'
)
})
.it('runs with config without probe request')
test
.stdout()
.do(() =>
cmd.run([
'--config',
resolve('./test/testConfigs/probes/noProbeAlerts.yml'),
])
)
.it('runs with config without probe alerts', (ctx) => {
expect(ctx.stdout).to.contain('Starting Monika.')
})
test
.stderr()
.do(() =>
cmd.run([
'--config',
resolve('./test/testConfigs/probes/invalidProbeRequestMethod.yml'),
])
)
.catch((error) => {
expect(error.message).to.contain(
'Probe request method is invalid! Valid methods are GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, PURGE, LINK, and UNLINK'
)
})
.it('runs with config with invalid probe request method')
test
.stderr()
.do(() =>
cmd.run([
'--config',
resolve('./test/testConfigs/probes/invalidProbeRequestURL.yml'),
])
)
.catch((error) => {
expect(error.message).to.contain(
'Probe request URL should start with http:// or https://'
)
})
.it('runs with config with invalid probe request URL')
test
.stderr()
.do(() =>
cmd.run([
'--config',
resolve('./test/testConfigs/probes/invalidProbeRequestAlert.yml'),
])
)
.catch((error) => {
expect(error.message).to.contain('Probe alert format is invalid!')
})
.it('runs with config with invalid probe request alert')
test
.stdout()
.do(() =>
cmd.run([
'--config',
resolve('./test/testConfigs/probes/stringProbeRequestAlert.yml'),
])
)
.it(
'runs with config with probe request alert in defined strings',
(ctx) => {
expect(ctx.stdout).to.contain('Starting Monika.')
}
)
test
.stdout()
.do(() =>
cmd.run([
'--config',
resolve('./test/testConfigs/probes/objectProbeRequestAlert.yml'),
])
)
.it(
'runs with config with probe request alert in object format with flexible query',
(ctx) => {
expect(ctx.stdout).to.contain('Starting Monika.')
}
)
test
.stdout()
.do(() =>
cmd.run([
'--config',
resolve('./test/testConfigs/probes/multipleProbeRequests.yml'),
])
)
.it('runs with multiple probe requests config', (ctx) => {
expect(ctx.stdout).to.contain('Starting Monika.')
})
test
.stdout()
.do(() =>
cmd.run([
'--config',
resolve('./test/testConfigs/probes/chainingRequests.yml'),
])
)
.it('runs with chaining probe requests config', (ctx) => {
expect(ctx.stdout).to.contain('Starting Monika.')
})
// Mailgun Tests
test
.stdout()
.do(() =>
cmd.run([
'--config',
resolve('./test/testConfigs/mailgun/mailgunconfig.yml'),
'--verbose',
])
)
.it('runs with mailgun config', (ctx) => {
expect(ctx.stdout).to.contain('Type: mailgun')
expect(ctx.stdout).to.contain('Domain:')
})
test
.stderr()
.do(() =>
cmd.run([
'--config',
resolve('./test/testConfigs/mailgun/mailgunconfigNoRecipients.yml'),
])
)
.catch((error) => {
expect(error.message).to.contain(
'Recipients does not exists or has length lower than 1!'
)
})
.it('runs with mailgun config but without recipients')
// Sendgrid Tests
test
.stdout()
.do(() =>
cmd.run([
'--config',
resolve('./test/testConfigs/sendgrid/sendgridconfig.yml'),
'--verbose',
])
)
.it('runs with sendgrid config', (ctx) => {
expect(ctx.stdout).to.contain('Type: sendgrid')
})
test
.stderr()
.do(() =>
cmd.run([
'--config',
resolve('./test/testConfigs/sendgrid/sendgridconfigNoRecipients.yml'),
])
)
.catch((error) => {
expect(error.message).to.contain(
'Recipients does not exists or has length lower than 1!'
)
})
.it('runs with sendgrid config but without recipients')
// SMTP Tests
test
.stdout()
.do(() =>
cmd.run([
'--config',
resolve('./test/testConfigs/smtp/smtpconfig.yml'),
'--verbose',
])
)
.it('runs with SMTP config', (ctx) => {
expect(ctx.stdout).to.contain('Type: smtp')
expect(ctx.stdout).to.contain('Hostname:')
expect(ctx.stdout).to.contain('Port:')
expect(ctx.stdout).to.contain('Username:')
})
test
.stderr()
.do(() =>
cmd.run([
'--config',
resolve('./test/testConfigs/smtp/smtpconfigNoRecipients.yml'),
])
)
.catch((error) => {
expect(error.message).to.contain(
'Recipients does not exists or has length lower than 1!'
)
})
.it('runs with SMTP config but without recipients')
// Webhook Tests
test
.stdout()
.do(() =>
cmd.run([
'--config',
resolve('./test/testConfigs/webhook/webhookconfig.yml'),
'--verbose',
])
)
.it('runs with Webhook config', (ctx) => {
expect(ctx.stdout).to.contain('URL:')
expect(ctx.stdout).to.contain('Method:')
})
// Discord Tests
test
.stdout()
.do(() =>
cmd.run([
'--config',
resolve('./test/testConfigs/discord/discordconfig.yml'),
'--verbose',
])
)
.it('runs with Discord config', (ctx) => {
expect(ctx.stdout).to.contain('URL:')
})
// Teams Tests
test
.stdout()
.do(() =>
cmd.run([
'--config',
resolve('./test/testConfigs/teams/teamsconfig.yml'),
'--verbose',
])
)
.it('runs with Teams config', (ctx) => {
expect(ctx.stdout).to.contain('URL:')
expect(ctx.stdout).to.contain('Method:')
})
test
.stderr()
.do(() =>
cmd.run([
'--config',
resolve('./test/testConfigs/teams/teamsconfigNoURL.yml'),
])
)
.catch((error) => {
expect(error.message).to.contain('Teams Webhook URL not found')
})
.it('runs with teams config but without webhook url')
test
.stdout()
.do(() =>
cmd.run([
'--config',
resolve('./test/testConfigs/monika-notif/monikaNotifconfig.yml'),
'--verbose',
])
)
.it('runs with Monika-Notif config', (ctx) => {
expect(ctx.stdout).to.contain('URL:')
})
}) | the_stack |
import { browser, ExpectedConditions as until } from 'protractor';
import { execSync } from 'child_process';
import { appHost, checkLogs, checkErrors, testName } from '../protractor.conf';
import * as crudView from '../views/crud.view';
import * as oauthView from '../views/oauth.view';
describe('OAuth', () => {
const oauthSettingsURL = `${appHost}/k8s/cluster/config.openshift.io~v1~OAuth/cluster`;
let originalOAuthConfig: any;
beforeAll(() => {
originalOAuthConfig = JSON.parse(execSync('kubectl get -o json oauths cluster').toString());
});
afterAll(() => {
const idpJSON = JSON.stringify(originalOAuthConfig.spec.identityProviders);
execSync(
`kubectl patch oauths cluster --type json -p='[{ op: 'replace', path: '/spec/identityProviders', value: ${idpJSON}}]'`,
);
});
afterEach(() => {
checkLogs();
checkErrors();
});
// TODO: Add tests for HTPasswd and Request Header identity providers.
// These IDPs require file upload.
describe('BasicAuth IDP', () => {
const idpName = `basic-auth-${testName}`;
it('creates a Basic Authentication IDP', async () => {
await browser.get(oauthSettingsURL);
await browser.wait(until.elementToBeClickable(oauthView.addIDPDropdown));
await oauthView.addIDPDropdown.click();
await browser.wait(until.elementToBeClickable(oauthView.basicAuthLink));
await oauthView.basicAuthLink.click();
await browser.wait(until.elementToBeClickable(oauthView.idpNameInput));
await oauthView.idpNameInput.clear();
await oauthView.idpNameInput.sendKeys(idpName);
await oauthView.basicAuthURLInput.sendKeys('https://example.com');
await oauthView.addIDPButton.click();
expect(oauthView.errorMessage.isPresent()).toBe(false);
});
it('shows the BasicAuth IDP on the OAuth settings page', async () => {
await browser.wait(until.presenceOf(crudView.resourceTitle));
expect(browser.getCurrentUrl()).toContain('config.openshift.io~v1~OAuth/cluster');
await crudView.isLoaded();
expect(oauthView.idpTableCellName(idpName).getText()).toEqual(idpName);
expect(oauthView.idpTableCellType(idpName).getText()).toEqual('BasicAuth');
expect(oauthView.idpTableCellMapping(idpName).getText()).toEqual('claim');
});
});
describe('GitHub IDP', () => {
const idpName = `github-${testName}`;
it('creates a GitHub IDP', async () => {
await browser.get(oauthSettingsURL);
await browser.wait(until.elementToBeClickable(oauthView.addIDPDropdown));
await oauthView.addIDPDropdown.click();
await browser.wait(until.elementToBeClickable(oauthView.githubLink));
await oauthView.githubLink.click();
await browser.wait(until.elementToBeClickable(oauthView.idpNameInput));
await oauthView.idpNameInput.clear();
await oauthView.idpNameInput.sendKeys(idpName);
await oauthView.githubClientIDInput.sendKeys('my-client-id');
await oauthView.githubClientSecretInput.sendKeys('my-client-secret');
await oauthView.githubOrganizationInput.sendKeys('my-organization');
await oauthView.addIDPButton.click();
expect(oauthView.errorMessage.isPresent()).toBe(false);
});
it('shows the GitHub IDP on the OAuth settings page', async () => {
await browser.wait(until.presenceOf(crudView.resourceTitle));
expect(browser.getCurrentUrl()).toContain('config.openshift.io~v1~OAuth/cluster');
await crudView.isLoaded();
expect(oauthView.idpTableCellName(idpName).getText()).toEqual(idpName);
expect(oauthView.idpTableCellType(idpName).getText()).toEqual('GitHub');
expect(oauthView.idpTableCellMapping(idpName).getText()).toEqual('claim');
});
});
describe('GitLab IDP', () => {
const idpName = `gitlab-${testName}`;
it('creates a GitLab IDP', async () => {
await browser.get(oauthSettingsURL);
await browser.wait(until.elementToBeClickable(oauthView.addIDPDropdown));
await oauthView.addIDPDropdown.click();
await browser.wait(until.elementToBeClickable(oauthView.gitlabLink));
await oauthView.gitlabLink.click();
await browser.wait(until.elementToBeClickable(oauthView.idpNameInput));
await oauthView.idpNameInput.clear();
await oauthView.idpNameInput.sendKeys(idpName);
await oauthView.gitlabURLInput.sendKeys('https://example.com');
await oauthView.gitlabClientIDInput.sendKeys('my-client-id');
await oauthView.gitlabClientSecretInput.sendKeys('my-client-secret');
await oauthView.addIDPButton.click();
expect(oauthView.errorMessage.isPresent()).toBe(false);
});
it('shows the GitLab IDP on the OAuth settings page', async () => {
await browser.wait(until.presenceOf(crudView.resourceTitle));
expect(browser.getCurrentUrl()).toContain('config.openshift.io~v1~OAuth/cluster');
await crudView.isLoaded();
expect(oauthView.idpTableCellName(idpName).getText()).toEqual(idpName);
expect(oauthView.idpTableCellType(idpName).getText()).toEqual('GitLab');
expect(oauthView.idpTableCellMapping(idpName).getText()).toEqual('claim');
});
});
describe('Google IDP', () => {
const idpName = `google-${testName}`;
it('creates a Google IDP', async () => {
await browser.get(oauthSettingsURL);
await browser.wait(until.elementToBeClickable(oauthView.addIDPDropdown));
await oauthView.addIDPDropdown.click();
await browser.wait(until.elementToBeClickable(oauthView.googleLink));
await oauthView.googleLink.click();
await browser.wait(until.elementToBeClickable(oauthView.idpNameInput));
await oauthView.idpNameInput.clear();
await oauthView.idpNameInput.sendKeys(idpName);
await oauthView.googleClientIDInput.sendKeys('my-client-id');
await oauthView.googleClientSecretInput.sendKeys('my-client-secret');
await oauthView.googleHostedDomainInput.sendKeys('example.com');
await oauthView.addIDPButton.click();
expect(oauthView.errorMessage.isPresent()).toBe(false);
});
it('shows the Google IDP on the OAuth settings page', async () => {
await browser.wait(until.presenceOf(crudView.resourceTitle));
expect(browser.getCurrentUrl()).toContain('config.openshift.io~v1~OAuth/cluster');
await crudView.isLoaded();
expect(oauthView.idpTableCellName(idpName).getText()).toEqual(idpName);
expect(oauthView.idpTableCellType(idpName).getText()).toEqual('Google');
expect(oauthView.idpTableCellMapping(idpName).getText()).toEqual('claim');
});
});
describe('Keystone IDP', () => {
const idpName = `keystone-${testName}`;
it('creates a Keystone IDP', async () => {
await browser.get(oauthSettingsURL);
await browser.wait(until.elementToBeClickable(oauthView.addIDPDropdown));
await oauthView.addIDPDropdown.click();
await browser.wait(until.elementToBeClickable(oauthView.keystoneLink));
await oauthView.keystoneLink.click();
await browser.wait(until.elementToBeClickable(oauthView.idpNameInput));
await oauthView.idpNameInput.clear();
await oauthView.idpNameInput.sendKeys(idpName);
await oauthView.keystoneDomainInput.sendKeys('example.com');
await oauthView.keystoneURLInput.sendKeys('https://example.com');
await oauthView.addIDPButton.click();
expect(oauthView.errorMessage.isPresent()).toBe(false);
});
it('shows the Keystone IDP on the OAuth settings page', async () => {
await browser.wait(until.presenceOf(crudView.resourceTitle));
expect(browser.getCurrentUrl()).toContain('config.openshift.io~v1~OAuth/cluster');
await crudView.isLoaded();
expect(oauthView.idpTableCellName(idpName).getText()).toEqual(idpName);
expect(oauthView.idpTableCellType(idpName).getText()).toEqual('Keystone');
expect(oauthView.idpTableCellMapping(idpName).getText()).toEqual('claim');
});
});
describe('LDAP IDP', () => {
const idpName = `ldap-${testName}`;
it('creates a LDAP IDP', async () => {
await browser.get(oauthSettingsURL);
await browser.wait(until.elementToBeClickable(oauthView.addIDPDropdown));
await oauthView.addIDPDropdown.click();
await browser.wait(until.elementToBeClickable(oauthView.ldapLink));
await oauthView.ldapLink.click();
await browser.wait(until.elementToBeClickable(oauthView.idpNameInput));
await oauthView.idpNameInput.clear();
await oauthView.idpNameInput.sendKeys(idpName);
await oauthView.ldapURLInput.sendKeys('ldap://ldap.example.com/o=Acme?cn?sub?(enabled=true)');
await oauthView.addIDPButton.click();
expect(oauthView.errorMessage.isPresent()).toBe(false);
});
it('shows the LDAP IDP on the OAuth settings page', async () => {
await browser.wait(until.presenceOf(crudView.resourceTitle));
expect(browser.getCurrentUrl()).toContain('config.openshift.io~v1~OAuth/cluster');
await crudView.isLoaded();
expect(oauthView.idpTableCellName(idpName).getText()).toEqual(idpName);
expect(oauthView.idpTableCellType(idpName).getText()).toEqual('LDAP');
expect(oauthView.idpTableCellMapping(idpName).getText()).toEqual('claim');
});
});
describe('OpenID IDP', () => {
const idpName = `oidc-${testName}`;
it('creates a OpenID IDP', async () => {
await browser.get(oauthSettingsURL);
await browser.wait(until.elementToBeClickable(oauthView.addIDPDropdown));
await oauthView.addIDPDropdown.click();
await browser.wait(until.elementToBeClickable(oauthView.oidcLink));
await oauthView.oidcLink.click();
await browser.wait(until.elementToBeClickable(oauthView.idpNameInput));
await oauthView.idpNameInput.clear();
await oauthView.idpNameInput.sendKeys(idpName);
await oauthView.oidcClientIDInput.sendKeys('my-client-id');
await oauthView.oidcClientSecretInput.sendKeys('my-client-secret');
await oauthView.oidcIssuerInput.sendKeys('https://example.com');
await oauthView.addIDPButton.click();
expect(oauthView.errorMessage.isPresent()).toBe(false);
});
it('shows the OpenID IDP on the OAuth settings page', async () => {
await browser.wait(until.presenceOf(crudView.resourceTitle));
expect(browser.getCurrentUrl()).toContain('config.openshift.io~v1~OAuth/cluster');
await crudView.isLoaded();
expect(oauthView.idpTableCellName(idpName).getText()).toEqual(idpName);
expect(oauthView.idpTableCellType(idpName).getText()).toEqual('OpenID');
expect(oauthView.idpTableCellMapping(idpName).getText()).toEqual('claim');
});
});
}); | the_stack |
import dayjs from 'dayjs';
import type { ForwardedRef, Ref } from 'react';
import React, {
useCallback,
useContext,
useEffect,
useImperativeHandle,
useMemo,
useRef,
useState,
} from 'react';
import { Platform, ScrollView, useWindowDimensions, View } from 'react-native';
import Animated, { FadeInDown, FadeOutUp } from 'react-native-reanimated';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import {
DataProvider,
LayoutProvider,
RecyclerListView,
} from 'recyclerlistview';
import type { ScrollEvent } from 'recyclerlistview/dist/reactnative/core/scrollcomponent/BaseScrollView';
import { ChatBubble } from './ChatBubble';
import { PropsContext } from './Chatty';
import { FAB, IFabRef } from './components/FAB';
import { LoadEarlier } from './components/LoadEarlier';
import { RenderDate } from './components/RenderDate';
import { TypingStatus } from './components/TypingStatus';
import { useHaptic } from './hooks/useHaptic';
import { usePrevious } from './hooks/usePrevious';
import { SwipeableBubble } from './SwipeableBubble';
import {
HapticType,
IListProps,
IMessage,
ITypingStatusRef,
LayoutType,
ListRef,
} from './types/Chatty.types';
import { ChatBubbleEmitter } from './utils/eventEmitter';
import { hapticEngine } from './utils/hapticEngine';
import { wait } from './utils/helpers';
const ScrollViewWithHeader = React.forwardRef(
({ children, ...props }, ref: Ref<ScrollView>) => {
const propsContext = useContext(PropsContext);
return (
<ScrollView ref={ref} {...props}>
{propsContext?.loadEarlierProps &&
propsContext.loadEarlierProps.show && (
<LoadEarlier {...propsContext.loadEarlierProps} />
)}
{children}
</ScrollView>
);
}
);
export const List = React.forwardRef(
(props: IListProps, ref: ForwardedRef<ListRef>) => {
const propsContext = useContext(PropsContext);
const recyclerlistviewRef = useRef<RecyclerListView<any, any>>();
const windowDimensions = useWindowDimensions();
const safeArea = useSafeAreaInsets();
const { trigger } = useHaptic();
const fabRef = useRef<IFabRef>(null);
const typingStatusRef = useRef<ITypingStatusRef>(null);
const listHeight = useMemo(
() => windowDimensions.height - 150 - safeArea.bottom - safeArea.top,
[windowDimensions, safeArea]
);
const { rowRenderer: rowRendererProp, data } = props;
const dataProvider = useMemo<DataProvider>(() => {
return new DataProvider((r1: IMessage, r2: IMessage) => {
if (r1.id !== r2.id) {
return true;
}
return false;
});
}, []);
const [messages, setMessages] = useState<DataProvider>(dataProvider);
const previousMessages = usePrevious<DataProvider>(messages);
/* This is a React Hook that is used to update the messages list when new messages are added. */
useEffect(() => {
setMessages(dataProvider.cloneWithRows(data));
}, [data, dataProvider]);
/* This code is listening to the event of a reply bubble being pressed. When it is pressed, it scrolls
to the replied message. */
useEffect(() => {
// When reply is pressed, scroll to replied message
ChatBubbleEmitter.addListener('replyBubblePressed', (messageId) => {
const index = messages
.getAllData()
.findIndex((m) => m.id === messageId);
if (index !== -1) {
recyclerlistviewRef.current?.scrollToIndex(index, true);
}
});
return () => {
ChatBubbleEmitter.removeAllListeners();
};
}, [messages]);
/* Using the useImperativeHandle hook to expose a function to the parent component that will allow
it to manipulate the messages list. */
useImperativeHandle(
ref,
() => ({
appendMessage: (
message: IMessage | IMessage[],
firstIndex?: boolean
) => {
if (firstIndex) {
if (Array.isArray(message)) {
setMessages(
dataProvider.cloneWithRows([
...message,
...messages.getAllData(),
])
);
} else {
setMessages(
dataProvider.cloneWithRows([message, ...messages.getAllData()])
);
}
} else {
if (Array.isArray(message)) {
setMessages(
dataProvider.cloneWithRows([
...messages.getAllData(),
...message,
])
);
} else {
setMessages(
dataProvider.cloneWithRows([...messages.getAllData(), message])
);
}
}
if (!Array.isArray(message)) {
if (!message.me && propsContext?.enableHapticFeedback) {
if (Platform.OS !== 'web' && hapticEngine)
trigger(HapticType.Heavy);
}
}
},
/* This is a function that is used to scroll to the bottom of the list. */
scrollToEnd: (animated?: boolean) => {
recyclerlistviewRef.current?.scrollToEnd(animated);
},
/* Setting the typing status of the user. */
setIsTyping: (typing?: boolean) => {
typingStatusRef.current?.setIsTyping(typing ?? false);
recyclerlistviewRef.current?.scrollToEnd(true);
},
/* Removing a message from the list of messages. */
removeMessage: (id: number) => {
setMessages(
dataProvider.cloneWithRows(
messages.getAllData().filter((message) => message.id !== id)
)
);
},
}),
[dataProvider, messages, propsContext.enableHapticFeedback, trigger]
);
/* This code is checking if the first message in the previous messages is the same as the first message
in the current messages. If it is, then it will not scroll to the bottom. */
useEffect(() => {
if (
previousMessages &&
previousMessages.getAllData()![0]?.id === messages.getAllData()![0]?.id
) {
wait(100).then(() => {
recyclerlistviewRef.current?.scrollToEnd(true);
});
}
}, [ref, messages, previousMessages]);
const layoutProvider = useCallback(() => {
return new LayoutProvider(
(index) => {
const currentMessage: IMessage = messages.getAllData()[index];
const prevMessage: IMessage = messages.getAllData()[index - 1];
if (currentMessage.text.length >= 600) {
return LayoutType.ExtremeLong;
}
if (currentMessage.text.length >= 400) {
return LayoutType.Long3x;
}
if (currentMessage.text.length >= 200) {
return LayoutType.Long2x;
}
if (currentMessage.text.length >= 100) {
return LayoutType.Long;
}
if (currentMessage?.media) {
if (currentMessage.media.length > 2) {
return LayoutType.Media2x;
}
return LayoutType.Media;
}
if (currentMessage.repliedTo) {
return LayoutType.Replied;
}
const isFirstMessage = index === 0;
if (
(!isFirstMessage &&
dayjs(currentMessage.createdAt).date() !==
dayjs(prevMessage.createdAt).date()) ||
isFirstMessage
) {
return LayoutType.Dated;
}
return LayoutType.Normal;
},
(type, dim) => {
dim.width = windowDimensions.width;
switch (type) {
case LayoutType.Normal:
dim.height = 85;
break;
case LayoutType.Replied:
dim.height = 190;
break;
case LayoutType.Dated:
dim.height = 110;
break;
case LayoutType.Long:
dim.height = 130;
break;
case LayoutType.Long2x:
dim.height = 170;
break;
case LayoutType.Long3x:
dim.height = 350;
break;
case LayoutType.ExtremeLong:
dim.height = 550;
break;
case LayoutType.Media:
dim.height = 180;
break;
case LayoutType.Media2x:
dim.height = 300;
break;
default:
dim.height = 85;
break;
}
}
);
}, [messages, windowDimensions.width]);
const renderBubble = useCallback(
(data: IMessage, withDate?: boolean) => {
if (rowRendererProp) {
return (
<View>
{withDate && (
<RenderDate
date={data.createdAt}
{...propsContext.renderDateProps}
/>
)}
<Animated.View entering={FadeInDown} exiting={FadeOutUp}>
<SwipeableBubble message={data} onReply={propsContext.onReply}>
{rowRendererProp(data)}
</SwipeableBubble>
</Animated.View>
</View>
);
}
return (
<View style={{ width: '100%' }}>
{withDate && (
<RenderDate
date={data.createdAt}
{...propsContext.renderDateProps}
/>
)}
<Animated.View entering={FadeInDown} exiting={FadeOutUp}>
{propsContext.onReply ? (
<>
<SwipeableBubble
message={data}
onReply={propsContext.onReply}
/>
</>
) : (
<ChatBubble message={data} />
)}
</Animated.View>
</View>
);
},
[propsContext.onReply, propsContext.renderDateProps, rowRendererProp]
);
const rowRenderer = useCallback(
(type, data: IMessage) => {
if (type === LayoutType.Dated) {
return renderBubble(data, true);
}
return renderBubble(data);
},
[renderBubble]
);
const onScroll = useCallback(
(e: ScrollEvent, offsetX: number, offsetY: number) => {
if (e.nativeEvent.contentOffset.y <= 0) {
fabRef.current?.show();
} else {
fabRef.current?.hide();
}
if (props.onScroll) {
props.onScroll(e, offsetX, offsetY);
}
},
[props]
);
const scrollToBottom = useCallback(() => {
recyclerlistviewRef.current?.scrollToEnd(true);
}, []);
return (
<View style={{ minWidth: 1, minHeight: 1, maxHeight: listHeight }}>
{propsContext.showScrollToBottomButton && (
<FAB
ref={fabRef}
onPress={scrollToBottom}
{...propsContext.scrollToBottomProps}
/>
)}
<RecyclerListView
layoutProvider={layoutProvider()}
externalScrollView={ScrollViewWithHeader}
dataProvider={messages}
style={[
{
height: propsContext.replyingTo ? '90%' : '100%',
},
props.containerStyle,
]}
// @ts-ignore
ref={recyclerlistviewRef}
scrollViewProps={{
keyboardShouldPersistTaps: 'never',
}}
onScroll={onScroll}
optimizeForInsertDeleteAnimations
forceNonDeterministicRendering
canChangeSize={true}
rowRenderer={rowRenderer}
renderFooter={() => <TypingStatus ref={typingStatusRef} />}
onEndReached={props?.onEndReached}
onEndReachedThreshold={props?.onEndReachedThreshold}
/>
</View>
);
}
); | the_stack |
/**
*
* Copyright 2018 Infosys Ltd.
* Use of this source code is governed by MIT license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.”
*
**/
import { Injectable } from "@angular/core";
import { Router } from "@angular/router";
@Injectable()
export class IdpdataService {
constructor() { }
template: any = {
"artifactVariable": false,
"artifactAppVariable": false,
"grantAccess": {
"applicationName": "",
"developers": [],
"pipelineAdmins": [],
"releaseManager": [],
"checkMarxDetails": {
"checkmarxBtn": "",
"checkmarxUrl": "",
"checkmarxUname": "",
"checkmarxPwd": ""
},
"artifactToStage": {},
"environmentOwnerDetails": [{
"environmentName": "",
"environmentOwners": [],
"dBOwners": []
}],
"virtualServiceServerDetails": {},
"slaveDetails": [
{
"slaveName": "",
"buildServerOS": "",
"workspacePath": "",
"createNewSlave": "",
"labels": "",
"sshKeyPath": "",
"slaveUsage": "both",
"build": "off",
"deploy": "off",
"test": "off"
}
]
},
"basicInfo": {
"additionalMailRecipients": {
"applicationTeam": "",
"emailIds": "",
"userName": ""
},
"pipelineStatus": "create",
"applicationName": "",
"buildInterval": {
"buildInterval": "",
"buildIntervalValue": 0,
"pollSCM": "off"
},
"buildServerOS": "",
"engine": "",
"pipelineName": "",
"pipelineType": "",
"rmsComponentName": "",
"customPipelineAdmins": [
]
},
"code": {
"category": "",
"technology": "",
"subApplication": "",
"scm": [],
"jobParam" : [],
"buildScript": [{ "tool": "" }, { "tool": "" }, {}]
},
"buildInfo": {
"buildtool": "",
"castAnalysis": {},
"artifactToStage": {},
"securityAnalysisTool":"",
"checkmarxAnalysis":{
"excludeFiles": "",
"excludeFileso": "",
"sastHigh": "",
"sastMedium": "",
"sastLow": "",
"enableOSA": "off",
"scanTag": "off",
"team": "",
"preset": ""
},
// "checkMarxAction":{"excludeFileso": ""},
"modules": []
},
"deployInfo": {
"deployEnv": []
},
"testInfo": {
"testEnv": []
},
"formStatus": {
"basicInfo": {
"appNameStatus": "0",
"formStatus": "0"
},
"codeInfo": "",
"buildInfo": {
"buildToolStatus": "0",
"formStatus": "0",
"ibmsiTypeStatus": "0"
},
"deployInfo": "",
"testInfo": "",
"operation": ""
},
"checkboxStatus": {
"basicInfo": {},
"codeInfo": {},
"buildInfo": {},
"deployInfo": {},
"testInfo": {},
"others": {}
},
"backUp": {
"deployInfo": {},
"testInfo": {}
},
"masterJson": {},
"pipelineList": []
};
releaseManagerTemplate: any = {
"applicationName": "",
"releasePipeline": [
{
"pipelineName": "",
"release": [
{
"actualEndDate": "",
"actualStartDate": "",
"additionalMailRecipients": {
"applicationTeam": "",
"emailIds": ""
},
"branchList": [
"na"
],
"expectedEndDate": "",
"expectedStartDate": "",
"releaseNumber": "",
"remarks": "",
"status": "on",
"vstsReleaseName": ""
}
]
}
]
};
passwordEncryptionList: any = {
"code.scm": ["password", "PSpassword"],
"code.buildScript": ["password"],
"buildInfo": ["password", "artifactToStage.artifactRepo.repoPassword", "artifactToStage.artifactRepo.passwordDR", "postBuildScript.password"],
"buildInfo.modules": ["npmProxyPassword", "password", "pegaPassword", "pegaDBPwd", "destPassword", "siebelPassword", "ipcPassword",
"servPass", "publishForms.password", "publishForms.dbPassword","sonarPassword",
"workFlowPublish.password", "workFlowPublish.dbPassword", "proxy.password", "sourcePassword"],
"deployInfo.deployEnv.deploySteps": ["password", "ipcPassword", "dbPassword", "dbpassword", "dbpasswordOTM",
"dbPasswordOTM", "dbOwnerPassword", "bizPassword", "formsDbPass", "databasePassword", "ddltmpPassword",
"datExportPassword", "workFlowDbPass", "deployPassword", "scalaPassword", "pigPassword", "hivePassword", "dbPwd", "staticPassword",
"srfPassword", "admPassword", "adminPassword", "dbOwnerPassword", "appsPass", "tomPwd",
"runScript.password", "deployToContainer.password", "deployToContainer.adminPassword",
"deployToContainer.sshPassword", "deployToContainer.proxypw","deployToContainer.dbOwnerPassword",
"deployToContainer.staticFiles.password", "deployDatabase.restorpassword",
"deployDatabase.dbpassword", "targetPassword", "proxy.password"],
"testInfo.testEnv.testSteps": ["runScript.password", "test.password"],
"virtualServiceServerDetails": ["password"]
};
propertySCM: any = {
};
pipelineListRm= "";
releaseManagerData= JSON.parse(JSON.stringify(this.releaseManagerTemplate));
data: any = JSON.parse(JSON.stringify(this.template));
language = "english";
idpUserName = "";
roles = [];
azureadflag= false;
isRepoSelected= false;
expireTime: any;
access_token: any;
permissions = [];
createAppflag = false;
createOrganisationflag = false;
createLicenseflag = false;
createPipelineflag = false;
copyPipelineflag = false;
insightsFlag=false;
cloudDeployFlag=false;
editPipelineflag = false;
deletePipelineflag = false;
test = false;
loadReleasePage= false;
devServerURL: any = "";
subscriptionServerURL: any = "";
IDPDashboardURL = "";
IDPLink = "";
geUrl = "";
role = "";
profile = "";
pausedBuildsData: any= {};
checkPausedBuilds: any= false;
allFormStatus: any= {
"basicInfo": false,
"codeInfo": false,
"buildInfo": false,
"deployInfo": false,
"testInfo": false,
"workflowInfo": false
};
IDPDropdownProperties: any = {};
showConfig: any;
pa= true;
continuecontrol: any;
geFlag: any;
p: any = false;
ejbVal: any;
warVal: any;
jarVal: any;
cloudDeployURL: any;
pipelineData: any;
triggerJobData: any;
jobParamList: any;
application: any;
freezeNavBars= false;
osFlag: any;
op: any;
operation: any;
initMain: any = false;
RestApiDetails: any = false;
buildInfoReset = false;
compMove: any;
unit: any;
uName: any= "";
pass: any= "";
code: any;
serverUrl= "";
copyEditOperation=false;
checkMarxData: any;
authorization= "";
unitTest: any= false;
artifactVariable: any= false;
artifactAppVariable: any= false;
public loading = false;
refreshBuild= false;
showRelease= false;
isSAPApplication= false;
checkpollALM: boolean ;
SAPScmCheck: any ;
landscapeName: any= "";
SAPEnvList: any= [];
VariantNameList: any= [];
SapBuildTemp: any;
SAPdataEvnDetails: any = [{
"client": "",
"dbowners": "",
"environmentName": "",
"environmentOwners": "",
"hostName": "",
"instanceNumber": "",
"landscapeType": "",
"language": "",
"password": "",
"userName": ""
}];
SAPdata: any = {
"grantAccess": {
"applicationName": "",
"checkMarxDetails": {
"checkmarxBtn": "",
"checkmarxUrl": "",
"checkmarxUname": "",
"checkmarxPwd": ""
},
"developers": [],
"pipelineAdmins": [],
"releaseManager": [],
"virtualServiceServerDetails": {},
"environmentOwnerDetails": [{
"client": "string",
"dbowners": "string",
"environmentName": "",
"environmentOwners": "",
"hostName": "",
"instanceNumber": "",
"landscapeType": "",
"language": "",
"password": "",
"userName": ""
}],
"slaveDetails": [
{
"slaveName": "",
"buildServerOS": "",
"workspacePath": "",
"createNewSlave": "",
"labels": "",
"sshKeyPath": "",
"slaveUsage": "both",
"build": "off",
"deploy": "off",
"test": "off"
}
]
},
"basicInfo": {
"applicationName": "",
"pipelineName": "",
"buildServerOS": "",
"engine": "",
"buildInterval": {
"pollSCM": "",
"buildInterval": "",
"buildIntervalValue": "0",
"pollALM": "",
"almTool": "",
"projectKey": ""
},
"additionalMailRecipients": {
"applicationTeam": "",
"emailIds": ""
}
},
"code": {
"category": "",
"technology": "",
"scm": [],
"jobParam" : [],
"buildScript": [
{
"tool": "",
},
{
"tool": "",
}
]
},
"buildInfo": {
"buildtool": "",
"checkmarxAnalysis":{
"excludeFiles": "",
"excludeFileso": "",
"sastHigh": "",
"sastMedium": "",
"sastLow": "",
"enableOSA": "off",
"scanTag": "off",
"team": "",
"preset": ""
},
// "checkMarxAction":{"excludeFileso": ""},
"castAnalysis": {
"applicationName": "",
"srcPath": "",
"connectionProfile": "",
"schemaName": "",
"landscapeName": ""
},
"artifactToStage": {},
"securityAnalysisTool":"",
"modules": [
{
"codeAnalysis": [
""
],
"unitTesting": "",
"inspectionName": "",
"varient": "",
"raiseJiraBug": "",
"landscapeName": ""
}
]
},
"deployInfo": {
"deployEnv": [
{
"envName": "",
"approver": "",
"deploySteps": [
{
}
]
}
]
},
"testInfo": {
"testEnv": [
{
"envName": "",
"testSteps": [
{
}
]
}
]
},
"formStatus": {
"basicInfo": {
"appNameStatus": "",
"formStatus": ""
},
"codeInfo": "",
"buildInfo": {
"buildToolStatus": "0",
"formStatus": "0",
"ibmsiTypeStatus": "0"
},
"deployInfo": "",
"testInfo": "",
"operation": ""
},
"checkboxStatus": {
"basicInfo": {},
"codeInfo": {},
"buildInfo": {},
"deployInfo": {},
"testInfo": {},
"others": {}
},
"backUp": {
"deployInfo": {},
"testInfo": {}
},
"masterJson": {}
};
BackupSapData: any= JSON.parse(JSON.stringify(this.SAPdata));
authmode= "ldap";
adalConfig: any=
{"clientId": "",
"tenate": "",
"postLogoutRedirectUri": "",
"endpoints": {},
};
pipelineName= "";
appName= "";
pipelineNames: any;
releaseAddSuccess: boolean;
releaseUpdateSuccess: boolean;
releasePipelineName: "";
activeReleasePipelineName: "";
noPipelines: boolean;
hideDashboard: boolean;
sapNewFlag= false;
buildSubscription= false;
deploySubscription= false;
testSubscription= false;
buildSubscriptionSubmit= false;
deploySubscriptionSubmit= false;
noAccess: boolean;
showService: boolean;
flag: boolean;
noAccessNavBars: boolean;
scheduleJob: any;
schedulePage: any= false;
index: any;
buildIntervalData: any= [];
statusCheck: any= [];
workflowData: any = [];
workflowDataTemp: any = [];
createWorkflowSequenceflag= false;
workflowTrigger= false;
triggerWorkflowJobData: any;
approveBuildFlag: any= false;
approveDeployFlag: any= false;
keycloakToken: any;
organization: any;
keycloakUrl: any;
keycloakRealm: any;
keycloakClientId: any;
isRmsApp: any;
isDockerRegistry: any;
buildUT = "";
buildCA = "";
buildCAUT = "";
hideApp= false;
dependencies = [];
PagePersmission: any= {
"basic" : false,
"code" : false,
"build" : false,
"deploy": false,
"test": false
};
setSAPdata() {
this.data = JSON.parse(JSON.stringify(this.SAPdata));
return true;
}
} | the_stack |
import * as childProcess from 'child_process';
import * as crypto from 'crypto';
import * as fsExtra from 'fs-extra';
import * as path from 'path';
import * as util from 'util';
const execFilePromise = util.promisify(childProcess.execFile);
const execPromise = util.promisify(childProcess.exec);
import {MountPoint} from './server';
import {
BenchmarkSpec,
GitDependency,
NpmPackageJson,
PackageDependencyMap,
PackageVersion,
} from './types';
import {fileKind, runNpm, throwUnreachable} from './util';
interface GitDependencyWithTempDir extends GitDependency {
tempDir: string;
sha: string;
}
/**
* Parse an array of strings of the form <package>@<version>.
*/
export function parsePackageVersions(flags: string[]): PackageVersion[] {
const versions: PackageVersion[] = [];
for (const flag of flags) {
const match = flag.match(/^(?:(.+)=)?(.+)@(.+)$/);
if (match === null) {
throw new Error(`Invalid package format ${flag}`);
}
const [, label, dep, version] = match;
versions.push({
label: label || `${dep}@${version}`,
dependencyOverrides: {
[dep]: version,
},
});
}
return versions;
}
export interface ServerPlan {
/** The benchmarks this server will handle. */
specs: BenchmarkSpec[];
/** NPM installations needed for this server. */
npmInstalls: NpmInstall[];
/** URL to disk path mappings. */
mountPoints: MountPoint[];
}
export interface NpmInstall {
installDir: string;
packageJson: NpmPackageJson;
}
export async function makeServerPlans(
benchmarkRoot: string,
npmInstallRoot: string,
specs: BenchmarkSpec[]
): Promise<{plans: ServerPlan[]; gitInstalls: GitDependencyWithTempDir[]}> {
const depSwaps = new Map<
string,
{
installDir: string;
packageJsonPath: string;
specs: BenchmarkSpec[];
dependencies: PackageDependencyMap;
}
>();
const defaultSpecs = [];
const gitInstalls = new Map<string, GitDependencyWithTempDir>();
for (const spec of specs) {
if (spec.url.kind === 'remote') {
// No server needed for remote URLs.
continue;
}
if (spec.url.version === undefined) {
defaultSpecs.push(spec);
continue;
}
const diskPath = path.join(benchmarkRoot, spec.url.urlPath);
const kind = await fileKind(diskPath);
if (kind === undefined) {
throw new Error(`No such file or directory ${diskPath}`);
}
const originalPackageJsonPath = await findPackageJsonPath(
kind === 'file' ? path.dirname(diskPath) : diskPath
);
if (originalPackageJsonPath === undefined) {
throw new Error(`Could not find a package.json for ${diskPath}`);
}
const originalPackageJson = (await fsExtra.readJson(
originalPackageJsonPath
)) as NpmPackageJson;
const updatedDeps: PackageDependencyMap = {
...originalPackageJson.dependencies,
};
for (const pkg of Object.keys(spec.url.version.dependencyOverrides)) {
const version = spec.url.version.dependencyOverrides[pkg];
if (typeof version === 'string') {
// NPM dependency syntax that can be handled directly by NPM without any
// help from us. This includes NPM packages, file paths, git repos (but
// not monorepos!), etc. (see
// https://docs.npmjs.com/configuring-npm/package-json.html#dependencies)
updatedDeps[pkg] = version;
} else {
switch (version.kind) {
case 'git': {
// NPM doesn't support directly installing from a sub-directory of a
// git repo, like in monorepos, so we handle those cases ourselves.
// If repo is a local relative path, we need to make it absolute.
// Otherwise, when we run "npm install" in our temp directory, our
// dependency will reference the wrong path.
const repo = makeLocalRelativeGitRepoAbsolute(
version.repo,
process.cwd()
);
// Immediately resolve the git reference (branch, tag, etc.) to a
// SHA and use that going forward, so that we never fall behind the
// origin repo when re-using temp directories.
const sha = looksLikeGitSha(version.ref)
? version.ref
: await remoteResolveGitRefToSha(repo, version.ref);
if (sha === undefined) {
throw new Error(
`Git repo ${version.repo} could not resolve ref "${version.ref}"`
);
}
// This hash uniquely identifies a `git clone` directory for some
// dependency at a particular SHA, with a particular setup routine.
const gitInstallHash = hashStrings(
// Include the tachometer version in case any changes or bugs
// would affect how we do this installation.
tachometerVersion,
repo,
sha,
JSON.stringify(version.setupCommands)
);
const tempDir = path.join(npmInstallRoot, gitInstallHash);
const tempPackageDir = version.subdir
? path.join(tempDir, version.subdir)
: tempDir;
updatedDeps[pkg] = tempPackageDir;
// We're using a Map here because we want to de-duplicate git
// installations that have the exact same parameters, since they can
// be re-used across multiple benchmarks.
gitInstalls.set(gitInstallHash, {...version, repo, tempDir, sha});
break;
}
default: {
throwUnreachable(
version.kind,
'Unknown dependency version kind: ' + version.kind
);
}
}
}
}
// This hash uniquely identifes the `npm install` location for some
// `package.json` where some of its dependencies have been swapped.
const depSwapHash = hashStrings(
// Include the tachometer version in case any changes or bugs
// would affect how we do this installation.
tachometerVersion,
originalPackageJsonPath,
// Sort deps by package name for more temp-directory cache hits since
// the order declared in the dependencies object doesn't matter.
JSON.stringify(
Object.entries(updatedDeps).sort(([pkgA], [pkgB]) =>
pkgA.localeCompare(pkgB)
)
)
);
let swap = depSwaps.get(depSwapHash);
if (swap === undefined) {
swap = {
specs: [],
installDir: path.join(npmInstallRoot, depSwapHash),
dependencies: updatedDeps,
packageJsonPath: originalPackageJsonPath,
};
depSwaps.set(depSwapHash, swap);
}
swap.specs.push(spec);
}
const plans = [];
if (defaultSpecs.length > 0) {
plans.push({
specs: defaultSpecs,
npmInstalls: [],
mountPoints: [
{
urlPath: `/`,
diskPath: benchmarkRoot,
},
],
});
}
for (const {
specs,
installDir,
dependencies,
packageJsonPath,
} of depSwaps.values()) {
plans.push({
specs,
npmInstalls: [
{
installDir,
packageJson: {
private: true,
dependencies,
},
},
],
mountPoints: [
{
urlPath: path.posix.join(
'/',
path
.relative(benchmarkRoot, path.dirname(packageJsonPath))
.replace(path.win32.sep, '/'),
'node_modules'
),
diskPath: path.join(installDir, 'node_modules'),
},
{
urlPath: `/`,
diskPath: benchmarkRoot,
},
],
});
}
return {plans, gitInstalls: [...gitInstalls.values()]};
}
// TODO(aomarks) Some consolidation with install.ts may be possible.
async function findPackageJsonPath(
startDir: string
): Promise<string | undefined> {
let cur = path.resolve(startDir);
while (true) {
const possibleLocation = path.join(cur, 'package.json');
if (await fsExtra.pathExists(possibleLocation)) {
return possibleLocation;
}
const parentDir = path.resolve(cur, '..');
if (parentDir === cur) {
return undefined;
}
cur = parentDir;
}
}
export function hashStrings(...strings: string[]) {
return crypto
.createHash('sha256')
.update(JSON.stringify(strings))
.digest('hex');
}
// eslint-disable-next-line @typescript-eslint/no-var-requires
export const tachometerVersion = require(path.join(
__dirname,
'..',
'package.json'
)).version;
/**
* Name of special file used to indicate that an NPM or git install directory
* completed successfully.
*/
const installSuccessFile = '__TACHOMETER_INSTALL_SUCCESS__';
/**
* Write the given package.json to the given directory and run "npm install" in
* it. If the directory already exists, don't do anything except log.
*/
export async function prepareVersionDirectory(
{installDir, packageJson}: NpmInstall,
forceCleanInstall: boolean
): Promise<void> {
if (forceCleanInstall) {
await fsExtra.remove(installDir);
} else if (await fsExtra.pathExists(installDir)) {
if (await fsExtra.pathExists(path.join(installDir, installSuccessFile))) {
console.log(`\nRe-using NPM install dir:\n ${installDir}\n`);
return;
} else {
console.log(`\nCleaning up failed npm install:\n ${installDir}\n`);
await fsExtra.remove(installDir);
}
}
console.log(`\nRunning npm install in temp dir:\n ${installDir}\n`);
await fsExtra.ensureDir(installDir);
await fsExtra.writeFile(
path.join(installDir, 'package.json'),
JSON.stringify(packageJson, null, 2)
);
await runNpm(['install'], {cwd: installDir});
await fsExtra.writeFile(path.join(installDir, installSuccessFile), '');
}
/**
* Check out the given commit from the given git repo, and run setup commands.
* If the directory already exists, don't do anything except log.
*/
export async function installGitDependency(
gitInstall: GitDependencyWithTempDir,
forceCleanInstall: boolean
): Promise<void> {
if (forceCleanInstall) {
await fsExtra.remove(gitInstall.tempDir);
} else if (await fsExtra.pathExists(gitInstall.tempDir)) {
if (
await fsExtra.pathExists(
path.join(gitInstall.tempDir, installSuccessFile)
)
) {
console.log(
`\nRe-using git checkout:\n` +
` ${gitInstall.repo}#${gitInstall.ref}\n` +
` ${gitInstall.tempDir}\n`
);
return;
} else {
console.log(
`\nCleaning up failed git checkout:\n ${gitInstall.tempDir}\n`
);
await fsExtra.remove(gitInstall.tempDir);
}
}
console.log(
`\nFetching git commit to temp dir:\n` +
` ${gitInstall.repo}#${gitInstall.ref}\n` +
` ${gitInstall.tempDir}\n`
);
// This approach only requires us to hit the remote repo once (as opposed to
// using `git clone`, which doesn't support fetching only one commit).
await fsExtra.ensureDir(gitInstall.tempDir);
const cwdOpts = {cwd: gitInstall.tempDir};
await execFilePromise('git', ['init'], cwdOpts);
await execFilePromise(
'git',
['remote', 'add', 'origin', gitInstall.repo],
cwdOpts
);
await execFilePromise(
'git',
['fetch', 'origin', '--depth=1', gitInstall.sha],
cwdOpts
);
await execFilePromise('git', ['checkout', gitInstall.sha], cwdOpts);
for (const setupCommand of gitInstall.setupCommands || []) {
console.log(`\nRunning setup command:\n ${setupCommand}\n`);
await execPromise(setupCommand, cwdOpts);
}
await fsExtra.writeFile(
path.join(gitInstall.tempDir, installSuccessFile),
''
);
}
/**
* Return whether the given string looks like a 40-characters of hexadecimal,
* i.e. a valid full length git commit SHA-1 hash.
*/
function looksLikeGitSha(ref: string): boolean {
return ref.match(/^[a-fA-F0-9]{40}$/) !== null;
}
/**
* Use the `git ls-remote` command to remotely query the given git repo, and
* resolve the given ref (e.g. a branch or tag) to a commit SHA. Returns
* `undefined` if the ref does not resolve to anything in the repo. Throws if
* the repo is invalid or errors.
*/
async function remoteResolveGitRefToSha(
repo: string,
ref: string
): Promise<string | undefined> {
const {stdout} = await execFilePromise('git', [
'ls-remote',
repo,
'--symref',
ref,
]);
if (stdout.trim() === '') {
return undefined;
}
const parts = stdout.trim().split(/\W/);
if (parts.length > 0 && looksLikeGitSha(parts[0])) {
return parts[0];
}
throw new Error(
`Could not parse output of \`git ls-remote ${repo} --symref ${ref}\`:\n${stdout}`
);
}
function makeLocalRelativeGitRepoAbsolute(repo: string, root: string): string {
if (repo.startsWith('.') || repo.startsWith('file://.')) {
const rel = repo.replace(/^file:\/\//, '');
return path.resolve(root, rel);
}
return repo;
} | the_stack |
import React from 'react';
import {
Text,
TouchableOpacity,
View,
} from 'react-native';
import {
fireEvent,
render,
RenderAPI,
waitForElement,
} from 'react-native-testing-library';
import {
light,
mapping,
} from '@eva-design/eva';
import { ApplicationProvider } from '../../theme';
import {
Datepicker,
DatepickerProps,
} from './datepicker.component';
import { Calendar } from '../calendar/calendar.component';
import { CalendarViewModes } from '../calendar/type';
jest.mock('react-native', () => {
const ActualReactNative = jest.requireActual('react-native');
ActualReactNative.UIManager.measureInWindow = (node, callback) => {
callback(0, 0, 42, 42);
};
return ActualReactNative;
});
const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0);
describe('@datepicker: component checks', () => {
afterAll(() => {
jest.clearAllMocks();
});
const TestDatepicker = React.forwardRef((props: Partial<DatepickerProps>, ref: React.Ref<Datepicker>) => {
const [date, setDate] = React.useState(props.date);
const onSelect = (nextDate: Date): void => {
setDate(nextDate);
props.onSelect && props.onSelect(nextDate);
};
return (
<ApplicationProvider mapping={mapping} theme={light}>
<Datepicker
ref={ref}
date={date}
{...props}
onSelect={onSelect}
/>
</ApplicationProvider>
);
});
/*
* In this test:
* [0] for input touchable
* [1] for backdrop
* ...rest for calendar touchable components
*/
const touchables = {
findInputTouchable: (api: RenderAPI) => api.queryAllByType(TouchableOpacity)[0],
findBackdropTouchable: (api: RenderAPI) => api.queryAllByType(TouchableOpacity)[1],
};
it('should not render calendar when not focused', () => {
const component = render(
<TestDatepicker/>,
);
expect(component.queryByType(Calendar)).toBeFalsy();
});
it('should render calendar when becomes focused', async () => {
const component = render(
<TestDatepicker/>,
);
fireEvent.press(touchables.findInputTouchable(component));
const calendar = await waitForElement(() => component.queryByType(Calendar));
expect(calendar).toBeTruthy();
});
it('should render label as string', async () => {
const component = render(
<TestDatepicker label='I love Babel'/>,
);
expect(component.queryByText('I love Babel')).toBeTruthy();
});
it('should render label as component', async () => {
const component = render(
<TestDatepicker label={props => <Text {...props}>I love Babel</Text>}/>,
);
expect(component.queryByText('I love Babel')).toBeTruthy();
});
it('should render placeholder as pure JSX component', async () => {
const component = render(
<TestDatepicker placeholder={<Text>I love Babel</Text>}/>,
);
expect(component.queryByText('I love Babel')).toBeTruthy();
});
it('should render placeholder as string', async () => {
const component = render(
<TestDatepicker placeholder='I love Babel'/>,
);
expect(component.queryByText('I love Babel')).toBeTruthy();
});
it('should render placeholder as component', async () => {
const component = render(
<TestDatepicker placeholder={props => <Text {...props}>I love Babel</Text>}/>,
);
expect(component.queryByText('I love Babel')).toBeTruthy();
});
it('should render label as pure JSX component', async () => {
const component = render(
<TestDatepicker label={<Text>I love Babel</Text>}/>,
);
expect(component.queryByText('I love Babel')).toBeTruthy();
});
it('should render caption as string', async () => {
const component = render(
<TestDatepicker caption='I love Babel'/>,
);
expect(component.queryByText('I love Babel')).toBeTruthy();
});
it('should render caption as component', async () => {
const component = render(
<TestDatepicker caption={props => <Text {...props}>I love Babel</Text>}/>,
);
expect(component.queryByText('I love Babel')).toBeTruthy();
});
it('should render caption', async () => {
const component = render(
<TestDatepicker caption={props => <View {...props} testID='caption icon'/>}/>,
);
expect(component.queryByTestId('caption icon')).toBeTruthy();
});
it('should render caption as pure JXS component', async () => {
const component = render(
<TestDatepicker caption={<View testID='caption icon'/>}/>,
);
expect(component.queryByTestId('caption icon')).toBeTruthy();
});
it('should render component passed to accessoryLeft prop', async () => {
const component = render(
<TestDatepicker accessoryLeft={props => <View {...props} testID='accessory left'/>}/>,
);
expect(component.queryByTestId('accessory left')).toBeTruthy();
});
it('should render pure JSX component passed to accessoryLeft prop', async () => {
const component = render(
<TestDatepicker accessoryLeft={<View testID='accessory left'/>}/>,
);
expect(component.queryByTestId('accessory left')).toBeTruthy();
});
it('should render component passed to accessoryRight prop', async () => {
const component = render(
<TestDatepicker accessoryRight={props => <View {...props} testID='accessory right'/>}/>,
);
expect(component.queryByTestId('accessory right')).toBeTruthy();
});
it('should render pure JSX component passed to accessoryRight prop', async () => {
const component = render(
<TestDatepicker accessoryRight={<View testID='accessory right'/>}/>,
);
expect(component.queryByTestId('accessory right')).toBeTruthy();
});
it('should request date change', async () => {
const onSelect = jest.fn();
const component = render(
<TestDatepicker onSelect={onSelect}/>,
);
fireEvent.press(touchables.findInputTouchable(component));
const dateTouchable = await waitForElement(() => component.queryAllByText('7')[0]);
fireEvent.press(dateTouchable);
expect(onSelect).toBeCalledWith(new Date(today.getFullYear(), today.getMonth(), 7));
});
it('should render element provided with renderDay prop', async () => {
const component = render(
<TestDatepicker renderDay={() => <View testID='@datepicker/cell'/>}/>,
);
fireEvent.press(touchables.findInputTouchable(component));
const cells = await waitForElement(() => component.queryAllByTestId('@datepicker/cell'));
expect(cells.length).not.toEqual(0);
});
it('should render element provided with renderMonth prop', async () => {
const component = render(
<TestDatepicker
startView={CalendarViewModes.MONTH}
renderMonth={() => <View testID='@datepicker/cell'/>}
/>,
);
fireEvent.press(touchables.findInputTouchable(component));
const cells = await waitForElement(() => component.queryAllByTestId('@datepicker/cell'));
expect(cells.length).not.toEqual(0);
});
it('should render element provided with renderYear prop', async () => {
const component = render(
<TestDatepicker
startView={CalendarViewModes.YEAR}
renderYear={() => <View testID='@datepicker/cell'/>}
/>,
);
fireEvent.press(touchables.findInputTouchable(component));
const cells = await waitForElement(() => component.queryAllByTestId('@datepicker/cell'));
expect(cells.length).not.toEqual(0);
});
it('should hide calendar when date pressed', async () => {
const component = render(
<TestDatepicker />,
);
fireEvent.press(touchables.findInputTouchable(component));
const dateTouchable = await waitForElement(() => component.queryAllByText('7')[0]);
fireEvent.press(dateTouchable);
const calendar = await waitForElement(() => component.queryByType(Calendar));
expect(calendar).toBeFalsy();
});
it('should not hide calendar when date pressed (autoDismiss)', async () => {
const component = render(
<TestDatepicker autoDismiss={false}/>,
);
fireEvent.press(touchables.findInputTouchable(component));
const dateTouchable = await waitForElement(() => component.queryAllByText('7')[0]);
fireEvent.press(dateTouchable);
const calendar = await waitForElement(() => component.queryByType(Calendar));
expect(calendar).toBeTruthy();
});
it('should hide calendar when backdrop pressed', async () => {
const component = render(
<TestDatepicker />,
);
fireEvent.press(touchables.findInputTouchable(component));
const backdrop = await waitForElement(() => touchables.findBackdropTouchable(component));
fireEvent.press(backdrop);
const calendar = await waitForElement(() => component.queryByType(Calendar));
expect(calendar).toBeFalsy();
});
it('should call onFocus when calendar becomes visible', async () => {
const onFocus = jest.fn();
const component = render(
<TestDatepicker onFocus={onFocus}/>,
);
fireEvent.press(touchables.findInputTouchable(component));
await waitForElement(() => null);
expect(onFocus).toBeCalled();
});
it('should call onBlur when calendar becomes invisible', async () => {
const onBlur = jest.fn();
const component = render(
<TestDatepicker onBlur={onBlur}/>,
);
fireEvent.press(touchables.findInputTouchable(component));
const backdrop = await waitForElement(() => touchables.findBackdropTouchable(component));
fireEvent.press(backdrop);
expect(onBlur).toBeCalled();
});
it('should show calendar by calling `show` with ref', async () => {
const componentRef: React.RefObject<Datepicker> = React.createRef();
const component = render(
<TestDatepicker ref={componentRef}/>,
);
componentRef.current.show();
const calendar = await waitForElement(() => component.queryByType(Calendar));
expect(calendar).toBeTruthy();
});
it('should hide calendar by calling `hide` with ref', async () => {
const componentRef: React.RefObject<Datepicker> = React.createRef();
const component = render(
<TestDatepicker ref={componentRef}/>,
);
componentRef.current.show();
await waitForElement(() => null);
componentRef.current.hide();
const calendar = await waitForElement(() => component.queryByType(Calendar));
expect(calendar).toBeFalsy();
});
it('should show calendar by calling `focus` with ref', async () => {
const componentRef: React.RefObject<Datepicker> = React.createRef();
const component = render(
<TestDatepicker ref={componentRef}/>,
);
componentRef.current.focus();
const calendar = await waitForElement(() => component.queryByType(Calendar));
expect(calendar).toBeTruthy();
});
it('should hide calendar by calling `blur` with ref', async () => {
const componentRef: React.RefObject<Datepicker> = React.createRef();
const component = render(
<TestDatepicker ref={componentRef}/>,
);
componentRef.current.focus();
await waitForElement(() => null);
componentRef.current.blur();
const calendar = await waitForElement(() => component.queryByType(Calendar));
expect(calendar).toBeFalsy();
});
it('should return false if calendar not visible by calling `isFocused` with ref', async () => {
const componentRef: React.RefObject<Datepicker> = React.createRef();
render(
<TestDatepicker ref={componentRef}/>,
);
expect(componentRef.current.isFocused()).toEqual(false);
});
it('should return true if calendar visible by calling `isFocused` with ref', async () => {
const componentRef: React.RefObject<Datepicker> = React.createRef();
render(
<TestDatepicker ref={componentRef}/>,
);
componentRef.current.focus();
await waitForElement(() => null);
expect(componentRef.current.isFocused()).toEqual(true);
});
it('should call onSelect with null when calling `clear` with ref', async () => {
const componentRef: React.RefObject<Datepicker> = React.createRef();
const onSelect = jest.fn();
render(
<TestDatepicker
ref={componentRef}
onSelect={onSelect}
/>,
);
componentRef.current.clear();
await waitForElement(() => null);
expect(onSelect).toBeCalledWith(null);
});
it('should call onPress', async () => {
const onPress = jest.fn();
const component = render(
<TestDatepicker onPress={onPress}/>,
);
fireEvent.press(touchables.findInputTouchable(component));
expect(onPress).toBeCalled();
});
it('should call onPressIn', async () => {
const onPressIn = jest.fn();
const component = render(
<TestDatepicker onPressIn={onPressIn}/>,
);
fireEvent(touchables.findInputTouchable(component), 'pressIn');
expect(onPressIn).toBeCalled();
});
it('should call onPressOut', async () => {
const onPressOut = jest.fn();
const component = render(
<TestDatepicker onPressOut={onPressOut}/>,
);
fireEvent(touchables.findInputTouchable(component), 'pressOut');
expect(onPressOut).toBeCalled();
});
}); | the_stack |
import { buildCellMatcher, buildCommonExpectedStateStyle, buildReceivedCellWithCommonAttributes, ExpectedCell, ExpectedStateStyle } from '../matcher-utils';
import {
ExpectedBoundaryEventModelElement,
ExpectedCallActivityModelElement,
ExpectedEventBasedGatewayModelElement,
ExpectedEventModelElement,
ExpectedShapeModelElement,
ExpectedStartEventModelElement,
ExpectedSubProcessModelElement,
getDefaultParentId,
} from '../../helpers/model-expect';
import { ShapeBpmnElementKind } from '../../../../src/model/bpmn/internal';
import { mxgraph } from '../../../../src/component/mxgraph/initializer';
import MatcherContext = jest.MatcherContext;
import CustomMatcherResult = jest.CustomMatcherResult;
function expectedStrokeWidth(kind: ShapeBpmnElementKind): number {
return [
ShapeBpmnElementKind.EVENT_BOUNDARY,
ShapeBpmnElementKind.EVENT_INTERMEDIATE_CATCH,
ShapeBpmnElementKind.EVENT_INTERMEDIATE_THROW,
ShapeBpmnElementKind.EVENT_START,
ShapeBpmnElementKind.GATEWAY_EVENT_BASED,
ShapeBpmnElementKind.GATEWAY_EXCLUSIVE,
ShapeBpmnElementKind.GATEWAY_INCLUSIVE,
ShapeBpmnElementKind.GATEWAY_PARALLEL,
ShapeBpmnElementKind.GROUP,
ShapeBpmnElementKind.SUB_PROCESS,
ShapeBpmnElementKind.TASK,
ShapeBpmnElementKind.TASK_BUSINESS_RULE,
ShapeBpmnElementKind.TASK_MANUAL,
ShapeBpmnElementKind.TASK_RECEIVE,
ShapeBpmnElementKind.TASK_SCRIPT,
ShapeBpmnElementKind.TASK_SERVICE,
ShapeBpmnElementKind.TASK_SEND,
ShapeBpmnElementKind.TASK_USER,
ShapeBpmnElementKind.TEXT_ANNOTATION,
].includes(kind)
? 2
: [ShapeBpmnElementKind.CALL_ACTIVITY, ShapeBpmnElementKind.EVENT_END].includes(kind)
? 5
: undefined;
}
function buildExpectedStateStyle(expectedModel: ExpectedShapeModelElement): ExpectedStateStyle {
const expectedStateStyle = buildCommonExpectedStateStyle(expectedModel);
expectedStateStyle.shape = !expectedModel.styleShape ? expectedModel.kind : expectedModel.styleShape;
expectedStateStyle.verticalAlign = expectedModel.verticalAlign ? expectedModel.verticalAlign : 'middle';
expectedStateStyle.align = expectedModel.align ? expectedModel.align : 'center';
expectedStateStyle.strokeWidth = expectedStrokeWidth(expectedModel.kind);
expectedStateStyle.fillColor = [ShapeBpmnElementKind.LANE, ShapeBpmnElementKind.POOL, ShapeBpmnElementKind.TEXT_ANNOTATION, ShapeBpmnElementKind.GROUP].includes(
expectedModel.kind,
)
? 'none'
: expectedStateStyle.fillColor;
if ('isHorizontal' in expectedModel) {
expectedStateStyle.horizontal = expectedModel.isHorizontal ? 0 : 1;
}
return expectedStateStyle;
}
function buildExpectedStyle(
expectedModel:
| ExpectedShapeModelElement
| ExpectedSubProcessModelElement
| ExpectedEventModelElement
| ExpectedStartEventModelElement
| ExpectedBoundaryEventModelElement
| ExpectedEventBasedGatewayModelElement
| ExpectedCallActivityModelElement,
): string {
let expectedStyle: string = expectedModel.kind;
if ('eventDefinitionKind' in expectedModel) {
expectedStyle = expectedStyle + `.*bpmn.eventDefinitionKind=${expectedModel.eventDefinitionKind}`;
}
if ('subProcessKind' in expectedModel) {
expectedStyle = expectedStyle + `.*bpmn.subProcessKind=${expectedModel.subProcessKind}`;
}
if ('globalTaskKind' in expectedModel) {
expectedStyle = expectedStyle + `.*bpmn.globalTaskKind=${expectedModel.globalTaskKind}`;
}
if (expectedModel.isInstantiating !== undefined) {
expectedStyle = expectedStyle + `.*bpmn.isInstantiating=${expectedModel.isInstantiating}`;
}
if (expectedModel.markers?.length > 0) {
expectedStyle = expectedStyle + `.*bpmn.markers=${expectedModel.markers.join(',')}`;
}
if ('isInterrupting' in expectedModel) {
expectedStyle = expectedStyle + `.*bpmn.isInterrupting=${expectedModel.isInterrupting}`;
}
if ('gatewayKind' in expectedModel) {
expectedStyle = expectedStyle + `.*bpmn.gatewayKind=${expectedModel.gatewayKind}`;
}
return expectedStyle + '.*';
}
function buildExpectedCell(id: string, expectedModel: ExpectedShapeModelElement): ExpectedCell {
const parentId = expectedModel.parentId;
const styleRegexp = buildExpectedStyle(expectedModel);
return {
id,
value: expectedModel.label,
style: expect.stringMatching(styleRegexp),
edge: false,
vertex: true,
parent: { id: parentId ? parentId : getDefaultParentId() },
state: {
style: buildExpectedStateStyle(expectedModel),
},
overlays: expectedModel.overlays,
};
}
function buildShapeMatcher(matcherName: string, matcherContext: MatcherContext, received: string, expected: ExpectedShapeModelElement): CustomMatcherResult {
return buildCellMatcher(matcherName, matcherContext, received, expected, 'Shape', buildExpectedCell, buildReceivedCellWithCommonAttributes);
}
export function toBeShape(this: MatcherContext, received: string, expected: ExpectedShapeModelElement): CustomMatcherResult {
return buildShapeMatcher('toBeShape', this, received, expected);
}
export function toBePool(this: MatcherContext, received: string, expected: ExpectedShapeModelElement): CustomMatcherResult {
const isHorizontal = 'isHorizontal' in expected ? expected.isHorizontal : true;
return buildShapeMatcher('toBePool', this, received, { ...expected, kind: ShapeBpmnElementKind.POOL, styleShape: mxgraph.mxConstants.SHAPE_SWIMLANE, isHorizontal });
}
export function toBeLane(this: MatcherContext, received: string, expected: ExpectedShapeModelElement): CustomMatcherResult {
const isHorizontal = 'isHorizontal' in expected ? expected.isHorizontal : true;
return buildShapeMatcher('toBeLane', this, received, { ...expected, kind: ShapeBpmnElementKind.LANE, styleShape: mxgraph.mxConstants.SHAPE_SWIMLANE, isHorizontal });
}
export function toBeCallActivity(this: MatcherContext, received: string, expected: ExpectedCallActivityModelElement): CustomMatcherResult {
return buildShapeMatcher('toBeCallActivity', this, received, { ...expected, kind: ShapeBpmnElementKind.CALL_ACTIVITY });
}
export function toBeSubProcess(this: MatcherContext, received: string, expected: ExpectedSubProcessModelElement): CustomMatcherResult {
return buildShapeMatcher('toBeSubProcess', this, received, { ...expected, kind: ShapeBpmnElementKind.SUB_PROCESS });
}
export function toBeTask(this: MatcherContext, received: string, expected: ExpectedShapeModelElement): CustomMatcherResult {
return buildShapeMatcher('toBeTask', this, received, { ...expected, kind: ShapeBpmnElementKind.TASK });
}
export function toBeServiceTask(this: MatcherContext, received: string, expected: ExpectedShapeModelElement): CustomMatcherResult {
return buildShapeMatcher('toBeServiceTask', this, received, { ...expected, kind: ShapeBpmnElementKind.TASK_SERVICE });
}
export function toBeUserTask(this: MatcherContext, received: string, expected: ExpectedShapeModelElement): CustomMatcherResult {
return buildShapeMatcher('toBeUserTask', this, received, { ...expected, kind: ShapeBpmnElementKind.TASK_USER });
}
export function toBeReceiveTask(this: MatcherContext, received: string, expected: ExpectedShapeModelElement): CustomMatcherResult {
return buildShapeMatcher('toBeReceiveTask', this, received, { ...expected, kind: ShapeBpmnElementKind.TASK_RECEIVE });
}
export function toBeSendTask(this: MatcherContext, received: string, expected: ExpectedShapeModelElement): CustomMatcherResult {
return buildShapeMatcher('toBeSendTask', this, received, { ...expected, kind: ShapeBpmnElementKind.TASK_SEND });
}
export function toBeManualTask(this: MatcherContext, received: string, expected: ExpectedShapeModelElement): CustomMatcherResult {
return buildShapeMatcher('toBeManualTask', this, received, { ...expected, kind: ShapeBpmnElementKind.TASK_MANUAL });
}
export function toBeScriptTask(this: MatcherContext, received: string, expected: ExpectedShapeModelElement): CustomMatcherResult {
return buildShapeMatcher('toBeScriptTask', this, received, { ...expected, kind: ShapeBpmnElementKind.TASK_SCRIPT });
}
export function toBeBusinessRuleTask(this: MatcherContext, received: string, expected: ExpectedShapeModelElement): CustomMatcherResult {
return buildShapeMatcher('toBeBusinessRuleTask', this, received, { ...expected, kind: ShapeBpmnElementKind.TASK_BUSINESS_RULE });
}
function buildEventMatcher(matcherName: string, matcherContext: MatcherContext, received: string, expected: ExpectedStartEventModelElement): CustomMatcherResult {
return buildShapeMatcher(matcherName, matcherContext, received, { ...expected, verticalAlign: 'top' });
}
export function toBeStartEvent(this: MatcherContext, received: string, expected: ExpectedStartEventModelElement): CustomMatcherResult {
return buildEventMatcher('toBeStartEvent', this, received, { ...expected, kind: ShapeBpmnElementKind.EVENT_START });
}
export function toBeEndEvent(this: MatcherContext, received: string, expected: ExpectedEventModelElement): CustomMatcherResult {
return buildEventMatcher('toBeStartEvent', this, received, { ...expected, kind: ShapeBpmnElementKind.EVENT_END });
}
export function toBeIntermediateThrowEvent(this: MatcherContext, received: string, expected: ExpectedEventModelElement): CustomMatcherResult {
return buildEventMatcher('toBeIntermediateThrowEvent', this, received, { ...expected, kind: ShapeBpmnElementKind.EVENT_INTERMEDIATE_THROW });
}
export function toBeIntermediateCatchEvent(this: MatcherContext, received: string, expected: ExpectedEventModelElement): CustomMatcherResult {
return buildEventMatcher('toBeIntermediateCatchEvent', this, received, { ...expected, kind: ShapeBpmnElementKind.EVENT_INTERMEDIATE_CATCH });
}
export function toBeBoundaryEvent(this: MatcherContext, received: string, expected: ExpectedBoundaryEventModelElement): CustomMatcherResult {
return buildEventMatcher('toBeBoundaryEvent', this, received, { ...expected, kind: ShapeBpmnElementKind.EVENT_BOUNDARY });
}
export function toBeEventBasedGateway(this: MatcherContext, received: string, expected: ExpectedEventBasedGatewayModelElement): CustomMatcherResult {
return buildShapeMatcher('toBeEventBasedGateway', this, received, { ...expected, kind: ShapeBpmnElementKind.GATEWAY_EVENT_BASED });
} | the_stack |
import { HttpInfrastructureClient } from "./generated/httpInfrastructure/src";
import { assert } from "chai";
import {
PipelinePolicy,
redirectPolicy,
exponentialRetryPolicy,
RestError
} from "@azure/core-rest-pipeline";
import { isNode } from "@azure/core-util";
import {
responseStatusChecker,
responseStatusChecker201,
responseStatusChecker202,
responseStatusChecker204,
responseStatusChecker301,
responseStatusChecker302,
responseStatusChecker404
} from "../utils/responseStatusChecker";
import { HttpClientWithCookieSupport } from "./testUtils/HttpClientWithCookieSupport";
describe("Http infrastructure Client", () => {
let client: HttpInfrastructureClient;
// Prevents caching redirects
const preventCachingPolicy: PipelinePolicy = {
sendRequest: (req, next) => {
if (req.url.includes("?")) {
req.url += `&_=${new Date().toISOString()}`;
} else {
req.url += `?_=${new Date().toISOString()}`;
}
return next(req);
},
name: "preventCachingPolicy"
};
beforeEach(() => {
client = new HttpInfrastructureClient({
httpClient: new HttpClientWithCookieSupport(),
allowInsecureConnection: true
});
client.pipeline.addPolicy(preventCachingPolicy);
client.pipeline.removePolicy({ phase: "Retry" });
client.pipeline.addPolicy(
exponentialRetryPolicy({
maxRetries: 3,
maxRetryDelayInMs: 0,
retryDelayInMs: 0
})
);
client.pipeline.removePolicy(redirectPolicy());
client.pipeline.addPolicy(redirectPolicy());
// client.pipeline.removePolicy({ name: proxyPolicyName });
// client.pipeline.addPolicy(
// proxyPolicy({ host: "http://127.0.0.1", port: 8888 })
// );
});
describe("Success scenarios", () => {
it("should work for all delete200", async () => {
await client.httpSuccess.delete200(responseStatusChecker);
});
it("should work for delete202", async () => {
await client.httpSuccess.delete202(responseStatusChecker202);
});
it("should work for delete204", async () => {
await client.httpSuccess.delete204(responseStatusChecker204);
});
it("should work for get200", async () => {
await client.httpSuccess.get200(responseStatusChecker);
});
it("should work for head200", async () => {
await client.httpSuccess.head200(responseStatusChecker);
});
it("should work for head204", async () => {
await client.httpSuccess.head204(responseStatusChecker204);
});
it("should work for head404", async () => {
await client.httpSuccess.head404(responseStatusChecker404);
});
it("should work for patch200", async () => {
await client.httpSuccess.patch200(responseStatusChecker);
});
it("should work for patch202", async () => {
await client.httpSuccess.patch202(responseStatusChecker202);
});
it("should work for patch204", async () => {
await client.httpSuccess.patch204(responseStatusChecker204);
});
it("should work for post200", async () => {
await client.httpSuccess.post200(responseStatusChecker);
});
it("should work for post201", async () => {
await client.httpSuccess.post201(responseStatusChecker201);
});
it("should work for post202", async () => {
await client.httpSuccess.post202(responseStatusChecker202);
});
it("should work for post204", async () => {
await client.httpSuccess.post204(responseStatusChecker204);
});
it("should work for put200", async () => {
await client.httpSuccess.put200(responseStatusChecker);
});
it("should work for put201", async () => {
await client.httpSuccess.put201(responseStatusChecker201);
});
it("should work for put202", async () => {
await client.httpSuccess.put202(responseStatusChecker202);
});
it("should work for put204", async () => {
await client.httpSuccess.put204(responseStatusChecker204);
});
it("should work for delete204", async () => {
await client.httpSuccess.delete204(responseStatusChecker204);
});
});
describe("Failure scenarios", () => {
it("Should get empty should throw error", async () => {
try {
await client.httpFailure.getEmptyError();
assert.fail("Expected error");
} catch (error) {
assert.equal(error.statusCode, 400);
}
});
});
describe("httpClientFailure scenarios", () => {
it("delete400 should throw error", async () => {
try {
await client.httpClientFailure.delete400();
assert.fail("Expected error");
} catch (error) {
assert.equal(error.statusCode, 400);
}
});
it("patch414 should throw error", async () => {
try {
await client.httpClientFailure.patch414();
assert.fail("Expected error");
} catch (error) {
if (isNode) {
assert.equal(error.statusCode, 414);
} else {
assert.notEqual(error.message, "Expected error");
}
}
});
it("delete417 should throw error", async () => {
try {
await client.httpClientFailure.delete417();
assert.fail("Expected error");
} catch (error) {
assert.equal(error.statusCode, 417);
}
});
it("get400 should throw error", async () => {
try {
await client.httpClientFailure.get400();
assert.fail("Expected error");
} catch (error) {
assert.equal(error.statusCode, 400);
}
});
it("get402 should throw error", async () => {
try {
await client.httpClientFailure.get402();
assert.fail("Expected error");
} catch (error) {
assert.equal(error.statusCode, 402);
}
});
it("get403 should throw error", async () => {
try {
await client.httpClientFailure.get403();
assert.fail("Expected error");
} catch (error) {
assert.equal(error.statusCode, 403);
}
});
it("get411 should throw error", async () => {
try {
await client.httpClientFailure.get411();
assert.fail("Expected error");
} catch (error) {
assert.equal(error.statusCode, 411);
}
});
it("get412 should throw error", async () => {
try {
await client.httpClientFailure.get412();
assert.fail("Expected error");
} catch (error) {
assert.equal(error.statusCode, 412);
}
});
it("get416 should throw error", async () => {
try {
await client.httpClientFailure.get416();
assert.fail("Expected error");
} catch (error) {
assert.equal(error.statusCode, 416);
}
});
it("head400 should throw error", async () => {
try {
await client.httpClientFailure.head400();
assert.fail("Expected error");
} catch (error) {
assert.equal(error.statusCode, 400);
}
});
it("head401 should throw error", async () => {
try {
await client.httpClientFailure.head401();
assert.fail("Expected error");
} catch (error) {
assert.equal(error.statusCode, 401);
}
});
it("head410 should throw error", async () => {
try {
await client.httpClientFailure.head410();
assert.fail("Expected error");
} catch (error) {
assert.equal(error.statusCode, 410);
}
});
it("delete407 should throw error", async () => {
try {
await client.httpClientFailure.delete407();
assert.fail("Expected error");
} catch (error) {
if (isNode) {
assert.equal(error.statusCode, 407);
} else {
assert.equal(error.code, "REQUEST_SEND_ERROR");
}
}
});
it("head429 should throw error", async () => {
try {
await client.httpClientFailure.head429();
assert.fail("Expected error");
} catch (error) {
assert.equal(error.statusCode, 429);
}
});
// TODO: Investigate why options calls are sending back 204
it.skip("options400 should throw error", async () => {
try {
const result = await client.httpClientFailure.options400();
assert.fail("Expected error");
} catch (error) {
assert.equal(error.statusCode, 400);
}
});
it.skip("options403 should throw error", async () => {
try {
await client.httpClientFailure.options403();
assert.fail("Expected error");
} catch (error) {
assert.equal(error.statusCode, 403);
}
});
it.skip("options412 should throw error", async () => {
try {
await client.httpClientFailure.options412();
assert.fail("Expected error");
} catch (error) {
assert.equal(error.statusCode, 412);
}
});
it("patch400 should throw error", async () => {
try {
await client.httpClientFailure.patch400();
assert.fail("Expected error");
} catch (error) {
assert.equal(error.statusCode, 400);
}
});
it("patch405 should throw error", async () => {
try {
await client.httpClientFailure.patch405();
assert.fail("Expected error");
} catch (error) {
assert.equal(error.statusCode, 405);
}
});
it("post400 should throw error", async () => {
try {
await client.httpClientFailure.post400();
assert.fail("Expected error");
} catch (error) {
assert.equal(error.statusCode, 400);
}
});
it("post406 should throw error", async () => {
try {
await client.httpClientFailure.post406();
assert.fail("Expected error");
} catch (error) {
assert.equal(error.statusCode, 406);
}
});
it("post415 should throw error", async () => {
try {
await client.httpClientFailure.post415();
assert.fail("Expected error");
} catch (error) {
assert.equal(error.statusCode, 415);
}
});
it("post415 should throw error", async () => {
try {
await client.httpClientFailure.post415();
assert.fail("Expected error");
} catch (error) {
assert.equal(error.statusCode, 415);
}
});
it("put400 should throw error", async () => {
try {
await client.httpClientFailure.put400();
assert.fail("Expected error");
} catch (error) {
assert.equal(error.statusCode, 400);
}
});
it("put404 should throw error", async () => {
try {
await client.httpClientFailure.put404();
assert.fail("Expected error");
} catch (error) {
assert.equal(error.statusCode, 404);
}
});
it("put409 should throw error", async () => {
try {
await client.httpClientFailure.put409();
assert.fail("Expected error");
} catch (error) {
assert.equal(error.statusCode, 409);
}
});
it("put413 should throw error", async () => {
try {
await client.httpClientFailure.put413();
assert.fail("Expected error");
} catch (error) {
assert.equal(error.statusCode, 413);
}
});
});
describe("Failure scenarios", () => {
it("delete307 should return 200", async () => {
await client.httpRedirects.delete307(responseStatusChecker);
});
it("get300 should return 200", async () => {
await client.httpRedirects.get300(responseStatusChecker);
});
it("get301 should return 200", async () => {
await client.httpRedirects.get301(responseStatusChecker);
});
it("get302 should return 200", async () => {
await client.httpRedirects.get302(responseStatusChecker);
});
it("get307 should return 200", async () => {
await client.httpRedirects.get307(responseStatusChecker);
});
it("head300 should return 200", async () => {
await client.httpRedirects.head300(responseStatusChecker);
});
it("head301 should return 200", async () => {
await client.httpRedirects.head301(responseStatusChecker);
});
it("head302 should return 200", async () => {
await client.httpRedirects.head302(responseStatusChecker);
});
it("head307 should return 200", async () => {
await client.httpRedirects.head307(responseStatusChecker);
});
it("patch302 should return 302", async function() {
// Manual redirection is not supported by the xhr in browser
// browsers will perform default redirect
if (!isNode) {
this.skip();
}
await client.httpRedirects.patch302(responseStatusChecker302);
});
it("patch307 should return 200", async () => {
await client.httpRedirects.patch307(responseStatusChecker);
});
it("post303 should return 200", async () => {
await client.httpRedirects.post303(responseStatusChecker);
});
it("post307 should return 200", async () => {
await client.httpRedirects.post307(responseStatusChecker);
});
it("put307 should return 200", async () => {
await client.httpRedirects.put307(responseStatusChecker);
});
it("put301 should return 301", async function() {
// Manual redirection is not supported by the xhr in browser
// browsers will perform default redirect
if (!isNode) {
this.skip();
}
await client.httpRedirects.put301(responseStatusChecker301);
});
});
describe("Retry scenarios", () => {
it("delete503 should retry and return 200", async () => {
await client.httpRetry.delete503(responseStatusChecker);
}).timeout(150000);
it("get502 should retry and return 200", async () => {
await client.httpRetry.get502(responseStatusChecker);
});
it("head408 should retry and return 200", async () => {
await client.httpRetry.head408(responseStatusChecker);
});
// TODO: Investigate options
it.skip("options502 should retry and return 200", async () => {
await client.httpRetry.options502(responseStatusChecker);
});
it("patch500 should retry and return 200", async () => {
await client.httpRetry.patch500(responseStatusChecker);
});
it("patch504 should retry and return 200", async () => {
await client.httpRetry.patch504(responseStatusChecker);
});
it("post503 should retry and return 200", async () => {
await client.httpRetry.post503(responseStatusChecker);
});
it("put500 should retry and return 200", async () => {
await client.httpRetry.put500(responseStatusChecker);
});
it("put504 should retry and return 200", async () => {
await client.httpRetry.put504(responseStatusChecker);
});
});
describe("ServerFailure scenarios", () => {
it("delete505 should throw error", async () => {
try {
await client.httpServerFailure.delete505();
assert.fail("Expected to throw");
} catch (error) {
assert.equal(error.statusCode, 505);
}
});
it("get501 should throw error", async () => {
try {
await client.httpServerFailure.get501();
assert.fail("Expected to throw");
} catch (error) {
assert.equal(error.statusCode, 501);
}
});
it("head501 should throw error", async () => {
try {
await client.httpServerFailure.head501();
assert.fail("Expected to throw");
} catch (error) {
assert.equal(error.statusCode, 501);
}
});
it("post505 should throw error", async () => {
try {
await client.httpServerFailure.post505();
assert.fail("Expected to throw");
} catch (error) {
assert.equal(error.statusCode, 505);
}
});
});
describe("Multipl Response scenarios", () => {
it("get200Model201ModelDefaultError200Valid should return 200", async () => {
const result = await client.multipleResponses.get200Model201ModelDefaultError200Valid();
assert.equal(result.statusCode, "200");
});
it("get200Model201ModelDefaultError201Valid should return 201", async () => {
const result = await client.multipleResponses.get200Model201ModelDefaultError201Valid();
assert.deepEqual(result as any, {
statusCode: "201",
textStatusCode: "Created"
});
});
it("get200Model201ModelDefaultError400Valid should throw", async () => {
try {
await client.multipleResponses.get200Model201ModelDefaultError400Valid();
assert.fail("Expected to throw");
} catch (error) {
assert.equal(error.statusCode, 400);
}
});
it("get200ModelA201ModelC404ModelDDefaultError200Valid should return 200", async () => {
const result = await client.multipleResponses.get200ModelA201ModelC404ModelDDefaultError200Valid();
assert.deepEqual(result as any, {
statusCode: "200"
});
});
it("get200Model204NoModelDefaultError201Invalid should throw", async () => {
try {
await client.multipleResponses.get200Model204NoModelDefaultError201Invalid();
assert.fail("Expected to throw");
} catch (error) {
assert.equal(error.statusCode, 201);
}
});
it("get200Model204NoModelDefaultError201Invalid should throw", async () => {
try {
await client.multipleResponses.get200Model204NoModelDefaultError202None();
assert.fail("Expected to throw");
} catch (error) {
assert.equal(error.statusCode, 202);
}
});
it("get200Model204NoModelDefaultError204Valid should return 200", async () => {
await client.multipleResponses.get200Model204NoModelDefaultError204Valid(
responseStatusChecker204
);
});
it("get200Model204NoModelDefaultError400Valid should throw", async () => {
try {
await client.multipleResponses.get200Model204NoModelDefaultError400Valid();
assert.fail("Expected to throw");
} catch (error) {
assert.equal(error.statusCode, 400);
}
});
it("get200ModelA200Invalid should return 200", async () => {
const result: any = await client.multipleResponses.get200ModelA200Invalid();
assert.equal(result.statusCodeInvalid, "200");
});
it("get200ModelA200None return 200", async () => {
await client.multipleResponses.get200ModelA200None(responseStatusChecker);
});
it("get200ModelA200Valid should return 200", async () => {
await client.multipleResponses.get200ModelA200Valid(
responseStatusChecker
);
});
it("get200ModelA201ModelC404ModelDDefaultError200Valid should return 200", async () => {
await client.multipleResponses.get200ModelA201ModelC404ModelDDefaultError200Valid(
responseStatusChecker
);
});
it("get200ModelA201ModelC404ModelDDefaultError201Valid should return 201", async () => {
await client.multipleResponses.get200ModelA201ModelC404ModelDDefaultError201Valid(
responseStatusChecker201
);
});
it("get200ModelA201ModelC404ModelDDefaultError201Valid should throw 400", async () => {
try {
await client.multipleResponses.get200ModelA201ModelC404ModelDDefaultError400Valid();
assert.fail("Expected to throw");
} catch (error) {
assert.deepEqual(error.statusCode, 400);
}
});
it("get200ModelA201ModelC404ModelDDefaultError404Valid should throw 404", async () => {
await client.multipleResponses.get200ModelA201ModelC404ModelDDefaultError404Valid(
responseStatusChecker404
);
});
it("get202None204NoneDefaultError202None should return 202", async () => {
await client.multipleResponses.get202None204NoneDefaultError202None(
responseStatusChecker202
);
});
it("get202None204NoneDefaultError204None should return 204", async () => {
await client.multipleResponses.get202None204NoneDefaultError204None(
responseStatusChecker204
);
});
it("get202None204NoneDefaultNone400Invalid should throw 400", async () => {
try {
await client.multipleResponses.get202None204NoneDefaultNone400Invalid();
assert.fail("Expected an Error");
} catch (error) {
assert.equal(error.statusCode, 400);
}
});
it("get202None204NoneDefaultNone400None should throw 400", async () => {
try {
await client.multipleResponses.get202None204NoneDefaultNone400None();
assert.fail("Expected an Error");
} catch (error) {
assert.equal(error.statusCode, 400);
}
});
it("getDefaultModelA200None should return 200", async () => {
await client.multipleResponses.getDefaultModelA200None(
responseStatusChecker
);
});
it("getDefaultModelA200Valid should return 200", async () => {
await client.multipleResponses.getDefaultModelA200Valid(
responseStatusChecker
);
});
it("getDefaultModelA400None should throw 400", async () => {
try {
await client.multipleResponses.getDefaultModelA400None();
assert.fail("Expected an Error");
} catch (error) {
assert.equal(error.statusCode, 400);
}
});
it("getDefaultModelA400Valid should throw 400", async () => {
try {
await client.multipleResponses.getDefaultModelA400Valid();
assert.fail("Expected an Error");
} catch (error) {
assert.equal(error.statusCode, 400);
}
});
it("getDefaultNone200Invalid should return 200", async () => {
await client.multipleResponses.getDefaultNone200Invalid(
responseStatusChecker
);
});
it("getDefaultNone200None should return 200", async () => {
await client.multipleResponses.getDefaultNone200None(
responseStatusChecker
);
});
it("getDefaultNone400Invalid should return 200", async () => {
try {
await client.multipleResponses.getDefaultNone400Invalid();
assert.fail("Expected an Error");
} catch (error) {
assert.equal(error.statusCode, 400);
}
});
it("getDefaultNone400None should return 200", async () => {
try {
client.httpClientFailure;
await client.multipleResponses.getDefaultNone400None();
assert.fail("Expected an Error");
} catch (error) {
assert.equal(error.statusCode, 400);
}
});
it("should handle get200Model204NoModelDefaultError200Valid", async () => {
const result = await client.multipleResponses.get200Model204NoModelDefaultError200Valid();
assert.strictEqual(result.statusCode, "200");
});
it("should handle ResponsesScenarioD400DefaultModel", async () => {
try {
await client.multipleResponses.get202None204NoneDefaultError400Valid();
assert.fail(
"Expected get202None204NoneDefaultError400Valid to throw an error"
);
} catch (error) {
assert.strictEqual(error.message, "client error");
assert.strictEqual(error.statusCode, 400);
}
});
it("should handle get202None204NoneDefaultNone202Invalid", async () => {
await client.multipleResponses.get202None204NoneDefaultNone202Invalid(
responseStatusChecker202
);
});
it("should handle get202None204NoneDefaultNone204None", async () => {
await client.multipleResponses.get202None204NoneDefaultNone204None(
responseStatusChecker204
);
});
it("should handle get200ModelA202Valid", async () => {
try {
await client.multipleResponses.get200ModelA202Valid();
assert.fail("Expected get200ModelA202Valid to throw");
} catch (e) {
const error: RestError = e;
assert.strictEqual(error.statusCode, 202);
assert.include(error.message, "202");
}
});
it("should handle get200ModelA400Invalid", async () => {
try {
await client.multipleResponses.get200ModelA400Invalid();
assert.fail("Expected get200ModelA400Invalid to throw");
} catch (e) {
const error: RestError = e;
assert.strictEqual(error.statusCode, 400);
assert.include(error.message, "400");
}
});
it("should handle get200ModelA400Valid", async () => {
try {
await client.multipleResponses.get200ModelA400Valid();
assert.fail("Expected get200ModelA400Valid to throw");
} catch (e) {
const error: RestError = e;
assert.strictEqual(error.statusCode, 400);
assert.include(error.message, "400");
}
});
it("should handle get200ModelA400None", async () => {
try {
await client.multipleResponses.get200ModelA400None();
assert.fail("Expected get200ModelA400None to throw");
} catch (e) {
const error: RestError = e;
assert.strictEqual(error.statusCode, 400);
}
});
});
describe("Failure scenarios", () => {
it("getEmptyError should throw error", async () => {
try {
await client.httpFailure.getEmptyError();
assert.fail("Expected error");
} catch (error) {
assert.equal(error.statusCode, 400);
}
});
it("getNoModelEmpty should throw 400", async () => {
try {
await client.httpFailure.getNoModelEmpty();
assert.fail("Expected getNoModelEmpty to throw");
} catch (e) {
const error: RestError = e;
assert.strictEqual(error.statusCode, 400);
}
});
it("getNoModelError should throw 400", async () => {
try {
await client.httpFailure.getNoModelError();
assert.fail("Expected getNoModelError to throw");
} catch (e) {
const error: RestError = e;
assert.strictEqual(error.statusCode, 400);
assert.include(error.message, "NoErrorModel");
}
});
});
}); | the_stack |
import {TweenMax, TimelineMax, Power2, Power3, Power4} from 'gsap';
import objectAssign from 'object-assign';
import {
PlaneBufferGeometry, DataTexture, Vector2,
Vector3, Vector4, RGBFormat, ShaderMaterial, TextureLoader, Color,
Mesh, UnsignedByteType, UVMapping, RepeatWrapping,
LinearFilter, Texture, CanvasTexture } from 'three';
import SimplexNoise from 'simplex-noise';
import {vertexShader} from './visual-track-vert';
import {gradientFragmentShader} from './visual-track-fragment';
import {EventsService} from '../../services/events.service';
import {PRESETS} from './visual-track-presets';
import {TextTexture} from './text-texture';
const SHOW_EQ = false;
export class VisualTrack {
public options;
public id;
public layer;
public name;
public color;
public gradient;
public renderer;
public scene;
public displayObject;
public uniforms;
public analyser;
public fftArray;
public shader;
public guiData;
public guiFolder;
public speedOffset;
public average;
public bufferLength = 1024;
public amplitude = PRESETS.default.amplitude;
public range1 = new Vector4(0, 1, 0, 0.7);
public range2 = new Vector4(0, 0, 0, 0);
public lowcut = PRESETS.default.lowcut;
public resolution = PRESETS.default.resolution;
public opacity = PRESETS.default.opacity;
public period = PRESETS.default.period;
public speed = PRESETS.default.speed;
public stillHeight = PRESETS.default.stillHeight;
public offsetHeight = PRESETS.default.offsetHeight;
public smoothing = PRESETS.default.smoothing;
public fake = {
state: PRESETS.default.fake,
value: PRESETS.default.fake
};
public fillType = 'flat';
public materials = {};
public bubbleAnim;
public simplex = new SimplexNoise();
public state = 'intro'; // Can be ['default', 'on', 'intro']
public state_secondary = '';
public has_bonus = false;
public titleTexture;
public titleSize = new Vector2(1024, 128);
public titleColor = PRESETS.default.titleColor;
constructor(options, private eventsService?: EventsService) {
this.options = options || {};
this.id = options.id || null;
this.layer = options.layer || this.id;
this.name = options.name || '';
this.color = options.color || PRESETS.default.color;
this.gradient = options.gradient || PRESETS.default.gradient;
this.renderer = options.renderer || null;
this.scene = options.scene;
this.speedOffset = Math.random() * 2.0;
this.init();
}
init() {
const dpi = this.renderer.getPixelRatio();
this.titleTexture = new TextTexture({
width: this.titleSize.x,
height: this.titleSize.y,
dpi: dpi,
});
this.eventsService.on('setTrackState', (data) => {
this.updateState(data.state, data.secondary);
});
this.uniforms = {
tAudioData: { value: this.makeDataTexture(this.resolution) },
tEqData: { value: this.makeDataTexture(this.bufferLength) },
iResolution: { value: new Vector2( this.renderer.domElement.width, this.renderer.domElement.height ) } ,
iGlobalTime: { type: 'f', value: Math.random() * 10 },
amplitude: { type: 'f', value: this.amplitude },
numBins: { type: 'f', value: this.resolution },
layer: { type: 'f', value: this.layer },
colorA: { type: 'vec3', value: new Vector3(this.color[0], this.color[1], this.color[2]) },
colorB: { type: 'vec3', value: new Vector3(this.color[0], this.color[1], this.color[2]) },
stillHeight: { type: 'f', value: this.stillHeight },
offsetHeight: { type: 'f', value: this.offsetHeight },
range1: { type: 'vec4', value: this.range1 },
range2: { type: 'vec4', value: this.range2 },
lowcut: { type: 'f', value: this.lowcut },
showeq: { type: 'f', value: 0 },
opacity: { type: 'f', value: this.opacity },
period: { type: 'f', value: this.period },
speed: { type: 'f', value: this.speed + this.speedOffset },
nameDampDur: { type: 'f', value: 0.35 },
nameDampMin: { type: 'f', value: 0.3 },
bubble_pos: { type: 'vec2', value: new Vector2(0.5, -0.1) },
bubble_r: { type: 'f', value: 0 },
bubble_a: { type: 'f', value: 0 },
// Title
tTitle: {value: new CanvasTexture(this.titleTexture.canvas)},
titleSize: { type: 'vec2', value: new Vector2(this.titleSize.x * dpi, this.titleSize.y * dpi) },
titlePos: { type: 'vec2', value: new Vector2(0, 0) },
titleColor: { type: 'vec4', value: new Vector4(
this.titleColor[0],
this.titleColor[1],
this.titleColor[2],
this.titleColor[3],
)}, // Controls both color and opacity
titleSpeed: { type: 'f', value: 1.0 },
};
this.uniforms.tTitle.value.needsUpdate = true;
// Update name now that uniforms are defined
this.updateName(this.name);
this.materials = {
gradient: new ShaderMaterial({
transparent: true,
uniforms: this.uniforms,
vertexShader: vertexShader,
fragmentShader: gradientFragmentShader(SHOW_EQ),
})
};
// create the displayobject for this track
const geometry = new PlaneBufferGeometry( 10, 10 );
const plane = new Mesh(geometry, this.getMaterial('gradient'));
plane.position.set(0, 0, -.01 * this.layer);
plane.rotation.set(Math.PI / 180 * 1, 0, 0);
this.displayObject = plane;
if (this.options.gui) {
this.setupGui();
}
// Apply the presets
this.applyPreset(true);
}
getMaterial(fillType) {
// TODO: Remove if we're not switching between material types
// Material from dictionary
if (this.materials[fillType]) {
return this.materials[fillType];
}
// Return first material current fill type does not exist
const keys = Object.keys(this.materials);
if (keys.length) {
return this.materials[keys[0]];
}
// No materials
return null;
}
makeDataTexture(width, height = 1) {
return new DataTexture(
new Uint8Array(width * height * 3),
width,
height,
RGBFormat,
UnsignedByteType,
UVMapping,
RepeatWrapping,
RepeatWrapping,
LinearFilter,
LinearFilter,
);
}
setupGui() {
const gui = this.options.gui;
const material_keys = Object.keys(this.materials);
this.guiData = {
amplitude: this.amplitude,
rangeX1: this.range1.x,
rangeX2: this.range1.y,
rangeY1: this.range1.z,
rangeY2: this.range1.w,
lowcut: this.lowcut,
rangeX1_2: this.range2.x,
rangeX2_2: this.range2.y,
rangeY1_2: this.range2.z,
rangeY2_2: this.range2.w,
stillHeight: this.stillHeight,
offsetHeight: this.offsetHeight,
resolution: this.resolution,
showeq: !!this.uniforms.showeq.value,
smoothing: this.smoothing,
fillType: material_keys.length ? material_keys[0] : '',
};
const _this = this;
function effectChanger() {
// update shader uniforms
_this.set({
amplitude: _this.guiData.amplitude,
rangeX1: _this.guiData.rangeX1,
rangeX2: _this.guiData.rangeX2,
rangeY1: _this.guiData.rangeY1,
rangeY2: _this.guiData.rangeY2,
lowcut: _this.guiData.lowcut,
rangeX1_2: _this.guiData.rangeX1_2,
rangeX2_2: _this.guiData.rangeX2_2,
rangeY1_2: _this.guiData.rangeY1_2,
rangeY2_2: _this.guiData.rangeY2_2,
stillHeight: _this.guiData.stillHeight,
offsetHeight: _this.guiData.offsetHeight,
resolution: _this.guiData.resolution,
showeq: _this.guiData.showeq,
fillType: _this.guiData.fillType,
});
}
function smoothingChanger() {
_this.smoothing = _this.guiData.smoothing;
}
// add folders per track
const f = gui.addFolder('Track ' + this.id);
f.add(this.guiData, 'amplitude', 0.0, 1.0, .001).onChange( effectChanger );
f.add(this.guiData, 'rangeX1', 0.0, 1.0, .001).onChange( effectChanger );
f.add(this.guiData, 'rangeX2', 0.0, 1.0, .001).onChange( effectChanger );
f.add(this.guiData, 'rangeY1', 0.0, 1.0, .001).onChange( effectChanger );
f.add(this.guiData, 'rangeY2', 0.0, 1.0, .001).onChange( effectChanger );
f.add(this.guiData, 'lowcut', 0.0, 1.0, .001).onChange( effectChanger );
f.add(this.guiData, 'rangeX1_2', 0.0, 1.0, .001).onChange( effectChanger );
f.add(this.guiData, 'rangeX2_2', 0.0, 1.0, .001).onChange( effectChanger );
f.add(this.guiData, 'rangeY1_2', 0.0, 1.0, .001).onChange( effectChanger );
f.add(this.guiData, 'rangeY2_2', 0.0, 1.0, .001).onChange( effectChanger );
f.add(this.guiData, 'stillHeight', 0.0, 0.25, .001).onChange( effectChanger );
f.add(this.guiData, 'offsetHeight', 0.0, 0.5, 0.001).onChange( effectChanger );
f.add(this.guiData, 'resolution', [2, 4, 8, 16, 32, 64, 128, 256]).onChange( effectChanger );
f.add(this.guiData, 'showeq').onChange( effectChanger );
f.add(this.guiData, 'smoothing', 0.0, 1.0, 0.001).onChange( smoothingChanger );
f.add(this.guiData, 'fillType', Object.keys(this.materials)).onChange( effectChanger );
this.guiFolder = f;
}
getPreset() {
// Find Preset
let key = 'guitar';
if (this.id === 2) {
key = 'drums';
} else if (this.id === 3) {
key = 'bass';
} else if (this.id === 4) {
key = 'keyboard';
} else if (this.id === 5) {
key = 'bonus';
}
const keyDefault = (PRESETS[key] && PRESETS[key].default) ? PRESETS[key].default : {};
const keyState = (PRESETS[key] && PRESETS[key][this.state]) ? PRESETS[key][this.state] : {};
const keyStateSecondary = (this.state_secondary
&& PRESETS[key]
&& PRESETS[key][this.state_secondary])
? PRESETS[key][this.state_secondary] : {};
const preset = objectAssign({}, PRESETS.default, keyDefault, keyState, keyStateSecondary);
return preset;
}
applyPreset(hard = false) {
const preset = this.getPreset();
// Apply Preset
this.set(preset, hard);
// UPDATE GUI
if (this.guiFolder) {
this.guiData.amplitude = this.amplitude;
this.guiData.rangeX1 = this.range1.x;
this.guiData.rangeX2 = this.range1.y;
this.guiData.rangeY1 = this.range1.z;
this.guiData.rangeY2 = this.range1.w;
this.guiData.lowcut = this.lowcut;
this.guiData.rangeX1_2 = this.range2.x;
this.guiData.rangeX2_2 = this.range2.y;
this.guiData.rangeY1_2 = this.range2.z;
this.guiData.rangeY2_2 = this.range2.w;
this.guiData.stillHeight = this.stillHeight;
this.guiData.offsetHeight = this.offsetHeight;
this.guiData.resolution = this.resolution;
this.guiData.showeq = !!this.uniforms.showeq.value;
this.guiData.smoothing = this.smoothing;
this.guiData.fillType = this.fillType;
for (let i = 0; i < this.guiFolder.__controllers.length; i++) {
this.guiFolder.__controllers[i].updateDisplay();
}
}
}
onResize() {
const dpi = this.renderer.getPixelRatio();
this.uniforms.iResolution.value.x = this.renderer.domElement.width;
this.uniforms.iResolution.value.y = this.renderer.domElement.height;
this.uniforms.titleSize.value.x = this.titleSize.x * dpi;
this.uniforms.titleSize.value.y = this.titleSize.y * dpi;
this.updateName(this.name);
}
set(options, hard = false) {
// console.log('Set options track id', this.id, options);
options = options || {};
// chack gradient fill and reassign
if (options.name) {
this.updateName(options.name);
}
if (options.analyser) {
this.analyser = options.analyser;
const bufferLength = this.analyser.frequencyBinCount;
// this.analyser.minDecibels = -100;
this.analyser.maxDecibels = 0;
this.analyser.smoothingTimeConstant = 0.94;
this.fftArray = new Uint8Array(bufferLength);
this.bufferLength = bufferLength;
this.state = 'on';
this.applyPreset();
}
if (options.resolution) {
const resolution = parseInt(options.resolution, 10);
if (this.resolution !== resolution) {
this.resolution = resolution;
this.uniforms.tAudioData.value = this.makeDataTexture(this.resolution);
this.uniforms.numBins.value = this.resolution;
}
}
if (options.amplitude !== undefined) {
this.amplitude = options.amplitude;
this.tweenShaderAmplitude(hard ? 0 : undefined);
}
if (options.color) {
this.color = options.color;
this.tweenShaderColors(hard ? 0 : undefined);
}
if (options.gradient) {
this.gradient = options.gradient;
this.tweenShaderColors(hard ? 0 : undefined);
}
if (options.titleColor) {
this.titleColor = options.titleColor;
this.tweenShaderTitleColor(hard ? 0 : undefined);
}
if (options.opacity !== undefined) {
this.opacity = options.opacity;
this.tweenShaderOpacity(hard ? 0 : undefined);
}
if (options.stillHeight !== undefined) {
this.stillHeight = options.stillHeight;
// this.uniforms.stillHeight.value = options.stillHeight;
this.tweenShaderStillHeight(hard ? 0 : undefined);
}
if (options.offsetHeight !== undefined) {
this.offsetHeight = options.offsetHeight;
// this.uniforms.offsetHeight.value = options.offsetHeight;
this.tweenShaderOffsetHeight(hard ? 0 : undefined);
}
if (options.rangeX1 !== undefined) {
this.range1.x = options.rangeX1;
}
if (options.rangeX2 !== undefined) {
this.range1.y = options.rangeX2;
}
if (options.rangeY1 !== undefined) {
this.range1.z = options.rangeY1;
}
if (options.rangeY2 !== undefined) {
this.range1.w = options.rangeY2;
}
if (options.fillType !== undefined) {
if (this.fillType !== options.fillType) {
this.fillType = options.fillType;
this.tweenShaderColors();
}
}
if (options.lowcut !== undefined) {
this.lowcut = options.lowcut;
this.tweenShaderLowcut(hard ? 0 : undefined);
}
if (options.rangeX1_2 !== undefined) {
this.range2.x = options.rangeX1_2;
}
if (options.rangeX2_2 !== undefined) {
this.range2.y = options.rangeX2_2;
}
if (options.rangeY1_2 !== undefined) {
this.range2.z = options.rangeY1_2;
}
if (options.rangeY2_2 !== undefined) {
this.range2.w = options.rangeY2_2;
}
if (options.showeq !== undefined) {
this.uniforms.showeq.value = options.showeq ? 1 : 0;
}
if (options.period !== undefined) {
this.period = options.period;
this.tweenShaderPeriod();
}
if (options.speed !== undefined) {
this.speed = options.speed;
this.tweenShaderSpeed();
}
if (options.smoothing !== undefined) {
this.smoothing = options.smoothing;
}
if (options.titleSpeed !== undefined) {
this.tweenShaderTitleSpeed(options.titleSpeed);
}
if (options.fake !== undefined) {
if (this.fake.state !== options.fake) {
this.tweenFake(options.fake);
}
}
}
// tween the stillHeight property to flatten out the curve wave
removeWaveCurve() {
this.state_secondary = 'maxout';
this.applyPreset();
}
lowcutTweenComplete() {
setTimeout(function() {
this.state_secondary = this.has_bonus ? 'bonus' : '';
this.applyPreset();
}.bind(this), 300);
}
// tween to show 5 tracks
showFiveTracks() {
this.state_secondary = 'bonus';
this.has_bonus = true;
if ( this.id === 5 ) {
this.scene.add( this.displayObject );
} else {
this.applyPreset();
}
}
hideFiveTracks() {
this.state_secondary = '';
this.has_bonus = false;
if ( this.id === 5 ) {
this.updateName('');
} else {
// Restore to regular position
this.applyPreset();
}
}
onHideFiveTracksComplete() {
if ( this.id === 5 ) {
this.scene.remove( this.displayObject );
}
}
pickColors() {
if (this.fillType === 'flat') {
return [this.color, this.color];
} else if (this.fillType === 'gradient') {
return this.gradient;
}
}
releaseBubble(x = 0.5, duration = 3.0) {
if (this.bubbleAnim) {
this.bubbleAnim.kill();
}
const anim = new TimelineMax();
anim.set(this.uniforms.bubble_pos.value, { x: x });
anim.fromTo(this.uniforms.bubble_pos.value, duration,
{
y: -0.1
}, {
y: 1.1,
ease: Power2.easeInOut,
}, 0);
anim.fromTo(this.uniforms.bubble_r, duration,
{
value: 0
}, {
value: 0.055,
ease: Power2.easeOut,
}, 0);
this.bubbleAnim = anim;
}
tweenShaderColors(duration = 7.3, ease = Power4.easeOut) {
// Kill Existing Tweens
TweenMax.killTweensOf(this.uniforms.colorA.value);
TweenMax.killTweensOf(this.uniforms.colorB.value);
// Pick Colors
const colors = this.pickColors();
// Animation Settings
const settingsA = {
x: colors[0][0],
y: colors[0][1],
z: colors[0][2],
ease,
};
const settingsB = {
x: colors[1][0],
y: colors[1][1],
z: colors[1][2],
ease,
};
// Animate
TweenMax.to(this.uniforms.colorA.value, duration, settingsA);
TweenMax.to(this.uniforms.colorB.value, duration, settingsB);
}
tweenShaderTitleColor(duration = 3.5, ease = Power4.easeOut) {
// Kill Existing Tweens
TweenMax.killTweensOf(this.uniforms.titleColor.value);
// Animate
TweenMax.to(this.uniforms.titleColor.value, duration, {
x: this.titleColor[0],
y: this.titleColor[1],
z: this.titleColor[2],
w: this.titleColor[3],
ease,
});
}
tweenShaderAmplitude(duration = 7.3, ease = Power4.easeOut) {
// Kill Existing Tweens
TweenMax.killTweensOf(this.uniforms.amplitude);
// Animate
TweenMax.to(this.uniforms.amplitude, duration, {
value: this.amplitude,
ease,
});
}
tweenShaderOpacity(duration = 7.3, ease = Power4.easeOut) {
// Kill Existing Tweens
TweenMax.killTweensOf(this.uniforms.opacity);
// Animate
TweenMax.to(this.uniforms.opacity, duration, {
value: this.opacity,
ease,
});
}
tweenShaderPeriod(duration = 7.3, ease = Power4.easeOut) {
// Kill Existing Tweens
TweenMax.killTweensOf(this.uniforms.period);
// Animate
TweenMax.to(this.uniforms.period, duration, {
value: this.period,
ease,
});
}
tweenShaderSpeed(duration = 7.3, ease = Power4.easeOut) {
// Kill Existing Tweens
TweenMax.killTweensOf(this.uniforms.speed);
// Animate
const speed = this.speed + this.speedOffset;
TweenMax.to(this.uniforms.speed, duration, {
value: speed,
ease,
});
}
tweenShaderOffsetHeight(duration = 1.0, ease = Power3.easeOut, onComplete = () => {}) {
// Kill Existing Tweens
TweenMax.killTweensOf(this.uniforms.offsetHeight);
// Overwrite Defaults
// All of state transition details should be settable via presets
if (this.id === 5 && this.offsetHeight === 0.08) {
duration = 1.5;
onComplete = this.onHideFiveTracksComplete.bind(this);
}
// Animate
TweenMax.to(this.uniforms.offsetHeight, duration, {
value: this.offsetHeight,
ease,
onComplete,
});
// Make sure the name is the right size
this.updateName(this.name);
}
tweenShaderTitleSpeed(to, duration = 1.0, ease = Power3.easeInOut) {
this.uniforms.titleSpeed.value = to;
return;
// Kill Existing Tweens
// TweenMax.killTweensOf(this.uniforms.titleSpeed);
// Animate
// TweenMax.to(this.uniforms.titleSpeed, duration, {
// value: to,
// ease,
// });
}
tweenShaderStillHeight(duration = 1.0, ease = Power3.easeOut) {
// Kill Existing Tweens
TweenMax.killTweensOf(this.uniforms.stillHeight);
// Animate
TweenMax.to(this.uniforms.stillHeight, duration, {
value: this.stillHeight,
ease,
});
}
tweenShaderLowcut(duration = 0.5, ease = Power2.easeOut, onComplete = () => {}) {
// Kill Existing Tweens
TweenMax.killTweensOf(this.uniforms.lowcut);
let delay = 0;
if (this.lowcut === 0) {
delay = 0.5;
} else {
onComplete = this.lowcutTweenComplete.bind(this);
}
// Animate
TweenMax.to(this.uniforms.lowcut, duration, {
value: this.lowcut,
ease: ease,
onComplete,
delay,
});
}
tweenFake(val, duration = 1.5, ease = Power3.easeOut) {
this.fake.state = val;
// Kill Existing Tweens
TweenMax.killTweensOf(this.fake);
/*
The bass track looks better at resolution 8 when it has real data,
and at resolution 32 when it has fake data. Switch resolution at:
- End of animation if going from 1 to 0
- Before the animation if going from 0 to 1
*/
let onComplete = function() {};
if (this.id === 3 && val === 0) {
onComplete = function() {
this.set({ resolution: 8 });
}.bind(this);
}
if (this.id === 3 && val === 1) {
this.set({ resolution: 32 });
}
// Animate
TweenMax.to(this.fake, duration, {
value: val,
ease,
onComplete: onComplete
});
}
reset() {
this.analyser = false;
this.state = 'default';
// Get this track's default:
this.applyPreset();
}
easeAudioTexture() {
for ( let i = 0; i < this.resolution; i++ ) {
const c = this.uniforms.tAudioData.value.image.data[ i * 3 ];
const v = 0;
this.uniforms.tAudioData.value.image.data[ i * 3 ] += (v - c) * this.smoothing ;
}
}
fakeAudioTexture(strength) {
// Generated Simplex Noise based data
const max = 127;
let speed = 0.25;
let m = 5.0;
let n = 9.0;
if (this.id === 3) {
speed = 0.4;
m = 6.0;
n = 28.0;
}
for ( let i = 0; i < this.resolution; i++ ) {
const c = this.uniforms.tAudioData.value.image.data[ i * 3 ];
let v = this.simplex.noise3D(m * i / this.resolution, n, this.uniforms.iGlobalTime.value * speed);
v = (v + 1.0) / 2.0;
if (this.id === 3) {
v *= v;
}
v = max * v;
v = v * strength;
this.uniforms.tAudioData.value.image.data[ i * 3 ] += (v - c) * this.smoothing ;
}
}
getFFTValue(p, range, w, h, l) {
let v = 0;
if (h > 0) {
const index = Math.min(l - 1, Math.max(0, Math.floor(l * (range.x + p * w))));
v = this.fftArray[ index ] / 255;
if (v < this.lowcut) {
v = 0;
}
// Cut off bottom
v = Math.max(v - range.z, 0);
// Scale to the new box
v = Math.min(255 * v / h, 255);
}
return v;
}
updateAudioTexture() {
const l = this.fftArray.length;
const w1 = this.range1.y - this.range1.x;
const h1 = this.range1.w - this.range1.z;
const w2 = this.range2.y - this.range2.x;
const h2 = this.range2.w - this.range2.z;
for ( let i = 0; i < this.resolution; i++ ) {
// For each item in the resolution find a corresponding value in the fftArray
const p = i / this.resolution;
// Range 1
const v1 = this.getFFTValue(p, this.range1, w1, h1, l);
// Range 2
const v2 = this.getFFTValue(p, this.range2, w2, h2, l);
// Combine ranges and smooth out
const v = Math.min(v1 + v2, 255);
const c = this.uniforms.tAudioData.value.image.data[ i * 3 ];
// Set value
this.uniforms.tAudioData.value.image.data[ i * 3 ] += (v - c) * this.smoothing;
}
}
tick(timeDelta) {
this.uniforms.iGlobalTime.value = timeDelta / 1000;
if (!this.analyser || this.fake.value) {
if (this.fake.value > 0) {
this.fakeAudioTexture(this.fake.value);
} else {
this.easeAudioTexture();
}
this.uniforms.tAudioData.value.needsUpdate = true;
return;
}
// Get analysis data
this.analyser.getByteFrequencyData(this.fftArray);
// Transfer all data to our data texture so we can use it in the fragment shader
this.updateAudioTexture();
this.uniforms.tAudioData.value.needsUpdate = true;
if (SHOW_EQ) {
for ( let i = 0; i < this.fftArray.length; i ++ ) {
this.uniforms.tEqData.value.image.data[ i * 3 ] = this.fftArray[i];
}
this.uniforms.tEqData.value.needsUpdate = true;
}
}
updateName(name) {
// Name Style
name = (name.length > 0) ? name[0].toUpperCase() + name.slice(1) : '';
this.name = name;
this.titleTexture.setText(this.name, this.getNameStyle());
this.uniforms.tTitle.value.needsUpdate = true;
// Name Offset
const offset = this.getNameOffset();
const dpi = this.renderer.getPixelRatio();
this.uniforms.titlePos.value.x = offset.x * dpi;
this.uniforms.titlePos.value.y = offset.y * dpi;
}
getNameStyle() {
if (window.innerWidth < 500 && window.innerHeight > window.innerWidth) {
return {
fontSize: 25
};
}
return {
fontSize: Math.max(18, Math.min(55, window.innerHeight * this.offsetHeight * 0.45))
};
}
getNameOffset() {
return new Vector2(
Math.max(12, window.innerHeight * this.offsetHeight * 0.15),
window.innerHeight * this.offsetHeight * 0.2
);
}
updateState(state, secondary = '') {
this.state = state;
this.state_secondary = secondary;
this.applyPreset();
}
} | the_stack |
import {createContext, useContext, useMemo, useState} from 'react'
import Link from 'next/link'
import {Badge, Button, Divider, H2, H4, H5, Tabs, Tag, Text} from '@/omui'
import {SearchInput, TopContent} from '@/components/lib'
import {Alert} from '@/components/Alert'
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'
import {faCalendar, faCheck, faLink, faTimes} from '@fortawesome/free-solid-svg-icons'
import cloneDeep from 'lodash.clonedeep'
import {TableItem, useOMUITable} from '@/components/Table'
import Modal from '@/components/Modal'
import {Base} from '@/components/Layouts'
import {AcceptDeny} from '@/components/AcceptDenyButtons'
import {useDisclosure} from 'react-use-disclosure'
import {formatDate} from '@/utils'
import {useDataRequests, useBudgetRequests, useRequests} from '@/lib/data'
import {RequestStatusBadge} from '@/components/RequestStatusBadge'
const RequestsContext = createContext({data: [], budget: [], highlighted: null, selected: []})
function Pending() {
const {data} = useContext(RequestsContext)
if (!data) return <EmptyDataRequests />
return <DataRequestsPendingTable />
}
function DataRequestsPendingTable() {
const {open, isOpen, close} = useDisclosure()
const [picked, setPicked] = useState(null)
const {data} = useContext(RequestsContext)
const tableData = useMemo(() => data?.filter(req => req?.req?.status === 'pending') ?? [], [data])
function openDetails(id) {
setPicked(() => cloneDeep(tableData.find(data => data.req.id === id)))
open()
}
function onClose() {
setPicked(null)
close()
}
const tableColumns = useMemo(
() => [
{
Header: 'ID#',
accessor: 'req.id',
Cell: ({cell: {value}}) => (
<Badge variant="gray" type="subtle" truncate className="w-24">
{value}
</Badge>
)
},
{
Header: 'Name',
accessor: 'user.name',
Cell: ({cell: {value}}) => <Text size="sm">{value}</Text>
},
{
Header: (
<Text size="sm" className="space-x-1">
<FontAwesomeIcon icon={faCalendar} /> <span>Request Date</span>
</Text>
),
accessor: 'req.date',
Cell: ({cell: {value}}) => (
<Text size="sm" uppercase>
{formatDate(value)}
</Text>
)
},
{
Header: (
<Text size="sm" className="space-x-1">
<FontAwesomeIcon icon={faLink} /> <span>Linked Datasets</span>
</Text>
),
accessor: 'linked_datasets',
Cell: ({cell: {value}}) => (
<TableItem center>
{value?.map?.(datasetName => (
<Badge type="subtle" variant="gray">
{datasetName}
</Badge>
))}
</TableItem>
)
},
{
Header: 'Request Size',
accessor: 'req.size',
Cell: ({cell: {value}}) => (
<TableItem center>
<Badge variant="primary" type="subtle">
{value} ε
</Badge>
</TableItem>
)
},
{
Header: 'Action',
accessor: d => d?.req?.id,
Cell: ({cell: {value}}) => {
const update = useRequests().update(value).mutate
return (
<div className="flex space-x-5">
<button onClick={() => openDetails(value)}>
<Text underline className="text-primary-600 hover:text-primary-500">
See Details
</Text>
</button>
<AcceptDeny onAccept={() => update({status: 'accepted'})} onDeny={() => update({status: 'denied'})} />
</div>
)
}
}
],
[]
)
const table = useOMUITable({
data: tableData,
columns: tableColumns,
selectable: true,
sortable: true
})
const selected = table.instance.selectedFlatRows
return (
<>
{/* <div className="col-span-3 mt-10"> */}
{/* <SearchInput /> */}
{/* </div> */}
{/* <div className="col-span-full mt-8"> */}
{/* <Divider color="light" /> */}
{/* </div> */}
<section className="col-span-full space-y-6 mt-4">
{/* <div className="flex items-center space-x-2"> */}
{/* <Button variant="primary" size="sm" disabled={!selected.length} onClick={open}> */}
{/* <Text size="xs" bold> */}
{/* Accept ({selected.length}) Requests */}
{/* </Text> */}
{/* </Button> */}
{/* <Button */}
{/* variant="outline" */}
{/* size="sm" */}
{/* disabled={!selected.length} */}
{/* onClick={open} */}
{/* className="border-error-500 text-error-500"> */}
{/* <Text size="xs" bold> */}
{/* Reject ({selected.length}) Requests */}
{/* </Text> */}
{/* </Button> */}
{/* <Button */}
{/* type="button" */}
{/* variant="ghost" */}
{/* size="xs" */}
{/* disabled={!selected.length} */}
{/* onClick={() => table.instance.toggleAllRowsSelected(false)}> */}
{/* <Text size="sm" bold className="text-gray-600"> */}
{/* Cancel */}
{/* </Text> */}
{/* </Button> */}
{/* </div> */}
{table.Component}
{/* TODO: support pagination */}
<Text as="p" size="sm">
{tableData.length} / {tableData.length} results
</Text>
{picked && <RequestModal onClose={onClose} show={isOpen} data={picked} />}
</section>
</>
)
}
function DataRequestsHistoryTable() {
const {open, isOpen, close} = useDisclosure()
const [picked, setPicked] = useState(null)
const {data} = useContext(RequestsContext)
const tableData = useMemo(() => data?.filter(req => req?.req?.status !== 'pending') ?? [], [data])
function openDetails(id) {
setPicked(() => cloneDeep(tableData.find(data => data.req.id === id)))
open()
}
const tableColumns = useMemo(
() => [
{
Header: 'ID#',
accessor: 'req.id',
Cell: ({cell: {value}}) => (
<Badge variant="gray" type="subtle" truncate className="w-24">
{value}
</Badge>
)
},
{
Header: 'Name',
accessor: 'user.name',
Cell: ({cell: {value}}) => <Text size="sm">{value}</Text>
},
{
Header: 'Status',
accessor: 'req.status',
Cell: ({cell: {value}}) => <RequestStatusBadge status={value} />
},
{
Header: (
<Text size="sm" className="space-x-1">
<FontAwesomeIcon icon={faCalendar} /> <span>Updated on</span>
</Text>
),
accessor: 'req.updated_on',
Cell: ({cell: {value}}) => (
<Text size="sm" uppercase>
{formatDate(value)}
</Text>
)
},
{
Header: (
<Text size="sm" className="space-x-1">
<FontAwesomeIcon icon={faCalendar} /> <span>Updated by</span>
</Text>
),
accessor: 'req.updated_by',
Cell: ({cell: {value}}) => (
<Text size="sm" uppercase>
{value}
</Text>
)
},
{
Header: 'Request Size',
accessor: 'req.size',
Cell: ({cell: {value, row}}) => (
<TableItem center>
<Badge variant={row.original.status === 'accepted' ? 'success' : 'danger'} type="subtle">
{value} ε
</Badge>
</TableItem>
)
},
{
Header: 'Action',
accessor: d => d?.req?.id,
Cell: ({cell: {value}}) => (
<div onClick={() => openDetails(value)}>
<Text underline className="text-primary-600 hover:text-primary-500 cursor-pointer">
See Details
</Text>
</div>
)
}
],
[]
)
const table = useOMUITable({
data: tableData,
columns: tableColumns,
selectable: true,
sortable: true
})
const selected = table.instance.selectedFlatRows
return (
<>
<div className="col-span-3 mt-10">
<SearchInput />
</div>
<div className="col-span-full mt-8">
<Divider color="light" className="col-span-full" />
</div>
<section className="col-span-full space-y-6 mt-6">
{table.Component}
{/* TODO: support pagination */}
<Text as="p" size="sm">
{tableData.length} / {tableData.length} results
</Text>
{picked && <RequestModal show={isOpen} onClose={close} data={picked} />}
</section>
</>
)
}
function History() {
const {data} = useContext(RequestsContext)
if (data?.length === 0) <EmptyDataRequests />
return <DataRequestsHistoryTable />
}
function RequestModal({show, onClose, data}) {
const update = useRequests().update(data?.req?.id).mutate
const userInformation = [
{
text: 'Role',
value: (
<Badge variant="primary" type="subtle">
{data?.user?.role}
</Badge>
)
},
{
text: 'Privacy Budget',
value: (
<span className="inline-flex space-x-2">
<Badge type="solid" variant="danger">
{Number(data?.user?.budget_spent).toFixed(2)}
</Badge>
<Text size="sm">used of</Text>
<Badge type="subtle" variant="gray">
{Number(data?.user?.current_budget).toFixed(2)}
</Badge>
</span>
)
},
{
text: 'Email',
value: (
<a href={`mailto:${data?.user?.email}`}>
<Text size="sm" underline>
{data?.user?.email}
</Text>
</a>
)
},
{text: 'Company/Institution', value: data?.user?.institution},
{text: 'Website/Profile', value: data?.user?.website}
]
const requestDetails = [
{text: 'Request Date', value: data?.req?.date},
{
text: 'Tags',
value: (
<>
{data?.req?.tags?.map(tag => (
<Tag size="sm" tagType="round" variant="primary" className="mr-2">
{tag}
</Tag>
))}
</>
)
},
{text: 'Resource or Result ID', value: data?.req?.result_id},
// {text: 'Actions', property: 'actions'},
{text: '# of Values', value: data?.req?.size}
]
return (
<Modal show={show} onClose={onClose} withExpand>
<div className="col-span-full grid grid-cols-12">
<div className="col-span-10 col-start-2 mt-6">
{/* id */}
<div className="flex space-x-2 items-center">
<Text bold size="sm" className="flex-shrink-0">
Request ID:
</Text>
<Badge type="subtle" variant="gray" truncate>
{data?.req?.id}
</Badge>
</div>
{/* info */}
<div className="flex justify-between mt-3">
<H2>{data?.user?.name}</H2>
<div className="flex space-x-3 flex-shrink-0 items-center">
<RequestStatusBadge status={data?.req?.status} />
{data?.req?.status === 'pending' && (
<>
<div className="rounded-full w-7 h-7 bg-gray-200 justify-center items-center flex text-white hover:bg-primary-500 cursor-pointer">
<FontAwesomeIcon icon={faCheck} onClick={() => update({status: 'accepted'})} />
</div>
<div className="rounded-full w-7 h-7 bg-gray-200 justify-center items-center flex text-white hover:bg-primary-500 cursor-pointer">
<FontAwesomeIcon icon={faTimes} onClick={() => update({status: 'denied'})} />
</div>
</>
)}
</div>
</div>
{/* cards */}
<div className="flex space-x-4 w-full mt-4">
{/* pb-card */}
<div
className="w-full bg-gray-50 border border-gray-100 pl-6 pr-8 pt-2 pb-4 space-y-4"
style={{
background:
'linear-gradient(90deg, rgba(255, 255, 255, 0.8) 0%, rgba(255, 255, 255, 0.5) 100%), #F1F0F4'
}}>
<div className="flex items-center w-full justify-between">
<div className="pr-6 border-r border-gray-200">
<div className="flex items-center space-x-2">
<Text as="p" size="3xl">
{data?.req?.size}
</Text>
<Text size="lg">ɛ</Text>
</div>
<Text as="p">
request size
{/* request size <Tooltip position="top">HELT OK</Tooltip> */}
</Text>
</div>
<div className="pl-6">
<Text size="3xl" as="p">
{data?.req?.subjects}
</Text>
<div className="flex items-start space-x-2">
<Text as="p">data subjects</Text> {/* <div> */}
{/* <Tooltip position="top">NOT OK</Tooltip> */}
{/* </div> */}
</div>
</div>
</div>
{/* info-card */}
<Divider color="light" />
<div>
<Text bold size="sm">
Linked Datasets
{/* Linked Datasets <Tooltip position="top">OK</Tooltip> */}
</Text>
<div className="flex flex-wrap w-full">
{data?.req?.datasets?.map(datasetName => (
<div key={datasetName} className="mr-2">
<Badge type="subtle" variant="gray" truncate>
{datasetName}
</Badge>
</div>
))}
</div>
</div>
</div>
{/* request details card */}
<div className="w-full border border-gray-100 p-6 space-y-4">
{userInformation.map(info => {
return (
<div key={info.text} className="w-full truncate">
<Text size="sm" bold>
{info.text}:
</Text>{' '}
<Text size="sm">{info.value}</Text>
</div>
)
})}
<div>
<Link href="/">
<a>
<Text as="p" underline size="xs" className="text-primary-600">
View User Profile
</Text>
</a>
</Link>
</div>
</div>
</div>
<Divider color="light" className="mt-6" />
<div className="mt-6 space-y-3">
<H5>Request Details</H5>
<div className="border border-gray-100 p-6 pb-8 relative">
<div className="flex flex-col space-y-4">
<div className="flex items-center">
<Text bold>Request ID: </Text>{' '}
<Badge variant="gray" type="subtle" truncate>
{data?.req?.id}
</Badge>
</div>
{requestDetails.map(reqDetail => (
<div key={reqDetail.text}>
<Text bold>{reqDetail.text}:</Text> <Text>{reqDetail.value}</Text>
</div>
))}
<Divider color="light" />
<div className="bg-gray-50 p-3">
<Text as="p" bold size="sm">
Reason:
</Text>
<Text as="p" size="sm">
{data?.req?.reason}
</Text>
</div>
{/* <Divider color="light" /> */}
{/* <div> */}
{/* <Button className="w-auto"> */}
{/* <Text size="sm" bold> */}
{/* <FontAwesomeIcon icon={faDownload} /> Preview Result */}
{/* </Text> */}
{/* </Button> */}
{/* </div> */}
{/* <Text size="sm" as="p"> */}
{/* By{' '} */}
{/* <Text mono className="text-primary-600" size="sm"> */}
{/* Previewing Results */}
{/* </Text>{' '} */}
{/* you are downloading the results this Data Scientist is requesting. Currently results are in */}
{/* [name_here] format. For help viewing the downloaded results you can go here for further instructions. */}
{/* </Text> */}
</div>
</div>
</div>
</div>
</div>
</Modal>
)
}
function EmptyDataRequests() {
return (
<div className="space-y-2 w-full text-center col-span-8 col-start-3 mt-20">
<H4>Congratulations</H4>
<Text className="text-gray-400">You’ve cleared all data requests in your queue!</Text>
</div>
)
}
export default function DataRequests() {
const {data: dataReq} = useDataRequests().all()
const {data: budgetReq} = useBudgetRequests().all()
const [currentTab, setCurrentTab] = useState(() => 1)
const tabsList = [
{id: 1, title: 'Pending'},
{id: 2, title: 'History'}
]
return (
<Base>
<RequestsContext.Provider value={{data: dataReq, budget: budgetReq, highlighted: null, selected: []}}>
<TopContent heading="Data Requests" />
<div className="col-span-10">
<Alert.Info
alertStyle="topAccent"
description="Data requests are one-time requests made from Data Scientists on your node to download the results of their computations. Unlike setting privacy budgets data requests must be manually triaged and do not count as ongoing credits. They are individual allowances based off of specific computations on specified data objects."
/>
</div>
<div className="col-span-full mt-10">
<Tabs tabsList={tabsList} onChange={setCurrentTab} align="auto" active={currentTab} />
</div>
{currentTab === 1 && <Pending />}
{currentTab === 2 && <History />}
</RequestsContext.Provider>
</Base>
)
} | the_stack |
import type {
FileBoxInterface,
} from 'file-box'
import {
log,
} from '../config.js'
import type { PuppetSkeleton } from '../puppet/puppet-skeleton.js'
import type {
ContactPayload,
ContactPayloadFilterFunction,
ContactQueryFilter,
} from '../schemas/contact.js'
import { PayloadType } from '../schemas/payload.js'
import type { CacheMixin } from './cache-mixin.js'
const contactMixin = <MixinBase extends CacheMixin & typeof PuppetSkeleton>(mixinBase: MixinBase) => {
abstract class ContactMixin extends mixinBase {
constructor (...args: any[]) {
super(...args)
log.verbose('PuppetContactMixin', 'constructor()')
}
/**
*
* ContactSelf
*
*/
abstract contactSelfName (name: string) : Promise<void>
abstract contactSelfQRCode () : Promise<string /* QR Code Value */>
abstract contactSelfSignature (signature: string) : Promise<void>
/**
*
* Contact
*
*/
abstract contactAlias (contactId: string) : Promise<string>
abstract contactAlias (contactId: string, alias: string | null) : Promise<void>
abstract contactAvatar (contactId: string) : Promise<FileBoxInterface>
abstract contactAvatar (contactId: string, file: FileBoxInterface) : Promise<void>
abstract contactPhone (contactId: string, phoneList: string[]) : Promise<void>
abstract contactCorporationRemark (contactId: string, corporationRemark: string | null): Promise<void>
abstract contactDescription (contactId: string, description: string | null): Promise<void>
abstract contactList (): Promise<string[]>
/**
* @protected Issue #155 - https://github.com/wechaty/puppet/issues/155
*/
abstract contactRawPayload (contactId: string): Promise<any>
/**
* @protected Issue #155 - https://github.com/wechaty/puppet/issues/155
*/
abstract contactRawPayloadParser (rawPayload: any) : Promise<ContactPayload>
// async contactRoomList (
// contactId: string,
// ): Promise<string[] /* roomId */> {
// log.verbose('PuppetContactMixin', 'contactRoomList(%s)', contactId)
// const roomIdList = await this.roomList()
// const roomPayloadList = await Promise.all(
// roomIdList.map(
// roomId => this.roomPayload(roomId),
// ),
// )
// const resultRoomIdList = roomPayloadList
// .filter(roomPayload => roomPayload.memberIdList.includes(contactId))
// .map(payload => payload.id)
// return resultRoomIdList
// }
/**
* @param query {string | Object} if string, then search `name` & `alias`
*/
async contactSearch (
query? : string | ContactQueryFilter,
searchIdList? : string[],
): Promise<string[]> {
log.verbose('PuppetContactMixin', 'contactSearch(query=%s, %s)',
JSON.stringify(query),
searchIdList
? `idList.length = ${searchIdList.length}`
: '',
)
/**
* Huan(202110): optimize for search id
*/
if (typeof query !== 'string' && query?.id) {
try {
// make sure the contact id has valid payload
await this.contactPayload(query.id)
return [query.id]
} catch (e) {
log.verbose('PuppetContactMixin', 'contactSearch() payload not found for id "%s"', query.id)
await this.contactPayloadDirty(query.id)
return []
}
}
/**
* Deal non-id queries
*/
if (!searchIdList) {
searchIdList = await this.contactList()
}
log.silly('PuppetContactMixin', 'contactSearch() searchIdList.length = %d', searchIdList.length)
if (!query) {
return searchIdList
}
if (typeof query === 'string') {
const nameIdList = await this.contactSearch({ name: query }, searchIdList)
const aliasIdList = await this.contactSearch({ alias: query }, searchIdList)
return Array.from(
new Set([
...nameIdList,
...aliasIdList,
]),
)
}
const filterFunction: ContactPayloadFilterFunction = this.contactQueryFilterFactory(query)
const BATCH_SIZE = 16
let batchIndex = 0
const resultIdList: string[] = []
const matchId = async (id: string) => {
try {
/**
* Does LRU cache matter at here?
*/
// const rawPayload = await this.contactRawPayload(id)
// const payload = await this.contactRawPayloadParser(rawPayload)
const payload = await this.contactPayload(id)
if (filterFunction(payload)) {
return id
}
} catch (e) {
this.emit('error', e)
await this.contactPayloadDirty(id)
}
return undefined
}
while (BATCH_SIZE * batchIndex < searchIdList.length) {
const batchSearchIdList = searchIdList.slice(
BATCH_SIZE * batchIndex,
BATCH_SIZE * (batchIndex + 1),
)
/**
* Huan(202110): TODO: use an iterator with works to control the concurrency of Promise.all.
* @see https://stackoverflow.com/a/51020535/1123955
*/
const matchBatchIdFutureList = batchSearchIdList.map(matchId)
const matchBatchIdList = await Promise.all(matchBatchIdFutureList)
const batchSearchIdResultList: string[] = matchBatchIdList.filter(id => !!id) as string[]
resultIdList.push(...batchSearchIdResultList)
batchIndex++
}
log.silly('PuppetContactMixin', 'contactSearch() searchContactPayloadList.length = %d', resultIdList.length)
return resultIdList
}
/**
* Issue #155 - https://github.com/wechaty/puppet/issues/155
*
* @protected
*/
contactQueryFilterFactory (
query: ContactQueryFilter,
): ContactPayloadFilterFunction {
log.verbose('PuppetContactMixin', 'contactQueryFilterFactory(%s)',
JSON.stringify(query),
)
/**
* Clean the query for keys with empty value
*/
Object.keys(query).forEach(key => {
if (query[key as keyof ContactQueryFilter] === undefined) {
delete query[key as keyof ContactQueryFilter]
}
})
if (Object.keys(query).length < 1) {
throw new Error('query must provide at least one key. current query is empty.')
} else if (Object.keys(query).length > 1) {
throw new Error('query only support one key. multi key support is not available now.')
}
// Huan(202105): we use `!` at here because the above `if` checks
const filterKey = Object.keys(query)[0]!.toLowerCase() as keyof ContactQueryFilter
const isValid = [
'alias',
'id',
'name',
'weixin',
].includes(filterKey)
if (!isValid) {
throw new Error('key not supported: ' + filterKey)
}
// TypeScript bug: have to set `undefined | string | RegExp` at here, or the later code type check will get error
const filterValue: undefined | string | RegExp = query[filterKey]
if (!filterValue) {
throw new Error('filterValue not found for filterKey: ' + filterKey)
}
let filterFunction
if (typeof filterValue === 'string') {
filterFunction = (payload: ContactPayload) => filterValue === payload[filterKey]
} else if (filterValue instanceof RegExp) {
filterFunction = (payload: ContactPayload) => !!payload[filterKey] && filterValue.test(payload[filterKey]!)
} else {
throw new Error('unsupported filterValue type: ' + typeof filterValue)
}
return filterFunction
}
/**
* Check a Contact Id if it's still valid.
* For example: talk to the server, and see if it should be deleted in the local cache.
*/
async contactValidate (contactId: string) : Promise<boolean> {
log.silly('PuppetContactMixin', 'contactValidate(%s) base class just return `true`', contactId)
return true
}
/**
* Issue #155 - https://github.com/wechaty/puppet/issues/155
*
* @protected
*/
contactPayloadCache (contactId: string): undefined | ContactPayload {
// log.silly('PuppetContactMixin', 'contactPayloadCache(id=%s) @ %s', contactId, this)
if (!contactId) {
throw new Error('no id')
}
const cachedPayload = this.cache.contact.get(contactId)
if (cachedPayload) {
// log.silly('PuppetContactMixin', 'contactPayload(%s) cache HIT', contactId)
} else {
log.silly('PuppetContactMixin', 'contactPayload(%s) cache MISS', contactId)
}
return cachedPayload
}
async contactPayload (
contactId: string,
): Promise<ContactPayload> {
// log.silly('PuppetContactMixin', 'contactPayload(id=%s) @ %s', contactId, this)
if (!contactId) {
throw new Error('no id')
}
/**
* 1. Try to get from cache first
*/
const cachedPayload = this.contactPayloadCache(contactId)
if (cachedPayload) {
return cachedPayload
}
/**
* 2. Cache not found
*/
const rawPayload = await this.contactRawPayload(contactId)
const payload = await this.contactRawPayloadParser(rawPayload)
this.cache.contact.set(contactId, payload)
log.silly('PuppetContactMixin', 'contactPayload(%s) cache SET', contactId)
return payload
}
async contactPayloadDirty (
id: string,
): Promise<void> {
log.verbose('PuppetContactMixin', 'contactPayloadDirty(%s)', id)
await this.__dirtyPayloadAwait(
PayloadType.Contact,
id,
)
}
}
return ContactMixin
}
type ProtectedPropertyContactMixin =
| 'contactRawPayload'
| 'contactRawPayloadParser'
| 'contactQueryFilterFactory'
| 'contactPayloadCache'
type ContactMixin = ReturnType<typeof contactMixin>
export type {
ContactMixin,
ProtectedPropertyContactMixin,
}
export { contactMixin } | the_stack |
* @module iModels
*/
// cspell:ignore cset csets ecchanges
import * as path from "path";
import {
AccessToken, BeDuration, ChangeSetStatus, GuidString, IModelHubStatus, IModelStatus, Logger, OpenMode,
} from "@itwin/core-bentley";
import {
BriefcaseId, BriefcaseIdValue, BriefcaseProps, ChangesetFileProps, ChangesetIndex, ChangesetType, IModelError, IModelVersion, LocalBriefcaseProps,
LocalDirName, LocalFileName, RequestNewBriefcaseProps, RpcActivity,
} from "@itwin/core-common";
import { TelemetryEvent } from "@itwin/core-telemetry";
import { AcquireNewBriefcaseIdArg } from "./BackendHubAccess";
import { BackendLoggerCategory } from "./BackendLoggerCategory";
import { CheckpointManager, CheckpointProps, ProgressFunction } from "./CheckpointManager";
import { BriefcaseDb, IModelDb, TokenArg } from "./IModelDb";
import { IModelHost } from "./IModelHost";
import { IModelJsFs } from "./IModelJsFs";
const loggerCategory = BackendLoggerCategory.IModelDb;
/** The argument for [[BriefcaseManager.downloadBriefcase]]
* @public
*/
export interface RequestNewBriefcaseArg extends TokenArg, RequestNewBriefcaseProps {
/** If present, a function called periodically during the download to indicate progress.
* @note return non-zero from this function to abort the download.
*/
onProgress?: ProgressFunction;
}
/**
* Parameters for pushing changesets to iModelHub
* @public
*/
export interface PushChangesArgs extends TokenArg {
/** A description of the changes. This is visible on the iModel's timeline. */
description: string;
/** if present, the locks are retained after the operation. Otherwise, *all* locks are released after the changeset is successfully pushed. */
retainLocks?: true;
/** number of times to retry pull/merge if other users are pushing at the same time. Default is 5 */
mergeRetryCount?: number;
/** delay to wait between pull/merge retry attempts. Default is 3 seconds */
mergeRetryDelay?: BeDuration;
/** the number of time to attempt to retry to push the changeset upon failure. Default is 3 */
pushRetryCount?: number;
/** The delay to wait between retry attempts on failed pushes. Default is 3 seconds. */
pushRetryDelay?: BeDuration;
}
/**
* Specifies a specific index for pulling changes.
* @public
*/
export interface ToChangesetArgs extends TokenArg {
/** The last ChangesetIndex to pull. If not present, pull *all* newer changesets. */
toIndex?: ChangesetIndex;
}
/** Arguments for [[BriefcaseManager.pullAndApplyChangesets]]
* @public
*/
export type PullChangesArgs = ToChangesetArgs;
/** Manages downloading Briefcases and downloading and uploading changesets.
* @public
*/
export class BriefcaseManager {
/** Get the local path of the folder storing files that are associated with an imodel */
public static getIModelPath(iModelId: GuidString): LocalDirName { return path.join(this._cacheDir, iModelId); }
/** @internal */
public static getChangeSetsPath(iModelId: GuidString): LocalDirName { return path.join(this.getIModelPath(iModelId), "changesets"); }
/** @internal */
public static getChangeCachePathName(iModelId: GuidString): LocalFileName { return path.join(this.getIModelPath(iModelId), iModelId.concat(".bim.ecchanges")); }
/** @internal */
public static getChangedElementsPathName(iModelId: GuidString): LocalFileName { return path.join(this.getIModelPath(iModelId), iModelId.concat(".bim.elems")); }
private static _briefcaseSubDir = "briefcases";
/** @internal */
public static getBriefcaseBasePath(iModelId: GuidString): LocalDirName {
return path.join(this.getIModelPath(iModelId), this._briefcaseSubDir);
}
/** Get the name of the local file that holds, or will hold, a local briefcase in the briefcase cache.
* @note The briefcase cache is a local directory established in the call to [[BriefcaseManager.initialize]].
* @param briefcase the iModelId and BriefcaseId for the filename
* @see getIModelPath
*/
public static getFileName(briefcase: BriefcaseProps): LocalFileName {
return path.join(this.getBriefcaseBasePath(briefcase.iModelId), `${briefcase.briefcaseId}.bim`);
}
private static setupCacheDir(cacheRootDir: LocalDirName) {
this._cacheDir = cacheRootDir;
IModelJsFs.recursiveMkDirSync(this._cacheDir);
}
private static _initialized?: boolean;
/** Initialize BriefcaseManager
* @param cacheRootDir The root directory for storing a cache of downloaded briefcase files on the local computer.
* Briefcases are stored relative to this path in sub-folders organized by IModelId.
* @note It is perfectly valid for applications to store briefcases in locations they manage, outside of `cacheRootDir`.
*/
public static initialize(cacheRootDir: LocalDirName) {
if (this._initialized)
return;
this.setupCacheDir(cacheRootDir);
IModelHost.onBeforeShutdown.addOnce(this.finalize, this);
this._initialized = true;
}
private static finalize() {
this._initialized = false;
}
/** Get a list of the local briefcase held in the briefcase cache, optionally for a single iModelId
* @param iModelId if present, only briefcases for this iModelId are returned, otherwise all briefcases for all
* iModels in the briefcase cache are returned.
* @note usually there should only be one briefcase per iModel.
*/
public static getCachedBriefcases(iModelId?: GuidString): LocalBriefcaseProps[] {
const briefcaseList: LocalBriefcaseProps[] = [];
const iModelDirs = IModelJsFs.readdirSync(this._cacheDir);
for (const iModelDir of iModelDirs) {
if (iModelId && iModelId !== iModelDir)
continue;
const bcPath = path.join(this._cacheDir, iModelDir, this._briefcaseSubDir);
try {
if (!IModelJsFs.lstatSync(bcPath)?.isDirectory)
continue;
} catch (err) {
continue;
}
const briefcases = IModelJsFs.readdirSync(bcPath);
for (const briefcaseName of briefcases) {
if (briefcaseName.endsWith(".bim")) {
try {
const fileName = path.join(bcPath, briefcaseName);
const fileSize = IModelJsFs.lstatSync(fileName)?.size ?? 0;
const db = IModelDb.openDgnDb({ path: fileName }, OpenMode.Readonly);
briefcaseList.push({ fileName, iTwinId: db.getITwinId(), iModelId: db.getIModelId(), briefcaseId: db.getBriefcaseId(), changeset: db.getCurrentChangeset(), fileSize });
db.closeIModel();
} catch (_err) {
}
}
}
}
return briefcaseList;
}
private static _cacheDir: LocalDirName;
/** Get the root directory for the briefcase cache */
public static get cacheDir(): LocalDirName { return this._cacheDir; }
/** Determine whether the supplied briefcaseId is in the range of assigned BriefcaseIds issued by iModelHub
* @note this does check whether the id was actually acquired by the caller.
*/
public static isValidBriefcaseId(id: BriefcaseId) {
return id >= BriefcaseIdValue.FirstValid && id <= BriefcaseIdValue.LastValid;
}
/** Acquire a new briefcaseId from iModelHub for the supplied iModelId
* @note usually there should only be one briefcase per iModel per user. If a single user acquires more than one briefcaseId,
* it's a good idea to supply different aliases for each of them.
*/
public static async acquireNewBriefcaseId(arg: AcquireNewBriefcaseIdArg): Promise<BriefcaseId> {
return IModelHost.hubAccess.acquireNewBriefcaseId(arg);
}
/** Download a new briefcase from iModelHub for the supplied iModelId.
*
* The process of downloading a briefcase file involves first obtaining a valid BriefcaseId from IModelHub. For each IModel, IModelHub maintains
* a list of BriefcaseIds assigned to users, to ensure that no two users have the same BriefcaseId. Typically a given user will have only
* one briefcase on their machine for a given iModelId. Rarely, it may be necessary to use more than one briefcase to make isolated independent sets of changes,
* but that is exceedingly complicated and rare. If no BriefcaseId is supplied, a new one is acquired from iModelHub.
*
* Then, a Checkpoint file (as of a ChangeSetId, typically "Latest") is downloaded from IModelHub. After the download completes,
* the briefcaseId in the local file is changed to acquired briefcaseId, changing the checkpoint file into a briefcase file.
*
* Each of these steps requires a valid `AuthorizedClientRequestContext` to provide the user's credentials for the requests.
*
* @param request The properties that specify the briefcase file to be downloaded.
* @returns The properties of the local briefcase in a Promise that is resolved after the briefcase is fully downloaded and the briefcase file is ready for use via [BriefcaseDb.open]($backend).
* @note The location of the local file to hold the briefcase is arbitrary and may be any valid *local* path on your machine. If you don't supply
* a filename, the local briefcase cache is used by creating a file with the briefcaseId as its name in the `briefcases` folder below the folder named
* for the IModelId.
* @note *It is invalid to edit briefcases on a shared network drive* and that is a sure way to corrupt your briefcase (see https://www.sqlite.org/howtocorrupt.html)
* @note The special briefcaseId [[BriefcaseIdValue.Unassigned]] (0) can be used for a local briefcase that can accept changesets but may not be generate changesets.
* @see CheckpointManager.downloadCheckpoint
*/
public static async downloadBriefcase(arg: RequestNewBriefcaseArg): Promise<LocalBriefcaseProps> {
const briefcaseId = arg.briefcaseId = arg.briefcaseId ?? await this.acquireNewBriefcaseId(arg);
const fileName = arg.fileName ?? this.getFileName(arg as BriefcaseProps);
if (IModelJsFs.existsSync(fileName))
throw new IModelError(IModelStatus.FileAlreadyExists, `Briefcase "${fileName}" already exists`);
const asOf = arg.asOf ?? IModelVersion.latest().toJSON();
const changeset = await IModelHost.hubAccess.getChangesetFromVersion({ ...arg, version: IModelVersion.fromJSON(asOf) });
const checkpoint: CheckpointProps = { ...arg, changeset };
await CheckpointManager.downloadCheckpoint({ localFile: fileName, checkpoint, onProgress: arg.onProgress });
const fileSize = IModelJsFs.lstatSync(fileName)?.size ?? 0;
const response: LocalBriefcaseProps = {
fileName,
briefcaseId,
iModelId: arg.iModelId,
iTwinId: arg.iTwinId,
changeset: checkpoint.changeset,
fileSize,
};
// now open the downloaded checkpoint and reset its BriefcaseId
const nativeDb = new IModelHost.platform.DgnDb();
try {
nativeDb.openIModel(fileName, OpenMode.ReadWrite);
} catch (err: any) {
throw new IModelError(err.errorNumber, `Could not open downloaded briefcase for write access: ${fileName}, err=${err.message}`);
}
try {
nativeDb.resetBriefcaseId(briefcaseId);
if (nativeDb.getCurrentChangeset().id !== checkpoint.changeset.id)
throw new IModelError(IModelStatus.InvalidId, `Downloaded briefcase has wrong changesetId: ${fileName}`);
} finally {
nativeDb.saveChanges();
nativeDb.closeIModel();
}
return response;
}
/** Deletes change sets of an iModel from local disk
* @internal
*/
public static deleteChangeSetsFromLocalDisk(iModelId: string) {
const changesetsPath = BriefcaseManager.getChangeSetsPath(iModelId);
BriefcaseManager.deleteFolderAndContents(changesetsPath);
}
/** Releases a briefcaseId from iModelHub. After this call it is illegal to generate changesets for the released briefcaseId.
* @note generally, this method should not be called directly. Instead use [[deleteBriefcaseFiles]].
* @see deleteBriefcaseFiles
*/
public static async releaseBriefcase(accessToken: AccessToken, briefcase: BriefcaseProps): Promise<void> {
if (this.isValidBriefcaseId(briefcase.briefcaseId))
return IModelHost.hubAccess.releaseBriefcase({ accessToken, iModelId: briefcase.iModelId, briefcaseId: briefcase.briefcaseId });
}
/**
* Delete and clean up a briefcase and all of its associated files. First, this method opens the supplied filename to determine its briefcaseId.
* Then, if a requestContext is supplied, it releases a BriefcaseId from iModelHub. Finally it deletes the local briefcase file and
* associated files (that is, all files in the same directory that start with the briefcase name).
* @param filePath the full file name of the Briefcase to delete
* @param accessToken for releasing the briefcaseId
*/
public static async deleteBriefcaseFiles(filePath: LocalFileName, accessToken?: AccessToken): Promise<void> {
try {
const db = IModelDb.openDgnDb({ path: filePath }, OpenMode.Readonly);
const briefcase: BriefcaseProps = {
iModelId: db.getIModelId(),
briefcaseId: db.getBriefcaseId(),
};
db.closeIModel();
if (accessToken) {
if (this.isValidBriefcaseId(briefcase.briefcaseId)) {
await BriefcaseManager.releaseBriefcase(accessToken, briefcase);
}
}
} catch (error) {
}
// first try to delete the briefcase file
try {
if (IModelJsFs.existsSync(filePath))
IModelJsFs.unlinkSync(filePath);
} catch (err) {
throw new IModelError(IModelStatus.BadRequest, `cannot delete briefcase file ${err}`);
}
// next, delete all files that start with the briefcase's filePath (e.g. "a.bim-locks", "a.bim-journal", etc.)
try {
const dirName = path.dirname(filePath);
const fileName = path.basename(filePath);
const files = IModelJsFs.readdirSync(dirName);
for (const file of files) {
if (file.startsWith(fileName))
this.deleteFile(path.join(dirName, file)); // don't throw on error
}
} catch (err) {
}
}
/** Deletes a file
* - Does not throw any error, but logs it instead
* - Returns true if the delete was successful
*/
private static deleteFile(pathname: LocalFileName): boolean {
try {
IModelJsFs.unlinkSync(pathname);
} catch (error) {
Logger.logError(loggerCategory, `Cannot delete file ${pathname}, ${error}`);
return false;
}
return true;
}
/** Deletes a folder, checking if it's empty
* - Does not throw any error, but logs it instead
* - Returns true if the delete was successful
*/
private static deleteFolderIfEmpty(folderPathname: LocalDirName): boolean {
try {
const files = IModelJsFs.readdirSync(folderPathname);
if (files.length > 0)
return false;
IModelJsFs.rmdirSync(folderPathname);
} catch (error) {
Logger.logError(loggerCategory, `Cannot delete folder: ${folderPathname}`);
return false;
}
return true;
}
/** Deletes the contents of a folder, but not the folder itself
* - Does not throw any errors, but logs them.
* - returns true if the delete was successful.
*/
private static deleteFolderContents(folderPathname: LocalDirName): boolean {
if (!IModelJsFs.existsSync(folderPathname))
return false;
let status = true;
const files = IModelJsFs.readdirSync(folderPathname);
for (const file of files) {
const curPath = path.join(folderPathname, file);
const locStatus = (IModelJsFs.lstatSync(curPath)?.isDirectory) ? BriefcaseManager.deleteFolderAndContents(curPath) : BriefcaseManager.deleteFile(curPath);
if (!locStatus)
status = false;
}
return status;
}
/** Deletes a folder and all it's contents.
* - Does not throw any errors, but logs them.
* - returns true if the delete was successful.
*/
private static deleteFolderAndContents(folderPathname: LocalDirName): boolean {
if (!IModelJsFs.existsSync(folderPathname))
return true;
let status = false;
status = BriefcaseManager.deleteFolderContents(folderPathname);
if (!status)
return false;
status = BriefcaseManager.deleteFolderIfEmpty(folderPathname);
return status;
}
private static async applySingleChangeset(db: IModelDb, changesetFile: ChangesetFileProps) {
if (changesetFile.changesType === ChangesetType.Schema)
db.clearCaches(); // for schema changesets, statement caches may become invalid. Do this *before* applying, in case db needs to be closed (open statements hold db open.)
db.nativeDb.applyChangeset(changesetFile);
db.changeset = db.nativeDb.getCurrentChangeset();
// we're done with this changeset, delete it
IModelJsFs.removeSync(changesetFile.pathname);
}
/** @internal */
public static async pullAndApplyChangesets(db: IModelDb, arg: ToChangesetArgs): Promise<void> {
if (!db.isOpen || db.nativeDb.isReadonly()) // don't use db.isReadonly - we reopen the file writable just for this operation but db.isReadonly is still true
throw new IModelError(ChangeSetStatus.ApplyError, "Briefcase must be open ReadWrite to process change sets");
let currentIndex = db.changeset.index;
if (currentIndex === undefined)
currentIndex = (await IModelHost.hubAccess.queryChangeset({ accessToken: arg.accessToken, iModelId: db.iModelId, changeset: { id: db.changeset.id } })).index;
const reverse = (arg.toIndex && arg.toIndex < currentIndex) ? true : false;
// Download change sets
const changesets = await IModelHost.hubAccess.downloadChangesets({
accessToken: arg.accessToken,
iModelId: db.iModelId,
range: { first: reverse ? arg.toIndex! + 1 : currentIndex + 1, end: reverse ? currentIndex : arg.toIndex }, // eslint-disable-line @typescript-eslint/no-non-null-assertion
targetDir: BriefcaseManager.getChangeSetsPath(db.iModelId),
});
if (changesets.length === 0)
return; // nothing to apply
if (reverse)
changesets.reverse();
for (const changeset of changesets)
await this.applySingleChangeset(db, changeset);
// notify listeners
db.notifyChangesetApplied();
}
/** create a changeset from the current changes, and push it to iModelHub */
private static async pushChanges(db: BriefcaseDb, arg: PushChangesArgs): Promise<void> {
const changesetProps = db.nativeDb.startCreateChangeset();
changesetProps.briefcaseId = db.briefcaseId;
changesetProps.description = arg.description;
changesetProps.size = IModelJsFs.lstatSync(changesetProps.pathname)?.size;
if (!changesetProps.size) // either undefined or 0 means error
throw new IModelError(IModelStatus.NoContent, "error creating changeset");
let retryCount = arg.pushRetryCount ?? 3;
while (true) {
try {
const accessToken = await IModelHost.getAccessToken();
const index = await IModelHost.hubAccess.pushChangeset({ accessToken, iModelId: db.iModelId, changesetProps });
db.nativeDb.completeCreateChangeset({ index });
db.changeset = db.nativeDb.getCurrentChangeset();
if (!arg.retainLocks)
await db.locks.releaseAllLocks();
return;
} catch (err: any) {
const shouldRetry = () => {
if (retryCount-- <= 0)
return false;
switch (err.errorNumber) {
case IModelHubStatus.AnotherUserPushing:
case IModelHubStatus.DatabaseTemporarilyLocked:
case IModelHubStatus.OperationFailed:
return true;
}
return false;
};
if (!shouldRetry()) {
db.nativeDb.abandonCreateChangeset();
throw err;
}
} finally {
IModelJsFs.removeSync(changesetProps.pathname);
}
}
}
/** Pull/merge (if necessary), then push all local changes as a changeset. Called by [[BriefcaseDb.pushChanges]]
* @internal
*/
public static async pullMergePush(db: BriefcaseDb, arg: PushChangesArgs): Promise<void> {
let retryCount = arg.mergeRetryCount ?? 5;
while (true) {
try {
await BriefcaseManager.pullAndApplyChangesets(db, arg);
return await BriefcaseManager.pushChanges(db, arg);
} catch (err: any) {
if (retryCount-- <= 0 || err.errorNumber !== IModelHubStatus.PullIsRequired)
throw (err);
await (arg.mergeRetryDelay ?? BeDuration.fromSeconds(3)).wait();
}
}
}
/** @internal */
public static logUsage(imodel: IModelDb, activity?: RpcActivity) {
const telemetryEvent = new TelemetryEvent(
"core-backend - Open iModel",
"7a6424d1-2114-4e89-b13b-43670a38ccd4", // Feature: "iModel Use"
imodel.iTwinId,
imodel.iModelId,
imodel.changeset?.id,
);
activity = activity ?? {
activityId: "",
applicationId: IModelHost.applicationId,
applicationVersion: IModelHost.applicationVersion,
sessionId: IModelHost.sessionId,
accessToken: "", // IModelHost.getAccessToken(); ACCESS_TOKEN_NEEDS_WORK
};
IModelHost.telemetry.postTelemetry(activity, telemetryEvent); // eslint-disable-line @typescript-eslint/no-floating-promises
}
} | the_stack |
namespace MakerJs.exporter {
/**
* @private
*/
interface IChainLinkFunction {
(pathValue: IPath, link: IChainLink): void;
}
/**
* @private
*/
interface IChainLinkFunctionMap {
[type: string]: IChainLinkFunction;
}
/**
* @private
*/
function wrap(prefix: string, content: string, condition: any): string {
if (condition) {
return prefix + '(' + content + ')';
} else {
return content;
}
}
/**
* @private
*/
function facetSizeToResolution(arcOrCircle: IPathCircle, facetSize: number): number {
if (!facetSize) return;
var circle = new paths.Circle([0, 0], arcOrCircle.radius);
var length = measure.pathLength(circle);
if (!length) return;
return Math.ceil(length / facetSize);
}
/**
* @private
*/
function chainToJscadScript(chainContext: IChain, facetSize?: number, accuracy?: number): string {
var head = '';
var tail = '';
var first = true;
var exit = false;
var reverseTail = false;
var beginMap: IChainLinkFunctionMap = {};
beginMap[pathType.Circle] = function (circle: IPathCircle, link: IChainLink) {
var circleOptions: jscad.CSG.ICircleOptions = {
center: <number[]>point.rounded(point.add(circle.origin, link.walkedPath.offset), accuracy),
radius: round(circle.radius, accuracy),
resolution: facetSizeToResolution(circle, facetSize)
};
head = wrap('CAG.circle', JSON.stringify(circleOptions), true);
exit = true;
};
beginMap[pathType.Line] = function (line: IPathLine, link: IChainLink) {
let points = link.endPoints.map(p => point.rounded(p, accuracy));
if (link.reversed) {
points.reverse();
}
head = wrap('new CSG.Path2D',
JSON.stringify(points), true);
};
beginMap[pathType.Arc] = function (arc: IPathArc, link: IChainLink) {
var endAngle = angle.ofArcEnd(arc);
if (link.reversed) {
reverseTail = true;
}
var arcOptions: jscad.CSG.IArcOptions = {
center: <number[]>point.rounded(point.add(arc.origin, link.walkedPath.offset), accuracy),
radius: round(arc.radius, accuracy),
startangle: round(arc.startAngle, accuracy),
endangle: round(endAngle, accuracy),
resolution: facetSizeToResolution(arc, facetSize)
};
head = wrap('new CSG.Path2D.arc', JSON.stringify(arcOptions), true);
};
var appendMap: IChainLinkFunctionMap = {};
appendMap[pathType.Line] = function (line: IPathLine, link: IChainLink) {
var reverse = (reverseTail != link.reversed);
var endPoint = point.rounded(link.endPoints[reverse ? 0 : 1], accuracy);
append(wrap('.appendPoint', JSON.stringify(endPoint), true));
};
appendMap[pathType.Arc] = function (arc: IPathArc, link: IChainLink) {
var reverse = (reverseTail != link.reversed);
var endAngle = angle.ofArcEnd(arc);
var arcOptions: jscad.CSG.IEllpiticalArcOptions = {
radius: round(arc.radius, accuracy),
clockwise: reverse,
large: Math.abs(endAngle - arc.startAngle) > 180,
resolution: facetSizeToResolution(arc, facetSize)
};
var endPoint = point.rounded(link.endPoints[reverse ? 0 : 1], accuracy);
append(wrap('.appendArc', JSON.stringify(endPoint) + ',' + JSON.stringify(arcOptions), true));
}
function append(s: string) {
if (reverseTail) {
tail = s + tail;
} else {
tail += s;
}
}
for (let i = 0; i < chainContext.links.length; i++) {
let link = chainContext.links[i];
var pathContext = link.walkedPath.pathContext;
var fn = first ? beginMap[pathContext.type] : appendMap[pathContext.type];
if (fn) {
fn(pathContext, link);
}
if (exit) {
return head;
}
first = false;
}
return head + tail + '.close().innerToCAG()';
}
/**
* @private
*/
interface IAdd<T> {
cag: T;
subtracts: T[][];
}
/**
* @private
*/
interface IOperate<T> {
(a: T, b: T): T
}
/**
* @private
*/
function makePhasedCallback(originalCb: IStatusCallback, phaseStart: number, phaseSpan: number) {
return function statusCallback(status) {
originalCb && originalCb({ progress: phaseStart + status.progress * phaseSpan / 100 });
}
}
/**
* Converts a model to a @jscad/csg CAG object - 2D to 2D. See https://en.wikibooks.org/wiki/OpenJSCAD_User_Guide#2D_Paths
*
* Example:
* ```
* //First, use npm install @jscad/csg from the command line in your jscad project
* //Create a CAG instance from a model.
* var { CAG } = require('@jscad/csg');
* var model = new makerjs.models.Ellipse(70, 40);
* var cag = makerjs.exporter.toJscadCAG(CAG, model, {maxArcFacet: 1});
* ```
*
* @param jscadCAG @jscad/csg CAG engine, see https://www.npmjs.com/package/@jscad/csg
* @param modelToExport Model object to export.
* @param options Optional options object.
* @param options.byLayers Optional flag to separate chains by layers.
* @param options.pointMatchingDistance Optional max distance to consider two points as the same.
* @param options.maxArcFacet The maximum length between points on an arc or circle.
* @param options.statusCallback Optional callback function to get the percentage complete.
* @returns jscad CAG object in 2D, or a map (keyed by layer id) of jscad CAG objects - if options.byLayers is true.
*/
export function toJscadCAG(jscadCAG: typeof jscad.CAG, modelToExport: IModel, jsCadCagOptions?: IJscadCagOptions): jscad.CAG | { [layerId: string]: jscad.CAG } {
function chainToJscadCag(c: IChain, maxArcFacet: number) {
const keyPoints = chain.toKeyPoints(c, maxArcFacet);
keyPoints.push(keyPoints[0]);
return jscadCAG.fromPoints(keyPoints);
}
function jscadCagUnion(augend: jscad.CAG, addend: jscad.CAG) {
return augend.union(addend);
}
function jscadCagSubtraction(minuend: jscad.CAG, subtrahend: jscad.CAG) {
return minuend.subtract(subtrahend);
}
return convertChainsTo2D<jscad.CAG>(chainToJscadCag, jscadCagUnion, jscadCagSubtraction, modelToExport, jsCadCagOptions);
}
/**
* @private
*/
function convertChainsTo2D<T>(convertToT: { (c: IChain, maxArcFacet: number): T }, union: IOperate<T>, subtraction: IOperate<T>, modelToExport: IModel, jsCadCagOptions: IJscadCagOptions = {}) {
const adds: { [layerId: string]: IAdd<T>[] } = {};
const status = { total: 0, complete: 0 };
function unionize(phaseStart: number, phaseSpan: number, arr: T[]) {
let result = arr.shift();
arr.forEach(el => result = union(result, el));
status.complete++;
jsCadCagOptions.statusCallback && jsCadCagOptions.statusCallback({ progress: phaseStart + phaseSpan * status.complete / status.total });
return result;
}
function subtractChains(layerId: string, cs: IChain[]) {
const subtracts: T[] = [];
cs.forEach(c => {
if (!c.endless) return;
if (c.contains) {
addChains(layerId, c.contains);
}
status.total++;
subtracts.unshift(convertToT(c, jsCadCagOptions.maxArcFacet));
});
return subtracts;
}
function addChains(layerId: string, cs: IChain[]) {
cs.forEach(c => {
if (!c.endless) return;
const add: IAdd<T> = { cag: convertToT(c, jsCadCagOptions.maxArcFacet), subtracts: [] };
if (c.contains) {
const subtracts = subtractChains(layerId, c.contains);
if (subtracts.length > 0) {
add.subtracts.push(subtracts);
}
}
status.total++;
if (!(layerId in adds)) {
adds[layerId] = [];
}
adds[layerId].unshift(add);
});
}
const options: IFindChainsOptions = {
pointMatchingDistance: jsCadCagOptions.pointMatchingDistance,
byLayers: jsCadCagOptions.byLayers,
contain: true
};
jsCadCagOptions.statusCallback && jsCadCagOptions.statusCallback({ progress: 25 });
const chainsResult = model.findChains(modelToExport, options);
if (Array.isArray(chainsResult)) {
addChains('', chainsResult);
} else {
for (let layerId in chainsResult) {
addChains(layerId, chainsResult[layerId]);
}
}
jsCadCagOptions.statusCallback && jsCadCagOptions.statusCallback({ progress: 50 });
let closedCount = 0;
for (let layerId in adds) {
closedCount += adds[layerId].length;
}
if (closedCount === 0) {
jsCadCagOptions.statusCallback && jsCadCagOptions.statusCallback({ progress: 100 });
throw ('No closed geometries found.');
}
const resultMap: { [layerId: string]: T } = {};
for (let layerId in adds) {
const flatAdds = adds[layerId].map(add => {
let result = add.cag;
add.subtracts.forEach(subtract => {
const union = unionize(50, 50, subtract);
result = subtraction(result, union);
})
return result;
});
resultMap[layerId] = unionize(50, 50, flatAdds);
}
jsCadCagOptions.statusCallback && jsCadCagOptions.statusCallback({ progress: 100 });
return options.byLayers ? resultMap : resultMap[''];
}
/**
* Converts a model to a @jscad/csg CSG object - 2D to 3D.
*
* Example:
* ```
* //First, use npm install @jscad/csg from the command line in your jscad project
* //Create a CSG instance from a model.
* var { CAG } = require('@jscad/csg');
* var model = new makerjs.models.Ellipse(70, 40);
* var csg = makerjs.exporter.toJscadCSG(CAG, model, {maxArcFacet: 1, extrude: 10});
* ```
*
* @param jscadCAG @jscad/csg CAG engine, see https://www.npmjs.com/package/@jscad/csg
* @param modelToExport Model object to export.
* @param options Optional options object.
* @param options.byLayers Optional flag to separate chains by layers.
* @param options.pointMatchingDistance Optional max distance to consider two points as the same.
* @param options.maxArcFacet The maximum length between points on an arc or circle.
* @param options.statusCallback Optional callback function to get the percentage complete.
* @param options.extrude Optional default extrusion distance.
* @param options.layerOptions Optional object map of options per layer, keyed by layer name. Each value for a key is an object with 'extrude' and 'z' properties.
* @returns jscad CAG object in 2D, or a map (keyed by layer id) of jscad CAG objects - if options.byLayers is true.
*/
export function toJscadCSG(jscadCAG: typeof jscad.CAG, modelToExport: IModel, options?: IJscadCsgOptions): jscad.CSG {
function to2D(opts: IJscadCsgOptions) {
return toJscadCAG(jscadCAG, modelToExport, opts);
}
function to3D(cag: jscad.CAG, extrude: number, z: number) {
var csg = cag.extrude({ offset: [0, 0, extrude] });
if (z) {
csg = csg.translate([0, 0, z]);
}
return csg;
}
function union3D(augend: jscad.CSG, addend: jscad.CSG) {
return augend.union(addend);
}
return convert2Dto3D<jscad.CAG, jscad.CSG>(to2D, to3D, union3D, modelToExport, options);
}
/**
* @private
*/
function convert2Dto3D<T2D, T3D>(
to2D: { (options: IJscadCsgOptions): T2D | { [layerId: string]: T2D } },
to3D: { (result2D: T2D, extrude: number, z: number): T3D },
union3D: { (a: T3D, b: T3D): T3D },
modelToExport: IModel, options: IJscadCsgOptions = {}) {
const originalCb = options.statusCallback;
function getDefinedNumber(a: number, b: number) {
if (isNumber(a)) return a;
return b;
}
if (modelToExport.exporterOptions) {
extendObject(options, modelToExport.exporterOptions['toJscadCSG']);
}
options.byLayers = options.byLayers || (options.layerOptions && true);
options.statusCallback = makePhasedCallback(originalCb, 0, 50);
const result2D = to2D(options);
const csgs: T3D[] = [];
if (options.byLayers) {
for (let layerId in result2D as { [layerId: string]: T2D }) {
let layerOptions = options.layerOptions[layerId];
let csg = to3D(result2D[layerId], layerOptions.extrude || options.extrude, getDefinedNumber(layerOptions.z, options.z));
csgs.push(csg);
}
} else {
let csg = to3D(result2D as T2D, options.extrude, options.z);
csgs.push(csg);
}
options.statusCallback = makePhasedCallback(originalCb, 50, 100);
const status = { total: csgs.length - 1, complete: 0 };
let result = csgs.shift();
csgs.forEach((el, i) => {
result = union3D(result, el);
status.complete++;
options.statusCallback({ progress: status.complete / status.total });
});
return result;
}
/**
* Creates a string of JavaScript code for execution with a Jscad environment.
*
* @param modelToExport Model object to export.
* @param options Export options object.
* @param options.byLayers Optional flag to separate chains by layers.
* @param options.pointMatchingDistance Optional max distance to consider two points as the same.
* @param options.maxArcFacet The maximum length between points on an arc or circle.
* @param options.statusCallback Optional callback function to get the percentage complete.
* @param options.extrude Optional default extrusion distance.
* @param options.layerOptions Optional object map of options per layer, keyed by layer name. Each value for a key is an object with 'extrude' and 'z' properties.
* @returns String of JavaScript containing a main() function for Jscad.
*/
export function toJscadScript(modelToExport: IModel, options: IJscadScriptOptions = {}) {
function _chainToJscadScript(c: IChain, maxArcFacet: number) {
return wrap(chainToJscadScript(c, maxArcFacet, options.accuracy));
}
function scriptUnion(augend: string, addend: string) {
return augend + `.union(${addend})`;
}
function scriptSubtraction(minuend: string, subtrahend: string) {
return minuend + `.subtract(${subtrahend})`;
}
function to2D(opts: IJscadCsgOptions) {
return convertChainsTo2D<string>(_chainToJscadScript, scriptUnion, scriptSubtraction, modelToExport, options);
}
function to3D(cag: string, extrude: number, z: number) {
var csg = cag + `.extrude({ offset: [0, 0, ${extrude}] })`;
if (z) {
csg = csg + `.translate([0, 0, ${z}])`;
}
return csg;
}
function wrap(s: string) {
return `${nl}${indent}${s}${nl}`;
}
const indent = new Array((options.indent || 0) + 1).join(' ');
const nl = options.indent ? '\n' : '';
const result = convert2Dto3D<string, string>(to2D, to3D, scriptUnion, modelToExport, options).trim();
return `function ${options.functionName || 'main'}(){${wrap(`return ${result};`)}}${nl}`;
}
/**
* Exports a model in STL format - 2D to 3D.
*
* @param jscadCAG @jscad/csg CAG engine, see https://www.npmjs.com/package/@jscad/csg
* @param stlSerializer @jscad/stl-serializer, see https://www.npmjs.com/package/@jscad/stl-serializer
* @param modelToExport Model object to export.
* @param options Optional options object.
* @param options.byLayers Optional flag to separate chains by layers.
* @param options.pointMatchingDistance Optional max distance to consider two points as the same.
* @param options.maxArcFacet The maximum length between points on an arc or circle.
* @param options.statusCallback Optional callback function to get the percentage complete.
* @param options.extrude Optional default extrusion distance.
* @param options.layerOptions Optional object map of options per layer, keyed by layer name. Each value for a key is an object with 'extrude' and 'z' properties.
* @returns String in STL ASCII format.
*/
export function toJscadSTL(CAG: typeof jscad.CAG, stlSerializer: jscad.StlSerializer, modelToExport: IModel, options?: IJscadCsgOptions) {
const originalCb = options.statusCallback;
options.statusCallback = makePhasedCallback(originalCb, 0, 50);
const csg = toJscadCSG(CAG, modelToExport, options);
return stlSerializer.serialize(csg, { binary: false, statusCallback: makePhasedCallback(originalCb, 50, 50) });
}
/**
* OpenJsCad export options.
*/
export interface IOpenJsCadOptions extends IFindLoopsOptions, IExportOptions {
/**
* Optional depth of 3D extrusion.
*/
extrusion?: number;
/**
* Optional size of curve facets.
*/
facetSize?: number;
/**
* Optional override of function name, default is "main".
*/
functionName?: string;
/**
* Optional options applied to specific first-child models by model id.
*/
modelMap?: IOpenJsCadOptionsMap;
}
/**
* Map of OpenJsCad export options.
*/
export interface IOpenJsCadOptionsMap {
[modelId: string]: IOpenJsCadOptions;
}
/**
* Jscad CAG export options.
*/
export interface IJscadCagOptions extends IExportOptions, IPointMatchOptions {
/**
* Flag to separate chains by layers.
*/
byLayers?: boolean;
/**
* The maximum length between points on an arc or circle.
*/
maxArcFacet?: number;
/**
* Optional callback to get status during the export.
*/
statusCallback?: IStatusCallback;
}
/**
* Jscad CAG extrusion options.
*/
export interface IJscadExtrudeOptions {
/**
* Optional depth of 3D extrusion.
*/
extrude?: number;
/**
* Optional depth of 3D extrusion.
*/
z?: number;
}
/**
* Jscad CSG export options.
*/
export interface IJscadCsgOptions extends IJscadCagOptions, IJscadExtrudeOptions {
/**
* SVG options per layer.
*/
layerOptions?: { [layerId: string]: IJscadExtrudeOptions };
}
/**
* Jscad Script export options.
*/
export interface IJscadScriptOptions extends IJscadCsgOptions {
/**
* Optional override of function name, default is "main".
*/
functionName?: string;
/**
* Optional number of spaces to indent.
*/
indent?: number;
}
} | the_stack |
import {ethers} from 'hardhat';
import {setupTestGiveaway} from './fixtures';
import {constants} from 'ethers';
import {waitFor, expectReceiptEventWithArgs} from '../utils';
import {expect} from '../chai-setup';
import helpers from '../../lib/merkleTreeHelper';
const {calculateClaimableAssetHash} = helpers;
const zeroAddress = constants.AddressZero;
// eslint-disable-next-line mocha/no-skipped-tests
describe('Asset_Giveaway', function () {
it('User cannot claim when test contract holds zero assets', async function () {
const options = {
assetsHolder: true,
};
const setUp = await setupTestGiveaway(options);
const {giveawayContract, others, tree, assets} = setUp;
const asset = assets[0];
const proof = tree.getProof(calculateClaimableAssetHash(asset));
const giveawayContractAsUser = giveawayContract.connect(
ethers.provider.getSigner(others[0])
);
await expect(
giveawayContractAsUser.claimAssets(
others[0],
asset.assetIds,
asset.assetValues,
proof,
asset.salt
)
).to.be.revertedWith(`can't substract more than there is`);
});
it('User can claim allocated multiple assets for multiple assetIds from Giveaway contract', async function () {
const options = {
mint: true,
};
const setUp = await setupTestGiveaway(options);
const {giveawayContract, others, tree, assets, assetContract} = setUp;
const asset = assets[0];
const proof = tree.getProof(calculateClaimableAssetHash(asset));
const giveawayContractAsUser = await giveawayContract.connect(
ethers.provider.getSigner(others[0])
);
const initBalanceAssetId1 = await assetContract[
'balanceOf(address,uint256)'
](giveawayContract.address, asset.assetIds[0]);
expect(initBalanceAssetId1).to.equal(asset.assetValues[0]);
const initBalanceAssetId2 = await assetContract[
'balanceOf(address,uint256)'
](giveawayContract.address, asset.assetIds[1]);
expect(initBalanceAssetId2).to.equal(asset.assetValues[1]);
const initBalanceAssetId3 = await assetContract[
'balanceOf(address,uint256)'
](giveawayContract.address, asset.assetIds[2]);
expect(initBalanceAssetId3).to.equal(asset.assetValues[2]);
await waitFor(
giveawayContractAsUser.claimAssets(
others[0],
asset.assetIds,
asset.assetValues,
proof,
asset.salt
)
);
const balanceAssetId1 = await assetContract['balanceOf(address,uint256)'](
others[0],
asset.assetIds[0]
);
expect(balanceAssetId1).to.equal(asset.assetValues[0]);
const balanceAssetId2 = await assetContract['balanceOf(address,uint256)'](
others[0],
asset.assetIds[1]
);
expect(balanceAssetId2).to.equal(asset.assetValues[1]);
const balanceAssetId3 = await assetContract['balanceOf(address,uint256)'](
others[0],
asset.assetIds[2]
);
expect(balanceAssetId3).to.equal(asset.assetValues[2]);
});
it('Claimed Event is emitted for successful claim', async function () {
const options = {
mint: true,
};
const setUp = await setupTestGiveaway(options);
const {giveawayContract, others, tree, assets} = setUp;
const asset = assets[0];
const proof = tree.getProof(calculateClaimableAssetHash(asset));
const giveawayContractAsUser = await giveawayContract.connect(
ethers.provider.getSigner(others[0])
);
const receipt = await waitFor(
giveawayContractAsUser.claimAssets(
others[0],
asset.assetIds,
asset.assetValues,
proof,
asset.salt
)
);
const claimedEvent = await expectReceiptEventWithArgs(
receipt,
'ClaimedAssets'
);
expect(claimedEvent.args[0]).to.equal(others[0]); // to
expect(claimedEvent.args[1][0]).to.equal(asset.assetIds[0]);
expect(claimedEvent.args[1][1]).to.equal(asset.assetIds[1]);
expect(claimedEvent.args[1][2]).to.equal(asset.assetIds[2]);
expect(claimedEvent.args[2][0]).to.equal(asset.assetValues[0]);
expect(claimedEvent.args[2][1]).to.equal(asset.assetValues[1]);
expect(claimedEvent.args[2][2]).to.equal(asset.assetValues[2]);
});
it('User can claim allocated single asset for single assetId from Giveaway contract', async function () {
const options = {
mint: true,
};
const setUp = await setupTestGiveaway(options);
const {giveawayContract, others, tree, assets} = setUp;
const asset = assets[1];
const proof = tree.getProof(calculateClaimableAssetHash(asset));
const giveawayContractAsUser = await giveawayContract.connect(
ethers.provider.getSigner(others[0])
);
await waitFor(
giveawayContractAsUser.claimAssets(
others[0],
asset.assetIds,
asset.assetValues,
proof,
asset.salt
)
);
});
it('User tries to claim the wrong amount of an assetID', async function () {
const options = {
mint: true,
};
const setUp = await setupTestGiveaway(options);
const {giveawayContract, others, tree, assets} = setUp;
const asset = assets[1];
const proof = tree.getProof(calculateClaimableAssetHash(asset));
const giveawayContractAsUser = await giveawayContract.connect(
ethers.provider.getSigner(others[0])
);
await expect(
giveawayContractAsUser.claimAssets(
others[0],
asset.assetIds,
[0], // bad param
proof,
asset.salt
)
).to.be.revertedWith('INVALID_CLAIM');
});
it('User cannot claim their assets more than once', async function () {
const options = {
mint: true,
};
const setUp = await setupTestGiveaway(options);
const {giveawayContract, others, tree, assets} = setUp;
const asset = assets[0];
const proof = tree.getProof(calculateClaimableAssetHash(asset));
const giveawayContractAsUser = await giveawayContract.connect(
ethers.provider.getSigner(others[0])
);
await waitFor(
giveawayContractAsUser.claimAssets(
others[0],
asset.assetIds,
asset.assetValues,
proof,
asset.salt
)
);
await expect(
giveawayContractAsUser.claimAssets(
others[0],
asset.assetIds,
asset.assetValues,
proof,
asset.salt
)
).to.be.revertedWith('DESTINATION_ALREADY_CLAIMED');
});
it('User cannot claim assets from Giveaway contract if destination is not the reserved address', async function () {
const options = {
mint: true,
};
const setUp = await setupTestGiveaway(options);
const {giveawayContract, others, tree, assets} = setUp;
const asset = assets[0];
const proof = tree.getProof(calculateClaimableAssetHash(asset));
const giveawayContractAsUser = await giveawayContract.connect(
ethers.provider.getSigner(others[0])
);
await expect(
giveawayContractAsUser.claimAssets(
others[1], // bad param
asset.assetIds,
asset.assetValues,
proof,
asset.salt
)
).to.be.revertedWith('INVALID_CLAIM');
});
it('User cannot claim assets from Giveaway contract to destination zeroAddress', async function () {
const options = {
mint: true,
};
const setUp = await setupTestGiveaway(options);
const {giveawayContract, others, tree, assets} = setUp;
const asset = assets[0];
const proof = tree.getProof(calculateClaimableAssetHash(asset));
const giveawayContractAsUser = await giveawayContract.connect(
ethers.provider.getSigner(others[0])
);
await expect(
giveawayContractAsUser.claimAssets(
zeroAddress,
asset.assetIds,
asset.assetValues,
proof,
asset.salt
)
).to.be.revertedWith('INVALID_TO_ZERO_ADDRESS');
});
it('User cannot claim assets from Giveaway contract with incorrect asset param', async function () {
const options = {
mint: true,
};
const setUp = await setupTestGiveaway(options);
const {giveawayContract, others, tree, assets} = setUp;
const asset = assets[0];
const proof = tree.getProof(calculateClaimableAssetHash(asset));
const giveawayContractAsUser = await giveawayContract.connect(
ethers.provider.getSigner(others[0])
);
await expect(
giveawayContractAsUser.claimAssets(
others[0],
asset.assetIds,
[5, 5], // length too short
proof,
asset.salt
)
).to.be.revertedWith('INVALID_INPUT');
});
it('User can claim allocated multiple assets for multiple assetIds from alternate address', async function () {
const options = {
mint: true,
assetsHolder: true, // others[5]
};
const setUp = await setupTestGiveaway(options);
const {giveawayContract, others, tree, assets, assetContract} = setUp;
const asset = assets[0];
const proof = tree.getProof(calculateClaimableAssetHash(asset));
const giveawayContractAsUser = await giveawayContract.connect(
ethers.provider.getSigner(others[0])
);
const initBalanceAssetId1 = await assetContract[
'balanceOf(address,uint256)'
](others[5], asset.assetIds[0]);
expect(initBalanceAssetId1).to.equal(asset.assetValues[0]);
const initBalanceAssetId2 = await assetContract[
'balanceOf(address,uint256)'
](others[5], asset.assetIds[1]);
expect(initBalanceAssetId2).to.equal(asset.assetValues[1]);
const initBalanceAssetId3 = await assetContract[
'balanceOf(address,uint256)'
](others[5], asset.assetIds[2]);
expect(initBalanceAssetId3).to.equal(asset.assetValues[2]);
await waitFor(
giveawayContractAsUser.claimAssets(
others[0],
asset.assetIds,
asset.assetValues,
proof,
asset.salt
)
);
const balanceAssetId1 = await assetContract['balanceOf(address,uint256)'](
others[0],
asset.assetIds[0]
);
expect(balanceAssetId1).to.equal(asset.assetValues[0]);
const balanceAssetId2 = await assetContract['balanceOf(address,uint256)'](
others[0],
asset.assetIds[1]
);
expect(balanceAssetId2).to.equal(asset.assetValues[1]);
const balanceAssetId3 = await assetContract['balanceOf(address,uint256)'](
others[0],
asset.assetIds[2]
);
expect(balanceAssetId3).to.equal(asset.assetValues[2]);
});
it('merkleRoot cannot be set twice', async function () {
const options = {};
const setUp = await setupTestGiveaway(options);
const {giveawayContract, nftGiveawayAdmin} = setUp;
const giveawayContractAsAdmin = await giveawayContract.connect(
ethers.provider.getSigner(nftGiveawayAdmin)
);
await expect(
giveawayContractAsAdmin.setMerkleRoot(
'0x0000000000000000000000000000000000000000000000000000000000000000'
)
).to.be.revertedWith('MERKLE_ROOT_ALREADY_SET');
});
it('merkleRoot can only be set by admin', async function () {
const options = {};
const setUp = await setupTestGiveaway(options);
const {giveawayContract, others} = setUp;
const giveawayContractAsUser = await giveawayContract.connect(
ethers.provider.getSigner(others[8])
);
await expect(
giveawayContractAsUser.setMerkleRoot(
'0x0000000000000000000000000000000000000000000000000000000000000000'
)
).to.be.revertedWith('ADMIN_ONLY');
});
// NOT USED BECAUSE NO EXPIRY
// it('User cannot claim assets after the expiryTime', async function () {
// const options = {};
// const setUp = await setupTestGiveaway(options);
// const {giveawayContract, others, tree, assets} = setUp;
// const asset = assets[0];
// const proof = tree.getProof(calculateClaimableAssetHash(asset));
// const giveawayContractAsUser = await giveawayContract.connect(
// ethers.provider.getSigner(others[0])
// );
// await increaseTime(60 * 60 * 24 * 30 * 4);
// await expect(
// giveawayContractAsUser.claimAssets(
// others[0],
// asset.assetIds,
// asset.assetValues,
// proof,
// asset.salt
// )
// ).to.be.revertedWith('CLAIM_PERIOD_IS_OVER');
// });
}); | the_stack |
import { Component, OnInit, NgModule } from "@angular/core";
import { Router } from "@angular/router";
import { IdprestapiService } from "../idprestapi.service";
import { IdpService } from "../idp-service.service";
import { IdpdataService } from "../idpdata.service";
import {BrowserAnimationsModule} from "@angular/platform-browser/animations";
import {ReactiveFormsModule} from "@angular/forms";
import { HttpModule, Http } from "@angular/http";
import { BrowserModule } from "@angular/platform-browser";
import { FormsModule } from "@angular/forms";
import { DateTimePickerModule } from "ng-pick-datetime";
import { CookieService } from "ngx-cookie";
@NgModule({
imports: [
BrowserModule,
BrowserAnimationsModule,
HttpModule,
ReactiveFormsModule,
FormsModule,
DateTimePickerModule
]
})
@Component({
selector: "app-manage-environment",
templateUrl: "./manage-environment.component.html",
styleUrls: ["./manage-environment.component.css"]
})
export class ManageEnvironmentComponent implements OnInit {
pipelineNames: any;
appNames: any;
intervalOptions: any = ["Day", "Week", "Month"];
weeklyOptions: any = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
dateOptions: any = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17",
"18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"];
envPlannigData: any;
envData: any = [];
temp: any;
envSlots: any = [];
timeZone: any;
slotsCardCollapseStatus:Array<any> = [];
public constructor(
private IdpdataService: IdpdataService,
private IdpService: IdpService,
private IdprestapiService: IdprestapiService,
private _cookieService: CookieService,
private router: Router
) {
this.envPlannigData = {
"applicationName": "",
"envNames": [],
"env": "",
"startTime": "",
"endTime": "",
"releaseNo": "",
"releaseNumbers": "",
"releaseNumber": "",
"type": "",
"week": [],
"date": [],
};
this.callforRest();
}
callforRest() {
this.IdprestapiService.getData()
.then(response => {
try {
if (response) {
this.IdpdataService.devServerURL = response.json().idpresturl;
this.IdpdataService.IDPDashboardURL = response.json().idpdashboardurl;
this.IdpdataService.IDPLink = response.json().IDPLink;
this.IdpdataService.geUrl = response.json().geUrl;
this.IdpdataService.geFlag = response.json().geFlag;
this.IdpdataService.serverUrl = response.json().tfsServerUrl;
this.IdpdataService.uName = response.json().uName;
this.IdpdataService.pass = response.json().pass;
console.log(this.IdpdataService.devServerURL);
if (this._cookieService.get("access_token")) {
console.log("details");
}
this.getApplicationName();
this.getTimeZone();
}
} catch (e) {
alert("failed to get properties details");
console.log(e);
}
});
}
ngOnInit() {
}
addJob() {
this.envData.push({"startTime": "", "endTime": "", "type": "", "week": [], "date": []});
}
/* To fetch environment */
getEnvSlots() {
this.IdprestapiService.getEnvSlots(this.envPlannigData.applicationName, this.envPlannigData.env).then(response => {
if (response) {
if (response.status === 200) {
this.envSlots = JSON.parse(response.json().resource).slot;
this.temp = this.envData.week;
} else if (response.text().status === "No previous slots") {
console.log("Application was not previously planned");
} else {
alert("failed to get the existing slots");
}
}
});
}
getTimeZone() {
this.IdprestapiService.getTimeZone().then(response => {
if (response) {
this.timeZone = JSON.parse(response.text()).status;
} else {
alert("could not get time zone");
}
});
}
getExistingSlots() {
this.IdprestapiService.getExistingSlot(this.envPlannigData.applicationName,
this.envPlannigData.releaseNumber, this.envPlannigData.env).then(response => {
if (response) {
if (response.status === 200) {
this.envData = JSON.parse(response.json().resource).slot;
this.temp = this.envData.week;
} else if (response.text().status === "No previous slots") {
console.log("Application was not previously planned");
} else {
alert("failed to get the existing slots");
}
}
});
}
deleteBuildInterval(i) {
const x = confirm("Are you sure you want to remove these details?");
if (x) {
this.envData.splice(i, 1);
}
}
/* Fetches Application Details */
getApplicationName() {
this.IdprestapiService.getApplicationNameForReleaseManager(this.IdpdataService.idpUserName)
.then(response => {
if (response) {
const appDetails = JSON.parse(response.json().resource);
console.log("appdetails" + JSON.stringify(appDetails));
this.appNames = appDetails.names;
}
});
const currentTime = new Date();
const hours = currentTime.getHours();
const minutes = currentTime.getMinutes();
}
/* Fetches Pipeline Details */
getpipelines() {
this.IdprestapiService.getPipelineEnv(this.envPlannigData.applicationName, this.envPlannigData.releaseNumber).then(response => {
if (response) {
if (response.status === 200) {
this.pipelineNames = JSON.parse(response.json().resource).envNames;
}
} else {
alert("Failed to get the Pipelines Affected");
}
});
}
updatePlan() {
const x = confirm("Are you sure you want to add this plan?");
if (x) {
console.log("whole object rinting" + this.envData);
if (this.envPlannigData.releaseNumber !== "") {
const send = {
"envData": this.envData,
};
console.log("printing send " + send);
this.IdprestapiService.updatePlan(this.envPlannigData.releaseNumber,
this.envPlannigData.applicationName, this.envPlannigData.env, send).then(response => {
console.log("logging response " + response.text());
if (response) {
console.log("logging json in update plan " + JSON.parse(response.json().resource));
if (response.status === 200) {
alert("Plan for the Environment added succesfully.");
this.envPlannigData.env = "";
this.envSlots = [];
this.envPlannigData.releaseNumber = "";
this.pipelineNames = "";
this.IdprestapiService.getUserName().then(response => {
if (response) {
const userDetails = JSON.parse(response.json().resource);
const username = userDetails.user_id;
const table = this.maketable();
const envOwner = {
"applicationName": this.envPlannigData.applicationName,
"envName": this.envPlannigData.env,
"mailBody": "Dear " + username +
"," + "<br> <br>Environment has been planned for <br> <br> Application Name: " +
this.envPlannigData.applicationName +
" <br> Release Number: " +
this.envPlannigData.releaseNumber +
" <br> Environment Name: " + this.envPlannigData.env +
"<br><br>" + table + "<br><br> Regards, <br> IDP Team",
"userName": username,
};
this.IdprestapiService.emailToEnvOwner(envOwner).then(response => {
if (response) {
if (response.status === 200) {
console.log("Email Sent Succesfully");
}
}
});
}
});
} else {
alert("Plan could not be added");
}
}
});
} else {
alert("Please feel the required fields");
}
}
}
maketable() {
if (this.envData.length !== 0) {
const style = "<html><head><style> table {font-family: arial," +
"sans-serif;border-collapse: collapse; width: 100%;}td, th {border: 1px solid #dddddd;text-align: left;padding: 8px;}" +
"tr:nth-child(even){background-color: grey;}</style></head>";
let table = style + "<table><tr><th>Slot Type</th><th>Start Time</th><th>End Time</th></tr>";
for (const i of this.envData) {
table = table + "<tr><td>" + i.type + "</td><td>" + i.startTime + "</td><td>" + i.endTime + "</td></tr>";
}
table = table + "</table>";
return table;
} else {
const table = " You can deploy in this environment 24*7.";
return table;
}
}
getReleaseNumber() {
this.IdprestapiService.getReleaseNumber(this.envPlannigData.applicationName).then(response => {
if (response) {
if (response.json().resource !== "No Release for this application") {
this.envPlannigData.releaseNumbers = JSON.parse(response.json().resource).releaseNumbers;
const temp = [];
for (const i of this.envPlannigData.releaseNumbers) {
if (temp.indexOf(i) === -1) {
temp.push(i);
}
}
this.envPlannigData.releaseNumbers = temp;
} else {
alert("No Active Release for this Application");
}
} else {
alert("No response for this application, something went wrong");
}
});
}
/* Fetches Environment names */
getEnvironmentNames() {
this.IdprestapiService.getEnvironmentNames(this.envPlannigData.applicationName).then(response => {
if (response) {
if (response.json().resource !== null) {
this.envPlannigData.envNames = JSON.parse(response.json().resource).envNames;
} else {
alert("There are no Environments to be planned for this application.");
}
} else {
alert("No response for this application, something went wrong");
}
});
}
} | the_stack |
import { expect } from "chai";
import {
parseOutput,
Result,
buildMessage,
parseErrorOutput,
Output,
TestCompleted,
parseResult,
} from "../result";
describe("result", () => {
describe("parse results", () => {
it("one line pass", () => {
const line =
'{"event":"testCompleted","status":"pass","labels":["suite","nested","test"],"failures":[],"duration":"13"}';
const output = parseOutput(line);
expectResult(output, (result) => {
expectEvent(result, (event) => {
expect(event.status.tag).to.eql("pass");
expect(event.labels).to.eql(["suite", "nested", "test"]);
expect(event.duration).to.eql(13);
});
});
});
it("one line todo", () => {
const line =
'{"event":"testCompleted","status":"todo","labels":["suite"],"failures":["todo comment"],"duration":"1"}';
const output = parseOutput(line);
expectResult(output, (result) => {
expectEvent(result, (event) => {
expect(event.labels).to.eql(["suite"]);
expect(event.duration).to.eql(1);
expect(event.status.tag).to.eql("todo");
if (event.status.tag === "todo") {
expect(event.status.comment).to.eql("todo comment");
}
});
});
});
it("a message", () => {
const line = "a message";
const output = parseOutput(line);
expect(output?.type).to.eq("message");
if (output?.type === "message") {
expect(output.line).to.eql(line);
}
});
it("broken json", () => {
const line = "{ broken";
const output = parseOutput(line);
expect(output?.type).to.eq("message");
if (output?.type === "message") {
expect(output.line).to.eql(line);
}
});
it("compile errors", () => {
const line = `
{
"type": "compile-errors",
"errors": [{
"path": "path/to/file.elm",
"name": "a name",
"problems": [{
"title": "THE ERROR",
"region": {
"start": {
"line": 17,
"column": 5
},
"end": {
"line": 17,
"column": 10
}
},
"message": [
"some text",
{ "string": "more text" }
]
}]
}]
}
`;
const output = parseErrorOutput(line);
const expected = {
type: "compile-errors",
errors: [
{
path: "path/to/file.elm",
name: "a name",
problems: [
{
title: "THE ERROR",
region: {
start: { line: 17, column: 5 },
end: { line: 17, column: 10 },
},
message: ["some text", { string: "more text" }],
},
],
},
],
};
expect(output).to.eql(expected);
});
});
describe("build message", () => {
it("empty", () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const raw: any = {
event: "tralala",
status: "pass",
labels: ["suite", "test"],
failures: [],
messages: [],
duration: "0",
};
expect(() => parseResult(raw)).to.throw("unknown event tralala");
});
it("with messages", () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const raw: any = {
event: "testCompleted",
status: "pass",
labels: ["suite", "test"],
failures: [],
messages: ["hello", "world"],
duration: "13",
};
const event: TestCompleted = {
tag: "testCompleted",
labels: ["suite", "test"],
messages: ["hello", "world"],
status: { tag: "pass" },
duration: 13,
};
const result: Result = {
type: "result",
event,
};
expect(parseResult(raw)).to.eql(result);
const message = buildMessage(event);
expect(message).to.eq("hello\nworld");
});
it("with failure with string reason", () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const raw: any = {
event: "testCompleted",
status: "fail",
labels: ["suite", "test"],
failures: [
{
message: "boom",
reason: {
data: "broken",
},
},
],
messages: [],
duration: "0",
};
const event: TestCompleted = {
tag: "testCompleted",
labels: ["suite", "test"],
messages: [],
duration: 0,
status: {
tag: "fail",
failures: [
{
tag: "message",
message: "broken",
},
],
},
};
const result: Result = {
type: "result",
event,
};
expect(parseResult(raw)).to.eql(result);
const message = buildMessage(event);
expect(message).to.eq("broken");
});
it("with failure without reason data", () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const raw: any = {
type: "result",
event: "testCompleted",
status: "fail",
labels: ["suite", "test"],
failures: [
{
message: "boom",
reason: {
data: undefined,
},
},
],
messages: [],
duration: "0",
};
const event: TestCompleted = {
tag: "testCompleted",
labels: ["suite", "test"],
messages: [],
duration: 0,
status: {
tag: "fail",
failures: [
{
tag: "message",
message: "boom",
},
],
},
};
const result: Result = {
type: "result",
event,
};
expect(parseResult(raw)).to.eql(result);
const message = buildMessage(event);
expect(message).to.eq("boom");
});
it("with failure with comparison data", () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const raw: any = {
event: "testCompleted",
status: "fail",
labels: ["suite", "test"],
failures: [
{
message: "boom",
reason: {
data: {
comparison: "compare",
actual: "actual",
expected: "expected",
},
},
},
],
messages: [],
duration: "0",
};
const event: TestCompleted = {
tag: "testCompleted",
labels: ["suite", "test"],
messages: [],
duration: 0,
status: {
tag: "fail",
failures: [
{
tag: "comparison",
comparison: "compare",
actual: "actual",
expected: "expected",
},
],
},
};
const result: Result = {
type: "result",
event,
};
expect(parseResult(raw)).to.eql(result);
const message = buildMessage(event);
expect(message).to.eq(["actual", "| compare", "expected"].join("\n"));
});
it("with failure with string literal in comparison data", () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const raw: any = {
event: "testCompleted",
status: "fail",
labels: ["suite", "test"],
failures: [
{
message: "boom",
reason: {
data: {
comparison: "compare",
actual: '"multi\\nline\\nactual"',
expected: '"quoted \\"expected\\""',
},
},
},
],
messages: [],
duration: "0",
};
const event: TestCompleted = {
tag: "testCompleted",
labels: ["suite", "test"],
messages: [],
duration: 0,
status: {
tag: "fail",
failures: [
{
tag: "comparison",
comparison: "compare",
actual: "multi\nline\nactual",
expected: 'quoted "expected"',
},
],
},
};
const result: Result = {
type: "result",
event,
};
expect(parseResult(raw)).to.eql(result);
const message = buildMessage(event);
expect(message).to.eq(
["multi", "line", "actual", "| compare", 'quoted "expected"'].join(
"\n",
),
);
});
it("with failure with other data", () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const raw: any = {
event: "testCompleted",
status: "fail",
labels: ["suite", "test"],
failures: [
{
message: "boom",
reason: {
data: {
key1: "value1",
key2: "value2",
},
},
},
],
messages: [],
duration: "0",
};
const event: TestCompleted = {
tag: "testCompleted",
labels: ["suite", "test"],
messages: [],
duration: 0,
status: {
tag: "fail",
failures: [
{
tag: "data",
data: {
key1: "value1",
key2: "value2",
},
},
],
},
};
const result: Result = {
type: "result",
event,
};
expect(parseResult(raw)).to.eql(result);
const message = buildMessage(event);
expect(message).to.eq(["key1: value1", "key2: value2"].join("\n"));
});
});
it("with message and failure with comparison data", () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const raw: any = {
event: "testCompleted",
status: "fail",
labels: ["suite", "test"],
failures: [
{
message: "boom",
reason: {
data: {
comparison: "compare",
actual: "actual",
expected: "expected",
},
},
},
],
messages: ["broken"],
duration: "0",
};
const event: TestCompleted = {
tag: "testCompleted",
labels: ["suite", "test"],
messages: ["broken"],
duration: 0,
status: {
tag: "fail",
failures: [
{
tag: "comparison",
comparison: "compare",
actual: "actual",
expected: "expected",
},
],
},
};
const result: Result = {
type: "result",
event,
};
expect(parseResult(raw)).to.eql(result);
const message = buildMessage(event);
expect(message).to.eq(
["broken", "actual", "| compare", "expected"].join("\n"),
);
});
});
function expectResult(output: Output, fun: (result: Result) => void) {
expect(output.type).to.eq("result");
if (output?.type === "result") {
fun(output);
}
}
function expectEvent(result: Result, fun: (event: TestCompleted) => void) {
expect(result.event.tag).to.eq("testCompleted");
if (result?.event.tag === "testCompleted") {
fun(result.event);
}
} | the_stack |
import * as React from "react";
import {Link} from "react-router-dom";
import {Helpers} from "../Helpers";
import {Component, FormEvent, ReactElement} from "react";
import {JobsonAPI} from "../JobsonAPI";
import {APIErrorMessage} from "../apitypes/APIErrorMessage";
import {APIJobDetails} from "../apitypes/APIJobDetails";
import {Subscription} from "rxjs/index";
import {APIJobDetailsCollection} from "../apitypes/APIJobDetailsCollection";
import {APITimestamp} from "../apitypes/APITimestamp";
export interface JobListComponentProps {
api: JobsonAPI;
routeProps: any;
}
export interface JobListComponentState {
isLoadingJobs: boolean,
jobLoadingError: null | APIErrorMessage,
activeQuery: string,
enteredQuery: string,
page: number,
jobs: APIJobDetails[],
}
export class JobListComponent extends Component<JobListComponentProps, JobListComponentState> {
private static getLatestStatus(timestamps: APITimestamp[]) {
return timestamps[timestamps.length - 1].status;
}
private static getWindowParams(routeProps: any): { [k: string]: any } {
const params = Helpers.extractParams(routeProps.location.search);
params.page = parseInt(params.page || "0");
params.query = params.query || "";
return params;
}
private static constructPath(page: number, query: string) {
const start = "jobs";
const rest = [];
if (page > 0) rest.push(`page=${page}`);
if (query.length > 0) rest.push(`query=${query}`);
return rest.length === 0 ?
start :
start + "?" + rest.join("&");
}
private static renderLoadingMessage(): ReactElement<any> {
return Helpers.renderLoadingMessage("jobs");
}
private static renderUserHasNoJobsMessage(): ReactElement<any> {
return (
<div className="ui info icon message">
<i className="info circle icon"/>
<div className="content">
<div className="header">
No jobs yet!
</div>
<p>
You don't seem to have any jobs yet
, <Link className="ui primary button" to="/submit">
Submit your first job
</Link>
</p>
</div>
</div>
);
}
private static renderNoResultsMessage(): ReactElement<any> {
return (
<div className="ui negative icon message">
<i className="warning icon"/>
<div className="content">
<div className="header">
Your search returned no results
</div>
</div>
</div>
);
}
private jobUpdatesSubscription: Subscription | null;
public constructor(props: JobListComponentProps, context: any) {
super(props, context);
const params = JobListComponent.getWindowParams(props.routeProps);
this.state = {
isLoadingJobs: true,
jobLoadingError: null,
activeQuery: params.query,
enteredQuery: params.query,
page: params.page,
jobs: [],
};
}
public componentWillMount(): void {
this.initializeJobUpdatesSubscription();
this.updateJobList();
}
private initializeJobUpdatesSubscription(): void {
this.jobUpdatesSubscription = this.props.api.onAllJobStatusChanges()
.subscribe(
() => this.updateJobList(),
() => {
}, // Swallow this for now - no feedback point in UI
() => {
});
}
private updateJobList(): void {
const stateUpdate = {
isLoadingJobs: true,
};
const afterStateUpdate = () => {
this.props.api.fetchJobSummaries(this.state.activeQuery, this.state.page)
.then(this.onJobSummariesLoaded.bind(this))
.catch(this.onJobSummariesLoadError.bind(this))
};
this.setState(stateUpdate, afterStateUpdate);
}
private onJobSummariesLoaded(page: APIJobDetailsCollection): void {
this.setState({
isLoadingJobs: false,
jobLoadingError: null,
jobs: page.entries,
});
}
private onJobSummariesLoadError(error: APIErrorMessage): void {
this.setState({
isLoadingJobs: false,
jobLoadingError: error,
});
}
public componentWillReceiveProps(newProps: JobListComponentProps): void {
const params = JobListComponent.getWindowParams(newProps.routeProps);
if (params.page != this.state.page ||
params.query != this.state.activeQuery) {
this.setState({
page: params.page,
activeQuery: params.query,
enteredQuery: params.query,
}, this.updateJobList.bind(this));
}
}
public componentWillUnmount(): void {
if (this.jobUpdatesSubscription !== null) {
this.jobUpdatesSubscription.unsubscribe();
}
}
private onSearchInputChange(e: FormEvent<HTMLInputElement>): void {
this.setState({
enteredQuery: e.currentTarget.value,
});
}
private onSearchKeyUp(e: KeyboardEvent): void {
if (e.key === "Enter" && this.state.enteredQuery !== this.state.activeQuery) {
this.pushHistory(0, this.state.enteredQuery);
}
}
private pushHistory(page: number, query: string): void {
this.props.routeProps.history.push(JobListComponent.constructPath(page, query));
}
private onClickedNextPage(): void {
this.pushHistory(this.state.page + 1, this.state.activeQuery);
}
private onClickedPreviousPage(): void {
this.pushHistory(this.state.page - 1, this.state.activeQuery);
}
private userHasNoJobs(): boolean {
return !this.state.isLoadingJobs &&
this.state.jobs.length === 0 &&
this.state.activeQuery.length === 0 &&
this.state.page === 0;
}
private isLoadingJobs(): boolean {
return this.state.isLoadingJobs;
}
private errorLoadingJobs(): boolean {
return this.state.jobLoadingError !== null;
}
public render(): ReactElement<any> {
return (
<div>
{this.renderSearchBar()}
{this.renderMainArea()}
</div>
);
}
private renderSearchBar(): ReactElement<any> {
return (
<div className={"ui fluid left icon input " + (this.isLoadingJobs() ? "loading" : "")}
style={{marginBottom: "2em"}}>
<i className="search icon"/>
<input type="text"
id="jobs-search"
placeholder="Search jobs..."
onChange={this.onSearchInputChange.bind(this)}
onKeyUp={this.onSearchKeyUp.bind(this)}
value={this.state.enteredQuery}
autoFocus
disabled={this.userHasNoJobs() || this.isLoadingJobs() || this.errorLoadingJobs()}/>
</div>
);
}
private renderMainArea(): ReactElement<any> {
if (this.state.isLoadingJobs) {
return JobListComponent.renderLoadingMessage();
} else if (this.state.jobLoadingError !== null) {
return this.renderLoadingErrorMessage();
} else if (this.userHasNoJobs()) {
return JobListComponent.renderUserHasNoJobsMessage();
} else if (this.state.jobs.length === 0) {
return JobListComponent.renderNoResultsMessage();
} else {
return this.renderJobSummaries();
}
}
private renderLoadingErrorMessage(): ReactElement<any> {
return Helpers.renderAPIErrorMessage(
"jobs",
this.state.jobLoadingError,
this.updateJobList.bind(this));
}
private renderJobSummaries(): ReactElement<any> {
const renderJobSummary = this.renderJobSummary.bind(this);
return (
<div>
<table id="job-list" className="ui very basic table">
<thead>
<tr>
<th className="center aligned">ID</th>
<th className="center aligned">Owner</th>
<th className="center aligned">Name</th>
<th className="center aligned">Status</th>
<th className="center aligned">Actions</th>
</tr>
</thead>
<tbody>
{this.state.jobs.map(renderJobSummary)}
</tbody>
</table>
<div style={{textAlign: "center"}}>
<button className="ui left attached button"
disabled={this.state.page === 0}
onClick={this.onClickedPreviousPage.bind(this)}>
Newer Jobs
</button>
<button className="ui right attached button"
onClick={this.onClickedNextPage.bind(this)}>
Older Jobs
</button>
</div>
</div>
);
}
private renderJobSummary(jobSummary: APIJobDetails, i: number): ReactElement<any> {
return (
<tr key={i}>
<td className="center aligned">
<Link to={"/jobs/" + jobSummary.id}>
<code>{jobSummary.id}</code>
</Link>
</td>
<td className="center aligned">
{jobSummary.owner}
</td>
<td className="center aligned">
{jobSummary.name}
</td>
<td className="center aligned">
{Helpers.renderStatusField(
JobListComponent.getLatestStatus(jobSummary.timestamps))}
</td>
<td className="center aligned">
{this.renderJobActions(jobSummary)}
</td>
</tr>
);
}
private renderJobActions(jobSummary: APIJobDetails): ReactElement<any>[] {
return Helpers.renderAllJobActions(this.props.api, this.props.routeProps, jobSummary.id, jobSummary._links);
}
} | the_stack |
import { closeSync, readFileSync, writeSync } from 'fs';
import { FileLoader, Vector2, Vector3 } from 'three';
import { writeDataToBuffer } from '../common/io';
import MutableTypedArray from '../common/MutableTypedArray';
import { dataSizeForType, getRuntimeParams } from '../common/utils';
import {
SparseMatrix,
Triplet,
DenseMatrix,
memoryManager,
} from '@penrose/linear-algebra';
import { saveOBJ } from '../common/ObjWriter';
const fileParams = getRuntimeParams();
const {
FILENAME,
OUTPUT_PATH,
} = fileParams;
const MESH_NUM = process.env.MESH_NUM ? parseInt(process.env.MESH_NUM) : 0;
const NUM_ITERS = process.env.NUM_ITERS ? parseInt(process.env.NUM_ITERS) : 200;
const STEP_SCALE = process.env.STEP_SCALE ? parseFloat(process.env.STEP_SCALE) : 0.2;
console.log(`Running unfolding animation on file ${FILENAME} Mesh ${MESH_NUM} for ${NUM_ITERS} iterations with step scale ${STEP_SCALE}.`);
// Parse OBJ.
// This script is expecting a specific flavor of OBJ that is generated by the make_obj script.
// Other imported OBJs may or may not work.
const obj = (readFileSync(`${OUTPUT_PATH}${FILENAME}_Mesh${MESH_NUM}.obj`, 'utf-8')).split('\n');
const vertices = new MutableTypedArray(new Float32Array(0), false, 3);
const faces = new MutableTypedArray(new Int32Array(0), false, 3);
const uvs = new MutableTypedArray(new Float32Array(0), false, 2);
for (let i = 0; i < obj.length; i++) {
const line = obj[i].split(' ');
const type = line.shift();
if (type === 'v') {
// Add vertex.
vertices.push(line.map(el => parseFloat(el)));
} else if (type === 'f') {
// Add face.
// Faces are 1 indexed.
faces.push(line.map(el => parseInt(el.split('/')[0]) - 1));
} else if (type === 'vt') {
// Add uv.
uvs.push(line.map(el => parseFloat(el)));
}
}
// Find all adjacent faces to each vertex, this is a regular mesh, so we know max num faces for each vertex is 6.
const vertexFaces = new MutableTypedArray(new Int32Array(30 * vertices.getLength()), true, 30);
vertexFaces.clear();
{
const tempArray1: number[] = [];
const tempArray2: number[] = [];
for (let i = 0; i < faces.getLength(); i++) {
const faceVertices = faces.get(i, tempArray1)!;
if (faceVertices === null) {
continue;
}
faceVertices.forEach(vertexIndex => {
const neighbors = vertexFaces.get(vertexIndex, tempArray2);
if (neighbors === null) {
vertexFaces.set(vertexIndex, [i]);
} else if (neighbors.indexOf(i) < 0) {
neighbors.push(i);
vertexFaces.set(vertexIndex, neighbors);
}
});
}
}
// Find all adjacent vertices to each vertex, this is a regular mesh, so we know max num vertices for each vertex is 6.
const vertexVertices = new MutableTypedArray(new Int32Array(30 * vertices.getLength()), true, 30);
vertexVertices.clear();
{
const tempArray1: number[] = [];
const tempArray2: number[] = [];
for (let i = 0; i < faces.getLength(); i++) {
const faceVertices = faces.get(i, tempArray1);
if (faceVertices === null) {
continue;
}
faceVertices.forEach(vertexIndex => {
const adjacent = faceVertices.slice();
adjacent.splice(adjacent.indexOf(vertexIndex), 1);
const neighbors = vertexVertices.get(vertexIndex, tempArray2);
if (neighbors === null) {
vertexVertices.set(vertexIndex, adjacent);
return;
}
if (neighbors.indexOf(adjacent[0]) < 0) {
neighbors.push(adjacent[0]);
}
if (neighbors.indexOf(adjacent[1]) < 0) {
neighbors.push(adjacent[1]);
}
vertexVertices.set(vertexIndex, neighbors);
});
}
}
// Find all faces with two vertices in common.
const adjacentFaces = new MutableTypedArray(new Int32Array(3 * faces.getLength()), true, 3);
adjacentFaces.clear();
{
const tempArray1: number[] = [];
const tempArray2: number[] = [];
const tempArray3: number[] = [];
const tempArray4: number[] = [];
const tempArray5: number[] = [];
for (let i = 0; i < vertexFaces.getLength(); i++) {
const vFaces = vertexFaces.get(i, tempArray1);
if (vFaces === null) {
continue;
}
vFaces.forEach(faceIndex1 => {
const face1Vertices = faces.get(faceIndex1, tempArray2)!;
face1Vertices.splice(face1Vertices.indexOf(i), 1);
if (face1Vertices.length !== 2) {
throw new Error(`vertex ${i} not found in face ${faceIndex1}`);
}
let face1Faces = adjacentFaces.get(faceIndex1, tempArray3);
if (face1Faces === null) {
face1Faces = tempArray3;
face1Faces.length = 0;
}
if (face1Faces.length === 3) {
return;
}
vFaces.forEach(faceIndex2 => {
if (faceIndex1 === faceIndex2) {
return;
}
if ((face1Faces as number[]).indexOf(faceIndex2) >= 0) {
return;
}
const face2Vertices = faces.get(faceIndex2, tempArray4)!;
let face2Faces = adjacentFaces.get(faceIndex2, tempArray5);
if (face2Faces === null) {
face2Faces = tempArray5;
face2Faces.length = 0;
}
if (face2Faces.length === 3) {
return;
}
face2Vertices.splice(face2Vertices.indexOf(i), 1);
if (face2Vertices.length !== 2) {
throw new Error(`vertex ${i} not found in face ${faceIndex2}`);
}
if (face1Vertices.indexOf(face2Vertices[0]) < 0 && face1Vertices.indexOf(face2Vertices[1]) < 0) {
return;
}
face2Faces.push(faceIndex1);
(face1Faces as number[]).push(faceIndex2);
adjacentFaces.set(faceIndex2, face2Faces);
});
adjacentFaces.set(faceIndex1, face1Faces);
});
}
}
function isLeftFace(faceVertices: number[], v1: number, v2: number) {
const index1 = faceVertices.indexOf(v1);
const index2 = faceVertices.indexOf(v2);
if ((index2 - index1 + 3) % 3 === 1) {
return true;
}
return false;
}
// Find all dihedral params.
const dihedralParams = new MutableTypedArray(new Int32Array(0), true, 6);
{
const tempArray1: number[] = [];
const tempArray2: number[] = [];
const tempArray3: number[] = [];
for (let i = 0; i < adjacentFaces.getLength(); i++) {
const neighbors = adjacentFaces.get(i, tempArray1);
if (neighbors === null) {
continue;
}
const faceVerticesI = faces.get(i, tempArray2)!;
neighbors.forEach(j => {
if (i < j) {
const params: number[] = [];
// Get common vertices
const faceVerticesJ = faces.get(j, tempArray3)!;
faceVerticesJ.forEach(vertexIndex => {
if (faceVerticesI.indexOf(vertexIndex) < 0) {
return;
}
params.push(vertexIndex);
});
// Get opposite vertices i then j.
if (isLeftFace(faceVerticesI, params[0], params[1])) {
faceVerticesI.forEach(vertexIndex => {
if (faceVerticesJ.indexOf(vertexIndex) < 0) {
params.push(vertexIndex);
}
});
faceVerticesJ.forEach(vertexIndex => {
if (faceVerticesI.indexOf(vertexIndex) < 0) {
params.push(vertexIndex);
}
});
params.push(i);
params.push(j);
} else {
faceVerticesJ.forEach(vertexIndex => {
if (faceVerticesI.indexOf(vertexIndex) < 0) {
params.push(vertexIndex);
}
});
faceVerticesI.forEach(vertexIndex => {
if (faceVerticesJ.indexOf(vertexIndex) < 0) {
params.push(vertexIndex);
}
});
params.push(j);
params.push(i);
}
if (params.length !== 6) {
throw new Error('Invalid dihedral params.');
}
dihedralParams.push(params);
}
});
}
}
// Destroy old stuff.
adjacentFaces.destroy();
vertexFaces.destroy();
// Set up matrices.
const axialStiffness = 10;
const bendingStiffness = 10;
// Mass matrix - diagonal matrix of vertex masses, set all const for now.
const masses = [];
for (let i = 0; i < vertices.getLength(); i++) {
masses.push(1e-8);
}
const Mvec = DenseMatrix.zeros(masses.length * 3, 1);
masses.forEach((mass, i) => {
Mvec.set(mass, 3 * i, 0);
Mvec.set(mass, 3 * i + 1, 0);
Mvec.set(mass, 3 * i + 2, 0);
});
const M = SparseMatrix.diag(Mvec);
console.log(`M matrix: ${masses.length * 3} x ${masses.length * 3}`);
// Diag matrix of stiffness.
const stiffnesses = [];
const targetEdgeLengths: number[] = [];
// Add edge stiffnesses.
{
const tempArray1: number[] = [];
const tempVector1 = new Vector3();
const tempVector2 = new Vector3();
for (let i = 0; i < vertexVertices.getLength(); i++) {
const neighbors = vertexVertices.get(i, tempArray1);
if (!neighbors) continue;
neighbors.forEach(j => {
if (i < j) {
const vi = vertices.getVector3(i, tempVector1)!;
const vj = vertices.getVector3(j, tempVector2)!;
const targetLength = (vj.sub(vi)).length();
targetEdgeLengths.push(targetLength);
if (targetLength === 0) stiffnesses.push(0);
else {
stiffnesses.push(axialStiffness / targetLength);
}
}
});
}
}
// Add dihedral stiffnesses.
{
const tempArray1: number[] = [];
const tempVector1 = new Vector3();
const tempVector2 = new Vector3();
for (let i = 0; i < dihedralParams.getLength(); i++) {
const [v1, v2, v3, v4, leftFace, rightFace] = dihedralParams.get(i, tempArray1)!;
const vi = vertices.getVector3(v1, tempVector1)!;
const vj = vertices.getVector3(v2, tempVector2)!;
const targetLength = (vj.sub(vi)).length();
stiffnesses.push(bendingStiffness * targetLength);
}
}
const Gvec = DenseMatrix.zeros(stiffnesses.length, 1);
stiffnesses.forEach((stiffness, i) => {
Gvec.set(stiffness, i, 0);
})
const G = SparseMatrix.diag(Gvec);
console.log(`G matrix: ${stiffnesses.length} x ${stiffnesses.length}`);
function cot(v1: Vector3, v2: Vector3) {
return v1.dot(v2) / (v1.clone().cross(v2)).length();
}
// Calc compatibility matrix.
function calcC(
_positions: MutableTypedArray,
_vertexVertices: MutableTypedArray,
_dihedralParams: MutableTypedArray,
_normals: MutableTypedArray,
_dihedrals: (number | null)[],
numConstraints: number,
) {
console.log(`C matrix: ${numConstraints} x ${3 * _positions.getLength()}`);
const Ctriplets = new Triplet(numConstraints, 3 * _positions.getLength());
let index = -1;
let numAdded = 0;
{
const tempArray1: number[] = [];
const tempVector1 = new Vector3();
const tempVector2 = new Vector3();
for (let i = 0; i < _vertexVertices.getLength(); i++) {
const neighbors = _vertexVertices.get(i, tempArray1);
if (!neighbors) continue;
neighbors.forEach(j => {
if (i < j) {
index++;
const vi = _positions.getVector3(i, tempVector1)!;
const vj = _positions.getVector3(j, tempVector2)!;
const edgeVec = vj.sub(vi);
const length = edgeVec.length();
if (length < 1e-3) {
return;
}
edgeVec.divideScalar(length);
Ctriplets.addEntry(-edgeVec.x, index, 3 * i);
Ctriplets.addEntry(-edgeVec.y, index, 3 * i + 1);
Ctriplets.addEntry(-edgeVec.z, index, 3 * i + 2);
Ctriplets.addEntry(edgeVec.x, index, 3 * j);
Ctriplets.addEntry(edgeVec.y, index, 3 * j + 1);
Ctriplets.addEntry(edgeVec.z, index, 3 * j + 2);
numAdded++;
}
});
}
}
{
const tempArray1: number[] = [];
const tempVector1 = new Vector3();
const tempVector2 = new Vector3();
const tempVector3 = new Vector3();
const tempVector4 = new Vector3();
const tempVector5 = new Vector3();
const tempVector6 = new Vector3();
for (let i = 0; i < _dihedralParams.getLength(); i++) {
index++;
const [v1, v2, vLeft, vRight, leftFace, rightFace] = _dihedralParams.get(i, tempArray1)!;
const vi = vertices.getVector3(v1, tempVector1)!;
const vj = vertices.getVector3(v2, tempVector2)!;
const vl = vertices.getVector3(vLeft, tempVector3)!;
const vr = vertices.getVector3(vRight, tempVector4)!;
const vij = vj.clone().sub(vi);
const vil = vl.clone().sub(vi);
const vir = vr.clone().sub(vi);
const vlj = vj.clone().sub(vl);
const vrj = vj.clone().sub(vr);
const cotlij = cot(vil, vij);
const cotlji = cot(vlj, vij);
const cotrij = cot(vir, vij);
const cotrji = cot(vrj, vij);
const sumL = cotlij + cotlji;
const sumR = cotrij + cotrji;
const lenvij = vij.length();
if (lenvij < 1e-3) {
continue;
}
const dL = (vil.clone().cross(vlj)).length() / lenvij;
const dR = (vir.clone().cross(vrj)).length() / lenvij;
if (dL === 0 || dR === 0) {
continue;
}
const nL = _normals.getVector3(leftFace, tempVector5)!.clone().divideScalar(dL);
const nR = _normals.getVector3(rightFace, tempVector6)!.clone().divideScalar(dR);
const jacobv1 = (nL.clone().multiplyScalar(-cotlji/sumL)).add(nR.clone().multiplyScalar(-cotrji/sumR))
const jacobv2 = (nL.clone().multiplyScalar(-cotlij/sumL)).add(nR.clone().multiplyScalar(-cotrij/sumR))
Ctriplets.addEntry(nL.x, index, 3 * vLeft);
Ctriplets.addEntry(nL.y, index, 3 * vLeft + 1);
Ctriplets.addEntry(nL.z, index, 3 * vLeft + 2);
Ctriplets.addEntry(nR.x, index, 3 * vRight);
Ctriplets.addEntry(nR.y, index, 3 * vRight + 1);
Ctriplets.addEntry(nR.z, index, 3 * vRight + 2);
Ctriplets.addEntry(jacobv1.x, index, 3 * v1);
Ctriplets.addEntry(jacobv1.y, index, 3 * v1 + 1);
Ctriplets.addEntry(jacobv1.z, index, 3 * v1 + 2);
Ctriplets.addEntry(jacobv2.x, index, 3 * v2);
Ctriplets.addEntry(jacobv2.y, index, 3 * v2 + 1);
Ctriplets.addEntry(jacobv2.z, index, 3 * v2 + 2);
numAdded++;
}
}
if (numAdded !== numConstraints) {
console.log(`${numConstraints - numAdded} constraints skipped.`);
}
return SparseMatrix.fromTriplet(Ctriplets);
}
function calcResidual(
_positions: MutableTypedArray,
_vertexVertices: MutableTypedArray,
_targetLengths: number[],
_currentDihedrals: (number | null)[],
) {
const e = [];
let edgeIndex = 0;
const tempArray1: number[] = [];
const tempVector1 = new Vector3();
const tempVector2 = new Vector3();
for (let i = 0; i < vertexVertices.getLength(); i++) {
const neighbors = vertexVertices.get(i, tempArray1);
if (!neighbors) continue;
neighbors.forEach(j => {
if (i < j) {
const vi = _positions.getVector3(i, tempVector1)!;
const vj = _positions.getVector3(j, tempVector2)!;
const length = (vj.sub(vi)).length();
e.push(_targetLengths[edgeIndex] - length);
edgeIndex++;
}
});
}
let minDihedral = Infinity;
let maxDihedral = -Infinity;
for (let i = 0; i < _currentDihedrals.length; i++) {
if (_currentDihedrals[i] === null) {
e.push(0);
} else {
minDihedral = Math.min(minDihedral, _currentDihedrals[i]!);
maxDihedral = Math.max(maxDihedral, _currentDihedrals[i]!);
e.push(-(_currentDihedrals[i]!));
}
}
console.log('dihedral range', minDihedral.toFixed(3), maxDihedral.toFixed(3));
const eVec = DenseMatrix.zeros(e.length, 1);
e.forEach((el, i) => {
eVec.set(el, i, 0);
});
console.log(`E vec: ${e.length} x ${1}`);
return eVec;
}
function updateNormals(
_positions: MutableTypedArray,
_faces: MutableTypedArray,
_normals: MutableTypedArray,
) {
const tempArray1: number[] = [];
const tempVector1 = new Vector3();
const tempVector2 = new Vector3();
const tempVector3 = new Vector3();
for (let i = 0; i < _faces.getLength(); i++) {
const faceVertices = _faces.get(i, tempArray1);
if (faceVertices === null) {
continue;
}
const v0 = _positions.getVector3(faceVertices[0], tempVector1)!;
const v1 = _positions.getVector3(faceVertices[1], tempVector2)!;
const v2 = _positions.getVector3(faceVertices[2], tempVector3)!;
const vec1 = v1.clone().sub(v0);
const vec2 = v2.clone().sub(v0);
const normal = (vec1.cross(vec2)).normalize();
_normals.setVector3(i, normal);
}
}
function updateDihedrals(
_positions: MutableTypedArray,
_dihedralParams: MutableTypedArray,
_normals: MutableTypedArray,
_dihedrals: (number | null)[] | null,
max: number,
) {
const nextDihedrals = [];
const tempArray1: number[] = [];
const tempVector1 = new Vector3();
const tempVector2 = new Vector3();
const tempVector3 = new Vector3();
const tempVector4 = new Vector3();
for (let i = 0; i < _dihedralParams.getLength(); i++) {
const [v1, v2, v3, v4, leftFace, rightFace] = dihedralParams.get(i, tempArray1)!;
const vertex1 = _positions.getVector3(v1, tempVector1)!;
const vertex2 = _positions.getVector3(v2, tempVector2)!;
const vec = (vertex2.clone().sub(vertex1)).normalize();
const normalI = _normals.getVector3(leftFace, tempVector3)!;
const normalJ = _normals.getVector3(rightFace, tempVector4)!;
let x = normalI.dot(normalJ);
if (x < -1) x = -1;
if (x > 1) x = 1;
let y = (normalI.clone().cross(vec)).dot(normalJ);
if (y < -1) y = -1;
if (y > 1) y = 1;
let theta: number | null = Math.atan2(y, x);
if (_dihedrals && _dihedrals[i] !== null) {
let diff = theta - (_dihedrals[i]!);
if (diff < -5) {
diff += Math.PI * 2;
} else if (diff > 5) {
diff -= Math.PI * 2;
}
theta = (_dihedrals[i]!) + diff;
}
if (Math.abs(theta) > max) {
theta = null;
}
nextDihedrals.push(theta);
}
return nextDihedrals;
}
const normals = new MutableTypedArray(new Float32Array(faces.getLength() * 3), true, 3);
normals.clear();
updateNormals(vertices, faces, normals);
let dihedrals = updateDihedrals(vertices, dihedralParams, normals, null, Math.PI);
const iMax = NUM_ITERS;
let i = iMax;
// Step sim until convergence.
const name = `${FILENAME}_Mesh${MESH_NUM}_UnfoldingAnimation`;
const simDataFile = vertices.saveHeader(OUTPUT_PATH, name);
const dataLength = dataSizeForType(vertices.type);
const buffer = Buffer.alloc(vertices.getLength() * vertices.numElementsPerIndex * dataLength);
// Fill remainder of buffer with data.
while (i-- > 0) {
console.log(`\niter num: ${i}`)
console.time('iter');
updateNormals(vertices, faces, normals);
let maxAngle = Math.PI/2 * i/iMax + Math.PI/2;
if (maxAngle < Math.PI / 2) maxAngle = Math.PI / 2;
// console.log(`maxAngle: ${maxAngle}`);
dihedrals = updateDihedrals(vertices, dihedralParams, normals, dihedrals, maxAngle);
const C = calcC(vertices, vertexVertices, dihedralParams, normals, dihedrals, stiffnesses.length);
const Ctrans = C.transpose();
const CtransG = Ctrans.timesSparse(G);
const K = CtransG.timesSparse(C).plus(M);
const e = calcResidual(vertices, vertexVertices, targetEdgeLengths, dihedrals);
const f = CtransG.timesDense(e);
const displacement = (K.chol()).solvePositiveDefinite(f);
const scale = STEP_SCALE;
const tempVector1 = new Vector3();
for (let j = 0; j < vertices.getLength(); j++) {
const disp = (new Vector3(
displacement.get(3 * j, 0),
displacement.get(3 * j + 1, 0),
displacement.get(3 * j + 2, 0))).multiplyScalar(scale);
const lastPosition = vertices.getVector3(j, tempVector1);
if (!lastPosition) continue;
vertices.setVector3(j, lastPosition.add(disp));
}
// Save vertex positions.
writeDataToBuffer(vertices.getData(), buffer, name, 0, vertices.getLength() * vertices.numElementsPerIndex);
writeSync(simDataFile, buffer);
memoryManager.deleteExcept([M, G]);
console.timeEnd('iter');
}
closeSync(simDataFile);
// Write an obj of final state.
saveOBJ(
OUTPUT_PATH,
`${FILENAME}_Mesh${MESH_NUM}_unfolded`,
`${fileParams.FILENAME}_Mesh${MESH_NUM}`,
(vertices.getData() as Float32Array).slice(0, vertices.getLength() * vertices.numElementsPerIndex),
(faces.getData() as Uint32Array).slice(0, faces.getLength() * faces.numElementsPerIndex),
uvs.getData() as Float32Array,
); | the_stack |
import {
AttributeResolutionDirectiveSet,
CdmCorpusDefinition,
CdmEntityAttributeDefinition,
CdmEntityDefinition,
CdmEntityReference,
CdmFolderDefinition,
cdmObjectType,
CdmProjection,
CdmTypeAttributeDefinition,
resolveOptions,
cdmStatusLevel,
CdmDataTypeReference
} from '../../../internal';
import { testHelper } from '../../testHelper';
import { projectionTestUtils } from '../../Utilities/projectionTestUtils';
import { CdmOperationAddArtifactAttribute } from 'Cdm/Projections/CdmOperationAddArtifactAttribute';
/**
* Class to handle AlterTraits operations
*/
describe('Cdm/Projection/TestProjectionAddArtifactAttribute', () => {
/**
* The path between TestDataPath and TestName.
*/
const testsSubpath: string = 'Cdm/Projection/ProjectionAddArtifactAttributeTest';
/**
* All possible combinations of the different resolution directives
*/
const resOptsCombinations: string[][] = [
[],
['referenceOnly'],
['normalized'],
['structured'],
['referenceOnly', 'normalized'],
['referenceOnly', 'structured'],
['normalized', 'structured'],
['referenceOnly', 'normalized', 'structured']
];
/**
* Test AddArtifactAttribute to add an entity attribute on an entity attribute.
*/
it('TestAddEntAttrOnEntAttrProj', async () => {
const testName: string = 'TestAddEntAttrOnEntAttrProj';
const entityName: string = 'NewPerson';
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
corpus.setEventCallback((statusLevel: cdmStatusLevel, message: string) => {
if (message.indexOf('CdmOperationAddArtifactAttribute | Operation AddArtifactAttribute is not supported on an entity attribute yet.') === -1) {
fail(`Some unexpected failure - ${message}!`);
}
}, cdmStatusLevel.warning);
const entity: CdmEntityDefinition = await corpus.fetchObjectAsync<CdmEntityDefinition>(`local:/${entityName}.cdm.json/${entityName}`);
const resolvedEntity: CdmEntityDefinition = await projectionTestUtils.getResolvedEntity(corpus, entity, [ ]);
});
/**
* Test AddArtifactAttribute to add an attribute group on an entity attribute.
*/
it('TestAddAttrGrpOnEntAttrProj', async () => {
const testName: string = 'TestAddAttrGrpOnEntAttrProj';
const entityName: string = 'NewPerson';
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
corpus.setEventCallback((statusLevel: cdmStatusLevel, message: string) => {
if (message.indexOf('CdmOperationAddArtifactAttribute | Operation AddArtifactAttribute is not supported on an attribute group yet.') === -1) {
fail(`Some unexpected failure - ${message}!`);
}
}, cdmStatusLevel.warning);
const entity: CdmEntityDefinition = await corpus.fetchObjectAsync<CdmEntityDefinition>(`local:/${entityName}.cdm.json/${entityName}`);
const resolvedEntity: CdmEntityDefinition = await projectionTestUtils.getResolvedEntity(corpus, entity, [ ]);
});
/**
* Test AddArtifactAttribute to add a type attribute on a type attribute.
*/
it('TestAddTypeAttrOnTypeAttrProj', async () => {
const testName: string = 'TestAddTypeAttrOnTypeAttrProj';
const entityName: string = 'Person';
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
for (const resOpt of resOptsCombinations) {
await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt);
}
const entity: CdmEntityDefinition = await corpus.fetchObjectAsync<CdmEntityDefinition>(`local:/${entityName}.cdm.json/${entityName}`);
const resolvedEntity: CdmEntityDefinition = await projectionTestUtils.getResolvedEntity(corpus, entity, [ ]);
expect(resolvedEntity.attributes.length)
.toEqual(2);
expect((resolvedEntity.attributes.allItems[0] as CdmTypeAttributeDefinition).name)
.toEqual('newTerm');
expect((resolvedEntity.attributes.allItems[1] as CdmTypeAttributeDefinition).name)
.toEqual('FavoriteTerm');
});
/**
* Test AddArtifactAttribute operation nested with ExcludeAttributes/RenameAttributes.
*/
it('TestCombineOpsNestedProj', async () => {
const testName: string = 'TestCombineOpsNestedProj';
const entityName: string = 'NewPerson';
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
for (const resOpt of resOptsCombinations) {
await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt);
}
const entity: CdmEntityDefinition = await corpus.fetchObjectAsync<CdmEntityDefinition>(`local:/${entityName}.cdm.json/${entityName}`);
const resolvedEntity: CdmEntityDefinition = await projectionTestUtils.getResolvedEntity(corpus, entity, [ ]);
// Original set of attributes: [ { "name", "age", "address", "phoneNumber", "email" }, "FavoriteTerm" ]
// Entity Attribuite:
// Exclude attributes: ["age", "phoneNumber", "name"]
// Add attribute: ["newName"]
// Rename attribute ["newName" -> "renaming-{m}" ]
// Rename attribute ["renaming-newName" -> "renamingAgain-{m}" ]
// Add attribute: ["newName_1"]
// Type Attribute:
// Add attribute: ["newName"]
// Rename attribute ["newName" -> "renamed-{m}" ]
// Add attribute: ["newTerm" (InsertAtTop:true)]
expect(resolvedEntity.attributes.length)
.toEqual(7);
expect((resolvedEntity.attributes.allItems[0] as CdmTypeAttributeDefinition).name)
.toEqual('address');
expect((resolvedEntity.attributes.allItems[1] as CdmTypeAttributeDefinition).name)
.toEqual('email');
expect((resolvedEntity.attributes.allItems[2] as CdmTypeAttributeDefinition).name)
.toEqual('renamingAgain-renaming-newName')
expect((resolvedEntity.attributes.allItems[3] as CdmTypeAttributeDefinition).name)
.toEqual('newName_1');
expect((resolvedEntity.attributes.allItems[4] as CdmTypeAttributeDefinition).name)
.toEqual('newTerm');
expect((resolvedEntity.attributes.allItems[5] as CdmTypeAttributeDefinition).name)
.toEqual('FavoriteTerm');
expect((resolvedEntity.attributes.allItems[6] as CdmTypeAttributeDefinition).name)
.toEqual('renamed-newName');
});
/**
* Test AddArtifactAttribute operation with a 'structured' condition.
*/
it('TestConditionalProj', async () => {
const testName: string = 'TestConditionalProj';
const entityName: string = 'NewPerson';
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
for (const resOpt of resOptsCombinations) {
await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt);
}
const entity: CdmEntityDefinition = await corpus.fetchObjectAsync<CdmEntityDefinition>(`local:/${entityName}.cdm.json/${entityName}`);
const resolvedEntity: CdmEntityDefinition = await projectionTestUtils.getResolvedEntity(corpus, entity, [ 'referenceOnly' ]);
// Original set of attributes: ['name', 'age', 'address', 'phoneNumber', 'email']
// Condition not met, keep attributes in flat list
expect(resolvedEntity.attributes.length)
.toEqual(5);
expect((resolvedEntity.attributes.allItems[0] as CdmTypeAttributeDefinition).name)
.toEqual('name');
expect((resolvedEntity.attributes.allItems[1] as CdmTypeAttributeDefinition).name)
.toEqual('age');
expect((resolvedEntity.attributes.allItems[2] as CdmTypeAttributeDefinition).name)
.toEqual('address');
expect((resolvedEntity.attributes.allItems[3] as CdmTypeAttributeDefinition).name)
.toEqual('phoneNumber');
expect((resolvedEntity.attributes.allItems[4] as CdmTypeAttributeDefinition).name)
.toEqual('email');
const resolvedEntity2: CdmEntityDefinition = await projectionTestUtils.getResolvedEntity(corpus, entity, [ 'structured' ]);
// Original set of attributes: ['name', 'age', 'address', 'phoneNumber', 'email']
// Condition met, keep attributes in flat list and add the new attribute "newName" all attributes at the end
expect(resolvedEntity2.attributes.length)
.toEqual(6);
expect((resolvedEntity2.attributes.allItems[0] as CdmTypeAttributeDefinition).name)
.toEqual('name')
expect((resolvedEntity2.attributes.allItems[1] as CdmTypeAttributeDefinition).name)
.toEqual('age');
expect((resolvedEntity2.attributes.allItems[2] as CdmTypeAttributeDefinition).name)
.toEqual('address');
expect((resolvedEntity2.attributes.allItems[3] as CdmTypeAttributeDefinition).name)
.toEqual('phoneNumber');
expect((resolvedEntity2.attributes.allItems[4] as CdmTypeAttributeDefinition).name)
.toEqual('email');
expect((resolvedEntity2.attributes.allItems[5] as CdmTypeAttributeDefinition).name)
.toEqual('newName');
});
/**
* Test for creating a projection with an AddArtifactAttribute operation and a condition using the object model.
*/
it('TestConditionalProjUsingObjectModel', async () => {
const testName: string = 'TestConditionalProjUsingObjectModel';
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
const localRoot: CdmFolderDefinition = corpus.storage.fetchRootFolder('local');
// Create an entity.
const entity: CdmEntityDefinition = projectionTestUtils.createEntity(corpus, localRoot);
// Create a projection with a condition that states the operation should only execute when the resolution directive is 'structured'.
const projection: CdmProjection = projectionTestUtils.createProjection(corpus, localRoot);
projection.condition = 'structured==true';
// Create an AddArtifactAttribute operation
const addArtifactAttributeOp:CdmOperationAddArtifactAttribute = corpus.MakeObject<CdmOperationAddArtifactAttribute>(cdmObjectType.operationAddArtifactAttributeDef);
addArtifactAttributeOp.newAttribute = corpus.MakeObject<CdmTypeAttributeDefinition>(cdmObjectType.typeAttributeDef, 'newName');
(addArtifactAttributeOp.newAttribute as CdmTypeAttributeDefinition).dataType = corpus.MakeRef<CdmDataTypeReference>(cdmObjectType.dataTypeRef, 'string', true);
projection.operations.push(addArtifactAttributeOp);
// Create an entity reference to hold this projection.
const projectionEntityRef: CdmEntityReference = corpus.MakeObject<CdmEntityReference>(cdmObjectType.entityRef, null);
projectionEntityRef.explicitReference = projection;
// Create an entity attribute that contains this projection and add this to the entity.
const entityAttribute: CdmEntityAttributeDefinition = corpus.MakeObject<CdmEntityAttributeDefinition>(cdmObjectType.entityAttributeDef, 'TestEntityAttribute');
entityAttribute.entity = projectionEntityRef;
entity.attributes.push(entityAttribute);
// Create resolution options with the 'referenceOnly' directive.
const resOpt = new resolveOptions(entity.inDocument)
resOpt.directives = new AttributeResolutionDirectiveSet(new Set<string>([ 'referenceOnly' ]));
// Resolve the entity with 'referenceOnly'
const resolvedEntityWithReferenceOnly: CdmEntityDefinition = await entity.createResolvedEntityAsync(`Resolved_${entity.entityName}.cdm.json`, resOpt, localRoot);
// Original set of attributes: ['id', 'name', 'value', 'date']
// Condition not met, keep attributes in flat list
expect(resolvedEntityWithReferenceOnly.attributes.length)
.toEqual(4);
expect((resolvedEntityWithReferenceOnly.attributes.allItems[0] as CdmTypeAttributeDefinition).name)
.toEqual('id');
expect((resolvedEntityWithReferenceOnly.attributes.allItems[1] as CdmTypeAttributeDefinition).name)
.toEqual('name');
expect((resolvedEntityWithReferenceOnly.attributes.allItems[2] as CdmTypeAttributeDefinition).name)
.toEqual('value');
expect((resolvedEntityWithReferenceOnly.attributes.allItems[3] as CdmTypeAttributeDefinition).name)
.toEqual('date');
// Now resolve the entity with the 'structured' directive
resOpt.directives = new AttributeResolutionDirectiveSet(new Set<string>([ 'structured' ]));
const resolvedEntityWithStructured: CdmEntityDefinition = await entity.createResolvedEntityAsync(`Resolved_${entity.entityName}.cdm.json`, resOpt, localRoot);
// Verify correctness of the resolved attributes after running the AddAttributeGroup operation
// Condition met, new traits are added
expect(resolvedEntityWithStructured.attributes.length)
.toEqual(5);
expect((resolvedEntityWithStructured.attributes.allItems[0] as CdmTypeAttributeDefinition).name)
.toEqual('id');
expect((resolvedEntityWithStructured.attributes.allItems[1] as CdmTypeAttributeDefinition).name)
.toEqual('name');
expect((resolvedEntityWithStructured.attributes.allItems[2] as CdmTypeAttributeDefinition).name)
.toEqual('value');
expect((resolvedEntityWithStructured.attributes.allItems[3] as CdmTypeAttributeDefinition).name)
.toEqual('date');
expect((resolvedEntityWithStructured.attributes.allItems[4] as CdmTypeAttributeDefinition).name)
.toEqual('newName');
});
/**
* Test AddArtifactAttribute operation on an entity definition.
*/
it('TestExtendsEntityProj', async () => {
const testName: string = 'TestExtendsEntityProj';
const entityName: string = 'Child';
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
for (const resOpt of resOptsCombinations) {
await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt);
}
const entity: CdmEntityDefinition = await corpus.fetchObjectAsync<CdmEntityDefinition>(`local:/${entityName}.cdm.json/${entityName}`);
const resolvedEntity: CdmEntityDefinition = await projectionTestUtils.getResolvedEntity(corpus, entity, [ ]);
// Original set of attributes: ['name', 'age', 'address', 'phoneNumber', 'email']
expect(resolvedEntity.attributes.length)
.toEqual(6);
expect((resolvedEntity.attributes.allItems[0] as CdmTypeAttributeDefinition).name)
.toEqual('name')
expect((resolvedEntity.attributes.allItems[1] as CdmTypeAttributeDefinition).name)
.toEqual('age');
expect((resolvedEntity.attributes.allItems[2] as CdmTypeAttributeDefinition).name)
.toEqual('address');
expect((resolvedEntity.attributes.allItems[3] as CdmTypeAttributeDefinition).name)
.toEqual('phoneNumber');
expect((resolvedEntity.attributes.allItems[4] as CdmTypeAttributeDefinition).name)
.toEqual('email');
expect((resolvedEntity.attributes.allItems[5] as CdmTypeAttributeDefinition).name)
.toEqual('newName');
});
/**
* Multiple AddArtifactAttribute operations on the same projection.
*/
it('TestMultipleOpProj', async () => {
const testName: string = 'TestMultipleOpProj';
const entityName: string = 'NewPerson';
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
for (const resOpt of resOptsCombinations) {
await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt);
}
const entity: CdmEntityDefinition = await corpus.fetchObjectAsync<CdmEntityDefinition>(`local:/${entityName}.cdm.json/${entityName}`);
const resolvedEntity: CdmEntityDefinition = await projectionTestUtils.getResolvedEntity(corpus, entity, [ ]);
// Original set of attributes: ["name", "age", "address", "phoneNumber", "email"]
// Add attribute: ["newName", "newName_1", "newName"]
// 2 "newName" will be merged
expect(resolvedEntity.attributes.length)
.toEqual(7);
expect((resolvedEntity.attributes.allItems[0] as CdmTypeAttributeDefinition).name)
.toEqual('name')
expect((resolvedEntity.attributes.allItems[1] as CdmTypeAttributeDefinition).name)
.toEqual('age');
expect((resolvedEntity.attributes.allItems[2] as CdmTypeAttributeDefinition).name)
.toEqual('address');
expect((resolvedEntity.attributes.allItems[3] as CdmTypeAttributeDefinition).name)
.toEqual('phoneNumber');
expect((resolvedEntity.attributes.allItems[4] as CdmTypeAttributeDefinition).name)
.toEqual('email');
expect((resolvedEntity.attributes.allItems[5] as CdmTypeAttributeDefinition).name)
.toEqual('newName');
expect((resolvedEntity.attributes.allItems[6] as CdmTypeAttributeDefinition).name)
.toEqual('newName_1');
});
/**
* Test insertAtTop field in AddArtifactAttribute operation.
*/
it('TestInsertAtTop', async () => {
const testName: string = 'TestInsertAtTop';
const entityName: string = 'NewPerson';
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
for (const resOpt of resOptsCombinations) {
await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt);
}
const entity: CdmEntityDefinition = await corpus.fetchObjectAsync<CdmEntityDefinition>(`local:/${entityName}.cdm.json/${entityName}`);
const resolvedEntity: CdmEntityDefinition = await projectionTestUtils.getResolvedEntity(corpus, entity, [ ]);
// Original set of attributes: ["name", "age", "address", "phoneNumber", "email"]
// Add attribute: ["newName" (InsertAtTop:false), "newName_1" (InsertAtTop:true)]
expect(resolvedEntity.attributes.length)
.toEqual(7);
expect((resolvedEntity.attributes.allItems[0] as CdmTypeAttributeDefinition).name)
.toEqual('newName_1');
expect((resolvedEntity.attributes.allItems[1] as CdmTypeAttributeDefinition).name)
.toEqual('name')
expect((resolvedEntity.attributes.allItems[2] as CdmTypeAttributeDefinition).name)
.toEqual('age');
expect((resolvedEntity.attributes.allItems[3] as CdmTypeAttributeDefinition).name)
.toEqual('address');
expect((resolvedEntity.attributes.allItems[4] as CdmTypeAttributeDefinition).name)
.toEqual('phoneNumber');
expect((resolvedEntity.attributes.allItems[5] as CdmTypeAttributeDefinition).name)
.toEqual('email');
expect((resolvedEntity.attributes.allItems[6] as CdmTypeAttributeDefinition).name)
.toEqual('newName');
});
/**
* Nested projections with AddArtifactAttribute.
*/
it('TestNestedProj', async () => {
const testName: string = 'TestNestedProj';
const entityName: string = 'NewPerson';
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
for (const resOpt of resOptsCombinations) {
await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt);
}
const entity: CdmEntityDefinition = await corpus.fetchObjectAsync<CdmEntityDefinition>(`local:/${entityName}.cdm.json/${entityName}`);
const resolvedEntity: CdmEntityDefinition = await projectionTestUtils.getResolvedEntity(corpus, entity, [ ]);
// Create resolution options with the 'referenceOnly' directive.
const resolvedEntityWithReferenceOnly: CdmEntityDefinition = await projectionTestUtils.getResolvedEntity(corpus, entity, [ 'referenceOnly' ]);
// Original set of attributes: ["name", "age", "address", "phoneNumber", "email"]
expect(resolvedEntity.attributes.length)
.toEqual(7);
expect((resolvedEntity.attributes.allItems[0] as CdmTypeAttributeDefinition).name)
.toEqual('name')
expect((resolvedEntity.attributes.allItems[1] as CdmTypeAttributeDefinition).name)
.toEqual('age');
expect((resolvedEntity.attributes.allItems[2] as CdmTypeAttributeDefinition).name)
.toEqual('address');
expect((resolvedEntity.attributes.allItems[3] as CdmTypeAttributeDefinition).name)
.toEqual('phoneNumber');
expect((resolvedEntity.attributes.allItems[4] as CdmTypeAttributeDefinition).name)
.toEqual('email');
expect((resolvedEntity.attributes.allItems[5] as CdmTypeAttributeDefinition).name)
.toEqual('newName_inner');
expect((resolvedEntity.attributes.allItems[6] as CdmTypeAttributeDefinition).name)
.toEqual('newName_outer');
});
}); | the_stack |
// As of 2022-01-17, PSD.js does not provide its own type definitions, and does
// not have an entry in the DefinitelyTyped project.
// As such, we provide our own types.
//
// Note: These types are based on the browser build, not the Node.js build!
export = PSD;
declare class PSD {
parsed: boolean;
header: any | null;
resources?: any;
layerMask: PSD.LayerMask;
image: PSD.Image;
/**
* Creates a new PSD object. Typically you will use a helper method to
* instantiate the PSD object. However, if you already have the PSD data
* stored as a `Uint8Array`, you can instantiate the PSD object directly.
*/
constructor(data: Uint8Array);
/**
* Parses the PSD. You must call this method before attempting to access PSD
* data. It will not re-parse the PSD if it has already been parsed.
*/
parse(): void;
/**
* Returns a tree representation of the PSD document, which is the preferred
* way of accessing most of the PSD's data.
*/
tree(): PSD.Node.Root;
// From shims/init.coffee
static fromURL(file: string): Promise<PSD>;
static fromEvent(e: InputEvent): Promise<PSD>;
static fromDroppedFile(file: Blob): Promise<PSD>;
}
declare namespace PSD {
// lib/psd/channel_image.coffee
/**
* Represents an image for a single layer, which differs slightly in format
* from the full size preview image.
*
* The full preview at the end of the PSD document has the same compression
* for all channels, whereas layer images define the compression per color
* channel. The dimensions can also differ per channel if we're parsing mask
* data (channel ID < -1).
*/
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface ChannelImage extends Image {
// TODO: Finish this
}
type ChildrenExport = Node.GroupExport | Node.LayerExport;
// lib/psd/image.coffee
/**
* Represents the full preview image at the end of the PSD document. For this
* image, the compression is defined for all channels, and there is no mask
* data. The width and height are derived from the PSD header, which is the
* full size of the PSD document.
*/
interface Image {
// TODO: Finish this
// Mixins from lib/psd/image_exports/png.coffee
// (shimmed with shims/png.coffee)
toBase64(): string;
toPng(): HTMLImageElement;
/**
* The resulting array that stores the pixel data, formatted in RGBA format.
*/
pixelData: Uint8Array;
width(): number;
height(): number;
}
// lib/psd/layer.coffee
// (not to be confused with PSD.Node.Layer)
/**
* Represents a single layer and all of the data associated with that layer.
* Typically you will access this data from a {@link Node} object, which simplifies
* access for you.
*/
interface Layer {
// Mixin from lib/psd/layer/position_channels.coffee
top: number;
left: number;
bottom: number;
right: number;
channels: number;
rows: number;
height: number;
cols: number;
width: number;
/**
* Every color channel has both an ID and a length. The ID correlates to the
* color channel, e.g. 0 = R, 1 = G, 2 = B, -1 = A, and the length is the
* size of the data.
*/
channelsInfo: {id: number; length: number}[];
// Mixin from lib/psd/layer/blend_modes.coffee
blendMode: BlendMode;
opacity: BlendMode["opacity"];
visible: BlendMode["visible"];
clipped: BlendMode["clipped"];
/** Opposite of {@link Layer.visible} */
hidden(): boolean;
blendingMode(): BlendMode["mode"];
// Mixin from lib/psd/layer/mask.coffee
mask: Mask;
// Mixin from lib/psd/layer/blending_ranges.coffee
blendingRanges: {
grey: Layer.BlendingSourceDest;
channels: Layer.BlendingSourceDest[];
};
// Mixin from lib/psd/layer/name.coffee
/**
* Every Photoshop document has what we can consider to be the "legacy"
* name. This used to be the sole place that Photoshop stored the layer
* name, but once people started using fancy UTF-8 characters, they moved
* the layer name out into a layer info block. This stayed behind for
* compatibility reasons. The newer layer name is always preferred since it
* covers all possible characters (even emojis), while this has a much more
* limited character set.
*/
legacyName: string;
// Mixin from lib/psd/layer/info.coffee
// TODO: This is too big to add right now. Let's add it later
// adjustments: {}
// Mixin from lib/psd/layer/helpers.coffee
isFolder(): boolean;
isFolderEnd(): boolean;
// Mixin from lib/psd/layer/channel_image.coffee
image: ChannelImage;
get name(): string;
// TODO: Finish this!
// Properties set by Node constructor (lib/psd/node.coffee)
node?: NodeChildren;
}
namespace Layer {
// Part of lib/psd/layer/blending_ranges.coffee
interface BlendingSourceDest {
source: {
black: [number, number];
white: [number, number];
};
dest: {
black: [number, number];
white: [number, number];
};
}
}
// lib/psd/layer_mask.coffee
/**
* The layer mask is the overarching data structure that describes both the
* layers/groups in the PSD document, and the global mask.
* This part of the document is ordered as such:
*
* * Layers
* * Layer images
* * Global Mask
*
* The file does not need to have a global mask. If there is none, then its
* length will be zero.
*/
interface LayerMask {
// TODO: Finish this
layers: Layer[];
}
type NodeChildren = Node.Group | Node.Layer;
type NodeParent = Node.Group | Node.Root;
type NodeType = "node" | "layer" | "group" | "root";
// lib/psd/node.coffee
/**
* The Node abstraction is one of the most important in PSD.js. It's the base
* for the tree representation of the document structure. Every layer and
* group is a node in the document tree. All common functionality is here, and
* both layers and groups extend this class with specialized functionality.
*
* While you can access the layer data directly, the Node interface provides a
* somewhat higher-level API that makes it easier and less verbose to access
* the wealth of information that's stored in each PSD.
*/
interface Node {
// Mixin from lib/psd/nodes/ancestry.coffee
root(): Node.Root;
isRoot(): boolean;
children(): NodeChildren[];
ancestors(): NodeParent[];
hasChildren(): boolean;
childless(): boolean;
siblings(): NodeChildren[];
nextSibling(): NodeChildren | null;
prevSibling(): NodeChildren | null;
hasSiblings(): boolean;
onlyChild(): boolean;
descendants(): NodeChildren[];
subtree(): NodeChildren[];
depth(): number;
path(asArray?: boolean): string;
// Mixin from lib/psd/nodes/search.coffee
childrenAtPath(
path: string | string[],
opts?: {
caseSensitive?: boolean;
}
): NodeChildren[];
// Mixin from lib/psd/nodes/build_preview.coffee
// (shimmed with shims/png.coffee)
toBase64(): string;
toPng(): HTMLImageElement;
type: NodeType;
layer: Layer;
parent: NodeParent | null;
name: string;
forceVisible: null;
coords: {
top: number;
bottom: number;
left: number;
right: number;
};
topOffset: number;
leftOffset: number;
/** The getter for this field returns `coords.top + topOffset`. */
get top(): number;
/** The setter for this field returns `coords.top`. */
set top(value: number);
/** The getter for this field returns `coords.right + leftOffset`. */
get right(): number;
/** The setter for this field returns `coords.right`. */
set right(value: number);
/** The getter for this field returns `coords.bottom + topOffset`. */
get bottom(): number;
/** The setter for this field returns `coords.bottom`. */
set bottom(value: number);
/** The getter for this field returns `coords.left + leftOffset`. */
get left(): number;
/** The setter for this field returns `coords.left`. */
set left(value: number);
get width(): number;
get height(): number;
/**
* **All properties should be accessed through `get()`**. While many
* things can be accessed without it, using `get()` provides 2 things:
*
* * Consistency
* * Access to both data on the Node and the Layer through the same
* interface.
*
* This makes it much cleaner to access stuff like layer info blocks,
* since you just give the name of the block you want to access. For
* example:
*
* ```js
* node.get('typeTool').export();
*
* // vs
*
* node.layer.typeTool().export();
* ```
*/
get(prop: string): any;
/**
* Is this layer/group visible? This checks all possible places that could
* define whether or not this is true, e.g. clipping masks. It also checks
* the current layer comp visibility override (not implemented yet).
*/
visible(): boolean;
/** Opposite of `visible()` */
hidden(): boolean;
isLayer(): boolean;
isGroup(): boolean;
/**
* Retrieves the clipping mask for this node. Because a clipping mask can
* be applied to multiple layers, we have to traverse the tree until we
* find the first node that does not have the `clipped` flag. We can do it
* this way because all layers that the clipping node affects must be
* siblings and in sequence.
*/
clippingMask(): any | null;
/** Alias of {@link clippingMask()} */
clippedBy(): any | null;
/**
* Export the most important information about this node as a plain
* object.
* If we're exporting a group, it will recursively export itself and all
* of it's descendants as well.
*/
export(): unknown;
}
interface NodeExport {
type: Node["type"];
visible: boolean;
opacity: number;
blendingMode: ReturnType<Layer["blendingMode"]>;
name: string;
left: number;
right: number;
top: number;
bottom: number;
height: number;
width: number;
}
namespace Node {
// lib/psd/nodes/group.coffee
interface Group extends Node {
parent: NodeParent;
type: "group";
passthruBlending(): boolean;
isEmpty(): boolean;
export(): GroupExport;
}
interface GroupExport extends NodeExport {
type: "group";
children: ChildrenExport[];
}
// lib/psd/nodes/layer.coffee
// (not to be confused with PSD.Layer)
interface Layer extends Node {
parent: NodeParent;
type: "layer";
isEmpty(): boolean;
export(): LayerExport;
}
interface LayerExport extends NodeExport {
type: "layer";
mask: MaskExport;
text: any;
image: EmptyObject;
}
// lib/psd/nodes/root.coffee
interface Root extends Node {
parent: null;
type: "root";
psd: PSD;
documentDimensions(): [width: number, height: number];
depth(): 0;
opacity(): 255;
fillOpacity(): 255;
export(): RootExport;
}
interface RootExport {
children: ChildrenExport[];
document: {
width: number;
height: number;
resources: {
layerComps: any;
resolutionInfo: any;
guides: any;
slices: []; // Seems to be non-functional?
};
};
}
}
}
// lib/psd/blend_mode.coffee
type BlendModeKey =
| "norm"
| "dark"
| "lite"
| "hue"
| "sat"
| "colr"
| "lum"
| "mul"
| "scrn"
| "diss"
| "over"
| "hLit"
| "sLit"
| "diff"
| "smud"
| "div"
| "idiv"
| "lbrn"
| "lddg"
| "vLit"
| "lLit"
| "pLit"
| "hMix"
| "pass"
| "dkCl"
| "lgCl"
| "fsub"
| "fdiv";
// lib/psd/blend_mode.coffee
type BlendModeName =
| "normal"
| "darken"
| "lighten"
| "hue"
| "saturation"
| "color"
| "luminosity"
| "multiply"
| "screen"
| "dissolve"
| "overlay"
| "hard_light"
| "soft_light"
| "difference"
| "exclusion"
| "color_dodge"
| "color_burn"
| "linear_burn"
| "linear_dodge"
| "vivid_light"
| "linear_light"
| "pin_light"
| "hard_mix"
| "passthru"
| "darker_color"
| "lighter_color"
| "subtract"
| "divide";
// lib/psd/blend_mode.coffee
interface BlendMode {
/** The 4 character key for the blending mode. */
blendKey: BlendModeKey;
/** The opacity of the layer, from [0, 255]. */
opacity: number;
/** Raw value for the clipping state of this layer. */
clipping: number;
/** Is this layer a clipping mask? */
clipped: boolean;
flags: number;
/** The readable representation of the blend mode. */
mode: BlendModeName;
/** Is this layer visible? */
visible: boolean;
/** Returns the layer opacity as a percentage. */
opacityPercentage(): number;
}
// lib/psd/mask.coffee
/**
* Each layer/group in the PSD document can have a mask, which is represented
* by this class. The mask describes which parts of the layer are visible and
* which are hidden.
*/
interface Mask {
top: number;
right: number;
bottom: number;
left: number;
size: number;
width: number;
height: number;
relative: boolean;
disabled: boolean;
invert: boolean;
defaultColor: number;
flags: number;
export(): MaskExport;
}
interface MaskExport {
top: Mask["top"];
left: Mask["left"];
bottom: Mask["bottom"];
right: Mask["right"];
width: Mask["width"];
height: Mask["height"];
defaultColor: Mask["defaultColor"];
relative: Mask["relative"];
disabled: Mask["disabled"];
invert: Mask["invert"];
}
type EmptyObject = Record<string, never>; | the_stack |
import { combineUrls, Components, registerComponent } from '../../lib/vulcan-lib';
import { useMulti } from '../../lib/crud/withMulti';
import React, { useEffect, useState } from 'react';
import { Link } from '../../lib/reactRouterWrapper';
import { useLocation } from '../../lib/routeUtil';
import { userCanDo } from '../../lib/vulcan-users/permissions';
import { userCanEdit, userGetDisplayName, userGetProfileUrl, userGetProfileUrlFromSlug } from "../../lib/collections/users/helpers";
import { userGetEditUrl } from '../../lib/vulcan-users/helpers';
import { DEFAULT_LOW_KARMA_THRESHOLD } from '../../lib/collections/posts/views'
import StarIcon from '@material-ui/icons/Star'
import DescriptionIcon from '@material-ui/icons/Description'
import MessageIcon from '@material-ui/icons/Message'
import PencilIcon from '@material-ui/icons/Create'
import LocationIcon from '@material-ui/icons/LocationOn'
import classNames from 'classnames';
import { useCurrentUser } from '../common/withUser';
import Tooltip from '@material-ui/core/Tooltip';
import Button from '@material-ui/core/Button';
import Divider from '@material-ui/core/Divider';
import {AnalyticsContext} from "../../lib/analyticsEvents";
import { forumTypeSetting, hasEventsSetting, siteNameWithArticleSetting, taggingNameIsSet, taggingNameCapitalSetting, taggingNameSetting } from '../../lib/instanceSettings';
import { separatorBulletStyles } from '../common/SectionFooter';
import { taglineSetting } from '../common/HeadTags';
import { SECTION_WIDTH } from '../common/SingleColumnSection';
import { socialMediaIconPaths } from '../form-components/PrefixedInput';
import { CAREER_STAGES, SOCIAL_MEDIA_PROFILE_FIELDS } from '../../lib/collections/users/custom_fields';
import { getBrowserLocalStorage } from '../async/localStorageHandlers';
import { SORT_ORDER_OPTIONS } from '../../lib/collections/posts/schema';
import { useUpdate } from '../../lib/crud/withUpdate';
import { useMessages } from '../common/withMessages';
export const sectionFooterLeftStyles = {
flexGrow: 1,
display: "flex",
'&&:after': {
content: '""'
}
}
const styles = (theme: ThemeType): JssStyles => ({
profilePage: {
display: 'grid',
gridTemplateColumns: `1fr ${SECTION_WIDTH}px 1fr`,
gridTemplateAreas: `
'. center right'
`,
justifyContent: 'center',
columnGap: 60,
paddingLeft: 10,
paddingRight: 10,
marginLeft: "auto",
[theme.breakpoints.down('lg')]: {
columnGap: 40,
},
[theme.breakpoints.down('md')]: {
display: 'block',
marginTop: -20
},
[theme.breakpoints.down('sm')]: {
paddingLeft: 5,
paddingRight: 5,
margin: 0,
}
},
centerColumnWrapper: {
gridArea: 'center'
},
usernameTitle: {
display: 'flex',
justifyContent: 'space-between',
fontSize: "3rem",
...theme.typography.display3,
...theme.typography.postStyle,
marginTop: 0,
[theme.breakpoints.down('sm')]: {
marginTop: 15
}
},
messageBtnDesktop: {
display: 'block',
[theme.breakpoints.down('xs')]: {
display: 'none'
}
},
messageBtnMobile: {
display: 'none',
[theme.breakpoints.down('xs')]: {
display: 'block'
}
},
messageBtn: {
boxShadow: 'none',
marginLeft: 20,
[theme.breakpoints.down('xs')]: {
margin: '5px 0 10px'
}
},
mapLocation: {
display: 'inline-flex',
alignItems: 'center',
columnGap: 4,
...theme.typography.commentStyle,
fontSize: 13,
color: theme.palette.grey[800],
marginBottom: 12
},
locationIcon: {
fontSize: 14,
},
userInfo: {
display: "flex",
flexWrap: "wrap",
color: theme.palette.lwTertiary.main,
marginTop: 8,
...separatorBulletStyles(theme)
},
meta: {
...sectionFooterLeftStyles,
[theme.breakpoints.down('sm')]: {
width: "100%",
marginBottom: theme.spacing.unit,
}
},
icon: {
'&$specificalz': {
fontSize: 18,
color: theme.palette.icon.dim,
marginRight: 4
}
},
actions: {
marginLeft: 20,
},
bio: {
marginTop: theme.spacing.unit*3,
},
helpFieldHeading: {
fontFamily: theme.typography.fontFamily,
marginTop: theme.spacing.unit*4,
},
primaryColor: {
color: theme.palette.primary.light
},
title: {
cursor: "pointer"
},
// Dark Magick
// https://giphy.com/gifs/psychedelic-art-phazed-12GGadpt5aIUQE
specificalz: {},
userMetaInfo: {
display: "inline-flex"
},
reportUserSection: {
marginTop: 60
},
reportUserBtn: {
...theme.typography.commentStyle,
background: 'none',
color: theme.palette.primary.main,
fontSize: 13,
padding: 0,
'&:hover': {
color: theme.palette.primary.dark,
}
},
rightSidebar: {
gridArea: 'right',
fontFamily: theme.typography.fontFamily,
fontSize: 16,
color: theme.palette.grey[700],
paddingTop: theme.spacing.unit * 2,
[theme.breakpoints.down('md')]: {
display: 'none',
}
},
sidebarDivider: {
margin: '40px 15px'
},
mobileSidebarUpper: {
display: 'none',
fontFamily: theme.typography.fontFamily,
fontSize: 16,
color: theme.palette.grey[700],
marginTop: 10,
[theme.breakpoints.down('md')]: {
display: 'block',
}
},
mobileSidebarLower: {
display: 'none',
fontFamily: theme.typography.fontFamily,
fontSize: 16,
color: theme.palette.grey[700],
marginTop: 30,
[theme.breakpoints.down('md')]: {
display: 'block',
}
},
currentRole: {
lineHeight: '26px',
marginBottom: 20
},
currentRoleSep: {
fontSize: 14,
color: theme.palette.grey[600],
marginRight: 5
},
jobTitle: {
fontWeight: 'bold',
color: theme.palette.grey[800],
marginRight: 5
},
organization: {
fontWeight: 'bold',
color: theme.palette.grey[800],
},
careerStages: {
marginBottom: 20
},
careerStage: {
fontSize: 15,
marginBottom: 10
},
socialMediaIcons: {
display: 'flex',
columnGap: 14,
marginBottom: 20
},
socialMediaIcon: {
flex: 'none',
height: 30,
fill: theme.palette.grey[700],
},
website: {
display: 'inline-flex',
justifyContent: 'center',
color: theme.palette.primary.main,
wordBreak: 'break-all',
marginLeft: 4,
},
websiteIcon: {
flex: 'none',
height: 20,
fill: theme.palette.primary.dark,
marginRight: 6
},
})
export const getUserFromResults = <T extends UsersMinimumInfo>(results: Array<T>|null|undefined): T|null => {
// HOTFIX: Filtering out invalid users
return results?.find(user => !!user.displayName) || results?.[0] || null
}
const UsersProfileFn = ({terms, slug, classes}: {
terms: UsersViewTerms,
slug: string,
classes: ClassesType,
}) => {
const [showSettings, setShowSettings] = useState(false);
const { mutate: updateUser } = useUpdate({
collectionName: "Users",
fragmentName: 'SunshineUsersList',
})
const currentUser = useCurrentUser();
const {loading, results} = useMulti({
terms,
collectionName: "Users",
fragmentName: 'UsersProfile',
enableTotal: false,
});
const user = getUserFromResults(results)
const { query } = useLocation()
// track profile views in local storage
useEffect(() => {
const ls = getBrowserLocalStorage()
// currently only used on the EA Forum
if (forumTypeSetting.get() === 'EAForum' && currentUser && user && currentUser._id !== user._id && ls) {
let from = query.from
let profiles = JSON.parse(ls.getItem('lastViewedProfiles')) || []
// if the profile user is already in the list, then remove them before re-adding them at the end
const profileUserIndex = profiles?.findIndex(profile => profile.userId === user._id)
if (profiles && profileUserIndex !== -1) {
// remember where we originally saw this profile, if necessary
from = from || profiles[profileUserIndex].from
profiles.splice(profileUserIndex, 1)
}
profiles.push({userId: user._id, ...(from && {from})})
// we only bother to save the last 10 profiles
if (profiles.length > 10) profiles.shift()
// save it in local storage
ls.setItem('lastViewedProfiles', JSON.stringify(profiles))
}
}, [currentUser, user, query.from])
const displaySequenceSection = (canEdit: boolean, user: UsersProfile) => {
if (forumTypeSetting.get() === 'AlignmentForum') {
return !!((canEdit && user.afSequenceDraftCount) || user.afSequenceCount) || !!(!canEdit && user.afSequenceCount)
} else {
return !!((canEdit && user.sequenceDraftCount) || user.sequenceCount) || !!(!canEdit && user.sequenceCount)
}
}
const { flash } = useMessages()
const reportUser = async () => {
if (!user) return
await updateUser({ selector: {_id: user._id}, data: { needsReview: true } })
flash({messageString: "Your report has been sent to the moderators"})
}
const renderMeta = () => {
if (!user) return null
const { karma, postCount, commentCount, afPostCount, afCommentCount, afKarma, tagRevisionCount } = user;
const userKarma = karma || 0
const userAfKarma = afKarma || 0
const userPostCount = forumTypeSetting.get() !== 'AlignmentForum' ? postCount || 0 : afPostCount || 0
const userCommentCount = forumTypeSetting.get() !== 'AlignmentForum' ? commentCount || 0 : afCommentCount || 0
return <div className={classes.meta}>
{ forumTypeSetting.get() !== 'AlignmentForum' && <Tooltip title={`${userKarma} karma`}>
<span className={classes.userMetaInfo}>
<StarIcon className={classNames(classes.icon, classes.specificalz)}/>
<Components.MetaInfo title="Karma">
{userKarma}
</Components.MetaInfo>
</span>
</Tooltip>}
{!!userAfKarma && <Tooltip title={`${userAfKarma} karma${(forumTypeSetting.get() !== 'AlignmentForum') ? " on alignmentforum.org" : ""}`}>
<span className={classes.userMetaInfo}>
<Components.OmegaIcon className={classNames(classes.icon, classes.specificalz)}/>
<Components.MetaInfo title="Alignment Karma">
{userAfKarma}
</Components.MetaInfo>
</span>
</Tooltip>}
<Tooltip title={`${userPostCount} posts`}>
<span className={classes.userMetaInfo}>
<DescriptionIcon className={classNames(classes.icon, classes.specificalz)}/>
<Components.MetaInfo title="Posts">
{userPostCount}
</Components.MetaInfo>
</span>
</Tooltip>
<Tooltip title={`${userCommentCount} comments`}>
<span className={classes.userMetaInfo}>
<MessageIcon className={classNames(classes.icon, classes.specificalz)}/>
<Components.MetaInfo title="Comments">
{ userCommentCount }
</Components.MetaInfo>
</span>
</Tooltip>
<Tooltip title={`${tagRevisionCount||0} ${taggingNameIsSet.get() ? taggingNameSetting.get() : 'wiki'} edit${tagRevisionCount === 1 ? '' : 's'}`}>
<span className={classes.userMetaInfo}>
<PencilIcon className={classNames(classes.icon, classes.specificalz)}/>
<Components.MetaInfo>
{ tagRevisionCount||0 }
</Components.MetaInfo>
</span>
</Tooltip>
</div>
}
const isEAForum = forumTypeSetting.get() === 'EAForum'
const render = () => {
const { SunshineNewUsersProfileInfo, SingleColumnSection, SectionTitle, SequencesNewButton, LocalGroupsList,
PostsListSettings, PostsList2, NewConversationButton, TagEditsByUser, NotifyMeButton, DialogGroup,
SectionButton, SettingsButton, ContentItemBody, Loading, Error404, PermanentRedirect, HeadTags,
Typography, ContentStyles } = Components
if (loading) {
return <div className={classNames("page", "users-profile", classes.profilePage)}>
<Loading/>
</div>
}
if (!user || !user._id || user.deleted) {
//eslint-disable-next-line no-console
console.error(`// missing user (_id/slug: ${slug})`);
return <Error404/>
}
if (user.oldSlugs?.includes(slug)) {
return <PermanentRedirect url={userGetProfileUrlFromSlug(user.slug)} />
}
// Does this profile page belong to a likely-spam account?
if (user.spamRiskScore < 0.4) {
if (currentUser?._id === user._id) {
// Logged-in spammer can see their own profile
} else if (currentUser && userCanDo(currentUser, 'posts.moderate.all')) {
// Admins and sunshines can see spammer's profile
} else {
// Anyone else gets a 404 here
// eslint-disable-next-line no-console
console.log(`Not rendering profile page for account with poor spam risk score: ${user.displayName}`);
return <Components.Error404/>
}
}
// on the EA Forum, the user's location links to the Community map
let mapLocationNode = (user.mapLocation && isEAForum) ? <div>
<Link to="/community#individuals" className={classes.mapLocation}>
<LocationIcon className={classes.locationIcon} />
{user.mapLocation.formatted_address}
</Link>
</div> : null
const draftTerms: PostsViewTerms = {view: "drafts", userId: user._id, limit: 4, sortDrafts: currentUser?.sortDrafts || "modifiedAt" }
const unlistedTerms: PostsViewTerms = {view: "unlisted", userId: user._id, limit: 20}
const afSubmissionTerms: PostsViewTerms = {view: "userAFSubmissions", userId: user._id, limit: 4}
const terms: PostsViewTerms = {view: "userPosts", ...query, userId: user._id, authorIsUnreviewed: null};
const sequenceTerms: SequencesViewTerms = {view: "userProfile", userId: user._id, limit:9}
const sequenceAllTerms: SequencesViewTerms = {view: "userProfileAll", userId: user._id, limit:9}
// maintain backward compatibility with bookmarks
const currentSorting = query.sortedBy || query.view || "new"
const currentFilter = query.filter || "all"
const ownPage = currentUser?._id === user._id
const currentShowLowKarma = (parseInt(query.karmaThreshold) !== DEFAULT_LOW_KARMA_THRESHOLD)
const currentIncludeEvents = (query.includeEvents === 'true')
terms.excludeEvents = !currentIncludeEvents && currentFilter !== 'events'
const username = userGetDisplayName(user)
const metaDescription = `${username}'s profile on ${siteNameWithArticleSetting.get()} — ${taglineSetting.get()}`
const nonAFMember = (forumTypeSetting.get()==="AlignmentForum" && !userCanDo(currentUser, "posts.alignment.new"))
// extra profile data that appears on the EA Forum
const jobTitle = user.jobTitle && <span className={classes.jobTitle}>{user.jobTitle}</span>
const currentRoleSep = user.organization ? <span className={classes.currentRoleSep}>
{!jobTitle && 'Works '}at
</span> : ''
const org = user.organization && <span className={classes.organization}>{user.organization}</span>
const currentRole = (jobTitle || org) && <div className={classes.currentRole}>
{jobTitle}<wbr/>{currentRoleSep}<wbr/>{org}
</div>
const careerStage = user.careerStage?.length && <div className={classes.careerStages}>
{user.careerStage.map(stage => {
return <div key={stage} className={classes.careerStage}>
{CAREER_STAGES.find(s => s.value === stage)?.label}
</div>
})}
</div>
// This info is in the righthand sidebar on desktop and moves above the bio on mobile
const sidebarInfoUpperNode = isEAForum && <>
{currentRole}
{careerStage}
</>
const userHasSocialMedia = Object.keys(SOCIAL_MEDIA_PROFILE_FIELDS).some(field => user[field])
const socialMediaIcon = (field) => {
if (!user[field]) return null
return <a key={field} href={`https://${combineUrls(SOCIAL_MEDIA_PROFILE_FIELDS[field],user[field])}`} target="_blank" rel="noopener noreferrer">
<svg viewBox="0 0 24 24" className={classes.socialMediaIcon}>{socialMediaIconPaths[field]}</svg>
</a>
}
// This data is in the righthand sidebar on desktop and moves under the bio on mobile
const sidebarInfoLowerNode = isEAForum && <>
{userHasSocialMedia && <>
<div className={classes.socialMediaIcons}>
{Object.keys(SOCIAL_MEDIA_PROFILE_FIELDS).map(field => socialMediaIcon(field))}
</div>
</>}
{user.website && <a href={`https://${user.website}`} target="_blank" rel="noopener noreferrer" className={classes.website}>
<svg viewBox="0 0 24 24" className={classes.websiteIcon}>{socialMediaIconPaths.website}</svg>
{user.website}
</a>}
</>
return (
<div className={classNames("page", "users-profile", classes.profilePage)}>
<HeadTags
description={metaDescription}
noIndex={(!user.postCount && !user.commentCount) || user.karma <= 0 || user.noindex}
/>
<AnalyticsContext pageContext={"userPage"}>
<div className={classes.centerColumnWrapper}>
{/* Bio Section */}
<SingleColumnSection>
<div className={classes.usernameTitle}>
<div>{username}</div>
{isEAForum && currentUser?._id != user._id && (
<div className={classes.messageBtnDesktop}>
<NewConversationButton user={user} currentUser={currentUser}>
<Button color="primary" variant="contained" className={classes.messageBtn} data-cy="message">
Message
</Button>
</NewConversationButton>
</div>
)}
</div>
{mapLocationNode}
{isEAForum && currentUser?._id != user._id && (
<div className={classes.messageBtnMobile}>
<NewConversationButton user={user} currentUser={currentUser}>
<Button color="primary" variant="contained" className={classes.messageBtn}>
Message
</Button>
</NewConversationButton>
</div>
)}
<Typography variant="body2" className={classes.userInfo}>
{ renderMeta() }
{ currentUser?.isAdmin &&
<div>
<DialogGroup
actions={[]}
trigger={<span>Add RSS</span>}
>
{ /*eslint-disable-next-line react/jsx-pascal-case*/ }
<div><Components.newFeedButton user={user} /></div>
</DialogGroup>
</div>
}
{ isEAForum && userCanEdit(currentUser, user) && <Link to={`/profile/${user.slug}/edit`}>
Edit Profile
</Link>}
{ currentUser && currentUser._id === user._id && <Link to="/manageSubscriptions">
Manage Subscriptions
</Link>}
{ !isEAForum && currentUser?._id != user._id && <NewConversationButton user={user} currentUser={currentUser}>
<a data-cy="message">Message</a>
</NewConversationButton>}
{ <NotifyMeButton
document={user}
subscribeMessage="Subscribe to posts"
unsubscribeMessage="Unsubscribe from posts"
/> }
{userCanEdit(currentUser, user) && <Link to={userGetEditUrl(user)}>
Account Settings
</Link>}
</Typography>
{isEAForum && <div className={classes.mobileSidebarUpper}>
{sidebarInfoUpperNode}
{(currentRole || careerStage) && (user.htmlBio || userHasSocialMedia || user.website) && <Divider className={classes.sidebarDivider} />}
</div>}
{user.htmlBio && <ContentStyles contentType="post">
<ContentItemBody className={classes.bio} dangerouslySetInnerHTML={{__html: user.htmlBio }} description={`user ${user._id} bio`} />
</ContentStyles>}
{isEAForum && user.howOthersCanHelpMe && <>
<h2 className={classes.helpFieldHeading}>How others can help me</h2>
<ContentStyles contentType="post">
<ContentItemBody dangerouslySetInnerHTML={{__html: user.howOthersCanHelpMe.html }} />
</ContentStyles>
</>}
{isEAForum && user.howICanHelpOthers && <>
<h2 className={classes.helpFieldHeading}>How I can help others</h2>
<ContentStyles contentType="post">
<ContentItemBody dangerouslySetInnerHTML={{__html: user.howICanHelpOthers.html }} />
</ContentStyles>
</>}
{isEAForum && !!user.organizerOfGroups?.length && <>
<h2 className={classes.helpFieldHeading}>Organizer of</h2>
<ContentStyles contentType="post">
<div className={classes.organizerOfGroups}>
{user.organizerOfGroups.map(group => {
return <div key={group._id}>
<Link to={`/groups/${group._id}`}>
{group.name}
</Link>
</div>
})}
</div>
</ContentStyles>
</>}
{isEAForum && <div className={classes.mobileSidebarLower}>
{sidebarInfoLowerNode}
</div>}
</SingleColumnSection>
<SingleColumnSection>
<SunshineNewUsersProfileInfo userId={user._id} />
</SingleColumnSection>
{/* Sequences Section */}
{ displaySequenceSection(ownPage, user) && <SingleColumnSection>
<SectionTitle title="Sequences">
{ownPage && <SequencesNewButton />}
</SectionTitle>
<Components.SequencesGridWrapper
terms={ownPage ? sequenceAllTerms : sequenceTerms}
showLoadMore={true}/>
</SingleColumnSection> }
{/* Drafts Section */}
{ ownPage && <SingleColumnSection>
<SectionTitle title="My Drafts">
<Link to={"/newPost"}>
<SectionButton>
<DescriptionIcon /> New Blog Post
</SectionButton>
</Link>
</SectionTitle>
<AnalyticsContext listContext={"userPageDrafts"}>
<Components.PostsList2 hideAuthor showDraftTag={false} terms={draftTerms}/>
<Components.PostsList2 hideAuthor showDraftTag={false} terms={unlistedTerms} showNoResults={false} showLoading={false} showLoadMore={false}/>
</AnalyticsContext>
{hasEventsSetting.get() && <Components.LocalGroupsList
terms={{view: 'userInactiveGroups', userId: currentUser?._id}}
showNoResults={false}
/>}
</SingleColumnSection> }
{/* AF Submissions Section */}
{ownPage && nonAFMember && <SingleColumnSection>
<Components.LWTooltip inlineBlock={false} title="Your posts are pending approval to the Alignment Forum and are only visible to you on the Forum.
They are visible to everyone on LessWrong.">
<SectionTitle title="My Submissions"/>
</Components.LWTooltip>
<Components.PostsList2 hideAuthor showDraftTag={false} terms={afSubmissionTerms}/>
</SingleColumnSection>
}
{/* Posts Section */}
<SingleColumnSection>
<div className={classes.title} onClick={() => setShowSettings(!showSettings)}>
<SectionTitle title={"Posts"}>
<SettingsButton label={`Sorted by ${ SORT_ORDER_OPTIONS[currentSorting].label }`}/>
</SectionTitle>
</div>
{showSettings && <PostsListSettings
hidden={false}
currentSorting={currentSorting}
currentFilter={currentFilter}
currentShowLowKarma={currentShowLowKarma}
currentIncludeEvents={currentIncludeEvents}
/>}
<AnalyticsContext listContext={"userPagePosts"}>
{user.shortformFeedId && <Components.ProfileShortform user={user}/>}
<PostsList2 terms={terms} hideAuthor />
</AnalyticsContext>
</SingleColumnSection>
{/* Groups Section */
(ownPage || currentUser?.isAdmin) && <LocalGroupsList terms={{
view: 'userActiveGroups',
userId: user._id,
limit: 300
}} heading="Organizer of" showNoResults={false} />
}
{/* Wiki Section */}
<SingleColumnSection>
<SectionTitle title={`${taggingNameIsSet.get() ? taggingNameCapitalSetting.get() : 'Wiki'} Contributions`} />
<AnalyticsContext listContext={"userPageWiki"}>
<TagEditsByUser
userId={user._id}
limit={10}
/>
</AnalyticsContext>
</SingleColumnSection>
{/* Comments Sections */}
<AnalyticsContext pageSectionContext="commentsSection">
{ownPage && nonAFMember && <SingleColumnSection>
<Components.LWTooltip inlineBlock={false } title="Your comments are pending approval to the Alignment Forum and are only visible to you on the Forum.
They are visible to everyone on LessWrong.">
<SectionTitle title={"Comment Submissions"} />
</Components.LWTooltip>
<Components.RecentComments terms={{view: 'afSubmissions', authorIsUnreviewed: null, limit: 5, userId: user._id}} />
</SingleColumnSection>}
<SingleColumnSection>
<Link to={`${userGetProfileUrl(user)}/replies`}>
<SectionTitle title={"Comments"} />
</Link>
<Components.RecentComments terms={{view: 'allRecentComments', authorIsUnreviewed: null, limit: 10, userId: user._id}} />
</SingleColumnSection>
</AnalyticsContext>
{currentUser && !user.reviewedByUserId && !user.needsReview && (currentUser._id !== user._id) &&
<SingleColumnSection className={classes.reportUserSection}>
<button className={classes.reportUserBtn} onClick={reportUser}>Report user</button>
</SingleColumnSection>
}
</div>
{isEAForum && <div className={classes.rightSidebar}>
{sidebarInfoUpperNode}
{(currentRole || careerStage) && (userHasSocialMedia || user.website) && <Divider className={classes.sidebarDivider} />}
{sidebarInfoLowerNode}
</div>}
</AnalyticsContext>
</div>
)
}
return render();
}
const UsersProfileComponent = registerComponent(
'UsersProfile', UsersProfileFn, {styles}
);
declare global {
interface ComponentTypes {
UsersProfile: typeof UsersProfileComponent
}
} | the_stack |
* Indicates an object that has resources that can be explicitly disposed.
*/
export interface Disposable {
/**
* Dispose this object's resources.
*/
[Disposable.dispose](): void;
}
export namespace Disposable {
const disposablePrototype: object = Object.defineProperty({ }, Symbol.toStringTag, { configurable: true, value: "Disposable" });
const reportIsDisposableDeprecation = createDeprecation("Use 'Disposable.hasInstance' instead.");
/**
* A well-known symbol used to define an explicit resource disposal method on an object.
*/
export const dispose = Symbol.for("@esfx/disposable:Disposable.dispose");
/**
* Creates a `Disposable` wrapper around a callback used to dispose of a resource.
*/
export function create(dispose: () => void): Disposable {
return Object.setPrototypeOf({ [Disposable.dispose]() { dispose(); } }, disposablePrototype);
}
/**
* Creates a `Disposable` wrapper around a set of other disposables.
* @param disposables An `Iterable` of `Disposable` objects.
*/
export function from(disposables: Iterable<Disposable | null | undefined>) {
const disposablesArray: DisposableRecord[] = [];
let i = 0;
for (const resource of disposables) {
const record = ToDisposableRecord(resource);
if (record === "not-disposable") throw new TypeError("Disposable element expected: disposables");
if (record === undefined) continue;
disposablesArray[i++] = record;
}
return create(() => Dispose(disposablesArray, undefined));
}
/**
* Executes a callback with the provided `Disposable` resource, disposing the resource when the callback completes.
*/
export function use<T extends Disposable | null | undefined, U>(resource: T, callback: (resource: T) => U) {
const record = ToDisposableRecord(resource);
if (record === "not-disposable") throw new TypeError("Disposable expected: resource");
let completion: ErrorCompletion | undefined;
try {
return callback(resource);
}
catch (e) {
completion = { value: e };
}
finally {
Dispose(record && [record], completion);
}
}
export const name = "Disposable";
/**
* Determines whether a value is Disposable.
*/
export function hasInstance(value: unknown): value is Disposable {
return typeof value === "object"
&& value != null
&& dispose in value;
}
Object.defineProperty(Disposable, Symbol.hasInstance, { writable: true, configurable: true, value: hasInstance });
/**
* Determines whether a value is Disposable.
* @deprecated Use `Disposable.hasInstance` instead.
*/
export function isDisposable(value: unknown): value is Disposable {
reportIsDisposableDeprecation();
return hasInstance(value);
}
}
/**
* Indicates an object that has resources that can be explicitly disposed asynchronously.
*/
export interface AsyncDisposable {
/**
* Dispose this object's resources.
*/
[AsyncDisposable.asyncDispose](): Promise<void>;
}
export namespace AsyncDisposable {
const asyncDisposablePrototype: object = Object.defineProperty({ }, Symbol.toStringTag, { configurable: true, value: "AsyncDisposable" });
const reportIsAsyncDisposableDeprecation = createDeprecation("Use 'AsyncDisposable.hasInstance' instead.");
/**
* A well-known symbol used to define an async explicit resource disposal method on an object.
*/
export const asyncDispose = Symbol.for("@esfx/disposable:AsyncDisposable.asyncDispose");
/**
* Creates an `AsyncDisposable` wrapper around a callback used to dispose resources.
*/
export function create(dispose: () => void | PromiseLike<void>): AsyncDisposable {
return Object.setPrototypeOf({ async [AsyncDisposable.asyncDispose]() { await dispose(); } }, asyncDisposablePrototype);
}
/**
* Creates an `AsyncDisposable` wrapper around a set of other disposables.
* @param resources An `Iterable` of `AsyncDisposable` or `Disposable` objects.
*/
export function from(resources: Iterable<AsyncDisposable | Disposable | null | undefined>) {
const disposablesArray: (AsyncDisposableRecord | DisposableRecord)[] = [];
let i = 0;
for (const resource of resources) {
const record = ToAsyncDisposableRecord(resource);
if (record === undefined) continue;
if (record === "not-disposable") throw new TypeError("AsyncDisposable element expected: resources");
disposablesArray[i++] = record;
}
return create(() => AsyncDispose(disposablesArray, undefined));
}
/**
* Executes a callback with the provided `AsyncDisposable` resource, disposing the resource when the callback completes asynchronously.
*/
export async function use<T extends AsyncDisposable | Disposable | null | undefined, U>(resource: T, callback: (resource: T) => U | PromiseLike<U>) {
const record = ToAsyncDisposableRecord(resource);
if (record === "not-disposable") throw new TypeError("AsyncDisposable expected: resource");
let completion: ErrorCompletion | undefined;
try {
return await callback(resource);
}
catch (e) {
completion = { value: e };
}
finally {
await AsyncDispose(record && [record], completion);
}
}
export const name = "AsyncDisposable";
/**
* Determines whether a value is [[AsyncDisposable]].
*/
export function hasInstance(value: unknown): value is AsyncDisposable {
return typeof value === "object"
&& value !== null
&& asyncDispose in value;
}
Object.defineProperty(AsyncDisposable, Symbol.hasInstance, { writable: true, configurable: true, value: hasInstance });
/**
* Determines whether a value is [[AsyncDisposable]].
* @deprecated Use `AsyncDisposable.hasInstance` instead.
*/
export function isAsyncDisposable(value: unknown): value is AsyncDisposable {
reportIsAsyncDisposableDeprecation();
return hasInstance(value);
}
}
const Call: <T, A extends any[], R>(f: (this: T, ...args: A) => R, thisArg: T, ...args: A ) => R = Function.prototype.call.bind(Function.prototype.call);
interface DisposableRecord {
hint: "sync";
resource: object;
disposeFn: (this: object) => void;
}
interface AsyncDisposableRecord {
hint: "async";
resource: object;
asyncDisposeFn: (this: object) => Promise<void>;
}
interface ErrorCompletion {
value: Error;
}
function ToDisposableRecord(resource: Disposable | null | undefined): DisposableRecord | "not-disposable" | undefined {
if (resource !== null && resource !== undefined) {
const disposeFn = typeof resource === "object" ? resource[Disposable.dispose] : undefined;
if (typeof disposeFn !== "function") return "not-disposable";
return { hint: "sync", resource, disposeFn };
}
return undefined;
}
function ToAsyncDisposableRecord(resource: AsyncDisposable | Disposable | null | undefined): AsyncDisposableRecord | DisposableRecord | "not-disposable" | undefined {
if (resource !== null && resource !== undefined) {
if (typeof resource === "object") {
const asyncDisposeFn = (resource as AsyncDisposable)[AsyncDisposable.asyncDispose];
if (asyncDisposeFn === undefined) {
const disposeFn = (resource as Disposable)[Disposable.dispose];
if (typeof disposeFn === "function") {
return { hint: "sync", resource, disposeFn };
}
}
else if (typeof asyncDisposeFn === "function") {
return { hint: "async", resource, asyncDisposeFn };
}
return "not-disposable";
}
}
return undefined;
}
function Dispose(records: (DisposableRecord | undefined)[] | undefined, completion: ErrorCompletion | undefined) {
let errors: any[] | undefined = completion ? [completion.value] : undefined;
let i = completion ? 1 : 0;
if (records) {
for (const record of records) {
try {
if (record) Call(record.disposeFn, record.resource);
}
catch (e) {
errors ||= [];
errors[i++]
}
}
}
if (errors) {
if (errors.length === 1) throw errors[0];
ThrowAggregateError(errors, Dispose);
}
}
async function AsyncDispose(records: (AsyncDisposableRecord | DisposableRecord | undefined)[] | undefined, completion: ErrorCompletion | undefined) {
let errors: any[] | undefined = completion ? [completion.value] : undefined;
let i = completion ? 1 : 0;
if (records) {
for (const record of records) {
try {
if (record) {
await Call(record.hint === "async" ? record.asyncDisposeFn : record.disposeFn, record.resource);
}
}
catch (e) {
errors ||= [];
errors[i++] = e;
}
}
}
if (errors) {
if (errors.length === 1) throw errors[0];
ThrowAggregateError(errors, AsyncDispose);
}
}
function ThrowAggregateError(errors: any[], stackCrawlMark: Function = ThrowAggregateError) {
let error: AggregateError;
if (typeof AggregateError === "function") {
error = new AggregateError(errors);
}
else {
error = new Error("One or more errors occurred") as AggregateError;
error.name = "AggregateError";
error.errors = errors;
}
if (Error.captureStackTrace) {
Error.captureStackTrace(error, stackCrawlMark);
}
throw error;
}
function createDeprecation(message: string) {
let hasReportedWarning = false;
return () => {
if (!hasReportedWarning) {
hasReportedWarning = true;
if (typeof process === "object" && process.emitWarning) {
process.emitWarning(message, "Deprecation");
}
else if (typeof console === "object") {
console.warn(`Deprecation: ${message}`)
}
}
}
} | the_stack |
import * as vscode from 'vscode';
import ActiveConnectionCodeLensProvider from './activeConnectionCodeLensProvider';
import ConnectionController, {
DataServiceEventTypes
} from '../connectionController';
import { createLogger } from '../logging';
import { ExplorerController, ConnectionTreeItem, DatabaseTreeItem } from '../explorer';
import { LanguageServerController } from '../language';
import ExportToLanguageCodeLensProvider from './exportToLanguageCodeLensProvider';
import { OutputChannel, ProgressLocation, TextEditor } from 'vscode';
import playgroundCreateIndexTemplate from '../templates/playgroundCreateIndexTemplate';
import playgroundCreateCollectionTemplate from '../templates/playgroundCreateCollectionTemplate';
import playgroundCreateCollectionWithTSTemplate from '../templates/playgroundCreateCollectionWithTSTemplate';
import {
PlaygroundResult,
ShellExecuteAllResult,
ExportToLanguageAddons,
ExportToLanguageNamespace
} from '../types/playgroundType';
import PlaygroundResultProvider, {
PLAYGROUND_RESULT_SCHEME,
PLAYGROUND_RESULT_URI
} from './playgroundResultProvider';
import playgroundSearchTemplate from '../templates/playgroundSearchTemplate';
import playgroundTemplate from '../templates/playgroundTemplate';
import { StatusView } from '../views';
import TelemetryService from '../telemetry/telemetryService';
import { ConnectionOptions } from '../types/connectionOptionsType';
import CodeActionProvider from './codeActionProvider';
const transpiler = require('bson-transpilers');
const log = createLogger('playground controller');
const getSSLFilePathsFromConnectionModel = (
connectionModelDriverOptions: ConnectionOptions
): {
sslCA?: string | string[];
sslCert?: string | string[];
sslKey?: string | string[];
} => {
const sslFilePaths = {};
['sslCA', 'sslCert', 'sslKey'].forEach((key) => {
if (connectionModelDriverOptions[key]) {
sslFilePaths[key] = connectionModelDriverOptions[key] as (
string | string[]
);
}
});
return sslFilePaths;
};
/**
* This controller manages playground.
*/
export default class PlaygroundController {
_connectionController: ConnectionController;
_activeTextEditor?: TextEditor;
_playgroundResult?: PlaygroundResult;
_context: vscode.ExtensionContext;
_languageServerController: LanguageServerController;
_telemetryService: TelemetryService;
_activeConnectionCodeLensProvider: ActiveConnectionCodeLensProvider;
_outputChannel: OutputChannel;
_connectionString?: string;
_selectedText?: string;
_codeToEvaluate = '';
_isPartialRun: boolean;
_playgroundResultViewColumn?: vscode.ViewColumn;
_playgroundResultTextDocument?: vscode.TextDocument;
_statusView: StatusView;
_playgroundResultViewProvider: PlaygroundResultProvider;
_explorerController: ExplorerController;
_exportToLanguageCodeLensProvider: ExportToLanguageCodeLensProvider;
_codeActionProvider: CodeActionProvider;
constructor(
context: vscode.ExtensionContext,
connectionController: ConnectionController,
languageServerController: LanguageServerController,
telemetryService: TelemetryService,
statusView: StatusView,
playgroundResultViewProvider: PlaygroundResultProvider,
activeConnectionCodeLensProvider: ActiveConnectionCodeLensProvider,
exportToLanguageCodeLensProvider: ExportToLanguageCodeLensProvider,
codeActionProvider: CodeActionProvider,
explorerController: ExplorerController
) {
this._context = context;
this._isPartialRun = false;
this._connectionController = connectionController;
this._languageServerController = languageServerController;
this._telemetryService = telemetryService;
this._statusView = statusView;
this._playgroundResultViewProvider = playgroundResultViewProvider;
this._outputChannel = vscode.window.createOutputChannel(
'Playground output'
);
this._activeConnectionCodeLensProvider = activeConnectionCodeLensProvider;
this._exportToLanguageCodeLensProvider = exportToLanguageCodeLensProvider;
this._codeActionProvider = codeActionProvider;
this._explorerController = explorerController;
this._connectionController.addEventListener(
DataServiceEventTypes.ACTIVE_CONNECTION_CHANGED,
() => {
void this._connectToServiceProvider();
}
);
const onDidChangeActiveTextEditor = (
editor: vscode.TextEditor | undefined
) => {
if (editor?.document.uri.scheme === PLAYGROUND_RESULT_SCHEME) {
this._playgroundResultViewColumn = editor.viewColumn;
this._playgroundResultTextDocument = editor?.document;
}
if (editor?.document.languageId !== 'Log') {
this._activeTextEditor = editor;
log.info('Active editor path', editor?.document.uri?.path);
}
};
vscode.window.onDidChangeActiveTextEditor(onDidChangeActiveTextEditor);
onDidChangeActiveTextEditor(vscode.window.activeTextEditor);
vscode.window.onDidChangeTextEditorSelection(
async (changeEvent: vscode.TextEditorSelectionChangeEvent) => {
if (
changeEvent?.textEditor?.document?.languageId === 'mongodb'
) {
// Sort lines selected as the may be mis-ordered from alt+click.
const sortedSelections = (changeEvent.selections as Array<vscode.Selection>)
.sort((a, b) => (a.start.line > b.start.line ? 1 : -1));
this._selectedText = sortedSelections
.map((item) => this._getSelectedText(item))
.join('\n');
const mode = await this._languageServerController.getExportToLanguageMode({
textFromEditor: this._getAllText(),
selection: sortedSelections[0]
});
this._codeActionProvider.refresh({ selection: sortedSelections[0], mode });
}
}
);
}
async _connectToServiceProvider(): Promise<void> {
// Disconnect if already connected.
await this._languageServerController.disconnectFromServiceProvider();
const dataService = this._connectionController.getActiveDataService();
const connectionId = this._connectionController.getActiveConnectionId();
const connectionModel = this._connectionController
.getActiveConnectionModel();
if (!dataService || !connectionId || !connectionModel) {
this._activeConnectionCodeLensProvider.refresh();
return;
}
const connectionDetails = dataService.getConnectionOptions();
const connectionString = connectionDetails.url;
// We pass file paths to the language server since it doesn't
// handle being passsed buffers well.
// With driver version 4.0 we should be able to remove any use
// of buffers and just pass file paths.
const sslOptionsFilePaths = getSSLFilePathsFromConnectionModel(
connectionModel.getAttributes({ derived: true }).driverOptions
);
const connectionOptions: ConnectionOptions = {
...connectionDetails.options,
...sslOptionsFilePaths
};
await this._languageServerController.connectToServiceProvider({
connectionId,
connectionString,
connectionOptions
});
this._activeConnectionCodeLensProvider.refresh();
}
async _createPlaygroundFileWithContent(
content: string | undefined
): Promise<boolean> {
try {
const document = await vscode.workspace.openTextDocument({
language: 'mongodb',
content
});
await vscode.window.showTextDocument(document);
return true;
} catch (error) {
const printableError = error as { message: string };
void vscode.window.showErrorMessage(
`Unable to create a playground: ${printableError.message}`
);
return false;
}
}
createPlaygroundForSearch(
databaseName: string,
collectionName: string
): Promise<boolean> {
const content = playgroundSearchTemplate
.replace('CURRENT_DATABASE', databaseName)
.replace('CURRENT_COLLECTION', collectionName);
return this._createPlaygroundFileWithContent(content);
}
async createPlaygroundForCreateCollection(
element: ConnectionTreeItem | DatabaseTreeItem
): Promise<boolean> {
const dataService = this._connectionController.getActiveDataService();
let content = playgroundCreateCollectionTemplate;
if (dataService) {
const adminDb = dataService.client.client.db('admin');
const buildInfo = await adminDb.command({ buildInfo: 1 });
if (buildInfo) {
const serverVersion = buildInfo.versionArray[0];
if (serverVersion >= 5) {
content = playgroundCreateCollectionWithTSTemplate;
}
}
}
element.cacheIsUpToDate = false;
if (element instanceof DatabaseTreeItem) {
content = content
.replace('NEW_DATABASE_NAME', element.databaseName)
.replace('Create a new database', 'The current database to use');
}
return this._createPlaygroundFileWithContent(content);
}
createPlaygroundForNewIndex(
databaseName: string,
collectionName: string
): Promise<boolean> {
const content = playgroundCreateIndexTemplate
.replace('CURRENT_DATABASE', databaseName)
.replace('CURRENT_COLLECTION', collectionName);
return this._createPlaygroundFileWithContent(content);
}
async createPlayground(): Promise<boolean> {
const useDefaultTemplate = !!vscode.workspace
.getConfiguration('mdb')
.get('useDefaultTemplateForPlayground');
try {
const document = await vscode.workspace.openTextDocument({
language: 'mongodb',
content: useDefaultTemplate ? playgroundTemplate : ''
});
await vscode.window.showTextDocument(document);
return true;
} catch (error) {
const printableError = error as { message: string };
void vscode.window.showErrorMessage(
`Unable to create a playground: ${printableError.message}`
);
return false;
}
}
async _evaluate(codeToEvaluate: string): Promise<ShellExecuteAllResult> {
const connectionId = this._connectionController.getActiveConnectionId();
if (!connectionId) {
throw new Error('Please connect to a database before running a playground.');
}
this._statusView.showMessage('Getting results...');
// Send a request to the language server to execute scripts from a playground.
const result: ShellExecuteAllResult = await this._languageServerController.executeAll({
codeToEvaluate,
connectionId
});
this._statusView.hideMessage();
this._telemetryService.trackPlaygroundCodeExecuted(
result,
this._isPartialRun,
result ? false : true
);
return result;
}
_getAllText(): string {
return this._activeTextEditor?.document.getText().trim() || '';
}
_getSelectedText(selection: vscode.Range): string {
return this._activeTextEditor?.document.getText(selection) || '';
}
async _evaluateWithCancelModal(): Promise<ShellExecuteAllResult> {
if (!this._connectionController.isCurrentlyConnected()) {
throw new Error('Please connect to a database before running a playground.');
}
try {
const progressResult = await vscode.window.withProgress(
{
location: ProgressLocation.Notification,
title: 'Running MongoDB playground...',
cancellable: true
},
async (progress, token) => {
token.onCancellationRequested(() => {
// If a user clicked the cancel button terminate all playground scripts.
this._languageServerController.cancelAll();
return { outputLines: undefined, result: undefined };
});
// Run all playground scripts.
const result: ShellExecuteAllResult = await this._evaluate(
this._codeToEvaluate
);
return result;
}
);
return progressResult;
} catch (error) {
log.error('Evaluate playground with cancel modal error', error);
return {
outputLines: undefined,
result: undefined
};
}
}
async _openPlaygroundResult(): Promise<void> {
this._playgroundResultViewProvider.setPlaygroundResult(
this._playgroundResult
);
if (!this._playgroundResultTextDocument) {
await this._openResultAsVirtualDocument();
} else {
this._refreshResultAsVirtualDocument();
}
await this._showResultAsVirtualDocument();
if (this._playgroundResultTextDocument) {
const language = this._playgroundResult?.language || 'plaintext';
await vscode.languages.setTextDocumentLanguage(
this._playgroundResultTextDocument,
language
);
}
}
_refreshResultAsVirtualDocument(): void {
this._playgroundResultViewProvider.refresh();
}
async _showResultAsVirtualDocument(): Promise<void> {
await vscode.window.showTextDocument(PLAYGROUND_RESULT_URI, {
preview: false,
preserveFocus: true,
viewColumn: this._playgroundResultViewColumn || vscode.ViewColumn.Beside
});
}
async _openResultAsVirtualDocument(): Promise<void> {
try {
this._playgroundResultTextDocument = await vscode.workspace.openTextDocument(
PLAYGROUND_RESULT_URI
);
} catch (error) {
const printableError = error as { message: string };
void vscode.window.showErrorMessage(
`Unable to open a result document: ${printableError.message}`
);
}
}
async _evaluatePlayground(): Promise<boolean> {
const shouldConfirmRunAll = vscode.workspace
.getConfiguration('mdb')
.get('confirmRunAll');
if (!this._connectionController.isCurrentlyConnected()) {
void vscode.window.showErrorMessage(
'Please connect to a database before running a playground.'
);
return false;
}
if (shouldConfirmRunAll === true) {
const name = this._connectionController.getActiveConnectionName();
const confirmRunAll = await vscode.window.showInformationMessage(
`Are you sure you want to run this playground against ${name}? This confirmation can be disabled in the extension settings.`,
{ modal: true },
'Yes'
);
if (confirmRunAll !== 'Yes') {
return false;
}
}
this._outputChannel.clear();
const evaluateResponse: ShellExecuteAllResult = await this._evaluateWithCancelModal();
if (evaluateResponse?.outputLines?.length) {
for (const line of evaluateResponse.outputLines) {
this._outputChannel.appendLine(line.content);
}
this._outputChannel.show(true);
}
if (
!evaluateResponse ||
(!evaluateResponse.outputLines && !evaluateResponse.result)
) {
return false;
}
this._playgroundResult = evaluateResponse.result;
this._explorerController.refresh();
await this._openPlaygroundResult();
return true;
}
runSelectedPlaygroundBlocks(): Promise<boolean> {
if (!this._selectedText) {
void vscode.window.showInformationMessage(
'Please select one or more lines in the playground.'
);
return Promise.resolve(true);
}
this._isPartialRun = true;
this._codeToEvaluate = this._selectedText;
return this._evaluatePlayground();
}
runAllPlaygroundBlocks(): Promise<boolean> {
if (
!this._activeTextEditor ||
this._activeTextEditor.document.languageId !== 'mongodb'
) {
void vscode.window.showErrorMessage(
"Please open a '.mongodb' playground file before running it."
);
return Promise.resolve(false);
}
this._isPartialRun = false;
this._codeToEvaluate = this._getAllText();
return this._evaluatePlayground();
}
runAllOrSelectedPlaygroundBlocks(): Promise<boolean> {
if (
!this._activeTextEditor ||
this._activeTextEditor.document.languageId !== 'mongodb'
) {
void vscode.window.showErrorMessage(
"Please open a '.mongodb' playground file before running it."
);
return Promise.resolve(false);
}
const selections = this._activeTextEditor.selections;
if (
!selections ||
!Array.isArray(selections) ||
(selections.length === 1 && this._getSelectedText(selections[0]) === '')
) {
this._isPartialRun = false;
this._codeToEvaluate = this._getAllText();
} else if (this._selectedText) {
this._isPartialRun = true;
this._codeToEvaluate = this._selectedText;
}
return this._evaluatePlayground();
}
async openPlayground(filePath: string): Promise<boolean> {
try {
const document = await vscode.workspace.openTextDocument(filePath);
await vscode.window.showTextDocument(document);
return true;
} catch (error) {
const printableError = error as { message: string };
void vscode.window.showErrorMessage(
`Unable to open a playground: ${printableError.message}`
);
return false;
}
}
changeExportToLanguageAddons(exportToLanguageAddons: ExportToLanguageAddons): Promise<boolean> {
this._exportToLanguageCodeLensProvider.refresh(exportToLanguageAddons);
return this._transpile();
}
async exportToLanguage(language: string): Promise<boolean> {
this._exportToLanguageCodeLensProvider.refresh({
...this._exportToLanguageCodeLensProvider._exportToLanguageAddons,
textFromEditor: this._getAllText(),
selectedText: this._selectedText,
selection: this._codeActionProvider.selection,
language,
mode: this._codeActionProvider.mode
});
return this._transpile();
}
async _transpile(): Promise<boolean> {
const {
textFromEditor,
selectedText,
selection,
importStatements,
driverSyntax,
builders,
language
} = this._exportToLanguageCodeLensProvider._exportToLanguageAddons;
log.info(`Start export to ${language} language`);
if (!textFromEditor || !selection) {
void vscode.window.showInformationMessage(
'Please select one or more lines in the playground.'
);
return true;
}
try {
let transpiledExpression = '';
let imports = '';
let namespace: ExportToLanguageNamespace = {
databaseName: null,
collectionName: null
};
if (driverSyntax) {
namespace = await this._languageServerController.getNamespaceForSelection({
textFromEditor,
selection
});
const dataService = this._connectionController.getActiveDataService();
const connectionDetails = dataService?.getConnectionOptions();
const toCompile = {
aggregation: selectedText,
options: {
collection: namespace.collectionName,
database: namespace.databaseName,
uri: connectionDetails?.url
}
};
transpiledExpression = transpiler.shell[language].compileWithDriver(toCompile, builders);
} else {
transpiledExpression = transpiler.shell[language].compile(selectedText, builders, false);
}
if (importStatements) {
imports = transpiler.shell[language].getImports(driverSyntax);
}
this._playgroundResult = {
namespace: namespace.databaseName && namespace.collectionName
? `${namespace.databaseName}.${namespace.collectionName}`
: null,
type: null,
content: imports ? `${imports}\n\n${transpiledExpression}` : transpiledExpression,
language
};
log.info(`Export to ${language} language result`, this._playgroundResult);
await this._openPlaygroundResult();
} catch (error) {
const printableError = error as { message: string };
log.error(`Export to ${language} language error`, error);
void vscode.window.showErrorMessage(
`Unable to export to ${language} language: ${printableError.message}`
);
}
return true;
}
deactivate(): void {
this._connectionController.removeEventListener(
DataServiceEventTypes.ACTIVE_CONNECTION_CHANGED,
() => {
// No action is required after removing the listener.
}
);
}
} | the_stack |
import $ from 'mdui.jq/es/$';
import extend from 'mdui.jq/es/functions/extend';
import { JQ } from 'mdui.jq/es/JQ';
import 'mdui.jq/es/methods/addClass';
import 'mdui.jq/es/methods/each';
import 'mdui.jq/es/methods/find';
import 'mdui.jq/es/methods/first';
import 'mdui.jq/es/methods/hasClass';
import 'mdui.jq/es/methods/off';
import 'mdui.jq/es/methods/on';
import 'mdui.jq/es/methods/one';
import 'mdui.jq/es/methods/removeClass';
import 'mdui.jq/es/methods/width';
import Selector from 'mdui.jq/es/types/Selector';
import mdui from '../../mdui';
import '../../jq_extends/methods/transitionEnd';
import '../../jq_extends/static/hideOverlay';
import '../../jq_extends/static/lockScreen';
import '../../jq_extends/static/showOverlay';
import '../../jq_extends/static/throttle';
import '../../jq_extends/static/unlockScreen';
import { componentEvent } from '../../utils/componentEvent';
import { $window } from '../../utils/dom';
declare module '../../interfaces/MduiStatic' {
interface MduiStatic {
/**
* Drawer 组件
*
* 请通过 `new mdui.Drawer()` 调用
*/
Drawer: {
/**
* 实例化 Drawer 组件
* @param selector CSS 选择器、或 DOM 元素、或 JQ 对象
* @param options 配置参数
*/
new (
selector: Selector | HTMLElement | ArrayLike<HTMLElement>,
options?: OPTIONS,
): Drawer;
};
}
}
type OPTIONS = {
/**
* 打开抽屉栏时是否显示遮罩层。该参数只对中等屏幕及以上的设备有效,在超小屏和小屏设备上始终会显示遮罩层。
*/
overlay?: boolean;
/**
* 是否启用滑动手势。
*/
swipe?: boolean;
};
type STATE = 'opening' | 'opened' | 'closing' | 'closed';
type EVENT = 'open' | 'opened' | 'close' | 'closed';
const DEFAULT_OPTIONS: OPTIONS = {
overlay: false,
swipe: false,
};
class Drawer {
/**
* drawer 元素的 JQ 对象
*/
public $element: JQ;
/**
* 配置参数
*/
public options: OPTIONS = extend({}, DEFAULT_OPTIONS);
/**
* 当前是否显示着遮罩层
*/
private overlay = false;
/**
* 抽屉栏的位置
*/
private position: 'left' | 'right';
/**
* 当前抽屉栏状态
*/
private state: STATE;
public constructor(
selector: Selector | HTMLElement | ArrayLike<HTMLElement>,
options: OPTIONS = {},
) {
this.$element = $(selector).first();
extend(this.options, options);
this.position = this.$element.hasClass('mdui-drawer-right')
? 'right'
: 'left';
if (this.$element.hasClass('mdui-drawer-close')) {
this.state = 'closed';
} else if (this.$element.hasClass('mdui-drawer-open')) {
this.state = 'opened';
} else if (this.isDesktop()) {
this.state = 'opened';
} else {
this.state = 'closed';
}
// 浏览器窗口大小调整时
$window.on(
'resize',
$.throttle(() => {
if (this.isDesktop()) {
// 由手机平板切换到桌面时
// 如果显示着遮罩,则隐藏遮罩
if (this.overlay && !this.options.overlay) {
$.hideOverlay();
this.overlay = false;
$.unlockScreen();
}
// 没有强制关闭,则状态为打开状态
if (!this.$element.hasClass('mdui-drawer-close')) {
this.state = 'opened';
}
} else if (!this.overlay && this.state === 'opened') {
// 由桌面切换到手机平板时。如果抽屉栏是打开着的且没有遮罩层,则关闭抽屉栏
if (this.$element.hasClass('mdui-drawer-open')) {
$.showOverlay();
this.overlay = true;
$.lockScreen();
$('.mdui-overlay').one('click', () => this.close());
} else {
this.state = 'closed';
}
}
}, 100),
);
// 绑定关闭按钮事件
this.$element.find('[mdui-drawer-close]').each((_, close) => {
$(close).on('click', () => this.close());
});
this.swipeSupport();
}
/**
* 是否是桌面设备
*/
private isDesktop(): boolean {
return $window.width() >= 1024;
}
/**
* 滑动手势支持
*/
private swipeSupport(): void {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const that = this;
// 抽屉栏滑动手势控制
let openNavEventHandler: (event: Event) => void;
let touchStartX: number;
let touchStartY: number;
let swipeStartX: number;
let swiping: null | 'opening' | 'closing' = null;
let maybeSwiping = false;
const $body = $('body');
// 手势触发的范围
const swipeAreaWidth = 24;
function setPosition(translateX: number): void {
const rtlTranslateMultiplier = that.position === 'right' ? -1 : 1;
const transformCSS = `translate(${
-1 * rtlTranslateMultiplier * translateX
}px, 0) !important;`;
const transitionCSS = 'initial !important;';
that.$element.css(
'cssText',
`transform: ${transformCSS}; transition: ${transitionCSS};`,
);
}
function cleanPosition(): void {
that.$element[0].style.transform = '';
that.$element[0].style.webkitTransform = '';
that.$element[0].style.transition = '';
that.$element[0].style.webkitTransition = '';
}
function getMaxTranslateX(): number {
return that.$element.width() + 10;
}
function getTranslateX(currentX: number): number {
return Math.min(
Math.max(
swiping === 'closing'
? swipeStartX - currentX
: getMaxTranslateX() + swipeStartX - currentX,
0,
),
getMaxTranslateX(),
);
}
function onBodyTouchEnd(event?: Event): void {
if (swiping) {
let touchX = (event as TouchEvent).changedTouches[0].pageX;
if (that.position === 'right') {
touchX = $body.width() - touchX;
}
const translateRatio = getTranslateX(touchX) / getMaxTranslateX();
maybeSwiping = false;
const swipingState = swiping;
swiping = null;
if (swipingState === 'opening') {
if (translateRatio < 0.92) {
cleanPosition();
that.open();
} else {
cleanPosition();
}
} else {
if (translateRatio > 0.08) {
cleanPosition();
that.close();
} else {
cleanPosition();
}
}
$.unlockScreen();
} else {
maybeSwiping = false;
}
$body.off({
// eslint-disable-next-line @typescript-eslint/no-use-before-define
touchmove: onBodyTouchMove,
touchend: onBodyTouchEnd,
// eslint-disable-next-line @typescript-eslint/no-use-before-define
touchcancel: onBodyTouchMove,
});
}
function onBodyTouchMove(event: Event): void {
let touchX = (event as TouchEvent).touches[0].pageX;
if (that.position === 'right') {
touchX = $body.width() - touchX;
}
const touchY = (event as TouchEvent).touches[0].pageY;
if (swiping) {
setPosition(getTranslateX(touchX));
} else if (maybeSwiping) {
const dXAbs = Math.abs(touchX - touchStartX);
const dYAbs = Math.abs(touchY - touchStartY);
const threshold = 8;
if (dXAbs > threshold && dYAbs <= threshold) {
swipeStartX = touchX;
swiping = that.state === 'opened' ? 'closing' : 'opening';
$.lockScreen();
setPosition(getTranslateX(touchX));
} else if (dXAbs <= threshold && dYAbs > threshold) {
onBodyTouchEnd();
}
}
}
function onBodyTouchStart(event: Event): void {
touchStartX = (event as TouchEvent).touches[0].pageX;
if (that.position === 'right') {
touchStartX = $body.width() - touchStartX;
}
touchStartY = (event as TouchEvent).touches[0].pageY;
if (that.state !== 'opened') {
if (
touchStartX > swipeAreaWidth ||
openNavEventHandler !== onBodyTouchStart
) {
return;
}
}
maybeSwiping = true;
$body.on({
touchmove: onBodyTouchMove,
touchend: onBodyTouchEnd,
touchcancel: onBodyTouchMove,
});
}
function enableSwipeHandling(): void {
if (!openNavEventHandler) {
$body.on('touchstart', onBodyTouchStart);
openNavEventHandler = onBodyTouchStart;
}
}
if (this.options.swipe) {
enableSwipeHandling();
}
}
/**
* 触发组件事件
* @param name
*/
private triggerEvent(name: EVENT): void {
componentEvent(name, 'drawer', this.$element, this);
}
/**
* 动画结束回调
*/
private transitionEnd(): void {
if (this.$element.hasClass('mdui-drawer-open')) {
this.state = 'opened';
this.triggerEvent('opened');
} else {
this.state = 'closed';
this.triggerEvent('closed');
}
}
/**
* 是否处于打开状态
*/
private isOpen(): boolean {
return this.state === 'opening' || this.state === 'opened';
}
/**
* 打开抽屉栏
*/
public open(): void {
if (this.isOpen()) {
return;
}
this.state = 'opening';
this.triggerEvent('open');
if (!this.options.overlay) {
$('body').addClass(`mdui-drawer-body-${this.position}`);
}
this.$element
.removeClass('mdui-drawer-close')
.addClass('mdui-drawer-open')
.transitionEnd(() => this.transitionEnd());
if (!this.isDesktop() || this.options.overlay) {
this.overlay = true;
$.showOverlay().one('click', () => this.close());
$.lockScreen();
}
}
/**
* 关闭抽屉栏
*/
public close(): void {
if (!this.isOpen()) {
return;
}
this.state = 'closing';
this.triggerEvent('close');
if (!this.options.overlay) {
$('body').removeClass(`mdui-drawer-body-${this.position}`);
}
this.$element
.addClass('mdui-drawer-close')
.removeClass('mdui-drawer-open')
.transitionEnd(() => this.transitionEnd());
if (this.overlay) {
$.hideOverlay();
this.overlay = false;
$.unlockScreen();
}
}
/**
* 切换抽屉栏打开/关闭状态
*/
public toggle(): void {
this.isOpen() ? this.close() : this.open();
}
/**
* 返回当前抽屉栏的状态。共包含四种状态:`opening`、`opened`、`closing`、`closed`
*/
public getState(): STATE {
return this.state;
}
}
mdui.Drawer = Drawer; | the_stack |
import * as vscode from 'vscode';
import { Utils } from 'vscode-uri';
import { FileSystem, Output, JsonValidator } from '../../utils';
import { Schematic } from './schematic';
import { CollectionJsonSchema, CollectionSchematicJsonSchema } from './json-schemas';
import { findCollectionUri } from './find-collection';
/** Configuration needed to load a schematic */
interface SchematicConfig {
name: string;
collectionName: string;
description?: string | undefined;
uri?: vscode.Uri;
collectionUri?: vscode.Uri;
}
export class Collection {
schematicsChoices: vscode.QuickPickItem[] = [];
private name: string;
private schematics = new Map<string, Schematic | undefined>();
constructor(name: string) {
this.name = name;
}
/**
* Load the collection.
* **Must** be called after each `new Collection()`
* (delegated because `async` is not possible on a constructor).
*/
async init(workspaceFolder: vscode.WorkspaceFolder, uri: vscode.Uri): Promise<vscode.FileSystemWatcher | undefined> {
const config = this.validateConfig(await FileSystem.parseJsonFile(uri));
await this.setSchematics(workspaceFolder, config, uri);
/* Only watch local schematics */
if (!uri.path.includes('node_modules') && (uri.scheme === 'file')) {
return vscode.workspace.createFileSystemWatcher(uri.fsPath);
}
return undefined;
}
/**
* Only load the collection's schematics' names (used for sub-collections only).
*/
async initSchematicsNames(uri: vscode.Uri): Promise<string[]> {
const rawConfig = await FileSystem.parseJsonFile(uri);
return Object.keys(JsonValidator.object(JsonValidator.object(rawConfig)?.['schematics']) ?? {});
}
/**
* Get collection's name
*/
getName(): string {
return this.name;
}
/**
* Get all collection's schematics' names
*/
getSchematicsNames(): string[] {
return Array.from(this.schematics.keys()).sort();
}
/**
* Get a schematic from cache, or load it.
*/
getSchematic(name: string): Schematic | undefined {
return this.schematics.get(name);
}
/**
* Get full schematic name (eg. `@schematics/angular:component`)
*/
private getFullSchematicName(name: string): string {
return `${this.name}:${name}`;
}
/**
* Validate collection.json
*/
private validateConfig(config: unknown): CollectionJsonSchema {
const configObject = JsonValidator.object(config);
/* Validate `extends` property */
const rootExtendsString = JsonValidator.string(configObject?.['extends']);
const rootExtends = JsonValidator.array(configObject?.['extends'], 'string')
?? (rootExtendsString ? [rootExtendsString] : [])
?? [];
/* Validate `schematics` property */
const schematics = new Map(Object.entries(JsonValidator.object(configObject?.['schematics']) ?? {})
.map(([name, rawConfig]) => {
const config = JsonValidator.object(rawConfig);
return [name, {
schema: JsonValidator.string(config?.['schema']),
description: JsonValidator.string(config?.['description']),
hidden: JsonValidator.boolean(config?.['hidden']),
private: JsonValidator.boolean(config?.['private']),
extends: JsonValidator.string(config?.['extends']),
}] as [string, CollectionSchematicJsonSchema];
})
.filter(([name, config]) => {
if (!config.schema && !config?.extends) {
Output.logWarning(`"${this.name}:${name}" schematic does not have a "schema" string property, so it is dropped.`);
return false;
}
return true;
}));
if (schematics.size === 0) {
throw new Error(`No schematic found for "${this.name}" collection, so it is dropped.`);
}
return {
extends: rootExtends,
schematics,
};
}
/**
* Set all schematics' configuration of the collection.
*/
private async setSchematics(workspaceFolder: vscode.WorkspaceFolder, config: CollectionJsonSchema, uri: vscode.Uri): Promise<void> {
/* Start from scratch as the function can be called again via watcher */
this.schematics.clear();
this.schematicsChoices = [];
const allSchematics = new Map<string, CollectionSchematicJsonSchema & { collectionUri?: vscode.Uri }>();
const extendedSchematicDescription = `Schematic inherited from`;
/* A collection can extend other ones */
for (const parentCollectionName of config.extends) {
/* Avoid infinite recursion */
if (parentCollectionName !== this.name) {
const parentCollection = new Collection(parentCollectionName);
const parentCollectionUri = await findCollectionUri(workspaceFolder, parentCollectionName);
if (!parentCollectionUri) {
Output.logWarning(`"${this.name}" collection wants to inherit from "${parentCollectionName}" collection, but the latest cannot be found.`);
} else {
const parentSchematicsNames = await parentCollection.initSchematicsNames(parentCollectionUri);
for (const parentSchematicName of parentSchematicsNames) {
allSchematics.set(parentSchematicName, {
extends: `${parentCollectionName}:${parentSchematicName}`,
collectionUri: parentCollectionUri,
});
}
}
}
}
/* Collection's own schematics */
for (const [schematicName, schematicConfig] of config.schematics) {
allSchematics.set(schematicName, schematicConfig);
}
Output.logInfo(`${allSchematics.size} schematic(s) detected for "${this.name}" collection: ${Array.from(allSchematics).map(([name]) => name).join(', ')}`);
const schematics = Array.from(allSchematics)
/* Remove internal schematics */
.filter(([, config]) => !config.hidden && !config.private)
/* Remove `ng-add` schematics are they are not relevant for the extension */
.filter(([name]) => (name !== 'ng-add'));
if (schematics.length === 0) {
throw new Error(`No public generation schematic found for "${this.name}" collection, so it is dropped.`);
}
Output.logInfo(`${schematics.length} filtered schematic(s) keeped for "${this.name}" collection: ${schematics.map(([name]) => name).join(', ')}`);
for (const [name, config] of schematics) {
const schematicFullName = this.getFullSchematicName(name);
Output.logInfo(`Loading "${schematicFullName}" schematic`);
let schematicConfig: SchematicConfig | undefined = undefined;
/* Some collection extends another one */
if (config.extends) {
const [collectionName] = config.extends.split(':');
if (!collectionName) {
Output.logWarning(`"${this.name}" collection's name is invalid.`);
} else {
const collectionUri = config?.collectionUri ?? await findCollectionUri(workspaceFolder, collectionName);
if (!collectionUri) {
Output.logWarning(`"${this.name}" collection wants to inherit "${name}" schematic from "${config.extends}" collection, but the latest cannot be found.`);
} else {
schematicConfig = {
name,
collectionName: this.name,
description: `${extendedSchematicDescription} "${collectionName}"`,
collectionUri: collectionUri,
};
}
}
} else if (config.schema) {
const schematicUri = vscode.Uri.joinPath(Utils.dirname(uri), config.schema);
schematicConfig = {
name,
collectionName: this.name,
description: config.description,
uri: schematicUri,
};
}
if (schematicConfig) {
const schematicInstance = new Schematic(schematicConfig.name, schematicConfig.collectionName);
try {
await schematicInstance.init({
uri: schematicConfig.uri,
collectionUri: schematicConfig.collectionUri,
});
this.schematics.set(name, schematicInstance);
this.setSchematicChoice(schematicConfig);
} catch {
Output.logError(`"${schematicFullName}" schematic loading failed.`);
}
}
}
this.schematicsChoices.sort((a, b) => {
if (a.description && b.description) {
// Collection's own schematics first, then extended ones
if ((a.description.startsWith(extendedSchematicDescription)) && (!b.description.startsWith(extendedSchematicDescription))) {
return 1;
} else if ((!a.description.startsWith(extendedSchematicDescription)) && (b.description.startsWith(extendedSchematicDescription))) {
return -1;
}
}
// Otherwise, alphabetical sort
return a.label.localeCompare(b.label);
});
}
/**
* Add schematic's choice (for caching)
*/
private setSchematicChoice(schematicConfig: SchematicConfig): void {
this.schematicsChoices.push((schematicConfig.description !== undefined) ? {
label: schematicConfig.name,
description: schematicConfig.description,
} : {
label: schematicConfig.name,
});
}
} | the_stack |
import abiDecoder from 'abi-decoder'
import Web3 from 'web3'
import { HttpProvider } from 'web3-core'
import { JsonRpcPayload, JsonRpcResponse } from 'web3-core-helpers'
import { PrefixedHexString } from 'ethereumjs-util'
import { EventData } from 'web3-eth-contract'
import { gsnRuntimeVersion } from '@opengsn/common'
import { LoggerInterface } from '@opengsn/common/dist/LoggerInterface'
import relayHubAbi from '@opengsn/common/dist/interfaces/IRelayHub.json'
import { GsnTransactionDetails } from '@opengsn/common/dist/types/GsnTransactionDetails'
import { AccountKeypair } from './AccountManager'
import { GsnEvent } from './GsnEvents'
import { _dumpRelayingResult, GSNUnresolvedConstructorInput, RelayClient, RelayingResult } from './RelayClient'
import { GSNConfig } from './GSNConfigurator'
import { Web3ProviderBaseInterface } from '@opengsn/common/dist/types/Aliases'
import { TransactionRejectedByPaymaster, TransactionRelayed } from '@opengsn/common/dist/types/GSNContractsDataTypes'
abiDecoder.addABI(relayHubAbi)
export type JsonRpcCallback = (error: Error | null, result?: JsonRpcResponse) => void
interface ISendAsync {
sendAsync?: any
}
/**
* This data can later be used to optimize creation of Transaction Receipts
*/
interface SubmittedRelayRequestInfo {
submissionBlock: number
validUntilTime: string
}
const TX_FUTURE = 'tx-future'
const TX_NOTFOUND = 'tx-notfound'
const TX_NOTSENTHERE = 'tx-notsenthere'
// TODO: stop faking the HttpProvider implementation - it won't work for any other 'origProvider' type
export class RelayProvider implements HttpProvider, Web3ProviderBaseInterface {
protected readonly origProvider: HttpProvider & ISendAsync
private readonly origProviderSend: any
protected readonly web3: Web3
protected readonly submittedRelayRequests = new Map<string, SubmittedRelayRequestInfo>()
protected config!: GSNConfig
readonly relayClient: RelayClient
logger!: LoggerInterface
static newProvider (input: GSNUnresolvedConstructorInput): RelayProvider {
return new RelayProvider(new RelayClient(input))
}
constructor (
relayClient: RelayClient
) {
if ((relayClient as any).send != null) {
throw new Error('Using new RelayProvider() constructor directly is deprecated.\nPlease create provider using RelayProvider.newProvider({})')
}
this.relayClient = relayClient
this.web3 = new Web3(relayClient.getUnderlyingProvider() as HttpProvider)
// TODO: stop faking the HttpProvider implementation
this.origProvider = this.relayClient.getUnderlyingProvider() as HttpProvider
this.host = this.origProvider.host
this.connected = this.origProvider.connected
this.logger = this.relayClient.logger
if (typeof this.origProvider.sendAsync === 'function') {
this.origProviderSend = this.origProvider.sendAsync.bind(this.origProvider)
} else {
this.origProviderSend = this.origProvider.send.bind(this.origProvider)
}
this._delegateEventsApi()
}
sendId = 1000
// async wrapper for calling origSend
async origSend (method: string, params: any[]): Promise<any> {
return await new Promise((resolve, reject) => {
this.origProviderSend({
id: this.sendId++,
jsonrpc: '2.0',
method,
params
}, (error: Error | null, result?: JsonRpcResponse) => {
if (error != null) {
reject(error)
} else {
resolve(result?.result)
}
})
})
}
async init (): Promise<this> {
await this.relayClient.init()
this.config = this.relayClient.config
this.logger.info(`Created new RelayProvider ver.${gsnRuntimeVersion}`)
return this
}
registerEventListener (handler: (event: GsnEvent) => void): void {
this.relayClient.registerEventListener(handler)
}
unregisterEventListener (handler: (event: GsnEvent) => void): void {
this.relayClient.unregisterEventListener(handler)
}
_delegateEventsApi (): void {
// If the subprovider is a ws or ipc provider, then register all its methods on this provider
// and delegate calls to the subprovider. This allows subscriptions to work.
['on', 'removeListener', 'removeAllListeners', 'reset', 'disconnect', 'addDefaultEvents', 'once', 'reconnect'].forEach(func => {
// @ts-ignore
if (this.origProvider[func] !== undefined) {
// @ts-ignore
this[func] = this.origProvider[func].bind(this.origProvider)
}
})
}
send (payload: JsonRpcPayload, callback: JsonRpcCallback): void {
if (this._useGSN(payload)) {
if (payload.method === 'eth_sendTransaction') {
if (payload.params[0].to === undefined) {
callback(new Error('GSN cannot relay contract deployment transactions. Add {from: accountWithEther, useGSN: false}.'))
return
}
void this._ethSendTransaction(payload, callback)
return
}
if (payload.method === 'eth_getTransactionReceipt') {
void this._ethGetTransactionReceipt(payload, callback)
return
}
if (payload.method === 'eth_getTransactionByHash') {
void this._ethGetTransactionByHash(payload, callback)
return
}
if (payload.method === 'eth_accounts') {
this._getAccounts(payload, callback)
}
}
this.origProviderSend(payload, (error: Error | null, result?: JsonRpcResponse) => {
callback(error, result)
})
}
_ethGetTransactionReceiptWithTransactionHash (payload: JsonRpcPayload, callback: JsonRpcCallback): void {
this.logger.info('calling sendAsync' + JSON.stringify(payload))
this.origProviderSend(payload, (error: Error | null, rpcResponse?: JsonRpcResponse): void => {
// Sometimes, ganache seems to return 'false' for 'no error' (breaking TypeScript declarations)
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
if (error) {
callback(error, rpcResponse)
return
}
if (rpcResponse == null || rpcResponse.result == null) {
callback(error, rpcResponse)
return
}
rpcResponse.result = this._getTranslatedGsnResponseResult(rpcResponse.result)
callback(error, rpcResponse)
})
}
/**
* pack promise call as a jsonrpc callback
* @param promise the promise request. return value is "result" for the callback
* @param payload original payload. used to copy rpc param (jsonrpc, id)
* @param callback callback to call result or error (for exception)
*/
asCallback (promise: Promise<any>, payload: JsonRpcPayload, callback: JsonRpcCallback): void {
promise
.then(result => {
callback(null, {
result,
// @ts-ignore
id: payload.id,
jsonrpc: payload.jsonrpc
})
})
.catch(error => {
const err: any = {
error,
// @ts-ignore
id: payload.id,
jsonrpc: payload.jsonrpc
}
callback(err)
})
}
async _ethGetTransactionByHash (payload: JsonRpcPayload, callback: JsonRpcCallback): Promise<void> {
const relayRequestID = payload.params[0]
let txHash = await this._getTransactionIdFromRequestId(relayRequestID)
if (!txHash.startsWith('0x')) {
txHash = relayRequestID
}
const tx = await this.origSend('eth_getTransactionByHash', [txHash])
// must return exactly what was requested..
tx.hash = relayRequestID
tx.actualTransactionHash = tx.hash
this.asCallback(Promise.resolve(tx), payload, callback)
}
/**
* The ID can be either a RelayRequestID which requires event-based lookup or Transaction Hash that goes through
* @param payload
* @param callback
*/
async _ethGetTransactionReceipt (payload: JsonRpcPayload, callback: JsonRpcCallback): Promise<void> {
const id = (typeof payload.id === 'string' ? parseInt(payload.id) : payload.id) ?? -1
const relayRequestID = payload.params[0] as string
const submissionDetails = this.submittedRelayRequests.get(relayRequestID)
if (submissionDetails == null) {
this._ethGetTransactionReceiptWithTransactionHash(payload, callback)
return
}
try {
const result = await this._createTransactionReceiptForRelayRequestID(relayRequestID, submissionDetails)
const rpcResponse = {
id,
result,
jsonrpc: '2.0'
}
callback(null, rpcResponse)
} catch (error: any) {
callback(error, undefined)
}
}
async _ethSendTransaction (payload: JsonRpcPayload, callback: JsonRpcCallback): Promise<void> {
this.logger.info('calling sendAsync' + JSON.stringify(payload))
let gsnTransactionDetails: GsnTransactionDetails
try {
gsnTransactionDetails = this._fixGasFees(payload.params[0])
} catch (e: any) {
this.logger.error(e)
callback(e)
return
}
try {
const r = await this.relayClient.relayTransaction(gsnTransactionDetails)
void this._onRelayTransactionFulfilled(r, payload, callback)
} catch (reason) {
void this._onRelayTransactionRejected(reason, callback)
}
}
async _onRelayTransactionFulfilled (relayingResult: RelayingResult, payload: JsonRpcPayload, callback: JsonRpcCallback): Promise<void> {
if (relayingResult.relayRequestID != null) {
const jsonRpcSendResult = this._convertRelayRequestIdToRpcSendResponse(relayingResult.relayRequestID, payload)
this.cacheSubmittedTransactionDetails(relayingResult)
callback(null, jsonRpcSendResult)
} else {
const message = `Failed to relay call. Results:\n${_dumpRelayingResult(relayingResult)}`
this.logger.error(message)
callback(new Error(message))
}
}
async _onRelayTransactionRejected (reason: any, callback: JsonRpcCallback): Promise<void> {
const reasonStr = reason instanceof Error ? reason.message : JSON.stringify(reason)
const msg = `Rejected relayTransaction call with reason: ${reasonStr}`
this.logger.info(msg)
callback(new Error(msg))
}
_convertRelayRequestIdToRpcSendResponse (relayRequestID: PrefixedHexString, request: JsonRpcPayload): JsonRpcResponse {
const id = (typeof request.id === 'string' ? parseInt(request.id) : request.id) ?? -1
return {
jsonrpc: '2.0',
id,
result: relayRequestID
}
}
/**
* convert relayRequestId (which is a "synthethic" transaction ID) into the actual transaction Id.
* This is done by parsing RelayHub event, and can only be done after mining.
* @param relayRequestId
* @return transactionId or marker:
* If the transaction is already mined, return a real transactionId
* If requestId doesn't appear in the cache, return TX_NOTSENTHERE
* If the transaction is no longer valid, return TX_NOTFOUND
* If the transaction can still be mined, returns TX_FUTURE
*/
async _getTransactionIdFromRequestId (relayRequestID: string): Promise<string> {
const submissionDetails = this.submittedRelayRequests.get(relayRequestID)
if (submissionDetails == null) {
return TX_NOTSENTHERE
}
const extraTopics = [undefined, undefined, [relayRequestID]]
const events = await this.relayClient.dependencies.contractInteractor.getPastEventsForHub(
extraTopics,
{ fromBlock: submissionDetails.submissionBlock },
[TransactionRelayed, TransactionRejectedByPaymaster])
if (events.length === 0) {
if (parseInt(submissionDetails.validUntilTime) > Date.now()) {
return TX_FUTURE
}
return TX_NOTFOUND
}
return this._pickSingleEvent(events, relayRequestID).transactionHash
}
/**
* If the transaction is already mined, return a simulated successful transaction receipt
* If the transaction is no longer valid, return a simulated reverted transaction receipt
* If the transaction can still be mined, returns "null" like a regular RPC call would do
*/
async _createTransactionReceiptForRelayRequestID (
relayRequestID: string,
submissionDetails: SubmittedRelayRequestInfo): Promise<TransactionReceipt | null> {
const extraTopics = [undefined, undefined, [relayRequestID]]
const events = await this.relayClient.dependencies.contractInteractor.getPastEventsForHub(
extraTopics,
{ fromBlock: submissionDetails.submissionBlock },
[TransactionRelayed, TransactionRejectedByPaymaster])
if (events.length === 0) {
if (parseInt(submissionDetails.validUntilTime) > Date.now()) {
return null
}
return this._createTransactionRevertedReceipt()
}
const eventData = await this._pickSingleEvent(events, relayRequestID)
const originalTransactionReceipt = await this.web3.eth.getTransactionReceipt(eventData.transactionHash)
return this._getTranslatedGsnResponseResult(originalTransactionReceipt, relayRequestID)
}
_getTranslatedGsnResponseResult (respResult: TransactionReceipt, relayRequestID?: string): TransactionReceipt {
const fixedTransactionReceipt = Object.assign({}, respResult)
// adding non declared field to receipt object - can be used in tests
// @ts-ignore
fixedTransactionReceipt.actualTransactionHash = fixedTransactionReceipt.transactionHash
fixedTransactionReceipt.transactionHash = relayRequestID ?? fixedTransactionReceipt.transactionHash
// older Web3.js versions require 'status' to be an integer. Will be set to '0' if needed later in this method.
// @ts-ignore
fixedTransactionReceipt.status = '1'
if (respResult.logs.length === 0) {
return fixedTransactionReceipt
}
const logs = abiDecoder.decodeLogs(respResult.logs)
const paymasterRejectedEvents = logs.find((e: any) => e != null && e.name === 'TransactionRejectedByPaymaster')
if (paymasterRejectedEvents !== null && paymasterRejectedEvents !== undefined) {
const paymasterRejectionReason: { value: string } = paymasterRejectedEvents.events.find((e: any) => e.name === 'reason')
if (paymasterRejectionReason !== undefined) {
this.logger.info(`Paymaster rejected on-chain: ${paymasterRejectionReason.value}. changing status to zero`)
// @ts-ignore
fixedTransactionReceipt.status = '0'
}
return fixedTransactionReceipt
}
const transactionRelayed = logs.find((e: any) => e != null && e.name === 'TransactionRelayed')
if (transactionRelayed != null) {
const transactionRelayedStatus = transactionRelayed.events.find((e: any) => e.name === 'status')
if (transactionRelayedStatus !== undefined) {
const status: string = transactionRelayedStatus.value.toString()
// 0 signifies success
if (status !== '0') {
this.logger.info(`reverted relayed transaction, status code ${status}. changing status to zero`)
// @ts-ignore
fixedTransactionReceipt.status = '0'
}
}
}
return fixedTransactionReceipt
}
_useGSN (payload: JsonRpcPayload): boolean {
if (payload.method === 'eth_accounts') {
return true
}
if (payload.params[0] === undefined) {
return false
}
const gsnTransactionDetails: GsnTransactionDetails = payload.params[0]
return gsnTransactionDetails?.useGSN ?? true
}
_fixGasFees (_txDetails: any): GsnTransactionDetails {
const txDetails = { ..._txDetails }
if (txDetails.maxFeePerGas != null && txDetails.maxPriorityFeePerGas != null) {
delete txDetails.gasPrice
return txDetails
}
if (txDetails.gasPrice != null && txDetails.maxFeePerGas == null && txDetails.maxPriorityFeePerGas == null) {
txDetails.maxFeePerGas = txDetails.gasPrice
txDetails.maxPriorityFeePerGas = txDetails.gasPrice
delete txDetails.gasPrice
return txDetails
}
throw new Error('Relay Provider: must provide either gasPrice or (maxFeePerGas and maxPriorityFeePerGas)')
}
/* wrapping HttpProvider interface */
host: string
connected: boolean
supportsSubscriptions (): boolean {
return this.origProvider.supportsSubscriptions()
}
disconnect (): boolean {
return this.origProvider.disconnect()
}
newAccount (): AccountKeypair {
return this.relayClient.newAccount()
}
async calculateGasFees (): Promise<{ maxFeePerGas: PrefixedHexString, maxPriorityFeePerGas: PrefixedHexString }> {
return await this.relayClient.calculateGasFees()
}
addAccount (privateKey: PrefixedHexString): void {
this.relayClient.addAccount(privateKey)
}
_getAccounts (payload: JsonRpcPayload, callback: JsonRpcCallback): void {
this.origProviderSend(payload, (error: Error | null, rpcResponse?: JsonRpcResponse): void => {
if (rpcResponse != null && Array.isArray(rpcResponse.result)) {
const ephemeralAccounts = this.relayClient.dependencies.accountManager.getAccounts()
rpcResponse.result = rpcResponse.result.concat(ephemeralAccounts)
}
callback(error, rpcResponse)
})
}
/**
* In an edge case many events with the same ID may be mined.
* If there is a successful {@link TransactionRelayed} event, it will be returned.
* If all events are {@link TransactionRejectedByPaymaster}, return the last one.
* If there is more than one successful {@link TransactionRelayed} throws as this is impossible for current Forwarder
*/
_pickSingleEvent (events: EventData[], relayRequestID: string): EventData {
const successes = events.filter(it => it.event === TransactionRelayed)
if (successes.length === 0) {
const sorted = events.sort((a: EventData, b: EventData) => b.blockNumber - a.blockNumber)
return sorted[0]
} else if (successes.length === 1) {
return successes[0]
} else {
throw new Error(`Multiple TransactionRelayed events with the same ${relayRequestID} found!`)
}
}
cacheSubmittedTransactionDetails (
relayingResult: RelayingResult
// relayRequestID: string,
// submissionBlock: number,
// validUntil: string
): void {
if (relayingResult.relayRequestID == null ||
relayingResult.submissionBlock == null ||
relayingResult.validUntilTime == null) {
throw new Error('Missing info in RelayingResult - internal GSN error, should not happen')
}
this.submittedRelayRequests.set(relayingResult.relayRequestID, {
validUntilTime: relayingResult.validUntilTime,
submissionBlock: relayingResult.submissionBlock
})
}
_createTransactionRevertedReceipt (): TransactionReceipt {
return {
to: '',
from: '',
contractAddress: '',
logsBloom: '',
blockHash: '',
transactionHash: '',
transactionIndex: 0,
gasUsed: 0,
logs: [],
blockNumber: 0,
cumulativeGasUsed: 0,
status: false // failure
}
}
} | the_stack |
import * as t from '@babel/types';
import traverse, {NodePath} from '@babel/traverse';
import MigrationReporter from './migration_reporter';
import flowTypeAtPos from './flow_type_at_pos';
export default function migrateToTypeScript(
reporter: MigrationReporter,
filePath: string,
file: t.File,
fileStats: {hasJsx: boolean},
): Promise<unknown> {
// We insert `any` more frequently when migrating a test file.
const isTestFile = filePath.endsWith('.test.js');
let shouldImportUtils = false;
function importUtils(path: NodePath<t.Node>): t.Expression {
if (!path.scope.hasBinding('u')) {
shouldImportUtils = true;
}
return t.identifier('u');
}
const awaitPromises: Array<Promise<unknown>> = [];
traverse(file, {
Program: {
exit(path) {
// If we need to import the `h`/`u` utilities then add an import declaration to the
// top of the program.
if (shouldImportUtils) {
path.node.body.unshift(t.importDeclaration(
[t.importDefaultSpecifier(t.identifier('u'))],
t.stringLiteral('client_server_shared/u'),
));
}
},
},
/* -------------------------------------------------------------------------------------- *\
| Type Annotations |
\* -------------------------------------------------------------------------------------- */
TypeAnnotation(path) {
// Flow automatically makes function parameters that accept `void` not required.
// However, TypeScript requires a parameter even if it is marked as void. So make all
// parameters that accept `void` optional.
if (
path.parent.type === 'Identifier' &&
path.parentPath.parent.type !== 'VariableDeclarator'
) {
// `function f(x: ?T)` → `function f(x?: T | null)`
if (path.node.typeAnnotation.type === 'NullableTypeAnnotation') {
path.parent.optional = true;
const nullableType = t.unionTypeAnnotation([
path.node.typeAnnotation.typeAnnotation,
t.nullLiteralTypeAnnotation(),
]);
inheritLocAndComments(path.node.typeAnnotation, nullableType);
path.node.typeAnnotation = nullableType;
}
// `function f(x: T | void)` → `function f(x?: T)`
if (
path.node.typeAnnotation.type === 'UnionTypeAnnotation' &&
path.node.typeAnnotation.types.some(unionType => unionType.type === 'VoidTypeAnnotation')
) {
path.parent.optional = true;
path.node.typeAnnotation.types =
path.node.typeAnnotation.types.filter(unionType => unionType.type !== 'VoidTypeAnnotation');
}
}
replaceWith(
path,
t.tsTypeAnnotation(migrateType(reporter, filePath, path.node.typeAnnotation)),
);
},
TypeParameterDeclaration(path) {
replaceWith(
path,
migrateTypeParameterDeclaration(reporter, filePath, path.node),
);
},
/* -------------------------------------------------------------------------------------- *\
| Declarations and Statements |
\* -------------------------------------------------------------------------------------- */
ImportDeclaration(path) {
// `import type {...} from` => `import {...} from`
if (path.node.importKind === 'type') {
path.node.importKind = 'value';
return;
}
// `import typeof X from` => ???
if (path.node.importKind === 'typeof') {
// noop, fix manually
return;
}
// `import {...} from`
if (!path.node.importKind || path.node.importKind === 'value') {
// `import {type X} from` => `import {X} from`
for (const specifier of path.node.specifiers) {
if (specifier.type === 'ImportSpecifier' && specifier.importKind === 'type') {
specifier.importKind = null;
}
}
return;
}
throw new Error(`Unrecognized import kind: ${JSON.stringify(path.node.importKind)}`);
},
ExportNamedDeclaration(path) {
delete path.node.exportKind;
},
TypeAlias(path) {
replaceWith(path, t.tsTypeAliasDeclaration(
path.node.id,
path.node.typeParameters
? migrateTypeParameterDeclaration(reporter, filePath, path.node.typeParameters)
: null,
migrateType(reporter, filePath, path.node.right),
));
},
OpaqueType(path) {
if (path.node.supertype)
throw new Error('Opaque types with a supertype are currently not supported.');
// Currently we just drop the `opaque` from an opaque type alias. We have only a few
// opaque types so this is unfortunate, but acceptable. We can manually migrate to a
// similar form.
replaceWith(path, t.tsTypeAliasDeclaration(
path.node.id,
path.node.typeParameters
? migrateTypeParameterDeclaration(reporter, filePath, path.node.typeParameters)
: null,
migrateType(reporter, filePath, path.node.impltype),
));
},
InterfaceDeclaration(path) {
if (path.node.mixins && path.node.mixins.length > 0)
throw new Error('Interface `mixins` are unsupported.');
if (path.node.implements && path.node.implements.length > 0)
throw new Error('Interface `implements` are unsupported.');
const typeParameters = path.node.typeParameters
? migrateTypeParameterDeclaration(reporter, filePath, path.node.typeParameters)
: null;
const extends_ = path.node.extends ? (
path.node.extends.map(flowExtends => {
const tsExtends = t.tsExpressionWithTypeArguments(
migrateQualifiedIdentifier(flowExtends.id),
flowExtends.typeParameters
? migrateTypeParameterInstantiation(
reporter,
filePath,
flowExtends.typeParameters
)
: null,
);
inheritLocAndComments(flowExtends, tsExtends);
return tsExtends;
})
) : null;
const body = migrateType(reporter, filePath, path.node.body);
if (body.type !== 'TSTypeLiteral')
throw new Error(`Unexpected AST node: ${JSON.stringify(body.type)}`);
replaceWith(path, t.tsInterfaceDeclaration(
path.node.id,
typeParameters,
extends_,
t.tsInterfaceBody(body.members),
));
},
VariableDeclarator(path) {
// `let x;` → `let x: any;`
// `let x = {};` → `let x: {[key: string]: any} = {};`
// `let x = [];` → `let x: Array<any> = [];`
//
// TypeScript can’t infer the type of an unannotated variable unlike Flow. We accept
// lower levels of soundness in test files. We’ll manually annotate non-test files.
if (isTestFile) {
if (
path.parent.type === 'VariableDeclaration' &&
path.parentPath.parent.type !== 'ForStatement' &&
path.parentPath.parent.type !== 'ForInStatement' &&
path.parentPath.parent.type !== 'ForOfStatement' &&
path.node.id.type === 'Identifier' &&
path.node.id.typeAnnotation == null
) {
if (path.node.init === null) {
path.node.id.typeAnnotation = t.tsTypeAnnotation(t.tsAnyKeyword());
} else if (
path.node.init.type === 'ObjectExpression' &&
path.node.init.properties.length === 0
) {
path.node.id.typeAnnotation = t.tsTypeAnnotation(t.tsTypeLiteral([
t.tsIndexSignature(
[tsIdentifier(
'key',
null,
t.tsTypeAnnotation(t.tsStringKeyword()),
)],
t.tsTypeAnnotation(t.tsAnyKeyword()),
)
]));
} else if (
path.node.init.type === 'ArrayExpression' &&
path.node.init.elements.length === 0
) {
path.node.id.typeAnnotation = t.tsTypeAnnotation(t.tsTypeReference(
t.identifier('Array'),
t.tsTypeParameterInstantiation([t.tsAnyKeyword()]),
));
}
}
}
},
FunctionDeclaration: {
enter(path) {
// Add Flow’s inferred type for all unannotated function parameters...
awaitPromises.push(annotateParamsWithFlowTypeAtPos(reporter, filePath, path.node.params));
// `function f(x, y, z)` → `function f(x: any, y: any, z: any)`
//
// TypeScript can’t infer unannotated function parameters unlike Flow. We accept lower
// levels of soundness in type files. We’ll manually annotate non-test files.
if (isTestFile) {
for (const param of path.node.params) {
if (!(param as any).typeAnnotation) {
(param as any).typeAnnotation = t.tsTypeAnnotation(t.tsAnyKeyword());
}
}
}
},
exit(path) {
let optional = true;
// `function f(a?: T, b: U)` → `function f(a: T | undefined, b: U)`
for (const param of path.node.params.slice().reverse()) {
let paramIsOptional = false;
if (param.type === 'AssignmentPattern') {
paramIsOptional = true;
if (param.left.type === 'Identifier' && param.left.optional) {
param.left.optional = false;
}
}
if (param.type === 'Identifier' && param.optional) {
paramIsOptional = true;
}
if (!paramIsOptional) {
optional = false;
} else {
if (!optional) {
const identifier = (param.type === 'AssignmentPattern' ? param.left : param) as t.Identifier;
delete identifier.optional;
if (identifier.typeAnnotation && identifier.typeAnnotation.type === 'TSTypeAnnotation') {
if (identifier.typeAnnotation.typeAnnotation.type === 'TSUnionType') {
identifier.typeAnnotation.typeAnnotation.types.push(t.tsUndefinedKeyword());
} else {
identifier.typeAnnotation.typeAnnotation = t.tsUnionType([
identifier.typeAnnotation.typeAnnotation,
t.tsUndefinedKeyword(),
]);
}
}
}
}
}
},
},
ClassProperty(path) {
// `class { +prop: boolean }` => `class { readonly prop: boolean }`
// the typescript decls for ClassProperty don't have variance for some reason
const nodeAsAny = path.node as any;
if (nodeAsAny.variance && nodeAsAny.variance.kind === 'plus') {
nodeAsAny.variance = null;
nodeAsAny.readonly = true;
}
},
ClassMethod(path) {
// Add Flow’s inferred type for all unannotated function parameters...
awaitPromises.push(annotateParamsWithFlowTypeAtPos(reporter, filePath, path.node.params));
},
ObjectMethod(path) {
if (isInsideCreateReactClass(path)) {
// Add Flow’s inferred type for all unannotated function parameters...
awaitPromises.push(annotateParamsWithFlowTypeAtPos(reporter, filePath, path.node.params));
}
},
/* -------------------------------------------------------------------------------------- *\
| Expressions |
\* -------------------------------------------------------------------------------------- */
TypeCastExpression(path) {
if (
// `((x: any): T)` → `(x as T)`
// `((x: Object): T)` → `(x as T)`
// `((x: Function): T)` → `(x as T)`
path.node.expression.type === 'TypeCastExpression' &&
(path.node.expression.typeAnnotation.typeAnnotation.type === 'AnyTypeAnnotation' ||
(path.node.expression.typeAnnotation.typeAnnotation.type === 'GenericTypeAnnotation' &&
path.node.expression.typeAnnotation.typeAnnotation.typeParameters &&
path.node.expression.typeAnnotation.typeAnnotation.id.type === 'Identifier' &&
(path.node.expression.typeAnnotation.typeAnnotation.id.name === 'Object' ||
path.node.expression.typeAnnotation.typeAnnotation.id.name === 'Function')))
) {
// If we are a `createReactClass()` instance property then transform
// into `((x as any) as T)`.
if (path.parent.type === 'ObjectProperty' && isInsideCreateReactClass(path)) {
replaceWith(path, t.tsAsExpression(
t.parenthesizedExpression(t.tsAsExpression(
path.node.expression.expression,
migrateType(reporter, filePath, path.node.expression.typeAnnotation.typeAnnotation),
)),
migrateType(reporter, filePath, path.node.typeAnnotation.typeAnnotation),
));
} else {
replaceWith(path, t.tsAsExpression(
path.node.expression.expression,
migrateType(reporter, filePath, path.node.typeAnnotation.typeAnnotation),
));
}
} else if (
// `(x: any)` → `(x as any)`
path.node.typeAnnotation.typeAnnotation.type === 'AnyTypeAnnotation'
) {
replaceWith(path, t.tsAsExpression(
path.node.expression,
migrateType(reporter, filePath, path.node.typeAnnotation.typeAnnotation),
));
} else if (
// `('foo': 'foo')` → `('foo' as const)`
// `(42: 42)` → `(42 as const)`
(path.node.expression.type === 'StringLiteral' &&
path.node.typeAnnotation.typeAnnotation.type === 'StringLiteralTypeAnnotation' &&
path.node.expression.value === path.node.typeAnnotation.typeAnnotation.value) ||
(path.node.expression.type === 'NumericLiteral' &&
path.node.typeAnnotation.typeAnnotation.type === 'NumberLiteralTypeAnnotation' &&
path.node.expression.value === path.node.typeAnnotation.typeAnnotation.value)
) {
replaceWith(path, t.tsAsExpression(
path.node.expression,
t.tsTypeReference(t.identifier('const')),
));
} else if (isComplexLiteral(path.node.expression)) {
// `(x: T)` → `(x as T)`
//
// When `x` is a literal like `[]` or `null`.
replaceWith(path, t.tsAsExpression(
path.node.expression,
migrateType(reporter, filePath, path.node.typeAnnotation.typeAnnotation),
));
} else {
// If you want to see all type casts which aren’t handled by the above:
//
// ```ts
// reporter.unsupportedTypeCast(filePath, path.node.expression.loc!);
// ```
const safeCast = t.callExpression(
t.memberExpression(importUtils(path), t.identifier('cast')),
[path.node.expression],
);
safeCast.typeParameters = t.tsTypeParameterInstantiation([
migrateType(reporter, filePath, path.node.typeAnnotation.typeAnnotation)
]);
replaceWith(path, safeCast);
}
},
/* -------------------------------------------------------------------------------------- *\
| Patterns |
\* -------------------------------------------------------------------------------------- */
AssignmentPattern(path) {
// `function f(x?: T = y)` → `function f(x: T = y)`
if (path.node.right && path.node.left.type === 'Identifier' && path.node.left.optional) {
path.node.left.optional = false;
}
},
/* -------------------------------------------------------------------------------------- *\
| JSX Detection |
\* -------------------------------------------------------------------------------------- */
JSXElement() {
fileStats.hasJsx = true;
},
JSXFragment() {
fileStats.hasJsx = true;
},
});
return Promise.all(awaitPromises);
}
/**
* Adds a type annotation to all unannotated function parameters.
*/
function annotateParamsWithFlowTypeAtPos(
reporter: MigrationReporter,
filePath: string,
params: t.FunctionDeclaration['params']
): Promise<unknown> {
const awaitPromises: Array<Promise<void>> = [];
for (const param of params) {
if (param.type === 'Identifier' && !param.typeAnnotation) {
awaitPromises.push((async () => {
// Get the type Flow is inferring for this unannotated function parameter.
const flowType = await flowTypeAtPos(filePath, param.loc!);
if (flowType === null) return;
// If Flow inferred `empty` then that means there were no calls to the
// function and therefore no “lower type bounds” for the parameter. This
// means you can do anything with the type effectively making it any. So
// treat it as such.
let tsType = flowType.type === 'EmptyTypeAnnotation'
? t.tsAnyKeyword()
: migrateType(reporter, filePath, flowType);
// Use a type alias so that developers understand why an `any`
// was inserted.
if (tsType.type === 'TSAnyKeyword') {
tsType = t.tsTypeReference(t.identifier('FlowAnyInferred'));
}
// Add the type annotation! Yaay.
param.typeAnnotation = t.tsTypeAnnotation(tsType);
})());
}
}
return Promise.all(awaitPromises);
}
function tsIdentifier(
name: string,
optional?: boolean | null,
typeAnnotation?: t.TSTypeAnnotation | null,
): t.Identifier {
const identifier = t.identifier(name);
if (optional != null) identifier.optional = optional
if (typeAnnotation != null) identifier.typeAnnotation = typeAnnotation;
return identifier;
}
function migrateType(
reporter: MigrationReporter,
filePath: string,
flowType: t.FlowType,
): t.TSType {
const tsType = actuallyMigrateType(reporter, filePath, flowType);
inheritLocAndComments(flowType, tsType);
return tsType;
}
function actuallyMigrateType(
reporter: MigrationReporter,
filePath: string,
flowType: t.FlowType,
): t.TSType {
switch (flowType.type) {
case 'AnyTypeAnnotation':
return t.tsAnyKeyword();
case 'ArrayTypeAnnotation':
return t.tsArrayType(migrateType(reporter, filePath, flowType.elementType));
case 'BooleanTypeAnnotation':
return t.tsBooleanKeyword();
case 'BooleanLiteralTypeAnnotation':
return t.tsLiteralType(t.booleanLiteral(flowType.value));
case 'NullLiteralTypeAnnotation':
return t.tsNullKeyword();
case 'ExistsTypeAnnotation':
// The existential type (`*`) in Flow is unsound and basically `any`. The Flow team even
// deprecated existentials and plans to replace all usages at FB with `any`.
return t.tsTypeReference(t.identifier('FlowAnyExistential'));
case 'FunctionTypeAnnotation': {
const typeParams = flowType.typeParameters
? migrateTypeParameterDeclaration(reporter, filePath, flowType.typeParameters)
: null;
const params = flowType.params.map<t.Identifier | t.RestElement>((flowParam, i) => {
const tsParam = tsIdentifier(
// If a Flow function type argument doesn’t have a name we call it `argN`. This
// matches the JavaScript convention of calling function inputs “arguments”.
flowParam.name ? flowParam.name.name : `arg${i + 1}`,
flowParam.optional,
t.tsTypeAnnotation(migrateType(reporter, filePath, flowParam.typeAnnotation)),
);
inheritLocAndComments(flowParam, tsParam);
return tsParam;
});
if (flowType.rest) {
// If a Flow rest element doesn’t have a name we call it `rest`.
const tsRestParam = t.restElement(flowType.rest.name || t.identifier('rest'));
tsRestParam.typeAnnotation = t.tsTypeAnnotation(
migrateType(reporter, filePath, flowType.rest.typeAnnotation),
);
inheritLocAndComments(flowType.rest, tsRestParam);
params.push(tsRestParam);
// Technically, Flow rest parameters can be optional (`(...rest?: T[]) => void`),
// but what does that even mean? We choose to ignore that.
}
return t.tsFunctionType(
typeParams,
params,
t.tsTypeAnnotation(migrateType(reporter, filePath, flowType.returnType)),
);
}
case 'GenericTypeAnnotation': {
const id = migrateQualifiedIdentifier(flowType.id);
const params = flowType.typeParameters && flowType.typeParameters.params.length > 0
? migrateTypeParameterInstantiation(reporter, filePath, flowType.typeParameters)
: null;
// `Object` → `FlowAnyObject`
if (id.type === 'Identifier' && id.name === 'Object' && !params) {
return t.tsTypeReference(t.identifier('FlowAnyObject'));
}
// `Function` → `FlowAnyFunction`
if (id.type === 'Identifier' && id.name === 'Function' && !params) {
return t.tsTypeReference(t.identifier('FlowAnyFunction'));
}
// `$ReadOnlyArray<T>` → `ReadonlyArray<T>`
if (
id.type === 'Identifier' &&
id.name === '$ReadOnlyArray' &&
params && params.params.length === 1
) {
return t.tsTypeReference(t.identifier('ReadonlyArray'), params);
}
// `$ReadOnly<T>` → `Readonly<T>`
if (
id.type === 'Identifier' &&
id.name === '$ReadOnly' &&
params && params.params.length === 1
) {
return t.tsTypeReference(t.identifier('Readonly'), params);
}
// `$Keys<T>` → `keyof T`
if (
id.type === 'Identifier' &&
id.name === '$Keys' &&
params && params.params.length === 1
) {
const typeOperator = t.tsTypeOperator(params.params[0]);
typeOperator.operator = 'keyof';
return typeOperator;
}
// `$Values<T>` → `h.ObjectValues<T>`
if (
id.type === 'Identifier' &&
id.name === '$Values' &&
params && params.params.length === 1
) {
return t.tsTypeReference(
t.tsQualifiedName(t.identifier('h'), t.identifier('ObjectValues')),
params,
);
}
// `$Shape<T>` → `Partial<T>`
if (
id.type === 'Identifier' &&
id.name === '$Shape' &&
params && params.params.length === 1
) {
return t.tsTypeReference(t.identifier('Partial'), params);
}
// `$Subtype<T>` → `any`
//
// `$Subtype` and `$Supertype` are these weird utilities from Flow which have very
// little to do with what their names are. They type check in one subtyping direction
// but are any on the other. So `$Subtype<T> ~> U` is `T ~> U` but `U ~> $Subtype<T>` is
// `U ~> any` (or the other way around, can’t quite remember).
//
// So basically these types are `any` and we will treat them as such in the migration.
if (
id.type === 'Identifier' &&
id.name === '$Subtype' &&
params && params.params.length === 1
) {
return t.tsTypeReference(t.identifier('FlowAnySubtype'), params);
}
// `$PropertyType<T, K>` → `T[K]`
if (
id.type === 'Identifier' &&
id.name === '$PropertyType' &&
params && params.params.length === 2
) {
return t.tsIndexedAccessType(params.params[0], params.params[1]);
}
// `$ElementType<T, K>` → `T[K]`
if (
id.type === 'Identifier' &&
id.name === '$ElementType' &&
params && params.params.length === 2
) {
return t.tsIndexedAccessType(params.params[0], params.params[1]);
}
// `React.Node` → `React.ReactNode`
if (
id.type === 'TSQualifiedName' &&
id.left.type === 'Identifier' &&
id.left.name === 'React' &&
id.right.type === 'Identifier' &&
id.right.name === 'Node' &&
!params
) {
return t.tsTypeReference(
t.tsQualifiedName(t.identifier('React'), t.identifier('ReactNode')),
);
}
// `React.Element<T>` → `React.ReactElement<React.ComponentProps<T>>`
if (
id.type === 'TSQualifiedName' &&
id.left.type === 'Identifier' &&
id.left.name === 'React' &&
id.right.type === 'Identifier' &&
id.right.name === 'Element' &&
params && params.params.length === 1
) {
if (
params.params[0].type === 'TSAnyKeyword' ||
(params.params[0].type === 'TSTypeReference' &&
(params.params[0] as any).typeName.type === 'Identifier' &&
(params.params[0] as any).typeName.name === 'FlowAnyExistential')
) {
return t.tsTypeReference(
t.tsQualifiedName(t.identifier('React'), t.identifier('ReactElement')),
params,
);
} else {
return t.tsTypeReference(
t.tsQualifiedName(t.identifier('React'), t.identifier('ReactElement')),
t.tsTypeParameterInstantiation([
t.tsTypeReference(
t.tsQualifiedName(t.identifier('React'), t.identifier('ComponentProps')),
params,
),
]),
);
}
}
return t.tsTypeReference(id, params);
}
case 'InterfaceTypeAnnotation':
throw new Error(`Unsupported AST node: ${JSON.stringify(flowType.type)}`);
case 'IntersectionTypeAnnotation':
return t.tsIntersectionType(flowType.types.map(flowMemberType => {
const tsMemberType = migrateType(reporter, filePath, flowMemberType);
// Function types have weird specificities in intersections/unions. Wrap them in
// parentheses to preserve the AST specificity.
return tsMemberType.type === 'TSFunctionType'
? t.tsParenthesizedType(tsMemberType)
: tsMemberType;
}));
case 'MixedTypeAnnotation':
return t.tsUnknownKeyword();
case 'EmptyTypeAnnotation':
return t.tsNeverKeyword();
case 'NullableTypeAnnotation': {
return t.tsUnionType([
migrateType(reporter, filePath, flowType.typeAnnotation),
t.tsNullKeyword(),
t.tsUndefinedKeyword(),
]);
}
case 'NumberLiteralTypeAnnotation':
return t.tsLiteralType(t.numericLiteral(flowType.value));
case 'NumberTypeAnnotation':
return t.tsNumberKeyword();
case 'ObjectTypeAnnotation': {
// We ignore `exact`/`inexact` for Flow object types since that just straight up doesn’t
// matter in TypeScript.
// Combine all the members into one array...
const flowMembers = [
...flowType.properties,
...(flowType.indexers || []),
...(flowType.callProperties || []),
...(flowType.internalSlots || []),
];
// Sort the members by their position in source code...
flowMembers.sort((a, b) => a.loc!.start.line - b.loc!.start.line);
// We need to split Flow object type spreads into intersection objects.
const intersectionTypes: Array<
| {kind: 'literal', members: Array<t.TSTypeElement>}
| {kind: 'reference', type: t.TSType}
> = [];
for (const flowMember of flowMembers) {
if (flowMember.type === 'ObjectTypeSpreadProperty') {
// Recast attaches comments to the `loc`. We don’t want to miss comments
// attached to a spread so wrap with a parenthesized type and attach the spread
// loc. Prettier should remove unnesecary parentheses.
const tsArgument = t.tsParenthesizedType(migrateType(reporter, filePath, flowMember.argument));
inheritLocAndComments(flowMember, tsArgument);
intersectionTypes.push({kind: 'reference', type: tsArgument});
} else {
// Push a migrated member into the last literal object in our intersection types
// array. If the last type is not an intersection, then add one.
let members: Array<t.TSTypeElement>;
const lastIntersectionType = intersectionTypes[intersectionTypes.length - 1];
if (lastIntersectionType && lastIntersectionType.kind === 'literal') {
members = lastIntersectionType.members;
} else {
members = [];
const nextIntersectionType = {kind: 'literal' as const, members};
intersectionTypes.push(nextIntersectionType);
}
members.push(migrateObjectMember(reporter, filePath, flowMember));
}
}
if (intersectionTypes.length === 0) {
return t.tsTypeLiteral([]);
}
const types = intersectionTypes.map(intersectionType => {
if (intersectionType.kind === 'literal') {
// TypeScript only supports `string` or `number` for `T` in `{[x: T]: U}`.
// TypeScript also provides `Record<K, V>` as a utility type for arbitrary key
// types. Convert all objects of that form to `Record`.
if (intersectionType.members.length === 1) {
const onlyMember = intersectionType.members[0];
if (onlyMember.type === 'TSIndexSignature') {
const indexType = onlyMember.parameters[0].typeAnnotation! as t.TSTypeAnnotation;
if (
indexType.typeAnnotation.type !== 'TSStringKeyword' &&
indexType.typeAnnotation.type !== 'TSNumberKeyword'
) {
return t.tsTypeReference(
t.tsQualifiedName(t.identifier('h'), t.identifier('ObjectMap')),
t.tsTypeParameterInstantiation([
indexType.typeAnnotation,
onlyMember.typeAnnotation!.typeAnnotation,
]),
);
}
}
}
return t.tsTypeLiteral(intersectionType.members);
} else {
return intersectionType.type;
}
});
if (types.length === 1) {
return types[0];
} else {
return t.tsIntersectionType(types);
}
}
case 'StringLiteralTypeAnnotation':
return t.tsLiteralType(t.stringLiteral(flowType.value));
case 'StringTypeAnnotation':
return t.tsStringKeyword();
case 'ThisTypeAnnotation':
return t.tsThisType();
case 'TupleTypeAnnotation': {
return t.tsTupleType(flowType.types.map(elementType => {
return migrateType(reporter, filePath, elementType);
}));
}
case 'TypeofTypeAnnotation': {
const tsType = migrateType(reporter, filePath, flowType.argument);
if (tsType.type !== 'TSTypeReference')
throw new Error(`Unexpected AST node: ${JSON.stringify(tsType.type)}`);
if (tsType.typeParameters)
throw new Error('Unexpected type parameters on `typeof` argument.');
return t.tsTypeQuery(tsType.typeName);
}
case 'UnionTypeAnnotation': {
let anyMemberIndex: number | null = null;
const tsUnionType = t.tsUnionType(flowType.types.map((flowMemberType, i) => {
const tsMemberType = migrateType(reporter, filePath, flowMemberType);
// If one of the union members is `any` then flatten out the union to just that.
// This happens fairly frequently for types coming from `flowTypeAtPos()`.
if (anyMemberIndex !== null && tsMemberType.type === 'TSAnyKeyword') {
anyMemberIndex = i;
}
// Function types have weird specificities in intersections/unions. Wrap them in
// parentheses to preserve the AST specificity.
return tsMemberType.type === 'TSFunctionType'
? t.tsParenthesizedType(tsMemberType)
: tsMemberType;
}));
return anyMemberIndex !== null ? tsUnionType.types[anyMemberIndex] : tsUnionType;
}
case 'VoidTypeAnnotation':
return t.tsVoidKeyword();
default: {
const never: never = flowType;
throw new Error(`Unexpected AST node: ${JSON.stringify(never['type'])}`);
}
}
}
function migrateQualifiedIdentifier(
identifier: t.Identifier | t.QualifiedTypeIdentifier,
): t.Identifier | t.TSQualifiedName {
if (identifier.type === 'Identifier') {
return identifier;
} else {
const tsQualifiedName = t.tsQualifiedName(
migrateQualifiedIdentifier(identifier.qualification),
identifier.id,
);
inheritLocAndComments(identifier.qualification, tsQualifiedName);
return tsQualifiedName;
}
}
function migrateTypeParameterDeclaration(
reporter: MigrationReporter,
filePath: string,
flowTypeParameters: t.TypeParameterDeclaration,
): t.TSTypeParameterDeclaration {
const params = flowTypeParameters.params.map(flowTypeParameter => {
if (flowTypeParameter.variance !== null) {
reporter.typeParameterWithVariance(filePath, flowTypeParameter.loc!);
}
const tsTypeParameter = t.tsTypeParameter(
flowTypeParameter.bound
? migrateType(reporter, filePath, flowTypeParameter.bound.typeAnnotation)
: null,
flowTypeParameter.default
? migrateType(reporter, filePath, flowTypeParameter.default)
: null,
);
tsTypeParameter.name = flowTypeParameter.name;
inheritLocAndComments(flowTypeParameter, tsTypeParameter);
return tsTypeParameter;
});
const tsTypeParameters = t.tsTypeParameterDeclaration(params);
inheritLocAndComments(flowTypeParameters, tsTypeParameters);
return tsTypeParameters;
}
function migrateTypeParameterInstantiation(
reporter: MigrationReporter,
filePath: string,
flowTypeParameters: t.TypeParameterInstantiation,
): t.TSTypeParameterInstantiation {
const params = flowTypeParameters.params.map(flowTypeParameter => {
return migrateType(reporter, filePath, flowTypeParameter);
});
const tsTypeParameters = t.tsTypeParameterInstantiation(params);
inheritLocAndComments(flowTypeParameters, tsTypeParameters);
return tsTypeParameters;
}
function migrateObjectMember(
reporter: MigrationReporter,
filePath: string,
flowMember:
| t.ObjectTypeProperty
| t.ObjectTypeIndexer
| t.ObjectTypeCallProperty
| t.ObjectTypeInternalSlot,
): t.TSTypeElement {
const tsMember = actuallyMigrateObjectMember(reporter, filePath, flowMember);
inheritLocAndComments(flowMember, tsMember);
return tsMember;
}
function actuallyMigrateObjectMember(
reporter: MigrationReporter,
filePath: string,
flowMember:
| t.ObjectTypeProperty
| t.ObjectTypeIndexer
| t.ObjectTypeCallProperty
| t.ObjectTypeInternalSlot,
): t.TSTypeElement {
switch (flowMember.type) {
case 'ObjectTypeProperty': {
if (flowMember.key.type === 'Identifier' && flowMember.key.name.startsWith('$'))
reporter.objectPropertyWithInternalName(filePath, flowMember.loc!);
if (flowMember.variance && flowMember.variance.kind !== 'plus')
reporter.objectPropertyWithMinusVariance(filePath, flowMember.loc!);
if (!(flowMember.kind || flowMember.kind === 'init'))
throw new Error(`Unsupported object type property kind: ${JSON.stringify(flowMember.kind)}`);
if (flowMember.proto)
throw new Error('Did not expect any Flow properties with `proto` set to true.');
if (flowMember.static)
throw new Error('Did not expect any Flow properties with `static` set to true.');
const tsValue = migrateType(reporter, filePath, flowMember.value);
// The Babel type are wrong here...
if (!(flowMember as any).method) {
const tsPropertySignature = t.tsPropertySignature(
flowMember.key,
t.tsTypeAnnotation(tsValue),
);
tsPropertySignature.computed = flowMember.key.type !== 'Identifier';
tsPropertySignature.optional = !!flowMember.optional;
tsPropertySignature.readonly =
flowMember.variance ? flowMember.variance.kind === 'plus' : null;
return tsPropertySignature;
} else {
if (tsValue.type !== 'TSFunctionType') {
throw new Error(`Unexpected AST node: ${JSON.stringify(tsValue.type)}`);
}
const tsMethodSignature = t.tsMethodSignature(
flowMember.key,
tsValue.typeParameters,
tsValue.parameters,
tsValue.typeAnnotation,
);
tsMethodSignature.computed = flowMember.key.type !== 'Identifier';
tsMethodSignature.optional = !!flowMember.optional;
return tsMethodSignature;
}
}
case 'ObjectTypeIndexer': {
if (flowMember.variance && flowMember.variance.kind !== 'plus')
reporter.objectPropertyWithMinusVariance(filePath, flowMember.loc!);
if (flowMember.static)
throw new Error('Did not expect any Flow properties with `static` set to true.');
const tsIndexSignature = t.tsIndexSignature(
[tsIdentifier(
flowMember.id ? flowMember.id.name : 'key',
null,
t.tsTypeAnnotation(migrateType(reporter, filePath, flowMember.key)),
)],
t.tsTypeAnnotation(migrateType(reporter, filePath, flowMember.value)),
);
tsIndexSignature.readonly = flowMember.variance ? flowMember.variance.kind === 'plus' : null;
return tsIndexSignature;
}
// Should instead use `ObjectTypeProperty` with `method` set to `true`.
case 'ObjectTypeCallProperty':
throw new Error(`Unsupported AST node: ${JSON.stringify(flowMember.type)}`);
case 'ObjectTypeInternalSlot':
throw new Error(`Unsupported AST node: ${JSON.stringify(flowMember.type)}`);
default: {
const never: never = flowMember;
throw new Error(`Unrecognized AST node: ${JSON.stringify(never['type'])}`);
}
}
}
/**
* Is this a literal expression? Includes literal objects and functions.
*/
function isComplexLiteral(expression: t.Expression): boolean {
if (t.isLiteral(expression)) {
return true;
}
if (expression.type === 'Identifier' && expression.name === 'undefined') {
return true;
}
if (expression.type === 'ArrayExpression') {
for (const element of expression.elements) {
if (element === null) {
continue;
}
if (element.type === 'SpreadElement') {
if (!isComplexLiteral(element.argument)) {
return false;
} else {
continue;
}
}
if (!isComplexLiteral(element)) {
return false;
}
}
return true;
}
if (expression.type === 'ObjectExpression') {
for (const property of expression.properties) {
if (property.type === 'ObjectMethod') {
return false;
} else if (property.type === 'SpreadElement') {
return false;
} else {
if (property.computed && !isComplexLiteral(property.key)) {
return false;
}
if (t.isExpression(property.value) && !isComplexLiteral(property.value)) {
return false;
}
}
}
return true;
}
return false;
}
/**
* Are we inside `createReactClass()`?
*/
function isInsideCreateReactClass(path: NodePath<t.Node>): boolean {
if (
path.node.type === 'CallExpression' &&
path.node.callee.type === 'Identifier' &&
path.node.callee.name === 'createReactClass'
) {
return true;
}
if (path.parentPath) {
return isInsideCreateReactClass(path.parentPath);
}
return false;
}
/**
* Copies the location and comments of one node to a new node.
*/
function inheritLocAndComments(oldNode: t.Node, newNode: t.Node) {
newNode.loc = oldNode.loc;
// Recast uses a different format for comments then Babel.
if ((oldNode as any).comments) {
(newNode as any).comments = (oldNode as any).comments;
delete (oldNode as any).comments;
}
}
/**
* Recast uses a different format for comments. We need to manually copy them over to the new node.
* We also attach the old location so that Recast prints it at the same place.
*
* https://github.com/benjamn/recast/issues/572
*/
function replaceWith(path: NodePath<t.Node>, node: t.Node) {
inheritLocAndComments(path.node, node);
path.replaceWith(node);
} | the_stack |
import React from "react";
import {
AppBar,
// Divider,
Drawer,
List,
// ListItem,
// ListItemIcon,
// ListItemText,
Toolbar,
Link as MuiLink,
Typography,
Backdrop,
NoSsr,
CircularProgress,
Grow,
Fade,
Hidden,
IconButton
} from "@material-ui/core";
import { Menu as MenuIcon, Close as CloseIcon } from "@material-ui/icons";
import { createStyles, makeStyles } from "@material-ui/core/styles";
// import {
// ChevronRight as ChevronRightIcon,
// PlaylistAddCheck as PlaylistAddCheckIcon
// } from "@material-ui/icons";
import Link from "next/link";
import { useRouter } from "next/router";
import clsx from "clsx";
import { AdrMenu } from "./components/AdrMenu";
import { CustomTheme } from "../../mui";
import { ConnectedSearchBox } from "./components/ConnectedSearchBox/ConnectedSearchBox";
import { AdrLight } from "../../types";
import { AdrNav, AdrNavContext } from "../../contexts";
import { RoutingProgress } from "./components/RoutingProgress";
const drawerWidth = 380;
const searchTransitionDuration = 300;
const useStyles = makeStyles((theme: CustomTheme) => {
const topSpace = theme.spacing(6);
return createStyles({
root: {
display: "flex"
},
layoutLeftCol: {
flexGrow: 0.5,
[theme.breakpoints.down("md")]: {
display: "none"
}
},
layoutCenterCol: {
paddingLeft: theme.custom.layout.centerColPadding,
paddingRight: theme.custom.layout.centerColPadding,
flexGrow: 1,
[theme.breakpoints.up("md")]: {
flexGrow: 0,
flexShrink: 0,
flexBasis: theme.custom.layout.centerColBasis
}
},
layoutRightCol: {
flexGrow: 1,
flexBasis: theme.custom.layout.rightColBasis,
[theme.breakpoints.down("md")]: {
display: "none"
}
},
appBar: {
zIndex: theme.zIndex.drawer + 1
},
appBarMenuButton: {
[theme.breakpoints.up("sm")]: {
display: "none"
}
},
appBarTitle: {
display: "none",
[theme.breakpoints.up("sm")]: {
display: "flex",
alignItems: "center",
width: drawerWidth - theme.spacing(3),
flexGrow: 0,
flexShrink: 0,
cursor: "pointer"
}
},
appBarTitleLink: {
display: "block",
color: "inherit",
"&:hover": {
color: "inherit"
},
marginLeft: theme.spacing(2)
},
searchBackdrop: {
zIndex: theme.zIndex.modal - 2
},
searchBox: {
zIndex: theme.zIndex.modal - 1,
width: "100%",
[theme.breakpoints.up("md")]: {
width: "70%"
},
transition: theme.transitions.create("width", {
duration: searchTransitionDuration
})
},
searchBoxOpen: {
width: "100%"
},
drawer: {
[theme.breakpoints.up("sm")]: {
width: drawerWidth,
flexShrink: 0
}
},
drawerPaper: {
width: drawerWidth
},
drawerContainer: {
height: "100%",
display: "flex",
flexDirection: "column",
[theme.breakpoints.up("sm")]: {
paddingTop: topSpace
}
},
drawerToolbar: {
visibility: "visible",
[theme.breakpoints.up("sm")]: {
visibility: "hidden"
},
justifyContent: "space-between"
},
adrMenu: {
flexGrow: 1,
flexShrink: 1,
overflow: "auto",
"&::-webkit-scrollbar": {
width: 6,
backgroundColor: theme.palette.background
},
"&::-webkit-scrollbar-thumb": {
borderRadius: 10,
"-webkit-box-shadow": "inset 0 0 2px rgba(0,0,0,.3)",
backgroundColor: theme.palette.grey[400]
}
},
bottomMenuList: {
flexGrow: 0,
flexShrink: 0
},
adlTitleAndSpinner: {
display: "flex",
justifyContent: "space-between",
paddingLeft: theme.spacing(2),
[theme.breakpoints.up("sm")]: {
paddingLeft: theme.spacing(3)
},
paddingBottom: theme.spacing(0.5),
paddingRight: theme.spacing(3)
},
adlTitle: {
fontWeight: theme.typography.fontWeightBold
},
adrMenuSpinner: {
alignSelf: "center",
marginTop: "30vh"
},
container: {
flexGrow: 1,
paddingTop: theme.spacing(2),
[theme.breakpoints.up("sm")]: {
paddingTop: topSpace
}
},
content: {
minHeight: `calc(100vh - 35px - ${
theme.spacing(1) + theme.spacing(8)
}px)`, // TODO: calc AppBar height more precisely
[theme.breakpoints.up("sm")]: {
minHeight: `calc(100vh - 35px - ${topSpace + theme.spacing(8)}px)` // TODO: calc AppBar height more precisely
}
},
footer: {
backgroundColor: theme.palette.grey[100],
color: theme.palette.grey[500],
height: 35,
display: "flex",
marginTop: theme.spacing(6)
},
footerText: {
fontSize: "0.77rem"
},
footerLink: {
color: theme.palette.grey[600],
fontSize: "0.8rem",
"&:hover": {
color: theme.palette.grey[800]
}
},
footerContent: {
display: "flex",
flexDirection: "column",
justifyContent: "center"
}
});
});
function buildAdrNav(currentAdr: AdrLight, adrs: AdrLight[]): AdrNav {
const currentIndex = adrs
.map((adr, index) => (adr.slug === currentAdr.slug ? index : undefined))
.filter((adr) => adr !== undefined)
.pop();
const previousAdr =
currentIndex !== undefined && currentIndex < adrs.length - 1
? adrs[currentIndex + 1]
: undefined;
const nextAdr =
currentIndex !== undefined && currentIndex > 0
? adrs[currentIndex - 1]
: undefined;
return {
previousAdr,
nextAdr
};
}
export type AdrBrowserLayoutProps = {
projectName: string;
adrs?: AdrLight[]; // undefined -> loading, empty -> empty
adrsReloading?: boolean;
currentAdr?: AdrLight;
children: React.ReactNode;
routing?: boolean;
l4bVersion: string;
};
export function AdrBrowserLayout({
projectName,
adrs,
adrsReloading = false,
currentAdr,
children,
routing = false,
l4bVersion
}: AdrBrowserLayoutProps) {
const classes = useStyles();
const router = useRouter();
const [mobileDrawerOpen, setMobileDrawerOpen] = React.useState(false);
const handleMobileDrawerToggle = () => {
setMobileDrawerOpen(!mobileDrawerOpen);
};
React.useEffect(() => {
const closeMobileDrawer = () => setMobileDrawerOpen(false);
router?.events.on("routeChangeStart", closeMobileDrawer);
return () => {
router?.events.off("routeChangeStart", closeMobileDrawer);
};
}, [router]);
const [searchOpen, setSearchOpenState] = React.useState(false);
const [searchReallyOpen, setSearchReallyOpenState] = React.useState(false);
const drawer = (
<div className={classes.drawerContainer}>
<Toolbar className={classes.drawerToolbar}>
<div />
<Link href="/" passHref>
<IconButton
size="small"
color="inherit"
aria-label="go to homepage"
title={`Architecture knowledge base of ${projectName}`}
>
<img
src={`${router?.basePath}/l4b-static/Log4brains-logo.png`}
alt="Log4brains logo"
width={40}
height={40}
/>
</IconButton>
</Link>
<IconButton
size="small"
color="inherit"
aria-label="close drawer"
title="Close"
onClick={handleMobileDrawerToggle}
>
<CloseIcon fontSize="small" />
</IconButton>
</Toolbar>
<div className={classes.adlTitleAndSpinner}>
<Typography variant="subtitle2" className={classes.adlTitle}>
Decision log
</Typography>
<Fade in={adrsReloading}>
<CircularProgress size={13} />
</Fade>
</div>
<Grow in={adrs !== undefined} style={{ transformOrigin: "center left" }}>
<AdrMenu
adrs={adrs}
currentAdrSlug={currentAdr?.slug}
className={classes.adrMenu}
/>
</Grow>
{adrs === undefined && (
<CircularProgress size={30} className={classes.adrMenuSpinner} />
)}
<List className={classes.bottomMenuList}>
{/* <Divider />
<ListItem button>
<ListItemIcon>
<ChevronRightIcon />
</ListItemIcon>
<ListItemText>
<Badge badgeContent={0} color="primary">
<Typography>Filters</Typography>
</Badge>
</ListItemText>
</ListItem> */}
{/* <Divider />
<Link href="/decision-backlog" passHref>
<ListItem button selected={backlog} component="a">
<ListItemIcon>
<PlaylistAddCheckIcon />
</ListItemIcon>
<ListItemText primary="Decision backlog" />
</ListItem>
</Link> */}
</List>
</div>
);
return (
<div className={classes.root}>
<AppBar position="fixed" className={classes.appBar}>
{routing && <RoutingProgress />}
<Toolbar>
<IconButton
color="inherit"
aria-label="open drawer"
edge="start"
onClick={handleMobileDrawerToggle}
className={classes.appBarMenuButton}
>
<MenuIcon />
</IconButton>
<Link href="/">
<div className={classes.appBarTitle}>
<div>
<img
src={`${router?.basePath}/l4b-static/Log4brains-logo-dark.png`}
alt="Log4brains logo"
width={50}
height={50}
/>
</div>
<div>
<Link href="/" passHref>
<MuiLink
variant="h6"
noWrap
className={classes.appBarTitleLink}
>
{projectName}
</MuiLink>
</Link>
<Link href="/" passHref>
<MuiLink
variant="body2"
noWrap
className={classes.appBarTitleLink}
>
Architecture knowledge base
</MuiLink>
</Link>
</div>
</div>
</Link>
<div className={classes.layoutLeftCol} />
<div className={clsx(classes.layoutCenterCol)}>
<Backdrop open={searchOpen} className={classes.searchBackdrop} />
<NoSsr>
<ConnectedSearchBox
onOpen={() => {
setSearchOpenState(true);
// Delayed real opening because otherwise the dropdown width is bugged
setTimeout(
() => setSearchReallyOpenState(true),
searchTransitionDuration + 100
);
}}
onClose={() => {
setSearchOpenState(false);
setSearchReallyOpenState(false);
}}
open={searchReallyOpen}
className={clsx(classes.searchBox, {
[classes.searchBoxOpen]: searchOpen
})}
/>
</NoSsr>
</div>
<div className={classes.layoutRightCol} />
</Toolbar>
</AppBar>
<nav
className={classes.drawer}
aria-label="architecture decision records list"
>
<Hidden smUp implementation="css">
<Drawer
variant="temporary"
anchor="left"
open={mobileDrawerOpen}
onClose={handleMobileDrawerToggle}
classes={{
paper: classes.drawerPaper
}}
ModalProps={{
keepMounted: true // Better open performance on mobile.
}}
>
{drawer}
</Drawer>
</Hidden>
<Hidden xsDown implementation="css">
<Drawer
variant="permanent"
open
classes={{
paper: classes.drawerPaper
}}
>
{drawer}
</Drawer>
</Hidden>
</nav>
<div className={classes.container}>
<Toolbar />
<main className={classes.content}>
<AdrNavContext.Provider
value={currentAdr && adrs ? buildAdrNav(currentAdr, adrs) : {}}
>
{children}
</AdrNavContext.Provider>
</main>
<footer className={classes.footer}>
<div className={classes.layoutLeftCol} />
<div className={clsx(classes.layoutCenterCol, classes.footerContent)}>
<Typography className={classes.footerText}>
Powered by{" "}
<MuiLink
href="https://github.com/thomvaill/log4brains"
className={classes.footerLink}
target="_blank"
rel="noopener"
>
Log4brains
</MuiLink>{" "}
<span style={{ fontSize: "0.8em" }}>
{l4bVersion ? `(v${l4bVersion})` : null}
</span>
</Typography>
</div>
<div className={classes.layoutRightCol} />
</footer>
</div>
</div>
);
} | the_stack |
import {
CdmCollection,
CdmCorpusContext,
CdmDataPartitionDefinition,
CdmDataPartitionPatternDefinition,
CdmEntityDeclarationDefinition,
CdmFileStatus,
cdmIncrementalPartitionType,
cdmLogCode,
CdmObject,
CdmObjectDefinitionBase,
cdmObjectType,
CdmTraitCollection,
CdmTraitReference,
CdmTraitReferenceBase,
constants,
Logger,
partitionFileStatusCheckType,
resolveOptions,
StorageAdapterBase,
StorageAdapterCacheContext,
VisitCallback
} from '../internal';
import * as timeUtils from '../Utilities/timeUtils';
import { StringUtils } from '../Utilities/StringUtils';
import { Argument } from '../Persistence/CdmFolder/types/Argument';
/**
* The object model implementation for local entity declaration.
*/
export class CdmLocalEntityDeclarationDefinition extends CdmObjectDefinitionBase implements CdmFileStatus, CdmEntityDeclarationDefinition {
private TAG: string = CdmLocalEntityDeclarationDefinition.name;
/**
* @inheritdoc
*/
public entityName: string;
/**
* @inheritdoc
*/
public entityPath: string;
/**
* @inheritdoc
* Note: Use setLastFileModifiedTime() for setting the value.
*/
public lastFileStatusCheckTime: Date;
/**
* @inheritdoc
*/
public lastFileModifiedTime: Date;
/**
* @inheritdoc
*/
public lastChildFileModifiedTime: Date;
private lastFileModifiedOldTime: Date;
public static get objectType(): cdmObjectType {
return cdmObjectType.localEntityDeclarationDef;
}
public readonly dataPartitions: CdmCollection<CdmDataPartitionDefinition>;
public readonly dataPartitionPatterns: CdmCollection<CdmDataPartitionPatternDefinition>;
public readonly incrementalPartitions: CdmCollection<CdmDataPartitionDefinition>;
public readonly incrementalPartitionPatterns: CdmCollection<CdmDataPartitionPatternDefinition>;
/**
* Initializes a new instance of the LocalEntityDeclarationImpl.
* @param ctx The context.
* @param entityName The entity name.
*/
constructor(ctx: CdmCorpusContext, entityName: string) {
super(ctx);
this.objectType = cdmObjectType.localEntityDeclarationDef;
this.entityName = entityName;
this.dataPartitions = new CdmCollection<CdmDataPartitionDefinition>(this.ctx, this, cdmObjectType.dataPartitionDef);
this.dataPartitionPatterns = new CdmCollection<CdmDataPartitionPatternDefinition>(this.ctx, this, cdmObjectType.dataPartitionDef);
this.incrementalPartitions = new CdmCollection<CdmDataPartitionDefinition>(this.ctx, this, cdmObjectType.dataPartitionDef);
this.incrementalPartitionPatterns = new CdmCollection<CdmDataPartitionPatternDefinition>(this.ctx, this, cdmObjectType.dataPartitionDef);
this.lastFileModifiedTime = null;
this.lastFileModifiedOldTime = null;
}
/**
* @inheritdoc
*/
public getObjectType(): cdmObjectType {
return cdmObjectType.localEntityDeclarationDef;
}
/**
* @inheritdoc
*/
public validate(): boolean {
if (!this.entityName) {
let missingFields: string[] = ['entityName'];
Logger.error(this.ctx, this.TAG, this.validate.name, this.atCorpusPath, cdmLogCode.ErrValdnIntegrityCheckFailure, missingFields.map((s: string) => `'${s}'`).join(', '), this.atCorpusPath);
return false;
}
return true;
}
/**
* @inheritdoc
*/
public copy(resOpt?: resolveOptions, host?: CdmObject): CdmLocalEntityDeclarationDefinition {
if (!resOpt) {
resOpt = new resolveOptions(this, this.ctx.corpus.defaultResolutionDirectives);
}
let copy: CdmLocalEntityDeclarationDefinition;
if (!host) {
copy = new CdmLocalEntityDeclarationDefinition(this.ctx, this.entityName);
} else {
copy = host as CdmLocalEntityDeclarationDefinition;
copy.entityName = this.entityName;
copy.dataPartitionPatterns.clear();
copy.dataPartitions.clear();
copy.incrementalPartitionPatterns.clear();
copy.incrementalPartitions.clear();
}
copy.entityPath = this.entityPath;
copy.lastFileStatusCheckTime = this.lastFileStatusCheckTime;
copy.lastFileModifiedTime = this.lastFileModifiedTime;
copy.lastChildFileModifiedTime = this.lastChildFileModifiedTime;
for (const partition of this.dataPartitions) {
copy.dataPartitions.push(partition.copy(resOpt) as CdmDataPartitionDefinition);
}
for (const pattern of this.dataPartitionPatterns) {
copy.dataPartitionPatterns.push(pattern.copy(resOpt) as CdmDataPartitionPatternDefinition);
}
for (const partition of this.incrementalPartitions) {
copy.incrementalPartitions.push(partition.copy(resOpt) as CdmDataPartitionDefinition);
}
for (const pattern of this.incrementalPartitionPatterns) {
copy.incrementalPartitionPatterns.push(pattern.copy(resOpt) as CdmDataPartitionPatternDefinition);
}
this.copyDef(resOpt, copy);
return copy;
}
/**
* @inheritdoc
*/
public getName(): string {
return this.entityName;
}
/**
* @inheritdoc
*/
public visit(pathFrom: string, preChildren: VisitCallback, postChildren: VisitCallback): boolean {
const path: string = this.fetchDeclaredPath(pathFrom);
if (preChildren && preChildren(this, path)) {
return false;
}
if (this.dataPartitions) {
if (this.dataPartitions.visitArray(`${path}/dataPartitions/`, preChildren, postChildren)) {
return true;
}
}
if (this.dataPartitionPatterns) {
if (this.dataPartitionPatterns.visitArray(`${path}/dataPartitionPatterns/`, preChildren, postChildren)) {
return true;
}
}
if (this.incrementalPartitions) {
if (this.incrementalPartitions.visitArray(`${path}/incrementalPartitions/`, preChildren, postChildren)) {
return true;
}
}
if (this.incrementalPartitionPatterns) {
if (this.incrementalPartitionPatterns.visitArray(`${path}/incrementalPartitionPatterns/`, preChildren, postChildren)) {
return true;
}
}
if (this.visitDef(path, preChildren, postChildren)) {
return true;
}
if (postChildren && postChildren(this, path)) {
return true;
}
return false;
}
/**
* @inheritdoc
*/
public isDerivedFrom(base: string, resOpt?: resolveOptions): boolean {
return false; // makes no sense
}
/**
* @inheritdoc
*/
public async fileStatusCheckAsync(partitionCheckType: partitionFileStatusCheckType = partitionFileStatusCheckType.Full, incrementalType: cdmIncrementalPartitionType = cdmIncrementalPartitionType.None): Promise<void> {
let adapter: StorageAdapterBase = this.ctx.corpus.storage.fetchAdapter(this.inDocument.namespace);
let cacheContext: StorageAdapterCacheContext = (adapter != null) ? adapter.createFileQueryCacheContext() : null;
try {
const fullPath: string = this.ctx.corpus.storage.createAbsoluteCorpusPath(this.entityPath, this.inDocument);
const modifiedTime: Date = await this.ctx.corpus.computeLastModifiedTimeAsync(fullPath, this);
// check patterns first as this is a more performant way of querying file modification times
// from ADLS and we can cache the times for reuse in the individual partition checks below
if (partitionCheckType === partitionFileStatusCheckType.Full || partitionCheckType === partitionFileStatusCheckType.FullAndIncremental) {
for (const pattern of this.dataPartitionPatterns) {
if (pattern.isIncremental) {
Logger.error(pattern.ctx, this.TAG, this.fileStatusCheckAsync.name, pattern.atCorpusPath, cdmLogCode.ErrUnexpectedIncrementalPartitionTrait,
CdmDataPartitionPatternDefinition.name, pattern.fetchObjectDefinitionName(), constants.INCREMENTAL_TRAIT_NAME, 'dataPartitionPatterns');
} else {
await pattern.fileStatusCheckAsync();
}
}
for (const partition of this.dataPartitions) {
if (partition.isIncremental) {
Logger.error(partition.ctx, this.TAG, this.fileStatusCheckAsync.name, partition.atCorpusPath, cdmLogCode.ErrUnexpectedIncrementalPartitionTrait,
CdmDataPartitionDefinition.name, partition.fetchObjectDefinitionName(), constants.INCREMENTAL_TRAIT_NAME, 'dataPartitions');
} else {
await partition.fileStatusCheckAsync();
}
}
}
if (partitionCheckType === partitionFileStatusCheckType.Incremental || partitionCheckType === partitionFileStatusCheckType.FullAndIncremental) {
for (const pattern of this.incrementalPartitionPatterns) {
if (this.shouldCallFileStatusCheck(incrementalType, true, pattern)) {
await pattern.fileStatusCheckAsync();
}
}
for (const partition of this.incrementalPartitions) {
if (this.shouldCallFileStatusCheck(incrementalType, false, partition)) {
await partition.fileStatusCheckAsync();
}
}
}
this.lastFileStatusCheckTime = new Date();
this.setLastFileModifiedTime(timeUtils.maxTime(modifiedTime, this.lastFileModifiedTime));
await this.reportMostRecentTimeAsync(this.lastFileModifiedTime);
}
finally {
if(cacheContext != null) {
cacheContext.dispose()
}
}
}
/**
* @internal
* Determine if calling FileStatusCheckAsync on the given pattern or the given partition is needed.
*/
public shouldCallFileStatusCheck(incrementalType: cdmIncrementalPartitionType, isPattern: boolean, patternOrPartitionObj: CdmObjectDefinitionBase): boolean {
var update = true;
var traitRef: CdmTraitReference = patternOrPartitionObj.exhibitsTraits.item(constants.INCREMENTAL_TRAIT_NAME) as CdmTraitReference;
if (traitRef === undefined){
Logger.error(patternOrPartitionObj.ctx, this.TAG, this.shouldCallFileStatusCheck.name, patternOrPartitionObj.atCorpusPath, cdmLogCode.ErrMissingIncrementalPartitionTrait,
isPattern ? CdmDataPartitionPatternDefinition.name : CdmDataPartitionDefinition.name, patternOrPartitionObj.fetchObjectDefinitionName(),
constants.INCREMENTAL_TRAIT_NAME, isPattern ? 'incrementalPartitionPatterns' : 'incrementalPartitions');
} else {
// None means update by default
if (incrementalType == cdmIncrementalPartitionType.None) {
return update;
}
var traitRefIncrementalTypeValue = traitRef.arguments?.fetchValue('type');
if (traitRefIncrementalTypeValue === undefined) {
update = false;
Logger.error(patternOrPartitionObj.ctx, this.TAG, this.shouldCallFileStatusCheck.name, patternOrPartitionObj.atCorpusPath, cdmLogCode.ErrTraitArgumentMissing,
'type', constants.INCREMENTAL_TRAIT_NAME, patternOrPartitionObj.fetchObjectDefinitionName());
} else if (typeof traitRefIncrementalTypeValue !== 'string') {
update = false;
Logger.error(patternOrPartitionObj.ctx, this.TAG, this.shouldCallFileStatusCheck.name, patternOrPartitionObj.atCorpusPath, cdmLogCode.ErrTraitInvalidArgumentValueType,
'type', constants.INCREMENTAL_TRAIT_NAME, patternOrPartitionObj.fetchObjectDefinitionName());
} else {
const traitRefIncrementalTypeValueStr = traitRefIncrementalTypeValue.toString()
if (Object.values(cdmIncrementalPartitionType).includes(traitRefIncrementalTypeValueStr)) {
update = cdmIncrementalPartitionType[traitRefIncrementalTypeValueStr as unknown as keyof cdmIncrementalPartitionType] === incrementalType;
} else {
update = false;
Logger.error(patternOrPartitionObj.ctx, this.TAG, this.shouldCallFileStatusCheck.name, patternOrPartitionObj.atCorpusPath, cdmLogCode.ErrEnumConversionFailure,
traitRefIncrementalTypeValue, 'cdmIncrementalPartitionType',
`'parameter 'type' of trait '${constants.INCREMENTAL_TRAIT_NAME}' from '${patternOrPartitionObj.fetchObjectDefinitionName()}'`);
}
}
}
return update;
}
/**
* @inheritdoc
*/
public async reportMostRecentTimeAsync(childTime: Date): Promise<void> {
this.lastChildFileModifiedTime = childTime;
const mostRecentAtThisLevel: Date = timeUtils.maxTime(childTime, this.lastFileModifiedTime);
if ((this.owner as CdmFileStatus).reportMostRecentTimeAsync && mostRecentAtThisLevel) {
await (this.owner as CdmFileStatus).reportMostRecentTimeAsync(mostRecentAtThisLevel);
}
}
/**
* @internal
* Creates a data partition object using the input, should be called by DataPartitionPattern object
* This function doesn't check if the data partition exists.
*/
public createDataPartitionFromPattern(
filePath: string,
exhibitsTraits: CdmTraitCollection,
args: Map<string, string[]>,
schema: string,
modifiedTime: Date,
isIncrementalPartition: boolean = false,
incrementPartitionPatternName: string = undefined): void {
const newPartition: CdmDataPartitionDefinition = this.ctx.corpus.MakeObject(cdmObjectType.dataPartitionDef);
newPartition.location = filePath;
newPartition.specializedSchema = schema;
newPartition.lastFileModifiedTime = modifiedTime;
newPartition.lastFileStatusCheckTime = new Date();
for (const trait of exhibitsTraits) {
newPartition.exhibitsTraits.push(trait.copy() as CdmTraitReferenceBase);
}
newPartition.arguments = new Map(args);
if (!isIncrementalPartition) {
this.dataPartitions.push(newPartition);
} else {
if (!StringUtils.isNullOrWhiteSpace(incrementPartitionPatternName)) {
(newPartition.exhibitsTraits.item(constants.INCREMENTAL_TRAIT_NAME) as CdmTraitReference).arguments.push(constants.INCREMENTAL_PATTERN_PARAMETER_NAME, incrementPartitionPatternName);
}
this.incrementalPartitions.push(newPartition)
}
}
public setLastFileModifiedTime(value : Date): void {
this.setLastFileModifiedOldTime(this.lastFileModifiedTime);
this.lastFileModifiedTime = value;
}
public getlastFileModifiedTime(): Date {
return this.lastFileModifiedTime;
}
private setLastFileModifiedOldTime(value: Date): void {
this.lastFileModifiedOldTime = value;
}
public getlastFileModifiedOldTime(): Date {
return this.lastFileModifiedOldTime;
}
public resetLastFileModifiedOldTime(): void {
this.setLastFileModifiedOldTime(null);
}
} | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { StorageAccounts } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { StorageManagementClient } from "../storageManagementClient";
import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro";
import { LroImpl } from "../lroImpl";
import {
StorageAccount,
StorageAccountsListNextOptionalParams,
StorageAccountsListOptionalParams,
StorageAccountsListByResourceGroupNextOptionalParams,
StorageAccountsListByResourceGroupOptionalParams,
StorageAccountCheckNameAvailabilityParameters,
StorageAccountsCheckNameAvailabilityOptionalParams,
StorageAccountsCheckNameAvailabilityResponse,
StorageAccountCreateParameters,
StorageAccountsCreateOptionalParams,
StorageAccountsCreateResponse,
StorageAccountsDeleteOptionalParams,
StorageAccountsGetPropertiesOptionalParams,
StorageAccountsGetPropertiesResponse,
StorageAccountUpdateParameters,
StorageAccountsUpdateOptionalParams,
StorageAccountsUpdateResponse,
StorageAccountsListResponse,
StorageAccountsListByResourceGroupResponse,
StorageAccountsListKeysOptionalParams,
StorageAccountsListKeysResponse,
StorageAccountRegenerateKeyParameters,
StorageAccountsRegenerateKeyOptionalParams,
StorageAccountsRegenerateKeyResponse,
AccountSasParameters,
StorageAccountsListAccountSASOptionalParams,
StorageAccountsListAccountSASResponse,
ServiceSasParameters,
StorageAccountsListServiceSASOptionalParams,
StorageAccountsListServiceSASResponse,
StorageAccountsFailoverOptionalParams,
StorageAccountsHierarchicalNamespaceMigrationOptionalParams,
StorageAccountsAbortHierarchicalNamespaceMigrationOptionalParams,
BlobRestoreParameters,
StorageAccountsRestoreBlobRangesOptionalParams,
StorageAccountsRestoreBlobRangesResponse,
StorageAccountsRevokeUserDelegationKeysOptionalParams,
StorageAccountsListNextResponse,
StorageAccountsListByResourceGroupNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing StorageAccounts operations. */
export class StorageAccountsImpl implements StorageAccounts {
private readonly client: StorageManagementClient;
/**
* Initialize a new instance of the class StorageAccounts class.
* @param client Reference to the service client
*/
constructor(client: StorageManagementClient) {
this.client = client;
}
/**
* Lists all the storage accounts available under the subscription. Note that storage keys are not
* returned; use the ListKeys operation for this.
* @param options The options parameters.
*/
public list(
options?: StorageAccountsListOptionalParams
): PagedAsyncIterableIterator<StorageAccount> {
const iter = this.listPagingAll(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listPagingPage(options);
}
};
}
private async *listPagingPage(
options?: StorageAccountsListOptionalParams
): AsyncIterableIterator<StorageAccount[]> {
let result = await this._list(options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listNext(continuationToken, options);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listPagingAll(
options?: StorageAccountsListOptionalParams
): AsyncIterableIterator<StorageAccount> {
for await (const page of this.listPagingPage(options)) {
yield* page;
}
}
/**
* Lists all the storage accounts available under the given resource group. Note that storage keys are
* not returned; use the ListKeys operation for this.
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param options The options parameters.
*/
public listByResourceGroup(
resourceGroupName: string,
options?: StorageAccountsListByResourceGroupOptionalParams
): PagedAsyncIterableIterator<StorageAccount> {
const iter = this.listByResourceGroupPagingAll(resourceGroupName, options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByResourceGroupPagingPage(resourceGroupName, options);
}
};
}
private async *listByResourceGroupPagingPage(
resourceGroupName: string,
options?: StorageAccountsListByResourceGroupOptionalParams
): AsyncIterableIterator<StorageAccount[]> {
let result = await this._listByResourceGroup(resourceGroupName, options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listByResourceGroupNext(
resourceGroupName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listByResourceGroupPagingAll(
resourceGroupName: string,
options?: StorageAccountsListByResourceGroupOptionalParams
): AsyncIterableIterator<StorageAccount> {
for await (const page of this.listByResourceGroupPagingPage(
resourceGroupName,
options
)) {
yield* page;
}
}
/**
* Checks that the storage account name is valid and is not already in use.
* @param accountName The name of the storage account within the specified resource group. Storage
* account names must be between 3 and 24 characters in length and use numbers and lower-case letters
* only.
* @param options The options parameters.
*/
checkNameAvailability(
accountName: StorageAccountCheckNameAvailabilityParameters,
options?: StorageAccountsCheckNameAvailabilityOptionalParams
): Promise<StorageAccountsCheckNameAvailabilityResponse> {
return this.client.sendOperationRequest(
{ accountName, options },
checkNameAvailabilityOperationSpec
);
}
/**
* Asynchronously creates a new storage account with the specified parameters. If an account is already
* created and a subsequent create request is issued with different properties, the account properties
* will be updated. If an account is already created and a subsequent create or update request is
* issued with the exact same set of properties, the request will succeed.
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage
* account names must be between 3 and 24 characters in length and use numbers and lower-case letters
* only.
* @param parameters The parameters to provide for the created account.
* @param options The options parameters.
*/
async beginCreate(
resourceGroupName: string,
accountName: string,
parameters: StorageAccountCreateParameters,
options?: StorageAccountsCreateOptionalParams
): Promise<
PollerLike<
PollOperationState<StorageAccountsCreateResponse>,
StorageAccountsCreateResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<StorageAccountsCreateResponse> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ resourceGroupName, accountName, parameters, options },
createOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Asynchronously creates a new storage account with the specified parameters. If an account is already
* created and a subsequent create request is issued with different properties, the account properties
* will be updated. If an account is already created and a subsequent create or update request is
* issued with the exact same set of properties, the request will succeed.
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage
* account names must be between 3 and 24 characters in length and use numbers and lower-case letters
* only.
* @param parameters The parameters to provide for the created account.
* @param options The options parameters.
*/
async beginCreateAndWait(
resourceGroupName: string,
accountName: string,
parameters: StorageAccountCreateParameters,
options?: StorageAccountsCreateOptionalParams
): Promise<StorageAccountsCreateResponse> {
const poller = await this.beginCreate(
resourceGroupName,
accountName,
parameters,
options
);
return poller.pollUntilDone();
}
/**
* Deletes a storage account in Microsoft Azure.
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage
* account names must be between 3 and 24 characters in length and use numbers and lower-case letters
* only.
* @param options The options parameters.
*/
delete(
resourceGroupName: string,
accountName: string,
options?: StorageAccountsDeleteOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, options },
deleteOperationSpec
);
}
/**
* Returns the properties for the specified storage account including but not limited to name, SKU
* name, location, and account status. The ListKeys operation should be used to retrieve storage keys.
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage
* account names must be between 3 and 24 characters in length and use numbers and lower-case letters
* only.
* @param options The options parameters.
*/
getProperties(
resourceGroupName: string,
accountName: string,
options?: StorageAccountsGetPropertiesOptionalParams
): Promise<StorageAccountsGetPropertiesResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, options },
getPropertiesOperationSpec
);
}
/**
* The update operation can be used to update the SKU, encryption, access tier, or tags for a storage
* account. It can also be used to map the account to a custom domain. Only one custom domain is
* supported per storage account; the replacement/change of custom domain is not supported. In order to
* replace an old custom domain, the old value must be cleared/unregistered before a new value can be
* set. The update of multiple properties is supported. This call does not change the storage keys for
* the account. If you want to change the storage account keys, use the regenerate keys operation. The
* location and name of the storage account cannot be changed after creation.
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage
* account names must be between 3 and 24 characters in length and use numbers and lower-case letters
* only.
* @param parameters The parameters to provide for the updated account.
* @param options The options parameters.
*/
update(
resourceGroupName: string,
accountName: string,
parameters: StorageAccountUpdateParameters,
options?: StorageAccountsUpdateOptionalParams
): Promise<StorageAccountsUpdateResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, parameters, options },
updateOperationSpec
);
}
/**
* Lists all the storage accounts available under the subscription. Note that storage keys are not
* returned; use the ListKeys operation for this.
* @param options The options parameters.
*/
private _list(
options?: StorageAccountsListOptionalParams
): Promise<StorageAccountsListResponse> {
return this.client.sendOperationRequest({ options }, listOperationSpec);
}
/**
* Lists all the storage accounts available under the given resource group. Note that storage keys are
* not returned; use the ListKeys operation for this.
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param options The options parameters.
*/
private _listByResourceGroup(
resourceGroupName: string,
options?: StorageAccountsListByResourceGroupOptionalParams
): Promise<StorageAccountsListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, options },
listByResourceGroupOperationSpec
);
}
/**
* Lists the access keys or Kerberos keys (if active directory enabled) for the specified storage
* account.
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage
* account names must be between 3 and 24 characters in length and use numbers and lower-case letters
* only.
* @param options The options parameters.
*/
listKeys(
resourceGroupName: string,
accountName: string,
options?: StorageAccountsListKeysOptionalParams
): Promise<StorageAccountsListKeysResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, options },
listKeysOperationSpec
);
}
/**
* Regenerates one of the access keys or Kerberos keys for the specified storage account.
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage
* account names must be between 3 and 24 characters in length and use numbers and lower-case letters
* only.
* @param regenerateKey Specifies name of the key which should be regenerated -- key1, key2, kerb1,
* kerb2.
* @param options The options parameters.
*/
regenerateKey(
resourceGroupName: string,
accountName: string,
regenerateKey: StorageAccountRegenerateKeyParameters,
options?: StorageAccountsRegenerateKeyOptionalParams
): Promise<StorageAccountsRegenerateKeyResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, regenerateKey, options },
regenerateKeyOperationSpec
);
}
/**
* List SAS credentials of a storage account.
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage
* account names must be between 3 and 24 characters in length and use numbers and lower-case letters
* only.
* @param parameters The parameters to provide to list SAS credentials for the storage account.
* @param options The options parameters.
*/
listAccountSAS(
resourceGroupName: string,
accountName: string,
parameters: AccountSasParameters,
options?: StorageAccountsListAccountSASOptionalParams
): Promise<StorageAccountsListAccountSASResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, parameters, options },
listAccountSASOperationSpec
);
}
/**
* List service SAS credentials of a specific resource.
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage
* account names must be between 3 and 24 characters in length and use numbers and lower-case letters
* only.
* @param parameters The parameters to provide to list service SAS credentials.
* @param options The options parameters.
*/
listServiceSAS(
resourceGroupName: string,
accountName: string,
parameters: ServiceSasParameters,
options?: StorageAccountsListServiceSASOptionalParams
): Promise<StorageAccountsListServiceSASResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, parameters, options },
listServiceSASOperationSpec
);
}
/**
* Failover request can be triggered for a storage account in case of availability issues. The failover
* occurs from the storage account's primary cluster to secondary cluster for RA-GRS accounts. The
* secondary cluster will become primary after failover.
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage
* account names must be between 3 and 24 characters in length and use numbers and lower-case letters
* only.
* @param options The options parameters.
*/
async beginFailover(
resourceGroupName: string,
accountName: string,
options?: StorageAccountsFailoverOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<void> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ resourceGroupName, accountName, options },
failoverOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs,
lroResourceLocationConfig: "location"
});
}
/**
* Failover request can be triggered for a storage account in case of availability issues. The failover
* occurs from the storage account's primary cluster to secondary cluster for RA-GRS accounts. The
* secondary cluster will become primary after failover.
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage
* account names must be between 3 and 24 characters in length and use numbers and lower-case letters
* only.
* @param options The options parameters.
*/
async beginFailoverAndWait(
resourceGroupName: string,
accountName: string,
options?: StorageAccountsFailoverOptionalParams
): Promise<void> {
const poller = await this.beginFailover(
resourceGroupName,
accountName,
options
);
return poller.pollUntilDone();
}
/**
* Live Migration of storage account to enable Hns
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage
* account names must be between 3 and 24 characters in length and use numbers and lower-case letters
* only.
* @param requestType Required. Hierarchical namespace migration type can either be a hierarchical
* namespace validation request 'HnsOnValidationRequest' or a hydration request
* 'HnsOnHydrationRequest'. The validation request will validate the migration whereas the hydration
* request will migrate the account.
* @param options The options parameters.
*/
async beginHierarchicalNamespaceMigration(
resourceGroupName: string,
accountName: string,
requestType: string,
options?: StorageAccountsHierarchicalNamespaceMigrationOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<void> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ resourceGroupName, accountName, requestType, options },
hierarchicalNamespaceMigrationOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs,
lroResourceLocationConfig: "location"
});
}
/**
* Live Migration of storage account to enable Hns
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage
* account names must be between 3 and 24 characters in length and use numbers and lower-case letters
* only.
* @param requestType Required. Hierarchical namespace migration type can either be a hierarchical
* namespace validation request 'HnsOnValidationRequest' or a hydration request
* 'HnsOnHydrationRequest'. The validation request will validate the migration whereas the hydration
* request will migrate the account.
* @param options The options parameters.
*/
async beginHierarchicalNamespaceMigrationAndWait(
resourceGroupName: string,
accountName: string,
requestType: string,
options?: StorageAccountsHierarchicalNamespaceMigrationOptionalParams
): Promise<void> {
const poller = await this.beginHierarchicalNamespaceMigration(
resourceGroupName,
accountName,
requestType,
options
);
return poller.pollUntilDone();
}
/**
* Abort live Migration of storage account to enable Hns
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage
* account names must be between 3 and 24 characters in length and use numbers and lower-case letters
* only.
* @param options The options parameters.
*/
async beginAbortHierarchicalNamespaceMigration(
resourceGroupName: string,
accountName: string,
options?: StorageAccountsAbortHierarchicalNamespaceMigrationOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<void> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ resourceGroupName, accountName, options },
abortHierarchicalNamespaceMigrationOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs,
lroResourceLocationConfig: "location"
});
}
/**
* Abort live Migration of storage account to enable Hns
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage
* account names must be between 3 and 24 characters in length and use numbers and lower-case letters
* only.
* @param options The options parameters.
*/
async beginAbortHierarchicalNamespaceMigrationAndWait(
resourceGroupName: string,
accountName: string,
options?: StorageAccountsAbortHierarchicalNamespaceMigrationOptionalParams
): Promise<void> {
const poller = await this.beginAbortHierarchicalNamespaceMigration(
resourceGroupName,
accountName,
options
);
return poller.pollUntilDone();
}
/**
* Restore blobs in the specified blob ranges
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage
* account names must be between 3 and 24 characters in length and use numbers and lower-case letters
* only.
* @param parameters The parameters to provide for restore blob ranges.
* @param options The options parameters.
*/
async beginRestoreBlobRanges(
resourceGroupName: string,
accountName: string,
parameters: BlobRestoreParameters,
options?: StorageAccountsRestoreBlobRangesOptionalParams
): Promise<
PollerLike<
PollOperationState<StorageAccountsRestoreBlobRangesResponse>,
StorageAccountsRestoreBlobRangesResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<StorageAccountsRestoreBlobRangesResponse> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ resourceGroupName, accountName, parameters, options },
restoreBlobRangesOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs,
lroResourceLocationConfig: "location"
});
}
/**
* Restore blobs in the specified blob ranges
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage
* account names must be between 3 and 24 characters in length and use numbers and lower-case letters
* only.
* @param parameters The parameters to provide for restore blob ranges.
* @param options The options parameters.
*/
async beginRestoreBlobRangesAndWait(
resourceGroupName: string,
accountName: string,
parameters: BlobRestoreParameters,
options?: StorageAccountsRestoreBlobRangesOptionalParams
): Promise<StorageAccountsRestoreBlobRangesResponse> {
const poller = await this.beginRestoreBlobRanges(
resourceGroupName,
accountName,
parameters,
options
);
return poller.pollUntilDone();
}
/**
* Revoke user delegation keys.
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage
* account names must be between 3 and 24 characters in length and use numbers and lower-case letters
* only.
* @param options The options parameters.
*/
revokeUserDelegationKeys(
resourceGroupName: string,
accountName: string,
options?: StorageAccountsRevokeUserDelegationKeysOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, options },
revokeUserDelegationKeysOperationSpec
);
}
/**
* ListNext
* @param nextLink The nextLink from the previous successful call to the List method.
* @param options The options parameters.
*/
private _listNext(
nextLink: string,
options?: StorageAccountsListNextOptionalParams
): Promise<StorageAccountsListNextResponse> {
return this.client.sendOperationRequest(
{ nextLink, options },
listNextOperationSpec
);
}
/**
* ListByResourceGroupNext
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param nextLink The nextLink from the previous successful call to the ListByResourceGroup method.
* @param options The options parameters.
*/
private _listByResourceGroupNext(
resourceGroupName: string,
nextLink: string,
options?: StorageAccountsListByResourceGroupNextOptionalParams
): Promise<StorageAccountsListByResourceGroupNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, nextLink, options },
listByResourceGroupNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const checkNameAvailabilityOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/providers/Microsoft.Storage/checkNameAvailability",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.CheckNameAvailabilityResult
}
},
requestBody: Parameters.accountName,
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.$host, Parameters.subscriptionId],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const createOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.StorageAccount
},
201: {
bodyMapper: Mappers.StorageAccount
},
202: {
bodyMapper: Mappers.StorageAccount
},
204: {
bodyMapper: Mappers.StorageAccount
}
},
requestBody: Parameters.parameters,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName1
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const deleteOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}",
httpMethod: "DELETE",
responses: { 200: {}, 204: {} },
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName1
],
serializer
};
const getPropertiesOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.StorageAccount
}
},
queryParameters: [Parameters.apiVersion, Parameters.expand],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName1
],
headerParameters: [Parameters.accept],
serializer
};
const updateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}",
httpMethod: "PATCH",
responses: {
200: {
bodyMapper: Mappers.StorageAccount
}
},
requestBody: Parameters.parameters1,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName1
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const listOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/providers/Microsoft.Storage/storageAccounts",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.StorageAccountListResult
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.$host, Parameters.subscriptionId],
headerParameters: [Parameters.accept],
serializer
};
const listByResourceGroupOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.StorageAccountListResult
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName
],
headerParameters: [Parameters.accept],
serializer
};
const listKeysOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/listKeys",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.StorageAccountListKeysResult
}
},
queryParameters: [Parameters.apiVersion, Parameters.expand1],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName1
],
headerParameters: [Parameters.accept],
serializer
};
const regenerateKeyOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/regenerateKey",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.StorageAccountListKeysResult
}
},
requestBody: Parameters.regenerateKey,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName1
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const listAccountSASOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/ListAccountSas",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.ListAccountSasResponse
}
},
requestBody: Parameters.parameters2,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName1
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const listServiceSASOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/ListServiceSas",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.ListServiceSasResponse
}
},
requestBody: Parameters.parameters3,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName1
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const failoverOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/failover",
httpMethod: "POST",
responses: { 200: {}, 201: {}, 202: {}, 204: {} },
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName1
],
serializer
};
const hierarchicalNamespaceMigrationOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/hnsonmigration",
httpMethod: "POST",
responses: {
200: {},
201: {},
202: {},
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion, Parameters.requestType],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName1
],
headerParameters: [Parameters.accept],
serializer
};
const abortHierarchicalNamespaceMigrationOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/aborthnsonmigration",
httpMethod: "POST",
responses: {
200: {},
201: {},
202: {},
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName1
],
headerParameters: [Parameters.accept],
serializer
};
const restoreBlobRangesOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/restoreBlobRanges",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.BlobRestoreStatus
},
201: {
bodyMapper: Mappers.BlobRestoreStatus
},
202: {
bodyMapper: Mappers.BlobRestoreStatus
},
204: {
bodyMapper: Mappers.BlobRestoreStatus
}
},
requestBody: Parameters.parameters4,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName1
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const revokeUserDelegationKeysOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/revokeUserDelegationKeys",
httpMethod: "POST",
responses: { 200: {} },
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName1
],
serializer
};
const listNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.StorageAccountListResult
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
};
const listByResourceGroupNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.StorageAccountListResult
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import { SyntaxNode } from "web-tree-sitter";
import { TreeUtils } from "../util/treeUtils";
import {
Expression,
EValueDeclaration,
mapSyntaxNodeToExpression,
ETypeAliasDeclaration,
ETypeDeclaration,
EUnionVariant,
EPortAnnotation,
} from "./utils/expressionTree";
import { IProgram } from "./program";
import { container } from "tsyringe";
import { Connection } from "vscode-languageserver";
import {
Type,
TUnknown,
InferenceScope,
InferenceResult,
} from "./typeInference";
import { ISourceFile } from "./forest";
import { IImport, Imports } from "./imports";
import { TypeRenderer } from "./typeRenderer";
import { performance } from "perf_hooks";
import { bindTreeContainer, ISymbol } from "./binder";
import { Sequence } from "../util/sequence";
import { Utils } from "../util/utils";
import { TypeExpression } from "./typeExpression";
import { ICancellationToken } from "../cancellation";
import { Diagnostic, Diagnostics, error } from "./diagnostics";
import { isKernelProject, nameIsKernel } from "./utils/elmUtils";
import { existsSync } from "fs";
import * as path from "../util/path";
import { URI } from "vscode-uri";
export let bindTime = 0;
export function resetBindTime(): void {
bindTime = 0;
}
export interface DefinitionResult {
symbol?: ISymbol;
diagnostics: Diagnostic[];
}
class DiagnosticsCollection extends Map<string, Diagnostic[]> {
public add(diagnostic: Diagnostic): void {
let diagnostics = super.get(diagnostic.uri);
if (!diagnostics) {
diagnostics = [];
super.set(diagnostic.uri, diagnostics);
}
diagnostics.push(diagnostic);
}
public get(uri: string): Diagnostic[] {
return super.get(uri) ?? [];
}
}
export interface TypeChecker {
findType: (node: SyntaxNode) => Type;
findDefinition: (
node: SyntaxNode,
sourceFile: ISourceFile,
) => DefinitionResult;
findDefinitionShallow: (
node: SyntaxNode,
sourceFile: ISourceFile,
) => DefinitionResult;
getAllImports: (sourceFile: ISourceFile) => Imports;
getQualifierForName: (
sourceFile: ISourceFile,
module: string,
name: string,
) => string | undefined;
typeToString: (t: Type, sourceFile?: ISourceFile) => string;
getDiagnostics: (
sourceFile: ISourceFile,
cancellationToken?: ICancellationToken,
) => Diagnostic[];
getDiagnosticsAsync: (
sourceFile: ISourceFile,
token?: ICancellationToken,
cancelCallback?: () => boolean,
) => Promise<Diagnostic[]>;
getSuggestionDiagnostics: (
sourceFile: ISourceFile,
cancellationToken?: ICancellationToken,
) => Diagnostic[];
findImportModuleNameNodes: (
moduleNameOrAlias: string,
sourceFile: ISourceFile,
) => SyntaxNode[];
}
export function createTypeChecker(program: IProgram): TypeChecker {
const forest = program.getForest();
const imports = new Map<string, Imports>();
const diagnostics = new DiagnosticsCollection();
const suggestionDiagnostics = new DiagnosticsCollection();
let cancellationToken: ICancellationToken | undefined;
const checkedNodes = new Set<number>();
const start = performance.now();
forest.treeMap.forEach((sourceFile) => {
bindTreeContainer(sourceFile);
});
bindTime = performance.now() - start;
const typeChecker: TypeChecker = {
findType,
findDefinition,
findDefinitionShallow,
getAllImports,
getQualifierForName,
typeToString,
getDiagnostics,
getDiagnosticsAsync,
getSuggestionDiagnostics,
findImportModuleNameNodes,
};
return typeChecker;
function findType(node: SyntaxNode): Type {
try {
const declaration = mapSyntaxNodeToExpression(
TreeUtils.findParentOfType("value_declaration", node, true),
);
const uri = node.tree.uri;
const findTypeOrParentType = (
expr: SyntaxNode | undefined,
inferenceResult: InferenceResult,
): Type | undefined => {
const found = expr
? inferenceResult.expressionTypes.get(expr as Expression)
: undefined;
if (found) {
return found;
}
// Check if the parent is the same text and position
if (
expr &&
expr.text === expr.parent?.text &&
expr.startIndex === expr.parent?.startIndex &&
expr.endIndex === expr.parent?.endIndex
) {
return findTypeOrParentType(expr.parent, inferenceResult);
}
};
if (declaration && declaration.nodeType === "ValueDeclaration") {
const inferenceResult = InferenceScope.valueDeclarationInference(
declaration,
uri,
program,
new Set<EValueDeclaration>(),
);
if (node?.type === "function_declaration_left") {
const declaration = TreeUtils.findParentOfType(
"value_declaration",
node,
);
if (declaration) {
return (
inferenceResult.expressionTypes.get(declaration as Expression) ??
inferenceResult.type
);
} else {
return TUnknown;
}
} else if (node.type === "value_declaration") {
return (
inferenceResult.expressionTypes.get(node as Expression) ??
inferenceResult.type
);
}
return findTypeOrParentType(node, inferenceResult) ?? TUnknown;
}
const typeAliasDeclaration = mapSyntaxNodeToExpression(
TreeUtils.findParentOfType("type_alias_declaration", node),
);
if (
typeAliasDeclaration &&
typeAliasDeclaration.nodeType === "TypeAliasDeclaration"
) {
const inferenceResult = TypeExpression.typeAliasDeclarationInference(
typeAliasDeclaration,
program,
);
if (node.type === "type_alias_declaration") {
return inferenceResult.type;
}
return findTypeOrParentType(node, inferenceResult) ?? TUnknown;
}
const unionVariant =
node.type === "union_variant"
? mapSyntaxNodeToExpression(node)
: undefined;
if (unionVariant && unionVariant.nodeType === "UnionVariant") {
return TypeExpression.unionVariantInference(unionVariant, program).type;
}
const typeDeclaration = mapSyntaxNodeToExpression(
TreeUtils.findParentOfType("type_declaration", node),
);
if (typeDeclaration && typeDeclaration.nodeType === "TypeDeclaration") {
const inferenceResult = TypeExpression.typeDeclarationInference(
typeDeclaration,
program,
);
return findTypeOrParentType(node, inferenceResult) ?? TUnknown;
}
const portAnnotation = mapSyntaxNodeToExpression(node);
if (portAnnotation && portAnnotation.nodeType === "PortAnnotation") {
return TypeExpression.portAnnotationInference(portAnnotation, program)
.type;
}
return TUnknown;
} catch (error) {
const connection = container.resolve<Connection>("Connection");
connection.console.warn(`Error while trying to infer a type. ${error}`);
return TUnknown;
}
}
function getDiagnostics(
sourceFile: ISourceFile,
token?: ICancellationToken,
): Diagnostic[] {
try {
cancellationToken = token;
checkNode(sourceFile.tree.rootNode);
return diagnostics.get(sourceFile.uri);
} finally {
cancellationToken = undefined;
}
}
function getDiagnosticsAsync(
sourceFile: ISourceFile,
token?: ICancellationToken,
cancelCallback?: () => boolean,
): Promise<Diagnostic[]> {
cancellationToken = token;
return new Promise((resolve, reject) => {
const children = sourceFile.tree.rootNode.children;
let index = 0;
const goNext = (): void => {
index++;
if (children.length > index) {
setImmediate(checkOne);
} else {
cancellationToken = undefined;
resolve(diagnostics.get(sourceFile.uri));
}
};
const checkOne = (): void => {
if (cancelCallback && cancelCallback()) {
reject();
return;
}
try {
checkNode(children[index]);
} catch {
cancellationToken = undefined;
reject();
return;
}
goNext();
};
checkOne();
});
}
function getSuggestionDiagnostics(
sourceFile: ISourceFile,
token?: ICancellationToken,
): Diagnostic[] {
try {
cancellationToken = token;
checkNode(sourceFile.tree.rootNode);
return suggestionDiagnostics.get(sourceFile.uri);
} finally {
cancellationToken = undefined;
}
}
function getAllImports(sourceFile: ISourceFile): Imports {
const cached = imports.get(sourceFile.uri);
if (cached) {
return cached;
}
const allImports = Imports.getImports(sourceFile, forest);
allImports.getDiagnostics().forEach((diagnostic) => {
diagnostics.add(diagnostic);
});
imports.set(sourceFile.uri, allImports);
return allImports;
}
function findImport(
sourceFile: ISourceFile,
name: string,
type?: "Var" | "Type" | "Constructor" | "Module",
): IImport[] {
const allImports = getAllImports(sourceFile);
if (type === "Type") {
return allImports.getType(name);
} else if (type === "Constructor") {
return allImports.getConstructor(name);
} else if (type === "Module") {
const module = allImports.getModule(name);
if (module) {
return [module];
} else {
return [];
}
} else if (type === "Var") {
return allImports.getVar(name);
}
let result = allImports.getVar(name);
if (result.length > 0) {
return result;
}
result = allImports.getType(name);
if (result.length > 0) {
return result;
}
return allImports.getConstructor(name);
}
function findDefinition(
nodeAtPosition: SyntaxNode,
sourceFile: ISourceFile,
): DefinitionResult {
const definition = findDefinitionShallow(nodeAtPosition, sourceFile);
if (
definition.symbol?.node?.type === "lower_pattern" &&
definition.symbol.node.firstNamedChild
) {
const innerDefinition = findDefinitionShallow(
definition.symbol.node.firstNamedChild,
sourceFile,
);
if (innerDefinition.symbol) {
return innerDefinition;
}
}
return definition;
}
function findDefinitionShallow(
nodeAtPosition: SyntaxNode,
sourceFile: ISourceFile,
): DefinitionResult {
const nodeText = nodeAtPosition.text;
const nodeParent = nodeAtPosition.parent;
if (!nodeParent) {
return { diagnostics: [] };
}
const nodeParentType = nodeParent.type;
const rootSymbols = sourceFile.symbolLinks?.get(sourceFile.tree.rootNode);
if (
nodeParentType === "upper_case_qid" &&
nodeParent.previousNamedSibling?.type === "module"
) {
const moduleNode = nodeParent.parent;
if (moduleNode) {
return {
symbol: { name: moduleNode.text, node: moduleNode, type: "Module" },
diagnostics: [],
};
}
} else if (
nodeParentType === "upper_case_qid" &&
nodeParent.previousNamedSibling?.type === "import"
) {
const upperCaseQid = nodeParent;
const upperCaseQidText = upperCaseQid.text;
return {
symbol: findImport(sourceFile, upperCaseQidText, "Module")[0],
diagnostics: [],
};
} else if (
(nodeParentType === "exposed_value" &&
nodeParent.parent?.parent?.type === "module_declaration") ||
nodeParentType === "type_annotation" ||
nodeParentType === "port_annotation"
) {
const symbol = rootSymbols?.get(nodeText);
if (symbol && (symbol.type === "Function" || symbol.type === "Port")) {
return {
symbol,
diagnostics: [],
};
}
} else if (
(nodeParentType === "exposed_type" &&
nodeParent.parent?.parent?.type === "module_declaration") ||
nodeAtPosition.previousNamedSibling?.type === "type" ||
nodeAtPosition.previousNamedSibling?.type === "alias"
) {
return {
symbol: rootSymbols?.get(
nodeText,
(symbol) => symbol.type === "Type" || symbol.type === "TypeAlias",
),
diagnostics: [],
};
} else if (
(nodeParentType === "exposed_value" ||
nodeParentType === "exposed_type") &&
nodeParent.parent?.parent?.type === "import_clause"
) {
const moduleName =
nodeParent.parent?.parent.childForFieldName("moduleName")?.text ?? "";
const imports = findImport(
sourceFile,
nodeText,
nodeParentType === "exposed_value" ? "Var" : "Type",
).filter((imp) => imp.fromModule.name === moduleName);
return {
symbol: imports[0],
diagnostics: [],
};
} else if (nodeParentType === "union_variant") {
const definitionNode = nodeParent;
return {
symbol: {
name: definitionNode.text,
node: definitionNode,
type: "UnionConstructor",
},
diagnostics: [],
};
} else if (nodeParent && nodeParent.type === "upper_case_qid") {
const upperCaseQid = nodeParent;
const upperCaseQidText = upperCaseQid.text;
// Usage is either a type or a constructor
// A type can only be used as a type
// A union variant can only be used as a constructor or as a pattern
// A type alias can be used as both a type and a constructor
const isTypeUsage =
TreeUtils.findParentOfType("type_ref", upperCaseQid) ||
upperCaseQid.parent?.type === "exposed_type";
const isConstructorUsage = upperCaseQid.parent?.type === "value_expr";
const localSymbols =
rootSymbols
?.getAll(upperCaseQidText)
?.filter((symbol) =>
isTypeUsage
? symbol.type === "Type" || symbol.type === "TypeAlias"
: isConstructorUsage
? symbol.type === "UnionConstructor" ||
(symbol.type === "TypeAlias" && symbol.constructors?.length)
: symbol.type === "UnionConstructor",
) ?? [];
if (localSymbols.length > 0) {
return {
symbol: localSymbols[0],
diagnostics: [],
};
}
const imports = findImport(
sourceFile,
upperCaseQidText,
isTypeUsage ? "Type" : "Constructor",
);
if (imports.length > 0) {
return {
symbol: imports.length === 1 ? imports[0] : undefined,
diagnostics:
imports.length > 1
? [
error(
upperCaseQid,
isTypeUsage
? Diagnostics.AmbiguousType
: Diagnostics.AmbiguousVariant,
upperCaseQidText,
),
]
: [],
};
}
// Make sure the next node is a dot, or else it isn't a Module
if (TreeUtils.nextNode(nodeAtPosition)?.type === "dot") {
const endPos = upperCaseQidText.indexOf(nodeText) + nodeText.length;
const moduleNameOrAlias = nodeParent.text.substring(0, endPos);
const moduleName =
findImportModuleNameNodes(moduleNameOrAlias, sourceFile)[0]?.text ??
moduleNameOrAlias;
const moduleImport = findImport(sourceFile, moduleName, "Module")[0];
if (moduleImport) {
return {
symbol: moduleImport,
diagnostics: [],
};
}
}
const moduleImport = findImport(
sourceFile,
findImportModuleNameNodes(upperCaseQidText, sourceFile)[0]?.text ??
upperCaseQidText,
"Module",
)[0];
if (moduleImport) {
return {
symbol: moduleImport,
diagnostics: [],
};
}
} else if (
nodeParentType === "lower_pattern" &&
nodeParent.parent?.type === "record_pattern"
) {
const type = findType(nodeParent.parent);
return {
symbol: TreeUtils.findFieldReference(type, nodeText),
diagnostics: [],
};
} else if (
nodeAtPosition.type === "lower_case_identifier" &&
nodeParentType === "function_declaration_left" &&
nodeParent.parent?.type === "value_declaration"
) {
// The function name should resolve to itself
if (nodeParent.firstNamedChild?.text === nodeText) {
return {
symbol: { name: nodeParent.text, node: nodeParent, type: "Function" },
diagnostics: [],
};
}
} else if (
nodeParentType === "value_qid" ||
nodeParentType === "lower_pattern" ||
nodeParentType === "record_base_identifier"
) {
let nodeAtPositionText = nodeText;
if (nodeParentType === "value_qid") {
nodeAtPositionText = nodeParent.text;
}
// Traverse the parents and find a binding
// For operator functions, there are two bindings:
// The infix declaration and the function
// Never resolve to the infix declaration
const localBinding = new Sequence(
nodeAtPosition,
(node) => node.parent ?? undefined,
)
.map((node) =>
sourceFile.symbolLinks
?.get(node)
?.get(
nodeAtPositionText,
(s) => s.node.type !== "infix_declaration",
),
)
.find(Utils.notUndefined);
if (localBinding) {
return {
symbol: localBinding,
diagnostics: [],
};
} else {
const nodeParentText = nodeParent.text;
// Get the full module name and handle an import alias if there is one
if (nodeAtPosition.type === "upper_case_identifier") {
const moduleNameOrAlias =
TreeUtils.findAllNamedChildrenOfType(
"upper_case_identifier",
nodeParent,
)
?.map((node) => node.text)
.join(".") ?? "";
const moduleName =
findImportModuleNameNodes(moduleNameOrAlias, sourceFile)[0]?.text ??
moduleNameOrAlias;
const moduleImport = findImport(sourceFile, moduleName, "Module")[0];
if (moduleImport) {
return {
symbol: moduleImport,
diagnostics: [],
};
}
}
const imports = findImport(sourceFile, nodeParentText, "Var");
return {
symbol: imports.length === 1 ? imports[0] : undefined,
diagnostics:
imports.length > 1
? [error(nodeParent, Diagnostics.AmbiguousVar, nodeParentText)]
: [],
};
}
} else if (nodeAtPosition.type === "operator_identifier") {
const operatorsCache = program.getOperatorsCache();
const cached = operatorsCache.get(nodeText);
if (cached) {
return cached;
}
const definitionNode = TreeUtils.findOperator(sourceFile, nodeText);
if (definitionNode) {
const result: DefinitionResult = {
symbol: {
name: definitionNode.text,
node: definitionNode,
type: "Operator",
},
diagnostics: [],
};
operatorsCache.set(nodeText, Object.freeze(result));
return result;
} else {
const operatorImport = findImport(sourceFile, nodeText, "Var")[0];
if (operatorImport) {
const result: DefinitionResult = {
symbol: operatorImport,
diagnostics: [],
};
operatorsCache.set(nodeText, Object.freeze(result));
return result;
}
}
} else if (nodeParentType === "field_access_expr") {
let target = nodeParent?.childForFieldName("target");
// Adjust for parenthesis expr. Will need to change when we handle it better in inference
if (target?.type === "parenthesized_expr") {
target = target.firstNamedChild;
}
if (target) {
const type = findType(target);
return {
symbol: TreeUtils.findFieldReference(type, nodeText),
diagnostics: [],
};
}
} else if (
nodeAtPosition.type === "lower_case_identifier" &&
nodeParentType === "field" &&
nodeParent.parent?.type === "record_expr"
) {
const type = findType(nodeParent.parent);
return {
symbol: TreeUtils.findFieldReference(type, nodeText),
diagnostics: [],
};
} else if (
nodeAtPosition.type === "lower_case_identifier" &&
nodeParentType === "field_accessor_function_expr"
) {
const type = findType(nodeParent);
if (type.nodeType === "Function") {
const paramType = type.params[0];
return {
symbol: TreeUtils.findFieldReference(paramType, nodeText),
diagnostics: [],
};
}
} else if (
nodeAtPosition.type === "lower_case_identifier" &&
nodeParentType === "field_type"
) {
return {
symbol: { name: nodeParent.text, node: nodeParent, type: "FieldType" },
diagnostics: [],
};
} else if (
nodeAtPosition.type === "upper_case_identifier" &&
nodeParentType === "ERROR"
) {
let fullModuleName = nodeText;
// Get fully qualified module name
// Ex: nodeText is Attributes, we need to get Html.Attributes manually
let currentNode = nodeAtPosition.previousNamedSibling;
while (
currentNode?.type === "dot" &&
currentNode.previousNamedSibling?.type === "upper_case_identifier"
) {
fullModuleName = `${currentNode.previousNamedSibling.text}.${fullModuleName}`;
currentNode = currentNode.previousNamedSibling.previousNamedSibling;
}
const moduleImport = findImport(
sourceFile,
findImportModuleNameNodes(fullModuleName, sourceFile)[0]?.text ??
fullModuleName,
"Module",
)[0];
if (moduleImport) {
return {
symbol: moduleImport,
diagnostics: [],
};
}
}
const parentType =
TreeUtils.findParentOfType("type_annotation", nodeAtPosition) ??
TreeUtils.findParentOfType("type_declaration", nodeAtPosition) ??
TreeUtils.findParentOfType("type_alias_declaration", nodeAtPosition);
if (parentType?.type === "type_annotation") {
const ancestorDeclarations = TreeUtils.getAllAncestorsOfType(
"value_declaration",
parentType,
);
const allAnnotations = [
...ancestorDeclarations
.map((n) => TreeUtils.getTypeAnnotation(n))
.filter((n) => !!n)
.reverse(),
parentType,
];
const callback = (annotation: SyntaxNode | undefined): SyntaxNode[] =>
annotation
? TreeUtils.descendantsOfType(annotation, "type_variable")
: [];
const allTypeVariables: SyntaxNode[] = allAnnotations.flatMap(callback);
const firstMatching = allTypeVariables.find((t) => t.text === nodeText);
if (firstMatching) {
return {
symbol: {
name: firstMatching.text,
node: firstMatching,
type: "TypeVariable",
},
diagnostics: [],
};
}
} else if (parentType) {
const allTypeNames = TreeUtils.findAllNamedChildrenOfType(
"lower_type_name",
parentType,
);
const firstMatching = allTypeNames?.find((t) => t.text === nodeText);
if (firstMatching) {
return {
symbol: {
name: firstMatching.text,
node: firstMatching,
type: "TypeVariable",
},
diagnostics: [],
};
}
}
return { diagnostics: [] };
}
function getQualifierForName(
sourceFile: ISourceFile,
module: string,
name: string,
): string | undefined {
const found = findImport(sourceFile, name)[0];
if (found) {
return "";
}
if (module === "List" && name === "List") {
return "";
}
const moduleImport = findImportModuleNameNodes(module, sourceFile)[0]
?.parent;
if (!moduleImport) {
return;
}
const asClause = TreeUtils.findFirstNamedChildOfType(
"as_clause",
moduleImport,
);
if (asClause) {
return `${asClause?.lastNamedChild?.text ?? module}.`;
}
return `${module}.`;
}
function typeToString(t: Type, sourceFile?: ISourceFile): string {
return new TypeRenderer(typeChecker, sourceFile).render(t);
}
/**
* Get the module name node if the name is an alias
*/
function findImportModuleNameNodes(
moduleNameOrAlias: string,
sourceFile: ISourceFile,
): SyntaxNode[] {
return (
sourceFile.symbolLinks
?.get(sourceFile.tree.rootNode)
?.getAll(moduleNameOrAlias)
?.filter((s) => s.type === "Import")
.map((s) => s.node.childForFieldName("moduleName"))
.filter(Utils.notUndefinedOrNull) ?? []
);
}
function checkNode(node: SyntaxNode): void {
if (checkedNodes.has(node.id)) {
return;
}
cancellationToken?.throwIfCancellationRequested();
switch (node.type) {
case "file":
node.children.forEach(checkNode);
break;
case "value_declaration":
checkValueDeclaration(node);
break;
case "import_clause":
checkImportClause(node);
break;
case "type_alias_declaration":
checkTypeAliasDeclaration(node);
break;
case "type_declaration":
checkTypeDeclaration(node);
break;
case "union_variant":
checkUnionVariant(node);
break;
case "port_annotation":
checkPortAnnotation(node);
break;
}
checkedNodes.add(node.id);
}
function checkValueDeclaration(valueDeclaration: SyntaxNode): void {
const declaration = mapSyntaxNodeToExpression(
valueDeclaration,
) as EValueDeclaration;
const result = InferenceScope.valueDeclarationInference(
declaration,
valueDeclaration.tree.uri,
program,
new Set(),
/* recursionAllowed */ false,
cancellationToken,
);
result.diagnostics.forEach((diagnostic) => diagnostics.add(diagnostic));
if (!declaration.typeAnnotation) {
const typeString: string = typeToString(
result.type,
getSourceFileOfNode(declaration),
);
if (
typeString &&
typeString !== "unknown" &&
declaration.firstNamedChild?.firstNamedChild
) {
suggestionDiagnostics.add(
error(
declaration.firstNamedChild.firstNamedChild,
Diagnostics.MissingTypeAnnotation,
typeString,
),
);
}
}
}
function checkImportClause(importClause: SyntaxNode): void {
const moduleNameNode = importClause.childForFieldName("moduleName");
if (moduleNameNode) {
const moduleName = moduleNameNode.text;
if (
!program.getSourceFileOfImportableModule(
getSourceFileOfNode(importClause),
moduleName,
)
) {
const project = getSourceFileOfNode(importClause).project;
if (
!nameIsKernel(moduleName) ||
!isKernelProject(project) ||
!existsSync(
path.join(
URI.parse(project.uri).fsPath,
"src",
moduleName.split(".").join("/") + ".js",
),
)
) {
diagnostics.add(
error(moduleNameNode, Diagnostics.ImportMissing, moduleName),
);
}
}
}
}
function checkTypeAliasDeclaration(typeAliasDeclaration: SyntaxNode): void {
TypeExpression.typeAliasDeclarationInference(
mapSyntaxNodeToExpression(typeAliasDeclaration) as ETypeAliasDeclaration,
program,
).diagnostics.forEach((diagnostic) => diagnostics.add(diagnostic));
}
function checkTypeDeclaration(typeDeclaration: SyntaxNode): void {
TypeExpression.typeDeclarationInference(
mapSyntaxNodeToExpression(typeDeclaration) as ETypeDeclaration,
program,
).diagnostics.forEach((diagnostic) => diagnostics.add(diagnostic));
// Need to check union variants
typeDeclaration.children.forEach(checkNode);
}
function checkUnionVariant(unionVariant: SyntaxNode): void {
TypeExpression.unionVariantInference(
mapSyntaxNodeToExpression(unionVariant) as EUnionVariant,
program,
).diagnostics.forEach((diagnostic) => diagnostics.add(diagnostic));
}
function checkPortAnnotation(portAnnotation: SyntaxNode): void {
TypeExpression.portAnnotationInference(
mapSyntaxNodeToExpression(portAnnotation) as EPortAnnotation,
program,
).diagnostics.forEach((diagnostic) => diagnostics.add(diagnostic));
}
function getSourceFileOfNode(node: SyntaxNode): ISourceFile {
const treeContainer = forest.getByUri(node.tree.uri);
if (!treeContainer) {
throw new Error(`Can't find treeContainer by uri "${node.tree.uri}"`);
} else {
return treeContainer;
}
}
} | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { Provider } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { WebSiteManagementClient } from "../webSiteManagementClient";
import {
ApplicationStackResource,
ProviderGetAvailableStacksNextOptionalParams,
ProviderGetAvailableStacksOptionalParams,
FunctionAppStack,
ProviderGetFunctionAppStacksNextOptionalParams,
ProviderGetFunctionAppStacksOptionalParams,
ProviderGetFunctionAppStacksForLocationNextOptionalParams,
ProviderGetFunctionAppStacksForLocationOptionalParams,
WebAppStack,
ProviderGetWebAppStacksForLocationNextOptionalParams,
ProviderGetWebAppStacksForLocationOptionalParams,
CsmOperationDescription,
ProviderListOperationsNextOptionalParams,
ProviderListOperationsOptionalParams,
ProviderGetWebAppStacksNextOptionalParams,
ProviderGetWebAppStacksOptionalParams,
ProviderGetAvailableStacksOnPremNextOptionalParams,
ProviderGetAvailableStacksOnPremOptionalParams,
ProviderGetAvailableStacksResponse,
ProviderGetFunctionAppStacksResponse,
ProviderGetFunctionAppStacksForLocationResponse,
ProviderGetWebAppStacksForLocationResponse,
ProviderListOperationsResponse,
ProviderGetWebAppStacksResponse,
ProviderGetAvailableStacksOnPremResponse,
ProviderGetAvailableStacksNextResponse,
ProviderGetFunctionAppStacksNextResponse,
ProviderGetFunctionAppStacksForLocationNextResponse,
ProviderGetWebAppStacksForLocationNextResponse,
ProviderListOperationsNextResponse,
ProviderGetWebAppStacksNextResponse,
ProviderGetAvailableStacksOnPremNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing Provider operations. */
export class ProviderImpl implements Provider {
private readonly client: WebSiteManagementClient;
/**
* Initialize a new instance of the class Provider class.
* @param client Reference to the service client
*/
constructor(client: WebSiteManagementClient) {
this.client = client;
}
/**
* Description for Get available application frameworks and their versions
* @param options The options parameters.
*/
public listAvailableStacks(
options?: ProviderGetAvailableStacksOptionalParams
): PagedAsyncIterableIterator<ApplicationStackResource> {
const iter = this.getAvailableStacksPagingAll(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.getAvailableStacksPagingPage(options);
}
};
}
private async *getAvailableStacksPagingPage(
options?: ProviderGetAvailableStacksOptionalParams
): AsyncIterableIterator<ApplicationStackResource[]> {
let result = await this._getAvailableStacks(options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._getAvailableStacksNext(continuationToken, options);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *getAvailableStacksPagingAll(
options?: ProviderGetAvailableStacksOptionalParams
): AsyncIterableIterator<ApplicationStackResource> {
for await (const page of this.getAvailableStacksPagingPage(options)) {
yield* page;
}
}
/**
* Description for Get available Function app frameworks and their versions
* @param options The options parameters.
*/
public listFunctionAppStacks(
options?: ProviderGetFunctionAppStacksOptionalParams
): PagedAsyncIterableIterator<FunctionAppStack> {
const iter = this.getFunctionAppStacksPagingAll(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.getFunctionAppStacksPagingPage(options);
}
};
}
private async *getFunctionAppStacksPagingPage(
options?: ProviderGetFunctionAppStacksOptionalParams
): AsyncIterableIterator<FunctionAppStack[]> {
let result = await this._getFunctionAppStacks(options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._getFunctionAppStacksNext(continuationToken, options);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *getFunctionAppStacksPagingAll(
options?: ProviderGetFunctionAppStacksOptionalParams
): AsyncIterableIterator<FunctionAppStack> {
for await (const page of this.getFunctionAppStacksPagingPage(options)) {
yield* page;
}
}
/**
* Description for Get available Function app frameworks and their versions for location
* @param location Function App stack location.
* @param options The options parameters.
*/
public listFunctionAppStacksForLocation(
location: string,
options?: ProviderGetFunctionAppStacksForLocationOptionalParams
): PagedAsyncIterableIterator<FunctionAppStack> {
const iter = this.getFunctionAppStacksForLocationPagingAll(
location,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.getFunctionAppStacksForLocationPagingPage(
location,
options
);
}
};
}
private async *getFunctionAppStacksForLocationPagingPage(
location: string,
options?: ProviderGetFunctionAppStacksForLocationOptionalParams
): AsyncIterableIterator<FunctionAppStack[]> {
let result = await this._getFunctionAppStacksForLocation(location, options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._getFunctionAppStacksForLocationNext(
location,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *getFunctionAppStacksForLocationPagingAll(
location: string,
options?: ProviderGetFunctionAppStacksForLocationOptionalParams
): AsyncIterableIterator<FunctionAppStack> {
for await (const page of this.getFunctionAppStacksForLocationPagingPage(
location,
options
)) {
yield* page;
}
}
/**
* Description for Get available Web app frameworks and their versions for location
* @param location Web App stack location.
* @param options The options parameters.
*/
public listWebAppStacksForLocation(
location: string,
options?: ProviderGetWebAppStacksForLocationOptionalParams
): PagedAsyncIterableIterator<WebAppStack> {
const iter = this.getWebAppStacksForLocationPagingAll(location, options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.getWebAppStacksForLocationPagingPage(location, options);
}
};
}
private async *getWebAppStacksForLocationPagingPage(
location: string,
options?: ProviderGetWebAppStacksForLocationOptionalParams
): AsyncIterableIterator<WebAppStack[]> {
let result = await this._getWebAppStacksForLocation(location, options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._getWebAppStacksForLocationNext(
location,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *getWebAppStacksForLocationPagingAll(
location: string,
options?: ProviderGetWebAppStacksForLocationOptionalParams
): AsyncIterableIterator<WebAppStack> {
for await (const page of this.getWebAppStacksForLocationPagingPage(
location,
options
)) {
yield* page;
}
}
/**
* Description for Gets all available operations for the Microsoft.Web resource provider. Also exposes
* resource metric definitions
* @param options The options parameters.
*/
public listOperations(
options?: ProviderListOperationsOptionalParams
): PagedAsyncIterableIterator<CsmOperationDescription> {
const iter = this.listOperationsPagingAll(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listOperationsPagingPage(options);
}
};
}
private async *listOperationsPagingPage(
options?: ProviderListOperationsOptionalParams
): AsyncIterableIterator<CsmOperationDescription[]> {
let result = await this._listOperations(options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listOperationsNext(continuationToken, options);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listOperationsPagingAll(
options?: ProviderListOperationsOptionalParams
): AsyncIterableIterator<CsmOperationDescription> {
for await (const page of this.listOperationsPagingPage(options)) {
yield* page;
}
}
/**
* Description for Get available Web app frameworks and their versions
* @param options The options parameters.
*/
public listWebAppStacks(
options?: ProviderGetWebAppStacksOptionalParams
): PagedAsyncIterableIterator<WebAppStack> {
const iter = this.getWebAppStacksPagingAll(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.getWebAppStacksPagingPage(options);
}
};
}
private async *getWebAppStacksPagingPage(
options?: ProviderGetWebAppStacksOptionalParams
): AsyncIterableIterator<WebAppStack[]> {
let result = await this._getWebAppStacks(options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._getWebAppStacksNext(continuationToken, options);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *getWebAppStacksPagingAll(
options?: ProviderGetWebAppStacksOptionalParams
): AsyncIterableIterator<WebAppStack> {
for await (const page of this.getWebAppStacksPagingPage(options)) {
yield* page;
}
}
/**
* Description for Get available application frameworks and their versions
* @param options The options parameters.
*/
public listAvailableStacksOnPrem(
options?: ProviderGetAvailableStacksOnPremOptionalParams
): PagedAsyncIterableIterator<ApplicationStackResource> {
const iter = this.getAvailableStacksOnPremPagingAll(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.getAvailableStacksOnPremPagingPage(options);
}
};
}
private async *getAvailableStacksOnPremPagingPage(
options?: ProviderGetAvailableStacksOnPremOptionalParams
): AsyncIterableIterator<ApplicationStackResource[]> {
let result = await this._getAvailableStacksOnPrem(options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._getAvailableStacksOnPremNext(
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *getAvailableStacksOnPremPagingAll(
options?: ProviderGetAvailableStacksOnPremOptionalParams
): AsyncIterableIterator<ApplicationStackResource> {
for await (const page of this.getAvailableStacksOnPremPagingPage(options)) {
yield* page;
}
}
/**
* Description for Get available application frameworks and their versions
* @param options The options parameters.
*/
private _getAvailableStacks(
options?: ProviderGetAvailableStacksOptionalParams
): Promise<ProviderGetAvailableStacksResponse> {
return this.client.sendOperationRequest(
{ options },
getAvailableStacksOperationSpec
);
}
/**
* Description for Get available Function app frameworks and their versions
* @param options The options parameters.
*/
private _getFunctionAppStacks(
options?: ProviderGetFunctionAppStacksOptionalParams
): Promise<ProviderGetFunctionAppStacksResponse> {
return this.client.sendOperationRequest(
{ options },
getFunctionAppStacksOperationSpec
);
}
/**
* Description for Get available Function app frameworks and their versions for location
* @param location Function App stack location.
* @param options The options parameters.
*/
private _getFunctionAppStacksForLocation(
location: string,
options?: ProviderGetFunctionAppStacksForLocationOptionalParams
): Promise<ProviderGetFunctionAppStacksForLocationResponse> {
return this.client.sendOperationRequest(
{ location, options },
getFunctionAppStacksForLocationOperationSpec
);
}
/**
* Description for Get available Web app frameworks and their versions for location
* @param location Web App stack location.
* @param options The options parameters.
*/
private _getWebAppStacksForLocation(
location: string,
options?: ProviderGetWebAppStacksForLocationOptionalParams
): Promise<ProviderGetWebAppStacksForLocationResponse> {
return this.client.sendOperationRequest(
{ location, options },
getWebAppStacksForLocationOperationSpec
);
}
/**
* Description for Gets all available operations for the Microsoft.Web resource provider. Also exposes
* resource metric definitions
* @param options The options parameters.
*/
private _listOperations(
options?: ProviderListOperationsOptionalParams
): Promise<ProviderListOperationsResponse> {
return this.client.sendOperationRequest(
{ options },
listOperationsOperationSpec
);
}
/**
* Description for Get available Web app frameworks and their versions
* @param options The options parameters.
*/
private _getWebAppStacks(
options?: ProviderGetWebAppStacksOptionalParams
): Promise<ProviderGetWebAppStacksResponse> {
return this.client.sendOperationRequest(
{ options },
getWebAppStacksOperationSpec
);
}
/**
* Description for Get available application frameworks and their versions
* @param options The options parameters.
*/
private _getAvailableStacksOnPrem(
options?: ProviderGetAvailableStacksOnPremOptionalParams
): Promise<ProviderGetAvailableStacksOnPremResponse> {
return this.client.sendOperationRequest(
{ options },
getAvailableStacksOnPremOperationSpec
);
}
/**
* GetAvailableStacksNext
* @param nextLink The nextLink from the previous successful call to the GetAvailableStacks method.
* @param options The options parameters.
*/
private _getAvailableStacksNext(
nextLink: string,
options?: ProviderGetAvailableStacksNextOptionalParams
): Promise<ProviderGetAvailableStacksNextResponse> {
return this.client.sendOperationRequest(
{ nextLink, options },
getAvailableStacksNextOperationSpec
);
}
/**
* GetFunctionAppStacksNext
* @param nextLink The nextLink from the previous successful call to the GetFunctionAppStacks method.
* @param options The options parameters.
*/
private _getFunctionAppStacksNext(
nextLink: string,
options?: ProviderGetFunctionAppStacksNextOptionalParams
): Promise<ProviderGetFunctionAppStacksNextResponse> {
return this.client.sendOperationRequest(
{ nextLink, options },
getFunctionAppStacksNextOperationSpec
);
}
/**
* GetFunctionAppStacksForLocationNext
* @param location Function App stack location.
* @param nextLink The nextLink from the previous successful call to the
* GetFunctionAppStacksForLocation method.
* @param options The options parameters.
*/
private _getFunctionAppStacksForLocationNext(
location: string,
nextLink: string,
options?: ProviderGetFunctionAppStacksForLocationNextOptionalParams
): Promise<ProviderGetFunctionAppStacksForLocationNextResponse> {
return this.client.sendOperationRequest(
{ location, nextLink, options },
getFunctionAppStacksForLocationNextOperationSpec
);
}
/**
* GetWebAppStacksForLocationNext
* @param location Web App stack location.
* @param nextLink The nextLink from the previous successful call to the GetWebAppStacksForLocation
* method.
* @param options The options parameters.
*/
private _getWebAppStacksForLocationNext(
location: string,
nextLink: string,
options?: ProviderGetWebAppStacksForLocationNextOptionalParams
): Promise<ProviderGetWebAppStacksForLocationNextResponse> {
return this.client.sendOperationRequest(
{ location, nextLink, options },
getWebAppStacksForLocationNextOperationSpec
);
}
/**
* ListOperationsNext
* @param nextLink The nextLink from the previous successful call to the ListOperations method.
* @param options The options parameters.
*/
private _listOperationsNext(
nextLink: string,
options?: ProviderListOperationsNextOptionalParams
): Promise<ProviderListOperationsNextResponse> {
return this.client.sendOperationRequest(
{ nextLink, options },
listOperationsNextOperationSpec
);
}
/**
* GetWebAppStacksNext
* @param nextLink The nextLink from the previous successful call to the GetWebAppStacks method.
* @param options The options parameters.
*/
private _getWebAppStacksNext(
nextLink: string,
options?: ProviderGetWebAppStacksNextOptionalParams
): Promise<ProviderGetWebAppStacksNextResponse> {
return this.client.sendOperationRequest(
{ nextLink, options },
getWebAppStacksNextOperationSpec
);
}
/**
* GetAvailableStacksOnPremNext
* @param nextLink The nextLink from the previous successful call to the GetAvailableStacksOnPrem
* method.
* @param options The options parameters.
*/
private _getAvailableStacksOnPremNext(
nextLink: string,
options?: ProviderGetAvailableStacksOnPremNextOptionalParams
): Promise<ProviderGetAvailableStacksOnPremNextResponse> {
return this.client.sendOperationRequest(
{ nextLink, options },
getAvailableStacksOnPremNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const getAvailableStacksOperationSpec: coreClient.OperationSpec = {
path: "/providers/Microsoft.Web/availableStacks",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ApplicationStackCollection
},
default: {
bodyMapper: Mappers.DefaultErrorResponse
}
},
queryParameters: [Parameters.apiVersion, Parameters.osTypeSelected],
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const getFunctionAppStacksOperationSpec: coreClient.OperationSpec = {
path: "/providers/Microsoft.Web/functionAppStacks",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.FunctionAppStackCollection
},
default: {
bodyMapper: Mappers.DefaultErrorResponse
}
},
queryParameters: [Parameters.apiVersion, Parameters.stackOsType],
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const getFunctionAppStacksForLocationOperationSpec: coreClient.OperationSpec = {
path: "/providers/Microsoft.Web/locations/{location}/functionAppStacks",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.FunctionAppStackCollection
},
default: {
bodyMapper: Mappers.DefaultErrorResponse
}
},
queryParameters: [Parameters.apiVersion, Parameters.stackOsType1],
urlParameters: [Parameters.$host, Parameters.location],
headerParameters: [Parameters.accept],
serializer
};
const getWebAppStacksForLocationOperationSpec: coreClient.OperationSpec = {
path: "/providers/Microsoft.Web/locations/{location}/webAppStacks",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.WebAppStackCollection
},
default: {
bodyMapper: Mappers.DefaultErrorResponse
}
},
queryParameters: [Parameters.apiVersion, Parameters.stackOsType2],
urlParameters: [Parameters.$host, Parameters.location],
headerParameters: [Parameters.accept],
serializer
};
const listOperationsOperationSpec: coreClient.OperationSpec = {
path: "/providers/Microsoft.Web/operations",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.CsmOperationCollection
},
default: {
bodyMapper: Mappers.DefaultErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const getWebAppStacksOperationSpec: coreClient.OperationSpec = {
path: "/providers/Microsoft.Web/webAppStacks",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.WebAppStackCollection
},
default: {
bodyMapper: Mappers.DefaultErrorResponse
}
},
queryParameters: [Parameters.apiVersion, Parameters.stackOsType3],
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const getAvailableStacksOnPremOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/providers/Microsoft.Web/availableStacks",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ApplicationStackCollection
},
default: {
bodyMapper: Mappers.DefaultErrorResponse
}
},
queryParameters: [Parameters.apiVersion, Parameters.osTypeSelected1],
urlParameters: [Parameters.$host, Parameters.subscriptionId],
headerParameters: [Parameters.accept],
serializer
};
const getAvailableStacksNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ApplicationStackCollection
},
default: {
bodyMapper: Mappers.DefaultErrorResponse
}
},
queryParameters: [Parameters.apiVersion, Parameters.osTypeSelected],
urlParameters: [Parameters.$host, Parameters.nextLink],
headerParameters: [Parameters.accept],
serializer
};
const getFunctionAppStacksNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.FunctionAppStackCollection
},
default: {
bodyMapper: Mappers.DefaultErrorResponse
}
},
queryParameters: [Parameters.apiVersion, Parameters.stackOsType],
urlParameters: [Parameters.$host, Parameters.nextLink],
headerParameters: [Parameters.accept],
serializer
};
const getFunctionAppStacksForLocationNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.FunctionAppStackCollection
},
default: {
bodyMapper: Mappers.DefaultErrorResponse
}
},
queryParameters: [Parameters.apiVersion, Parameters.stackOsType1],
urlParameters: [Parameters.$host, Parameters.nextLink, Parameters.location],
headerParameters: [Parameters.accept],
serializer
};
const getWebAppStacksForLocationNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.WebAppStackCollection
},
default: {
bodyMapper: Mappers.DefaultErrorResponse
}
},
queryParameters: [Parameters.apiVersion, Parameters.stackOsType2],
urlParameters: [Parameters.$host, Parameters.nextLink, Parameters.location],
headerParameters: [Parameters.accept],
serializer
};
const listOperationsNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.CsmOperationCollection
},
default: {
bodyMapper: Mappers.DefaultErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.$host, Parameters.nextLink],
headerParameters: [Parameters.accept],
serializer
};
const getWebAppStacksNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.WebAppStackCollection
},
default: {
bodyMapper: Mappers.DefaultErrorResponse
}
},
queryParameters: [Parameters.apiVersion, Parameters.stackOsType3],
urlParameters: [Parameters.$host, Parameters.nextLink],
headerParameters: [Parameters.accept],
serializer
};
const getAvailableStacksOnPremNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ApplicationStackCollection
},
default: {
bodyMapper: Mappers.DefaultErrorResponse
}
},
queryParameters: [Parameters.apiVersion, Parameters.osTypeSelected1],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
export interface DescribeProjectResponse {
/**
* 项目id
*/
ProjectId?: string;
/**
* 项目名称
*/
ProjectName?: string;
/**
* 项目预算
*/
ProjectBudget?: number;
/**
* 项目机构
*/
ProjectOrg?: string;
/**
* 项目简介
*/
ProjectIntroduction?: string;
/**
* 子项目列表
*/
SubProjectList?: Array<SubProjectInfo>;
/**
* 项目状态
*/
ProjectStatus?: string;
/**
* 项目机构Id
注意:此字段可能返回 null,表示取不到有效值。
*/
ProjectOrgId?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CheckStaffChUser请求参数结构体
*/
export interface CheckStaffChUserRequest {
/**
* 员工ID
*/
UserId: Array<string>;
/**
* 渠道状态:checkpass审核通过, checkreject审核拒绝, enableoperate启用, stopoperate停用
*/
OperateType: string;
}
/**
* DescribeResourceTemplateHeaders返回参数结构体
*/
export interface DescribeResourceTemplateHeadersResponse {
/**
* 记录条数
*/
TotalCount?: number;
/**
* 模板列表
注意:此字段可能返回 null,表示取不到有效值。
*/
TmplList?: Array<ResourceTemplateHeader>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DeleteProject请求参数结构体
*/
export interface DeleteProjectRequest {
/**
* 项目ID
*/
ProjectId: string;
}
/**
* ReplenishProjectStock返回参数结构体
*/
export interface ReplenishProjectStockResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* SendWxTouchTask返回参数结构体
*/
export interface SendWxTouchTaskResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeCustomers请求参数结构体
*/
export interface DescribeCustomersRequest {
/**
* 查询类型,0.个人,1负责部门,2.指定部门
*/
QueryType: string;
/**
* 分组ID
*/
GroupId?: string;
/**
* 是否星级标记 1是 0否
*/
MarkFlag?: number;
/**
* 客户标签,多个标签用逗号隔开
*/
TagIds?: string;
/**
* 员工标识筛选,0:非员工,1:员工
*/
RelChannelFlag?: string;
/**
* 必须存在手机 1是 0否
*/
NeedPhoneFlag?: number;
/**
* 省份
*/
Province?: string;
/**
* 城市
*/
City?: string;
/**
* 性别 1男 2女
*/
Sex?: string;
/**
* 城市
*/
KeyWord?: string;
/**
* 查询开始位置
*/
Offset?: number;
/**
* 每页记录条数
*/
Limit?: number;
/**
* 子项目ID
*/
SubProjectId?: string;
}
/**
* DescribeProjects请求参数结构体
*/
export interface DescribeProjectsRequest {
/**
* 页码
*/
PageNo: number;
/**
* 页面大小
*/
PageSize: number;
/**
* 过滤规则
*/
SearchWord?: string;
/**
* 部门范围过滤
*/
Filters?: Filters;
/**
* 项目状态, 0:编辑中 1:运营中 2:已下线 3:已删除 4:审批中
*/
ProjectStatus?: number;
}
/**
* ModifyProject请求参数结构体
*/
export interface ModifyProjectRequest {
/**
* 项目ID
*/
ProjectId: string;
/**
* 项目名称
*/
ProjectName: string;
/**
* 项目预算
*/
ProjectBudget: string;
/**
* 项目机构
*/
ProjectOrg: string;
/**
* 项目简介
*/
ProjectIntroduction: string;
/**
* 项目机构Id
*/
ProjectOrgId?: string;
}
/**
* OffLineProject请求参数结构体
*/
export interface OffLineProjectRequest {
/**
* 项目ID
*/
ProjectId: string;
}
/**
* DescribeSubProject请求参数结构体
*/
export interface DescribeSubProjectRequest {
/**
* 子项目id
*/
SubProjectId: string;
}
/**
* ExpireFlow请求参数结构体
*/
export interface ExpireFlowRequest {
/**
* 工单ID
*/
FlowId: string;
}
/**
* CopyActivityChannel请求参数结构体
*/
export interface CopyActivityChannelRequest {
/**
* 活动ID
*/
ActivityId: string;
/**
* 来源渠道ID
*/
ChannelFrom: string;
/**
* 目的渠道id
*/
ChannelTo: Array<string>;
}
/**
* CopyActivityChannel返回参数结构体
*/
export interface CopyActivityChannelResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeProjects返回参数结构体
*/
export interface DescribeProjectsResponse {
/**
* 项目列表
*/
ProjectList?: Array<ProjectInfo>;
/**
* 项目数
*/
TotalCount?: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ReplenishProjectStock请求参数结构体
*/
export interface ReplenishProjectStockRequest {
/**
* 项目id
*/
SubProjectId: string;
/**
* 奖品id
*/
PrizeId: string;
/**
* 奖品数量
*/
PrizeNum: number;
/**
* 奖池索引
*/
PoolIndex: number;
/**
* 奖池名称
*/
PoolName?: string;
}
/**
* 项目奖品库存
*/
export interface ProjectStock {
/**
* 奖品id
*/
PrizeId: string;
/**
* 奖品批次
*/
PrizeBat: number;
/**
* 奖品名称
*/
PrizeName: string;
/**
* 已分配奖品数量
*/
UsedStock: number;
/**
* 该奖品剩余库存数量
*/
RemainStock: number;
/**
* 奖品所在奖池index
*/
PoolIdx: number;
/**
* 奖品所在奖池名称
*/
PoolName: string;
}
/**
* DescribeProjectStock返回参数结构体
*/
export interface DescribeProjectStockResponse {
/**
* 项目库存列表
*/
ProjectStocks?: Array<ProjectStock>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CheckStaffChUser返回参数结构体
*/
export interface CheckStaffChUserResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeCustomer请求参数结构体
*/
export interface DescribeCustomerRequest {
/**
* 用户ID
*/
UserId: string;
}
/**
* 内容页结构
*/
export interface ProductInfo {
/**
* 模板id
注意:此字段可能返回 null,表示取不到有效值。
*/
TemplateId: string;
/**
* 模板主题
注意:此字段可能返回 null,表示取不到有效值。
*/
ProductTitle: string;
/**
* 模板描述
注意:此字段可能返回 null,表示取不到有效值。
*/
ProductDesc: string;
/**
* 模板封面地址
注意:此字段可能返回 null,表示取不到有效值。
*/
ProductCover: string;
/**
* 内容作品id
注意:此字段可能返回 null,表示取不到有效值。
*/
ProductId: string;
/**
* 作品预览链接
注意:此字段可能返回 null,表示取不到有效值。
*/
ProductUrl: string;
/**
* 作品名称
注意:此字段可能返回 null,表示取不到有效值。
*/
ProductName: string;
}
/**
* 子项目信息
*/
export interface SubProjectInfo {
/**
* 子项目id
*/
SubProjectId: string;
/**
* 子项目名称
*/
SubProjectName: string;
/**
* 子项目状态
*/
SubProjectStatus: string;
}
/**
* 素材模板消息标题的样例列表
*/
export interface ResourceTemplateHeader {
/**
* 模板预览区内容
注意:此字段可能返回 null,表示取不到有效值。
*/
Content: string;
/**
* 模板预览示例
注意:此字段可能返回 null,表示取不到有效值。
*/
Example: string;
/**
* 模板预览区域键数组
注意:此字段可能返回 null,表示取不到有效值。
*/
KeyArray: string;
/**
* 模板id
*/
TemplateId: string;
/**
* 模板标题
注意:此字段可能返回 null,表示取不到有效值。
*/
Title: string;
}
/**
* CreateSubProject返回参数结构体
*/
export interface CreateSubProjectResponse {
/**
* 子项目id
*/
SubProjectId?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 可见范围过滤参数
*/
export interface Filters {
/**
* 过滤类型, 0: 默认(可见部门+自创) 1: 自创 2: 指定部门(部门在可见范围内)
*/
Type?: number;
/**
* 指定部门Id, 类型2使用
*/
DeptIds?: Array<string>;
/**
* 用户Id列表
*/
UserIds?: Array<string>;
}
/**
* 项目基础信息
*/
export interface ProjectInfo {
/**
* 项目ID
*/
ProjectId: string;
/**
* 项目名称
*/
ProjectName: string;
/**
* 项目所属机构
*/
ProjectOrg: string;
/**
* 项目预算
*/
ProjectBudget: number;
/**
* 项目状态
*/
ProjectStatus: string;
/**
* 项目创建时间
*/
CreateTime: string;
/**
* 项目简介
*/
ProjectIntroduction: string;
/**
* 项目所属机构Id
注意:此字段可能返回 null,表示取不到有效值。
*/
ProjectOrgId: string;
}
/**
* DescribeCustomer返回参数结构体
*/
export interface DescribeCustomerResponse {
/**
* 地址列表
注意:此字段可能返回 null,表示取不到有效值。
*/
AddressList?: Array<string>;
/**
* 用户id
注意:此字段可能返回 null,表示取不到有效值。
*/
UserId?: string;
/**
* 头像
注意:此字段可能返回 null,表示取不到有效值。
*/
Avatar?: string;
/**
* 生日
注意:此字段可能返回 null,表示取不到有效值。
*/
Birthday?: string;
/**
* 城市
注意:此字段可能返回 null,表示取不到有效值。
*/
City?: string;
/**
* 创建时间
注意:此字段可能返回 null,表示取不到有效值。
*/
CreateTime?: string;
/**
* 设备
注意:此字段可能返回 null,表示取不到有效值。
*/
Device?: string;
/**
* 行业
注意:此字段可能返回 null,表示取不到有效值。
*/
Industrys?: Array<string>;
/**
* 上次登录时间
注意:此字段可能返回 null,表示取不到有效值。
*/
LastActiveTime?: string;
/**
* 是否星标 1是 0否
注意:此字段可能返回 null,表示取不到有效值。
*/
MarkFlag?: string;
/**
* 手机型号
注意:此字段可能返回 null,表示取不到有效值。
*/
Model?: string;
/**
* 微信openid
注意:此字段可能返回 null,表示取不到有效值。
*/
OpenId?: string;
/**
* 消费特点
注意:此字段可能返回 null,表示取不到有效值。
*/
PayFeature?: string;
/**
* 手机号
注意:此字段可能返回 null,表示取不到有效值。
*/
Phone?: string;
/**
* 手机号码列表
注意:此字段可能返回 null,表示取不到有效值。
*/
PhoneList?: string;
/**
* 最近记录省份
注意:此字段可能返回 null,表示取不到有效值。
*/
Province?: string;
/**
* 姓名
注意:此字段可能返回 null,表示取不到有效值。
*/
RealName?: string;
/**
* 员工标识 0:非员工 1:员工
注意:此字段可能返回 null,表示取不到有效值。
*/
RelChannelFlag?: string;
/**
* 备注
注意:此字段可能返回 null,表示取不到有效值。
*/
Remark?: string;
/**
* 性别 1男 2女
注意:此字段可能返回 null,表示取不到有效值。
*/
Sex?: string;
/**
* 最初来源
注意:此字段可能返回 null,表示取不到有效值。
*/
SourceAudienceVo?: string;
/**
* 关注公众号列表
注意:此字段可能返回 null,表示取不到有效值。
*/
SubWechats?: Array<string>;
/**
* 微信unionid
注意:此字段可能返回 null,表示取不到有效值。
*/
UnionId?: string;
/**
* 更新时间
注意:此字段可能返回 null,表示取不到有效值。
*/
UpdateTime?: string;
/**
* 用户类型
注意:此字段可能返回 null,表示取不到有效值。
*/
UserTypes?: Array<string>;
/**
* 城市
注意:此字段可能返回 null,表示取不到有效值。
*/
WxCity?: string;
/**
* 国家
注意:此字段可能返回 null,表示取不到有效值。
*/
WxCountry?: string;
/**
* 昵称
注意:此字段可能返回 null,表示取不到有效值。
*/
WxNickname?: string;
/**
* 省份
注意:此字段可能返回 null,表示取不到有效值。
*/
WxProvince?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeCustomers返回参数结构体
*/
export interface DescribeCustomersResponse {
/**
* 总记录条数
*/
TotalCount?: number;
/**
* 数据列表
注意:此字段可能返回 null,表示取不到有效值。
*/
UserList?: Array<CustomerInfo>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateSubProject请求参数结构体
*/
export interface CreateSubProjectRequest {
/**
* 所属项目id
*/
ProjectId: string;
/**
* 子项目名称
*/
SubProjectName: string;
}
/**
* ModifyProject返回参数结构体
*/
export interface ModifyProjectResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateProject返回参数结构体
*/
export interface CreateProjectResponse {
/**
* 项目ID
*/
ProjectId?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeProjectStock请求参数结构体
*/
export interface DescribeProjectStockRequest {
/**
* 子项目id
*/
SubProjectId: string;
}
/**
* DeleteProject返回参数结构体
*/
export interface DeleteProjectResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* SendWxTouchTask请求参数结构体
*/
export interface SendWxTouchTaskRequest {
/**
* 客户分组ID
*/
GroupId: string;
/**
* 去除今日已发送的客户
*/
DistinctFlag: boolean;
/**
* 是否立马发送
*/
IsSendNow: boolean;
/**
* 发送时间,一般为0
*/
SendDate: number;
/**
* 任务名称
*/
TaskName: string;
/**
* 微信触达类型,text, news, smallapp, tmplmsg
*/
WxTouchType: string;
/**
* 标题
*/
Title?: string;
/**
* 文本内容
*/
Content?: string;
/**
* 图文素材ID
*/
NewsId?: string;
/**
* 小程序卡片ID
*/
SmallProgramId?: string;
/**
* 模板消息ID
*/
TemplateId?: string;
/**
* 微信公众号appId
*/
WxAppId?: string;
}
/**
* DescribeProject请求参数结构体
*/
export interface DescribeProjectRequest {
/**
* 项目ID
*/
ProjectId: string;
}
/**
* OffLineProject返回参数结构体
*/
export interface OffLineProjectResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 客户档案
*/
export interface CustomerInfo {
/**
* 总活跃度
注意:此字段可能返回 null,表示取不到有效值。
*/
Activity: number;
/**
* 客户ID
*/
AudienceUserId: string;
/**
* 头像
注意:此字段可能返回 null,表示取不到有效值。
*/
Avatar: string;
/**
* 最近记录城市
注意:此字段可能返回 null,表示取不到有效值。
*/
City: string;
/**
* 最活跃时间
注意:此字段可能返回 null,表示取不到有效值。
*/
LastActiveTime: string;
/**
* 是否星标客户
注意:此字段可能返回 null,表示取不到有效值。
*/
MarkFlag: string;
/**
* 30天活跃度
注意:此字段可能返回 null,表示取不到有效值。
*/
MonthActive: number;
/**
* 30天推荐度
注意:此字段可能返回 null,表示取不到有效值。
*/
MonthRecommend: number;
/**
* 手机号
注意:此字段可能返回 null,表示取不到有效值。
*/
Phone: string;
/**
* 最近记录省份
注意:此字段可能返回 null,表示取不到有效值。
*/
Province: string;
/**
* 姓名
注意:此字段可能返回 null,表示取不到有效值。
*/
RealName: string;
/**
* 员工标识 0 未关联 1 已关联
注意:此字段可能返回 null,表示取不到有效值。
*/
RelChannelFlag: number;
/**
* 性别 1男 2女
注意:此字段可能返回 null,表示取不到有效值。
*/
Sex: number;
/**
* 传播力(好友数)
注意:此字段可能返回 null,表示取不到有效值。
*/
Spread: number;
/**
* 7天活跃度
注意:此字段可能返回 null,表示取不到有效值。
*/
WeekActive: number;
/**
* 7天推荐度
注意:此字段可能返回 null,表示取不到有效值。
*/
WeekRecommend: number;
/**
* 微信城市
注意:此字段可能返回 null,表示取不到有效值。
*/
WxCity: string;
/**
* 微信国家或地区
注意:此字段可能返回 null,表示取不到有效值。
*/
WxCountry: string;
/**
* 微信呢称
注意:此字段可能返回 null,表示取不到有效值。
*/
WxNickname: string;
/**
* 微信省份
注意:此字段可能返回 null,表示取不到有效值。
*/
WxProvince: string;
}
/**
* 活动详情
*/
export interface ActivityInfo {
/**
* 活动使用模板id
注意:此字段可能返回 null,表示取不到有效值。
*/
TemplateId: string;
/**
* 活动标题
注意:此字段可能返回 null,表示取不到有效值。
*/
ActivityTitle: string;
/**
* 活动描述
注意:此字段可能返回 null,表示取不到有效值。
*/
ActivityDesc: string;
/**
* 活动封面地址
注意:此字段可能返回 null,表示取不到有效值。
*/
ActivityCover: string;
/**
* 活动类型
注意:此字段可能返回 null,表示取不到有效值。
*/
ActivityType: string;
/**
* 活动id
注意:此字段可能返回 null,表示取不到有效值。
*/
ActivityId: string;
/**
* 活动模板自定义配置
注意:此字段可能返回 null,表示取不到有效值。
*/
PersonalConfig: string;
}
/**
* DescribeResourceTemplateHeaders请求参数结构体
*/
export interface DescribeResourceTemplateHeadersRequest {
/**
* 微信公众号appId
*/
WxAppId?: string;
}
/**
* ExpireFlow返回参数结构体
*/
export interface ExpireFlowResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeSubProject返回参数结构体
*/
export interface DescribeSubProjectResponse {
/**
* 作品信息
注意:此字段可能返回 null,表示取不到有效值。
*/
ProductInfo?: ProductInfo;
/**
* 活动信息
注意:此字段可能返回 null,表示取不到有效值。
*/
ActivityInfo?: ActivityInfo;
/**
* 分享标题
注意:此字段可能返回 null,表示取不到有效值。
*/
ShareTitle?: string;
/**
* 分享描述
注意:此字段可能返回 null,表示取不到有效值。
*/
ShareDesc?: string;
/**
* 分享图标
注意:此字段可能返回 null,表示取不到有效值。
*/
ShareImg?: string;
/**
* 是否已创建策略
注意:此字段可能返回 null,表示取不到有效值。
*/
HasStrategy?: number;
/**
* 子项目状态
注意:此字段可能返回 null,表示取不到有效值。
*/
SubProjectStatus?: string;
/**
* 分享公众号的appId
注意:此字段可能返回 null,表示取不到有效值。
*/
ShareAppId?: string;
/**
* 分享公众号的wsId
注意:此字段可能返回 null,表示取不到有效值。
*/
ShareWsId?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateProject请求参数结构体
*/
export interface CreateProjectRequest {
/**
* 项目名称
*/
ProjectName: string;
/**
* 项目机构
*/
ProjectOrg: string;
/**
* 项目预算
*/
ProjectBudget: string;
/**
* 项目简介
*/
ProjectIntroduction: string;
/**
* 所属部门ID
*/
ProjectOrgId?: string;
} | the_stack |
import Point from "openfl/geom/Point";
import MatrixUtil from "./../../starling/utils/MatrixUtil";
import TextureOptions from "./../../starling/textures/TextureOptions";
import Rectangle from "openfl/geom/Rectangle";
import Matrix from "openfl/geom/Matrix";
import Bitmap from "openfl/display/Bitmap";
import BitmapData from "openfl/display/BitmapData";
import ByteArray from "openfl/utils/ByteArray";
import ArgumentError from "openfl/errors/ArgumentError";
import Texture from "openfl/display3D/textures/Texture";
import ConcretePotTexture from "./../../starling/textures/ConcretePotTexture";
import RectangleTexture from "openfl/display3D/textures/RectangleTexture";
import ConcreteRectangleTexture from "./../../starling/textures/ConcreteRectangleTexture";
import VideoTexture from "openfl/display3D/textures/VideoTexture";
import ConcreteVideoTexture from "./../../starling/textures/ConcreteVideoTexture";
import Starling from "./../../starling/core/Starling";
import MissingContextError from "./../../starling/errors/MissingContextError";
import AtfData from "./../../starling/textures/AtfData";
import Reflect from "./../../Reflect";
import SystemUtil from "./../../starling/utils/SystemUtil";
import NotSupportedError from "./../../starling/errors/NotSupportedError";
import MathUtil from "./../../starling/utils/MathUtil";
import SubTexture from "./../../starling/textures/SubTexture";
import TextureBase from "openfl/display3D/textures/TextureBase";
import ConcreteTexture from "./ConcreteTexture";
import Context3DTextureFormat from "openfl/display3D/Context3DTextureFormat";
import NetStream from "openfl/net/NetStream";
import VertexData from "./../rendering/VertexData";
declare namespace starling.textures
{
/** <p>A texture stores the information that represents an image. It cannot be added to the
* display list directly; instead it has to be mapped onto a display object. In Starling,
* the most probably candidate for this job is the <code>Image</code> class.</p>
*
* <strong>Creating a texture</strong>
*
* <p>The <code>Texture</code> class is abstract, i.e. you cannot create instance of this
* class through its constructor. Instead, it offers a variety of factory methods, like
* <code>fromBitmapData</code> or <code>fromEmbeddedAsset</code>.</p>
*
* <strong>Texture Formats</strong>
*
* <p>Since textures can be created from a "BitmapData" object, Starling supports any bitmap
* format that is supported by Flash. And since you can render any Flash display object into
* a BitmapData object, you can use this to display non-Starling content in Starling - e.g.
* Shape objects.</p>
*
* <p>Starling also supports ATF textures (Adobe Texture Format), which is a container for
* compressed texture formats that can be rendered very efficiently by the GPU. Refer to
* the Flash documentation for more information about this format.</p>
*
* <p>Beginning with AIR 17, you can use Starling textures to show video content (if the
* current platform supports it; see "SystemUtil.supportsVideoTexture").
* The two factory methods "fromCamera" and "fromNetStream" allow you to make use of
* this feature.</p>
*
* <strong>Mip Mapping</strong>
*
* <p>MipMaps are scaled down versions of a texture. When an image is displayed smaller than
* its natural size, the GPU may display the mip maps instead of the original texture. This
* reduces aliasing and accelerates rendering. It does, however, also need additional memory;
* for that reason, mipmapping is disabled by default.</p>
*
* <strong>Texture Frame</strong>
*
* <p>The frame property of a texture allows you to let a texture appear inside the bounds of
* an image, leaving a transparent border around the texture. The frame rectangle is specified
* in the coordinate system of the texture (not the image):</p>
*
* <listing>
* frame:Rectangle = new Rectangle(-10, -10, 30, 30);
* texture:Texture = Texture.fromTexture(anotherTexture, null, frame);
* image:Image = new Image(texture);</listing>
*
* <p>This code would create an image with a size of 30x30, with the texture placed at
* <code>x=10, y=10</code> within that image (assuming that 'anotherTexture' has a width and
* height of 10 pixels, it would appear in the middle of the image).</p>
*
* <p>The texture atlas makes use of this feature, as it allows to crop transparent edges
* of a texture and making up for the changed size by specifying the original texture frame.
* Tools like <a href="http://www.texturepacker.com/">TexturePacker</a> use this to
* optimize the atlas.</p>
*
* <strong>Texture Coordinates</strong>
*
* <p>If, on the other hand, you want to show only a part of the texture in an image
* (i.e. to crop the the texture), you can either create a subtexture (with the method
* 'Texture.fromTexture()' and specifying a rectangle for the region), or you can manipulate
* the texture coordinates of the image object. The method <code>image.setTexCoords</code>
* allows you to do that.</p>
*
* <strong>Context Loss</strong>
*
* <p>When the current rendering context is lost (which can happen on all platforms, but is
* especially common on Android and Windows), all texture data is destroyed. However,
* Starling will try to restore the textures. To do that, it will keep the bitmap
* and ATF data in memory - at the price of increased RAM consumption. You can optimize
* this behavior, though, by restoring the texture directly from its source, like in this
* example:</p>
*
* <listing>
* texture:Texture = Texture.fromBitmap(new EmbeddedBitmap());
* texture.root.onRestore = function():void
* {
* texture.root.uploadFromBitmap(new EmbeddedBitmap());
* };</listing>
*
* <p>The <code>onRestore</code>-method will be called when the context was lost and the
* texture has been recreated (but is still empty). If you use the "AssetManager" class to
* manage your textures, this will be done automatically.</p>
*
* @see starling.display.Image
* @see starling.utils.AssetManager
* @see starling.utils.SystemUtil
* @see TextureAtlas
*/
export class Texture
{
/** Disposes the underlying texture data. Note that not all textures need to be disposed:
* SubTextures (created with 'Texture.fromTexture') just reference other textures and
* and do not take up resources themselves; this is also true for textures from an
* atlas. */
public dispose():void;
/** Creates a texture from any of the supported data types, using the specified options.
*
* @param data Either an embedded asset class, a Bitmap, BitmapData, or a ByteArray
* with ATF data.
* @param options Specifies options about the texture settings, e.g. the scale factor.
* If left empty, the default options will be used.
*/
public static fromData(data:any, options?:TextureOptions):Texture;
/** Creates a texture from a <code>TextureBase</code> object.
*
* @param base a Stage3D texture object created through the current context.
* @param width the width of the texture in pixels (not points!).
* @param height the height of the texture in pixels (not points!).
* @param options specifies options about the texture settings, e.g. the scale factor.
* If left empty, the default options will be used. Note that not all
* options are supported by all texture types.
*/
public static fromTextureBase(base:TextureBase, width:number, height:number,
options?:TextureOptions):ConcreteTexture;
/** Creates a texture object from an embedded asset class. Textures created with this
* method will be restored directly from the asset class in case of a context loss,
* which guarantees a very economic memory usage.
*
* @param assetClass must contain either a Bitmap or a ByteArray with ATF data.
* @param mipMapping for Bitmaps, indicates if mipMaps will be created;
* for ATF data, indicates if the contained mipMaps will be used.
* @param optimizeForRenderToTexture indicates if this texture will be used as
* render target.
* @param scale the scale factor of the created texture.
* @param format the context3D texture format to use. Ignored for ATF data.
* @param forcePotTexture indicates if the underlying Stage3D texture should be created
* as the power-of-two based "Texture" class instead of the more memory
* efficient "RectangleTexture". (Only applicable to bitmaps; ATF
* textures are always POT-textures, anyway.)
*/
public static fromEmbeddedAsset(assetClass:any, mipMapping?:boolean,
optimizeForRenderToTexture?:boolean,
scale?:number, format?:Context3DTextureFormat,
forcePotTexture?:boolean):Texture;
/** Creates a texture object from a bitmap.
* Beware: you must not dispose the bitmap's data if Starling should handle a lost device
* context (except if you handle restoration yourself via "texture.root.onRestore").
*
* @param bitmap the texture will be created with the bitmap data of this object.
* @param generateMipMaps indicates if mipMaps will be created.
* @param optimizeForRenderToTexture indicates if this texture will be used as
* render target
* @param scale the scale factor of the created texture. This affects the reported
* width and height of the texture object.
* @param format the context3D texture format to use. Pass one of the packed or
* compressed formats to save memory (at the price of reduced image
* quality).
* @param forcePotTexture indicates if the underlying Stage3D texture should be created
* as the power-of-two based "Texture" class instead of the more memory
* efficient "RectangleTexture".
* @param async If you pass a callback function, the texture will be uploaded
* asynchronously, which allows smooth rendering even during the
* loading process. However, don't use the texture before the callback
* has been executed. This is the expected definition:
* <code>function(texture:Texture, error:ErrorEvent):void;</code>
* The second parameter is optional and typically <code>null</code>.
*/
public static fromBitmap(bitmap:Bitmap, generateMipMaps?:boolean,
optimizeForRenderToTexture?:boolean,
scale?:number, format?:Context3DTextureFormat,
forcePotTexture?:boolean,
async?:(Texture)=>void):Texture;
/** Creates a texture object from bitmap data.
* Beware: you must not dispose 'data' if Starling should handle a lost device context
* (except if you handle restoration yourself via "texture.root.onRestore").
*
* @param data the bitmap data to upload to the texture.
* @param generateMipMaps indicates if mipMaps will be created.
* @param optimizeForRenderToTexture indicates if this texture will be used as
* render target
* @param scale the scale factor of the created texture. This affects the reported
* width and height of the texture object.
* @param format the context3D texture format to use. Pass one of the packed or
* compressed formats to save memory (at the price of reduced image
* quality).
* @param forcePotTexture indicates if the underlying Stage3D texture should be created
* as the power-of-two based "Texture" class instead of the more memory
* efficient "RectangleTexture".
* @param async If you pass a callback function, the texture will be uploaded
* asynchronously, which allows smooth rendering even during the
* loading process. However, don't use the texture before the callback
* has been executed. This is the expected definition:
* <code>function(texture:Texture, error:ErrorEvent):void;</code>
* The second parameter is optional and typically <code>null</code>.
*/
public static fromBitmapData(data:BitmapData, generateMipMaps?:boolean,
optimizeForRenderToTexture?:boolean,
scale?:number, format?:Context3DTextureFormat,
forcePotTexture?:boolean,
async?:(Texture)=>void):Texture;
/** Creates a texture from ATF data (Adobe Texture Compression).
* Beware: you must not dispose 'data' if Starling should handle a lost device context;
* alternatively, you can handle restoration yourself via "texture.root.onRestore".
*
* @param data the raw data from an ATF file.
* @param scale the scale factor of the created texture. This affects the reported
* width and height of the texture object.
* @param useMipMaps If the ATF data contains mipmaps, this parameter controls if they
* are used; if it does not, this parameter has no effect.
* @param async If you pass a callback function, the texture will be decoded
* asynchronously, which allows a smooth framerate even during the
* loading process. However, don't use the texture before the callback
* has been executed. This is the expected definition:
* <code>function(texture:Texture):void;</code>
* @param premultipliedAlpha Indicates if the ATF data contains pixels in PMA format.
* This is "false" for most ATF files, but can be customized in some
* tools.
*/
public static fromAtfData(data:ByteArray, scale?:number, useMipMaps?:boolean,
async?:(Texture)=>void, premultipliedAlpha?:boolean):Texture;
/** Creates a video texture from a NetStream.
*
* <p>Below, you'll find a minimal sample showing how to stream a video from a file.
* Note that <code>ns.play()</code> is called only after creating the texture, and
* outside the <code>onComplete</code>-callback. It's recommended to always make the
* calls in this order; otherwise, playback won't start on some platforms.</p>
*
* <listing>
* nc:NetConnection = new NetConnection();
* nc.connect(null);
*
* ns:NetStream = new NetStream(nc);
* texture:Texture = Texture.fromNetStream(ns, 1, function():void
* {
* addChild(new Image(texture));
* });
*
* file:File = File.applicationDirectory.resolvePath("bugs-bunny.m4v");
* ns.play(file.url);</listing>
*
* @param stream the NetStream from which the video data is streamed. Beware that 'play'
* should be called only after the method returns, and outside the
* <code>onComplete</code> callback.
* @param scale the scale factor of the created texture. This affects the reported
* width and height of the texture object.
* @param onComplete will be executed when the texture is ready. Contains a parameter
* of type 'Texture'.
*/
public static fromNetStream(stream:NetStream, scale?:number,
onComplete?:(Texture)=>void):Texture;
/** Creates a video texture from a camera. Beware that the texture must not be used
* before the 'onComplete' callback has been executed; until then, it will have a size
* of zero pixels.
*
* <p>Here is a minimal sample showing how to display a camera video:</p>
*
* <listing>
* camera:Camera = Camera.getCamera();
* texture:Texture = Texture.fromCamera(camera, 1, function():void
* {
* addChild(new Image(texture));
* });</listing>
*
* @param camera the camera from which the video data is streamed.
* @param scale the scale factor of the created texture. This affects the reported
* width and height of the texture object.
* @param onComplete will be executed when the texture is ready. May contain a parameter
* of type 'Texture'.
*/
// #if flash
// public static fromCamera(camera:Camera, scale?:number,
// onComplete?:(Texture)=>void):Texture;
// #end
/** Creates a texture with a certain size and color.
*
* @param width in points; number of pixels depends on scale parameter
* @param height in points; number of pixels depends on scale parameter
* @param color the RGB color the texture will be filled up
* @param alpha the alpha value that will be used for every pixel
* @param optimizeForRenderToTexture indicates if this texture will be used as render target
* @param scale if you omit this parameter, 'Starling.contentScaleFactor' will be used.
* @param format the context3D texture format to use. Pass one of the packed or
* compressed formats to save memory.
* @param forcePotTexture indicates if the underlying Stage3D texture should be created
* as the power-of-two based "Texture" class instead of the more memory
* efficient "RectangleTexture".
*/
public static fromColor(width:number, height:number,
color?:number, alpha?:number,
optimizeForRenderToTexture?:boolean,
scale?:number, format?:string,
forcePotTexture?:boolean):Texture;
/** Creates an empty texture of a certain size.
* Beware that the texture can only be used after you either upload some color data
* ("texture.root.upload...") or clear the texture ("texture.root.clear()").
*
* @param width in points; number of pixels depends on scale parameter
* @param height in points; number of pixels depends on scale parameter
* @param premultipliedAlpha the PMA format you will use the texture with. If you will
* use the texture for bitmap data, use "true"; for ATF data, use "false".
* @param mipMapping indicates if mipmaps should be used for this texture. When you upload
* bitmap data, this decides if mipmaps will be created; when you upload ATF
* data, this decides if mipmaps inside the ATF file will be displayed.
* @param optimizeForRenderToTexture indicates if this texture will be used as render target
* @param scale if you omit this parameter, 'Starling.contentScaleFactor' will be used.
* @param format the context3D texture format to use. Pass one of the packed or
* compressed formats to save memory (at the price of reduced image quality).
* @param forcePotTexture indicates if the underlying Stage3D texture should be created
* as the power-of-two based "Texture" class instead of the more memory
* efficient "RectangleTexture".
*/
public static empty(width:number, height:number, premultipliedAlpha?:boolean,
mipMapping?:boolean, optimizeForRenderToTexture?:boolean,
scale?:number, format?:string,
forcePotTexture?:boolean):Texture;
/** Creates a texture that contains a region (in pixels) of another texture. The new
* texture will reference the base texture; no data is duplicated.
*
* @param texture The texture you want to create a SubTexture from.
* @param region The region of the parent texture that the SubTexture will show
* (in points).
* @param frame If the texture was trimmed, the frame rectangle can be used to restore
* the trimmed area.
* @param rotated If true, the SubTexture will show the parent region rotated by
* 90 degrees (CCW).
* @param scaleModifier The scale factor of the new texture will be calculated by
* multiplying the parent texture's scale factor with this value.
*/
public static fromTexture(texture:Texture, region?:Rectangle,
frame?:Rectangle, rotated?:boolean,
scaleModifier?:number):Texture;
/** Sets up a VertexData instance with the correct positions for 4 vertices so that
* the texture can be mapped onto it unscaled. If the texture has a <code>frame</code>,
* the vertices will be offset accordingly.
*
* @param vertexData the VertexData instance to which the positions will be written.
* @param vertexID the start position within the VertexData instance.
* @param attrName the attribute name referencing the vertex positions.
* @param bounds useful only for textures with a frame. This will position the
* vertices at the correct position within the given bounds,
* distorted appropriately.
*/
public setupVertexPositions(vertexData:VertexData, vertexID?:number,
attrName?:string,
bounds?:Rectangle):void;
/** Sets up a VertexData instance with the correct texture coordinates for
* 4 vertices so that the texture is mapped to the complete quad.
*
* @param vertexData the vertex data to which the texture coordinates will be written.
* @param vertexID the start position within the VertexData instance.
* @param attrName the attribute name referencing the vertex positions.
*/
public setupTextureCoordinates(vertexData:VertexData, vertexID?:number,
attrName?:string):void;
/** Transforms the given texture coordinates from the local coordinate system
* into the root texture's coordinate system. */
public localToGlobal(u:number, v:number, out?:Point):Point;
/** Transforms the given texture coordinates from the root texture's coordinate system
* to the local coordinate system. */
public globalToLocal(u:number, v:number, out?:Point):Point;
/** Writes the given texture coordinates to a VertexData instance after transforming
* them into the root texture's coordinate system. That way, the texture coordinates
* can be used directly to sample the texture in the fragment shader. */
public setTexCoords(vertexData:VertexData, vertexID:number, attrName:string,
u:number, v:number):void;
/** Reads a pair of texture coordinates from the given VertexData instance and transforms
* them into the current texture's coordinate system. (Remember, the VertexData instance
* will always contain the coordinates in the root texture's coordinate system!) */
public getTexCoords(vertexData:VertexData, vertexID:number,
attrName?:string, out?:Point):Point;
// properties
/** The texture frame if it has one (see class description), otherwise <code>null</code>.
* <p>CAUTION: not a copy, but the actual object! Do not modify!</p> */
public readonly frame:Rectangle;
protected get_frame():Rectangle;
/** The height of the texture in points, taking into account the frame rectangle
* (if there is one). */
public readonly frameWidth:number;
protected get_frameWidth():number;
/** The width of the texture in points, taking into account the frame rectangle
* (if there is one). */
public readonly frameHeight:number;
protected get_frameHeight():number;
/** The width of the texture in points. */
public readonly width:number;
protected get_width():number;
/** The height of the texture in points. */
public readonly height:number;
protected get_height():number;
/** The width of the texture in pixels (without scale adjustment). */
public readonly nativeWidth:number;
protected get_nativeWidth():number;
/** The height of the texture in pixels (without scale adjustment). */
public readonly nativeHeight:number;
protected get_nativeHeight():number;
/** The scale factor, which influences width and height properties. */
public readonly scale:number;
protected get_scale():number;
/** The Stage3D texture object the texture is based on. */
public readonly base:TextureBase;
protected get_base():TextureBase;
/** The concrete texture the texture is based on. */
public readonly root:ConcreteTexture;
protected get_root():ConcreteTexture;
/** The <code>Context3DTextureFormat</code> of the underlying texture data. */
public readonly format:Context3DTextureFormat;
protected get_format():Context3DTextureFormat;
/** Indicates if the texture contains mip maps. */
public readonly mipMapping:boolean;
protected get_mipMapping():boolean;
/** Indicates if the alpha values are premultiplied into the RGB values. */
public readonly premultipliedAlpha:boolean;
protected get_premultipliedAlpha():boolean;
/** The matrix that is used to transform the texture coordinates into the coordinate
* space of the parent texture, if there is one. @default null
*
* <p>CAUTION: not a copy, but the actual object! Never modify this matrix!</p> */
public readonly transformationMatrix:Matrix;
protected get_transformationMatrix():Matrix;
/** The matrix that is used to transform the texture coordinates into the coordinate
* space of the root texture, if this instance is not the root. @default null
*
* <p>CAUTION: not a copy, but the actual object! Never modify this matrix!</p> */
public readonly transformationMatrixToRoot:Matrix;
protected get_transformationMatrixToRoot():Matrix;
/** Returns the maximum size constraint (for both width and height) for uncompressed
* textures in the current Context3D profile. */
public static readonly maxSize:number;
protected static get_maxSize():number;
public static getMaxSize(textureFormat?:Context3DTextureFormat):number;
/** Indicates if it should be attempted to upload bitmaps asynchronously when the <code>async</code> parameter
* is supplied to supported methods. Since this feature is still not 100% reliable in AIR 26 (especially on
* Android), it defaults to 'false' for now.
*
* <p>If the feature is disabled or not available in the current AIR/Flash runtime, the async callback will
* still be executed; however, the upload itself will be made synchronously.</p>
*/
public static asyncBitmapUploadEnabled:boolean;
protected static get_asyncBitmapUploadEnabled():boolean;
protected static set_asyncBitmapUploadEnabled(value:boolean):boolean;
}
}
export default starling.textures.Texture; | the_stack |
import { Component, OnInit, Renderer2, ViewChild, ElementRef, Input } from '@angular/core';
import * as jp from 'jsplumb';
import { fromEvent } from 'rxjs/internal/observable/fromEvent';
import { ActivatedRoute } from '@angular/router';
import { WorkflowNode } from '../model/workflowNode';
import { WorkflowLink } from '../model/workflowLink';
import { WorkflowFlowService } from 'src/app/business/workflow/workflow-flow.service';
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
import { BehaviorSubject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { PositionService } from 'src/app/business/group-manage/position.service';
import { DepartmentService } from 'src/app/business/group-manage/department.service';
import { WorkflowFormService } from 'src/app/business/workflow/workflow-form.service';
import { WorkflowNodeCondition } from '../model/workflowNodeCondition';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef, NzModalService } from 'ng-zorro-antd/modal';
import { UserService } from 'src/app/business/system-manage/user.service';
@Component({
selector: 'app-flow-design',
templateUrl: './flow-design.component.html',
styleUrls: ['./flow-design.component.less']
})
export class FlowDesignComponent implements OnInit {
// 流程图
@ViewChild('flowContainer', { static: true })
private _flowContainer: ElementRef;
@ViewChild('selectedBorder', { static: true })
private _sborder: ElementRef;
// 节点编辑
@ViewChild('nodeEditTpl', { static: true })
private _nodeEditTpl;
// 编辑节点表单
workflowNodeEditForm: FormGroup = new FormGroup({});
connections = [];
connectionFormControls: { [key: string]: any[]; } = {};
// 节点数据
private _nodeDataList: WorkflowNode[] = [];
private _linkDataList: WorkflowLink[] = [];
private _conditionDataList: WorkflowNodeCondition[] = [];
private _jsPlumb = jp.jsPlumb;
private _jsPlumbInstance;
private _endpointOption: jp.EndpointOptions = {
maxConnections: 10,
reattachConnections: true,
type: 'Dot',
connector: 'Flowchart',
isSource: true,
isTarget: true,
paintStyle: { fill: 'transparent', stroke: 'transparent', strokeWidth: 1 },
hoverPaintStyle: { fill: 'rgba(95, 158, 160, 1)', stroke: 'rgba(95, 158, 160, 1)', strokeWidth: 2 },
connectorStyle: { stroke: 'rgba(102, 96, 255, 0.9)', strokeWidth: 3 },
connectorHoverStyle: { strokeWidth: 4 },
connectorOverlays: [["PlainArrow", { location: 1 }]],
};
nodes = [
{ key: 'start', name: '开始节点', icon: 'play-circle' },
{ key: 'work', name: '工作节点', icon: 'check-circle' },
{ key: 'end', name: '结束节点', icon: 'stop' }
];
// 拖拽的节点类型key
private _draggedKey;
// 点击选中的节点
private _checkedNode = null;
// 加载中
isLoading = false;
// 用户
userSearchChange$ = new BehaviorSubject('');
userList = [];
// 用户
positionSearchChange$ = new BehaviorSubject('');
positionList = [];
// 用户
departmentSearchChange$ = new BehaviorSubject('');
departmentList = [];
// 模态框
nzModal: NzModalRef;
// 表单选项
formControlList = [];
// 工作流ID
@Input()
workflowId = null;
@Input()
workflowName = null;
constructor(
private _renderer: Renderer2,
private _route: ActivatedRoute,
private _formService: WorkflowFormService,
private _flowService: WorkflowFlowService,
private _messageService: NzMessageService,
private _formBuilder: FormBuilder,
private _userService: UserService,
private _positionService: PositionService,
private _departmentService: DepartmentService,
private _modalServce: NzModalService) { }
ngOnInit(): void {
this.listenKeyboard();
this.initGraph();
this.initData();
// 初始化搜索事件
this.userSearchChange$.asObservable().pipe(debounceTime(500)).subscribe(value => {
this._userService.getUserDic(value).subscribe((result: any) => {
this.userList = result;
this.isLoading = false;
});
});
this.positionSearchChange$.asObservable().pipe(debounceTime(500)).subscribe(value => {
this._positionService.getDic(value).subscribe((result: any) => {
this.positionList = result;
this.isLoading = false;
});
});
this.departmentSearchChange$.asObservable().pipe(debounceTime(500)).subscribe(value => {
this._departmentService.getDic(value).subscribe((result: any) => {
this.departmentList = result;
this.isLoading = false;
});
});
// 初始化表单选项
this._formService.getControlDic(this.workflowId).subscribe((result: any) => {
this.formControlList = result;
});
}
// 初始化流程图
initGraph() {
// 创建实例
this._jsPlumbInstance = this._jsPlumb.getInstance({
DragOptions: { cursor: 'move', zIndex: 2000 },
Container: 'flow-container'
});
// 绑定点击
this._jsPlumbInstance.bind('click', (conn, orignalEvent) => {
this._jsPlumbInstance.deleteConnection(conn);
});
}
// 监听键盘
listenKeyboard() {
fromEvent(window, 'keydown').subscribe((event: any) => {
if (this._checkedNode) {
if (event.key == 'Delete') {
this._jsPlumbInstance.remove(this._checkedNode);
this._nodeDataList = this._nodeDataList.filter(d => d.domId != this._checkedNode.id);
}
}
});
}
// 初始化数据
initData() {
this._flowService.get(this.workflowId).subscribe((result: any) => {
this._nodeDataList = result.workFlowNodeResults ? result.workFlowNodeResults : [];
this._linkDataList = result.workFlowLinkResults ? result.workFlowLinkResults : [];
this._conditionDataList = result.workFlowConditionResults ? result.workFlowConditionResults : [];
this._nodeDataList.forEach(nodeData => {
switch (nodeData.nodeType) {
case 0:
this.addStartNode(nodeData.domId, nodeData.left, nodeData.top, nodeData.name);
break;
case 1:
this.addWorkNode(nodeData.domId, nodeData.left, nodeData.top, nodeData.name);
break;
case 99:
this.addEndNode(nodeData.domId, nodeData.left, nodeData.top, nodeData.name);
break;
}
});
this._linkDataList.forEach(linkData => {
this._jsPlumbInstance.connect({
source: linkData.sourceId,
target: linkData.targetId,
anchor: 'Continuous'
});
});
});
}
addStartNode(id, x, y, title = "开始节点") {
this.addNode(id, x, y, title);
this._endpointOption.maxConnections = 1;
this._endpointOption.isSource = true;
this._endpointOption.isTarget = false;
// 配置源
this._jsPlumbInstance.makeSource(id, {
anchor: 'Continuous',
allowLoopback: false,
filter: (event, element) => {
return event.target.classList.contains('connectable');
}
}, this._endpointOption);
}
addWorkNode(id, x, y, title = '工作节点') {
this.addNode(id, x, y, title, true);
this._endpointOption.maxConnections = 10;
this._endpointOption.isSource = true;
this._endpointOption.isTarget = true;
// 配置源
this._jsPlumbInstance.makeSource(id, {
anchor: 'Continuous',
allowLoopback: false,
filter: (event, element) => {
return event.target.classList.contains('connectable');
}
}, this._endpointOption);
// 配置目标
this._jsPlumbInstance.makeTarget(id, {
anchor: 'Continuous',
allowLoopback: false,
filter: (event, element) => {
return event.target.classList.contains('connectable');
}
}, this._endpointOption);
}
addEndNode(id, x, y, title = '结束节点') {
this.addNode(id, x, y, title);
this._endpointOption.maxConnections = 100;
this._endpointOption.isSource = false;
this._endpointOption.isTarget = true;
// 配置源
this._jsPlumbInstance.makeTarget(id, {
anchor: 'Continuous',
allowLoopback: false,
filter: (event, element) => {
return event.target.classList.contains('connectable');
}
}, this._endpointOption);
}
addNode(id, x, y, title, hasDblClickEvent = false) {
// 节点
let node = this._renderer.createElement('div');
this._renderer.setStyle(node, 'top', `${y}px`);
this._renderer.setStyle(node, 'left', `${x}px`);
this._renderer.addClass(node, 'node');
this._renderer.setAttribute(node, 'id', id);
// 设置节点事件
this._renderer.listen(node, 'mousedown', event => {
this._checkedNode = node;
// 绑定四个元素作为border的目的是为了以后修改为调整大小的瞄点
this._renderer.setStyle(this._sborder.nativeElement, 'display', 'block');
this._renderer.appendChild(node, this._sborder.nativeElement);
});
// 双击编辑节点事件
if (hasDblClickEvent) {
this._renderer.listen(node, 'dblclick', event => {
let data = this._nodeDataList.find(d => d.domId == node.id);
if (data) {
let idArray = [];
if (data.handlers) {
this.userList = [];
data.handlers?.split(',').forEach(id => {
idArray.push(Number.parseInt(id));
})
this.initUserSelectData(idArray);
}
if (data.position) {
this.positionList = [];
this.initPositionSelectData(data.position);
}
if (data.department) {
this.departmentList = [];
this.initDepartmentSelectData(data.department);
}
this.connections = this._jsPlumbInstance.getAllConnections().filter(element => {
return element.sourceId == node.id;
});
// 构建表单成员
this.workflowNodeEditForm = this._formBuilder.group({
id: data.domId,
name: [data.name, [Validators.required, Validators.maxLength(15)]],
handleMode: [data.handleMode, [Validators.required, Validators.pattern('^[12345]$')]],
handlers: [idArray, [Validators.required]],
position: [Number.parseInt(data.position), [Validators.required]],
department: [Number.parseInt(data.department), [Validators.required]]
});
// 构建条件列表
this.connectionFormControls = {};
this.connections.forEach(connection => {
this.connectionFormControls[connection.targetId] = [];
let conditions = this._conditionDataList.filter(data => data.sourceId == node.id && data.targetId == connection.targetId);
conditions.forEach(condition => {
// 添加表单项并赋值
this.addFormControl(connection.targetId, condition.formControlId, condition.compareMode, condition.compareValue);
});
});
this.nzModal = this._modalServce.create({
nzTitle: '编辑节点信息',
nzContent: this._nodeEditTpl,
nzFooter: null,
nzMaskClosable: false,
nzWidth: 800
});
}
});
}
// 拼接节点到流程图
this._renderer.appendChild(this._flowContainer.nativeElement, node);
// 设置节点连线区域
let iconArea = this._renderer.createElement('div');
this._renderer.addClass(iconArea, 'connectable');
// let newEl = icon.nativeElement.cloneNode(true);
// this._renderer.setStyle(newEl, 'display', 'inline');
// this._renderer.appendChild(iconArea, newEl);
this._renderer.appendChild(node, iconArea);
// 设置节点拖拽区域
let draggableArea = this._renderer.createElement('div');
this._renderer.addClass(draggableArea, 'draggable');
let titleEl = this._renderer.createText(title);
this._renderer.appendChild(draggableArea, titleEl);
this._renderer.appendChild(node, draggableArea);
// 设施元素在流程图中可拖拽
this._jsPlumbInstance.draggable(node, {
filter: '.draggable',
filterExclude: false,
drag: (event) => {
let data = this._nodeDataList.find(d => d.domId == this._checkedNode.id);
data.top = Number.parseInt(event.el.style.top);
data.left = Number.parseInt(event.el.style.left);
}
});
}
// 添加一组条件
addFormControl(targetId, formControlIdValue = null, compareModeValue = null, compareValueValue = null) {
let formControlId = `formControlId${this.randomKey()}`;
let compareMode = `compareMode${this.randomKey()}`;
let compareValue = `compareValue${this.randomKey()}`;
this.connectionFormControls[targetId].push({
formControlId: formControlId,
compareMode: compareMode,
compareValue: compareValue,
});
this.workflowNodeEditForm.addControl(formControlId, new FormControl(formControlIdValue?.toString()));
this.workflowNodeEditForm.addControl(compareMode, new FormControl(compareModeValue));
this.workflowNodeEditForm.addControl(compareValue, new FormControl(compareValueValue));
}
// 删除一组条件
removeFormControl(targetId, formControlId) {
let controlInfo = this.connectionFormControls[targetId].find(o => o.formControlId == formControlId);
this.workflowNodeEditForm.removeControl(controlInfo.formControlId);
this.workflowNodeEditForm.removeControl(controlInfo.compareModel);
this.workflowNodeEditForm.removeControl(controlInfo.compareValue);
this.connectionFormControls[targetId] = this.connectionFormControls[targetId].filter(o => o.formControlId != formControlId);
}
// cdk的drag和drop
// drop(event) {
// console.log(event);
// console.log(event.previousContainer === event.container);
// if (event.isPointerOverContainer) {
// this.addNode(event.distance.x, event.distance.y);
// }
// }
// // 禁止任何元素进入
//noReturnPredicate() {
// return false;
//}
back() {
history.go(-1);
}
// 保存流程图
save() {
this._linkDataList = [];
this._jsPlumbInstance.getAllConnections().forEach(element => {
this._linkDataList.push({
sourceId: element.sourceId,
targetId: element.targetId,
})
});
this._nodeDataList.forEach(n => {
n.left = Number.parseInt(n.left.toString());
n.top = Number.parseInt(n.top.toString());
});
this._flowService.addOrUpdate({
workFlowId: Number.parseInt(this.workflowId),
workFlowLinkViewModels: this._linkDataList,
workFlowNodeViewModels: this._nodeDataList,
workFlowConditionViewModels: this._conditionDataList,
}).subscribe(result => {
this._messageService.success('修改成功!');
})
}
onDragStart(event, key) {
//event.target.style.background = 'red';
this._draggedKey = key;
}
onDragOver(event) {
event.preventDefault();
}
dropZone(event) {
event.preventDefault();
// 取得offsetx时,如果有子元素会冒泡,将子元素的offset设置
let rect = event.currentTarget.getBoundingClientRect();
let x = event.clientX - rect.left - 100;
let y = event.clientY - rect.top - 25;
let id = `node${this.randomKey()}`;
// 保存节点数据
let nodeData = new WorkflowNode();
switch (this._draggedKey) {
case 'start':
if (this._nodeDataList.find(d => d.nodeType == 0)) {
this._messageService.error('已经有一个开始节点了!');
} else {
this.addStartNode(id, x, y);
nodeData.name = '开始节点';
nodeData.nodeType = 0;
}
break;
case 'work':
this.addWorkNode(id, x, y);
nodeData.name = '工作节点';
nodeData.nodeType = 1;
break;
case 'end':
if (this._nodeDataList.find(d => d.nodeType == 99)) {
this._messageService.error('已经有一个开始节点了!');
} else {
this.addEndNode(id, x, y);
nodeData.name = '结束节点';
nodeData.nodeType = 99;
}
break;
}
nodeData.domId = id;
nodeData.top = y;
nodeData.left = x;
this._nodeDataList.push(nodeData);
}
// 键入用户关键字搜索
onSearchUser(value: string): void {
if (value) {
this.isLoading = true;
this.userSearchChange$.next(value);
}
}
// 键入职位关键字搜索
onSearchPosition(value: string): void {
if (value) {
this.isLoading = true;
this.positionSearchChange$.next(value);
}
}
// 键入职位关键字搜索
onSearchDepartment(value: string): void {
if (value) {
this.isLoading = true;
this.departmentSearchChange$.next(value);
}
}
// 提交节点编辑结果
submitWorkflowNodeEdit() {
this.workflowNodeEditForm.controls['name'].markAsDirty();
this.workflowNodeEditForm.controls['name'].updateValueAndValidity();
this.workflowNodeEditForm.controls['handleMode'].markAsDirty();
this.workflowNodeEditForm.controls['handleMode'].updateValueAndValidity();
let validResult = false;
if (this.workflowNodeEditForm.value['handleMode'] == 1) {
this.workflowNodeEditForm.controls['handlers'].markAsDirty();
this.workflowNodeEditForm.controls['handlers'].updateValueAndValidity();
validResult = this.workflowNodeEditForm.controls['name'].valid &&
this.workflowNodeEditForm.controls['handleMode'].valid &&
this.workflowNodeEditForm.controls['handlers'].valid;
} else if (this.workflowNodeEditForm.value['handleMode'] == 2) {
this.workflowNodeEditForm.controls['position'].markAsDirty();
this.workflowNodeEditForm.controls['position'].updateValueAndValidity();
validResult = this.workflowNodeEditForm.controls['name'].valid &&
this.workflowNodeEditForm.controls['handleMode'].valid &&
this.workflowNodeEditForm.controls['position'].valid;
} else if (this.workflowNodeEditForm.value['handleMode'] == 3) {
this.workflowNodeEditForm.controls['department'].markAsDirty();
this.workflowNodeEditForm.controls['department'].updateValueAndValidity();
validResult = this.workflowNodeEditForm.controls['name'].valid &&
this.workflowNodeEditForm.controls['handleMode'].valid &&
this.workflowNodeEditForm.controls['department'].valid;
} else if (this.workflowNodeEditForm.value['handleMode'] == 4) {
validResult = this.workflowNodeEditForm.controls['name'].valid &&
this.workflowNodeEditForm.controls['handleMode'].valid
}
if (validResult) {
// 基本信息,办理信息
let data = this._nodeDataList.find(d => d.domId == this.workflowNodeEditForm.value['id']);
data.name = this.workflowNodeEditForm.value['name'];
data.handleMode = this.workflowNodeEditForm.value['handleMode'];
data.handlers = this.workflowNodeEditForm.value['handlers']?.join(',');
data.position = this.workflowNodeEditForm.value['position'];
data.department = this.workflowNodeEditForm.value['department'];
this._checkedNode.childNodes[1].innerText = data.name;
// 转出条件
for (let key in this.connectionFormControls) {
let data = this.connectionFormControls[key];
// 清理当前节点的指向key节点的所有条件,在下边重新添加
this._conditionDataList = this._conditionDataList.filter(data => !(data.sourceId == this._checkedNode.id && data.targetId == key));
data.forEach(element => {
let formControlId = this.workflowNodeEditForm.value[element.formControlId];
let compareMode = this.workflowNodeEditForm.value[element.compareMode];
let compareValue = this.workflowNodeEditForm.value[element.compareValue];
if (formControlId && compareMode && compareValue) {
let condition = new WorkflowNodeCondition();
condition.sourceId = this._checkedNode.id;
condition.targetId = key;
condition.formControlId = formControlId;
condition.compareMode = compareMode;
condition.compareValue = compareValue;
this._conditionDataList.push(condition);
}
});
}
this.nzModal.close();
}
}
initUserSelectData(handlers) {
handlers.forEach(handler => {
this._userService.getUser(handler).subscribe((result: any) => {
this.userList.push({
key: result.id,
value: result.name
});
});
});
}
initPositionSelectData(id) {
this._positionService.getPosition(id).subscribe((result: any) => {
this.positionList.push({
key: result.id,
value: result.name
});
});
}
initDepartmentSelectData(id) {
this._departmentService.get(id).subscribe((result: any) => {
this.departmentList.push({
key: result.id,
value: result.name
});
});
}
getNodeName(id) {
return this._nodeDataList.find(data => data.domId == id).name;
}
cancel() {
this.nzModal.close();
}
randomKey(): number {
return Date.parse(new Date().toString()) + Math.floor(Math.random() * Math.floor(999));
}
} | the_stack |
import { mapValues, compact, xor, uniq, pickBy } from "lodash-es"
import Prismatic from "data/specs/Prismatic"
import Capstone from "data/specs/Capstone"
import Elementary from "data/specs/Elementary"
import { Polyhedron, Face, Cap } from "math/polyhedra"
import { isInverse, getOrthonormalTransform, PRECISION } from "math/geom"
import { repeat, getCyclic, getSingle } from "utils"
import { makeOperation } from "../Operation"
import { withOrigin } from "../../geom"
import { oppositeFace, deduplicateVertices } from "../operationUtils"
import { inc, dec, CutPasteSpecs } from "./cutPasteUtils"
type AugmentSpecs = Prismatic | CutPasteSpecs
type AugmentType = "pyramid" | "cupola" | "rotunda"
// TODO simplify using Specs
const augmentees: Record<AugmentType, Record<number, string>> = {
pyramid: {
3: "tetrahedron",
4: "square pyramid",
5: "pentagonal pyramid",
},
cupola: {
2: "triangular prism",
3: "triangular cupola",
4: "square cupola",
5: "pentagonal cupola",
},
rotunda: {
5: "pentagonal rotunda",
},
}
const augmentData = mapValues(augmentees, (type) =>
mapValues(type, Polyhedron.get),
)
const augmentTypes: Record<string, AugmentType> = {
Y: "pyramid",
U: "cupola",
R: "rotunda",
}
function hasAugmentAlignment(info: AugmentSpecs) {
if (!info.isComposite()) return false
const { source, augmented } = info.data
if (augmented !== 1) return false
// Only hexagonal prism has augment alignment
if (source.isPrismatic()) return source.data.base === 6
// If Classical, has alignment if it has icosahedral symmetry
return source.isIcosahedral()
}
function getAugmentAlignment(polyhedron: Polyhedron, face: Face) {
const boundary = getSingle(Cap.getAll(polyhedron)).boundary()
return isInverse(boundary.normal(), face.normal()) ? "para" : "meta"
}
function getPossibleAugmentees(n: number) {
const { pyramid, cupola, rotunda } = augmentData
return compact([pyramid[n], cupola[n / 2], rotunda[n / 2]])
}
// Checks to see if the polyhedron can be augmented at the base while remaining convex
function canAugmentWith(base: Face, augmentee: Polyhedron, offset: number) {
const n = base.numSides
if (!augmentee) return false
const underside = augmentee.faceWithNumSides(n)
return base.edges.every((edge, i: number) => {
const baseAngle = edge.dihedralAngle()
const edge2 = getCyclic(underside.edges, i - 1 + offset)
const augmenteeAngle = edge2.dihedralAngle()
return baseAngle + augmenteeAngle < Math.PI - PRECISION
})
}
function canAugmentWithType(base: Face, using: string) {
const augmentType = getUsingType(using)
const n = augmentType === "pyramid" ? base.numSides : base.numSides / 2
for (const offset of [0, 1]) {
if (canAugmentWith(base, augmentData[augmentType][n], offset)) {
return true
}
}
return false
}
function canAugment(base: Face) {
const n = base.numSides
const augmentees = getPossibleAugmentees(n)
for (const augmentee of augmentees) {
for (const offset of [0, 1]) {
if (canAugmentWith(base, augmentee, offset)) {
return true
}
}
}
return false
}
// Computes the set equality of two arrays
const setEquals = <T>(array1: T[], array2: T[]) =>
xor(array1, array2).length === 0
function getBaseType(base: Face) {
const adjacentFaces = base.adjacentFaces()
const adjacentFaceCounts = uniq(adjacentFaces.map((f) => f.numSides))
if (setEquals(adjacentFaceCounts, [3, 4])) {
return "cupola"
} else if (setEquals(adjacentFaceCounts, [4])) {
return "prism"
} else if (setEquals(adjacentFaceCounts, [3])) {
return "pyramidOrAntiprism"
} else if (setEquals(adjacentFaceCounts, [3, 5])) {
return "rotunda"
} else if (setEquals(adjacentFaceCounts, [4, 5])) {
return "rhombicosidodecahedron"
} else {
return "truncated"
}
}
function isCupolaRotunda(baseType: string, augmentType: string) {
return setEquals(["cupola", "rotunda"], [baseType, augmentType])
}
// TODO redo this function to rely on tableUtils instead
// Return true if the base and augmentee are aligned
function isAligned(
polyhedron: Polyhedron,
base: Face,
underside: Face,
gyrate: string | undefined,
augmentType: string,
) {
if (augmentType === "pyramid") return true
const baseType = getBaseType(base)
if (baseType === "pyramidOrAntiprism") {
return true
}
if (baseType === "prism" && Cap.getAll(polyhedron).length === 0) {
return true
}
if (baseType !== "truncated" && !gyrate) {
throw new Error(`Must define 'gyrate' for augmenting ${baseType} `)
}
const adjFace =
baseType === "prism" ? oppositeFace(base.edges[0]) : base.adjacentFaces()[0]
const alignedFace = getCyclic(underside.adjacentFaces(), -1)
if (baseType === "rhombicosidodecahedron") {
const isOrtho = (adjFace.numSides !== 4) === (alignedFace.numSides !== 4)
return isOrtho === (gyrate === "ortho")
}
// It's orthogonal if triangle faces are aligned or non-triangle faces are aligned
const isOrtho = (adjFace.numSides !== 3) === (alignedFace.numSides !== 3)
if (baseType === "truncated") {
return !isOrtho
}
// "ortho" or "gyro" is actually determined by whether the *tops* are aligned, not the bottoms
// So for a cupola-rotunda, it's actually the opposite of everything else
if (isCupolaRotunda(Cap.getAll(polyhedron)[0].type, augmentType)) {
return isOrtho !== (gyrate === "ortho")
}
return isOrtho === (gyrate === "ortho")
}
function getAugmentee(augmentType: AugmentType, numSides: number) {
const index = ["cupola", "rotunda"].includes(augmentType)
? numSides / 2
: numSides
return augmentData[augmentType][index]
}
function isFastigium(augmentType: string, numSides: number) {
return augmentType === "cupola" && numSides === 4
}
// Augment the following
function doAugment(
info: AugmentSpecs,
polyhedron: Polyhedron,
base: Face,
augmentType: AugmentType,
gyrate?: string,
) {
const numSides = base.numSides
const augmentee = getAugmentee(augmentType, numSides)
const underside = augmentee.faceWithNumSides(base.numSides)
// Determine the orientations of the underside and the base
const undersideRadius = underside.vertices[0].vec
.sub(underside.centroid())
.getNormalized()
const baseIsAligned = isAligned(
polyhedron,
base,
underside,
isFastigium(augmentType, numSides) ? "gyro" : gyrate,
augmentType,
)
const offset = baseIsAligned ? 0 : 1
const baseRadius = base.vertices[offset].vec
.sub(base.centroid())
.getNormalized()
// https://math.stackexchange.com/questions/624348/finding-rotation-axis-and-angle-to-align-two-oriented-vectors
// Determine the transformation that rotates the underside orientation to the base orientation
// TODO we probably want this as some sort of generic method
const transformMatrix = getOrthonormalTransform(
undersideRadius,
underside.normal().getInverted(),
baseRadius,
base.normal(),
)
const transform = withOrigin(base.centroid(), (u) =>
transformMatrix.applyTo(u),
)
// Scale and position the augmentee so that it lines up with the base
const alignedVertices = augmentee.vertices.map((v) => {
return v.vec
.sub(underside.centroid())
.scale(base.sideLength() / augmentee.edgeLength())
.add(base.centroid())
})
// Rotate the vertices so that they align with the base
const rotatedVertices = alignedVertices.map((v) => transform(v))
const newAugmentee = augmentee.withChanges((s) =>
s.withVertices(rotatedVertices).withoutFaces([underside]),
)
const augmenteeInitial = augmentee.withVertices(
repeat(base.centroid(), augmentee.numVertices()),
)
const endResult = polyhedron.addPolyhedron(newAugmentee)
return {
animationData: {
start: polyhedron.addPolyhedron(augmenteeInitial),
endVertices: endResult.vertices,
},
result: deduplicateVertices(endResult.withoutFaces([base])),
}
}
function defaultAugmentType(numSides: number) {
return numSides <= 5 ? "pyramid" : "cupola"
}
const defaultAugmentees: Record<number, string> = {
3: "Y3",
4: "Y4",
5: "Y5",
6: "U3",
8: "U4",
10: "U5",
}
function getAugmenteeNumSides(using: string) {
const { type, base } = getUsingData(using)
return ["rotunda", "cupola"].includes(type) ? base * 2 : base
}
function getUsingOpt(numSides: number, using?: string) {
return !!using && getAugmenteeNumSides(using) === numSides
? using
: defaultAugmentees[numSides]
}
function hasRotunda(info: AugmentSpecs) {
if (info.isPrismatic()) {
return info.data.base === 10
}
if (info.isCapstone()) {
return info.isMono() && !info.isPyramid() && info.isPentagonal()
}
return false
}
function getUsingData(using: string) {
const [prefix, baseStr] = using
return { type: augmentTypes[prefix], base: parseInt(baseStr) }
}
function getUsingType(using: string) {
return getUsingData(using).type
}
function getUsingOpts(info: AugmentSpecs) {
// Triangular prism or fastigium
if (info.canonicalName() === "triangular prism") {
return ["Y4", "U2"]
}
if (hasRotunda(info)) {
return ["U5", "R5"]
}
return null
}
function hasGyrateOpts(info: AugmentSpecs) {
if (info.isCapstone()) {
// Gyroelongated capstones are always gyro
if (info.isGyroelongated()) return false
// Cupolae and rotundae (that are not the gyrobifastigium) always have gyrate opts
if (!info.isDigonal() && !info.isPyramid()) return true
return false
}
if (info.isComposite()) {
return info.data.source.canonicalName() === "rhombicosidodecahedron"
}
return false
}
type GyrateOpts = "ortho" | "gyro"
const allGyrateOpts: GyrateOpts[] = ["ortho", "gyro"]
interface Options {
face: Face
gyrate?: GyrateOpts
using?: string
}
export const augment = makeOperation<Options, AugmentSpecs>("augment", {
apply({ specs, geom }, { face, gyrate, using }) {
const augmentType = using
? getUsingType(using)
: defaultAugmentType(face.numSides)
return doAugment(specs, geom, face, augmentType, gyrate)
},
canApplyTo(info) {
if (info.isPrismatic()) {
const { base } = info.data
if (info.isAntiprism() && base === 3) return false
return base > 2
}
if (info.isCapstone()) {
return info.isMono()
}
if (info.isComposite()) {
const { source, diminished, augmented } = info.data
if (source.canonicalName() === "rhombicosidodecahedron") {
return diminished > 0
}
if (source.canonicalName() === "icosahedron") {
return diminished > 0 && augmented === 0
}
if (source.isPrismatic()) {
return (
augmented < (source.data.base % 3 === 0 ? 3 : 2) && !info.isPara()
)
}
if (source.isClassical()) {
return augmented < source.data.family - 2 && !info.isPara()
}
}
if (info.isElementary()) {
return info.canonicalName() === "sphenocorona"
}
return false
},
isPreferredSpec(info, { face, using }) {
const n = face.numSides
const { type, base } = getUsingData(getUsingOpt(n, using))
if (base === 4 && type === "pyramid") {
if (info.isPrismatic() && info.isPrism()) return false
}
// for the fastigium, depend on what the using option is
if (info.canonicalName() === "triangular prism") {
if (type === "cupola") return info.isCapstone()
return base === 3 ? info.isPrismatic() : info.isComposite()
}
return true
},
getResult({ specs, geom }, { face, using, gyrate }) {
const n = face.numSides
const { type, base } = getUsingData(getUsingOpt(n, using))
if (specs.isPrismatic()) {
return Capstone.query.withData({
count: 1,
elongation: specs.data.type,
type,
base: base as any,
})
}
if (specs.isCapstone()) {
return specs.withData({
count: 2,
gyrate: base === 2 ? "gyro" : gyrate,
type: type === specs.data.type ? type : "cupolarotunda",
})
}
if (specs.isComposite()) {
const { source, augmented, diminished, gyrate: gyrated } = specs.data
if (source.canonicalName() === "rhombicosidodecahedron") {
if (gyrate === "ortho") {
return specs.withData({
gyrate: inc(gyrated),
diminished: dec(diminished),
})
} else {
return specs.withData({ diminished: dec(diminished), align: "meta" })
}
}
if (source.canonicalName() === "icosahedron") {
if (base === 3) {
return specs.withData({ augmented: 1 })
}
return specs.withData({ diminished: dec(diminished), align: "meta" })
}
return specs.withData({
augmented: inc(augmented),
align: hasAugmentAlignment(specs)
? getAugmentAlignment(geom, face)
: undefined,
})
}
if (specs.isElementary()) {
return Elementary.query.withName("augmented sphenocorona")
}
throw new Error()
},
hasOptions() {
return true
},
*allOptionCombos({ specs, geom }) {
const gyrateOpts = hasGyrateOpts(specs) ? allGyrateOpts : [undefined]
const usingOpts = getUsingOpts(specs) ?? [undefined]
const faceOpts = geom.faces.filter((face) => canAugment(face))
for (const face of faceOpts) {
for (const gyrate of gyrateOpts) {
for (const using of usingOpts) {
if (!using || canAugmentWithType(face, using)) {
yield { gyrate, using, face }
}
}
}
}
},
hitOption: "face",
getHitOption({ geom }, hitPnt, options) {
if (!options) return {}
const face = geom.hitFace(hitPnt)
if (!options.using) {
return canAugment(face) ? { face } : {}
}
if (!canAugmentWithType(face, options.using)) {
return {}
}
return { face }
},
faceSelectionStates({ geom }, { face, using }) {
return geom.faces.map((f) => {
if (face && f.equals(face)) return "selected"
if (!using && canAugment(f)) return "selectable"
if (using && canAugmentWithType(f, using)) return "selectable"
return undefined
})
},
allOptions({ specs, geom }, optionName) {
switch (optionName) {
case "gyrate":
return hasGyrateOpts(specs) ? allGyrateOpts : []
case "using":
return getUsingOpts(specs) ?? []
case "face":
return geom.faces.filter((face) => canAugment(face))
}
},
defaultOptions(info) {
const usingOpts = getUsingOpts(info) ?? []
return pickBy({
gyrate: hasGyrateOpts(info) && "gyro",
using: usingOpts.length > 1 && usingOpts[0],
})
},
}) | the_stack |
import * as a from '../parser/ast';
import { orStr } from '../util';
import { TypeContext, IdentTypeDef } from './context';
import { TypeError } from './error';
export function typeCheck(mod: a.Module, ctx: TypeContext) {
ctx.enterScope();
// FIXME: process imports
// register global decls
mod.value.decls.forEach(decl => registerDeclType(decl, ctx));
// actual type checks for exprs (including function body)
mod.value.decls.forEach(decl => checkDeclType(decl, ctx));
ctx.leaveScope();
return mod;
}
function cloneType<T, TY extends a.Type<T>>(
orig: TY,
{ row, column }: { row: number; column: number },
): TY {
return new (orig.constructor as any)(orig.value, row, column);
}
export function checkExprType(
expr: a.Expr<any>,
ctx: TypeContext,
checkFuncBody: boolean = true,
): a.Type<any> {
if (expr.type) {
return expr.type;
}
const ty = checkExprTypeWithoutCache(expr, ctx, checkFuncBody);
// do not cache the result for FuncExpr without body check
if (!(expr instanceof a.FuncExpr && !checkFuncBody)) {
expr.type = ty;
}
return ty;
}
function checkExprTypeWithoutCache(
expr: a.Expr<any>,
ctx: TypeContext,
checkFuncBody: boolean = true,
): a.Type<any> {
if (expr instanceof a.LitExpr) {
if (expr.value instanceof a.IntLit) {
return new a.IntType(expr.row, expr.column);
} else if (expr.value instanceof a.FloatLit) {
return new a.FloatType(expr.row, expr.column);
} else if (expr.value instanceof a.CharLit) {
return new a.CharType(expr.row, expr.column);
} else if (expr.value instanceof a.BoolLit) {
return new a.BoolType(expr.row, expr.column);
} else if (expr.value instanceof a.StrLit) {
return new a.StrType(expr.row, expr.column);
}
} else if (expr instanceof a.IdentExpr) {
const ty = ctx.getTypeOf(expr.value);
if (ty) {
return cloneType(ty, expr);
} else {
throw new TypeError(
{
row: expr.row,
column: expr.column,
name: expr.value.value,
},
undefined,
'undefined identifier',
'SemanticError',
);
}
} else if (expr instanceof a.TupleExpr) {
return new a.TupleType(
{
size: expr.value.size,
items: expr.value.items.map(item => checkExprType(item, ctx)),
},
expr.row,
expr.column,
);
} else if (expr instanceof a.ArrayExpr) {
if (expr.value.length === 0) {
return new a.ArrayType(a.AnyType.instance, expr.row, expr.column);
}
const ty = checkExprType(expr.value[0], ctx);
for (let i = 1; i < expr.value.length; i++) {
assertType(checkExprType(expr.value[i], ctx), ty);
}
return new a.ArrayType(ty, expr.row, expr.column);
} else if (expr instanceof a.FuncExpr) {
let param: a.Type<any>;
if (expr.value.params.size === 1) {
param = expr.value.params.items[0].type;
} else {
param = new a.TupleType(
{
size: expr.value.params.size,
items: expr.value.params.items.map(item => item.type),
},
expr.row,
expr.column,
);
}
if (checkFuncBody) {
const bodyType = checkBlockType(
expr.value.body,
ctx,
expr.value.params.items.map(({ name, type: ty }) => ({
ident: name,
type: ty,
})),
);
try {
assertType(bodyType, expr.value.returnType);
} catch {
let message = 'Function return type mismatch';
if (expr.value.returnType instanceof a.VoidType) {
message += ", ';' may be missing";
}
throw new TypeError(bodyType, expr.value.returnType, message);
}
}
return new a.FuncType(
{ param, return: expr.value.returnType },
expr.row,
expr.column,
);
} else if (expr instanceof a.CallExpr) {
const funcType = checkExprType(expr.value.func, ctx);
const argsType = checkExprType(expr.value.args, ctx);
if (!(funcType instanceof a.FuncType)) {
throw new TypeError(
funcType,
{ name: 'function' },
'non-callable target',
'SemanticError',
);
}
try {
assertType(argsType, funcType.value.param);
} catch {
throw new TypeError(
argsType,
funcType.value.param,
'Function parameter type mismatch',
);
}
return cloneType(funcType.value.return, expr);
} else if (expr instanceof a.IndexExpr) {
const targetType = checkExprType(expr.value.target, ctx);
if (targetType instanceof a.ArrayType) {
const indexType = checkExprType(expr.value.index, ctx);
if (indexType instanceof a.IntType) {
return cloneType(targetType.value, expr);
} else {
throw new TypeError(
indexType,
a.IntType.instance,
'Index type mismatch',
);
}
} else if (targetType instanceof a.StrType) {
const indexType = checkExprType(expr.value.index, ctx);
if (indexType instanceof a.IntType) {
return new a.CharType(expr.row, expr.column);
} else {
throw new TypeError(
indexType,
a.IntType.instance,
'Index type mismatch',
);
}
} else if (targetType instanceof a.TupleType) {
const index = expr.value.index;
if (index instanceof a.LitExpr && index.value instanceof a.IntLit) {
const lit = index.value;
if (lit.parsedValue < targetType.value.size) {
return cloneType(targetType.value.items[lit.parsedValue], expr);
} else {
throw new TypeError(
{ row: lit.row, column: lit.column, name: lit.value },
{ name: `int < ${targetType.value.size}` },
'Tuple index out of range',
);
}
} else {
throw new TypeError(
{ row: index.row, column: index.column, name: 'expr' },
undefined,
'Invalid tuple index: only int literal is allowed for tuple index',
);
}
} else {
throw new TypeError(
targetType,
{ name: 'array, str or tuple' },
'Indexable type mismatch',
);
}
} else if (expr instanceof a.CondExpr) {
assertType(
checkExprType(expr.value.if, ctx),
new a.BoolType(expr.row, expr.column),
);
const ifBlockType = checkBlockType(expr.value.then, ctx);
const elseBlockType = checkBlockType(expr.value.else, ctx);
try {
assertType(ifBlockType, elseBlockType);
} catch {
let message = "'else' block should have the same type as 'if' block";
if (ifBlockType instanceof a.VoidType) {
message += ", ';' may be missing";
}
throw new TypeError(elseBlockType, ifBlockType, message);
}
return ifBlockType;
} else if (expr instanceof a.LoopExpr) {
const condType = checkExprType(expr.value.while, ctx);
if (condType instanceof a.BoolType) {
ctx.enterLoop(expr);
checkBlockType(expr.value.body, ctx);
ctx.leaveLoop();
return a.VoidType.instance;
} else {
throw new TypeError(
condType,
undefined,
'Loop condition should be a boolean',
);
}
} else if (expr instanceof a.NewExpr) {
const lengthType = checkExprType(expr.value.length, ctx);
if (lengthType instanceof a.IntType) {
return new a.ArrayType(expr.value.type, expr.row, expr.column);
} else {
throw new TypeError(
lengthType,
a.IntType.instance,
'Length type mismatch',
);
}
} else if (expr instanceof a.UnaryExpr) {
const opTypes = expr.value.op.getOperandTypes();
const rightActualTy = checkExprType(expr.value.right, ctx);
for (const { right, ret } of opTypes) {
try {
assertType(rightActualTy, right);
return cloneType(ret, expr);
} catch {
// ignore, try the next
}
}
// fails for all the operand types
throw new TypeError(
rightActualTy,
{
name: orStr(opTypes.map(x => x.right.name)),
},
`Operand type mismatch for '${expr.value.op.value}'`,
);
} else if (expr instanceof a.BinaryExpr) {
const leftActualTy = checkExprType(expr.value.left, ctx);
const opTypes = expr.value.op.getOperandTypes(leftActualTy);
const rightActualTy = checkExprType(expr.value.right, ctx);
for (const { left, right, ret } of opTypes) {
try {
assertType(leftActualTy, left);
} catch {
// ignore, try the next
continue;
}
try {
assertType(rightActualTy, right);
return cloneType(ret, expr);
} catch {
throw new TypeError(
rightActualTy,
right,
`Right-hand operand type mismatch for '${expr.value.op.value}'`,
);
}
}
// fails for all the operand types
throw new TypeError(
leftActualTy,
{
name: orStr(opTypes.map(x => x.left.name)),
},
`Left-hand operand type mismatch for '${expr.value.op.value}'`,
);
}
throw new TypeError({
row: expr.row,
column: expr.column,
name: 'invalid type',
});
}
function registerDeclType(decl: a.Decl, ctx: TypeContext) {
if (!decl.value.type) {
// ensure type property
decl.value.type = checkExprType(decl.value.expr, ctx, false);
}
ctx.push({ ident: decl.value.name, type: decl.value.type });
}
function checkDeclType(decl: a.Decl, ctx: TypeContext) {
if (!decl.value.type) {
throw new TypeError(
decl,
undefined,
'Type of decl should be tagged before being checked',
);
}
if (containsVoidType(decl.value.type)) {
throw new TypeError(
{ name: decl.value.type.name, row: decl.row, column: decl.column },
undefined,
'A decl type cannot contain void',
'SemanticError',
);
}
assertType(checkExprType(decl.value.expr, ctx), decl.value.type);
}
function checkAssignType(assign: a.Assign, ctx: TypeContext) {
assertType(
checkExprType(assign.value.expr, ctx),
checkExprType(assign.value.lVal, ctx),
);
}
function checkBreakType(break_: a.Break, ctx: TypeContext) {
if (!ctx.currentLoop) {
throw new TypeError(
{ name: 'unexpected break', row: break_.row, column: break_.column },
undefined,
'break can be only used in a loop',
'SemanticError',
);
}
}
function containsVoidType(ty: a.Type<any>): boolean {
if (ty instanceof a.VoidType) {
return true;
} else if (ty instanceof a.TupleType) {
return ty.value.items.some(containsVoidType);
} else if (ty instanceof a.ArrayType) {
return containsVoidType(ty.value);
} else {
return false;
}
}
export function checkBlockType(
block: a.Block,
ctx: TypeContext,
initialDefs: Array<IdentTypeDef> = [],
): a.Type<any> {
ctx.enterScope();
initialDefs.forEach(def => ctx.push(def));
let exprType: a.Type<any> = new a.VoidType(block.row, block.column);
block.value.bodies.forEach(body => {
if (body instanceof a.Decl) {
registerDeclType(body, ctx);
checkDeclType(body, ctx);
} else if (body instanceof a.Expr) {
exprType = checkExprType(body, ctx);
} else if (body instanceof a.Assign) {
checkAssignType(body, ctx);
} else {
checkBreakType(body, ctx);
}
});
const ty: a.Type<any> = block.value.returnVoid
? new a.VoidType(block.row, block.column)
: exprType;
ctx.leaveScope();
return ty;
}
export function assertType(actual: a.Type<any>, expected: a.Type<any>) {
// if any of them is AnyType, it always succeeds
if (actual instanceof a.AnyType || expected instanceof a.AnyType) {
return;
}
// simple types
if (
(actual instanceof a.IntType && expected instanceof a.IntType) ||
(actual instanceof a.FloatType && expected instanceof a.FloatType) ||
(actual instanceof a.StrType && expected instanceof a.StrType) ||
(actual instanceof a.BoolType && expected instanceof a.BoolType) ||
(actual instanceof a.CharType && expected instanceof a.CharType) ||
(actual instanceof a.VoidType && expected instanceof a.VoidType)
) {
return;
}
// func type
if (actual instanceof a.FuncType && expected instanceof a.FuncType) {
try {
assertType(actual.value.param, expected.value.param);
assertType(actual.value.return, expected.value.return);
} catch {
throw new TypeError(actual, expected);
}
return;
}
// tuple type
if (actual instanceof a.TupleType && expected instanceof a.TupleType) {
if (expected.value.size !== actual.value.size) {
throw new TypeError(actual, expected, 'Tuple length mismatch');
}
for (let i = 0; i < expected.value.size; i++) {
try {
assertType(actual.value.items[i], expected.value.items[i]);
} catch {
throw new TypeError(actual, expected);
}
}
return;
}
// array type
if (actual instanceof a.ArrayType && expected instanceof a.ArrayType) {
try {
assertType(actual.value, expected.value);
} catch {
throw new TypeError(actual, expected);
}
return;
}
throw new TypeError(actual, expected);
} | the_stack |
import * as assert from "assert";
import * as llvm from "llvm-node";
import * as ts from "typescript";
import {CodeGenerationDiagnostics} from "../../code-generation-diagnostic";
import {CompilationContext} from "../../compilation-context";
import {CodeGenerationContext} from "../code-generation-context";
import {invoke} from "../util/functions";
import {llvmArrayValue} from "../util/llvm-array-helpers";
import {getArrayElementType, getCallSignature, isFunctionType} from "../util/types";
import {TypePlace} from "../util/typescript-to-llvm-type-converter";
import {FunctionPointer, FunctionReference} from "./function-reference";
import {ObjectReference} from "./object-reference";
import {createResolvedFunctionFromSignature, ResolvedFunction, ResolvedFunctionParameter} from "./resolved-function";
import {Undefined} from "./undefined";
import {AssignableValue, Value} from "./value";
/**
* Base class for function references. Handles the coercion of the argument values to the expected types of the function parametes
* and as well as handling var arg parameters correctly.
*/
export abstract class AbstractFunctionReference implements FunctionReference {
/**
* Creates a new instance
* @param classType the type of the class to which this function belongs (static or instance method) or absent, if it is
* a stand alone function.
*/
constructor(protected classType?: ts.ObjectType) {}
/**
* Returns the default resolved function in case this function reference is dereferenced (e.g. assigned to a variable).
* @throws in case this function is overloaded and therefore, cannot be dereferenced
*/
protected abstract getResolvedFunction(callerContext: CodeGenerationContext): ResolvedFunction;
/**
* Returns the llvm function for the given resolved function and passed arguments
* @param resolvedFunction the resolved function
* @param context the context
* @param passedArguments the arguments passed
*/
protected abstract getLLVMFunction(resolvedFunction: ResolvedFunction, context: CodeGenerationContext, passedArguments?: llvm.Value[]): FunctionPointer;
invoke(callExpression: ts.CallExpression | ts.NewExpression, callerContext: CodeGenerationContext): void | Value {
const resolvedSignature = callerContext.typeChecker.getResolvedSignature(callExpression);
const resolvedFunction = this.getResolvedFunctionFromSignature(resolvedSignature, callerContext.compilationContext);
const passedArguments = toLlvmArgumentValues(callExpression.arguments || [] as ts.Expression[], resolvedFunction, callerContext);
return this.invokeResolvedFunction(resolvedFunction, passedArguments, callerContext);
}
invokeWith(args: llvm.Value[], callerContext: CodeGenerationContext): void | Value {
return this.invokeResolvedFunction(this.getResolvedFunction(callerContext), args, callerContext);
}
protected getResolvedFunctionFromSignature(signature: ts.Signature, compilationContext: CompilationContext): ResolvedFunction {
return createResolvedFunctionFromSignature(signature, compilationContext, this.classType);
}
private invokeResolvedFunction(resolvedFunction: ResolvedFunction, args: llvm.Value[], callerContext: CodeGenerationContext) {
const llvmFunction = this.getLLVMFunction(resolvedFunction, callerContext, args);
assert(llvmFunction.type.isPointerTy() && (llvmFunction.type as llvm.PointerType).elementType.isFunctionTy(), "Expected pointer to a function type");
const callArguments = this.getCallArguments(resolvedFunction, args, callerContext);
let name: string | undefined;
if (!(resolvedFunction.returnType.flags & ts.TypeFlags.Void)) {
name = resolvedFunction.functionName ? `${resolvedFunction.functionName}ReturnValue` : undefined;
}
const returnType = callerContext.toLLVMType(resolvedFunction.returnType, TypePlace.RETURN_VALUE);
let dereferenceableSize: number | undefined;
if (resolvedFunction.returnType.flags & ts.TypeFlags.Object) {
const classReference = callerContext.resolveClass(resolvedFunction.returnType)!;
dereferenceableSize = classReference.getTypeStoreSize(resolvedFunction.returnType as ts.ObjectType, callerContext);
}
const returnValue = invoke(llvmFunction, callArguments, returnType, callerContext, { name, dereferenceableSize });
if (resolvedFunction.returnType.flags & ts.TypeFlags.Void) {
return Undefined.create(callerContext);
}
return callerContext.value(returnValue, resolvedFunction.returnType);
}
/**
* Gets the call arguments for invoking the specified function
* @param resolvedFunction the specific signature of the function to call
* @param passedArguments the parameters passed in the invoke statement
* @param callerContext the callers code generation context
* @return the values that are to be passed to the llvm function
*/
protected getCallArguments(resolvedFunction: ResolvedFunction, passedArguments: llvm.Value[], callerContext: CodeGenerationContext): llvm.Value[] {
const result: llvm.Value[] = [];
for (let i = 0; i < resolvedFunction.parameters.length; ++i) {
const parameter = resolvedFunction.parameters[i];
let arg: llvm.Value | undefined;
if (passedArguments.length > i) {
arg = passedArguments[i];
} else if (parameter.initializer) {
arg = callerContext.generateValue(parameter.initializer).generateIR(callerContext);
} else if (parameter.optional) {
break;
} else if (!parameter.variadic) {
assert(false, `Missing value for not optional parameter ${parameter.name}`);
break;
}
if (parameter.variadic) {
const arrayType = (parameter.type as ts.GenericType);
const elementType = getArrayElementType(arrayType);
const elementLLVMType = callerContext.toLLVMType(elementType, TypePlace.PARAMETER);
const elements = llvmArrayValue(passedArguments.slice(i), elementLLVMType, callerContext, parameter.name);
result.push(
elements,
llvm.ConstantInt.get(callerContext.llvmContext, passedArguments.length - i, undefined, false)
);
break;
} else {
result.push(arg!);
}
}
return result;
}
isAssignable(): this is AssignableValue {
return false;
}
isObject(): this is ObjectReference {
return false;
}
dereference(): this {
return this;
}
generateIR(context: CodeGenerationContext): llvm.Value {
return this.getLLVMFunction(this.getResolvedFunction(context), context);
}
castImplicit(type: ts.Type, context: CodeGenerationContext): Value | undefined {
assert(isFunctionType(type), "Target type needs to be a function type");
const signature = getCallSignature(type);
const resolvedFunction = this.getResolvedFunction(context);
const parameters = signature.getParameters();
const declaredParameters = signature.getDeclaration().parameters;
const parameterTypes = resolvedFunction.parameters.map((p, i) => context.typeChecker.getTypeOfSymbolAtLocation(parameters[i], declaredParameters[i]));
const returnTypeEqual = signature.getReturnType() === resolvedFunction.returnType;
const parameterTypesEqual = resolvedFunction.parameters.length === parameterTypes.length &&
resolvedFunction.parameters.every((parameter, i) => parameter.type === parameterTypes[i]);
if (returnTypeEqual && parameterTypesEqual) {
return this; // no cast needed
}
// casting functions is not yet supported
return undefined;
}
}
function toLlvmArgumentValues(args: ts.Expression[], resolvedFunction: ResolvedFunction, callerContext: CodeGenerationContext) {
const values: llvm.Value[] = [];
for (let i = 0; i < Math.min(args.length, resolvedFunction.parameters.length); ++i) {
const parameter = resolvedFunction.parameters[i];
if (parameter.variadic) {
const llvmVarArgs = toLlvmVariadicArgument(args.slice(i), parameter, callerContext);
values.push(...llvmVarArgs);
} else {
const argumentValue = toLlvmArgumentValue(args[i], parameter, callerContext);
values.push(argumentValue);
}
}
return values;
}
function toLlvmVariadicArgument(varArgs: ts.Expression[], parameter: ResolvedFunctionParameter, callerContext: CodeGenerationContext) {
const elementType = getArrayElementType(parameter.type);
const llvmVarArgs = new Array<llvm.Value>(varArgs.length);
for (let j = 0; j < varArgs.length; ++j) {
const varArgNode = varArgs[j];
const castedElement = callerContext.generateValue(varArgNode).castImplicit(elementType, callerContext);
if (!castedElement) {
throw CodeGenerationDiagnostics.unsupportedImplicitCastOfArgument(
varArgNode,
callerContext.typeChecker.typeToString(elementType),
callerContext.typeChecker.typeToString(callerContext.typeChecker.getTypeAtLocation(varArgNode))
);
}
llvmVarArgs[j] = castedElement.generateIR(callerContext);
}
return llvmVarArgs;
}
function toLlvmArgumentValue(arg: ts.Expression, parameter: ResolvedFunctionParameter, callerContext: CodeGenerationContext) {
const castedElement = callerContext.generateValue(arg).castImplicit(parameter.type, callerContext);
const argumentType = callerContext.typeChecker.getTypeAtLocation(arg);
if (!castedElement) {
throw CodeGenerationDiagnostics.unsupportedImplicitCastOfArgument(
arg,
callerContext.typeChecker.typeToString(parameter.type),
callerContext.typeChecker.typeToString(argumentType)
);
}
return castedElement.generateIR(callerContext);
} | the_stack |
export const setupPrestoMode = (ace) => {
ace.define("ace/mode/presto_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text_highlight_rules"], function (require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var SqlHighlightRules = function () {
var keywords = (
"select|insert|update|delete|from|where|and|or|group|by|order|limit|offset|having|as|case|" +
"when|else|end|type|left|right|join|on|outer|desc|asc|union|create|table|primary|key|if|" +
"foreign|not|references|default|null|inner|cross|natural|database|drop|grant"
);
var prestoKeywords = (
"|ALL|ALL PRIVILEGES|ALTER TABLE|ADD COLUMN|RENAME COLUMN TO|RENAME TO|AS|ASC|CALL|COMMIT|CREATE|CREATE TABLE" +
"|CROSS JOIN|CUBE|DATA|DELETE FROM|DESC|DESCRIBE|DISTINCT|DISTRIBUTED|DROP TABLE|DROP VIEW|EXPLAIN" +
"|EXPLAIN ANALYZE|FORMAT|FROM|FULL|GRANT|GRANT OPTION FOR|GRAPHVIZ|GROUP BY|GROUPING SETS|HAVING|IF EXISTS" +
"|IF NOT EXISTS|INNER|INSERT INTO|ISOLATION LEVEL|JOIN|LEFT|LIKE|LIMIT|LOGICAL|NO|ON|ONLY|OR REPLACE|ORDER BY" +
"|OUTER|PUBLIC|READ|READ COMMITTED|READ UNCOMMITTED|REPEATABLE READ|RESET SESSION|REVOKE|RIGHT|ROLLBACK|ROLLUP" +
"|SELECT|SERIALIZABLE|SET SESSION|SHOW CATALOGS|SHOW COLUMNS FROM|SHOW CREATE TABLE|SHOW CREATE VIEW" +
"|SHOW FUNCTIONS|SHOW PARTITIONS FROM|SHOW SCHEMAS|SHOW SESSION|SHOW TABLES|START TRANSACTION|TABLE" +
"|TEXT|TO|TYPE|UNION|USE|USING|VALUES|VIEW AS|WHERE|WITH|WITH GRANT OPTION|WORK|WRITE"
);
var builtinConstants = (
"true|false"
);
var builtinFunctions = (
"avg|count|first|last|max|min|sum|ucase|lcase|mid|len|round|rank|now|format|" +
"coalesce|ifnull|isnull|nvl"
);
var prestoFunctions = (
"|abs|acos|approx_distinct|approx_percentile|arbitrary|array_agg|array_distinct|array_intersect|array_join|" +
"array_max|array_min|array_position|array_remove|array_sort|asin|atan|atan2|avg|bar|bit_count|bitwise_and|" +
"bitwise_not|bitwise_or|bitwise_xor|bool_and|bool_or|cardinality|cardinality|cast|cbrt|ceil|ceiling|" +
"char2hexint|checksum|chr|color|concat|concat|contains|corr|cos|cosh|cosine_similarity|count|count_if|" +
"covar_pop|covar_samp|cume_dist|current_timezone|date_add|date_diff|date_format|date_parse|date_trunc|day|" +
"day_of_month|day_of_week|day_of_year|degrees|dense_rank|dow|doy|e|element_at|element_at|every|exp|extract|" +
"first_value|flatten|floor|format_datetime|from_base|from_base64|from_base64url|from_hex|from_iso8601_date|" +
"from_iso8601_timestamp|from_unixtime|from_utf8|geometric_mean|greatest|histogram|hour|index|infinity|is_finite|" +
"is_infinite|is_nan|json_array_contains|json_array_get|json_array_length|json_extract|json_extract_scalar|" +
"json_format|json_parse|json_size|lag|last_value|lead|least|length|length|ln|log|log10|log2|lower|lpad|ltrim|" +
"map|map_agg|map_concat|map_keys|map_union|map_values|max|max_by|md5|min|min_by|minute|mod|month|multimap_agg|" +
"nan|normalize|now|nth_value|ntile|numeric_histogram|parse_datetime|percent_rank|pi|position|pow|power|quarter|" +
"radians|rand|random|rank|regexp_extract|regexp_extract_all|regexp_like|regexp_replace|regexp_split|" +
"regr_intercept|regr_slope|render|replace|reverse|rgb|round|row_number|rpad|rtrim|second|sequence|" +
"sha1|sha256|sha512|sign|sin|slice|split|split_part|split_to_map|sqrt|stddev|stddev_pop|stddev_samp|strpos|" +
"substr|substring|sum|tan|tanh|timezone_hour|timezone_minute|to_base|to_base64|to_base64url|to_char|to_date|" +
"to_hex|to_iso8601|to_timestamp|to_unixtime|to_utf8|trim|truncate|try_cast|upper|url_decode|url_encode|" +
"url_extract_fragment|url_extract_host|url_extract_parameter|url_extract_path|url_extract_port|" +
"url_extract_protocol|url_extract_query|var_pop|var_samp|variance|week|week_of_year|width_bucket|" +
"year|year_of_week|yow|zip"
);
var dataTypes = (
"int|numeric|decimal|date|varchar|char|bigint|float|double|bit|binary|text|set|timestamp|" +
"money|real|number|integer"
);
var prestoDataTypes = "|varbinary|json|time|interval|array|map";
var keywordMapper = this.createKeywordMapper({
"support.function": builtinFunctions + prestoFunctions,
"keyword": keywords + prestoKeywords,
"constant.language": builtinConstants,
"storage.type": dataTypes + prestoDataTypes
}, "identifier", true);
this.$rules = {
"start": [{
token: "comment",
regex: "--.*$"
}, {
token: "comment",
start: "/\\*",
end: "\\*/"
}, {
token: "string", // " string
start: '"',
end: '"'
}, {
token: "string", // ' string
start: "'",
end: "'"
}, {
token: "constant.numeric", // float
regex: "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
}, {
token: keywordMapper,
regex: "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
}, {
token: "keyword.operator",
regex: "\\+|\\-|\\/|\\/\\/|%|<@>|@>|<@|&|\\^|~|<|>|<=|=>|==|!=|<>|="
}, {
token: "paren.lparen",
regex: "[\\(]"
}, {
token: "paren.rparen",
regex: "[\\)]"
}, {
token: "text",
regex: "\\s+"
}, {
token: "custom-keyword--reference",
regex: "@[^\\s@]+"
}]
};
this.normalizeRules();
};
oop.inherits(SqlHighlightRules, TextHighlightRules);
exports.SqlHighlightRules = SqlHighlightRules;
});
ace.define("ace/mode/folding/presto", ["require", "exports", "module", "ace/lib/oop", "ace/mode/folding/fold_mode", "ace/range"],
function (require, exports, module) {
"use strict";
// function escapeRegExp(str) {
// return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
// }
var oop = require("../../lib/oop");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;
var TokenIterator = require("../../token_iterator").TokenIterator;
var FoldMode = exports.FoldMode = function () {};
oop.inherits(FoldMode, BaseFoldMode);
(function () {
this.foldingStartMarker = /(\()[^)]*$|^\s*(\/\*)/;
this.foldingStopMarker = /^[^(]*(\))|^.*(\*\/)/;
this.singleLineBlockCommentRe = /^.*(\/\*).*\*\/.*$/;
this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/;
this.startRegionRe = /^\s*--#?region\b/;
this.sqlCommentRe = /^--.*/;
this._getFoldWidgetBase = this.getFoldWidget;
this.getFoldWidget = function (session, foldStyle, row) {
var line = session.getLine(row);
// if (this.sqlCommentRe.test(line)) {
// return this.sqlCommentFoldWidget(session, foldStyle, row);
// }
if (this.singleLineBlockCommentRe.test(line)) {
if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line))
return "";
}
var fw = this._getFoldWidgetBase(session, foldStyle, row);
if (!fw && this.startRegionRe.test(line))
return "start"; // lineCommentRegionStart
if (!fw && this.isStartIndentationBlock(session, line, row)) {
return "start";
}
return fw;
};
this.getFoldWidgetRange = function (session, foldStyle, row, forceMultiline) {
var line = session.getLine(row);
if (this.startRegionRe.test(line))
return this.getCommentRegionBlock(session, line, row);
// if (this.sqlCommentRe.test(line)) {
// var type = this.sqlCommentFoldWidget(session, foldStyle, row);
// if (type === "start") {
// return this.getCommentFoldRange(session, row, 0, 1);
// } else if (type === "end") {
// return this.getCommentFoldRange(session, row, line.length - 1, -1);
// } else {
// return;
// }
// }
var match = line.match(this.foldingStartMarker);
if (match) {
var i = match.index;
if (match[1])
return this.openingBracketBlock(session, match[1], row, i);
var range = this.getCommentFoldRange(session, row, i + match[0].length, 1);
if (range && !range.isMultiLine()) {
if (forceMultiline) {
range = this.getSectionRange(session, row);
} else if (foldStyle != "all")
range = null;
}
return range;
}
if (foldStyle === "markbegin")
return;
var match = line.match(this.foldingStopMarker);
if (match) {
var i = match.index + match[0].length;
if (match[1])
return this.closingBracketBlock(session, match[1], row, i);
return this.getCommentFoldRange(session, row, i, -1);
}
if (this.isStartIndentationBlock(session, line, row)) {
return this.indentationBlock(session, row);
}
};
this.isStartIndentationBlock = function (session, line, row) {
if (session.getLength() - 1 === row) {
return;
}
var re = /\S/;
var nextLineRow = row + 1;
var firstCharPosNextLine;
var firstCharPos = line.search(re);
if (firstCharPos !== -1) {
do {
firstCharPosNextLine = session.getLine(nextLineRow).search(re);
} while (firstCharPosNextLine === -1 && session.getLength() > ++nextLineRow);
if (firstCharPosNextLine !== -1 && firstCharPos < firstCharPosNextLine) {
return 'start';
}
}
};
// this.sqlCommentFoldWidget = function (session, foldStyle, row) {
// var nextLine = session.getLine(row + 1);
// var prevLine = session.getLine(row - 1);
// var nextLineIsComment = this.sqlCommentRe.test(nextLine);
// var prevLineIsComment = this.sqlCommentRe.test(prevLine);
// if (nextLineIsComment && !prevLineIsComment) {
// return 'start';
// } else if (foldStyle === 'markbeginend' && !nextLineIsComment && prevLineIsComment) {
// return 'end';
// } else {
// return '';
// }
// };
this.getCommentFoldRange = function (session, row, column, dir) {
var iterator = new TokenIterator(session, row, column);
var token = iterator.getCurrentToken();
if (token && /^comment|string/.test(token.type)) {
var range = new Range();
var re = new RegExp(token.type.replace(/\..*/, ""));
if (dir != 1) {
do {
token = iterator.stepBackward();
} while (token && re.test(token.type));
iterator.stepForward();
}
range.start.row = iterator.getCurrentTokenRow();
// range.start.row = iterator.getCurrentTokenRow() + 1;
// range.start.column = iterator.getCurrentTokenColumn() + 2;
range.start.column = session.getLine(iterator.getCurrentTokenRow()).length;
iterator = new TokenIterator(session, row, column);
if (dir != -1) {
do {
token = iterator.stepForward();
} while (token && re.test(token.type));
token = iterator.stepBackward();
} else
token = iterator.getCurrentToken();
range.end.row = iterator.getCurrentTokenRow();
range.end.column = iterator.getCurrentTokenColumn() + token.value.length - 2;
return range;
}
};
this.getSectionRange = function (session, row) {
var line = session.getLine(row);
var startIndent = line.search(/\S/);
var startRow = row;
var startColumn = line.length;
row = row + 1;
var endRow = row;
var maxRow = session.getLength();
while (++row < maxRow) {
line = session.getLine(row);
var indent = line.search(/\S/);
if (indent === -1)
continue;
if (startIndent > indent)
break;
var subRange = this.getFoldWidgetRange(session, "all", row);
if (subRange) {
if (subRange.start.row <= startRow) {
break;
} else if (subRange.isMultiLine()) {
row = subRange.end.row;
} else if (startIndent == indent) {
break;
}
}
endRow = row;
}
return new Range(startRow, startColumn, endRow, session.getLine(endRow).length);
};
this.getCommentRegionBlock = function (session, line, row) {
var startColumn = line.search(/\s*$/);
var maxRow = session.getLength();
var startRow = row;
var re = /^\s*--#?(end)?region\b/;
var depth = 1;
while (++row < maxRow) {
line = session.getLine(row);
var m = re.exec(line);
if (!m) continue;
if (m[1]) depth--;
else depth++;
if (!depth) break;
}
var endRow = row;
if (endRow > startRow) {
return new Range(startRow, startColumn, endRow, line.length);
}
};
}).call(FoldMode.prototype);
});
ace.define("ace/mode/presto", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text", "ace/mode/presto_highlight_rules", "ace/range"], function (require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var SqlHighlightRules = require("./presto_highlight_rules").SqlHighlightRules;
// var Range = require("../range").Range;
var SqlFoldMode = require("./folding/presto").FoldMode;
var Mode = function () {
this.HighlightRules = SqlHighlightRules;
this.foldingRules = new SqlFoldMode();
};
oop.inherits(Mode, TextMode);
(function () {
this.lineCommentStart = "--";
this.$id = "ace/mode/presto";
// syntax validation worker
// var WorkerClient = require("ace/worker/worker_client").WorkerClient;
// this.createWorker = function(session) {
// var document = session.getDocument();
// this.$worker = new WorkerClient(["ace"], "ace/worker/sql-worker", "SqlWorker", "3rd-party/ace/modes/sql-worker.js");
// this.$worker.attachToDocument(document);
// this.$worker.on('annotate', function(e) {
// session.setAnnotations(e.data);
// });
// this.$worker.on('terminate', function() {
// session.clearAnnotations();
// });
// return this.$worker;
// };
}).call(Mode.prototype);
exports.Mode = Mode;
});
} | the_stack |
import {
DiagramPluginSettings,
SettingsTheme,
} from "src/DiagramPluginSettings";
export type DrawioUiThemes = "kennedy" | "min" | "atlas" | "dark" | "sketch";
export type DrawioUrlParamsFlag = "0" | "1";
/**
* UrlParams configuration read by drawio
* See: https://www.diagrams.net/doc/faq/supported-url-parameters
* See: https://www.diagrams.net/doc/faq/embed-mode
*/
export interface DrawioUrlParams {
/**
* Runs diagrams.net in embed mode. Use this mode with embed.diagrams.net only.
*/
embed?: "1";
/**
* Uses JSON for message passing in embed and client mode.
*/
proto?: "json";
/**
* Sends the configure event and waits for the configure action.
*/
configure?: DrawioUrlParamsFlag;
/**
* Uses the Minimal, Atlas, Dark or Sketch UI theme (default is Kennedy).
* Note sketch=1 must also be set for the Sketch UI theme
*/
ui?: DrawioUiThemes;
/**
* Disables/enables dark mode in sketch and minimal theme.
*/
dark?: DrawioUrlParamsFlag;
/**
* Disables/enables sketch style (default is 1 for sketch theme and 0 for all other themes).
*/
rough?: DrawioUrlParamsFlag;
/**
* Undocumented but seems to enable the Sketch UI theme
*/
sketch?: DrawioUrlParamsFlag;
/**
* Displays an additional Save and Exit button. Instead of using this URL parameter, you can specify this setting in the load message. If noSaveBtn=1 is used, this can be disabled with saveAndExit=0
*/
saveAndExit?: "0";
/**
* Displays a Save and Exit button instead of a Save button.
* Instead of using this URL parameter, you can specify this setting in the load message. If this is used, then the saveAndExit URL parameter is ignored.
*/
noSaveBtn?: "1";
/**
* Hides the Exit button. Instead of using this URL parameter, you can specify this setting in the load message.
* Note: To hide all buttons in embed mode, use saveAndExit=0&noSaveBtn=1&noExitBtn=1
*/
noExitBtn?: "1";
/**
* Undocumented. Hides the file menu.
*/
noFileMenu?: "1";
/**
* Disables all features that require external web services (such as PDF export).
*/
stealth?: "1";
/**
* Undocumented. Hides page controls.
*/
pages?: "0";
/**
* Sets the default pageVisible to false.
*/
pv?: "0";
}
export interface DrawioResource {
main: string;
}
export interface DrawioLibrarySection {
title: DrawioResource;
entries: {
id: string;
preview?: string;
title: DrawioResource;
desc?: DrawioResource;
libs: ({
title: DrawioResource;
tags?: string;
} & ({ data: unknown } | { url: string }))[];
}[];
}
export interface ColorScheme {
fill?: string;
stroke?: string;
gradient?: string;
}
interface DrawioCellStyle {
fontColor?: string;
fillColor?: string;
strokeColor?: string;
gradientColor?: string;
}
interface DrawioGraphStyle {
background?: string;
gridColor?: string;
}
interface DrawioStyles {
commonStyle?: DrawioCellStyle;
vertexStyle?: DrawioCellStyle;
edgeStyle?: DrawioCellStyle;
graph?: DrawioGraphStyle;
}
/**
* Configuration read by Drawio
*/
export interface DrawioConfig {
/**
* An array of font family names in the format panel font drop-down list.
*/
defaultFonts?: Array<string>;
/**
* An array of font family names to be added before defaultFonts (9.2.4 and later).
* Note: Fonts must be installed on the server and all client devices, or be added using the fontCss option. (6.5.4 and later).
*/
customFonts?: Array<string>;
/**
* Colour codes for the upper palette in the colour dialog (no leading # for the colour codes).
*/
presetColors?: Array<string>;
/**
* Colour codes to be added before presetColors (no leading # for the colour codes) (9.2.5 and later).
*/
customPresetColors?: Array<string>;
/**
* Available colour schemes in the style section at the top of the format panel (use leading # for the colour codes).
* Possible colour keys are fill, stroke, gradient and font (font is ignored for connectors).
*/
defaultColorSchemes?: Array<string>;
/**
* Colour schemes to be added before defaultColorSchemes (9.2.4 and later).
*/
customColorSchemes?: Array<Array<ColorScheme>>;
/**
* Defines the initial default styles for vertices and edges (connectors).
* Note that the styles defined here are copied to the styles of new cells, for each cell.
* This means that these values override everything else that is inherited from other styles or themes
* (which may be supported at a later time).
* Therefore, it is recommended to use a minimal set of values for the default styles.
* To find the key/value pairs to be used, set the style in the application and find the key and value via Edit Style (Ctrl+E) (6.5.2 and later).
* For example, to assign a default fontFamily of Courier New to all edges and vertices (and override all other default styles),
* use
* ```json
* {
* "defaultVertexStyle": {"fontFamily": "Courier New"},
* "defaultEdgeStyle": {"fontFamily": "Courier New"}
* }
* ```
* (6.5.2 and later).
*/
defaultVertexStyle?: Record<string, string>;
/**
* See `defaultVertexStyle`.
*/
defaultEdgeStyle?: Record<string, string>;
/**
* Defines a string with CSS rules to be used to configure the diagrams.net user interface.
* For example, to change the background colour of the menu bar, use the following:
* ```css
* .geMenubarContainer { background-color: #c0c0c0 !important; }
* .geMenubar { background-color: #c0c0c0 !important; }
* ```
* (6.5.2 and later).
*/
css?: string;
/**
* Defines a string with CSS rules for web fonts to be used in diagrams.
*/
fontCss?: string;
/**
* Defines a semicolon-separated list of library keys (unique names)
* in a string to be initially displayed in the left panel (e.g. "general;uml;company-graphics").
* Possible keys include custom entry IDs from the libraries field,
* or keys for the libs URL parameter (6.5.2 and later).
* The default value is `"general;uml;er;bpmn;flowchart;basic;arrows2"`.
*/
defaultLibraries?: string;
/**
* Defines an array of objects that list additional libraries and sections
* in the left panel and the More Shapes dialog.
*/
libraries?: Array<DrawioLibrarySection>;
/**
* Defines the XML for blank diagrams and libraries (6.5.4 and later).
*/
emptyDiagramXml?: string;
/**
* Specifies if the XML output should be compressed. The default is true.
*/
compressXml?: boolean;
/**
* Defines an array of objects that contain the colours (fontColor, fillColor,
* strokeColor and gradientColor) for the Style tab of the format panel if the
* selection is empty. These objects can have a commonStyle (which is applied to
* both vertices and edges), vertexStyle (applied to vertices) and edgeStyle
* (applied to edges), and a graph with background and gridColor. An empty object
* will apply the default colors.
*/
styles?: Array<{} | DrawioStyles>;
}
const defaultConfiguration: DrawioConfig = {
defaultLibraries: "general",
libraries: [],
// defaultEdgeStyle: {
// // strokeColor: "currentColor",
// },
// defaultVertexStyle: {
// // fillColor: "#ffffff",
// // strokeColor: "currentColor",
// },
// styles: [
// {},
// {
// commonStyle: {
// fillColor: "#ffffff",
// strokeColor: "#000000",
// },
// },
// ],
};
const defaultUrlParams: DrawioUrlParams = {
embed: "1",
configure: "0",
noExitBtn: "1",
noSaveBtn: "1",
noFileMenu: "1",
pages: "0",
proto: "json",
pv: "0",
saveAndExit: "0",
stealth: "1",
ui: "sketch",
dark: "0",
rough: "1",
sketch: "1",
};
export class ConfigurationManager {
private drawioConfig: any;
private urlParams: any;
constructor(win: Window) {
this.urlParams = {};
this.drawioConfig = {};
this.defineUrlParams(win);
this.defineDrawioConfig(win);
this.setDrawioConfig(defaultConfiguration);
this.setUrlParams(defaultUrlParams);
}
private defineUrlParams(win: Window) {
const urlParamsProxy = new Proxy(this.urlParams, {
get(target, propertyKey, receiver) {
const value = Reflect.get(target, propertyKey, receiver);
// NOTE: This is a really helpful place to debug values that drawio is reading
return value;
},
set() {
return true;
},
});
Object.defineProperty(win, "urlParams", {
value: urlParamsProxy,
});
}
private defineDrawioConfig(win: Window) {
const drawioConfigProxy = new Proxy(this.drawioConfig, {
get(target, propertyKey, receiver) {
const value = Reflect.get(target, propertyKey, receiver);
// NOTE: This is a really helpful place to debug values that drawio is reading
return value;
},
set() {
return true;
},
});
Object.defineProperty(win, "DRAWIO_CONFIG", {
value: drawioConfigProxy,
});
Object.defineProperty(win, "mxLoadSettings", {
value: false,
});
}
public setConfig(settings: DiagramPluginSettings) {
// Apply configuration from settings
const config = this.getDrawioConfig(settings);
this.setDrawioConfig(config);
// Apply UrlParams from settings
const urlParams: DrawioUrlParams = {
ui: this.getUiTheme(settings),
dark: this.getDarkFromTheme(settings),
rough: this.getRough(settings),
sketch: this.getSketch(settings),
};
this.setUrlParams(urlParams);
}
private setDrawioConfig(drawioConfig: DrawioConfig) {
Object.assign(this.drawioConfig, drawioConfig);
}
private setUrlParams(urlParams: DrawioUrlParams) {
Object.assign(this.urlParams, urlParams);
}
private getUiTheme(settings: DiagramPluginSettings): DrawioUiThemes {
const theme = settings.theme;
if (theme.layout === "full") {
if (theme.dark) {
return "dark";
}
return "kennedy";
} else if (theme.layout === "compact") {
return "min";
}
return "sketch";
}
private getDarkFromTheme(
settings: DiagramPluginSettings
): DrawioUrlParamsFlag {
const dark = settings.theme.dark;
if (dark) {
return "1";
}
return "0";
}
private getRough(settings: DiagramPluginSettings): DrawioUrlParamsFlag {
return settings.drawing.sketch ? "1" : "0";
}
private getSketch(settings: DiagramPluginSettings): DrawioUrlParamsFlag {
return settings.theme.layout === SettingsTheme.sketch ? "1" : "0";
}
private getDrawioConfig(settings: DiagramPluginSettings): DrawioConfig {
return {
defaultLibraries: "general",
libraries: [],
defaultEdgeStyle: this.getDefaultEdgeStyle(settings),
defaultVertexStyle: this.getDefaultVertexStyle(settings),
styles: [
{},
// {
// commonStyle: {
// fillColor: "#ffffff",
// strokeColor: "currentColor",
// },
// },
],
};
}
private getDefaultVertexStyle(
settings: DiagramPluginSettings
): Record<string, string> {
const defaultVertexStyle = {
// fillColor: "#ffffff",
// strokeColor: "currentColor",
};
// if (settings.drawing.sketch) {
// Object.assign(defaultVertexStyle, {
// fillColor: "none",
// hachureGap: "4",
// fontFamily: "Architects Daughter",
// fontSource:
// "https%3A%2F%2Ffonts.googleapis.com%2Fcss%3Ffamily%3DArchitects%2BDaughter",
// sketch: "1",
// });
// }
return defaultVertexStyle;
}
private getDefaultEdgeStyle(
settings: DiagramPluginSettings
): Record<string, string> {
const defaultEdgeStyle = {
// edgeStyle: "none",
// strokeColor: "currentColor",
};
// if (settings.drawing.sketch) {
// Object.assign(defaultEdgeStyle, {
// hachureGap: "4",
// fontFamily: "Architects Daughter",
// fontSource:
// "https%3A%2F%2Ffonts.googleapis.com%2Fcss%3Ffamily%3DArchitects%2BDaughter",
// sourcePerimeterSpacing: "8",
// targetPerimeterSpacing: "8",
// endSize: "12",
// startSize: "12",
// endArrow: "open",
// sketch: "1",
// });
// } else {
// Object.assign(defaultEdgeStyle, {
// endArrow: "block",
// sketch: "0",
// });
// }
return defaultEdgeStyle;
}
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.