text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import coBody from 'co-body';
import type Koa from 'koa';
/**
* Options for fakeGitHubMiddleware.
*/
export interface FakeGitHubMiddlewareOptions {
/**
* GitHub OAuth App client ID.
*
* In reality, this is generated when a GitHub OAuth App is first created. For
* this fake, it can be any string.
*/
clientId: string;
/**
* GitHub OAuth app secret.
*
* In reality, this is generated from the GitHub OAuth App settings screen.
* For this fake, it can be any string.
*/
clientSecret: string;
/**
* URL to redirect to after app authentication or installation.
*
* In reality, this is configured in the GitHub OAuth App settings screen. For
* this fake, it can be any URL.
*/
redirectUrl: string;
}
/**
* Koa middleware that simulates various GitHub APIs and authentication screens
* used by the lit.dev Playground.
*/
export const fakeGitHubMiddleware = (
options: FakeGitHubMiddlewareOptions
): Koa.Middleware => {
let fake = new FakeGitHub(options);
let failNextRequest = false;
return async (ctx, next) => {
ctx.set('Access-Control-Allow-Origin', '*');
if (ctx.method === 'OPTIONS') {
// CORS preflight
ctx.status = 204;
ctx.set('Access-Control-Allow-Headers', 'Authorization');
ctx.set('Access-Control-Allow-Methods', 'GET, POST, PATCH');
return;
} else if (ctx.path === '/favicon.ico') {
// Don't count this automatic request when failing intentionally.
return next();
} else if (ctx.path === '/fail-next-request') {
failNextRequest = true;
ctx.status = 200;
ctx.body = 'Next request will fail';
return;
} else if (failNextRequest) {
ctx.status = 500;
ctx.body = 'Failed intentionally';
failNextRequest = false;
return;
} else if (ctx.path === '/reset') {
failNextRequest = false;
return fake.reset(ctx);
} else if (ctx.path === '/login/oauth/authorize') {
return fake.authorize(ctx);
} else if (ctx.path === '/login/oauth/access_token') {
return fake.accessToken(ctx);
} else if (ctx.path === '/user' && ctx.method === 'GET') {
return fake.getUser(ctx);
} else if (ctx.path.startsWith('/u/') && ctx.method === 'GET') {
return fake.getAvatarImage(ctx);
} else if (ctx.path === '/gists' && ctx.method === 'POST') {
return fake.createGist(ctx);
} else if (ctx.path.startsWith('/gists/') && ctx.method === 'GET') {
return fake.getGist(ctx);
} else if (ctx.path.startsWith('/gists/') && ctx.method === 'PATCH') {
return fake.updateGist(ctx);
} else {
return next();
}
};
};
const randomNumber = () => Math.floor(Math.random() * 1e10);
interface UserAndScope {
userId: number;
scope: string;
}
interface GistFile {
filename: string;
content: string;
}
interface CreateGistRequest {
files: {[filename: string]: GistFile};
}
interface UpdateGistRequest {
files: {[filename: string]: GistFile};
}
interface GetGistResponse {
id: string;
files: {[filename: string]: GistFile};
owner: {id: number};
}
interface UserDetails {
login: string;
}
const jsonResponse = (
ctx: Koa.Context,
status: number,
response: any
): void => {
ctx.status = status;
ctx.type = 'application/json';
ctx.body = JSON.stringify(response);
};
class FakeGitHub {
private readonly _options: FakeGitHubMiddlewareOptions;
private readonly _temporaryCodes = new Map<string, UserAndScope>();
private readonly _accessTokens = new Map<string, UserAndScope>();
private readonly _gists = new Map<string, GetGistResponse>();
private readonly _userDetails = new Map<number, UserDetails>();
constructor(options: FakeGitHubMiddlewareOptions) {
this._options = options;
}
/**
* Generate a random user ID for this session and persist it in a cookie.
*/
private _getOrSetUserIdFromCookie(ctx: Koa.Context): number {
let userIdStr = ctx.cookies.get('userid');
let userId = userIdStr ? Number(userIdStr) : undefined;
if (
userId === undefined ||
// The server must have restarted, so this is an invalid user id now.
!this._userDetails.has(userId)
) {
userId = randomNumber();
this._userDetails.set(userId, {
login: 'fakeuser',
});
ctx.cookies.set('userid', String(userId));
}
return userId;
}
private _checkAccept(ctx: Koa.Context): boolean {
const accept = ctx.get('accept');
if (accept !== 'application/vnd.github.v3+json') {
jsonResponse(ctx, 415, {
message: "Unsupported 'Accept' header",
});
return false;
}
return true;
}
private _checkAuthentication(ctx: Koa.Context): UserAndScope | undefined {
const match = (ctx.get('authorization') ?? '').match(
/^\s*(?:token|bearer)\s(?<token>.+)$/
);
const token = match?.groups?.token?.trim() ?? '';
const userAndScope = this._accessTokens.get(token);
if (!userAndScope) {
jsonResponse(ctx, 401, {message: 'Bad credentials'});
return undefined;
}
return userAndScope;
}
/**
* Clear all server state and browser cookies.
*
* Note this is not a real GitHub API. It is a convenience for developing and
* testing with this fake server, so that we can quickly reset to a
* pre-authenticated state.
*/
reset(ctx: Koa.Context) {
this._temporaryCodes.clear();
this._accessTokens.clear();
this._gists.clear();
this._userDetails.clear();
ctx.cookies.set('userid', null);
ctx.cookies.set('authorized', null);
ctx.status = 200;
ctx.body = 'fake github successfully reset';
}
/**
* Simulates https://github.com/login/oauth/authorize, the screen that prompts
* a user to authorize a GitHub OAuth App.
*
* Documentation:
* https://docs.github.com/en/developers/apps/building-oauth-apps/authorizing-oauth-apps#1-request-a-users-github-identity
*/
authorize(ctx: Koa.Context) {
const req = ctx.query as {client_id?: string; scope?: string};
if (req.client_id !== this._options.clientId) {
ctx.status = 400;
ctx.body = 'error: missing or incorrect client_id url parameter';
return;
}
const scope = req.scope ?? '';
const userId = this._getOrSetUserIdFromCookie(ctx);
const code = `fake-code-${randomNumber()}`;
this._temporaryCodes.set(code, {userId, scope});
const authorizeUrl = `${this._options.redirectUrl}?code=${code}`;
const cancelUrl = `${this._options.redirectUrl}?error=access_denied`;
if (ctx.cookies.get('authorized')) {
return ctx.redirect(authorizeUrl);
}
ctx.status = 200;
ctx.type = 'text/html';
ctx.body = `
<h2>Fake GitHub authorization prompt</h2>
<button onclick="cancel()">Cancel</button>
<button style="background:green;color:white"
onclick="authorize()">Authorize lit</button>
<script>
function authorize() {
document.cookie = 'authorized=1;path=/';
location.assign("${authorizeUrl}");
}
function cancel() {
location.assign("${cancelUrl}");
}
</script>
`;
}
/**
* Simulates https://github.com/login/oauth/access_token, the API that
* exchanges a temporary GitHub OAuth code for a longer term authentication
* token.
*
* Documentation:
* https://docs.github.com/en/developers/apps/building-oauth-apps/authorizing-oauth-apps#2-users-are-redirected-back-to-your-site-by-github
*/
async accessToken(ctx: Koa.Context) {
const req = ctx.query as {
code?: string;
client_id?: string;
client_secret?: string;
};
if (!req.code || !req.client_id || !req.client_secret) {
ctx.status = 400;
ctx.body =
'error: missing or incorrect code, client_id, and/or client_secret';
return;
}
if (ctx.get('accept') !== 'application/json') {
ctx.status = 400;
ctx.body = 'error: expected accept: application/json request header';
return;
}
if (req.client_secret !== this._options.clientSecret) {
return jsonResponse(ctx, 200, {
error: 'incorrect_client_credentials',
});
}
const userAndScope = this._temporaryCodes.get(req.code);
if (userAndScope === undefined) {
// TODO(aomarks) Could also simulate the 10 minute expiry, but since the
// error returned is indistinguishable from a completely invalid code,
// there doesn't seem to be much point.
return jsonResponse(ctx, 200, {error: 'bad_verification_code'});
}
this._temporaryCodes.delete(req.code);
// TODO(aomarks) Store this so that it can be checked by the gist APIs.
const accessToken = `fake-token-${randomNumber()}`;
this._accessTokens.set(accessToken, userAndScope);
return jsonResponse(ctx, 200, {
access_token: accessToken,
scope: userAndScope.scope,
token_type: 'bearer',
});
}
/**
* Simulates get https://api.github.com/user, the API for getting details
* about the authenticated user.
*/
async getUser(ctx: Koa.Context) {
if (!this._checkAccept(ctx)) {
return;
}
const userAndScope = this._checkAuthentication(ctx);
if (!userAndScope) {
return;
}
const {userId} = userAndScope;
const details = this._userDetails.get(userId);
if (!details) {
return jsonResponse(ctx, 500, {message: 'Missing user details'});
}
return jsonResponse(ctx, 200, {
id: userId,
login: details.login,
});
}
/**
* Simulates https://avatars.githubusercontent.com/u/<numeric user id>, the
* endpoint that serves GitHub avatar images.
*/
async getAvatarImage(ctx: Koa.Context) {
const id = ctx.path.match(/^\/u\/(?<id>\d+)/)?.groups?.id;
ctx.status = 200;
ctx.type = 'image/svg+xml';
const size = parseInt((ctx.query.s as string | undefined) ?? '245', 10);
const widthHeight = `width="${size}" height="${size}"`;
if (id && this._userDetails.has(Number(id))) {
// Yellow smiley
ctx.body = `
<svg xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 100 100" ${widthHeight}>
<circle cx="50" cy="50" r="50" fill="#fd0" />
<circle cx="30" cy="40" r="10" fill="#000" />
<circle cx="70" cy="40" r="10" fill="#000" />
<path d="M20,65 c15,15 45,15 60,0"
style="fill:none;stroke:#000;stroke-width:5" />
</svg>
`;
} else {
// Red cross
ctx.body = `
<svg xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 100 100" ${widthHeight}>
<path d="M5,5 L95,95 M5,95 L95,5"
style="fill:none;stroke:#f00;stroke-width:15" />
</svg>
`;
}
}
/**
* Simulates GET https://api.github.com/gists/<id>, the API for getting a
* GitHub gist.
*
* Documentation:
* https://docs.github.com/en/rest/reference/gists#get-a-gist
*/
async getGist(ctx: Koa.Context) {
if (!this._checkAccept(ctx)) {
return;
}
const match = ctx.path.match(/^\/gists\/(?<id>.+)/);
const id = match?.groups?.id;
if (!id) {
return jsonResponse(ctx, 400, {message: 'Invalid gist request'});
}
const gist = this._gists.get(id);
if (!gist) {
return jsonResponse(ctx, 404, {message: 'Not Found'});
}
// Gist files are always sorted alphabetically regardless of the order
// given.
gist.files = Object.fromEntries(
Object.entries(gist.files).sort(([aName], [bName]) =>
aName.localeCompare(bName)
)
);
return jsonResponse(ctx, 200, gist);
}
/**
* Simulates POST https://api.github.com/gists/, the API for creating a GitHub
* gist.
*
* Documentation:
* https://docs.github.com/en/rest/reference/gists#create-a-gist
*/
async createGist(ctx: Koa.Context) {
if (!this._checkAccept(ctx)) {
return;
}
const userAndScope = this._checkAuthentication(ctx);
if (!userAndScope) {
return;
}
let createRequest: CreateGistRequest;
try {
createRequest = await coBody.json(ctx);
} catch (e) {
return jsonResponse(ctx, 400, {message: 'Problems parsing JSON'});
}
if (!createRequest.files || Object.keys(createRequest.files).length === 0) {
return jsonResponse(ctx, 422, {message: 'Invalid files'});
}
for (const [filename, file] of Object.entries(createRequest.files)) {
if (!file.content) {
// Empty files are not allowed.
return jsonResponse(ctx, 422, {message: 'Validation Failed'});
}
file.filename = filename;
}
const gist = {
id: `fake-gist-${randomNumber()}`,
files: createRequest.files,
owner: {id: userAndScope.userId},
};
this._gists.set(gist.id, gist);
// Add a similar latency to the real API.
await new Promise((resolve) => setTimeout(resolve, 500));
return jsonResponse(ctx, 200, gist);
}
/**
* Simulates PATCH https://api.github.com/gists/<id>, the API for creating a
* new revision of an existing GitHub gist.
*
* Documentation:
* https://docs.github.com/en/rest/reference/gists#update-a-gist
*/
async updateGist(ctx: Koa.Context) {
if (!this._checkAccept(ctx)) {
return;
}
const userAndScope = this._checkAuthentication(ctx);
if (!userAndScope) {
return;
}
const idMatch = ctx.path.match(/^\/gists\/(?<id>.+)/);
const id = idMatch?.groups?.id;
const gist = this._gists.get(id ?? '');
if (!gist) {
// TODO(aomarks) Check error code
return jsonResponse(ctx, 404, {message: 'Invalid gist'});
}
let updateRequest: UpdateGistRequest;
try {
updateRequest = await coBody.json(ctx);
} catch (e) {
return jsonResponse(ctx, 400, {message: 'Problems parsing JSON'});
}
if (!updateRequest.files || Object.keys(updateRequest.files).length === 0) {
return jsonResponse(ctx, 422, {message: 'Invalid files'});
}
// TODO(aomarks) In the real API, each revision is stored individually, and
// you can GET either the latest revision, or a specific revision. Until
// needed, though, this fake just directly updates the simplified flat gist
// instead.
const newFiles = updateRequest.files;
const oldFiles = gist.files;
for (const [newFilename, newFile] of Object.entries(newFiles)) {
newFile.filename = newFilename;
if (!newFile.content && oldFiles[newFilename] === undefined) {
// New empty files are not allowed.
return jsonResponse(ctx, 422, {message: 'Validation Failed'});
}
}
for (const [oldFilename, oldFile] of Object.entries(oldFiles)) {
// To delete a file, you set its content to an empty string or undefined.
// If entirely omitted, the existing file is unchanged. See
// https://github.community/t/deleting-or-renaming-files-in-a-multi-file-gist-using-github-api/170967
if (newFiles[oldFilename] === undefined) {
newFiles[oldFilename] = oldFile;
} else if (!newFiles[oldFilename]?.content) {
delete newFiles[oldFilename];
}
}
gist.files = newFiles;
// Add a similar latency to the real API.
await new Promise((resolve) => setTimeout(resolve, 500));
return jsonResponse(ctx, 200, gist);
}
} | the_stack |
import {Request} from '../lib/request';
import {Response} from '../lib/response';
import {AWSError} from '../lib/error';
import {Service} from '../lib/service';
import {ServiceConfigurationOptions} from '../lib/service';
import {ConfigBase as Config} from '../lib/config-base';
interface Blob {}
declare class ServiceQuotas extends Service {
/**
* Constructs a service object. This object has one method for each API operation.
*/
constructor(options?: ServiceQuotas.Types.ClientConfiguration)
config: Config & ServiceQuotas.Types.ClientConfiguration;
/**
* Associates the Service Quotas template with your organization so that when new accounts are created in your organization, the template submits increase requests for the specified service quotas. Use the Service Quotas template to request an increase for any adjustable quota value. After you define the Service Quotas template, use this operation to associate, or enable, the template.
*/
associateServiceQuotaTemplate(params: ServiceQuotas.Types.AssociateServiceQuotaTemplateRequest, callback?: (err: AWSError, data: ServiceQuotas.Types.AssociateServiceQuotaTemplateResponse) => void): Request<ServiceQuotas.Types.AssociateServiceQuotaTemplateResponse, AWSError>;
/**
* Associates the Service Quotas template with your organization so that when new accounts are created in your organization, the template submits increase requests for the specified service quotas. Use the Service Quotas template to request an increase for any adjustable quota value. After you define the Service Quotas template, use this operation to associate, or enable, the template.
*/
associateServiceQuotaTemplate(callback?: (err: AWSError, data: ServiceQuotas.Types.AssociateServiceQuotaTemplateResponse) => void): Request<ServiceQuotas.Types.AssociateServiceQuotaTemplateResponse, AWSError>;
/**
* Removes a service quota increase request from the Service Quotas template.
*/
deleteServiceQuotaIncreaseRequestFromTemplate(params: ServiceQuotas.Types.DeleteServiceQuotaIncreaseRequestFromTemplateRequest, callback?: (err: AWSError, data: ServiceQuotas.Types.DeleteServiceQuotaIncreaseRequestFromTemplateResponse) => void): Request<ServiceQuotas.Types.DeleteServiceQuotaIncreaseRequestFromTemplateResponse, AWSError>;
/**
* Removes a service quota increase request from the Service Quotas template.
*/
deleteServiceQuotaIncreaseRequestFromTemplate(callback?: (err: AWSError, data: ServiceQuotas.Types.DeleteServiceQuotaIncreaseRequestFromTemplateResponse) => void): Request<ServiceQuotas.Types.DeleteServiceQuotaIncreaseRequestFromTemplateResponse, AWSError>;
/**
* Disables the Service Quotas template. Once the template is disabled, it does not request quota increases for new accounts in your organization. Disabling the quota template does not apply the quota increase requests from the template. Related operations To enable the quota template, call AssociateServiceQuotaTemplate. To delete a specific service quota from the template, use DeleteServiceQuotaIncreaseRequestFromTemplate.
*/
disassociateServiceQuotaTemplate(params: ServiceQuotas.Types.DisassociateServiceQuotaTemplateRequest, callback?: (err: AWSError, data: ServiceQuotas.Types.DisassociateServiceQuotaTemplateResponse) => void): Request<ServiceQuotas.Types.DisassociateServiceQuotaTemplateResponse, AWSError>;
/**
* Disables the Service Quotas template. Once the template is disabled, it does not request quota increases for new accounts in your organization. Disabling the quota template does not apply the quota increase requests from the template. Related operations To enable the quota template, call AssociateServiceQuotaTemplate. To delete a specific service quota from the template, use DeleteServiceQuotaIncreaseRequestFromTemplate.
*/
disassociateServiceQuotaTemplate(callback?: (err: AWSError, data: ServiceQuotas.Types.DisassociateServiceQuotaTemplateResponse) => void): Request<ServiceQuotas.Types.DisassociateServiceQuotaTemplateResponse, AWSError>;
/**
* Retrieves the default service quotas values. The Value returned for each quota is the AWS default value, even if the quotas have been increased..
*/
getAWSDefaultServiceQuota(params: ServiceQuotas.Types.GetAWSDefaultServiceQuotaRequest, callback?: (err: AWSError, data: ServiceQuotas.Types.GetAWSDefaultServiceQuotaResponse) => void): Request<ServiceQuotas.Types.GetAWSDefaultServiceQuotaResponse, AWSError>;
/**
* Retrieves the default service quotas values. The Value returned for each quota is the AWS default value, even if the quotas have been increased..
*/
getAWSDefaultServiceQuota(callback?: (err: AWSError, data: ServiceQuotas.Types.GetAWSDefaultServiceQuotaResponse) => void): Request<ServiceQuotas.Types.GetAWSDefaultServiceQuotaResponse, AWSError>;
/**
* Retrieves the ServiceQuotaTemplateAssociationStatus value from the service. Use this action to determine if the Service Quota template is associated, or enabled.
*/
getAssociationForServiceQuotaTemplate(params: ServiceQuotas.Types.GetAssociationForServiceQuotaTemplateRequest, callback?: (err: AWSError, data: ServiceQuotas.Types.GetAssociationForServiceQuotaTemplateResponse) => void): Request<ServiceQuotas.Types.GetAssociationForServiceQuotaTemplateResponse, AWSError>;
/**
* Retrieves the ServiceQuotaTemplateAssociationStatus value from the service. Use this action to determine if the Service Quota template is associated, or enabled.
*/
getAssociationForServiceQuotaTemplate(callback?: (err: AWSError, data: ServiceQuotas.Types.GetAssociationForServiceQuotaTemplateResponse) => void): Request<ServiceQuotas.Types.GetAssociationForServiceQuotaTemplateResponse, AWSError>;
/**
* Retrieves the details for a particular increase request.
*/
getRequestedServiceQuotaChange(params: ServiceQuotas.Types.GetRequestedServiceQuotaChangeRequest, callback?: (err: AWSError, data: ServiceQuotas.Types.GetRequestedServiceQuotaChangeResponse) => void): Request<ServiceQuotas.Types.GetRequestedServiceQuotaChangeResponse, AWSError>;
/**
* Retrieves the details for a particular increase request.
*/
getRequestedServiceQuotaChange(callback?: (err: AWSError, data: ServiceQuotas.Types.GetRequestedServiceQuotaChangeResponse) => void): Request<ServiceQuotas.Types.GetRequestedServiceQuotaChangeResponse, AWSError>;
/**
* Returns the details for the specified service quota. This operation provides a different Value than the GetAWSDefaultServiceQuota operation. This operation returns the applied value for each quota. GetAWSDefaultServiceQuota returns the default AWS value for each quota.
*/
getServiceQuota(params: ServiceQuotas.Types.GetServiceQuotaRequest, callback?: (err: AWSError, data: ServiceQuotas.Types.GetServiceQuotaResponse) => void): Request<ServiceQuotas.Types.GetServiceQuotaResponse, AWSError>;
/**
* Returns the details for the specified service quota. This operation provides a different Value than the GetAWSDefaultServiceQuota operation. This operation returns the applied value for each quota. GetAWSDefaultServiceQuota returns the default AWS value for each quota.
*/
getServiceQuota(callback?: (err: AWSError, data: ServiceQuotas.Types.GetServiceQuotaResponse) => void): Request<ServiceQuotas.Types.GetServiceQuotaResponse, AWSError>;
/**
* Returns the details of the service quota increase request in your template.
*/
getServiceQuotaIncreaseRequestFromTemplate(params: ServiceQuotas.Types.GetServiceQuotaIncreaseRequestFromTemplateRequest, callback?: (err: AWSError, data: ServiceQuotas.Types.GetServiceQuotaIncreaseRequestFromTemplateResponse) => void): Request<ServiceQuotas.Types.GetServiceQuotaIncreaseRequestFromTemplateResponse, AWSError>;
/**
* Returns the details of the service quota increase request in your template.
*/
getServiceQuotaIncreaseRequestFromTemplate(callback?: (err: AWSError, data: ServiceQuotas.Types.GetServiceQuotaIncreaseRequestFromTemplateResponse) => void): Request<ServiceQuotas.Types.GetServiceQuotaIncreaseRequestFromTemplateResponse, AWSError>;
/**
* Lists all default service quotas for the specified AWS service or all AWS services. ListAWSDefaultServiceQuotas is similar to ListServiceQuotas except for the Value object. The Value object returned by ListAWSDefaultServiceQuotas is the default value assigned by AWS. This request returns a list of all service quotas for the specified service. The listing of each you'll see the default values are the values that AWS provides for the quotas. Always check the NextToken response parameter when calling any of the List* operations. These operations can return an unexpected list of results, even when there are more results available. When this happens, the NextToken response parameter contains a value to pass the next call to the same API to request the next part of the list.
*/
listAWSDefaultServiceQuotas(params: ServiceQuotas.Types.ListAWSDefaultServiceQuotasRequest, callback?: (err: AWSError, data: ServiceQuotas.Types.ListAWSDefaultServiceQuotasResponse) => void): Request<ServiceQuotas.Types.ListAWSDefaultServiceQuotasResponse, AWSError>;
/**
* Lists all default service quotas for the specified AWS service or all AWS services. ListAWSDefaultServiceQuotas is similar to ListServiceQuotas except for the Value object. The Value object returned by ListAWSDefaultServiceQuotas is the default value assigned by AWS. This request returns a list of all service quotas for the specified service. The listing of each you'll see the default values are the values that AWS provides for the quotas. Always check the NextToken response parameter when calling any of the List* operations. These operations can return an unexpected list of results, even when there are more results available. When this happens, the NextToken response parameter contains a value to pass the next call to the same API to request the next part of the list.
*/
listAWSDefaultServiceQuotas(callback?: (err: AWSError, data: ServiceQuotas.Types.ListAWSDefaultServiceQuotasResponse) => void): Request<ServiceQuotas.Types.ListAWSDefaultServiceQuotasResponse, AWSError>;
/**
* Requests a list of the changes to quotas for a service.
*/
listRequestedServiceQuotaChangeHistory(params: ServiceQuotas.Types.ListRequestedServiceQuotaChangeHistoryRequest, callback?: (err: AWSError, data: ServiceQuotas.Types.ListRequestedServiceQuotaChangeHistoryResponse) => void): Request<ServiceQuotas.Types.ListRequestedServiceQuotaChangeHistoryResponse, AWSError>;
/**
* Requests a list of the changes to quotas for a service.
*/
listRequestedServiceQuotaChangeHistory(callback?: (err: AWSError, data: ServiceQuotas.Types.ListRequestedServiceQuotaChangeHistoryResponse) => void): Request<ServiceQuotas.Types.ListRequestedServiceQuotaChangeHistoryResponse, AWSError>;
/**
* Requests a list of the changes to specific service quotas. This command provides additional granularity over the ListRequestedServiceQuotaChangeHistory command. Once a quota change request has reached CASE_CLOSED, APPROVED, or DENIED, the history has been kept for 90 days.
*/
listRequestedServiceQuotaChangeHistoryByQuota(params: ServiceQuotas.Types.ListRequestedServiceQuotaChangeHistoryByQuotaRequest, callback?: (err: AWSError, data: ServiceQuotas.Types.ListRequestedServiceQuotaChangeHistoryByQuotaResponse) => void): Request<ServiceQuotas.Types.ListRequestedServiceQuotaChangeHistoryByQuotaResponse, AWSError>;
/**
* Requests a list of the changes to specific service quotas. This command provides additional granularity over the ListRequestedServiceQuotaChangeHistory command. Once a quota change request has reached CASE_CLOSED, APPROVED, or DENIED, the history has been kept for 90 days.
*/
listRequestedServiceQuotaChangeHistoryByQuota(callback?: (err: AWSError, data: ServiceQuotas.Types.ListRequestedServiceQuotaChangeHistoryByQuotaResponse) => void): Request<ServiceQuotas.Types.ListRequestedServiceQuotaChangeHistoryByQuotaResponse, AWSError>;
/**
* Returns a list of the quota increase requests in the template.
*/
listServiceQuotaIncreaseRequestsInTemplate(params: ServiceQuotas.Types.ListServiceQuotaIncreaseRequestsInTemplateRequest, callback?: (err: AWSError, data: ServiceQuotas.Types.ListServiceQuotaIncreaseRequestsInTemplateResponse) => void): Request<ServiceQuotas.Types.ListServiceQuotaIncreaseRequestsInTemplateResponse, AWSError>;
/**
* Returns a list of the quota increase requests in the template.
*/
listServiceQuotaIncreaseRequestsInTemplate(callback?: (err: AWSError, data: ServiceQuotas.Types.ListServiceQuotaIncreaseRequestsInTemplateResponse) => void): Request<ServiceQuotas.Types.ListServiceQuotaIncreaseRequestsInTemplateResponse, AWSError>;
/**
* Lists all service quotas for the specified AWS service. This request returns a list of the service quotas for the specified service. you'll see the default values are the values that AWS provides for the quotas. Always check the NextToken response parameter when calling any of the List* operations. These operations can return an unexpected list of results, even when there are more results available. When this happens, the NextToken response parameter contains a value to pass the next call to the same API to request the next part of the list.
*/
listServiceQuotas(params: ServiceQuotas.Types.ListServiceQuotasRequest, callback?: (err: AWSError, data: ServiceQuotas.Types.ListServiceQuotasResponse) => void): Request<ServiceQuotas.Types.ListServiceQuotasResponse, AWSError>;
/**
* Lists all service quotas for the specified AWS service. This request returns a list of the service quotas for the specified service. you'll see the default values are the values that AWS provides for the quotas. Always check the NextToken response parameter when calling any of the List* operations. These operations can return an unexpected list of results, even when there are more results available. When this happens, the NextToken response parameter contains a value to pass the next call to the same API to request the next part of the list.
*/
listServiceQuotas(callback?: (err: AWSError, data: ServiceQuotas.Types.ListServiceQuotasResponse) => void): Request<ServiceQuotas.Types.ListServiceQuotasResponse, AWSError>;
/**
* Lists the AWS services available in Service Quotas. Not all AWS services are available in Service Quotas. To list the see the list of the service quotas for a specific service, use ListServiceQuotas.
*/
listServices(params: ServiceQuotas.Types.ListServicesRequest, callback?: (err: AWSError, data: ServiceQuotas.Types.ListServicesResponse) => void): Request<ServiceQuotas.Types.ListServicesResponse, AWSError>;
/**
* Lists the AWS services available in Service Quotas. Not all AWS services are available in Service Quotas. To list the see the list of the service quotas for a specific service, use ListServiceQuotas.
*/
listServices(callback?: (err: AWSError, data: ServiceQuotas.Types.ListServicesResponse) => void): Request<ServiceQuotas.Types.ListServicesResponse, AWSError>;
/**
* Defines and adds a quota to the service quota template. To add a quota to the template, you must provide the ServiceCode, QuotaCode, AwsRegion, and DesiredValue. Once you add a quota to the template, use ListServiceQuotaIncreaseRequestsInTemplate to see the list of quotas in the template.
*/
putServiceQuotaIncreaseRequestIntoTemplate(params: ServiceQuotas.Types.PutServiceQuotaIncreaseRequestIntoTemplateRequest, callback?: (err: AWSError, data: ServiceQuotas.Types.PutServiceQuotaIncreaseRequestIntoTemplateResponse) => void): Request<ServiceQuotas.Types.PutServiceQuotaIncreaseRequestIntoTemplateResponse, AWSError>;
/**
* Defines and adds a quota to the service quota template. To add a quota to the template, you must provide the ServiceCode, QuotaCode, AwsRegion, and DesiredValue. Once you add a quota to the template, use ListServiceQuotaIncreaseRequestsInTemplate to see the list of quotas in the template.
*/
putServiceQuotaIncreaseRequestIntoTemplate(callback?: (err: AWSError, data: ServiceQuotas.Types.PutServiceQuotaIncreaseRequestIntoTemplateResponse) => void): Request<ServiceQuotas.Types.PutServiceQuotaIncreaseRequestIntoTemplateResponse, AWSError>;
/**
* Retrieves the details of a service quota increase request. The response to this command provides the details in the RequestedServiceQuotaChange object.
*/
requestServiceQuotaIncrease(params: ServiceQuotas.Types.RequestServiceQuotaIncreaseRequest, callback?: (err: AWSError, data: ServiceQuotas.Types.RequestServiceQuotaIncreaseResponse) => void): Request<ServiceQuotas.Types.RequestServiceQuotaIncreaseResponse, AWSError>;
/**
* Retrieves the details of a service quota increase request. The response to this command provides the details in the RequestedServiceQuotaChange object.
*/
requestServiceQuotaIncrease(callback?: (err: AWSError, data: ServiceQuotas.Types.RequestServiceQuotaIncreaseResponse) => void): Request<ServiceQuotas.Types.RequestServiceQuotaIncreaseResponse, AWSError>;
}
declare namespace ServiceQuotas {
export interface AssociateServiceQuotaTemplateRequest {
}
export interface AssociateServiceQuotaTemplateResponse {
}
export type AwsRegion = string;
export type CustomerServiceEngagementId = string;
export type DateTime = Date;
export interface DeleteServiceQuotaIncreaseRequestFromTemplateRequest {
/**
* Specifies the code for the service that you want to delete.
*/
ServiceCode: ServiceCode;
/**
* Specifies the code for the quota that you want to delete.
*/
QuotaCode: QuotaCode;
/**
* Specifies the AWS Region for the quota that you want to delete.
*/
AwsRegion: AwsRegion;
}
export interface DeleteServiceQuotaIncreaseRequestFromTemplateResponse {
}
export interface DisassociateServiceQuotaTemplateRequest {
}
export interface DisassociateServiceQuotaTemplateResponse {
}
export type ErrorCode = "DEPENDENCY_ACCESS_DENIED_ERROR"|"DEPENDENCY_THROTTLING_ERROR"|"DEPENDENCY_SERVICE_ERROR"|"SERVICE_QUOTA_NOT_AVAILABLE_ERROR"|string;
export type ErrorMessage = string;
export interface ErrorReason {
/**
* Service Quotas returns the following error values. DEPENDENCY_ACCESS_DENIED_ERROR is returned when the caller does not have permission to call the service or service quota. To resolve the error, you need permission to access the service or service quota. DEPENDENCY_THROTTLING_ERROR is returned when the service being called is throttling Service Quotas. DEPENDENCY_SERVICE_ERROR is returned when the service being called has availability issues. SERVICE_QUOTA_NOT_AVAILABLE_ERROR is returned when there was an error in Service Quotas.
*/
ErrorCode?: ErrorCode;
/**
* The error message that provides more detail.
*/
ErrorMessage?: ErrorMessage;
}
export interface GetAWSDefaultServiceQuotaRequest {
/**
* Specifies the service that you want to use.
*/
ServiceCode: ServiceCode;
/**
* Identifies the service quota you want to select.
*/
QuotaCode: QuotaCode;
}
export interface GetAWSDefaultServiceQuotaResponse {
/**
* Returns the ServiceQuota object which contains all values for a quota.
*/
Quota?: ServiceQuota;
}
export interface GetAssociationForServiceQuotaTemplateRequest {
}
export interface GetAssociationForServiceQuotaTemplateResponse {
/**
* Specifies whether the template is ASSOCIATED or DISASSOCIATED. If the template is ASSOCIATED, then it requests service quota increases for all new accounts created in your organization.
*/
ServiceQuotaTemplateAssociationStatus?: ServiceQuotaTemplateAssociationStatus;
}
export interface GetRequestedServiceQuotaChangeRequest {
/**
* Identifies the quota increase request.
*/
RequestId: RequestId;
}
export interface GetRequestedServiceQuotaChangeResponse {
/**
* Returns the RequestedServiceQuotaChange object for the specific increase request.
*/
RequestedQuota?: RequestedServiceQuotaChange;
}
export interface GetServiceQuotaIncreaseRequestFromTemplateRequest {
/**
* Specifies the service that you want to use.
*/
ServiceCode: ServiceCode;
/**
* Specifies the quota you want.
*/
QuotaCode: QuotaCode;
/**
* Specifies the AWS Region for the quota that you want to use.
*/
AwsRegion: AwsRegion;
}
export interface GetServiceQuotaIncreaseRequestFromTemplateResponse {
/**
* This object contains the details about the quota increase request.
*/
ServiceQuotaIncreaseRequestInTemplate?: ServiceQuotaIncreaseRequestInTemplate;
}
export interface GetServiceQuotaRequest {
/**
* Specifies the service that you want to use.
*/
ServiceCode: ServiceCode;
/**
* Identifies the service quota you want to select.
*/
QuotaCode: QuotaCode;
}
export interface GetServiceQuotaResponse {
/**
* Returns the ServiceQuota object which contains all values for a quota.
*/
Quota?: ServiceQuota;
}
export type GlobalQuota = boolean;
export interface ListAWSDefaultServiceQuotasRequest {
/**
* Specifies the service that you want to use.
*/
ServiceCode: ServiceCode;
/**
* (Optional) Use this parameter in a request if you receive a NextToken response in a previous request that indicates that there's more output available. In a subsequent call, set it to the value of the previous call's NextToken response to indicate where the output should continue from. If additional items exist beyond the specified maximum, the NextToken element is present and has a value (isn't null). Include that value as the NextToken request parameter in the call to the operation to get the next part of the results. You should check NextToken after every operation to ensure that you receive all of the results.
*/
NextToken?: NextToken;
/**
* (Optional) Limits the number of results that you want to include in the response. If you don't include this parameter, the response defaults to a value that's specific to the operation. If additional items exist beyond the specified maximum, the NextToken element is present and has a value (isn't null). Include that value as the NextToken request parameter in the call to the operation to get the next part of the results. You should check NextToken after every operation to ensure that you receive all of the results.
*/
MaxResults?: MaxResults;
}
export interface ListAWSDefaultServiceQuotasResponse {
/**
* (Optional) Use this parameter in a request if you receive a NextToken response in a previous request that indicates that there's more output available. In a subsequent call, set it to the value of the previous call's NextToken response to indicate where the output should continue from.
*/
NextToken?: NextToken;
/**
* A list of the quotas in the account with the AWS default values.
*/
Quotas?: ServiceQuotaListDefinition;
}
export interface ListRequestedServiceQuotaChangeHistoryByQuotaRequest {
/**
* Specifies the service that you want to use.
*/
ServiceCode: ServiceCode;
/**
* Specifies the service quota that you want to use
*/
QuotaCode: QuotaCode;
/**
* Specifies the status value of the quota increase request.
*/
Status?: RequestStatus;
/**
* (Optional) Use this parameter in a request if you receive a NextToken response in a previous request that indicates that there's more output available. In a subsequent call, set it to the value of the previous call's NextToken response to indicate where the output should continue from.
*/
NextToken?: NextToken;
/**
* (Optional) Limits the number of results that you want to include in the response. If you don't include this parameter, the response defaults to a value that's specific to the operation. If additional items exist beyond the specified maximum, the NextToken element is present and has a value (isn't null). Include that value as the NextToken request parameter in the call to the operation to get the next part of the results. You should check NextToken after every operation to ensure that you receive all of the results.
*/
MaxResults?: MaxResults;
}
export interface ListRequestedServiceQuotaChangeHistoryByQuotaResponse {
/**
* If present in the response, this value indicates there's more output available that what's included in the current response. This can occur even when the response includes no values at all, such as when you ask for a filtered view of a very long list. Use this value in the NextToken request parameter in a subsequent call to the operation to continue processing and get the next part of the output. You should repeat this until the NextToken response element comes back empty (as null).
*/
NextToken?: NextToken;
/**
* Returns a list of service quota requests.
*/
RequestedQuotas?: RequestedServiceQuotaChangeHistoryListDefinition;
}
export interface ListRequestedServiceQuotaChangeHistoryRequest {
/**
* Specifies the service that you want to use.
*/
ServiceCode?: ServiceCode;
/**
* Specifies the status value of the quota increase request.
*/
Status?: RequestStatus;
/**
* (Optional) Use this parameter in a request if you receive a NextToken response in a previous request that indicates that there's more output available. In a subsequent call, set it to the value of the previous call's NextToken response to indicate where the output should continue from.
*/
NextToken?: NextToken;
/**
* (Optional) Limits the number of results that you want to include in the response. If you don't include this parameter, the response defaults to a value that's specific to the operation. If additional items exist beyond the specified maximum, the NextToken element is present and has a value (isn't null). Include that value as the NextToken request parameter in the call to the operation to get the next part of the results. You should check NextToken after every operation to ensure that you receive all of the results.
*/
MaxResults?: MaxResults;
}
export interface ListRequestedServiceQuotaChangeHistoryResponse {
/**
* If present in the response, this value indicates there's more output available that what's included in the current response. This can occur even when the response includes no values at all, such as when you ask for a filtered view of a very long list. Use this value in the NextToken request parameter in a subsequent call to the operation to continue processing and get the next part of the output. You should repeat this until the NextToken response element comes back empty (as null).
*/
NextToken?: NextToken;
/**
* Returns a list of service quota requests.
*/
RequestedQuotas?: RequestedServiceQuotaChangeHistoryListDefinition;
}
export interface ListServiceQuotaIncreaseRequestsInTemplateRequest {
/**
* The identifier for a service. When performing an operation, use the ServiceCode to specify a particular service.
*/
ServiceCode?: ServiceCode;
/**
* Specifies the AWS Region for the quota that you want to use.
*/
AwsRegion?: AwsRegion;
/**
* (Optional) Use this parameter in a request if you receive a NextToken response in a previous request that indicates that there's more output available. In a subsequent call, set it to the value of the previous call's NextToken response to indicate where the output should continue from.
*/
NextToken?: NextToken;
/**
* (Optional) Limits the number of results that you want to include in the response. If you don't include this parameter, the response defaults to a value that's specific to the operation. If additional items exist beyond the specified maximum, the NextToken element is present and has a value (isn't null). Include that value as the NextToken request parameter in the call to the operation to get the next part of the results. You should check NextToken after every operation to ensure that you receive all of the results.
*/
MaxResults?: MaxResults;
}
export interface ListServiceQuotaIncreaseRequestsInTemplateResponse {
/**
* Returns the list of values of the quota increase request in the template.
*/
ServiceQuotaIncreaseRequestInTemplateList?: ServiceQuotaIncreaseRequestInTemplateList;
/**
* If present in the response, this value indicates there's more output available that what's included in the current response. This can occur even when the response includes no values at all, such as when you ask for a filtered view of a very long list. Use this value in the NextToken request parameter in a subsequent call to the operation to continue processing and get the next part of the output. You should repeat this until the NextToken response element comes back empty (as null).
*/
NextToken?: NextToken;
}
export interface ListServiceQuotasRequest {
/**
* The identifier for a service. When performing an operation, use the ServiceCode to specify a particular service.
*/
ServiceCode: ServiceCode;
/**
* (Optional) Use this parameter in a request if you receive a NextToken response in a previous request that indicates that there's more output available. In a subsequent call, set it to the value of the previous call's NextToken response to indicate where the output should continue from.
*/
NextToken?: NextToken;
/**
* (Optional) Limits the number of results that you want to include in the response. If you don't include this parameter, the response defaults to a value that's specific to the operation. If additional items exist beyond the specified maximum, the NextToken element is present and has a value (isn't null). Include that value as the NextToken request parameter in the call to the operation to get the next part of the results. You should check NextToken after every operation to ensure that you receive all of the results.
*/
MaxResults?: MaxResults;
}
export interface ListServiceQuotasResponse {
/**
* If present in the response, this value indicates there's more output available that what's included in the current response. This can occur even when the response includes no values at all, such as when you ask for a filtered view of a very long list. Use this value in the NextToken request parameter in a subsequent call to the operation to continue processing and get the next part of the output. You should repeat this until the NextToken response element comes back empty (as null).
*/
NextToken?: NextToken;
/**
* The response information for a quota lists all attribute information for the quota.
*/
Quotas?: ServiceQuotaListDefinition;
}
export interface ListServicesRequest {
/**
* (Optional) Use this parameter in a request if you receive a NextToken response in a previous request that indicates that there's more output available. In a subsequent call, set it to the value of the previous call's NextToken response to indicate where the output should continue from.
*/
NextToken?: NextToken;
/**
* (Optional) Limits the number of results that you want to include in the response. If you don't include this parameter, the response defaults to a value that's specific to the operation. If additional items exist beyond the specified maximum, the NextToken element is present and has a value (isn't null). Include that value as the NextToken request parameter in the call to the operation to get the next part of the results. You should check NextToken after every operation to ensure that you receive all of the results.
*/
MaxResults?: MaxResults;
}
export interface ListServicesResponse {
/**
* If present in the response, this value indicates there's more output available that what's included in the current response. This can occur even when the response includes no values at all, such as when you ask for a filtered view of a very long list. Use this value in the NextToken request parameter in a subsequent call to the operation to continue processing and get the next part of the output. You should repeat this until the NextToken response element comes back empty (as null).
*/
NextToken?: NextToken;
/**
* Returns a list of services.
*/
Services?: ServiceInfoListDefinition;
}
export type MaxResults = number;
export type MetricDimensionName = string;
export type MetricDimensionValue = string;
export type MetricDimensionsMapDefinition = {[key: string]: MetricDimensionValue};
export interface MetricInfo {
/**
* The namespace of the metric. The namespace is a container for CloudWatch metrics. You can specify a name for the namespace when you create a metric.
*/
MetricNamespace?: QuotaMetricNamespace;
/**
* The name of the CloudWatch metric that measures usage of a service quota. This is a required field.
*/
MetricName?: QuotaMetricName;
/**
* A dimension is a name/value pair that is part of the identity of a metric. Every metric has specific characteristics that describe it, and you can think of dimensions as categories for those characteristics. These dimensions are part of the CloudWatch Metric Identity that measures usage against a particular service quota.
*/
MetricDimensions?: MetricDimensionsMapDefinition;
/**
* Statistics are metric data aggregations over specified periods of time. This is the recommended statistic to use when comparing usage in the CloudWatch Metric against your Service Quota.
*/
MetricStatisticRecommendation?: Statistic;
}
export type NextToken = string;
export type PeriodUnit = "MICROSECOND"|"MILLISECOND"|"SECOND"|"MINUTE"|"HOUR"|"DAY"|"WEEK"|string;
export type PeriodValue = number;
export interface PutServiceQuotaIncreaseRequestIntoTemplateRequest {
/**
* Specifies the service quota that you want to use.
*/
QuotaCode: QuotaCode;
/**
* Specifies the service that you want to use.
*/
ServiceCode: ServiceCode;
/**
* Specifies the AWS Region for the quota.
*/
AwsRegion: AwsRegion;
/**
* Specifies the new, increased value for the quota.
*/
DesiredValue: QuotaValue;
}
export interface PutServiceQuotaIncreaseRequestIntoTemplateResponse {
/**
* A structure that contains information about one service quota increase request.
*/
ServiceQuotaIncreaseRequestInTemplate?: ServiceQuotaIncreaseRequestInTemplate;
}
export type QuotaAdjustable = boolean;
export type QuotaArn = string;
export type QuotaCode = string;
export type QuotaMetricName = string;
export type QuotaMetricNamespace = string;
export type QuotaName = string;
export interface QuotaPeriod {
/**
* The value of a period.
*/
PeriodValue?: PeriodValue;
/**
* The time unit of a period.
*/
PeriodUnit?: PeriodUnit;
}
export type QuotaUnit = string;
export type QuotaValue = number;
export type RequestId = string;
export interface RequestServiceQuotaIncreaseRequest {
/**
* Specifies the service that you want to use.
*/
ServiceCode: ServiceCode;
/**
* Specifies the service quota that you want to use.
*/
QuotaCode: QuotaCode;
/**
* Specifies the value submitted in the service quota increase request.
*/
DesiredValue: QuotaValue;
}
export interface RequestServiceQuotaIncreaseResponse {
/**
* Returns a list of service quota requests.
*/
RequestedQuota?: RequestedServiceQuotaChange;
}
export type RequestStatus = "PENDING"|"CASE_OPENED"|"APPROVED"|"DENIED"|"CASE_CLOSED"|string;
export interface RequestedServiceQuotaChange {
/**
* The unique identifier of a requested service quota change.
*/
Id?: RequestId;
/**
* The case Id for the service quota increase request.
*/
CaseId?: CustomerServiceEngagementId;
/**
* Specifies the service that you want to use.
*/
ServiceCode?: ServiceCode;
/**
* The name of the AWS service specified in the increase request.
*/
ServiceName?: ServiceName;
/**
* Specifies the service quota that you want to use.
*/
QuotaCode?: QuotaCode;
/**
* Name of the service quota.
*/
QuotaName?: QuotaName;
/**
* New increased value for the service quota.
*/
DesiredValue?: QuotaValue;
/**
* State of the service quota increase request.
*/
Status?: RequestStatus;
/**
* The date and time when the service quota increase request was received and the case Id was created.
*/
Created?: DateTime;
/**
* The date and time of the most recent change in the service quota increase request.
*/
LastUpdated?: DateTime;
/**
* The IAM identity who submitted the service quota increase request.
*/
Requester?: Requester;
/**
* The Amazon Resource Name (ARN) of the service quota.
*/
QuotaArn?: QuotaArn;
/**
* Identifies if the quota is global.
*/
GlobalQuota?: GlobalQuota;
/**
* Specifies the unit used for the quota.
*/
Unit?: QuotaUnit;
}
export type RequestedServiceQuotaChangeHistoryListDefinition = RequestedServiceQuotaChange[];
export type Requester = string;
export type ServiceCode = string;
export interface ServiceInfo {
/**
* Specifies the service that you want to use.
*/
ServiceCode?: ServiceCode;
/**
* The name of the AWS service specified in the increase request.
*/
ServiceName?: ServiceName;
}
export type ServiceInfoListDefinition = ServiceInfo[];
export type ServiceName = string;
export interface ServiceQuota {
/**
* Specifies the service that you want to use.
*/
ServiceCode?: ServiceCode;
/**
* The name of the AWS service specified in the increase request.
*/
ServiceName?: ServiceName;
/**
* The Amazon Resource Name (ARN) of the service quota.
*/
QuotaArn?: QuotaArn;
/**
* The code identifier for the service quota specified.
*/
QuotaCode?: QuotaCode;
/**
* The name identifier of the service quota.
*/
QuotaName?: QuotaName;
/**
* The value of service quota.
*/
Value?: QuotaValue;
/**
* The unit of measurement for the value of the service quota.
*/
Unit?: QuotaUnit;
/**
* Specifies if the quota value can be increased.
*/
Adjustable?: QuotaAdjustable;
/**
* Specifies if the quota is global.
*/
GlobalQuota?: GlobalQuota;
/**
* Specifies the details about the measurement.
*/
UsageMetric?: MetricInfo;
/**
* Identifies the unit and value of how time is measured.
*/
Period?: QuotaPeriod;
/**
* Specifies the ErrorCode and ErrorMessage when success isn't achieved.
*/
ErrorReason?: ErrorReason;
}
export interface ServiceQuotaIncreaseRequestInTemplate {
/**
* The code identifier for the AWS service specified in the increase request.
*/
ServiceCode?: ServiceCode;
/**
* The name of the AWS service specified in the increase request.
*/
ServiceName?: ServiceName;
/**
* The code identifier for the service quota specified in the increase request.
*/
QuotaCode?: QuotaCode;
/**
* The name of the service quota in the increase request.
*/
QuotaName?: QuotaName;
/**
* Identifies the new, increased value of the service quota in the increase request.
*/
DesiredValue?: QuotaValue;
/**
* The AWS Region where the increase request occurs.
*/
AwsRegion?: AwsRegion;
/**
* The unit of measure for the increase request.
*/
Unit?: QuotaUnit;
/**
* Specifies if the quota is a global quota.
*/
GlobalQuota?: GlobalQuota;
}
export type ServiceQuotaIncreaseRequestInTemplateList = ServiceQuotaIncreaseRequestInTemplate[];
export type ServiceQuotaListDefinition = ServiceQuota[];
export type ServiceQuotaTemplateAssociationStatus = "ASSOCIATED"|"DISASSOCIATED"|string;
export type Statistic = string;
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
export type apiVersion = "2019-06-24"|"latest"|string;
export interface ClientApiVersions {
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
apiVersion?: apiVersion;
}
export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions;
/**
* Contains interfaces for use with the ServiceQuotas client.
*/
export import Types = ServiceQuotas;
}
export = ServiceQuotas; | the_stack |
import { expect } from "chai";
import { Lists, List } from "../../src/sharepoint/lists";
import { ControlMode, PageType } from "../../src/sharepoint/types";
import { testSettings } from "../test-config.test";
import pnp from "../../src/pnp";
import { toMatchEndRegex } from "../testutils";
describe("Lists", () => {
let lists: Lists;
beforeEach(() => {
lists = new Lists("_api/web");
});
it("Should be an object", () => {
expect(lists).to.be.a("object");
});
describe("url", () => {
it("Should return _api/web/lists", () => {
expect(lists.toUrl()).to.match(toMatchEndRegex("_api/web/lists"));
});
});
describe("getByTitle", () => {
it("Should return _api/web/lists/getByTitle('Tasks')", () => {
let list = lists.getByTitle("Tasks");
expect(list.toUrl()).to.match(toMatchEndRegex("_api/web/lists/getByTitle('Tasks')"));
});
});
describe("getById", () => {
it("Should return _api/web/lists('4FC65058-FDDE-4FAD-AB21-2E881E1CF527')", () => {
let list = lists.getById("4FC65058-FDDE-4FAD-AB21-2E881E1CF527");
expect(list.toUrl()).to.match(toMatchEndRegex("_api/web/lists('4FC65058-FDDE-4FAD-AB21-2E881E1CF527')"));
});
});
describe("getById with {}", () => {
it("Should return _api/web/lists('{4FC65058-FDDE-4FAD-AB21-2E881E1CF527}')", () => {
let list = lists.getById("{4FC65058-FDDE-4FAD-AB21-2E881E1CF527}");
expect(list.toUrl()).to.match(toMatchEndRegex("_api/web/lists('{4FC65058-FDDE-4FAD-AB21-2E881E1CF527}')"));
});
});
if (testSettings.enableWebTests) {
describe("getByTitle", () => {
it("Should get a list by title with the expected title", () => {
// we are expecting that the OOTB list exists
return expect(pnp.sp.web.lists.getByTitle("Documents").get()).to.eventually.have.property("Title", "Documents");
});
});
describe("getById", () => {
it("Should get a list by id with the expected title", () => {
return expect(pnp.sp.web.lists.getByTitle("Documents").select("ID").getAs<{ Id: string }>().then((list) => {
return pnp.sp.web.lists.getById(list.Id).select("Title").get();
})).to.eventually.have.property("Title", "Documents");
});
});
describe("add", () => {
it("Should add a list with the expected title", () => {
return expect(pnp.sp.web.lists.add("pnp testing add").then(() => {
return pnp.sp.web.lists.getByTitle("pnp testing add").select("Title").get();
})).to.eventually.have.property("Title", "pnp testing add");
});
});
describe("ensure", () => {
it("Should ensure a list with the expected title", () => {
return expect(pnp.sp.web.lists.ensure("pnp testing ensure").then(() => {
return pnp.sp.web.lists.getByTitle("pnp testing ensure").select("Title").get();
})).to.eventually.have.property("Title", "pnp testing ensure");
});
});
describe("ensureSiteAssetsLibrary", () => {
it("Should ensure that the site assets library exists", () => {
return expect(pnp.sp.web.lists.ensureSiteAssetsLibrary()).to.eventually.be.fulfilled;
});
});
describe("ensureSitePagesLibrary", () => {
it("Should ensure that the site pages library exists", () => {
return expect(pnp.sp.web.lists.ensureSitePagesLibrary()).to.eventually.be.fulfilled;
});
});
}
});
describe("List", () => {
let list: List;
beforeEach(() => {
list = new List("_api/web/lists", "getByTitle('Tasks')");
});
it("Should be an object", () => {
expect(list).to.be.a("object");
});
describe("contentTypes", () => {
it("should return _api/web/lists/getByTitle('Tasks')/contenttypes", () => {
expect(list.contentTypes.toUrl()).to.match(toMatchEndRegex("_api/web/lists/getByTitle('Tasks')/contenttypes"));
});
});
describe("items", () => {
it("should return _api/web/lists/getByTitle('Tasks')/items", () => {
expect(list.items.toUrl()).to.match(toMatchEndRegex("_api/web/lists/getByTitle('Tasks')/items"));
});
});
describe("views", () => {
it("should return _api/web/lists/getByTitle('Tasks')/views", () => {
expect(list.views.toUrl()).to.match(toMatchEndRegex("_api/web/lists/getByTitle('Tasks')/views"));
});
});
describe("fields", () => {
it("should return _api/web/lists/getByTitle('Tasks')/fields", () => {
expect(list.fields.toUrl()).to.match(toMatchEndRegex("_api/web/lists/getByTitle('Tasks')/fields"));
});
});
describe("defaultView", () => {
it("should return _api/web/lists/getByTitle('Tasks')/DefaultView", () => {
expect(list.defaultView.toUrl()).to.match(toMatchEndRegex("_api/web/lists/getByTitle('Tasks')/DefaultView"));
});
});
describe("defaultView/viewFields", () => {
it("should return _api/web/lists/getByTitle('Tasks')/DefaultView/viewfields", () => {
expect(list.defaultView.fields.toUrl()).to.match(toMatchEndRegex("_api/web/lists/getByTitle('Tasks')/DefaultView/viewfields"));
});
});
describe("effectiveBasePermissions", () => {
it("should return _api/web/lists/getByTitle('Tasks')/EffectiveBasePermissions", () => {
expect(list.effectiveBasePermissions.toUrl())
.to.match(toMatchEndRegex("_api/web/lists/getByTitle('Tasks')/EffectiveBasePermissions"));
});
});
describe("eventReceivers", () => {
it("should return _api/web/lists/getByTitle('Tasks')/EventReceivers", () => {
expect(list.eventReceivers.toUrl()).to.match(toMatchEndRegex("_api/web/lists/getByTitle('Tasks')/EventReceivers"));
});
});
describe("relatedFields", () => {
it("should return _api/web/lists/getByTitle('Tasks')/getRelatedFields", () => {
expect(list.relatedFields.toUrl()).to.match(toMatchEndRegex("_api/web/lists/getByTitle('Tasks')/getRelatedFields"));
});
});
describe("informationRightsManagementSettings", () => {
it("should return _api/web/lists/getByTitle('Tasks')/InformationRightsManagementSettings", () => {
expect(list.informationRightsManagementSettings.toUrl())
.to.match(toMatchEndRegex("_api/web/lists/getByTitle('Tasks')/InformationRightsManagementSettings"));
});
});
describe("userCustomActions", () => {
it("should return _api/web/lists/getByTitle('Tasks')/usercustomactions", () => {
expect(list.userCustomActions.toUrl())
.to.match(toMatchEndRegex("_api/web/lists/getByTitle('Tasks')/usercustomactions"));
});
});
describe("getView", () => {
it("should return _api/web/lists/getByTitle('Tasks')/getView('b81b1b32-ed0a-4b80-bd16-67c99a4f3c1c')", () => {
expect(list.getView("b81b1b32-ed0a-4b80-bd16-67c99a4f3c1c").toUrl())
.to.match(toMatchEndRegex("_api/web/lists/getByTitle('Tasks')/getView('b81b1b32-ed0a-4b80-bd16-67c99a4f3c1c')"));
});
});
if (testSettings.enableWebTests) {
describe("contentTypes", () => {
it("should return a list of content types on the list", () => {
return expect(pnp.sp.web.lists.getByTitle("Documents").contentTypes.get()).to.eventually.be.fulfilled;
});
});
describe("items", () => {
it("should return items from the list", () => {
return expect(pnp.sp.web.lists.getByTitle("Documents").items.get()).to.eventually.be.fulfilled;
});
});
describe("views", () => {
it("should return views from the list", () => {
return expect(pnp.sp.web.lists.getByTitle("Documents").views.get()).to.eventually.be.fulfilled;
});
});
describe("fields", () => {
it("should return fields from the list", () => {
return expect(pnp.sp.web.lists.getByTitle("Documents").fields.get()).to.eventually.be.fulfilled;
});
});
describe("defaultView", () => {
it("should return the default view from the list", () => {
return expect(pnp.sp.web.lists.getByTitle("Documents").defaultView.get()).to.eventually.be.fulfilled;
});
});
describe("userCustomActions", () => {
it("should return the user custom actions from the list", () => {
return expect(pnp.sp.web.lists.getByTitle("Documents").userCustomActions.get()).to.eventually.be.fulfilled;
});
});
describe("effectiveBasePermissions", () => {
it("should return the effective base permissions from the list", () => {
return expect(pnp.sp.web.lists.getByTitle("Documents").effectiveBasePermissions.get()).to.eventually.be.fulfilled;
});
});
describe("eventReceivers", () => {
it("should return the event receivers from the list", () => {
return expect(pnp.sp.web.lists.getByTitle("Documents").eventReceivers.get()).to.eventually.be.fulfilled;
});
});
describe("relatedFields", () => {
it("should return the related fields from the list", () => {
return expect(pnp.sp.web.lists.getByTitle("Documents").relatedFields.get()).to.eventually.be.fulfilled;
});
});
describe("informationRightsManagementSettings", () => {
it("should return the information rights management settings from the list", () => {
return expect(pnp.sp.web.lists.getByTitle("Documents").informationRightsManagementSettings.get())
.to.eventually.be.fulfilled;
});
});
describe("getView", () => {
it("should return the default view by id from the list", () => {
return expect(pnp.sp.web.lists.getByTitle("Documents").defaultView.select("Id").get().then(v => {
return pnp.sp.web.lists.getByTitle("Documents").getView(v.Id).get();
})).to.eventually.be.fulfilled;
});
});
describe("update", () => {
it("should create a new list, update the title, and then ensure it is set as expected", () => {
let newTitle = "I have a new title";
return expect(pnp.sp.web.lists.ensure("pnp testing list update").then(result => {
return result.list.update({
Title: newTitle,
}).then(result2 => {
return result2.list.select("Title").get();
});
})).to.eventually.have.property("Title", newTitle);
});
});
describe("delete", () => {
it("should create a new list, delete it, and then ensure it is gone", () => {
return expect(pnp.sp.web.lists.ensure("pnp testing list delete").then(result => {
return result.list.delete().then(() => {
return result.list.select("Title").get();
});
})).to.eventually.be.rejected;
});
});
describe("getChanges", () => {
it("should get a list of changes", () => {
return expect(pnp.sp.web.lists.getByTitle("Documents").getChanges({
Add: true,
DeleteObject: true,
Restore: true,
})).to.eventually.be.fulfilled;
});
});
/* tslint:disable */
describe("getItemsByCAMLQuery", () => {
it("should get items based on the supplied CAML query", () => {
let caml = {
ViewXml: "<View><ViewFields><FieldRef Name='Title' /><FieldRef Name='RoleAssignments' /></ViewFields><RowLimit>5</RowLimit></View>"
};
return expect(pnp.sp.web.lists.getByTitle("Documents").getItemsByCAMLQuery(caml, "RoleAssignments")).to.eventually.be.fulfilled;
});
});
/* tslint:enable */
describe("getListItemChangesSinceToken", () => {
it("should get items based on the supplied change query");
});
describe("recycle", () => {
it("should create a new list, recycle it, and then ensure it is gone", () => {
return expect(pnp.sp.web.lists.ensure("pnp testing list recycle").then(result => {
return result.list.recycle().then(recycleResponse => {
if (typeof recycleResponse !== "string") {
throw new Error("Expected a string returned from recycle.");
}
return result.list.select("Title").get();
});
})).to.eventually.be.rejected;
});
});
describe("renderListData", () => {
it("should return a set of data which can be used to render an html view of the list", () => {
// create a list, add some items, render a view
return expect(pnp.sp.web.lists.ensure("pnp testing renderListData").then(result => {
return Promise.all([
result.list.items.add({ Title: "Item 1" }),
result.list.items.add({ Title: "Item 2" }),
result.list.items.add({ Title: "Item 3" }),
]).then(() => {
return result.list;
});
}).then(l => {
let viewXml = "<View><RowLimit>5</RowLimit></View>";
return l.renderListData(viewXml);
})).to.eventually.have.property("Row").that.is.not.empty;
});
});
describe("renderListFormData", () => {
it("should return a set of data which can be used to render an html view of the list", () => {
// create a list, add an item, get the form, render that form
return expect(pnp.sp.web.lists.ensure("pnp testing renderListFormData").then(result => {
return result.list.items.add({ Title: "Item 1" }).then(() => {
return result.list;
});
}).then(l => {
return l.forms.select("Id").filter(`FormType eq ${PageType.DisplayForm}`).get().then(f => {
return l.renderListFormData(1, f[0].Id, ControlMode.Display);
});
})).to.eventually.have.property("Title").that.is.not.null;
});
});
describe("reserveListItemId", () => {
it("should return a number", () => {
// create a list, reserve an item id
return expect(pnp.sp.web.lists.ensure("pnp testing reserveListItemId").then(result => {
return result.list.reserveListItemId();
})).to.eventually.be.a("number");
});
});
}
}); | the_stack |
import * as coreClient from "@azure/core-client";
import * as Parameters from "./models/parameters";
import * as Mappers from "./models/mappers";
import {
GeneratedClientOptionalParams,
AnalyzeOptionalParams,
AnalyzeResponse,
AnalyzeStatusOptionalParams,
AnalyzeStatusResponse,
HealthStatusOptionalParams,
HealthStatusResponse,
CancelHealthJobOptionalParams,
CancelHealthJobResponse,
MultiLanguageBatchInput,
HealthOptionalParams,
HealthResponse,
EntitiesRecognitionGeneralOptionalParams,
EntitiesRecognitionGeneralResponse,
EntitiesRecognitionPiiOptionalParams,
EntitiesRecognitionPiiResponse,
EntitiesLinkingOptionalParams,
EntitiesLinkingResponse,
KeyPhrasesOptionalParams,
KeyPhrasesResponse,
LanguageBatchInput,
LanguagesOptionalParams,
LanguagesResponse,
SentimentOptionalParams,
SentimentOperationResponse
} from "./models";
/** @internal */
export class GeneratedClient extends coreClient.ServiceClient {
endpoint: string;
/**
* Initializes a new instance of the GeneratedClient class.
* @param endpoint Supported Cognitive Services endpoints (protocol and hostname, for example:
* https://westus.api.cognitive.microsoft.com).
* @param options The parameter options
*/
constructor(endpoint: string, options?: GeneratedClientOptionalParams) {
if (endpoint === undefined) {
throw new Error("'endpoint' cannot be null");
}
// Initializing default values for options
if (!options) {
options = {};
}
const defaults: GeneratedClientOptionalParams = {
requestContentType: "application/json; charset=utf-8"
};
const packageDetails = `azsdk-js-textanalytics/1.0.0-preview1`;
const userAgentPrefix =
options.userAgentOptions && options.userAgentOptions.userAgentPrefix
? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`
: `${packageDetails}`;
const optionsWithDefaults = {
...defaults,
...options,
userAgentOptions: {
userAgentPrefix
},
baseUri: options.endpoint || "{Endpoint}/text/analytics/v3.1-preview.4"
};
super(optionsWithDefaults);
// Parameter assignments
this.endpoint = endpoint;
}
/**
* Submit a collection of text documents for analysis. Specify one or more unique tasks to be executed.
* @param options The options parameters.
*/
analyze(options?: AnalyzeOptionalParams): Promise<AnalyzeResponse> {
return this.sendOperationRequest({ options }, analyzeOperationSpec);
}
/**
* Get the status of an analysis job. A job may consist of one or more tasks. Once all tasks are
* completed, the job will transition to the completed state and results will be available for each
* task.
* @param jobId Job ID for Analyze
* @param options The options parameters.
*/
analyzeStatus(
jobId: string,
options?: AnalyzeStatusOptionalParams
): Promise<AnalyzeStatusResponse> {
return this.sendOperationRequest(
{ jobId, options },
analyzeStatusOperationSpec
);
}
/**
* Get details of the healthcare prediction job specified by the jobId.
* @param jobId Job ID
* @param options The options parameters.
*/
healthStatus(
jobId: string,
options?: HealthStatusOptionalParams
): Promise<HealthStatusResponse> {
return this.sendOperationRequest(
{ jobId, options },
healthStatusOperationSpec
);
}
/**
* Cancel healthcare prediction job.
* @param jobId Job ID
* @param options The options parameters.
*/
cancelHealthJob(
jobId: string,
options?: CancelHealthJobOptionalParams
): Promise<CancelHealthJobResponse> {
return this.sendOperationRequest(
{ jobId, options },
cancelHealthJobOperationSpec
);
}
/**
* Start a healthcare analysis job to recognize healthcare related entities (drugs, conditions,
* symptoms, etc) and their relations.
* @param input Collection of documents to analyze.
* @param options The options parameters.
*/
health(
input: MultiLanguageBatchInput,
options?: HealthOptionalParams
): Promise<HealthResponse> {
return this.sendOperationRequest({ input, options }, healthOperationSpec);
}
/**
* The API returns a list of general named entities in a given document. For the list of supported
* entity types, check <a href="https://aka.ms/taner">Supported Entity Types in Text Analytics API</a>.
* See the <a href="https://aka.ms/talangs">Supported languages in Text Analytics API</a> for the list
* of enabled languages.
* @param input Collection of documents to analyze.
* @param options The options parameters.
*/
entitiesRecognitionGeneral(
input: MultiLanguageBatchInput,
options?: EntitiesRecognitionGeneralOptionalParams
): Promise<EntitiesRecognitionGeneralResponse> {
return this.sendOperationRequest(
{ input, options },
entitiesRecognitionGeneralOperationSpec
);
}
/**
* The API returns a list of entities with personal information (\"SSN\", \"Bank Account\" etc) in the
* document. For the list of supported entity types, check <a href="https://aka.ms/tanerpii">Supported
* Entity Types in Text Analytics API</a>. See the <a href="https://aka.ms/talangs">Supported languages
* in Text Analytics API</a> for the list of enabled languages.
*
* @param input Collection of documents to analyze.
* @param options The options parameters.
*/
entitiesRecognitionPii(
input: MultiLanguageBatchInput,
options?: EntitiesRecognitionPiiOptionalParams
): Promise<EntitiesRecognitionPiiResponse> {
return this.sendOperationRequest(
{ input, options },
entitiesRecognitionPiiOperationSpec
);
}
/**
* The API returns a list of recognized entities with links to a well known knowledge base. See the <a
* href="https://aka.ms/talangs">Supported languages in Text Analytics API</a> for the list of enabled
* languages.
* @param input Collection of documents to analyze.
* @param options The options parameters.
*/
entitiesLinking(
input: MultiLanguageBatchInput,
options?: EntitiesLinkingOptionalParams
): Promise<EntitiesLinkingResponse> {
return this.sendOperationRequest(
{ input, options },
entitiesLinkingOperationSpec
);
}
/**
* The API returns a list of strings denoting the key phrases in the input text. See the <a
* href="https://aka.ms/talangs">Supported languages in Text Analytics API</a> for the list of enabled
* languages.
* @param input Collection of documents to analyze.
* @param options The options parameters.
*/
keyPhrases(
input: MultiLanguageBatchInput,
options?: KeyPhrasesOptionalParams
): Promise<KeyPhrasesResponse> {
return this.sendOperationRequest(
{ input, options },
keyPhrasesOperationSpec
);
}
/**
* The API returns the detected language and a numeric score between 0 and 1. Scores close to 1
* indicate 100% certainty that the identified language is true. See the <a
* href="https://aka.ms/talangs">Supported languages in Text Analytics API</a> for the list of enabled
* languages.
* @param input Collection of documents to analyze for language endpoint.
* @param options The options parameters.
*/
languages(
input: LanguageBatchInput,
options?: LanguagesOptionalParams
): Promise<LanguagesResponse> {
return this.sendOperationRequest(
{ input, options },
languagesOperationSpec
);
}
/**
* The API returns a detailed sentiment analysis for the input text. The analysis is done in multiple
* levels of granularity, start from the a document level, down to sentence and key terms (targets and
* assessments).
* @param input Collection of documents to analyze.
* @param options The options parameters.
*/
sentiment(
input: MultiLanguageBatchInput,
options?: SentimentOptionalParams
): Promise<SentimentOperationResponse> {
return this.sendOperationRequest(
{ input, options },
sentimentOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const analyzeOperationSpec: coreClient.OperationSpec = {
path: "/analyze",
httpMethod: "POST",
responses: {
202: {
headersMapper: Mappers.GeneratedClientAnalyzeHeaders
},
400: {
bodyMapper: Mappers.ErrorResponse,
isError: true
},
500: {
bodyMapper: Mappers.ErrorResponse,
isError: true
}
},
requestBody: Parameters.body,
urlParameters: [Parameters.endpoint],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const analyzeStatusOperationSpec: coreClient.OperationSpec = {
path: "/analyze/jobs/{jobId}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.AnalyzeJobState
},
404: {
bodyMapper: Mappers.ErrorResponse,
isError: true
},
500: {
bodyMapper: Mappers.ErrorResponse,
isError: true
}
},
queryParameters: [
Parameters.includeStatistics,
Parameters.top,
Parameters.skip
],
urlParameters: [Parameters.endpoint, Parameters.jobId],
headerParameters: [Parameters.accept],
serializer
};
const healthStatusOperationSpec: coreClient.OperationSpec = {
path: "/entities/health/jobs/{jobId}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.HealthcareJobState
},
404: {
bodyMapper: Mappers.ErrorResponse,
isError: true
},
500: {
bodyMapper: Mappers.ErrorResponse,
isError: true
}
},
queryParameters: [
Parameters.includeStatistics,
Parameters.top,
Parameters.skip
],
urlParameters: [Parameters.endpoint, Parameters.jobId1],
headerParameters: [Parameters.accept],
serializer
};
const cancelHealthJobOperationSpec: coreClient.OperationSpec = {
path: "/entities/health/jobs/{jobId}",
httpMethod: "DELETE",
responses: {
202: {
headersMapper: Mappers.GeneratedClientCancelHealthJobHeaders
},
404: {
bodyMapper: Mappers.ErrorResponse,
isError: true
},
500: {
bodyMapper: Mappers.ErrorResponse,
isError: true
}
},
urlParameters: [Parameters.endpoint, Parameters.jobId1],
headerParameters: [Parameters.accept],
serializer
};
const healthOperationSpec: coreClient.OperationSpec = {
path: "/entities/health/jobs",
httpMethod: "POST",
responses: {
202: {
headersMapper: Mappers.GeneratedClientHealthHeaders
},
400: {
bodyMapper: Mappers.ErrorResponse,
isError: true
},
500: {
bodyMapper: Mappers.ErrorResponse,
isError: true
}
},
requestBody: Parameters.input,
queryParameters: [Parameters.modelVersion, Parameters.stringIndexType],
urlParameters: [Parameters.endpoint],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const entitiesRecognitionGeneralOperationSpec: coreClient.OperationSpec = {
path: "/entities/recognition/general",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.EntitiesResult
},
400: {
bodyMapper: Mappers.ErrorResponse,
isError: true
},
500: {
bodyMapper: Mappers.ErrorResponse,
isError: true
}
},
requestBody: Parameters.input,
queryParameters: [
Parameters.includeStatistics,
Parameters.modelVersion,
Parameters.stringIndexType
],
urlParameters: [Parameters.endpoint],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const entitiesRecognitionPiiOperationSpec: coreClient.OperationSpec = {
path: "/entities/recognition/pii",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.PiiResult
},
400: {
bodyMapper: Mappers.ErrorResponse,
isError: true
},
500: {
bodyMapper: Mappers.ErrorResponse,
isError: true
}
},
requestBody: Parameters.input,
queryParameters: [
Parameters.includeStatistics,
Parameters.modelVersion,
Parameters.stringIndexType,
Parameters.domain,
Parameters.piiCategories
],
urlParameters: [Parameters.endpoint],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const entitiesLinkingOperationSpec: coreClient.OperationSpec = {
path: "/entities/linking",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.EntityLinkingResult
},
400: {
bodyMapper: Mappers.ErrorResponse,
isError: true
},
500: {
bodyMapper: Mappers.ErrorResponse,
isError: true
}
},
requestBody: Parameters.input,
queryParameters: [
Parameters.includeStatistics,
Parameters.modelVersion,
Parameters.stringIndexType
],
urlParameters: [Parameters.endpoint],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const keyPhrasesOperationSpec: coreClient.OperationSpec = {
path: "/keyPhrases",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.KeyPhraseResult
},
400: {
bodyMapper: Mappers.ErrorResponse,
isError: true
},
500: {
bodyMapper: Mappers.ErrorResponse,
isError: true
}
},
requestBody: Parameters.input,
queryParameters: [Parameters.includeStatistics, Parameters.modelVersion],
urlParameters: [Parameters.endpoint],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const languagesOperationSpec: coreClient.OperationSpec = {
path: "/languages",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.LanguageResult
},
400: {
bodyMapper: Mappers.ErrorResponse,
isError: true
},
500: {
bodyMapper: Mappers.ErrorResponse,
isError: true
}
},
requestBody: Parameters.input1,
queryParameters: [Parameters.includeStatistics, Parameters.modelVersion],
urlParameters: [Parameters.endpoint],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const sentimentOperationSpec: coreClient.OperationSpec = {
path: "/sentiment",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.SentimentResponse
},
400: {
bodyMapper: Mappers.ErrorResponse,
isError: true
},
500: {
bodyMapper: Mappers.ErrorResponse,
isError: true
}
},
requestBody: Parameters.input,
queryParameters: [
Parameters.includeStatistics,
Parameters.modelVersion,
Parameters.stringIndexType,
Parameters.opinionMining
],
urlParameters: [Parameters.endpoint],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
}; | the_stack |
import { core } from './core';
// for docs
// noinspection ES6UnusedImports
import * as el from '../';
// ============================================================================
// Native
// Unary
// in is in in.d.ts because it collides with the in function from basics
/**
* Computes the sine of the operand.
*
* @param [props]
* props object with optional key
*
* @param operand
* to compute the sine of
*
* @returns
* a {@link core.SinNode} that computes the sine of the operand
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.SinNode
*/
export const sin:
core.NodeFactory<'sin',
core.KeyProps,
[
operand: core.Child
]>;
/**
* Computes the cosine of the operand.
*
* @param [props]
* props object with optional key
*
* @param operand
* to compute the cosine of
*
* @returns
* a {@link core.CosNode} that computes the cosine of the operand
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.CosNode
*/
export const cos:
core.NodeFactory<'cos',
core.KeyProps,
[
operand: core.Child
]>;
/**
* Computes the tangent of the operand.
*
* @param [props]
* props object with optional key
*
* @param operand
* to compute the tangent of
*
* @returns
* a {@link core.TanNode} that computes the tangent of the operand
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.TanNode
*/
export const tan:
core.NodeFactory<'tan',
core.KeyProps,
[
operand: core.Child
]>;
/**
* Computes the hyperbolic tangent of the operand.
*
* @param [props]
* props object with optional key
*
* @param operand
* to compute the hyperbolic tangent of
*
* @returns
* a {@link core.TanhNode} that computes the hyperbolic tangent of the operand
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.TanhNode
*/
export const tanh:
core.NodeFactory<'tanh',
core.KeyProps,
[
operand: core.Child
]>;
/**
* Computes the inverse hyperbolic sine of the operand.
*
* @param [props]
* props object with optional key
*
* @param operand
* to compute the inverse hyperbolic sine of
*
* @returns
* a {@link core.AsinhNode} that computes the inverse hyperbolic sine
* of the operand
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.AsinhNode
*/
export const asinh:
core.NodeFactory<'asinh',
core.KeyProps,
[
operand: core.Child
]>;
/**
* Computes the natural logarithm of the operand.
*
* @param [props]
* props object with optional key
*
* @param operand
* to compute the natural logarithm of
*
* @returns
* a {@link core.LnNode} that computes the natural logarithm of the operand
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.LnNode
*/
export const ln:
core.NodeFactory<'ln',
core.KeyProps,
[
operand: core.Child
]>;
// TODO: confirm its the log in base 10
/**
* Computes the logarithm in base 10 of the operand.
*
* @param [props]
* props object with optional key
*
* @param operand
* to compute the logarithm in base 10 of
*
* @returns
* a {@link core.LogNode} that computes the logarithm in base 10 of the operand
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.LogNode
*/
export const log:
core.NodeFactory<'log',
core.KeyProps,
[
operand: core.Child
]>;
/**
* Computes the logarithm in base 2 of the operand.
*
* @param [props]
* props object with optional key
*
* @param operand
* to compute the logarithm in base 2 of
*
* @returns
* a {@link core.Log2Node} that computes the logarithm in base 2 of the operand
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.Log2Node
*/
export const log2:
core.NodeFactory<'log2',
core.KeyProps,
[
operand: core.Child
]>;
/**
* Computes the ceiling of the operand.
*
* @param [props]
* props object with optional key
*
* @param operand
* to compute the ceiling of
*
* @returns
* a {@link core.CeilNode} that computes the ceiling of the operand
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.CeilNode
*/
export const ceil:
core.NodeFactory<'ceil',
core.KeyProps,
[
operand: core.Child
]>;
/**
* Computes the floor of the operand.
*
* @param [props]
* props object with optional key
*
* @param operand
* to compute the floor of
*
* @returns
* a {@link core.FloorNode} that computes the floor of the operand
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.FloorNode
*/
export const floor:
core.NodeFactory<'floor',
core.KeyProps,
[
operand: core.Child
]>;
/**
* Computes the square root of the operand.
*
* @param [props]
* props object with optional key
*
* @param operand
* to compute the square root of
*
* @returns
* a {@link core.SqrtNode} that computes the square root of the operand
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.SqrtNode
*/
export const sqrt:
core.NodeFactory<'sqrt',
core.KeyProps,
[
operand: core.Child
]>;
// TODO: confirm base 10
/**
* Computes the exponential in base 10 of the operand.
*
* @param [props]
* props object with optional key
*
* @param operand
* to compute the exponential in base 10 of
*
* @returns
* a {@link core.ExpNode} that computes the exponential in base 10 of the operand
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.ExpNode
*/
export const exp:
core.NodeFactory<'exp',
core.KeyProps,
[
operand: core.Child
]>;
/**
* Computes the absolute number of the operand.
*
* @param [props]
* props object with optional key
*
* @param operand
* to compute the absolute number of
*
* @returns
* a {@link core.AbsNode} that computes the absolute number of the operand
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.AbsNode
*/
export const abs:
core.NodeFactory<'abs',
core.KeyProps,
[
operand: core.Child
]>;
// Binary
/**
* Computes whether the first is lesser than the second.
*
* @param [props]
* props object with optional key
*
* @param first
* first operand
*
* @param second
* second operand
*
* @returns
* a {@link core.LeNode} that computes whether the first is lesser
* than the second operand
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.LeNode
*/
export const le:
core.NodeFactory<'le',
core.KeyProps,
[
first: core.Child,
second: core.Child
]>;
/**
* Computes whether the first is lesser or equal than the second.
*
* @param [props]
* props object with optional key
*
* @param first
* first operand
*
* @param second
* second operand
*
* @returns
* a {@link core.LeqNode} that computes whether the first is lesser or equal
* than the second operand
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.LeqNode
*/
export const leq:
core.NodeFactory<'leq',
core.KeyProps,
[
first: core.Child,
second: core.Child
]>;
/**
* Computes whether the first is greater than the second.
*
* @param [props]
* props object with optional key
*
* @param first
* first operand
*
* @param second
* second operand
*
* @returns
* a {@link core.GeNode} that computes whether the first is greater
* than the second operand
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.GeNode
*/
export const ge:
core.NodeFactory<'ge',
core.KeyProps,
[
first: core.Child,
second: core.Child
]>;
/**
* Computes whether the first is greater or equal than the second.
*
* @param [props]
* props object with optional key
*
* @param first
* first operand
*
* @param second
* second operand
*
* @returns
* a {@link core.GeqNode} that computes whether the first is greater or equal
* than the second operand
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.GeqNode
*/
export const geq:
core.NodeFactory<'geq',
core.KeyProps,
[
first: core.Child,
second: core.Child
]>;
/**
* Computes the power of the first with with the second as the exponent.
*
* @param [props]
* props object with optional key
*
* @param first
* first operand
*
* @param second
* second operand
*
* @returns
* a {@link core.PowNode} that computes the power of the first with
* the second as the exponent
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.PowNode
*/
export const pow:
core.NodeFactory<'pow',
core.KeyProps,
[
first: core.Child,
second: core.Child
]>;
/**
* Computes the modulo of the first with the second.
*
* @param [props]
* props object with optional key
*
* @param first
* first operand
*
* @param second
* second operand
*
* @returns
* a {@link core.ModNode} that computes the module of the first with the second
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.ModNode
*/
export const mod:
core.NodeFactory<'mod',
core.KeyProps,
[
first: core.Child,
second: core.Child
]>;
/**
* Returns the result of the minimal operand.
*
* @param [props]
* props object with optional key
*
* @param first
* first operand
*
* @param second
* second operand
*
* @returns
* a {@link core.MinNode} that returns the result of the minimal operand
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.MinNode
*/
export const min:
core.NodeFactory<'min',
core.KeyProps,
[
first: core.Child,
second: core.Child
]>;
/**
* Returns the result of the maximal operand.
*
* @param [props]
* props object with optional key
*
* @param first
* first operand
*
* @param second
* second operand
*
* @returns
* a {@link core.MaxNode} that returns the result of the maximal operand
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.MaxNode
*/
export const max:
core.NodeFactory<'max',
core.KeyProps,
[
first: core.Child,
second: core.Child
]>;
// Variadic
/**
* Adds up the operands.
* Identical to: (((child1 + child2) + child3) + ... )
*
* Expects at least one operand.
* If only one is passed it behaves as the identity function.
*
* @param [props]
* props object with optional key
*
* @param operands
* the operands to add up
*
* @returns
* a {@link core.AddNode} that sums up the operands
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.AddNode
*/
export const add:
core.NodeFactory<'add',
core.KeyProps,
[
...operands: core.VariadicChildrenArray
]>;
/**
* Subtracts the rest of the operands from the first.
* Identical to: (((child1 - child2) - child3) - ... )
*
* Expects at least one operand.
* If only one is passed it behaves as the identity function.
*
* @param operands
* the operands to subtract
*
* @returns
* a {@link core.SubNode} that subtracts the rest of the operands from the first
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.SubNode
*/
export const sub:
core.NodeFactory<'sub',
core.KeyProps,
[
...operands: core.VariadicChildrenArray
]>;
/**
* Multiplies the operands.
* Identical to: (((child1 * child2) * child3) * ... )
*
* Expects at least one operand.
* If only one is passed it as the identity function.
*
* @param [props]
* props object with optional key
*
* @param rest
* the operands to multiply
*
* @returns
* a {@link core.MulNode} that multiplies the operands
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.MulNode
*/
export const mul:
core.NodeFactory<'mul',
core.KeyProps,
[
...operands: core.VariadicChildrenArray
]>;
/**
* Divides the first with the rest of the operands.
* Identical to: (((child1 / child2) / child3) / ... )
*
* Expects at least one operand.
* If only one is passed it behaves as the identity function.
*
* @param [props]
* props object with optional key
*
* @param operands
* the operands to divide
*
* @returns
* a {@link core.DivNode} that divides the first with the rest of the operands
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.DivNode
*/
export const div:
core.NodeFactory<'div',
core.KeyProps,
[
...operands: core.VariadicChildrenArray
]>; | the_stack |
import { expect } from "chai";
import * as React from "react";
import { PropertyRecord } from "@itwin/appui-abstract";
import {
IPropertyDataProvider, PrimitivePropertyValueRenderer, PropertyDataChangeEvent, PropertyValueRendererContext, PropertyValueRendererManager,
VirtualizedPropertyGridWithDataProvider,
} from "@itwin/components-react";
import { IModelConnection, SnapshotConnection } from "@itwin/core-frontend";
import { ContentSpecificationTypes, KeySet, Ruleset, RuleTypes } from "@itwin/presentation-common";
import { PresentationPropertyDataProvider } from "@itwin/presentation-components";
import { Presentation } from "@itwin/presentation-frontend";
import { render } from "@testing-library/react";
import { initialize, terminate } from "../../../IntegrationTests";
import { printRuleset } from "../../Utils";
describe("Learning Snippets", () => {
let imodel: IModelConnection;
beforeEach(async () => {
await initialize();
imodel = await SnapshotConnection.openFile("assets/datasets/Properties_60InstancesWithUrl2.ibim");
});
afterEach(async () => {
await imodel.close();
await terminate();
});
describe("Content Customization", () => {
describe("PropertySpecification", () => {
it("uses `overridesPriority` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Presentation.Content.Customization.PropertySpecification.OverridesPriority.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. In addition, the `UserLabel`
// property has a couple of property overrides which set renderer, editor and label. The label is
// overriden by both specifications and the one with higher `overridesPriority` takes precedence.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
propertyOverrides: [{
name: "UserLabel",
overridesPriority: 1,
labelOverride: "A",
renderer: {
rendererName: "my-renderer",
},
}, {
name: "UserLabel",
overridesPriority: 2,
labelOverride: "B",
editor: {
editorName: "my-editor",
},
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// Ensure the `UserLabel` field is assigned attributes from both specifications
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
expect(content.descriptor.fields).to.containSubset([{
label: "B",
renderer: {
name: "my-renderer",
},
editor: {
name: "my-editor",
},
}]);
});
it("uses `labelOverride` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Presentation.Content.Customization.PropertySpecification.LabelOverride.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. In addition, the `UserLabel`
// property has a label override that relabels it to "Custom Label".
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
propertyOverrides: [{
name: "UserLabel",
labelOverride: "Custom Label",
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// Ensure the `UserLabel` field is assigned attributes from both specifications
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
expect(content.descriptor.fields).to.containSubset([{
label: "Custom Label",
}]);
});
it("uses `categoryId` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Presentation.Content.Customization.PropertySpecification.CategoryId.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. In addition, the `UserLabel`
// property is placed into a custom category by assigning it a `categoryId`.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
propertyCategories: [{
id: "custom-category",
label: "Custom Category",
}],
propertyOverrides: [{
name: "UserLabel",
categoryId: "custom-category",
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// Ensure the `UserLabel` field has the correct category
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
expect(content.descriptor.fields).to.containSubset([{
label: "User Label",
category: {
label: "Custom Category",
},
}]);
});
it("uses `isDisplayed` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Presentation.Content.Customization.PropertySpecification.IsDisplayed.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. In addition,
// the `LastMod` property, which is hidden using a custom attribute in ECSchema, is force-displayed
// using a property override.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
propertyOverrides: [{
name: "LastMod",
isDisplayed: true,
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// Ensure the `LastMod` is there
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
expect(content.descriptor.fields).to.containSubset([{
label: "Last Modified",
}]);
});
it("uses `doNotHideOtherPropertiesOnDisplayOverride` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Presentation.Content.Customization.PropertySpecification.DoNotHideOtherPropertiesOnDisplayOverride.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. In addition,
// the `UserLabel` property is set to be displayed with `doNotHideOtherPropertiesOnDisplayOverride` flag,
// which ensures other properties are also kept displayed.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
propertyOverrides: [{
name: "UserLabel",
isDisplayed: true,
doNotHideOtherPropertiesOnDisplayOverride: true,
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// Ensure the `UserLabel` property is not the only property in content
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
expect(content.descriptor.fields).to.containSubset([{
label: "User Label",
}]).and.to.have.lengthOf(4);
});
it("uses `renderer` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Presentation.Content.Customization.PropertySpecification.Renderer.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. In addition,
// it assigns the `CodeValue` property a custom "my-renderer" renderer.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
propertyOverrides: [{
name: "CodeValue",
renderer: {
rendererName: "my-renderer",
},
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// __PUBLISH_EXTRACT_START__ Presentation.Content.Customization.PropertySpecification.Renderer.Result
// Ensure the `CodeValue` field is assigned the "my-renderer" renderer
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
expect(content.descriptor.fields).to.containSubset([{
label: "Code",
renderer: {
name: "my-renderer",
},
}]);
// __PUBLISH_EXTRACT_END__
try {
// __PUBLISH_EXTRACT_START__ Presentation.Content.Customization.PropertySpecification.Renderer.Register
// The custom renderer renders the property value in red
PropertyValueRendererManager.defaultManager.registerRenderer("my-renderer", {
canRender: () => true,
render: function myRenderer(record: PropertyRecord, ctx?: PropertyValueRendererContext) {
const defaultRenderer = new PrimitivePropertyValueRenderer();
return defaultRenderer.render(record, { ...ctx, style: { ...ctx?.style, color: "red" } });
},
});
// __PUBLISH_EXTRACT_END__
const dataProvider = new PresentationPropertyDataProvider({ imodel, ruleset });
dataProvider.keys = new KeySet([{ className: "BisCore:Subject", id: "0x1" }]);
const expandedDataProvider: IPropertyDataProvider = {
onDataChanged: new PropertyDataChangeEvent(),
getData: async () => {
const data = await dataProvider.getData();
data.categories.forEach((c) => c.expand = true);
return data;
},
};
const { findAllByText } = render(
<VirtualizedPropertyGridWithDataProvider
dataProvider={expandedDataProvider}
width={500}
height={1200}
/>,
);
const renderedElements = await findAllByText("DgnV8Bridge");
expect(renderedElements[0].style.color).to.eq("red");
} finally {
PropertyValueRendererManager.defaultManager.unregisterRenderer("my-renderer");
}
});
it("uses `editor` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Presentation.Content.Customization.PropertySpecification.Editor.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. In addition,
// it assigns the `UserLabel` property a custom "my-editor" editor.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
propertyOverrides: [{
name: "UserLabel",
editor: {
editorName: "my-editor",
},
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// __PUBLISH_EXTRACT_START__ Presentation.Content.Customization.PropertySpecification.Editor.Result
// Ensure the `UserLabel` field is assigned the "my-editor" editor
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
expect(content.descriptor.fields).to.containSubset([{
label: "User Label",
editor: {
name: "my-editor",
},
}]);
// __PUBLISH_EXTRACT_END__
});
it("uses `isReadOnly` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Presentation.Content.Customization.PropertySpecification.IsReadOnly.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. In addition, the `UserLabel`
// property is made read-only.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
propertyOverrides: [{
name: "UserLabel",
isReadOnly: true,
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// __PUBLISH_EXTRACT_START__ Presentation.Content.Customization.PropertySpecification.IsReadOnly.Result
// Ensure the `UserLabel` field is read-only.
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
expect(content.descriptor.fields).to.containSubset([{
label: "User Label",
isReadonly: true,
}]);
// __PUBLISH_EXTRACT_END__
});
it("uses `priority` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Presentation.Content.Customization.PropertySpecification.Priority.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. In addition, the `UserLabel`
// property's priority is set to 9999.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
propertyOverrides: [{
name: "UserLabel",
priority: 9999,
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// Ensure the `UserLabel` field's priority is 9999, which makes it appear higher in the property grid.
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
expect(content.descriptor.fields).to.containSubset([{
label: "User Label",
priority: 9999,
}]);
});
});
});
}); | the_stack |
import pipe1 from "./pipe1";
import reduce from "./reduce";
import Awaited from "./types/Awaited";
import ReturnPipeType from "./types/ReturnPipeType";
/**
* Performs left to right function composition.
* The first argument can have any value; the remaining arguments must be unary.
*
* @example
* ```ts
* pipe(
* [1, 2, 3, 4, 5],
* map(a => a + 10),
* filter(a => a % 2 === 0),
* toArray,
* ); // [12, 14]
*
* await pipe(
* Promise.resolve([1, 2, 3, 4, 5]),
* map(a => a + 10),
* filter(a => a % 2 === 0),
* toArray,
* ); // [12, 14]
*
* // if you want to use asynchronous callback
* await pipe(
* Promise.resolve([1, 2, 3, 4, 5]),
* toAsync,
* map(async (a) => a + 10),
* filter((a) => a % 2 === 0),
* toArray,
* ); // [12, 14]
*
* // with toAsync
* await pipe(
* [Promise.resolve(1), Promise.resolve(2), Promise.resolve(3), Promise.resolve(4), Promise.resolve(5)],
* toAsync,
* map(a => a + 10),
* filter(a => a % 2 === 0),
* toArray,
* ); // [12, 14]
* ```
*
* {@link https://codesandbox.io/s/fxts-toarray-fy84i | Try It}
*
* see {@link https://fxts.dev/docs/pipe | pipe}, {@link https://fxts.dev/docs/toAsync | toAsync},
* {@link https://fxts.dev/docs/map | map}, {@link https://fxts.dev/docs/filter | filter}
*/
// eslint-disable-next-line
// @ts-ignore
// prettier-ignore
function pipe<T1, R>(
a: T1,
f1: (a: Awaited<T1>) => R
): ReturnPipeType<[T1,R]>;
// prettier-ignore
function pipe<T1, T2, R>(
a: T1,
f1: (a: Awaited<T1>) => T2,
f2: (a: Awaited<T2>) => R
): ReturnPipeType<[T1, T2, R]>;
function pipe<T1, T2, T3, R>(
a: T1,
f1: (a: Awaited<T1>) => T2,
f2: (a: Awaited<T2>) => T3,
f3: (a: Awaited<T3>) => R,
): ReturnPipeType<[T1, T2, T3, R]>;
function pipe<T1, T2, T3, T4, R>(
a: T1,
f1: (a: Awaited<T1>) => T2,
f2: (a: Awaited<T2>) => T3,
f3: (a: Awaited<T3>) => T4,
f4: (a: Awaited<T4>) => R,
): ReturnPipeType<[T1, T2, T3, T4, R]>;
function pipe<T1, T2, T3, T4, T5, R>(
a: T1,
f1: (a: Awaited<T1>) => T2,
f2: (a: Awaited<T2>) => T3,
f3: (a: Awaited<T3>) => T4,
f4: (a: Awaited<T4>) => T5,
f5: (a: Awaited<T5>) => R,
): ReturnPipeType<[T1, T2, T3, T4, T5, R]>;
function pipe<T1, T2, T3, T4, T5, T6, R>(
a: T1,
f1: (a: Awaited<T1>) => T2,
f2: (a: Awaited<T2>) => T3,
f3: (a: Awaited<T3>) => T4,
f4: (a: Awaited<T4>) => T5,
f5: (a: Awaited<T5>) => T6,
f6: (a: Awaited<T6>) => R,
): ReturnPipeType<[T1, T2, T3, T4, T5, T6, R]>;
function pipe<T1, T2, T3, T4, T5, T6, T7, R>(
a: T1,
f1: (a: Awaited<T1>) => T2,
f2: (a: Awaited<T2>) => T3,
f3: (a: Awaited<T3>) => T4,
f4: (a: Awaited<T4>) => T5,
f5: (a: Awaited<T5>) => T6,
f6: (a: Awaited<T6>) => T7,
f7: (a: Awaited<T7>) => R,
): ReturnPipeType<[T1, T2, T3, T4, T5, T6, T7, R]>;
function pipe<T1, T2, T3, T4, T5, T6, T7, T8, R>(
a: T1,
f1: (a: Awaited<T1>) => T2,
f2: (a: Awaited<T2>) => T3,
f3: (a: Awaited<T3>) => T4,
f4: (a: Awaited<T4>) => T5,
f5: (a: Awaited<T5>) => T6,
f6: (a: Awaited<T6>) => T7,
f7: (a: Awaited<T7>) => T8,
f8: (a: Awaited<T8>) => R,
): ReturnPipeType<[T1, T2, T3, T4, T5, T6, T7, T8, R]>;
function pipe<T1, T2, T3, T4, T5, T6, T7, T8, T9, R>(
a: T1,
f1: (a: Awaited<T1>) => T2,
f2: (a: Awaited<T2>) => T3,
f3: (a: Awaited<T3>) => T4,
f4: (a: Awaited<T4>) => T5,
f5: (a: Awaited<T5>) => T6,
f6: (a: Awaited<T6>) => T7,
f7: (a: Awaited<T7>) => T8,
f8: (a: Awaited<T8>) => T9,
f9: (a: Awaited<T9>) => R,
): ReturnPipeType<[T1, T2, T3, T4, T5, T6, T7, T8, T9, R]>;
function pipe<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, R>(
a: T1,
f1: (a: Awaited<T1>) => T2,
f2: (a: Awaited<T2>) => T3,
f3: (a: Awaited<T3>) => T4,
f4: (a: Awaited<T4>) => T5,
f5: (a: Awaited<T5>) => T6,
f6: (a: Awaited<T6>) => T7,
f7: (a: Awaited<T7>) => T8,
f8: (a: Awaited<T8>) => T9,
f9: (a: Awaited<T9>) => T10,
f10: (a: Awaited<T10>) => R,
): ReturnPipeType<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, R]>;
function pipe<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, R>(
a: T1,
f1: (a: Awaited<T1>) => T2,
f2: (a: Awaited<T2>) => T3,
f3: (a: Awaited<T3>) => T4,
f4: (a: Awaited<T4>) => T5,
f5: (a: Awaited<T5>) => T6,
f6: (a: Awaited<T6>) => T7,
f7: (a: Awaited<T7>) => T8,
f8: (a: Awaited<T8>) => T9,
f9: (a: Awaited<T9>) => T10,
f10: (a: Awaited<T10>) => T11,
f11: (a: Awaited<T11>) => R,
): ReturnPipeType<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, R]>;
function pipe<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, R>(
a: T1,
f1: (a: Awaited<T1>) => T2,
f2: (a: Awaited<T2>) => T3,
f3: (a: Awaited<T3>) => T4,
f4: (a: Awaited<T4>) => T5,
f5: (a: Awaited<T5>) => T6,
f6: (a: Awaited<T6>) => T7,
f7: (a: Awaited<T7>) => T8,
f8: (a: Awaited<T8>) => T9,
f9: (a: Awaited<T9>) => T10,
f10: (a: Awaited<T10>) => T11,
f11: (a: Awaited<T11>) => T12,
f12: (a: Awaited<T12>) => R,
): ReturnPipeType<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, R]>;
function pipe<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, R>(
a: T1,
f1: (a: Awaited<T1>) => T2,
f2: (a: Awaited<T2>) => T3,
f3: (a: Awaited<T3>) => T4,
f4: (a: Awaited<T4>) => T5,
f5: (a: Awaited<T5>) => T6,
f6: (a: Awaited<T6>) => T7,
f7: (a: Awaited<T7>) => T8,
f8: (a: Awaited<T8>) => T9,
f9: (a: Awaited<T9>) => T10,
f10: (a: Awaited<T10>) => T11,
f11: (a: Awaited<T11>) => T12,
f12: (a: Awaited<T12>) => T13,
f13: (a: Awaited<T13>) => R,
): ReturnPipeType<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, R]>;
// prettier-ignore
function pipe<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, R>(
a: T1,
f1: (a: Awaited<T1>) => T2,
f2: (a: Awaited<T2>) => T3,
f3: (a: Awaited<T3>) => T4,
f4: (a: Awaited<T4>) => T5,
f5: (a: Awaited<T5>) => T6,
f6: (a: Awaited<T6>) => T7,
f7: (a: Awaited<T7>) => T8,
f8: (a: Awaited<T8>) => T9,
f9: (a: Awaited<T9>) => T10,
f10: (a: Awaited<T10>) => T11,
f11: (a: Awaited<T11>) => T12,
f12: (a: Awaited<T12>) => T13,
f13: (a: Awaited<T13>) => T14,
f14: (a: Awaited<T14>) => R,
): ReturnPipeType<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, R]>;
// prettier-ignore
function pipe<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, R>(
a: T1,
f1: (a: Awaited<T1>) => T2,
f2: (a: Awaited<T2>) => T3,
f3: (a: Awaited<T3>) => T4,
f4: (a: Awaited<T4>) => T5,
f5: (a: Awaited<T5>) => T6,
f6: (a: Awaited<T6>) => T7,
f7: (a: Awaited<T7>) => T8,
f8: (a: Awaited<T8>) => T9,
f9: (a: Awaited<T9>) => T10,
f10: (a: Awaited<T10>) => T11,
f11: (a: Awaited<T11>) => T12,
f12: (a: Awaited<T12>) => T13,
f13: (a: Awaited<T13>) => T14,
f14: (a: Awaited<T14>) => T15,
f15: (a: Awaited<T15>) => R,
): ReturnPipeType<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, R]>;
// prettier-ignore
function pipe<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, R>(
a: T1,
f1: (a: Awaited<T1>) => T2,
f2: (a: Awaited<T2>) => T3,
f3: (a: Awaited<T3>) => T4,
f4: (a: Awaited<T4>) => T5,
f5: (a: Awaited<T5>) => T6,
f6: (a: Awaited<T6>) => T7,
f7: (a: Awaited<T7>) => T8,
f8: (a: Awaited<T8>) => T9,
f9: (a: Awaited<T9>) => T10,
f10: (a: Awaited<T10>) => T11,
f11: (a: Awaited<T11>) => T12,
f12: (a: Awaited<T12>) => T13,
f13: (a: Awaited<T13>) => T14,
f14: (a: Awaited<T14>) => T15,
f15: (a: Awaited<T15>) => T16,
f16: (a: Awaited<T16>) => R,
): ReturnPipeType<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, R]>;
// prettier-ignore
function pipe<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, R>(
a: T1,
f1: (a: Awaited<T1>) => T2,
f2: (a: Awaited<T2>) => T3,
f3: (a: Awaited<T3>) => T4,
f4: (a: Awaited<T4>) => T5,
f5: (a: Awaited<T5>) => T6,
f6: (a: Awaited<T6>) => T7,
f7: (a: Awaited<T7>) => T8,
f8: (a: Awaited<T8>) => T9,
f9: (a: Awaited<T9>) => T10,
f10: (a: Awaited<T10>) => T11,
f11: (a: Awaited<T11>) => T12,
f12: (a: Awaited<T12>) => T13,
f13: (a: Awaited<T13>) => T14,
f14: (a: Awaited<T14>) => T15,
f15: (a: Awaited<T15>) => T16,
f16: (a: Awaited<T16>) => T17,
f17: (a: Awaited<T17>) => R,
): ReturnPipeType<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, R]>;
// prettier-ignore
function pipe<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, R>(
a: T1,
f1: (a: Awaited<T1>) => T2,
f2: (a: Awaited<T2>) => T3,
f3: (a: Awaited<T3>) => T4,
f4: (a: Awaited<T4>) => T5,
f5: (a: Awaited<T5>) => T6,
f6: (a: Awaited<T6>) => T7,
f7: (a: Awaited<T7>) => T8,
f8: (a: Awaited<T8>) => T9,
f9: (a: Awaited<T9>) => T10,
f10: (a: Awaited<T10>) => T11,
f11: (a: Awaited<T11>) => T12,
f12: (a: Awaited<T12>) => T13,
f13: (a: Awaited<T13>) => T14,
f14: (a: Awaited<T14>) => T15,
f15: (a: Awaited<T15>) => T16,
f16: (a: Awaited<T16>) => T17,
f17: (a: Awaited<T17>) => T18,
f18: (a: Awaited<T18>) => R,
): ReturnPipeType<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, R]>;
// prettier-ignore
function pipe<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, R>(
a: T1,
f1: (a: Awaited<T1>) => T2,
f2: (a: Awaited<T2>) => T3,
f3: (a: Awaited<T3>) => T4,
f4: (a: Awaited<T4>) => T5,
f5: (a: Awaited<T5>) => T6,
f6: (a: Awaited<T6>) => T7,
f7: (a: Awaited<T7>) => T8,
f8: (a: Awaited<T8>) => T9,
f9: (a: Awaited<T9>) => T10,
f10: (a: Awaited<T10>) => T11,
f11: (a: Awaited<T11>) => T12,
f12: (a: Awaited<T12>) => T13,
f13: (a: Awaited<T13>) => T14,
f14: (a: Awaited<T14>) => T15,
f15: (a: Awaited<T15>) => T16,
f16: (a: Awaited<T16>) => T17,
f17: (a: Awaited<T17>) => T18,
f18: (a: Awaited<T18>) => T19,
f19: (a: Awaited<T19>) => R,
): ReturnPipeType<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, R]>;
// prettier-ignore
function pipe<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, R>(
a: T1,
f1: (a: Awaited<T1>) => T2,
f2: (a: Awaited<T2>) => T3,
f3: (a: Awaited<T3>) => T4,
f4: (a: Awaited<T4>) => T5,
f5: (a: Awaited<T5>) => T6,
f6: (a: Awaited<T6>) => T7,
f7: (a: Awaited<T7>) => T8,
f8: (a: Awaited<T8>) => T9,
f9: (a: Awaited<T9>) => T10,
f10: (a: Awaited<T10>) => T11,
f11: (a: Awaited<T11>) => T12,
f12: (a: Awaited<T12>) => T13,
f13: (a: Awaited<T13>) => T14,
f14: (a: Awaited<T14>) => T15,
f15: (a: Awaited<T15>) => T16,
f16: (a: Awaited<T16>) => T17,
f17: (a: Awaited<T17>) => T18,
f18: (a: Awaited<T18>) => T19,
f19: (a: Awaited<T19>) => T20,
f20: (a: Awaited<T20>) => R,
): ReturnPipeType<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, R]>;
function pipe(a: any, ...fns: any[]) {
return reduce(pipe1, a, fns);
}
export default pipe; | the_stack |
export interface Translation {
notFound: NotFound
error: TranslationError
errorBoundary: ErrorBoundary
companies: TranslationCompanies
home: Home
application: Application
companySignup: CompanySignup
company: TranslationCompany
user: User
privacyPolicy: PrivacyPolicy
header: Header
footer: Footer
validation: TranslationValidation
routes: Routes
}
export interface Application {
title: string
noConnection: NoConnection
}
export interface NoConnection {
content: string
button: string
}
export interface TranslationCompanies {
name: string
title: string
intro: string
description: string
notes: Notes
FAQ: CompaniesFAQ
cta: CompaniesClass
}
export interface CompaniesFAQ {
title: string
items: PurpleItem[]
videos: Video[]
}
export interface PurpleItem {
label: string
contents: Array<string[] | string>
}
export interface Video {
id: string
label: string
url: string
}
export interface CompaniesClass {
label: string
content: string
}
export interface Notes {
label: string
items: string[]
disclaimer: string
}
export interface TranslationCompany {
congratulations: Congratulations
notQualified: NotQualified
signup: Signup
}
export interface Congratulations {
title: string
intro: string
description: string
button: string
contents: string[]
}
export interface NotQualified {
title: string
intro: string
description: string
conditions: string[]
caption: string
button: string
}
export interface Signup {
intro: string
form: SignupForm
}
export interface SignupForm {
validation: FormValidation
companyName: CompanyName
companySSN: CompanyName
companyDisplayName: CompanyDisplayName
serviceCategory: ServiceCategory
operation: Operation
operationsTrouble: GotPublicHelp
gotPublicHelp: GotPublicHelp
gotPublicHelpAmount: string
contact: Contact
submit: string
}
export interface CompanyDisplayName {
label: string
tooltip: string
}
export interface CompanyName {
label: string
}
export interface Contact {
label: string
name: string
email: string
generalEmail: string
webpage: string
phoneNumber: string
}
export interface GotPublicHelp {
positiveLabel: string
negativeLabel: string
label: string
tooltip: string
}
export interface Operation {
label: string
instructions: string[]
options: OperationOption[]
}
export interface OperationOption {
name: string
label: string
tooltip: string
}
export interface ServiceCategory {
label: string
placeholder: string
options: ServiceCategoryOption[]
}
export interface ServiceCategoryOption {
label: string
value: string
}
export interface FormValidation {
operations: string
operationsTrouble: string
}
export interface CompanySignup {
intro: string
form: CompanySignupForm
caption: string
}
export interface CompanySignupForm {
company: FormCompany
submit: string
}
export interface FormCompany {
label: string
placeholder: string
}
export interface TranslationError {
title: string
intro: string
introKennitalaIsNotAPerson: string
introUserNotOldEnough: string
button: string
}
export interface ErrorBoundary {
title: string
contents: string[]
}
export interface Footer {
topLinks: Link[]
bottomLinks: Link[]
}
export interface Link {
href: string
title: string
}
export interface Header {
logout: string
}
export interface Home {
name: string
title: string
intro: string
description: string[]
privacyPolicyButton: string
FAQ: HomeFAQ
cta: HomeCta
}
export interface HomeFAQ {
title: string
items: FluffyItem[]
}
export interface FluffyItem {
label: string
contents: string[]
}
export interface HomeCta {
users: CompaniesClass
companies: CompaniesClass
}
export interface NotFound {
title: string
content: string
button: string
}
export interface PrivacyPolicy {
title: string
sections: string[]
}
export interface Routes {
home: string
companies: RoutesCompanies
users: Users
privacyPolicy: string
}
export interface RoutesCompanies {
home: string
application: string
applicationSsn: string
}
export interface Users {
home: string
}
export interface User {
title: string
intro: string
appStore: AppStore
privacyPolicyButton: string
barcode: Barcode
mobileForm: MobileForm
confirmCodeForm: ConfirmCodeForm
}
export interface AppStore {
title: string
content: string
google: string
apple: string
}
export interface Barcode {
noGiftCards: string
title: string
intro: string
currentAmount: string
initialAmount: string
createButton: string
giveButton: string
fromPrefix: string
value: string
total: string
giveGiftCard: string
phoneNumberInput: string
messageInput: string
giveContinueButton: string
giftOverview: string
confirmGift: string
receiver: string
message: string
editButton: string
giveSubmitButton: string
successToastTitle: string
successToastText: string
errorToastTitle: string
errorToastText: string
expires: Expires
expired: string
new: string
backButton: string
error: BarcodeError
}
export interface BarcodeError {
title: string
message: string
backButton: string
}
export interface Expires {
pre: string
post: string
attention: string
disclaimer: string
}
export interface ConfirmCodeForm {
title: string
intro: string
noSMS: string
sendSMSButton: string
validation: Errors
errors: Errors
form: ConfirmCodeFormForm
}
export interface Errors {
confirmCode: string
}
export interface ConfirmCodeFormForm {
confirmCode: CompanyName
submit: string
}
export interface MobileForm {
title: string
intro: string
validation: MobileFormValidation
form: MobileFormForm
}
export interface MobileFormForm {
phoneNumber: CompanyName
confirmPhoneNumber: CompanyName
submit: string
}
export interface MobileFormValidation {
confirmPhoneNumber: string
}
export interface TranslationValidation {
required: string
phoneNumber: string
phoneNumberInvalid: string
email: string
webpage: string
}
// Converts JSON strings to/from your types
// and asserts the results of JSON.parse at runtime
export class Convert {
public static toTranslation(json: string): Translation {
return cast(JSON.parse(json), r('Translation'))
}
public static translationToJson(value: Translation): string {
return JSON.stringify(uncast(value, r('Translation')), null, 2)
}
}
function invalidValue(typ: any, val: any): never {
throw Error(
`Invalid value ${JSON.stringify(val)} for type ${JSON.stringify(typ)}`,
)
}
function jsonToJSProps(typ: any): any {
if (typ.jsonToJS === undefined) {
const map: any = {}
typ.props.forEach((p: any) => (map[p.json] = { key: p.js, typ: p.typ }))
typ.jsonToJS = map
}
return typ.jsonToJS
}
function jsToJSONProps(typ: any): any {
if (typ.jsToJSON === undefined) {
const map: any = {}
typ.props.forEach((p: any) => (map[p.js] = { key: p.json, typ: p.typ }))
typ.jsToJSON = map
}
return typ.jsToJSON
}
function transform(val: any, typ: any, getProps: any): any {
function transformPrimitive(typ: string, val: any): any {
if (typeof typ === typeof val) return val
return invalidValue(typ, val)
}
function transformUnion(typs: any[], val: any): any {
// val must validate against one typ in typs
const l = typs.length
for (let i = 0; i < l; i++) {
const typ = typs[i]
try {
return transform(val, typ, getProps)
} catch (_) {}
}
return invalidValue(typs, val)
}
function transformEnum(cases: string[], val: any): any {
if (cases.indexOf(val) !== -1) return val
return invalidValue(cases, val)
}
function transformArray(typ: any, val: any): any {
// val must be an array with no invalid elements
if (!Array.isArray(val)) return invalidValue('array', val)
return val.map((el) => transform(el, typ, getProps))
}
function transformDate(val: any): any {
if (val === null) {
return null
}
const d = new Date(val)
if (isNaN(d.valueOf())) {
return invalidValue('Date', val)
}
return d
}
function transformObject(
props: { [k: string]: any },
additional: any,
val: any,
): any {
if (val === null || typeof val !== 'object' || Array.isArray(val)) {
return invalidValue('object', val)
}
const result: any = {}
Object.getOwnPropertyNames(props).forEach((key) => {
const prop = props[key]
const v = Object.prototype.hasOwnProperty.call(val, key)
? val[key]
: undefined
result[prop.key] = transform(v, prop.typ, getProps)
})
Object.getOwnPropertyNames(val).forEach((key) => {
if (!Object.prototype.hasOwnProperty.call(props, key)) {
result[key] = transform(val[key], additional, getProps)
}
})
return result
}
if (typ === 'any') return val
if (typ === null) {
if (val === null) return val
return invalidValue(typ, val)
}
if (typ === false) return invalidValue(typ, val)
while (typeof typ === 'object' && typ.ref !== undefined) {
typ = typeMap[typ.ref]
}
if (Array.isArray(typ)) return transformEnum(typ, val)
if (typeof typ === 'object') {
return typ.hasOwnProperty('unionMembers')
? transformUnion(typ.unionMembers, val)
: typ.hasOwnProperty('arrayItems')
? transformArray(typ.arrayItems, val)
: typ.hasOwnProperty('props')
? transformObject(getProps(typ), typ.additional, val)
: invalidValue(typ, val)
}
// Numbers can be parsed by Date but shouldn't be.
if (typ === Date && typeof val !== 'number') return transformDate(val)
return transformPrimitive(typ, val)
}
function cast<T>(val: any, typ: any): T {
return transform(val, typ, jsonToJSProps)
}
function uncast<T>(val: T, typ: any): any {
return transform(val, typ, jsToJSONProps)
}
function a(typ: any) {
return { arrayItems: typ }
}
function u(...typs: any[]) {
return { unionMembers: typs }
}
function o(props: any[], additional: any) {
return { props, additional }
}
function m(additional: any) {
return { props: [], additional }
}
function r(name: string) {
return { ref: name }
}
const typeMap: any = {
Translation: o(
[
{ json: 'notFound', js: 'notFound', typ: r('NotFound') },
{ json: 'error', js: 'error', typ: r('TranslationError') },
{ json: 'errorBoundary', js: 'errorBoundary', typ: r('ErrorBoundary') },
{ json: 'companies', js: 'companies', typ: r('TranslationCompanies') },
{ json: 'home', js: 'home', typ: r('Home') },
{ json: 'application', js: 'application', typ: r('Application') },
{ json: 'companySignup', js: 'companySignup', typ: r('CompanySignup') },
{ json: 'company', js: 'company', typ: r('TranslationCompany') },
{ json: 'user', js: 'user', typ: r('User') },
{ json: 'privacyPolicy', js: 'privacyPolicy', typ: r('PrivacyPolicy') },
{ json: 'header', js: 'header', typ: r('Header') },
{ json: 'footer', js: 'footer', typ: r('Footer') },
{ json: 'validation', js: 'validation', typ: r('TranslationValidation') },
{ json: 'routes', js: 'routes', typ: r('Routes') },
],
false,
),
Application: o(
[
{ json: 'title', js: 'title', typ: '' },
{ json: 'noConnection', js: 'noConnection', typ: r('NoConnection') },
],
false,
),
NoConnection: o(
[
{ json: 'content', js: 'content', typ: '' },
{ json: 'button', js: 'button', typ: '' },
],
false,
),
TranslationCompanies: o(
[
{ json: 'name', js: 'name', typ: '' },
{ json: 'title', js: 'title', typ: '' },
{ json: 'intro', js: 'intro', typ: '' },
{ json: 'description', js: 'description', typ: '' },
{ json: 'notes', js: 'notes', typ: r('Notes') },
{ json: 'FAQ', js: 'FAQ', typ: r('CompaniesFAQ') },
{ json: 'cta', js: 'cta', typ: r('CompaniesClass') },
],
false,
),
CompaniesFAQ: o(
[
{ json: 'title', js: 'title', typ: '' },
{ json: 'items', js: 'items', typ: a(r('PurpleItem')) },
{ json: 'videos', js: 'videos', typ: a(r('Video')) },
],
false,
),
PurpleItem: o(
[
{ json: 'label', js: 'label', typ: '' },
{ json: 'contents', js: 'contents', typ: a(u(a(''), '')) },
],
false,
),
Video: o(
[
{ json: 'id', js: 'id', typ: '' },
{ json: 'label', js: 'label', typ: '' },
{ json: 'url', js: 'url', typ: '' },
],
false,
),
CompaniesClass: o(
[
{ json: 'label', js: 'label', typ: '' },
{ json: 'content', js: 'content', typ: '' },
],
false,
),
Notes: o(
[
{ json: 'label', js: 'label', typ: '' },
{ json: 'items', js: 'items', typ: a('') },
{ json: 'disclaimer', js: 'disclaimer', typ: '' },
],
false,
),
TranslationCompany: o(
[
{
json: 'congratulations',
js: 'congratulations',
typ: r('Congratulations'),
},
{ json: 'notQualified', js: 'notQualified', typ: r('NotQualified') },
{ json: 'signup', js: 'signup', typ: r('Signup') },
],
false,
),
Congratulations: o(
[
{ json: 'title', js: 'title', typ: '' },
{ json: 'intro', js: 'intro', typ: '' },
{ json: 'description', js: 'description', typ: '' },
{ json: 'button', js: 'button', typ: '' },
{ json: 'contents', js: 'contents', typ: a('') },
],
false,
),
NotQualified: o(
[
{ json: 'title', js: 'title', typ: '' },
{ json: 'intro', js: 'intro', typ: '' },
{ json: 'description', js: 'description', typ: '' },
{ json: 'conditions', js: 'conditions', typ: a('') },
{ json: 'caption', js: 'caption', typ: '' },
{ json: 'button', js: 'button', typ: '' },
],
false,
),
Signup: o(
[
{ json: 'intro', js: 'intro', typ: '' },
{ json: 'form', js: 'form', typ: r('SignupForm') },
],
false,
),
SignupForm: o(
[
{ json: 'validation', js: 'validation', typ: r('FormValidation') },
{ json: 'companyName', js: 'companyName', typ: r('CompanyName') },
{ json: 'companySSN', js: 'companySSN', typ: r('CompanyName') },
{
json: 'companyDisplayName',
js: 'companyDisplayName',
typ: r('CompanyDisplayName'),
},
{
json: 'serviceCategory',
js: 'serviceCategory',
typ: r('ServiceCategory'),
},
{ json: 'operation', js: 'operation', typ: r('Operation') },
{
json: 'operationsTrouble',
js: 'operationsTrouble',
typ: r('GotPublicHelp'),
},
{ json: 'gotPublicHelp', js: 'gotPublicHelp', typ: r('GotPublicHelp') },
{ json: 'gotPublicHelpAmount', js: 'gotPublicHelpAmount', typ: '' },
{ json: 'contact', js: 'contact', typ: r('Contact') },
{ json: 'submit', js: 'submit', typ: '' },
],
false,
),
CompanyDisplayName: o(
[
{ json: 'label', js: 'label', typ: '' },
{ json: 'tooltip', js: 'tooltip', typ: '' },
],
false,
),
CompanyName: o([{ json: 'label', js: 'label', typ: '' }], false),
Contact: o(
[
{ json: 'label', js: 'label', typ: '' },
{ json: 'name', js: 'name', typ: '' },
{ json: 'email', js: 'email', typ: '' },
{ json: 'generalEmail', js: 'generalEmail', typ: '' },
{ json: 'webpage', js: 'webpage', typ: '' },
{ json: 'phoneNumber', js: 'phoneNumber', typ: '' },
],
false,
),
GotPublicHelp: o(
[
{ json: 'positiveLabel', js: 'positiveLabel', typ: '' },
{ json: 'negativeLabel', js: 'negativeLabel', typ: '' },
{ json: 'label', js: 'label', typ: '' },
{ json: 'tooltip', js: 'tooltip', typ: '' },
],
false,
),
Operation: o(
[
{ json: 'label', js: 'label', typ: '' },
{ json: 'instructions', js: 'instructions', typ: a('') },
{ json: 'options', js: 'options', typ: a(r('OperationOption')) },
],
false,
),
OperationOption: o(
[
{ json: 'name', js: 'name', typ: '' },
{ json: 'label', js: 'label', typ: '' },
{ json: 'tooltip', js: 'tooltip', typ: '' },
],
false,
),
ServiceCategory: o(
[
{ json: 'label', js: 'label', typ: '' },
{ json: 'placeholder', js: 'placeholder', typ: '' },
{ json: 'options', js: 'options', typ: a(r('ServiceCategoryOption')) },
],
false,
),
ServiceCategoryOption: o(
[
{ json: 'label', js: 'label', typ: '' },
{ json: 'value', js: 'value', typ: '' },
],
false,
),
FormValidation: o(
[
{ json: 'operations', js: 'operations', typ: '' },
{ json: 'operationsTrouble', js: 'operationsTrouble', typ: '' },
],
false,
),
CompanySignup: o(
[
{ json: 'intro', js: 'intro', typ: '' },
{ json: 'form', js: 'form', typ: r('CompanySignupForm') },
{ json: 'caption', js: 'caption', typ: '' },
],
false,
),
CompanySignupForm: o(
[
{ json: 'company', js: 'company', typ: r('FormCompany') },
{ json: 'submit', js: 'submit', typ: '' },
],
false,
),
FormCompany: o(
[
{ json: 'label', js: 'label', typ: '' },
{ json: 'placeholder', js: 'placeholder', typ: '' },
],
false,
),
TranslationError: o(
[
{ json: 'title', js: 'title', typ: '' },
{ json: 'intro', js: 'intro', typ: '' },
{
json: 'introKennitalaIsNotAPerson',
js: 'introKennitalaIsNotAPerson',
typ: '',
},
{ json: 'introUserNotOldEnough', js: 'introUserNotOldEnough', typ: '' },
{ json: 'button', js: 'button', typ: '' },
],
false,
),
ErrorBoundary: o(
[
{ json: 'title', js: 'title', typ: '' },
{ json: 'contents', js: 'contents', typ: a('') },
],
false,
),
Footer: o(
[
{ json: 'topLinks', js: 'topLinks', typ: a(r('Link')) },
{ json: 'bottomLinks', js: 'bottomLinks', typ: a(r('Link')) },
],
false,
),
Link: o(
[
{ json: 'href', js: 'href', typ: '' },
{ json: 'title', js: 'title', typ: '' },
],
false,
),
Header: o([{ json: 'logout', js: 'logout', typ: '' }], false),
Home: o(
[
{ json: 'name', js: 'name', typ: '' },
{ json: 'title', js: 'title', typ: '' },
{ json: 'intro', js: 'intro', typ: '' },
{ json: 'description', js: 'description', typ: a('') },
{ json: 'privacyPolicyButton', js: 'privacyPolicyButton', typ: '' },
{ json: 'FAQ', js: 'FAQ', typ: r('HomeFAQ') },
{ json: 'cta', js: 'cta', typ: r('HomeCta') },
],
false,
),
HomeFAQ: o(
[
{ json: 'title', js: 'title', typ: '' },
{ json: 'items', js: 'items', typ: a(r('FluffyItem')) },
],
false,
),
FluffyItem: o(
[
{ json: 'label', js: 'label', typ: '' },
{ json: 'contents', js: 'contents', typ: a('') },
],
false,
),
HomeCta: o(
[
{ json: 'users', js: 'users', typ: r('CompaniesClass') },
{ json: 'companies', js: 'companies', typ: r('CompaniesClass') },
],
false,
),
NotFound: o(
[
{ json: 'title', js: 'title', typ: '' },
{ json: 'content', js: 'content', typ: '' },
{ json: 'button', js: 'button', typ: '' },
],
false,
),
PrivacyPolicy: o(
[
{ json: 'title', js: 'title', typ: '' },
{ json: 'sections', js: 'sections', typ: a('') },
],
false,
),
Routes: o(
[
{ json: 'home', js: 'home', typ: '' },
{ json: 'companies', js: 'companies', typ: r('RoutesCompanies') },
{ json: 'users', js: 'users', typ: r('Users') },
{ json: 'privacyPolicy', js: 'privacyPolicy', typ: '' },
],
false,
),
RoutesCompanies: o(
[
{ json: 'home', js: 'home', typ: '' },
{ json: 'application', js: 'application', typ: '' },
{ json: 'applicationSsn', js: 'applicationSsn', typ: '' },
],
false,
),
Users: o([{ json: 'home', js: 'home', typ: '' }], false),
User: o(
[
{ json: 'title', js: 'title', typ: '' },
{ json: 'intro', js: 'intro', typ: '' },
{ json: 'appStore', js: 'appStore', typ: r('AppStore') },
{ json: 'privacyPolicyButton', js: 'privacyPolicyButton', typ: '' },
{ json: 'barcode', js: 'barcode', typ: r('Barcode') },
{ json: 'mobileForm', js: 'mobileForm', typ: r('MobileForm') },
{
json: 'confirmCodeForm',
js: 'confirmCodeForm',
typ: r('ConfirmCodeForm'),
},
],
false,
),
AppStore: o(
[
{ json: 'title', js: 'title', typ: '' },
{ json: 'content', js: 'content', typ: '' },
{ json: 'google', js: 'google', typ: '' },
{ json: 'apple', js: 'apple', typ: '' },
],
false,
),
Barcode: o(
[
{ json: 'noGiftCards', js: 'noGiftCards', typ: '' },
{ json: 'title', js: 'title', typ: '' },
{ json: 'intro', js: 'intro', typ: '' },
{ json: 'currentAmount', js: 'currentAmount', typ: '' },
{ json: 'initialAmount', js: 'initialAmount', typ: '' },
{ json: 'createButton', js: 'createButton', typ: '' },
{ json: 'giveButton', js: 'giveButton', typ: '' },
{ json: 'fromPrefix', js: 'fromPrefix', typ: '' },
{ json: 'value', js: 'value', typ: '' },
{ json: 'total', js: 'total', typ: '' },
{ json: 'giveGiftCard', js: 'giveGiftCard', typ: '' },
{ json: 'phoneNumberInput', js: 'phoneNumberInput', typ: '' },
{ json: 'messageInput', js: 'messageInput', typ: '' },
{ json: 'giveContinueButton', js: 'giveContinueButton', typ: '' },
{ json: 'giftOverview', js: 'giftOverview', typ: '' },
{ json: 'confirmGift', js: 'confirmGift', typ: '' },
{ json: 'receiver', js: 'receiver', typ: '' },
{ json: 'message', js: 'message', typ: '' },
{ json: 'editButton', js: 'editButton', typ: '' },
{ json: 'giveSubmitButton', js: 'giveSubmitButton', typ: '' },
{ json: 'successToastTitle', js: 'successToastTitle', typ: '' },
{ json: 'successToastText', js: 'successToastText', typ: '' },
{ json: 'errorToastTitle', js: 'errorToastTitle', typ: '' },
{ json: 'errorToastText', js: 'errorToastText', typ: '' },
{ json: 'expires', js: 'expires', typ: r('Expires') },
{ json: 'expired', js: 'expired', typ: '' },
{ json: 'new', js: 'new', typ: '' },
{ json: 'backButton', js: 'backButton', typ: '' },
{ json: 'error', js: 'error', typ: r('BarcodeError') },
],
false,
),
BarcodeError: o(
[
{ json: 'title', js: 'title', typ: '' },
{ json: 'message', js: 'message', typ: '' },
{ json: 'backButton', js: 'backButton', typ: '' },
],
false,
),
Expires: o(
[
{ json: 'pre', js: 'pre', typ: '' },
{ json: 'post', js: 'post', typ: '' },
{ json: 'attention', js: 'attention', typ: '' },
{ json: 'disclaimer', js: 'disclaimer', typ: '' },
],
false,
),
ConfirmCodeForm: o(
[
{ json: 'title', js: 'title', typ: '' },
{ json: 'intro', js: 'intro', typ: '' },
{ json: 'noSMS', js: 'noSMS', typ: '' },
{ json: 'sendSMSButton', js: 'sendSMSButton', typ: '' },
{ json: 'validation', js: 'validation', typ: r('Errors') },
{ json: 'errors', js: 'errors', typ: r('Errors') },
{ json: 'form', js: 'form', typ: r('ConfirmCodeFormForm') },
],
false,
),
Errors: o([{ json: 'confirmCode', js: 'confirmCode', typ: '' }], false),
ConfirmCodeFormForm: o(
[
{ json: 'confirmCode', js: 'confirmCode', typ: r('CompanyName') },
{ json: 'submit', js: 'submit', typ: '' },
],
false,
),
MobileForm: o(
[
{ json: 'title', js: 'title', typ: '' },
{ json: 'intro', js: 'intro', typ: '' },
{ json: 'validation', js: 'validation', typ: r('MobileFormValidation') },
{ json: 'form', js: 'form', typ: r('MobileFormForm') },
],
false,
),
MobileFormForm: o(
[
{ json: 'phoneNumber', js: 'phoneNumber', typ: r('CompanyName') },
{
json: 'confirmPhoneNumber',
js: 'confirmPhoneNumber',
typ: r('CompanyName'),
},
{ json: 'submit', js: 'submit', typ: '' },
],
false,
),
MobileFormValidation: o(
[{ json: 'confirmPhoneNumber', js: 'confirmPhoneNumber', typ: '' }],
false,
),
TranslationValidation: o(
[
{ json: 'required', js: 'required', typ: '' },
{ json: 'phoneNumber', js: 'phoneNumber', typ: '' },
{ json: 'phoneNumberInvalid', js: 'phoneNumberInvalid', typ: '' },
{ json: 'email', js: 'email', typ: '' },
{ json: 'webpage', js: 'webpage', typ: '' },
],
false,
),
} | the_stack |
import {CATEGORY_GL} from './Category';
import {FloatToIntGlNode, IntToFloatGlNode, IntToBoolGlNode, BoolToIntGlNode} from '../../../nodes/gl/_ConversionMisc';
import {FloatToVec2GlNode, FloatToVec3GlNode, FloatToVec4GlNode} from '../../../nodes/gl/_ConversionToVec';
import {
Vec2ToFloatGlNode,
Vec3ToFloatGlNode,
Vec4ToFloatGlNode,
Vec4ToVec3GlNode,
Vec3ToVec4GlNode,
Vec3ToVec2GlNode,
Vec2ToVec3GlNode,
} from '../../../nodes/gl/_ConversionVecTo';
import {
AbsGlNode,
AcosGlNode,
AsinGlNode,
AtanGlNode,
CeilGlNode,
CosGlNode,
DegreesGlNode,
ExpGlNode,
Exp2GlNode,
FloorGlNode,
FractGlNode,
InverseSqrtGlNode,
LogGlNode,
Log2GlNode,
NormalizeGlNode,
RadiansGlNode,
SignGlNode,
SinGlNode,
SqrtGlNode,
TanGlNode,
} from '../../../nodes/gl/_Math_Arg1';
import {
DistanceGlNode,
DotGlNode,
MaxGlNode,
MinGlNode,
ModGlNode,
PowGlNode,
ReflectGlNode,
StepGlNode,
} from '../../../nodes/gl/_Math_Arg2';
import {ClampGlNode, FaceforwardGlNode, SmoothstepGlNode} from '../../../nodes/gl/_Math_Arg3';
import {AddGlNode, DivideGlNode, MultGlNode, SubstractGlNode} from '../../../nodes/gl/_Math_Arg2Operation';
import {AndGlNode, OrGlNode} from '../../../nodes/gl/_Math_Arg2Boolean';
import {AccelerationGlNode} from '../../../nodes/gl/Acceleration';
import {AlignGlNode} from '../../../nodes/gl/Align';
import {AttributeGlNode} from '../../../nodes/gl/Attribute';
import {ColorCorrectGlNode} from '../../../nodes/gl/ColorCorrect';
import {CompareGlNode} from '../../../nodes/gl/Compare';
import {ComplementGlNode} from '../../../nodes/gl/Complement';
import {ConstantGlNode} from '../../../nodes/gl/Constant';
import {CrossGlNode} from '../../../nodes/gl/Cross';
import {CycleGlNode} from '../../../nodes/gl/Cycle';
import {DiskGlNode} from '../../../nodes/gl/Disk';
import {EasingGlNode} from '../../../nodes/gl/Easing';
import {FitGlNode, FitTo01GlNode, FitFrom01GlNode, FitFrom01ToVarianceGlNode} from '../../../nodes/gl/Fit';
import {FogGlNode} from '../../../nodes/gl/Fog';
import {ForLoopGlNode} from '../../../nodes/gl/ForLoop';
import {GlobalsGlNode} from '../../../nodes/gl/Globals';
import {HsluvToRgbGlNode} from '../../../nodes/gl/HsluvToRgb';
import {HsvToRgbGlNode} from '../../../nodes/gl/HsvToRgb';
import {IfThenGlNode} from '../../../nodes/gl/IfThen';
import {ImpostorUvGlNode} from '../../../nodes/gl/ImpostorUv';
import {InstanceTransformGlNode} from '../../../nodes/gl/InstanceTransform';
// import {LabToRgbGlNode} from '../../../nodes/gl/LabToRgb'; // TODO: still need work, not looking good
// import {LchToRgbGlNode} from '../../../nodes/gl/LchToRgb'; // TODO: still need work, not looking good
import {LengthGlNode} from '../../../nodes/gl/Length';
import {LuminanceGlNode} from '../../../nodes/gl/Luminance';
import {MaxLengthGlNode} from '../../../nodes/gl/MaxLength';
import {MixGlNode} from '../../../nodes/gl/Mix';
import {ModelViewMatrixMultGlNode} from '../../../nodes/gl/ModelViewMatrixMult';
import {MultAddGlNode} from '../../../nodes/gl/MultAdd';
import {NegateGlNode} from '../../../nodes/gl/Negate';
import {NoiseGlNode} from '../../../nodes/gl/Noise';
import {NullGlNode} from '../../../nodes/gl/Null';
import {OutputGlNode} from '../../../nodes/gl/Output';
import {ParamGlNode} from '../../../nodes/gl/Param';
import {RefractGlNode} from '../../../nodes/gl/Refract';
import {SSSModelGlNode} from '../../../nodes/gl/SSSModel';
import {QuatMultGlNode} from '../../../nodes/gl/QuatMult';
import {QuatFromAxisAngleGlNode} from '../../../nodes/gl/QuatFromAxisAngle';
import {QuatToAngleGlNode} from '../../../nodes/gl/QuatToAngle';
import {QuatToAxisGlNode} from '../../../nodes/gl/QuatToAxis';
import {RampGlNode} from '../../../nodes/gl/Ramp';
import {RandomGlNode} from '../../../nodes/gl/Random';
import {RgbToHsvGlNode} from '../../../nodes/gl/RgbToHsv';
import {RotateGlNode} from '../../../nodes/gl/Rotate';
import {RoundGlNode} from '../../../nodes/gl/Round';
import {SphereGlNode} from '../../../nodes/gl/Sphere';
import {SubnetGlNode} from '../../../nodes/gl/Subnet';
import {SubnetInputGlNode} from '../../../nodes/gl/SubnetInput';
import {SubnetOutputGlNode} from '../../../nodes/gl/SubnetOutput';
import {SwitchGlNode} from '../../../nodes/gl/Switch';
import {TextureGlNode} from '../../../nodes/gl/Texture';
import {ToWorldSpaceGlNode} from '../../../nodes/gl/ToWorldSpace';
import {TwoWaySwitchGlNode} from '../../../nodes/gl/TwoWaySwitch';
import {VaryingWriteGlNode} from '../../../nodes/gl/VaryingWrite';
import {VaryingReadGlNode} from '../../../nodes/gl/VaryingRead';
import {VectorAlignGlNode} from '../../../nodes/gl/VectorAlign';
import {VectorAngleGlNode} from '../../../nodes/gl/VectorAngle';
export interface GlNodeChildrenMap {
abs: AbsGlNode;
acceleration: AccelerationGlNode;
acos: AcosGlNode;
add: AddGlNode;
align: AlignGlNode;
and: AndGlNode;
asin: AsinGlNode;
atan: AtanGlNode;
attribute: AttributeGlNode;
boolToInt: BoolToIntGlNode;
ceil: CeilGlNode;
clamp: ClampGlNode;
colorCorrect: ColorCorrectGlNode;
compare: CompareGlNode;
complement: ComplementGlNode;
constant: ConstantGlNode;
cos: CosGlNode;
cross: CrossGlNode;
cycle: CycleGlNode;
degrees: DegreesGlNode;
disk: DiskGlNode;
distance: DistanceGlNode;
divide: DivideGlNode;
dot: DotGlNode;
easing: EasingGlNode;
exp: ExpGlNode;
exp2: Exp2GlNode;
faceForward: FaceforwardGlNode;
fit: FitGlNode;
fitTo01: FitTo01GlNode;
fitFrom01: FitFrom01GlNode;
fitFrom01ToVariance: FitFrom01ToVarianceGlNode;
floatToInt: FloatToIntGlNode;
floatToVec2: FloatToVec2GlNode;
floatToVec3: FloatToVec3GlNode;
floatToVec4: FloatToVec4GlNode;
floor: FloorGlNode;
fract: FractGlNode;
fog: FogGlNode;
forLoop: ForLoopGlNode;
globals: GlobalsGlNode;
hsluvToRgb: HsluvToRgbGlNode;
hsvToRgb: HsvToRgbGlNode;
ifThen: IfThenGlNode;
impostorUv: ImpostorUvGlNode;
intToBool: IntToBoolGlNode;
intToFloat: IntToFloatGlNode;
inverseSqrt: InverseSqrtGlNode;
instanceTransform: InstanceTransformGlNode;
// lab_to_rgb: LabToRgbGlNode;
// lch_to_rgb: LchToRgbGlNode;
length: LengthGlNode;
log: LogGlNode;
log2: Log2GlNode;
luminance: LuminanceGlNode;
max: MaxGlNode;
maxLength: MaxLengthGlNode;
min: MinGlNode;
mix: MixGlNode;
mod: ModGlNode;
modelViewMatrixMult: ModelViewMatrixMultGlNode;
mult: MultGlNode;
multAdd: MultAddGlNode;
negate: NegateGlNode;
noise: NoiseGlNode;
normalize: NormalizeGlNode;
null: NullGlNode;
or: OrGlNode;
output: OutputGlNode;
param: ParamGlNode;
pow: PowGlNode;
quatMult: QuatMultGlNode;
quatFromAxisAngle: QuatFromAxisAngleGlNode;
quatToAngle: QuatToAngleGlNode;
quatToAxis: QuatToAxisGlNode;
radians: RadiansGlNode;
ramp: RampGlNode;
random: RandomGlNode;
reflect: ReflectGlNode;
refract: RefractGlNode;
rgbToHsv: RgbToHsvGlNode;
rotate: RotateGlNode;
round: RoundGlNode;
sign: SignGlNode;
sin: SinGlNode;
smoothstep: SmoothstepGlNode;
sphere: SphereGlNode;
sqrt: SqrtGlNode;
SSSModel: SSSModelGlNode;
step: StepGlNode;
subnet: SubnetGlNode;
subnetInput: SubnetInputGlNode;
subnetOutput: SubnetOutputGlNode;
substract: SubstractGlNode;
switch: SwitchGlNode;
tan: TanGlNode;
texture: TextureGlNode;
toWorldSpace: ToWorldSpaceGlNode;
twoWaySwitch: TwoWaySwitchGlNode;
varyingWrite: VaryingWriteGlNode;
varyingRead: VaryingReadGlNode;
vec2ToFloat: Vec2ToFloatGlNode;
vec2ToVec3: Vec2ToVec3GlNode;
vec3ToFloat: Vec3ToFloatGlNode;
vec3ToVec2: Vec3ToVec2GlNode;
vec3ToVec4: Vec3ToVec4GlNode;
vec4ToFloat: Vec4ToFloatGlNode;
vec4ToVec3: Vec4ToVec3GlNode;
vectorAlign: VectorAlignGlNode;
vectorAngle: VectorAngleGlNode;
}
import {NodeContext} from '../../NodeContext';
import {PolyEngine} from '../../../Poly';
const SUBNET_CHILD_OPTION = {
only: [
`${IfThenGlNode.context()}/${IfThenGlNode.type()}`,
`${SubnetGlNode.context()}/${SubnetGlNode.type()}`,
`${ForLoopGlNode.context()}/${ForLoopGlNode.type()}`,
],
};
export class GlRegister {
static run(poly: PolyEngine) {
poly.registerNode(AbsGlNode, CATEGORY_GL.MATH);
poly.registerNode(AccelerationGlNode, CATEGORY_GL.PHYSICS);
poly.registerNode(AcosGlNode, CATEGORY_GL.TRIGO);
poly.registerNode(AddGlNode, CATEGORY_GL.MATH);
poly.registerNode(AlignGlNode, CATEGORY_GL.TRIGO);
poly.registerNode(AndGlNode, CATEGORY_GL.LOGIC);
poly.registerNode(AsinGlNode, CATEGORY_GL.TRIGO);
poly.registerNode(AtanGlNode, CATEGORY_GL.TRIGO);
poly.registerNode(AttributeGlNode, CATEGORY_GL.GLOBALS, {except: [`${NodeContext.COP}/builder`]});
poly.registerNode(BoolToIntGlNode, CATEGORY_GL.CONVERSION);
poly.registerNode(CeilGlNode, CATEGORY_GL.MATH);
poly.registerNode(ClampGlNode, CATEGORY_GL.MATH);
poly.registerNode(ColorCorrectGlNode, CATEGORY_GL.COLOR);
poly.registerNode(CompareGlNode, CATEGORY_GL.LOGIC);
poly.registerNode(ComplementGlNode, CATEGORY_GL.MATH);
poly.registerNode(ConstantGlNode, CATEGORY_GL.GLOBALS);
poly.registerNode(CosGlNode, CATEGORY_GL.TRIGO);
poly.registerNode(CrossGlNode, CATEGORY_GL.GEOMETRY);
poly.registerNode(CycleGlNode, CATEGORY_GL.MATH);
poly.registerNode(DegreesGlNode, CATEGORY_GL.CONVERSION);
poly.registerNode(DiskGlNode, CATEGORY_GL.GEOMETRY);
poly.registerNode(DistanceGlNode, CATEGORY_GL.GEOMETRY);
poly.registerNode(DivideGlNode, CATEGORY_GL.MATH);
poly.registerNode(DotGlNode, CATEGORY_GL.GEOMETRY);
poly.registerNode(EasingGlNode, CATEGORY_GL.MATH);
poly.registerNode(ExpGlNode, CATEGORY_GL.MATH);
poly.registerNode(Exp2GlNode, CATEGORY_GL.MATH);
poly.registerNode(FaceforwardGlNode, CATEGORY_GL.GEOMETRY);
poly.registerNode(FitGlNode, CATEGORY_GL.MATH);
poly.registerNode(FitTo01GlNode, CATEGORY_GL.MATH);
poly.registerNode(FitFrom01GlNode, CATEGORY_GL.MATH);
poly.registerNode(FitFrom01ToVarianceGlNode, CATEGORY_GL.MATH);
poly.registerNode(FloatToIntGlNode, CATEGORY_GL.CONVERSION);
poly.registerNode(FloatToVec2GlNode, CATEGORY_GL.CONVERSION);
poly.registerNode(FloatToVec3GlNode, CATEGORY_GL.CONVERSION);
poly.registerNode(FloatToVec4GlNode, CATEGORY_GL.CONVERSION);
poly.registerNode(FloorGlNode, CATEGORY_GL.MATH);
poly.registerNode(FogGlNode, CATEGORY_GL.COLOR);
poly.registerNode(ForLoopGlNode, CATEGORY_GL.LOGIC);
poly.registerNode(FractGlNode, CATEGORY_GL.MATH);
poly.registerNode(GlobalsGlNode, CATEGORY_GL.GLOBALS);
poly.registerNode(HsluvToRgbGlNode, CATEGORY_GL.COLOR);
poly.registerNode(HsvToRgbGlNode, CATEGORY_GL.COLOR);
poly.registerNode(IfThenGlNode, CATEGORY_GL.LOGIC);
poly.registerNode(ImpostorUvGlNode, CATEGORY_GL.UTIL);
poly.registerNode(IntToBoolGlNode, CATEGORY_GL.CONVERSION);
poly.registerNode(IntToFloatGlNode, CATEGORY_GL.CONVERSION);
poly.registerNode(InverseSqrtGlNode, CATEGORY_GL.MATH);
poly.registerNode(InstanceTransformGlNode, CATEGORY_GL.GEOMETRY);
// poly.registerNode(LabToRgbGlNode, CATEGORY_GL.COLOR);
// poly.registerNode(LchToRgbGlNode, CATEGORY_GL.COLOR);
poly.registerNode(LengthGlNode, CATEGORY_GL.GEOMETRY);
poly.registerNode(LuminanceGlNode, CATEGORY_GL.COLOR);
poly.registerNode(LogGlNode, CATEGORY_GL.MATH);
poly.registerNode(Log2GlNode, CATEGORY_GL.MATH);
poly.registerNode(MaxGlNode, CATEGORY_GL.MATH);
poly.registerNode(MaxLengthGlNode, CATEGORY_GL.MATH);
poly.registerNode(MinGlNode, CATEGORY_GL.MATH);
poly.registerNode(ModGlNode, CATEGORY_GL.MATH);
poly.registerNode(ModelViewMatrixMultGlNode, CATEGORY_GL.MATH);
poly.registerNode(MixGlNode, CATEGORY_GL.MATH);
poly.registerNode(MultGlNode, CATEGORY_GL.MATH);
poly.registerNode(MultAddGlNode, CATEGORY_GL.MATH);
poly.registerNode(NegateGlNode, CATEGORY_GL.MATH);
poly.registerNode(NullGlNode, CATEGORY_GL.UTIL);
poly.registerNode(NoiseGlNode, CATEGORY_GL.GEOMETRY);
poly.registerNode(NormalizeGlNode, CATEGORY_GL.MATH);
poly.registerNode(OrGlNode, CATEGORY_GL.LOGIC);
poly.registerNode(OutputGlNode, CATEGORY_GL.GLOBALS);
poly.registerNode(ParamGlNode, CATEGORY_GL.GLOBALS);
poly.registerNode(PowGlNode, CATEGORY_GL.MATH);
poly.registerNode(QuatMultGlNode, CATEGORY_GL.QUAT);
poly.registerNode(QuatFromAxisAngleGlNode, CATEGORY_GL.QUAT);
poly.registerNode(QuatToAngleGlNode, CATEGORY_GL.QUAT);
poly.registerNode(QuatToAxisGlNode, CATEGORY_GL.QUAT);
poly.registerNode(RampGlNode, CATEGORY_GL.GLOBALS);
poly.registerNode(RandomGlNode, CATEGORY_GL.GLOBALS);
poly.registerNode(RadiansGlNode, CATEGORY_GL.CONVERSION);
poly.registerNode(ReflectGlNode, CATEGORY_GL.GEOMETRY);
poly.registerNode(RefractGlNode, CATEGORY_GL.GEOMETRY);
poly.registerNode(RgbToHsvGlNode, CATEGORY_GL.COLOR);
poly.registerNode(RotateGlNode, CATEGORY_GL.GEOMETRY);
poly.registerNode(RoundGlNode, CATEGORY_GL.MATH);
poly.registerNode(SignGlNode, CATEGORY_GL.MATH);
poly.registerNode(SinGlNode, CATEGORY_GL.TRIGO);
poly.registerNode(SmoothstepGlNode, CATEGORY_GL.MATH);
poly.registerNode(SphereGlNode, CATEGORY_GL.GEOMETRY);
poly.registerNode(SqrtGlNode, CATEGORY_GL.MATH);
poly.registerNode(SSSModelGlNode, CATEGORY_GL.LIGHTING);
poly.registerNode(StepGlNode, CATEGORY_GL.GEOMETRY);
poly.registerNode(SubnetGlNode, CATEGORY_GL.LOGIC);
poly.registerNode(SubnetInputGlNode, CATEGORY_GL.LOGIC, SUBNET_CHILD_OPTION);
poly.registerNode(SubnetOutputGlNode, CATEGORY_GL.LOGIC, SUBNET_CHILD_OPTION);
poly.registerNode(SubstractGlNode, CATEGORY_GL.MATH);
poly.registerNode(SwitchGlNode, CATEGORY_GL.LOGIC);
poly.registerNode(TanGlNode, CATEGORY_GL.TRIGO);
poly.registerNode(TextureGlNode, CATEGORY_GL.COLOR);
poly.registerNode(ToWorldSpaceGlNode, CATEGORY_GL.GLOBALS);
poly.registerNode(TwoWaySwitchGlNode, CATEGORY_GL.LOGIC);
poly.registerNode(VaryingWriteGlNode, CATEGORY_GL.GLOBALS);
poly.registerNode(VaryingReadGlNode, CATEGORY_GL.GLOBALS);
poly.registerNode(Vec2ToFloatGlNode, CATEGORY_GL.CONVERSION);
poly.registerNode(Vec2ToVec3GlNode, CATEGORY_GL.CONVERSION);
poly.registerNode(Vec3ToFloatGlNode, CATEGORY_GL.CONVERSION);
poly.registerNode(Vec3ToVec2GlNode, CATEGORY_GL.CONVERSION);
poly.registerNode(Vec3ToVec4GlNode, CATEGORY_GL.CONVERSION);
poly.registerNode(Vec4ToFloatGlNode, CATEGORY_GL.CONVERSION);
poly.registerNode(Vec4ToVec3GlNode, CATEGORY_GL.CONVERSION);
poly.registerNode(VectorAlignGlNode, CATEGORY_GL.GEOMETRY);
poly.registerNode(VectorAngleGlNode, CATEGORY_GL.GEOMETRY);
}
} | the_stack |
import * as React from 'react';
import { IConfiguration, Strategies } from '../../../common/types';
import DataMap from '../../organisms/datamap/Component';
import SimulationSummary from '../../molecules/simulation-summary/Component';
import AttackSummary from '../../molecules/attack-summary/Component';
import TransactionSummary from '../../molecules/transaction-summary/Component';
import BlockTree from '../../molecules/block-tree/Component';
import SimulationEvents from '../../molecules/simulation-events/Component';
import Button from '../../atoms/button/Component';
import fetchEvents, { ISimulationPayload } from './fetchSimulationPayload';
import EventsRange from '../../molecules/events-range/Component';
import { Chart } from 'react-google-charts';
import { EventTypes } from '../../molecules/simulation-events/types';
import FloodAttackSummary from '../../molecules/flood-attack-summary/Component';
// Uncaught Error: Google Charts loader.js can only be loaded once.
// This error seems to be on the side of the package.
// https://github.com/rakannimer/react-google-charts/issues/195
interface ISimulationState {
selectedIndex?: number;
moveIntoViewPort: boolean;
simulationPayload?: ISimulationPayload;
isFetching: boolean;
}
interface ISimulationProps extends IConfiguration {
[index: string]: any;
onNewSimulation: () => void;
}
export default class Simulation extends React.Component<ISimulationProps, ISimulationState> {
private static transactionConfirmationStatusPerFee(simulationPayload: ISimulationPayload) {
const multi: any[][] = [['Transaction Fees', 'Confirmed Transactions', 'Unconfirmed Transactions']];
for (const transaction of simulationPayload.transactions) {
for (let j = 0; j < multi.length; j += 1) {
if (multi[j][0] === transaction.transactionFee) {
if (transaction.confirmation) {
multi[j][1] += 1;
} else {
multi[j][2] += 1;
}
break;
} else if (j === multi.length - 1) {
if (transaction.confirmation) {
multi.push([transaction.transactionFee, 1, 0]);
} else {
multi.push([transaction.transactionFee, 0, 1]);
}
}
}
}
return multi;
}
private static confirmationTime(simulationPayload: ISimulationPayload) {
const multi: number[][] = [[]];
for (const transaction of simulationPayload.transactions) {
for (let j = 0; j < multi.length; j += 1) {
if (multi[j][0] === transaction.transactionFee) {
if (transaction.confirmation) {
multi[j][1] += 1;
multi[j][2] = multi[j][2]
+ transaction.confirmationLevel
- transaction.creationLevel;
}
break;
} else if (j === multi.length - 1) {
multi.push([transaction.transactionFee, 1, 0]);
}
}
}
multi.shift(); // don't know better a way to get rid of empty element at the beginning
const multi2: any[][] = [['Transaction Fees', 'Confirmation Time']];
for (const item of multi) {
multi2.push([item[0], Math.round(item[2] / item[1] * 100) / 100]);
}
return multi2;
}
private static timeBetweenBlocks(simulationPayload: any) {
const multi: any[][] = [['Blocks', 'Time'], [1,
(new Date(simulationPayload.events[0].timestamp).getTime() -
new Date(simulationPayload.simulationStart).getTime()) / 1000 / 60]];
for (let i = 1; i < simulationPayload.events.length; i += 1) {
if (simulationPayload.events[i].eventType === EventTypes.IBlockMine) {
multi.push([simulationPayload.events[i].level + 1,
(new Date(simulationPayload.events[i].timestamp).getTime()
- new Date(simulationPayload.events[i - 1].timestamp).getTime()) / 1000 / 60]);
}
}
return multi;
}
constructor(props: ISimulationProps) {
super(props);
this.state = { moveIntoViewPort: false, isFetching: false };
this.handleSelectIndex = this.handleSelectIndex.bind(this);
this.fetchEvents = this.fetchEvents.bind(this);
}
public render() {
const { simulationPayload, selectedIndex, moveIntoViewPort, isFetching } = this.state;
if (this.props.strategy === 'BITCOIN_LIKE_BLOCKCHAIN') {
return (
<div className="simulation">
<div className="simulation__grid">
<div className="simulation__map u-plate">
<div className="simulation__title">
Simulation
</div>
<DataMap
event={(simulationPayload && selectedIndex !== undefined)
? simulationPayload.events[selectedIndex]
: undefined}
/>
<EventsRange
events={simulationPayload ? simulationPayload.events : undefined}
selectedIndex={selectedIndex}
onSelectIndex={this.handleSelectIndex}
/>
</div>
<div className="simulation__summary u-plate">
<div className="simulation-summary__title">
Summary
</div>
{simulationPayload && (
<SimulationSummary
duration={simulationPayload.duration}
longestChainLength={simulationPayload.longestChainLength}
longestChainSize={simulationPayload.longestChainSize}
longestChainNumberTransactions={simulationPayload.longestChainNumberTransactions}
timesWithOutliers10={simulationPayload.timesWithOutliers10}
timesWithOutliers50={simulationPayload.timesWithOutliers50}
timesWithOutliers90={simulationPayload.timesWithOutliers90}
timesNoOutliers10={simulationPayload.timesNoOutliers10}
timesNoOutliers50={simulationPayload.timesNoOutliers50}
timesNoOutliers90={simulationPayload.timesNoOutliers90}
firstBlockNumberOfRecipients={simulationPayload.firstBlockNumberOfRecipients}
lastBlockNumberOfRecipients={simulationPayload.lastBlockNumberOfRecipients}
totalNumberOfNodes={simulationPayload.totalNumberOfNodes}
staleBlocks={simulationPayload.staleBlocks}
strategy={this.props.strategy}
avgBlockTime={simulationPayload.avgBlockTime}
/>
)}
</div>
<div className="simulation__events u-plate">
<SimulationEvents
events={simulationPayload ? simulationPayload.events : undefined}
selectedIndex={selectedIndex}
onSelectIndex={this.handleSelectIndex}
moveIntoViewPort={moveIntoViewPort}
strategy={this.props.strategy}
/>
</div>
</div>
<div className="simulation__buttons">
<div>
<Button
className="simulation__button"
title="New Simulation"
onClick={() => {
this.setState({ simulationPayload: undefined });
this.props.onNewSimulation();
}}
active={true}
/>
</div>
{!isFetching && (
<div>
<Button
className="simulation__button"
title="START"
onClick={this.fetchEvents}
active={true}
/>
</div>
)}
{isFetching && (
<div>
<div className="u-loader">Loading...</div>
</div>
)}
</div>
{this.props.hashRate > 0 ?
<div className="attack__grid">
<div className="attack__summary u-plate">
<div className="attack-summary__title">
Attack Summary
</div>
{simulationPayload && (
<AttackSummary
attackSucceeded={simulationPayload.attackSucceeded}
successfulAttackInBlocks={simulationPayload.successfulAttackInBlocks}
probabilityOfSuccessfulAttack={simulationPayload.probabilityOfSuccessfulAttack}
maximumSafeTransactionValue={simulationPayload.maximumSafeTransactionValue}
hashRate={this.props.hashRate}
confirmations={this.props.confirmations}
B={simulationPayload.B}
o={simulationPayload.o}
alpha={simulationPayload.alpha}
k={simulationPayload.k}
goodBlockchainLength={simulationPayload.goodBlockchainLength}
maliciousBlockchainLength={simulationPayload.maliciousBlockchainLength}
/>
)}
</div>
<div className="block__tree u-plate">
<div className="block-tree__title">
Block Tree and Branch Selection
</div>
{simulationPayload && (
<BlockTree
maliciousBlockchainLength={simulationPayload.maliciousBlockchainLength}
goodBlockchainLength={simulationPayload.goodBlockchainLength}
attackDuration={simulationPayload.attackDuration}
successfulAttackInBlocks={simulationPayload.successfulAttackInBlocks}
attackSucceeded={simulationPayload.attackSucceeded}
/>
)}
</div>
</div>
: ''}
<div className="simulation-time-between-blocks u-plate">
<div className="simulation-time-between-blocks__title">
time between blocks
</div>
{simulationPayload && (
<div className={'time-between-blocks-chart-container'}>
<Chart
chartType="LineChart"
data={Simulation.timeBetweenBlocks(simulationPayload)}
options={{
hAxis: {
title: 'Blocks',
gridlines: { count: -1 },
minValue: 1,
viewWindow: {
min: 1,
},
},
vAxis: {
title: 'Time (in Minutes)',
},
series: {
1: { curveType: 'function' },
},
legend: 'none',
tooltip: {
isHtml: true,
},
}}
graph_id="Time Between Blocks LineChart"
width="100%"
height="264px"
/>
</div>
)}
</div>
<div className="simulation-pending-transactions u-plate">
<div className="simulation-pending-transactions__title">
Pending Transactions Per Block
</div>
{simulationPayload && (
<div className={'pending-transactions-chart-container'}>
{this.props.transactionFee > 0 && this.props.hashRate === 0 ? <Chart
chartType="AreaChart"
data={this.pendingTransactions(simulationPayload)}
options={{
hAxis: {
title: 'Blocks',
gridlines: { count: -1 },
minValue: 1,
viewWindow: {
min: 1,
},
},
vAxis: {
title: 'Pending Transactions',
},
series: {
1: { curveType: 'function' },
},
focusTarget: 'category',
legend: { position: 'bottom' },
tooltip: {
isHtml: true,
},
}}
graph_id="Pending Transactions AreaChart"
width="100%"
height="264px"
/> :
<Chart
chartType="AreaChart"
data={this.pendingTransactions(simulationPayload)}
options={{
hAxis: {
title: 'Blocks',
gridlines: { count: -1 },
minValue: 1,
viewWindow: {
min: 1,
},
},
vAxis: {
title: 'Pending Transactions',
},
series: {
1: { curveType: 'function' },
},
legend: 'none',
tooltip: {
isHtml: true,
},
}}
graph_id="Pending Transactions AreaChart"
width="100%"
height="264px"
/>
},
</div>
)
}
</div>
<div className="simulation-processed-transactions__grid">
<div className="transaction__summary u-plate">
<div className="transaction-summary__title">
Transaction Summary
</div>
{simulationPayload && (
<TransactionSummary
isSegWitEnabled={simulationPayload.segWitMaxTransactionsPerBlock !== 0}
segWitTheoreticalMaxBlockSize={this.props.maxBlockWeight}
segWitMaxBlockWeight={simulationPayload.segWitMaxBlockWeight}
segWitMaxTransactionsPerBlock={simulationPayload.segWitMaxTransactionsPerBlock}
segWitMaxTPS={simulationPayload.segWitMaxTPS}
nonSegWitMaxBlockSize={this.props.maxBlockSize}
nonSegWitMaxTransactionsPerBlock={simulationPayload.
nonSegWitMaxTransactionsPerBlock}
nonSegWitMaxTPS={simulationPayload.nonSegWitMaxTPS}
actualTPS={simulationPayload.tps}
blockchainSize={simulationPayload.longestChainSize}
totalNumberOfProcessedTransactions={simulationPayload.
longestChainNumberTransactions}
blockchainLength={simulationPayload.longestChainLength}
/>
)}
</div>
<div className="simulation-processed-transactions u-plate">
<div className="simulation-processed-transactions__title">
Processed Transactions Per Block
</div>
{simulationPayload && (
<div className={'processed-transactions-chart-container'}>
<Chart
chartType="LineChart"
data={this.processedTransactions(simulationPayload)}
options={{
hAxis: {
title: 'Blocks',
gridlines: { count: -1 },
minValue: 1,
viewWindow: {
min: 1,
},
},
vAxis: {
title: 'Processed Transactions',
},
series: {
1: { curveType: 'function' },
},
legend: { position: 'bottom' },
focusTarget: 'category',
tooltip: {
isHtml: true,
},
}}
graph_id="Processed Transactions LineChart"
width="100%"
height="264px"
/>
</div>
)}
</div>
</div>
{this.props.transactionFee > 0 && this.props.hashRate === 0 ?
<div className="simulation-flood-attack__grid">
<div className="flood-attack__summary u-plate">
<div className="flood-attack-summary__title">
Flood Attack Summary
</div>
{simulationPayload && (
<FloodAttackSummary
confirmedFloodAttackTransactions={simulationPayload.
confirmedFloodAttackTransactions}
floodAttackSpentTransactionFees={simulationPayload.
floodAttackSpentTransactionFees}
confirmedTransactionsBelowTargetTransactionFee={simulationPayload.
confirmedTransactionsBelowTargetTransactionFee}
/>
)
}
</div>
<div className="simulation-flood-attack u-plate">
<div className="simulation-flood-attack__title">
Transaction Confirmation Status Per Transaction Fee
</div>
{simulationPayload && (
<div className={'transaction-count-per-fee-chart-container'}>
<Chart
chartType="AreaChart"
data={Simulation.transactionConfirmationStatusPerFee(simulationPayload)}
options={{
hAxis: {
title: 'Transaction Fees (in Satoshi)',
gridlines: { count: -1 },
},
vAxis: {
title: 'Transactions',
},
series: {
1: { curveType: 'function' },
},
focusTarget: 'category',
tooltip: {
isHtml: true,
},
legend: { position: 'bottom' },
colors: ['#9ACD32', '#FF0000'],
}}
graph_id="Confirmation Status AreaChart"
width="100%"
height="264px"
/>
</div>
)}
</div>
</div>
:
<div className="simulation-transaction-count-per-fee u-plate">
<div className="simulation-transaction-count-per-fee__title">
Transaction Confirmation Status Per Transaction Fee
</div>
{simulationPayload && (
<div className={'transaction-count-per-fee-chart-container'}>
<Chart
chartType="AreaChart"
data={Simulation.transactionConfirmationStatusPerFee(simulationPayload)}
options={{
hAxis: {
title: 'Transaction Fees (in Satoshi)',
gridlines: { count: -1 },
},
vAxis: {
title: 'Transactions',
},
series: {
1: { curveType: 'function' },
},
focusTarget: 'category',
tooltip: {
isHtml: true,
},
legend: { position: 'bottom' },
colors: ['#9ACD32', '#FF0000'],
}}
graph_id="Confirmation Status AreaChart"
width="100%"
height="264px"
/>
</div>
)}
</div>
}
<div className="confirmation-time-per-fee u-plate">
<div className="confirmation-time-per-fee__title">
Average Transaction Confirmation Time per Transaction Fee
</div>
{simulationPayload && (
<div className={'confirmation-time-per-fee-chart-container'}>
<Chart
chartType="AreaChart"
data={Simulation.confirmationTime(simulationPayload)}
options={{
hAxis: {
title: 'Transaction Fees (in Satoshi)',
gridlines: { count: -1 },
},
vAxis: {
title: 'Confirmation Time (in Blocks)',
},
series: {
1: { curveType: 'function' },
},
focusTarget: 'category',
tooltip: {
isHtml: true,
},
legend: { position: 'none' },
}}
graph_id="Confirmation Time AreaChart"
width="100%"
height="264px"
/>
</div>
)}
</div>
</div>
);
}
return (
<div className="simulation">
<div className="simulation__grid">
<div className="simulation__map u-plate">
<div className="simulation__title">
Simulation
</div>
<DataMap
event={(simulationPayload && selectedIndex !== undefined)
? simulationPayload.events[selectedIndex]
: undefined}
/>
<EventsRange
events={simulationPayload ? simulationPayload.events : undefined}
selectedIndex={selectedIndex}
onSelectIndex={this.handleSelectIndex}
/>
</div>
<div className="simulation__summary u-plate">
<div className="simulation-summary__title">
Summary
</div>
{simulationPayload && (
<SimulationSummary
duration={simulationPayload.duration}
longestChainLength={simulationPayload.longestChainLength}
longestChainSize={simulationPayload.longestChainSize}
longestChainNumberTransactions={simulationPayload.longestChainNumberTransactions}
timesWithOutliers10={simulationPayload.timesWithOutliers10}
timesWithOutliers50={simulationPayload.timesWithOutliers50}
timesWithOutliers90={simulationPayload.timesWithOutliers90}
timesNoOutliers10={simulationPayload.timesNoOutliers10}
timesNoOutliers50={simulationPayload.timesNoOutliers50}
timesNoOutliers90={simulationPayload.timesNoOutliers90}
firstBlockNumberOfRecipients={simulationPayload.firstBlockNumberOfRecipients}
lastBlockNumberOfRecipients={simulationPayload.lastBlockNumberOfRecipients}
totalNumberOfNodes={simulationPayload.totalNumberOfNodes}
staleBlocks={simulationPayload.staleBlocks}
strategy={this.props.strategy}
avgBlockTime={simulationPayload.avgBlockTime}
/>
)}
</div>
<div className="simulation__events u-plate">
<SimulationEvents
events={simulationPayload ? simulationPayload.events : undefined}
selectedIndex={selectedIndex}
onSelectIndex={this.handleSelectIndex}
moveIntoViewPort={moveIntoViewPort}
strategy={this.props.strategy}
/>
</div>
</div>
<div className="simulation__buttons">
<div>
<Button
className="simulation__button"
title="New Simulation"
onClick={() => {
this.setState({ simulationPayload: undefined });
this.props.onNewSimulation();
}}
active={true}
/>
</div>
{!isFetching && (
<div>
<Button
className="simulation__button"
title="START"
onClick={this.fetchEvents}
active={true}
/>
</div>
)}
{isFetching && (
<div>
<div className="u-loader">Loading...</div>
</div>
)}
</div>
</div>
);
}
private pendingTransactions(simulationPayload: any) {
if (this.props.transactionFee > 0 && this.props.hashRate === 0) {
const floodAttackData: any[][] = [['Blocks', 'Pending Transactions', 'Winning Miner - Pending Transactions',
'Flood Attack Transactions']];
for (const event of simulationPayload.events) {
if (event.eventType === EventTypes.IBlockMine) {
let pendingFloodAttackTransactions = 0;
let pendingTransactions = 0;
for (const transaction of simulationPayload.transactions) {
if (event.level >= transaction.creationLevel &&
(transaction.confirmationLevel > event.level || transaction.confirmationLevel === -1)) {
if (transaction.isFloodAttack) {
pendingFloodAttackTransactions = pendingFloodAttackTransactions + 1;
}
pendingTransactions = pendingTransactions + 1;
}
}
floodAttackData.push(
[event.level + 1, pendingTransactions, event.transactionPoolSize, pendingFloodAttackTransactions]);
}
}
return floodAttackData;
}
const data: any[][] = [['Blocks', 'Pending Transactions']];
for (const event of simulationPayload.events) {
if (event.eventType === EventTypes.IBlockMine) {
data.push([event.level + 1, event.transactionPoolSize]);
}
}
return data;
}
private fetchEvents() {
this.setState({ isFetching: true });
fetchEvents(this.props)
.then(simulationPayload => this.setState({ simulationPayload, isFetching: false, selectedIndex: 0 }));
}
private handleSelectIndex(selectedIndex: number, moveIntoViewPort: boolean) {
this.setState({ selectedIndex, moveIntoViewPort });
}
private processedTransactions(simulationPayload: any) {
let multi: any[][] = [];
if (this.props.strategy === Strategies.BITCOIN_LIKE_BLOCKCHAIN) {
if (simulationPayload.nonSegWitMaxTransactionsPerBlock !== 0 ||
simulationPayload.segWitMaxTransactionsPerBlock !== 0) {
if (this.props.transactionFee > 0 && this.props.hashRate === 0) {
multi = [['Blocks', 'Processed Transactions', 'Maximum Possible Transactions', 'Flood Attack Transactions',
'Transactions below Target']];
// I think it is better to have only one calculation of max processed transactions,
// therefore this value is not calculated here, but instead uses a value from the server.
// This makes it easier to change the implementation in just one place.
for (const event of simulationPayload.events) {
let floodAttackTransactions = 0;
let transactionsBelowTarget = 0;
for (const transaction of simulationPayload.transactions) {
if (event.level === transaction.confirmationLevel && transaction.confirmation) {
if (transaction.isFloodAttack) {
floodAttackTransactions = floodAttackTransactions + 1;
}
if (transaction.transactionFee < this.props.transactionFee) {
transactionsBelowTarget = transactionsBelowTarget + 1;
}
}
}
if (event.eventType === EventTypes.IBlockMine) {
multi.push([
event.level + 1,
event.processedTransactions,
simulationPayload.segWitMaxTransactionsPerBlock !== 0 ?
simulationPayload.segWitMaxTransactionsPerBlock :
simulationPayload.nonSegWitMaxTransactionsPerBlock,
floodAttackTransactions,
transactionsBelowTarget,
],
);
}
}
} else {
multi = [['Blocks', 'Processed Transactions', 'Maximum Possible Transactions']];
// I think it is better to have only one calculation of max processed transactions,
// therefore this value is not calculated here, but instead uses a value from the server.
// This makes it easier to change the implementation in just one place.
for (const event of simulationPayload.events) {
if (event.eventType === EventTypes.IBlockMine) {
multi.push([event.level + 1, event.processedTransactions,
simulationPayload.segWitMaxTransactionsPerBlock !== 0 ?
simulationPayload.segWitMaxTransactionsPerBlock :
simulationPayload.nonSegWitMaxTransactionsPerBlock]);
}
}
}
} else {
// no max limit
multi = [['Blocks', 'Processed Transactions']];
// I think it is better to have only one calculation of max processed transactions,
// therefore this value is not calculated here, but instead uses a value from the server.
// This makes it easier to change the implementation in just one place.
for (const event of simulationPayload.events) {
if (event.eventType === EventTypes.IBlockMine) {
multi.push([event.level + 1, event.processedTransactions]);
}
}
}
} else if (this.props.strategy === Strategies.GENERIC_SIMULATION) {
multi = [['Blocks', 'Processed Transactions']];
for (const event of simulationPayload.events) {
if (event.eventType === EventTypes.IBlockMine) {
multi.push([event.level + 1, event.processedTransactions]);
}
}
}
return multi;
}
} | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace FormQuick_Campaign {
interface Header extends DevKit.Controls.IHeader {
/** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
CreatedOn: DevKit.Controls.DateTime;
/** Choose the activity to create that determines how target prospects or customers in this quick campaign are contacted. */
CreatedRecordTypeCode: DevKit.Controls.OptionSet;
/** Select the quick campaign's status. */
StatusCode: DevKit.Controls.OptionSet;
/** Select the type of records targeted in the quick campaign to identify the target audience. */
TargetedRecordTypeCode: DevKit.Controls.OptionSet;
}
interface tab_Responses_Sections {
Responses: DevKit.Controls.Section;
}
interface tab_Summary_Sections {
excludedMembers: DevKit.Controls.Section;
Information: DevKit.Controls.Section;
RELATED_PANE: DevKit.Controls.Section;
selectedMembers: DevKit.Controls.Section;
}
interface tab_Responses extends DevKit.Controls.ITab {
Section: tab_Responses_Sections;
}
interface tab_Summary extends DevKit.Controls.ITab {
Section: tab_Summary_Sections;
}
interface Tabs {
Responses: tab_Responses;
Summary: tab_Summary;
}
interface Body {
Tab: Tabs;
/** Type additional information to describe the quick campaign, such as the products or services offered. */
Description: DevKit.Controls.String;
/** Number of records which failed in the bulk operation. */
FailureCount: DevKit.Controls.Integer;
notescontrol: DevKit.Controls.Note;
/** Unique identifier of the user or team who owns the activity. */
OwnerId: DevKit.Controls.Lookup;
/** Type a short description about the objective or primary topic of the quick campaign. */
Subject: DevKit.Controls.String;
/** Number of records which succeeded in the bulk operation. */
SuccessCount: DevKit.Controls.Integer;
}
interface Navigation {
navRelationshipActivities: DevKit.Controls.NavigationItem,
navRelationshipBulkOperationLogs: DevKit.Controls.NavigationItem
}
interface Grid {
selected_accounts: DevKit.Controls.Grid;
selected_contacts: DevKit.Controls.Grid;
selected_leads: DevKit.Controls.Grid;
excluded_accounts: DevKit.Controls.Grid;
excluded_contacts: DevKit.Controls.Grid;
excluded_leads: DevKit.Controls.Grid;
Responses: DevKit.Controls.Grid;
}
}
class FormQuick_Campaign extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Quick_Campaign
* @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 Quick_Campaign */
Body: DevKit.FormQuick_Campaign.Body;
/** The Header section of form Quick_Campaign */
Header: DevKit.FormQuick_Campaign.Header;
/** The Navigation of form Quick_Campaign */
Navigation: DevKit.FormQuick_Campaign.Navigation;
/** The Grid of form Quick_Campaign */
Grid: DevKit.FormQuick_Campaign.Grid;
}
namespace FormQuick_Campaign_deprecated {
interface Header extends DevKit.Controls.IHeader {
/** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
CreatedOn: DevKit.Controls.DateTime;
/** Choose the activity to create that determines how target prospects or customers in this quick campaign are contacted. */
CreatedRecordTypeCode: DevKit.Controls.OptionSet;
/** Select the quick campaign's status. */
StatusCode: DevKit.Controls.OptionSet;
/** Select the type of records targeted in the quick campaign to identify the target audience. */
TargetedRecordTypeCode: DevKit.Controls.OptionSet;
}
interface tab_Responses_Sections {
Responses: DevKit.Controls.Section;
}
interface tab_Summary_Sections {
excludedMembers: DevKit.Controls.Section;
Information: DevKit.Controls.Section;
RELATED_PANE: DevKit.Controls.Section;
selectedMembers: DevKit.Controls.Section;
}
interface tab_Responses extends DevKit.Controls.ITab {
Section: tab_Responses_Sections;
}
interface tab_Summary extends DevKit.Controls.ITab {
Section: tab_Summary_Sections;
}
interface Tabs {
Responses: tab_Responses;
Summary: tab_Summary;
}
interface Body {
Tab: Tabs;
/** Type additional information to describe the quick campaign, such as the products or services offered. */
Description: DevKit.Controls.String;
/** Number of records which failed in the bulk operation. */
FailureCount: DevKit.Controls.Integer;
notescontrol: DevKit.Controls.Note;
/** Unique identifier of the user or team who owns the activity. */
OwnerId: DevKit.Controls.Lookup;
/** Type a short description about the objective or primary topic of the quick campaign. */
Subject: DevKit.Controls.String;
/** Number of records which succeeded in the bulk operation. */
SuccessCount: DevKit.Controls.Integer;
}
interface Navigation {
navRelationshipActivities: DevKit.Controls.NavigationItem,
navRelationshipBulkOperationLogs: DevKit.Controls.NavigationItem
}
interface Grid {
accounts: DevKit.Controls.Grid;
contacts: DevKit.Controls.Grid;
leads: DevKit.Controls.Grid;
leads_uci: DevKit.Controls.Grid;
accounts_uci: DevKit.Controls.Grid;
contacts_uci: DevKit.Controls.Grid;
excluded_contacts_uci: DevKit.Controls.Grid;
excluded_accounts_uci: DevKit.Controls.Grid;
excluded_leads_uci: DevKit.Controls.Grid;
Responses: DevKit.Controls.Grid;
}
}
class FormQuick_Campaign_deprecated extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Quick_Campaign_deprecated
* @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 Quick_Campaign_deprecated */
Body: DevKit.FormQuick_Campaign_deprecated.Body;
/** The Header section of form Quick_Campaign_deprecated */
Header: DevKit.FormQuick_Campaign_deprecated.Header;
/** The Navigation of form Quick_Campaign_deprecated */
Navigation: DevKit.FormQuick_Campaign_deprecated.Navigation;
/** The Grid of form Quick_Campaign_deprecated */
Grid: DevKit.FormQuick_Campaign_deprecated.Grid;
}
class BulkOperationApi {
/**
* DynamicsCrm.DevKit BulkOperationApi
* @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;
/** Additional information provided by the external application as JSON. For internal use only. */
ActivityAdditionalParams: DevKit.WebApi.StringValue;
/** Unique identifier of the bulk operation. */
ActivityId: DevKit.WebApi.GuidValue;
/** Actual duration of the bulk operation in minutes. */
ActualDurationMinutes: DevKit.WebApi.IntegerValueReadonly;
/** Shows the date and time when the quick campaign was completed or canceled. */
ActualEnd_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Shows the date and time when the activity was started or created. */
ActualStart_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows the number for the quick campaign record, used to identify the quick campaign. */
BulkOperationNumber: DevKit.WebApi.StringValueReadonly;
/** Shows how contact about the social activity originated, such as from Twitter or Facebook. This field is read-only. */
Community: DevKit.WebApi.OptionSetValue;
/** Shows who created the record. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who created the bulk operation. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Choose the activity to create that determines how target prospects or customers in this quick campaign are contacted. */
CreatedRecordTypeCode: DevKit.WebApi.OptionSetValue;
/** Date and time when the delivery of the activity was last attempted. */
DeliveryLastAttemptedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Priority of delivery of the activity to the email server. */
DeliveryPriorityCode: DevKit.WebApi.OptionSetValue;
/** Type additional information to describe the quick campaign, such as the products or services offered. */
Description: DevKit.WebApi.StringValueReadonly;
/** Shows the error code that is used to troubleshoot issues in the quick campaign. */
ErrorNumber: DevKit.WebApi.IntegerValue;
/** The message id of activity which is returned from Exchange Server. */
ExchangeItemId: DevKit.WebApi.StringValue;
/** Exchange rate for the currency associated with the activitypointer with respect to the base currency. */
ExchangeRate: DevKit.WebApi.DecimalValueReadonly;
/** Shows the web link of Activity of type email. */
ExchangeWebLink: DevKit.WebApi.StringValue;
/** Number of records which failed in the bulk operation. */
FailureCount: DevKit.WebApi.IntegerValue;
/** Sequence number of the import that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Type of instance of a recurring series. */
InstanceTypeCode: DevKit.WebApi.OptionSetValueReadonly;
/** For internal use only. */
IsBilled: DevKit.WebApi.BooleanValueReadonly;
/** For internal use only. */
IsMapiPrivate: DevKit.WebApi.BooleanValue;
/** Information regarding whether the activity is a regular activity type or event type. */
IsRegularActivity: DevKit.WebApi.BooleanValueReadonly;
/** Specifies if the bulk operation was created from a workflow rule. */
IsWorkflowCreated: DevKit.WebApi.BooleanValueReadonly;
/** Contains the date and time stamp of the last on hold time. */
LastOnHoldTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Left the voice mail */
LeftVoiceMail: DevKit.WebApi.BooleanValue;
/** Shows who last updated the record. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the bulk operation was last modified. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who last modified the bulk operation. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Shows how long, in minutes, that the record was on hold. */
OnHoldTime: DevKit.WebApi.IntegerValueReadonly;
/** Select the type of bulk operation process, such as quick campaign or campaign activity distribution. */
OperationTypeCode: DevKit.WebApi.OptionSetValue;
/** 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 of the business unit that owns the activity. */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the team that owns the activity. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the user that owns the activity. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** XML string that contains the parameters to the bulk operation. */
Parameters: DevKit.WebApi.StringValue;
/** For internal use only. */
PostponeActivityProcessingUntil_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Priority of the activity. */
PriorityCode: DevKit.WebApi.OptionSetValue;
/** Unique identifier of the Process. */
ProcessId: DevKit.WebApi.GuidValue;
/** Choose the campaign from which the campaign activities were bulk-distributed. */
regardingobjectid_campaignactivity_bulkoperation: DevKit.WebApi.LookupValue;
/** Choose the campaign from which the campaign activities were bulk-distributed. */
regardingobjectid_list: DevKit.WebApi.LookupValue;
/** Scheduled duration of the bulk operation, specified in minutes. */
ScheduledDurationMinutes: DevKit.WebApi.IntegerValueReadonly;
/** Scheduled end date and time of the bulk operation. */
ScheduledEnd_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValueReadonly;
/** Scheduled start date and time of the bulk operation. */
ScheduledStart_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValueReadonly;
/** Unique identifier of the mailbox associated with the sender of the email message. */
SenderMailboxId: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the activity was sent. */
SentOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Uniqueidentifier specifying the id of recurring series of an instance. */
SeriesId: DevKit.WebApi.GuidValueReadonly;
/** Unique identifier for an associated service. */
ServiceId: DevKit.WebApi.LookupValue;
/** Choose the service level agreement (SLA) that you want to apply to the case record. */
SLAId: DevKit.WebApi.LookupValue;
/** Last SLA that was applied to this case. This field is for internal use only. */
SLAInvokedId: DevKit.WebApi.LookupValueReadonly;
SLAName: DevKit.WebApi.StringValueReadonly;
/** Shows the date and time by which the activities are sorted. */
SortDate_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Unique identifier of the Stage. */
StageId: DevKit.WebApi.GuidValue;
/** Shows whether the quick campaign is open, closed, or canceled. Closed or canceled quick campaigns are read-only and can't be edited. */
StateCode: DevKit.WebApi.OptionSetValueReadonly;
/** Select the quick campaign's status. */
StatusCode: DevKit.WebApi.OptionSetValue;
/** Type a short description about the objective or primary topic of the quick campaign. */
Subject: DevKit.WebApi.StringValue;
/** Number of records which succeeded in the bulk operation. */
SuccessCount: DevKit.WebApi.IntegerValue;
/** Select the type of records targeted in the quick campaign to identify the target audience. */
TargetedRecordTypeCode: DevKit.WebApi.OptionSetValue;
/** Number of members to target. */
TargetMembersCount: DevKit.WebApi.IntegerValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Unique identifier of the currency associated with the activitypointer. */
TransactionCurrencyId: DevKit.WebApi.LookupValue;
/** For internal use only. */
TraversedPath: DevKit.WebApi.StringValue;
/** Time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
/** Version number of the activity. */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
/** Information for bulk operation workflow. */
WorkflowInfo: DevKit.WebApi.StringValue;
/** The array of object that can cast object to ActivityPartyApi class */
ActivityParties: Array<any>;
}
}
declare namespace OptionSet {
namespace BulkOperation {
enum Community {
/** 5 */
Cortana,
/** 6 */
Direct_Line,
/** 8 */
Direct_Line_Speech,
/** 9 */
Email,
/** 1 */
Facebook,
/** 10 */
GroupMe,
/** 11 */
Kik,
/** 3 */
Line,
/** 7 */
Microsoft_Teams,
/** 0 */
Other,
/** 13 */
Skype,
/** 14 */
Slack,
/** 12 */
Telegram,
/** 2 */
Twitter,
/** 4 */
Wechat,
/** 15 */
WhatsApp
}
enum CreatedRecordTypeCode {
/** 5 */
Appointment,
/** 4 */
Email,
/** 2 */
Fax,
/** 3 */
Letter,
/** 1 */
Phone_Call,
/** 6 */
Send_Direct_Email
}
enum DeliveryPriorityCode {
/** 2 */
High,
/** 0 */
Low,
/** 1 */
Normal
}
enum InstanceTypeCode {
/** 0 */
Not_Recurring,
/** 3 */
Recurring_Exception,
/** 4 */
Recurring_Future_Exception,
/** 2 */
Recurring_Instance,
/** 1 */
Recurring_Master
}
enum OperationTypeCode {
/** 2 */
Create_Activities,
/** 1 */
Create_Opportunities,
/** 4 */
Distribute,
/** 5 */
Execute,
/** 7 */
Quick_Campaign,
/** 3 */
Send_Direct_Mail
}
enum PriorityCode {
/** 2 */
High,
/** 0 */
Low,
/** 1 */
Normal
}
enum StateCode {
/** 2 */
Canceled,
/** 1 */
Closed,
/** 0 */
Open
}
enum StatusCode {
/** 3 */
Aborted,
/** 5 */
Canceled,
/** 4 */
Completed,
/** 2 */
In_Progress,
/** 1 */
Pending
}
enum TargetedRecordTypeCode {
/** 1 */
Account,
/** 2 */
Contact,
/** 4 */
Lead
}
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':['Quick Campaign','Quick Campaign (deprecated)'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import { EMPTY, isObservable, Observable, Subject, Subscription, AsyncSubject, BehaviorSubject } from "rxjs";
import { distinctUntilChanged, filter, map, merge, scan, takeUntil } from "rxjs/operators";
import { shallowEqual } from "./shallowEqual";
import { ActionDispatch, CleanupState, Reducer, StateChangeNotification, StateMutation } from "./types";
// TODO use typings here
declare var require: any;
const isPlainObject = require("lodash.isplainobject");
const isObject = require("lodash.isobject");
/**
* A function which takes a Payload and return a state mutation function.
*/
type RootReducer<R, P> = (payload: P) => StateMutation<R>;
/**
* Creates a state based on a stream of StateMutation functions and an initial state. The returned observable
* is hot and caches the last emitted value (will emit the last emitted value immediately upon subscription).
* @param stateMutators
* @param initialState
*/
function createState<S>(stateMutators: Observable<StateMutation<S>>, initialState: S): BehaviorSubject<S> {
const state = new BehaviorSubject<S>(initialState);
stateMutators.pipe(scan((state: S, reducer: StateMutation<S>) => reducer(state), initialState)).subscribe(state);
return state;
}
export class Store<S> {
/**
* Observable that emits when the store was destroyed using the .destroy() function.
*/
public readonly destroyed: Observable<void>;
// TODO This is truly an BehaviorSubject but due to some typing issues we need to cast it as Observable?
private readonly state: Observable<S>;
public get currentState(): S {
// TODO see above: this.state is actually a BehaviorSubject but typescript or rxjs typings make trouble
return (this.state as any).value;
}
/**
* All reducers always produce a state mutation of the original root store type R;
* However, we only now type R for the root store; all other stores may have different type
* so we use any here as the root type.
*/
private readonly stateMutators: Subject<StateMutation<any>>;
/**
* A list of transformation functions that will transform the state to different projections
* and backwards. Use for scoped reducers.
*/
private readonly forwardProjections: Function[];
private readonly backwardProjections: Function[];
/**
* Is completed when the slice is unsubscribed and no longer needed.
*/
private readonly _destroyed = new AsyncSubject<void>();
/**
* Used for manual dispatches without observables
*/
private readonly actionDispatch: Subject<ActionDispatch<any>>;
private readonly stateChangeNotificationSubject: Subject<StateChangeNotification>;
/**
* Only used for debugging purposes (so we can bridge Redux Devtools to the store)
* Note: Do not use in day-to-day code, use .select() instead.
*/
public readonly stateChangedNotification: Observable<StateChangeNotification>;
private constructor(
state: BehaviorSubject<S>,
stateMutators: Subject<StateMutation<S>>,
forwardProjections: Function[],
backwardProjections: Function[],
notifyRootStateChangedSubject: Subject<StateChangeNotification>,
actionDispatch: Subject<ActionDispatch<any>>,
) {
this.state = state;
this.stateMutators = stateMutators;
this.forwardProjections = forwardProjections;
this.backwardProjections = backwardProjections;
this.destroyed = this._destroyed.asObservable();
this.actionDispatch = actionDispatch;
this.stateChangeNotificationSubject = notifyRootStateChangedSubject;
this.stateChangedNotification = this.stateChangeNotificationSubject
.asObservable()
.pipe(takeUntil(this.destroyed));
}
/**
* Create a new Store based on an initial state
*/
static create<S>(initialState?: S): Store<S> {
if (initialState === undefined) initialState = {} as S;
else {
if (isObject(initialState) && !Array.isArray(initialState) && !isPlainObject(initialState))
throw new Error("initialState must be a plain object, an array, or a primitive type");
}
const stateMutators = new Subject<StateMutation<S>>();
const state = createState(stateMutators, initialState);
const store = new Store<S>(state, stateMutators, [], [], new Subject(), new Subject());
// emit a single state mutation so that we emit the initial state on subscription
stateMutators.next(s => s);
return store;
}
/**
* Creates a new linked store, that Selects a slice on the main store.
* @deprecated
*/
createSlice<K extends keyof S>(key: K, initialState?: S[K], cleanupState?: CleanupState<S[K]>): Store<S[K]> {
if (isObject(initialState) && !Array.isArray(initialState) && !isPlainObject(initialState))
throw new Error("initialState must be a plain object, an array, or a primitive type");
if (isObject(cleanupState) && !Array.isArray(cleanupState) && !isPlainObject(cleanupState))
throw new Error("cleanupState must be a plain object, an array, or a primitive type");
const forward = (state: S) => (state as any)[key] as S[K];
const backward = (state: S[K], parentState: S) => {
(parentState as any)[key] = state;
return parentState;
};
const initial = initialState === undefined ? undefined : () => initialState;
// legacy cleanup for slices
const cleanup =
cleanupState === undefined
? undefined
: (state: any, parentState: any) => {
if (cleanupState === "undefined") {
parentState[key] = undefined;
} else if (cleanupState === "delete") delete parentState[key];
else {
parentState[key] = cleanupState;
}
return parentState;
};
return this.createProjection(forward, backward, initial, cleanup);
}
/**
* Create a clone of the store which holds the same state. This is an alias to createProjection with
* the identity functions as forward/backwards projection. Usefull to unsubscribe from select()/watch()
* subscriptions as the destroy() event is specific to the new cloned instance (=will not destroy the original)
* Also usefull to scope string-based action dispatches to .dispatch() as action/reducers pairs added to the
* clone can not be dispatched by the original and vice versa.
*/
clone() {
return this.createProjection((s: S) => s, (s: S, p: S) => s);
}
/**
* Creates a new slice of the store. The slice holds a transformed state that is created by applying the
* forwardProjection function. To transform the slice state back to the parent state, a backward projection
* function must be given.
* @param forwardProjection - Projection function that transforms a State S to a new projected state TProjectedState
* @param backwardProjection - Back-Projection to obtain state S from already projected state TProjectedState
* @param initial - Function to be called initially with state S that must return an initial state to use for TProjected
* @param cleanup - Function to be called when the store is destroyed to return a cleanup state based on parent state S
*/
createProjection<TProjectedState>(
forwardProjection: (state: S) => TProjectedState,
backwardProjection: (state: TProjectedState, parentState: S) => S,
// TODO make this a flat object instead of a function?
initial?: (state: S) => TProjectedState,
cleanup?: (state: TProjectedState, parentState: S) => S,
): Store<TProjectedState> {
const forwardProjections = [...this.forwardProjections, forwardProjection];
const backwardProjections = [backwardProjection, ...this.backwardProjections];
const initialState = initial
? initial((this.state as any).value)
: forwardProjection((this.state as any).value);
if (initial !== undefined) {
this.stateMutators.next(s => {
const initialReducer = () => initialState;
return mutateRootState(s, forwardProjections, backwardProjections, initialReducer);
});
}
const state = new BehaviorSubject<TProjectedState>(initialState);
this.state.pipe(map(state => forwardProjection(state))).subscribe(state);
const onDestroy = () => {
if (cleanup !== undefined) {
this.stateMutators.next(s => {
const backward = [cleanup, ...this.backwardProjections];
return mutateRootState(s, forwardProjections, backward, (s: any) => s);
});
}
};
const sliceStore = new Store<TProjectedState>(
state,
this.stateMutators,
forwardProjections,
backwardProjections,
this.stateChangeNotificationSubject,
this.actionDispatch,
);
sliceStore.destroyed.subscribe(undefined, undefined, onDestroy);
// destroy the slice if the parent gets destroyed
this._destroyed.subscribe(undefined, undefined, () => {
sliceStore.destroy();
});
return sliceStore;
}
/**
* Adds an Action/Reducer pair. This will make the reducer become active whenever the action observable emits a
* value.
* @param action An observable whose payload will be passed to the reducer on each emit, or a string identifier
* as an action name. In the later case, .dispatch() can be used to manually dispatch actions based
* on their string name.
* @param reducer A reducer function. @see Reducer
* @param actionName An optional name (only used during development/debugging) to assign to the action when an
* Observable is passed as first argument. Must not be specified if the action argument is a string.
*/
addReducer<P>(action: Observable<P> | string, reducer: Reducer<S, P>, actionName?: string): Subscription {
if (typeof action === "string" && typeof actionName !== "undefined")
throw new Error("cannot specify a string-action AND a string alias at the same time");
if (!isObservable(action) && typeof action !== "string")
throw new Error("first argument must be an observable or a string");
if (typeof reducer !== "function") throw new Error("reducer argument must be a function");
if (
(typeof actionName === "string" && actionName.length === 0) ||
(typeof action === "string" && action.length === 0)
)
throw new Error("action/actionName must have non-zero length");
const name = typeof action === "string" ? action : actionName!;
const actionFromStringBasedDispatch = this.actionDispatch.pipe(
filter(s => s.actionName === name),
map(s => s.actionPayload),
merge(isObservable(action) ? action : EMPTY),
takeUntil(this.destroyed),
);
const rootReducer: RootReducer<S, P> = (payload: P) => rootState => {
// transform the rootstate to a slice by applying all forward projections
const sliceReducer = (slice: any) => reducer(slice, payload);
rootState = mutateRootState(rootState, this.forwardProjections, this.backwardProjections, sliceReducer);
// Send state change notification
const changeNotification: StateChangeNotification = {
actionName: name,
actionPayload: payload,
newState: rootState,
};
this.stateChangeNotificationSubject.next(changeNotification);
return rootState;
};
return actionFromStringBasedDispatch.pipe(map(payload => rootReducer(payload))).subscribe(rootStateMutation => {
this.stateMutators.next(rootStateMutation);
});
}
/**
* Selects a part of the state using a selector function. If no selector function is given, the identity function
* is used (which returns the state of type S).
* Note: The returned observable does only update when the result of the selector function changed
* compared to a previous emit. A shallow copy test is performed to detect changes.
* This requires that your reducers update all nested properties in
* an immutable way, which is required practice with Redux and also with reactive-state.
* To make the observable emit any time the state changes, use .select() instead
* For correct nested reducer updates, see:
* http://redux.js.org/docs/recipes/reducers/ImmutableUpdatePatterns.html#updating-nested-objects
*
* @param selectorFn A selector function which returns a mapped/transformed object based on the state
* @returns An observable that emits the result of the selector function after a
* change of the return value of the selector function
*/
watch<T = S>(selectorFn?: (state: S) => T): Observable<T> {
return this.select(selectorFn).pipe(distinctUntilChanged((a, b) => shallowEqual(a, b)));
}
/**
* Same as .watch() except that EVERY state change is emitted. Use with care, you might want to pipe the output
* to your own implementation of .distinctUntilChanged() or use only for debugging purposes.
*/
select<T = S>(selectorFn?: (state: S) => T): Observable<T> {
if (!selectorFn) selectorFn = (state: S) => <T>(<any>state);
const mapped = this.state.pipe(
takeUntil(this._destroyed),
map(selectorFn),
);
return mapped;
}
/**
* Destroys the Store/Slice. All Observables obtained via .select() will complete when called.
*/
destroy(): void {
this._destroyed.next(undefined);
this._destroyed.complete();
}
/**
* Manually dispatch an action by its actionName and actionPayload.
*
* This function exists for compatibility reasons, development and devtools. It is not adviced to use
* this function extensively.
*
* Note: While the observable-based actions
* dispatches only reducers registered for that slice, the string based action dispatch here will forward the
* action to ALL stores, (sub-)slice and parent alike so make sure you separate your actions based on the strings.
*/
public dispatch<P>(actionName: string, actionPayload: P) {
this.actionDispatch.next({ actionName, actionPayload });
}
}
function mutateRootState<S, TSlice>(
rootState: S,
forwardProjections: Function[],
backwardProjections: Function[],
sliceReducer: (state: TSlice) => TSlice,
) {
// transform the rootstate to a slice by applying all forward projections
let forwardState: any = rootState;
const intermediaryState = [rootState] as any[];
forwardProjections.map(fp => {
forwardState = fp.call(undefined, forwardState);
intermediaryState.push(forwardState);
});
// perform the reduction
const reducedState = sliceReducer(forwardState);
// apply all backward projections to obtain the root state again
let backwardState = reducedState;
[...backwardProjections].map((bp, index) => {
const intermediaryIndex = intermediaryState.length - index - 2;
backwardState = bp.call(undefined, backwardState, intermediaryState[intermediaryIndex]);
});
return backwardState;
} | the_stack |
import express from "express";
import path from "path";
import fs from "fs";
import os from "os";
import { getHandlebars } from '../handlebar'
import logger from "../logger";
import { ProxyResponse } from "../handlebar/ProxyHelper";
import * as httpProxy from "http-proxy";
const proxy = httpProxy.createProxyServer({});
let DELAY = 0;
const Handlebars = getHandlebars()
/**
* Create a parser class which defines methods to parse
* 1. Request URL to get a matching directory
* 2. From matched directory get .mock file content and generate a response
*/
export class HttpParser {
private req: express.Request;
private mockDir: string;
private res: express.Response;
/**
*
* @param {express.Request} req Express Request object for current instance of incoming request
* @param {express.Response} res Express response to be sent to client
* @param {string} mockDir location of http mocks
*/
constructor(req: express.Request, res: express.Response, mockDir: string) {
this.req = req;
this.mockDir = mockDir;
this.res = res;
}
/**
* Finds a closest match dir for an incoming request
* @returns {string} matchedDir for a given incoming request
*/
getMatchedDir = (): string => {
const reqDetails = {
method: this.req.method.toUpperCase(),
path: this.req.path,
protocol: this.req.protocol,
httpVersion: this.req.httpVersion,
query: this.req.query,
headers: this.req.headers,
body: this.req.body,
};
const matchedDir = getWildcardPath(reqDetails.path, this.mockDir);
return matchedDir;
};
/**
* Defines a default response, if the closest matchedDir is present, parses and sends the response from mockfile,
* Looks for API Level, and Global level default response overrides if mockfile is not found.
* If no default response overrides are found, send the defined default response
* @param {string} mockFile location of of the closest mached mockfile for incoming request
* @returns {string} matchedDir for a given incoming request
*/
getResponse = (mockFile: string) => {
// Default response
const response = {
status: 404,
body: '{"error": "Not Found"}',
headers: {
"content-type": "application/json",
},
};
// Check if mock file exists
if (fs.existsSync(mockFile)) {
this.prepareResponse(mockFile);
} else {
logger.error(`No suitable mock file found: ${mockFile}`);
if (fs.existsSync(path.join(this.mockDir, "__", "GET.mock"))) {
logger.debug(`Found a custom global override for default response. Sending custom default response.`);
this.prepareResponse(path.join(this.mockDir, "__", "GET.mock"));
} else {
//If no mockFile is found, return default response
logger.debug(`No custom global override for default response. Sending default Camouflage response.`);
this.res.statusCode = response.status;
this.res.set(response.headers)
this.res.send(response.body);
}
}
};
/**
* - Since response file contains headers and body both, a PARSE_BODY flag is required to tell the logic if it's currently parsing headers or body
* - Set responseBody to an empty string and set a default response object
* - Set default response
* - Compile the handlebars used in the contents of mockFile
* - Generate actual response i.e. replace handlebars with their actual values and split the content into lines
* - If the mockfile contains the delimiter ====, split the content using the delimiter and pick one of the responses at random
* - Split file contents by os.EOL and read file line by line
* - Set PARSE_BODY flag to try when reader finds a blank line, since according to standard format of a raw HTTP Response, headers and body are separated by a blank line.
* - If line includes HTTP/HTTPS i.e. first line. Get the response status code
* - If following conditions are met:
* - Line is not blank; and
* - Parser is not currently parsing response body yet i.e. PARSE_BODY === false
* - Then:
* - Split line by :, of which first part will be header key and 2nd part will be header value
* - If headerKey is response delay, set variable DELAY to headerValue
* - If parsing response body, i.e. PARSE_BODY === true. Concatenate every line till last line to a responseBody variable
* - If on last line of response, do following:
* - Trim and remove whitespaces from the responseBody
* - Compile the Handlebars to generate a final response
* - Set PARSE_BODY flag back to false and responseBody to blank
* - Set express.Response Status code to response.status
* - Send the generated Response, from a timeout set to send the response after a DELAY value
* @param {string} mockFile location of of the closest mached mockfile for incoming request
*/
private prepareResponse = async (mockFile: string) => {
let PARSE_BODY = false;
let responseBody = "";
const response = {
status: 404,
body: '{"error": "Not Found"}',
headers: {
"content-type": "application/json",
},
};
const template = Handlebars.compile(fs.readFileSync(mockFile).toString());
let fileResponse = await template({ request: this.req, logger: logger });
if (fileResponse.includes("====")) {
const fileContentArray = removeBlanks(fileResponse.split("===="));
fileResponse = fileContentArray[Math.floor(Math.random() * fileContentArray.length)];
}
const newLine = getNewLine(fileResponse);
const fileContent = fileResponse.trim().split(newLine);
fileContent.forEach((line: string, index: number) => {
if (line === "") {
PARSE_BODY = true;
}
if (line.includes("HTTP")) {
const regex = /(?<=HTTP\/\d).*?\s+(\d{3,3})/i;
if (!regex.test(line)) {
logger.error("Response code should be valid string");
throw new Error("Response code should be valid string");
}
response.status = <number>(<unknown>line.match(regex)[1]);
logger.debug("Response Status set to " + response.status);
} else {
if (line !== "" && !PARSE_BODY) {
const headerKey = line.split(":")[0];
const headerValue = line.split(":").slice(1).join(":");
if (headerKey === "Response-Delay") {
DELAY = <number>(<unknown>headerValue);
logger.debug(`Delay Set ${headerValue}`);
} else {
this.res.setHeader(headerKey, headerValue);
logger.debug(`Headers Set ${headerKey}: ${headerValue}`);
}
}
}
if (PARSE_BODY) {
responseBody = responseBody + line;
}
if (index == fileContent.length - 1) {
this.res.statusCode = response.status;
if (responseBody.includes("camouflage_file_helper")) {
const fileResponse = responseBody.split(";")[1];
if (!fs.existsSync(fileResponse)) this.res.status(404)
setTimeout(() => {
this.res.sendFile(fileResponse);
}, DELAY);
} else {
responseBody = responseBody.replace(/\s+/g, " ").trim();
responseBody = responseBody.replace(/{{{/, "{ {{");
responseBody = responseBody.replace(/}}}/, "}} }");
const template = Handlebars.compile(responseBody);
try {
const codeResponse = JSON.parse(responseBody.replace(/"/g, "\""));
switch (codeResponse["CamouflageResponseType"]) {
case "code":
this.res.statusCode = codeResponse["status"] || this.res.statusCode;
if (codeResponse["headers"]) {
this.res.set(codeResponse["headers"])
}
setTimeout(() => {
logger.debug(`Generated Response ${codeResponse["body"]}`);
this.res.send(codeResponse["body"]);
});
break;
case "proxy":
/* eslint-disable no-case-declarations */
const proxyResponse: ProxyResponse = JSON.parse(responseBody);
/* eslint-disable no-case-declarations */
proxy.web(this.req, this.res, proxyResponse.options);
break;
case "fault":
const faultType = codeResponse["FaultType"];
switch (faultType) {
case "ERR_EMPTY_RESPONSE":
this.res.socket.destroy()
break;
case "ERR_INCOMPLETE_CHUNKED_ENCODING":
this.res.writeHead(200);
this.res.write('123sdlyndb;aie10-)(&2*2++1dnb/vlaj');
setTimeout(() => {
this.res.socket.destroy();
}, 100);
break;
case "ERR_CONTENT_LENGTH_MISMATCH":
this.res.setHeader('Content-Length', 100);
this.res.writeHead(200);
this.res.write('123sdlyndb;aie10-)(&2*2++1dnb/vlaj');
setTimeout(() => {
this.res.socket.destroy();
}, 100);
break;
default:
break;
}
break;
default:
setTimeout(async () => {
logger.debug(`Generated Response ${await template({ request: this.req, logger: logger })}`);
this.res.send(await template({ request: this.req, logger: logger }));
}, DELAY);
break;
}
} catch (error) {
logger.warn(error.message);
setTimeout(async () => {
logger.debug(`Generated Response ${await template({ request: this.req, logger: logger })}`);
this.res.send(await template({ request: this.req, logger: logger }));
}, DELAY);
}
}
PARSE_BODY = false;
responseBody = "";
DELAY = 0;
}
});
};
}
const removeBlanks = (array: Array<any>) => {
return array.filter(function (i) {
return i;
});
};
const getWildcardPath = (dir: string, mockDir: string) => {
const steps = removeBlanks(dir.split("/"));
let testPath;
let newPath = path.resolve(mockDir);
while (steps.length) {
const next = steps.shift();
testPath = path.join(newPath, next);
if (fs.existsSync(testPath)) {
newPath = testPath;
testPath = path.join(newPath, next);
} else {
testPath = path.join(newPath, "__");
if (fs.existsSync(testPath)) {
newPath = testPath;
continue;
} else {
newPath = testPath;
break;
}
}
}
return newPath;
};
const getNewLine = (source: string) => {
const cr = source.split("\r").length;
const lf = source.split("\n").length;
const crlf = source.split("\r\n").length;
if (cr + lf === 0) {
logger.warn(`No valid new line found in the mock file. Using OS default: ${os.EOL}`);
return os.EOL;
}
if (crlf === cr && crlf === lf) {
logger.debug("Using new line as \\r\\n")
return "\r\n";
}
if (cr > lf) {
logger.debug("Using new line as \\r")
return "\r";
} else {
logger.debug("Using new line as \\n")
return "\n";
}
} | the_stack |
import React, {useState, useEffect} from 'react';
import sanitize from 'sanitize-filename';
import {createClient, AuthType, FileStat, ResponseDataDetailed, BufferLike} from "webdav/web";
import EventEmitter from "eventemitter3";
import {
RenameArgs,
NewFileCreateArgs,
OnNewfileCreatedArgs,
FileTreeEntry,
NewFolderCreateArgs,
UploadFilesArgs, StatusMessageArgs, SaveFileArgs
} from "./typedefs";
import filesize from "filesize";
//const connectionstring: string = "http://localhost:8000"
const connectionstring: string = "https://webdav.reactoxide.com/"
export const webdavClient = createClient(connectionstring, {
//username: "username",
//password: "password"
});
const maxFileSize: number = 10 * 1000 * 1000; // 10 megabytes
type Props = {
emitter: EventEmitter<string | symbol, any>;
}
type LoadFileResult = {
filename: string,
response: Buffer | ArrayBuffer | string | ResponseDataDetailed<BufferLike | string>,
}
const standardiseDirectoryPath = (directory: string) => {
// returns a cleaned up directory path including top slash and tail slash
let directoryArray: string[] = directory.split("/")
// double slashes in the source string with result in the array containing items that are empty strings
// remove them via filter
directoryArray = directoryArray.filter(item => item !== "")
// stick it back together into a nicely cleaned up string, wiuthout a trailing slash
let directoryString = directoryArray.join("/")
if (!directoryString.startsWith("/")) {
directoryString = "/" + directoryString
}
if (!directoryString.endsWith("/")) {
directoryString += "/"
}
return directoryString
}
export const useWebdav = ({emitter}: Props) => {
const [getDirectoryItems, setDirectoryItems] = useState<Array<FileTreeEntry>>([]);
const [getLoadFileResult, setLoadFileResult] = useState<LoadFileResult>();
const [getOpenFiles, setOpenFiles] = React.useState<string[]>([])
const getDirectoryContents = async (directory: string) => {
const result = await webdavClient.getDirectoryContents(standardiseDirectoryPath(directory));
let rv: Array<FileTreeEntry> = []
for (const item of result as Array<FileStat>) {
rv.push({
containingDirectoryPath: standardiseDirectoryPath(directory),
depth: item.filename.split("/").length - 2, // minus root, minus filename
dummy: false,
filePath: item.filename,
id: item.filename,
isDirectoryOpen: false,
isSelected: false,
type: item.type,
})
}
return rv
}
const loadSubtree = React.useCallback(async (directory: string) => {
// load the new directory entries and store in a variable
const newFileTreeEntries = await getDirectoryContents(directory)
directory = standardiseDirectoryPath(directory)
setDirectoryItems((prev) => {
// get information about which directories are open
let opendirectories = prev.filter((item) => item.isDirectoryOpen).map((item) => standardiseDirectoryPath(item.filePath))
// we have to manually add the directory we are currently opening
opendirectories.push(directory)
// root must be manually added
if (!opendirectories.includes("/")) {
opendirectories.push("/")
}
let rv: FileTreeEntry[] = []
// remove the subdirectory entries
rv = prev.filter((item) => item.containingDirectoryPath !== directory)
// append the newly loaded entries
rv = [...rv, ...newFileTreeEntries]
// restore information about which directories are open
rv = rv.map((item) => {
if ((item.type === "directory") && opendirectories.includes(item.filePath + "/")) {
return {...item, isDirectoryOpen: true}
}
return {...item, isDirectoryOpen: false}
})
// mark this directory as open
const directoryItem = rv.find((item) => (item.filePath === directory) && (item.type === "directory"))
if (directoryItem !== undefined) {
const arrayIndex = rv.findIndex(((item) => item.filePath === directoryItem.filePath));
if (arrayIndex !== -1) {
rv[arrayIndex].isDirectoryOpen = true
}
}
// get id of the selected file tree item
const selectedItem = prev.find((item) => item.isSelected)
// restore the selected file tree item
//Find index of specific object using findIndex method.
if (selectedItem !== undefined) {
const arrayIndex = rv.findIndex(((item) => item.id === selectedItem.id));
if (arrayIndex !== -1) {
rv[arrayIndex].isSelected = true
}
}
// removed orphaned subdirectory entries
// it is possible that there was an open directory that is now gone, leaving orphaned items in the filetree
// we must remove them
rv = rv.filter((item) => opendirectories.includes(item.containingDirectoryPath))
return rv
})
}, [setDirectoryItems])
const transformGetDirectoryItems = React.useCallback(() => {
return getDirectoryItems.map((item: FileTreeEntry): FileTreeEntry => {
const id = (item.type === "directory") ? standardiseDirectoryPath(item.filePath) : item.filePath
return {
containingDirectoryPath: standardiseDirectoryPath(item.containingDirectoryPath),
depth: item.depth, // minus root, minus filename
dummy: false,
filePath: item.filePath,
id: id,
isDirectoryOpen: item.isDirectoryOpen,
isSelected: item.isSelected,
type: item.type,
}
})
}, [getDirectoryItems])
useEffect(() => {
const doSelectFileOrDirectory = (fileTreeEntry: FileTreeEntry) => {
/* if (fileTreeEntry.filePath !== undefined) {
alert("undefined")
}*/
setDirectoryItems((prev) => {
return prev.map((item) => {
if (fileTreeEntry.id === item.id) {
return {...item, isSelected: true}
}
return {...item, isSelected: false}
})
})
// open the file, but only if it is not already open
if (!getOpenFiles.includes(fileTreeEntry.filePath)) {
emitter.emit("DO_LOAD_FILE", fileTreeEntry)
}
}
emitter.addListener("DO_SELECT_FILE_OR_DIRECTORY", doSelectFileOrDirectory)
return () => {
emitter.removeListener("DO_SELECT_FILE_OR_DIRECTORY", doSelectFileOrDirectory)
}
}, [emitter, setDirectoryItems, getOpenFiles])
useEffect(() => {
const handler = (openFiles: string[]) => {
console.log("ON_OPEN_FILES_CHANGED", openFiles)
setOpenFiles(openFiles)
}
emitter.addListener("ON_OPEN_FILES_CHANGED", handler)
return () => {
emitter.removeListener("ON_OPEN_FILES_CHANGED", handler)
}
}, [emitter, setOpenFiles])
useEffect(() => {
const init = async () => {
await loadSubtree("/");
}
init();
}, [loadSubtree]);
useEffect(() => {
const asyncHandler = async (fileTreeEntry: FileTreeEntry) => {
await loadSubtree(fileTreeEntry.filePath)
}
const handler = (fileTreeEntry: FileTreeEntry) => asyncHandler(fileTreeEntry)
emitter.addListener("ON_DIRECTORY_OPEN", handler)
return () => {
emitter.removeListener("ON_DIRECTORY_OPEN", handler)
}
}, [loadSubtree, setDirectoryItems, emitter])
const closeSubdirectory = React.useCallback((fileTreeEntry: FileTreeEntry) => {
setDirectoryItems((prev) => {
return prev.map((item) => {
if ((item.filePath === fileTreeEntry.filePath) && (item.type === "directory")) {
return {...item, isDirectoryOpen: false}
}
return item
})
}
)
setDirectoryItems((prev) => {
//removeDirectoryItems(prev)
return prev.filter((item) => {
if (item.filePath === standardiseDirectoryPath(fileTreeEntry.filePath)) {
return true
}
return !item.filePath.startsWith(standardiseDirectoryPath(fileTreeEntry.filePath)) // NOTE TRAILING SLASH!
})
});
}, [setDirectoryItems])
useEffect(() => {
emitter.addListener("ON_DIRECTORY_CLOSE", closeSubdirectory)
return () => {
emitter.removeListener("ON_DIRECTORY_CLOSE", closeSubdirectory)
}
}, [emitter, closeSubdirectory])
useEffect(() => {
const asyncHandler = async (fileTreeEntry: FileTreeEntry) => {
await loadSubtree(fileTreeEntry.containingDirectoryPath);
}
const handler = (fileTreeEntry: FileTreeEntry) => asyncHandler(fileTreeEntry)
emitter.addListener("ON_FILE_RENAMED", handler)
return () => {
emitter.removeListener("ON_FILE_RENAMED", handler)
}
}, [emitter, setDirectoryItems])
useEffect(() => {
const asyncHandler = async (fileTreeEntry: FileTreeEntry) => {
setDirectoryItems((prev) => {
// remove any file from the tree that is underneath the renamed directoiry
return prev.filter((item) => {
// we DONT remove the renamed directory itself, because doing so disappears it from the tree
if (item.filePath === fileTreeEntry.filePath) {
return true
}
// NOTE THE ADDED SLASH! Without this, NAY directory starting the the target name is removed
return !item.filePath.startsWith(`${fileTreeEntry.filePath}/`)
})
});
// then reload the directory that the renamed directory lives in
await loadSubtree(fileTreeEntry.containingDirectoryPath);
}
const handler = (fileTreeEntry: FileTreeEntry) => asyncHandler(fileTreeEntry)
emitter.addListener("ON_DIRECTORY_RENAMED", handler)
return () => {
emitter.removeListener("ON_DIRECTORY_RENAMED", handler)
}
}, [emitter, setDirectoryItems]
)
useEffect(() => {
const asyncHandler = async (fileTreeEntry: FileTreeEntry) => {
await loadSubtree(fileTreeEntry.containingDirectoryPath);
}
const handler = (fileTreeEntry: FileTreeEntry) => asyncHandler(fileTreeEntry)
emitter.addListener("ON_FILE_OR_DIRECTORY_DELETED", handler)
return () => {
emitter.removeListener("ON_FILE_OR_DIRECTORY_DELETED", handler)
}
}, [emitter])
useEffect(() => {
const asyncHandler = async (fileTreeEntry: FileTreeEntry) => {
//const stat: FileStat | ResponseDataDetailed<FileStat> = await webdavClient.stat(fileTreeEntry.filePath);
// grrr can't wrk out corrcet syntax to get the size property with correct typing
const stat: any = await webdavClient.stat(fileTreeEntry.filePath);
// maxFileSize 0 means do not enforce a maximum
if (maxFileSize > 0) {
if (stat.size > maxFileSize) {
alert(`file size (${filesize(stat.size)}) exceeds maxFileSize ${filesize(maxFileSize)}`)
return
}
}
const response = await webdavClient.getFileContents(fileTreeEntry.filePath);
//const rv = await webdavClient.getFileContents(filename, {format: "text"});
setLoadFileResult(
{
filename: fileTreeEntry.filePath,
response: response,
}
);
emitter.emit("ON_FILE_LOADED", {
filename: fileTreeEntry.filePath,
response: response,
})
}
const handler = (fileTreeEntry: FileTreeEntry) => asyncHandler(fileTreeEntry)
emitter.addListener("DO_LOAD_FILE", handler)
return () => {
emitter.removeListener("DO_LOAD_FILE", handler)
}
}, [emitter])
useEffect(() => {
const asyncHandler = async (saveFileArgs: SaveFileArgs) => {
const {filepath, data} = saveFileArgs
const response = await webdavClient.putFileContents(filepath, data);
emitter.emit("ON_FILE_SAVED")
}
const handler = (saveFileArgs: SaveFileArgs) => asyncHandler(saveFileArgs)
emitter.addListener("DO_SAVE_FILE", handler)
return () => {
emitter.removeListener("DO_SAVE_FILE", handler)
}
}, [emitter])
useEffect(() => {
const asyncHandler = async (fileTreeEntry: FileTreeEntry) => {
const response = await webdavClient.deleteFile(fileTreeEntry.filePath);
// after deletion of a file or directory we tell the rest of the system to clean up
emitter.emit("ON_FILE_OR_DIRECTORY_DELETED", fileTreeEntry)
// after deletion of a file or directory we make sure nothing is selected
emitter.emit("DO_DESELECT_ALL")
}
const handler = (fileTreeEntry: FileTreeEntry) => asyncHandler(fileTreeEntry)
emitter.addListener("DO_DELETE_FILE_OR_DIRECTORY", handler)
return () => {
emitter.removeListener("DO_DELETE_FILE_OR_DIRECTORY", handler)
}
}, [emitter])
useEffect(() => {
type Args = {
fileTreeEntry: FileTreeEntry,
destinationName: string;
}
const asyncHandler = async (args: Args) => {
const {fileTreeEntry} = args
if (fileTreeEntry.type === "directory") {
await doRenameDirectory(args)
} else {
await doRenameFile(args)
}
}
const doRenameDirectory = async (args: Args) => {
const {destinationName, fileTreeEntry} = args
// clean up the destinationName - make sure it has no path
let destinationFilename: string = destinationName.split("/").pop() ?? ""
const response = await webdavClient.moveFile(
fileTreeEntry.filePath,
fileTreeEntry.containingDirectoryPath + destinationFilename
);
// after renaming of a file or directory we tell the rest of the system to clean up
emitter.emit("ON_DIRECTORY_RENAMED", fileTreeEntry)
// after renaming of a file or directory we make sure nothing is selected
emitter.emit("DO_DESELECT_ALL")
}
const doRenameFile = async (args: Args) => {
// we start with a source absolute path (sourceAbsolutePath) and the new name of the target item
const {destinationName, fileTreeEntry} = args
// clean up the destinationName - make sure it has no path
let destinationFilename: string = destinationName.split("/").pop() ?? ""
const response = await webdavClient.moveFile(
fileTreeEntry.filePath,
fileTreeEntry.containingDirectoryPath + destinationFilename
);
// after renaming of a file or directory we tell the rest of the system to clean up
emitter.emit("ON_FILE_RENAMED", fileTreeEntry)
// after renaming of a file or directory we make sure nothing is selected
emitter.emit("DO_DESELECT_ALL")
}
const handler = (args: Args) => asyncHandler(args)
emitter.addListener("DO_RENAME_FILE_OR_DIRECTORY", handler)
return () => {
emitter.removeListener("DO_RENAME_FILE_OR_DIRECTORY", handler)
}
}, [emitter])
useEffect(() => {
const asyncHandler = async (directory: string) => {
// we remove all the open items from the tree that live under the renamed directory
// there's probably a way to do this whilst retaining the open/closed state of all directories
// but it got too hard and it doesn't matter enough to pursue
setDirectoryItems((prev) => {
return prev.filter((item) => {
return !(standardiseDirectoryPath(item.containingDirectoryPath) === standardiseDirectoryPath(directory))
})
});
await loadSubtree(directory);
}
const handler = (directory: string) => asyncHandler(directory)
emitter.addListener("ON_FILE_CREATED", handler)
return () => {
emitter.removeListener("ON_FILE_CREATED", handler)
}
}, [emitter, loadSubtree, setDirectoryItems])
useEffect(() => {
const asyncHandler = async (args: NewFileCreateArgs) => {
let {newFilename, fileTreeEntry} = args
// if the user clicked the "new file" icon on a file, then we create the file in the directory of the file
// if the user clicked the "new file" icon on a directory, then we create the file inside that directory
let targetDirectory: string;
if (fileTreeEntry.type === "directory") {
// so, if it's a file, we get the target directory by removing the filename
targetDirectory = standardiseDirectoryPath(fileTreeEntry.filePath) + "/"
} else {
targetDirectory = standardiseDirectoryPath(fileTreeEntry.containingDirectoryPath) + "/"
}
// clean up the destinationName - make sure it has no path
newFilename = newFilename.split("/").pop() ?? ""
const data: string = ""
const response = await webdavClient.putFileContents(targetDirectory + newFilename, data);
// after renaming of a file or directory we tell the rest of the system to clean up
emitter.emit("ON_FILE_CREATED", targetDirectory)
// after renaming of a file or directory we make sure nothing is selected
emitter.emit("DO_DESELECT_ALL")
}
const handler = (args: NewFileCreateArgs) => asyncHandler(args)
emitter.addListener("DO_NEWFILE_CREATE", handler)
return () => {
emitter.removeListener("DO_NEWFILE_CREATE", handler)
}
}, [emitter])
useEffect(() => {
const asyncHandler = async (directory: string) => {
// we remove all the open items from the tree that live under the renamed directory
// there's probably a way to do this whilst retaining the open/closed state of all directories
// but it got too hard and it doesn't matter enough to pursue
setDirectoryItems((prev) => {
return prev.filter((item) => {
return !(standardiseDirectoryPath(item.containingDirectoryPath) === standardiseDirectoryPath(directory))
})
});
await loadSubtree(directory);
}
const handler = (directory: string) => asyncHandler(directory)
emitter.addListener("ON_FOLDER_CREATED", handler)
return () => {
emitter.removeListener("ON_FOLDER_CREATED", handler)
}
}, [emitter, loadSubtree, setDirectoryItems])
useEffect(() => {
const asyncHandler = async (args: NewFolderCreateArgs) => {
let {newFoldername, fileTreeEntry} = args
// if the user clicked the "new file" icon on a file, then we create the file in the directory of the file
// if the user clicked the "new file" icon on a directory, then we create the file inside that directory
let targetDirectory: string;
if (fileTreeEntry.type === "directory") {
// so, if it's a file, we get the target directory by removing the filename
targetDirectory = standardiseDirectoryPath(fileTreeEntry.filePath) + "/"
} else {
targetDirectory = standardiseDirectoryPath(fileTreeEntry.containingDirectoryPath) + "/"
}
// clean up the destinationName - make sure it has no path
newFoldername = newFoldername.split("/").pop() ?? ""
const data: string = ""
const response = await webdavClient.createDirectory(targetDirectory + newFoldername);
// after renaming of a file or directory we tell the rest of the system to clean up
emitter.emit("ON_FOLDER_CREATED", targetDirectory)
// after renaming of a file or directory we make sure nothing is selected
emitter.emit("DO_DESELECT_ALL")
}
const handler = (args: NewFolderCreateArgs) => asyncHandler(args)
emitter.addListener("DO_NEWFOLDER_CREATE", handler)
return () => {
emitter.removeListener("DO_NEWFOLDER_CREATE", handler)
}
}, [emitter])
useEffect(() => {
const asyncHandler = async (targetDirectory: string) => {
await loadSubtree(targetDirectory);
}
const handler = (targetDirectory: string) => asyncHandler(targetDirectory)
emitter.addListener("ON_FILE_UPLOAD_COMPLETE", handler)
return () => {
emitter.removeListener("ON_FILE_UPLOAD_COMPLETE", handler)
}
}, [emitter])
useEffect(() => {
const asyncHandler = async (args: UploadFilesArgs) => {
let {filesToUpload, fileTreeEntry} = args
// if the user clicked the "new file" icon on a file, then we create the file in the directory of the file
// if the user clicked the "new file" icon on a directory, then we create the file inside that directory
let targetDirectory: string;
if (fileTreeEntry.type === "directory") {
// so, if it's a file, we get the target directory by removing the filename
targetDirectory = standardiseDirectoryPath(fileTreeEntry.filePath) + "/"
} else {
targetDirectory = standardiseDirectoryPath(fileTreeEntry.containingDirectoryPath) + "/"
}
for (const file of filesToUpload) {
if (file.name === undefined) return
// clean up the destinationName - make sure it has no path
let filename = file.name.split("/").pop()
if (filename === undefined) return
filename = sanitize(filename)
if (filename === undefined) return
const filedataBuffer = await file.arrayBuffer();
const response = await webdavClient.putFileContents(targetDirectory + filename, filedataBuffer,
{
onUploadProgress: (progress) => {
const args: StatusMessageArgs = {
message: `Uploaded ${progress.loaded} bytes of ${file.size}`,
filename: filename ?? "",
}
emitter.emit("ON_FILE_UPLOAD_PROGRESS", args)
}
});
}
// after renaming of a file or directory we tell the rest of the system to clean up
emitter.emit("ON_FILE_UPLOAD_COMPLETE", targetDirectory)
// after renaming of a file or directory we make sure nothing is selected
emitter.emit("DO_DESELECT_ALL")
}
const handler = (args: UploadFilesArgs) => asyncHandler(args)
emitter.addListener("DO_UPLOAD_FILES", handler)
return () => {
emitter.removeListener("DO_UPLOAD_FILES", handler)
}
}, [emitter])
return {getDirectoryItems: transformGetDirectoryItems} // syntax for aliasing the function name
} | the_stack |
import {
expect
} from 'chai';
import {
Datastore,
Fields,
IServerAdapter,
ListField,
MapField,
RegisterField,
TextField
} from '@phosphor/datastore';
import {
MessageLoop
} from '@phosphor/messaging';
import {
Signal
} from '@phosphor/signaling';
type CustomMetadata = { id: string };
type TestSchema = {
id: string;
fields: {
content: TextField,
count: RegisterField<number>,
enabled: RegisterField<boolean>,
tags: MapField<string>,
links: ListField<string>,
metadata: RegisterField<CustomMetadata>
}
}
let schema1: TestSchema = {
id: 'test-schema-1',
fields: {
content: Fields.Text(),
count:Fields.Number(),
enabled: Fields.Boolean(),
tags: Fields.Map<string>(),
links: Fields.List<string>(),
metadata: Fields.Register<CustomMetadata>({ value: { id: 'identifier' }})
}
};
let schema2: TestSchema = {
id: 'test-schema-2',
fields: {
content: Fields.Text(),
count:Fields.Number(),
enabled: Fields.Boolean(),
tags: Fields.Map<string>(),
links: Fields.List<string>(),
metadata: Fields.Register<CustomMetadata>({ value: { id: 'identifier' }})
}
};
let state = {
[schema1.id]: [
{
content: 'Lorem Ipsum',
count: 42,
enabled: true,
links: ['www.example.com'],
metadata: { id: 'myidentifier' }
}
],
[schema2.id]: [
{
content: 'Ipsum Lorem',
count: 33,
enabled: false,
links: ['www.example.com', 'https://github.com/phosphor/phosphorjs'],
metadata: null
}
]
};
/**
* Return a shuffled copy of an array
*/
function shuffle<T>(array: ReadonlyArray<T>): T[] {
let ret = array.slice();
for (let i = ret.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1)); // random index from 0 to i
[ret[i], ret[j]] = [ret[j], ret[i]]; // swap elements
}
return ret;
}
/**
* An in-memory implementation of a patch store.
*/
class InMemoryServerAdapter implements IServerAdapter {
constructor() {
this.onRemoteTransaction = null;
this.onUndo = null;
this.onRedo = null;
}
broadcast(transaction: Datastore.Transaction): void {
this._transactions[transaction.id] = transaction;
}
undo(id: string): Promise<void> {
if (this.onUndo) {
this.onUndo(this._transactions[id]);
}
return Promise.resolve(undefined);
}
redo(id: string): Promise<void> {
if (this.onRedo) {
this.onRedo(this._transactions[id]);
}
return Promise.resolve(undefined);
}
onRemoteTransaction: ((transaction: Datastore.Transaction) => void) | null;
onUndo: ((transaction: Datastore.Transaction) => void) | null;
onRedo: ((transaction: Datastore.Transaction) => void) | null;
get transactions(): { [id: string]: Datastore.Transaction } {
return this._transactions;
}
get isDisposed(): boolean {
return this._isDisposed;
}
dispose(): void {
if (this._isDisposed) {
return;
}
this._isDisposed = true;
Signal.clearData(this);
}
private _isDisposed = false;
private _transactions: { [id: string]: Datastore.Transaction } = {};
}
describe('@phosphor/datastore', () => {
describe('Datastore', () => {
let datastore: Datastore;
let adapter: InMemoryServerAdapter;
const DATASTORE_ID = 1234;
beforeEach(() => {
adapter = new InMemoryServerAdapter();
datastore = Datastore.create({
id: DATASTORE_ID,
schemas: [schema1, schema2],
adapter
});
});
afterEach(() => {
datastore.dispose();
adapter.dispose();
});
describe('create()', () => {
it('should create a new datastore', () => {
let datastore = Datastore.create({ id: 1, schemas: [schema1] });
expect(datastore).to.be.instanceof(Datastore);
});
it('should throw an error for an invalid schema', () => {
let invalid1 = {
id: 'invalid-schema',
fields: {
'@content': Fields.Text(),
}
};
expect(() => {
Datastore.create({ id: 1, schemas: [invalid1] });
}).to.throw(/validation failed/);
let invalid2 = {
id: 'invalid-schema',
fields: {
'$content': Fields.Text(),
}
};
expect(() => {
Datastore.create({ id: 1, schemas: [invalid2] });
}).to.throw(/validation failed/);
});
it('should restore valid state', () => {
let datastore = Datastore.create({
id: 1,
schemas: [schema1, schema2],
restoreState: JSON.stringify(state)
});
let reexport = datastore.toString();
expect(JSON.parse(reexport)).to.eql(state);
});
it('should restore partial state', () => {
let partialState = {[schema1.id]: state[schema1.id] };
let datastore = Datastore.create({
id: 1,
schemas: [schema1, schema2],
restoreState: JSON.stringify(partialState)
});
let reexport = datastore.toString();
expect(JSON.parse(reexport)).to.eql(
{
...partialState,
[schema2.id]: []
});
});
});
describe('dispose()', () => {
it('should dispose of the resources held by the datastore', () => {
expect(datastore.adapter).to.not.be.null;
datastore.dispose();
expect(datastore.adapter).to.be.null;
});
it('should be safe to call more than once', () => {
datastore.dispose();
datastore.dispose();
});
});
describe('isDisposed()', () => {
it('should indicate whether the datastore is disposed', () => {
expect(datastore.isDisposed).to.be.false;
datastore.dispose();
expect(datastore.isDisposed).to.be.true;
});
});
describe('changed', () => {
it('should should emit upon changes to the datastore', () => {
let called = false;
let id = '';
datastore.changed.connect((_, change) => {
called = true;
expect(change.type).to.equal('transaction');
expect(change.transactionId).to.equal(id);
expect(change.storeId).to.equal(DATASTORE_ID);
expect(change.change['test-schema-1']).to.not.be.undefined;
expect(change.change['test-schema-2']).to.be.undefined;
});
let t1 = datastore.get(schema1);
id = datastore.beginTransaction();
t1.update({ 'my-record': { enabled: true } });
datastore.endTransaction();
expect(called).to.be.true;
});
});
describe('id', () => {
it('should return the unique store id', () => {
expect(datastore.id).to.equal(DATASTORE_ID);
});
});
describe('inTransaction', () => {
it('should indicate whether the datastore is in a transaction', () => {
expect(datastore.inTransaction).to.be.false;
datastore.beginTransaction();
expect(datastore.inTransaction).to.be.true;
datastore.endTransaction();
expect(datastore.inTransaction).to.be.false;
});
});
describe('adapter', () => {
it('should be the adapter for the datastore', () => {
expect(datastore.adapter).to.equal(adapter);
});
it('should recieve transactions from the datastore', () => {
let t2 = datastore.get(schema2);
datastore.beginTransaction();
t2.update({ 'my-record': { enabled: true } });
expect(Object.keys(adapter.transactions).length).to.equal(0);
datastore.endTransaction();
expect(Object.keys(adapter.transactions).length).to.equal(1);
});
});
describe('version', () => {
it('should increase with each transaction', () => {
let version = datastore.version;
let t1 = datastore.get(schema1);
let t2 = datastore.get(schema2);
datastore.beginTransaction();
t2.update({ 'my-record': { enabled: true } });
datastore.endTransaction();
expect(datastore.version).to.be.above(version);
version = datastore.version;
datastore.beginTransaction();
t1.update({ 'my-record': { enabled: true } });
datastore.endTransaction();
expect(datastore.version).to.be.above(version);
});
});
describe('iter()', () => {
it('should return an iterator over the tables of the datastore', () => {
let iterator = datastore.iter();
let t1 = iterator.next();
let t2 = iterator.next();
expect(t1!.schema).to.equal(schema1);
expect(t2!.schema).to.equal(schema2);
expect(iterator.next()).to.be.undefined;
});
});
describe('get()', () => {
it('should return a table for a schema', () => {
let t1 = datastore.get(schema1);
let t2 = datastore.get(schema2);
expect(t1.schema).to.equal(schema1);
expect(t2.schema).to.equal(schema2);
});
it('should throw an error for a nonexistent schema', () => {
let schema3 = { ...schema2, id: 'new-schema' };
expect(() => { datastore.get(schema3); }).to.throw(/No table found/);
});
});
describe('beginTransaction()', () => {
it('should allow for mutations on the datastore', () => {
let t1 = datastore.get(schema1);
expect(datastore.inTransaction).to.be.false;
expect(() => {
t1.update({ 'my-record': { enabled: true } });
}).to.throw(/A table can only be updated/);
datastore.beginTransaction();
t1.update({ 'my-record': { enabled: true } });
expect(datastore.inTransaction).to.be.true;
datastore.endTransaction();
expect(datastore.inTransaction).to.be.false;
});
it('should return a transaction id', () => {
expect(datastore.beginTransaction()).to.not.equal('');
datastore.endTransaction();
});
it('should throw if called multiple times', () => {
datastore.beginTransaction();
expect(() => datastore.beginTransaction()).to.throw(/Already/);
datastore.endTransaction();
});
it('should queue additional transactions for processing later', async () => {
// First, generate a transaction to apply later.
let id = datastore.beginTransaction();
let t2 = datastore.get(schema2);
t2.update({
'my-record': {
content: { index: 0, remove: 0, text: 'hello, world' }
}
});
datastore.endTransaction();
// Create a new datastore
let adapter2 = new InMemoryServerAdapter();
let datastore2 = Datastore.create({
id: 5678,
schemas: [schema1, schema2],
adapter: adapter2
});
// Begin a transaction in the new datastore
datastore2.beginTransaction();
t2 = datastore2.get(schema2);
t2.update({
'my-record': {
enabled: true
}
});
// Trigger a remote transaction. It should be queued.
adapter2.onRemoteTransaction!(adapter.transactions[id]);
datastore2.endTransaction();
expect(t2.get('my-record')!.enabled).to.be.true;
expect(t2.get('my-record')!.content).to.equal('');
// Flush the message loop to trigger processing of the queue.
MessageLoop.flush();
expect(t2.get('my-record')!.enabled).to.be.true;
expect(t2.get('my-record')!.content).to.equal('hello, world');
datastore2.dispose();
adapter2.dispose();
});
it('should automatically close a transaction later', async () => {
datastore.beginTransaction();
expect(datastore.inTransaction).to.be.true;
// Flush the message loop to trigger processing of the queue.
MessageLoop.flush();
expect(datastore.inTransaction).to.be.false;
});
});
describe('endTransaction()', () => {
it('should emit a changed signal with the user-facing changes', () => {
let called = false;
let id = '';
datastore.changed.connect((_, change) => {
called = true;
expect(change.type).to.equal('transaction');
expect(change.transactionId).to.equal(id);
expect(change.storeId).to.equal(DATASTORE_ID);
expect(change.change['test-schema-2']).to.not.be.undefined;
expect(change.change['test-schema-1']).to.be.undefined;
});
let t2 = datastore.get(schema2);
id = datastore.beginTransaction();
t2.update({ 'my-record': { enabled: true } });
datastore.endTransaction();
expect(called).to.be.true;
});
it('should broadcast the transaction to the server adapter', () => {
let t2 = datastore.get(schema2);
datastore.beginTransaction();
t2.update({ 'my-record': { enabled: true } });
expect(Object.keys(adapter.transactions).length).to.equal(0);
datastore.endTransaction();
expect(Object.keys(adapter.transactions).length).to.equal(1);
});
it('should throw if there is not a transaction begun', () => {
expect(() => datastore.endTransaction()).to.throw(/No transaction/);
});
});
describe('undo()', () => {
it('should be throw without a patch server', async () => {
let datastore = Datastore.create({
id: DATASTORE_ID,
schemas: [schema1, schema2]
});
let thrown = false;
try {
await datastore.undo('');
} catch {
thrown = true;
} finally {
expect(thrown).to.be.true;
datastore.dispose();
}
});
it('should throw if invoked during a transaction', async () => {
let thrown = false;
try {
datastore.beginTransaction();
await datastore.undo('');
} catch {
thrown = true;
} finally {
datastore.endTransaction();
expect(thrown).to.be.true;
}
});
it('should unapply a transaction by id', async () => {
let t2 = datastore.get(schema2);
let id = datastore.beginTransaction();
t2.update({ 'my-record': { enabled: true } });
datastore.endTransaction();
let record = t2.get('my-record')!;
expect(record.enabled).to.be.true;
await datastore.undo(id);
record = t2.get('my-record')!;
expect(record.enabled).to.be.false;
});
it ('should allow for multiple undos', async () => {
let t2 = datastore.get(schema2);
let id = datastore.beginTransaction();
t2.update({ 'my-record': { enabled: true } });
datastore.endTransaction();
await datastore.undo(id);
await datastore.undo(id);
await datastore.undo(id);
let record = t2.get('my-record')!;
expect(record.enabled).to.be.false;
});
it('should allow for concurrent undos', async () => {
// Create a transaction.
let t2 = datastore.get(schema2);
let id = datastore.beginTransaction();
t2.update({
'my-record': {
enabled: true,
content: { index: 0, remove: 0, text: 'hello, world' }
}
});
datastore.endTransaction();
let transaction = adapter.transactions[id];
// Create a new datastore and undo the transaction before it's applied.
let datastore2 = Datastore.create({
id: 5678,
schemas: [schema1, schema2],
adapter
});
t2 = datastore2.get(schema2);
// No change for concurrently undone transaction.
adapter.onUndo!(transaction);
let record = t2.get('my-record');
expect(record).to.be.undefined;
// Now apply the transaction, it should be undone still
adapter.onRemoteTransaction!(transaction);
record = t2.get('my-record')!;
expect(record).to.be.undefined;
// Now redo the transaction, it should appear.
adapter.onRedo!(transaction);
record = t2.get('my-record')!;
expect(record.enabled).to.be.true;
expect(record.content).to.equal('hello, world');
});
it('should emit a changed signal when undoing a change', async () => {
let t2 = datastore.get(schema2);
let id = datastore.beginTransaction();
t2.update({ 'my-record': { enabled: true } });
datastore.endTransaction();
let record = t2.get('my-record')!;
expect(record.enabled).to.be.true;
let called = false;
datastore.changed.connect((sender, args) => {
expect(args.type).to.equal('undo');
expect(args.transactionId).to.equal(id);
called = true;
});
await datastore.undo(id);
expect(called).to.be.true;
});
it('should not emit a changed signal when there is nothing to undo', async () => {
let t2 = datastore.get(schema2);
let id = datastore.beginTransaction();
t2.update({ 'my-record': { enabled: true } });
datastore.endTransaction();
let record = t2.get('my-record')!;
expect(record.enabled).to.be.true;
await datastore.undo(id);
let called = false;
datastore.changed.connect((sender, args) => {
called = true;
});
// Already undone, so no signal should be emitted.
await datastore.undo(id);
expect(called).to.be.false;
});
});
describe('redo()', () => {
it('should be throw without a patch server', async () => {
let datastore = Datastore.create({
id: DATASTORE_ID,
schemas: [schema1, schema2]
});
let thrown = false;
try {
await datastore.redo('');
} catch {
thrown = true;
} finally {
expect(thrown).to.be.true;
datastore.dispose();
}
});
it('should throw if invoked during a transaction', async () => {
let thrown = false;
try {
datastore.beginTransaction();
await datastore.redo('');
} catch {
thrown = true;
} finally {
datastore.endTransaction();
expect(thrown).to.be.true;
}
});
it('should reapply a transaction by id', async () => {
let t2 = datastore.get(schema2);
let id = datastore.beginTransaction();
t2.update({
'my-record': {
enabled: true,
content: { index: 0, remove: 0, text: 'hello, world' }
}
});
datastore.endTransaction();
let record = t2.get('my-record')!;
expect(record.enabled).to.be.true;
expect(record.content).to.equal('hello, world');
await datastore.undo(id);
record = t2.get('my-record')!;
expect(record.enabled).to.be.false;
expect(record.content).to.equal('');
await datastore.redo(id);
record = t2.get('my-record')!;
expect(record.enabled).to.be.true;
expect(record.content).to.equal('hello, world');
});
it ('should have redos winning in a tie', async () => {
let t2 = datastore.get(schema2);
let id = datastore.beginTransaction();
t2.update({
'my-record': {
enabled: true,
content: { index: 0, remove: 0, text: 'hello, world' }
}
});
datastore.endTransaction();
let record = t2.get('my-record')!;
expect(record.enabled).to.be.true;
expect(record.content).to.equal('hello, world');
await datastore.undo(id);
await datastore.undo(id);
await datastore.undo(id);
record = t2.get('my-record')!;
expect(record.enabled).to.be.false;
expect(record.content).to.equal('');
await datastore.redo(id);
await datastore.redo(id);
await datastore.redo(id);
record = t2.get('my-record')!;
expect(record.enabled).to.be.true;
expect(record.content).to.equal('hello, world');
});
it ('should be safe to call extra times', async () => {
let t2 = datastore.get(schema2);
let id = datastore.beginTransaction();
t2.update({
'my-record': {
enabled: true,
content: { index: 0, remove: 0, text: 'hello, world' }
}
});
datastore.endTransaction();
let record = t2.get('my-record')!;
expect(record.enabled).to.be.true;
expect(record.content).to.equal('hello, world');
await datastore.undo(id);
record = t2.get('my-record')!;
expect(record.enabled).to.be.false;
expect(record.content).to.equal('');
// Try to redo extra times, should not duplicate the patch.
await datastore.redo(id);
await datastore.redo(id);
await datastore.redo(id);
record = t2.get('my-record')!;
expect(record.enabled).to.be.true;
expect(record.content).to.equal('hello, world');
});
it('should emit a changed signal when redoing a change', async () => {
let t2 = datastore.get(schema2);
let id = datastore.beginTransaction();
t2.update({ 'my-record': { enabled: true } });
datastore.endTransaction();
let record = t2.get('my-record')!;
expect(record.enabled).to.be.true;
await datastore.undo(id);
let called = false;
datastore.changed.connect((sender, args) => {
expect(args.type).to.equal('redo');
expect(args.transactionId).to.equal(id);
called = true;
});
await datastore.redo(id);
expect(called).to.be.true;
});
it('should not emit a changed signal when there is nothing to redo', async () => {
let t2 = datastore.get(schema2);
let id = datastore.beginTransaction();
t2.update({ 'my-record': { enabled: true } });
datastore.endTransaction();
let record = t2.get('my-record')!;
expect(record.enabled).to.be.true;
await datastore.undo(id);
await datastore.redo(id);
let called = false;
datastore.changed.connect((sender, args) => {
called = true;
});
// Already redone, so no signal should be emitted.
await datastore.redo(id);
expect(called).to.be.false;
});
it('should be insensitive to causality', async () => {
// Generate transactions that add then delete a value in a map.
let t2 = datastore.get(schema2);
let id1 = datastore.beginTransaction();
t2.update({ 'record': { tags: { value: 'tagged' } } });
datastore.endTransaction();
expect(t2.get('record')!.tags.value).to.equal('tagged');
let id2 = datastore.beginTransaction();
t2.update({ 'record': { tags: { value: null } } });
datastore.endTransaction();
expect(t2.get('record')!.tags.value).to.be.undefined;
let transaction1 = adapter.transactions[id1];
let transaction2 = adapter.transactions[id2];
// Design a set of undo and redo operations, after which
// transaction1 should be showing, and transaction 2 should not.
let operations = ['t1', 't2', 'u1', 'r1', 'u2', 'u1', 'r1', 'u2', 'r2'];
// Shuffle the operations many times so that we don't accidentally
// get the right answer.
for (let i = 0; i < 20; i++) {
let ops = shuffle(operations);
// Create a new datastore
let adapt = new InMemoryServerAdapter();
let store = Datastore.create({
id: 5678,
schemas: [schema1, schema2],
adapter: adapt
});
let table = store.get(schema2);
for (let op of ops) {
switch (op) {
case 't1':
adapt.onRemoteTransaction!(transaction1);
break;
case 't2':
adapt.onRemoteTransaction!(transaction2);
break;
case 'u1':
adapt.onUndo!(transaction1);
break;
case 'u2':
adapt.onUndo!(transaction2);
break;
case 'r1':
adapt.onRedo!(transaction1);
break;
case 'r2':
adapt.onRedo!(transaction2);
break;
default:
throw 'Unreachable';
break;
}
}
expect(table.get('record')!.tags.value).to.equal('tagged');
adapt.dispose();
store.dispose();
}
});
});
});
}); | the_stack |
import axios from "axios";
import { getLargestVersionFromIntersection } from "./utils";
import { cdiSupported } from "./version";
import NormalisedURLDomain from "./normalisedURLDomain";
import NormalisedURLPath from "./normalisedURLPath";
import { PROCESS_STATE, ProcessState } from "./processState";
export class Querier {
private static initCalled = false;
private static hosts: NormalisedURLDomain[] | undefined = undefined;
private static apiKey: string | undefined = undefined;
private static apiVersion: string | undefined = undefined;
private static lastTriedIndex = 0;
private static hostsAliveForTesting: Set<string> = new Set<string>();
private __hosts: NormalisedURLDomain[] | undefined;
private rIdToCore: string | undefined;
// we have rIdToCore so that recipes can force change the rId sent to core. This is a hack until the core is able
// to support multiple rIds per API
private constructor(hosts: NormalisedURLDomain[] | undefined, rIdToCore?: string) {
this.__hosts = hosts;
this.rIdToCore = rIdToCore;
}
getAPIVersion = async (): Promise<string> => {
if (Querier.apiVersion !== undefined) {
return Querier.apiVersion;
}
ProcessState.getInstance().addState(PROCESS_STATE.CALLING_SERVICE_IN_GET_API_VERSION);
let response = await this.sendRequestHelper(
new NormalisedURLPath("/apiversion"),
"GET",
(url: string) => {
let headers: any = {};
if (Querier.apiKey !== undefined) {
headers = {
"api-key": Querier.apiKey,
};
}
return axios.get(url, {
headers,
});
},
this.__hosts?.length || 0
);
let cdiSupportedByServer: string[] = response.versions;
let supportedVersion = getLargestVersionFromIntersection(cdiSupportedByServer, cdiSupported);
if (supportedVersion === undefined) {
throw Error(
"The running SuperTokens core version is not compatible with this NodeJS SDK. Please visit https://supertokens.io/docs/community/compatibility to find the right versions"
);
}
Querier.apiVersion = supportedVersion;
return Querier.apiVersion;
};
static reset() {
if (process.env.TEST_MODE !== "testing") {
throw Error("calling testing function in non testing env");
}
Querier.initCalled = false;
}
getHostsAliveForTesting = () => {
if (process.env.TEST_MODE !== "testing") {
throw Error("calling testing function in non testing env");
}
return Querier.hostsAliveForTesting;
};
static getNewInstanceOrThrowError(rIdToCore?: string): Querier {
if (!Querier.initCalled) {
throw Error("Please call the supertokens.init function before using SuperTokens");
}
return new Querier(Querier.hosts, rIdToCore);
}
static init(hosts?: NormalisedURLDomain[], apiKey?: string) {
if (!Querier.initCalled) {
Querier.initCalled = true;
Querier.hosts = hosts;
Querier.apiKey = apiKey;
Querier.apiVersion = undefined;
Querier.lastTriedIndex = 0;
Querier.hostsAliveForTesting = new Set<string>();
}
}
// path should start with "/"
sendPostRequest = async (path: NormalisedURLPath, body: any): Promise<any> => {
return this.sendRequestHelper(
path,
"POST",
async (url: string) => {
let apiVersion = await this.getAPIVersion();
let headers: any = {
"cdi-version": apiVersion,
"content-type": "application/json; charset=utf-8",
};
if (Querier.apiKey !== undefined) {
headers = {
...headers,
"api-key": Querier.apiKey,
};
}
if (path.isARecipePath() && this.rIdToCore !== undefined) {
headers = {
...headers,
rid: this.rIdToCore,
};
}
return await axios({
method: "POST",
url,
data: body,
headers,
});
},
this.__hosts?.length || 0
);
};
// path should start with "/"
sendDeleteRequest = async (path: NormalisedURLPath, body: any): Promise<any> => {
return this.sendRequestHelper(
path,
"DELETE",
async (url: string) => {
let apiVersion = await this.getAPIVersion();
let headers: any = { "cdi-version": apiVersion };
if (Querier.apiKey !== undefined) {
headers = {
...headers,
"api-key": Querier.apiKey,
"content-type": "application/json; charset=utf-8",
};
}
if (path.isARecipePath() && this.rIdToCore !== undefined) {
headers = {
...headers,
rid: this.rIdToCore,
};
}
return await axios({
method: "DELETE",
url,
data: body,
headers,
});
},
this.__hosts?.length || 0
);
};
// path should start with "/"
sendGetRequest = async (path: NormalisedURLPath, params: any): Promise<any> => {
return this.sendRequestHelper(
path,
"GET",
async (url: string) => {
let apiVersion = await this.getAPIVersion();
let headers: any = { "cdi-version": apiVersion };
if (Querier.apiKey !== undefined) {
headers = {
...headers,
"api-key": Querier.apiKey,
};
}
if (path.isARecipePath() && this.rIdToCore !== undefined) {
headers = {
...headers,
rid: this.rIdToCore,
};
}
return await axios.get(url, {
params,
headers,
});
},
this.__hosts?.length || 0
);
};
// path should start with "/"
sendPutRequest = async (path: NormalisedURLPath, body: any): Promise<any> => {
return this.sendRequestHelper(
path,
"PUT",
async (url: string) => {
let apiVersion = await this.getAPIVersion();
let headers: any = { "cdi-version": apiVersion };
if (Querier.apiKey !== undefined) {
headers = {
...headers,
"api-key": Querier.apiKey,
"content-type": "application/json; charset=utf-8",
};
}
if (path.isARecipePath() && this.rIdToCore !== undefined) {
headers = {
...headers,
rid: this.rIdToCore,
};
}
return await axios({
method: "PUT",
url,
data: body,
headers,
});
},
this.__hosts?.length || 0
);
};
// path should start with "/"
private sendRequestHelper = async (
path: NormalisedURLPath,
method: string,
axiosFunction: (url: string) => Promise<any>,
numberOfTries: number
): Promise<any> => {
if (this.__hosts === undefined) {
throw Error(
"No SuperTokens core available to query. Please pass supertokens > connectionURI to the init function, or override all the functions of the recipe you are using."
);
}
if (numberOfTries === 0) {
throw Error("No SuperTokens core available to query");
}
let currentHost: string = this.__hosts[Querier.lastTriedIndex].getAsStringDangerous();
Querier.lastTriedIndex++;
Querier.lastTriedIndex = Querier.lastTriedIndex % this.__hosts.length;
try {
ProcessState.getInstance().addState(PROCESS_STATE.CALLING_SERVICE_IN_REQUEST_HELPER);
let response = await axiosFunction(currentHost + path.getAsStringDangerous());
if (process.env.TEST_MODE === "testing") {
Querier.hostsAliveForTesting.add(currentHost);
}
if (response.status !== 200) {
throw response;
}
return response.data;
} catch (err) {
if (err.message !== undefined && err.message.includes("ECONNREFUSED")) {
return await this.sendRequestHelper(path, method, axiosFunction, numberOfTries - 1);
}
if (err.response !== undefined && err.response.status !== undefined && err.response.data !== undefined) {
throw new Error(
"SuperTokens core threw an error for a " +
method +
" request to path: '" +
path.getAsStringDangerous() +
"' with status code: " +
err.response.status +
" and message: " +
err.response.data
);
} else {
throw err;
}
}
};
} | the_stack |
import fetch from "node-fetch";
import { URLSearchParams } from "url";
import { Channel } from "../..";
import { Base } from "../../base";
import type Client from "../../base/Client";
import { ExternalError, HTTPError, InternalError, snakeCasify, TwitchAPIError } from "../../shared";
import { BASE_URL } from "../../shared/";
import type { UserData } from "../../types/classes";
/**
* Represents a user on Twitch.
* @class
* @extends {Base}
*/
export default class User extends Base {
public readonly client;
/**
* Creates a user from the given client and
* @param {Client} client Client that instantiated this user.
* @param {UserData} data The raw data provided by the Twitch API.
* @constructor
*/
public constructor(client: Client, protected data: UserData) {
super(client);
/**
* Client that instantiated this user.
* @type {Client}
* @readonly
*/
this.client = client;
this.client.emit("userCreate", this);
}
/**
* The user's ID.
* @type {string}
* @readonly
*/
public get id() {
return this.data.id;
}
/**
* The user's login name (username but all lowercase).
* @type {string}
* @readonly
*/
public get login() {
return this.data.login;
}
/**
* The user's display name.
* @type {string}
* @readonly
*/
public get displayName() {
return this.data.display_name;
}
/**
* The user's type (staff status).
* @type {string}
* @readonly
*/
public get type() {
return this.data.type;
}
/**
* The user's broadcaster type (partner program).
* @type {string}
* @readonly
*/
public get broadcasterType() {
return this.data.broadcaster_type;
}
/**
* Total number of views on this user's channel.
* @type {number}
* @readonly
*/
public get viewCount() {
return this.data.view_count;
}
/**
* Returns the email of the user (scope `user:read:email` is required).
* @type {string | undefined}
* @readonly
*/
public get email() {
return this.data.email;
}
/**
* The user's description.
* @type {string}
* @readonly
*/
public get description() {
return this.data.description;
}
protected updateDescription(desc: string) {
this.data.description = desc;
}
/**
* The Date object when the user was created.
* @type {Date}
* @readonly
*/
public get createdAt() {
return new Date(this.data.created_at);
}
/**
* The unix timestamp when the user was created.
* @type {number}
* @readonly
*/
public get createdTimestamp() {
return new Date(this.data.created_at).getTime();
}
/**
* Returns the user's avatar URL.
* If `options.offline` is true, the offline avatar will be returned.
* @param {AvatarURLOptions} options Options for the avatar URL.
* @returns {string} The user's avatar URL.
*/
public avatarURL(options?: { offline?: boolean }): string {
return options?.offline ? this.data.offline_image_url : this.data.profile_image_url;
}
/**
* Updates this user object to hold the newest data.
* @returns {Promise<boolean>} True if the update was successful.
*/
public async update(): Promise<boolean> {
if (!this.client.options.update.channels) {
if (!this.client.options.suppressRejections)
throw new Error(`updating users was disabled but was still attempted`);
return false;
}
if (!this.client.token) throw new Error("token is not available");
const response = await fetch(`${BASE_URL}/users?id=${this.id}`, {
headers: {
authorization: `Bearer ${this.client.token}`,
"client-id": this.client.options.clientId,
},
}).catch((e) => {
throw new HTTPError(e);
});
if (response.ok) {
const data = (await response.json())?.data[0];
if (!data) {
if (!this.client.options.suppressRejections)
throw new TwitchAPIError(`user was fetched but no data was returned`);
return false;
}
this.data = data;
return true;
}
if (!this.client.options.suppressRejections) throw new Error("unable to update user");
return false;
}
/**
* Blocks the user. Requires the `user:manage:blocked_users` scope.
* @param {BlockOptions | undefined} options User block options.
* @returns {Promise<boolean>} True if the user was unblocked.
*/
public async block(options?: {
reason?: "chat" | "whisper";
sourceContext?: "spam" | "harassment" | "other";
}): Promise<boolean> {
if (!this.client.scope.includes("user:manage:blocked_users"))
throw new ExternalError(`scope 'user:manage:blocked_users' is required to block users`);
const { reason, sourceContext } = options ?? {};
const response = await fetch(
`${BASE_URL}/users/blocks?${new URLSearchParams(
snakeCasify({
targetUserId: this.id,
reason,
sourceContext,
})
).toString()}`,
{
headers: {
authorization: `Bearer ${this.client.token}`,
"client-id": this.client.options.clientId,
},
method: "PUT",
}
).catch((e) => {
throw new HTTPError(e);
});
if (response.ok) return true;
if (!this.client.options.suppressRejections) throw new TwitchAPIError(`unable to block user`);
return false;
}
/**
* Unblocks the given user. Requires the `user:manage:blocked_users` scope.
* @returns {Promise<boolean>} True if the user was unblocked.
*/
public async unblock(user: User | string): Promise<boolean> {
const id = typeof user === "string" ? user : user.id;
if (!this.client.scope.includes("user:manage:blocked_users"))
throw new ExternalError(`scope 'user:manage:blocked_users' is required to unblock users`);
const response = await fetch(`${BASE_URL}/users/blocks?target_user_id=${id}`, {
method: "DELETE",
headers: {
authorization: `Bearer ${this.client.token}`,
"client-id": this.client.options.clientId,
},
}).catch((e) => {
throw new HTTPError(e);
});
if (response.ok) return true;
if (!this.client.options.suppressRejections) throw new TwitchAPIError(`unable to unblock user`);
return false;
}
/**
* Returns an array of users that are blocked by this user.
* @param {BlocksFetchOptions | undefined} options Fetch options.
* @returns {Promise<User[]>} An array of users that are blocked.
*/
public async fetchBlocks(options?: { first?: number; after?: string }): Promise<User[]> {
const { first, after } = options ?? {};
const response = await fetch(
`${BASE_URL}/users/blocks?${new URLSearchParams(
snakeCasify({ broadcaster_id: this.id, after, first }).toString()
)}`,
{
headers: {
authorization: `Bearer ${this.client.token}`,
"client-id": this.client.options.clientId,
},
method: "delete",
}
).catch((e) => {
throw new HTTPError(e);
});
if (!response.ok) throw new HTTPError(response.statusText);
const { data }: { data: any[] } = await response.json();
let users: User[] = [];
data.forEach((u) => {
let usr = new User(this.client, u);
users.push(usr);
this.client.users.cache.set(usr.id, usr);
});
return users;
}
/**
* Follows a channel.
* @param {Channel | string} channel Channel to follow.
* @returns {Promise<boolean>} True if the follow was successful.
*/
public async follow(channel: Channel | string) {
const id = this.id;
const channelId = channel instanceof Channel ? channel.id : channel;
if (!this.client.token) throw new InternalError(`token is not available`);
const response = await fetch(`${BASE_URL}/users/follows?`, {
headers: {
Authorization: `Bearer ${this.client.token}`,
"Client-Id": this.client.options.clientId,
},
body: JSON.stringify(
snakeCasify({
fromId: id,
toId: channelId,
})
),
method: "POST",
}).catch((e) => {
throw new HTTPError(e);
});
if (!response.ok) {
if (!this.client.options.suppressRejections) throw new TwitchAPIError("Unable to follow user");
return false;
}
return true;
}
/**
* Stops following a channel.
* @param {Channel | string} channel Channel to stop following.
* @returns {Promise<boolean>} True if the unfollow was successful.
*/
public async unfollow(channel: Channel | string) {
const id = this.id;
const channelId = channel instanceof Channel ? channel.id : channel;
if (!this.client.token) throw new InternalError(`token is not available`);
const response = await fetch(
`${BASE_URL}/users/follows?${new URLSearchParams(snakeCasify({ fromId: id, toId: channelId }))}`,
{
headers: {
Authorization: `Bearer ${this.client.token}`,
"Client-Id": this.client.options.clientId,
},
method: "DELETE",
}
).catch((e) => {
throw new HTTPError(e);
});
if (!response.ok) {
if (!this.client.options.suppressRejections) throw new TwitchAPIError("Unable to unfollow user");
return false;
}
return true;
}
}
/**
* Options to retrieve an avatar url.
* @typedef {object} AvatarURLOptions
* @prop {boolean | undefined} offline Fetch offline avatar instead.
*/
/**
* Options for blocking a user.
* @typedef {object} BlockOptions
* @prop {string | undefined} reason Reason for the block.
* @prop {string | undefined} sourceContext Context for the block.
*/
/**
* Options for fetching blocks.
* @typedef {object} BlocksFetchOptions
* @prop {number | undefined} first Offset the first result.
* @prop {string | undefined} after After this date represented as a string.
*/ | the_stack |
import { GrpcError, RpcCode } from '@chopsui/prpc-client';
import { autorun, computed, observable } from 'mobx';
import { fromPromise, IPromiseBasedObservable } from 'mobx-utils';
import { getGitilesRepoURL, renderBugUrlTemplate } from '../libs/build_utils';
import { POTENTIALLY_EXPIRED } from '../libs/constants';
import { createContextLink } from '../libs/context';
import * as iter from '../libs/iter_utils';
import { attachTags, InnerTag, TAG_SOURCE } from '../libs/tag';
import { unwrapObservable } from '../libs/unwrap_observable';
import { BuildExt } from '../models/build_ext';
import {
Build,
BUILD_FIELD_MASK,
BuilderID,
BuilderItem,
GetBuildRequest,
GitilesCommit,
SEARCH_BUILD_FIELD_MASK,
} from '../services/buildbucket';
import { Project, QueryBlamelistRequest, QueryBlamelistResponse } from '../services/milo_internal';
import { getInvIdFromBuildId, getInvIdFromBuildNum } from '../services/resultdb';
import { AppState } from './app_state';
export class GetBuildError extends Error implements InnerTag {
readonly [TAG_SOURCE]: Error;
constructor(source: Error) {
super(source.message);
this[TAG_SOURCE] = source;
}
}
/**
* Records state of a build.
*/
export class BuildState {
@observable.ref builderIdParam?: BuilderID;
@observable.ref buildNumOrIdParam?: string;
/**
* Indicates whether a computed invocation ID should be used.
* Computed invocation ID may not work on older builds.
*/
@observable.ref useComputedInvId = true;
@computed get builderId() {
return this.builderIdParam || this.build?.builder;
}
/**
* buildNum is defined when this.buildNumOrId is defined and doesn't start
* with 'b'.
*/
@computed get buildNum() {
return this.buildNumOrIdParam?.startsWith('b') === false ? Number(this.buildNumOrIdParam) : null;
}
/**
* buildId is defined when this.buildNumOrId is defined and starts with 'b',
* or we have a matching cached build ID in appState.
*/
@computed get buildId() {
const cached =
this.builderIdParam && this.buildNum !== null
? this.appState.getBuildId(this.builderIdParam, this.buildNum)
: null;
return cached || (this.buildNumOrIdParam?.startsWith('b') ? this.buildNumOrIdParam.slice(1) : null);
}
@computed private get invocationId$(): IPromiseBasedObservable<string> {
if (!this.useComputedInvId) {
if (this.build === null) {
return fromPromise(Promise.race([]));
}
const invIdFromBuild = this.build.infra?.resultdb?.invocation?.slice('invocations/'.length) || '';
return fromPromise(Promise.resolve(invIdFromBuild));
} else if (this.buildId) {
// Favor ID over builder + number to ensure cache hit when the build page
// is redirected from a short build link to a long build link.
return fromPromise(Promise.resolve(getInvIdFromBuildId(this.buildId)));
} else if (this.builderIdParam && this.buildNum) {
return fromPromise(getInvIdFromBuildNum(this.builderIdParam, this.buildNum));
} else {
return fromPromise(Promise.race([]));
}
}
@computed get invocationId() {
return unwrapObservable(this.invocationId$, null);
}
private disposers: Array<() => void> = [];
constructor(private appState: AppState) {
this.disposers.push(
autorun(() => {
if (!this.build) {
return;
}
// If the associated gitiles commit is in the blamelist pins, select it.
// Otherwise, select the first blamelist pin.
const buildInputCommitRepo = this.build.associatedGitilesCommit
? getGitilesRepoURL(this.build.associatedGitilesCommit)
: null;
let selectedBlamelistPinIndex =
this.build.blamelistPins.findIndex((pin) => getGitilesRepoURL(pin) === buildInputCommitRepo) || 0;
if (selectedBlamelistPinIndex === -1) {
selectedBlamelistPinIndex = 0;
}
this.selectedBlamelistPinIndex = selectedBlamelistPinIndex;
})
);
}
@observable.ref private isDisposed = false;
/**
* Perform cleanup.
* Must be called before the object is GCed.
*/
dispose() {
this.isDisposed = true;
// Evaluates @computed({keepAlive: true}) properties after this.isDisposed
// is set to true so they no longer subscribes to any external observable.
this.build$;
this.relatedBuilds$;
this.queryBlamelistResIterFns;
this.permittedActions$;
this.projectCfg$;
this.disposers.reverse().forEach((disposer) => disposer());
this.disposers = [];
}
private buildQueryTime = this.appState.timestamp;
@computed({ keepAlive: true })
private get build$(): IPromiseBasedObservable<BuildExt> {
if (
this.isDisposed ||
!this.appState.buildsService ||
(!this.buildId && (!this.builderIdParam || !this.buildNum))
) {
// Returns a promise that never resolves when the dependencies aren't
// ready.
return fromPromise(Promise.race([]));
}
// If we use a simple boolean property here,
// 1. the boolean property cannot be an observable because we don't want to
// update observables in a computed property, and
// 2. we still need an observable (like this.timestamp) to trigger the
// update, and
// 3. this.refresh() will need to reset the boolean properties of all
// time-sensitive computed value.
//
// If we record the query time instead, no other code will need to read
// or update the query time.
const cacheOpt = {
acceptCache: this.buildQueryTime >= this.appState.timestamp,
};
this.buildQueryTime = this.appState.timestamp;
// Favor ID over builder + number to ensure cache hit when the build page is
// redirected from a short build link to a long build link.
const req: GetBuildRequest = this.buildId
? { id: this.buildId, fields: BUILD_FIELD_MASK }
: { builder: this.builderIdParam, buildNumber: this.buildNum!, fields: BUILD_FIELD_MASK };
return fromPromise(
this.appState.buildsService
.getBuild(req, cacheOpt)
.catch((e) => {
if (e instanceof GrpcError && e.code === RpcCode.NOT_FOUND) {
attachTags(e, POTENTIALLY_EXPIRED);
}
throw new GetBuildError(e);
})
.then((b) => new BuildExt(b))
);
}
@computed
get build(): BuildExt | null {
return unwrapObservable(this.build$, null);
}
@computed({ keepAlive: true })
private get relatedBuilds$(): IPromiseBasedObservable<readonly BuildExt[]> {
if (this.isDisposed || !this.build) {
return fromPromise(Promise.race([]));
}
const buildsPromises = this.build.buildSets
// Remove the commit/git/ buildsets because we know they're redundant with
// the commit/gitiles/ buildsets, and we don't need to ask Buildbucket
// twice.
.filter((b) => !b.startsWith('commit/git/'))
.map((b) =>
this.appState
.buildsService!.searchBuilds({
predicate: { tags: [{ key: 'buildset', value: b }] },
fields: SEARCH_BUILD_FIELD_MASK,
pageSize: 1000,
})
.then((res) => res.builds)
);
return fromPromise(
Promise.all(buildsPromises).then((buildArrays) => {
const buildMap = new Map<string, Build>();
for (const builds of buildArrays) {
for (const build of builds) {
// Filter out duplicate builds by overwriting them.
buildMap.set(build.id, build);
}
}
return [...buildMap.values()]
.sort((b1, b2) => (b1.id.length === b2.id.length ? b1.id.localeCompare(b2.id) : b1.id.length - b2.id.length))
.map((b) => new BuildExt(b));
})
);
}
@computed
get relatedBuilds(): readonly BuildExt[] | null {
return unwrapObservable(this.relatedBuilds$, null);
}
@observable.ref selectedBlamelistPinIndex = 0;
private getQueryBlamelistResIterFn(gitilesCommit: GitilesCommit, multiProjectSupport = false) {
if (!this.appState.milo || !this.build) {
// eslint-disable-next-line require-yield
return async function* () {
await Promise.race([]);
};
}
let req: QueryBlamelistRequest = {
gitilesCommit,
builder: this.build.builder,
multiProjectSupport,
};
const milo = this.appState.milo;
async function* streamBlamelist() {
let res: QueryBlamelistResponse;
do {
res = await milo.queryBlamelist(req);
req = { ...req, pageToken: res.nextPageToken };
yield res;
} while (res.nextPageToken);
}
return iter.teeAsync(streamBlamelist());
}
@computed
private get gitilesCommitRepo() {
if (!this.build?.associatedGitilesCommit) {
return null;
}
return getGitilesRepoURL(this.build.associatedGitilesCommit);
}
@computed({ keepAlive: true })
get queryBlamelistResIterFns() {
if (this.isDisposed || !this.build) {
return [];
}
return this.build.blamelistPins.map((pin) => {
const pinRepo = getGitilesRepoURL(pin);
return this.getQueryBlamelistResIterFn(pin, pinRepo !== this.gitilesCommitRepo);
});
}
@computed({ keepAlive: true })
private get builder$() {
// We should not merge this with the if statement below because no other
// observables should be accessed when this.isDisposed is set to true.
if (this.isDisposed) {
return fromPromise(Promise.race([]));
}
if (!this.appState.buildersService || !this.builderId) {
return fromPromise(Promise.race([]));
}
return fromPromise(this.appState.buildersService.getBuilder({ id: this.builderId }));
}
@computed
get builder(): BuilderItem | null {
return unwrapObservable(this.builder$, null);
}
@computed private get bucketResourceId() {
if (!this.builderId) {
return null;
}
return `luci.${this.builderId.project}.${this.builderId.bucket}`;
}
@computed({ keepAlive: true })
private get permittedActions$() {
if (this.isDisposed || !this.appState.accessService || !this.bucketResourceId) {
// Returns a promise that never resolves when the dependencies aren't
// ready.
return fromPromise(Promise.race([]));
}
// Establish a dependency on the timestamp.
this.appState.timestamp;
return fromPromise(
this.appState.accessService?.permittedActions({
resourceKind: 'bucket',
resourceIds: [this.bucketResourceId],
})
);
}
@computed
get permittedActions(): Set<string> {
const permittedActionRes = unwrapObservable(this.permittedActions$, null);
return new Set(permittedActionRes?.permitted[this.bucketResourceId!].actions || []);
}
@computed({ keepAlive: true })
private get projectCfg$() {
if (this.isDisposed || !this.appState.milo || !this.builderId?.project) {
// Returns a promise that never resolves when the dependencies aren't
// ready.
return fromPromise(Promise.race([]));
}
// Establishes a dependency on the timestamp.
this.appState.timestamp;
return fromPromise(
this.appState.milo.getProjectCfg({
project: this.builderId.project,
})
);
}
@computed
private get projectCfg(): Project | null {
return unwrapObservable(this.projectCfg$, null);
}
@computed
get customBugLink(): string | null {
if (!this.build || !this.projectCfg?.bugUrlTemplate) {
return null;
}
return renderBugUrlTemplate(this.projectCfg.bugUrlTemplate, this.build);
}
}
export const [provideBuildState, consumeBuildState] = createContextLink<BuildState>(); | the_stack |
class eKit {
/**
* 根据name关键字创建一个Bitmap对象。name属性请参考resources/resource.json配置文件的内容。
* @param {string} name
* @param {Object} settings?
*/
public static createSprite(settings?: Object) {
let result = new egret.Sprite();
if (settings) {
for (let key in settings) {
result[key] = settings[key];
}
}
return result;
}
/**
* 根据name关键字创建一个Bitmap对象。name属性请参考resources/resource.json配置文件的内容。
* @param {string} name
* @param {Object} settings?
*/
public static createBitmapByName(name: string, settings?: Object): egret.Bitmap {
let result = new egret.Bitmap();
let texture: egret.Texture = RES.getRes(name);
result.texture = texture;
if (settings) {
for (let key in settings) {
result[key] = settings[key];
}
}
return result;
}
/**
* 根据text创建TextField对象
* @param {string} text
* @param {Object} settings?
*/
public static createText(text: string, settings?: Object): egret.TextField {
let result = new egret.TextField();
result.text = text;
if (settings) {
for (let key in settings) {
result[key] = settings[key];
}
}
return result;
}
/**
* 异步根据URL获取头像
* @param {any=''} url
* @param {Object} settings?
*/
public static async createAvatar(url: any = '', settings?: Object) {
return new Promise((resolve, reject) => {
if (!url) { reject('无头像') }
RES.getResByUrl(url, function (evt: any) {
let textTure: egret.Texture = <egret.Texture>evt;
let bitmap: egret.Bitmap = new egret.Bitmap(textTure);
if (settings) {
for (let key in settings) {
bitmap[key] = settings[key];
}
}
resolve(bitmap);
}, this, RES.ResourceItem.TYPE_IMAGE)
})
}
/**
* 根据参数绘制直线段
* @param {Array<any>} points
* @param {{beginFill?:{color:number} param
* @param {number}} alpha
* @param {{thickness?:number} lineStyle?
* @param {number} color?
* @param {number} alpha?
* @param {boolean} pixelHinting?
* @param {string} scaleMode?
* @param {string} caps?
* @param {string} joints?
* @param {number}}} miterLimit?
* @param {Object} settings?
* @returns egret
*/
public static createLine(points: Array<any>, param: { beginFill?: { color: number, alpha: number }, lineStyle?: { thickness?: number, color?: number, alpha?: number, pixelHinting?: boolean, scaleMode?: string, caps?: string, joints?: string, miterLimit?: number } }, settings?: Object): egret.Shape {
let shp = new egret.Shape();
if (param.beginFill) {
shp.graphics.beginFill(param.beginFill.color, param.beginFill.alpha);
}
if (param.lineStyle) {
shp.graphics.lineStyle(param.lineStyle.thickness, param.lineStyle.color, param.lineStyle.alpha, param.lineStyle.pixelHinting, param.lineStyle.scaleMode, param.lineStyle.caps, param.lineStyle.joints, param
.lineStyle.miterLimit);
}
shp.graphics.moveTo(points[0][0], points[0][1]);
points.map((point, index) => {
index > 0 && shp.graphics.lineTo(points[index][0], points[index][1]);
});
shp.graphics.endFill();
if (settings) {
for (let key in settings) {
shp[key] = settings[key];
}
}
return shp;
}
/**
* 根据参数绘制矩形
* @param {Array<any>} points
* @param {{beginFill?:{color:number} param
* @param {number}} alpha
* @param {{thickness?:number} lineStyle?
* @param {number} color?
* @param {number} alpha?
* @param {boolean} pixelHinting?
* @param {string} scaleMode?
* @param {string} caps?
* @param {string} joints?
* @param {number}}} miterLimit?
* @param {Object} settings?
* @returns egret
*/
public static createRect(points: Array<any>, param: { beginFill?: { color: number, alpha: number }, lineStyle?: { thickness?: number, color?: number, alpha?: number, pixelHinting?: boolean, scaleMode?: string, caps?: string, joints?: string, miterLimit?: number } }, settings?: Object): egret.Shape {
let shp = new egret.Shape();
if (param.beginFill) {
shp.graphics.beginFill(param.beginFill.color, param.beginFill.alpha);
}
if (param.lineStyle) {
shp.graphics.lineStyle(param.lineStyle.thickness, param.lineStyle.color, param.lineStyle.alpha, param.lineStyle.pixelHinting, param.lineStyle.scaleMode, param.lineStyle.caps, param.lineStyle.joints, param
.lineStyle.miterLimit);
}
shp.graphics.drawRect(points[0], points[1], points[2], points[3]);
if (settings) {
for (let key in settings) {
shp[key] = settings[key];
}
}
return shp;
}
/**
* 根据参数绘制圆形
* @param {Array<any>} points
* @param {{beginFill?:{color:number} param
* @param {number}} alpha
* @param {{thickness?:number} lineStyle?
* @param {number} color?
* @param {number} alpha?
* @param {boolean} pixelHinting?
* @param {string} scaleMode?
* @param {string} caps?
* @param {string} joints?
* @param {number}}} miterLimit?
* @param {Object} settings?
* @returns egret
*/
public static createCircle(points: Array<any>, param: { beginFill?: { color: number, alpha: number }, lineStyle?: { thickness?: number, color?: number, alpha?: number, pixelHinting?: boolean, scaleMode?: string, caps?: string, joints?: string, miterLimit?: number } }, settings?: Object): egret.Shape {
let shp = new egret.Shape();
if (param.beginFill) {
shp.graphics.beginFill(param.beginFill.color, param.beginFill.alpha);
}
if (param.lineStyle) {
shp.graphics.lineStyle(param.lineStyle.thickness, param.lineStyle.color, param.lineStyle.alpha, param.lineStyle.pixelHinting, param.lineStyle.scaleMode, param.lineStyle.caps, param.lineStyle.joints, param
.lineStyle.miterLimit);
}
shp.graphics.drawCircle(points[0], points[1], points[2]);
if (settings) {
for (let key in settings) {
shp[key] = settings[key];
}
}
return shp;
}
/**
* 根据参数绘制圆弧路径
* @param {Array<any>} points
* @param {{beginFill?:{color:number} param
* @param {number}} alpha
* @param {{thickness?:number} lineStyle?
* @param {number} color?
* @param {number} alpha?
* @param {boolean} pixelHinting?
* @param {string} scaleMode?
* @param {string} caps?
* @param {string} joints?
* @param {number}}} miterLimit?
* @param {Object} settings?
* @returns egret
*/
public static createArc(points: Array<any>, param: { beginFill?: { color: number, alpha: number }, lineStyle?: { thickness?: number, color?: number, alpha?: number, pixelHinting?: boolean, scaleMode?: string, caps?: string, joints?: string, miterLimit?: number } }, settings?: Object): egret.Shape {
let shp = new egret.Shape();
if (param.beginFill) {
shp.graphics.beginFill(param.beginFill.color, param.beginFill.alpha);
}
if (param.lineStyle) {
shp.graphics.lineStyle(param.lineStyle.thickness, param.lineStyle.color, param.lineStyle.alpha, param.lineStyle.pixelHinting, param.lineStyle.scaleMode, param.lineStyle.caps, param.lineStyle.joints, param
.lineStyle.miterLimit);
}
shp.graphics.drawArc(points[0], points[1], points[2], points[3], points[4], points[5]);
if (settings) {
for (let key in settings) {
shp[key] = settings[key];
}
}
return shp;
}
/**
* 根据参数绘制圆角矩形
* @param {Array<any>} points
* @param {{beginFill?:{color:number} param
* @param {number}} alpha
* @param {{thickness?:number} lineStyle?
* @param {number} color?
* @param {number} alpha?
* @param {boolean} pixelHinting?
* @param {string} scaleMode?
* @param {string} caps?
* @param {string} joints?
* @param {number}}} miterLimit?
* @param {Object} settings?
* @returns egret
*/
public static createRoundRect(points: Array<any>, param: { beginFill?: { color: number, alpha: number }, lineStyle?: { thickness?: number, color?: number, alpha?: number, pixelHinting?: boolean, scaleMode?: string, caps?: string, joints?: string, miterLimit?: number } }, settings?: Object): egret.Shape {
let shp = new egret.Shape();
if (param.beginFill) {
shp.graphics.beginFill(param.beginFill.color, param.beginFill.alpha);
}
if (param.lineStyle) {
shp.graphics.lineStyle(param.lineStyle.thickness, param.lineStyle.color, param.lineStyle.alpha, param.lineStyle.pixelHinting, param.lineStyle.scaleMode, param.lineStyle.caps, param.lineStyle.joints, param
.lineStyle.miterLimit);
}
shp.graphics.drawRoundRect(points[0], points[1], points[2], points[3], points[4], points[5]);
if (settings) {
for (let key in settings) {
shp[key] = settings[key];
}
}
return shp;
}
/**
* 传入一个DisplayObject,将其从其父元素上移除
* @param {egret.DisplayObject} children
*/
public static removeChild(children: egret.DisplayObject) {
if (children.parent) {
children.parent.removeChild(children);
}
}
/**
* 清空显示容器内显示元素,可输入start防止索引号之前的元素被清空
* @param {egret.DisplayObjectContainer} displayObjectContainer
* @param {number} start?
*/
public static clearView(displayObjectContainer: egret.DisplayObjectContainer, start?: number) {
isNaN(start) && (start = -1);
while (displayObjectContainer.$children.length > start + 1) {
displayObjectContainer.removeChildAt(start + 1);
}
return true;
}
} | the_stack |
import {fromJwkTo, toJwkFrom} from './converter';
import {getJwkThumbprint} from './thumbprint';
import jseu from 'js-encoding-utils';
import {getJwkType, getSec1KeyType, isAsn1Encrypted, isAsn1Public} from './util';
import {
DER,
OctetEC,
PEM,
KeyFormat,
CurveTypes,
PublicOrPrivate,
KeyExportOptions,
JwkThumbprintFormat, HashTypes
} from './typedef';
const cloneDeep = require('lodash.clonedeep');
type CurrentKeyStatus = {jwk: boolean, der: boolean, oct: boolean};
/**
* Key class to abstract public and private key objects in string or binary.
* This class provides functions to interchangeably convert key formats,
* and key objects will be used for the root package, js-crypto-utils, as inputs to exposed APIs.
*/
export class Key {
private _type: PublicOrPrivate|null;
private _jwk: JsonWebKey|null;
private _der: Uint8Array|null;
private _oct: {namedCurve?: CurveTypes, key?: OctetEC};
private _isEncrypted: boolean;
private _current: CurrentKeyStatus;
/**
* @constructor
* @param {KeyFormat} format - Key format: 'jwk', 'der', 'pem' or 'oct' (only for ECC key).
* @param {JsonWebKey|PEM|DER|OctetEC} key - Key object in the specified format.
* @param {Object} [options={}] - Required if format='oct', and then it is {namedCurve: String}.
* @throws {Error} - Throws if the input format and key are incompatible to the constructor.
*/
constructor(format: KeyFormat, key: JsonWebKey|PEM|DER|OctetEC, options: {namedCurve?: CurveTypes}={}){
const localKey = cloneDeep(key);
const localOpt = cloneDeep(options);
this._type = null;
this._jwk = null;
this._der = null;
this._oct = {}; // only for EC keys
this._isEncrypted = false;
this._current = {jwk: false, der: false, oct: false};
if(format === 'jwk'){
this._setJwk(<JsonWebKey>localKey);
}
else if (format === 'der' || format === 'pem'){
if(format === 'der' && !(localKey instanceof Uint8Array)) throw new Error('DerKeyMustBeUint8Array');
if(format === 'pem' && (typeof localKey !== 'string')) throw new Error('PemKeyMustBeString');
this._setAsn1(<any>localKey, format);
}
else if (format === 'oct'){
if(typeof localOpt.namedCurve !== 'string') throw new Error('namedCurveMustBeSpecified');
if(!(localKey instanceof Uint8Array)) throw new Error('OctetKeyMustBeUint8Array');
this._setSec1(<Uint8Array>localKey, localOpt.namedCurve);
}
else throw new Error('UnsupportedType');
}
///////////////////////////////////////////////////////////
// private method handling instance variables
// all instance variables must be set via these methods
/**
* Set a key in JWK to the Key object.
* @param {JsonWebKey} jwkey - The Json Web Key.
* @private
*/
private _setJwk(jwkey: JsonWebKey){
this._type = getJwkType(jwkey); // this also check key format
this._jwk = jwkey;
if(this._isEncrypted) this._der = null;
this._isEncrypted = false;
this._setCurrentStatus();
}
/**
* Set a key in DER or PEM to the Key object.
* @param {DER|PEM} asn1key - The DER key byte array or PEM key string.
* @param {String} format - 'der' or 'pem' specifying the format.
* @private
*/
private _setAsn1(asn1key: DER|PEM, format: 'der'|'pem'){
this._type = (isAsn1Public(asn1key, format)) ? 'public' : 'private'; // this also check key format
this._isEncrypted = isAsn1Encrypted(asn1key, format);
this._der = <Uint8Array>((format === 'pem') ? jseu.formatter.pemToBin(<PEM>asn1key): asn1key);
if(this._isEncrypted){
this._jwk = null;
this._oct = {};
}
this._setCurrentStatus();
}
/**
* Set a key in SEC1 = Octet format to the Key Object.
* @param {OctetEC} sec1key - The Octet SEC1 key byte array.
* @param {CurveTypes} namedCurve - Name of curve like 'P-256'.
* @private
*/
private _setSec1(sec1key: OctetEC, namedCurve: CurveTypes){
this._type = getSec1KeyType(sec1key, namedCurve); // this also check key format
this._oct = { namedCurve, key: sec1key };
if(this._isEncrypted) this._der = null;
this._isEncrypted = false;
this._setCurrentStatus();
}
/**
* Set the current internal status. In particular, manage what the object is based on.
* @private
*/
private _setCurrentStatus() {
this._current.jwk = (this._jwk !== null && (this._jwk.kty === 'RSA' || this._jwk.kty === 'EC') );
this._current.der = (this._der !== null && this._der.length > 0);
this._current.oct = (
typeof this._oct.key !== 'undefined'
&& typeof this._oct.namedCurve !== 'undefined'
&& this._oct.key.length > 0
);
}
///////////////////////////////////////////////////////////
// (pseudo) public methods allowed to be accessed from outside
/**
* Convert the stored key and export the key in desired format.
* Imported key must be basically decrypted except the case where the key is exported as-is.
* @param {String} format - Intended format of exported key. 'jwk', 'pem', 'der' or 'oct'
* @param {KeyExportOptions} [options={}] - Optional arguments.
* @return {Promise<JsonWebKey|PEM|DER|OctetEC>} - Exported key object.
*/
async export(format: KeyFormat = 'jwk', options: KeyExportOptions = {}): Promise<JsonWebKey|PEM|DER|OctetEC>{
// return 'as is' without passphrase when nothing is given as 'options'
// only for the case to export der key from der key (considering encrypted key). expect to be called from getter
if(this._isEncrypted && this._type === 'private'){
if((format === 'der' || format === 'pem') && Object.keys(options).length === 0 && this._current.der) {
return (format === 'pem') ? jseu.formatter.binToPem(<DER>(this._der), 'encryptedPrivate') : <DER>this._der;
}
else throw new Error('DecryptionRequired');
}
// first converted to jwk
let jwkey: JsonWebKey;
if(this._current.jwk){
jwkey = <JsonWebKey>this._jwk;
}
else if(this._current.oct) { // options.type is not specified here to import jwk
jwkey = await toJwkFrom('oct', <OctetEC>this._oct.key, {namedCurve: this._oct.namedCurve});
}
else if(this._current.der) {
jwkey = await toJwkFrom('der', <DER>this._der);
}
else throw new Error('InvalidStatus');
this._setJwk(jwkey); // store jwk if the exiting private key is not encrypted
// then export as the key in intended format
if (format === 'der' || format === 'pem') {
return await fromJwkTo(format, jwkey, {
outputPublic: options.outputPublic,
compact: options.compact,
//passphrase: options.encryptParams.passphrase,
encryptParams: options.encryptParams
});
}
else if (format === 'oct') {
return await fromJwkTo(format, jwkey, {
outputPublic: options.outputPublic,
output: options.output,
compact: options.compact
});
}
else return jwkey;
}
/**
* Encrypt stored key and set the encrypted key to this instance.
* @param {String} passphrase - String passphrase.
* @return {Promise<boolean>} - Always true otherwise thrown.
* @throws {Error} - Throws if AlreadyEncrypted.
*/
async encrypt (passphrase: string): Promise<boolean>{
if(this._isEncrypted) throw new Error('AlreadyEncrypted');
const options = {encryptParams: {passphrase}};
this._setAsn1(<DER>(await this.export('der', options)), 'der');
return true;
}
/**
* Decrypted stored key and set the decrypted key in JWK to this instance.
* @param {String} passphrase - String passphrase.
* @return {Promise<boolean>} - Always true otherwise thrown.
* @throws {Error} - Throws if NotEncrypted or FailedToDecrypt.
*/
async decrypt (passphrase: string): Promise<boolean>{
if(!this._isEncrypted) throw new Error('NotEncrypted');
let jwkey;
if(this._current.der){
jwkey = await toJwkFrom('der', <DER>this._der, {passphrase}); // type is not specified here to import jwk
}
else throw new Error('FailedToDecrypt');
this._setJwk(jwkey);
return true;
}
/**
* Conpute JWK thumbprint specified in RFC7638 {@link https://tools.ietf.org/html/rfc7638}.
* @param {HashTypes} [alg='SHA-256'] - Name of hash algorithm for thumbprint computation like 'SHA-256'.
* @param {JwkThumbpirntFormat} [output='binary'] - Output format of JWK thumbprint. 'binary', 'hex' or 'base64'.
* @return {Promise<Uint8Array|String>} - Computed thumbprint.
* @throws {Error} - Throws if DecryptionRequired.
*/
async getJwkThumbprint(alg: HashTypes ='SHA-256', output: JwkThumbprintFormat='binary'){
if(this._isEncrypted) throw new Error('DecryptionRequired');
return await getJwkThumbprint(<JsonWebKey>(await this.export('jwk')), alg, output);
}
// getters
/**
* Get keyType in JWK format
* @return {Promise<String>} - 'RSA' or 'EC'
* @throws {Error} - Throws if DecryptionRequired.
*/
get keyType(): Promise<string> {
if(this._isEncrypted) throw new Error('DecryptionRequired');
return new Promise( (resolve, reject) => {
this.export('jwk')
.then( (r) => {
resolve( <string>((<JsonWebKey>r).kty));
})
.catch( (e) => {reject(e);});
});
}
/**
* Get jwkThumbprint of this key.
* @return {Promise<Uint8Array>} - Returns binary thumbprint.
*/
get jwkThumbprint(){
return this.getJwkThumbprint();
}
/**
* Check if this is encrypted.
* @return {boolean}
*/
get isEncrypted(){ return this._isEncrypted; }
/**
* Check if this is a private key.
* @return {boolean}
*/
get isPrivate(){ return this._type === 'private'; }
/**
* Returns the key in DER format.
* @return {Promise<DER>}
*/
get der(){ return this.export('der'); }
/**
* Returns the key in PEM format.
* @return {Promise<PEM>}
*/
get pem(){ return this.export('pem'); }
/**
* Returns the key in JWK format
* @return {Promise<JsonWebKey>}
*/
get jwk(){ return this.export('jwk'); }
/**
* Returns the 'EC' key in Octet SEC1 format.
* @return {Promise<OctetEC>}
*/
get oct(){ return this.export('oct', {output: 'string'}); }
} | the_stack |
"use strict";
import * as path from "path";
import { commands, Uri, window } from "vscode";
import { RepositoryType } from "../contexts/repositorycontext";
import { TfvcContext } from "../contexts/tfvccontext";
import { ExtensionManager } from "../extensionmanager";
import { TfvcCommandNames, TfvcTelemetryEvents } from "../helpers/constants";
import { Strings } from "../helpers/strings";
import { UrlBuilder } from "../helpers/urlbuilder";
import { Utils } from "../helpers/utils";
import { VsCodeUtils } from "../helpers/vscodeutils";
import { IButtonMessageItem } from "../helpers/vscodeutils.interfaces";
import { Telemetry } from "../services/telemetry";
import { Resource } from "./scm/resource";
import { Status } from "./scm/status";
import { TfvcSCMProvider } from "./tfvcscmprovider";
import { TfvcErrorCodes } from "./tfvcerror";
import { TfvcRepository } from "./tfvcrepository";
import { UIHelper } from "./uihelper";
import { AutoResolveType, ICheckinInfo, IItemInfo, ISyncResults } from "./interfaces";
import { TfvcOutput } from "./tfvcoutput";
export class TfvcExtension {
private _repo: TfvcRepository;
private _manager: ExtensionManager;
constructor(manager: ExtensionManager) {
this._manager = manager;
}
public async Checkin(): Promise<void> {
this.displayErrors(
async () => {
// get the checkin info from the SCM viewlet
const checkinInfo: ICheckinInfo = TfvcSCMProvider.GetCheckinInfo();
if (!checkinInfo) {
window.showInformationMessage(Strings.NoChangesToCheckin);
return;
}
Telemetry.SendEvent(this._repo.IsExe ? TfvcTelemetryEvents.CheckinExe : TfvcTelemetryEvents.CheckinClc);
const changeset: string =
await this._repo.Checkin(checkinInfo.files, checkinInfo.comment, checkinInfo.workItemIds);
TfvcOutput.AppendLine(`Changeset ${changeset} checked in.`);
TfvcSCMProvider.ClearCheckinMessage();
TfvcSCMProvider.Refresh();
},
"Checkin");
}
/**
* This command runs a delete command on the selected file. It gets a Uri object from vscode.
*/
public async Delete(uri?: Uri): Promise<void> {
this.displayErrors(
async () => {
if (uri) {
const basename: string = path.basename(uri.fsPath);
try {
const message: string = `Are you sure you want to delete '${basename}'?`;
if (await UIHelper.PromptForConfirmation(message, Strings.DeleteFile)) {
Telemetry.SendEvent(this._repo.IsExe ? TfvcTelemetryEvents.DeleteExe : TfvcTelemetryEvents.DeleteClc);
await this._repo.Delete([uri.fsPath]);
}
} catch (err) {
//Provide a better error message if the file to be deleted isn't in the workspace (e.g., it's a new file)
if (err.tfvcErrorCode && err.tfvcErrorCode === TfvcErrorCodes.FileNotInWorkspace) {
this._manager.DisplayErrorMessage(`Cannot delete '${basename}' as it is not in your workspace.`);
} else {
throw err;
}
}
} else {
this._manager.DisplayWarningMessage(Strings.CommandRequiresExplorerContext);
}
},
"Delete");
}
public async Exclude(resources?: Resource[]): Promise<void> {
this.displayErrors(
async () => {
if (resources && resources.length > 0) {
//Keep an in-memory list of items that were explicitly excluded. The list is not persisted at this time.
const paths: string[] = [];
resources.forEach((resource) => {
paths.push(resource.resourceUri.fsPath);
});
await TfvcSCMProvider.Exclude(paths);
}
},
"Exclude");
}
public async Include(resources?: Resource[]): Promise<void> {
this.displayErrors(
async () => {
if (resources && resources.length > 0) {
const pathsToUnexclude: string[] = [];
const pathsToAdd: string[] = [];
const pathsToDelete: string[] = [];
resources.forEach((resource) => {
const path: string = resource.resourceUri.fsPath;
//Unexclude each file passed in
pathsToUnexclude.push(path);
//At this point, an unversioned file could be a candidate file, so call Add.
//Once it is added, it should be a Pending change.
if (!resource.IsVersioned) {
pathsToAdd.push(path);
}
//If a file is a candidate change and has been deleted (e.g., outside of
//the TFVC command), we need to ensure that it gets 'tf delete' run on it.
if (resource.PendingChange.isCandidate && resource.HasStatus(Status.DELETE)) {
pathsToDelete.push(path);
}
});
//If we need to add files, run a single Add with those files
if (pathsToAdd.length > 0) {
Telemetry.SendEvent(this._repo.IsExe ? TfvcTelemetryEvents.AddExe : TfvcTelemetryEvents.AddClc);
await this._repo.Add(pathsToAdd);
}
//If we need to delete files, run a single Delete with those files
if (pathsToDelete.length > 0) {
Telemetry.SendEvent(this._repo.IsExe ? TfvcTelemetryEvents.DeleteExe : TfvcTelemetryEvents.DeleteClc);
await this._repo.Delete(pathsToDelete);
}
//Otherwise, ensure its not in the explicitly excluded list (if it's already there)
//Unexclude doesn't explicitly INclude. It defers to the status of the individual item.
await TfvcSCMProvider.Unexclude(pathsToUnexclude);
}
},
"Include");
}
/**
* This is the default action when an resource is clicked in the viewlet.
* For ADD, AND UNDELETE just show the local file.
* For DELETE just show the server file.
* For EDIT AND RENAME show the diff window (server on left, local on right).
*/
public async Open(resource?: Resource): Promise<void> {
this.displayErrors(
async () => {
if (resource) {
const left: Uri = TfvcSCMProvider.GetLeftResource(resource);
const right: Uri = TfvcSCMProvider.GetRightResource(resource);
const title: string = resource.GetTitle();
if (!right) {
// TODO
console.error("oh no");
return;
}
if (!left) {
return await commands.executeCommand<void>("vscode.open", right);
}
return await commands.executeCommand<void>("vscode.diff", left, right, title);
}
},
"Open");
}
public async OpenDiff(resource?: Resource): Promise<void> {
this.displayErrors(
async () => {
if (resource) {
return await TfvcSCMProvider.OpenDiff(resource);
}
},
"OpenDiff");
}
public async OpenFile(resource?: Resource): Promise<void> {
this.displayErrors(
async () => {
if (resource) {
return await commands.executeCommand<void>("vscode.open", resource.resourceUri);
}
},
"OpenFile");
}
public async Refresh(): Promise<void> {
this.displayErrors(
async () => {
await TfvcSCMProvider.Refresh();
},
"Refresh");
}
/**
* This command runs a rename command on the selected file. It gets a Uri object from vscode.
*/
public async Rename(uri?: Uri): Promise<void> {
this.displayErrors(
async () => {
if (uri) {
const basename: string = path.basename(uri.fsPath);
const newFilename: string = await window.showInputBox({ value: basename, prompt: Strings.RenamePrompt, placeHolder: undefined, password: false });
if (newFilename && newFilename !== basename) {
const dirName: string = path.dirname(uri.fsPath);
const destination: string = path.join(dirName, newFilename);
try {
Telemetry.SendEvent(this._repo.IsExe ? TfvcTelemetryEvents.RenameExe : TfvcTelemetryEvents.RenameClc);
await this._repo.Rename(uri.fsPath, destination);
} catch (err) {
//Provide a better error message if the file to be renamed isn't in the workspace (e.g., it's a new file)
if (err.tfvcErrorCode && err.tfvcErrorCode === TfvcErrorCodes.FileNotInWorkspace) {
this._manager.DisplayErrorMessage(`Cannot rename '${basename}' as it is not in your workspace.`);
} else {
throw err;
}
}
}
} else {
this._manager.DisplayWarningMessage(Strings.CommandRequiresExplorerContext);
}
},
"Rename");
}
public async Resolve(resource: Resource, autoResolveType: AutoResolveType): Promise<void> {
this.displayErrors(
async () => {
if (resource) {
const localPath: string = resource.resourceUri.fsPath;
const resolveTypeString: string = UIHelper.GetDisplayTextForAutoResolveType(autoResolveType);
const basename: string = path.basename(localPath);
const message: string = `Are you sure you want to resolve changes in '${basename}' as ${resolveTypeString}?`;
if (await UIHelper.PromptForConfirmation(message, resolveTypeString)) {
Telemetry.SendEvent(this._repo.IsExe ? TfvcTelemetryEvents.ResolveConflictsExe : TfvcTelemetryEvents.ResolveConflictsClc);
await this._repo.ResolveConflicts([localPath], autoResolveType);
TfvcSCMProvider.Refresh();
}
} else {
this._manager.DisplayWarningMessage(Strings.CommandRequiresFileContext);
}
},
"Resolve");
}
public async ShowOutput(): Promise<void> {
TfvcOutput.Show();
}
/**
* This command runs a 'tf get' command on the VSCode workspace folder and
* displays the results to the user.
*/
public async Sync(): Promise<void> {
this.displayErrors(
async () => {
Telemetry.SendEvent(this._repo.IsExe ? TfvcTelemetryEvents.SyncExe : TfvcTelemetryEvents.SyncClc);
const results: ISyncResults = await this._repo.Sync([this._repo.Path], true);
await UIHelper.ShowSyncResults(results, results.hasConflicts || results.hasErrors, true);
},
"Sync");
}
/**
* This command runs an undo command on the currently open file in the VSCode workspace folder and
* editor. If the undo command applies to the file, the pending changes will be undone. The
* file system watcher will update the UI soon thereafter. No results are displayed to the user.
*/
public async Undo(resources?: Resource[]): Promise<void> {
this.displayErrors(
async () => {
if (resources) {
const pathsToUndo: string[] = [];
resources.forEach((resource) => {
pathsToUndo.push(resource.resourceUri.fsPath);
});
//When calling from UI, we have the uri of the resource from which the command was invoked
if (pathsToUndo.length > 0) {
const basename: string = path.basename(pathsToUndo[0]);
let message: string = `Are you sure you want to undo changes to '${basename}'?`;
if (pathsToUndo.length > 1) {
message = `Are you sure you want to undo changes to ${pathsToUndo.length.toString()} files?`;
}
if (await UIHelper.PromptForConfirmation(message, Strings.UndoChanges)) {
Telemetry.SendEvent(this._repo.IsExe ? TfvcTelemetryEvents.UndoExe : TfvcTelemetryEvents.UndoClc);
await this._repo.Undo(pathsToUndo);
}
}
}
},
"Undo");
}
/**
* This command runs an undo command on all of the currently open files in the VSCode workspace folder
* If the undo command applies to the file, the pending changes will be undone. The
* file system watcher will update the UI soon thereafter. No results are displayed to the user.
*/
public async UndoAll(): Promise<void> {
this.displayErrors(
async () => {
if (TfvcSCMProvider.HasItems()) {
const message: string = `Are you sure you want to undo all changes?`;
if (await UIHelper.PromptForConfirmation(message, Strings.UndoChanges)) {
Telemetry.SendEvent(this._repo.IsExe ? TfvcTelemetryEvents.UndoAllExe : TfvcTelemetryEvents.UndoAllClc);
await this._repo.Undo(["*"]);
}
} else {
window.showInformationMessage(Strings.NoChangesToUndo);
return;
}
},
"UndoAll");
}
/**
* This command runs the info command on the passed in itemPath and
* opens a web browser to the appropriate history page.
*/
public async ViewHistory(): Promise<void> {
//Since this command provides Team Services functionality, we need
//to ensure it is initialized for Team Services
if (!this._manager.EnsureInitialized(RepositoryType.TFVC)) {
this._manager.DisplayErrorMessage();
return;
}
try {
let itemPath: string;
const editor = window.activeTextEditor;
//Get the path to the file open in the VSCode editor (if any)
if (editor) {
itemPath = editor.document.fileName;
}
if (!itemPath) {
//If no file open in editor, just display the history url of the entire repo
this.showRepositoryHistory();
return;
}
const itemInfos: IItemInfo[] = await this._repo.GetInfo([itemPath]);
//With a single file, show that file's history
if (itemInfos && itemInfos.length === 1) {
Telemetry.SendEvent(TfvcTelemetryEvents.OpenFileHistory);
const serverPath: string = itemInfos[0].serverItem;
const file: string = encodeURIComponent(serverPath);
let historyUrl: string = UrlBuilder.Join(this._manager.RepoContext.RemoteUrl, "_versionControl");
historyUrl = UrlBuilder.AddQueryParams(historyUrl, `path=${file}`, `_a=history`);
Utils.OpenUrl(historyUrl);
return;
} else {
//If the file is in the workspace folder (but not mapped), just display the history url of the entire repo
this.showRepositoryHistory();
}
} catch (err) {
if (err.tfvcErrorCode && err.tfvcErrorCode === TfvcErrorCodes.FileNotInMappings) {
//If file open in editor is not in the mappings, just display the history url of the entire repo
this.showRepositoryHistory();
} else {
this._manager.DisplayErrorMessage(err.message);
}
}
}
private async displayErrors(funcToTry: (prefix) => Promise<void>, prefix: string): Promise<void> {
if (!this._manager.EnsureInitializedForTFVC()) {
this._manager.DisplayErrorMessage();
return;
}
//This occurs in the case where we 1) sign in successfully, 2) sign out, 3) sign back in but with invalid credentials
//Essentially, the tfvcExtension.InitializeClients call hasn't been made successfully yet.
if (!this._repo) {
this._manager.DisplayErrorMessage(Strings.UserMustSignIn);
return;
}
try {
await funcToTry(prefix);
} catch (err) {
let messageOptions: IButtonMessageItem[] = [];
TfvcOutput.AppendLine(Utils.FormatMessage(`[${prefix}] ${err.message}`));
//If we also have text in err.stdout, provide that to the output channel
if (err.stdout) { //TODO: perhaps just for 'Checkin'? Or the CLC?
TfvcOutput.AppendLine(Utils.FormatMessage(`[${prefix}] ${err.stdout}`));
}
//If an exception provides its own messageOptions, use them
if (err.messageOptions && err.messageOptions.length > 0) {
messageOptions = err.messageOptions;
} else {
messageOptions.push({ title : Strings.ShowTfvcOutput, command: TfvcCommandNames.ShowOutput });
}
VsCodeUtils.ShowErrorMessage(err.message, ...messageOptions);
}
}
public async InitializeClients(repoType: RepositoryType): Promise<void> {
//We only need to initialize for Tfvc repositories
if (repoType !== RepositoryType.TFVC) {
return;
}
const tfvcContext: TfvcContext = <TfvcContext>this._manager.RepoContext;
this._repo = tfvcContext.TfvcRepository;
}
private showRepositoryHistory(): void {
Telemetry.SendEvent(TfvcTelemetryEvents.OpenRepositoryHistory);
let historyUrl: string = UrlBuilder.Join(this._manager.RepoContext.RemoteUrl, "_versionControl");
historyUrl = UrlBuilder.AddQueryParams(historyUrl, `_a=history`);
Utils.OpenUrl(historyUrl);
}
dispose() {
// nothing to dispose
}
} | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement } from "../shared";
/**
* Statement provider for service [mediatailor](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awselementalmediatailor.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Mediatailor extends PolicyStatement {
public servicePrefix = 'mediatailor';
/**
* Statement provider for service [mediatailor](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awselementalmediatailor.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
constructor (sid?: string) {
super(sid);
}
/**
* Grants permission to create a new channel
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/channel-channelname.html
*/
public toCreateChannel() {
return this.to('CreateChannel');
}
/**
* Grants permission to create a new program on the channel with the specified channel name
*
* Access Level: Write
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/channel-channelname-program-programname.html
*/
public toCreateProgram() {
return this.to('CreateProgram');
}
/**
* Grants permission to create a new source location
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/sourcelocation-sourcelocationname.html
*/
public toCreateSourceLocation() {
return this.to('CreateSourceLocation');
}
/**
* Grants permission to create a new VOD source on the source location with the specified source location name
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/sourcelocation-sourcelocationname-vodsource-vodsourcename.html
*/
public toCreateVodSource() {
return this.to('CreateVodSource');
}
/**
* Grants permission to delete the channel with the specified channel name
*
* Access Level: Write
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/channel-channelname.html
*/
public toDeleteChannel() {
return this.to('DeleteChannel');
}
/**
* Grants permission to delete the IAM policy on the channel with the specified channel name
*
* Access Level: Permissions management
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/channel-channelname-policy.html
*/
public toDeleteChannelPolicy() {
return this.to('DeleteChannelPolicy');
}
/**
* Deletes the playback configuration for the specified name
*
* Access Level: Write
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/playbackconfiguration-name.html
*/
public toDeletePlaybackConfiguration() {
return this.to('DeletePlaybackConfiguration');
}
/**
* Grants permission to delete the program with the specified program name on the channel with the specified channel name
*
* Access Level: Write
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/channel-channelname-program-programname.html
*/
public toDeleteProgram() {
return this.to('DeleteProgram');
}
/**
* Grants permission to delete the source location with the specified source location name
*
* Access Level: Write
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/sourcelocation-sourcelocationname.html
*/
public toDeleteSourceLocation() {
return this.to('DeleteSourceLocation');
}
/**
* Grants permission to delete the VOD source with the specified VOD source name on the source location with the specified source location name
*
* Access Level: Write
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/sourcelocation-sourcelocationname-vodsource-vodsourcename.html
*/
public toDeleteVodSource() {
return this.to('DeleteVodSource');
}
/**
* Grants permission to retrieve the channel with the specified channel name
*
* Access Level: Read
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/channel-channelname.html
*/
public toDescribeChannel() {
return this.to('DescribeChannel');
}
/**
* Grants permission to retrieve the program with the specified program name on the channel with the specified channel name
*
* Access Level: Read
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/channel-channelname-program-programname.html
*/
public toDescribeProgram() {
return this.to('DescribeProgram');
}
/**
* Grants permission to retrieve the source location with the specified source location name
*
* Access Level: Read
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/sourcelocation-sourcelocationname.html
*/
public toDescribeSourceLocation() {
return this.to('DescribeSourceLocation');
}
/**
* Grants permission to retrieve the VOD source with the specified VOD source name on the source location with the specified source location name
*
* Access Level: Read
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/sourcelocation-sourcelocationname-vodsource-vodsourcename.html
*/
public toDescribeVodSource() {
return this.to('DescribeVodSource');
}
/**
* Grants permission to read the IAM policy on the channel with the specified channel name
*
* Access Level: Read
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/channel-channelname-policy.html
*/
public toGetChannelPolicy() {
return this.to('GetChannelPolicy');
}
/**
* Grants permission to retrieve the schedule of programs on the channel with the specified channel name
*
* Access Level: Read
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/channel-channelname-schedule.html
*/
public toGetChannelSchedule() {
return this.to('GetChannelSchedule');
}
/**
* Grants permission to retrieve the configuration for the specified name
*
* Access Level: Read
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/playbackconfiguration-name.html
*/
public toGetPlaybackConfiguration() {
return this.to('GetPlaybackConfiguration');
}
/**
* Grants permission to retrieve the list of alerts on a resource
*
* Access Level: Read
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/alerts.html
*/
public toListAlerts() {
return this.to('ListAlerts');
}
/**
* Grants permission to retrieve the list of existing channels
*
* Access Level: Read
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/channels.html
*/
public toListChannels() {
return this.to('ListChannels');
}
/**
* Grants permission to retrieve the list of available configurations
*
* Access Level: List
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/playbackconfigurations.html
*/
public toListPlaybackConfigurations() {
return this.to('ListPlaybackConfigurations');
}
/**
* Grants permission to retrieve the list of existing source locations
*
* Access Level: Read
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/sourcelocations.html
*/
public toListSourceLocations() {
return this.to('ListSourceLocations');
}
/**
* Returns a list of the tags assigned to the specified playback configuration resource
*
* Access Level: Read
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/tags-resourcearn.html
*/
public toListTagsForResource() {
return this.to('ListTagsForResource');
}
/**
* Grants permission to retrieve the list of existing VOD sources on the source location with the specified source location name
*
* Access Level: Read
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/sourcelocation-sourcelocationname-vodsources.html
*/
public toListVodSources() {
return this.to('ListVodSources');
}
/**
* Grants permission to set the IAM policy on the channel with the specified channel name
*
* Access Level: Permissions management
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/channel-channelname-policy.html
*/
public toPutChannelPolicy() {
return this.to('PutChannelPolicy');
}
/**
* Grants permission to add a new configuration
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/playbackconfiguration.html
*/
public toPutPlaybackConfiguration() {
return this.to('PutPlaybackConfiguration');
}
/**
* Grants permission to start the channel with the specified channel name
*
* Access Level: Write
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/channel-channelname-start.html
*/
public toStartChannel() {
return this.to('StartChannel');
}
/**
* Grants permission to stop the channel with the specified channel name
*
* Access Level: Write
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/channel-channelname-stop.html
*/
public toStopChannel() {
return this.to('StopChannel');
}
/**
* Adds tags to the specified playback configuration resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/tags-resourcearn.html
*/
public toTagResource() {
return this.to('TagResource');
}
/**
* Removes tags from the specified playback configuration resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/tags-resourcearn.html
*/
public toUntagResource() {
return this.to('UntagResource');
}
/**
* Grants permission to update the channel with the specified channel name
*
* Access Level: Write
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/channel-channelname.html
*/
public toUpdateChannel() {
return this.to('UpdateChannel');
}
/**
* Grants permission to update the source location with the specified source location name
*
* Access Level: Write
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/sourcelocation-sourcelocationname.html
*/
public toUpdateSourceLocation() {
return this.to('UpdateSourceLocation');
}
/**
* Grants permission to update the VOD source with the specified VOD source name on the source location with the specified source location name
*
* Access Level: Write
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/sourcelocation-sourcelocationname-vodsource-vodsourcename.html
*/
public toUpdateVodSource() {
return this.to('UpdateVodSource');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"CreateChannel",
"CreateProgram",
"CreateSourceLocation",
"CreateVodSource",
"DeleteChannel",
"DeletePlaybackConfiguration",
"DeleteProgram",
"DeleteSourceLocation",
"DeleteVodSource",
"PutPlaybackConfiguration",
"StartChannel",
"StopChannel",
"UpdateChannel",
"UpdateSourceLocation",
"UpdateVodSource"
],
"Permissions management": [
"DeleteChannelPolicy",
"PutChannelPolicy"
],
"Read": [
"DescribeChannel",
"DescribeProgram",
"DescribeSourceLocation",
"DescribeVodSource",
"GetChannelPolicy",
"GetChannelSchedule",
"GetPlaybackConfiguration",
"ListAlerts",
"ListChannels",
"ListSourceLocations",
"ListTagsForResource",
"ListVodSources"
],
"List": [
"ListPlaybackConfigurations"
],
"Tagging": [
"TagResource",
"UntagResource"
]
};
/**
* Adds a resource of type playbackConfiguration to the statement
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/playbackconfiguration.html
*
* @param resourceId - Identifier for the resourceId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onPlaybackConfiguration(resourceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:mediatailor:${Region}:${Account}:playbackConfiguration/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type channel to the statement
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/channel-channelname.html
*
* @param resourceId - Identifier for the resourceId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onChannel(resourceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:mediatailor:${Region}:${Account}:channel/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type program to the statement
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/channel-channelname-program-programname.html
*
* @param resourceId - Identifier for the resourceId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onProgram(resourceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:mediatailor:${Region}:${Account}:program/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type sourceLocation to the statement
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/sourcelocation-sourcelocationname.html
*
* @param resourceId - Identifier for the resourceId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onSourceLocation(resourceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:mediatailor:${Region}:${Account}:sourceLocation/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type vodSource to the statement
*
* https://docs.aws.amazon.com/mediatailor/latest/apireference/sourcelocation-sourcelocationname-vodsource-vodsourcename.html
*
* @param resourceId - Identifier for the resourceId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onVodSource(resourceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:mediatailor:${Region}:${Account}:vodSource/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
} | the_stack |
import {LOCALES} from '../locales';
export default {
property: {
weight: 'Espessura do texto',
label: 'Rótulo',
fillColor: 'Cor do preenchimento',
color: 'Cor',
strokeColor: 'Cor da borda',
radius: 'Raio',
outline: 'Contorno',
stroke: 'Traçado',
density: 'Densidade',
height: 'Altura',
sum: 'Soma',
pointCount: 'Contagem de Pontos'
},
placeholder: {
search: 'Pesquisar',
selectField: 'Selecione um campo',
yAxis: 'Eixo Y',
selectType: 'Selecione um Tipo',
selectValue: 'Selecione um valor',
enterValue: 'Insira um valor',
empty: 'Vazio'
},
misc: {
by: '',
valuesIn: 'Valores em',
valueEquals: 'Valor igual a',
dataSource: 'Origem dos dados',
brushRadius: 'Raio do Traço (km)',
empty: ' '
},
mapLayers: {
title: 'Camadas do mapa',
label: 'Rótulo',
road: 'Estrada',
border: 'Fronteira',
building: 'Edifícios',
water: 'Água',
land: 'Terra',
'3dBuilding': 'Edifícios em 3d'
},
panel: {
text: {
label: 'Rótulo',
labelWithId: 'Rótulo {labelId}',
fontSize: 'Tamanho da fonte',
fontColor: 'Cor da fonte',
textAnchor: 'Âncora do texto',
alignment: 'Alinhamento',
addMoreLabel: 'Adicionar mais Rótulos'
}
},
sidebar: {
panels: {
layer: 'Camadas',
filter: 'Filtros',
interaction: 'Interações',
basemap: 'Mapa base'
}
},
layer: {
required: 'Obrigatório*',
radius: 'Raio',
color: 'Cor',
fillColor: 'Cor de preenchimento',
outline: 'Contorno',
weight: 'Espessura',
propertyBasedOn: '{property} baseada em',
coverage: 'Cobertura',
stroke: 'Traço',
strokeWidth: 'Largura do Traçado',
strokeColor: 'Cor do Traçado',
basic: 'Básico',
trailLength: 'Comprimento da trilha',
trailLengthDescription: 'Número de segundos para um caminho completamente desaparecer',
newLayer: 'nova camada',
elevationByDescription: 'Quando desligado, a altura é baseada na contagem de pontos',
colorByDescription: 'Quando desligado, a cor é baseada na contagem de pontos',
aggregateBy: '{field} agregado por',
'3DModel': 'Modelo 3D',
'3DModelOptions': 'Opções do Modelo 3D',
type: {
point: 'ponto',
arc: 'arco',
line: 'linha',
grid: 'grade',
hexbin: 'hexágono',
polygon: 'polígono',
geojson: 'geojson',
cluster: 'grupo',
icon: 'icon',
heatmap: 'mapa de calor',
hexagon: 'hexágono',
hexagonid: 'H3',
trip: 'viagem',
s2: 'S2',
'3d': '3D'
}
},
layerVisConfigs: {
strokeWidth: 'Largura do Traço',
strokeWidthRange: 'Alcance da Largura do Traço',
radius: 'Raio',
fixedRadius: 'Raio ajustado para metro',
fixedRadiusDescription: 'Raio do Mapa para Raio absoluto em metros, e.g. 5 para 5 metros',
radiusRange: 'Alcance do Raio',
clusterRadius: 'Raio do Agrupamento em pixels',
radiusRangePixels: 'Alcance do Raio em pixels',
opacity: 'Opacidade',
coverage: 'Cobertura',
outline: 'Contorno',
colorRange: 'Alcance da Cor',
stroke: 'Traçado',
strokeColor: 'Cor do Traçado',
strokeColorRange: 'Alcance da Cor do Traçado',
targetColor: 'Cor de destino',
colorAggregation: 'Agregação da Cor',
heightAggregation: 'Agregação da Altura',
resolutionRange: 'Alcance da Resolução',
sizeScale: 'Escala de tamanho',
worldUnitSize: 'Tamanho unitário do mundo',
elevationScale: 'Escala de Elevação',
enableElevationZoomFactor: 'Use fator de zoom de elevação',
enableElevationZoomFactorDescription:
'Ajuste a altura / elevação com base no fator de zoom atual',
enableHeightZoomFactor: 'Usar fator de zoom de altura',
heightScale: 'Escala de Altura',
coverageRange: 'Alcance de cobertura',
highPrecisionRendering: 'Renderização de Alta Precisão',
highPrecisionRenderingDescription: 'Alta precisão irá em resultar em baixa performance',
height: 'Altura',
heightDescription:
'Clique no botão no canto superior direito para trocar para a visualização 3d',
fill: 'Preenchimento',
enablePolygonHeight: 'Habilitar Altura de Polígono',
showWireframe: 'Mostrar Wireframe',
weightIntensity: 'Intensidade da Espessura',
zoomScale: 'Escala do Zoom',
heightRange: 'Alcance da Altura',
heightMultiplier: 'Multiplicador de altura'
},
layerManager: {
addData: 'Adicionar Dados',
addLayer: 'Adicionar Camada',
layerBlending: 'Mistura de Camada'
},
mapManager: {
mapStyle: 'Estilo do Mapa',
addMapStyle: 'Adicionar Estilo de Mapa',
'3dBuildingColor': 'Cor do Edifício 3D'
},
layerConfiguration: {
defaultDescription: 'Calcular {property} baseada no campo selecionado',
howTo: 'Como'
},
filterManager: {
addFilter: 'Adicionar Filtro'
},
datasetTitle: {
showDataTable: 'Mostrar tabela de dados',
removeDataset: 'Remover tabela de dados'
},
datasetInfo: {
rowCount: '{rowCount} linhas'
},
tooltip: {
hideLayer: 'esconder camada',
showLayer: 'mostrar camada',
hideFeature: 'Esconder propriedade',
showFeature: 'Mostrar propriedade',
hide: 'esconder',
show: 'mostrar',
removeLayer: 'Remover Camada',
layerSettings: 'Configurações de Camada',
closePanel: 'Fechar painel atual',
switchToDualView: 'Trocar para visualização dupla de mapa',
showLegend: 'mostrar legenda',
disable3DMap: 'Desabilitar Mapa 3D',
DrawOnMap: 'Desenhar no mapa',
selectLocale: 'Selecionar língua',
hideLayerPanel: 'Esconder painel de camada',
showLayerPanel: 'Mostrar painel de camada',
moveToTop: 'Mover para o topo das camadas',
selectBaseMapStyle: 'Selecionar o Estilo do Mapa Base',
delete: 'Deletar',
timePlayback: 'Tempo de reprodução',
cloudStorage: 'Armazenamento Cloud',
'3DMap': ' Mapa 3D'
},
toolbar: {
exportImage: 'Exportar Imagem',
exportData: 'Exportar Dados',
exportMap: 'Exportar Mapa',
shareMapURL: 'Compartilhar URL do Mapa',
saveMap: 'Salvar Mapa',
select: 'selecionar',
polygon: 'polígono',
rectangle: 'retângulo',
hide: 'esconder',
show: 'mostrar',
...LOCALES
},
modal: {
title: {
deleteDataset: 'Deletar Conjunto de Dados',
addDataToMap: 'Adicionar Dados ao Mapa',
exportImage: 'Exportar Imagem',
exportData: 'Exportar Dados',
exportMap: 'Exportar Mapa',
addCustomMapboxStyle: 'Adicionar Estilo Mapbox Customizado',
saveMap: 'Salvar Mapa',
shareURL: 'Compartilhar URL'
},
button: {
delete: 'Deletar',
download: 'Download',
export: 'Exportar',
addStyle: 'Adicionar Estilo',
save: 'Salvar',
defaultCancel: 'Cancelar',
defaultConfirm: 'Confirmar'
},
exportImage: {
ratioTitle: 'Proporção',
ratioDescription: 'Escolha a proporção para vários usos.',
ratioOriginalScreen: 'Tela Original',
ratioCustom: 'Customizado',
ratio4_3: '4:3',
ratio16_9: '16:9',
resolutionTitle: 'Resolução',
resolutionDescription: 'Alta resolução é melhor para impressões.',
mapLegendTitle: 'Legenda do Mapa',
mapLegendAdd: 'Adicionar Legenda no mapa'
},
exportData: {
datasetTitle: 'Conjunto de dados',
datasetSubtitle: 'Escolha o conjunto de dados que você quer exportar',
allDatasets: 'Todos',
dataTypeTitle: 'Tipo de Dado',
dataTypeSubtitle: 'Escolha o tipo de dados que você quer exportar',
filterDataTitle: 'Filtrar Dados',
filterDataSubtitle: 'Você pode escolher exportar os dados originais ou os dados filtrados',
filteredData: 'Dados Filtrados',
unfilteredData: 'Dados não filtrados',
fileCount: '{fileCount} Arquivos',
rowCount: '{rowCount} Linhas'
},
deleteData: {
warning: 'você irá deletar esse conjunto de dados. Isso irá afetar {length} camadas'
},
addStyle: {
publishTitle: '1. Publique o seu Estilo no Mapbox ou providencie a chave de acesso',
publishSubtitle1: 'Você pode criar o seu próprio estilo em',
publishSubtitle2: 'e',
publishSubtitle3: 'publicar',
publishSubtitle4: 'isso.',
publishSubtitle5: 'Para utilizar estilo privado, cole a sua',
publishSubtitle6: 'chave de acesso',
publishSubtitle7:
'aqui. *kepler.gl é uma aplicação client-side, os dados permanecem no seu browser..',
exampleToken: 'e.g. pk.abcdefg.xxxxxx',
pasteTitle: '2. Cole a url do seu estilo',
pasteSubtitle1: 'O que é uma',
pasteSubtitle2: 'URL de estilo',
namingTitle: '3. Nomeie o seu estilo'
},
shareMap: {
shareUriTitle: 'Compartilhar a URL do Mapa',
shareUriSubtitle: 'Gerar a url do mapa e compartilhar com outros',
cloudTitle: 'Armazenamento Cloud',
cloudSubtitle: 'Conecte-se e envie os dados do mapa para o seu armazenamento cloud pessoal',
shareDisclaimer:
'kepler.gl irá salvar os dados do mapa em seu armazenamento cloud pessoal, apenas pessoas com a URL podem acessar o seu mapa e dados. ' +
'Você pode editar/deletar o arquivo de dados na sua conta de armazenamento cloud em qualquer momento.',
gotoPage: 'Vá para a sua página Kepler.gl {currentProvider}'
},
statusPanel: {
mapUploading: 'Enviando Mapa',
error: 'Erro'
},
saveMap: {
title: 'Armazenamento Cloud',
subtitle: 'Conecte-se para salvar o mapa para o seu armazenamento cloud pessoal'
},
exportMap: {
formatTitle: 'Formato do mapa',
formatSubtitle: 'Escolher o formato de mapa para exportar',
html: {
selection: 'Exportar seu mapa em um arquivo html interativo.',
tokenTitle: 'Chave de acesso do Mapbox',
tokenSubtitle: 'Use a sua própria chave de acesso Mapbox em seu arquivo html (opcional)',
tokenPlaceholder: 'Cole a sua chave de acesso Mapbox',
tokenMisuseWarning:
'* Se você não fornecer a sua própria chave de acesso, o mapa pode falhar em exibir a qualquer momento quando nós substituirmos a nossa para evitar mau uso. ',
tokenDisclaimer:
'Você pode trocar a sua chave de acesso Mapbox mais tarde utizando as instruções seguintes: ',
tokenUpdate: 'Como atualizar a chave de acesso de um mapa existente.',
modeTitle: 'Modo do Mapa',
modeSubtitle1: 'Selecionar o modo do aplicativo. Mais ',
modeSubtitle2: 'info',
modeDescription: 'Permitir usuários a {mode} o mapa',
read: 'ler',
edit: 'editar'
},
json: {
configTitle: 'Configurações do Mapa',
configDisclaimer:
'A configuração do mapa será incluida no arquivo Json. Se você está utilizando kepler.gl no seu próprio mapa. Você pode copiar essa configuração e passar para ele ',
selection:
'Exportar atuais dados e configurações do mapa em um único arquivo Json. Você pode mais tarde abrir o mesmo mapa enviando esse arquivo para o kepler.gl.',
disclaimer:
'* Configuração do mapa é aclopado com conjunto de dados carregados. ‘dataId’ é utilizado para ligar as camadas, filtros, e dicas de contextos a conjunto de dados expecíficos. ' +
'Quando passando essa configuração para addDataToMap, tenha certeza de que o id do conjunto de dados combina com o(s) dataId/s nessa configuração.'
}
},
loadingDialog: {
loading: 'Carregando...'
},
loadData: {
upload: 'Carregar arquivo',
storage: 'Carregar do armazenamento'
},
tripInfo: {
title: 'Como habilitar animação de viagem',
description1:
'Para animar o caminho, o dado geoJSON deve conter `LineString` na sua propriedade geometry, e as coordenadas na LineString devem ter 4 elementos no seguinte formato',
code: ' [longitude, latitude, altitude, data] ',
description2:
'com um ultimo elemento sendo uma data. Um formato de data válida inclui segundos unix como `1564184363` ou em milisegundos como `1564184363000`.',
example: 'Exemplo:'
},
iconInfo: {
title: 'Como desenhar ícones',
description1:
'No seu csv, crie uma coluna, coloque o nome do ícone que você quer desenhar nele. Você pode deixar o campo vazio se você não desejar que o ícone apareça para alguns pontos. Quando a coluna tem nome',
code: 'icon',
description2: ' kepler.gl irá automaticamente criar uma camada de ícone para você.',
example: 'Exemplos:',
icons: 'Ícones'
},
storageMapViewer: {
lastModified: 'Modificado há {lastUpdated}',
back: 'Voltar'
},
overwriteMap: {
title: 'Salvando mapa...',
alreadyExists: 'já existe no mapa {mapSaved}. Você desejaria sobrescrever o mapa?'
},
loadStorageMap: {
back: 'Voltar',
goToPage: 'Vá para a sua página {displayName} do Kepler.gl',
storageMaps: 'Armazenamento / Mapas',
noSavedMaps: 'Nenhum mapa salvo'
}
},
header: {
visibleLayers: 'Camadas Visíveis',
layerLegend: 'Legenda da Camada'
},
interactions: {
tooltip: 'Dica de contexto',
brush: 'Pincel',
coordinate: 'Coordenadas'
},
layerBlending: {
title: 'Mistura de Camadas',
additive: 'aditivo',
normal: 'normal',
subtractive: 'subtrativo'
},
columns: {
title: 'Colunas',
lat: 'lat',
lng: 'lon',
altitude: 'altitude',
icon: 'ícone',
geojson: 'geojson',
arc: {
lat0: 'origem lat',
lng0: 'origem lng',
lat1: 'destino lat',
lng1: 'destino lng'
},
line: {
alt0: 'origem altitude',
alt1: 'destino altitude'
},
grid: {
worldUnitSize: 'Tamanho da Grade (km)'
},
hexagon: {
worldUnitSize: 'Raio do Hexágono (km)'
}
},
color: {
customPalette: 'Paletas customizadas',
steps: 'caminhos',
type: 'tipo',
reversed: 'reverso'
},
scale: {
colorScale: 'Escala da Cor',
sizeScale: 'Tamanho da Escala',
strokeScale: 'Escala do Traço',
scale: 'Escala'
},
fileUploader: {
message: 'Arraste e solte seu(s) arquivo(s) aqui',
chromeMessage:
'*Usuários do chrome: O limite de tamanho de arquivo é 250mb, se você precisa fazer upload de arquivos maiores tente o Safari',
disclaimer:
'*kepler.gl é uma aplicação client-side, sem um servidor backend. Os dados ficam apenas na sua máquina/browser. ' +
'Nenhuma informação ou dados de mapa é enviado para qualquer server.',
configUploadMessage:
'Envie {fileFormatNames} ou mapas salvos **Json**. Leia mais sobre [**tipos de arquivos suportados**]',
browseFiles: 'procure seus arquivos',
uploading: 'Enviando',
fileNotSupported: 'Arquivo {errorFiles} não é suportado.',
or: 'ou'
},
density: 'densidade',
'Bug Report': 'Reportar Bug',
'User Guide': 'Guia do Usuário',
Save: 'Salvar',
Share: 'Compartilhar'
}; | the_stack |
import React from "react";
import ReactDOM from "react-dom";
import ReactDOMServer from "react-dom/server";
import * as defs from "./types/jsonx/index";
import * as jsonxComponents from "./components";
import * as jsonxProps from "./props";
import * as jsonxChildren from "./children";
import * as jsonxUtils from "./utils";
import numeral from "numeral";
import * as luxon from "luxon";
import { ReactElementLike } from "prop-types";
import { JSONReactElement, Context } from "./types/jsonx/index";
const createElement = React.createElement;
const {
componentMap,
getComponentFromMap,
getBoundedComponents,
DynamicComponent,
FormComponent,
ReactHookForm,
getReactLibrariesAndComponents,
} = jsonxComponents;
const { getComputedProps } = jsonxProps;
const { getJSONXChildren } = jsonxChildren;
const { displayComponent, validSimpleJSONXSyntax, simpleJSONXSyntax } = jsonxUtils;
export let renderIndex = 0;
/**
* Use JSONX without any configuration to render JSONX JSON to HTML and insert JSONX into querySelector using ReactDOM.render
* @example
* // Uses react to create <!DOCTYPE html><body><div id="myApp"><div class="jsonx-generated"><p style="color:red;">hello world</p></div></div></body>
* jsonx.jsonxRender({ jsonx: { component: 'div', props:{className:'jsonx-generated',children:[{ component:'p',props:{style:{color:'red'}}, children:'hello world' }]}}, querySelector:'#myApp', });
* @param {object} config - options used to inject html via ReactDOM.render
* @param {object} config.jsonx - any valid JSONX JSON object
* @param {object} config.resources - any additional resource used for asynchronous properties
* @param {string} config.querySelector - selector for document.querySelector
* @property {object} this - options for getReactElementFromJSONX
*/
export function jsonxRender(
this: defs.Context,
config: defs.RenderConfig = { jsonx: { component: "" }, querySelector: "" }
): void {
const { jsonx, resources, querySelector, DOM, portal } = config;
const Render = portal ? ReactDOM.createPortal : ReactDOM.render;
const RenderDOM: HTMLElement | null =
DOM || document.querySelector(querySelector);
const JSONXReactElement: any = getReactElementFromJSONX.call(
this || {},
jsonx,
resources
);
if (!JSONXReactElement) throw ReferenceError("Invalid React Element");
else if (!RenderDOM) throw ReferenceError("Invalid Render DOM Element");
Render(JSONXReactElement, RenderDOM);
}
/**
* Use ReactDOMServer.renderToString to render html from JSONX
* @example
* // Uses react to create <div class="jsonx-generated"><p style="color:red;">hello world</p></div>
* jsonx.outputHTML({ jsonx: { component: 'div', props:{className:'jsonx-generated',children:[{ component:'p',props:{style:{color:'red'}}, children:'hello world' }]}}, });
* @param {object} config - options used to inject html via ReactDOM.render
* @param {object} config.jsonx - any valid JSONX JSON object
* @param {object} config.resources - any additional resource used for asynchronous properties
* @property {object} this - options for getReactElementFromJSONX
* @returns {string} React genereated html via JSONX JSON
*/
export function outputHTML(
this: defs.OutputHTMLContext,
config: defs.OutputHTMLConfig = { jsonx: { component: "" } }
): string {
const { jsonx, resources, type, props, children } = config;
return this && this.useJSON
? ReactDOMServer.renderToString(
getReactElementFromJSON.call(this || {}, { type:(type||jsonx.type||jsonx.component||'Fragment' as string), props:props||jsonx.props, children:children||jsonx.children })
)
: ReactDOMServer.renderToString(
getReactElementFromJSONX.call(
this || {},
jsonx,
resources
) as ReactElementLike
);
}
/**
* Use React.createElement and JSONX JSON to create React elements
* @example
* // Uses react to create the equivalent JSX <myComponent style={{color:blue}}>hello world</myComponent>
* jsonx.getReactElementFromJSONX({component:'myCompnent',props:{style:{color:'blue'}},children:'hello world'})
* @param {object} jsonx - any valid JSONX JSON object
* @param {object} resources - any additional resource used for asynchronous properties
* @property {object} this - options for getReactElementFromJSONX
* @property {Object} [this.componentLibraries] - react components to render with JSONX
* @property {boolean} [this.debug=false] - use debug messages
* @property {boolean} [this.returnJSON=false] - return json object of {type,props,children} instead of react element
* @property {boolean} [this.disableRenderIndexKey=false] - disables auto assign a key prop
* @property {function} [this.logError=console.error] - error logging function
* @property {string[]} [this.boundedComponents=[]] - list of components that require a bound this context (usefult for redux router)
* @returns {function} React element via React.createElement
*/
export function getReactElementFromJSONX(
this: defs.Context,
jsonx?: defs.jsonx | defs.simpleJsonx,
resources = {}
): ReactElementLike | JSONReactElement | null |string|undefined{
// eslint-disable-next-line
const {
customComponents,
debug = false,
returnJSON = false,
logError = console.error,
boundedComponents = [],
disableRenderIndexKey = true
} = this || {};
let {
componentLibraries = {},
} = this ||{};
componentLibraries.ReactHookForm = ReactHookForm
if (!jsonx) return null;
if (jsonx.type) jsonx.component = jsonx.type;
if (!jsonx.component && validSimpleJSONXSyntax(jsonx)) {
jsonx = simpleJSONXSyntax(jsonx);
}
if (!jsonx || !jsonx.component)
return createElement(
"span",
{},
debug ? "Error: Missing Component Object" : ""
);
try {
let components = Object.assign(
{ DynamicComponent: DynamicComponent.bind(this) },
{ FormComponent: FormComponent.bind(this) },
componentMap,
this?.reactComponents
);
let reactComponents = boundedComponents.length
? getBoundedComponents.call(this, {
boundedComponents,
reactComponents: components
})
: components;
if(customComponents && Array.isArray(customComponents) && customComponents.length){
const cxt = {...this,componentLibraries,reactComponents:components}
const {
customComponentLibraries,
customReactComponents
} = getReactLibrariesAndComponents.call(cxt,customComponents);
componentLibraries = {...componentLibraries, ...customComponentLibraries};
reactComponents = {...reactComponents, ...customReactComponents};
}
if(disableRenderIndexKey===false) renderIndex++;
const element = getComponentFromMap.call(this, {
jsonx,
reactComponents,
componentLibraries,
debug,
logError
});
const props = getComputedProps.call(this, {
jsonx,
resources,
renderIndex,
componentLibraries,
debug,
logError,
disableRenderIndexKey
});
const displayElement = jsonx.comparisonprops
? displayComponent.call(this, {
jsonx,
props,
renderIndex,
componentLibraries,
debug
})
: true;
if (displayElement) {
const children = getJSONXChildren.call(this, {
jsonx,
props,
resources,
renderIndex
});
//@ts -ignore
if (returnJSON) return { type: element as string, props, children };
else if (jsonx.test) return JSON.stringify({ element, props, children }, null, 2);
//TODO: Fix
else return createElement(element, props, children);
} else {
return null;
}
} catch (e) {
if (debug) {
logError({ jsonx, resources }, "getReactElementFromJSONX this", this);
logError(e, e.stack ? e.stack : "no stack");
return e.toString()
}
throw e;
}
}
export const getRenderedJSON = getReactElementFromJSONX;
export const getReactElement = getReactElementFromJSONX;
/** converts a json object {type,props,children} into a react element
* @example
* jsonx.getReactElementFromJSON({type:'div',props:{title:'some title attribute'},children:'inner html text'})
* @param {Object|String} options.type - 'div' or react component
* @param {Object} options.props - props for react element
* @param {String|[Object]} options.children - children elements
* @returns {function} React element via React.createElement
*/
export function getReactElementFromJSON({
type,
props,
children
}: JSONReactElement): ReactElementLike {
return createElement(
type,
props,
children && Array.isArray(children)
? children.map(getReactElementFromJSON)
: children
);
}
/** converts a jsonx json object into a react function component
* @example
* jsonx.compile({jsonx:{component:'div',props:{title:'some title attribute'},children:'inner html text'}}) //=>React Function Component
* @param {Object} jsonx - valid JSONX JSON
* @param {Object} resources - props for react element
* @returns {function} React element via React.createElement
*/
export function compile(this: Context, jsonx: defs.jsonx, resources = {}) {
const context = Object.assign({}, this, { returnJSON: true });
const json = getReactElementFromJSONX.call(
context,
jsonx,
resources
) as defs.JSONReactElement;
const func = function compiledJSONX(props: any) {
json.props = Object.assign({}, json.props, props);
return getReactElementFromJSON(json);
};
Object.defineProperty(func, "name", { value: this.name });
return func;
}
/**
* converts JSONX JSON IR to JSX
* @example
* jsonx.jsonToJSX({ type: 'div', props: { key: 5, title: 'test' }, children: 'hello' }) // => '<div key={5} title="test">hello</div>'
* @param {Object} json - {type,props,children}
* @returns {String} jsx string
*/
export function outputJSX(this: Context, jsonx: defs.jsonx, resources = {}) {
const context = Object.assign({}, this, { returnJSON: true });
const json = getReactElementFromJSONX.call(
context,
jsonx,
resources
) as defs.JSONReactElement;
return jsonToJSX(json);
}
/**
* Compiles JSONX into JSON IR format for react create element
* @example
* jsonx.outputJSON({ component: 'div', props: { title: 'test', }, children: 'hello', }); //=> { type: 'div',
props: { key: 5, title: 'test' },
children: 'hello' }
* @property {object} this - options for getReactElementFromJSONX
* @param {object} jsonx - any valid JSONX JSON object
* @param {object} resources - any additional resource used for asynchronous properties
* @returns {Object} json - {type,props,children}
*/
export function outputJSON(
jsonx: defs.jsonx,
resources = {}
): JSONReactElement {
//@ts-ignore
const context = Object.assign({}, this, { returnJSON: true });
return getReactElementFromJSONX.call(
context,
jsonx,
resources
) as JSONReactElement;
}
export const jsonxHTMLString = outputHTML;
/**
* converts JSONX JSON IR to JSX
* @example
* jsonx.jsonToJSX({ type: 'div', props: { key: 5, title: 'test' }, children: 'hello' }) // => '<div key={5} title="test">hello</div>'
* @param {Object} json - {type,props,children}
* @returns {String} jsx string
*/
export function jsonToJSX(json: JSONReactElement): string {
const propsString = json.props
? Object.keys(json.props)
.filter(prop => prop.includes("__eval_") === false)
.reduce((propString, prop) => {
propString += ` ${prop.toString()}=${
typeof json.props[prop] === "string"
? `"${json.props[prop].toString()}"`
: `{${(
json.props[`__eval_${prop}`] || json.props[prop]
).toString()}}`
}`;
return propString;
}, "")
: "";
return Array.isArray(json.children)
? `<${json.type} ${propsString}>
${json.children.map(jsonToJSX).join('\r\n')}
</${json.type}>`
: `<${json.type}${propsString}>${json.children}</${json.type}>`;
}
/**
* Exposes react module used in JSONX
* @returns {Object} React
*/
export function __getReact() {
return React;
}
/**
* Exposes react dom module used in JSONX
* @returns {Object} ReactDOM
*/
export function __getReactDOM() {
return ReactDOM;
}
export const _jsonxChildren = jsonxChildren;
export const _jsonxComponents = jsonxComponents;
export const _jsonxProps = jsonxProps;
export const _jsonxUtils = jsonxUtils;
export const _jsonxHelpers = { numeral, luxon };
export { __express, __express as renderFile } from "./express";
export default getReactElementFromJSONX; | the_stack |
module Kiwi {
/**
* The plugin manager registers plugins, checks plugin dependencies, and calls designated functions on each registered plugin at boot time, and during the update loop if required.
* Plugins are registered on the global Kiwi instance. Once a plugin in registered it is allocated a place on the Kiwi.Plugins name space.
* Eg. FooPlugin will be accessible at Kiwi.Plugins.FooPlugin.
* When a game instance is created, it can contain a list of required plugins in the configuration object. At this point the plugin manager will validate that the plugins
* exist, and that dependencies are met (both Kiwi version and versions of other required plugins).
* If the plugin has a "create" function, the plugin manager instance will call that function as part of the boot process. The create function may do anything, but usually it would create
* an instance of an object.
* The plugin manager update function is called every update loop. If an object was created by the "create" function and it has an "update" function, that function will be called in turn.
* @class PluginManager
* @namespace Kiwi
* @constructor
* @param game {Kiwi.Game} The state that this entity belongs to. Used to generate the Unique ID and for garbage collection.
* @param plugins {string[]} The entities position on the x axis.
* @return {Kiwi.PluginManager} This PluginManager.
*
*/
export class PluginManager {
constructor(game: Kiwi.Game,plugins:string[]) {
this._game = game;
this._plugins = plugins || new Array();
this._bootObjects = new Array();
this.validatePlugins();
this._createPlugins();
}
/**
* An array of plugins which have been included in the webpage and registered successfully.
* @property _availablePlugins
* @type Array
* @static
* @private
*/
private static _availablePlugins = new Array();
/**
* An array of objects represetning all available plugins, each containing the name and version number of an available plugin
* @property getAvailablePlugins
* @type Array
* @static
* @private
*/
public static get availablePlugins():any {
var plugins = [];
for (var i = 0; i < PluginManager._availablePlugins.length; i++) {
plugins.push({
name: PluginManager._availablePlugins[i].name, version: PluginManager._availablePlugins[i].version});
}
return plugins;
}
/**
* Registers a plugin object as available. Any game instance can choose to use the plugin.
* Plugins need only be registered once per webpage. If registered a second time it will be ignored.
* Two plugins with the same names cannot be reigstered simultaneously, even if different versions.
* @method register
* @param {object} plugin
* @public
* @static
*/
public static register(plugin: any) {
Kiwi.Log.log("Kiwi.PluginManager: Attempting to register plugin : " + plugin.name, '#plugin');
if (this._availablePlugins.indexOf(plugin) == -1) {
//check if plugin with same name is registered
var uniqueName: boolean = true;
for (var i = 0; i < this._availablePlugins.length; i++) {
if (plugin.name === this._availablePlugins[i].name) {
uniqueName = false;
}
}
if (uniqueName) {
this._availablePlugins.push(plugin);
Kiwi.Log.log(" Kiwi.PluginManager: Registered plugin " + plugin.name + ": version " + plugin.version, '#plugin');
} else {
Kiwi.Log.warn(" Kiwi.PluginManager: A plugin with the same name has already been registered. Ignoring this plugin.", '#plugin');
}
} else {
Kiwi.Log.warn(" Kiwi.PluginManager: This plugin has already been registered. Ignoring second registration.", '#plugin');
}
}
/**
* Identifies the object as a PluginManager.
* @property objType
* @type {string} "PluginManager"
* @public
*/
public get objType(): string {
return "PluginManager";
}
/**
* A reference to the game instance that owns the PluginManager.
* @property objType
* @type Kiwi.Game
* @private
*/
private _game: Kiwi.Game;
/**
* An array of plugin names which the game instance has been configured to use. Each name must match the constructor function for the plugin.
* @property _plugins
* @type Array
* @private
*/
private _plugins: string[];
/**
* An array of objects that contain a boot function, each of which will be called when PluginManager.boot is invoked.
* @property _bootObjects
* @type Array
* @private
*/
private _bootObjects: any[];
/**
* Builds a list of valid plugins used by the game instance. Each plugin name that is supplied in the Kiwi.Game constructor configuration object
* is checked against the Kiwi.Plugins namespace to ensure that a property of the same name exists.
* This will ignore plugin that are registered but not used by the game instance.
* @method validatePlugins
* @public
*/
public validatePlugins() {
var validPlugins: string[] = new Array();
Kiwi.Log.log("Kiwi.PluginManager: Validating Plugins", '#plugins');
for (var i = 0; i < this._plugins.length; i++) {
var plugin: any = this._plugins[i];
if (typeof plugin == 'string' || plugin instanceof String) {
if (Kiwi.Plugins.hasOwnProperty(plugin) && this.pluginIsRegistered(plugin)) {
validPlugins.push(plugin);
Kiwi.Log.log(" Kiwi.PluginManager: Plugin '" + plugin + "' appears to be valid.", '#plugin');
Kiwi.Log.log(" Kiwi.PluginManager: Name:" + Kiwi.Plugins[plugin].name, '#plugin');
Kiwi.Log.log(" Kiwi.PluginManager: Version:" + Kiwi.Plugins[plugin].version, '#plugin');
//test for kiwi version compatiblity
if (typeof Kiwi.Plugins[plugin].minimumKiwiVersion !== "undefined") {
Kiwi.Log.log(" Kiwi.PluginManager: " + plugin + " requires minimum Kiwi version " + Kiwi.Plugins[plugin].minimumKiwiVersion, '#plugin');
var parsedKiwiVersion = Utils.Version.parseVersion(Kiwi.VERSION);
var parsedPluginMinVersion = Utils.Version.parseVersion(Kiwi.Plugins[plugin].minimumKiwiVersion);
if (parsedKiwiVersion.majorVersion > parsedPluginMinVersion.majorVersion) {
Kiwi.Log.warn(" Kiwi.PluginManager: This major version of Kiwi is greater than that required by '" + plugin + "'. It is unknown whether this plugin will work with this version of Kiwi", '#plugin');
} else {
if (Utils.Version.greaterOrEqual(Kiwi.VERSION, Kiwi.Plugins[plugin].minimumKiwiVersion)) {
Kiwi.Log.log(" Kiwi.PluginManager: Kiwi version meets minimum version requirements for '" + plugin + "'.", '#plugin');
} else {
Kiwi.Log.warn(" Kiwi.PluginManager: Kiwi version (" + Kiwi.VERSION + ") does not meet minimum version requirements for the plugin (" + Kiwi.Plugins[plugin].minimumKiwiVersion + ").", '#plugin');
}
}
} else {
Kiwi.Log.warn(" Kiwi.PluginManager: '" + plugin + "' is missing the minimumKiwiVersion property. It is unknown whether '" + plugin + "' will work with this version of Kiwi", '#plugin');
}
} else {
Kiwi.Log.log(" Kiwi.PluginManager: Plugin '" + plugin + "' appears to be invalid. No property with that name exists on the Kiwi.Plugins object or the Plugin is not registered. Check that the js file containing the plugin has been included. This plugin will be ignored", '#plugin');
}
} else {
Kiwi.Log.log(" Kiwi.PluginManager: The supplied plugin name at index " + i + "is not a string and will be ignored", '#plugin');
}
}
this._plugins = validPlugins;
for (var i = 0; i < this._plugins.length; i++) {
//test for plugin dependencies on other plugins
var pluginName: string = this._plugins[i];
var plugin = Kiwi.Plugins[pluginName];
if (typeof plugin.pluginDependencies !== "undefined") {
if (plugin.pluginDependencies.length === 0) {
Kiwi.Log.log(" Kiwi.PluginManager: '" + pluginName + "' does not depend on any other plugins.", '#plugin');
} else {
Kiwi.Log.log(" Kiwi.PluginManager: '" + pluginName + "' depends on the following plugins:", '#plugin', '#dependencies');
for (var j = 0; j < plugin.pluginDependencies.length; j++) {
Kiwi.Log.log(plugin.pluginDependencies[j].name, plugin.pluginDependencies[j].minimumVersion, '#plugin', '#dependencies' );
if (!this.validMinimumPluginVersionExists(plugin.pluginDependencies[j].name, plugin.pluginDependencies[j].minimumVersion)) {
Kiwi.Log.warn(" Kiwi.PluginManager: '" + plugin.pluginDependencies[j].name + " hasn't been added to this game via the config, doesn't exist, or does not meet minimum version requirement ( " + plugin.pluginDependencies[j].minimumVersion + ").", '#plugin', '#dependencies');
}
}
}
} else {
Kiwi.Log.log(" Kiwi.PluginManager: '" + pluginName + "' does not depend on any other plugins.", '#plugin', '#dependencies');
}
}
}
/**
* Returns whether a valid minimum version of a plugin exists.
* @method validMinimumPluginVersionExists
* @param name {string} Name of plugin
* @param version {string} Minimum version
* @return boolean
* @public
*/
public validMinimumPluginVersionExists( name: string, version: string ): boolean {
if ( this._plugins.indexOf( name ) !== -1 ) {
if ( Utils.Version.greaterOrEqual( Kiwi.Plugins[ name ].version, version ) ) {
return true;
}
}
return false;
}
/**
* Returns true if a plugin identified by the supplied pluginName is registered.
* @method pluginIsRegistered
* @param {string} pluginName
* @public
*/
public pluginIsRegistered(pluginName: string):boolean {
var isRegistered: boolean = false;
for (var i = 0; i < Kiwi.PluginManager._availablePlugins.length; i++) {
if (Kiwi.PluginManager._availablePlugins[i].name === pluginName) {
isRegistered = true;
}
}
return isRegistered;
}
/**
* Called after all other core objects and services created by the Kiwi.Game constructor are created.
* Attempts to find a "create" function on each plugin and calls it if it exists.
* The create function may return an object on which a boot function exists - to be called during boot process.
* @method _createPlugins
* @private
*/
private _createPlugins() {
for (var i = 0; i < this._plugins.length; i++) {
var plugin: string = this._plugins[i];
if (Kiwi.Plugins[plugin].hasOwnProperty("create")) {
var bootObject = Kiwi.Plugins[plugin].create(this._game);
if (bootObject) this._bootObjects.push(bootObject);
}
}
}
/**
* Calls the boot functions on any objects that plugins used by the game instance have designated during creation.
* @method boot
* @public
*/
public boot() {
for (var i = 0; i < this._bootObjects.length; i++) {
if ("boot" in this._bootObjects[i]) {
this._bootObjects[i].boot.call(this._bootObjects[i]);
} else {
Kiwi.Log.warn("Kiwi.PluginManager: Warning! No boot function found on boot object.", '#plugin');
}
}
}
/**
* Calls the update functions on any objects that plugins used by the game instance have designated during creation.
* @method update
* @public
*/
public update() {
for (var i = 0; i < this._bootObjects.length; i++) {
if ("update" in this._bootObjects[i]) {
this._bootObjects[i].update.call(this._bootObjects[i]);
}
}
}
}
} | the_stack |
export interface Schema {
/**
* Mandatory type "Schema".
*/
type: "Schema";
/**
* JSON-LD <a href="https://www.w3.org/TR/json-ld11/#the-context">@context</a> for ShEx.
*/
"@context"?: "http://www.w3.org/ns/shex.jsonld" | undefined;
/**
* List of semantic actions to be executed when evaluating conformance.
*/
startActs?: SemAct[] | undefined; // +
/**
* Identifies default starting shape expression.
*/
start?: shapeExpr | undefined;
/**
* List of ShEx schemas to <a href="http://shex.io/shex-semantics/#import">import</a> when processing this schema.
*/
imports?: IRIREF[] | undefined; // +
/**
* The list of {@link shapeExpr}s defined in this schema. Each MUST include and {@link ShapeOr#id}.
*/
shapes?: shapeExpr[] | undefined; // +
}
/**
* Union of shape expression types.
* @see <a href="http://shex.io/shex-semantics/#dfn-shapeexpr">ShEx shapeExpr definition</a>
*/
export type shapeExpr = ShapeOr | ShapeAnd | ShapeNot | NodeConstraint | Shape | ShapeExternal | shapeExprRef;
/**
* A non-exclusive choice of shape expressions; considered conformant if any of {@link #shapeExprs} conforms.
* @see <a href="http://shex.io/shex-semantics/#dfn-shapeor">ShEx shapeExpr definition</a>
*/
export interface ShapeOr {
/**
* Mandatory type "ShapeOr".
*/
type: "ShapeOr";
/**
* Only top-level expressions (i.e. embedded directly in {@link Schema#shapes) have an identifier.
* The identifier is an <a href="https://www.w3.org/TR/json-ld11/#node-identifiers">IRI</a> or a <a href="https://www.w3.org/TR/json-ld11/#identifying-blank-nodes">BlankNode</a>
* as expressed in <a href="https://www.w3.org/TR/json-ld11/">JSON-LD 1.1</a>.
*/
id?: shapeExprLabel | undefined;
/**
* List of two or more {@link shapeExpr}s in this disjunction.
*/
shapeExprs: shapeExpr[]; // {2,}
}
/**
* A conjunction of shape expressions; considered conformant if each conjunct conforms.
* @see <a href="http://shex.io/shex-semantics/#dfn-shapeor">ShEx shapeExpr definition</a>
*/
export interface ShapeAnd {
/**
* Mandatory type "ShapeAnd".
*/
type: "ShapeAnd";
/**
* Only top-level expressions (i.e. embedded directly in {@link Schema#shapes) have an identifier.
* The identifier is an <a href="https://www.w3.org/TR/json-ld11/#node-identifiers">IRI</a> or a <a href="https://www.w3.org/TR/json-ld11/#identifying-blank-nodes">BlankNode</a>
* as expressed in <a href="https://www.w3.org/TR/json-ld11/">JSON-LD 1.1</a>.
*/
id?: shapeExprLabel | undefined;
/**
* List of two or more {@link shapeExpr}s in this conjunction.
*/
shapeExprs: shapeExpr[]; // {2,}
}
/**
* A negated shape expressions; considered conformant if {@link #shapeExpr} is not conformant.
* @see <a href="http://shex.io/shex-semantics/#dfn-shapenot">ShEx shapeExpr definition</a>
*/
export interface ShapeNot {
/**
* Mandatory type "ShapeNot".
*/
type: "ShapeNot";
/**
* Only top-level expressions (i.e. embedded directly in {@link Schema#shapes) have an identifier.
* The identifier is an <a href="https://www.w3.org/TR/json-ld11/#node-identifiers">IRI</a> or a <a href="https://www.w3.org/TR/json-ld11/#identifying-blank-nodes">BlankNode</a>
* as expressed in <a href="https://www.w3.org/TR/json-ld11/">JSON-LD 1.1</a>.
*/
id?: shapeExprLabel | undefined;
/**
* The {@link shapeExpr} that must be non-conformant for this shape expression to be conformant.
*/
shapeExpr: shapeExpr;
}
/**
* A shape expression not defined in this schema or in any imported schema. The definition of this shape expression is NOT defined by ShEx.
* @see <a href="http://shex.io/shex-semantics/#dfn-shapeexternal">ShEx shapeExpr definition</a>
*/
export interface ShapeExternal {
/**
* Mandatory type "ShapeExternal".
*/
type: "ShapeExternal";
/**
* Only top-level expressions (i.e. embedded directly in {@link Schema#shapes) have an identifier.
* The identifier is an <a href="https://www.w3.org/TR/json-ld11/#node-identifiers">IRI</a> or a <a href="https://www.w3.org/TR/json-ld11/#identifying-blank-nodes">BlankNode</a>
* as expressed in <a href="https://www.w3.org/TR/json-ld11/">JSON-LD 1.1</a>.
*/
id?: shapeExprLabel | undefined;
}
/**
* A reference a shape expression.
* The reference is an <a href="https://www.w3.org/TR/json-ld11/#node-identifiers">IRI</a> or a <a href="https://www.w3.org/TR/json-ld11/#identifying-blank-nodes">BlankNode</a>
* as expressed in <a href="https://www.w3.org/TR/json-ld11/">JSON-LD 1.1</a>.
*/
export type shapeExprRef = shapeExprLabel;
/**
* An identifier for a shape expression.
* The identifier is an <a href="https://www.w3.org/TR/json-ld11/#node-identifiers">IRI</a> or a <a href="https://www.w3.org/TR/json-ld11/#identifying-blank-nodes">BlankNode</a>
* as expressed in <a href="https://www.w3.org/TR/json-ld11/">JSON-LD 1.1</a>.
*/
export type shapeExprLabel = IRIREF | BNODE;
/**
* A collection of constraints on <a href="https://www.w3.org/TR/rdf11-concepts/#dfn-node">RDF Term</a>s expected for conformance.
* The identifier is an <a href="https://www.w3.org/TR/json-ld11/#node-identifiers">IRI</a> or a <a href="https://www.w3.org/TR/json-ld11/#identifying-blank-nodes">BlankNode</a>
* as expressed in <a href="https://www.w3.org/TR/json-ld11/">JSON-LD 1.1</a>.
*/
export interface NodeConstraint extends xsFacet {
/**
* Mandatory type "NodeConstraint".
*/
type: "NodeConstraint";
/**
* Only top-level expressions (i.e. embedded directly in {@link Schema#shapes) have an identifier.
* The identifier is an <a href="https://www.w3.org/TR/json-ld11/#node-identifiers">IRI</a> or a <a href="https://www.w3.org/TR/json-ld11/#identifying-blank-nodes">BlankNode</a>
* as expressed in <a href="https://www.w3.org/TR/json-ld11/">JSON-LD 1.1</a>.
*/
id?: shapeExprLabel | undefined;
/**
* Type of <a href="https://www.w3.org/TR/rdf11-concepts/#dfn-node">RDF Term</a> expected for a conformant RDF node.
* @see <a href="http://shex.io/shex-semantics/#nodeKind">ShEx nodeKind definition</a>
*/
nodeKind?: "iri" | "bnode" | "nonliteral" | "literal" | undefined;
/**
* The <a href="https://www.w3.org/TR/rdf11-concepts/#dfn-datatype-iri">RDF Literal datatype IRITerm</a> expected for a conformant RDF node.
* @see <a href="http://shex.io/shex-semantics/#datatype">ShEx datatype definition</a>
*/
datatype?: IRIREF | undefined;
/**
* The set of permissible values.
* @see <a href="http://shex.io/shex-semantics/#values">ShEx values definition</a>
*/
values?: valueSetValue[] | undefined;
}
/**
* The set of XML Schema Facets supported in ShEx; defers to {@link stringFacet} and {@link numericFacet}.
* @see <a href="http://shex.io/shex-semantics/#xs-string">ShEx String Facet Constraints</a> and <a href="http://shex.io/shex-semantics/#xs-numeric">ShEx Numeric Facet Constraints</a>.
*/
export interface xsFacet extends stringFacet, numericFacet {
}
/**
* The set of <a href="https://www.w3.org/TR/xmlschema-2/#facets">XML Schema Facets</a> applying to <a href="https://www.w3.org/TR/rdf11-concepts/#dfn-lexical-form">lexical forms of RDF terms</a>.
* @see <a href="http://shex.io/shex-semantics/#xs-string">ShEx String Facet Constraints</a>.
*/
export interface stringFacet {
/**
* Expected length of the lexical form of an RDF Term.
*/
length?: INTEGER | undefined;
/**
* Expected minimum length of the lexical form of an RDF Term.
*/
minlength?: INTEGER | undefined;
/**
* Expected maximum length of the lexical form of an RDF Term.
*/
maxlength?: INTEGER | undefined;
/**
* Regular expression which the lexical forn of an RDF Term must match.
*/
pattern?: STRING | undefined;
/**
* Optional flags for the regular expression in {@link pattern}.
*/
flags?: STRING | undefined;
}
/**
* The set of <a href="https://www.w3.org/TR/xmlschema-2/#facets">XML Schema Facets</a> applying to <a href="https://www.w3.org/TR/rdf11-concepts/#dfn-value-space">numeric values of RDF terms</a>.
* @see <a href="http://shex.io/shex-semantics/#xs-numeric">ShEx Numeric Facet Constraints</a>.
*/
export interface numericFacet {
/**
* Conformant <a href="https://www.w3.org/TR/rdf11-concepts/#dfn-literal">RDF Literal</a> has as a numeric value <= {@link mininclusive}.
*/
mininclusive?: numericLiteral | undefined;
/**
* Conformant <a href="https://www.w3.org/TR/rdf11-concepts/#dfn-literal">RDF Literal</a> has as a numeric value < {@link minexclusive}.
*/
minexclusive?: numericLiteral | undefined;
/**
* Conformant <a href="https://www.w3.org/TR/rdf11-concepts/#dfn-literal">RDF Literal</a> has as a numeric value > {@link maxinclusive}.
*/
maxinclusive?: numericLiteral | undefined;
/**
* Conformant <a href="https://www.w3.org/TR/rdf11-concepts/#dfn-literal">RDF Literal</a> has as a numeric value >= {@link maxexclusive}.
*/
maxexclusive?: numericLiteral | undefined;
/**
* Conformant <a href="https://www.w3.org/TR/rdf11-concepts/#dfn-literal">RDF Literal</a> has as a numeric value whose canonical form has {@link totaldigits} digits.
* @see <a href="http://shex.io/shex-semantics/#nodeSatisfies-totaldigits">ShEx totalDigits definition</a>
*/
totaldigits?: INTEGER | undefined;
/**
* Conformant <a href="https://www.w3.org/TR/rdf11-concepts/#dfn-literal">RDF Literal</a> has as a numeric value whose canonical form has {@link fractiondigits} digits.
* @see <a href="http://shex.io/shex-semantics/#nodeSatisfies-fractiondigits">ShEx fractionDigits definition</a>
*/
fractiondigits?: INTEGER | undefined;
}
/**
* Union of numeric types in ShEx used in {@link numericFacet}s.
*/
export type numericLiteral = INTEGER | DECIMAL | DOUBLE;
/**
* Union of numeric types that may appear in a value set.
* @see {@link NodeConstraint#values}.
*/
export type valueSetValue = objectValue | IriStem | IriStemRange | LiteralStem | LiteralStemRange | Language | LanguageStem | LanguageStemRange;
/**
* JSON-LD representation of a URL or a Literal.
*/
export type objectValue = IRIREF | ObjectLiteral;
/**
* A <a href="https://www.w3.org/TR/json-ld11/#value-objects">JSON-LD Value Object</a> used to express an <a href="https://www.w3.org/TR/rdf11-concepts/#dfn-literal">RDF Literal</a>.
*/
export interface ObjectLiteral {
/**
* The <a href="https://www.w3.org/TR/rdf11-concepts/#dfn-lexical-form">lexical form</a> of an RDF Literal.
*/
value: STRING;
/**
* The <a href="https://www.w3.org/TR/rdf11-concepts/#dfn-language-tag">language tag</a> of an RDF Literal.
*/
language?: STRING | undefined;
/**
* The <a href="https://www.w3.org/TR/rdf11-concepts/#dfn-datatype">datatype</a> of an RDF Literal.
*/
type?: STRING | undefined;
}
/**
* Matchs an <a href="https://www.w3.org/TR/rdf11-concepts/#dfn-iri">RDF IRI</a> starting with the character sequence in {@link stem}.
*/
export interface IriStem {
/**
* Mandatory type "IriStem".
*/
type: "IriStem";
/**
* substring of IRI to be matched.
*/
stem: IRIREF;
}
/**
* Filters a matching <a href="https://www.w3.org/TR/rdf11-concepts/#dfn-iri">RDF IRI</a>s through a list of exclusions.
* The initial match is made on an IRI stem per {@link IriStem} or a {@link Wildcard} to accept any IRI.
* The {@link exclusion}s are either specific IRIs or {@link IRIStem}s.
*/
export interface IriStemRange {
/**
* Mandatory type "IriStemRange".
*/
type: "IriStemRange";
/**
* substring of IRI to be matched or a {@link Wildcard} matching any IRI.
*/
stem: IRIREF | Wildcard;
/**
* IRIs or {@link IRIStem}s to exclude.
*/
exclusions: Array<IRIREF | IriStem>; // +
}
/**
* Matchs an <a href="https://www.w3.org/TR/rdf11-concepts/#dfn-literal">RDF Literal</a> starting with the character sequence in {@link stem}.
*/
export interface LiteralStem {
/**
* Mandatory type "LiteralStem".
*/
type: "LiteralStem";
/**
* substring of Literal to be matched.
*/
stem: STRING;
}
/**
* Filters a matching <a href="https://www.w3.org/TR/rdf11-concepts/#dfn-literal">RDF Literal</a>s through a list of exclusions.
* The initial match is made on an Literal stem per {@link LiteralStem} or a {@link Wildcard} to accept any Literal.
* The {@link exclusion}s are either specific Literals or {@link LiteralStem}s.
*/
export interface LiteralStemRange {
/**
* Mandatory type "LiteralStemRange".
*/
type: "LiteralStemRange";
/**
* substring of Literal to be matched or a {@link Wildcard} matching any Literal.
*/
stem: STRING | Wildcard;
/**
* Literals or {@link LiteralStem}s to exclude.
*/
exclusions: Array<STRING | LiteralStem>; // +
}
/**
* An <a href="https://www.w3.org/TR/rdf11-concepts/#dfn-language-tag">RDF Language Tag</a>.
*/
export interface Language {
/**
* Mandatory type "Language".
*/
type: "Language";
/**
* The <a href="https://www.w3.org/TR/rdf11-concepts/#dfn-lexical-form">lexical representation</a> of an RDF Language Tag.
*/
languageTag: LANGTAG;
}
/**
* Matchs an <a href="https://www.w3.org/TR/rdf11-concepts/#dfn-language-tag">RDF Language Tag</a> starting with the character sequence in {@link stem}.
*/
export interface LanguageStem {
/**
* Mandatory type "LanguageStem".
*/
type: "LanguageStem";
/**
* substring of Language Tag to be matched.
*/
stem: LANGTAG;
}
/**
* Filters a matching <a href="https://www.w3.org/TR/rdf11-concepts/#dfn-langugae-tag">RDF Language Tag</a>s through a list of exclusions.
* The initial match is made on an Language Tag stem per {@link Language TagStem} or a {@link Wildcard} to accept any Language Tag.
* The {@link exclusion}s are either specific Language Tags or {@link Language TagStem}s.
*/
export interface LanguageStemRange {
/**
* Mandatory type "LanguageStemRange".
*/
type: "LanguageStemRange";
/**
* substring of Language-Tag to be matched or a {@link Wildcard} matching any Language Tag.
*/
stem: LANGTAG | Wildcard;
/**
* Language Tags or {@link LanguageStem}s to exclude.
*/
exclusions: Array<LANGTAG | LanguageStem>; // +
}
/**
* An empty object signifying than any item may be matched.
* This is used in {@link IriStemRange}, {@link LiteralStemRange} and {@link LanguageStemRange}.
*/
export interface Wildcard {
/**
* Mandatory type "Wildcard".
*/
type: "Wildcard";
}
/**
* A collection of {@link tripleExpr}s which must be matched by <a href="https://www.w3.org/TR/rdf11-concepts/#dfn-triple">RDF Triple</a>s in conformance data.
*/
export interface Shape {
/**
* Mandatory type "Shape".
*/
type: "Shape";
/**
* Only top-level expressions (i.e. embedded directly in {@link Schema#shapes) have an identifier.
* The identifier is an <a href="https://www.w3.org/TR/json-ld11/#node-identifiers">IRI</a> or a <a href="https://www.w3.org/TR/json-ld11/#identifying-blank-nodes">BlankNode</a>
* as expressed in <a href="https://www.w3.org/TR/json-ld11/">JSON-LD 1.1</a>.
*/
id?: shapeExprLabel | undefined;
/**
* Only the predicates mentioned in the {@link expression} may appear in conformant data.
*/
closed?: BOOL | undefined;
/**
* Permit extra triples with these predicates to appear in triples which don't match any {@link TripleConstraint}s mentioned in the {@link expression}.
*/
extra?: IRIREF[] | undefined;
/**
* A tree of {@link tripleExpr}s specifying a set triples into or out of conformant <a href="https://www.w3.org/TR/rdf11-concepts/#dfn-node">RDF Nodes</a>.
*/
expression?: tripleExpr | undefined;
/**
* List of semantic actions to be executed when evaluating conformance.
*/
semActs?: SemAct[] | undefined; // +;
/**
* List of {@link SemAct#predicate}/{@link SemAct#object} annotations attached to this {@link Shape}.
*/
annotations?: Annotation[] | undefined; // +
}
/**
* Union of triple expression types.
* @see <a href="http://shex.io/shex-semantics/#dfn-tripleexpr">ShEx shapeExpr definition</a>
*/
export type tripleExpr = EachOf | OneOf | TripleConstraint | tripleExprRef;
/**
* Common attributes appearing in every form of {@link tripleExpr}.
*/
export interface tripleExprBase {
/**
* Optional identifier for {@link tripleExpr}s for reference by {@link tripleExprRef}.
* The identifier is an <a href="https://www.w3.org/TR/json-ld11/#node-identifiers">IRI</a> or a <a href="https://www.w3.org/TR/json-ld11/#identifying-blank-nodes">BlankNode</a>
* as expressed in <a href="https://www.w3.org/TR/json-ld11/">JSON-LD 1.1</a>.
*/
id?: shapeExprLabel | undefined;
/**
* Minimum number of times matching triples must appear in conformant data.
*/
min?: INTEGER | undefined;
/**
* Maximum number of times matching triples must appear in conformant data.
*/
max?: INTEGER | undefined;
/**
* List of semantic actions to be executed when evaluating conformance.
*/
semActs?: SemAct[] | undefined; // +;
/**
* List of {@link SemAct#predicate}/{@link SemAct#object} annotations attached to this {@link tripleExpr}.
*/
annotations?: Annotation[] | undefined; // +
}
/**
* A list of of triple expressions; considered conformant if there is some conforming mapping of the examined triples to the {@link #tripleExprs}.
* @see <a href="http://shex.io/shex-semantics/#dfn-eachof">ShEx EachOf definition</a>
*/
export interface EachOf extends tripleExprBase {
/**
* Mandatory type "EachOf".
*/
type: "EachOf";
expressions: tripleExpr[]; // {2,}
}
/**
* An exclusive choice of triple expressions; considered conformant if exactly one of {@link #shapeExprs} conforms.
* @see <a href="http://shex.io/shex-semantics/#dfn-oneof">ShEx OneOf definition</a>
*/
export interface OneOf extends tripleExprBase {
/**
* Mandatory type "OneOf".
*/
type: "OneOf";
expressions: tripleExpr[]; // {2,}
}
/**
* A template matching a number of triples attached to the node being validated.
*/
export interface TripleConstraint extends tripleExprBase {
/**
* Mandatory type "TripleConstraint".
*/
type: "TripleConstraint";
/**
* If false, the TripleConstraint matches the a triple composed of a focus node, the {@link predicate} and an object matching the (optional) {@link shapeExpr}.
* If true, the TripleConstraint matches the a triple composed of a subject matching the (optional) {@link shapeExpr}, the {@link predicate} and focus node.
*/
inverse?: BOOL | undefined;
/**
* The predicate expected in a matching <a href="https://www.w3.org/TR/rdf11-concepts/#dfn-triple">RDF Triple</a>.
*/
predicate: IRIREF;
/**
* A {@link shapeExpr} matching a conformant <a href="https://www.w3.org/TR/rdf11-concepts/#dfn-triple">RDF Triple</a>s subject or object, depending on the value of {@link inverse}.
*/
valueExpr?: shapeExpr | undefined;
}
/**
* A reference a triple expression.
* The reference is an <a href="https://www.w3.org/TR/json-ld11/#node-identifiers">IRI</a> or a <a href="https://www.w3.org/TR/json-ld11/#identifying-blank-nodes">BlankNode</a>
* as expressed in <a href="https://www.w3.org/TR/json-ld11/">JSON-LD 1.1</a>.
*/
export type tripleExprRef = tripleExprLabel;
/**
* An identifier for a triple expression.
* The identifier is an <a href="https://www.w3.org/TR/json-ld11/#node-identifiers">IRI</a> or a <a href="https://www.w3.org/TR/json-ld11/#identifying-blank-nodes">BlankNode</a>
* as expressed in <a href="https://www.w3.org/TR/json-ld11/">JSON-LD 1.1</a>.
*/
export type tripleExprLabel = IRIREF | BNODE;
/**
* An extension point for Shape Expressions allowing external code to be invoked during validation.
*/
export interface SemAct {
/**
* Mandatory type "SemAct".
*/
type: "SemAct";
/*
* Identifier of the language for this semantic action.
*/
name: IRIREF;
/*
* The actual code to be interpreted/executed.
* This may be kept separate from the ShEx containing the schema by including only {@link name}s in the schema.
*/
code?: STRING | undefined;
}
/**
* An assertion about some part of a ShEx schema which has no affect on conformance checking.
* These can be useful for documentation, provenance tracking, form generation, etch.
*/
export interface Annotation {
/**
* Mandatory type "Annotation".
*/
type: "Annotation";
/**
* The <a href="https://www.w3.org/TR/json-ld11/#node-identifiers">RDF Predicate</a> of the annotation.
*/
predicate: IRI;
/**
* A value for the above {@link predicate}.
*/
object: objectValue;
}
export type IRIREF = string;
export type BNODE = string;
export type INTEGER = number;
export type STRING = string;
export type DECIMAL = number;
export type DOUBLE = number;
export type LANGTAG = string;
export type BOOL = boolean;
export type IRI = string; | the_stack |
import { BaseResource } from 'ms-rest-azure';
import { CloudError } from 'ms-rest-azure';
import * as moment from 'moment';
export { BaseResource } from 'ms-rest-azure';
export { CloudError } from 'ms-rest-azure';
/**
* @class
* Initializes a new instance of the SubResource class.
* @constructor
* The Sub Resource model definition.
*
* @member {string} [id] Resource Id
* @member {string} name Resource name
* @member {string} [type] Resource type
*/
export interface SubResource {
readonly id?: string;
name: string;
readonly type?: string;
}
/**
* @class
* Initializes a new instance of the StorageAccountInfo class.
* @constructor
* Azure Storage account information.
*
* @member {string} accessKey the access key associated with this Azure Storage
* account that will be used to connect to it.
* @member {string} [suffix] the optional suffix for the storage account.
*/
export interface StorageAccountInfo extends SubResource {
accessKey: string;
suffix?: string;
}
/**
* @class
* Initializes a new instance of the StorageContainer class.
* @constructor
* Azure Storage blob container information.
*
* @member {string} [id] the unique identifier of the blob container.
* @member {string} [name] the name of the blob container.
* @member {string} [type] the type of the blob container.
* @member {date} [lastModifiedTime] the last modified time of the blob
* container.
*/
export interface StorageContainer {
readonly id?: string;
readonly name?: string;
readonly type?: string;
readonly lastModifiedTime?: Date;
}
/**
* @class
* Initializes a new instance of the SasTokenInfo class.
* @constructor
* SAS token information.
*
* @member {string} [accessToken] the access token for the associated Azure
* Storage Container.
*/
export interface SasTokenInfo {
readonly accessToken?: string;
}
/**
* @class
* Initializes a new instance of the DataLakeStoreAccountInfo class.
* @constructor
* Data Lake Store account information.
*
* @member {string} [suffix] the optional suffix for the Data Lake Store
* account.
*/
export interface DataLakeStoreAccountInfo extends SubResource {
suffix?: string;
}
/**
* @class
* Initializes a new instance of the OptionalSubResource class.
* @constructor
* The Resource model definition for a nested resource with no required
* properties.
*
* @member {string} [id] Resource Id
* @member {string} [name] Resource name
* @member {string} [type] Resource type
*/
export interface OptionalSubResource {
readonly id?: string;
name?: string;
readonly type?: string;
}
/**
* @class
* Initializes a new instance of the FirewallRule class.
* @constructor
* Data Lake Analytics firewall rule information
*
* @member {string} startIpAddress the start IP address for the firewall rule.
* This can be either ipv4 or ipv6. Start and End should be in the same
* protocol.
* @member {string} endIpAddress the end IP address for the firewall rule. This
* can be either ipv4 or ipv6. Start and End should be in the same protocol.
*/
export interface FirewallRule extends OptionalSubResource {
startIpAddress: string;
endIpAddress: string;
}
/**
* @class
* Initializes a new instance of the ComputePolicyAccountCreateParameters class.
* @constructor
* The parameters used to create a new compute policy.
*
* @member {string} name The unique name of the policy to create
* @member {uuid} objectId The AAD object identifier for the entity to create a
* policy for.
* @member {string} objectType The type of AAD object the object identifier
* refers to. Possible values include: 'User', 'Group', 'ServicePrincipal'
* @member {number} [maxDegreeOfParallelismPerJob] The maximum degree of
* parallelism per job this user can use to submit jobs. This property, the min
* priority per job property, or both must be passed.
* @member {number} [minPriorityPerJob] The minimum priority per job this user
* can use to submit jobs. This property, the max degree of parallelism per job
* property, or both must be passed.
*/
export interface ComputePolicyAccountCreateParameters {
name: string;
objectId: string;
objectType: string;
maxDegreeOfParallelismPerJob?: number;
minPriorityPerJob?: number;
}
/**
* @class
* Initializes a new instance of the ComputePolicy class.
* @constructor
* The parameters used to create a new compute policy.
*
* @member {string} [name] The name of the compute policy
* @member {uuid} [objectId] The AAD object identifier for the entity to create
* a policy for.
* @member {string} [objectType] The type of AAD object the object identifier
* refers to. Possible values include: 'User', 'Group', 'ServicePrincipal'
* @member {number} [maxDegreeOfParallelismPerJob] The maximum degree of
* parallelism per job this user can use to submit jobs.
* @member {number} [minPriorityPerJob] The minimum priority per job this user
* can use to submit jobs.
*/
export interface ComputePolicy {
readonly name?: string;
readonly objectId?: string;
readonly objectType?: string;
maxDegreeOfParallelismPerJob?: number;
minPriorityPerJob?: number;
}
/**
* @class
* Initializes a new instance of the AddDataLakeStoreParameters class.
* @constructor
* Additional Data Lake Store parameters.
*
* @member {string} [suffix] the optional suffix for the Data Lake Store
* account.
*/
export interface AddDataLakeStoreParameters {
suffix?: string;
}
/**
* @class
* Initializes a new instance of the AddStorageAccountParameters class.
* @constructor
* Storage account parameters for a storage account being added to a Data Lake
* Analytics account.
*
* @member {string} accessKey the access key associated with this Azure Storage
* account that will be used to connect to it.
* @member {string} [suffix] the optional suffix for the storage account.
*/
export interface AddStorageAccountParameters {
accessKey: string;
suffix?: string;
}
/**
* @class
* Initializes a new instance of the UpdateStorageAccountParameters class.
* @constructor
* Storage account parameters for a storage account being updated in a Data
* Lake Analytics account.
*
* @member {string} [accessKey] the updated access key associated with this
* Azure Storage account that will be used to connect to it.
* @member {string} [suffix] the optional suffix for the storage account.
*/
export interface UpdateStorageAccountParameters {
accessKey?: string;
suffix?: string;
}
/**
* @class
* Initializes a new instance of the ComputePolicyCreateOrUpdateParameters class.
* @constructor
* The parameters used to create a new compute policy.
*
* @member {uuid} objectId The AAD object identifier for the entity to create a
* policy for.
* @member {string} objectType The type of AAD object the object identifier
* refers to. Possible values include: 'User', 'Group', 'ServicePrincipal'
* @member {number} [maxDegreeOfParallelismPerJob] The maximum degree of
* parallelism per job this user can use to submit jobs. This property, the min
* priority per job property, or both must be passed.
* @member {number} [minPriorityPerJob] The minimum priority per job this user
* can use to submit jobs. This property, the max degree of parallelism per job
* property, or both must be passed.
*/
export interface ComputePolicyCreateOrUpdateParameters {
objectId: string;
objectType: string;
maxDegreeOfParallelismPerJob?: number;
minPriorityPerJob?: number;
}
/**
* @class
* Initializes a new instance of the DataLakeAnalyticsAccountUpdateParameters class.
* @constructor
* The parameters that can be used to update an existing Data Lake Analytics
* account.
*
* @member {object} [tags] Resource tags
* @member {number} [maxDegreeOfParallelism] the maximum supported degree of
* parallelism for this account.
* @member {number} [queryStoreRetention] the number of days that job metadata
* is retained.
* @member {number} [maxJobCount] the maximum supported jobs running under the
* account at the same time.
* @member {string} [newTier] the commitment tier to use for next month.
* Possible values include: 'Consumption', 'Commitment_100AUHours',
* 'Commitment_500AUHours', 'Commitment_1000AUHours', 'Commitment_5000AUHours',
* 'Commitment_10000AUHours', 'Commitment_50000AUHours',
* 'Commitment_100000AUHours', 'Commitment_500000AUHours'
* @member {string} [firewallState] The current state of the IP address
* firewall for this Data Lake Analytics account. Possible values include:
* 'Enabled', 'Disabled'
* @member {string} [firewallAllowAzureIps] The current state of allowing or
* disallowing IPs originating within Azure through the firewall. If the
* firewall is disabled, this is not enforced. Possible values include:
* 'Enabled', 'Disabled'
* @member {array} [firewallRules] The list of firewall rules associated with
* this Data Lake Analytics account.
* @member {number} [maxDegreeOfParallelismPerJob] the maximum supported degree
* of parallelism per job for this account.
* @member {number} [minPriorityPerJob] the minimum supported priority per job
* for this account.
* @member {array} [computePolicies] the list of existing compute policies to
* update in this account.
*/
export interface DataLakeAnalyticsAccountUpdateParameters {
tags?: { [propertyName: string]: string };
maxDegreeOfParallelism?: number;
queryStoreRetention?: number;
maxJobCount?: number;
newTier?: string;
firewallState?: string;
firewallAllowAzureIps?: string;
firewallRules?: FirewallRule[];
maxDegreeOfParallelismPerJob?: number;
minPriorityPerJob?: number;
computePolicies?: ComputePolicy[];
}
/**
* @class
* Initializes a new instance of the DataLakeAnalyticsAccountPropertiesBasic class.
* @constructor
* The basic account specific properties that are associated with an underlying
* Data Lake Analytics account.
*
* @member {string} [provisioningState] the provisioning status of the Data
* Lake Analytics account. Possible values include: 'Failed', 'Creating',
* 'Running', 'Succeeded', 'Patching', 'Suspending', 'Resuming', 'Deleting',
* 'Deleted', 'Undeleting', 'Canceled'
* @member {string} [state] the state of the Data Lake Analytics account.
* Possible values include: 'Active', 'Suspended'
* @member {date} [creationTime] the account creation time.
* @member {date} [lastModifiedTime] the account last modified time.
* @member {string} [endpoint] the full CName endpoint for this account.
* @member {uuid} [accountId] The unique identifier associated with this Data
* Lake Analytics account.
*/
export interface DataLakeAnalyticsAccountPropertiesBasic {
readonly provisioningState?: string;
readonly state?: string;
readonly creationTime?: Date;
readonly lastModifiedTime?: Date;
readonly endpoint?: string;
readonly accountId?: string;
}
/**
* @class
* Initializes a new instance of the Resource class.
* @constructor
* The Resource model definition.
*
* @member {string} [id] Resource Id
* @member {string} [name] Resource name
* @member {string} [type] Resource type
* @member {string} location Resource location
* @member {object} [tags] Resource tags
*/
export interface Resource extends BaseResource {
readonly id?: string;
readonly name?: string;
readonly type?: string;
location: string;
tags?: { [propertyName: string]: string };
}
/**
* @class
* Initializes a new instance of the DataLakeAnalyticsAccountBasic class.
* @constructor
* A Data Lake Analytics account object, containing all information associated
* with the named Data Lake Analytics account.
*
* @member {string} [provisioningState] the provisioning status of the Data
* Lake Analytics account. Possible values include: 'Failed', 'Creating',
* 'Running', 'Succeeded', 'Patching', 'Suspending', 'Resuming', 'Deleting',
* 'Deleted', 'Undeleting', 'Canceled'
* @member {string} [state] the state of the Data Lake Analytics account.
* Possible values include: 'Active', 'Suspended'
* @member {date} [creationTime] the account creation time.
* @member {date} [lastModifiedTime] the account last modified time.
* @member {string} [endpoint] the full CName endpoint for this account.
* @member {uuid} [accountId] The unique identifier associated with this Data
* Lake Analytics account.
*/
export interface DataLakeAnalyticsAccountBasic extends Resource {
readonly provisioningState?: string;
readonly state?: string;
readonly creationTime?: Date;
readonly lastModifiedTime?: Date;
readonly endpoint?: string;
readonly accountId?: string;
}
/**
* @class
* Initializes a new instance of the DataLakeAnalyticsAccount class.
* @constructor
* A Data Lake Analytics account object, containing all information associated
* with the named Data Lake Analytics account.
*
* @member {string} [provisioningState] the provisioning status of the Data
* Lake Analytics account. Possible values include: 'Failed', 'Creating',
* 'Running', 'Succeeded', 'Patching', 'Suspending', 'Resuming', 'Deleting',
* 'Deleted', 'Undeleting', 'Canceled'
* @member {string} [state] the state of the Data Lake Analytics account.
* Possible values include: 'Active', 'Suspended'
* @member {date} [creationTime] the account creation time.
* @member {date} [lastModifiedTime] the account last modified time.
* @member {string} [endpoint] the full CName endpoint for this account.
* @member {uuid} [accountId] The unique identifier associated with this Data
* Lake Analytics account.
* @member {string} defaultDataLakeStoreAccount the default data lake storage
* account associated with this Data Lake Analytics account.
* @member {number} [maxDegreeOfParallelism] the maximum supported degree of
* parallelism for this account. Default value: 30 .
* @member {number} [queryStoreRetention] the number of days that job metadata
* is retained. Default value: 30 .
* @member {number} [maxJobCount] the maximum supported jobs running under the
* account at the same time. Default value: 3 .
* @member {number} [systemMaxDegreeOfParallelism] the system defined maximum
* supported degree of parallelism for this account, which restricts the
* maximum value of parallelism the user can set for the account..
* @member {number} [systemMaxJobCount] the system defined maximum supported
* jobs running under the account at the same time, which restricts the maximum
* number of running jobs the user can set for the account.
* @member {array} dataLakeStoreAccounts the list of Data Lake storage accounts
* associated with this account.
* @member {array} [storageAccounts] the list of Azure Blob storage accounts
* associated with this account.
* @member {string} [newTier] the commitment tier for the next month. Possible
* values include: 'Consumption', 'Commitment_100AUHours',
* 'Commitment_500AUHours', 'Commitment_1000AUHours', 'Commitment_5000AUHours',
* 'Commitment_10000AUHours', 'Commitment_50000AUHours',
* 'Commitment_100000AUHours', 'Commitment_500000AUHours'
* @member {string} [currentTier] the commitment tier in use for the current
* month. Possible values include: 'Consumption', 'Commitment_100AUHours',
* 'Commitment_500AUHours', 'Commitment_1000AUHours', 'Commitment_5000AUHours',
* 'Commitment_10000AUHours', 'Commitment_50000AUHours',
* 'Commitment_100000AUHours', 'Commitment_500000AUHours'
* @member {string} [firewallState] The current state of the IP address
* firewall for this Data Lake Analytics account. Possible values include:
* 'Enabled', 'Disabled'
* @member {string} [firewallAllowAzureIps] The current state of allowing or
* disallowing IPs originating within Azure through the firewall. If the
* firewall is disabled, this is not enforced. Possible values include:
* 'Enabled', 'Disabled'
* @member {array} [firewallRules] The list of firewall rules associated with
* this Data Lake Analytics account.
* @member {number} [maxDegreeOfParallelismPerJob] the maximum supported degree
* of parallelism per job for this account.
* @member {number} [minPriorityPerJob] the minimum supported priority per job
* for this account.
* @member {array} [computePolicies] the list of compute policies to create in
* this account.
*/
export interface DataLakeAnalyticsAccount extends Resource {
readonly provisioningState?: string;
readonly state?: string;
readonly creationTime?: Date;
readonly lastModifiedTime?: Date;
readonly endpoint?: string;
readonly accountId?: string;
defaultDataLakeStoreAccount: string;
maxDegreeOfParallelism?: number;
queryStoreRetention?: number;
maxJobCount?: number;
readonly systemMaxDegreeOfParallelism?: number;
readonly systemMaxJobCount?: number;
dataLakeStoreAccounts: DataLakeStoreAccountInfo[];
storageAccounts?: StorageAccountInfo[];
newTier?: string;
readonly currentTier?: string;
firewallState?: string;
firewallAllowAzureIps?: string;
firewallRules?: FirewallRule[];
maxDegreeOfParallelismPerJob?: number;
minPriorityPerJob?: number;
computePolicies?: ComputePolicyAccountCreateParameters[];
}
/**
* @class
* Initializes a new instance of the UpdateFirewallRuleParameters class.
* @constructor
* Data Lake Analytics firewall rule update parameters
*
* @member {string} [startIpAddress] the start IP address for the firewall
* rule. This can be either ipv4 or ipv6. Start and End should be in the same
* protocol.
* @member {string} [endIpAddress] the end IP address for the firewall rule.
* This can be either ipv4 or ipv6. Start and End should be in the same
* protocol.
*/
export interface UpdateFirewallRuleParameters {
startIpAddress?: string;
endIpAddress?: string;
}
/**
* @class
* Initializes a new instance of the ComputePolicyListResult class.
* @constructor
* The list of compute policies in the account.
*
* @member {string} [nextLink] the link (url) to the next page of results.
*/
export interface ComputePolicyListResult extends Array<ComputePolicy> {
readonly nextLink?: string;
}
/**
* @class
* Initializes a new instance of the DataLakeAnalyticsFirewallRuleListResult class.
* @constructor
* Data Lake Analytics firewall rule list information.
*
* @member {string} [nextLink] the link (url) to the next page of results.
*/
export interface DataLakeAnalyticsFirewallRuleListResult extends Array<FirewallRule> {
readonly nextLink?: string;
}
/**
* @class
* Initializes a new instance of the ListStorageContainersResult class.
* @constructor
* The list of blob containers associated with the storage account attached to
* the Data Lake Analytics account.
*
* @member {string} [nextLink] the link (url) to the next page of results.
*/
export interface ListStorageContainersResult extends Array<StorageContainer> {
readonly nextLink?: string;
}
/**
* @class
* Initializes a new instance of the ListSasTokensResult class.
* @constructor
* The SAS response that contains the storage account, container and associated
* SAS token for connection use.
*
* @member {string} [nextLink] the link (url) to the next page of results.
*/
export interface ListSasTokensResult extends Array<SasTokenInfo> {
readonly nextLink?: string;
}
/**
* @class
* Initializes a new instance of the DataLakeAnalyticsAccountListStorageAccountsResult class.
* @constructor
* Azure Storage Account list information.
*
* @member {string} [nextLink] the link (url) to the next page of results.
*/
export interface DataLakeAnalyticsAccountListStorageAccountsResult extends Array<StorageAccountInfo> {
readonly nextLink?: string;
}
/**
* @class
* Initializes a new instance of the DataLakeAnalyticsAccountListDataLakeStoreResult class.
* @constructor
* Data Lake Account list information.
*
* @member {string} [nextLink] the link (url) to the next page of results.
*/
export interface DataLakeAnalyticsAccountListDataLakeStoreResult extends Array<DataLakeStoreAccountInfo> {
readonly nextLink?: string;
}
/**
* @class
* Initializes a new instance of the DataLakeAnalyticsAccountListResult class.
* @constructor
* DataLakeAnalytics Account list information.
*
* @member {string} [nextLink] the link (url) to the next page of results.
*/
export interface DataLakeAnalyticsAccountListResult extends Array<DataLakeAnalyticsAccountBasic> {
readonly nextLink?: string;
} | the_stack |
import { DebtRegistryEntry, DebtRegistryEntryData, TxData } from "../../types";
import * as promisify from "tiny-promisify";
import { classUtils } from "../../../utils/class_utils";
import { Web3Utils } from "../../../utils/web3_utils";
import { BigNumber } from "../../../utils/bignumber";
import { DebtRegistry as ContractArtifacts } from "@dharmaprotocol/contracts";
import * as Web3 from "web3";
import { BaseContract, CONTRACT_WRAPPER_ERRORS } from "./base_contract_wrapper";
export class DebtRegistryContract extends BaseContract {
public getTermsContractParameters = {
async callAsync(issuanceHash: string, defaultBlock?: Web3.BlockParam): Promise<string> {
const self = this as DebtRegistryContract;
const result = await promisify<string>(
self.web3ContractInstance.getTermsContractParameters.call,
self.web3ContractInstance,
)(issuanceHash);
return result;
},
};
public unpause = {
async sendTransactionAsync(txData: TxData = {}): Promise<string> {
const self = this as DebtRegistryContract;
const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(
txData,
self.unpause.estimateGasAsync.bind(self),
);
const txHash = await promisify<string>(
self.web3ContractInstance.unpause,
self.web3ContractInstance,
)(txDataWithDefaults);
return txHash;
},
async estimateGasAsync(txData: TxData = {}): Promise<number> {
const self = this as DebtRegistryContract;
const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData);
const gas = await promisify<number>(
self.web3ContractInstance.unpause.estimateGas,
self.web3ContractInstance,
)(txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(txData: TxData = {}): string {
const self = this as DebtRegistryContract;
const abiEncodedTransactionData = self.web3ContractInstance.unpause.getData();
return abiEncodedTransactionData;
},
};
public addAuthorizedEditAgent = {
async sendTransactionAsync(agent: string, txData: TxData = {}): Promise<string> {
const self = this as DebtRegistryContract;
const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(
txData,
self.addAuthorizedEditAgent.estimateGasAsync.bind(self, agent),
);
const txHash = await promisify<string>(
self.web3ContractInstance.addAuthorizedEditAgent,
self.web3ContractInstance,
)(agent, txDataWithDefaults);
return txHash;
},
async estimateGasAsync(agent: string, txData: TxData = {}): Promise<number> {
const self = this as DebtRegistryContract;
const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData);
const gas = await promisify<number>(
self.web3ContractInstance.addAuthorizedEditAgent.estimateGas,
self.web3ContractInstance,
)(agent, txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(agent: string, txData: TxData = {}): string {
const self = this as DebtRegistryContract;
const abiEncodedTransactionData = self.web3ContractInstance.addAuthorizedEditAgent.getData();
return abiEncodedTransactionData;
},
};
public modifyBeneficiary = {
async sendTransactionAsync(
issuanceHash: string,
newBeneficiary: string,
txData: TxData = {},
): Promise<string> {
const self = this as DebtRegistryContract;
const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(
txData,
self.modifyBeneficiary.estimateGasAsync.bind(self, issuanceHash, newBeneficiary),
);
const txHash = await promisify<string>(
self.web3ContractInstance.modifyBeneficiary,
self.web3ContractInstance,
)(issuanceHash, newBeneficiary, txDataWithDefaults);
return txHash;
},
async estimateGasAsync(
issuanceHash: string,
newBeneficiary: string,
txData: TxData = {},
): Promise<number> {
const self = this as DebtRegistryContract;
const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData);
const gas = await promisify<number>(
self.web3ContractInstance.modifyBeneficiary.estimateGas,
self.web3ContractInstance,
)(issuanceHash, newBeneficiary, txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(
issuanceHash: string,
newBeneficiary: string,
txData: TxData = {},
): string {
const self = this as DebtRegistryContract;
const abiEncodedTransactionData = self.web3ContractInstance.modifyBeneficiary.getData();
return abiEncodedTransactionData;
},
};
public paused = {
async callAsync(defaultBlock?: Web3.BlockParam): Promise<boolean> {
const self = this as DebtRegistryContract;
const result = await promisify<boolean>(
self.web3ContractInstance.paused.call,
self.web3ContractInstance,
)();
return result;
},
};
public getAuthorizedInsertAgents = {
async callAsync(defaultBlock?: Web3.BlockParam): Promise<string[]> {
const self = this as DebtRegistryContract;
const result = await promisify<string[]>(
self.web3ContractInstance.getAuthorizedInsertAgents.call,
self.web3ContractInstance,
)();
return result;
},
};
public getDebtorsDebts = {
async callAsync(debtor: string, defaultBlock?: Web3.BlockParam): Promise<string[]> {
const self = this as DebtRegistryContract;
const result = await promisify<[string, string]>(
self.web3ContractInstance.getDebtorsDebts.call,
self.web3ContractInstance,
)(debtor);
return result;
},
};
public getTerms = {
async callAsync(
issuanceHash: string,
defaultBlock?: Web3.BlockParam,
): Promise<[string, string]> {
const self = this as DebtRegistryContract;
const result = await promisify<[string, string]>(
self.web3ContractInstance.getTerms.call,
self.web3ContractInstance,
)(issuanceHash);
return result;
},
};
public getIssuanceBlockNumber = {
async callAsync(issuanceHash: string, defaultBlock?: Web3.BlockParam): Promise<BigNumber> {
const self = this as DebtRegistryContract;
const result = await promisify<BigNumber>(
self.web3ContractInstance.getIssuanceBlockNumber.call,
self.web3ContractInstance,
)(issuanceHash);
return result;
},
};
public pause = {
async sendTransactionAsync(txData: TxData = {}): Promise<string> {
const self = this as DebtRegistryContract;
const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(
txData,
self.pause.estimateGasAsync.bind(self),
);
const txHash = await promisify<string>(
self.web3ContractInstance.pause,
self.web3ContractInstance,
)(txDataWithDefaults);
return txHash;
},
async estimateGasAsync(txData: TxData = {}): Promise<number> {
const self = this as DebtRegistryContract;
const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData);
const gas = await promisify<number>(
self.web3ContractInstance.pause.estimateGas,
self.web3ContractInstance,
)(txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(txData: TxData = {}): string {
const self = this as DebtRegistryContract;
const abiEncodedTransactionData = self.web3ContractInstance.pause.getData();
return abiEncodedTransactionData;
},
};
public owner = {
async callAsync(defaultBlock?: Web3.BlockParam): Promise<string> {
const self = this as DebtRegistryContract;
const result = await promisify<string>(
self.web3ContractInstance.owner.call,
self.web3ContractInstance,
)();
return result;
},
};
public get = {
async callAsync(
issuanceHash: string,
defaultBlock?: Web3.BlockParam,
): Promise<DebtRegistryEntry> {
const self = this as DebtRegistryContract;
const result = await promisify<DebtRegistryEntryData>(
self.web3ContractInstance.get.call,
self.web3ContractInstance,
)(issuanceHash);
return DebtRegistryEntry.fromData(result);
},
};
public revokeEditAgentAuthorization = {
async sendTransactionAsync(agent: string, txData: TxData = {}): Promise<string> {
const self = this as DebtRegistryContract;
const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(
txData,
self.revokeEditAgentAuthorization.estimateGasAsync.bind(self, agent),
);
const txHash = await promisify<string>(
self.web3ContractInstance.revokeEditAgentAuthorization,
self.web3ContractInstance,
)(agent, txDataWithDefaults);
return txHash;
},
async estimateGasAsync(agent: string, txData: TxData = {}): Promise<number> {
const self = this as DebtRegistryContract;
const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData);
const gas = await promisify<number>(
self.web3ContractInstance.revokeEditAgentAuthorization.estimateGas,
self.web3ContractInstance,
)(agent, txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(agent: string, txData: TxData = {}): string {
const self = this as DebtRegistryContract;
const abiEncodedTransactionData = self.web3ContractInstance.revokeEditAgentAuthorization.getData();
return abiEncodedTransactionData;
},
};
public addAuthorizedInsertAgent = {
async sendTransactionAsync(agent: string, txData: TxData = {}): Promise<string> {
const self = this as DebtRegistryContract;
const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(
txData,
self.addAuthorizedInsertAgent.estimateGasAsync.bind(self, agent),
);
const txHash = await promisify<string>(
self.web3ContractInstance.addAuthorizedInsertAgent,
self.web3ContractInstance,
)(agent, txDataWithDefaults);
return txHash;
},
async estimateGasAsync(agent: string, txData: TxData = {}): Promise<number> {
const self = this as DebtRegistryContract;
const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData);
const gas = await promisify<number>(
self.web3ContractInstance.addAuthorizedInsertAgent.estimateGas,
self.web3ContractInstance,
)(agent, txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(agent: string, txData: TxData = {}): string {
const self = this as DebtRegistryContract;
const abiEncodedTransactionData = self.web3ContractInstance.addAuthorizedInsertAgent.getData();
return abiEncodedTransactionData;
},
};
public getBeneficiary = {
async callAsync(issuanceHash: string, defaultBlock?: Web3.BlockParam): Promise<string> {
const self = this as DebtRegistryContract;
const result = await promisify<string>(
self.web3ContractInstance.getBeneficiary.call,
self.web3ContractInstance,
)(issuanceHash);
return result;
},
};
public revokeInsertAgentAuthorization = {
async sendTransactionAsync(agent: string, txData: TxData = {}): Promise<string> {
const self = this as DebtRegistryContract;
const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(
txData,
self.revokeInsertAgentAuthorization.estimateGasAsync.bind(self, agent),
);
const txHash = await promisify<string>(
self.web3ContractInstance.revokeInsertAgentAuthorization,
self.web3ContractInstance,
)(agent, txDataWithDefaults);
return txHash;
},
async estimateGasAsync(agent: string, txData: TxData = {}): Promise<number> {
const self = this as DebtRegistryContract;
const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData);
const gas = await promisify<number>(
self.web3ContractInstance.revokeInsertAgentAuthorization.estimateGas,
self.web3ContractInstance,
)(agent, txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(agent: string, txData: TxData = {}): string {
const self = this as DebtRegistryContract;
const abiEncodedTransactionData = self.web3ContractInstance.revokeInsertAgentAuthorization.getData();
return abiEncodedTransactionData;
},
};
public insert = {
async sendTransactionAsync(
_version: string,
_beneficiary: string,
_debtor: string,
_underwriter: string,
_underwriterRiskRating: BigNumber,
_termsContract: string,
_termsContractParameters: string,
_salt: BigNumber,
txData: TxData = {},
): Promise<string> {
const self = this as DebtRegistryContract;
const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(
txData,
self.insert.estimateGasAsync.bind(
self,
_version,
_beneficiary,
_debtor,
_underwriter,
_underwriterRiskRating,
_termsContract,
_termsContractParameters,
_salt,
),
);
const txHash = await promisify<string>(
self.web3ContractInstance.insert,
self.web3ContractInstance,
)(
_version,
_beneficiary,
_debtor,
_underwriter,
_underwriterRiskRating,
_termsContract,
_termsContractParameters,
_salt,
txDataWithDefaults,
);
return txHash;
},
async estimateGasAsync(
_version: string,
_beneficiary: string,
_debtor: string,
_underwriter: string,
_underwriterRiskRating: BigNumber,
_termsContract: string,
_termsContractParameters: string,
_salt: BigNumber,
txData: TxData = {},
): Promise<number> {
const self = this as DebtRegistryContract;
const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData);
const gas = await promisify<number>(
self.web3ContractInstance.insert.estimateGas,
self.web3ContractInstance,
)(
_version,
_beneficiary,
_debtor,
_underwriter,
_underwriterRiskRating,
_termsContract,
_termsContractParameters,
_salt,
txDataWithDefaults,
);
return gas;
},
getABIEncodedTransactionData(
_version: string,
_beneficiary: string,
_debtor: string,
_underwriter: string,
_underwriterRiskRating: BigNumber,
_termsContract: string,
_termsContractParameters: string,
_salt: BigNumber,
txData: TxData = {},
): string {
const self = this as DebtRegistryContract;
const abiEncodedTransactionData = self.web3ContractInstance.insert.getData();
return abiEncodedTransactionData;
},
};
public transferOwnership = {
async sendTransactionAsync(newOwner: string, txData: TxData = {}): Promise<string> {
const self = this as DebtRegistryContract;
const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(
txData,
self.transferOwnership.estimateGasAsync.bind(self, newOwner),
);
const txHash = await promisify<string>(
self.web3ContractInstance.transferOwnership,
self.web3ContractInstance,
)(newOwner, txDataWithDefaults);
return txHash;
},
async estimateGasAsync(newOwner: string, txData: TxData = {}): Promise<number> {
const self = this as DebtRegistryContract;
const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData);
const gas = await promisify<number>(
self.web3ContractInstance.transferOwnership.estimateGas,
self.web3ContractInstance,
)(newOwner, txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(newOwner: string, txData: TxData = {}): string {
const self = this as DebtRegistryContract;
const abiEncodedTransactionData = self.web3ContractInstance.transferOwnership.getData();
return abiEncodedTransactionData;
},
};
public getTermsContract = {
async callAsync(issuanceHash: string, defaultBlock?: Web3.BlockParam): Promise<string> {
const self = this as DebtRegistryContract;
const result = await promisify<string>(
self.web3ContractInstance.getTermsContract.call,
self.web3ContractInstance,
)(issuanceHash);
return result;
},
};
public getAuthorizedEditAgents = {
async callAsync(defaultBlock?: Web3.BlockParam): Promise<string[]> {
const self = this as DebtRegistryContract;
const result = await promisify<string[]>(
self.web3ContractInstance.getAuthorizedEditAgents.call,
self.web3ContractInstance,
)();
return result;
},
};
constructor(web3ContractInstance: Web3.ContractInstance, defaults: Partial<TxData>) {
super(web3ContractInstance, defaults);
classUtils.bindAll(this, ["web3ContractInstance", "defaults"]);
}
public static async deployed(
web3: Web3,
defaults: Partial<TxData>,
): Promise<DebtRegistryContract> {
const web3Utils = new Web3Utils(web3);
const currentNetwork = await web3Utils.getNetworkIdAsync();
const { abi, networks }: { abi: any; networks: any } = ContractArtifacts;
if (networks[currentNetwork]) {
const { address: contractAddress } = networks[currentNetwork];
const contractExists = await web3Utils.doesContractExistAtAddressAsync(contractAddress);
if (contractExists) {
const web3ContractInstance = web3.eth.contract(abi).at(contractAddress);
return new DebtRegistryContract(web3ContractInstance, defaults);
} else {
throw new Error(
CONTRACT_WRAPPER_ERRORS.CONTRACT_NOT_FOUND_ON_NETWORK(
"DebtRegistry",
currentNetwork,
),
);
}
} else {
throw new Error(
CONTRACT_WRAPPER_ERRORS.CONTRACT_NOT_FOUND_ON_NETWORK(
"DebtRegistry",
currentNetwork,
),
);
}
}
public static async at(
address: string,
web3: Web3,
defaults: Partial<TxData>,
): Promise<DebtRegistryContract> {
const web3Utils = new Web3Utils(web3);
const { abi }: { abi: any } = ContractArtifacts;
const contractExists = await web3Utils.doesContractExistAtAddressAsync(address);
const currentNetwork = await web3Utils.getNetworkIdAsync();
if (contractExists) {
const web3ContractInstance = web3.eth.contract(abi).at(address);
return new DebtRegistryContract(web3ContractInstance, defaults);
} else {
throw new Error(
CONTRACT_WRAPPER_ERRORS.CONTRACT_NOT_FOUND_ON_NETWORK(
"DebtRegistry",
currentNetwork,
),
);
}
}
} // tslint:disable:max-file-line-count | the_stack |
import {
App,
Notice,
Plugin,
PluginSettingTab,
Setting,
TFile,
} from "obsidian";
import safeRegex from "safe-regex";
import { imageTagProcessor } from "./contentProcessor";
import { replaceAsync, cleanContent } from "./utils";
import {
ISettings,
DEFAULT_SETTINGS,
EXTERNAL_MEDIA_LINK_PATTERN,
ANY_URL_PATTERN,
NOTICE_TIMEOUT,
TIMEOUT_LIKE_INFINITY,
} from "./config";
import { UniqueQueue } from "./uniqueQueue";
export default class LocalImagesPlugin extends Plugin {
settings: ISettings;
modifiedQueue = new UniqueQueue<TFile>();
intervalId: number = null;
private async proccessPage(file: TFile, silent = false) {
// const content = await this.app.vault.read(file);
const content = await this.app.vault.cachedRead(file);
await this.ensureFolderExists(this.settings.mediaRootDirectory);
const cleanedContent = this.settings.cleanContent
? cleanContent(content)
: content;
const fixedContent = await replaceAsync(
cleanedContent,
EXTERNAL_MEDIA_LINK_PATTERN,
imageTagProcessor(this.app, this.settings.mediaRootDirectory)
);
if (content != fixedContent) {
this.modifiedQueue.remove(file);
await this.app.vault.modify(file, fixedContent);
if (!silent && this.settings.showNotifications) {
new Notice(`Images for "${file.path}" were processed.`);
}
} else {
if (!silent && this.settings.showNotifications) {
new Notice(
`Page "${file.path}" has been processed, but nothing was changed.`
);
}
}
}
// using arrow syntax for callbacks to correctly pass this context
processActivePage = async () => {
const activeFile = this.app.workspace.getActiveFile();
await this.proccessPage(activeFile);
};
processAllPages = async () => {
const files = this.app.vault.getMarkdownFiles();
const includeRegex = new RegExp(this.settings.include, "i");
const pagesCount = files.length;
const notice = this.settings.showNotifications
? new Notice(
`Local Images \nStart processing. Total ${pagesCount} pages. `,
TIMEOUT_LIKE_INFINITY
)
: null;
for (const [index, file] of files.entries()) {
if (file.path.match(includeRegex)) {
if (notice) {
// setMessage() is undeclared but factically existing, so ignore the TS error
// @ts-expect-error
notice.setMessage(
`Local Images: Processing \n"${file.path}" \nPage ${index} of ${pagesCount}`
);
}
await this.proccessPage(file, true);
}
}
if (notice) {
// @ts-expect-error
notice.setMessage(`Local Images: ${pagesCount} pages were processed.`);
setTimeout(() => {
notice.hide();
}, NOTICE_TIMEOUT);
}
};
async onload() {
await this.loadSettings();
this.addCommand({
id: "download-images",
name: "Download images locally",
callback: this.processActivePage,
});
this.addCommand({
id: "download-images-all",
name: "Download images locally for all your notes",
callback: this.processAllPages,
});
this.registerCodeMirror((cm: CodeMirror.Editor) => {
// on("beforeChange") can not execute async function in event handler, so we use queue to pass modified pages to timeouted handler
cm.on("change", async (instance: CodeMirror.Editor, changeObj: any) => {
if (
changeObj.origin == "paste" &&
ANY_URL_PATTERN.test(changeObj.text)
) {
this.enqueueActivePage();
}
});
});
this.setupQueueInterval();
this.addSettingTab(new SettingTab(this.app, this));
}
setupQueueInterval() {
if (this.intervalId) {
const intervalId = this.intervalId;
this.intervalId = null;
window.clearInterval(intervalId);
}
if (
this.settings.realTimeUpdate &&
this.settings.realTimeUpdateInterval > 0
) {
this.intervalId = window.setInterval(
this.processModifiedQueue,
this.settings.realTimeUpdateInterval
);
this.registerInterval(this.intervalId);
}
}
processModifiedQueue = async () => {
const iteration = this.modifiedQueue.iterationQueue();
for (const page of iteration) {
this.proccessPage(page);
}
};
enqueueActivePage() {
const activeFile = this.app.workspace.getActiveFile();
this.modifiedQueue.push(
activeFile,
this.settings.realTimeAttemptsToProcess
);
}
// It is good idea to create the plugin more verbose
displayError(error: Error | string, file?: TFile): void {
if (file) {
new Notice(
`LocalImages: Error while handling file ${
file.name
}, ${error.toString()}`
);
} else {
new Notice(error.toString());
}
console.error(`LocalImages: error: ${error}`);
}
onunload() {}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
this.setupQueueInterval();
}
async saveSettings() {
try {
await this.saveData(this.settings);
} catch (error) {
this.displayError(error);
}
}
async ensureFolderExists(folderPath: string) {
try {
await this.app.vault.createFolder(folderPath);
} catch (error) {
if (!error.message.contains("Folder already exists")) {
throw error;
}
}
}
}
class SettingTab extends PluginSettingTab {
plugin: LocalImagesPlugin;
constructor(app: App, plugin: LocalImagesPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
let { containerEl } = this;
containerEl.empty();
containerEl.createEl("h2", { text: "Local images" });
new Setting(containerEl)
.setName("On paste processing")
.setDesc("Process active page if external link was pasted.")
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.realTimeUpdate)
.onChange(async (value) => {
this.plugin.settings.realTimeUpdate = value;
await this.plugin.saveSettings();
this.plugin.setupQueueInterval();
})
);
new Setting(containerEl)
.setName("On paste processing interval")
.setDesc("Interval in milliseconds for processing update.")
.setTooltip(
"I could not process content on the fly when it is pasted. So real processing implements periodically with the given here timeout."
)
.addText((text) =>
text
.setValue(String(this.plugin.settings.realTimeUpdateInterval))
.onChange(async (value: string) => {
const numberValue = Number(value);
if (
isNaN(numberValue) ||
!Number.isInteger(numberValue) ||
numberValue < 0
) {
this.plugin.displayError(
"Realtime processing interval should be a positive integer number!"
);
return;
}
this.plugin.settings.realTimeUpdateInterval = numberValue;
await this.plugin.saveSettings();
this.plugin.setupQueueInterval();
})
);
new Setting(containerEl)
.setName("Attempts to process")
.setDesc(
"Number of attempts to process content on paste. For me 3 attempts is enouth with 1 second update interval."
)
.setTooltip(
"I could not find the way to access newly pasted content immediatily, after pasting, Plugin's API returns old text for a while. The workaround is to process page several times until content is changed."
)
.addText((text) =>
text
.setValue(String(this.plugin.settings.realTimeAttemptsToProcess))
.onChange(async (value: string) => {
const numberValue = Number(value);
if (
isNaN(numberValue) ||
!Number.isInteger(numberValue) ||
numberValue < 1 ||
numberValue > 100
) {
this.plugin.displayError(
"Realtime processing interval should be a positive integer number greater than 1 and lower than 100!"
);
return;
}
this.plugin.settings.realTimeAttemptsToProcess = numberValue;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName("Clean content")
.setDesc("Clean malformed image tags before processing.")
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.cleanContent)
.onChange(async (value) => {
this.plugin.settings.cleanContent = value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName("Show notifications")
.setDesc("Show notifications when pages were processed.")
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.showNotifications)
.onChange(async (value) => {
this.plugin.settings.showNotifications = value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName("Include")
.setDesc(
"Include only files matching this regex pattern when running on all notes."
)
.addText((text) =>
text.setValue(this.plugin.settings.include).onChange(async (value) => {
if (!safeRegex(value)) {
this.plugin.displayError(
"Unsafe regex! https://www.npmjs.com/package/safe-regex"
);
return;
}
this.plugin.settings.include = value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName("Media folder")
.setDesc("Folder to keep all downloaded media files.")
.addText((text) =>
text
.setValue(this.plugin.settings.mediaRootDirectory)
.onChange(async (value) => {
this.plugin.settings.mediaRootDirectory = value;
await this.plugin.saveSettings();
})
);
}
} | the_stack |
export type TypePageType_Video = 'video'
export type TypePageType_Webpage = 'webpage'
export type TypePageType_Article = 'article'
export type TypePageType = TypePageType_Video | TypePageType_Webpage | TypePageType_Article
export type TypeUserInfoResponse_TabsInfo_Tab = {
id: 2
tabKey: 'weibo'
must_show: 1
hidden: 0
title: '微博'
tab_type: 'weibo'
containerid: '1076031245161127'
apipath: '/profile/statuses'
url: '/index/my'
}
export type TypeUserInfoResponse = {
ok: 1
data: {
avatar_guide: []
userInfo: {
id: 1245161127
screen_name: 'eprom'
profile_image_url: 'https://tva2.sinaimg.cn/crop.0.0.180.180.180/4a37a6a7jw1e8qgp5bmzyj2050050aa8.jpg?KID=imgbed,tva&Expires=1568225294&ssig=sM99PIQa4u'
profile_url: 'https://m.weibo.cn/u/1245161127?uid=1245161127&luicode=10000011&lfid=1005051245161127'
statuses_count: 60406
verified: true
verified_type: 0
verified_type_ext: 1
verified_reason: '知名科学科普博主 微博签约自媒体'
close_blue_v: false
description: '群龙之首,傲视天际,万民敬仰'
gender: 'm'
mbtype: 12
urank: 48
mbrank: 7
follow_me: false
following: true
followers_count: 334141
follow_count: 207
cover_image_phone: 'https://wx1.sinaimg.cn/crop.0.0.640.640.640/4a37a6a7ly1fj7ou6dawvj20u00u044p.jpg'
avatar_hd: 'https://ww2.sinaimg.cn/orj480/4a37a6a7jw1e8qgp5bmzyj2050050aa8.jpg'
like: false
like_me: false
toolbar_menus: [
{
type: 'profile_follow'
name: '已关注'
sub_type: 1
params: {
uid: 1245161127
}
actionlog: {
act_code: '594'
fid: '2307741245161127'
oid: '1005051245161127'
cardid: '230774_-_WEIBO_INDEX_PROFILE_FOLLOW'
ext: 'uid:1718734760|ouid:1245161127|ptype:0|verified_type:0|load_read_level:0|btn_name:关注'
}
},
{
type: 'link'
name: '聊天'
params: {
scheme: 'sinaweibo://messagelist?uid=1245161127&nick=eprom&verified_type=0&send_from=user_profile'
}
actionlog: {
act_code: '594'
fid: '2307741245161127'
oid: 'messagelist'
cardid: '230774_-_WEIBO_INDEX_PROFILE_CHAT'
ext: 'uid:1718734760|ouid:1245161127|ptype:0|verified_type:0|load_read_level:0|btn_name:聊天'
}
scheme: 'https://m.weibo.cn/msg/chat?uid=1245161127&nick=eprom&verified_type=0&send_from=user_profile&luicode=10000011&lfid=1005051245161127'
},
{
type: 'toolbar_menu_list'
name: '他的热门'
params: {
menu_list: [
{
type: 'link'
name: '热门内容'
params: {
scheme: 'sinaweibo://cardlist?containerid=2310021245161127_-_HOTMBLOG'
}
actionlog: {
act_code: '594'
fid: '2307741245161127'
oid: '2310021245161127_-_HOTMBLOG'
cardid: '230774_-_WEIBO_INDEX_PROFILE_HOTWEIBO'
ext: 'uid:1718734760|ouid:1245161127|ptype:0|verified_type:0|load_read_level:0|btn_name:热门内容'
}
scheme: 'https://m.weibo.cn/p/index?containerid=2310021245161127_-_HOTMBLOG&luicode=10000011&lfid=1005051245161127'
},
{
type: 'link'
name: '橱窗'
params: {
scheme: 'sinaweibo://cardlist?containerid=2316161245161127_-_USERSHOPWINDOW'
}
actionlog: {
act_code: '594'
fid: '2307741245161127'
oid: '2316161245161127_-_USERSHOPWINDOW'
cardid: '230774_-_WEIBO_INDEX_PROFILE_SHOPWINDOW'
ext: 'uid:1718734760|ouid:1245161127|ptype:0|verified_type:0|load_read_level:0|btn_name:橱窗'
}
scheme: 'https://m.weibo.cn/p/index?containerid=2316161245161127_-_USERSHOPWINDOW&luicode=10000011&lfid=1005051245161127'
},
]
}
actionlog: {
act_code: '594'
fid: '2307741245161127'
oid: '1005051245161127'
cardid: '230774_-_WEIBO_INDEX_PROFILE_BTN_ALL'
ext: 'uid:1718734760|ouid:1245161127|ptype:0|verified_type:0|load_read_level:0|btn_name:他的热门'
}
},
]
}
fans_scheme: 'https://m.weibo.cn/p/index?containerid=231051_-_fans_intimacy_-_1245161127&luicode=10000011&lfid=1005051245161127'
follow_scheme: 'https://m.weibo.cn/p/index?containerid=231051_-_followersrecomm_-_1245161127&luicode=10000011&lfid=1005051245161127'
tabsInfo: {
selectedTab: 1
tabs: Array<TypeUserInfoResponse_TabsInfo_Tab>
}
scheme: 'sinaweibo://userinfo?uid=1245161127&type=uid&value=1245161127&luicode=10000011&lfid=1076031245161127&v_p=42&fid=1005051245161127&uicode=10000011'
showAppTips: 1
}
}
export type TypeWeiboUserInfo = {
id: 1245161127
screen_name: 'eprom'
profile_image_url: 'https://tva2.sinaimg.cn/crop.0.0.180.180.180/4a37a6a7jw1e8qgp5bmzyj2050050aa8.jpg?KID=imgbed,tva&Expires=1568225849&ssig=HCSlyweo%2BV'
profile_url: 'https://m.weibo.cn/u/1245161127?uid=1245161127&luicode=10000011&lfid=2304131245161127_-_WEIBO_SECOND_PROFILE_WEIBO'
statuses_count: 59804
verified: true
verified_type: 0
verified_type_ext: 1
verified_reason: '知名科学科普博主 微博签约自媒体'
close_blue_v: false
description: '群龙之首,傲视天际,万民敬仰'
gender: 'm'
mbtype: 12
urank: 48
mbrank: 7
follow_me: false
following: true
followers_count: 293997
follow_count: 205
cover_image_phone: 'https://wx1.sinaimg.cn/crop.0.0.640.640.640/4a37a6a7ly1fj7ou6dawvj20u00u044p.jpg'
avatar_hd: 'https://ww2.sinaimg.cn/orj480/4a37a6a7jw1e8qgp5bmzyj2050050aa8.jpg'
like: false
like_me: false
badge: {
taobao: 1
gongyi_level: 1
bind_taobao: 1
self_media: 1
dzwbqlx_2016: 1
follow_whitelist_video: 1
panda: 1
user_name_certificate: 1
wenchuan_10th: 1
asiad_2018: 1
relation_display: 1
china_2019: 1
hongkong_2019: 1
}
}
export type TypenWeiboRecord_UserInfo = {
id: 1221171697
screen_name: '兔主席'
profile_image_url: 'https://tva3.sinaimg.cn/crop.0.0.180.180.180/48c999f1jw1e8qgp5bmzyj2050050aa8.jpg?KID=imgbed,tva&Expires=1568350906&ssig=Efm2vfVTjS'
profile_url: 'https://m.weibo.cn/u/1221171697?uid=1221171697&luicode=10000011&lfid=1076031221171697'
statuses_count: 6979
verified: true
verified_type: 0
verified_type_ext: 1
verified_reason: '知名历史博主 头条文章作者'
close_blue_v: false
description: '大历史。大社会。 独立。理性。批判。建设。'
gender: 'm'
mbtype: 11
urank: 38
mbrank: 6
follow_me: false
following: true
followers_count: 1053009
follow_count: 468
cover_image_phone: 'https://tva1.sinaimg.cn/crop.0.0.640.640.640/549d0121tw1egm1kjly3jj20hs0hsq4f.jpg'
avatar_hd: 'https://ww3.sinaimg.cn/orj480/48c999f1jw1e8qgp5bmzyj2050050aa8.jpg'
like: false
like_me: false
badge: {
bind_taobao: 1
dzwbqlx_2016: 1
follow_whitelist_video: 1
user_name_certificate: 1
china_2019: 1
hongkong_2019: 1
}
}
export type TypePageInfo = {
page_pic: {
url: 'https://wx4.sinaimg.cn/wap720/48c999f1gy1g6uza6a6qlj20d407egm6.jpg'
}
page_url: 'https://m.weibo.cn/feature/applink?scheme=sinaweibo%3A%2F%2Farticlebrowser%3Fobject_id%3D1022%253A2309404446645566701785%26url%3Dhttps%253A%252F%252Fcard.weibo.com%252Farticle%252Fm%252Fshow%252Fid%252F2309404446645566701785%253F_wb_client_%253D1%26extparam%3Dlmid--4446645569803228&luicode=10000011&lfid=2304131913094142_-_WEIBO_SECOND_PROFILE_WEIBO'
page_title: '香港反对派推促的美国反华法案对香港经济的影响?'
content1: '香港反对派推促的美国反华法案对香港经济的影响?'
content2: ''
icon: 'https://h5.sinaimg.cn/upload/2016/12/28/14/feed_headlines_icon_flash20161228_2.png'
type: TypePageType
object_id: '1022:2309404414789865570479'
// 视频中带的key
play_count: "36万次播放"
"media_info": {
"duration": 161.957,
"stream_url": "https://f.video.weibocdn.com/NMJVsI9olx07LzZ45oti01041200k0S70E010.mp4?label=mp4_ld&template=640x360.25.0&trans_finger=40a32e8439c5409a63ccf853562a60ef&ori=0&ps=1CwnkDw1GXwCQx&Expires=1617380389&ssig=9i8xY5%2Bsww&KID=unistore,video",
"stream_url_hd": "https://f.video.weibocdn.com/UmEGuRZXlx07LzZ4GhsA01041200uhlA0E010.mp4?label=mp4_hd&template=852x480.25.0&trans_finger=62b30a3f061b162e421008955c73f536&ori=0&ps=1CwnkDw1GXwCQx&Expires=1617380389&ssig=iHKgDfh3oq&KID=unistore,video"
},
}
/**
* 最终版微博类型定义
*/
export type TypeMblog = {
visible: {
type: 0
list_id: 0
}
created_at: '09-08' | string
/**
* 需要主动解析为该值, 作为微博发表时间戳
*/
created_timestamp_at: number
/**
* 当delete值存在时,表示该微博已被删除. 此时created_timestamp_at不存在. 所有字段存在性都不能保证
*/
deleted?: '1'
/**
* 微博状态, 当微博异常时, 会有该字段
* 7 => 抱歉,此微博已被作者删除
* 8 => 该微博因被多人投诉,根据《微博社区公约》,已被删除
*
*/
state: 7
id: '4414052358656728'
idstr: '4414052358656728'
mid: '4414052358656728'
can_edit: boolean
thumbnail_pic: 'http://wx4.sinaimg.cn/thumbnail/48c999f1gy1g6rg0izojkj20yi1pce84.jpg'
bmiddle_pic: 'http://wx4.sinaimg.cn/bmiddle/48c999f1gy1g6rg0izojkj20yi1pce84.jpg'
original_pic: 'http://wx4.sinaimg.cn/large/48c999f1gy1g6rg0izojkj20yi1pce84.jpg'
is_paid: false
mblog_vip_type: 0
user: TypenWeiboRecord_UserInfo
picStatus: '0:1,1:1,2:1,3:1,4:1'
reposts_count: 53
comments_count: 56
attitudes_count: 347
pending_approval_count: 0
isLongText: boolean
reward_exhibition_type: 2
reward_scheme: 'sinaweibo://reward?bid=1000293251&enter_id=1000293251&enter_type=1&oid=4414052358656728&seller=1221171697&share=18cb5613ebf3d8aadd9975c1036ab1f47&sign=72970c731f265faf8d166e6281da4fc9'
hide_flag: 0
mblogtype: 0
more_info_type: 0
extern_safe: 0
number_display_strategy: {
apply_scenario_flag: 3
display_text_min_number: 1000000
display_text: '100万+'
}
content_auth: 0
pic_num: 5
mblog_menu_new_style: 0
edit_config: {
edited: false
}
weibo_position: 1
show_attitude_bar: 0
bid: 'I5Tz5Ak0E'
pics: Array<TypenWeiboRecord_Pic>
version: 4
show_additional_indication: 0
text: '发布了头条文章:《香港反对派推促的美国反华法案对香港经济的影响?》 与香港反对派及许多市民想象的不同,反华法案对香港经济的影响不大。1)香港贸易经济主要受制于中美贸易摩擦;2)香港的金融行业与贸易相关性间接有限。 <a data-url="http://t.cn/AiEi7fCM" href="https://media.weibo.cn/article?object_id=1022%3A2309404414789865570479&extparam=lmid--4414789868083942&luicode=10000011&lfid=2304131221171697_-_WEIBO_SECOND_PROFILE_WEIBO&id=2309404414789865570479" data-hide=""><span class=\'url-icon\'><img style=\'width: 1rem;height: 1rem\' src=\'https://h5.sinaimg.cn/upload/2015/09/25/3/timeline_card_small_article_default.png\'></span><span class="surl-text">香港反对派推促的美国反华法案对香港经济的影响?</span></a> '
/**
* 只在isLongText为false时有
*/
raw_text?: '看见没有,放了多少油[偷笑],还好吃就得多放油,然后。。。'
textLength: 230
source: '微博 weibo.com'
favorited: false
pic_types: ''
isTop: 1
page_info: TypePageInfo
title: {
text: '置顶'
base_color: 1
}
// 微博文章json, 仅当微博为文章类型时, 才添加到数据记录中
article?: TypeWeiboArticleRecord
// 被转发的微博
retweeted_status?: TypeMblog
}
export type TypenWeiboRecord_Pic = {
pid: '48c999f1gy1g6rg0p5ctvj20yi1pc4qq'
url: 'https://wx3.sinaimg.cn/orj360/48c999f1gy1g6rg0p5ctvj20yi1pc4qq.jpg'
size: 'orj360'
geo: {
width: 360
height: 640
croped: false
}
large: {
size: 'large'
url: 'https://wx3.sinaimg.cn/large/48c999f1gy1g6rg0p5ctvj20yi1pc4qq.jpg'
geo: {
width: '1242'
height: '2208'
croped: false
}
}
}
export type TypeWeiboRecord = {
card_type: 9
itemid: '1076031221171697_-_4414052358656728'
scheme: 'https://m.weibo.cn/status/I5Tz5Ak0E?mblogid=I5Tz5Ak0E&luicode=10000011&lfid=1076031221171697'
mblog: TypeMblog
show_type: 0
title: ''
}
export type TypeWeiboListResponse = {
ok: 1
data: {
cardlistInfo: {
containerid: '1076031221171697'
v_p: 42
show_style: 1
total: 7022
since_id: 4414047003058832
}
cards: Array<TypeWeiboRecord>
scheme: 'sinaweibo://cardlist?containerid=1076031221171697&extparam=&uid=1221171697&luicode=10000011&lfid=100103type%3D1%26q%3D%E5%85%94%E4%B8%BB%E5%B8%AD&type=uid&value=1221171697&since_id=4414889093011824&v_p=42&fid=1076031221171697&uicode=10000011'
}
}
export type TypeLongTextWeiboResponse = {
ok: 1
data: TypeMblog
}
export type TypeWeiboArticleRecord = {
"object_id": "1022:2309404619352241471539",
"vuid": 0,
"uid": 1221171697,
"cover_img": {
"image": {
"url": "https://wx2.sinaimg.cn/large/48c999f1ly1goyedm5xexj20kg0bi10f.jpg",
"height": 450,
"width": 800
},
"full_image": {
"url": "https://wx2.sinaimg.cn/large/48c999f1ly1goyedm5xexj20kg0bi10f.jpg",
"height": 562,
"width": 1000
}
},
"target_url": "https://card.weibo.com/article/m/show/id/2309404619352241471539",
"title": "理解西方人对“种族灭绝”的近代历史心结",
"create_at": "03-27 13:27",
"read_count": "40万+",
"summary": "",
"writer": [],
"ourl": "",
"url": "https://weibo.com/ttarticle/p/show?id=2309404619352241471539",
"is_pay": 0,
"is_reward": 0,
"is_vclub": 0,
"is_original": 0,
"pay_status": 0,
"follow_to_read": 1,
"userinfo": {
"uid": 1221171697,
"id": 1221171697,
"screen_name": "兔主席",
"description": "大历史。大社会。 独立。理性。批判。建设。",
"followers_count": 1762801,
"friends_count": 465,
"verified": true,
"verified_type": 0,
"verified_type_ext": 0,
"verified_reason": "知名历史博主 头条文章作者",
"avatar_large": "https://tva3.sinaimg.cn/crop.0.0.180.180.180/48c999f1jw1e8qgp5bmzyj2050050aa8.jpg?KID=imgbed,tva&Expires=1616914030&ssig=rphdPBquHf",
"profile_image_url": "https://tva3.sinaimg.cn/crop.0.0.180.180.50/48c999f1jw1e8qgp5bmzyj2050050aa8.jpg?KID=imgbed,tva&Expires=1616914030&ssig=eXClERRC%2FH",
"cover_image": "",
"cover_image_phone": "https://ww1.sinaimg.cn/crop.0.0.640.640.640/549d0121tw1egm1kjly3jj20hs0hsq4f.jpg",
"following": false,
"mbtype": 11,
"mbrank": 6,
"url": "https://weibo.com/u/1221171697",
"target_url": "https://m.weibo.cn/profile/1221171697",
"scheme_url": "sinaweibo://userinfo?uid=1221171697",
"is_vclub": 0,
"is_vclub_gold": 0
},
"content": "文本内容",
"is_import": 0,
"is_repost_to_share": 0,
"reward_data": {
"seller": 1221171697,
"bid": 1000207805,
"oid": "1022:2309404619352241471539",
"access_type": "mobileLayer",
"share": 1,
"sign": "6233ad671c5222c7f2aee451af28a202"
},
"copyright": 0,
"mid": 4619352240819112,
"is_word": 1,
"article_browser": 1,
"scheme_url": "sinaweibo://articlebrowser?object_id=1022:2309404619352241471539&url=https%3A%2F%2Fcard.weibo.com%2Farticle%2Fm%2Fshow%2Fid%2F2309404619352241471539",
"article_recommend": [],
"article_recommend_info": {
"type": 1
},
"ignore_read_count": 0,
"is_new_style": 1,
"card_list": [],
"object_info": [],
"extra": null,
"article_type": "v3_h5",
"history": "",
"origin_oid": "",
"update_at": "",
"show_edit": 0,
"pay_info": [],
"pay_info_ext": [],
"pay_edit_tips": "",
"pay_data": {
"version": "531294344d21a6d3",
"ua": "h5",
"vuid": 1221171697,
"body_btn": [],
"footer_btn": []
},
"is_checking": null,
"real_oid": null,
"hide_share_button": 0,
"hide_repost_button": 0,
"article_fingerprinting": "f8a66a53c0cf5b726a6703d83df4fdd9",
"is_follow": 0
}
/**
* 仅用于记录, 作为微博被删除的示例
*/
type TypeDeleteWeiboRecordDemo = {
visible: {
/**
* 0 => 已被删除/只在半年内可见
* 1 => 你没有查看这条微博的权限
*/
type: 0 | 1
list_id: 0
}
created_at: '08-16'
id: '4405996207851235'
idstr: '4405996207851235'
mid: '4405996207851235'
text: "抱歉,此微博已被作者删除。查看帮助:<a href='http://t.cn/Rfd3rQV' data-hide=''><span class='url-icon'><img style='width: 1rem;height: 1rem' src='//h5.sinaimg.cn/upload/2015/09/25/3/timeline_card_small_web_default.png'></span> <span class='surl-text'>网页链接</span></a>"
state: 7
deleted: '1'
weibo_position: 2
show_attitude_bar: 0
retweeted: 1
user: null
bid: 'I2vZiwWsP'
source: ''
}
/**
* 仅用于记录, 作为被隐藏微博的示例
*/
type TypePrivateWeiboRecordDemo = {
visible: { type: 0; list_id: 3; list_idstr: '3' }
created_at: '2010-06-18'
id: '20110061812539159'
idstr: '730379578'
mid: '20110061812539159'
text: '抱歉,作者已设置仅展示半年内微博,此微博已不可见。 '
retweeted: 1
user: null
bid: '1b1AKe'
source: ''
}
export type TypeWeiboListByDay = {
/**
* 微博列表
*/
weiboList: Array<TypeMblog>
/**
* 时间(当天0点0分)
*/
dayStartAt: number
/**
* 分类标记
*/
splitByStr: string
/**
* 文件名.
* 如果分卷模式为count, 则文件名为`${开始日期}-${结束日期}`
* 如果分卷模式为其他, 则文件名为`${记录所在日期}`
*/
title: string
/**
* 容器内微博开始时间
*/
postStartAt: number
/**
* 容器内微博结束时间
*/
postEndAt: number
}
export type TypeWeiboEpub = {
weiboDayList: Array<TypeWeiboListByDay>
// 作者信息. 便于生成封面等信息
userInfo: TypeWeiboUserInfo
// 作者名
screenName: string
startDayAt: number
endDayAt: number
// 本书是第几本
bookIndex: number
// 总共几本
totalBookCount: number
// 书中总共包含微博数
mblogInThisBookCount: number
// 收集到的总微博数
totalMblogCount: number
} | the_stack |
const PI = Math.PI
/**
* Modulate a value between two ranges.
* @param value
* @param rangeA from [low, high]
* @param rangeB to [low, high]
* @param clamp
*/
export function modulate(
value: number,
rangeA: number[],
rangeB: number[],
clamp = false
) {
const [fromLow, fromHigh] = rangeA
const [toLow, toHigh] = rangeB
const result =
toLow + ((value - fromLow) / (fromHigh - fromLow)) * (toHigh - toLow)
if (clamp === true) {
if (toLow < toHigh) {
if (result < toLow) {
return toLow
}
if (result > toHigh) {
return toHigh
}
} else {
if (result > toLow) {
return toLow
}
if (result < toHigh) {
return toHigh
}
}
}
return result
}
/**
* Rotate a point around a center.
* @param x The x-axis coordinate of the point.
* @param y The y-axis coordinate of the point.
* @param cx The x-axis coordinate of the point to rotate round.
* @param cy The y-axis coordinate of the point to rotate round.
* @param angle The distance (in radians) to rotate.
*/
export function rotatePoint(
x: number,
y: number,
cx: number,
cy: number,
angle: number
) {
const s = Math.sin(angle)
const c = Math.cos(angle)
const px = x - cx
const py = y - cy
const nx = px * c - py * s
const ny = px * s + py * c
return [nx + cx, ny + cy]
}
/**
* Get the distance between two points.
* @param x0 The x-axis coordinate of the first point.
* @param y0 The y-axis coordinate of the first point.
* @param x1 The x-axis coordinate of the second point.
* @param y1 The y-axis coordinate of the second point.
*/
export function getDistance(x0: number, y0: number, x1: number, y1: number) {
return Math.hypot(y1 - y0, x1 - x0)
}
/**
* Get an angle (radians) between two points.
* @param x0 The x-axis coordinate of the first point.
* @param y0 The y-axis coordinate of the first point.
* @param x1 The x-axis coordinate of the second point.
* @param y1 The y-axis coordinate of the second point.
*/
export function getAngle(x0: number, y0: number, x1: number, y1: number) {
return Math.atan2(y1 - y0, x1 - x0)
}
/**
* Move a point in an angle by a distance.
* @param x0
* @param y0
* @param a angle (radians)
* @param d distance
*/
export function projectPoint(x0: number, y0: number, a: number, d: number) {
return [Math.cos(a) * d + x0, Math.sin(a) * d + y0]
}
/**
* Get a point between two points.
* @param x0 The x-axis coordinate of the first point.
* @param y0 The y-axis coordinate of the first point.
* @param x1 The x-axis coordinate of the second point.
* @param y1 The y-axis coordinate of the second point.
* @param d Normalized
*/
export function getPointBetween(
x0: number,
y0: number,
x1: number,
y1: number,
d = 0.5
) {
return [x0 + (x1 - x0) * d, y0 + (y1 - y0) * d]
}
/**
* Get the sector of an angle (e.g. quadrant, octant)
* @param a The angle to check.
* @param s The number of sectors to check.
*/
export function getSector(a: number, s = 8) {
return Math.floor(s * (0.5 + ((a / (PI * 2)) % s)))
}
/**
* Get a normal value representing how close two points are from being at a 45 degree angle.
* @param x0 The x-axis coordinate of the first point.
* @param y0 The y-axis coordinate of the first point.
* @param x1 The x-axis coordinate of the second point.
* @param y1 The y-axis coordinate of the second point.
*/
export function getAngliness(x0: number, y0: number, x1: number, y1: number) {
return Math.abs((x1 - x0) / 2 / ((y1 - y0) / 2))
}
/**
* Get the points at which an ellipse intersects a rectangle.
* @param x
* @param y
* @param w
* @param h
* @param cx
* @param cy
* @param rx
* @param ry
* @param angle
*/
export function getEllipseRectangleIntersectionPoints(
x: number,
y: number,
w: number,
h: number,
cx: number,
cy: number,
rx: number,
ry: number,
angle: number
) {
let points: number[][] = []
for (let [px0, py0, px1, py1] of [
[x, y, x + w, y],
[x + w, y, x + w, y + h],
[x + w, y + h, x, y + h],
[x, y + h, x, y],
]) {
const ints = getEllipseSegmentIntersections(
px0,
py0,
px1,
py1,
cx,
cy,
rx,
ry,
angle
)
if (ints.length > 0) {
points.push(...ints)
}
}
points = points.sort(([x0, y0], [x1, y1]) => {
return Math.sin(getAngle(cx, cy, x0, y0) - getAngle(cx, cy, x1, y1)) > 0
? -1
: 1
})
return points
}
/**
* Find the point(s) where a line segment intersects an ellipse.
* @param x0 The x-axis coordinate of the line's start point.
* @param y0 The y-axis coordinate of the line's start point.
* @param x1 The x-axis coordinate of the line's end point.
* @param y1 The y-axis coordinate of the line's end point.
* @param cx The x-axis (horizontal) coordinate of the ellipse's center.
* @param cy The y-axis (vertical) coordinate of the ellipse's center.
* @param rx The ellipse's major-axis radius. Must be non-negative.
* @param ry The ellipse's minor-axis radius. Must be non-negative.
* @param rotation The rotation of the ellipse, expressed in radians.
* @param segment_only When true, will test the segment as a line (of infinite length).
*/
export function getEllipseSegmentIntersections(
x0: number,
y0: number,
x1: number,
y1: number,
cx: number,
cy: number,
rx: number,
ry: number,
rotation = 0,
segment_only = true
) {
// If the ellipse or line segment are empty, return no tValues.
if (rx === 0 || ry === 0 || (x0 === x1 && y0 === y1)) {
return []
}
// Get the semimajor and semiminor axes.
rx = rx < 0 ? rx : -rx
ry = ry < 0 ? ry : -ry
// Rotate points.
if (rotation !== 0) {
;[x0, y0] = rotatePoint(x0, y0, cx, cy, -rotation)
;[x1, y1] = rotatePoint(x1, y1, cx, cy, -rotation)
}
// Translate so the ellipse is centered at the origin.
x0 -= cx
y0 -= cy
x1 -= cx
y1 -= cy
// Calculate the quadratic parameters.
var A = ((x1 - x0) * (x1 - x0)) / rx / rx + ((y1 - y0) * (y1 - y0)) / ry / ry
var B = (2 * x0 * (x1 - x0)) / rx / rx + (2 * y0 * (y1 - y0)) / ry / ry
var C = (x0 * x0) / rx / rx + (y0 * y0) / ry / ry - 1
// Make a list of t values (normalized points on the line where intersections occur).
var tValues: number[] = []
// Calculate the discriminant.
var discriminant = B * B - 4 * A * C
if (discriminant === 0) {
// One real solution.
tValues.push(-B / 2 / A)
} else if (discriminant > 0) {
// Two real solutions.
tValues.push((-B + Math.sqrt(discriminant)) / 2 / A)
tValues.push((-B - Math.sqrt(discriminant)) / 2 / A)
}
return (
tValues
// Filter to only points that are on the segment.
.filter(t => !segment_only || (t >= 0 && t <= 1))
// Solve for points.
.map(t => [x0 + (x1 - x0) * t + cx, y0 + (y1 - y0) * t + cy])
// Counter-rotate points
.map(p =>
rotation === 0 ? p : rotatePoint(p[0], p[1], cx, cy, rotation)
)
)
}
/**
* Check whether two rectangles will collide (overlap).
* @param x0 The x-axis coordinate of the first rectangle.
* @param y0 The y-axis coordinate of the first rectangle.
* @param w0 The width of the first rectangle.
* @param h0 The height of the first rectangle.
* @param x1 The x-axis coordinate of the second rectangle.
* @param y1 The y-axis coordinate of the second rectangle.
* @param w1 The width of the second rectangle.
* @param h1 The height of the second rectangle.
*/
export function doRectanglesCollide(
x0: number,
y0: number,
w0: number,
h0: number,
x1: number,
y1: number,
w1: number,
h1: number
) {
return !(x0 >= x1 + w1 || x1 >= x0 + w0 || y0 >= y1 + h1 || y1 >= y0 + h0)
}
/**
* Find the point(s) where a segment intersects a rectangle.
* @param x0 The x-axis coordinate of the segment's starting point.
* @param y0 The y-axis coordinate of the segment's starting point.
* @param x1 The x-axis coordinate of the segment's ending point.
* @param y1 The y-axis coordinate of the segment's ending point.
* @param x The x-axis coordinate of the rectangle.
* @param y The y-axis coordinate of the rectangle.
* @param w The width of the rectangle.
* @param h The height of the rectangle.
*/
export function getSegmentRectangleIntersectionPoints(
x0: number,
y0: number,
x1: number,
y1: number,
x: number,
y: number,
w: number,
h: number
) {
let points: number[][] = []
for (let [px0, py0, px1, py1] of [
[x, y, x + w, y],
[x + w, y, x + w, y + h],
[x + w, y + h, x, y + h],
[x, y + h, x, y],
]) {
const ints = getSegmentSegmentIntersection(
px0,
py0,
px1,
py1,
x0,
y0,
x1,
y1
)
if (ints) {
points.push(ints)
}
}
return points
}
/**
* Find the point, if any, where two segments intersect.
* @param x0 The x-axis coordinate of the first segment's starting point.
* @param y0 The y-axis coordinate of the first segment's starting point.
* @param x1 The x-axis coordinate of the first segment's ending point.
* @param y1 The y-axis coordinate of the first segment's ending point.
* @param x2 The x-axis coordinate of the second segment's starting point.
* @param y2 The y-axis coordinate of the second segment's starting point.
* @param x3 The x-axis coordinate of the second segment's ending point.
* @param y3 The y-axis coordinate of the second segment's ending point.
*/
export function getSegmentSegmentIntersection(
x0: number,
y0: number,
x1: number,
y1: number,
x2: number,
y2: number,
x3: number,
y3: number
) {
const denom = (y3 - y2) * (x1 - x0) - (x3 - x2) * (y1 - y0)
const numeA = (x3 - x2) * (y0 - y2) - (y3 - y2) * (x0 - x2)
const numeB = (x1 - x0) * (y0 - y2) - (y1 - y0) * (x0 - x2)
if (denom === 0) {
if (numeA === 0 && numeB === 0) {
return undefined // Colinear
}
return undefined // Parallel
}
const uA = numeA / denom
const uB = numeB / denom
if (uA >= 0 && uA <= 1 && uB >= 0 && uB <= 1) {
return [x0 + uA * (x1 - x0), y0 + uA * (y1 - y0)]
}
return undefined // No intersection
}
/**
* Get the intersection points between a line segment and a rectangle with rounded corners.
* @param x0 The x-axis coordinate of the segment's starting point.
* @param y0 The y-axis coordinate of the segment's ending point.
* @param x1 The delta-x of the ray.
* @param y1 The delta-y of the ray.
* @param x The x-axis coordinate of the rectangle.
* @param y The y-axis coordinate of the rectangle.
* @param w The width of the rectangle.
* @param h The height of the rectangle.
* @param r The corner radius of the rectangle.
*/
export function getSegmentRoundedRectangleIntersectionPoints(
x0: number,
y0: number,
x1: number,
y1: number,
x: number,
y: number,
w: number,
h: number,
r: number
) {
const mx = x + w,
my = y + h,
rx = x + r,
ry = y + r,
mrx = x + w - r,
mry = y + h - r
const segments = [
[x, mry, x, ry, x, y],
[rx, y, mrx, y, mx, y],
[mx, ry, mx, mry, mx, my],
[mrx, my, rx, my, x, my],
]
const corners = [
[rx, ry, PI, PI * 1.5],
[mrx, ry, PI * 1.5, PI * 2],
[mrx, mry, 0, PI * 0.5],
[rx, mry, PI * 0.5, PI],
]
let points: number[][] = []
segments.forEach((segment, i) => {
const [px0, py0, px1, py1] = segment
const [cx, cy, as, ae] = corners[i]
getSegmentCircleIntersections(cx, cy, r, x0, y0, x1, y1)
.filter(pt => {
const pointAngle = normalizeAngle(getAngle(cx, cy, pt[0], pt[1]))
return pointAngle > as && pointAngle < ae
})
.forEach(pt => points.push(pt))
const segmentInt = getSegmentSegmentIntersection(
x0,
y0,
x1,
y1,
px0,
py0,
px1,
py1
)
if (!!segmentInt) {
points.push(segmentInt)
}
})
return points
}
/**
* Get the point(s) where a line segment intersects a circle.
* @param cx The x-axis coordinate of the circle's center.
* @param cy The y-axis coordinate of the circle's center.
* @param r The circle's radius.
* @param x0 The x-axis coordinate of the segment's starting point.
* @param y0 The y-axis coordinate of ththe segment's ending point.
* @param x1 The delta-x of the ray.
* @param y1 The delta-y of the ray.
*/
export function getSegmentCircleIntersections(
cx: number,
cy: number,
r: number,
x0: number,
y0: number,
x1: number,
y1: number
) {
var b: number,
c: number,
d: number,
u1: number,
u2: number,
ret: number[][],
retP1: number[],
retP2: number[],
v1 = [x1 - x0, y1 - y0],
v2 = [x0 - cx, y0 - cy]
b = v1[0] * v2[0] + v1[1] * v2[1]
c = 2 * (v1[0] * v1[0] + v1[1] * v1[1])
b *= -2
d = Math.sqrt(b * b - 2 * c * (v2[0] * v2[0] + v2[1] * v2[1] - r * r))
if (isNaN(d)) {
// no intercept
return []
}
u1 = (b - d) / c // these represent the unit distance of point one and two on the line
u2 = (b + d) / c
retP1 = [] // return points
retP2 = []
ret = [] // return array
if (u1 <= 1 && u1 >= 0) {
// add point if on the line segment
retP1[0] = x0 + v1[0] * u1
retP1[1] = y0 + v1[1] * u1
ret[0] = retP1
}
if (u2 <= 1 && u2 >= 0) {
// second add point if on the line segment
retP2[0] = x0 + v1[0] * u2
retP2[1] = y0 + v1[1] * u2
ret[ret.length] = retP2
}
return ret
}
/**
* Normalize an angle (in radians)
* @param radians The radians quantity to normalize.
*/
export function normalizeAngle(radians: number) {
return radians - PI * 2 * Math.floor(radians / (PI * 2))
}
/**
*
* @param x The x-axis coordinate of the ray's origin.
* @param y The y-axis coordinate of the ray's origin.
* @param w
* @param h
* @param x0
* @param y0
* @param x1
* @param y1
*/
export function getRayRectangleIntersectionPoints(
ox: number,
oy: number,
dx: number,
dy: number,
x: number,
y: number,
w: number,
h: number
) {
let points: number[][] = []
for (let [px0, py0, px1, py1] of [
[x, y, x + w, y],
[x + w, y, x + w, y + h],
[x + w, y + h, x, y + h],
[x, y + h, x, y],
]) {
const ints = getRaySegmentIntersection(ox, oy, dx, dy, px0, py0, px1, py1)
if (ints) {
points.push(ints)
}
}
return points
}
/**
* Get the point at which a ray intersects a segment.
* @param x The x-axis coordinate of the ray's origin.
* @param y The y-axis coordinate of the ray's origin.
* @param dx The x-axis delta of the angle.
* @param dy The y-axis delta of the angle.
* @param x0 The x-axis coordinate of the segment's start point.
* @param y0 The y-axis coordinate of the segment's start point.
* @param x1 The x-axis coordinate of the segment's end point.
* @param y1 The y-axis coordinate of the segment's end point.
*/
export function getRaySegmentIntersection(
x: number,
y: number,
dx: number,
dy: number,
x0: number,
y0: number,
x1: number,
y1: number
) {
let r: number, s: number, d: number
if (dy * (x1 - x0) !== dx * (y1 - y0)) {
d = dx * (y1 - y0) - dy * (x1 - x0)
if (d !== 0) {
r = ((y - y0) * (x1 - x0) - (x - x0) * (y1 - y0)) / d
s = ((y - y0) * dx - (x - x0) * dy) / d
if (r >= 0 && s >= 0 && s <= 1) {
return [x + r * dx, y + r * dy]
}
}
}
return undefined
}
/**
* Get the normalized delta (x and y) for an angle.
* @param angle The angle in radians
*/
export function getDelta(angle: number) {
return [Math.cos(angle), Math.sin(angle)]
}
export function getIntermediate(angle: number) {
return Math.abs(Math.abs(angle % (PI / 2)) - PI / 4) / (PI / 4)
}
/**
* Get a line between two rounded rectangles.
* @param x0
* @param y0
* @param w0
* @param h0
* @param r0
* @param x1
* @param y1
* @param w1
* @param h1
* @param r1
*/
export function getLineBetweenRoundedRectangles(
x0: number,
y0: number,
w0: number,
h0: number,
r0: number,
x1: number,
y1: number,
w1: number,
h1: number,
r1: number
) {
const cx0 = x0 + w0 / 2,
cy0 = y0 + h0 / 2,
cx1 = x1 + w1 / 2,
cy1 = y1 + h1 / 2,
[[di0x, di0y]] = getRayRoundedRectangleIntersection(
cx0,
cy0,
cx1 - cx0,
cy1 - cy0,
x0,
y0,
w0,
h0,
r0
) || [[cx0, cy0]],
[[di1x, di1y]] = getRayRoundedRectangleIntersection(
cx1,
cy1,
cx0 - cx1,
cy0 - cy1,
x1,
y1,
w1,
h1,
r1
) || [[cx1, cy1]]
return [di0x, di0y, di1x, di1y]
}
/**
* Get the intersection points between a ray and a rectangle with rounded corners.
* @param ox The x-axis coordinate of the ray's origin.
* @param oy The y-axis coordinate of the ray's origin.
* @param dx The delta-x of the ray.
* @param dy The delta-y of the ray.
* @param x The x-axis coordinate of the rectangle.
* @param y The y-axis coordinate of the rectangle.
* @param w The width of the rectangle.
* @param h The height of the rectangle.
* @param r The corner radius of the rectangle.
*/
export function getRayRoundedRectangleIntersection(
ox: number,
oy: number,
dx: number,
dy: number,
x: number,
y: number,
w: number,
h: number,
r: number
) {
const mx = x + w,
my = y + h,
rx = x + r - 1,
ry = y + r - 1,
mrx = x + w - r + 1,
mry = y + h - r + 1
const segments = [
[x, mry, x, ry],
[rx, y, mrx, y],
[mx, ry, mx, mry],
[mrx, my, rx, my],
]
const corners = [
[rx, ry, Math.PI, Math.PI * 1.5],
[mrx, ry, Math.PI * 1.5, Math.PI * 2],
[mrx, mry, 0, Math.PI * 0.5],
[rx, mry, Math.PI * 0.5, Math.PI],
]
let points: number[][] = []
segments.forEach((segment, i) => {
const [px0, py0, px1, py1] = segment
const [cx, cy, as, ae] = corners[i]
const intersections = getRayCircleIntersection(cx, cy, r, ox, oy, dx, dy)
intersections &&
intersections
.filter(pt => {
const pointAngle = normalizeAngle(getAngle(cx, cy, pt[0], pt[1]))
return pointAngle > as && pointAngle < ae
})
.forEach(pt => points.push(pt))
const segmentInt = getRaySegmentIntersection(
ox,
oy,
dx,
dy,
px0,
py0,
px1,
py1
)
if (!!segmentInt) {
points.push(segmentInt)
}
})
return points
}
export function getRectangleSegmentIntersectedByRay(
x: number,
y: number,
w: number,
h: number,
ox: number,
oy: number,
dx: number,
dy: number
) {
return getRectangleSegments(x, y, w, h).find(([sx0, sy0, sx1, sy1]) =>
getRaySegmentIntersection(ox, oy, dx, dy, sx0, sy0, sx1, sy1)
)
}
export function getRectangleSegments(
x: number,
y: number,
w: number,
h: number
) {
return [
[x, y, x + w, y],
[x + w, y, x + w, y + h],
[x + w, y + h, x, y + h],
[x, y + h, x, y],
]
}
export function getRoundedRectangleSegments(
x: number,
y: number,
w: number,
h: number,
r: number
) {
const rx = x + r,
ry = y + r,
mx = x + w,
my = y + h,
mrx = x + w - r,
mry = y + h - r
return [
[x, mry, x, ry, x, y],
[rx, y, mrx, y, mx, y],
[mx, ry, mx, mry, mx, my],
[mrx, my, rx, my, x, my],
]
}
export function getRayCircleIntersection(
cx: number,
cy: number,
r: number,
ox: number,
oy: number,
dx: number,
dy: number
) {
// This is a shitty hack
return getSegmentCircleIntersections(
cx,
cy,
r,
ox,
oy,
dx * 999999,
dy * 999999
)
} | the_stack |
// ===============================================================
//
// ===============================================================
var domTimelineOptions: any;
interface ExtendedMutationRecord extends MutationRecord {
claim: string
stack: string
timestamp: number
newValue: string
}
var domHistory: {
past: Array<ExtendedMutationRecord>
future: Array<ExtendedMutationRecord>
lostFuture: Array<ExtendedMutationRecord>
undo:()=>boolean
redo:()=>boolean
startRecording:()=>boolean
stopRecording:()=>boolean
isRecording:boolean
isRecordingStopped:boolean
generateDashboardData:(knownData:{history:number,lostFuture:number,domData:number})=>any
};
// ===============================================================
//
// ===============================================================
module VORLON {
export class DOMTimelineClient extends ClientPlugin {
constructor() {
super("domtimeline"); // Name
(<any>this)._ready = true; // No need to wait
//console.log('Started');
}
//Return unique id for your plugin
public getID(): string {
return "DOMTIMELINE";
}
public refresh(): void {
//override this method with cleanup work that needs to happen
//as the user switches between clients on the dashboard
//we don't really need to do anything in this sample
}
// This code will run on the client //////////////////////
// Start the clientside code
public startClientSide(): void {
var domData : NodeMappingSystem = null;
//window.addEventListener('DOMContentLoaded', x => console.warn('DOMContentLoaded'));
//window.addEventListener('load', x => console.warn('load'));
domTimelineOptions.onRecordingStart = function() {
domData = MappingSystem.NodeMappingSystem.initFromDocument();
window["domData"] = domData;
}
domTimelineOptions.considerLoggingRecords = function(c,entries,s) {
if(!domData) return console.warn("domData not yet initalized; entries ignored: ", entries);
for(var i = entries.length; i--;) {
var e = entries[i];
// TODO: we should undo then redo all changes
ensureDomDataIsUpToDate(e);
e.__dashboardData = generateDashboardDataForEntry(e);
}
function ensureDomDataIsUpToDate(e: ExtendedMutationRecord) {
if(e.addedNodes && e.addedNodes.length) {
for(var i = 0; i < e.addedNodes.length; i++) {
var addedNode = e.addedNodes[i];
domData.addNodeAndChildren(addedNode);
}
}
}
}
domHistory.generateDashboardData = function(knownData:{history:number,lostFuture:number,domData:number}) {
var data:any = {};
// basic data
data.url = location.href;
data.title = document.title;
data.isRecordingNow = domHistory.isRecording;
data.isRecordingEnded = domHistory.isRecordingStopped;
data.isPageFrozen = domHistory.future.length>0;
data.pastEventsCount = domHistory.past.length;
data.futureEventsCount = domHistory.future.length;
data.assumedKnownData = knownData;
// history
data.history = (
[]
.concat(domHistory.past.map(getDashboardDataForEntry))
.concat(domHistory.future.map(getDashboardDataForEntry))
);
data.history.splice(0,knownData.history|0);
// lostFuture
data.lostFuture = (
domHistory.lostFuture.map(getDashboardDataForEntry)
);
data.lostFuture.splice(0,knownData.lostFuture|0);
// domData
data.domData = domData ? domData.data.slice(knownData.domData|0) : [];
return data;
}
if(!!sessionStorage['domTimelineOptions_startRecordingImmediately']) {
sessionStorage['domTimelineOptions_startRecordingImmediately'] = false;
domHistory.startRecording();
}
function getDashboardDataForEntry(e) {
return e.__dashboardData;
}
function generateDashboardDataForEntry(e:ExtendedMutationRecord):ClientDataForEntry {
var targetDescription = descriptionOf(e.target);
if(e.addedNodes.length > 0) {
var nodeDescription = (
(e.addedNodes.length == 1)
? (descriptionOf(e.addedNodes[0]))
: e.addedNodes.length + " nodes"
);
return {
type:"added",
description: "Inserted " + nodeDescription + " into " + targetDescription,
timestamp: e.timestamp,
details: {
"Added nodes": descriptionOfNodeList(e.addedNodes),
"Target": targetDescription,
"Timestamp": Math.round(10*e.timestamp)/10000+"s",
"Claim": e.claim,
"Stack": "`"+e.stack.split('\n').filter(l => l.indexOf("vorlon.max")==-1).join('\n')+"`"
},
rawData: {
type: "childList",
addedNodes: domData.getPointerListFor(e.addedNodes),
nextSibling: domData.getPointerFor(e.nextSibling),
target: domData.getPointerFor(e.target),
}
}
} else if(e.removedNodes.length > 0) {
var nodeDescription = (
(e.removedNodes.length == 1)
? (descriptionOf(e.removedNodes[0]))
: e.removedNodes.length + " nodes"
);
return {
type:"removed",
description: "Removed " + nodeDescription + " from " + targetDescription,
timestamp: e.timestamp,
details: {
"Removed nodes": descriptionOfNodeList(e.addedNodes),
"Target": targetDescription,
"Timestamp": Math.round(10*e.timestamp)/10000+"s",
"Claim": e.claim,
"Stack": "`"+e.stack.split('\n').filter(l => l.indexOf("vorlon.max")==-1).join('\n')+"`"
},
rawData: {
type: "childList",
removedNodes: domData.getPointerListFor(e.removedNodes),
nextSibling: domData.getPointerFor(e.nextSibling),
target: domData.getPointerFor(e.target),
}
}
} else if(e.attributeName) {
if(e.newValue === null || e.newValue === undefined) {
return {
type:"modified",
description: "Removed attribute `"+e.attributeName+"` from " + targetDescription,
timestamp: e.timestamp,
details: {
"Attribute name": e.attributeName,
"Old value": e.oldValue,
"New value": e.newValue,
"Target": targetDescription,
"Timestamp": Math.round(10*e.timestamp)/10000+"s",
"Claim": e.claim,
"Stack": "`"+e.stack.split('\n').filter(l => l.indexOf("vorlon.max")==-1).join('\n')+"`"
},
rawData: {
type: "attributes",
attributeName: e.attributeName,
oldValue: e.oldValue,
newValue: e.newValue,
target: domData.getPointerFor(e.target)
}
}
} else if(e.oldValue === null || e.oldValue === undefined) {
return {
type:"modified",
description: "Added attribute `"+e.attributeName+"` to " + targetDescription,
timestamp: e.timestamp,
details: {
"Attribute name": e.attributeName,
"Old value": e.oldValue,
"New value": e.newValue,
"Target": targetDescription,
"Timestamp": Math.round(10*e.timestamp)/10000+"s",
"Claim": e.claim,
"Stack": "`"+e.stack.split('\n').filter(l => l.indexOf("vorlon.max")==-1).join('\n')+"`"
},
rawData: {
type: "attributes",
attributeName: e.attributeName,
oldValue: e.oldValue,
newValue: e.newValue,
target: domData.getPointerFor(e.target)
}
}
} else {
return {
type:"modified",
description: "Updated attribute `"+e.attributeName+"` of " + targetDescription,
timestamp: e.timestamp,
details: {
"Attribute name": e.attributeName,
"Old value": e.oldValue,
"New value": e.newValue,
"Target": targetDescription,
"Timestamp": Math.round(10*e.timestamp)/10000+"s",
"Claim": e.claim,
"Stack": "`"+e.stack.split('\n').filter(l => l.indexOf("vorlon.max")==-1).join('\n')+"`"
},
rawData: {
type: "attributes",
attributeName: e.attributeName,
oldValue: e.oldValue,
newValue: e.newValue,
target: domData.getPointerFor(e.target)
}
}
}
} else {
var nodeDescription = descriptionOf(e.target.parentNode)
return {
type:"modified",
description: "Updated text content of " + nodeDescription,
timestamp: e.timestamp,
details: {
"Old value": e.oldValue,
"New value": e.newValue,
"Timestamp": Math.round(10*e.timestamp)/10000+"s",
"Claim": e.claim,
"Stack": "`"+e.stack.split('\n').filter(l => l.indexOf("vorlon.max")==-1).join('\n')+"`"
},
rawData: {
type: "characterData",
oldValue: e.oldValue,
newValue: e.newValue,
target: domData.getPointerFor(e.target)
}
}
}
}
function descriptionOf(e:Node) {
if(e instanceof HTMLElement) {
if(e.firstChild) {
e = e.cloneNode(false);
e.appendChild(document.createTextNode("…"));
return "`"+(<any>e).outerHTML+"`"
} else {
return "`"+(<any>e).outerHTML+"`"
}
}
if(e instanceof SVGElement) { return "`<"+e.tagName+"…>`" }
if(e.nodeName[0] != "#") { return "`attribute "+e.nodeName+"`" }
if(e.nodeValue.length < 15) { return "`"+e.nodeValue+"`" }
return "`"+e.nodeValue.substr(0,15)+"…`"
}
function descriptionOfNodeList(elements:NodeList) {
if(elements.length == 0) { return "`empty node list`" }
if(elements.length == 1) { return "`1 node: "+descriptionOf(elements[0]).replace(/^`|`$/g,'')+"`"}
var desc = "`"+elements.length + " nodes:";
for(var i = 0; i < elements.length; i++) {
desc += '\n'+descriptionOf(elements[i]).replace(/^`|`$/g,'');
}
return desc+"`";
}
}
// Handle messages from the dashboard, on the client
public onRealtimeMessageReceivedFromDashboardSide(receivedObject: any): void {
var result; try {
result = window.eval(receivedObject.message);
} catch (ex) {
result = ex.stack;
}
this.sendToDashboard({ message: result, messageId: receivedObject.messageId });
}
}
//Register the plugin with vorlon core
Core.RegisterClientPlugin(new DOMTimelineClient());
} | the_stack |
import { Lang } from '../../resources/languages';
import logDefinitions from '../../resources/netlog_defs';
import { DeathReportData, OopsyMistake } from '../../types/oopsy';
import {
kAttackFlags,
kHealFlags,
kShiftFlagValues,
Translate,
UnscrambleDamage,
} from './oopsy_common';
import {
TrackedDeathReasonEvent,
TrackedEvent,
TrackedEventType,
TrackedLineEvent,
TrackedMistakeEvent,
} from './player_state_tracker';
// TODO: lots of things left to do with death reports
// * probably include max hp as well?
// * consolidate HoT/DoT (with expandable CSS)
// * show mitigation effects that are active during damage (with icons?? or at least text to start?)
// * also need to track effects that are active prior to the set of events passed in
// * also need to handle effects lost (and gained?!) after death
// * consolidate multiple damage that killed (e.g. Solemn Confiteor x4) into summary text
// * maybe if a player is fully healed, trim abilities before that?
const processAbilityLine = (splitLine: string[]) => {
const flagIdx = logDefinitions.Ability.fields.flags;
let flags = splitLine[flagIdx] ?? '';
let damage = splitLine[flagIdx + 1] ?? '';
if (kShiftFlagValues.includes(flags)) {
flags = splitLine[flagIdx + 2] ?? flags;
damage = splitLine[flagIdx + 3] ?? damage;
}
const amount = UnscrambleDamage(damage);
const lowByte = `00${flags}`.substr(-2);
return {
amount: amount,
lowByte: lowByte,
flags: flags,
isHeal: kHealFlags.includes(lowByte),
isAttack: kAttackFlags.includes(lowByte),
};
};
export type ParsedDeathReportLine = {
timestamp: number;
timestampStr: string;
type: TrackedEventType;
currentHp?: number;
amount?: number;
amountStr?: string;
amountClass?: string;
icon?: string;
text?: string;
};
// Contains all the information to display information about a player's death.
// `events` contain the last N seconds of tracked line events that pertain to the player.
// This class's job is to sort through those raw lines and generate a subset of parsed
// lines that various views might want to display in some fashion.
export class DeathReport {
private lang: Lang;
private baseTimestamp: number | undefined;
public deathTimestamp: number;
public targetId: string;
public targetName: string;
private events: TrackedEvent[];
private parsedReportLines?: ParsedDeathReportLine[];
constructor(data: DeathReportData) {
this.lang = data.lang;
this.baseTimestamp = data.baseTimestamp;
this.deathTimestamp = data.deathTimestamp;
this.targetId = data.targetId;
this.targetName = data.targetName;
this.events = data.events;
}
// Generates an OopsyMistake that represents this DeathReport.
public static generateMistake(data: DeathReportData): OopsyMistake {
// Walk backward through events until we find the last damage or a death reason.
for (let i = data.events.length - 1; i >= 0; i--) {
const event = data.events[i];
if (!event)
break;
if (event.type === 'DeathReason') {
return {
type: 'death',
name: data.targetName,
text: event.text,
report: data,
};
}
// TODO: consider combining multiple abilities that are taken in a very
// short period of time, e.g. "A + B" or "C x4".
if (event.type === 'Ability') {
const ability = processAbilityLine(event.splitLine);
if (ability.isAttack && ability.amount > 0) {
const abilityName = event.splitLine[logDefinitions.Ability.fields.ability] ?? '???';
const currentHp = event.splitLine[logDefinitions.Ability.fields.targetCurrentHp] ?? '???';
const text = `${abilityName} (${ability.amount}/${currentHp})`;
return {
type: 'death',
name: data.targetName,
text: text,
report: data,
};
}
}
}
return {
type: 'death',
name: data.targetName,
text: '???',
report: data,
};
}
// A helper function to turn a timestamp into a string relative to this DeathReport.
// The base timestamp it is relative to is generally the start of the fight.
makeRelativeTimeString(timestamp: number): string {
const base = this.baseTimestamp;
if (!base)
return '';
const deltaMs = timestamp - base;
const prefix = deltaMs < 0 ? '-' : '';
const deltaTotalSeconds = Math.round(Math.abs(deltaMs) / 1000);
const deltaSeconds = `00${deltaTotalSeconds % 60}`.substr(-2);
const deltaMinutes = Math.floor(deltaTotalSeconds / 60);
return `${prefix}${deltaMinutes}:${deltaSeconds}`;
}
// Lazily do some work to process the tracked lines from `this.events` into something that
// can be displayed to the user. This is the model for the live/summary views.
public parseReportLines(): ParsedDeathReportLine[] {
if (this.parsedReportLines)
return this.parsedReportLines;
this.parsedReportLines = [];
let lastCertainHp: number | undefined = undefined;
let currentHp: number | undefined = undefined;
let deathReasonIdx: number | undefined = undefined;
for (const event of this.events) {
let parsed: ParsedDeathReportLine | undefined = undefined;
if (event.type === 'Ability')
parsed = this.processAbility(event);
else if (event.type === 'HoTDoT')
parsed = this.processHoTDoT(event);
else if (event.type === 'MissedAbility' || event.type === 'MissedEffect')
parsed = this.processMissedBuff(event);
else if (event.type === 'Mistake')
parsed = this.processMistake(event);
else if (event.type === 'DeathReason')
parsed = this.processDeathReason(event);
// After this point, we will always append this event,
// but still have some post-processing to do.
if (!parsed)
continue;
if (
event.type === 'Ability' &&
parsed.amount !== undefined &&
parsed.amount < 0 &&
deathReasonIdx !== undefined
) {
// Found damage after a DeathReason, remove previous DeathReason.
this.parsedReportLines.splice(deathReasonIdx);
deathReasonIdx = undefined;
} else if (event.type === 'DeathReason') {
// Found a new DeathReason, track this index in case it needs to be removed.
deathReasonIdx = this.parsedReportLines.length;
}
// Touch up the hp so it looks more valid. There are only hp fields on certain
// log lines, and more importantly it is polled from memory. Therefore, if a
// player takes a bunch of attacks simultaneously, the hp will be the same on
// every line. This looks incorrect, so do our best to fix this up.
if (currentHp === undefined || lastCertainHp === undefined) {
// If we haven't seen any log lines with hp yet, try to set it as an initial guess.
currentHp = parsed.currentHp;
lastCertainHp = parsed.currentHp;
} else if (parsed.currentHp !== lastCertainHp) {
// If we see a new hp value, then this is likely valid.
currentHp = lastCertainHp = parsed.currentHp;
} else {
// For log lines that don't have a hitpoints line, fill in our best guess.
// Or, we're seeing an identical hp value, so use previously adjusted amount.
parsed.currentHp = currentHp;
}
// Note: parsed.amount < 0 is damage, parsed.amount > 0 is heals.
if (currentHp !== undefined && parsed.amount !== undefined) {
// If this attack killed somebody (or this is overkill), set an icon unless there's
// already a mistake icon set. Don't do this for belated heals because it looks weird.
if (parsed.amount < 0 && currentHp + parsed.amount <= 0)
parsed.icon ??= 'death';
// TODO: maybe use max hp here to clamp this?
currentHp += parsed.amount;
}
this.parsedReportLines.push(parsed);
}
return this.parsedReportLines;
}
processGainsEffect(event: TrackedLineEvent): ParsedDeathReportLine {
// TODO: we also need to filter effects that we don't care about, e.g. swiftcast?
const effectName = event.splitLine[logDefinitions.GainsEffect.fields.effect] ?? '???';
const text = Translate(this.lang, {
en: `Gain: ${effectName}`,
de: `Erhalten: ${effectName}`,
ja: `獲得: ${effectName}`,
cn: `获得: ${effectName}`,
ko: `얻음: ${effectName}`,
});
return {
timestamp: event.timestamp,
timestampStr: this.makeRelativeTimeString(event.timestamp),
type: event.type,
text: text,
};
}
processLosesEffect(event: TrackedLineEvent): ParsedDeathReportLine {
// TODO: we also need to filter effects that we don't care about, e.g. swiftcast?
const effectName = event.splitLine[logDefinitions.LosesEffect.fields.effect] ?? '???';
const text = Translate(this.lang, {
en: `Lose: ${effectName}`,
de: `Verloren: ${effectName}`,
ja: `失う: ${effectName}`,
cn: `失去: ${effectName}`,
ko: `잃음: ${effectName}`,
});
return {
timestamp: event.timestamp,
timestampStr: this.makeRelativeTimeString(event.timestamp),
type: event.type,
text: text,
};
}
private processAbility(event: TrackedLineEvent): ParsedDeathReportLine | undefined {
const splitLine = event.splitLine;
const ability = processAbilityLine(splitLine);
// Zero damage abilities can be noisy and don't contribute much information, so skip.
if (ability.amount === 0)
return;
let amount;
let amountClass: string | undefined;
let amountStr: string | undefined;
if (ability.isHeal) {
amountClass = 'heal';
amountStr = ability.amount > 0 ? `+${ability.amount.toString()}` : ability.amount.toString();
amount = ability.amount;
} else if (ability.isAttack) {
amountClass = 'damage';
amountStr = ability.amount > 0 ? `-${ability.amount.toString()}` : ability.amount.toString();
amount = -1 * ability.amount;
}
// Ignore abilities that are not damage or heals. Any important abilities should generate an
// effect.
if (amountClass === undefined || amountStr === undefined)
return;
const abilityName = splitLine[logDefinitions.Ability.fields.ability] ?? '???';
const currentHpStr = splitLine[logDefinitions.Ability.fields.targetCurrentHp];
const currentHp = currentHpStr !== undefined ? parseInt(currentHpStr) : 0;
return {
timestamp: event.timestamp,
timestampStr: this.makeRelativeTimeString(event.timestamp),
type: event.type,
currentHp: currentHp,
amount: amount,
amountStr: amountStr,
amountClass: amountClass,
icon: event.mistake,
text: event.mistakeText ?? abilityName,
};
}
private processHoTDoT(event: TrackedLineEvent): ParsedDeathReportLine | undefined {
const which = event.splitLine[logDefinitions.NetworkDoT.fields.which];
const isHeal = which === 'HoT';
// Note: this amount is just raw bytes, and not the UnscrambleDamage version.
let amount = parseInt(event.splitLine[logDefinitions.NetworkDoT.fields.damage] ?? '', 16);
if (amount <= 0)
return;
let amountClass: string;
let amountStr: string;
if (isHeal) {
amountClass = 'heal';
amountStr = amount > 0 ? `+${amount.toString()}` : amount.toString();
} else {
amountClass = 'damage';
amountStr = amount > 0 ? `-${amount.toString()}` : amount.toString();
amount *= -1;
}
const currentHpStr = event.splitLine[logDefinitions.NetworkDoT.fields.currentHp];
const currentHp = currentHpStr !== undefined ? parseInt(currentHpStr) : 0;
// TODO: this line has an effect id, but we don't have an id -> string mapping for all ids.
// We could consider looking this up in effects to try to find a name, but common ones
// like Regen or Asylum aren't mapped there.
return {
timestamp: event.timestamp,
timestampStr: this.makeRelativeTimeString(event.timestamp),
type: event.type,
currentHp: currentHp,
amount: amount,
amountStr: amountStr,
amountClass: amountClass,
text: which,
};
}
private processMissedBuff(event: TrackedLineEvent): ParsedDeathReportLine | undefined {
let buffName: string | undefined;
let sourceName: string | undefined;
if (event.type === 'MissedAbility') {
buffName = event.splitLine[logDefinitions.Ability.fields.ability];
sourceName = event.splitLine[logDefinitions.Ability.fields.source];
} else if (event.type === 'MissedEffect') {
buffName = event.splitLine[logDefinitions.GainsEffect.fields.effect];
sourceName = event.splitLine[logDefinitions.GainsEffect.fields.source];
}
if (!buffName || !sourceName)
return;
const text = Translate(this.lang, {
en: `Missed ${buffName} (${sourceName})`,
de: `${buffName} verfehlte (${sourceName})`,
ja: `${buffName}をミスした (${sourceName}から)`,
cn: `没吃到 ${buffName} (来自${sourceName})`,
ko: `${buffName} 놓침 (${sourceName})`,
});
return {
timestamp: event.timestamp,
timestampStr: this.makeRelativeTimeString(event.timestamp),
type: event.type,
icon: 'heal',
text: Translate(this.lang, text),
};
}
private processMistake(event: TrackedMistakeEvent): ParsedDeathReportLine | undefined {
const mistake = event.mistakeEvent;
const triggerType = mistake.triggerType;
// Buffs are handled separately, and Damage types are annotated directly on the lines
// where there is damage, rather than having a separate line. Solo/Share mistakes
// are merged with their ability via `mistakeText`.
if (
triggerType === 'Buff' ||
triggerType === 'Damage' ||
triggerType === 'Solo' ||
triggerType === 'Share'
)
return;
const text = Translate(this.lang, mistake.text);
return {
timestamp: event.timestamp,
timestampStr: this.makeRelativeTimeString(event.timestamp),
type: event.type,
icon: mistake.type,
text: text,
};
}
private processDeathReason(event: TrackedDeathReasonEvent): ParsedDeathReportLine | undefined {
return {
timestamp: event.timestamp,
timestampStr: this.makeRelativeTimeString(event.timestamp),
type: event.type,
icon: 'death',
text: event.text,
};
}
} | the_stack |
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zza {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zza>;
public asBinder(): globalAndroid.os.IBinder;
public constructor(param0: string);
public onTransact(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean;
public dispatchTransaction(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzb {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzb>;
public constructor(param0: globalAndroid.os.IBinder, param1: string);
public asBinder(): globalAndroid.os.IBinder;
public obtainAndWriteInterfaceToken(): globalAndroid.os.Parcel;
public transactAndReadException(param0: number, param1: globalAndroid.os.Parcel): globalAndroid.os.Parcel;
public transactAndReadExceptionReturnVoid(param0: number, param1: globalAndroid.os.Parcel): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzc {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzc>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzc interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzd>;
public static writeBoolean(param0: globalAndroid.os.Parcel, param1: boolean): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zze {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zze>;
public constructor();
public constructor(param0: globalAndroid.os.Looper, param1: globalAndroid.os.Handler.Callback);
public dispatchMessage(param0: globalAndroid.os.Message): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzf {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzf>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzf interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzgi extends com.google.android.gms.internal.firebase_ml.zzgp {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzgi>;
public getLength(): number;
public constructor(param0: string);
public writeTo(param0: java.io.OutputStream): void;
public getType(): string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzgk extends com.google.android.gms.internal.firebase_ml.zzgo {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzgk>;
public constructor();
public getName(): string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzgl extends com.google.android.gms.internal.firebase_ml.zzgp {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzgl>;
public constructor();
public getLength(): number;
public writeTo(param0: java.io.OutputStream): void;
public getType(): string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzgm extends com.google.android.gms.internal.firebase_ml.zziy {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzgm>;
public constructor();
public hashCode(): number;
public constructor(param0: string);
public constructor(param0: any /* java.util.EnumSet<com.google.android.gms.internal.firebase_ml.zziy.zzc>*/);
public constructor(param0: java.net.URL);
public toString(): string;
public equals(param0: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzgn {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzgn>;
public close(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzgo {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzgo>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzgo interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getName(): string;
zza(param0: any /* com.google.android.gms.internal.firebase_ml.zzjm*/, param1: java.io.OutputStream): void;
});
public constructor();
public getName(): string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzgp extends com.google.android.gms.internal.firebase_ml.zzjm {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzgp>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzgp interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getLength(): number;
getType(): string;
zzfp(): boolean;
writeTo(param0: java.io.OutputStream): void;
});
public constructor();
public getLength(): number;
public writeTo(param0: java.io.OutputStream): void;
public getType(): string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzgq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzgq>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzgq interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zzb(param0: any /* com.google.android.gms.internal.firebase_ml.zzgu*/): void;
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzgr extends com.google.android.gms.internal.firebase_ml.zzjm {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzgr>;
public writeTo(param0: java.io.OutputStream): void;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzjm*/, param1: any /* com.google.android.gms.internal.firebase_ml.zzgo*/);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzgs {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzgs>;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzgt*/, param1: java.lang.StringBuilder);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzgt extends com.google.android.gms.internal.firebase_ml.zziy {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzgt>;
public constructor();
public getUserAgent(): string;
public constructor(param0: any /* java.util.EnumSet<com.google.android.gms.internal.firebase_ml.zziy.zzc>*/);
public getContentType(): string;
public getLocation(): string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzgu {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzgu>;
public getRequestMethod(): string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzgv {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzgv>;
public hashCode(): number;
public constructor(param0: string);
public toString(): string;
public equals(param0: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzgw {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzgw>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzgw interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zza(param0: any /* com.google.android.gms.internal.firebase_ml.zzgu*/): void;
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzgx {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzgx>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzgy {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzgy>;
public getStatusCode(): number;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzgz*/);
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzhb*/);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzgz {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzgz>;
public getStatusCode(): number;
public getStatusMessage(): string;
public getContent(): java.io.InputStream;
public disconnect(): void;
public getContentType(): string;
public ignore(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzha {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzha>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzha interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zza(param0: any /* com.google.android.gms.internal.firebase_ml.zzgz*/): void;
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzhb {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzhb>;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzgz*/);
public constructor(param0: number, param1: string, param2: any /* com.google.android.gms.internal.firebase_ml.zzgt*/);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzhc {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzhc>;
public constructor();
public setContentLength(param0: number): void;
public setContentEncoding(param0: string): void;
public addHeader(param0: string, param1: string): void;
public getContentEncoding(): string;
public setContentType(param0: string): void;
public getContentType(): string;
public getContentLength(): number;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzhd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzhd>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzhe {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzhe>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzhf {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzhf>;
public constructor();
public getStatusCode(): number;
public getContent(): java.io.InputStream;
public disconnect(): void;
public getContentEncoding(): string;
public getContentType(): string;
public getReasonPhrase(): string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzhg extends com.google.android.gms.internal.firebase_ml.zzgi {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzhg>;
public getLength(): number;
public constructor(param0: string);
public writeTo(param0: java.io.OutputStream): void;
public constructor(param0: any);
public getType(): string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzhh {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzhh>;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zzhh>*/;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzhj extends com.google.android.gms.internal.firebase_ml.zzji {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzhj>;
public static MEDIA_TYPE: string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzif {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzif>;
public static UTF_8: java.nio.charset.Charset;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzih {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzih>;
public constructor(param0: number, param1: number, param2: number, param3: number);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzii extends com.google.android.gms.internal.firebase_ml.zzih {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzii>;
public constructor();
public constructor(param0: number, param1: number, param2: number, param3: number);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzij {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzij>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzik {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzik>;
public toString(): string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzil<K, V> extends java.util.AbstractMap<any,any> implements java.lang.Cloneable {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzil<any,any>>;
public constructor();
public get(param0: any): any;
public entrySet(): java.util.Set<java.util.Map.Entry<any,any>>;
public set(param0: number, param1: any): any;
public remove(param0: number): any;
public size(): number;
public remove(param0: any): any;
public containsKey(param0: any): boolean;
public clear(): void;
public put(param0: any, param1: any): any;
public containsValue(param0: any): boolean;
}
export module zzil {
export class zza extends java.util.Map.Entry<any,any> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzil.zza>;
public setValue(param0: any): any;
public getValue(): any;
public equals(param0: any): boolean;
public hashCode(): number;
public getKey(): any;
}
export class zzb extends java.util.AbstractSet<java.util.Map.Entry<any,any>> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzil.zzb>;
public size(): number;
public iterator(): java.util.Iterator<java.util.Map.Entry<any,any>>;
}
export class zzc extends java.util.Iterator<java.util.Map.Entry<any,any>> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzil.zzc>;
public hasNext(): boolean;
public remove(): void;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzim {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzim>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzin {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzin>;
public constructor(param0: any);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzio {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzio>;
public static UTF_8: java.nio.charset.Charset;
public static ISO_8859_1: java.nio.charset.Charset;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzip {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzip>;
public write(param0: native.Array<number>, param1: number, param2: number): void;
public write(param0: number): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zziq extends java.util.Comparator<string> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zziq>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzir {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzir>;
public isEnum(): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzis extends java.util.AbstractMap<string,any> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzis>;
public get(param0: any): any;
public containsKey(param0: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzit {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzit>;
public static clone(param0: any): any;
public static isNull(param0: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zziu extends java.util.Iterator<java.util.Map.Entry<string,any>> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zziu>;
public hasNext(): boolean;
public remove(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zziv extends java.util.Map.Entry<string,any> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zziv>;
public getValue(): any;
public hashCode(): number;
public setValue(param0: any): any;
public equals(param0: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zziw {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zziw>;
public hashCode(): number;
public toString(): string;
public equals(param0: any): boolean;
public constructor(param0: number);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzix extends java.util.AbstractSet<java.util.Map.Entry<string,any>> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzix>;
public size(): number;
public clear(): void;
public isEmpty(): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zziy extends java.util.AbstractMap<string,any> implements java.lang.Cloneable {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zziy>;
public constructor();
public get(param0: any): any;
public entrySet(): java.util.Set<java.util.Map.Entry<string,any>>;
public remove(param0: any): any;
public constructor(param0: any /* java.util.EnumSet<com.google.android.gms.internal.firebase_ml.zziy.zzc>*/);
public putAll(param0: java.util.Map<any,any>): void;
}
export module zziy {
export class zza extends java.util.AbstractSet<java.util.Map.Entry<string,any>> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zziy.zza>;
public clear(): void;
public size(): number;
public iterator(): java.util.Iterator<java.util.Map.Entry<string,any>>;
}
export class zzb extends java.util.Iterator<java.util.Map.Entry<string,any>> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zziy.zzb>;
public hasNext(): boolean;
public remove(): void;
}
export class zzc {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zziy.zzc>;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zziy.zzc>*/;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zziz {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zziz>;
public isPrimitive(): boolean;
public getName(): string;
public getGenericType(): java.lang.reflect.Type;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzja {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzja>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzjb {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzjb>;
public constructor(param0: java.util.logging.Logger, param1: java.util.logging.Level, param2: number);
public close(): void;
public write(param0: native.Array<number>, param1: number, param2: number): void;
public write(param0: number): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzjc {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzjc>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzjc interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
value(): string;
});
public constructor();
public value(): string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzjd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzjd>;
public close(): void;
public write(param0: native.Array<number>, param1: number, param2: number): void;
public write(param0: number): void;
public constructor(param0: java.io.OutputStream, param1: java.util.logging.Logger, param2: java.util.logging.Level, param3: number);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzje {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzje>;
public close(): void;
public constructor(param0: java.io.InputStream, param1: java.util.logging.Logger, param2: java.util.logging.Level, param3: number);
public read(): number;
public read(param0: native.Array<number>, param1: number, param2: number): number;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzjf {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzjf>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzjf interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzjg extends com.google.android.gms.internal.firebase_ml.zzjm {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzjg>;
public writeTo(param0: java.io.OutputStream): void;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzjm*/, param1: java.util.logging.Logger, param2: java.util.logging.Level, param3: number);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzjh {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzjh>;
public static checkArgument(param0: boolean, param1: string, param2: native.Array<any>): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzji {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzji>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzji interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zza(param0: java.io.InputStream, param1: java.nio.charset.Charset, param2: java.lang.Class): any;
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzjj extends com.google.android.gms.internal.firebase_ml.zzjk {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzjj>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzjk {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzjk>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzjk interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
<clinit>(): void;
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzjl {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzjl>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzjm {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzjm>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzjm interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
writeTo(param0: java.io.OutputStream): void;
});
public constructor();
public writeTo(param0: java.io.OutputStream): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzjn extends java.lang.Iterable<any> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzjn>;
public iterator(): java.util.Iterator<any>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzjo {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzjo>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzjp {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzjp>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzjp interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
value(): string;
});
public constructor();
public value(): string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzjq extends java.util.Iterator<any> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzjq>;
public hasNext(): boolean;
public remove(): void;
public next(): any;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzjr {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzjr>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzjs {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzjs>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzjt {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzjt>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzju extends com.google.android.gms.internal.firebase_ml.zzjv {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzju>;
public constructor();
public constructor(param0: string, param1: boolean);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzjv extends com.google.android.gms.internal.firebase_ml.zzjr {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzjv>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzjw extends java.lang.ThreadLocal<native.Array<string>> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzjw>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzll<T> extends java.util.Iterator<any> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzll<any>>;
public constructor();
public hasNext(): boolean;
public remove(): void;
public next(): any;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzlm<T> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzlz<any>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzlm<any>>;
public get(): any;
public hashCode(): number;
public toString(): string;
public equals(param0: any): boolean;
public isPresent(): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzln extends java.lang.Object {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzln>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzlo {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzlo>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzlp extends com.google.android.gms.internal.firebase_ml.zzlq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzlp>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzlq extends java.lang.Object {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzlq>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzlr extends com.google.android.gms.internal.firebase_ml.zzlp {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzlr>;
public toString(): string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzls extends com.google.android.gms.internal.firebase_ml.zzlp {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzls>;
public toString(): string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzlt {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzlt>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzlu extends com.google.android.gms.internal.firebase_ml.zzlr {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzlu>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzlv {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzlv>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzlw {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzlw>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzlx {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzlx>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzly {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzly>;
public toString(): string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzlz<T> extends java.io.Serializable {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzlz<any>>;
public get(): any;
public isPresent(): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzma extends com.google.android.gms.internal.firebase_ml.zzlt {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzma>;
public static equal(param0: any, param1: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzmb {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzmb>;
}
export module zzmb {
export class zza {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzmb.zza>;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzmc {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzmc>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzmc interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzmd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzmd>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzme<T> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzlz<any>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzme<any>>;
public get(): any;
public hashCode(): number;
public toString(): string;
public equals(param0: any): boolean;
public isPresent(): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzmf {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzmf>;
public static checkArgument(param0: boolean): void;
public static checkNotNull(param0: any): any;
public static checkArgument(param0: boolean, param1: any): void;
public static checkNotNull(param0: any, param1: any): any;
public static checkState(param0: boolean): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzmg extends com.google.android.gms.internal.firebase_ml.zzml {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzmg>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzmh {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzmh>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzmi extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzll<string>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzmi>;
public constructor();
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzmh*/, param1: string);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzmj extends com.google.android.gms.internal.firebase_ml.zzmi {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzmj>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzmk {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzmk>;
public toString(): string;
public value(): string;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zzmk>*/;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzml {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzml>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzml interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zza(param0: any /* com.google.android.gms.internal.firebase_ml.zzmh*/, param1: string): java.util.Iterator<string>;
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzmm {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzmm>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzmn {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzmn>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzmo<E> extends java.util.AbstractCollection<any> implements java.io.Serializable {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzmo<any>>;
public add(param0: any): boolean;
public remove(param0: any): boolean;
public removeAll(param0: java.util.Collection<any>): boolean;
public toArray(param0: native.Array<any>): native.Array<any>;
public clear(): void;
public toArray(): native.Array<any>;
public addAll(param0: java.util.Collection<any>): boolean;
public retainAll(param0: java.util.Collection<any>): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzmp<E> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzmx<any>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzmp<any>>;
public constructor();
public previousIndex(): number;
public constructor(param0: number, param1: number);
public previous(): any;
public nextIndex(): number;
public hasNext(): boolean;
public get(param0: number): any;
public hasPrevious(): boolean;
public next(): any;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzmq<E> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzmp<any>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzmq<any>>;
public get(param0: number): any;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzmr<E> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzmo<any>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzmr<any>>;
public addAll(param0: number, param1: java.util.Collection<any>): boolean;
public contains(param0: any): boolean;
public set(param0: number, param1: any): any;
public remove(param0: number): any;
public add(param0: any): boolean;
public lastIndexOf(param0: any): number;
public hashCode(): number;
public remove(param0: any): boolean;
public add(param0: number, param1: any): void;
public indexOf(param0: any): number;
public equals(param0: any): boolean;
public addAll(param0: java.util.Collection<any>): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzms {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzms>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzmt extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzmr<any>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzmt>;
public size(): number;
public get(param0: number): any;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzmu<E> extends java.util.Iterator<any> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzmu<any>>;
public constructor();
public remove(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzmv<E> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzmr<any>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzmv<any>>;
public size(): number;
public get(param0: number): any;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzmx<E> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzmu<any>*/ implements java.util.ListIterator<any> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzmx<any>>;
public constructor();
public set(param0: any): void;
public add(param0: any): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzmy {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzmy>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzmz {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzmz>;
}
export module zzmz {
export class zza extends com.google.android.gms.internal.firebase_ml.zzmy {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzmz.zza>;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzna extends java.lang.ref.WeakReference<java.lang.Throwable> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzna>;
public hashCode(): number;
public equals(param0: any): boolean;
public constructor(param0: java.lang.Throwable, param1: java.lang.ref.ReferenceQueue<java.lang.Throwable>);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zznb {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zznb>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zznc extends com.google.android.gms.internal.firebase_ml.zzmy {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zznc>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzne extends com.google.android.gms.internal.firebase_ml.zzmy {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzne>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzng {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng>;
}
export module zzng {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zza,com.google.android.gms.internal.firebase_ml.zzng.zza.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zza>;
public isInitialized(): boolean;
}
export module zza {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zza.zza,com.google.android.gms.internal.firebase_ml.zzng.zza.zza.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zza.zza>;
public isInitialized(): boolean;
}
export module zza {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zza.zza,com.google.android.gms.internal.firebase_ml.zzng.zza.zza.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zza.zza.zza>;
public isInitialized(): boolean;
}
}
export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zza,com.google.android.gms.internal.firebase_ml.zzng.zza.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zza.zzb>;
public isInitialized(): boolean;
}
}
export class zzaa extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzaa,com.google.android.gms.internal.firebase_ml.zzng.zzaa.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzaa>;
public isInitialized(): boolean;
}
export module zzaa {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwb*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzaa.zza>;
public toString(): string;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zzng.zzaa.zza>*/;
}
export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzaa,com.google.android.gms.internal.firebase_ml.zzng.zzaa.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzaa.zzb>;
public isInitialized(): boolean;
}
export class zzc extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwb*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzaa.zzc>;
public toString(): string;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zzng.zzaa.zzc>*/;
}
export class zzd extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwb*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzaa.zzd>;
public toString(): string;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zzng.zzaa.zzd>*/;
}
export class zze extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwb*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzaa.zze>;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zzng.zzaa.zze>*/;
public toString(): string;
}
}
export class zzab extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zze<com.google.android.gms.internal.firebase_ml.zzng.zzab,com.google.android.gms.internal.firebase_ml.zzng.zzab.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzab>;
public isInitialized(): boolean;
}
export module zzab {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zzb<com.google.android.gms.internal.firebase_ml.zzng.zzab,com.google.android.gms.internal.firebase_ml.zzng.zzab.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzab.zza>;
public isInitialized(): boolean;
}
}
export class zzac extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzac,com.google.android.gms.internal.firebase_ml.zzng.zzac.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzac>;
public isInitialized(): boolean;
}
export module zzac {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwb*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzac.zza>;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zzng.zzac.zza>*/;
public toString(): string;
}
export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzac,com.google.android.gms.internal.firebase_ml.zzng.zzac.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzac.zzb>;
public isInitialized(): boolean;
}
}
export class zzad extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzad,com.google.android.gms.internal.firebase_ml.zzng.zzad.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzad>;
public isInitialized(): boolean;
}
export module zzad {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzad,com.google.android.gms.internal.firebase_ml.zzng.zzad.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzad.zza>;
public isInitialized(): boolean;
}
}
export class zzae extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzae,com.google.android.gms.internal.firebase_ml.zzng.zzae.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzae>;
public isInitialized(): boolean;
}
export module zzae {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzae,com.google.android.gms.internal.firebase_ml.zzng.zzae.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzae.zza>;
public isInitialized(): boolean;
}
}
export class zzaf extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzaf,com.google.android.gms.internal.firebase_ml.zzng.zzaf.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzaf>;
public isInitialized(): boolean;
}
export module zzaf {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzaf,com.google.android.gms.internal.firebase_ml.zzng.zzaf.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzaf.zza>;
public isInitialized(): boolean;
}
}
export class zzag extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzag,com.google.android.gms.internal.firebase_ml.zzng.zzag.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzag>;
public isInitialized(): boolean;
}
export module zzag {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzag,com.google.android.gms.internal.firebase_ml.zzng.zzag.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzag.zza>;
public isInitialized(): boolean;
}
export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwb*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzag.zzb>;
public toString(): string;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zzng.zzag.zzb>*/;
}
}
export class zzah extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzah,com.google.android.gms.internal.firebase_ml.zzng.zzah.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzah>;
public isInitialized(): boolean;
}
export module zzah {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwb*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzah.zza>;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zzng.zzah.zza>*/;
public toString(): string;
}
export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzah,com.google.android.gms.internal.firebase_ml.zzng.zzah.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzah.zzb>;
public isInitialized(): boolean;
}
export class zzc extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwb*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzah.zzc>;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zzng.zzah.zzc>*/;
public toString(): string;
}
}
export class zzai extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzai,com.google.android.gms.internal.firebase_ml.zzng.zzai.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzai>;
public isInitialized(): boolean;
}
export module zzai {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzai.zza,com.google.android.gms.internal.firebase_ml.zzng.zzai.zza.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzai.zza>;
public isInitialized(): boolean;
}
export module zza {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzai.zza,com.google.android.gms.internal.firebase_ml.zzng.zzai.zza.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzai.zza.zza>;
public isInitialized(): boolean;
}
}
export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzai,com.google.android.gms.internal.firebase_ml.zzng.zzai.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzai.zzb>;
public isInitialized(): boolean;
}
}
export class zzaj extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzaj,com.google.android.gms.internal.firebase_ml.zzng.zzaj.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzaj>;
public isInitialized(): boolean;
}
export module zzaj {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwb*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzaj.zza>;
public toString(): string;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zzng.zzaj.zza>*/;
}
export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzaj,com.google.android.gms.internal.firebase_ml.zzng.zzaj.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzaj.zzb>;
public isInitialized(): boolean;
}
}
export class zzak extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzak,com.google.android.gms.internal.firebase_ml.zzng.zzak.zzc>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzak>;
public isInitialized(): boolean;
}
export module zzak {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwb*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzak.zza>;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zzng.zzak.zza>*/;
public toString(): string;
}
export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwb*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzak.zzb>;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zzng.zzak.zzb>*/;
public toString(): string;
}
export class zzc extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzak,com.google.android.gms.internal.firebase_ml.zzng.zzak.zzc>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzak.zzc>;
public isInitialized(): boolean;
}
}
export class zzal extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzal,com.google.android.gms.internal.firebase_ml.zzng.zzal.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzal>;
public isInitialized(): boolean;
}
export module zzal {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzal,com.google.android.gms.internal.firebase_ml.zzng.zzal.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzal.zza>;
public isInitialized(): boolean;
}
}
export class zzam extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzam,com.google.android.gms.internal.firebase_ml.zzng.zzam.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzam>;
public isInitialized(): boolean;
}
export module zzam {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzam,com.google.android.gms.internal.firebase_ml.zzng.zzam.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzam.zza>;
public isInitialized(): boolean;
}
}
export class zzan extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzan,com.google.android.gms.internal.firebase_ml.zzng.zzan.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzan>;
public isInitialized(): boolean;
}
export module zzan {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzan,com.google.android.gms.internal.firebase_ml.zzng.zzan.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzan.zza>;
public isInitialized(): boolean;
}
}
export class zzao extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzao,com.google.android.gms.internal.firebase_ml.zzng.zzao.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzao>;
public isInitialized(): boolean;
}
export module zzao {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzao,com.google.android.gms.internal.firebase_ml.zzng.zzao.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzao.zza>;
public isInitialized(): boolean;
}
export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzao.zzb,com.google.android.gms.internal.firebase_ml.zzng.zzao.zzb.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzao.zzb>;
public isInitialized(): boolean;
}
export module zzb {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzao.zzb,com.google.android.gms.internal.firebase_ml.zzng.zzao.zzb.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzao.zzb.zza>;
public isInitialized(): boolean;
}
}
export class zzc extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzao.zzc,com.google.android.gms.internal.firebase_ml.zzng.zzao.zzc.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzao.zzc>;
public isInitialized(): boolean;
}
export module zzc {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzao.zzc,com.google.android.gms.internal.firebase_ml.zzng.zzao.zzc.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzao.zzc.zza>;
public isInitialized(): boolean;
}
}
export class zzd extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzao.zzd,com.google.android.gms.internal.firebase_ml.zzng.zzao.zzd.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzao.zzd>;
public isInitialized(): boolean;
}
export module zzd {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzao.zzd,com.google.android.gms.internal.firebase_ml.zzng.zzao.zzd.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzao.zzd.zza>;
public isInitialized(): boolean;
}
}
}
export class zzap extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzap,com.google.android.gms.internal.firebase_ml.zzng.zzap.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzap>;
public isInitialized(): boolean;
}
export module zzap {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzap,com.google.android.gms.internal.firebase_ml.zzng.zzap.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzap.zza>;
public isInitialized(): boolean;
}
}
export class zzaq extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzaq,com.google.android.gms.internal.firebase_ml.zzng.zzaq.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzaq>;
public isInitialized(): boolean;
}
export module zzaq {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzaq,com.google.android.gms.internal.firebase_ml.zzng.zzaq.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzaq.zza>;
public isInitialized(): boolean;
}
export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwb*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzaq.zzb>;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zzng.zzaq.zzb>*/;
public toString(): string;
}
}
export class zzar extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzar,com.google.android.gms.internal.firebase_ml.zzng.zzar.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzar>;
public isInitialized(): boolean;
}
export module zzar {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzar,com.google.android.gms.internal.firebase_ml.zzng.zzar.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzar.zza>;
public isInitialized(): boolean;
}
}
export class zzas extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzas,com.google.android.gms.internal.firebase_ml.zzng.zzas.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzas>;
public isInitialized(): boolean;
}
export module zzas {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzas,com.google.android.gms.internal.firebase_ml.zzng.zzas.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzas.zza>;
public isInitialized(): boolean;
}
}
export class zzat extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzat,com.google.android.gms.internal.firebase_ml.zzng.zzat.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzat>;
public isInitialized(): boolean;
}
export module zzat {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwb*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzat.zza>;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zzng.zzat.zza>*/;
public toString(): string;
}
export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzat,com.google.android.gms.internal.firebase_ml.zzng.zzat.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzat.zzb>;
public isInitialized(): boolean;
}
export class zzc extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzat.zzc,com.google.android.gms.internal.firebase_ml.zzng.zzat.zzc.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzat.zzc>;
public isInitialized(): boolean;
}
export module zzc {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzat.zzc,com.google.android.gms.internal.firebase_ml.zzng.zzat.zzc.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzat.zzc.zza>;
public isInitialized(): boolean;
}
}
}
export class zzau extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzau,com.google.android.gms.internal.firebase_ml.zzng.zzau.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzau>;
public isInitialized(): boolean;
}
export module zzau {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzau,com.google.android.gms.internal.firebase_ml.zzng.zzau.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzau.zza>;
public isInitialized(): boolean;
}
}
export class zzav extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzav,com.google.android.gms.internal.firebase_ml.zzng.zzav.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzav>;
public isInitialized(): boolean;
}
export module zzav {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzav,com.google.android.gms.internal.firebase_ml.zzng.zzav.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzav.zza>;
public isInitialized(): boolean;
}
export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwb*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzav.zzb>;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zzng.zzav.zzb>*/;
public toString(): string;
}
}
export class zzaw extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzaw,com.google.android.gms.internal.firebase_ml.zzng.zzaw.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzaw>;
public isInitialized(): boolean;
}
export module zzaw {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzaw,com.google.android.gms.internal.firebase_ml.zzng.zzaw.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzaw.zza>;
public isInitialized(): boolean;
}
}
export class zzax extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzax,com.google.android.gms.internal.firebase_ml.zzng.zzax.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzax>;
public isInitialized(): boolean;
}
export module zzax {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzax,com.google.android.gms.internal.firebase_ml.zzng.zzax.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzax.zza>;
public isInitialized(): boolean;
}
}
export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzb,com.google.android.gms.internal.firebase_ml.zzng.zzb.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzb>;
public isInitialized(): boolean;
}
export module zzb {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzb.zza,com.google.android.gms.internal.firebase_ml.zzng.zzb.zza.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzb.zza>;
public isInitialized(): boolean;
}
export module zza {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzb.zza,com.google.android.gms.internal.firebase_ml.zzng.zzb.zza.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzb.zza.zza>;
public isInitialized(): boolean;
}
}
export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzb,com.google.android.gms.internal.firebase_ml.zzng.zzb.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzb.zzb>;
public isInitialized(): boolean;
}
}
export class zzc extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzc,com.google.android.gms.internal.firebase_ml.zzng.zzc.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzc>;
public isInitialized(): boolean;
}
export module zzc {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzc.zza,com.google.android.gms.internal.firebase_ml.zzng.zzc.zza.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzc.zza>;
public isInitialized(): boolean;
}
export module zza {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzc.zza,com.google.android.gms.internal.firebase_ml.zzng.zzc.zza.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzc.zza.zza>;
public isInitialized(): boolean;
}
}
export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzc,com.google.android.gms.internal.firebase_ml.zzng.zzc.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzc.zzb>;
public isInitialized(): boolean;
}
}
export class zzd extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzd,com.google.android.gms.internal.firebase_ml.zzng.zzd.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzd>;
public isInitialized(): boolean;
}
export module zzd {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzd.zza,com.google.android.gms.internal.firebase_ml.zzng.zzd.zza.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzd.zza>;
public isInitialized(): boolean;
}
export module zza {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzd.zza,com.google.android.gms.internal.firebase_ml.zzng.zzd.zza.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzd.zza.zza>;
public isInitialized(): boolean;
}
}
export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzd,com.google.android.gms.internal.firebase_ml.zzng.zzd.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzd.zzb>;
public isInitialized(): boolean;
}
}
export class zze extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zze,com.google.android.gms.internal.firebase_ml.zzng.zze.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zze>;
public isInitialized(): boolean;
}
export module zze {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zze.zza,com.google.android.gms.internal.firebase_ml.zzng.zze.zza.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zze.zza>;
public isInitialized(): boolean;
}
export module zza {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zze.zza,com.google.android.gms.internal.firebase_ml.zzng.zze.zza.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zze.zza.zza>;
public isInitialized(): boolean;
}
}
export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zze,com.google.android.gms.internal.firebase_ml.zzng.zze.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zze.zzb>;
public isInitialized(): boolean;
}
}
export class zzf extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzf,com.google.android.gms.internal.firebase_ml.zzng.zzf.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzf>;
public isInitialized(): boolean;
}
export module zzf {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzf.zza,com.google.android.gms.internal.firebase_ml.zzng.zzf.zza.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzf.zza>;
public isInitialized(): boolean;
}
export module zza {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzf.zza,com.google.android.gms.internal.firebase_ml.zzng.zzf.zza.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzf.zza.zza>;
public isInitialized(): boolean;
}
}
export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzf,com.google.android.gms.internal.firebase_ml.zzng.zzf.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzf.zzb>;
public isInitialized(): boolean;
}
}
export class zzg extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzg,com.google.android.gms.internal.firebase_ml.zzng.zzg.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzg>;
public isInitialized(): boolean;
}
export module zzg {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzg.zza,com.google.android.gms.internal.firebase_ml.zzng.zzg.zza.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzg.zza>;
public isInitialized(): boolean;
}
export module zza {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzg.zza,com.google.android.gms.internal.firebase_ml.zzng.zzg.zza.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzg.zza.zza>;
public isInitialized(): boolean;
}
}
export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzg,com.google.android.gms.internal.firebase_ml.zzng.zzg.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzg.zzb>;
public isInitialized(): boolean;
}
}
export class zzh extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzh,com.google.android.gms.internal.firebase_ml.zzng.zzh.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzh>;
public isInitialized(): boolean;
}
export module zzh {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzh,com.google.android.gms.internal.firebase_ml.zzng.zzh.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzh.zza>;
public isInitialized(): boolean;
}
}
export class zzi extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzi,com.google.android.gms.internal.firebase_ml.zzng.zzi.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzi>;
public isInitialized(): boolean;
}
export module zzi {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzi,com.google.android.gms.internal.firebase_ml.zzng.zzi.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzi.zza>;
public isInitialized(): boolean;
}
}
export class zzj extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzj,com.google.android.gms.internal.firebase_ml.zzng.zzj.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzj>;
public isInitialized(): boolean;
}
export module zzj {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzj,com.google.android.gms.internal.firebase_ml.zzng.zzj.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzj.zza>;
public isInitialized(): boolean;
}
}
export class zzk extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzk,com.google.android.gms.internal.firebase_ml.zzng.zzk.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzk>;
public isInitialized(): boolean;
}
export module zzk {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzk,com.google.android.gms.internal.firebase_ml.zzng.zzk.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzk.zza>;
public isInitialized(): boolean;
}
}
export class zzl extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzl,com.google.android.gms.internal.firebase_ml.zzng.zzl.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzl>;
public isInitialized(): boolean;
}
export module zzl {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzl,com.google.android.gms.internal.firebase_ml.zzng.zzl.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzl.zza>;
public isInitialized(): boolean;
}
export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwb*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzl.zzb>;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zzng.zzl.zzb>*/;
public toString(): string;
}
}
export class zzm extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzm,com.google.android.gms.internal.firebase_ml.zzng.zzm.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzm>;
public isInitialized(): boolean;
}
export module zzm {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzm,com.google.android.gms.internal.firebase_ml.zzng.zzm.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzm.zza>;
public isInitialized(): boolean;
}
}
export class zzn extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzn,com.google.android.gms.internal.firebase_ml.zzng.zzn.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzn>;
public isInitialized(): boolean;
}
export module zzn {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzn,com.google.android.gms.internal.firebase_ml.zzng.zzn.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzn.zza>;
public isInitialized(): boolean;
}
}
export class zzo extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzo,com.google.android.gms.internal.firebase_ml.zzng.zzo.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzo>;
public isInitialized(): boolean;
}
export module zzo {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzo,com.google.android.gms.internal.firebase_ml.zzng.zzo.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzo.zza>;
public isInitialized(): boolean;
}
}
export class zzp extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzp,com.google.android.gms.internal.firebase_ml.zzng.zzp.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzp>;
public isInitialized(): boolean;
}
export module zzp {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzp,com.google.android.gms.internal.firebase_ml.zzng.zzp.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzp.zza>;
public isInitialized(): boolean;
}
}
export class zzq extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzq,com.google.android.gms.internal.firebase_ml.zzng.zzq.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzq>;
public isInitialized(): boolean;
}
export module zzq {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzq,com.google.android.gms.internal.firebase_ml.zzng.zzq.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzq.zza>;
public isInitialized(): boolean;
}
}
export class zzr extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzr,com.google.android.gms.internal.firebase_ml.zzng.zzr.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzr>;
public isInitialized(): boolean;
}
export module zzr {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzr,com.google.android.gms.internal.firebase_ml.zzng.zzr.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzr.zza>;
public isInitialized(): boolean;
}
}
export class zzs extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzs,com.google.android.gms.internal.firebase_ml.zzng.zzs.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzs>;
public isInitialized(): boolean;
}
export module zzs {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzs,com.google.android.gms.internal.firebase_ml.zzng.zzs.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzs.zza>;
public isInitialized(): boolean;
}
}
export class zzt extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzt,com.google.android.gms.internal.firebase_ml.zzng.zzt.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzt>;
public isInitialized(): boolean;
}
export module zzt {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzt,com.google.android.gms.internal.firebase_ml.zzng.zzt.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzt.zza>;
public isInitialized(): boolean;
}
}
export class zzu extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzu,com.google.android.gms.internal.firebase_ml.zzng.zzu.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzu>;
public isInitialized(): boolean;
}
export module zzu {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzu,com.google.android.gms.internal.firebase_ml.zzng.zzu.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzu.zza>;
public isInitialized(): boolean;
}
}
export class zzv extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzv,com.google.android.gms.internal.firebase_ml.zzng.zzv.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzv>;
public isInitialized(): boolean;
}
export module zzv {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzv,com.google.android.gms.internal.firebase_ml.zzng.zzv.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzv.zza>;
public isInitialized(): boolean;
}
}
export class zzw extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzw,com.google.android.gms.internal.firebase_ml.zzng.zzw.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzw>;
public isInitialized(): boolean;
}
export module zzw {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzw.zza,com.google.android.gms.internal.firebase_ml.zzng.zzw.zza.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzw.zza>;
public isInitialized(): boolean;
}
export module zza {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwb*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzw.zza.zza>;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zzng.zzw.zza.zza>*/;
public toString(): string;
}
export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzw.zza,com.google.android.gms.internal.firebase_ml.zzng.zzw.zza.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzw.zza.zzb>;
public isInitialized(): boolean;
}
}
export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzw,com.google.android.gms.internal.firebase_ml.zzng.zzw.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzw.zzb>;
public isInitialized(): boolean;
}
}
export class zzx extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzx,com.google.android.gms.internal.firebase_ml.zzng.zzx.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzx>;
public isInitialized(): boolean;
}
export module zzx {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzx,com.google.android.gms.internal.firebase_ml.zzng.zzx.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzx.zza>;
public isInitialized(): boolean;
}
}
export class zzy extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzy,com.google.android.gms.internal.firebase_ml.zzng.zzy.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzy>;
public isInitialized(): boolean;
}
export module zzy {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzy,com.google.android.gms.internal.firebase_ml.zzng.zzy.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzy.zza>;
public isInitialized(): boolean;
}
}
export class zzz extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzng.zzz,com.google.android.gms.internal.firebase_ml.zzng.zzz.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzz>;
public isInitialized(): boolean;
}
export module zzz {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzng.zzz,com.google.android.gms.internal.firebase_ml.zzng.zzz.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzng.zzz.zza>;
public isInitialized(): boolean;
}
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zznh {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zznh>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzni extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwe<java.lang.Integer,com.google.android.gms.internal.firebase_ml.zzng.zzak.zzb>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzni>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zznj extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwe<java.lang.Integer,com.google.android.gms.internal.firebase_ml.zzng.zzak.zza>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zznj>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zznk extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwe<java.lang.Integer,com.google.android.gms.internal.firebase_ml.zznq>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zznk>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zznl extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwa<com.google.android.gms.internal.firebase_ml.zzng.zzl.zzb>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zznl>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zznm extends com.google.android.gms.internal.firebase_ml.zzwd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zznm>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zznn extends com.google.android.gms.internal.firebase_ml.zzwd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zznn>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzno extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwa<com.google.android.gms.internal.firebase_ml.zzng.zzw.zza.zza>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzno>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zznp extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwe<java.lang.Integer,com.google.android.gms.internal.firebase_ml.zznq>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zznp>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zznq extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwb*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zznq>;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zznq>*/;
public toString(): string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zznr extends com.google.android.gms.internal.firebase_ml.zzwd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zznr>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzns extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwa<com.google.android.gms.internal.firebase_ml.zznq>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzns>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zznt extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwa<com.google.android.gms.internal.firebase_ml.zznu>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zznt>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zznu extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwb*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zznu>;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zznu>*/;
public toString(): string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zznv extends com.google.android.gms.internal.firebase_ml.zzwd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zznv>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zznw extends com.google.android.gms.internal.firebase_ml.zzwd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zznw>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zznx extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwa<com.google.android.gms.internal.firebase_ml.zzng.zzaa.zza>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zznx>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzny extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwa<com.google.android.gms.internal.firebase_ml.zzng.zzaa.zzc>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzny>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zznz extends com.google.android.gms.internal.firebase_ml.zzwd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zznz>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzoa extends com.google.android.gms.internal.firebase_ml.zzwd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzoa>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzob extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwa<com.google.android.gms.internal.firebase_ml.zzng.zzaa.zzd>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzob>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzoc extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwa<com.google.android.gms.internal.firebase_ml.zzng.zzaa.zze>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzoc>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzod extends com.google.android.gms.internal.firebase_ml.zzwd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzod>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzoe extends com.google.android.gms.internal.firebase_ml.zzwd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzoe>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzof extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwa<com.google.android.gms.internal.firebase_ml.zzng.zzac.zza>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzof>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzog extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwa<com.google.android.gms.internal.firebase_ml.zzng.zzag.zzb>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzog>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzoh extends com.google.android.gms.internal.firebase_ml.zzwd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzoh>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzoi extends com.google.android.gms.internal.firebase_ml.zzwd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzoi>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzoj extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwa<com.google.android.gms.internal.firebase_ml.zzng.zzah.zza>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzoj>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzok extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwa<com.google.android.gms.internal.firebase_ml.zzng.zzah.zzc>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzok>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzol extends com.google.android.gms.internal.firebase_ml.zzwd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzol>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzom extends com.google.android.gms.internal.firebase_ml.zzwd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzom>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzon extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwa<com.google.android.gms.internal.firebase_ml.zzng.zzaj.zza>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzon>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzoo extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwe<java.lang.Integer,com.google.android.gms.internal.firebase_ml.zzng.zzak.zza>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzoo>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzop extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwe<java.lang.Integer,com.google.android.gms.internal.firebase_ml.zzng.zzak.zzb>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzop>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzoq extends com.google.android.gms.internal.firebase_ml.zzwd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzoq>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzor extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwa<com.google.android.gms.internal.firebase_ml.zzng.zzak.zza>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzor>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzos extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwa<com.google.android.gms.internal.firebase_ml.zzng.zzak.zzb>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzos>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzot extends com.google.android.gms.internal.firebase_ml.zzwd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzot>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzou extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwa<com.google.android.gms.internal.firebase_ml.zzng.zzaq.zzb>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzou>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzov extends com.google.android.gms.internal.firebase_ml.zzwd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzov>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzow extends com.google.android.gms.internal.firebase_ml.zzwd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzow>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzox extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwa<com.google.android.gms.internal.firebase_ml.zzng.zzat.zza>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzox>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzoy extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwa<com.google.android.gms.internal.firebase_ml.zzng.zzav.zzb>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzoy>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzoz extends com.google.android.gms.internal.firebase_ml.zzwd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzoz>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzpa<K, V> extends java.lang.Object {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzpa<any,any>>;
public constructor();
public create(param0: K): V;
public get(param0: K): V;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzpb {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzpb>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzpc<T, S> extends java.lang.Object {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzpc<any,any>>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzpc<any,any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zza(param0: S): T;
zznl(): any /* com.google.android.gms.internal.firebase_ml.zzpx*/;
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzpd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzpd>;
public getVersion(param0: string): string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzpe {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzpe>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzpf {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzpf>;
public getHandler(): globalAndroid.os.Handler;
public handleMessage(param0: globalAndroid.os.Message): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzpg {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzpg>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzpg interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzph extends java.util.concurrent.Executor {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzph>;
public execute(param0: java.lang.Runnable): void;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zzph>*/;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzpi {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzpi>;
public call(): any;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzpj {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzpj>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzpk {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzpk>;
public create(param0: com.google.firebase.components.ComponentContainer): any;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzpl {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzpl>;
public call(): any;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzpm {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzpm>;
public create(param0: com.google.firebase.components.ComponentContainer): any;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzpn {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzpn>;
public getPersistenceKey(): string;
public getApplicationContext(): globalAndroid.content.Context;
public get(param0: java.lang.Class): any;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzpo {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzpo>;
}
export module zzpo {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzpa<java.lang.Integer,com.google.android.gms.internal.firebase_ml.zzpo>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzpo.zza>;
}
export class zzb {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzpo.zzb>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzpo$zzb interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zza(param0: any /* com.google.android.gms.internal.firebase_ml.zzng.zzab*/): void;
});
public constructor();
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzpp<T> extends java.lang.Object {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzpp<any>>;
public hashCode(): number;
public toString(): string;
public equals(param0: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzpq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzpq>;
public call(): any;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzpr {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzpr>;
public call(): any;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzps {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzps>;
public create(param0: com.google.firebase.components.ComponentContainer): any;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzpt {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzpt>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzpu<K> extends java.lang.Object {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzpu<any>>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzpu<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzpv {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzpv>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzpw {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzpw>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzpw interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zznt(): any /* com.google.android.gms.internal.firebase_ml.zzng.zzab.zza*/;
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzpx {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzpx>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzpx interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zznu(): void;
release(): void;
});
public constructor();
public release(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzpy {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzpy>;
public onBackgroundStateChanged(param0: boolean): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzpz {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzpz>;
}
export module zzpz {
export class zza extends java.util.concurrent.Callable<java.lang.Void> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzpz.zza>;
public equals(param0: any): boolean;
public hashCode(): number;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzqa {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzqa>;
public create(param0: com.google.firebase.components.ComponentContainer): any;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzqb {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzqb>;
public create(param0: com.google.firebase.components.ComponentContainer): any;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzqc {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzqc>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzqd extends com.google.android.gms.internal.firebase_ml.zzpo.zzb {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzqd>;
public constructor(param0: globalAndroid.content.Context);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzsl {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzsl>;
}
export module zzsl {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzsl.zza,com.google.android.gms.internal.firebase_ml.zzsl.zza.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzsl.zza>;
public isInitialized(): boolean;
}
export module zza {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzsl.zza,com.google.android.gms.internal.firebase_ml.zzsl.zza.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzsl.zza.zza>;
public isInitialized(): boolean;
}
}
export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<com.google.android.gms.internal.firebase_ml.zzsl.zzb,com.google.android.gms.internal.firebase_ml.zzsl.zzb.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzsl.zzb>;
public isInitialized(): boolean;
}
export module zzb {
export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<com.google.android.gms.internal.firebase_ml.zzsl.zzb,com.google.android.gms.internal.firebase_ml.zzsl.zzb.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzsl.zzb.zza>;
public isInitialized(): boolean;
}
export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwb*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzsl.zzb.zzb>;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zzsl.zzb.zzb>*/;
public toString(): string;
}
export class zzc extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwb*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzsl.zzb.zzc>;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zzsl.zzb.zzc>*/;
public toString(): string;
}
export class zzd extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwb*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzsl.zzb.zzd>;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zzsl.zzb.zzd>*/;
public toString(): string;
}
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzsn {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzsn>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzso extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwe<java.lang.Integer,com.google.android.gms.internal.firebase_ml.zzuf>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzso>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzsp extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwa<com.google.android.gms.internal.firebase_ml.zzsl.zzb.zzb>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzsp>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzsq extends com.google.android.gms.internal.firebase_ml.zzwd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzsq>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzsr extends com.google.android.gms.internal.firebase_ml.zzwd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzsr>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzss extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwa<com.google.android.gms.internal.firebase_ml.zzsl.zzb.zzc>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzss>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzst extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwa<com.google.android.gms.internal.firebase_ml.zzsl.zzb.zzd>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzst>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzsv extends com.google.android.gms.internal.firebase_ml.zzwd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzsv>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzue extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwa<com.google.android.gms.internal.firebase_ml.zzuf>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzue>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzuf extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzwb*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzuf>;
public toString(): string;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zzuf>*/;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzug<MessageType, BuilderType> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzxg*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzug<any,any>>;
public constructor();
public isInitialized(): boolean;
public toByteArray(): native.Array<number>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzuh extends com.google.android.gms.internal.firebase_ml.zzwd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzuh>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzui extends com.google.android.gms.internal.firebase_ml.zzxp {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzui>;
public constructor();
public isInitialized(): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzuj<MessageType, BuilderType> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzxj*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzuj<any,any>>;
public constructor();
public isInitialized(): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzuk<E> extends java.util.AbstractList<any> implements any /* com.google.android.gms.internal.firebase_ml.zzwh<any>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzuk<any>>;
public addAll(param0: number, param1: java.util.Collection<any>): boolean;
public remove(param0: number): any;
public set(param0: number, param1: any): any;
public add(param0: any): boolean;
public hashCode(): number;
public remove(param0: any): boolean;
public removeAll(param0: java.util.Collection<any>): boolean;
public add(param0: number, param1: any): void;
public clear(): void;
public equals(param0: any): boolean;
public addAll(param0: java.util.Collection<any>): boolean;
public retainAll(param0: java.util.Collection<any>): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzul<MessageType> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzxt<any>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzul<any>>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzum {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzum>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzun {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzun>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzuo extends com.google.android.gms.internal.firebase_ml.zzuk<java.lang.Boolean> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzuo>;
public addAll(param0: number, param1: java.util.Collection<any>): boolean;
public remove(param0: number): any;
public size(): number;
public hashCode(): number;
public addBoolean(param0: boolean): void;
public remove(param0: any): boolean;
public equals(param0: any): boolean;
public removeRange(param0: number, param1: number): void;
public addAll(param0: java.util.Collection<any>): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzup {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzup>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzuq extends java.lang.Object {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzuq>;
public size(): number;
public hashCode(): number;
public toString(): string;
public equals(param0: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzur {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzur>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzus extends java.lang.Object /* java.util.Comparator<com.google.android.gms.internal.firebase_ml.zzuq>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzus>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzut extends com.google.android.gms.internal.firebase_ml.zzuv {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzut>;
public nextByte(): number;
public hasNext(): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzuu extends com.google.android.gms.internal.firebase_ml.zzuw {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzuu>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzuv extends com.google.android.gms.internal.firebase_ml.zzuz {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzuv>;
public nextByte(): number;
public remove(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzuw {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzuw>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzuw interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zzd(param0: native.Array<number>, param1: number, param2: number): native.Array<number>;
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzux extends com.google.android.gms.internal.firebase_ml.zzva {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzux>;
public size(): number;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzuy {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzuy>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzuz extends java.util.Iterator<java.lang.Byte> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzuz>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzuz interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
nextByte(): number;
});
public constructor();
public nextByte(): number;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzva extends com.google.android.gms.internal.firebase_ml.zzvb {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzva>;
public bytes: native.Array<number>;
public size(): number;
public equals(param0: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzvb extends com.google.android.gms.internal.firebase_ml.zzuq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvb>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzvc {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvc>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzvd extends com.google.android.gms.internal.firebase_ml.zzuw {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvd>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzve extends com.google.android.gms.internal.firebase_ml.zzvc {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzve>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzvf {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvf>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzvg {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvg>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzvh extends com.google.android.gms.internal.firebase_ml.zzur {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvh>;
}
export module zzvh {
export class zza {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvh.zza>;
}
export class zzb extends com.google.android.gms.internal.firebase_ml.zzvh {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvh.zzb>;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzvi extends com.google.android.gms.internal.firebase_ml.zzuk<java.lang.Double> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvi>;
public addAll(param0: number, param1: java.util.Collection<any>): boolean;
public remove(param0: number): any;
public size(): number;
public hashCode(): number;
public remove(param0: any): boolean;
public equals(param0: any): boolean;
public removeRange(param0: number, param1: number): void;
public addAll(param0: java.util.Collection<any>): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzvj extends com.google.android.gms.internal.firebase_ml.zzzp {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvj>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzvk {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvk>;
}
export module zzvk {
export class zza {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvk.zza>;
public equals(param0: any): boolean;
public hashCode(): number;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzvl<ContainingType, Type> extends java.lang.Object {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvl<any,any>>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzvm<T> extends java.lang.Object {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvm<any>>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzvn {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvn>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzvo extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvm<com.google.android.gms.internal.firebase_ml.zzvx.zzd>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvo>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzvp {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvp>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzvq<T> extends java.lang.Object {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvq<any>>;
public hashCode(): number;
public iterator(): java.util.Iterator<java.util.Map.Entry<T,any>>;
public equals(param0: any): boolean;
public isInitialized(): boolean;
public isImmutable(): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzvr {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvr>;
public id(): number;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zzvr>*/;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzvs<T> extends java.lang.Comparable<any> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvs<any>>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzvs<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zzb(): number;
zztn(): any /* com.google.android.gms.internal.firebase_ml.zzzj*/;
zzto(): any /* com.google.android.gms.internal.firebase_ml.zzzm*/;
zztp(): boolean;
zztq(): boolean;
zza(param0: any /* com.google.android.gms.internal.firebase_ml.zzxj*/, param1: any /* com.google.android.gms.internal.firebase_ml.zzxg*/): any /* com.google.android.gms.internal.firebase_ml.zzxj*/;
zza(param0: any /* com.google.android.gms.internal.firebase_ml.zzxp*/, param1: any /* com.google.android.gms.internal.firebase_ml.zzxp*/): any /* com.google.android.gms.internal.firebase_ml.zzxp*/;
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzvt {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvt>;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zzvt>*/;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzvu {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvu>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzvv extends com.google.android.gms.internal.firebase_ml.zzxh {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvv>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzvw extends com.google.android.gms.internal.firebase_ml.zzuk<java.lang.Float> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvw>;
public addAll(param0: number, param1: java.util.Collection<any>): boolean;
public remove(param0: number): any;
public size(): number;
public hashCode(): number;
public remove(param0: any): boolean;
public equals(param0: any): boolean;
public removeRange(param0: number, param1: number): void;
public addAll(param0: java.util.Collection<any>): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzvx<MessageType, BuilderType> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzug<any,any>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvx<any,any>>;
public constructor();
public hashCode(): number;
public toString(): string;
public equals(param0: any): boolean;
public isInitialized(): boolean;
}
export module zzvx {
export class zza<MessageType, BuilderType> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzuj<any,any>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvx.zza<any,any>>;
public constructor(param0: any);
public isInitialized(): boolean;
public constructor();
}
export class zzb<MessageType, BuilderType> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx.zza<any,any>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvx.zzb<any,any>>;
public constructor(param0: any);
public isInitialized(): boolean;
public constructor();
}
export class zzc<T> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzul<any>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvx.zzc<any>>;
public constructor(param0: any);
public constructor();
}
export class zzd extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvs<com.google.android.gms.internal.firebase_ml.zzvx.zzd>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvx.zzd>;
}
export abstract class zze<MessageType, BuilderType> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvx<any,any>*/ implements any /* com.google.android.gms.internal.firebase_ml.zzxi*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvx.zze<any,any>>;
public isInitialized(): boolean;
public constructor();
}
export class zzf extends java.lang.Object {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvx.zzf>;
public static values$50KLMJ33DTMIUPRFDTJMOP9FE1P6UT3FC9QMCBQ7CLN6ASJ1EHIM8JB5EDPM2PR59HKN8P949LIN8Q3FCHA6UIBEEPNMMP9R0(): native.Array<number>;
}
export class zzg<ContainingType, Type> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzvl<any,any>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvx.zzg<any,any>>;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzvy {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvy>;
public static hashCode(param0: native.Array<number>): number;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzvz extends com.google.android.gms.internal.firebase_ml.zzuk<java.lang.Integer> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzvz>;
public addAll(param0: number, param1: java.util.Collection<any>): boolean;
public remove(param0: number): any;
public size(): number;
public hashCode(): number;
public remove(param0: any): boolean;
public equals(param0: any): boolean;
public removeRange(param0: number, param1: number): void;
public getInt(param0: number): number;
public addAll(param0: java.util.Collection<any>): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzwa<T> extends java.lang.Object {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzwa<any>>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzwa<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzwb {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzwb>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzwb interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zzb(): number;
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzwc extends com.google.android.gms.internal.firebase_ml.zzwh<java.lang.Float> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzwc>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzwc interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zzsp(): void;
zzso(): boolean;
zzcr(param0: number): any /* com.google.android.gms.internal.firebase_ml.zzwh<any>*/;
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzwd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzwd>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzwd interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zzb(param0: number): boolean;
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzwe<F, T> extends java.lang.Object {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzwe<any,any>>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzwe<any,any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzwf extends com.google.android.gms.internal.firebase_ml.zzwh<java.lang.Integer> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzwf>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzwf interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zzdo(param0: number): void;
zzdn(param0: number): any /* com.google.android.gms.internal.firebase_ml.zzwf*/;
zzsp(): void;
zzso(): boolean;
zzcr(param0: number): any /* com.google.android.gms.internal.firebase_ml.zzwh<any>*/;
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzwg {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzwg>;
public constructor(param0: string);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzwh<E> extends java.lang.Object {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzwh<any>>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzwh<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zzsp(): void;
zzso(): boolean;
zzcr(param0: number): any /* com.google.android.gms.internal.firebase_ml.zzwh<E>*/;
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzwi {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzwi>;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zzwi>*/;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzwj extends com.google.android.gms.internal.firebase_ml.zzwg {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzwj>;
public constructor(param0: string);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzwk {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzwk>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzwl extends com.google.android.gms.internal.firebase_ml.zzwp {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzwl>;
public hashCode(): number;
public toString(): string;
public equals(param0: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzwm<K> extends java.util.Iterator<java.util.Map.Entry<any,any>> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzwm<any>>;
public constructor(param0: java.util.Iterator<java.util.Map.Entry<any,any>>);
public hasNext(): boolean;
public remove(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzwn<K> extends java.util.Map.Entry<any,any> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzwn<any>>;
public getValue(): any;
public getKey(): any;
public setValue(param0: any): any;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzwo extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzuk<string>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzwo>;
public constructor();
public addAll(param0: number, param1: java.util.Collection<any>): boolean;
public size(): number;
public getRaw(param0: number): any;
public clear(): void;
public constructor(param0: number);
public addAll(param0: java.util.Collection<any>): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzwp {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzwp>;
public constructor();
public hashCode(): number;
public equals(param0: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzwq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzwq>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzwr {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzwr>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzwr interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getRaw(param0: number): any;
zze(param0: any /* com.google.android.gms.internal.firebase_ml.zzuq*/): void;
zzur(): java.util.List<any>;
zzus(): any /* com.google.android.gms.internal.firebase_ml.zzwr*/;
});
public constructor();
public getRaw(param0: number): any;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzws extends com.google.android.gms.internal.firebase_ml.zzwq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzws>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzwt {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzwt>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzwu extends com.google.android.gms.internal.firebase_ml.zzuk<java.lang.Long> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzwu>;
public addAll(param0: number, param1: java.util.Collection<any>): boolean;
public remove(param0: number): any;
public size(): number;
public hashCode(): number;
public remove(param0: any): boolean;
public equals(param0: any): boolean;
public removeRange(param0: number, param1: number): void;
public getLong(param0: number): number;
public addAll(param0: java.util.Collection<any>): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzwv extends com.google.android.gms.internal.firebase_ml.zzwq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzwv>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzww extends com.google.android.gms.internal.firebase_ml.zzxh {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzww>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzwx extends com.google.android.gms.internal.firebase_ml.zzyd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzwx>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzwy<K, V> extends java.lang.Object {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzwy<any,any>>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzwz extends com.google.android.gms.internal.firebase_ml.zzxh {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzwz>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzxa<K, V> extends java.util.LinkedHashMap<any,any> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzxa<any,any>>;
public entrySet(): java.util.Set<java.util.Map.Entry<any,any>>;
public hashCode(): number;
public remove(param0: any): any;
public clear(): void;
public isMutable(): boolean;
public put(param0: any, param1: any): any;
public equals(param0: any): boolean;
public putAll(param0: java.util.Map<any,any>): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzxb<K, V> extends java.lang.Object {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzxb<any,any>>;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzzj*/, param1: K, param2: any /* com.google.android.gms.internal.firebase_ml.zzzj*/, param3: V);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzxc extends com.google.android.gms.internal.firebase_ml.zzxd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzxc>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzxd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzxd>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzxd interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zzu(param0: any): java.util.Map<any,any>;
zzw(param0: any): java.util.Map<any,any>;
zzx(param0: any): boolean;
zzy(param0: any): any;
zzz(param0: any): any;
zzv(param0: any): any /* com.google.android.gms.internal.firebase_ml.zzxb<any,any>*/;
zzd(param0: any, param1: any): any;
zzd(param0: number, param1: any, param2: any): number;
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzxe {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzxe>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzxe interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zzva(): number;
zzvb(): boolean;
zzvc(): any /* com.google.android.gms.internal.firebase_ml.zzxg*/;
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzxf {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzxf>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzxg extends com.google.android.gms.internal.firebase_ml.zzxi {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzxg>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzxg interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zzb(param0: any /* com.google.android.gms.internal.firebase_ml.zzvh*/): void;
zzua(): number;
zzsk(): any /* com.google.android.gms.internal.firebase_ml.zzuq*/;
zzuf(): any /* com.google.android.gms.internal.firebase_ml.zzxj*/;
zzue(): any /* com.google.android.gms.internal.firebase_ml.zzxj*/;
zzty(): any /* com.google.android.gms.internal.firebase_ml.zzxg*/;
isInitialized(): boolean;
});
public constructor();
public isInitialized(): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzxh {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzxh>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzxh interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zzh(param0: java.lang.Class<any>): boolean;
zzi(param0: java.lang.Class<any>): any /* com.google.android.gms.internal.firebase_ml.zzxe*/;
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzxi {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzxi>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzxi interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zzty(): any /* com.google.android.gms.internal.firebase_ml.zzxg*/;
isInitialized(): boolean;
});
public constructor();
public isInitialized(): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzxj extends com.google.android.gms.internal.firebase_ml.zzxi {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzxj>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzxj interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zztx(): any /* com.google.android.gms.internal.firebase_ml.zzxg*/;
zztw(): any /* com.google.android.gms.internal.firebase_ml.zzxg*/;
zza(param0: any /* com.google.android.gms.internal.firebase_ml.zzxg*/): any /* com.google.android.gms.internal.firebase_ml.zzxj*/;
zzty(): any /* com.google.android.gms.internal.firebase_ml.zzxg*/;
isInitialized(): boolean;
});
public constructor();
public isInitialized(): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzxk<T> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzya<any>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzxk<any>>;
public hashCode(param0: any): number;
public newInstance(): any;
public equals(param0: any, param1: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzxl {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzxl>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzxm<T> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzya<any>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzxm<any>>;
public hashCode(param0: any): number;
public newInstance(): any;
public equals(param0: any, param1: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzxn {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzxn>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzxo {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzxo>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzxo interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
newInstance(param0: any): any;
});
public constructor();
public newInstance(param0: any): any;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzxp extends com.google.android.gms.internal.firebase_ml.zzxg {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzxp>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzxp interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zzsm(): any /* com.google.android.gms.internal.firebase_ml.zzxp*/;
zzb(param0: any /* com.google.android.gms.internal.firebase_ml.zzvh*/): void;
zzua(): number;
zzsk(): any /* com.google.android.gms.internal.firebase_ml.zzuq*/;
zzuf(): any /* com.google.android.gms.internal.firebase_ml.zzxj*/;
zzue(): any /* com.google.android.gms.internal.firebase_ml.zzxj*/;
zzty(): any /* com.google.android.gms.internal.firebase_ml.zzxg*/;
isInitialized(): boolean;
});
public constructor();
public isInitialized(): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzxq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzxq>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzxr extends com.google.android.gms.internal.firebase_ml.zzxo {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzxr>;
public newInstance(param0: any): any;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzxs {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzxs>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzxs interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzxt<MessageType> extends java.lang.Object {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzxt<any>>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzxt<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzxu<E> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzuk<any>*/ implements java.util.RandomAccess {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzxu<any>>;
public remove(param0: number): any;
public set(param0: number, param1: any): any;
public add(param0: any): boolean;
public size(): number;
public remove(param0: any): boolean;
public add(param0: number, param1: any): void;
public get(param0: number): any;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzxv {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzxv>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzxw extends com.google.android.gms.internal.firebase_ml.zzuq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzxw>;
public size(): number;
public equals(param0: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzxx extends com.google.android.gms.internal.firebase_ml.zzxe {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzxx>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzxy {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzxy>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzxz extends com.google.android.gms.internal.firebase_ml.zzuv {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzxz>;
public nextByte(): number;
public hasNext(): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzya<T> extends java.lang.Object {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzya<any>>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzya<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zza(param0: T, param1: any /* com.google.android.gms.internal.firebase_ml.zzzp*/): void;
zza(param0: T, param1: native.Array<number>, param2: number, param3: number, param4: any /* com.google.android.gms.internal.firebase_ml.zzup*/): void;
zzq(param0: T): void;
zzac(param0: T): boolean;
newInstance(): T;
equals(param0: T, param1: T): boolean;
hashCode(param0: T): number;
zze(param0: T, param1: T): void;
zzaa(param0: T): number;
});
public constructor();
public equals(param0: T, param1: T): boolean;
public newInstance(): T;
public hashCode(param0: T): number;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzyb extends java.lang.Object /* java.util.Iterator<com.google.android.gms.internal.firebase_ml.zzvb>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzyb>;
public hasNext(): boolean;
public remove(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzyc {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzyc>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzyd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzyd>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzyd interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zzk(param0: java.lang.Class): any /* com.google.android.gms.internal.firebase_ml.zzya<any>*/;
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzye extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzyf<any,any>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzye>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzyf<K, V> extends java.util.AbstractMap<any,any> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzyf<any,any>>;
public get(param0: any): any;
public entrySet(): java.util.Set<java.util.Map.Entry<any,any>>;
public size(): number;
public hashCode(): number;
public remove(param0: any): any;
public containsKey(param0: any): boolean;
public clear(): void;
public equals(param0: any): boolean;
public isImmutable(): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzyg extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzym*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzyg>;
public iterator(): java.util.Iterator<java.util.Map.Entry<any,any>>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzyh extends java.util.Iterator<java.util.Map.Entry<any,any>> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzyh>;
public hasNext(): boolean;
public remove(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzyi extends java.util.Iterator<any> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzyi>;
public hasNext(): boolean;
public remove(): void;
public next(): any;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzyj {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzyj>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzyk extends java.lang.Object {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzyk>;
public getValue(): any;
public hashCode(): number;
public toString(): string;
public setValue(param0: any): any;
public equals(param0: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzyl extends java.lang.Iterable<any> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzyl>;
public iterator(): java.util.Iterator<any>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzym extends java.util.AbstractSet<java.util.Map.Entry<any,any>> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzym>;
public contains(param0: any): boolean;
public size(): number;
public remove(param0: any): boolean;
public clear(): void;
public iterator(): java.util.Iterator<java.util.Map.Entry<any,any>>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzyn extends java.util.Iterator<java.util.Map.Entry<any,any>> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzyn>;
public hasNext(): boolean;
public remove(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzyo {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzyo>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzyp extends com.google.android.gms.internal.firebase_ml.zzxe {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzyp>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzyq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzyq>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzyq interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
size(): number;
zzcs(param0: number): number;
});
public constructor();
public size(): number;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzyr extends com.google.android.gms.internal.firebase_ml.zzyq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzyr>;
public size(): number;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzys<T, B> extends java.lang.Object {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzys<any,any>>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzyt {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzyt>;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzxg*/);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzyu extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzys<com.google.android.gms.internal.firebase_ml.zzyv,com.google.android.gms.internal.firebase_ml.zzyv>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzyu>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzyv {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzyv>;
public hashCode(): number;
public equals(param0: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzyw extends java.util.ListIterator<string> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzyw>;
public previousIndex(): number;
public nextIndex(): number;
public hasNext(): boolean;
public remove(): void;
public hasPrevious(): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzyx extends java.util.AbstractList<string> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzyx>;
public listIterator(param0: number): java.util.ListIterator<string>;
public iterator(): java.util.Iterator<string>;
public size(): number;
public getRaw(param0: number): any;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzwr*/);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzyy {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzyy>;
}
export module zzyy {
export class zza extends com.google.android.gms.internal.firebase_ml.zzyy.zzd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzyy.zza>;
}
export class zzb extends com.google.android.gms.internal.firebase_ml.zzyy.zzd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzyy.zzb>;
}
export class zzc extends com.google.android.gms.internal.firebase_ml.zzyy.zzd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzyy.zzc>;
}
export abstract class zzd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzyy.zzd>;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzyz extends java.util.Iterator<string> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzyz>;
public hasNext(): boolean;
public remove(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzza extends java.security.PrivilegedExceptionAction<sun.misc.Unsafe> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzza>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzzb {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzzb>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzzc {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzzc>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzzd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzzd>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzze {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzze>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzzf extends com.google.android.gms.internal.firebase_ml.zzzc {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzzf>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzzg {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzzg>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzzh extends com.google.android.gms.internal.firebase_ml.zzzc {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzzh>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzzi extends com.google.android.gms.internal.firebase_ml.zzzj {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzzi>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzzj {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzzj>;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zzzj>*/;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzzk extends com.google.android.gms.internal.firebase_ml.zzzj {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzzk>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzzl extends com.google.android.gms.internal.firebase_ml.zzzj {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzzl>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzzm {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzzm>;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zzzm>*/;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzzn extends com.google.android.gms.internal.firebase_ml.zzzj {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzzn>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzzp {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzzp>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzzp interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zztg(): number;
zzs(param0: number, param1: number): void;
zzi(param0: number, param1: number): void;
zzj(param0: number, param1: number): void;
zza(param0: number, param1: number): void;
zza(param0: number, param1: number): void;
zzt(param0: number, param1: number): void;
zza(param0: number, param1: number): void;
zzi(param0: number, param1: number): void;
zzc(param0: number, param1: number): void;
zzl(param0: number, param1: number): void;
zza(param0: number, param1: boolean): void;
zzb(param0: number, param1: string): void;
zza(param0: number, param1: any /* com.google.android.gms.internal.firebase_ml.zzuq*/): void;
zzj(param0: number, param1: number): void;
zzk(param0: number, param1: number): void;
zzb(param0: number, param1: number): void;
zza(param0: number, param1: any, param2: any /* com.google.android.gms.internal.firebase_ml.zzya<any>*/): void;
zzb(param0: number, param1: any, param2: any /* com.google.android.gms.internal.firebase_ml.zzya<any>*/): void;
zzdl(param0: number): void;
zzdm(param0: number): void;
zza(param0: number, param1: java.util.List<java.lang.Integer>, param2: boolean): void;
zzb(param0: number, param1: java.util.List<java.lang.Integer>, param2: boolean): void;
zzc(param0: number, param1: java.util.List<java.lang.Long>, param2: boolean): void;
zzd(param0: number, param1: java.util.List<java.lang.Long>, param2: boolean): void;
zze(param0: number, param1: java.util.List<java.lang.Long>, param2: boolean): void;
zzf(param0: number, param1: java.util.List<java.lang.Float>, param2: boolean): void;
zzg(param0: number, param1: java.util.List<java.lang.Double>, param2: boolean): void;
zzh(param0: number, param1: java.util.List<java.lang.Integer>, param2: boolean): void;
zzi(param0: number, param1: java.util.List<java.lang.Boolean>, param2: boolean): void;
zza(param0: number, param1: java.util.List<string>): void;
zzb(param0: number, param1: any /* java.util.List<com.google.android.gms.internal.firebase_ml.zzuq>*/): void;
zzj(param0: number, param1: java.util.List<java.lang.Integer>, param2: boolean): void;
zzk(param0: number, param1: java.util.List<java.lang.Integer>, param2: boolean): void;
zzl(param0: number, param1: java.util.List<java.lang.Long>, param2: boolean): void;
zzm(param0: number, param1: java.util.List<java.lang.Integer>, param2: boolean): void;
zzn(param0: number, param1: java.util.List<java.lang.Long>, param2: boolean): void;
zza(param0: number, param1: java.util.List<any>, param2: any /* com.google.android.gms.internal.firebase_ml.zzya<any>*/): void;
zzb(param0: number, param1: java.util.List<any>, param2: any /* com.google.android.gms.internal.firebase_ml.zzya<any>*/): void;
zza(param0: number, param1: any): void;
zza(param0: number, param1: any /* com.google.android.gms.internal.firebase_ml.zzxb<any,any>*/, param2: java.util.Map): void;
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export class CommonComponentRegistrar {
public static class: java.lang.Class<com.google.firebase.ml.common.CommonComponentRegistrar>;
public constructor();
public getComponents(): java.util.List<com.google.firebase.components.Component<any>>;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export class FirebaseMLException {
public static class: java.lang.Class<com.google.firebase.ml.common.FirebaseMLException>;
public static OK: number;
public static CANCELLED: number;
public static UNKNOWN: number;
public static INVALID_ARGUMENT: number;
public static DEADLINE_EXCEEDED: number;
public static NOT_FOUND: number;
public static ALREADY_EXISTS: number;
public static PERMISSION_DENIED: number;
public static RESOURCE_EXHAUSTED: number;
public static FAILED_PRECONDITION: number;
public static ABORTED: number;
public static OUT_OF_RANGE: number;
public static UNIMPLEMENTED: number;
public static INTERNAL: number;
public static UNAVAILABLE: number;
public static DATA_LOSS: number;
public static UNAUTHENTICATED: number;
public static MODEL_INCOMPATIBLE_WITH_TFLITE: number;
public static NOT_ENOUGH_SPACE: number;
public static MODEL_HASH_MISMATCH: number;
public constructor(param0: string, param1: number);
public getCode(): number;
public constructor(param0: string, param1: number, param2: java.lang.Throwable);
}
export module FirebaseMLException {
export class Code {
public static class: java.lang.Class<com.google.firebase.ml.common.FirebaseMLException.Code>;
/**
* Constructs a new instance of the com.google.firebase.ml.common.FirebaseMLException$Code interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class RemoteModelManagerInterface<TRemote> extends java.lang.Object {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.RemoteModelManagerInterface<any>>;
/**
* Constructs a new instance of the com.google.firebase.ml.common.internal.modeldownload.RemoteModelManagerInterface<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
download(param0: TRemote, param1: com.google.firebase.ml.common.modeldownload.FirebaseModelDownloadConditions): com.google.android.gms.tasks.Task<java.lang.Void>;
deleteDownloadedModel(param0: TRemote): com.google.android.gms.tasks.Task<java.lang.Void>;
isModelDownloaded(param0: TRemote): com.google.android.gms.tasks.Task<java.lang.Boolean>;
getDownloadedModels(): com.google.android.gms.tasks.Task<java.util.Set<TRemote>>;
});
public constructor();
public download(param0: TRemote, param1: com.google.firebase.ml.common.modeldownload.FirebaseModelDownloadConditions): com.google.android.gms.tasks.Task<java.lang.Void>;
public isModelDownloaded(param0: TRemote): com.google.android.gms.tasks.Task<java.lang.Boolean>;
public getDownloadedModels(): com.google.android.gms.tasks.Task<java.util.Set<TRemote>>;
public deleteDownloadedModel(param0: TRemote): com.google.android.gms.tasks.Task<java.lang.Void>;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zza extends com.google.firebase.ml.common.internal.modeldownload.zzk {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zza>;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzaa {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzaa>;
public constructor(param0: string, param1: globalAndroid.net.Uri, param2: string, param3: any /* com.google.firebase.ml.common.internal.modeldownload.zzn*/);
public getModelHash(): string;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzab extends com.google.firebase.ml.common.internal.modeldownload.zzk {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzab>;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzac {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzac>;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzad {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzad>;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzae extends com.google.firebase.ml.common.internal.modeldownload.zzk {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzae>;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzaf {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzaf>;
/**
* Constructs a new instance of the com.google.firebase.ml.common.internal.modeldownload.zzaf interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zzby(param0: string): java.nio.MappedByteBuffer;
});
public constructor();
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzag {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzag>;
public load(): java.nio.MappedByteBuffer;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzah {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzah>;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzai {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzai>;
public openConnection(): java.net.URLConnection;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzb extends com.google.firebase.ml.common.internal.modeldownload.zze {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzb>;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzc extends com.google.firebase.ml.common.internal.modeldownload.zze {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzc>;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzd {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzd>;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zze {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zze>;
/**
* Constructs a new instance of the com.google.firebase.ml.common.internal.modeldownload.zze interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zza(param0: java.io.BufferedWriter): void;
});
public constructor();
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzf {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzf>;
public constructor(param0: globalAndroid.content.Context, param1: com.google.firebase.ml.common.modeldownload.FirebaseLocalModel);
public load(): java.nio.MappedByteBuffer;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzg {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzg>;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzpn*/);
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzh {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzh>;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzi {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzi>;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzpn*/);
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzj {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzj>;
public constructor(param0: any /* com.google.firebase.ml.common.internal.modeldownload.zzag*/, param1: any /* com.google.firebase.ml.common.internal.modeldownload.zzf*/, param2: any /* com.google.firebase.ml.common.internal.modeldownload.zzl*/);
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzk {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzk>;
/**
* Constructs a new instance of the com.google.firebase.ml.common.internal.modeldownload.zzk interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zza(param0: java.io.File): java.io.File;
});
public constructor();
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzl {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzl>;
/**
* Constructs a new instance of the com.google.firebase.ml.common.internal.modeldownload.zzl interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zze(param0: any /* java.util.List<com.google.android.gms.internal.firebase_ml.zznq>*/): void;
});
public constructor();
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzm {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzm>;
/**
* Constructs a new instance of the com.google.firebase.ml.common.internal.modeldownload.zzm interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zza(param0: java.nio.MappedByteBuffer): void;
});
public constructor();
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzn {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzn>;
public static values(): any /* native.Array<com.google.firebase.ml.common.internal.modeldownload.zzn>*/;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzo extends java.lang.Object {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzo>;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzp {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzp>;
/**
* Constructs a new instance of the com.google.firebase.ml.common.internal.modeldownload.zzp interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zza(param0: java.io.File, param1: any /* com.google.firebase.ml.common.internal.modeldownload.zzw*/): any /* com.google.firebase.ml.common.internal.modeldownload.zzs*/;
});
public constructor();
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzq {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzq>;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzr {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzr>;
public static values(): any /* native.Array<com.google.firebase.ml.common.internal.modeldownload.zzr>*/;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzs {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzs>;
public constructor(param0: any /* com.google.firebase.ml.common.internal.modeldownload.zzr*/, param1: string);
public isValid(): boolean;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzt {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzt>;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzu {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzu>;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzv {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzv>;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzw {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzw>;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzpn*/, param1: com.google.firebase.ml.common.modeldownload.FirebaseRemoteModel);
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzx {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzx>;
public onReceive(param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent): void;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzy {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzy>;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module internal {
export module modeldownload {
export class zzz {
public static class: java.lang.Class<com.google.firebase.ml.common.internal.modeldownload.zzz>;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzpn*/, param1: com.google.firebase.ml.common.modeldownload.FirebaseRemoteModel, param2: any /* com.google.firebase.ml.common.internal.modeldownload.zzp*/, param3: any /* com.google.firebase.ml.common.internal.modeldownload.zzn*/, param4: any /* com.google.firebase.ml.common.internal.modeldownload.zzi*/);
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module modeldownload {
export class BaseModel {
public static class: java.lang.Class<com.google.firebase.ml.common.modeldownload.BaseModel>;
public static TRANSLATE: com.google.firebase.ml.common.modeldownload.BaseModel;
public static values(): native.Array<com.google.firebase.ml.common.modeldownload.BaseModel>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module modeldownload {
export class FirebaseLocalModel {
public static class: java.lang.Class<com.google.firebase.ml.common.modeldownload.FirebaseLocalModel>;
public hashCode(): number;
public getFilePath(): string;
public constructor(param0: string, param1: string, param2: string);
public getAssetFilePath(): string;
public equals(param0: any): boolean;
}
export module FirebaseLocalModel {
export class Builder {
public static class: java.lang.Class<com.google.firebase.ml.common.modeldownload.FirebaseLocalModel.Builder>;
public setAssetFilePath(param0: string): com.google.firebase.ml.common.modeldownload.FirebaseLocalModel.Builder;
public setFilePath(param0: string): com.google.firebase.ml.common.modeldownload.FirebaseLocalModel.Builder;
public constructor(param0: string);
public build(): com.google.firebase.ml.common.modeldownload.FirebaseLocalModel;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module modeldownload {
export class FirebaseModelDownloadConditions {
public static class: java.lang.Class<com.google.firebase.ml.common.modeldownload.FirebaseModelDownloadConditions>;
public hashCode(): number;
public isDeviceIdleRequired(): boolean;
public isWifiRequired(): boolean;
public equals(param0: any): boolean;
public isChargingRequired(): boolean;
}
export module FirebaseModelDownloadConditions {
export class Builder {
public static class: java.lang.Class<com.google.firebase.ml.common.modeldownload.FirebaseModelDownloadConditions.Builder>;
public requireCharging(): com.google.firebase.ml.common.modeldownload.FirebaseModelDownloadConditions.Builder;
public requireDeviceIdle(): com.google.firebase.ml.common.modeldownload.FirebaseModelDownloadConditions.Builder;
public constructor();
public requireWifi(): com.google.firebase.ml.common.modeldownload.FirebaseModelDownloadConditions.Builder;
public build(): com.google.firebase.ml.common.modeldownload.FirebaseModelDownloadConditions;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module modeldownload {
export class FirebaseModelManager {
public static class: java.lang.Class<com.google.firebase.ml.common.modeldownload.FirebaseModelManager>;
public deleteDownloadedModel(param0: com.google.firebase.ml.common.modeldownload.FirebaseRemoteModel): com.google.android.gms.tasks.Task<java.lang.Void>;
public getDownloadedModels(param0: java.lang.Class): com.google.android.gms.tasks.Task;
public static getInstance(param0: com.google.firebase.FirebaseApp): com.google.firebase.ml.common.modeldownload.FirebaseModelManager;
public download(param0: com.google.firebase.ml.common.modeldownload.FirebaseRemoteModel, param1: com.google.firebase.ml.common.modeldownload.FirebaseModelDownloadConditions): com.google.android.gms.tasks.Task<java.lang.Void>;
public isModelDownloaded(param0: com.google.firebase.ml.common.modeldownload.FirebaseRemoteModel): com.google.android.gms.tasks.Task<java.lang.Boolean>;
public static getInstance(): com.google.firebase.ml.common.modeldownload.FirebaseModelManager;
public constructor(param0: java.util.Set<com.google.firebase.ml.common.modeldownload.FirebaseModelManager.RemoteModelManagerRegistration>);
}
export module FirebaseModelManager {
export class RemoteModelManagerRegistration {
public static class: java.lang.Class<com.google.firebase.ml.common.modeldownload.FirebaseModelManager.RemoteModelManagerRegistration>;
public constructor(param0: java.lang.Class, param1: com.google.firebase.inject.Provider);
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module modeldownload {
export class FirebaseRemoteModel {
public static class: java.lang.Class<com.google.firebase.ml.common.modeldownload.FirebaseRemoteModel>;
public getUniqueModelNameForPersist(): string;
public isBaseModel(): boolean;
public baseModelHashMatches(param0: string): boolean;
public getModelNameForBackend(): string;
public hashCode(): number;
public getModelHash(): string;
public setModelHash(param0: string): void;
public getModelName(): string;
public equals(param0: any): boolean;
public constructor(param0: string, param1: com.google.firebase.ml.common.modeldownload.BaseModel);
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export module modeldownload {
export class zza {
public static class: java.lang.Class<com.google.firebase.ml.common.modeldownload.zza>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export class zza {
public static class: java.lang.Class<com.google.firebase.ml.common.zza>;
public create(param0: com.google.firebase.components.ComponentContainer): any;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module common {
export class zzb {
public static class: java.lang.Class<com.google.firebase.ml.common.zzb>;
public create(param0: com.google.firebase.components.ComponentContainer): any;
}
}
}
}
}
}
//Generics information:
//com.google.android.gms.internal.firebase_ml.zzil:2
//com.google.android.gms.internal.firebase_ml.zzll:1
//com.google.android.gms.internal.firebase_ml.zzlm:1
//com.google.android.gms.internal.firebase_ml.zzlz:1
//com.google.android.gms.internal.firebase_ml.zzme:1
//com.google.android.gms.internal.firebase_ml.zzmo:1
//com.google.android.gms.internal.firebase_ml.zzmp:1
//com.google.android.gms.internal.firebase_ml.zzmq:1
//com.google.android.gms.internal.firebase_ml.zzmr:1
//com.google.android.gms.internal.firebase_ml.zzmu:1
//com.google.android.gms.internal.firebase_ml.zzmv:1
//com.google.android.gms.internal.firebase_ml.zzmx:1
//com.google.android.gms.internal.firebase_ml.zzpa:2
//com.google.android.gms.internal.firebase_ml.zzpc:2
//com.google.android.gms.internal.firebase_ml.zzpp:1
//com.google.android.gms.internal.firebase_ml.zzpu:1
//com.google.android.gms.internal.firebase_ml.zzug:2
//com.google.android.gms.internal.firebase_ml.zzuj:2
//com.google.android.gms.internal.firebase_ml.zzuk:1
//com.google.android.gms.internal.firebase_ml.zzul:1
//com.google.android.gms.internal.firebase_ml.zzvl:2
//com.google.android.gms.internal.firebase_ml.zzvm:1
//com.google.android.gms.internal.firebase_ml.zzvq:1
//com.google.android.gms.internal.firebase_ml.zzvs:1
//com.google.android.gms.internal.firebase_ml.zzvx:2
//com.google.android.gms.internal.firebase_ml.zzvx.zza:2
//com.google.android.gms.internal.firebase_ml.zzvx.zzb:2
//com.google.android.gms.internal.firebase_ml.zzvx.zzc:1
//com.google.android.gms.internal.firebase_ml.zzvx.zze:2
//com.google.android.gms.internal.firebase_ml.zzvx.zzg:2
//com.google.android.gms.internal.firebase_ml.zzwa:1
//com.google.android.gms.internal.firebase_ml.zzwe:2
//com.google.android.gms.internal.firebase_ml.zzwh:1
//com.google.android.gms.internal.firebase_ml.zzwm:1
//com.google.android.gms.internal.firebase_ml.zzwn:1
//com.google.android.gms.internal.firebase_ml.zzwy:2
//com.google.android.gms.internal.firebase_ml.zzxa:2
//com.google.android.gms.internal.firebase_ml.zzxb:2
//com.google.android.gms.internal.firebase_ml.zzxk:1
//com.google.android.gms.internal.firebase_ml.zzxm:1
//com.google.android.gms.internal.firebase_ml.zzxt:1
//com.google.android.gms.internal.firebase_ml.zzxu:1
//com.google.android.gms.internal.firebase_ml.zzya:1
//com.google.android.gms.internal.firebase_ml.zzyf:2
//com.google.android.gms.internal.firebase_ml.zzys:2
//com.google.firebase.ml.common.internal.modeldownload.RemoteModelManagerInterface:1 | the_stack |
import * as isBlank from 'is-blank';
// @ts-ignore: no declaration file
import * as RadixRouter from 'radix-router';
import { uniq } from 'ramda';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { URL as NodeURL } from 'url';
import { isNotInstallableApplication } from '../application-settings/selectors';
import { getApplicationId, getApplicationManifestURL, getApplicationCustomURL } from '../applications/get';
import ManifestProvider from '../applications/manifest-provider/manifest-provider';
import { getApplicationById, getApplications, getApplicationCustomURLsWithApplicationId } from '../applications/selectors';
import { ApplicationImmutable } from '../applications/types';
import { handleError } from '../services/api/helpers';
import { getTabIdMatchingURL } from '../tabs/selectors';
import { StationState, StationStore } from '../types';
import { DEFAULT_BROWSER, NEW_TAB, NEW_WINDOW, Targets } from './constants';
import {
ApplicationConnectionNode,
ApplicationItem,
ParsedURL,
RoutingOrigin,
URLRouterAction,
URLRouterActionAndDestination,
} from './types';
const normalizeURL = (url:string): string => new NodeURL(url).toString();
/* TODO Next Steps
- add `radix-router` typing
- Use `radix-router` even for `isInScope` and `findInInstalledScopes`
- For this, listen to `getApplications` updates and create a second `scopesRadix` for installed apps
- We should not need `manifestProvider` anymore (dataRouter + getApplications should be enough)
- `buildScopesRadix` should not create the full radix tree from scratch each time its updated
*/
export default class URLRouter {
public dataRouter: BehaviorSubject<ApplicationItem[] | null>;
private getState: StationStore['getState'];
private manifestProvider: ManifestProvider;
private scopesRadix: any;
constructor(getState: StationStore['getState'], manifestProvider: ManifestProvider) {
this.getState = getState;
this.dataRouter = new BehaviorSubject(null);
this.manifestProvider = manifestProvider;
// Observe all potential app scopes and build a tree when it arrives
this.dataRouter.subscribe((data) => {
this.scopesRadix = this.buildScopesRadix(data);
});
}
get state(): StationState {
return this.getState();
}
public async routeURL(
url: string,
origin?: RoutingOrigin,
options: { target?: Targets, forceCaptive?: boolean } = {}
): Promise<URLRouterActionAndDestination> {
// Handy re-usable checks
const newTab = options.target === NEW_TAB;
const newWindow = options.target === NEW_WINDOW;
const defaultBrowser = options.target === DEFAULT_BROWSER;
if (defaultBrowser) {
return [URLRouterAction.DEFAULT_BROWSER, null];
}
try {
// Station tabs
const match = this.hasMatchingTab(url);
if (match) {
if (match.type === 'exact') {
return (origin && origin.tabId === match.tabId)
? [URLRouterAction.RELOAD, { tabId: match.tabId }]
: [URLRouterAction.NAV_TO_TAB, { tabId: match.tabId }];
}
return [URLRouterAction.PUSH_AND_NAV_TO_TAB, { tabId: match.tabId }];
}
// Scope
if (origin && await this.isInScope(url, origin)) {
// Decide where to open
if (newTab) return [URLRouterAction.NEW_TAB, origin];
if (newWindow) return [URLRouterAction.NEW_WINDOW, origin];
return [URLRouterAction.NAV_IN_TAB, origin];
}
// Deeplink
const application = await this.findApplicationInInstalledScopes(url);
if (application) {
const applicationId = getApplicationId(application);
return (newWindow)
? [URLRouterAction.NEW_WINDOW, { applicationId }]
: [URLRouterAction.NEW_TAB, { applicationId }];
}
// Others
const manifestURL = this.findInAllScopes(url);
if (manifestURL) {
return [URLRouterAction.INSTALL_AND_OPEN, { manifestURL }];
}
} catch (err) {
console.warn('URL Router : routing failed, redirecting to browser');
handleError()(err);
}
// URL not handled by anyone
return [URLRouterAction.DEFAULT_BROWSER, null];
}
// SCOPES
/**
* Checks if the given URL is covered by the scopes of the current app
* (the one from which emanate the routing call).
* @param url URL to check against the current scopes
* @param origin Params describing the origin of the routing call
*/
async isInScope(url: string, origin: RoutingOrigin = {}) {
if (!origin.applicationId) return false;
const app = getApplicationById(this.state, origin.applicationId);
if (!app) return false;
const scopes = await this.getScopes(app);
return this.searchScopes(url, scopes);
}
/**
* Search if the given URL is covered by any of the already installed app scopes in Station
* and returns its ID if one is found.
* @param url URL to check against all the installed scopes
*/
async findApplicationInInstalledScopes(url: string): Promise<ApplicationImmutable | null> {
const allApps: ApplicationImmutable[] = getApplications(this.state).toArray();
const appsWithCustomUrls: ApplicationImmutable[] = allApps.filter(app => !!getApplicationCustomURL(app));
const appsWithoutCustomUrls: ApplicationImmutable[] = allApps.filter(app => !getApplicationCustomURL(app));
const apps = [...appsWithCustomUrls, ...appsWithoutCustomUrls];
for (const app of apps) {
const scopes = await this.getScopes(app);
if (this.searchScopes(url, scopes)) return app;
}
return null;
}
/**
* Search if the given url is covered by any of the available scopes in the GraphQL API (App Store)
* and returns its manifestURL if one is found. It also checks if the user opted out to install this app.
* @param url URL to check against all the available scopes
*/
findInAllScopes(url: string) {
const urlPath = this.toRadixPath(url);
if (!urlPath) return null;
const result = this.scopesRadix.lookup(urlPath);
if (result) {
const { manifestURL } = result.data;
const optedOut = isNotInstallableApplication(this.state, manifestURL);
if (!optedOut) return manifestURL;
}
return null;
}
// INTERNALS
searchScopes(rawUrl: string, scopes: string[] | undefined) {
if (!scopes || !rawUrl) return false;
const url = this.parseUrl(rawUrl);
if (!url) return false;
// Search at least one scope that could match the url
return scopes.some((rawScope: string) => {
const scope = this.parseUrl(rawScope);
if (!scope) return false;
return this.matchScope(url, scope);
});
}
buildScopesRadix(data: ApplicationItem[] | null) {
const radix = new RadixRouter();
if (!data || data.length === 0) return radix;
data.map(item => {
// Insert scope path into the tree
if (item.manifest.scope) {
this.tryInsertRadixPath(radix, item, item.manifest.scope);
}
// Insert all extended scopes into the tree
if (item.manifest.extended_scopes) {
for (const scope of item.manifest.extended_scopes) {
this.tryInsertRadixPath(radix, item, scope);
}
}
});
return radix;
}
// UTILS
private tryInsertRadixPath(radix: any, item: ApplicationConnectionNode['node'], scope: string) {
try {
const path = this.toRadixPath(scope);
const radixObject = {
data: {
manifestURL: item.bxAppManifestURL,
name: item.name,
},
};
radix.insert({
path, // because wildcard does not match with root url (e.g. https://getstation.com)
...radixObject,
});
radix.insert({
path: `${path}/**`,
...radixObject,
});
} catch (e) {
handleError()(e, {
metaData: {
scope,
manifestURL: item.bxAppManifestURL,
},
});
}
}
private matchScope(url: ParsedURL, scope: ParsedURL): boolean {
const matchingSubdomains = (
url.subdomain === scope.subdomain
|| (url.subdomain === '*' && Boolean(scope.subdomain))
|| (Boolean(url.subdomain) && scope.subdomain === '*')
);
const matchingPathname = (
!Boolean(scope.pathname)
|| (Boolean(url.pathname) && url.pathname!.startsWith(scope.pathname!))
);
return (
url.protocol === scope.protocol
&& url.domain === scope.domain
&& url.port === scope.port
&& matchingSubdomains
&& matchingPathname
);
}
private parseUrl(rawUrl: string): ParsedURL | undefined {
if (!rawUrl) return undefined;
// URL module in browser escapes some characters, that NodeJS 'url' module don't
const url = new NodeURL(rawUrl);
const splitHostname = url.hostname.split('.');
const hostname = (splitHostname.length === 3)
? { subdomain: splitHostname.shift(), domain: splitHostname.join('.') }
: { subdomain: null, domain: url.hostname };
return {
protocol: url.protocol,
subdomain: hostname.subdomain,
domain: hostname.domain,
port: isBlank(url.port) ? null : url.port,
pathname: url.pathname,
};
}
private toRadixPath(rawUrl: any) {
const parsed = this.parseUrl(rawUrl);
if (!parsed) return undefined;
// If subdomain is a wildcard, create a path placeholder sink
const subdomain = (parsed.subdomain === '*') ? ':subdomain' : parsed.subdomain;
const pathname = (!parsed.pathname || parsed.pathname === '/') ? '' : parsed.pathname;
// Build a path like : /http/google/null/www/a/b/c/**
return `/${parsed.protocol}/${parsed.domain}/${parsed.port}/${subdomain}${pathname}`;
}
private hasMatchingTab(url: string) {
return getTabIdMatchingURL(this.state, url);
}
// Gather all the scopes (+ extended scopes) recorded in the manifest of an App
private async getScopes(app: ApplicationImmutable) {
const manifestURL = getApplicationManifestURL(app);
const applicationId = getApplicationId(app);
const bxApp = await this.manifestProvider.getFirstValue(manifestURL);
if (!bxApp || !bxApp.manifest || !bxApp.manifest.scope) return undefined;
// Split the scopes and gather the extended scopes
const scopes = bxApp.manifest.scope.split(',');
const extendedScope = (bxApp.manifest.extended_scopes) ? bxApp.manifest.extended_scopes : [];
// Add customScopes (on-premise configuration)
const customURLs = getApplicationCustomURLsWithApplicationId(this.getState(), applicationId);
const customScopes = customURLs.map(normalizeURL);
// Mix everything
return uniq([...customScopes, ...scopes, ...extendedScope]);
}
} | the_stack |
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { DownloadService } from './../../../shared/services/download.service';
import { CommonResponseService } from '../../../shared/services/common-response.service';
import { AssetGroupObservableService } from '../../../core/services/asset-group-observable.service';
import { AutorefreshService } from '../../services/autorefresh.service';
import { environment } from './../../../../environments/environment';
import { LoggerService } from '../../../shared/services/logger.service';
import { ErrorHandlingService } from '../../../shared/services/error-handling.service';
import { ToastObservableService } from '../../../post-login-app/common/services/toast-observable.service';
import { RefactorFieldsService } from '../../../shared/services/refactor-fields.service';
@Component({
selector: 'app-all-certificate-table',
templateUrl: './all-certificate-table.component.html',
styleUrls: ['./all-certificate-table.component.css'],
providers: [CommonResponseService, AutorefreshService]
})
export class AllCertificateTableComponent implements OnInit, OnDestroy {
public somedata: any;
public outerArr: any;
public allColumns: any;
selectedAssetGroup: string;
public apiData: any;
public applicationValue: any;
public errorMessage: any;
public dataComing = true;
public showLoader = true;
public tableHeaderData: any;
pageTitle = 'All Certificates';
private subscriptionToAssetGroup: Subscription;
private dataSubscription: Subscription;
private downloadSubscription: Subscription;
public seekdata = false;
durationParams: any;
autoRefresh: boolean;
paginatorSize = 10;
totalRows = 0;
dataTableData: any = [];
tableDataLoaded = false;
bucketNumber = 0;
popRows: any = ['Download Data'];
currentBucket: any = [];
firstPaginator = 1;
lastPaginator: number;
currentPointer = 0;
errorValue = 0;
searchTxt = '';
showGenericMessage = false;
constructor( private commonResponseService: CommonResponseService,
private assetGroupObservableService: AssetGroupObservableService,
private autorefreshService: AutorefreshService,
private logger: LoggerService,
private errorHandling: ErrorHandlingService,
private downloadService: DownloadService,
private toastObservableService: ToastObservableService,
private refactorFieldsService: RefactorFieldsService ) {
this.subscriptionToAssetGroup = this.assetGroupObservableService.getAssetGroup().subscribe(
assetGroupName => {
this.selectedAssetGroup = assetGroupName;
this.updateComponent();
});
this.durationParams = this.autorefreshService.getDuration();
this.durationParams = parseInt(this.durationParams, 10);
this.autoRefresh = this.autorefreshService.autoRefresh;
}
ngOnInit() {
// this.updateComponent();
}
updateComponent() {
/* All functions variables which are required to be set for component to be reloaded should go here */
this.outerArr = [];
this.searchTxt = '';
this.currentBucket = [];
this.bucketNumber = 0;
this.firstPaginator = 1;
this.currentPointer = 0;
this.dataTableData = [];
this.tableDataLoaded = false;
this.showLoader = true;
this.dataComing = false;
this.seekdata = false;
this.errorValue = 0;
this.showGenericMessage = false;
this.getData();
}
getData() {
if (this.selectedAssetGroup !== undefined) {
/* All functions to get data should go here */
this.getAllPatchingDetails();
}
}
getAllPatchingDetails() {
if (this.dataSubscription) {
this.dataSubscription.unsubscribe();
}
const payload = {
'ag': this.selectedAssetGroup,
'filter': {},
'from': (this.bucketNumber) * this.paginatorSize,
'searchtext': this.searchTxt,
'size': this.paginatorSize
};
this.errorValue = 0;
const allcertificateTableUrl = environment.certificateTable.url;
const allcertificateTableMethod = environment.certificateTable.method;
this.dataSubscription = this.commonResponseService.getData( allcertificateTableUrl, allcertificateTableMethod, payload, {}).subscribe(
response => {
this.showGenericMessage = false;
try {
this.errorValue = 1;
this.showLoader = false;
this.tableDataLoaded = true;
this.seekdata = false;
this.dataTableData = response.data.response;
this.dataComing = true;
if (response.data.response.length === 0) {
this.errorValue = -1;
this.outerArr = [];
this.allColumns = [];
this.totalRows = 0;
}
if (response.data.response.length > 0) {
this.totalRows = response.data.total;
this.firstPaginator = (this.bucketNumber * this.paginatorSize) + 1;
this.lastPaginator = (this.bucketNumber * this.paginatorSize) + this.paginatorSize;
this.currentPointer = this.bucketNumber;
if (this.lastPaginator > this.totalRows) {
this.lastPaginator = this.totalRows;
}
const updatedResponse = this.massageData(response.data.response);
this.currentBucket[this.bucketNumber] = updatedResponse;
this.processData(updatedResponse);
}
} catch (e) {
this.errorValue = 0;
this.errorMessage = this.errorHandling.handleJavascriptError(e);
this.getErrorValues();
}
},
error => {
this.showGenericMessage = true;
this.errorMessage = error;
this.getErrorValues();
});
}
getErrorValues(): void {
this.errorValue = -1;
this.showLoader = false;
this.dataComing = false;
this.seekdata = true;
}
massageData(data) {
/*
* added by Trinanjan 14/02/2017
* the funciton replaces keys of the table header data to a readable format
*/
const refactoredService = this.refactorFieldsService;
const newData = [];
data.map(function(rowObj) {
const KeysTobeChanged = Object.keys(rowObj);
let newObj = {};
KeysTobeChanged.forEach(element => {
const elementnew =
refactoredService.getDisplayNameForAKey(element.toLocaleLowerCase()) || element;
newObj = Object.assign(newObj, { [elementnew]: rowObj[element] });
});
newData.push(newObj);
});
return newData;
}
processData(data) {
let innerArr = {};
const totalVariablesObj = {};
let cellObj = {};
this.outerArr = [];
const datainString = JSON.stringify(data);
const getData = JSON.parse(datainString);
const getCols = Object.keys(getData[0]);
for (let row = 0 ; row < getData.length ; row++) {
innerArr = {};
for (let col = 0; col < getCols.length; col++) {
if (getCols[col].toLowerCase() === 'expiringin' || getCols[col].toLowerCase() === 'expiring in') {
cellObj = {
'link': '',
'properties':
{
'color': ''
},
'colName': getCols[col],
'hasPreImg': false,
'imgLink': '',
'text': getData[row][getCols[col]],
'valText': parseInt(getData[row][getCols[col]], 10)
};
} else if (getCols[col].toLowerCase() === 'validfrom' || getCols[col].toLowerCase() === 'valid from' || getCols[col].toLowerCase() === 'validuntil' || getCols[col].toLowerCase() === 'valid until' ) {
cellObj = {
'link': '',
'properties':
{
'color': ''
},
'colName': getCols[col],
'hasPreImg': false,
'imgLink': '',
'text': this.calculateDate(getData[row][getCols[col]]),
'valText': (new Date(getData[row][getCols[col]])).getTime()
};
} else {
cellObj = {
'link': '',
'properties':
{
'color': ''
},
'colName': getCols[col],
'hasPreImg': false,
'imgLink': '',
'text': getData[row][getCols[col]],
'valText': getData[row][getCols[col]]
};
}
// innerArr.push(cellObj);
innerArr[getCols[col]] = cellObj;
totalVariablesObj[getCols[col]] = '';
}
this.outerArr.push(innerArr);
}
if (this.outerArr.length > getData.length) {
const halfLength = this.outerArr.length / 2;
this.outerArr = this.outerArr.splice(halfLength);
}
this.allColumns = Object.keys(totalVariablesObj);
}
calculateDate(_JSDate) {
if (!_JSDate) {
return 'No Data';
}
const date = new Date(_JSDate);
const year = date.getFullYear().toString();
const month = date.getMonth() + 1;
let monthString;
if (month < 10) {
monthString = '0' + month.toString();
} else {
monthString = month.toString();
}
const day = date.getDate();
let dayString;
if (day < 10) {
dayString = '0' + day.toString();
} else {
dayString = day.toString();
}
return monthString + '-' + dayString + '-' + year ;
}
prevPg() {
this.currentPointer--;
this.processData(this.currentBucket[this.currentPointer]);
this.firstPaginator = (this.currentPointer * this.paginatorSize) + 1;
this.lastPaginator = (this.currentPointer * this.paginatorSize) + this.paginatorSize;
}
nextPg() {
if (this.currentPointer < this.bucketNumber) {
this.currentPointer++;
this.processData(this.currentBucket[this.currentPointer]);
this.firstPaginator = (this.currentPointer * this.paginatorSize) + 1;
this.lastPaginator = (this.currentPointer * this.paginatorSize) + this.paginatorSize;
if (this.lastPaginator > this.totalRows) {
this.lastPaginator = this.totalRows;
}
} else {
this.bucketNumber++;
this.getData();
}
}
handlePopClick(rowText) {
const fileType = 'csv';
try {
let queryParams;
queryParams = {
'fileFormat': 'csv',
'serviceId': 5,
'fileType': fileType
};
const downloadRequest = {
'ag': this.selectedAssetGroup,
'filter': {},
'from': 0,
'searchtext': this.searchTxt,
'size': this.totalRows
};
const downloadUrl = environment.download.url;
const downloadMethod = environment.download.method;
this.downloadService.requestForDownload(
queryParams,
downloadUrl,
downloadMethod,
downloadRequest,
this.pageTitle,
this.totalRows);
} catch (error) {
this.logger.log('error', error);
}
}
searchCalled(search) {
this.searchTxt = search;
}
callNewSearch() {
this.bucketNumber = 0;
this.currentBucket = [];
this.getData();
}
ngOnDestroy() {
try {
this.subscriptionToAssetGroup.unsubscribe();
this.dataSubscription.unsubscribe();
} catch (error) {
this.errorMessage = this.errorHandling.handleJavascriptError(error);
this.getErrorValues();
}
}
} | the_stack |
import {
HVal,
NOT_SUPPORTED_IN_FILTER_MSG,
CANNOT_CHANGE_READONLY_VALUE,
isHVal,
valueIsKind,
valueEquals,
OptionalHVal,
ZINC_NULL,
} from './HVal'
import { HDict, DictStore, HValObj } from './HDict'
import { Kind } from './Kind'
import { HaysonGrid, HaysonDict } from './hayson'
import { HStr } from './HStr'
import { HFilter } from '../filter/HFilter'
import { Node, isNode } from '../filter/Node'
import { HList } from './HList'
import { makeValue } from './util'
import { HRef } from './HRef'
import { EvalContext, EvalContextResolve } from '../filter/EvalContext'
/**
* The default grid version number.
*/
export const DEFAULT_GRID_VERSION = '3.0'
/**
* Returns the zinc for the meta data.
*
* @param meta The meta data dict.
* @returns The zinc used for meta data in a grid.
*/
function toMetaZinc(meta: HDict): string {
const zinc = meta.toZinc()
// Remove the braces from the dict zinc encoding
return zinc.substring(1, zinc.length - 1)
}
/**
* A grid column.
*/
export class GridColumn {
/**
* Inner name of the column.
*/
private $name: string
/**
* Inner meta data for the column.
*/
private $meta: HDict
/**
* Constructs a new column.
*
* @param name The name of the column.
* @param meta The column's meta data.
*/
public constructor(name: string, meta?: HDict) {
this.$name = name
this.$meta = meta || HDict.make()
}
/**
* @returns The column's name.
*/
public get name(): string {
return this.$name
}
public set name(name: string) {
throw new Error(CANNOT_CHANGE_READONLY_VALUE)
}
/**
* @returns The column's meta data.
*/
public get meta(): HDict {
return this.$meta
}
public set meta(meta: HDict) {
throw new Error(CANNOT_CHANGE_READONLY_VALUE)
}
/**
* @returns The display name for the column.
*/
public get dis(): string {
const dis = this.meta.get('dis')
return (valueIsKind<HStr>(dis, Kind.Str) && dis.value) || this.name
}
/**
* @returns The display name for the column.
*/
public get displayName(): string {
return this.dis
}
/**
* Column equality check.
*
* @param column The column to test.
* @returns True if the value is the same.
*/
public equals(column: GridColumn): boolean {
if (!isGridColumn(column)) {
return false
}
if (column.name !== this.$name) {
return false
}
if (!column.meta.equals(this.$meta)) {
return false
}
return true
}
/**
* Flag used to identify a grid column.
*/
public readonly _isAGridColumn = true
}
function isGridColumn(val: unknown): val is GridColumn {
return !!(val && (val as GridColumn)._isAGridColumn)
}
/**
* A dict store for a row in a grid.
*
* This is used as the backing store for a dict (row) held in a grid. The dict itself
* requires a reference to its parent grid. It wraps the inner Dict used to store the actual
* row data.
*
* When a grid is filtered, this inner dict is reused across grids to maximize memory usage.
*/
class GridRowDictStore<DictVal extends HDict> implements DictStore {
/**
* A reference to the outer grid instance.
*/
private readonly $grid: HGrid
/**
* The inner dict that holds the data.
*/
private readonly $cells: DictVal
public constructor(grid: HGrid, cells: DictVal) {
this.$grid = grid
this.$cells = cells
}
public get(name: string): HVal | undefined | null {
return this.$cells.get(name)
}
public set(name: string, value: OptionalHVal): void {
// The column to the grid if it's missing.
if (!this.$grid.hasColumn(name)) {
this.$grid.addColumn(name)
}
this.$cells.set(name, value)
}
public remove(name: string): void {
this.$cells.remove(name)
}
public clear(): void {
this.$cells.clear()
}
public getKeys(): string[] {
return this.$cells.keys
}
public toObj(): HValObj {
return this.$cells.toObj()
}
}
/**
* An iterator for dicts.
*/
export class GridDictIterator<DictVal extends HDict>
implements Iterator<DictVal> {
private readonly $grid: HGrid
private $index = 0
public constructor(grid: HGrid) {
this.$grid = grid
}
public next(): IteratorResult<DictVal> {
const dict = this.$grid.get(this.$index++)
return {
done: !dict,
value: dict ? (dict as DictVal) : (HDict.make() as DictVal),
}
}
}
/**
* Implements the storage for an HGrid.
*
* This separates the HGrid interface from the actual storage,
* which could be backed by a native one
*/
class GridStore<DictVal extends HDict> {
/**
* The internal grid's meta data.
*/
private $meta: HDict
/**
* The internal grid's columns.
*/
private $columns: GridColumn[]
/**
* An internal column index cache.
*
* This is used to increase the performance of column name look ups.
*/
private $columnNameCache: { [prop: string]: number }
/**
* The internal cached rows.
*/
private $rows: DictVal[]
public constructor(meta: HDict, columns: GridColumn[], rows: DictVal[]) {
this.$columnNameCache = {}
this.$meta = meta
this.$columns = columns
this.$rows = rows
this.rebuildColumnCache()
}
/**
* The stores's meta data.
*/
public get meta(): HDict {
return this.$meta
}
/**
* True if store has the column
* @param name - the column name
*/
public hasColumn(name: string): boolean {
return this.$columnNameCache[name] !== undefined
}
/**
* The stores's columns.
*/
public get columns(): GridColumn[] {
return this.$columns
}
/**
* Sets a column for this store
*/
public setColumn(index: number, column: GridColumn): void {
this.$columns[index] = column
this.$columnNameCache[column.name] = index
}
/**
* Returns a store column via its name or index number. If it can't be found
* then return undefined.
*/
public getColumn(index: number | string): GridColumn | undefined {
let column: GridColumn | undefined
if (typeof index === 'number') {
column = this.$columns[index as number]
} else if (typeof index === 'string') {
const i = this.$columnNameCache[index]
if (i !== undefined) {
column = this.$columns[i]
}
} else {
throw new Error('Invalid input')
}
return column
}
public addColumn(name: string, meta: HDict | undefined): GridColumn {
const index = this.$columnNameCache[name]
const col = new GridColumn(name, meta || HDict.make())
// If the column already exists then just update it.
if (typeof index === 'number') {
this.setColumn(index, col)
return col
} else {
this.$columns.push(col)
this.rebuildColumnCache()
return col
}
}
/**
* Reorder the columns with the specified new order of names.
*/
public reorderColumns(colNames: string[]): void {
this.$columns = this.$columns.sort((first, second): number => {
let firstIndex = 0
let secondIndex = 0
for (let i = 0; i < colNames.length; ++i) {
if (colNames[i] === first.name) {
firstIndex = i
}
if (colNames[i] === second.name) {
secondIndex = i
}
}
return firstIndex - secondIndex
})
this.rebuildColumnCache()
}
/**
* Rebuilds the store's column cache
*/
public rebuildColumnCache(): void {
for (const key of Object.keys(this.$columnNameCache)) {
delete this.$columnNameCache[key]
}
for (let i = 0; i < this.$columns.length; ++i) {
this.$columnNameCache[this.$columns[i].name] = i
}
}
/**
* Get the row by index
* @param index the index of the row
*/
public get(index: number): DictVal | undefined {
return this.$rows[index]
}
/**
* The store's rows.
*/
public get rows(): DictVal[] {
return this.$rows
}
public size(): number {
return this.$rows ? this.$rows.length : 0
}
}
export interface GridObj<DictVal extends HDict = HDict> {
meta?: HDict
columns?: { name: string; meta?: HDict }[]
rows?: DictVal[]
version?: string
}
/**
* A haystack grid.
*
* ```typescript
* const grid = new HGrid({
* columns: [
* {
* name: 'name'
* },
* {
* name: 'height'
* }
* ],
* // rows
* rows: [
* new HDict({ name: HStr.make('Mall'), height: HNum.make(200, 'm') }),
* new HDict({ name: HStr.make('House'), height: HNum.make(30, 'm') })
* ]
* })
*
* // The same grid can be specified without any rows. The columns will be dynamically
* // generated based upon the row data...
* const grid0 = new HGrid({
* rows: [
* new HDict({ name: HStr.make('Mall'), height: HNum.make(200, 'm') }),
* new HDict({ name: HStr.make('House'), height: HNum.make(30, 'm') })
* ]
* })
*
* // The same grid can be created from a Hayson object.
* // Again columns don't have to be specified unless precise order and meta data is required...
* const grid1 = new HGrid({
* rows: [
* { name: 'Mall', height: { _kind: 'number', val: 200, unit: 'm' } },
* { name: 'House', height: { _kind: 'number', val: 30, unit: 'm' } },
* ]
* })
*
* // Iterate a grid
* for (let dict of grid) {
* console.log(dict)
* }
*
* // Filter a grid
* const filteredGrid = grid.filter('name == "House"')
* console.log(filteredGrid)
*
* // Test a grid
* if (grid.has('name == "House"')) {
* console.log('Found house!')
* }
*
* // Remove items from a grid
* grid.remove('name == "Mall"')
*
* // Average, sum, max and min...
* console.log(grid.avgOf('height'))
* console.log(grid.sumOf('height'))
* console.log(grid.maxOf('height'))
* console.log(grid.minOf('height'))
* ```
*/
export class HGrid<DictVal extends HDict = HDict>
implements HVal, Iterable<DictVal> {
/**
* The grid's version number.
*/
public version: string
/**
* The internal grid storage.
*/
private readonly $store: GridStore<DictVal>;
/**
* Numerical index access.
*/
[prop: number]: DictVal | undefined
/**
* Constructs a new grid.
*
* ```typescript
* const grid = new HGrid({
* columns: [
* {
* name: 'name'
* },
* {
* name: 'height'
* }
* ],
* // rows
* rows: [
* new HDict({ name: HStr.make('Mall'), height: HNum.make(200, 'm') }),
* new HDict({ name: HStr.make('House'), height: HNum.make(30, 'm') })
* ]
* })
*
* // The same grid can be specified without any rows. The columns will be dynamically
* // generated based upon the row data...
* const grid0 = new HGrid({
* rows: [
* new HDict({ name: HStr.make('Mall'), height: HNum.make(200, 'm') }),
* new HDict({ name: HStr.make('House'), height: HNum.make(30, 'm') })
* ]
* })
*
* // The same grid can be created from a Hayson object.
* // Again columns don't have to be specified unless precise order and meta data is required...
* const grid1 = new HGrid({
* rows: [
* { name: 'Mall', height: { _kind: 'number', val: 200, unit: 'm' } },
* { name: 'House', height: { _kind: 'number', val: 30, unit: 'm' } },
* ]
* })
*
* // Pass in a haystack value to create a grid...
* const grid3 = new HGrid(HNum.make(24)) // Creates a grid with one column called 'val' and one row.
*
* // Pass in an array of dicts to create a grid...
* const grid4 = new HGrid([
* new HDict({ name: HStr.make('Mall'), height: HNum.make(200, 'm') }),
* new HDict({ name: HStr.make('House'), height: HNum.make(30, 'm') })
* ])
*
* // Pass in an array of Hayson dicts to create a grid...
* const grid5 = new HGrid([
* { name: 'Mall', height: { _kind: 'number', val: 200, unit: 'm' } },
* { name: 'House', height: { _kind: 'number', val: 30, unit: 'm' } },
* ])
* ```
*
* @param value The values used to create a grid.
* @param skipChecks This flag should be only used internally. If true then any error
* checking on dicts is skipped. This is useful when we already know the dict being added
* is valid.
*/
public constructor(
arg?: GridObj<DictVal> | HaysonGrid | HVal | (HaysonDict | DictVal)[],
skipChecks = false
) {
let meta: HDict | undefined
let columns: { name: string; meta?: HDict }[] | undefined
let rows: DictVal[] | HaysonDict[] | undefined
let version = DEFAULT_GRID_VERSION
const value = arg as
| GridObj<DictVal>
| HaysonGrid
| HVal
| (HaysonDict | DictVal)[]
| undefined
| null
if (value === undefined) {
rows = []
} else if (isHVal(value) || value === null) {
// Don't skip any column checks when we pass in haystack values
// since we need the columns to be automatically generated for us.
skipChecks = false
if (valueIsKind<HGrid<DictVal>>(value, Kind.Grid)) {
meta = value.meta
columns = value.getColumns()
rows = value.getRows()
version = value.version
} else if (valueIsKind<HDict>(value, Kind.Dict)) {
rows = [value] as DictVal[]
} else {
rows = [HDict.make({ val: value }) as DictVal]
}
} else if (Array.isArray(value)) {
rows = value.map(
(dict: HaysonDict | DictVal): DictVal =>
HDict.make(dict) as DictVal
) as DictVal[]
} else {
if (value.meta) {
meta = makeValue(value.meta) as HDict
}
if ((value as GridObj).columns) {
columns = (value as GridObj).columns || []
} else if ((value as HaysonGrid).cols) {
const obj = value as HaysonGrid
if (obj.cols) {
columns = obj.cols.map((col): {
name: string
meta?: HDict
} => ({
name: col.name,
meta: col.meta
? (makeValue(col.meta) as HDict)
: undefined,
}))
}
}
// Both HaysonGrid and GridObj share a rows iterator property.
if ((value as GridObj).rows) {
rows = (value as GridObj<DictVal>).rows || []
}
if ((value as GridObj).version) {
version =
(value as GridObj<DictVal>).version || DEFAULT_GRID_VERSION
}
}
meta = meta ?? HDict.make()
columns = columns ?? []
rows = rows ?? []
for (let i = 0; i < rows.length; ++i) {
rows[i] = makeValue(rows[i]) as DictVal
}
this.version = version
this.$store = new GridStore(
meta,
columns.map(
(column): GridColumn => new GridColumn(column.name, column.meta)
),
skipChecks ? (rows as DictVal[]) : []
)
// If we're check each row then create the grid and add each dict.
// Adding in this way enforces error checking on each row.
if (!skipChecks) {
for (const dict of rows) {
this.add(makeValue(dict) as DictVal)
}
}
return this.makeProxy()
}
/**
* Implement proxy to make it easy to get and set internal values.
*/
private makeProxy(): HGrid<DictVal> {
const handler = {
get: function (target: HGrid, prop: string): any {
const anyTarget = target as any
return typeof prop === 'string' && /^[0-9]+$/.test(prop)
? target.get(Number(prop))
: (anyTarget[prop] as any)
},
set(target: HGrid, prop: string, value: any): boolean {
const anyTarget = target as any
if (typeof prop === 'string' && /^[0-9]+$/.test(prop)) {
target.set(Number(prop), value)
} else {
anyTarget[prop] = value
}
return true
},
}
return new Proxy(this, handler) as HGrid<DictVal>
}
/**
* Makes a new grid.
*
* @param value The values used to create a grid.
* @param skipChecks This flag should be only used internally. If true then any error
* checking on dicts is skipped. This is useful when we already know the dict being added
* is valid.
* @returns A grid.
*/
public static make<DictVal extends HDict = HDict>(
arg?: GridObj<DictVal> | HaysonGrid | HVal | (HaysonDict | DictVal)[],
skipChecks = false
): HGrid<DictVal> {
return valueIsKind<HGrid<DictVal>>(arg, Kind.Grid)
? arg
: new HGrid(arg, skipChecks)
}
/**
* The grid's meta data.
*/
public get meta(): HDict {
return this.$store.meta
}
/**
* @returns The value's kind.
*/
public getKind(): Kind {
return Kind.Grid
}
/**
* Compares the value's kind.
*
* @param kind The kind to compare against.
* @returns True if the kind matches.
*/
public isKind(kind: Kind): boolean {
return valueIsKind<HGrid>(this, kind)
}
/**
* @returns A JSON reprentation of the object.
*/
public toJSON(): HaysonGrid {
const rows = this.getRows().map(
(row: DictVal): HaysonDict => {
this.addMissingColumns(row)
return row.toJSON()
}
)
return {
_kind: this.getKind(),
meta: {
ver: this.version,
...(this.meta ? this.meta.toJSON() : {}),
},
cols: this.$store.columns.map((column: GridColumn): {
name: string
meta: HaysonDict
} => ({
name: column.name,
meta: column.meta.toJSON(),
})),
rows,
}
}
/**
* Encodes to an encoded zinc value that can be used
* in a haystack filter string.
*
* A grid isn't supported in filter so throw an error.
*
* @returns The encoded value that can be used in a haystack filter.
*/
public toFilter(): string {
throw new Error(NOT_SUPPORTED_IN_FILTER_MSG)
}
/**
* Encodes to an encoding zinc value.
*
* @param nested An optional flag used to indiciate whether the
* value being encoded is nested.
* @returns The encoded zinc string.
*/
public toZinc(nested?: boolean): string {
// Check whether we need to add any missing columns. We need to do this
// as a developer could have adding a new dict to the grid's internal rows array.
// Therefore we need lazily make sure we have all the correct columns in place for
// the grid to be valid.
const rows = this.getRows()
rows.forEach((dict: DictVal): void => this.addMissingColumns(dict))
let zinc = nested ? '<<\n' : ''
// Header and version
zinc += `ver:${HStr.make(this.version).toZinc()}`
// Meta
const metaZinc = toMetaZinc(this.meta)
if (metaZinc) {
zinc += ` ${metaZinc}`
}
zinc += '\n'
// Columns
if (!rows.length && !this.$store.columns.length) {
zinc += 'empty\n'
} else {
zinc +=
this.$store.columns
.map((col: GridColumn): string => {
let colZinc = col.name
const metaZinc = toMetaZinc(col.meta)
if (metaZinc) {
colZinc += ` ${metaZinc}`
}
return colZinc
})
.join(',') + '\n'
}
// Rows
zinc +=
rows
.map((row: DictVal): string =>
this.$store.columns
.map((col, index: number): string => {
const val = row.get(col.name)
return (
(index > 0 ? ',' : '') +
(val === undefined
? ''
: val?.toZinc(/*nested*/ true) ?? ZINC_NULL)
)
})
.join('')
)
.join('\n') + '\n'
if (nested) {
// Footer
zinc += '>>'
}
return zinc
}
/**
* @returns An Axon encoded string.
*/
public toAxon(): string {
let axon = `${HList.make(this.getRows()).toAxon()}.toGrid`
if (!this.meta.isEmpty()) {
axon += `.addMeta(${this.meta.toAxon()})`
}
return axon
}
/**
* Grid equality check.
*
* @param value The value to test.
* @returns True if the value is the same.
*/
public equals(value: unknown): boolean {
if (!valueIsKind<HGrid>(value, Kind.Grid)) {
return false
}
if (this.version !== value.version) {
return false
}
if (!this.meta.equals(value.meta)) {
return false
}
if (this.$store.columns.length !== value.$store.columns.length) {
return false
}
for (let i = 0; i < this.$store.columns.length; ++i) {
if (!this.$store.columns[i].equals(value.$store.columns[i])) {
return false
}
}
if (this.length !== value.length) {
return false
}
for (let i = 0; i < this.length; ++i) {
const row0 = this.get(i)
const row1 = value.get(i)
if (!row0?.equals(row1)) {
return false
}
}
return true
}
/**
* Compares two grids.
*
* @param value The value to compare against.
* @returns The sort order as negative, 0, or positive.
*/
public compareTo(value: unknown): number {
if (!valueIsKind<HGrid>(value, Kind.Grid)) {
return -1
}
const zinc0 = this.toZinc()
const zinc1 = value.toZinc()
if (zinc0 < zinc1) {
return -1
}
if (zinc0 === zinc1) {
return 0
}
return 1
}
/**
* Return all the rows of the grid.
*
* ```typescript
* const anArrayOfDicts = grid.getRows()
* ```
*
* @returns All rows in the grid.
*/
public getRows(): DictVal[] {
return this.$store.rows
}
/**
* Return a row or undefined if it can't find it via its
* row number.
*
* ```typescript
* // Get a dict at a given index or returned undefined if it can't be found.
* const dict = grid.get(0)
* if (dict) {
* // Do something
* }
* ```
*
* @param index The index number of the row.
* @returns The dict or undefined if it does not exist.
*/
public get(index: number): DictVal | undefined {
this.checkRowIndexNum(index)
return this.$store.get(index)
}
/**
* Return the first row in the grid or undefined if it can't be found.
*
* ```typescript
* const dict = grid.first
* if (dict) {
* // Do something
* }
* ```
*
* @returns The dict or undefined if it does not exist.
*/
public get first(): DictVal | undefined {
return this.get(0)
}
/**
* Return the last row in the grid or undefined if it can't be found.
*
* ```typescript
* const dict = grid.last
* if (dict) {
* // Do something
* }
* ```
*
* @returns The dict or undefined if it does not exist.
*/
public get last(): DictVal | undefined {
return this.get(Math.max(0, this.length - 1))
}
/**
* Remove the row from the grid via its index number of a haystack filter.
*
* ```typescript
* // Remove a row via its index
* grid.remove(0)
*
* // Remove multiple rows via a Haystack Filter
* grid.remove('foo == "baa"')
* ```
*
* @param filter A haystack filter, index number or AST node.
* @param cx Optional haystack filter evaluation context.
* @returns The rows that were removed. If no rows were removed then the is empty.
*/
public remove(
filter: number | string | Node,
cx?: Partial<EvalContext>
): DictVal[] {
let removed: DictVal[]
if (typeof filter === 'string' || isNode(filter)) {
removed = []
const toRemove: number[] = []
this.runFilter(
filter as string,
(match: boolean, row: DictVal, index: number): boolean => {
if (match) {
toRemove.push(index)
removed.push(row)
}
// Keep iterating.
return true
},
cx
)
for (let i = toRemove.length - 1; i >= 0; --i) {
this.getRows().splice(toRemove[i], 1)
}
} else {
const index = filter as number
this.checkRowIndexNum(index)
removed = this.getRows().splice(index, 1)
}
return removed
}
/**
* Filter the grid with the haystack filter and return a new grid with the results.
*
* ```typescript
* // Filter a grid with a haystack filter
* const newGridWithFoo = grid.filter('foo')
*
* // Filter a grid with a function callback
* const newGridWithFooAgain = grid.filter((row: HDict): boolean => row.has('foo'))
* ```
*
* @param filter The haystack filter, AST node or filter function callback.
* @param cx Optional haystack filter evaluation context.
* @returns A new filtered grid.
*/
public filter(
filter: string | Node | ((row: DictVal, index: number) => boolean),
cx?: Partial<EvalContext>
): HGrid<DictVal> {
const grid = HGrid.make<DictVal>({
meta: this.meta,
rows: [],
version: this.version,
})
if (typeof filter === 'function') {
for (const row of this.getRows().filter(filter)) {
grid.add(row)
}
} else {
this.runFilter(
filter,
(match: boolean, row: DictVal): boolean => {
if (match) {
grid.add(row)
}
// Keep iterating.
return true
},
cx
)
}
this.syncColumnMeta(grid)
return grid
}
/**
* Synchronize column meta information from this grid to the specified grid.
*
* @param grid The grid to synchronize data to.
*/
private syncColumnMeta(grid: HGrid): void {
for (const col of this.getColumns()) {
const newCol = grid.getColumn(col.name)
if (newCol && !newCol.meta.equals(col.meta)) {
newCol.meta.clear()
newCol.meta.update(col.meta)
}
}
}
/**
* Filters an individual column in a grid.
*
* For example, if a particular column in a grid holds a list.
* The inner filter can be run against all of the list values
* held in that column.
*
* The filter can be run against a list, dict or grid.
*
* ```typescript
* const grid = HGrid.make({
* rows: [
* { list: [ 'foo', 'boo', 'goo' ] },
* { list: [ 'foo', 'boo1', 'goo1' ] },
* { list: [ 'doo', 'boo1', 'goo1' ] },
* ]
* })
*
* // Returns a grid with only the first two rows.
* const newGrid = grid.filterBy('list', 'item == "foo"')
* ```
*
* @param name The name of the column that holds the list values.
* @param innerFilter The haystack filter to run against the list.
* @param cx Optional haystack filter evaluation context.
* @returns A filtered grid.
*/
public filterBy(
name: string,
innerFilter: string | Node,
cx?: Partial<EvalContext>
): HGrid<DictVal> {
// Parse the AST node so we don't need to reparse it each time.
const node =
typeof innerFilter === 'string'
? HFilter.parse(innerFilter)
: innerFilter
cx = {
namespace: cx?.namespace,
resolve: this.makeResolveFunc(),
}
return this.filter((row: DictVal): boolean => {
const val = row.get(name)
if (
valueIsKind<HList>(val, Kind.List) ||
valueIsKind<HGrid>(val, Kind.Grid)
) {
return val.any(node, cx)
} else if (valueIsKind<HDict>(val, Kind.Dict)) {
return val.matches(node, cx)
} else {
return false
}
})
}
/**
* Provide a grid with unique values in the specified columns.
*
* ```typescript
* const grid = HGrid.make({
* rows: [
* { id: 1, name: 'Jason' },
* { id: 2, name: 'Gareth' },
* { id: 3, name: 'Gareth' },
* ]
* })
*
* // Returns a new grid with rows 1 and 2.
* const uniqueGrid = grid.unique('name')
* ```
*
* @param names The column names.
* @returns The filtered grid instance.
*/
public uniqueBy(names: string | string[]): HGrid<DictVal> {
const uniqueNames = Array.isArray(names) ? names : [names]
const grid = HGrid.make<DictVal>({
meta: this.meta,
rows: [],
version: this.version,
})
let rows = this.getRows()
// First filter out any rows that don't have any data.
rows = rows.filter((dict: DictVal): boolean => {
for (const name of uniqueNames) {
if (!dict.has(name)) {
return false
}
}
return true
})
// Filter unique data.
rows = rows.filter((dict: DictVal, index: number): boolean => {
// For each row identify if there are other rows that have the same
// value but a different index.
// The test passes if there are no other rows with the same values.
for (let i = 0; i < index; ++i) {
let duplicates = 0
for (const name of uniqueNames) {
const val0 = dict.get(name)
const val1 = rows[i].get(name)
if (valueEquals(val0, val1)) {
++duplicates
} else {
break
}
}
// If all the rows are duplicates then exclude this result.
if (duplicates === uniqueNames.length) {
return false
}
}
return true
})
// Add all the newly filtered rows to the grid.
if (rows.length) {
grid.add(rows as DictVal[])
this.syncColumnMeta(grid)
}
return grid
}
/**
* Return true if the filter matches at least one row.
*
* ```typescript
* if (grid.any('site')) {
* // The grid has some sites.
* }
* ```
*
* @param filter The haystack filter or AST node.
* @param cx Optional haystack filter evaluation context.
* @returns true if there's at least one match
*/
public any(filter: string | Node, cx?: Partial<EvalContext>): boolean {
let result = false
this.runFilter(
filter,
(match: boolean): boolean => {
if (match) {
result = true
// Stop iterating since we have one match.
return false
}
// Keep iterating.
return true
},
cx
)
return result
}
/**
* Returns true if the haystack filter matches the value.
*
* This is the same as the `any` method.
*
* ```typescript
* if (grid.matches('site')) {
* // The grid has some sites.
* }
* ```
*
* @param filter The filter to test.
* @param cx Optional haystack filter evaluation context.
* @returns True if the filter matches ok.
*/
public matches(filter: string | Node, cx?: Partial<EvalContext>): boolean {
return this.any(filter, cx)
}
/**
* Return true if the filter matches at least one cell
* in a particular column in the grid.
*
* This filter runs on the data held in the particular column.
*
* ```typescript
* const grid = HGrid.make({
* rows: [
* { list: [ 'foo', 'boo', 'goo' ] },
* { list: [ 'foo', 'boo1', 'goo1' ] },
* { list: [ 'doo', 'boo1', 'goo1' ] },
* ]
* })
*
* if (grid.anyBy('list', 'item === "foo"')) {
* // One or more of the items in the list contains 'foo'
* }
* ```
*
* @param filter The haystack filter or AST node.
* @param cx Optional haystack filter evaluation context.
* @returns true if there's at least one match
*/
public anyBy(
name: string,
innerFilter: string | Node,
cx?: Partial<EvalContext>
): boolean {
// Parse the AST node so we don't need to reparse it each time.
const node =
typeof innerFilter === 'string'
? HFilter.parse(innerFilter)
: innerFilter
cx = {
namespace: cx?.namespace,
resolve: this.makeResolveFunc(),
}
for (const row of this) {
const val = row.get(name)
if (
valueIsKind<HList>(val, Kind.List) ||
valueIsKind<HGrid>(val, Kind.Grid)
) {
if (val.any(node, cx)) {
return true
}
} else if (valueIsKind<HDict>(val, Kind.Dict)) {
if (val.matches(node, cx)) {
return true
}
}
}
return false
}
/**
* Return true if the filter matches at least one row.
*
* ```typescript
* const grid = HGrid.make({
* rows: [
* { name: 'Fred' },
* { name: 'Fred' },
* { name: 'Fred' },
* ]
* })
*
* if (grid.all('name == "Fred")) {
* // All rows in the grid have the name Fred.
* }
* ```
*
* @param filter The haystack filter or AST node.
* @param cx Optional haystack filter evaluation context.
* @returns true if there's at least one match
*/
public all(filter: string | Node, cx?: Partial<EvalContext>): boolean {
if (this.isEmpty()) {
return false
}
let result = true
this.runFilter(
filter,
(match: boolean): boolean => {
if (!match) {
result = false
// Stop iterating because the test has failed.
return false
}
// Keep iterating.
return true
},
cx
)
return result
}
/**
* Return true if the filter matches all the values
* in a particular column in the grid.
*
* This filter runs on the data held in the particular column.
*
* ```typescript
* const grid = HGrid.make({
* rows: [
* { list: [ 'foo', 'foo', 'foo' ] },
* { list: [ 'foo', 'foo', 'foo' ] },
* { list: [ 'foo', 'foo', 'foo' ] },
* ]
* })
*
* if (grid.allBy('list', 'item == "foo"')) {
* // True if all the lists contain all foos.
* }
* ```
*
* @param filter The haystack filter or AST node.
* @param cx Optional haystack filter evaluation context.
* @returns true if there's at least one match
*/
public allBy(
name: string,
innerFilter: string | Node,
cx?: Partial<EvalContext>
): boolean {
// Parse the AST node so we don't need to reparse it each time.
const node =
typeof innerFilter === 'string'
? HFilter.parse(innerFilter)
: innerFilter
if (this.isEmpty()) {
return false
}
cx = {
namespace: cx?.namespace,
resolve: this.makeResolveFunc(),
}
for (const row of this) {
const val = row.get(name)
if (
valueIsKind<HList>(val, Kind.List) ||
valueIsKind<HGrid>(val, Kind.Grid)
) {
if (!val.all(node, cx)) {
return false
}
} else if (valueIsKind<HDict>(val, Kind.Dict)) {
if (val.matches(node, cx)) {
return false
}
} else {
return false
}
}
return true
}
/**
* Run the filter. For each match invoke the callback function.
*
* The callback takes a match flag, a row and an index argument. If false is returned
* the filter stops running.
*
* @param filter The haystack filter to run or an AST node.
* @param callback The callback invoked for each match.
* @param cx Optional haystack filter evaluation context.
*/
private runFilter(
filter: string | Node,
callback: (match: boolean, row: DictVal, index: number) => boolean,
cx: Partial<EvalContext> | undefined
): void {
const hfilter = new HFilter(filter)
const context = {
dict: HDict.make(),
resolve: this.makeResolveFunc(),
namespace: cx?.namespace,
}
// Use iterator so we don't have to drain all the rows.
let i = 0
for (const dict of this) {
context.dict = dict
// Run the filter against the row.
// If the callback returns false then stop the filtering.
if (!callback(hfilter.eval(context), dict, i++)) {
break
}
}
}
/**
* Return a function that when called will search for a
* dict (record) via its id.
*
* The method lazily optimizes the request by indexing the grid's id.
*
* @returns The evaluation context resolve method for a grid.
*/
private makeResolveFunc(): EvalContextResolve {
let ids: Map<string, HDict>
return (ref: HRef): HDict | undefined => {
// Lazily build up a map of id refs to records in this grid.
if (!ids) {
ids = new Map()
if (this.hasColumn('id')) {
for (const row of this) {
const id = row.get('id')
if (valueIsKind<HRef>(id, Kind.Ref)) {
ids.set(id.value, row)
}
}
}
}
return ids.get(ref.value)
}
}
/**
* A mapping function that maps from an array of dicts into something else.
*
* ```typescript
* // Map each row to a div using React...
* grid.map((dict: HDict) => <div>{dict.toZinc()}</div>>)
* ```
*
* @param callback A mapping callback that takes a row dict, an index number
* and returns a new value.
*/
public map<U>(callback: (row: DictVal, index: number) => U): U[] {
return this.getRows().map(callback)
}
/**
* Reduce the rows in a grid.
*
* ```typescript
* // Reduce the grid down to one row...
* grid = HGrid.make({
* rows: [
* { a: 1, b: 2 },
* { a: 3, b: 4 },
* ],
* })
*
* grid.reduce((prev, cur): HGrid => {
* const dict = prev.get(0)
*
* if (dict) {
* dict.set('a', Number(cur.get<HNum>('a')?.value) + Number(dict.get<HNum>('a')?.value))
* dict.set('b', Number(cur.get<HNum>('b')?.value) + Number(dict.get<HNum>('b')?.value))
* }
*
* return prev
*}, HGrid.make({ rows: [{ a: 0, b: 0 }] }))
* ```
*
* @param callback The reducer callback. This method will be called with the previous and
* current rows (dicts) as well as the index number.
* @param initialValue Optional initial value for the reduce.
*/
public reduce<U = DictVal>(
callback: (
prev: U,
current: DictVal,
currentIndex: number,
array: DictVal[]
) => U,
initialValue?: U
): U {
return initialValue === undefined
? (this.getRows().reduce(callback as any) as any)
: this.getRows().reduce(callback, initialValue)
}
/**
* ```typescript
* // The number of rows in a grid.
* console.log(grid.length)
* ```
*
* @returns The total number of rows.
*/
public get length(): number {
return this.$store.size()
}
/**
* Set the values or dict for an individual row.
*
* ```typescript
* // Set a row in a grid.
* grid.set(0, new HDict({ foo: HStr.make('foobar') }))
*
* // Set a row via Hayson.
* grid.set(0, { foo: 'foobar' })
* ```
*
* @param index The index number of the row.
* @param values The dict or Hayson Dict.
* @returns The grid instance.
* @throws An error if the index is invalid or the number of rows incorrect.
*/
public set(index: number, values: DictVal | HaysonDict): this {
const dict = makeValue(values) as DictVal
if (!dict.isKind(Kind.Dict)) {
throw new Error('Invalid value')
}
this.checkRowIndexNum(index)
const row = this.makeRowDictFromValues(dict)
this.addMissingColumns(dict)
this.getRows()[index] = row
return this
}
/**
* Adds any missing columns for the dict.
*
* @param dict The dict to check.
*/
private addMissingColumns(dict: DictVal): void {
// Add any missing columns.
for (const key of dict.keys) {
if (!this.hasColumn(key)) {
this.addColumn(key)
}
}
}
/**
* Add a single or multiple rows using dicts.
*
* This method can be called in different ways to add multiple rows at a time.
*
* ```typescript
* // Add a single dict.
* grid.add(new HDict({ foo: HStr.make('bar') }))
*
* // Add multiple dicts.
* grid.add(new HDict({ foo: HStr.make('bar') }), new HDict({ foo: HStr.make('bar') }))
*
* // Add multiple dicts using an array...
* grid.add([new HDict({ foo: HStr.make('bar') }), new HDict({ foo: HStr.make('bar') })])
*
* // Same but using Hayson...
* grid.add({ foo: 'bar' }))
* grid.add({ foo: 'bar' }), { foo: 'bar' })
* grid.add([{ foo: 'bar' }), { foo: 'bar' }])
* ```
* @param rows The rows to add.
* @returns The grid instance.
* @throws If the values being added are not dicts.
*/
public add(
...rows: (DictVal[] | HaysonDict[] | DictVal | HaysonDict)[]
): this {
const toAdd = HGrid.toDicts(rows)
if (!toAdd.length) {
throw new Error('No dicts to add to grid')
}
for (let row of toAdd) {
row = makeValue(row) as DictVal
if (!valueIsKind<HDict>(row, Kind.Dict)) {
throw new Error('Row is not a dict')
}
const dict = this.makeRowDictFromValues(row)
this.addMissingColumns(dict)
this.getRows().push(dict)
}
return this
}
/**
* Insert rows as dicts at the specified index.
*
* ```typescript
* // Insert a single dict.
* grid.insert(1, new HDict({ foo: HStr.make('bar') }))
*
* // Insert multiple dicts.
* grid.insert(1, new HDict({ foo: HStr.make('bar') }), new HDict({ foo: HStr.make('bar') }))
*
* // Insert multiple dicts using an array...
* grid.insert(1, [new HDict({ foo: HStr.make('bar') }), new HDict({ foo: HStr.make('bar') })])
*
* // Same but using Hayson...
* grid.insert(1, { foo: 'bar' }))
* grid.insert(1, { foo: 'bar' }), { foo: 'bar' })
* grid.insert(1, [{ foo: 'bar' }), { foo: 'bar' }])
* ```
*
* @param index The index number to insert the rows at.
* @param rows The rows to insert.
* @returns The grid instance.
* @throws An error if the index is invalid or the rows are not dicts.
*/
public insert(
index: number,
...rows: (DictVal[] | HaysonDict[] | DictVal | HaysonDict)[]
): this {
const toInsert = HGrid.toDicts(rows)
if (!toInsert.length) {
throw new Error('No dicts to insert into grid')
}
if (index < 0) {
throw new Error('Index cannot be less than zero')
}
if (index > this.length) {
throw new Error('Index not in range')
}
for (let row of toInsert) {
row = makeValue(row) as DictVal
if (!valueIsKind<HDict>(row, Kind.Dict)) {
throw new Error('Row is not a dict')
}
const dict = this.makeRowDictFromValues(row)
this.addMissingColumns(dict)
// Insert into the array
this.getRows().splice(index++, 0, dict)
}
return this
}
/**
* Sort the grid in ascending order via a column name. This also
* supports sorting via multiple column names.
*
* Precedence is given to the first columns in the table.
*
* ```typescript
* // Sorts the grid in ascending order by 'foo'
* grid.sortBy('foo')
*
* // Sorts the grid in ascending order by 'foo' and then by 'boo'
* grid.sortBy(['foo', 'boo'])
* ```
*
* @param names The name of the column to sort by.
* @returns The grid instance.
*/
public sortBy(names: string | string[]): this {
const sortNames = Array.isArray(names) ? names : [names]
if (sortNames.length) {
this.getRows().sort((first: DictVal, second: DictVal): number => {
for (const name of sortNames) {
const firstVal = first.get(name)
const secondVal = second.get(name)
if (firstVal && secondVal) {
const res = firstVal.compareTo(secondVal)
if (res !== 0) {
return res
}
}
}
return -1
})
}
return this
}
/**
* Reverses the order of all the rows in the grid.
*
* ```typescript
* // Sort the grid in descending order by foo
* grid.sortBy('foo').reverse()
* ```
*/
public reverse(): void {
this.getRows().reverse()
}
/**
* Returns a flattened array of dicts.
*
* @param rows The rows to flatten into an array of dicts.
* @returns An array of dicts.
*/
private static toDicts<DictVal extends HDict>(
rows: (DictVal[] | HaysonDict[] | DictVal | HaysonDict)[]
): DictVal[] {
const dicts: DictVal[] = []
for (const row of rows) {
if (Array.isArray(row)) {
for (const innerRow of row) {
dicts.push(makeValue(innerRow) as DictVal)
}
} else {
dicts.push(makeValue(row) as DictVal)
}
}
return dicts
}
/**
* Make a dict that can be used as a row in a dict.
*
* @param dict The dict to insert as a row into the grid.
* @returns The row dict.
*/
private makeRowDictFromValues(dict: DictVal): DictVal {
const store = new GridRowDictStore(this, dict)
return HDict.makeFromStore(store) as DictVal
}
/**
* ```typescript
* // Create a grid with no rows (still retains column and meta).
* grid.clear()
* ```
*
* Clear all the rows from the grid.
*/
public clear(): void {
this.getRows().splice(0, this.length)
}
/**
* Return an array of column information.
*
* ```typescript
* // Return an array of column objects.
* const cols = grid.getColumns()
* ```
*
* @returns A copy of the grid's columns.
*/
public getColumns(): GridColumn[] {
return [...this.$store.columns]
}
/**
* Return the column names (not display names).
*
* @returns The column names.
*/
public getColumnNames(): string[] {
return this.$store.columns.map((col: GridColumn): string => col.name)
}
/**
* Add a column and return its new instance.
*
* If the column is already available then update it.
*
* ```typescript
* grid.addColumn('Address', new HDict({ length: 30 }))
* ```
*
* @param name The name of the column.
* @param meta The column's meta data.
* @returns The new column or the one already found.
*/
public addColumn(name: string, meta?: HDict): GridColumn {
return this.$store.addColumn(name, meta)
}
/**
* Does the grid have the specified column?
*
* ```typescript
* if (grid.hasColumn('Address)) {
* // The grid has a column called address.
* }
* ```
*
* @param name The name of the column.
* @returns True if the grid has the column.
*/
public hasColumn(name: string): boolean {
return this.$store.hasColumn(name)
}
/**
* Set the column at the specified index number.
*
* ```typescript
* // Set the column at the specified index with the new name and length.
* grid.setColumn(3, 'Address', new HDict({ length: 30 }))
* ```
*
* @param index The zero based index number of the column.
* @param name The name of the column.
* @param meta Optional column's meta data.
* @returns The updated column.
* @throws An error if index does not exist in the columns.
*/
public setColumn(index: number, name: string, meta?: HDict): GridColumn {
if (!this.$store.columns[index]) {
throw new Error('Cannot set an invalid column')
}
const col = new GridColumn(name, meta || HDict.make())
this.$store.setColumn(index, col)
return col
}
/**
* Returns a grid column via its name or index number. If it can't be found
* then return undefined.
*
* ```typescript
* // Get the column at the specified index or return undefined
* const col = grid.getColumn('Address')
* if (col) {
* // Do something
* }
*
* // Alternatively use the column index to get the column
* const col1 = grid.getColumn(3)
* if (col1) {
* // Do something
* }
* ```
*
* @param index The column index number or name.
* @returns The column or undefined if not found.
*/
public getColumn(index: number | string): GridColumn | undefined {
return this.$store.getColumn(index)
}
/**
* Returns the number of columns.
*
* ```typescript
* console.log('The table has this many columns: ' + grid.getColumnsLength())
* ```
*
* @returns The number of columns.
*/
public getColumnsLength(): number {
return this.$store.columns.length
}
/**
* Reorder the columns with the specified new order of names.
*
* ```typescript
* const grid = HGrid.make({
* columns: [
* { name: 'b' },
* { name: 'c' },
* { name: 'a' },
* ]
* })
*
* // Reorder the columns to be a, b and then c.
* grid.reorderColumns([ 'a', 'b', 'c' ])
* ```
*
* @param names The new order of column names to use.
*/
public reorderColumns(names: string | string[]): void {
const colNames = Array.isArray(names) ? names : [names]
this.$store.reorderColumns(colNames)
}
/**
* Return a haystack list for all the values in
* the specified column.
*
* If the column can't be found then an empty list is returned.
*
* ```typescript
* const grid = HGrid.make({
* rows: [
* { name: 'Gareth', id: 1 },
* { name: 'Jason', id: 2 },
* { name: 'Radu', id: 3 },
* ]
* })
*
* // Returns an HList<HStr> of the names (Gareth, Jason and Radu).
* const listOfNames = grid.listBy<HStr>('name')
* ```
*
* @param column The column name, column index or instance to
* create the list from.
*/
public listBy<Value extends OptionalHVal>(
column: string | number | GridColumn
): HList<Value> {
let name: string | undefined
if (isGridColumn(column)) {
for (let i = 0; i < this.$store.columns.length; ++i) {
if (column.name === this.$store.columns[i].name) {
name = column.name
break
}
}
} else {
switch (typeof column) {
case 'string':
name = column
break
case 'number':
const col = this.$store.columns[column]
if (col) {
name = col.name
}
}
}
if (name === undefined) {
return HList.make()
}
const values = this.getRows()
.map((row: DictVal): OptionalHVal | undefined =>
row.get(name as string)
)
.filter((value): boolean => value !== undefined) as Value[]
return HList.make(values as Value[])
}
/**
* Limit the grid only to the specified columns.
*
* This will return a new instance of a grid.
*
* ```typescript
* grid.filter('site').limitColumns(['id', 'dis']).inspect()
* ```
*
* @param names The column names.
* @returns A new grid instance with the specified columns.
*/
public limitColumns<LimitDictVal extends HDict = DictVal>(
names: string[]
): HGrid<LimitDictVal> {
return HGrid.make<LimitDictVal>({
version: this.version,
meta: this.meta.newCopy() as HDict,
rows: this.getRows().map(
(dict: DictVal): LimitDictVal => {
const newDict = new HDict()
for (const name of names) {
if (dict.has(name)) {
newDict.set(name, dict.get(name) as HVal)
}
}
return newDict as LimitDictVal
}
),
columns: this.getColumns()
.filter((col: GridColumn) => names.includes(col.name))
.map((col: GridColumn): {
name: string
meta?: HDict
} => ({ name: col.name, meta: col.meta.newCopy() as HDict })),
})
}
/**
* Iterate over a grid using dicts for rows.
*
* This enables a 'for ... of' loop to be used directly on an iterator.
*
* @returns A new iterator for a grid.
*
* ```typescript
* // Iterate a grid
* for (let dict of grid) {
* console.log(dict)
* }
*
* // Destructure a grid into an array of dicts...
* const fooDict = [...grid].filter((dict): boolean => dict.get('foo') === 'foo')[0]
* ```
*/
public [Symbol.iterator](): Iterator<DictVal> {
return new GridDictIterator(this)
}
/**
* ```typescript
* if (grid.isEmpty()) {
* // Grid is empty.
* }
* ```
*
* @returns true if the grid is empty.
*/
public isEmpty(): boolean {
return this.length === 0
}
/**
* Selects a range from the grid.
*
* The start and end can be used to specify a range...
* ```typescript
* // from [0, 1, 2, 3, 4, 5] to [1, 2, 3, 4]
* grid.filter('site').range(1, 4).inspect()
* ```
*
* //If only the first argument then a quantity can be used...
* ```typescript
* // select the first 4 rows - [0, 1, 2, 4]...
* grid.filter('site').range(4).inspect()
* ```
*
* @param startOrQuantity The start of the range or quantity.
* @param end Optional end range.
* @returns This grid instance.
*/
public range(startOrQuantity: number, end?: number): this {
const rows = this.getRows()
if (end === undefined) {
end = --startOrQuantity
startOrQuantity = 0
}
if (startOrQuantity <= end) {
for (let i = rows.length; i >= 0; --i) {
if (i < startOrQuantity || i > end) {
this.remove(i)
}
}
}
return this
}
/**
* Return the sum of values for the specified column.
*
* ```typescript
* const grid = HGrid.make({
* rows: [
* { id: 34, num: 1 },
* { id: 35, num: 2 },
* { id: 36, num: 3 },
* ]
* })
* // Sum all the values in the num column (6)
* const sum = grid.sumOf('num')
* ```
*
* @param column The column name, column index or column instance.
* @returns The sum of all the numeric values.
*/
public sumOf(column: string | number | GridColumn): number {
return this.listBy(column).sum
}
/**
* Return the maximum value in the specified column.
*
* If there are no numbers then Number.MIN_SAFE_INTEGER is returned.
*
* ```typescript
* const grid = HGrid.make({
* rows: [
* { id: 34, num: 1 },
* { id: 35, num: 2 },
* { id: 36, num: 3 },
* ]
* })
* // Return the maximum value in the num column (3).
* const max = grid.maxOf('num')
* ```
*
* @param column The column name, column index or column instance.
* @returns The maximum numerical value found.
*/
public maxOf(column: string | number | GridColumn): number {
return this.listBy(column).max
}
/**
* Return the minimum of value in the specified column.
*
* If there are no numbers then Number.MAX_SAFE_INTEGER is returned.
*
* ```typescript
* const grid = HGrid.make({
* rows: [
* { id: 34, num: 1 },
* { id: 35, num: 2 },
* { id: 36, num: 3 },
* ]
* })
* // Return the maximum value in the num column (1).
* const min = grid.minOf('num')
* ```
*
* @param column The column name, column index or column instance.
* @returns The minimum numerical value found.
*/
public minOf(column: string | number | GridColumn): number {
return this.listBy(column).min
}
/**
* Return the sum of values for the specified column.
*
* If there are no numbers then Number.NaN is returned.
*
* ```typescript
* const grid = HGrid.make({
* rows: [
* { id: 34, num: 1 },
* { id: 35, num: 2 },
* { id: 36, num: 3 },
* ]
* })
* // Return average of the num column (2).
* const avg = grid.avgOf('num')
* ```
*
* @param column The column name, column index or column instance.
* @returns The average of all the numeric values.
*/
public avgOf(column: string | number | GridColumn): number {
return this.listBy(column).avg
}
/**
* ```typescript
* if (grid.isError()) {
* // Do something.
* }
* ```
*
* @returns true if the grid has an error associated with it.
*/
public isError(): boolean {
return this.meta.has('err')
}
/**
* ```typescript
* const err = grid.getError()
* if (err) {
* // Do something with the error.
* }
* ```
*
* @returns Error information or undefined if not available.
*/
public getError():
| undefined
| { type: string; trace: string; dis: string } {
if (!this.isError()) {
return undefined
}
const errType = this.meta.get<HStr>('errType')
const errTrace = this.meta.get<HStr>('errTrace')
const dis = this.meta.get<HStr>('dis')
return {
type: (errType && errType.value) || '',
trace: (errTrace && errTrace.value) || '',
dis: (dis && dis.value) || '',
}
}
/**
* @returns The grid as an array like object.
*/
public asArrayLike(): ArrayLike<DictVal> {
return (this as unknown) as ArrayLike<DictVal>
}
/**
* @returns A string representation of the value.
*/
public toString(): string {
return `[${this.getRows()
.map((dict: DictVal): string => String(dict))
.join(', ')}]`
}
/**
* Dump the value to the local console output.
*
* @param message An optional message to display before the value.
* @returns The value instance.
*/
public inspect(message?: string): this {
if (message) {
console.log(String(message))
}
console.table(
this.getRows().map((row: DictVal): {
[prop: string]: string | number
} => {
const obj: { [prop: string]: string } = {}
for (const val of row) {
obj[val.name] = String(val.value)
}
return obj
})
)
return this
}
/**
* Check whether the index number for the row is a valid number.
*
* @param index The row index number to check.
* @throws An error if the index number is invalid.
*/
private checkRowIndexNum(index: number): void {
if (index < 0) {
throw new Error('Row index must be greater than zero')
}
}
/**
* @returns Returns a copy of the grid.
*/
public newCopy(): HGrid<DictVal> {
return HGrid.make<DictVal>({
version: this.version,
meta: this.meta.newCopy() as HDict,
rows: this.getRows().map(
(dict: DictVal): DictVal => dict.newCopy() as DictVal
),
columns: this.getColumns().map((col: GridColumn): {
name: string
meta?: HDict
} => ({ name: col.name, meta: col.meta.newCopy() as HDict })),
})
}
/**
* @returns The value as a grid.
*/
public toGrid(): HGrid<DictVal> {
return this
}
/**
* @returns The value as a list.
*/
public toList(): HList<DictVal> {
return HList.make(this.getRows())
}
/**
* @returns The value as a dict.
*/
public toDict(): HDict {
const obj: HValObj = {}
const rows = this.getRows()
for (let i = 0; i < rows.length; ++i) {
obj[`row${i}`] = rows[i]
}
return HDict.make(this)
}
} | the_stack |
import {DOCUMENT} from '@angular/common';
import {Inject, Injectable, OnDestroy, APP_ID, inject} from '@angular/core';
import {Platform} from '@angular/cdk/platform';
import {addAriaReferencedId, getAriaReferenceIds, removeAriaReferencedId} from './aria-reference';
/**
* Interface used to register message elements and keep a count of how many registrations have
* the same message and the reference to the message element used for the `aria-describedby`.
*/
export interface RegisteredMessage {
/** The element containing the message. */
messageElement: Element;
/** The number of elements that reference this message element via `aria-describedby`. */
referenceCount: number;
}
/**
* ID used for the body container where all messages are appended.
* @deprecated No longer being used. To be removed.
* @breaking-change 14.0.0
*/
export const MESSAGES_CONTAINER_ID = 'cdk-describedby-message-container';
/**
* ID prefix used for each created message element.
* @deprecated To be turned into a private variable.
* @breaking-change 14.0.0
*/
export const CDK_DESCRIBEDBY_ID_PREFIX = 'cdk-describedby-message';
/**
* Attribute given to each host element that is described by a message element.
* @deprecated To be turned into a private variable.
* @breaking-change 14.0.0
*/
export const CDK_DESCRIBEDBY_HOST_ATTRIBUTE = 'cdk-describedby-host';
/** Global incremental identifier for each registered message element. */
let nextId = 0;
/**
* Utility that creates visually hidden elements with a message content. Useful for elements that
* want to use aria-describedby to further describe themselves without adding additional visual
* content.
*/
@Injectable({providedIn: 'root'})
export class AriaDescriber implements OnDestroy {
private _document: Document;
/** Map of all registered message elements that have been placed into the document. */
private _messageRegistry = new Map<string | Element, RegisteredMessage>();
/** Container for all registered messages. */
private _messagesContainer: HTMLElement | null = null;
/** Unique ID for the service. */
private readonly _id = `${nextId++}`;
constructor(
@Inject(DOCUMENT) _document: any,
/**
* @deprecated To be turned into a required parameter.
* @breaking-change 14.0.0
*/
private _platform?: Platform,
) {
this._document = _document;
this._id = inject(APP_ID) + '-' + nextId++;
}
/**
* Adds to the host element an aria-describedby reference to a hidden element that contains
* the message. If the same message has already been registered, then it will reuse the created
* message element.
*/
describe(hostElement: Element, message: string, role?: string): void;
/**
* Adds to the host element an aria-describedby reference to an already-existing message element.
*/
describe(hostElement: Element, message: HTMLElement): void;
describe(hostElement: Element, message: string | HTMLElement, role?: string): void {
if (!this._canBeDescribed(hostElement, message)) {
return;
}
const key = getKey(message, role);
if (typeof message !== 'string') {
// We need to ensure that the element has an ID.
setMessageId(message, this._id);
this._messageRegistry.set(key, {messageElement: message, referenceCount: 0});
} else if (!this._messageRegistry.has(key)) {
this._createMessageElement(message, role);
}
if (!this._isElementDescribedByMessage(hostElement, key)) {
this._addMessageReference(hostElement, key);
}
}
/** Removes the host element's aria-describedby reference to the message. */
removeDescription(hostElement: Element, message: string, role?: string): void;
/** Removes the host element's aria-describedby reference to the message element. */
removeDescription(hostElement: Element, message: HTMLElement): void;
removeDescription(hostElement: Element, message: string | HTMLElement, role?: string): void {
if (!message || !this._isElementNode(hostElement)) {
return;
}
const key = getKey(message, role);
if (this._isElementDescribedByMessage(hostElement, key)) {
this._removeMessageReference(hostElement, key);
}
// If the message is a string, it means that it's one that we created for the
// consumer so we can remove it safely, otherwise we should leave it in place.
if (typeof message === 'string') {
const registeredMessage = this._messageRegistry.get(key);
if (registeredMessage && registeredMessage.referenceCount === 0) {
this._deleteMessageElement(key);
}
}
if (this._messagesContainer?.childNodes.length === 0) {
this._messagesContainer.remove();
this._messagesContainer = null;
}
}
/** Unregisters all created message elements and removes the message container. */
ngOnDestroy() {
const describedElements = this._document.querySelectorAll(
`[${CDK_DESCRIBEDBY_HOST_ATTRIBUTE}="${this._id}"]`,
);
for (let i = 0; i < describedElements.length; i++) {
this._removeCdkDescribedByReferenceIds(describedElements[i]);
describedElements[i].removeAttribute(CDK_DESCRIBEDBY_HOST_ATTRIBUTE);
}
this._messagesContainer?.remove();
this._messagesContainer = null;
this._messageRegistry.clear();
}
/**
* Creates a new element in the visually hidden message container element with the message
* as its content and adds it to the message registry.
*/
private _createMessageElement(message: string, role?: string) {
const messageElement = this._document.createElement('div');
setMessageId(messageElement, this._id);
messageElement.textContent = message;
if (role) {
messageElement.setAttribute('role', role);
}
this._createMessagesContainer();
this._messagesContainer!.appendChild(messageElement);
this._messageRegistry.set(getKey(message, role), {messageElement, referenceCount: 0});
}
/** Deletes the message element from the global messages container. */
private _deleteMessageElement(key: string | Element) {
this._messageRegistry.get(key)?.messageElement?.remove();
this._messageRegistry.delete(key);
}
/** Creates the global container for all aria-describedby messages. */
private _createMessagesContainer() {
if (this._messagesContainer) {
return;
}
const containerClassName = 'cdk-describedby-message-container';
const serverContainers = this._document.querySelectorAll(
`.${containerClassName}[platform="server"]`,
);
for (let i = 0; i < serverContainers.length; i++) {
// When going from the server to the client, we may end up in a situation where there's
// already a container on the page, but we don't have a reference to it. Clear the
// old container so we don't get duplicates. Doing this, instead of emptying the previous
// container, should be slightly faster.
serverContainers[i].remove();
}
const messagesContainer = this._document.createElement('div');
// We add `visibility: hidden` in order to prevent text in this container from
// being searchable by the browser's Ctrl + F functionality.
// Screen-readers will still read the description for elements with aria-describedby even
// when the description element is not visible.
messagesContainer.style.visibility = 'hidden';
// Even though we use `visibility: hidden`, we still apply `cdk-visually-hidden` so that
// the description element doesn't impact page layout.
messagesContainer.classList.add(containerClassName);
messagesContainer.classList.add('cdk-visually-hidden');
// @breaking-change 14.0.0 Remove null check for `_platform`.
if (this._platform && !this._platform.isBrowser) {
messagesContainer.setAttribute('platform', 'server');
}
this._document.body.appendChild(messagesContainer);
this._messagesContainer = messagesContainer;
}
/** Removes all cdk-describedby messages that are hosted through the element. */
private _removeCdkDescribedByReferenceIds(element: Element) {
// Remove all aria-describedby reference IDs that are prefixed by CDK_DESCRIBEDBY_ID_PREFIX
const originalReferenceIds = getAriaReferenceIds(element, 'aria-describedby').filter(
id => id.indexOf(CDK_DESCRIBEDBY_ID_PREFIX) != 0,
);
element.setAttribute('aria-describedby', originalReferenceIds.join(' '));
}
/**
* Adds a message reference to the element using aria-describedby and increments the registered
* message's reference count.
*/
private _addMessageReference(element: Element, key: string | Element) {
const registeredMessage = this._messageRegistry.get(key)!;
// Add the aria-describedby reference and set the
// describedby_host attribute to mark the element.
addAriaReferencedId(element, 'aria-describedby', registeredMessage.messageElement.id);
element.setAttribute(CDK_DESCRIBEDBY_HOST_ATTRIBUTE, this._id);
registeredMessage.referenceCount++;
}
/**
* Removes a message reference from the element using aria-describedby
* and decrements the registered message's reference count.
*/
private _removeMessageReference(element: Element, key: string | Element) {
const registeredMessage = this._messageRegistry.get(key)!;
registeredMessage.referenceCount--;
removeAriaReferencedId(element, 'aria-describedby', registeredMessage.messageElement.id);
element.removeAttribute(CDK_DESCRIBEDBY_HOST_ATTRIBUTE);
}
/** Returns true if the element has been described by the provided message ID. */
private _isElementDescribedByMessage(element: Element, key: string | Element): boolean {
const referenceIds = getAriaReferenceIds(element, 'aria-describedby');
const registeredMessage = this._messageRegistry.get(key);
const messageId = registeredMessage && registeredMessage.messageElement.id;
return !!messageId && referenceIds.indexOf(messageId) != -1;
}
/** Determines whether a message can be described on a particular element. */
private _canBeDescribed(element: Element, message: string | HTMLElement | void): boolean {
if (!this._isElementNode(element)) {
return false;
}
if (message && typeof message === 'object') {
// We'd have to make some assumptions about the description element's text, if the consumer
// passed in an element. Assume that if an element is passed in, the consumer has verified
// that it can be used as a description.
return true;
}
const trimmedMessage = message == null ? '' : `${message}`.trim();
const ariaLabel = element.getAttribute('aria-label');
// We shouldn't set descriptions if they're exactly the same as the `aria-label` of the
// element, because screen readers will end up reading out the same text twice in a row.
return trimmedMessage ? !ariaLabel || ariaLabel.trim() !== trimmedMessage : false;
}
/** Checks whether a node is an Element node. */
private _isElementNode(element: Node): element is Element {
return element.nodeType === this._document.ELEMENT_NODE;
}
}
/** Gets a key that can be used to look messages up in the registry. */
function getKey(message: string | Element, role?: string): string | Element {
return typeof message === 'string' ? `${role || ''}/${message}` : message;
}
/** Assigns a unique ID to an element, if it doesn't have one already. */
function setMessageId(element: HTMLElement, serviceId: string) {
if (!element.id) {
element.id = `${CDK_DESCRIBEDBY_ID_PREFIX}-${serviceId}-${nextId++}`;
}
} | the_stack |
import ts, { TsConfigSourceFile } from 'typescript';
import { tmpdir } from 'os';
import { Component } from '@teambit/component';
import { ComponentUrl } from '@teambit/component.modules.component-url';
import { BuildTask } from '@teambit/builder';
import { merge } from 'lodash';
import { Bundler, BundlerContext, DevServer, DevServerContext } from '@teambit/bundler';
import { CompilerMain } from '@teambit/compiler';
import {
BuilderEnv,
CompilerEnv,
DependenciesEnv,
DevEnv,
LinterEnv,
PackageEnv,
TesterEnv,
FormatterEnv,
PipeServiceModifier,
PipeServiceModifiersMap,
} from '@teambit/envs';
import { JestMain } from '@teambit/jest';
import { PkgMain } from '@teambit/pkg';
import { Tester, TesterMain } from '@teambit/tester';
import { TsConfigTransformer, TypescriptMain } from '@teambit/typescript';
import type { TypeScriptCompilerOptions } from '@teambit/typescript';
import { WebpackConfigTransformer, WebpackMain } from '@teambit/webpack';
import { Workspace } from '@teambit/workspace';
import { ESLintMain, EslintConfigTransformer } from '@teambit/eslint';
import { PrettierConfigTransformer, PrettierMain } from '@teambit/prettier';
import { Linter, LinterContext } from '@teambit/linter';
import { Formatter, FormatterContext } from '@teambit/formatter';
import { pathNormalizeToLinux } from '@teambit/legacy/dist/utils';
import type { ComponentMeta } from '@teambit/react.ui.highlighter.component-metadata.bit-component-meta';
import { SchemaExtractor } from '@teambit/schema';
import { join, resolve } from 'path';
import { outputFileSync } from 'fs-extra';
// Makes sure the @teambit/react.ui.docs-app is a dependency
// TODO: remove this import once we can set policy from component to component with workspace version. Then set it via the component.json
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { ReactMainConfig } from './react.main.runtime';
import { ReactAspect } from './react.aspect';
// webpack configs for both components and envs
import basePreviewConfigFactory from './webpack/webpack.config.base';
import basePreviewProdConfigFactory from './webpack/webpack.config.base.prod';
// webpack configs for envs only
// import devPreviewConfigFactory from './webpack/webpack.config.preview.dev';
import envPreviewDevConfigFactory from './webpack/webpack.config.env.dev';
// webpack configs for components only
import componentPreviewProdConfigFactory from './webpack/webpack.config.component.prod';
import componentPreviewDevConfigFactory from './webpack/webpack.config.component.dev';
export const AspectEnvType = 'react';
const defaultTsConfig = require('./typescript/tsconfig.json');
const buildTsConfig = require('./typescript/tsconfig.build.json');
const eslintConfig = require('./eslint/eslintrc');
const prettierConfig = require('./prettier/prettier.config.js');
// TODO: move to be taken from the key mode of compiler context
type CompilerMode = 'build' | 'dev';
type GetBuildPipeModifiers = PipeServiceModifiersMap & {
tsModifier?: PipeServiceModifier;
};
/**
* a component environment built for [React](https://reactjs.org) .
*/
export class ReactEnv
implements TesterEnv, CompilerEnv, LinterEnv, DevEnv, BuilderEnv, DependenciesEnv, PackageEnv, FormatterEnv
{
constructor(
/**
* jest extension
*/
private jestAspect: JestMain,
/**
* typescript extension.
*/
private tsAspect: TypescriptMain,
/**
* compiler extension.
*/
private compiler: CompilerMain,
/**
* webpack extension.
*/
private webpack: WebpackMain,
/**
* workspace extension.
*/
private workspace: Workspace,
/**
* pkg extension.
*/
private pkg: PkgMain,
/**
* tester extension
*/
private tester: TesterMain,
private config: ReactMainConfig,
private eslint: ESLintMain,
private prettier: PrettierMain
) {}
getTsConfig(targetTsConfig?: TsConfigSourceFile): TsConfigSourceFile {
return targetTsConfig ? merge({}, defaultTsConfig, targetTsConfig) : defaultTsConfig;
}
getBuildTsConfig(targetTsConfig?: TsConfigSourceFile): TsConfigSourceFile {
return targetTsConfig ? merge({}, buildTsConfig, targetTsConfig) : buildTsConfig;
}
/**
* returns a component tester.
*/
getTester(jestConfigPath: string, jestModulePath?: string): Tester {
const config = jestConfigPath || require.resolve('./jest/jest.config');
return this.jestAspect.createTester(config, jestModulePath || require.resolve('jest'));
}
private getTsCompilerOptions(mode: CompilerMode = 'dev'): TypeScriptCompilerOptions {
const tsconfig = mode === 'dev' ? defaultTsConfig : buildTsConfig;
const pathToSource = pathNormalizeToLinux(__dirname).replace('/dist/', '/src/');
const compileJs = true;
const compileJsx = true;
return {
tsconfig,
// TODO: @david please remove this line and refactor to be something that makes sense.
types: [resolve(pathToSource, './typescript/style.d.ts'), resolve(pathToSource, './typescript/asset.d.ts')],
compileJs,
compileJsx,
};
}
private getTsCompiler(mode: CompilerMode = 'dev', transformers: TsConfigTransformer[] = [], tsModule = ts) {
const tsCompileOptions = this.getTsCompilerOptions(mode);
return this.tsAspect.createCompiler(tsCompileOptions, transformers, tsModule);
}
getCompiler(transformers: TsConfigTransformer[] = [], tsModule = ts) {
return this.getTsCompiler('dev', transformers, tsModule);
}
/**
* returns and configures the component linter.
*/
getLinter(context: LinterContext, transformers: EslintConfigTransformer[] = []): Linter {
const defaultTransformer: EslintConfigTransformer = (configMutator) => {
configMutator.addExtensionTypes(['.md', '.mdx']);
return configMutator;
};
const allTransformers = [defaultTransformer, ...transformers];
return this.eslint.createLinter(
context,
{
config: eslintConfig,
// resolve all plugins from the react environment.
pluginPath: __dirname,
},
allTransformers
);
}
/**
* returns and configures the component formatter.
*/
getFormatter(context: FormatterContext, transformers: PrettierConfigTransformer[] = []): Formatter {
return this.prettier.createFormatter(
context,
{
config: prettierConfig,
},
transformers
);
}
private getFileMap(components: Component[], local = false) {
return components.reduce<{ [key: string]: ComponentMeta }>((index, component: Component) => {
component.state.filesystem.files.forEach((file) => {
index[file.path] = {
id: component.id.toString(),
homepage: local ? `/${component.id.fullName}` : ComponentUrl.toUrl(component.id),
};
});
return index;
}, {});
}
private writeFileMap(components: Component[], local?: boolean) {
const fileMap = this.getFileMap(components, local);
const path = join(tmpdir(), `${Math.random().toString(36).substr(2, 9)}.json`);
outputFileSync(path, JSON.stringify(fileMap));
return path;
}
/**
* required for `bit start`
*/
getDevEnvId(id?: string) {
if (typeof id !== 'string') return ReactAspect.id;
return id || ReactAspect.id;
}
/**
* get a schema generator instance configured with the correct tsconfig.
*/
getSchemaExtractor(tsconfig: TsConfigSourceFile): SchemaExtractor {
return this.tsAspect.createSchemaExtractor(this.getTsConfig(tsconfig));
}
/**
* returns and configures the React component dev server.
* required for `bit start`
*/
getDevServer(context: DevServerContext, transformers: WebpackConfigTransformer[] = []): DevServer {
const baseConfig = basePreviewConfigFactory(false);
const envDevConfig = envPreviewDevConfigFactory(context.id);
const componentDevConfig = componentPreviewDevConfigFactory(this.workspace.path, context.id);
const defaultTransformer: WebpackConfigTransformer = (configMutator) => {
const merged = configMutator.merge([baseConfig, envDevConfig, componentDevConfig]);
return merged;
};
return this.webpack.createDevServer(context, [defaultTransformer, ...transformers]);
}
async getBundler(context: BundlerContext, transformers: WebpackConfigTransformer[] = []): Promise<Bundler> {
// const fileMapPath = this.writeFileMap(context.components);
const baseConfig = basePreviewConfigFactory(true);
const baseProdConfig = basePreviewProdConfigFactory();
// const componentProdConfig = componentPreviewProdConfigFactory(fileMapPath);
const componentProdConfig = componentPreviewProdConfigFactory();
const defaultTransformer: WebpackConfigTransformer = (configMutator) => {
const merged = configMutator.merge([baseConfig, baseProdConfig, componentProdConfig]);
return merged;
};
return this.webpack.createPreviewBundler(context, [defaultTransformer, ...transformers]);
}
/**
* returns a path to a docs template.
*/
getDocsTemplate() {
return require.resolve('@teambit/react.ui.docs-app');
}
icon = 'https://static.bit.dev/extensions-icons/react.svg';
/**
* returns a paths to a function which mounts a given component to DOM
*/
getMounter() {
return require.resolve('./mount');
}
/**
* define the package json properties to add to each component.
*/
getPackageJsonProps() {
return this.tsAspect.getPackageJsonProps();
}
/**
* adds dependencies to all configured components.
*/
getDependencies() {
return {
dependencies: {
react: '-',
'react-dom': '-',
'core-js': '^3.0.0',
},
// TODO: add this only if using ts
devDependencies: {
react: '-',
'react-dom': '-',
'@types/mocha': '-',
'@types/node': '12.20.4',
'@types/react': '^17.0.8',
'@types/react-dom': '^17.0.5',
'@types/jest': '^26.0.0',
// '@types/react-router-dom': '^5.0.0', // TODO - should not be here (!)
// This is added as dev dep since our jest file transformer uses babel plugins that require this to be installed
'@babel/runtime': '7.12.18',
'@types/testing-library__jest-dom': '5.9.5',
},
peerDependencies: {
react: '^16.8.0 || ^17.0.0',
'react-dom': '^16.8.0 || ^17.0.0',
},
};
}
/**
* returns the component build pipeline.
*/
getBuildPipe(modifiers: GetBuildPipeModifiers = {}): BuildTask[] {
const transformers: TsConfigTransformer[] =
(modifiers?.tsModifier?.transformers as any as TsConfigTransformer[]) || [];
return [this.getCompilerTask(transformers, modifiers?.tsModifier?.module || ts), this.tester.task];
}
private getCompilerTask(transformers: TsConfigTransformer[] = [], tsModule = ts) {
const tsCompiler = this.getTsCompiler('build', transformers, tsModule);
return this.compiler.createTask('TSCompiler', tsCompiler);
}
async __getDescriptor() {
return {
type: AspectEnvType,
};
}
} | the_stack |
import { gunzipSync } from 'zlib';
import nock from 'nock';
import { GraphQLSchemaModule } from 'apollo-graphql';
import gql from 'graphql-tag';
import { buildSubgraphSchema } from '@apollo/subgraph';
import { ApolloServer } from 'apollo-server';
import { ApolloServerPluginUsageReporting } from 'apollo-server-core';
import { execute } from '@apollo/client/link/core';
import { toPromise } from '@apollo/client/link/utils';
import { createHttpLink } from '@apollo/client/link/http';
import fetch from 'node-fetch';
import { ApolloGateway } from '../..';
import { Plugin, Config, Refs } from 'pretty-format';
import { Report, Trace } from 'apollo-reporting-protobuf';
import { fixtures } from 'apollo-federation-integration-testsuite';
import { nockAfterEach, nockBeforeEach } from '../nockAssertions';
// Normalize specific fields that change often (eg timestamps) to static values,
// to make snapshot testing viable. (If these helpers are more generally
// useful, they could be moved to a different file.)
const alreadyProcessed = '__already_processed__';
function replaceFieldValuesSerializer(
replacements: Record<string, any>,
): Plugin {
const fieldNames = Object.keys(replacements);
return {
test(value: any) {
return (
value &&
typeof value === 'object' &&
!value[alreadyProcessed] &&
fieldNames.some((n) => n in value)
);
},
serialize(
value: Record<string, any>,
config: Config,
indentation: string,
depth: number,
refs: Refs,
printer: any,
): string {
// Clone object so pretty-format doesn't consider it as a circular
// reference. Put a special (non-enumerable) property on it so that *we*
// don't reprocess it ourselves.
const newValue = { ...value };
Object.defineProperty(newValue, alreadyProcessed, { value: true });
fieldNames.forEach((fn) => {
if (fn in value) {
const replacement = replacements[fn];
if (typeof replacement === 'function') {
newValue[fn] = replacement(value[fn]);
} else {
newValue[fn] = replacement;
}
}
});
return printer(newValue, config, indentation, depth, refs, printer);
},
};
}
expect.addSnapshotSerializer(
replaceFieldValuesSerializer({
header: '<HEADER>',
// We do want to differentiate between zero and non-zero in these numbers.
durationNs: (v: number) => (v ? 12345 : 0),
sentTimeOffset: (v: number) => (v ? 23456 : 0),
// endTime and startTime are annoyingly used both for top-level Timestamps
// and for node-level nanosecond offsets. The Timestamps will get normalized
// by the nanos/seconds below.
startTime: (v: any) => (typeof v === 'string' ? '34567' : v),
endTime: (v: any) => (typeof v === 'string' ? '45678' : v),
nanos: 123000000,
seconds: '1562203363',
}),
);
async function startFederatedServer(modules: GraphQLSchemaModule[]) {
const schema = buildSubgraphSchema(modules);
const server = new ApolloServer({ schema });
const { url } = await server.listen({ port: 0 });
return { url, server };
}
describe('reporting', () => {
let backendServers: ApolloServer[];
let gatewayServer: ApolloServer;
let gatewayUrl: string;
let reportPromise: Promise<any>;
beforeEach(async () => {
let reportResolver: (report: any) => void;
reportPromise = new Promise<any>((resolve) => {
reportResolver = resolve;
});
nockBeforeEach();
nock('https://usage-reporting.api.apollographql.com')
.post('/api/ingress/traces')
.reply(200, (_: any, requestBody: string) => {
reportResolver(requestBody);
return 'ok';
});
backendServers = [];
const serviceList = [];
for (const fixture of fixtures) {
const { server, url } = await startFederatedServer([fixture]);
backendServers.push(server);
serviceList.push({ name: fixture.name, url });
}
const gateway = new ApolloGateway({ serviceList });
const { schema, executor } = await gateway.load();
gatewayServer = new ApolloServer({
schema,
executor,
apollo: {
key: 'service:foo:bar',
graphRef: 'foo@current',
},
plugins: [
ApolloServerPluginUsageReporting({
sendReportsImmediately: true,
}),
],
});
({ url: gatewayUrl } = await gatewayServer.listen({ port: 0 }));
});
afterEach(async () => {
for (const server of backendServers) {
await server.stop();
}
if (gatewayServer) {
await gatewayServer.stop();
}
nockAfterEach();
});
it(`queries three services`, async () => {
const query = gql`
query {
me {
name {
first
last
}
}
topProducts {
name
}
}
`;
const result = await toPromise(
execute(createHttpLink({ uri: gatewayUrl, fetch: fetch as any }), {
query,
}),
);
expect(result).toMatchInlineSnapshot(`
Object {
"data": Object {
"me": Object {
"name": Object {
"first": "Ada",
"last": "Lovelace",
},
},
"topProducts": Array [
Object {
"name": "Table",
},
Object {
"name": "Couch",
},
Object {
"name": "Chair",
},
Object {
"name": "Structure and Interpretation of Computer Programs (1996)",
},
Object {
"name": "Object Oriented Software Construction (1997)",
},
],
},
}
`);
const reportBody = await reportPromise;
// nock returns binary bodies as hex strings
const gzipReportBuffer = Buffer.from(reportBody, 'hex');
const reportBuffer = gunzipSync(gzipReportBuffer);
const report = Report.decode(reportBuffer);
// Some handwritten tests to capture salient properties.
const statsReportKey = '# -\n{me{name{first last}}topProducts{name}}';
expect(Object.keys(report.tracesPerQuery)).toStrictEqual([statsReportKey]);
expect(report.tracesPerQuery[statsReportKey]!.trace!.length).toBe(1);
const trace = report.tracesPerQuery[statsReportKey]!.trace![0]! as Trace;
// In the gateway, the root trace is just an empty node (unless there are errors).
expect(trace.root!.child).toStrictEqual([]);
// The query plan has (among other things) a fetch against 'accounts' and a
// fetch against 'product'.
expect(trace.queryPlan).toBeTruthy();
const queryPlan = trace.queryPlan!;
expect(queryPlan.parallel).toBeTruthy();
expect(queryPlan.parallel!.nodes![0]!.fetch!.serviceName).toBe('accounts');
expect(
queryPlan.parallel!.nodes![0]!.fetch!.trace!.root!.child![0]!
.responseName,
).toBe('me');
expect(queryPlan.parallel!.nodes![1]!.sequence).toBeTruthy();
expect(
queryPlan.parallel!.nodes![1]!.sequence!.nodes![0]!.fetch!.serviceName,
).toBe('product');
expect(
queryPlan.parallel!.nodes![1]!.sequence!.nodes![0]!.fetch!.trace!.root!
.child![0].responseName,
).toBe('topProducts');
expect(report).toMatchInlineSnapshot(`
Object {
"endTime": Object {
"nanos": 123000000,
"seconds": "1562203363",
},
"header": "<HEADER>",
"tracesPerQuery": Object {
"# -
{me{name{first last}}topProducts{name}}": Object {
"trace": Array [
Object {
"cachePolicy": Object {
"maxAgeNs": "30000000000",
"scope": "PRIVATE",
},
"clientName": "",
"clientReferenceId": "",
"clientVersion": "",
"details": Object {},
"durationNs": 12345,
"endTime": Object {
"nanos": 123000000,
"seconds": "1562203363",
},
"forbiddenOperation": false,
"fullQueryCacheHit": false,
"http": Object {
"method": "POST",
},
"queryPlan": Object {
"parallel": Object {
"nodes": Array [
Object {
"fetch": Object {
"receivedTime": Object {
"nanos": 123000000,
"seconds": "1562203363",
},
"sentTime": Object {
"nanos": 123000000,
"seconds": "1562203363",
},
"sentTimeOffset": 23456,
"serviceName": "accounts",
"trace": Object {
"durationNs": 12345,
"endTime": Object {
"nanos": 123000000,
"seconds": "1562203363",
},
"root": Object {
"child": Array [
Object {
"child": Array [
Object {
"child": Array [
Object {
"endTime": "45678",
"parentType": "Name",
"responseName": "first",
"startTime": "34567",
"type": "String",
},
Object {
"endTime": "45678",
"parentType": "Name",
"responseName": "last",
"startTime": "34567",
"type": "String",
},
],
"endTime": "45678",
"parentType": "User",
"responseName": "name",
"startTime": "34567",
"type": "Name",
},
],
"endTime": "45678",
"parentType": "Query",
"responseName": "me",
"startTime": "34567",
"type": "User",
},
],
},
"startTime": Object {
"nanos": 123000000,
"seconds": "1562203363",
},
},
"traceParsingFailed": false,
},
},
Object {
"sequence": Object {
"nodes": Array [
Object {
"fetch": Object {
"receivedTime": Object {
"nanos": 123000000,
"seconds": "1562203363",
},
"sentTime": Object {
"nanos": 123000000,
"seconds": "1562203363",
},
"sentTimeOffset": 23456,
"serviceName": "product",
"trace": Object {
"durationNs": 12345,
"endTime": Object {
"nanos": 123000000,
"seconds": "1562203363",
},
"root": Object {
"child": Array [
Object {
"child": Array [
Object {
"child": Array [
Object {
"endTime": "45678",
"parentType": "Furniture",
"responseName": "name",
"startTime": "34567",
"type": "String",
},
],
"index": 0,
},
Object {
"child": Array [
Object {
"endTime": "45678",
"parentType": "Furniture",
"responseName": "name",
"startTime": "34567",
"type": "String",
},
],
"index": 1,
},
Object {
"child": Array [
Object {
"endTime": "45678",
"parentType": "Furniture",
"responseName": "name",
"startTime": "34567",
"type": "String",
},
],
"index": 2,
},
Object {
"child": Array [
Object {
"endTime": "45678",
"parentType": "Book",
"responseName": "isbn",
"startTime": "34567",
"type": "String!",
},
],
"index": 3,
},
Object {
"child": Array [
Object {
"endTime": "45678",
"parentType": "Book",
"responseName": "isbn",
"startTime": "34567",
"type": "String!",
},
],
"index": 4,
},
],
"endTime": "45678",
"parentType": "Query",
"responseName": "topProducts",
"startTime": "34567",
"type": "[Product]",
},
],
},
"startTime": Object {
"nanos": 123000000,
"seconds": "1562203363",
},
},
"traceParsingFailed": false,
},
},
Object {
"flatten": Object {
"node": Object {
"fetch": Object {
"receivedTime": Object {
"nanos": 123000000,
"seconds": "1562203363",
},
"sentTime": Object {
"nanos": 123000000,
"seconds": "1562203363",
},
"sentTimeOffset": 23456,
"serviceName": "books",
"trace": Object {
"durationNs": 12345,
"endTime": Object {
"nanos": 123000000,
"seconds": "1562203363",
},
"root": Object {
"child": Array [
Object {
"child": Array [
Object {
"child": Array [
Object {
"endTime": "45678",
"parentType": "Book",
"responseName": "title",
"startTime": "34567",
"type": "String",
},
Object {
"endTime": "45678",
"parentType": "Book",
"responseName": "year",
"startTime": "34567",
"type": "Int",
},
],
"index": 0,
},
Object {
"child": Array [
Object {
"endTime": "45678",
"parentType": "Book",
"responseName": "title",
"startTime": "34567",
"type": "String",
},
Object {
"endTime": "45678",
"parentType": "Book",
"responseName": "year",
"startTime": "34567",
"type": "Int",
},
],
"index": 1,
},
],
"endTime": "45678",
"parentType": "Query",
"responseName": "_entities",
"startTime": "34567",
"type": "[_Entity]!",
},
],
},
"startTime": Object {
"nanos": 123000000,
"seconds": "1562203363",
},
},
"traceParsingFailed": false,
},
},
"responsePath": Array [
Object {
"fieldName": "topProducts",
},
Object {
"fieldName": "@",
},
],
},
},
Object {
"flatten": Object {
"node": Object {
"fetch": Object {
"receivedTime": Object {
"nanos": 123000000,
"seconds": "1562203363",
},
"sentTime": Object {
"nanos": 123000000,
"seconds": "1562203363",
},
"sentTimeOffset": 23456,
"serviceName": "product",
"trace": Object {
"durationNs": 12345,
"endTime": Object {
"nanos": 123000000,
"seconds": "1562203363",
},
"root": Object {
"child": Array [
Object {
"child": Array [
Object {
"child": Array [
Object {
"endTime": "45678",
"parentType": "Book",
"responseName": "name",
"startTime": "34567",
"type": "String",
},
],
"index": 0,
},
Object {
"child": Array [
Object {
"endTime": "45678",
"parentType": "Book",
"responseName": "name",
"startTime": "34567",
"type": "String",
},
],
"index": 1,
},
],
"endTime": "45678",
"parentType": "Query",
"responseName": "_entities",
"startTime": "34567",
"type": "[_Entity]!",
},
],
},
"startTime": Object {
"nanos": 123000000,
"seconds": "1562203363",
},
},
"traceParsingFailed": false,
},
},
"responsePath": Array [
Object {
"fieldName": "topProducts",
},
Object {
"fieldName": "@",
},
],
},
},
],
},
},
],
},
},
"registeredOperation": false,
"root": Object {},
"startTime": Object {
"nanos": 123000000,
"seconds": "1562203363",
},
},
],
},
},
}
`);
});
}); | the_stack |
// @ui {"widget":"group_start", "label":"Video Control"}
// @input bool showVideo = true
// @input Asset.Texture movie { "label":"Background Video" }
// @ui {"widget":"group_end"}
// @ui {"widget":"label"}
// @ui {"widget":"group_start", "label":"Tracked Image Control"}
// @input Asset.Texture mainImage { "label":"Image" }
// @input Asset.Texture opacityTexture { "label":"Opacity Image" }
// @input float imageSize = 0.5 {"label":"Size", "widget":"slider", "min":0.0, "max":1.0, "step":0.01}
// @input float imageOffsetX = 0.0 {"label":"Offset X","widget":"slider", "min":-1.0, "max":1.0, "step":0.01}
// @input float imageOffsetY = 0.0 {"label":"Offset Y", "widget":"slider", "min":-1.0, "max":1.0, "step":0.01}
// @input float imageRotation = 0.0 {"label":"Rotate","widget":"slider", "min":0.0, "max":360.0, "step":0.5}
// @input float imageAlpha = 1.0 {"label":"Alpha","widget":"slider", "min":0.0, "max":1.0, "step":0.1}
// @input int imageSort {"widget":"combobox", "values":[{"label":"In Front of Video", "value":0}, {"label":"Behind Video", "value":1}, {"label":"Manual Sorting", "value":2}]}
// @ui {"widget":"group_end"}
// @ui {"widget":"label"}
// @ui {"widget":"separator"}
// @input bool advanced
// @ui {"widget":"group_start", "label":"Tracking Control", "showIf": "advanced"}
// @input bool trackPosition = true {"label":"Position"}
// @input bool trackScale = true {"label":"Scale"}
// @input bool trackRotation = true {"label":"Rotation"}
// @ui {"widget":"group_end"}
// @ui {"widget":"separator", "showIf": "advanced"}
// @input Component.ScreenTransform trackedImageTransform {"showIf": "advanced"}
// @input Component.Image movieImage {"showIf": "advanced"}
// @input Component.ScreenTransform extentsTarget {"showIf": "advanced"}
// @input Component.Image backgroundImage {"showIf": "advanced"}
// @input Component.Image errorImage {"showIf": "advanced"}
import type { AnimationData } from './animation-data';
declare global {
interface Pass {
/** Specifies the base color (albedo) of the material if the ‘Base Texture’ is disabled. Multiplied with the ‘Base Texture’ otherwise. */
baseColor: vec4;
/** Most materials use a base texture (albedo), but disabling it means the base texture will be considered white, and ‘Base Color’ will solely control the color. */
baseTex: Asset.Texture;
/**
* Normally, the Base Texture’s alpha is taken as opacity. Enabling this allows you to define a separate greyscale opacity texture. The ‘Opacity Texture’ value will be multiplied with the
* Base Texture’s alpha (which is 1 for textures without alpha) to get the final opacity. ‘Opacity Texture’ is only available if ‘Blend Mode’ is not ‘Disabled’.
*/
opacityTex: Asset.Texture;
}
namespace SnapchatLensStudio {
interface ScriptInputs {
showVideo: boolean;
movie: Asset.Texture;
mainImage: Asset.Texture;
opacityTexture: Asset.Texture;
imageSize: number;
imageOffsetX: number;
imageOffsetY: number;
imageRotation: number;
imageAlpha: number;
imageSort: number;
advanced: boolean;
trackPosition: boolean;
trackScale: boolean;
trackRotation: boolean;
trackedImageTransform: Component.ScreenTransform;
movieImage: Component.Image;
extentsTarget: Component.ScreenTransform;
backgroundImage: Component.Image;
errorImage: Component.Image;
}
}
}
let animationData: AnimationData;
let provider: AnimatedTextureFileProvider;
let timer = 0;
let timeLimit: number;
let startTime = 0;
let startingPositionOffset: vec2;
let startingScaleOffset: vec2;
let startingRotationOffset: quat;
let animatedTextureInitialized = false;
const {
showVideo,
movie,
mainImage,
opacityTexture,
imageSize,
imageOffsetX,
imageOffsetY,
imageRotation,
imageAlpha,
imageSort,
advanced,
trackPosition,
trackScale,
trackRotation,
trackedImageTransform,
movieImage,
extentsTarget,
backgroundImage,
errorImage,
} = script;
initialize();
function initialize() {
findAnimationData();
if (checkProperties()) {
setupTracking();
configureImageTransform({
mainImage,
opacityTexture,
trackedImageTransform,
imageSize,
imageOffsetX,
imageOffsetY,
imageRotation,
imageAlpha,
});
}
}
function configureImageTransform({
mainImage: texture,
opacityTexture,
trackedImageTransform: objectsToTransform,
imageSize: scaleToAdd,
imageOffsetX: xOffsetToAdd,
imageOffsetY: yOffsetToAdd,
imageRotation: rotationToAdd,
imageAlpha,
}: Pick<
SnapchatLensStudio.ScriptInputs,
| 'mainImage'
| 'opacityTexture'
| 'trackedImageTransform'
| 'imageSize'
| 'imageOffsetX'
| 'imageOffsetY'
| 'imageRotation'
| 'imageAlpha'
>) {
const scaleMultiplier = 20;
const degToRad = 0.0175;
const screenTransform = objectsToTransform;
const trackedImageComp = getImageComponent(screenTransform);
trackedImageComp.mainPass.baseTex = texture;
if (opacityTexture) {
trackedImageComp.mainPass.opacityTex = opacityTexture;
}
trackedImageComp.mainPass.baseColor = setAlpha(trackedImageComp.mainPass.baseColor, imageAlpha);
const anchors = screenTransform.anchors;
const offsets = screenTransform.offsets;
const aspectScaling = new vec2(1, 1);
const aspect = texture.control.getAspect();
if (aspect > 1) {
aspectScaling.x *= aspect;
} else {
aspectScaling.y /= aspect;
}
offsets.setSize(aspectScaling.uniformScale(scaleToAdd * scaleMultiplier));
const offsetVec = new vec3(xOffsetToAdd, yOffsetToAdd, 0);
anchors.left += offsetVec.x;
anchors.right += offsetVec.x;
anchors.top += offsetVec.y;
anchors.bottom += offsetVec.y;
const rotateTo = screenTransform.rotation.multiply(quat.angleAxis(rotationToAdd * degToRad, vec3.forward()));
screenTransform.rotation = rotateTo;
startingPositionOffset = screenTransform.anchors.getCenter();
startingScaleOffset = screenTransform.offsets.getSize();
startingRotationOffset = screenTransform.rotation;
}
function setupTracking() {
if (!showVideo) {
movieImage.enabled = false;
if (movie) {
print('WARNING: Please remove Background Video texture from the script component to save memory.');
}
} else {
movieImage.mainPass.baseTex = movie;
}
errorImage.enabled = false;
movieImage.extentsTarget = extentsTarget;
let trackedImageMesh: Component.Image;
let moveImageMesh: Component.Image;
if (imageSort === 0) {
trackedImageMesh = getImageComponent(trackedImageTransform);
moveImageMesh = getImageComponent(movieImage);
trackedImageMesh.setRenderOrder(moveImageMesh.getRenderOrder() + 1);
if (backgroundImage) {
backgroundImage.setRenderOrder(moveImageMesh.getRenderOrder() - 1);
}
} else if (imageSort === 1) {
trackedImageMesh = getImageComponent(trackedImageTransform);
moveImageMesh = getImageComponent(movieImage);
trackedImageMesh.setRenderOrder(moveImageMesh.getRenderOrder() - 1);
if (backgroundImage) {
backgroundImage.setRenderOrder(trackedImageMesh.getRenderOrder() - 1);
}
}
if (!showVideo) {
animatedTextureInitialized = true;
} else {
playAnimatedTexture();
}
setAnimatedTextureTime(0);
}
function playAnimatedTexture() {
const isAnimated = 'getDuration' in movie.control;
if (isAnimated) {
provider = movie.control as AnimatedTextureFileProvider;
provider.pause();
provider.isAutoplay = false;
if (animationData.duration + 1 !== provider.getFramesCount()) {
showError(
"ERROR: Exported tracking data frame numbers don't match the animated texture duration. Make sure to export the whole comp in After Effects or trim your comp.",
);
return;
}
const providerDurationCheck = roundToNearest(animationData.duration / animationData.frameRate);
const providerDuration = roundToNearest(provider.getDuration());
if (providerDuration !== providerDurationCheck) {
showError('ERROR: You need to set the duration on animated texture to: ' + providerDurationCheck);
return;
}
animatedTextureInitialized = true;
} else {
showError("ERROR: Please assign a 2D Animated Texture file in the Video's texture input");
return;
}
}
function setAnimatedTextureTime(overtime: number) {
startTime = getTime() - (overtime || 0);
}
function positionImage(frame: number) {
if (animationData.positions[frame] !== null) {
if (trackPosition) {
const screenPos = animationData.positions[frame];
const offsetPos = startingPositionOffset.add(screenPos);
const worldPoint = extentsTarget.localPointToWorldPoint(offsetPos);
const parentPoint = trackedImageTransform.worldPointToParentPoint(worldPoint);
trackedImageTransform.anchors.setCenter(parentPoint);
}
if (trackScale) {
const { x, y } = animationData.scales[frame];
const trackedScale = new vec2(x, y).uniformScale(1 / 100);
const newScale = startingScaleOffset.mult(trackedScale);
trackedImageTransform.offsets.setSize(newScale);
}
if (trackRotation) {
const rot = quat.fromEulerVec(animationData.rotations[frame].uniformScale(-Math.PI / 180));
const rotateTo = startingRotationOffset.multiply(rot);
trackedImageTransform.rotation = rotateTo;
}
}
}
function trackAnimatedTexture() {
if (animatedTextureInitialized) {
const frameNumber = Math.floor(timer * animationData.frameRate);
if (frameNumber <= animationData.duration) {
positionImage(frameNumber);
if (showVideo) {
provider.playFromFrame(frameNumber, -1);
}
}
}
}
script.createEvent('UpdateEvent').bind(function onUpdate() {
playBackTimer();
trackAnimatedTexture();
});
function playBackTimer() {
timer = getTime() - startTime;
if (timer > timeLimit) {
let overtime = timer - timeLimit;
overtime = overtime % timeLimit;
setAnimatedTextureTime(overtime);
}
}
function findAnimationData() {
const results: AnimationData[] = [];
const allComponents = script.getSceneObject().getComponents('Component.ScriptComponent');
for (const component of allComponents) {
if (component.api) {
if (component.api.animationData) {
results.push(component.api.animationData);
}
}
}
if (results.length < 1) {
return;
}
if (results.length > 1) {
showError(
'WARNING: There are multiple Tracking Data scripts on the faceInVideoController [EDIT_ME] object. Please make sure to only have one',
);
}
animationData = results[results.length - 1];
timeLimit = animationData.duration / animationData.frameRate;
}
function roundToNearest(value: number) {
return Math.round(value * 1000) / 1000;
}
function getImageComponent(obj: Component) {
return obj.getSceneObject().getComponent('Component.Image');
}
function setAlpha(color: vec4, alpha: number) {
return new vec4(color.r, color.g, color.b, alpha);
}
function checkProperties() {
if (!animationData) {
showError(
'ERROR: Tracking data not found. Please place the tracking data on the FaceInVideoController [EDIT_ME] object',
);
return false;
}
if (!mainImage) {
showError('ERROR: Please assign a texture to Image texture input on FaceInVideoController script.');
return false;
}
if (!trackedImageTransform) {
showError(
'ERROR: Please make sure Tracked Image object exists and assign the Tracked Image object under the advanced checkbox',
);
return false;
}
if (!movieImage) {
showError(
'ERROR: Please make sure Movie Image object exists and assign the Movie Image object under the advanced checkbox',
);
return false;
}
if (!extentsTarget) {
showError(
'ERROR: Please make sure Movie Image object exists and assign the Movie Image object under the advanced checkbox',
);
return false;
}
if (!backgroundImage) {
showError('WARNING: Please make sure Background Image object exists and assigned under the advanced checkbox');
}
if (!movie && showVideo) {
showError('ERROR: Please assign a video or animated texture to Video input on FaceInVideoController script.');
return false;
}
return true;
}
function showError(message: string) {
if (errorImage) {
errorImage.enabled = true;
}
print('FaceInVideoController, ' + message);
} | the_stack |
import { mat4, vec2, vec3 } from 'webgl-operate';
import {
AccumulatePass,
AntiAliasingKernel,
BlitPass,
Camera,
Canvas,
Context,
CuboidGeometry,
DefaultFramebuffer,
EventProvider,
Framebuffer,
Invalidate,
Navigation,
NdcFillingTriangle,
PlaneGeometry,
Program,
Renderbuffer,
Renderer,
Shader,
ShadowPass,
Texture2D,
Wizard,
} from 'webgl-operate';
import { Example } from './example';
/* spellchecker: enable */
// tslint:disable:max-classes-per-file
class ShadowMapMultiframeRenderer extends Renderer {
protected _cuboids: Array<CuboidGeometry>;
protected _plane: PlaneGeometry;
protected _ndcTriangle: NdcFillingTriangle;
protected _defaultFBO: DefaultFramebuffer;
protected _colorRenderTexture: Texture2D;
protected _depthRenderbuffer: Renderbuffer;
protected _intermediateFBO: Framebuffer;
protected _navigation: Navigation;
protected _camera: Camera;
protected _light: Camera;
protected _lightSamples: Array<vec3>;
protected _ndcOffsetKernel: AntiAliasingKernel;
protected _uNdcOffset: WebGLUniformLocation;
protected _program: Program;
protected _uViewProjection: WebGLUniformLocation;
protected _uModel: WebGLUniformLocation;
protected _uColored: WebGLUniformLocation;
protected _uLightViewProjection: WebGLUniformLocation;
protected _uLightPosition: WebGLUniformLocation;
protected _shadowProgram: Program;
protected _uModelS: WebGLUniformLocation;
protected _uLightViewProjectionS: WebGLUniformLocation;
protected _uLightPositionS: WebGLUniformLocation;
protected _shadowPass: ShadowPass;
protected _accumulate: AccumulatePass;
protected _blit: BlitPass;
protected onInitialize(context: Context, callback: Invalidate,
eventProvider: EventProvider): boolean {
context.enable(['ANGLE_instanced_arrays', 'OES_standard_derivatives',
'WEBGL_color_buffer_float', 'OES_texture_float', 'OES_texture_float_linear']);
this._defaultFBO = new DefaultFramebuffer(context, 'DefaultFBO');
this._defaultFBO.initialize();
this._defaultFBO.bind();
const gl = context.gl as WebGLRenderingContext;
const gl2facade = this._context.gl2facade;
this._cuboids = new Array(4);
for (let i = 0; i < this._cuboids.length; ++i) {
this._cuboids[i] = new CuboidGeometry(context, 'cube', true, [0.25, 0.5 + 0.5 * i, 2.0]);
this._cuboids[i].initialize();
}
this._plane = new PlaneGeometry(context, 'plane');
this._plane.initialize();
this._plane.scale = vec2.fromValues(100, 100);
this._ndcTriangle = new NdcFillingTriangle(this._context);
this._ndcTriangle.initialize();
if (this._camera === undefined) {
this._camera = new Camera();
this._camera.center = vec3.fromValues(0.0, 0.75, 0.0);
this._camera.up = vec3.fromValues(0.0, 1.0, 0.0);
this._camera.eye = vec3.fromValues(1.8, 2.6, 3.4);
this._camera.near = 2.0;
this._camera.far = 11.0;
}
if (this._light === undefined) {
this._light = new Camera();
this._light.center = vec3.fromValues(0.0, 0.0, 0.0);
this._light.up = vec3.fromValues(0.0, 1.0, 0.0);
this._light.eye = vec3.fromValues(-3.0, 5.0, 4.0);
this._light.near = 3.0;
this._light.far = 20.0;
}
this._colorRenderTexture = new Texture2D(this._context, 'ColorRenderTexture');
this._depthRenderbuffer = new Renderbuffer(this._context, 'DepthRenderbuffer');
this._intermediateFBO = new Framebuffer(this._context, 'IntermediateFBO');
const vert = new Shader(context, gl.VERTEX_SHADER, 'mesh-shadowed.vert');
vert.initialize(require('./data/mesh-shadowed.vert'));
const frag = new Shader(context, gl.FRAGMENT_SHADER, 'mesh-shadowed.frag');
frag.initialize(require('./data/mesh-shadowed-multiframe.frag'));
this._program = new Program(context, 'MeshShadowedProgram');
this._program.initialize([vert, frag], false);
this._program.attribute('a_vertex', this._cuboids[0].vertexLocation);
this._program.attribute('a_texCoord', this._cuboids[0].uvCoordLocation);
this._program.link();
this._program.bind();
gl.uniform2f(this._program.uniform('u_lightNearFar'), this._light.near, this._light.far);
gl.uniform1i(this._program.uniform('u_shadowMap'), 0);
this._uViewProjection = this._program.uniform('u_viewProjection');
this._uModel = this._program.uniform('u_model');
this._uLightViewProjection = this._program.uniform('u_lightViewProjection');
this._uLightPosition = this._program.uniform('u_lightPosition');
this._uNdcOffset = this._program.uniform('u_ndcOffset');
this._uColored = this._program.uniform('u_colored');
const shadowVert = new Shader(context, gl.VERTEX_SHADER, 'shadow.vert');
shadowVert.initialize(require('./data/shadow.vert'));
const shadowFrag = new Shader(context, gl.FRAGMENT_SHADER, 'shadow.frag');
shadowFrag.initialize(require('./data/shadow-multiframe.frag'));
this._shadowProgram = new Program(context);
this._shadowProgram.initialize([shadowVert, shadowFrag], false);
this._shadowProgram.attribute('a_vertex', this._cuboids[0].vertexLocation);
this._shadowProgram.link();
this._shadowProgram.bind();
gl.uniform2f(this._shadowProgram.uniform('u_lightNearFar'), this._light.near, this._light.far);
this._uModelS = this._shadowProgram.uniform('u_model');
this._uLightViewProjectionS = this._shadowProgram.uniform('u_lightViewProjection');
this._uLightPositionS = this._shadowProgram.uniform('u_lightPosition');
this._navigation = new Navigation(callback, eventProvider);
this._navigation.camera = this._camera;
this._accumulate = new AccumulatePass(context);
this._accumulate.initialize(this._ndcTriangle);
this._accumulate.precision = this._framePrecision;
this._accumulate.texture = this._colorRenderTexture;
this._blit = new BlitPass(this._context);
this._blit.initialize(this._ndcTriangle);
this._blit.readBuffer = gl2facade.COLOR_ATTACHMENT0;
this._blit.drawBuffer = gl.BACK;
this._blit.target = this._defaultFBO;
this._shadowPass = new ShadowPass(context);
this._shadowPass.initialize(ShadowPass.ShadowMappingType.HardLinear, [1024, 1024]);
this.finishLoading();
return true;
}
protected onUninitialize(): void {
super.uninitialize();
this._defaultFBO.uninitialize();
for (const cuboid of this._cuboids) {
cuboid.uninitialize();
}
this._plane.uninitialize();
this._ndcTriangle.uninitialize();
this._shadowPass.uninitialize();
}
protected onDiscarded(): void {
this._altered.alter('canvasSize');
this._altered.alter('clearColor');
this._altered.alter('frameSize');
}
protected onUpdate(): boolean {
this._navigation.update();
return this._camera.altered;
}
protected onPrepare(): void {
const gl = this._context.gl;
const gl2facade = this._context.gl2facade;
if (!this._intermediateFBO.initialized) {
this._colorRenderTexture.initialize(this._frameSize[0], this._frameSize[1],
this._context.isWebGL2 ? gl.RGBA8 : gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE);
this._depthRenderbuffer.initialize(this._frameSize[0], this._frameSize[1], gl.DEPTH_COMPONENT16);
this._intermediateFBO.initialize([[gl2facade.COLOR_ATTACHMENT0, this._colorRenderTexture]
, [gl.DEPTH_ATTACHMENT, this._depthRenderbuffer]]);
this._intermediateFBO.clearColor([1.0, 1.0, 1.0, 1.0]);
}
if (this._altered.frameSize) {
this._intermediateFBO.resize(this._frameSize[0], this._frameSize[1]);
this._camera.viewport = [this._frameSize[0], this._frameSize[1]];
}
if (this._altered.canvasSize) {
this._camera.aspect = this._canvasSize[0] / this._canvasSize[1];
}
if (this._altered.clearColor) {
this._defaultFBO.clearColor(this._clearColor);
}
if (this._altered.multiFrameNumber) {
this._ndcOffsetKernel = new AntiAliasingKernel(this._multiFrameNumber);
// /* Create light samples along circle around eye (light position). */
const n = vec3.sub(vec3.create(), this._light.eye, this._light.center);
vec3.normalize(n, n);
const u = vec3.cross(vec3.create(), n, vec3.fromValues(0.0, 1.0, 0.0));
const v = vec3.cross(vec3.create(), n, u);
this._lightSamples = new Array<vec3>(this._multiFrameNumber);
for (let i = 0; i < this._multiFrameNumber; ++i) {
const p = vec3.clone(this._light.eye);
const r = Math.random() * 0.25; // Math.sqrt(i / this._multiFrameNumber);
const theta = Math.random() * Math.PI * 2.0;
vec3.scaleAndAdd(p, p, u, r * Math.cos(theta));
vec3.scaleAndAdd(p, p, v, r * Math.sin(theta));
this._lightSamples[i] = p;
}
this._lightSamples.sort((a: vec3, b: vec3) =>
vec3.sqrDist(a, this._light.eye) - vec3.sqrDist(b, this._light.eye));
}
this._accumulate.update();
this._altered.reset();
this._camera.altered = false;
}
protected onFrame(frameNumber: number): void {
const gl = this._context.gl as WebGLRenderingContext;
this._light.eye = this._lightSamples[frameNumber];
this._shadowPass.frame(() => {
gl.enable(gl.DEPTH_TEST);
this._shadowProgram.bind();
gl.uniformMatrix4fv(this._uLightViewProjectionS, false, this._light.viewProjection);
gl.uniform3fv(this._uLightPositionS, this._light.eye);
this.drawCuboids(this._uModelS);
this._shadowProgram.unbind();
gl.disable(gl.DEPTH_TEST);
});
this._intermediateFBO.bind();
this._intermediateFBO.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT, true, false);
gl.viewport(0, 0, this._frameSize[0], this._frameSize[1]);
const ndcOffset = this._ndcOffsetKernel.get(frameNumber);
ndcOffset[0] = 2.0 * ndcOffset[0] / this._frameSize[0];
ndcOffset[1] = 2.0 * ndcOffset[1] / this._frameSize[1];
gl.enable(gl.DEPTH_TEST);
gl.enable(gl.CULL_FACE);
this._program.bind();
gl.uniformMatrix4fv(this._uViewProjection, false, this._camera.viewProjection);
gl.uniformMatrix4fv(this._uLightViewProjection, false, this._light.viewProjection);
gl.uniform3fv(this._uLightPosition, this._light.eye);
gl.uniform2fv(this._uNdcOffset, ndcOffset);
this._shadowPass.shadowMapTexture.bind(gl.TEXTURE0);
gl.uniform1i(this._uColored, Number(true));
this.drawCuboids(this._uModel);
gl.uniform1i(this._uColored, Number(false));
this.drawPlane(this._uModel);
this._program.unbind();
this._shadowPass.shadowMapTexture.unbind();
gl.disable(gl.DEPTH_TEST);
gl.disable(gl.CULL_FACE);
this._accumulate.frame(frameNumber);
}
protected onSwap(): void {
this._blit.framebuffer = this._accumulate.framebuffer ?
this._accumulate.framebuffer : this._blit.framebuffer = this._intermediateFBO;
this._blit.frame();
}
protected drawCuboids(model: WebGLUniformLocation): void {
const gl = this._context.gl;
const M = mat4.create();
for (let i = 0; i < this._cuboids.length; ++i) {
const x = i * 0.5 - 0.75;
const y = this._cuboids[i].extent[1] * 0.5;
mat4.fromTranslation(M, vec3.fromValues(-x, y, 0.0));
gl.uniformMatrix4fv(model, false, M);
this._cuboids[i].bind();
this._cuboids[i].draw();
}
}
protected drawPlane(model: WebGLUniformLocation): void {
const gl = this._context.gl;
gl.uniformMatrix4fv(model, false, this._plane.transformation);
this._plane.bind();
this._plane.draw();
}
}
export class ShadowMapMultiframeExample extends Example {
private _canvas: Canvas;
private _renderer: ShadowMapMultiframeRenderer;
onInitialize(element: HTMLCanvasElement | string): boolean {
this._canvas = new Canvas(element);
this._canvas.framePrecision = Wizard.Precision.half;
this._canvas.frameScale = [1.0, 1.0];
this._canvas.clearColor.fromHex('ffffff');
this._canvas.controller.multiFrameNumber = 128;
this._renderer = new ShadowMapMultiframeRenderer();
this._canvas.renderer = this._renderer;
return true;
}
onUninitialize(): void {
this._canvas.dispose();
(this._renderer as Renderer).uninitialize();
}
get canvas(): Canvas {
return this._canvas;
}
get renderer(): ShadowMapMultiframeRenderer {
return this._renderer;
}
} | the_stack |
import VData from '../VData'
import {
mount,
MountOptions,
Wrapper,
} from '@vue/test-utils'
describe('VData.ts', () => {
type Instance = InstanceType<typeof VData>
let mountFunction: (options?: MountOptions<Instance>) => Wrapper<Instance>
beforeEach(() => {
mountFunction = (options?: MountOptions<Instance>) => {
return mount(VData, {
...options,
sync: false,
})
}
})
it('should render data through default scoped slot', async () => {
const wrapper = mountFunction({
propsData: {
items: [
{ id: 1, text: 'foo' },
{ id: 2, text: 'bar' },
],
},
scopedSlots: {
default (data) {
return this.$createElement('div', data.items.map(item => this.$createElement('div', [item.text])))
},
},
})
await wrapper.vm.$nextTick()
expect(wrapper.html()).toMatchSnapshot()
})
it('should ignore items length if using server-items-length', async () => {
const render = jest.fn()
const wrapper = mountFunction({
propsData: {
items: [
{ id: 1, text: 'foo' },
{ id: 2, text: 'bar' },
],
},
scopedSlots: {
default: render,
},
})
await wrapper.vm.$nextTick()
expect(render).toHaveBeenCalledWith(expect.objectContaining({
pagination: expect.objectContaining({
itemsLength: 2,
}),
}))
wrapper.setProps({
serverItemsLength: 10,
})
await wrapper.vm.$nextTick()
expect(render).toHaveBeenCalledWith(expect.objectContaining({
pagination: expect.objectContaining({
itemsLength: 10,
}),
}))
})
it('should group items', async () => {
const render = jest.fn()
const items = [
{ id: 1, text: 'foo', baz: 'one' },
{ id: 2, text: 'bar', baz: 'two' },
{ id: 3, text: 'baz', baz: 'one' },
]
const wrapper = mountFunction({
propsData: {
items,
groupBy: ['baz'],
},
scopedSlots: {
default: render,
},
})
expect(render).toHaveBeenCalledWith(expect.objectContaining({
groupedItems: [
{
name: 'one',
items: [items[0], items[2]],
},
{
name: 'two',
items: [items[1]],
},
],
}))
})
it('should group items with null key and missing key as a null group', async () => {
const render = jest.fn()
const items = [
{ id: 1, text: 'foo', baz: null },
{ id: 2, text: 'bar', baz: 'one' },
{ id: 3, text: 'baz' },
]
const wrapper = mountFunction({
propsData: {
items,
groupBy: ['baz'],
},
scopedSlots: {
default: render,
},
})
expect(render).toHaveBeenCalledWith(expect.objectContaining({
groupedItems: [
{
name: '',
items: [items[0], items[2]],
},
{
name: 'one',
items: [items[1]],
},
],
}))
})
it('should group items by deep keys', async () => {
const render = jest.fn()
const items = [
{ id: 1, text: 'foo', foo: { bar: 'one' } },
{ id: 2, text: 'bar', foo: { bar: 'two' } },
{ id: 3, text: 'baz', foo: { bar: 'one' } },
]
const wrapper = mountFunction({
propsData: {
items,
groupBy: ['foo.bar'],
},
scopedSlots: {
default: render,
},
})
expect(render).toHaveBeenCalledWith(expect.objectContaining({
groupedItems: [
{
name: 'one',
items: [items[0], items[2]],
},
{
name: 'two',
items: [items[1]],
},
],
}))
})
it('should group items with a custom group function', async () => {
const render = jest.fn()
const items = [
{ id: 1, text: 'foo', value: 1 },
{ id: 2, text: 'bar', value: 4 },
{ id: 3, text: 'baz', value: 3 },
]
const wrapper = mountFunction({
propsData: {
items,
groupBy: ['value'],
customGroup: function evenOddGrouper (items: any[], groupBy: string[]) {
const key = groupBy[0]
return items.reduce((rv, x) => {
const group = x[key] % 2 ? 'odd' : 'even';
(rv[group] = rv[group] || []).push(x)
return rv
}, {})
},
},
scopedSlots: {
default: render,
},
})
expect(render).toHaveBeenCalledWith(expect.objectContaining({
groupedItems: {
even: [items[1]],
odd: [items[0], items[2]],
},
}))
})
it('should sort items', () => {
const render = jest.fn()
const unsorted = [
{ id: 1, text: 'c' },
{ id: 2, text: 'a' },
{ id: 3, text: 'd' },
{ id: 4, text: 'b' },
]
const sorted = [
{ id: 2, text: 'a' },
{ id: 4, text: 'b' },
{ id: 1, text: 'c' },
{ id: 3, text: 'd' },
]
const wrapper = mountFunction({
propsData: {
items: unsorted,
sortBy: ['text'],
},
scopedSlots: {
default: render,
},
})
expect(render).toHaveBeenCalledWith(expect.objectContaining({
items: sorted,
}))
})
it('should sort items by multiple properties', async () => {
const render = jest.fn()
const unsorted = [
{ id: 1, foo: 'a', bar: 'b' },
{ id: 2, foo: 'b', bar: 'b' },
{ id: 3, foo: 'b', bar: 'a' },
{ id: 4, foo: 'a', bar: 'a' },
]
const sorted = [
{ id: 4, foo: 'a', bar: 'a' },
{ id: 1, foo: 'a', bar: 'b' },
{ id: 3, foo: 'b', bar: 'a' },
{ id: 2, foo: 'b', bar: 'b' },
]
const wrapper = mountFunction({
propsData: {
items: unsorted,
sortBy: ['foo'],
},
scopedSlots: {
default: render,
},
})
await wrapper.vm.$nextTick()
wrapper.setProps({
sortBy: ['foo', 'bar'],
})
await wrapper.vm.$nextTick()
expect(render).toHaveBeenCalledWith(expect.objectContaining({
items: sorted,
}))
})
it('should paginate items', () => {
const render = jest.fn()
const items = [
{ id: 1, foo: 'a' },
{ id: 2, foo: 'b' },
{ id: 3, foo: 'c' },
{ id: 4, foo: 'd' },
{ id: 5, foo: 'e' },
{ id: 6, foo: 'f' },
{ id: 7, foo: 'g' },
{ id: 8, foo: 'h' },
{ id: 9, foo: 'i' },
{ id: 10, foo: 'j' },
]
const wrapper = mountFunction({
propsData: {
items,
itemsPerPage: 5,
page: 2,
},
scopedSlots: {
default: render,
},
})
expect(render).toHaveBeenCalledWith(expect.objectContaining({
items: items.slice(5),
}))
})
it('should not sort items if disableSort is active', () => {
const render = jest.fn()
const items = [
{ text: 'Foo', id: 1 },
{ text: 'Bar', id: 2 },
{ text: 'Fizz', id: 3 },
{ text: 'Buzz', id: 4 },
{ text: 'Fizzbuzz', id: 5 },
]
const wrapper = mountFunction({
propsData: {
items,
sortBy: ['text'],
disableSort: true,
},
scopedSlots: {
default: render,
},
})
expect(render).toHaveBeenCalledWith(expect.objectContaining({
items,
}))
})
it('should conditionally paginate items', async () => {
const render = jest.fn()
const items = [
{ text: 'Foo', id: 1 },
{ text: 'Bar', id: 2 },
{ text: 'Fizz', id: 3 },
{ text: 'Buzz', id: 4 },
{ text: 'Fizzbuzz', id: 5 },
]
const wrapper = mountFunction({
propsData: { items },
scopedSlots: {
default: render,
},
})
expect(render).toHaveBeenCalledWith(expect.objectContaining({
items,
}))
wrapper.setProps({ itemsPerPage: 2 })
await wrapper.vm.$nextTick()
expect(render).toHaveBeenCalledWith(expect.objectContaining({
items: items.slice(0, 2),
}))
wrapper.setProps({ disablePagination: true })
await wrapper.vm.$nextTick()
expect(render).toHaveBeenCalledWith(expect.objectContaining({
items,
}))
})
it('should toggle sorting', async () => {
const unsorted = [
{ id: 1, text: 'c' },
{ id: 2, text: 'a' },
{ id: 3, text: 'd' },
{ id: 4, text: 'b' },
]
const wrapper = mountFunction({
propsData: {
items: unsorted,
},
scopedSlots: {
default (props) {
const items = props.items.map(item => this.$createElement('div', [item.text]))
return this.$createElement('div', {
attrs: {
id: 'wrapper',
},
on: {
click: () => props.sort('text'),
},
}, items)
},
},
})
expect(wrapper.html()).toMatchSnapshot()
const el = wrapper.find('#wrapper').element
el.click()
await wrapper.vm.$nextTick()
expect(wrapper.html()).toMatchSnapshot()
el.click()
await wrapper.vm.$nextTick()
expect(wrapper.html()).toMatchSnapshot()
})
it('should toggle sorting on multiple properties', async () => {
const unsorted = [
{ id: 1, text: 'c', group: 'foo' },
{ id: 2, text: 'a', group: 'bar' },
{ id: 3, text: 'd', group: 'foo' },
{ id: 4, text: 'b', group: 'bar' },
]
const wrapper = mountFunction({
propsData: {
items: unsorted,
},
scopedSlots: {
default (props) {
const items = props.items.map(item => this.$createElement('div', [`${item.group}-${item.text}`]))
return this.$createElement('div', {
attrs: {
id: 'wrapper',
},
on: {
click: () => props.sort(['group', 'text']),
},
}, items)
},
},
})
expect(wrapper.html()).toMatchSnapshot()
const el = wrapper.find('#wrapper').element
el.click()
await wrapper.vm.$nextTick()
expect(wrapper.html()).toMatchSnapshot()
})
it('should toggle grouping', async () => {
const unsorted = [
{ id: 1, text: 'c', group: 'foo' },
{ id: 4, text: 'a', group: 'bar' },
{ id: 3, text: 'd', group: 'foo' },
{ id: 2, text: 'b', group: 'bar' },
]
const wrapper = mountFunction({
propsData: {
items: unsorted,
},
scopedSlots: {
default (props) {
const items = props.groupedItems
? props.groupedItems.map(group => group.name)
: props.items.map(item => item.text)
return this.$createElement('div', {
attrs: {
id: 'wrapper',
},
on: {
click: () => props.group('group'),
},
}, items.map(item => this.$createElement('div', [item])))
},
},
})
expect(wrapper.html()).toMatchSnapshot()
const el = wrapper.find('#wrapper').element
el.click()
await wrapper.vm.$nextTick()
expect(wrapper.html()).toMatchSnapshot()
})
// https://github.com/vuetifyjs/vuetify/issues/10372
it('should handle setting itemsPerPage to zero', async () => {
const render = jest.fn()
const wrapper = mountFunction({
propsData: {
items: [
{ id: 1, text: 'foo' },
{ id: 2, text: 'bar' },
],
itemsPerPage: 0,
},
scopedSlots: {
default: render,
},
})
await wrapper.vm.$nextTick()
expect(render).toHaveBeenCalledWith(expect.objectContaining({
pagination: expect.objectContaining({
itemsPerPage: 0,
page: 1,
pageCount: 1,
pageStart: 0,
pageStop: 0,
}),
}))
wrapper.setProps({
itemsPerPage: 1,
})
await wrapper.vm.$nextTick()
expect(render).toHaveBeenCalledWith(expect.objectContaining({
pagination: expect.objectContaining({
itemsPerPage: 1,
page: 1,
pageCount: 2,
pageStart: 0,
pageStop: 1,
}),
}))
})
// https://github.com/vuetifyjs/vuetify/issues/10627
it('should sort grouped column', async () => {
const unsorted = [
{ id: 1, text: 'c', group: 'foo' },
{ id: 4, text: 'a', group: 'bar' },
{ id: 3, text: 'd', group: 'foo' },
{ id: 2, text: 'b', group: 'bar' },
]
const wrapper = mountFunction({
propsData: {
items: unsorted,
groupBy: ['text'],
},
scopedSlots: {
default (props) {
return this.$createElement('div', {
attrs: {
id: 'wrapper',
},
on: {
click: () => props.group('group'),
},
}, props.groupedItems.map(group => this.$createElement('div', [group.name])))
},
},
})
wrapper.setProps({ groupDesc: [false] })
await wrapper.vm.$nextTick()
expect(wrapper.html()).toMatchSnapshot()
wrapper.setProps({ groupDesc: [true] })
await wrapper.vm.$nextTick()
expect(wrapper.html()).toMatchSnapshot()
})
// https://github.com/vuetifyjs/vuetify/issues/11905
it('should group items when sort is disabled', async () => {
const render = jest.fn()
const items = [
{ id: 1, text: 'foo', baz: 'one' },
{ id: 2, text: 'bar', baz: 'two' },
{ id: 3, text: 'baz', baz: 'one' },
]
const wrapper = mountFunction({
propsData: {
items,
groupBy: ['baz'],
disableSort: true,
},
scopedSlots: {
default: render,
},
})
expect(render).toHaveBeenCalledWith(expect.objectContaining({
groupedItems: [
{
name: 'one',
items: [items[0], items[2]],
},
{
name: 'two',
items: [items[1]],
},
],
}))
})
}) | the_stack |
// Copyright(c) 2019, Michael Fogleman, Vladimir Agafonkin
// Permission to use, copy, modify, and / or distribute this software for any purpose
// with or without fee is hereby granted, provided that the above copyright notice
// and this permission notice appear in all copies.
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS.IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
// OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
// TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
// THIS SOFTWARE.
// @ts-nocheck
/* eslint-disable complexity, max-params, max-statements, max-depth, no-constant-condition */
export default class Delatin {
constructor(data, width, height = width) {
this.data = data; // height data
this.width = width;
this.height = height;
this.coords = []; // vertex coordinates (x, y)
this.triangles = []; // mesh triangle indices
// additional triangle data
this._halfedges = [];
this._candidates = [];
this._queueIndices = [];
this._queue = []; // queue of added triangles
this._errors = [];
this._rms = [];
this._pending = []; // triangles pending addition to queue
this._pendingLen = 0;
this._rmsSum = 0;
const x1 = width - 1;
const y1 = height - 1;
const p0 = this._addPoint(0, 0);
const p1 = this._addPoint(x1, 0);
const p2 = this._addPoint(0, y1);
const p3 = this._addPoint(x1, y1);
// add initial two triangles
const t0 = this._addTriangle(p3, p0, p2, -1, -1, -1);
this._addTriangle(p0, p3, p1, t0, -1, -1);
this._flush();
}
// refine the mesh until its maximum error gets below the given one
run(maxError = 1) {
while (this.getMaxError() > maxError) {
this.refine();
}
}
// refine the mesh with a single point
refine() {
this._step();
this._flush();
}
// max error of the current mesh
getMaxError() {
return this._errors[0];
}
// root-mean-square deviation of the current mesh
getRMSD() {
return this._rmsSum > 0 ? Math.sqrt(this._rmsSum / (this.width * this.height)) : 0;
}
// height value at a given position
heightAt(x, y) {
return this.data[this.width * y + x];
}
// rasterize and queue all triangles that got added or updated in _step
_flush() {
const coords = this.coords;
for (let i = 0; i < this._pendingLen; i++) {
const t = this._pending[i];
// rasterize triangle to find maximum pixel error
const a = 2 * this.triangles[t * 3 + 0];
const b = 2 * this.triangles[t * 3 + 1];
const c = 2 * this.triangles[t * 3 + 2];
this._findCandidate(
coords[a],
coords[a + 1],
coords[b],
coords[b + 1],
coords[c],
coords[c + 1],
t
);
}
this._pendingLen = 0;
}
// rasterize a triangle, find its max error, and queue it for processing
_findCandidate(p0x, p0y, p1x, p1y, p2x, p2y, t) {
// triangle bounding box
const minX = Math.min(p0x, p1x, p2x);
const minY = Math.min(p0y, p1y, p2y);
const maxX = Math.max(p0x, p1x, p2x);
const maxY = Math.max(p0y, p1y, p2y);
// forward differencing variables
let w00 = orient(p1x, p1y, p2x, p2y, minX, minY);
let w01 = orient(p2x, p2y, p0x, p0y, minX, minY);
let w02 = orient(p0x, p0y, p1x, p1y, minX, minY);
const a01 = p1y - p0y;
const b01 = p0x - p1x;
const a12 = p2y - p1y;
const b12 = p1x - p2x;
const a20 = p0y - p2y;
const b20 = p2x - p0x;
// pre-multiplied z values at vertices
const a = orient(p0x, p0y, p1x, p1y, p2x, p2y);
const z0 = this.heightAt(p0x, p0y) / a;
const z1 = this.heightAt(p1x, p1y) / a;
const z2 = this.heightAt(p2x, p2y) / a;
// iterate over pixels in bounding box
let maxError = 0;
let mx = 0;
let my = 0;
let rms = 0;
for (let y = minY; y <= maxY; y++) {
// compute starting offset
let dx = 0;
if (w00 < 0 && a12 !== 0) {
dx = Math.max(dx, Math.floor(-w00 / a12));
}
if (w01 < 0 && a20 !== 0) {
dx = Math.max(dx, Math.floor(-w01 / a20));
}
if (w02 < 0 && a01 !== 0) {
dx = Math.max(dx, Math.floor(-w02 / a01));
}
let w0 = w00 + a12 * dx;
let w1 = w01 + a20 * dx;
let w2 = w02 + a01 * dx;
let wasInside = false;
for (let x = minX + dx; x <= maxX; x++) {
// check if inside triangle
if (w0 >= 0 && w1 >= 0 && w2 >= 0) {
wasInside = true;
// compute z using barycentric coordinates
const z = z0 * w0 + z1 * w1 + z2 * w2;
const dz = Math.abs(z - this.heightAt(x, y));
rms += dz * dz;
if (dz > maxError) {
maxError = dz;
mx = x;
my = y;
}
} else if (wasInside) {
break;
}
w0 += a12;
w1 += a20;
w2 += a01;
}
w00 += b12;
w01 += b20;
w02 += b01;
}
if ((mx === p0x && my === p0y) || (mx === p1x && my === p1y) || (mx === p2x && my === p2y)) {
maxError = 0;
}
// update triangle metadata
this._candidates[2 * t] = mx;
this._candidates[2 * t + 1] = my;
this._rms[t] = rms;
// add triangle to priority queue
this._queuePush(t, maxError, rms);
}
// process the next triangle in the queue, splitting it with a new point
_step() {
// pop triangle with highest error from priority queue
const t = this._queuePop();
const e0 = t * 3 + 0;
const e1 = t * 3 + 1;
const e2 = t * 3 + 2;
const p0 = this.triangles[e0];
const p1 = this.triangles[e1];
const p2 = this.triangles[e2];
const ax = this.coords[2 * p0];
const ay = this.coords[2 * p0 + 1];
const bx = this.coords[2 * p1];
const by = this.coords[2 * p1 + 1];
const cx = this.coords[2 * p2];
const cy = this.coords[2 * p2 + 1];
const px = this._candidates[2 * t];
const py = this._candidates[2 * t + 1];
const pn = this._addPoint(px, py);
if (orient(ax, ay, bx, by, px, py) === 0) {
this._handleCollinear(pn, e0);
} else if (orient(bx, by, cx, cy, px, py) === 0) {
this._handleCollinear(pn, e1);
} else if (orient(cx, cy, ax, ay, px, py) === 0) {
this._handleCollinear(pn, e2);
} else {
const h0 = this._halfedges[e0];
const h1 = this._halfedges[e1];
const h2 = this._halfedges[e2];
const t0 = this._addTriangle(p0, p1, pn, h0, -1, -1, e0);
const t1 = this._addTriangle(p1, p2, pn, h1, -1, t0 + 1);
const t2 = this._addTriangle(p2, p0, pn, h2, t0 + 2, t1 + 1);
this._legalize(t0);
this._legalize(t1);
this._legalize(t2);
}
}
// add coordinates for a new vertex
_addPoint(x, y) {
const i = this.coords.length >> 1;
this.coords.push(x, y);
return i;
}
// add or update a triangle in the mesh
_addTriangle(a, b, c, ab, bc, ca, e = this.triangles.length) {
const t = e / 3; // new triangle index
// add triangle vertices
this.triangles[e + 0] = a;
this.triangles[e + 1] = b;
this.triangles[e + 2] = c;
// add triangle halfedges
this._halfedges[e + 0] = ab;
this._halfedges[e + 1] = bc;
this._halfedges[e + 2] = ca;
// link neighboring halfedges
if (ab >= 0) {
this._halfedges[ab] = e + 0;
}
if (bc >= 0) {
this._halfedges[bc] = e + 1;
}
if (ca >= 0) {
this._halfedges[ca] = e + 2;
}
// init triangle metadata
this._candidates[2 * t + 0] = 0;
this._candidates[2 * t + 1] = 0;
this._queueIndices[t] = -1;
this._rms[t] = 0;
// add triangle to pending queue for later rasterization
this._pending[this._pendingLen++] = t;
// return first halfedge index
return e;
}
_legalize(a) {
// if the pair of triangles doesn't satisfy the Delaunay condition
// (p1 is inside the circumcircle of [p0, pl, pr]), flip them,
// then do the same check/flip recursively for the new pair of triangles
//
// pl pl
// /||\ / \
// al/ || \bl al/ \a
// / || \ / \
// / a||b \ flip /___ar___\
// p0\ || /p1 => p0\---bl---/p1
// \ || / \ /
// ar\ || /br b\ /br
// \||/ \ /
// pr pr
const b = this._halfedges[a];
if (b < 0) {
return;
}
const a0 = a - (a % 3);
const b0 = b - (b % 3);
const al = a0 + ((a + 1) % 3);
const ar = a0 + ((a + 2) % 3);
const bl = b0 + ((b + 2) % 3);
const br = b0 + ((b + 1) % 3);
const p0 = this.triangles[ar];
const pr = this.triangles[a];
const pl = this.triangles[al];
const p1 = this.triangles[bl];
const coords = this.coords;
if (
!inCircle(
coords[2 * p0],
coords[2 * p0 + 1],
coords[2 * pr],
coords[2 * pr + 1],
coords[2 * pl],
coords[2 * pl + 1],
coords[2 * p1],
coords[2 * p1 + 1]
)
) {
return;
}
const hal = this._halfedges[al];
const har = this._halfedges[ar];
const hbl = this._halfedges[bl];
const hbr = this._halfedges[br];
this._queueRemove(a0 / 3);
this._queueRemove(b0 / 3);
const t0 = this._addTriangle(p0, p1, pl, -1, hbl, hal, a0);
const t1 = this._addTriangle(p1, p0, pr, t0, har, hbr, b0);
this._legalize(t0 + 1);
this._legalize(t1 + 2);
}
// handle a case where new vertex is on the edge of a triangle
_handleCollinear(pn, a) {
const a0 = a - (a % 3);
const al = a0 + ((a + 1) % 3);
const ar = a0 + ((a + 2) % 3);
const p0 = this.triangles[ar];
const pr = this.triangles[a];
const pl = this.triangles[al];
const hal = this._halfedges[al];
const har = this._halfedges[ar];
const b = this._halfedges[a];
if (b < 0) {
const t0 = this._addTriangle(pn, p0, pr, -1, har, -1, a0);
const t1 = this._addTriangle(p0, pn, pl, t0, -1, hal);
this._legalize(t0 + 1);
this._legalize(t1 + 2);
return;
}
const b0 = b - (b % 3);
const bl = b0 + ((b + 2) % 3);
const br = b0 + ((b + 1) % 3);
const p1 = this.triangles[bl];
const hbl = this._halfedges[bl];
const hbr = this._halfedges[br];
this._queueRemove(b0 / 3);
const t0 = this._addTriangle(p0, pr, pn, har, -1, -1, a0);
const t1 = this._addTriangle(pr, p1, pn, hbr, -1, t0 + 1, b0);
const t2 = this._addTriangle(p1, pl, pn, hbl, -1, t1 + 1);
const t3 = this._addTriangle(pl, p0, pn, hal, t0 + 2, t2 + 1);
this._legalize(t0);
this._legalize(t1);
this._legalize(t2);
this._legalize(t3);
}
// priority queue methods
_queuePush(t, error, rms) {
const i = this._queue.length;
this._queueIndices[t] = i;
this._queue.push(t);
this._errors.push(error);
this._rmsSum += rms;
this._queueUp(i);
}
_queuePop() {
const n = this._queue.length - 1;
this._queueSwap(0, n);
this._queueDown(0, n);
return this._queuePopBack();
}
_queuePopBack() {
const t = this._queue.pop();
this._errors.pop();
this._rmsSum -= this._rms[t];
this._queueIndices[t] = -1;
return t;
}
_queueRemove(t) {
const i = this._queueIndices[t];
if (i < 0) {
const it = this._pending.indexOf(t);
if (it !== -1) {
this._pending[it] = this._pending[--this._pendingLen];
} else {
throw new Error('Broken triangulation (something went wrong).');
}
return;
}
const n = this._queue.length - 1;
if (n !== i) {
this._queueSwap(i, n);
if (!this._queueDown(i, n)) {
this._queueUp(i);
}
}
this._queuePopBack();
}
_queueLess(i, j) {
return this._errors[i] > this._errors[j];
}
_queueSwap(i, j) {
const pi = this._queue[i];
const pj = this._queue[j];
this._queue[i] = pj;
this._queue[j] = pi;
this._queueIndices[pi] = j;
this._queueIndices[pj] = i;
const e = this._errors[i];
this._errors[i] = this._errors[j];
this._errors[j] = e;
}
_queueUp(j0) {
let j = j0;
while (true) {
const i = (j - 1) >> 1;
if (i === j || !this._queueLess(j, i)) {
break;
}
this._queueSwap(i, j);
j = i;
}
}
_queueDown(i0, n) {
let i = i0;
while (true) {
const j1 = 2 * i + 1;
if (j1 >= n || j1 < 0) {
break;
}
const j2 = j1 + 1;
let j = j1;
if (j2 < n && this._queueLess(j2, j1)) {
j = j2;
}
if (!this._queueLess(j, i)) {
break;
}
this._queueSwap(i, j);
i = j;
}
return i > i0;
}
}
function orient(ax, ay, bx, by, cx, cy) {
return (bx - cx) * (ay - cy) - (by - cy) * (ax - cx);
}
function inCircle(ax, ay, bx, by, cx, cy, px, py) {
const dx = ax - px;
const dy = ay - py;
const ex = bx - px;
const ey = by - py;
const fx = cx - px;
const fy = cy - py;
const ap = dx * dx + dy * dy;
const bp = ex * ex + ey * ey;
const cp = fx * fx + fy * fy;
return dx * (ey * cp - bp * fy) - dy * (ex * cp - bp * fx) + ap * (ex * fy - ey * fx) < 0;
} | the_stack |
import { TransactionResponse } from "@ethersproject/abstract-provider"
import { BigNumber } from "@ethersproject/bignumber"
import { Overrides } from "@ethersproject/contracts"
import { formatEther, parseEther } from "@ethersproject/units"
import AmmArtifact from "@perp/contract/build/contracts/Amm.json"
import AmmReaderArtifact from "@perp/contract/build/contracts/AmmReader.json"
import ClearingHouseArtifact from "@perp/contract/build/contracts/ClearingHouse.json"
import ClearingHouseViewerArtifact from "@perp/contract/build/contracts/ClearingHouseViewer.json"
import InsuranceFundArtifact from "@perp/contract/build/contracts/InsuranceFund.json"
import Big from "big.js"
import { Wallet, ethers } from "ethers"
import { Service } from "typedi"
import { Amm, AmmReader, ClearingHouse, ClearingHouseViewer, InsuranceFund } from "../types/ethers"
import { EthService } from "./EthService"
import { Log } from "./Log"
import { ServerProfile } from "./ServerProfile"
import { EthMetadata, SystemMetadataFactory } from "./SystemMetadataFactory"
export enum Side {
BUY,
SELL,
}
export enum PnlCalcOption {
SPOT_PRICE,
TWAP,
}
export interface Decimal {
d: BigNumber
}
export interface AmmProps {
priceFeedKey: string
quoteAssetSymbol: string
baseAssetSymbol: string
baseAssetReserve: Big
quoteAssetReserve: Big
}
export interface Position {
size: Big
margin: Big
openNotional: Big
lastUpdatedCumulativePremiumFraction: Big
}
export interface PositionCost {
side: Side
size: Big
baseAssetReserve: Big
quoteAssetReserve: Big
}
export interface PositionChangedLog {
trader: string
amm: string
margin: Big
positionNotional: Big
exchangedPositionSize: Big
fee: Big
positionSizeAfter: Big
realizedPnl: Big
unrealizedPnlAfter: Big
badDebt: Big
liquidationPenalty: Big
spotPrice: Big
fundingPayment: Big
}
@Service()
export class PerpService {
private readonly log = Log.getLogger(PerpService.name)
constructor(
readonly ethService: EthService,
readonly systemMetadataFactory: SystemMetadataFactory,
readonly serverProfile: ServerProfile,
) {}
private async createInsuranceFund(): Promise<InsuranceFund> {
return await this.createContract<InsuranceFund>(
ethMetadata => ethMetadata.insuranceFundAddr,
InsuranceFundArtifact.abi,
)
}
private createAmm(ammAddr: string): Amm {
return this.ethService.createContract<Amm>(ammAddr, AmmArtifact.abi)
}
private async createAmmReader(): Promise<AmmReader> {
return this.createContract<AmmReader>(systemMetadata => systemMetadata.ammReaderAddr, AmmReaderArtifact.abi)
}
private async createClearingHouse(signer?: ethers.Signer): Promise<ClearingHouse> {
return this.createContract<ClearingHouse>(
systemMetadata => systemMetadata.clearingHouseAddr,
ClearingHouseArtifact.abi,
signer,
)
}
private async createClearingHouseViewer(signer?: ethers.Signer): Promise<ClearingHouseViewer> {
return this.createContract<ClearingHouseViewer>(
systemMetadata => systemMetadata.clearingHouseViewerAddr,
ClearingHouseViewerArtifact.abi,
signer,
)
}
private async createContract<T>(
addressGetter: (systemMetadata: EthMetadata) => string,
abi: ethers.ContractInterface,
signer?: ethers.Signer,
): Promise<T> {
const systemMetadata = await this.systemMetadataFactory.fetch()
return this.ethService.createContract<T>(addressGetter(systemMetadata), abi, signer)
}
async getAllOpenAmms(): Promise<Amm[]> {
const amms: Amm[] = []
const insuranceFund = await this.createInsuranceFund()
const allAmms = await insuranceFund.functions.getAllAmms()
for (const ammAddr of allAmms[0]) {
const amm = this.createAmm(ammAddr)
if (await amm.open()) {
amms.push(amm)
}
}
this.log.info(
JSON.stringify({
event: "GetAllOpenAmms",
params: {
ammAddrs: amms.map(amm => amm.address),
},
}),
)
return amms
}
async getAmmStates(ammAddr: string): Promise<AmmProps> {
const ammReader = await this.createAmmReader()
const props = (await ammReader.functions.getAmmStates(ammAddr))[0]
return {
priceFeedKey: props.priceFeedKey,
quoteAssetSymbol: props.quoteAssetSymbol,
baseAssetSymbol: props.baseAssetSymbol,
baseAssetReserve: PerpService.fromWei(props.baseAssetReserve),
quoteAssetReserve: PerpService.fromWei(props.quoteAssetReserve),
}
}
async getPosition(ammAddr: string, traderAddr: string): Promise<Position> {
const clearingHouse = await this.createClearingHouse()
const position = (await clearingHouse.functions.getPosition(ammAddr, traderAddr))[0]
return {
size: PerpService.fromWei(position.size.d),
margin: PerpService.fromWei(position.margin.d),
openNotional: PerpService.fromWei(position.openNotional.d),
lastUpdatedCumulativePremiumFraction: PerpService.fromWei(position.lastUpdatedCumulativePremiumFraction.d),
}
}
async getPersonalPositionWithFundingPayment(ammAddr: string, traderAddr: string): Promise<Position> {
const clearingHouseViewer = await this.createClearingHouseViewer()
const position = await clearingHouseViewer.getPersonalPositionWithFundingPayment(ammAddr, traderAddr)
return {
size: PerpService.fromWei(position.size.d),
margin: PerpService.fromWei(position.margin.d),
openNotional: PerpService.fromWei(position.openNotional.d),
lastUpdatedCumulativePremiumFraction: PerpService.fromWei(position.lastUpdatedCumulativePremiumFraction.d),
}
}
async getMarginRatio(ammAddr: string, traderAddr: string): Promise<Big> {
const clearingHouse = await this.createClearingHouse()
return PerpService.fromWei((await clearingHouse.functions.getMarginRatio(ammAddr, traderAddr))[0].d)
}
async getPositionNotionalAndUnrealizedPnl(
ammAddr: string,
traderAddr: string,
pnlCalcOption: PnlCalcOption,
): Promise<{
positionNotional: Big
unrealizedPnl: Big
}> {
const clearingHouse = await this.createClearingHouse()
const ret = await clearingHouse.getPositionNotionalAndUnrealizedPnl(ammAddr, traderAddr, pnlCalcOption)
return {
positionNotional: PerpService.fromWei(ret.positionNotional.d),
unrealizedPnl: PerpService.fromWei(ret.unrealizedPnl.d),
}
}
toPositionChangedLog(log: any): PositionChangedLog {
return {
trader: log.trader,
amm: log.amm,
margin: PerpService.fromWei(log.margin),
positionNotional: PerpService.fromWei(log.positionNotional),
exchangedPositionSize: PerpService.fromWei(log.exchangedPositionSize),
fee: PerpService.fromWei(log.fee),
positionSizeAfter: PerpService.fromWei(log.positionSizeAfter),
realizedPnl: PerpService.fromWei(log.realizedPnl),
unrealizedPnlAfter: PerpService.fromWei(log.unrealizedPnlAfter),
badDebt: PerpService.fromWei(log.badDebt),
liquidationPenalty: PerpService.fromWei(log.liquidationPenalty),
spotPrice: PerpService.fromWei(log.spotPrice),
fundingPayment: PerpService.fromWei(log.fundingPayment),
}
}
async openPosition(
trader: Wallet,
ammAddr: string,
side: Side,
quoteAssetAmount: Big,
leverage: Big,
minBaseAssetAmount: Big = Big(0),
overrides?: Overrides,
): Promise<TransactionResponse> {
const clearingHouse = await this.createClearingHouse(trader)
// if the tx gonna fail it will throw here
/*
const gasEstimate = await clearingHouse.estimateGas.openPosition(
ammAddr,
side.valueOf(),
{ d: PerpService.toWei(quoteAssetAmount) },
{ d: PerpService.toWei(leverage) },
{ d: PerpService.toWei(minBaseAssetAmount) },
)*/
const tx = await clearingHouse.functions.openPosition(
ammAddr,
side.valueOf(),
{ d: PerpService.toWei(quoteAssetAmount) },
{ d: PerpService.toWei(leverage) },
{ d: PerpService.toWei(minBaseAssetAmount) },
{
// add a margin for gas limit since its estimation was sometimes too tight
gasLimit: 5_000_000,
...overrides,
},
)
this.log.jinfo({
event: "OpenPositionTxSent",
params: {
trader: trader.address,
amm: ammAddr,
side,
quoteAssetAmount: +quoteAssetAmount,
leverage: +leverage,
minBaseAssetAmount: +minBaseAssetAmount,
txHash: tx.hash,
gasPrice: tx.gasPrice ? tx.gasPrice.toString() : null,
nonce: tx.nonce,
},
})
return tx
}
async closePosition(
trader: Wallet,
ammAddr: string,
minBaseAssetAmount: Big = Big(0),
overrides?: Overrides,
): Promise<TransactionResponse> {
const clearingHouse = await this.createClearingHouse(trader)
const tx = await clearingHouse.functions.closePosition(
ammAddr,
{ d: PerpService.toWei(minBaseAssetAmount) },
{
gasLimit: 5_000_000,
...overrides,
},
)
this.log.jinfo({
event: "ClosePositionTxSent",
params: {
trader: trader.address,
amm: ammAddr,
txHash: tx.hash,
gasPrice: tx.gasPrice ? tx.gasPrice.toString() : null,
nonce: tx.nonce,
},
})
return tx
}
async removeMargin(
trader: Wallet,
ammAddr: string,
marginToBeRemoved: Big,
overrides?: Overrides,
): Promise<TransactionResponse> {
const clearingHouse = await this.createClearingHouse(trader)
const tx = await clearingHouse.functions.removeMargin(
ammAddr,
{ d: PerpService.toWei(marginToBeRemoved) },
{
gasLimit: 5_000_000,
...overrides,
},
)
this.log.jinfo({
event: "RemoveMarginTxSent",
params: {
trader: trader.address,
amm: ammAddr,
marginToBeRemoved: +marginToBeRemoved.toFixed(),
txHash: tx.hash,
gasPrice: tx.gasPrice ? tx.gasPrice.toString() : null,
nonce: tx.nonce,
},
})
return tx
}
async addMargin(
trader: Wallet,
ammAddr: string,
marginToBeAdded: Big,
overrides?: Overrides,
): Promise<TransactionResponse> {
const clearingHouse = await this.createClearingHouse(trader)
const tx = await clearingHouse.functions.addMargin(
ammAddr,
{ d: PerpService.toWei(marginToBeAdded) },
{
gasLimit: 5_000_000,
...overrides,
},
)
this.log.jinfo({
event: "AddMarginTxSent",
params: {
trader: trader.address,
amm: ammAddr,
marginToBeRemoved: +marginToBeAdded.toFixed(),
txHash: tx.hash,
gasPrice: tx.gasPrice ? tx.gasPrice.toString() : null,
nonce: tx.nonce,
},
})
return tx
}
async getUnrealizedPnl(ammAddr: string, traderAddr: string, pnlCalOption: PnlCalcOption): Promise<Big> {
const clearingHouseViewer = await this.createClearingHouseViewer()
const unrealizedPnl = (
await clearingHouseViewer.functions.getUnrealizedPnl(ammAddr, traderAddr, BigNumber.from(pnlCalOption))
)[0]
return Big(PerpService.fromWei(unrealizedPnl.d))
}
// noinspection JSMethodCanBeStatic
static fromWei(wei: BigNumber): Big {
return Big(formatEther(wei))
}
// noinspection JSMethodCanBeStatic
static toWei(val: Big): BigNumber {
return parseEther(val.toFixed(18))
}
} | the_stack |
import { DisposableStore, IDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { ICodeEditor, IActiveCodeEditor, IEditorConstructionOptions } from 'vs/editor/browser/editorBrowser';
import { IEditorContributionCtor } from 'vs/editor/browser/editorExtensions';
import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService';
import { View } from 'vs/editor/browser/view/viewImpl';
import { CodeEditorWidget, ICodeEditorWidgetOptions } from 'vs/editor/browser/widget/codeEditorWidget';
import * as editorOptions from 'vs/editor/common/config/editorOptions';
import { IConfiguration, IEditorContribution } from 'vs/editor/common/editorCommon';
import { ITextBufferFactory, ITextModel } from 'vs/editor/common/model';
import { ILanguageConfigurationService } from 'vs/editor/common/modes/languageConfigurationRegistry';
import { IModelService } from 'vs/editor/common/services/modelService';
import { ModelServiceImpl } from 'vs/editor/common/services/modelServiceImpl';
import { IModeService } from 'vs/editor/common/services/modeService';
import { ModeServiceImpl } from 'vs/editor/common/services/modeServiceImpl';
import { ITextResourcePropertiesService } from 'vs/editor/common/services/textResourceConfigurationService';
import { ViewModel } from 'vs/editor/common/viewModel/viewModelImpl';
import { TestCodeEditorService, TestCommandService } from 'vs/editor/test/browser/editorTestServices';
import { createTextModel2 } from 'vs/editor/test/common/editorTestUtils';
import { TestConfiguration } from 'vs/editor/test/common/mocks/testConfiguration';
import { TestLanguageConfigurationService } from 'vs/editor/test/common/modes/testLanguageConfigurationService';
import { TestTextResourcePropertiesService } from 'vs/editor/test/common/services/testTextResourcePropertiesService';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService';
import { IContextKeyService, IContextKeyServiceTarget } from 'vs/platform/contextkey/common/contextkey';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { TestDialogService } from 'vs/platform/dialogs/test/common/testDialogService';
import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
import { BrandedService, IInstantiationService, ServiceIdentifier } from 'vs/platform/instantiation/common/instantiation';
import { InstantiationService } from 'vs/platform/instantiation/common/instantiationService';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { MockContextKeyService } from 'vs/platform/keybinding/test/common/mockKeybindingService';
import { ILogService, NullLogService } from 'vs/platform/log/common/log';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { TestNotificationService } from 'vs/platform/notification/test/common/testNotificationService';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { NullTelemetryServiceShape } from 'vs/platform/telemetry/common/telemetryUtils';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { TestThemeService } from 'vs/platform/theme/test/common/testThemeService';
import { IUndoRedoService } from 'vs/platform/undoRedo/common/undoRedo';
import { UndoRedoService } from 'vs/platform/undoRedo/common/undoRedoService';
export interface ITestCodeEditor extends IActiveCodeEditor {
getViewModel(): ViewModel | undefined;
registerAndInstantiateContribution<T extends IEditorContribution, Services extends BrandedService[]>(id: string, ctor: new (editor: ICodeEditor, ...services: Services) => T): T;
registerDisposable(disposable: IDisposable): void;
}
export class TestCodeEditor extends CodeEditorWidget implements ICodeEditor {
//#region testing overrides
protected override _createConfiguration(options: Readonly<IEditorConstructionOptions>): IConfiguration {
return new TestConfiguration(options);
}
protected override _createView(viewModel: ViewModel): [View, boolean] {
// Never create a view
return [null! as View, false];
}
private _hasTextFocus = false;
public setHasTextFocus(hasTextFocus: boolean): void {
this._hasTextFocus = hasTextFocus;
}
public override hasTextFocus(): boolean {
return this._hasTextFocus;
}
//#endregion
//#region Testing utils
public getViewModel(): ViewModel | undefined {
return this._modelData ? this._modelData.viewModel : undefined;
}
public registerAndInstantiateContribution<T extends IEditorContribution, Services extends BrandedService[]>(id: string, ctor: new (editor: ICodeEditor, ...services: Services) => T): T {
const r: T = this._instantiationService.createInstance(ctor as IEditorContributionCtor, this);
this._contributions[id] = r;
return r;
}
public registerDisposable(disposable: IDisposable): void {
this._register(disposable);
}
}
class TestCodeEditorWithAutoModelDisposal extends TestCodeEditor {
public override dispose() {
super.dispose();
if (this._modelData) {
this._modelData.model.dispose();
}
}
}
class TestEditorDomElement {
parentElement: IContextKeyServiceTarget | null = null;
setAttribute(attr: string, value: string): void { }
removeAttribute(attr: string): void { }
hasAttribute(attr: string): boolean { return false; }
getAttribute(attr: string): string | undefined { return undefined; }
addEventListener(event: string): void { }
removeEventListener(event: string): void { }
}
export interface TestCodeEditorCreationOptions extends editorOptions.IEditorOptions {
/**
* The initial model associated with this code editor.
*/
model?: ITextModel;
serviceCollection?: ServiceCollection;
/**
* If the editor has text focus.
* Defaults to true.
*/
hasTextFocus?: boolean;
}
export function withTestCodeEditor(text: string | string[] | ITextBufferFactory | null, options: TestCodeEditorCreationOptions, callback: (editor: ITestCodeEditor, viewModel: ViewModel) => void): void {
const [instantiationService, disposables] = createTestCodeEditorServices(options.serviceCollection);
delete options.serviceCollection;
// create a model if necessary
if (!options.model) {
if (Array.isArray(text)) {
options.model = disposables.add(createTextModel2(instantiationService, text.join('\n')));
} else if (text !== null) {
options.model = disposables.add(createTextModel2(instantiationService, text));
}
}
const editor = disposables.add(doCreateTestCodeEditor(instantiationService, options));
const viewModel = editor.getViewModel()!;
viewModel.setHasFocus(true);
callback(<ITestCodeEditor>editor, editor.getViewModel()!);
disposables.dispose();
}
export async function withAsyncTestCodeEditor(text: string | string[] | ITextBufferFactory | null, options: TestCodeEditorCreationOptions, callback: (editor: ITestCodeEditor, viewModel: ViewModel, instantiationService: IInstantiationService) => Promise<void>): Promise<void> {
const [instantiationService, disposables] = createTestCodeEditorServices(options.serviceCollection);
delete options.serviceCollection;
// create a model if necessary
if (!options.model) {
if (Array.isArray(text)) {
options.model = disposables.add(createTextModel2(instantiationService, text.join('\n')));
} else if (text !== null) {
options.model = disposables.add(createTextModel2(instantiationService, text));
}
}
const editor = disposables.add(doCreateTestCodeEditor(instantiationService, options));
const viewModel = editor.getViewModel()!;
viewModel.setHasFocus(true);
await callback(<ITestCodeEditor>editor, editor.getViewModel()!, instantiationService);
disposables.dispose();
}
export function createTestCodeEditor(options: TestCodeEditorCreationOptions): ITestCodeEditor {
const [instantiationService, disposables] = createTestCodeEditorServices(options.serviceCollection);
delete options.serviceCollection;
const editor = doCreateTestCodeEditor(instantiationService, options);
editor.registerDisposable(disposables);
return editor;
}
export function createTestCodeEditorServices(services: ServiceCollection = new ServiceCollection()): [IInstantiationService, DisposableStore] {
const serviceIdentifiers: ServiceIdentifier<any>[] = [];
const define = <T>(id: ServiceIdentifier<T>, ctor: new (...args: any[]) => T) => {
if (!services.has(id)) {
services.set(id, new SyncDescriptor(ctor));
}
serviceIdentifiers.push(id);
};
define(INotificationService, TestNotificationService);
define(IDialogService, TestDialogService);
define(IUndoRedoService, UndoRedoService);
define(IModeService, ModeServiceImpl);
define(ILanguageConfigurationService, TestLanguageConfigurationService);
define(IConfigurationService, TestConfigurationService);
define(ITextResourcePropertiesService, TestTextResourcePropertiesService);
define(IThemeService, TestThemeService);
define(ILogService, NullLogService);
define(IModelService, ModelServiceImpl);
define(ICodeEditorService, TestCodeEditorService);
define(IContextKeyService, MockContextKeyService);
define(ICommandService, TestCommandService);
define(ITelemetryService, NullTelemetryServiceShape);
const instantiationService: IInstantiationService = new InstantiationService(services);
const disposables = new DisposableStore();
disposables.add(toDisposable(() => {
for (const id of serviceIdentifiers) {
const instanceOrDescriptor = services.get(id);
if (typeof instanceOrDescriptor.dispose === 'function') {
instanceOrDescriptor.dispose();
}
}
}));
return [instantiationService, disposables];
}
function doCreateTestCodeEditor(instantiationService: IInstantiationService, options: TestCodeEditorCreationOptions): ITestCodeEditor {
const model = options.model;
delete options.model;
const codeEditorWidgetOptions: ICodeEditorWidgetOptions = {
contributions: []
};
const editor = instantiationService.createInstance(
TestCodeEditorWithAutoModelDisposal,
<HTMLElement><any>new TestEditorDomElement(),
options,
codeEditorWidgetOptions
);
if (typeof options.hasTextFocus === 'undefined') {
options.hasTextFocus = true;
}
editor.setHasTextFocus(options.hasTextFocus);
editor.setModel(model);
return <ITestCodeEditor>editor;
}
export interface TestCodeEditorCreationOptions2 extends editorOptions.IEditorOptions {
/**
* If the editor has text focus.
* Defaults to true.
*/
hasTextFocus?: boolean;
}
export function createTestCodeEditor2(instantiationService: IInstantiationService, model: ITextModel, options: TestCodeEditorCreationOptions2): TestCodeEditor {
const codeEditorWidgetOptions: ICodeEditorWidgetOptions = {
contributions: []
};
const editor = instantiationService.createInstance(
TestCodeEditor,
<HTMLElement><any>new TestEditorDomElement(),
options,
codeEditorWidgetOptions
);
if (typeof options.hasTextFocus === 'undefined') {
options.hasTextFocus = true;
}
editor.setHasTextFocus(options.hasTextFocus);
editor.setModel(model);
editor.getViewModel()!.setHasFocus(true);
return editor;
} | the_stack |
type Constructor<E> = new (...args: any[]) => E;
type CatchFilter<E> = ((error: E) => boolean) | (object & E);
type Resolvable<R> = R | PromiseLike<R>;
type IterateFunction<T, R> = (item: T, index: number, arrayLength: number) => Resolvable<R>;
type PromisifyAllKeys<T> = T extends string ? `${T}Async` : never;
type WithoutLast<T> = T extends [...infer A, any] ? A : [];
type Last<T> = T extends [...any[], infer L] ? L : never;
type ExtractCallbackValueType<T> = T extends (error: any, ...data: infer D) => any ? D : never;
type PromiseMethod<TArgs, TReturn> = TReturn extends never ? never : (...args: WithoutLast<TArgs>) => Promise<TReturn>;
type ExtractAsyncMethod<T> = T extends (...args: infer A) => any
? PromiseMethod<A, ExtractCallbackValueType<Last<Required<A>>>[0]>
: never;
type PromisifyAllItems<T> = {
[K in keyof T as PromisifyAllKeys<K>]: ExtractAsyncMethod<T[K]>;
};
type NonNeverValues<T> = {
[K in keyof T as T[K] extends never ? never : K]: T[K];
};
// Drop `never` values
type PromisifyAll<T> = NonNeverValues<PromisifyAllItems<T>> & T;
declare class Bluebird<R> implements PromiseLike<R>, Bluebird.Inspection<R> {
readonly [Symbol.toStringTag]: "Object";
/**
* Create a new promise. The passed in function will receive functions
* `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise.
*
* If promise cancellation is enabled, passed in function will receive
* one more function argument `onCancel` that allows to register an optional cancellation callback.
*/
constructor(callback: (resolve: (thenableOrResult?: Resolvable<R>) => void, reject: (error?: any) => void, onCancel?: (callback: () => void) => void) => void);
/**
* Promises/A+ `.then()`. Returns a new promise chained from this promise.
*
* The new promise will be rejected or resolved depending on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise.
*/
// Based on PromiseLike.then, but returns a Bluebird instance.
then<U>(onFulfill?: (value: R) => Resolvable<U>, onReject?: (error: any) => Resolvable<U>): Bluebird<U>; // For simpler signature help.
then<TResult1 = R, TResult2 = never>(
onfulfilled?: ((value: R) => Resolvable<TResult1>) | null,
onrejected?: ((reason: any) => Resolvable<TResult2>) | null
): Bluebird<TResult1 | TResult2>;
/**
* This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise.
*
* Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler.
*
* Alias `.caught();` for compatibility with earlier ECMAScript version.
*/
catch<U = R>(onReject: ((error: any) => Resolvable<U>) | undefined | null): Bluebird<U | R>;
/**
* This extends `.catch` to work more like catch-clauses in languages like Java or C#.
*
* Instead of manually checking `instanceof` or `.name === "SomeError"`,
* you may specify a number of error constructors which are eligible for this catch handler.
* The catch handler that is first met that has eligible constructors specified, is the one that will be called.
*
* This method also supports predicate-based filters.
* If you pass a predicate function instead of an error constructor, the predicate will receive the error as an argument.
* The return result of the predicate will be used determine whether the error handler should be called.
*
* Alias `.caught();` for compatibility with earlier ECMAScript version.
*/
catch<U, E1, E2, E3, E4, E5>(
filter1: Constructor<E1>,
filter2: Constructor<E2>,
filter3: Constructor<E3>,
filter4: Constructor<E4>,
filter5: Constructor<E5>,
onReject: (error: E1 | E2 | E3 | E4 | E5) => Resolvable<U>,
): Bluebird<U | R>;
catch<U, E1, E2, E3, E4, E5>(
filter1: Constructor<E1> | CatchFilter<E1>,
filter2: Constructor<E2> | CatchFilter<E2>,
filter3: Constructor<E3> | CatchFilter<E3>,
filter4: Constructor<E4> | CatchFilter<E4>,
filter5: Constructor<E5> | CatchFilter<E5>,
onReject: (error: E1 | E2 | E3 | E4 | E5) => Resolvable<U>,
): Bluebird<U | R>;
catch<U, E1, E2, E3, E4>(
filter1: Constructor<E1>,
filter2: Constructor<E2>,
filter3: Constructor<E3>,
filter4: Constructor<E4>,
onReject: (error: E1 | E2 | E3 | E4) => Resolvable<U>,
): Bluebird<U | R>;
catch<U, E1, E2, E3, E4>(
filter1: Constructor<E1> | CatchFilter<E1>,
filter2: Constructor<E2> | CatchFilter<E2>,
filter3: Constructor<E3> | CatchFilter<E3>,
filter4: Constructor<E4> | CatchFilter<E4>,
onReject: (error: E1 | E2 | E3 | E4) => Resolvable<U>,
): Bluebird<U | R>;
catch<U, E1, E2, E3>(
filter1: Constructor<E1>,
filter2: Constructor<E2>,
filter3: Constructor<E3>,
onReject: (error: E1 | E2 | E3) => Resolvable<U>,
): Bluebird<U | R>;
catch<U, E1, E2, E3>(
filter1: Constructor<E1> | CatchFilter<E1>,
filter2: Constructor<E2> | CatchFilter<E2>,
filter3: Constructor<E3> | CatchFilter<E3>,
onReject: (error: E1 | E2 | E3) => Resolvable<U>,
): Bluebird<U | R>;
catch<U, E1, E2>(
filter1: Constructor<E1>,
filter2: Constructor<E2>,
onReject: (error: E1 | E2) => Resolvable<U>,
): Bluebird<U | R>;
catch<U, E1, E2>(
filter1: Constructor<E1> | CatchFilter<E1>,
filter2: Constructor<E2> | CatchFilter<E2>,
onReject: (error: E1 | E2) => Resolvable<U>,
): Bluebird<U | R>;
catch<U, E1>(
filter1: Constructor<E1>,
onReject: (error: E1) => Resolvable<U>,
): Bluebird<U | R>;
catch<U, E1>(
// tslint:disable-next-line:unified-signatures
filter1: Constructor<E1> | CatchFilter<E1>,
onReject: (error: E1) => Resolvable<U>,
): Bluebird<U | R>;
/**
* This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise.
*
* Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler.
*
* Alias `.caught();` for compatibility with earlier ECMAScript version.
*/
caught: Bluebird<R>["catch"];
/**
* Like `.catch` but instead of catching all types of exceptions,
* it only catches those that don't originate from thrown errors but rather from explicit rejections.
*/
error<U>(onReject: (reason: any) => Resolvable<U>): Bluebird<U>;
/**
* Pass a handler that will be called regardless of this promise's fate. Returns a new promise chained from this promise.
*
* There are special semantics for `.finally()` in that the final value cannot be modified from the handler.
*
* Alias `.lastly();` for compatibility with earlier ECMAScript version.
*/
finally(handler: () => Resolvable<any>): Bluebird<R>;
lastly: Bluebird<R>["finally"];
/**
* Create a promise that follows this promise, but is bound to the given `thisArg` value.
* A bound promise will call its handlers with the bound value set to `this`.
*
* Additionally promises derived from a bound promise will also be bound promises with the same `thisArg` binding as the original promise.
*/
bind(thisArg: any): Bluebird<R>;
/**
* Like `.then()`, but any unhandled rejection that ends up here will be thrown as an error.
*/
done<U>(onFulfilled?: (value: R) => Resolvable<U>, onRejected?: (error: any) => Resolvable<U>): void;
/**
* Like `.finally()`, but not called for rejections.
*/
tap(onFulFill: (value: R) => Resolvable<any>): Bluebird<R>;
/**
* Like `.catch()` but rethrows the error
*/
tapCatch(onReject: (error?: any) => Resolvable<any>): Bluebird<R>;
tapCatch<E1, E2, E3, E4, E5>(
filter1: Constructor<E1>,
filter2: Constructor<E2>,
filter3: Constructor<E3>,
filter4: Constructor<E4>,
filter5: Constructor<E5>,
onReject: (error: E1 | E2 | E3 | E4 | E5) => Resolvable<any>,
): Bluebird<R>;
tapCatch<E1, E2, E3, E4, E5>(
filter1: Constructor<E1> | CatchFilter<E1>,
filter2: Constructor<E2> | CatchFilter<E2>,
filter3: Constructor<E3> | CatchFilter<E3>,
filter4: Constructor<E4> | CatchFilter<E4>,
filter5: Constructor<E5> | CatchFilter<E5>,
onReject: (error: E1 | E2 | E3 | E4 | E5) => Resolvable<any>,
): Bluebird<R>;
tapCatch<E1, E2, E3, E4>(
filter1: Constructor<E1>,
filter2: Constructor<E2>,
filter3: Constructor<E3>,
filter4: Constructor<E4>,
onReject: (error: E1 | E2 | E3 | E4) => Resolvable<any>,
): Bluebird<R>;
tapCatch<E1, E2, E3, E4>(
filter1: Constructor<E1> | CatchFilter<E1>,
filter2: Constructor<E2> | CatchFilter<E2>,
filter3: Constructor<E3> | CatchFilter<E3>,
filter4: Constructor<E4> | CatchFilter<E4>,
onReject: (error: E1 | E2 | E3 | E4) => Resolvable<any>,
): Bluebird<R>;
tapCatch<E1, E2, E3>(
filter1: Constructor<E1>,
filter2: Constructor<E2>,
filter3: Constructor<E3>,
onReject: (error: E1 | E2 | E3) => Resolvable<any>,
): Bluebird<R>;
tapCatch<E1, E2, E3>(
filter1: Constructor<E1> | CatchFilter<E1>,
filter2: Constructor<E2> | CatchFilter<E2>,
filter3: Constructor<E3> | CatchFilter<E3>,
onReject: (error: E1 | E2 | E3) => Resolvable<any>,
): Bluebird<R>;
tapCatch<E1, E2>(
filter1: Constructor<E1>,
filter2: Constructor<E2>,
onReject: (error: E1 | E2) => Resolvable<any>,
): Bluebird<R>;
tapCatch<E1, E2>(
filter1: Constructor<E1> | CatchFilter<E1>,
filter2: Constructor<E2> | CatchFilter<E2>,
onReject: (error: E1 | E2) => Resolvable<any>,
): Bluebird<R>;
tapCatch<E1>(
filter1: Constructor<E1>,
onReject: (error: E1) => Resolvable<any>,
): Bluebird<R>;
tapCatch<E1>(
// tslint:disable-next-line:unified-signatures
filter1: Constructor<E1> | CatchFilter<E1>,
onReject: (error: E1) => Resolvable<any>,
): Bluebird<R>;
/**
* Same as calling `Promise.delay(ms, this)`.
*/
delay(ms: number): Bluebird<R>;
/**
* Returns a promise that will be fulfilled with this promise's fulfillment value or rejection reason.
* However, if this promise is not fulfilled or rejected within ms milliseconds, the returned promise
* is rejected with a TimeoutError or the error as the reason.
*
* You may specify a custom error message with the `message` parameter.
*/
timeout(ms: number, message?: string | Error): Bluebird<R>;
/**
* Register a node-style callback on this promise.
*
* When this promise is is either fulfilled or rejected,
* the node callback will be called back with the node.js convention
* where error reason is the first argument and success value is the second argument.
*
* The error argument will be `null` in case of success.
* If the `callback` argument is not a function, this method does not do anything.
*/
nodeify(callback: (err: any, value?: R) => void, options?: Bluebird.SpreadOption): this;
nodeify(...sink: any[]): this;
asCallback(callback: (err: any, value?: R) => void, options?: Bluebird.SpreadOption): this;
asCallback(...sink: any[]): this;
/**
* See if this `promise` has been fulfilled.
*/
isFulfilled(): boolean;
/**
* See if this `promise` has been rejected.
*/
isRejected(): boolean;
/**
* See if this `promise` is still defer.
*/
isPending(): boolean;
/**
* See if this `promise` has been cancelled.
*/
isCancelled(): boolean;
/**
* See if this `promise` is resolved -> either fulfilled or rejected.
*/
isResolved(): boolean;
/**
* Get the fulfillment value of the underlying promise. Throws if the promise isn't fulfilled yet.
*
* throws `TypeError`
*/
value(): R;
/**
* Get the rejection reason for the underlying promise. Throws if the promise isn't rejected yet.
*
* throws `TypeError`
*/
reason(): any;
/**
* Synchronously inspect the state of this `promise`. The `PromiseInspection` will represent the state of
* the promise as snapshotted at the time of calling `.reflect()`.
*/
reflect(): Bluebird<Bluebird.Inspection<R>>;
/**
* This is a convenience method for doing:
*
* <code>
* promise.then(function(obj){
* return obj[propertyName].call(obj, arg...);
* });
* </code>
*/
call<U extends keyof Q, Q>(this: Bluebird<Q>, propertyName: U, ...args: any[]): Bluebird<Q[U] extends (...args: any[]) => any ? ReturnType<Q[U]> : never>;
/**
* This is a convenience method for doing:
*
* <code>
* promise.then(function(obj){
* return obj[propertyName];
* });
* </code>
*/
get<U extends keyof R>(key: U): Bluebird<R[U]>;
/**
* Convenience method for:
*
* <code>
* .then(function() {
* return value;
* });
* </code>
*
* in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.return()`
*
* Alias `.thenReturn();` for compatibility with earlier ECMAScript version.
*/
return(): Bluebird<void>;
return<U>(value: U): Bluebird<U>;
thenReturn(): Bluebird<void>;
thenReturn<U>(value: U): Bluebird<U>;
/**
* Convenience method for:
*
* <code>
* .then(function() {
* throw reason;
* });
* </code>
* Same limitations apply as with `.return()`.
*
* Alias `.thenThrow();` for compatibility with earlier ECMAScript version.
*/
throw(reason: Error): Bluebird<never>;
thenThrow(reason: Error): Bluebird<never>;
/**
* Convenience method for:
*
* <code>
* .catch(function() {
* return value;
* });
* </code>
*
* in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.catchReturn()`
*/
catchReturn<U>(value: U): Bluebird<R | U>;
// No need to be specific about Error types in these overrides, since there's no handler function
catchReturn<U>(
filter1: Constructor<Error>,
filter2: Constructor<Error>,
filter3: Constructor<Error>,
filter4: Constructor<Error>,
filter5: Constructor<Error>,
value: U,
): Bluebird<R | U>;
catchReturn<U>(
filter1: Constructor<Error> | CatchFilter<Error>,
filter2: Constructor<Error> | CatchFilter<Error>,
filter3: Constructor<Error> | CatchFilter<Error>,
filter4: Constructor<Error> | CatchFilter<Error>,
filter5: Constructor<Error> | CatchFilter<Error>,
value: U,
): Bluebird<R | U>;
catchReturn<U>(
filter1: Constructor<Error>,
filter2: Constructor<Error>,
filter3: Constructor<Error>,
filter4: Constructor<Error>,
value: U,
): Bluebird<R | U>;
catchReturn<U>(
filter1: Constructor<Error> | CatchFilter<Error>,
filter2: Constructor<Error> | CatchFilter<Error>,
filter3: Constructor<Error> | CatchFilter<Error>,
filter4: Constructor<Error> | CatchFilter<Error>,
value: U,
): Bluebird<R | U>;
catchReturn<U>(
filter1: Constructor<Error>,
filter2: Constructor<Error>,
filter3: Constructor<Error>,
value: U,
): Bluebird<R | U>;
catchReturn<U>(
filter1: Constructor<Error> | CatchFilter<Error>,
filter2: Constructor<Error> | CatchFilter<Error>,
filter3: Constructor<Error> | CatchFilter<Error>,
value: U,
): Bluebird<R | U>;
catchReturn<U>(
filter1: Constructor<Error>,
filter2: Constructor<Error>,
value: U,
): Bluebird<R | U>;
catchReturn<U>(
filter1: Constructor<Error> | CatchFilter<Error>,
filter2: Constructor<Error> | CatchFilter<Error>,
value: U,
): Bluebird<R | U>;
catchReturn<U>(
filter1: Constructor<Error>,
value: U,
): Bluebird<R | U>;
catchReturn<U>(
// tslint:disable-next-line:unified-signatures
filter1: Constructor<Error> | CatchFilter<Error>,
value: U,
): Bluebird<R | U>;
/**
* Convenience method for:
*
* <code>
* .catch(function() {
* throw reason;
* });
* </code>
* Same limitations apply as with `.catchReturn()`.
*/
catchThrow(reason: Error): Bluebird<R>;
// No need to be specific about Error types in these overrides, since there's no handler function
catchThrow(
filter1: Constructor<Error>,
filter2: Constructor<Error>,
filter3: Constructor<Error>,
filter4: Constructor<Error>,
filter5: Constructor<Error>,
reason: Error,
): Bluebird<R>;
catchThrow(
filter1: Constructor<Error> | CatchFilter<Error>,
filter2: Constructor<Error> | CatchFilter<Error>,
filter3: Constructor<Error> | CatchFilter<Error>,
filter4: Constructor<Error> | CatchFilter<Error>,
filter5: Constructor<Error> | CatchFilter<Error>,
reason: Error,
): Bluebird<R>;
catchThrow(
filter1: Constructor<Error>,
filter2: Constructor<Error>,
filter3: Constructor<Error>,
filter4: Constructor<Error>,
reason: Error,
): Bluebird<R>;
catchThrow(
filter1: Constructor<Error> | CatchFilter<Error>,
filter2: Constructor<Error> | CatchFilter<Error>,
filter3: Constructor<Error> | CatchFilter<Error>,
filter4: Constructor<Error> | CatchFilter<Error>,
reason: Error,
): Bluebird<R>;
catchThrow(
filter1: Constructor<Error>,
filter2: Constructor<Error>,
filter3: Constructor<Error>,
reason: Error,
): Bluebird<R>;
catchThrow(
filter1: Constructor<Error> | CatchFilter<Error>,
filter2: Constructor<Error> | CatchFilter<Error>,
filter3: Constructor<Error> | CatchFilter<Error>,
reason: Error,
): Bluebird<R>;
catchThrow(
filter1: Constructor<Error>,
filter2: Constructor<Error>,
reason: Error,
): Bluebird<R>;
catchThrow(
filter1: Constructor<Error> | CatchFilter<Error>,
filter2: Constructor<Error> | CatchFilter<Error>,
reason: Error,
): Bluebird<R>;
catchThrow(
filter1: Constructor<Error>,
reason: Error,
): Bluebird<R>;
catchThrow(
// tslint:disable-next-line:unified-signatures
filter1: Constructor<Error> | CatchFilter<Error>,
reason: Error,
): Bluebird<R>;
/**
* Convert to String.
*/
toString(): string;
/**
* This is implicitly called by `JSON.stringify` when serializing the object. Returns a serialized representation of the `Promise`.
*/
toJSON(): object;
/**
* Like calling `.then`, but the fulfillment value or rejection reason is assumed to be an array, which is flattened to the formal parameters of the handlers.
*/
spread<U, Q>(this: Bluebird<R & Iterable<Q>>, fulfilledHandler: (...values: Q[]) => Resolvable<U>): Bluebird<U>;
/**
* Same as calling `Promise.all(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
all<T1, T2, T3, T4, T5>(this: Bluebird<[Resolvable<T1>, Resolvable<T2>, Resolvable<T3>, Resolvable<T4>, Resolvable<T5>]>): Bluebird<[T1, T2, T3, T4, T5]>;
all<T1, T2, T3, T4>(this: Bluebird<[Resolvable<T1>, Resolvable<T2>, Resolvable<T3>, Resolvable<T4>]>): Bluebird<[T1, T2, T3, T4]>;
all<T1, T2, T3>(this: Bluebird<[Resolvable<T1>, Resolvable<T2>, Resolvable<T3>]>): Bluebird<[T1, T2, T3]>;
all<T1, T2>(this: Bluebird<[Resolvable<T1>, Resolvable<T2>]>): Bluebird<[T1, T2]>;
all<T1>(this: Bluebird<[Resolvable<T1>]>): Bluebird<[T1]>;
all<R>(this: Bluebird<Iterable<Resolvable<R>>>): Bluebird<R[]>;
/**
* Same as calling `Promise.all(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
all(): Bluebird<never>;
/**
* Same as calling `Promise.props(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
props<K, V>(this: PromiseLike<Map<K, Resolvable<V>>>): Bluebird<Map<K, V>>;
props<T>(this: PromiseLike<Bluebird.ResolvableProps<T>>): Bluebird<T>;
/**
* Same as calling `Promise.any(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
any<Q>(this: Bluebird<R & Iterable<Q>>): Bluebird<Q>;
/**
* Same as calling `Promise.any(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
any(): Bluebird<never>;
/**
* Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
* Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
some<Q>(this: Bluebird<R & Iterable<Q>>, count: number): Bluebird<R>;
/**
* Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
* Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
some(count: number): Bluebird<never>;
/**
* Same as calling `Promise.race(thisPromise, count)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
race<Q>(this: Bluebird<R & Iterable<Q>>): Bluebird<Q>;
/**
* Same as calling `Promise.race(thisPromise, count)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
race(): Bluebird<never>;
/**
* Same as calling `Bluebird.map(thisPromise, mapper)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
map<U, Q>(this: Bluebird<R & Iterable<Q>>, mapper: IterateFunction<Q, U>, options?: Bluebird.ConcurrencyOption): Bluebird<U[]>;
/**
* Same as calling `Promise.reduce(thisPromise, Function reducer, initialValue)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
reduce<U, Q>(this: Bluebird<R & Iterable<Q>>, reducer: (memo: U, item: Q, index: number, arrayLength: number) => Resolvable<U>, initialValue?: U): Bluebird<U>;
/**
* Same as calling ``Promise.filter(thisPromise, filterer)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
filter<Q>(this: Bluebird<R & Iterable<Q>>, filterer: IterateFunction<Q, boolean>, options?: Bluebird.ConcurrencyOption): Bluebird<R>;
/**
* Same as calling ``Bluebird.each(thisPromise, iterator)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
each<Q>(this: Bluebird<R & Iterable<Q>>, iterator: IterateFunction<Q, any>): Bluebird<R>;
/**
* Same as calling ``Bluebird.mapSeries(thisPromise, iterator)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
mapSeries<U, Q>(this: Bluebird<R & Iterable<Q>>, iterator: IterateFunction<Q, U>): Bluebird<U[]>;
/**
* Cancel this `promise`. Will not do anything if this promise is already settled or if the cancellation feature has not been enabled
*/
cancel(): void;
/**
* Basically sugar for doing: somePromise.catch(function(){});
*
* Which is needed in case error handlers are attached asynchronously to the promise later, which would otherwise result in premature unhandled rejection reporting.
*/
suppressUnhandledRejections(): void;
/**
* Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise.
*
* Note about second argument: if it's specifically a true array, its values become respective arguments for the function call.
* Otherwise it is passed as is as the first argument for the function call.
*
* Alias for `attempt();` for compatibility with earlier ECMAScript version.
*/
static try<R>(fn: () => Resolvable<R>): Bluebird<R>;
static attempt<R>(fn: () => Resolvable<R>): Bluebird<R>;
/**
* Returns a new function that wraps the given function `fn`.
* The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function.
* This method is convenient when a function can sometimes return synchronously or throw synchronously.
*/
static method<R>(fn: () => Resolvable<R>): () => Bluebird<R>;
static method<R, A1>(fn: (arg1: A1) => Resolvable<R>): (arg1: A1) => Bluebird<R>;
static method<R, A1, A2>(fn: (arg1: A1, arg2: A2) => Resolvable<R>): (arg1: A1, arg2: A2) => Bluebird<R>;
static method<R, A1, A2, A3>(fn: (arg1: A1, arg2: A2, arg3: A3) => Resolvable<R>): (arg1: A1, arg2: A2, arg3: A3) => Bluebird<R>;
static method<R, A1, A2, A3, A4>(fn: (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Resolvable<R>): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Bluebird<R>;
static method<R, A1, A2, A3, A4, A5>(fn: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Resolvable<R>): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Bluebird<R>;
static method<R>(fn: (...args: any[]) => Resolvable<R>): (...args: any[]) => Bluebird<R>;
/**
* Create a promise that is resolved with the given `value`. If `value` is a thenable or promise, the returned promise will assume its state.
*/
static resolve(): Bluebird<void>;
static resolve<R>(value: Resolvable<R>): Bluebird<R>;
/**
* Create a promise that is rejected with the given `reason`.
*/
static reject(reason: any): Bluebird<never>;
/**
* @deprecated
* Create a promise with undecided fate and return a `PromiseResolver` to control it. See resolution?: Promise(#promise-resolution).
* @see http://bluebirdjs.com/docs/deprecated-apis.html#promise-resolution
*/
static defer<R>(): Bluebird.Resolver<R>;
/**
* Cast the given `value` to a trusted promise.
*
* If `value` is already a trusted `Promise`, it is returned as is. If `value` is not a thenable, a fulfilled is: Promise returned with `value` as its fulfillment value.
* If `value` is a thenable (Promise-like object, like those returned by jQuery's `$.ajax`), returns a trusted that: Promise assimilates the state of the thenable.
*/
static cast<R>(value: Resolvable<R>): Bluebird<R>;
/**
* Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`.
*/
static bind(thisArg: any): Bluebird<void>;
/**
* See if `value` is a trusted Promise.
*/
static is(value: any): boolean;
/**
* Call this right after the library is loaded to enabled long stack traces.
*
* Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have already been created.
* Long stack traces imply a substantial performance penalty, around 4-5x for throughput and 0.5x for latency.
*/
static longStackTraces(): void;
/**
* Returns a promise that will be resolved with value (or undefined) after given ms milliseconds.
* If value is a promise, the delay will start counting down when it is fulfilled and the returned
* promise will be fulfilled with the fulfillment value of the value promise.
*/
static delay<R>(ms: number, value: Resolvable<R>): Bluebird<R>;
static delay(ms: number): Bluebird<void>;
/**
* Returns a function that will wrap the given `nodeFunction`.
*
* Instead of taking a callback, the returned function will return a promise whose fate is decided by the callback behavior of the given node function.
* The node function should conform to node.js convention of accepting a callback as last argument and
* calling that callback with error as the first argument and success value on the second argument.
*
* If the `nodeFunction` calls its callback with multiple success values, the fulfillment value will be an array of them.
*
* If you pass a `receiver`, the `nodeFunction` will be called as a method on the `receiver`.
*/
static promisify<T>(
func: (callback: (err: any, result?: T) => void) => void,
options?: Bluebird.PromisifyOptions
): () => Bluebird<T>;
static promisify<T, A1>(
func: (arg1: A1, callback: (err: any, result?: T) => void) => void,
options?: Bluebird.PromisifyOptions
): (arg1: A1) => Bluebird<T>;
static promisify<T, A1, A2>(
func: (arg1: A1, arg2: A2, callback: (err: any, result?: T) => void) => void,
options?: Bluebird.PromisifyOptions
): (arg1: A1, arg2: A2) => Bluebird<T>;
static promisify<T, A1, A2, A3>(
func: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, result?: T) => void) => void,
options?: Bluebird.PromisifyOptions
): (arg1: A1, arg2: A2, arg3: A3) => Bluebird<T>;
static promisify<T, A1, A2, A3, A4>(
func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, result?: T) => void) => void,
options?: Bluebird.PromisifyOptions
): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Bluebird<T>;
static promisify<T, A1, A2, A3, A4, A5>(
func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, result?: T) => void) => void,
options?: Bluebird.PromisifyOptions
): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Bluebird<T>;
static promisify(nodeFunction: (...args: any[]) => void, options?: Bluebird.PromisifyOptions): (...args: any[]) => Bluebird<any>;
/**
* Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain.
*
* The promisified method name will be the original method name postfixed with `Async`. Returns the input object.
*
* Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example,
* if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method.
*/
// TODO how to model promisifyAll?
static promisifyAll<T extends object>(target: T, options?: Bluebird.PromisifyAllOptions<T>): PromisifyAll<T>;
/**
* Returns a promise that is resolved by a node style callback function.
*/
static fromNode<T>(resolver: (callback: (err: any, result?: T) => void) => void, options?: Bluebird.FromNodeOptions): Bluebird<T>;
static fromCallback<T>(resolver: (callback: (err: any, result?: T) => void) => void, options?: Bluebird.FromNodeOptions): Bluebird<T>;
/**
* Returns a function that can use `yield` to run asynchronous code synchronously.
*
* This feature requires the support of generators which are drafted in the next version of the language.
* Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch.
*/
// TODO: After https://github.com/Microsoft/TypeScript/issues/2983 is implemented, we can use
// the return type propagation of generators to automatically infer the return type T.
static coroutine<T>(
generatorFunction: () => IterableIterator<any>,
options?: Bluebird.CoroutineOptions
): () => Bluebird<T>;
static coroutine<T, A1>(
generatorFunction: (a1: A1) => IterableIterator<any>,
options?: Bluebird.CoroutineOptions
): (a1: A1) => Bluebird<T>;
static coroutine<T, A1, A2>(
generatorFunction: (a1: A1, a2: A2) => IterableIterator<any>,
options?: Bluebird.CoroutineOptions
): (a1: A1, a2: A2) => Bluebird<T>;
static coroutine<T, A1, A2, A3>(
generatorFunction: (a1: A1, a2: A2, a3: A3) => IterableIterator<any>,
options?: Bluebird.CoroutineOptions
): (a1: A1, a2: A2, a3: A3) => Bluebird<T>;
static coroutine<T, A1, A2, A3, A4>(
generatorFunction: (a1: A1, a2: A2, a3: A3, a4: A4) => IterableIterator<any>,
options?: Bluebird.CoroutineOptions
): (a1: A1, a2: A2, a3: A3, a4: A4) => Bluebird<T>;
static coroutine<T, A1, A2, A3, A4, A5>(
generatorFunction: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5) => IterableIterator<any>,
options?: Bluebird.CoroutineOptions
): (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5) => Bluebird<T>;
static coroutine<T, A1, A2, A3, A4, A5, A6>(
generatorFunction: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6) => IterableIterator<any>,
options?: Bluebird.CoroutineOptions
): (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6) => Bluebird<T>;
static coroutine<T, A1, A2, A3, A4, A5, A6, A7>(
generatorFunction: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7) => IterableIterator<any>,
options?: Bluebird.CoroutineOptions
): (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7) => Bluebird<T>;
static coroutine<T, A1, A2, A3, A4, A5, A6, A7, A8>(
generatorFunction: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8) => IterableIterator<any>,
options?: Bluebird.CoroutineOptions
): (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8) => Bluebird<T>;
/**
* Add `handler` as the handler to call when there is a possibly unhandled rejection. The default handler logs the error stack to stderr or `console.error` in browsers.
*
* Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections.
*/
static onPossiblyUnhandledRejection(handler: (reason: any) => any): void;
/**
* Add handler as the handler to call when there is a possibly unhandled rejection.
* The default handler logs the error stack to stderr or console.error in browsers.
*
* Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections.
*
* Note: this hook is specific to the bluebird instance its called on, application developers should use global rejection events.
*/
static onPossiblyUnhandledRejection(handler?: (error: Error, promise: Bluebird<any>) => void): void;
/**
* Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are fulfilled.
* The promise's fulfillment value is an array with fulfillment values at respective positions to the original array.
* If any promise in the array rejects, the returned promise is rejected with the rejection reason.
*/
// TODO enable more overloads
// array with promises of different types
static all<T1, T2, T3, T4, T5>(values: [Resolvable<T1>, Resolvable<T2>, Resolvable<T3>, Resolvable<T4>, Resolvable<T5>]): Bluebird<[T1, T2, T3, T4, T5]>;
static all<T1, T2, T3, T4>(values: [Resolvable<T1>, Resolvable<T2>, Resolvable<T3>, Resolvable<T4>]): Bluebird<[T1, T2, T3, T4]>;
static all<T1, T2, T3>(values: [Resolvable<T1>, Resolvable<T2>, Resolvable<T3>]): Bluebird<[T1, T2, T3]>;
static all<T1, T2>(values: [Resolvable<T1>, Resolvable<T2>]): Bluebird<[T1, T2]>;
static all<T1>(values: [Resolvable<T1>]): Bluebird<[T1]>;
// array with values
static all<R>(values: Resolvable<Iterable<Resolvable<R>>>): Bluebird<R[]>;
static allSettled<T1, T2, T3, T4, T5>(values: [Resolvable<T1>, Resolvable<T2>, Resolvable<T3>, Resolvable<T4>, Resolvable<T5>]): Bluebird<[Bluebird.Inspection<T1>, Bluebird.Inspection<T2>,
Bluebird.Inspection<T3>, Bluebird.Inspection<T4>, Bluebird.Inspection<T5>]>;
static allSettled<T1, T2, T3, T4>(values: [Resolvable<T1>, Resolvable<T2>, Resolvable<T3>, Resolvable<T4>]): Bluebird<[Bluebird.Inspection<T1>, Bluebird.Inspection<T2>,
Bluebird.Inspection<T3>, Bluebird.Inspection<T4>]>;
static allSettled<T1, T2, T3>(values: [Resolvable<T1>, Resolvable<T2>, Resolvable<T3>]): Bluebird<[Bluebird.Inspection<T1>, Bluebird.Inspection<T2>, Bluebird.Inspection<T3>]>;
static allSettled<T1, T2>(values: [Resolvable<T1>, Resolvable<T2>]): Bluebird<[Bluebird.Inspection<T1>, Bluebird.Inspection<T2>]>;
static allSettled<T1>(values: [Resolvable<T1>]): Bluebird<[Bluebird.Inspection<T1>]>;
static allSettled<R>(values: Resolvable<Iterable<Resolvable<R>>>): Bluebird<Array<Bluebird.Inspection<R>>>;
/**
* Like ``Promise.all`` but for object properties instead of array items. Returns a promise that is fulfilled when all the properties of the object are fulfilled.
*
* The promise's fulfillment value is an object with fulfillment values at respective keys to the original object.
* If any promise in the object rejects, the returned promise is rejected with the rejection reason.
*
* If `object` is a trusted `Promise`, then it will be treated as a promise for object rather than for its properties.
* All other objects are treated for their properties as is returned by `Object.keys` - the object's own enumerable properties.
*
* *The original object is not modified.*
*/
// map
static props<K, V>(map: Resolvable<Map<K, Resolvable<V>>>): Bluebird<Map<K, V>>;
// trusted promise for object
static props<T>(object: PromiseLike<Bluebird.ResolvableProps<T>>): Bluebird<T>;
// object
static props<T>(object: Bluebird.ResolvableProps<T>): Bluebird<T>; // tslint:disable-line:unified-signatures
/**
* Like `Promise.some()`, with 1 as `count`. However, if the promise fulfills, the fulfillment value is not an array of 1 but the value directly.
*/
static any<R>(values: Resolvable<Iterable<Resolvable<R>>>): Bluebird<R>;
/**
* Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is
* fulfilled or rejected as soon as a promise in the array is fulfilled or rejected with the respective rejection reason or fulfillment value.
*
* **Note** If you pass empty array or a sparse array with no values, or a promise/thenable for such, it will be forever pending.
*/
static race<R>(values: Resolvable<Iterable<Resolvable<R>>>): Bluebird<R>;
/**
* Initiate a competitive race between multiple promises or values (values will become immediately fulfilled promises).
* When `count` amount of promises have been fulfilled, the returned promise is fulfilled with an array that contains the fulfillment values of
* the winners in order of resolution.
*
* If too many promises are rejected so that the promise can never become fulfilled,
* it will be immediately rejected with an array of rejection reasons in the order they were thrown in.
*
* *The original array is not modified.*
*/
static some<R>(values: Resolvable<Iterable<Resolvable<R>>>, count: number): Bluebird<R[]>;
/**
* Promise.join(
* Promise<any>|any values...,
* function handler
* ) -> Promise
* For coordinating multiple concurrent discrete promises.
*
* Note: In 1.x and 0.x Promise.join used to be a Promise.all that took the values in as arguments instead in an array.
* This behavior has been deprecated but is still supported partially - when the last argument is an immediate function value the new semantics will apply
*/
static join<R, A1>(
arg1: Resolvable<A1>,
handler: (arg1: A1) => Resolvable<R>
): Bluebird<R>;
static join<R, A1, A2>(
arg1: Resolvable<A1>,
arg2: Resolvable<A2>,
handler: (arg1: A1, arg2: A2) => Resolvable<R>
): Bluebird<R>;
static join<R, A1, A2, A3>(
arg1: Resolvable<A1>,
arg2: Resolvable<A2>,
arg3: Resolvable<A3>,
handler: (arg1: A1, arg2: A2, arg3: A3) => Resolvable<R>
): Bluebird<R>;
static join<R, A1, A2, A3, A4>(
arg1: Resolvable<A1>,
arg2: Resolvable<A2>,
arg3: Resolvable<A3>,
arg4: Resolvable<A4>,
handler: (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Resolvable<R>
): Bluebird<R>;
static join<R, A1, A2, A3, A4, A5>(
arg1: Resolvable<A1>,
arg2: Resolvable<A2>,
arg3: Resolvable<A3>,
arg4: Resolvable<A4>,
arg5: Resolvable<A5>,
handler: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Resolvable<R>
): Bluebird<R>;
// variadic array
/** @deprecated use .all instead */
static join<R>(...values: Array<Resolvable<R>>): Bluebird<R[]>;
/**
* Map an array, or a promise of an array,
* which contains a promises (or a mix of promises and values) with the given `mapper` function with the signature `(item, index, arrayLength)`
* where `item` is the resolved value of a respective promise in the input array.
* If any promise in the input array is rejected the returned promise is rejected as well.
*
* If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well.
*
* *The original array is not modified.*
*/
static map<R, U>(
values: Resolvable<Iterable<Resolvable<R>>>,
mapper: IterateFunction<R, U>,
options?: Bluebird.ConcurrencyOption
): Bluebird<U[]>;
/**
* Reduce an array, or a promise of an array,
* which contains a promises (or a mix of promises and values) with the given `reducer` function with the signature `(total, current, index, arrayLength)`
* where `item` is the resolved value of a respective promise in the input array.
* If any promise in the input array is rejected the returned promise is rejected as well.
*
* If the reducer function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration.
*
* *The original array is not modified. If no `initialValue` is given and the array doesn't contain at least 2 items,
* the callback will not be called and `undefined` is returned.
*
* If `initialValue` is given and the array doesn't have at least 1 item, `initialValue` is returned.*
*/
static reduce<R, U>(
values: Resolvable<Iterable<Resolvable<R>>>,
reducer: (total: U, current: R, index: number, arrayLength: number) => Resolvable<U>,
initialValue?: U
): Bluebird<U>;
/**
* Filter an array, or a promise of an array,
* which contains a promises (or a mix of promises and values) with the given `filterer` function with the signature `(item, index, arrayLength)`
* where `item` is the resolved value of a respective promise in the input array.
* If any promise in the input array is rejected the returned promise is rejected as well.
*
* The return values from the filtered functions are coerced to booleans, with the exception of promises and thenables which are awaited for their eventual result.
*
* *The original array is not modified.
*/
static filter<R>(
values: Resolvable<Iterable<Resolvable<R>>>,
filterer: IterateFunction<R, boolean>,
option?: Bluebird.ConcurrencyOption
): Bluebird<R[]>;
/**
* Iterate over an array, or a promise of an array,
* which contains promises (or a mix of promises and values) with the given iterator function with the signature `(item, index, value)`
* where item is the resolved value of a respective promise in the input array.
* Iteration happens serially. If any promise in the input array is rejected the returned promise is rejected as well.
*
* Resolves to the original array unmodified, this method is meant to be used for side effects.
* If the iterator function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration.
*/
static each<R>(
values: Resolvable<Iterable<Resolvable<R>>>,
iterator: IterateFunction<R, any>
): Bluebird<R[]>;
/**
* Given an Iterable(arrays are Iterable), or a promise of an Iterable, which produces promises (or a mix of promises and values),
* iterate over all the values in the Iterable into an array and iterate over the array serially, in-order.
*
* Returns a promise for an array that contains the values returned by the iterator function in their respective positions.
* The iterator won't be called for an item until its previous item, and the promise returned by the iterator for that item are fulfilled.
* This results in a mapSeries kind of utility but it can also be used simply as a side effect iterator similar to Array#forEach.
*
* If any promise in the input array is rejected or any promise returned by the iterator function is rejected, the result will be rejected as well.
*/
static mapSeries<R, U>(
values: Resolvable<Iterable<Resolvable<R>>>,
iterator: IterateFunction<R, U>
): Bluebird<U[]>;
/**
* A meta method used to specify the disposer method that cleans up a resource when using `Promise.using`.
*
* Returns a Disposer object which encapsulates both the resource as well as the method to clean it up.
* The user can pass this object to `Promise.using` to get access to the resource when it becomes available,
* as well as to ensure its automatically cleaned up.
*
* The second argument passed to a disposer is the result promise of the using block, which you can
* inspect synchronously.
*/
disposer(disposeFn: (arg: R, promise: Bluebird<R>) => Resolvable<void>): Bluebird.Disposer<R>;
/**
* In conjunction with `.disposer`, using will make sure that no matter what, the specified disposer
* will be called when the promise returned by the callback passed to using has settled. The disposer is
* necessary because there is no standard interface in node for disposing resources.
*/
static using<R, T>(
disposer: Bluebird.Disposer<R>,
executor: (transaction: R) => PromiseLike<T>
): Bluebird<T>;
static using<R1, R2, T>(
disposer: Bluebird.Disposer<R1>,
disposer2: Bluebird.Disposer<R2>,
executor: (transaction1: R1, transaction2: R2
) => PromiseLike<T>): Bluebird<T>;
static using<R1, R2, R3, T>(
disposer: Bluebird.Disposer<R1>,
disposer2: Bluebird.Disposer<R2>,
disposer3: Bluebird.Disposer<R3>,
executor: (transaction1: R1, transaction2: R2, transaction3: R3) => PromiseLike<T>
): Bluebird<T>;
/**
* Configure long stack traces, warnings, monitoring and cancellation.
* Note that even though false is the default here, a development environment might be detected which automatically
* enables long stack traces and warnings.
*/
static config(options: {
/** Enable warnings */
warnings?: boolean | {
/** Enables all warnings except forgotten return statements. */
wForgottenReturn: boolean;
} | undefined;
/** Enable long stack traces */
longStackTraces?: boolean | undefined;
/** Enable cancellation */
cancellation?: boolean | undefined;
/** Enable monitoring */
monitoring?: boolean | undefined;
/** Enable async hooks */
asyncHooks?: boolean | undefined;
}): void;
/**
* Create a new promise. The passed in function will receive functions `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise.
* If promise cancellation is enabled, passed in function will receive one more function argument `onCancel` that allows to register an optional cancellation callback.
*/
static Promise: typeof Bluebird;
/**
* The version number of the library
*/
static version: string;
}
declare namespace Bluebird {
interface ConcurrencyOption {
concurrency: number;
}
interface SpreadOption {
spread: boolean;
}
interface FromNodeOptions {
multiArgs?: boolean | undefined;
}
interface PromisifyOptions {
context?: any;
multiArgs?: boolean | undefined;
}
interface PromisifyAllOptions<T> extends PromisifyOptions {
suffix?: string | undefined;
filter?(name: string, func: (...args: any[]) => any, target?: any, passesDefaultFilter?: boolean): boolean;
// The promisifier gets a reference to the original method and should return a function which returns a promise
promisifier?(this: T, originalMethod: (...args: any[]) => any, defaultPromisifer: (...args: any[]) => (...args: any[]) => Bluebird<any>): () => PromiseLike<any>;
}
interface CoroutineOptions {
yieldHandler(value: any): any;
}
/**
* Represents an error is an explicit promise rejection as opposed to a thrown error.
* For example, if an error is errbacked by a callback API promisified through undefined or undefined
* and is not a typed error, it will be converted to a `OperationalError` which has the original error in
* the `.cause` property.
*
* `OperationalError`s are caught in `.error` handlers.
*/
class OperationalError extends Error { }
/**
* Signals that an operation has timed out. Used as a custom cancellation reason in `.timeout`.
*/
class TimeoutError extends Error { }
/**
* Signals that an operation has been aborted or cancelled. The default reason used by `.cancel`.
*/
class CancellationError extends Error { }
/**
* A collection of errors. `AggregateError` is an array-like object, with numeric indices and a `.length` property.
* It supports all generic array methods such as `.forEach` directly.
*
* `AggregateError`s are caught in `.error` handlers, even if the contained errors are not operational.
*
* `Promise.some` and `Promise.any` use `AggregateError` as rejection reason when they fail.
*/
class AggregateError extends Error implements ArrayLike<Error> {
length: number;
[index: number]: Error;
join(separator?: string): string;
pop(): Error;
push(...errors: Error[]): number;
shift(): Error;
unshift(...errors: Error[]): number;
slice(begin?: number, end?: number): AggregateError;
filter(callback: (element: Error, index: number, array: AggregateError) => boolean, thisArg?: any): AggregateError;
forEach(callback: (element: Error, index: number, array: AggregateError) => void, thisArg?: any): undefined;
some(callback: (element: Error, index: number, array: AggregateError) => boolean, thisArg?: any): boolean;
every(callback: (element: Error, index: number, array: AggregateError) => boolean, thisArg?: any): boolean;
map(callback: (element: Error, index: number, array: AggregateError) => boolean, thisArg?: any): AggregateError;
indexOf(searchElement: Error, fromIndex?: number): number;
lastIndexOf(searchElement: Error, fromIndex?: number): number;
reduce(callback: (accumulator: any, element: Error, index: number, array: AggregateError) => any, initialValue?: any): any;
reduceRight(callback: (previousValue: any, element: Error, index: number, array: AggregateError) => any, initialValue?: any): any;
sort(compareFunction?: (errLeft: Error, errRight: Error) => number): AggregateError;
reverse(): AggregateError;
}
/**
* returned by `Bluebird.disposer()`.
*/
class Disposer<R> { }
/** @deprecated Use PromiseLike<T> directly. */
type Thenable<T> = PromiseLike<T>;
type ResolvableProps<T> = object & {[K in keyof T]: Resolvable<T[K]>};
interface Resolver<R> {
/**
* Returns a reference to the controlled promise that can be passed to clients.
*/
promise: Bluebird<R>;
/**
* Resolve the underlying promise with `value` as the resolution value. If `value` is a thenable or a promise, the underlying promise will assume its state.
*/
resolve(value: R): void;
resolve(): void;
/**
* Reject the underlying promise with `reason` as the rejection reason.
*/
reject(reason: any): void;
/**
* Gives you a callback representation of the `PromiseResolver`. Note that this is not a method but a property.
* The callback accepts error object in first argument and success values on the 2nd parameter and the rest, I.E. node js conventions.
*
* If the the callback is called with multiple success values, the resolver fulfills its promise with an array of the values.
*/
// TODO specify resolver callback
callback(err: any, value: R, ...values: R[]): void;
}
interface Inspection<R> {
/**
* See if the underlying promise was fulfilled at the creation time of this inspection object.
*/
isFulfilled(): boolean;
/**
* See if the underlying promise was rejected at the creation time of this inspection object.
*/
isRejected(): boolean;
/**
* See if the underlying promise was cancelled at the creation time of this inspection object.
*/
isCancelled(): boolean;
/**
* See if the underlying promise was defer at the creation time of this inspection object.
*/
isPending(): boolean;
/**
* Get the fulfillment value of the underlying promise. Throws if the promise wasn't fulfilled at the creation time of this inspection object.
*
* throws `TypeError`
*/
value(): R;
/**
* Get the rejection reason for the underlying promise. Throws if the promise wasn't rejected at the creation time of this inspection object.
*
* throws `TypeError`
*/
reason(): any;
}
/**
* Returns a new independent copy of the Bluebird library.
*
* This method should be used before you use any of the methods which would otherwise alter the global Bluebird object - to avoid polluting global state.
*/
function getNewLibraryCopy(): typeof Bluebird;
/**
* This is relevant to browser environments with no module loader.
*
* Release control of the Promise namespace to whatever it was before this library was loaded.
* Returns a reference to the library namespace so you can attach it to something else.
*/
function noConflict(): typeof Bluebird;
/**
* Changes how bluebird schedules calls a-synchronously.
*
* @param scheduler Should be a function that asynchronously schedules
* the calling of the passed in function
*/
function setScheduler(scheduler: (callback: (...args: any[]) => void) => void): void;
}
export = Bluebird; | the_stack |
import {
after as importedAfter,
before as importedBefore,
afterEach as importedAfterEach,
beforeEach as importedBeforeEach,
describe as importedDescribe,
it as importedIt,
xit as importedXit
} from 'mocha';
import LocalMocha = require('mocha');
// Warning!!
// Don't refer node.d.ts!!
// See #22510.
(): number => setTimeout(() => 0, 0);
declare let number: number;
declare let boolean: boolean;
declare let string: string;
declare let stringOrUndefined: string | undefined;
declare let any: any;
// Use module augmentation to add a third-party interface or reporter
declare module 'mocha' {
interface InterfaceContributions {
'third-party-interface': never;
}
interface ReporterContributions {
'third-party-reporter': never;
}
}
const thirdPartyInterface: Mocha.Interface = 'third-party-interface';
const thirdPartyReporter: Mocha.Reporter = 'third-party-reporter';
// Lazy tests of compatibility between imported and global functions; should be identical
const _after: typeof after = importedAfter;
const _after2: typeof importedAfter = after;
const _before: typeof before = importedBefore;
const _before2: typeof importedBefore = before;
const _afterEach: typeof afterEach = importedAfterEach;
const _afterEach2: typeof importedAfterEach = afterEach;
const _beforeEach: typeof beforeEach = importedBeforeEach;
const _beforeEach2: typeof importedBeforeEach = beforeEach;
const _describe: typeof describe = importedDescribe;
const _describe2: typeof importedDescribe = describe;
const _it: typeof it = importedIt;
const _it2: typeof importedIt = it;
const _xit: typeof xit = importedXit;
const _xit2: typeof importedXit = xit;
function test_bdd_describe() {
// $ExpectType Suite
describe('something', function() {
// $ExpectType Suite
this;
});
// $ExpectType Suite
describe.only('something', function() {
// $ExpectType Suite
this;
});
// $ExpectType void | Suite
describe.skip('something', function() {
// $ExpectType Suite
this;
});
}
function test_bdd_context() {
// $ExpectType Suite
context('something', function() {
// $ExpectType Suite
this;
});
// $ExpectType Suite
context.only('something', function() {
// $ExpectType Suite
this;
});
// $ExpectType void | Suite
context.skip('something', function() {
// $ExpectType Suite
this;
});
}
function test_bdd_xdescribe() {
// $ExpectType void | Suite
xdescribe('something', function() {
// $ExpectType Suite
this;
});
}
function test_bdd_xcontext() {
// $ExpectType void | Suite
xcontext('something', function() {
// $ExpectType Suite
this;
});
}
function test_tdd_suite() {
// $ExpectType Suite
suite('something', function() {
// $ExpectType Suite
this;
});
// $ExpectType Suite
suite.only('something', function() {
// $ExpectType Suite
this;
});
// $ExpectType void | Suite
suite.skip('something', function() {
// $ExpectType Suite
this;
});
}
function test_qunit_suite() {
// $ExpectType Suite
suite('some context');
// $ExpectType Suite
suite.only('some context');
}
function test_bdd_it() {
// $ExpectType Test
it(function doesSomething(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
// $ExpectType Test
it(async function doesSomething() {
// $ExpectType Context
this;
});
// $ExpectType Test
it('does something', function(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
// $ExpectType Test
it('does something', async function() {
// $ExpectType Context
this;
});
// $ExpectType Test
it.only(function doesSomething(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
// $ExpectType Test
it.only(async function doesSomething() {
// $ExpectType Context
this;
});
// $ExpectType Test
it.only('does something', function(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
// $ExpectType Test
it.only('does something', async function() {
// $ExpectType Context
this;
});
// $ExpectType Test
it.skip(function doesSomething(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
// $ExpectType Test
it.skip(async function doesSomething() {
// $ExpectType Context
this;
});
// $ExpectType Test
it.skip('does something', function(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
// $ExpectType Test
it.skip('does something', async function() {
// $ExpectType Context
this;
});
// $ExpectType void
it.retries(number);
}
function test_bdd_xit() {
// $ExpectType Test
xit(function doesSomething(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
// $ExpectType Test
xit(async function doesSomething() {
// $ExpectType Context
this;
});
// $ExpectType Test
xit('does something', function(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
// $ExpectType Test
xit('does something', async function() {
// $ExpectType Context
this;
});
}
function test_bdd_specify() {
// $ExpectType Test
specify(function doesSomething(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
// $ExpectType Test
specify(async function doesSomething() {
// $ExpectType Context
this;
});
// $ExpectType Test
specify('does something', function(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
// $ExpectType Test
specify('does something', async function() {
// $ExpectType Context
this;
});
// $ExpectType Test
specify.only(function doesSomething(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
// $ExpectType Test
specify.only(async function doesSomething() {
// $ExpectType Context
this;
});
// $ExpectType Test
specify.only('does something', function(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
// $ExpectType Test
specify.only('does something', async function() {
// $ExpectType Context
this;
});
// $ExpectType Test
specify.skip(function doesSomething(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
// $ExpectType Test
specify.skip(async function doesSomething() {
// $ExpectType Context
this;
});
// $ExpectType Test
specify.skip('does something', function(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
// $ExpectType Test
specify.skip('does something', async function() {
// $ExpectType Context
this;
});
// $ExpectType void
specify.retries(number);
}
function test_bdd_xspecify() {
// $ExpectType Test
xspecify(function doesSomething(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
// $ExpectType Test
xspecify(async function doesSomething() {
// $ExpectType Context
this;
});
// $ExpectType Test
xspecify('does something', function(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
// $ExpectType Test
xspecify('does something', async function() {
// $ExpectType Context
this;
});
}
function test_tdd_qunit_test() {
// $ExpectType Test
test(function doesSomething(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
// $ExpectType Test
test(async function doesSomething() {
// $ExpectType Context
this;
});
// $ExpectType Test
test('does something', function(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
// $ExpectType Test
test('does something', async function() {
// $ExpectType Context
this;
});
// $ExpectType Test
test.only(function doesSomething(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
// $ExpectType Test
test.only(async function doesSomething() {
// $ExpectType Context
this;
});
// $ExpectType Test
test.only('does something', function(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
// $ExpectType Test
test.only('does something', async function() {
// $ExpectType Context
this;
});
// $ExpectType Test
test.skip(function doesSomething(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
// $ExpectType Test
test.skip(async function doesSomething() {
// $ExpectType Context
this;
});
// $ExpectType Test
test.skip('does something', function(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
// $ExpectType Test
test.skip('does something', async function() {
// $ExpectType Context
this;
});
// $ExpectType void
test.retries(number);
}
function test_bdd_qunit_before() {
before(function(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
before(async function() {
// $ExpectType Context
this;
});
before('description', function(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
before('description', async function() {
// $ExpectType Context
this;
});
}
function test_tdd_setup() {
setup(function(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
setup(async function() {
// $ExpectType Context
this;
});
setup('description', function(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
setup('description', async function() {
// $ExpectType Context
this;
});
}
function test_bdd_qunit_after() {
after(function(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
after(async function() {
// $ExpectType Context
this;
});
after('description', function(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
after('description', async function() {
// $ExpectType Context
this;
});
}
function test_tdd_teardown() {
teardown(function(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
teardown(async function() {
// $ExpectType Context
this;
});
teardown('description', function(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
teardown('description', async function() {
// $ExpectType Context
this;
});
}
function test_bdd_qunit_beforeEach() {
beforeEach(function(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
beforeEach(async function() {
// $ExpectType Context
this;
});
beforeEach('description', function(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
beforeEach('description', async function() {
// $ExpectType Context
this;
});
}
function test_tdd_suiteSetup() {
suiteSetup(function(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
suiteSetup(async function() {
// $ExpectType Context
this;
});
suiteSetup('description', function(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
suiteSetup('description', async function() {
// $ExpectType Context
this;
});
}
function test_bdd_qunit_afterEach() {
afterEach(function(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
afterEach(async function() {
// $ExpectType Context
this;
});
afterEach('description', function(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
afterEach('description', async function() {
// $ExpectType Context
this;
});
}
function test_tdd_suiteTeardown() {
suiteTeardown(function(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
suiteTeardown(async function() {
// $ExpectType Context
this;
});
suiteTeardown('description', function(done) {
// $ExpectType Done
done;
// $ExpectType Context
this;
});
suiteTeardown('description', async function() {
// $ExpectType Context
this;
});
}
function test_Context(ctx: LocalMocha.Context, runnable: LocalMocha.Runnable) {
// $ExpectType never
ctx.skip(); // throws
// $ExpectType boolean
ctx.enableTimeouts();
// $ExpectType Context
ctx.enableTimeouts(boolean);
// $ExpectType number
ctx.retries();
// $ExpectType Context
ctx.retries(number);
// $ExpectType Runnable
ctx.runnable();
// $ExpectType Context
ctx.runnable(runnable);
// $ExpectType number
ctx.slow();
// $ExpectType Context
ctx.slow(number);
// $ExpectType number
ctx.timeout();
// $ExpectType Context
ctx.timeout(number);
// $ExpectType Test | undefined
ctx.currentTest;
// $ExpectType Runnable | undefined
ctx.test;
ctx["extended"] = any;
// $ExpectType any
ctx["extended"];
ctx.enableTimeouts(boolean)
.retries(number)
.runnable(runnable)
.slow(number)
.timeout(number)
.skip();
}
function test_reporter_string(localMocha: LocalMocha) {
// $ExpectType BrowserMocha
mocha.reporter('html');
const m: Mocha = localMocha.reporter('html');
}
function test_reporter_function(localMocha: LocalMocha) {
// $ExpectType BrowserMocha
mocha.reporter(class extends LocalMocha.reporters.Base { });
const m: Mocha = localMocha.reporter(class extends LocalMocha.reporters.Base { });
}
function test_browser_mocha_setup_slow_option() {
// $ExpectType BrowserMocha
mocha.setup({ slow: 25 });
}
function test_browser_mocha_setup_timeout_option() {
// $ExpectType BrowserMocha
mocha.setup({ timeout: 25 });
}
function test_browser_mocha_setup_globals_option() {
// $ExpectType BrowserMocha
mocha.setup({ globals: ['mocha'] });
}
function test_browser_mocha_setup_ui_option() {
// $ExpectType BrowserMocha
mocha.setup({ ui: 'bdd' });
}
function test_browser_mocha_setup_reporter_string_option() {
// $ExpectType BrowserMocha
mocha.setup({ reporter: 'html' });
}
function test_browser_mocha_setup_require_stringArray_option() {
// $ExpectType BrowserMocha
mocha.setup({ require: ['ts-node/register'] });
}
function test_browser_mocha_setup_reporter_function_option() {
// $ExpectType BrowserMocha
mocha.setup({ reporter: class extends LocalMocha.reporters.Base { } });
}
function test_browser_mocha_setup_bail_option() {
// $ExpectType BrowserMocha
mocha.setup({ bail: false });
}
function test_browser_mocha_setup_ignore_leaks_option() {
// $ExpectType BrowserMocha
mocha.setup({ ignoreLeaks: false });
}
function test_browser_mocha_setup_grep_string_option() {
// $ExpectType BrowserMocha
mocha.setup({ grep: "describe" });
}
function test_browser_mocha_setup_grep_regex_option() {
// $ExpectType BrowserMocha
mocha.setup({ grep: new RegExp('describe') });
}
function test_browser_mocha_setup_grep_regex_literal_option() {
// $ExpectType BrowserMocha
mocha.setup({ grep: /(expect|should)/i });
}
function test_browser_mocha_setup_all_options() {
// $ExpectType BrowserMocha
mocha.setup({
slow: 25,
timeout: 25,
ui: 'bdd',
globals: ['mocha'],
reporter: 'html',
bail: true,
ignoreLeaks: true,
grep: 'test',
require: ['ts-node/register'] // TODO: It doesn't appear this is actually supported. Should it be removed?
});
}
function testLoadFilesAsync() {
mocha.loadFilesAsync();
}
function test_constructor_slow_option() {
const m: Mocha = new LocalMocha({ slow: 25 });
}
function test_constructor_timeout_option() {
const m: Mocha = new LocalMocha({ timeout: 25 });
}
function test_constructor_timeout_option_string() {
const m: Mocha = new LocalMocha({ timeout: '1s' });
}
function test_constructor_globals_option() {
const m: Mocha = new LocalMocha({ globals: ['mocha'] });
}
function test_constructor_ui_option() {
const m: Mocha = new LocalMocha({ ui: 'bdd' });
}
function test_constructor_reporter_string_option() {
const m: Mocha = new LocalMocha({ reporter: 'html' });
}
function test_constructor_reporter_function_option() {
const m: Mocha = new LocalMocha({ reporter: class extends LocalMocha.reporters.Base { } });
}
function test_constructor_bail_option() {
const m: Mocha = new LocalMocha({ bail: false });
}
function test_constructor_ignore_leaks_option() {
const m: Mocha = new LocalMocha({ ignoreLeaks: false });
}
function test_constructor_grep_string_option() {
const m: Mocha = new LocalMocha({ grep: "describe" });
}
function test_constructor_grep_regex_option() {
const m: Mocha = new LocalMocha({ grep: new RegExp('describe') });
}
function test_constructor_grep_regex_literal_option() {
const m: Mocha = new LocalMocha({ grep: /(expect|should)/i });
}
function test_constructor_all_options() {
const m: Mocha = new LocalMocha({
slow: 25,
timeout: 25,
ui: 'bdd',
globals: ['mocha'],
reporter: 'html',
bail: true,
ignoreLeaks: true,
grep: 'test'
});
}
function test_run(localMocha: LocalMocha) {
// $ExpectType Runner
mocha.run();
// $ExpectType Runner
mocha.run((failures) => {
// $ExpectType number
failures;
});
// $ExpectType Runner
localMocha.run();
// $ExpectType Runner
localMocha.run((failures) => {
// $ExpectType number
failures;
});
}
function test_growl() {
mocha.growl();
}
function test_chaining() {
new LocalMocha({ slow: 25 })
.growl()
.reporter('html')
.reporter(class extends LocalMocha.reporters.Base { });
}
function test_require_constructor_empty() {
const instance = new LocalMocha();
}
function test_require_constructor_noOptions() {
const instance = new LocalMocha({});
}
function test_require_constructor_allOptions() {
const instance = new LocalMocha({
grep: /[a-z]*/,
ui: 'tdd',
reporter: 'dot',
timeout: 500,
bail: true
});
}
function test_require_fluentParams() {
const instance = new LocalMocha();
instance.bail(true)
.bail()
.addFile('foo.js')
.reporter('dot')
.ui('bdd')
.grep('[a-z]*')
.grep(/[a-z]*/)
.invert()
.ignoreLeaks(true)
.checkLeaks()
.growl()
.globals('foo')
.globals(['bar', 'zap'])
.useColors(true)
.useInlineDiffs(true)
.timeout(500)
.slow(100)
.enableTimeouts(true)
.asyncOnly()
.noHighlighting()
.run();
}
function test_throwError() {
mocha.throwError(new Error("I'm an error!"));
}
function test_mochaRunner_properties(runner: LocalMocha.Runner, suite: LocalMocha.Suite) {
// $Expecttype Runner
runner.abort();
// $ExpectType Suite
runner.suite;
// $ExpectType boolean
runner.started;
// $ExpectType number
runner.total;
// $ExpectType number
runner.failures;
// $ExpectType Runner
runner.grep(/regex/, false);
// $ExpectType number
runner.grepTotal(suite);
// $ExpectType string[]
runner.globals();
// $ExpectType Runner
runner.globals(["hello", "world"]);
// $ExpectType Runner
runner.run();
// $ExpectType Runner
runner.run((failures) => {
// $ExpectType number
failures;
});
}
function test_base_reporter_properties(reporter: LocalMocha.reporters.Base) {
// $ExpectType number
reporter.stats.failures;
// $ExpectType number
reporter.stats.passes;
// $ExpectType number
reporter.stats.pending;
// $ExpectType number
reporter.stats.suites;
// $ExpectType number
reporter.stats.tests;
// $ExpectType Date | undefined
reporter.stats.start;
// $ExpectType Date | undefined
reporter.stats.end;
// $ExpectType number | undefined
reporter.stats.duration;
}
function test_runner_events(runner: LocalMocha.Runner) {
// $ExpectType Runner
runner.on("start", () => {});
// $ExpectType Runner
runner.on(LocalMocha.Runner.constants.EVENT_RUN_BEGIN, () => {});
// $ExpectType Runner
runner.on("end", () => {});
// $ExpectType Runner
runner.on(LocalMocha.Runner.constants.EVENT_RUN_END, () => {});
// $ExpectType Runner
runner.on("suite", (suite) => {
// $ExpectType Suite
suite;
});
// $ExpectType Runner
runner.on(LocalMocha.Runner.constants.EVENT_SUITE_BEGIN, (suite) => {
// $ExpectType Suite
suite;
});
// $ExpectType Runner
runner.on("suite end", (suite) => {
// $ExpectType Suite
suite;
});
// $ExpectType Runner
runner.on(LocalMocha.Runner.constants.EVENT_SUITE_END, (suite) => {
// $ExpectType Suite
suite;
});
// $ExpectType Runner
runner.on("test", (test) => {
// $ExpectType Test
test;
});
// $ExpectType Runner
runner.on(LocalMocha.Runner.constants.EVENT_TEST_BEGIN, (test) => {
// $ExpectType Test
test;
});
// $ExpectType Runner
runner.on("test end", (test) => {
// $ExpectType Test
test;
});
// $ExpectType Runner
runner.on(LocalMocha.Runner.constants.EVENT_TEST_END, (test) => {
// $ExpectType Test
test;
});
// $ExpectType Runner
runner.on("hook", (hook) => {
// $ExpectType Hook
hook;
});
// $ExpectType Runner
runner.on(LocalMocha.Runner.constants.EVENT_HOOK_BEGIN, (hook) => {
// $ExpectType Hook
hook;
});
// $ExpectType Runner
runner.on("hook end", (hook) => {
// $ExpectType Hook
hook;
});
// $ExpectType Runner
runner.on(LocalMocha.Runner.constants.EVENT_HOOK_END, (hook) => {
// $ExpectType Hook
hook;
});
// $ExpectType Runner
runner.on("pass", (test) => {
// $ExpectType Test
test;
});
// $ExpectType Runner
runner.on(LocalMocha.Runner.constants.EVENT_TEST_PASS, (test) => {
// $ExpectType Test
test;
});
// $ExpectType Runner
runner.on("fail", (test, err) => {
// $ExpectType Test
test;
// $ExpectType any
err;
});
// $ExpectType Runner
runner.on(LocalMocha.Runner.constants.EVENT_TEST_FAIL, (test, err) => {
// $ExpectType Test
test;
// $ExpectType any
err;
});
// $ExpectType Runner
runner.on("pending", (test) => {
// $ExpectType Test
test;
});
// $ExpectType Runner
runner.on(LocalMocha.Runner.constants.EVENT_TEST_PENDING, (test) => {
// $ExpectType Test
test;
});
}
function test_runnable_events(runnable: LocalMocha.Runnable) {
// $ExpectType Runnable
runnable.on("error", (error) => {
// $ExpectType any
error;
});
}
function test_suite_events(suite: LocalMocha.Suite) {
// $ExpectType Suite
suite.on("beforeAll", (hook) => {
// $ExpectType Hook
hook;
});
// $ExpectType Suite
suite.on(LocalMocha.Suite.constants.EVENT_SUITE_ADD_HOOK_BEFORE_ALL, (hook) => {
// $ExpectType Hook
hook;
});
// $ExpectType Suite
suite.on("afterAll", (hook) => {
// $ExpectType Hook
hook;
});
// $ExpectType Suite
suite.on(LocalMocha.Suite.constants.EVENT_SUITE_ADD_HOOK_AFTER_ALL, (hook) => {
// $ExpectType Hook
hook;
});
// $ExpectType Suite
suite.on("beforeEach", (hook) => {
// $ExpectType Hook
hook;
});
// $ExpectType Suite
suite.on(LocalMocha.Suite.constants.EVENT_SUITE_ADD_HOOK_BEFORE_EACH, (hook) => {
// $ExpectType Hook
hook;
});
// $ExpectType Suite
suite.on("afterEach", (hook) => {
// $ExpectType Hook
hook;
});
// $ExpectType Suite
suite.on(LocalMocha.Suite.constants.EVENT_SUITE_ADD_HOOK_AFTER_EACH, (hook) => {
// $ExpectType Hook
hook;
});
// $ExpectType Suite
suite.on("run", () => { });
// $ExpectType Suite
suite.on(LocalMocha.Suite.constants.EVENT_ROOT_SUITE_RUN, () => { });
// $ExpectType Suite
suite.on("pre-require", (context, file, mocha) => {
// $ExpectType MochaGlobals
context;
// $ExpectType string
file;
const m: Mocha = mocha;
});
// $ExpectType Suite
suite.on(LocalMocha.Suite.constants.EVENT_FILE_PRE_REQUIRE, (context, file, mocha) => {
// $ExpectType MochaGlobals
context;
// $ExpectType string
file;
const m: Mocha = mocha;
});
// $ExpectType Suite
suite.on("require", (module, file, mocha) => {
// $ExpectType any
module;
// $ExpectType string
file;
const m: Mocha = mocha;
});
suite.on(LocalMocha.Suite.constants.EVENT_FILE_REQUIRE, (module, file, mocha) => {
// $ExpectType any
module;
// $ExpectType string
file;
const m: Mocha = mocha;
});
// $ExpectType Suite
suite.on("post-require", (context, file, mocha) => {
// $ExpectType MochaGlobals
context;
// $ExpectType string
file;
const m: Mocha = mocha;
});
suite.on(LocalMocha.Suite.constants.EVENT_FILE_POST_REQUIRE, (context, file, mocha) => {
// $ExpectType MochaGlobals
context;
// $ExpectType string
file;
const m: Mocha = mocha;
});
}
function test_backcompat_Suite(suite: Mocha.Suite, iSuite: Mocha.ISuite, iSuiteContext: Mocha.ISuiteCallbackContext, iTest: Mocha.ITest, iContext: Mocha.IContext) {
iSuite = suite;
iSuiteContext = suite;
suite.addTest(iTest);
suite.addSuite(iSuite);
LocalMocha.Suite.create(iSuite, string);
new LocalMocha.Suite(string, iContext);
}
function test_backcompat_Runner(runner: Mocha.Runner, iRunner: Mocha.IRunner, iSuite: Mocha.ISuite) {
iRunner = runner;
runner.grepTotal(iSuite);
}
function test_backcompat_Runnable(runnable: Mocha.Runnable, iRunnable: Mocha.IRunnable) {
iRunnable = runnable;
}
function test_backcompat_Test(test: Mocha.Test, iTest: Mocha.ITest) {
iTest = test;
}
function test_backcompat_Hook(hook: Mocha.Hook, iHook: Mocha.IHook) {
iHook = hook;
}
function test_backcompat_Context(context: Mocha.Context, iContext: Mocha.IContext,
iHookContext: Mocha.IHookCallbackContext, iBeforeAfterContext: Mocha.IBeforeAndAfterContext,
iTestContext: Mocha.ITestCallbackContext, iRunnable: Mocha.IRunnable) {
iContext = context;
iHookContext = context;
iBeforeAfterContext = context;
iTestContext = context;
context.runnable(iRunnable);
}
function test_backcompat_Base(iRunner: Mocha.IRunner) {
new LocalMocha.reporters.Base(iRunner);
}
function test_backcompat_XUnit(iRunner: Mocha.IRunner) {
new LocalMocha.reporters.XUnit(iRunner);
}
function test_backcompat_Progress(iRunner: Mocha.IRunner) {
new LocalMocha.reporters.Progress(iRunner);
}
import common = require("mocha/lib/interfaces/common");
function test_interfaces_common(suites: Mocha.Suite[], context: Mocha.MochaGlobals, localMocha: Mocha,
fn: Mocha.Func | Mocha.AsyncFunc, test: Mocha.Test) {
const funcs = common(suites, context, localMocha);
// $ExpectType CommonFunctions
funcs;
funcs.before(fn);
funcs.before(string, fn);
funcs.beforeEach(fn);
funcs.beforeEach(string, fn);
funcs.after(fn);
funcs.after(string, fn);
funcs.afterEach(fn);
funcs.afterEach(string, fn);
// $ExpectType Suite
funcs.suite.create({ title: string });
funcs.suite.create({ title: string, file: string, fn: () => {}, pending: boolean, isOnly: boolean });
// $ExpectType Suite
funcs.suite.only({ title: string });
funcs.suite.only({ title: string, file: string, fn: () => {}, pending: boolean, isOnly: boolean });
// $ExpectType Suite
funcs.suite.skip({ title: string });
funcs.suite.skip({ title: string, file: string, fn: () => {}, pending: boolean, isOnly: boolean });
// $ExpectType Test
funcs.test.only(mocha, test);
funcs.test.skip(string);
funcs.test.retries(number);
}
// mocha-typescript (https://www.npmjs.com/package/mocha-typescript/) augments
// the mocha functions and enables them to work as test class decorators.
declare module "mocha" {
interface SuiteFunction {
<TFunction extends Function>(target: TFunction): TFunction | void;
}
interface PendingSuiteFunction {
<TFunction extends Function>(target: TFunction): TFunction | void;
}
interface ExclusiveSuiteFunction {
<TFunction extends Function>(target: TFunction): TFunction | void;
}
interface TestFunction {
(target: Object, propertyKey: string | symbol): void;
}
interface PendingTestFunction {
(target: Object, propertyKey: string | symbol): void;
}
interface ExclusiveTestFunction {
(target: Object, propertyKey: string | symbol): void;
}
}
@suite
class TestClass1 {
@test method1() {}
@test.only method2() {}
@test.skip method3() {}
}
@suite.skip
class TestClass2 {
}
@suite.only
class TestClass3 {
}
// end of augmentations used by mocha-typescript | the_stack |
const token = /d{1,4}|M{1,4}|YY(?:YY)?|S{1,3}|Do|ZZ|Z|([HhMsDm])\1?|[aA]|"[^"]*"|'[^']*'/g;
const twoDigitsOptional = "[1-9]\\d?";
const twoDigits = "\\d\\d";
const threeDigits = "\\d{3}";
const fourDigits = "\\d{4}";
const word = "[^\\s]+";
const literal = /\[([^]*?)\]/gm;
type DateInfo = {
year: number;
month: number;
day: number;
hour: number;
minute: number;
second: number;
millisecond: number;
isPm: number | null;
timezoneOffset: number | null;
};
export type I18nSettings = {
amPm: [string, string];
dayNames: Days;
dayNamesShort: Days;
monthNames: Months;
monthNamesShort: Months;
DoFn(dayOfMonth: number): string;
};
export type I18nSettingsOptional = Partial<I18nSettings>;
export type Days = [string, string, string, string, string, string, string];
export type Months = [
string,
string,
string,
string,
string,
string,
string,
string,
string,
string,
string,
string
];
function shorten<T extends string[]>(arr: T, sLen: number): string[] {
const newArr: string[] = [];
for (let i = 0, len = arr.length; i < len; i++) {
newArr.push(arr[i].substr(0, sLen));
}
return newArr;
}
const monthUpdate = (
arrName: "monthNames" | "monthNamesShort" | "dayNames" | "dayNamesShort"
) => (v: string, i18n: I18nSettings): number | null => {
const lowerCaseArr = i18n[arrName].map(v => v.toLowerCase());
const index = lowerCaseArr.indexOf(v.toLowerCase());
if (index > -1) {
return index;
}
return null;
};
export function assign<A>(a: A): A;
export function assign<A, B>(a: A, b: B): A & B;
export function assign<A, B, C>(a: A, b: B, c: C): A & B & C;
export function assign<A, B, C, D>(a: A, b: B, c: C, d: D): A & B & C & D;
export function assign(origObj: any, ...args: any[]): any {
for (const obj of args) {
for (const key in obj) {
// @ts-ignore ex
origObj[key] = obj[key];
}
}
return origObj;
}
const dayNames: Days = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
];
const monthNames: Months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
];
const monthNamesShort: Months = shorten(monthNames, 3) as Months;
const dayNamesShort: Days = shorten(dayNames, 3) as Days;
const defaultI18n: I18nSettings = {
dayNamesShort,
dayNames,
monthNamesShort,
monthNames,
amPm: ["am", "pm"],
DoFn(dayOfMonth: number) {
return (
dayOfMonth +
["th", "st", "nd", "rd"][
dayOfMonth % 10 > 3
? 0
: ((dayOfMonth - (dayOfMonth % 10) !== 10 ? 1 : 0) * dayOfMonth) % 10
]
);
}
};
let globalI18n = assign({}, defaultI18n);
const setGlobalDateI18n = (i18n: I18nSettingsOptional): I18nSettings =>
(globalI18n = assign(globalI18n, i18n));
const regexEscape = (str: string): string =>
str.replace(/[|\\{()[^$+*?.-]/g, "\\$&");
const pad = (val: string | number, len = 2): string => {
val = String(val);
while (val.length < len) {
val = "0" + val;
}
return val;
};
const formatFlags: Record<
string,
(dateObj: Date, i18n: I18nSettings) => string
> = {
D: (dateObj: Date): string => String(dateObj.getDate()),
DD: (dateObj: Date): string => pad(dateObj.getDate()),
Do: (dateObj: Date, i18n: I18nSettings): string =>
i18n.DoFn(dateObj.getDate()),
d: (dateObj: Date): string => String(dateObj.getDay()),
dd: (dateObj: Date): string => pad(dateObj.getDay()),
ddd: (dateObj: Date, i18n: I18nSettings): string =>
i18n.dayNamesShort[dateObj.getDay()],
dddd: (dateObj: Date, i18n: I18nSettings): string =>
i18n.dayNames[dateObj.getDay()],
M: (dateObj: Date): string => String(dateObj.getMonth() + 1),
MM: (dateObj: Date): string => pad(dateObj.getMonth() + 1),
MMM: (dateObj: Date, i18n: I18nSettings): string =>
i18n.monthNamesShort[dateObj.getMonth()],
MMMM: (dateObj: Date, i18n: I18nSettings): string =>
i18n.monthNames[dateObj.getMonth()],
YY: (dateObj: Date): string =>
pad(String(dateObj.getFullYear()), 4).substr(2),
YYYY: (dateObj: Date): string => pad(dateObj.getFullYear(), 4),
h: (dateObj: Date): string => String(dateObj.getHours() % 12 || 12),
hh: (dateObj: Date): string => pad(dateObj.getHours() % 12 || 12),
H: (dateObj: Date): string => String(dateObj.getHours()),
HH: (dateObj: Date): string => pad(dateObj.getHours()),
m: (dateObj: Date): string => String(dateObj.getMinutes()),
mm: (dateObj: Date): string => pad(dateObj.getMinutes()),
s: (dateObj: Date): string => String(dateObj.getSeconds()),
ss: (dateObj: Date): string => pad(dateObj.getSeconds()),
S: (dateObj: Date): string =>
String(Math.round(dateObj.getMilliseconds() / 100)),
SS: (dateObj: Date): string =>
pad(Math.round(dateObj.getMilliseconds() / 10), 2),
SSS: (dateObj: Date): string => pad(dateObj.getMilliseconds(), 3),
a: (dateObj: Date, i18n: I18nSettings): string =>
dateObj.getHours() < 12 ? i18n.amPm[0] : i18n.amPm[1],
A: (dateObj: Date, i18n: I18nSettings): string =>
dateObj.getHours() < 12
? i18n.amPm[0].toUpperCase()
: i18n.amPm[1].toUpperCase(),
ZZ(dateObj: Date): string {
const offset = dateObj.getTimezoneOffset();
return (
(offset > 0 ? "-" : "+") +
pad(Math.floor(Math.abs(offset) / 60) * 100 + (Math.abs(offset) % 60), 4)
);
},
Z(dateObj: Date): string {
const offset = dateObj.getTimezoneOffset();
return (
(offset > 0 ? "-" : "+") +
pad(Math.floor(Math.abs(offset) / 60), 2) +
":" +
pad(Math.abs(offset) % 60, 2)
);
}
};
type ParseInfo = [
keyof DateInfo,
string,
((v: string, i18n: I18nSettings) => number | null)?,
string?
];
const monthParse = (v: string): number => +v - 1;
const emptyDigits: ParseInfo = [null, twoDigitsOptional];
const emptyWord: ParseInfo = [null, word];
const amPm: ParseInfo = [
"isPm",
word,
(v: string, i18n: I18nSettings): number | null => {
const val = v.toLowerCase();
if (val === i18n.amPm[0]) {
return 0;
} else if (val === i18n.amPm[1]) {
return 1;
}
return null;
}
];
const timezoneOffset: ParseInfo = [
"timezoneOffset",
"[^\\s]*?[\\+\\-]\\d\\d:?\\d\\d|[^\\s]*?Z?",
(v: string): number | null => {
const parts = (v + "").match(/([+-]|\d\d)/gi);
if (parts) {
const minutes = +parts[1] * 60 + parseInt(parts[2], 10);
return parts[0] === "+" ? minutes : -minutes;
}
return 0;
}
];
const parseFlags: Record<string, ParseInfo> = {
D: ["day", twoDigitsOptional],
DD: ["day", twoDigits],
Do: ["day", twoDigitsOptional + word, (v: string): number => parseInt(v, 10)],
M: ["month", twoDigitsOptional, monthParse],
MM: ["month", twoDigits, monthParse],
YY: [
"year",
twoDigits,
(v: string): number => {
const now = new Date();
const cent = +("" + now.getFullYear()).substr(0, 2);
return +("" + (+v > 68 ? cent - 1 : cent) + v);
}
],
h: ["hour", twoDigitsOptional, undefined, "isPm"],
hh: ["hour", twoDigits, undefined, "isPm"],
H: ["hour", twoDigitsOptional],
HH: ["hour", twoDigits],
m: ["minute", twoDigitsOptional],
mm: ["minute", twoDigits],
s: ["second", twoDigitsOptional],
ss: ["second", twoDigits],
YYYY: ["year", fourDigits],
S: ["millisecond", "\\d", (v: string): number => +v * 100],
SS: ["millisecond", twoDigits, (v: string): number => +v * 10],
SSS: ["millisecond", threeDigits],
d: emptyDigits,
dd: emptyDigits,
ddd: emptyWord,
dddd: emptyWord,
MMM: ["month", word, monthUpdate("monthNamesShort")],
MMMM: ["month", word, monthUpdate("monthNames")],
a: amPm,
A: amPm,
ZZ: timezoneOffset,
Z: timezoneOffset
};
// Some common format strings
const globalMasks: { [key: string]: string } = {
default: "ddd MMM DD YYYY HH:mm:ss",
shortDate: "M/D/YY",
mediumDate: "MMM D, YYYY",
longDate: "MMMM D, YYYY",
fullDate: "dddd, MMMM D, YYYY",
isoDate: "YYYY-MM-DD",
isoDateTime: "YYYY-MM-DDTHH:mm:ssZ",
shortTime: "HH:mm",
mediumTime: "HH:mm:ss",
longTime: "HH:mm:ss.SSS"
};
const setGlobalDateMasks = (masks: {
[key: string]: string;
}): { [key: string]: string } => assign(globalMasks, masks);
/***
* Format a date
* @method format
* @param {Date|number} dateObj
* @param {string} mask Format of the date, i.e. 'mm-dd-yy' or 'shortDate'
* @returns {string} Formatted date string
*/
const format = (
dateObj: Date,
mask: string = globalMasks["default"],
i18n: I18nSettingsOptional = {}
): string => {
if (typeof dateObj === "number") {
dateObj = new Date(dateObj);
}
if (
Object.prototype.toString.call(dateObj) !== "[object Date]" ||
isNaN(dateObj.getTime())
) {
throw new Error("Invalid Date pass to format");
}
mask = globalMasks[mask] || mask;
const literals: string[] = [];
// Make literals inactive by replacing them with @@@
mask = mask.replace(literal, function($0, $1) {
literals.push($1);
return "@@@";
});
const combinedI18nSettings: I18nSettings = assign(
assign({}, globalI18n),
i18n
);
// Apply formatting rules
mask = mask.replace(token, $0 =>
formatFlags[$0](dateObj, combinedI18nSettings)
);
// Inline literal values back into the formatted value
return mask.replace(/@@@/g, () => literals.shift());
};
/**
* Parse a date string into a Javascript Date object /
* @method parse
* @param {string} dateStr Date string
* @param {string} format Date parse format
* @param {i18n} I18nSettingsOptional Full or subset of I18N settings
* @returns {Date|null} Returns Date object. Returns null what date string is invalid or doesn't match format
*/
function parse(
dateStr: string,
format: string,
i18n: I18nSettingsOptional = {}
): Date | null {
if (typeof format !== "string") {
throw new Error("Invalid format in fecha parse");
}
// Check to see if the format is actually a mask
format = globalMasks[format] || format;
// Avoid regular expression denial of service, fail early for really long strings
// https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS
if (dateStr.length > 1000) {
return null;
}
// Default to the beginning of the year.
const today = new Date();
const dateInfo: DateInfo = {
year: today.getFullYear(),
month: 0,
day: 1,
hour: 0,
minute: 0,
second: 0,
millisecond: 0,
isPm: null,
timezoneOffset: null
};
const parseInfo: ParseInfo[] = [];
const literals: string[] = [];
// Replace all the literals with @@@. Hopefully a string that won't exist in the format
let newFormat = format.replace(literal, ($0, $1) => {
literals.push(regexEscape($1));
return "@@@";
});
const specifiedFields: { [field: string]: boolean } = {};
const requiredFields: { [field: string]: boolean } = {};
// Change every token that we find into the correct regex
newFormat = regexEscape(newFormat).replace(token, $0 => {
const info = parseFlags[$0];
const [field, regex, , requiredField] = info;
// Check if the person has specified the same field twice. This will lead to confusing results.
if (specifiedFields[field]) {
throw new Error(`Invalid format. ${field} specified twice in format`);
}
specifiedFields[field] = true;
// Check if there are any required fields. For instance, 12 hour time requires AM/PM specified
if (requiredField) {
requiredFields[requiredField] = true;
}
parseInfo.push(info);
return "(" + regex + ")";
});
// Check all the required fields are present
Object.keys(requiredFields).forEach(field => {
if (!specifiedFields[field]) {
throw new Error(
`Invalid format. ${field} is required in specified format`
);
}
});
// Add back all the literals after
newFormat = newFormat.replace(/@@@/g, () => literals.shift());
// Check if the date string matches the format. If it doesn't return null
const matches = dateStr.match(new RegExp(newFormat, "i"));
if (!matches) {
return null;
}
const combinedI18nSettings: I18nSettings = assign(
assign({}, globalI18n),
i18n
);
// For each match, call the parser function for that date part
for (let i = 1; i < matches.length; i++) {
const [field, , parser] = parseInfo[i - 1];
const value = parser
? parser(matches[i], combinedI18nSettings)
: +matches[i];
// If the parser can't make sense of the value, return null
if (value == null) {
return null;
}
dateInfo[field] = value;
}
if (dateInfo.isPm === 1 && dateInfo.hour != null && +dateInfo.hour !== 12) {
dateInfo.hour = +dateInfo.hour + 12;
} else if (dateInfo.isPm === 0 && +dateInfo.hour === 12) {
dateInfo.hour = 0;
}
const dateWithoutTZ: Date = new Date(
dateInfo.year,
dateInfo.month,
dateInfo.day,
dateInfo.hour,
dateInfo.minute,
dateInfo.second,
dateInfo.millisecond
);
const validateFields: [
"month" | "day" | "hour" | "minute" | "second",
"getMonth" | "getDate" | "getHours" | "getMinutes" | "getSeconds"
][] = [
["month", "getMonth"],
["day", "getDate"],
["hour", "getHours"],
["minute", "getMinutes"],
["second", "getSeconds"]
];
for (let i = 0, len = validateFields.length; i < len; i++) {
// Check to make sure the date field is within the allowed range. Javascript dates allows values
// outside the allowed range. If the values don't match the value was invalid
if (
specifiedFields[validateFields[i][0]] &&
dateInfo[validateFields[i][0]] !== dateWithoutTZ[validateFields[i][1]]()
) {
return null;
}
}
if (dateInfo.timezoneOffset == null) {
return dateWithoutTZ;
}
return new Date(
Date.UTC(
dateInfo.year,
dateInfo.month,
dateInfo.day,
dateInfo.hour,
dateInfo.minute - dateInfo.timezoneOffset,
dateInfo.second,
dateInfo.millisecond
)
);
}
export default {
format,
parse,
defaultI18n,
setGlobalDateI18n,
setGlobalDateMasks
};
export { format, parse, defaultI18n, setGlobalDateI18n, setGlobalDateMasks }; | the_stack |
import { AppState } from "../AppState";
import { Constants as C } from "../Constants";
import { DialogBase } from "../DialogBase";
import * as I from "../Interfaces";
import { PubSub } from "../PubSub";
import { Singletons } from "../Singletons";
import { ValidatedState } from "../ValidatedState";
import { AudioPlayer } from "../widget/AudioPlayer";
import { CompIntf } from "../widget/base/CompIntf";
import { Button } from "../widget/Button";
import { ButtonBar } from "../widget/ButtonBar";
import { Div } from "../widget/Div";
import { Form } from "../widget/Form";
import { Icon } from "../widget/Icon";
import { TextField } from "../widget/TextField";
let S: Singletons;
PubSub.sub(C.PUBSUB_SingletonsReady, (s: Singletons) => {
S = s;
});
/**
* NOTE: currently the AD-skip (Advertisement Skip) feature is a proof-of-concept (and it does functionally work!), but croud sourcing
* the collection of the time-offsets of the begin/end array of commercial segments has not yet been implemented. Also I decided
* creating technology to destroy podcast's ability to collect ad-revenue is counter-productive to the entire podcasting industry
* which is an industry i love, and I won't want to be associated with such a hostile act against podcasters as trying to eliminate
* their ads!! So the ad-skipping technology in here is disabled.
*
* https://www.w3.org/2010/05/video/mediaevents.html
* See also: VideoPlayerDlg (which is very similar)
*/
export class AudioPlayerDlg extends DialogBase {
player: HTMLAudioElement;
audioPlayer: AudioPlayer;
startTimePending: number = null;
/*
If the 'adSegments' array variable below contains an array of start/stop times then during playback this player will seamlessly and autmatically
jump over those time ranges in the audio during playing just like they didn't even exist, basically censoring out those time ranges.
Currently we aren't using this at all, becasue it's not friendly to the podcasting industry!
*/
private adSegments: I.AdSegment[] = null;
private saveTimer: any = null;
urlHash: string;
timeLeftTextField: TextField;
timeLeftState: ValidatedState<any> = new ValidatedState<any>();
intervalTimer: any;
playButton: Icon;
pauseButton: Icon;
constructor(private customTitle, private customSubTitle: string, private customDiv: CompIntf, private sourceUrl: string, private startTimePendingOverride: number, state: AppState) {
super(customTitle || "Audio Player", null, false, state);
this.urlHash = S.util.hashOfString(sourceUrl);
this.startTimePending = localStorage[this.urlHash];
this.intervalTimer = setInterval(() => {
this.oneMinuteTimeslice();
}, 60000);
setTimeout(() => {
this.updatePlayButton();
}, 750);
}
preUnmount(): any {
if (this.intervalTimer) {
clearInterval(this.intervalTimer);
clearInterval(this.saveTimer);
}
}
// This makes the sleep timer work "Stop After (mins.)"
oneMinuteTimeslice = () => {
if (this.timeLeftState.getValue()) {
try {
let timeVal = parseInt(this.timeLeftState.getValue());
timeVal--;
this.timeLeftState.setValue(timeVal <= 0 ? "" : "" + timeVal);
if (timeVal <= 0 && this.player && !this.player.paused && !this.player.ended) {
this.player.pause();
}
}
catch (e) {
}
}
}
renderDlg(): CompIntf[] {
let children = [
new Form(null, [
this.customSubTitle ? new Div(this.customSubTitle, { className: "dialogSubTitle" }) : null,
this.audioPlayer = new AudioPlayer({
src: this.sourceUrl,
className: "audioPlayer",
onPause: () => { this.savePlayerInfo(this.player.src, this.player.currentTime); },
onTimeUpdate: () => { this.onTimeUpdate(); },
onCanPlay: () => { this.restoreStartTime(); },
controls: "controls",
autoPlay: "autoplay",
preload: "auto",
controlsList: "nodownload"
}),
new Div(null, { className: "playerButtonsContainer" }, [
this.playButton = new Icon({
className: "playerButton fa fa-play fa-3x",
style: { display: "none" },
onClick: () => {
if (this.player) this.player.play();
}
}),
this.pauseButton = new Icon({
className: "playerButton fa fa-pause fa-3x",
onClick: () => {
if (this.player) this.player.pause();
}
})
]),
new Div(null, null, [
this.timeLeftTextField = new TextField("Stop After (mins.)", false, null, "timeRemainingEditField", true, this.timeLeftState)
]),
new ButtonBar([
new Button("Close", this.destroyPlayer)
]),
new ButtonBar([
new Button("< 30s", (): void => {
this.skip(-30);
}),
new Button("30s >", (): void => {
this.skip(30);
})
]),
new ButtonBar([
new Button("1x", (): void => {
this.speed(1);
}),
new Button("1.25x", (): void => {
this.speed(1.25);
}),
new Button("1.5x", (): void => {
this.speed(1.5);
}),
new Button("1.75x", (): void => {
this.speed(1.75);
}),
new Button("2x", (): void => {
this.speed(2);
})
]),
new ButtonBar([
new Button("Copy", this.copyToClipboard),
new Button("Post", this.postComment)
]),
this.customDiv
])
];
this.audioPlayer.whenElm((elm: HTMLElement) => {
this.player = elm as HTMLAudioElement;
this.player.onpause = (event) => {
this.updatePlayButton();
};
this.player.onplay = (event) => {
this.updatePlayButton();
};
this.player.onended = (event) => {
this.updatePlayButton();
};
});
return children;
}
updatePlayButton = (): void => {
if (this.player) {
this.playButton.whenElm((elm: HTMLElement) => {
elm.style.display = this.player.paused || this.player.ended ? "inline-block" : "none";
});
this.pauseButton.whenElm((elm: HTMLElement) => {
elm.style.display = !this.player.paused && !this.player.ended ? "inline-block" : "none";
});
}
}
cancel(): void {
this.close();
if (this.player) {
this.player.pause();
this.player.remove();
}
}
speed = (rate: number): void => {
if (this.player) {
this.player.playbackRate = rate;
}
}
skip = (delta: number): void => {
if (this.player) {
this.player.currentTime += delta;
}
}
destroyPlayer = (): void => {
if (this.player) {
this.player.pause();
}
this.cancel();
}
postComment = (): void => {
let link = this.getLink();
S.edit.addNode(null, "\n\n" + link, null, null, this.appState);
}
copyToClipboard = (): void => {
let link = this.getLink();
S.util.copyToClipboard(link);
S.util.flashMessage("Copied link clipboard, with timecode.", "Clipboard", true);
}
getLink = (): string => {
let port = (location.port !== "80" && location.port !== "443") ? (":" + location.port) : "";
let link = location.protocol + "//" + location.hostname + port + "/app?audioUrl=" + this.sourceUrl + "&t=" + Math.trunc(this.player.currentTime);
return link;
}
restoreStartTime = () => {
/* makes player always start wherever the user last was when they clicked "pause" */
if (this.player) {
if (this.startTimePendingOverride > 0) {
this.player.currentTime = this.startTimePendingOverride;
this.startTimePendingOverride = null;
this.startTimePending = null;
}
else if (this.startTimePending) {
this.player.currentTime = this.startTimePending;
this.startTimePending = null;
}
}
}
onTimeUpdate = (): void => {
if (!this.saveTimer) {
/* save time offset into browser local storage every 3 seconds */
this.saveTimer = setInterval(this.saveTime, 3000);
}
this.restoreStartTime();
if (this.adSegments) {
for (let seg of this.adSegments) {
/* endTime of -1 means the rest of the media should be considered ADs */
if (this.player.currentTime >= seg.beginTime && //
(this.player.currentTime <= seg.endTime || seg.endTime < 0)) {
/* jump to end of audio if rest is an add, with logic of -3 to ensure we don't
go into a loop jumping to end over and over again */
if (seg.endTime < 0 && this.player.currentTime < this.player.duration - 3) {
/* jump to last to seconds of audio, i'll do this instead of pausing, in case
there are is more audio automatically about to play, we don't want to halt it all */
this.player.loop = false;
this.player.currentTime = this.player.duration - 2;
}
/* or else we are in a commercial segment so jump to one second past it */
else {
this.player.currentTime = seg.endTime + 1;
}
return;
}
}
}
}
saveTime = (state: AppState): void => {
if (this.player && !this.player.paused) {
/* this safety check to be sure no hidden audio can still be playing should no longer be needed
now that I have the close listener even on the dialog, but i'll leave this here anyway. Can't hurt. */
if (!S.util.isElmVisible(this.player)) {
this.player.pause();
}
this.savePlayerInfo(this.player.src, this.player.currentTime);
}
}
savePlayerInfo = (url: string, timeOffset: number): void => {
let urlHash = S.util.hashOfString(url);
localStorage[urlHash] = timeOffset;
}
} | the_stack |
import useGqlHandler from "./useGqlHandler";
import useHandler from "./../updateSettings/useHandler";
jest.setTimeout(100000);
describe("Settings Test", () => {
const {
createCategory,
createPage,
getSettings,
getDefaultSettings,
updateSettings,
until,
listPublishedPages,
publishPage
} = useGqlHandler();
beforeEach(async () => {
await createCategory({
data: {
slug: `category`,
name: `name`,
url: `/some-url/`,
layout: `layout`
}
});
});
test("get and update settings", async () => {
// 1. Should return default settings.
const [getResponse] = await getSettings();
expect(getResponse).toEqual({
data: {
pageBuilder: {
getSettings: {
data: null,
error: null,
id: "T#root#L#en-US#PB#SETTINGS"
}
}
}
});
// 2. Updating existing settings should immediately return the updated ones.
const [updateResponse] = await updateSettings({
data: {
name: "test 1",
websiteUrl: "https://www.test.com/",
websitePreviewUrl: "https://preview.test.com/",
prerendering: {
app: {
url: "https://www.app.com/"
},
storage: { name: "storage-name" }
},
social: {
facebook: "https://www.facebook.com/",
instagram: "https://www.instagram.com/",
twitter: "https://www.twitter.com/",
image: {
id: "1kucKwtX3vI2w6tYuPwJsvRFn9g",
src: "https://d1peg08dnrinui.cloudfront.net/files/9ki1goobp-webiny_security__1_.png"
}
}
}
});
expect(updateResponse).toMatchObject({
data: {
pageBuilder: {
updateSettings: {
data: {
name: "test 1",
websiteUrl: "https://www.test.com",
websitePreviewUrl: "https://preview.test.com",
prerendering: {
app: {
url: "https://www.app.com"
},
storage: { name: "storage-name" }
},
social: {
instagram: "https://www.instagram.com/",
facebook: "https://www.facebook.com/",
twitter: "https://www.twitter.com/",
image: {
id: "1kucKwtX3vI2w6tYuPwJsvRFn9g",
src: "https://d1peg08dnrinui.cloudfront.net/files/9ki1goobp-webiny_security__1_.png"
}
}
},
error: null,
id: "T#root#L#en-US#PB#SETTINGS"
}
}
}
});
// 3. Finally, getting the settings again should return the updated ones.
const [response] = await getSettings();
expect(response).toMatchObject({
data: {
pageBuilder: {
getSettings: {
data: {
name: "test 1",
websiteUrl: "https://www.test.com",
websitePreviewUrl: "https://preview.test.com",
prerendering: {
app: {
url: "https://www.app.com"
},
storage: { name: "storage-name" }
},
social: {
instagram: "https://www.instagram.com/",
facebook: "https://www.facebook.com/",
twitter: "https://www.twitter.com/",
image: {
id: "1kucKwtX3vI2w6tYuPwJsvRFn9g",
src: "https://d1peg08dnrinui.cloudfront.net/files/9ki1goobp-webiny_security__1_.png"
}
}
},
error: null,
id: "T#root#L#en-US#PB#SETTINGS"
}
}
}
});
});
test("ensure we don't overload settings when listing pages", async () => {
// Let's create five pages and publish them.
for (let i = 0; i < 5; i++) {
const [createPageResponse] = await createPage({ category: "category" });
await publishPage({ id: createPageResponse.data.pageBuilder.createPage.data.id });
}
// Wait until all are created.
await until(
listPublishedPages,
([res]: any) => res.data.pageBuilder.listPublishedPages.data.length === 5
);
await listPublishedPages();
});
test("must return default settings", async () => {
await getSettings().then(([res]) =>
expect(res).toEqual({
data: {
pageBuilder: {
getSettings: {
id: "T#root#L#en-US#PB#SETTINGS",
data: null,
error: null
}
}
}
})
);
await getDefaultSettings().then(([res]) =>
expect(res).toEqual({
data: {
pageBuilder: {
getDefaultSettings: {
id: "PB#SETTINGS",
data: null,
error: null
}
}
}
})
);
const { handler } = useHandler();
await handler({
data: {
name: "test 1",
websiteUrl: "https://www.test.com/",
websitePreviewUrl: "https://preview.test.com/",
prerendering: {
app: {
url: "https://www.app.com/"
},
storage: { name: "storage-name" }
},
social: {
facebook: "https://www.facebook.com/",
instagram: "https://www.instagram.com/",
twitter: "https://www.twitter.com/",
image: {
id: "1kucKwtX3vI2w6tYuPwJsvRFn9g",
src: "https://d1peg08dnrinui.cloudfront.net/files/9ki1goobp-webiny_security__1_.png"
}
}
}
});
await getDefaultSettings().then(([res]) =>
expect(res).toEqual({
data: {
pageBuilder: {
getDefaultSettings: {
data: {
name: "test 1",
pages: {
home: null,
notFound: null
},
prerendering: {
app: {
url: "https://www.app.com"
},
storage: {
name: "storage-name"
}
},
social: {
facebook: "https://www.facebook.com/",
image: {
id: "1kucKwtX3vI2w6tYuPwJsvRFn9g",
src: "https://d1peg08dnrinui.cloudfront.net/files/9ki1goobp-webiny_security__1_.png"
},
instagram: "https://www.instagram.com/",
twitter: "https://www.twitter.com/"
},
websitePreviewUrl: "https://preview.test.com",
websiteUrl: "https://www.test.com"
},
error: null,
id: "PB#SETTINGS"
}
}
}
})
);
// Updating settings for tenant / locale should not affect default settings. Default settings can only
// be affected by changing default system and default tenant data.
await updateSettings({
data: {
name: "test 1-UPDATED",
websiteUrl: "https://www.test.com/-UPDATED",
websitePreviewUrl: "https://preview.test.com/-UPDATED",
prerendering: {
app: {
url: "https://www.app.com/-UPDATED"
},
storage: { name: "storage-name-UPDATED" }
},
social: {
facebook: "https://www.facebook.com/-UPDATED",
instagram: "https://www.instagram.com/-UPDATED",
twitter: "https://www.twitter.com/-UPDATED",
image: {
id: "1kucKwtX3vI2w6tYuPwJsvRFn9g-UPDATED",
src: "https://d1peg08dnrinui.cloudfront.net/files/9ki1goobp-webiny_security__1_.png-UPDATED"
}
}
}
});
await getDefaultSettings().then(([res]) =>
expect(res).toEqual({
data: {
pageBuilder: {
getDefaultSettings: {
data: {
name: "test 1",
pages: {
home: null,
notFound: null
},
prerendering: {
app: {
url: "https://www.app.com"
},
storage: {
name: "storage-name"
}
},
social: {
facebook: "https://www.facebook.com/",
image: {
id: "1kucKwtX3vI2w6tYuPwJsvRFn9g",
src: "https://d1peg08dnrinui.cloudfront.net/files/9ki1goobp-webiny_security__1_.png"
},
instagram: "https://www.instagram.com/",
twitter: "https://www.twitter.com/"
},
websitePreviewUrl: "https://preview.test.com",
websiteUrl: "https://www.test.com"
},
error: null,
id: "PB#SETTINGS"
}
}
}
})
);
});
test("settings special pages (notFound, home)", async () => {
const page = await createPage({ category: "category" }).then(
([res]) => res.data.pageBuilder.createPage.data
);
await updateSettings({
data: {
pages: {
home: page.id
}
}
}).then(([res]) =>
expect(res).toEqual({
data: {
pageBuilder: {
updateSettings: {
id: "T#root#L#en-US#PB#SETTINGS",
data: null,
error: {
code: "NOT_FOUND",
data: null,
message: "Page not found."
}
}
}
}
})
);
await publishPage({ id: page.id });
const [pid] = page.id.split("#");
await updateSettings({
data: {
pages: {
home: page.id
}
}
}).then(([res]) =>
expect(res).toMatchObject({
data: {
pageBuilder: {
updateSettings: {
id: "T#root#L#en-US#PB#SETTINGS",
data: {
pages: {
home: pid
}
},
error: null
}
}
}
})
);
await getSettings().then(([res]) =>
expect(res).toMatchObject({
data: {
pageBuilder: {
getSettings: {
id: "T#root#L#en-US#PB#SETTINGS",
data: {
pages: {
home: pid
}
},
error: null
}
}
}
})
);
});
test("must not be able to unset pages as special", async () => {
const page = await createPage({ category: "category" }).then(
([res]) => res.data.pageBuilder.createPage.data
);
const [pid] = page.id.split("#");
await publishPage({ id: page.id }).then(() =>
updateSettings({
data: {
pages: {
home: page.id,
notFound: page.id
}
}
})
);
await getSettings().then(([res]) =>
expect(res).toMatchObject({
data: {
pageBuilder: {
getSettings: {
id: "T#root#L#en-US#PB#SETTINGS",
data: {
pages: {
home: pid,
notFound: pid
}
}
}
}
}
})
);
await updateSettings({
data: {
pages: {
home: null,
notFound: null
}
}
}).then(([res]) =>
expect(res).toEqual({
data: {
pageBuilder: {
updateSettings: {
id: "T#root#L#en-US#PB#SETTINGS",
data: null,
error: {
code: "CANNOT_UNSET_SPECIAL_PAGE",
data: null,
message:
'Cannot unset "home" page. Please provide a new page if you want to unset current one.'
}
}
}
}
})
);
await getSettings().then(([res]) =>
expect(res).toMatchObject({
data: {
pageBuilder: {
getSettings: {
id: "T#root#L#en-US#PB#SETTINGS",
data: {
pages: {
home: pid,
notFound: pid
}
}
}
}
}
})
);
});
}); | the_stack |
import * as cloudwatch from '@aws-cdk/aws-cloudwatch';
import * as notifications from '@aws-cdk/aws-codestarnotifications';
import * as iam from '@aws-cdk/aws-iam';
import * as logs from '@aws-cdk/aws-logs';
import * as sns from '@aws-cdk/aws-sns';
import * as cdk from '@aws-cdk/core';
import { Construct } from 'constructs';
import { CfnSlackChannelConfiguration } from './chatbot.generated';
/**
* Properties for a new Slack channel configuration
*/
export interface SlackChannelConfigurationProps {
/**
* The name of Slack channel configuration
*/
readonly slackChannelConfigurationName: string;
/**
* The permission role of Slack channel configuration
*
* @default - A role will be created.
*/
readonly role?: iam.IRole;
/**
* The ID of the Slack workspace authorized with AWS Chatbot.
*
* To get the workspace ID, you must perform the initial authorization flow with Slack in the AWS Chatbot console.
* Then you can copy and paste the workspace ID from the console.
* For more details, see steps 1-4 in Setting Up AWS Chatbot with Slack in the AWS Chatbot User Guide.
* @see https://docs.aws.amazon.com/chatbot/latest/adminguide/setting-up.html#Setup_intro
*/
readonly slackWorkspaceId: string;
/**
* The ID of the Slack channel.
*
* To get the ID, open Slack, right click on the channel name in the left pane, then choose Copy Link.
* The channel ID is the 9-character string at the end of the URL. For example, ABCBBLZZZ.
*/
readonly slackChannelId: string;
/**
* The SNS topics that deliver notifications to AWS Chatbot.
*
* @default None
*/
readonly notificationTopics?: sns.ITopic[];
/**
* Specifies the logging level for this configuration.
* This property affects the log entries pushed to Amazon CloudWatch Logs.
*
* @default LoggingLevel.NONE
*/
readonly loggingLevel?: LoggingLevel;
/**
* The number of days log events are kept in CloudWatch Logs. When updating
* this property, unsetting it doesn't remove the log retention policy. To
* remove the retention policy, set the value to `INFINITE`.
*
* @default logs.RetentionDays.INFINITE
*/
readonly logRetention?: logs.RetentionDays;
/**
* The IAM role for the Lambda function associated with the custom resource
* that sets the retention policy.
*
* @default - A new role is created.
*/
readonly logRetentionRole?: iam.IRole;
/**
* When log retention is specified, a custom resource attempts to create the CloudWatch log group.
* These options control the retry policy when interacting with CloudWatch APIs.
*
* @default - Default AWS SDK retry options.
*/
readonly logRetentionRetryOptions?: logs.LogRetentionRetryOptions;
}
/**
* Logging levels include ERROR, INFO, or NONE.
*/
export enum LoggingLevel {
/**
* ERROR
*/
ERROR = 'ERROR',
/**
* INFO
*/
INFO = 'INFO',
/**
* NONE
*/
NONE = 'NONE',
}
/**
* Represents a Slack channel configuration
*/
export interface ISlackChannelConfiguration extends cdk.IResource, iam.IGrantable, notifications.INotificationRuleTarget {
/**
* The ARN of the Slack channel configuration
* In the form of arn:aws:chatbot:{region}:{account}:chat-configuration/slack-channel/{slackChannelName}
* @attribute
*/
readonly slackChannelConfigurationArn: string;
/**
* The name of Slack channel configuration
* @attribute
*/
readonly slackChannelConfigurationName: string;
/**
* The permission role of Slack channel configuration
* @attribute
*
* @default - A role will be created.
*/
readonly role?: iam.IRole;
/**
* Adds a statement to the IAM role.
*/
addToRolePolicy(statement: iam.PolicyStatement): void;
/**
* Return the given named metric for this SlackChannelConfiguration
*/
metric(metricName: string, props?: cloudwatch.MetricOptions): cloudwatch.Metric;
}
/**
* Either a new or imported Slack channel configuration
*/
abstract class SlackChannelConfigurationBase extends cdk.Resource implements ISlackChannelConfiguration {
abstract readonly slackChannelConfigurationArn: string;
abstract readonly slackChannelConfigurationName: string;
abstract readonly grantPrincipal: iam.IPrincipal;
abstract readonly role?: iam.IRole;
/**
* Adds extra permission to iam-role of Slack channel configuration
* @param statement
*/
public addToRolePolicy(statement: iam.PolicyStatement): void {
if (!this.role) {
return;
}
this.role.addToPrincipalPolicy(statement);
}
/**
* Return the given named metric for this SlackChannelConfiguration
*/
public metric(metricName: string, props?: cloudwatch.MetricOptions): cloudwatch.Metric {
// AWS Chatbot publishes metrics to us-east-1 regardless of stack region
// https://docs.aws.amazon.com/chatbot/latest/adminguide/monitoring-cloudwatch.html
return new cloudwatch.Metric({
namespace: 'AWS/Chatbot',
region: 'us-east-1',
dimensionsMap: {
ConfigurationName: this.slackChannelConfigurationName,
},
metricName,
...props,
});
}
public bindAsNotificationRuleTarget(_scope: Construct): notifications.NotificationRuleTargetConfig {
return {
targetType: 'AWSChatbotSlack',
targetAddress: this.slackChannelConfigurationArn,
};
}
}
/**
* A new Slack channel configuration
*/
export class SlackChannelConfiguration extends SlackChannelConfigurationBase {
/**
* Import an existing Slack channel configuration provided an ARN
* @param scope The parent creating construct
* @param id The construct's name
* @param slackChannelConfigurationArn configuration ARN (i.e. arn:aws:chatbot::1234567890:chat-configuration/slack-channel/my-slack)
*
* @returns a reference to the existing Slack channel configuration
*/
public static fromSlackChannelConfigurationArn(scope: Construct, id: string, slackChannelConfigurationArn: string): ISlackChannelConfiguration {
const re = /^slack-channel\//;
const resourceName = cdk.Arn.extractResourceName(slackChannelConfigurationArn, 'chat-configuration');
if (!cdk.Token.isUnresolved(slackChannelConfigurationArn) && !re.test(resourceName)) {
throw new Error('The ARN of a Slack integration must be in the form: arn:aws:chatbot:{region}:{account}:chat-configuration/slack-channel/{slackChannelName}');
}
class Import extends SlackChannelConfigurationBase {
/**
* @attribute
*/
readonly slackChannelConfigurationArn = slackChannelConfigurationArn;
readonly role?: iam.IRole = undefined;
readonly grantPrincipal: iam.IPrincipal;
/**
* Returns a name of Slack channel configuration
*
* NOTE:
* For example: arn:aws:chatbot::1234567890:chat-configuration/slack-channel/my-slack
* The ArnComponents API will return `slack-channel/my-slack`
* It need to handle that to gets a correct name.`my-slack`
*/
readonly slackChannelConfigurationName: string;
constructor(s: Construct, i: string) {
super(s, i);
this.grantPrincipal = new iam.UnknownPrincipal({ resource: this });
// handle slackChannelConfigurationName as specified above
if (cdk.Token.isUnresolved(slackChannelConfigurationArn)) {
this.slackChannelConfigurationName = cdk.Fn.select(1, cdk.Fn.split('slack-channel/', resourceName));
} else {
this.slackChannelConfigurationName = resourceName.substring('slack-channel/'.length);
}
}
}
return new Import(scope, id);
}
/**
* Return the given named metric for All SlackChannelConfigurations
*/
public static metricAll(metricName: string, props?: cloudwatch.MetricOptions): cloudwatch.Metric {
// AWS Chatbot publishes metrics to us-east-1 regardless of stack region
// https://docs.aws.amazon.com/chatbot/latest/adminguide/monitoring-cloudwatch.html
return new cloudwatch.Metric({
namespace: 'AWS/Chatbot',
region: 'us-east-1',
metricName,
...props,
});
}
readonly slackChannelConfigurationArn: string;
readonly slackChannelConfigurationName: string;
readonly role?: iam.IRole;
readonly grantPrincipal: iam.IPrincipal;
/**
* The SNS topic that deliver notifications to AWS Chatbot.
* @attribute
*/
private readonly notificationTopics: sns.ITopic[];
constructor(scope: Construct, id: string, props: SlackChannelConfigurationProps) {
super(scope, id, {
physicalName: props.slackChannelConfigurationName,
});
this.role = props.role || new iam.Role(this, 'ConfigurationRole', {
assumedBy: new iam.ServicePrincipal('chatbot.amazonaws.com'),
});
this.grantPrincipal = this.role;
this.notificationTopics = props.notificationTopics ?? [];
const configuration = new CfnSlackChannelConfiguration(this, 'Resource', {
configurationName: props.slackChannelConfigurationName,
iamRoleArn: this.role.roleArn,
slackWorkspaceId: props.slackWorkspaceId,
slackChannelId: props.slackChannelId,
snsTopicArns: cdk.Lazy.list({ produce: () => this.notificationTopics.map(topic => topic.topicArn) }, { omitEmpty: true } ),
loggingLevel: props.loggingLevel?.toString(),
});
// Log retention
// AWS Chatbot publishes logs to us-east-1 regardless of stack region https://docs.aws.amazon.com/chatbot/latest/adminguide/cloudwatch-logs.html
if (props.logRetention) {
new logs.LogRetention(this, 'LogRetention', {
logGroupName: `/aws/chatbot/${props.slackChannelConfigurationName}`,
retention: props.logRetention,
role: props.logRetentionRole,
logGroupRegion: 'us-east-1',
logRetentionRetryOptions: props.logRetentionRetryOptions,
});
}
this.slackChannelConfigurationArn = configuration.ref;
this.slackChannelConfigurationName = props.slackChannelConfigurationName;
}
/**
* Adds a SNS topic that deliver notifications to AWS Chatbot.
* @param notificationTopic
*/
public addNotificationTopic(notificationTopic: sns.ITopic): void {
this.notificationTopics.push(notificationTopic);
}
} | the_stack |
import _ from 'lodash'
import {
ObjectType, ElemID, InstanceElement, Element, isEqualElements, isObjectType, ReferenceExpression,
} from '@salto-io/adapter-api'
import { client as clientUtils, filterUtils } from '@salto-io/adapter-components'
import { DetailedDependency } from '@salto-io/adapter-utils'
import ZuoraClient from '../../src/client/client'
import { paginate } from '../../src/client/pagination'
import { ZUORA_BILLING, CUSTOM_OBJECT_DEFINITION_TYPE, STANDARD_OBJECT_DEFINITION_TYPE } from '../../src/constants'
import filterCreator from '../../src/filters/object_defs'
describe('Object defs filter', () => {
let client: ZuoraClient
type FilterType = filterUtils.FilterWith<'onFetch'>
let filter: FilterType
const generateElements = (): Element[] => {
const customObjectDefType = new ObjectType({
elemID: new ElemID(ZUORA_BILLING, CUSTOM_OBJECT_DEFINITION_TYPE),
path: [ZUORA_BILLING, 'Types', 'CustomObjectDefinitions'],
})
const standardObjectDefType = new ObjectType({
elemID: new ElemID(ZUORA_BILLING, STANDARD_OBJECT_DEFINITION_TYPE),
})
const account = new InstanceElement(
'account',
standardObjectDefType,
{
additionalProperties: {
type: 'account',
},
schema: {
$schema: 'http://json-schema.org/draft-04/schema#',
title: 'Account',
type: 'object',
required: [
'Id',
'CreatedById',
'AccountNumber',
'Name',
],
properties: {
Id: {
type: 'string',
format: 'uuid',
},
CreatedById: {
type: 'string',
format: 'uuid',
},
additionalProperties: {
AccountNumber: {
type: 'string',
additionalProperties: {
maxLength: 512,
},
},
Name: {
type: 'string',
additionalProperties: {
maxLength: 512,
},
},
},
},
relationships: [
{
cardinality: 'oneToMany',
namespace: 'default',
object: 'Custom1',
fields: {
additionalProperties: {
Id: 'AccountId__c',
},
},
recordConstraints: {
create: {
enforceValidMapping: false,
},
},
},
],
},
},
)
const accountingcode = new InstanceElement(
'AccountingCode',
standardObjectDefType,
{
additionalProperties: {
type: 'AccountingCode',
},
schema: {
$schema: 'http://json-schema.org/draft-04/schema#',
title: 'AccountingCode',
type: 'object',
required: [
'Name',
'Id',
],
properties: {
additionalProperties: {
deleted: {
type: 'boolean',
},
Category: {
type: 'string',
maxLength: 512,
},
},
Id: {
type: 'string',
format: 'uuid',
},
},
},
},
)
const Custom1 = new InstanceElement(
'Custom1',
customObjectDefType,
{
additionalProperties: {
Id: 'some id',
type: 'Custom1',
},
CreatedById: 'id1',
UpdatedById: 'id1',
CreatedDate: '2021-01-01T01:23:45.678Z',
UpdatedDate: '2021-01-01T01:23:45.678Z',
schema: {
object: 'Custom1',
label: 'Custom1',
properties: {
additionalProperties: {
field1__c: {
format: 'uuid',
label: 'field1 label',
origin: 'custom',
type: 'string',
additionalProperties: {
description: 'some description',
},
},
field2__c: {
label: 'field2 label',
type: 'number',
},
SubscriptionId__c: {
format: 'uuid',
label: 'Subscription',
origin: 'custom',
type: 'string',
additionalProperties: {
description: 'The subscription that is associated with the record.',
},
},
AccountId__c: {
format: 'uuid',
label: 'Account',
origin: 'custom',
type: 'string',
additionalProperties: {
description: 'The account that is associated with the record.',
},
},
Custom2Id__c: {
format: 'uuid',
label: 'Custom2',
origin: 'custom',
type: 'string',
},
},
Id: {
format: 'uuid',
label: 'Id',
origin: 'system',
type: 'string',
},
},
required: [
'field2__c',
'Id',
'AccountId__c',
],
description: 'this is a decription',
filterable: [
'field2__c',
'Id',
],
relationships: [
{
cardinality: 'manyToOne',
namespace: 'com_zuora',
object: 'subscription',
fields: {
additionalProperties: {
SubscriptionId__c: 'Id',
},
},
recordConstraints: {
create: {
enforceValidMapping: false,
},
},
},
{
cardinality: 'manyToOne',
namespace: 'com_zuora',
object: 'account',
fields: {
additionalProperties: {
AccountId__c: 'Id',
},
},
recordConstraints: {
create: {
enforceValidMapping: false,
},
},
},
{
cardinality: 'oneToMany',
namespace: 'com_zuora',
object: 'account',
fields: {
additionalProperties: {
Id: 'Id',
},
},
},
{
cardinality: 'manyToOne',
namespace: 'default',
object: 'Custom2',
fields: {
additionalProperties: {
Custom2Id__c: 'Id',
},
},
recordConstraints: {
create: {
enforceValidMapping: false,
},
},
},
],
},
},
)
const Custom2 = new InstanceElement(
'Custom2',
customObjectDefType,
{
additionalProperties: {
Id: 'some other id',
type: 'Custom2',
},
CreatedById: 'id1',
UpdatedById: 'id1',
CreatedDate: '2021-01-01T01:23:45.678Z',
UpdatedDate: '2021-01-01T01:23:45.678Z',
schema: {
object: 'Custom2',
label: 'Custom2',
properties: {
Id: {
format: 'uuid',
label: 'Id',
origin: 'system',
type: 'string',
},
},
required: [],
description: 'this is a decription',
filterable: [],
// not supposed to happen
relationships: {},
},
},
)
return [customObjectDefType, standardObjectDefType, account, accountingcode, Custom1, Custom2]
}
beforeAll(() => {
client = new ZuoraClient({
credentials: { baseURL: 'http://localhost', clientId: 'id', clientSecret: 'secret' },
})
filter = filterCreator({
client,
paginator: clientUtils.createPaginator({
client,
paginationFuncCreator: paginate,
}),
config: {
fetch: {
includeTypes: [],
},
apiDefinitions: {
swagger: { url: 'ignore' },
typeDefaults: {
transformation: {
idFields: ['name'],
},
},
types: {},
},
},
}) as FilterType
})
describe('nothing to do', () => {
it('keep elements as-is when custom object def is missing', async () => {
const origElements = generateElements()
const elements = generateElements().slice(1)
await filter.onFetch(elements)
expect(elements.length).toEqual(origElements.length - 1)
expect(elements.every((e, i) => isEqualElements(e, origElements[i + 1]))).toBeTruthy()
})
})
describe('convert instances to object types and fields', () => {
let origElements: Element[]
let elements: Element[]
beforeAll(async () => {
origElements = generateElements()
elements = generateElements()
await filter.onFetch(elements)
})
it('replace each instance with an object', () => {
expect(elements.length).toEqual(origElements.length)
expect(elements.every(isObjectType)).toBeTruthy()
expect(elements.map(e => e.elemID.getFullName()).sort()).toEqual([
'zuora_billing.AccountingCode',
'zuora_billing.Custom1__c',
'zuora_billing.Custom2__c',
'zuora_billing.CustomObjectDefinition',
'zuora_billing.StandardObjectDefinition',
'zuora_billing.account',
])
})
it('should create standard objects and fields correctly', () => {
const account = elements.find(e => e.elemID.typeName === 'account') as ObjectType
const accountingcode = elements.find(e => e.elemID.typeName === 'AccountingCode') as ObjectType
expect(account).toBeInstanceOf(ObjectType)
expect(accountingcode).toBeInstanceOf(ObjectType)
expect(_.mapValues(account.fields, f => f.refType.elemID.getFullName())).toEqual({
AccountNumber: 'string',
CreatedById: 'string',
Id: 'string',
Name: 'string',
})
expect(_.mapValues(accountingcode.fields, f => f.refType.elemID.getFullName())).toEqual({
deleted: 'boolean',
Category: 'string',
Id: 'string',
})
expect(account.fields.Id.annotations).toEqual({
filterable: false,
format: 'uuid',
required: true,
type: 'string',
})
expect(account.annotations).toEqual({
metadataType: 'StandardObject',
})
})
it('should create custom objects and fields correctly, with the __c suffix', () => {
const custom1 = elements.find(e => e.elemID.typeName === 'Custom1__c') as ObjectType
expect(custom1).toBeInstanceOf(ObjectType)
expect(_.mapValues(custom1.fields, f => f.refType.elemID.getFullName())).toEqual({
field1__c: 'string',
field2__c: 'number',
SubscriptionId__c: 'string',
AccountId__c: 'string',
Custom2Id__c: 'string',
Id: 'string',
})
expect(custom1.fields.Id.annotations).toEqual({
filterable: true,
format: 'uuid',
label: 'Id',
origin: 'system',
required: true,
type: 'string',
})
expect(custom1.fields.SubscriptionId__c.annotations).toEqual({
format: 'uuid',
label: 'Subscription',
description: 'The subscription that is associated with the record.',
origin: 'custom',
type: 'string',
filterable: false,
required: false,
cardinality: 'manyToOne',
recordConstraints: { create: { enforceValidMapping: false } },
// not a reference because subscription was not found
referenceTo: ['subscription.Id'],
})
expect(custom1.fields.Custom2Id__c.annotations).toEqual({
format: 'uuid',
label: 'Custom2',
origin: 'custom',
type: 'string',
filterable: false,
required: false,
cardinality: 'manyToOne',
recordConstraints: { create: { enforceValidMapping: false } },
referenceTo: [expect.any(ReferenceExpression)],
})
const fieldRef = custom1.fields.Custom2Id__c.annotations.referenceTo[0] as ReferenceExpression
expect(fieldRef.elemID.getFullName()).toEqual('zuora_billing.Custom2__c.field.Id')
const custom2 = elements.find(e => e.elemID.typeName === 'Custom2__c') as ObjectType
expect(custom2).toBeInstanceOf(ObjectType)
expect(_.mapValues(custom2.fields, f => f.refType.elemID.getFullName())).toEqual({ Id: 'string' })
expect(custom1.fields.Id.annotations).toEqual({
filterable: true,
format: 'uuid',
label: 'Id',
origin: 'system',
required: true,
type: 'string',
})
})
it('should create the right references, ignoring lower/uppercase in type names', () => {
const custom1 = elements.find(e => e.elemID.typeName === 'Custom1__c') as ObjectType
expect(custom1).toBeInstanceOf(ObjectType)
expect(custom1.fields.AccountId__c.annotations).toEqual({
format: 'uuid',
label: 'Account',
description: 'The account that is associated with the record.',
origin: 'custom',
type: 'string',
filterable: false,
required: true,
cardinality: 'manyToOne',
recordConstraints: { create: { enforceValidMapping: false } },
// not a reference because subscription was not found
referenceTo: [expect.any(ReferenceExpression)],
})
const fieldRef = custom1.fields.AccountId__c.annotations.referenceTo[0] as ReferenceExpression
expect(fieldRef.elemID.getFullName()).toEqual('zuora_billing.account.field.Id')
expect(custom1.annotations).toEqual({
// eslint-disable-next-line camelcase
_generated_dependencies: [expect.anything(), expect.anything()],
description: 'this is a decription',
id: 'some id',
label: 'Custom1',
metadataType: 'CustomObject',
})
// eslint-disable-next-line no-underscore-dangle
const objRefs = custom1.annotations._generated_dependencies as DetailedDependency[]
expect(objRefs[0].reference.elemID.getFullName()).toEqual('zuora_billing.Custom2__c')
expect(objRefs[1].reference.elemID.getFullName()).toEqual('zuora_billing.account')
})
})
}) | the_stack |
import axios, { AxiosResponse } from "axios";
import {
AssertionPublicKeyCredentialResult,
AssertionResult,
AttestationPublicKeyCredential,
AttestationPublicKeyCredentialJSON,
AttestationPublicKeyCredentialResult,
AttestationResult,
AuthenticatorAttestationResponseFuture,
CredentialCreation,
CredentialRequest,
PublicKeyCredentialCreationOptionsJSON,
PublicKeyCredentialCreationOptionsStatus,
PublicKeyCredentialDescriptorJSON,
PublicKeyCredentialJSON,
PublicKeyCredentialRequestOptionsJSON,
PublicKeyCredentialRequestOptionsStatus,
} from "@models/Webauthn";
import {
OptionalDataServiceResponse,
ServiceResponse,
WebauthnAssertionPath,
WebauthnAttestationPath,
WebauthnIdentityFinishPath,
} from "@services/Api";
import { SignInResponse } from "@services/SignIn";
import { getBase64WebEncodingFromBytes, getBytesFromBase64 } from "@utils/Base64";
export function isWebauthnSecure(): boolean {
if (window.isSecureContext) {
return true;
}
return window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1";
}
export function isWebauthnSupported(): boolean {
return window?.PublicKeyCredential !== undefined && typeof window.PublicKeyCredential === "function";
}
export async function isWebauthnPlatformAuthenticatorAvailable(): Promise<boolean> {
if (!isWebauthnSupported()) {
return false;
}
return window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();
}
function arrayBufferEncode(value: ArrayBuffer): string {
return getBase64WebEncodingFromBytes(new Uint8Array(value));
}
function arrayBufferDecode(value: string): ArrayBuffer {
return getBytesFromBase64(value);
}
function decodePublicKeyCredentialDescriptor(
descriptor: PublicKeyCredentialDescriptorJSON,
): PublicKeyCredentialDescriptor {
return {
id: arrayBufferDecode(descriptor.id),
type: descriptor.type,
transports: descriptor.transports,
};
}
function decodePublicKeyCredentialCreationOptions(
options: PublicKeyCredentialCreationOptionsJSON,
): PublicKeyCredentialCreationOptions {
return {
attestation: options.attestation,
authenticatorSelection: options.authenticatorSelection,
challenge: arrayBufferDecode(options.challenge),
excludeCredentials: options.excludeCredentials?.map(decodePublicKeyCredentialDescriptor),
extensions: options.extensions,
pubKeyCredParams: options.pubKeyCredParams,
rp: options.rp,
timeout: options.timeout,
user: {
displayName: options.user.displayName,
id: arrayBufferDecode(options.user.id),
name: options.user.name,
},
};
}
function decodePublicKeyCredentialRequestOptions(
options: PublicKeyCredentialRequestOptionsJSON,
): PublicKeyCredentialRequestOptions {
let allowCredentials: PublicKeyCredentialDescriptor[] | undefined = undefined;
if (options.allowCredentials?.length !== 0) {
allowCredentials = options.allowCredentials?.map(decodePublicKeyCredentialDescriptor);
}
return {
allowCredentials: allowCredentials,
challenge: arrayBufferDecode(options.challenge),
extensions: options.extensions,
rpId: options.rpId,
timeout: options.timeout,
userVerification: options.userVerification,
};
}
function encodeAttestationPublicKeyCredential(
credential: AttestationPublicKeyCredential,
): AttestationPublicKeyCredentialJSON {
const response = credential.response as AuthenticatorAttestationResponseFuture;
let transports: AuthenticatorTransport[] | undefined;
if (response?.getTransports !== undefined && typeof response.getTransports === "function") {
transports = response.getTransports();
}
return {
id: credential.id,
type: credential.type,
rawId: arrayBufferEncode(credential.rawId),
clientExtensionResults: credential.getClientExtensionResults(),
response: {
attestationObject: arrayBufferEncode(response.attestationObject),
clientDataJSON: arrayBufferEncode(response.clientDataJSON),
},
transports: transports,
};
}
function encodeAssertionPublicKeyCredential(
credential: PublicKeyCredential,
targetURL: string | undefined,
): PublicKeyCredentialJSON {
const response = credential.response as AuthenticatorAssertionResponse;
let userHandle: string;
if (response.userHandle == null) {
userHandle = "";
} else {
userHandle = arrayBufferEncode(response.userHandle);
}
return {
id: credential.id,
type: credential.type,
rawId: arrayBufferEncode(credential.rawId),
clientExtensionResults: credential.getClientExtensionResults(),
response: {
authenticatorData: arrayBufferEncode(response.authenticatorData),
clientDataJSON: arrayBufferEncode(response.clientDataJSON),
signature: arrayBufferEncode(response.signature),
userHandle: userHandle,
},
targetURL: targetURL,
};
}
function getAttestationResultFromDOMException(exception: DOMException): AttestationResult {
// Docs for this section:
// https://w3c.github.io/webauthn/#sctn-op-make-cred
switch (exception.name) {
case "UnknownError":
// § 6.3.2 Step 1 and Step 8.
return AttestationResult.FailureSyntax;
case "NotSupportedError":
// § 6.3.2 Step 2.
return AttestationResult.FailureSupport;
case "InvalidStateError":
// § 6.3.2 Step 3.
return AttestationResult.FailureExcluded;
case "NotAllowedError":
// § 6.3.2 Step 3 and Step 6.
return AttestationResult.FailureUserConsent;
case "ConstraintError":
// § 6.3.2 Step 4.
return AttestationResult.FailureUserVerificationOrResidentKey;
default:
console.error(`Unhandled DOMException occurred during WebAuthN attestation: ${exception}`);
return AttestationResult.FailureUnknown;
}
}
function getAssertionResultFromDOMException(
exception: DOMException,
requestOptions: PublicKeyCredentialRequestOptions,
): AssertionResult {
// Docs for this section:
// https://w3c.github.io/webauthn/#sctn-op-get-assertion
switch (exception.name) {
case "UnknownError":
// § 6.3.3 Step 1 and Step 12.
return AssertionResult.FailureSyntax;
case "NotAllowedError":
// § 6.3.3 Step 6 and Step 7.
return AssertionResult.FailureUserConsent;
case "SecurityError":
if (requestOptions.extensions?.appid !== undefined) {
// § 10.1 and 10.2 Step 3.
return AssertionResult.FailureU2FFacetID;
} else {
return AssertionResult.FailureUnknownSecurity;
}
default:
console.error(`Unhandled DOMException occurred during WebAuthN assertion: ${exception}`);
return AssertionResult.FailureUnknown;
}
}
async function getAttestationCreationOptions(token: string): Promise<PublicKeyCredentialCreationOptionsStatus> {
let response: AxiosResponse<ServiceResponse<CredentialCreation>>;
response = await axios.post<ServiceResponse<CredentialCreation>>(WebauthnIdentityFinishPath, {
token: token,
});
if (response.data.status !== "OK" || response.data.data == null) {
return {
status: response.status,
};
}
return {
options: decodePublicKeyCredentialCreationOptions(response.data.data.publicKey),
status: response.status,
};
}
export async function getAssertionRequestOptions(): Promise<PublicKeyCredentialRequestOptionsStatus> {
let response: AxiosResponse<ServiceResponse<CredentialRequest>>;
response = await axios.get<ServiceResponse<CredentialRequest>>(WebauthnAssertionPath);
if (response.data.status !== "OK" || response.data.data == null) {
return {
status: response.status,
};
}
return {
options: decodePublicKeyCredentialRequestOptions(response.data.data.publicKey),
status: response.status,
};
}
async function getAttestationPublicKeyCredentialResult(
creationOptions: PublicKeyCredentialCreationOptions,
): Promise<AttestationPublicKeyCredentialResult> {
const result: AttestationPublicKeyCredentialResult = {
result: AttestationResult.Success,
};
try {
result.credential = (await navigator.credentials.create({
publicKey: creationOptions,
})) as AttestationPublicKeyCredential;
} catch (e) {
result.result = AttestationResult.Failure;
const exception = e as DOMException;
if (exception !== undefined) {
result.result = getAttestationResultFromDOMException(exception);
return result;
} else {
console.error(`Unhandled exception occurred during WebAuthN attestation: ${e}`);
}
}
if (result.credential == null) {
result.result = AttestationResult.Failure;
} else {
result.result = AttestationResult.Success;
}
return result;
}
export async function getAssertionPublicKeyCredentialResult(
requestOptions: PublicKeyCredentialRequestOptions,
): Promise<AssertionPublicKeyCredentialResult> {
const result: AssertionPublicKeyCredentialResult = {
result: AssertionResult.Success,
};
try {
result.credential = (await navigator.credentials.get({ publicKey: requestOptions })) as PublicKeyCredential;
} catch (e) {
result.result = AssertionResult.Failure;
const exception = e as DOMException;
if (exception !== undefined) {
result.result = getAssertionResultFromDOMException(exception, requestOptions);
return result;
} else {
console.error(`Unhandled exception occurred during WebAuthN assertion: ${e}`);
}
}
if (result.credential == null) {
result.result = AssertionResult.Failure;
} else {
result.result = AssertionResult.Success;
}
return result;
}
async function postAttestationPublicKeyCredentialResult(
credential: AttestationPublicKeyCredential,
): Promise<AxiosResponse<OptionalDataServiceResponse<any>>> {
const credentialJSON = encodeAttestationPublicKeyCredential(credential);
return axios.post<OptionalDataServiceResponse<any>>(WebauthnAttestationPath, credentialJSON);
}
export async function postAssertionPublicKeyCredentialResult(
credential: PublicKeyCredential,
targetURL: string | undefined,
): Promise<AxiosResponse<ServiceResponse<SignInResponse>>> {
const credentialJSON = encodeAssertionPublicKeyCredential(credential, targetURL);
return axios.post<ServiceResponse<SignInResponse>>(WebauthnAssertionPath, credentialJSON);
}
export async function performAttestationCeremony(token: string): Promise<AttestationResult> {
const attestationCreationOpts = await getAttestationCreationOptions(token);
if (attestationCreationOpts.status !== 200 || attestationCreationOpts.options == null) {
if (attestationCreationOpts.status === 403) {
return AttestationResult.FailureToken;
}
return AttestationResult.Failure;
}
const attestationResult = await getAttestationPublicKeyCredentialResult(attestationCreationOpts.options);
if (attestationResult.result !== AttestationResult.Success) {
return attestationResult.result;
} else if (attestationResult.credential == null) {
return AttestationResult.Failure;
}
const response = await postAttestationPublicKeyCredentialResult(attestationResult.credential);
if (response.data.status === "OK" && (response.status === 200 || response.status === 201)) {
return AttestationResult.Success;
}
return AttestationResult.Failure;
}
export async function performAssertionCeremony(targetURL: string | undefined): Promise<AssertionResult> {
const assertionRequestOpts = await getAssertionRequestOptions();
if (assertionRequestOpts.status !== 200 || assertionRequestOpts.options == null) {
return AssertionResult.FailureChallenge;
}
const assertionResult = await getAssertionPublicKeyCredentialResult(assertionRequestOpts.options);
if (assertionResult.result !== AssertionResult.Success) {
return assertionResult.result;
} else if (assertionResult.credential == null) {
return AssertionResult.Failure;
}
const response = await postAssertionPublicKeyCredentialResult(assertionResult.credential, targetURL);
if (response.data.status === "OK" && response.status === 200) {
return AssertionResult.Success;
}
return AssertionResult.Failure;
} | the_stack |
import {div, icon, span, TagElement} from "../../tags";
import {NotebookMessageDispatcher} from "../../../messaging/dispatcher";
import {Disposable, IDisposable, MoveArrayValue, NoUpdate, setValue, StateHandler, UpdateResult} from "../../../state";
import {CellMetadata} from "../../../data/data";
import {CellContainer} from "./cell";
import {NotebookConfigEl} from "./notebookconfig";
import {VimStatus} from "./vim_status";
import {PosRange} from "../../../data/result";
import {CellState, NotebookStateHandler} from "../../../state/notebook_state";
import {NotebookScrollLocationsHandler} from "../../../state/preferences";
import {ServerStateHandler} from "../../../state/server_state";
import {Main} from "../../../main";
type CellInfo = {cell: CellContainer, handler: StateHandler<CellState>, el: TagElement<"div">};
export class Notebook extends Disposable {
readonly el: TagElement<"div">;
readonly cells: Record<number, CellInfo> = {};
constructor(private dispatcher: NotebookMessageDispatcher, private notebookState: NotebookStateHandler) {
super()
const path = notebookState.state.path;
const config = new NotebookConfigEl(dispatcher, notebookState.lens("config"), notebookState.view("kernel").view("status"));
const cellsEl = div(['notebook-cells'], [config.el, this.newCellDivider()]);
cellsEl.addEventListener('scroll', evt => {
NotebookScrollLocationsHandler.updateField(path, () => cellsEl.scrollTop);
});
this.el = div(['notebook-content'], [cellsEl]);
let needLayout = true;
const layoutCells = () => {
if (!needLayout)
return;
// console.time("Layout cells")
const cells = Object.values(this.cells);
const layoutCell = cellsEl.querySelector('.code-cell .cell-input-editor');
if (cells.length) {
const width = layoutCell?.clientWidth || cells[0].cell.cell.editorEl.clientWidth;
const didLayoutCells = cells.map(cellInfo => {
return cellInfo.cell.layout(width)
});
needLayout = !didLayoutCells.every(x => x);
}
// console.timeEnd("Layout cells")
}
const handleVisibility = (currentNotebook: string | undefined) => {
if (currentNotebook === path) {
// when this notebook becomes visible, scroll to the saved location (if present)
const maybeScrollLocation = NotebookScrollLocationsHandler.state[path]
if (maybeScrollLocation !== undefined) {
cellsEl.scrollTop = maybeScrollLocation
}
notebookState.loaded.then(() => layoutCells())
} else {
// deselect cells.
this.notebookState.selectCell(undefined)
}
}
handleVisibility(ServerStateHandler.state.currentNotebook)
ServerStateHandler.view("currentNotebook").addObserver(handleVisibility).disposeWith(notebookState)
const cellsHandler = notebookState.cellsHandler
const handleAddedCells = (added: Partial<Record<number, CellState>>, cellOrderUpdate: UpdateResult<number[]>) => {
// if no cells exist yet, we'll need to do an initial layout after adding the cells.
const layoutAllCells = Object.keys(this.cells).length === 0;
// layout each new cell because we're no longer initializing.
const layoutNewCells = !layoutAllCells && cellsEl.isConnected; // if cellsEl is in the DOM it means we're done initializing.
Object.entries(cellOrderUpdate.addedValues!).forEach(([idx, id]) => {
const handler = cellsHandler.lens(id)
const cell = new CellContainer(this.newCellDivider(), dispatcher, notebookState, handler);
const el = cell.el;
this.cells[id] = {cell, handler, el};
const cellIdx = parseInt(idx);
const nextCellIdAtIdx = cellOrderUpdate.newValue[cellIdx + 1];
if (nextCellIdAtIdx !== undefined && this.cells[nextCellIdAtIdx] !== undefined) {
// there's a different cell at this index. we need to insert this cell above the existing cell
const nextCellEl = this.cells[nextCellIdAtIdx].el;
// note that inserting a node that is already in the DOM will move it from its current location to here.
cellsEl.insertBefore(el, nextCellEl);
} else {
// index not found, must be at the end
cellsEl.appendChild(el);
}
if (layoutNewCells) {
cell.layout()
}
})
if (layoutAllCells) {
needLayout = true;
window.requestAnimationFrame(layoutCells);
}
}
const handleDeletedCells = (deletedPartial: Partial<Record<number, CellState>>, cellOrderUpdate: UpdateResult<number[]>) => {
Object.entries(cellOrderUpdate.removedValues!).forEach(([idx, id]) => {
const deletedCell = deletedPartial[id]!;
const deletedIdx = parseInt(idx);
const cellEl = this.cells[id].el!;
const prevCellId = cellOrderUpdate.newValue[deletedIdx - 1] ?? -1;
const undoEl = div(['undo-delete'], [
icon(['close-button'], 'times', 'close icon').click(evt => {
undoEl.parentNode!.removeChild(undoEl)
}),
span(['undo-message'], [
'Cell deleted. ',
span(['undo-link'], ['Undo']).click(evt => {
this.insertCell(prevCellId, deletedCell.language, deletedCell.content, deletedCell.metadata)
undoEl.parentNode!.removeChild(undoEl);
})
])
])
cellEl.replaceWith(undoEl)
this.cells[id].handler.dispose()
this.cells[id].cell.delete();
delete this.cells[id];
})
}
notebookState.addObserver((state, update) => {
const cellOrderUpdate = update.fieldUpdates?.cellOrder
const maybeDeletedCells = update.fieldUpdates?.cells?.removedValues
const maybeAddedCells = update.fieldUpdates?.cells?.addedValues
if (cellOrderUpdate && cellOrderUpdate.update instanceof MoveArrayValue) {
const newIndex = cellOrderUpdate.update.toIndex;
// Move the cell's element such that it's in the correct order
// Which cell should it be before now?
const newNextCellId = cellOrderUpdate.newValue[newIndex + 1];
const targetCellId = cellOrderUpdate.update.movedValue;
if (targetCellId !== undefined) {
const targetCell = this.cells[targetCellId]?.el;
if (targetCell) {
const newNextCell = this.cells[newNextCellId]?.el;
if (newNextCell) {
cellsEl.insertBefore(targetCell, newNextCell);
} else {
cellsEl.appendChild(targetCell);
}
if (state.activeCellId !== undefined) {
const activeCellId = state.activeCellId;
// re-select the cell, so that its available values get recomputed
notebookState.updateAsync(
s => {
if (s.activeCellId !== activeCellId)
return NoUpdate;
return {activeCellId: setValue(undefined)}
},
this,
'activeCellId'
).then(() => notebookState.update(s => {
if (s.activeCellId !== undefined)
return NoUpdate;
return {activeCellId: setValue(activeCellId)}
}, this, 'activeCellId'))
}
}
}
} else {
if (maybeDeletedCells) {
if (cellOrderUpdate === undefined) {
console.error("Got deleted cells", maybeDeletedCells, "but cellOrder didn't change! This is weird. Update:", update)
} else {
handleDeletedCells(maybeDeletedCells, cellOrderUpdate)
}
}
if (maybeAddedCells) {
if (cellOrderUpdate === undefined) {
console.error("Got deleted cells", maybeDeletedCells, "but cellOrder didn't change! This is weird. Update:", update)
} else {
handleAddedCells(maybeAddedCells, cellOrderUpdate)
}
}
}
}, "cellOrder") // in theory, this should make it so this observer only gets called when `cellOrder` changes.
this.notebookState.view("activeCellId").addObserver(cell => {
if (cell === undefined) {
VimStatus.get.hide()
}
}).disposeWith(this)
this.notebookState.loaded.then(() => {
Main.get.splitView.onEndResize(width => {
needLayout = true;
if (ServerStateHandler.state.currentNotebook === path) {
layoutCells();
}
}).disposeWith(this);
})
// select cell + highlight based on the current hash
const hash = document.location.hash;
// the hash can (potentially) have two parts: the selected cell and selected position.
// for example: #Cell2,6-12 would mean Cell2, positions at offset 6 to 12
const [hashId, pos] = hash.slice(1).split(",");
const cellId = parseInt(hashId.slice("Cell".length))
// cell might not yet be loaded, so be sure to wait for it
this.waitForCell(cellId).then(() => {
this.notebookState.selectCell(cellId)
if (pos) {
const range = PosRange.fromString(pos)
// TODO: when should this go away? maybe when you edit the cell
cellsHandler.updateField(cellId, () => ({
currentHighlight: {
range,
className: "link-highlight"
}
}))
}
})
}
/**
* Create a cell divider that inserts new cells at a given position
*/
private newCellDivider() {
return div(['new-cell-divider'], []).click((evt) => {
const self = evt.target as TagElement<"div">;
const prevCell = Object.values(this.cells).reduce((acc: CellState, next) => {
if (self.parentElement === next.cell.el) {
acc = next.handler.state
}
return acc;
}, undefined);
const lang = prevCell?.language && prevCell.language !== "text" && prevCell.language !== "viz" ? prevCell.language : "scala"; // TODO: make this configurable
this.insertCell(prevCell?.id ?? -1, lang, '');
});
}
private insertCell(prev: number, language: string, content: string, metadata?: CellMetadata) {
this.notebookState.insertCell("below", {id: prev, language, content, metadata: metadata ?? new CellMetadata()})
.then(newCellId => {
this.notebookState.selectCell(newCellId, {editing: true})
})
}
/**
* Wait for a specific cell to be loaded. Since we load cells lazily, we might get actions for certain cells
* (e.g., highlighting them) before they have been loaded by the page.
*
* @returns the id of the cell, useful if you pass this Promise somewhere else.
*/
private waitForCell(cellId: number): Promise<number> {
// wait for the cell to appear in the state
return new Promise(resolve => {
const wait = this.notebookState.addObserver(state => {
if (state.cellOrder.find(id => id === cellId)) {
wait.dispose();
requestAnimationFrame(() => {
resolve(cellId)
})
}
}).disposeWith(this)
}).then((cellId: number) => {
// wait for the cell to appear on the page
return new Promise(resolve => {
const interval = window.setInterval(() => {
const maybeCell = this.cells[cellId]?.cell
if (maybeCell && this.el.contains(maybeCell.el)) {
window.clearInterval(interval)
resolve(cellId)
}
}, 100)
})
})
}
} | the_stack |
import * as Path from 'path'
import { flatten, get, omit, trimStart } from 'lodash'
import { File } from '@main/file'
import { Status, parseStatus } from '@lib/frameworks/status'
import { IFramework } from '@lib/frameworks/framework'
import { ITest, ITestResult, Test } from '@lib/frameworks/test'
import { Nugget } from '@lib/frameworks/nugget'
export interface ISuite extends Nugget {
readonly file: string
getId (): string
getFile (): string
getFilePath (): string
getRelativePath (): string
getDisplayName (): string
getStatus (): Status
getNuggetIds (selective: boolean): Array<string>
getMeta (): any
resetMeta (): void
getConsole (): Array<any> | null
getFramework (): IFramework
testsLoaded (): boolean
rebuildTests (result: ISuiteResult): Promise<void>
canBeOpened (): boolean
canToggleTests (): boolean
toggleSelected (toggle?: boolean, cascade?: boolean): Promise<void>
toggleExpanded (toggle?: boolean, cascade?: boolean): Promise<void>
debrief (result: ISuiteResult, selective: boolean): Promise<void>
render (status?: Status | false): ISuiteResult
persist (status?: Status | false): ISuiteResult
setFresh (fresh: boolean): void
isFresh (): boolean
countChildren (): number
hasChildren(): boolean
contextMenu (): Array<Electron.MenuItemConstructorOptions>
getRunningOrder (): number | null
}
export interface ISuiteResult {
file: string
status?: Status
tests?: Array<ITestResult>
meta?: object | null
console?: Array<any>
testsLoaded?: boolean
hasChildren?: boolean
selected?: boolean
partial?: boolean
relative?: string
}
export class Suite extends Nugget implements ISuite {
public file!: string
protected result!: ISuiteResult
constructor (framework: IFramework, result: ISuiteResult) {
super(framework)
this.build(result)
}
/**
* Prepares the suite for sending out to renderer process.
*
* @param status Which status to recursively set on tests. False will persist current status.
*/
public render (status: Status | false = 'idle'): ISuiteResult {
return {
file: this.file,
meta: this.getMeta(),
hasChildren: this.testsLoaded() && this.hasChildren(),
selected: this.selected,
partial: this.partial,
relative: this.getRelativePath()
}
}
/**
* Prepares the suite for persistence.
*
* @param status Which status to recursively set on tests. False will persist current status.
*/
public persist (status: Status | false = 'idle'): ISuiteResult {
return omit({
...this.render(),
testsLoaded: this.testsLoaded(),
tests: this.bloomed
? this.tests.map((test: ITest) => test.persist(status))
: this.getTestResults().map((test: ITestResult) => this.defaults(test, status))
}, ['hasChildren', 'selected', 'partial', 'relative'])
}
/**
* Build this suite from a result object.
*
* @param result The result object with which to build this suite.
*/
protected build (result: ISuiteResult): void {
this.file = result.file
this.result = result
if (this.expanded) {
this.bloom().then(() => {
this.updateStatus()
})
} else {
this.updateStatus()
}
}
/**
* Rebuild this suite's tests from a result object.
*
* @param result The result object with which to build this suite's tests.
*/
public async rebuildTests (result: ISuiteResult): Promise<void> {
this.tests = (result.tests || []).map((result: ITestResult) => {
return this.makeTest(result, false)
})
if (!this.expanded) {
await this.wither()
}
// Update the status in case new tests have been created
// or old tests have been removed.
this.updateStatus()
}
/**
* Whether the suite's file can be opened
*/
public canBeOpened (): boolean {
return File.isSafe(this.getFilePath()) && File.exists(this.getFilePath())
}
/**
* Whether the suite can run tests selectively.
*/
public canToggleTests (): boolean {
return this.framework.canToggleTests
}
/**
* Instantiate a new test.
*
* @param result The test result with which to instantiate a new test.
*/
protected newTest (result: ITestResult): ITest {
return new Test(this.framework, result)
}
/**
* Update this suite's status.
*
* Override default status parsing to make sure we don't mark suites
* without loaded tests as "empty". Mark them as "idle", instead.
*
* @param to The status we're updating to.
*/
protected updateStatus (to?: Status): void {
if (typeof to === 'undefined') {
const statuses = this.bloomed
? this.tests.map((test: ITest) => test.getStatus())
: this.getTestResults().map((test: ITestResult) => this.framework.getNuggetStatus(test.id))
to = parseStatus(statuses)
if (to === 'empty' && !this.testsLoaded()) {
to = 'idle'
}
}
const from = this.getStatus()
if (to !== from) {
this.framework.setNuggetStatus(this.getId(), to, from, true)
}
}
/**
* Get this suite's id.
*/
public getId (): string {
return this.file!
}
/**
* Get this suite's file.
*/
public getFile (): string {
return this.file!
}
/**
* Get this suite's local file path, regardless of running remotely.
*/
public getFilePath (): string {
if (!this.framework.runsInRemote) {
return this.file
}
return Path.join(
this.framework.fullPath,
Path.relative(
Path.join(
this.framework.getRemotePath(),
this.framework.path
),
this.file
)
)
}
/**
* Get this suite's relative file path.
*/
public getRelativePath (): string {
return this.framework.runsInRemote && (!this.framework.getRemotePath() || this.framework.getRemotePath() === '/')
? trimStart(this.file, '/')
: Path.relative(
this.framework.runsInRemote
? (Path.join(this.framework.getRemotePath(), this.framework.path))
: this.framework.fullPath,
this.file
)
}
/**
* Get this suite's display name.
*/
public getDisplayName (): string {
return this.getRelativePath()
}
/**
* Get this suite's status.
*/
public getStatus (): Status {
// If tests haven't been loaded, suite status will of course come back
// as empty. This won't be confirmed until we actually parse the suite
// and load its tests, so until then we'll force an "idle" status.
if (super.getStatus() === 'empty' && !this.testsLoaded()) {
return 'idle'
}
return super.getStatus()
}
/**
* Get the ids of this suite and the nuggets it is supposed to run.
*/
public getNuggetIds (selective: boolean): Array<string> {
return flatten([
this.getId(),
...(
selective && this.canToggleTests()
? this.tests
.filter(test => test.selected)
.map((test: ITest) => this.getRecursiveNuggetIds(test.getResult()))
: (this.bloomed
? this.tests.map((test: ITest) => this.getRecursiveNuggetIds(test.getResult()))
: (this.result.tests || []).map((test: ITestResult) => {
return this.getRecursiveNuggetIds(test)
})
)
)
])
}
/**
* Get metadata for this suite.
*/
public getMeta (key?: string, fallback?: any): any {
if (!key) {
return this.result.meta || {}
}
return !this.result.meta ? fallback : get(this.result.meta!, key, fallback)
}
/**
* Reset metadata for this suite.
*/
public resetMeta (): void {
if (this.result.meta) {
this.result.meta = null
}
}
/**
* Get this suite's console output.
*/
public getConsole (): Array<any> | null {
return this.result.console && this.result.console.length ? this.result.console : null
}
/**
* Get this suites's parent framework.
*/
public getFramework (): IFramework {
return this.framework
}
/**
* Get this nugget's running order, if any.
*/
public getRunningOrder (): number | null {
return this.getMeta('n', null)
}
/**
* Whether this suite's tests are loaded.
*/
public testsLoaded (): boolean {
return this.result.testsLoaded !== false
}
/**
* Debrief this suite.
*
* @param result The result object with which to debrief this suite.
* @param cleanup Whether to clean obsolete children after debriefing.
*/
public async debrief (result: ISuiteResult, cleanup: boolean): Promise<void> {
const emit = !this.testsLoaded()
this.file = result.file
this.result.meta = result.meta
this.result.console = result.console
this.result.testsLoaded = result.testsLoaded
return new Promise((resolve, reject) => {
// Bloom suite before debriefing, which ensures we can find and
// create tests using the actual models, not plain results.
this.bloom().then(() => {
this.debriefTests(result.tests || [], cleanup)
.then(() => {
if (emit) {
// Only emit the :children event if tests weren't loaded initially.
this.emitToRenderer(`${this.getId()}:children`, this.testsLoaded() && this.hasChildren())
}
resolve()
})
})
})
}
} | the_stack |
import {
Accepts,
isIP,
parseRange,
readableStreamFromReader,
readerFromStreamReader,
typeofrequest,
} from "../deps.ts";
import type { ConnInfo } from "../deps.ts";
import { fresh } from "./utils/fresh.ts";
import { parseUrl } from "./utils/parseUrl.ts";
import { all, proxyaddr } from "./utils/proxyAddr.ts";
import {
Application,
NextFunction,
OpineRequest,
OpineResponse,
ParamsDictionary,
ParsedURL,
RangeParserOptions,
RangeParserRanges,
RangeParserResult,
} from "../src/types.ts";
function emptyReader(): Deno.Reader {
return {
read(_: Uint8Array): Promise<number | null> {
return Promise.resolve(null);
},
};
}
const isDenoReader = (body: unknown): body is Deno.Reader =>
body !== null &&
typeof body === "object" &&
typeof (body as Deno.Reader).read === "function";
export class WrappedRequest implements OpineRequest {
#request: Request;
#connInfo: ConnInfo;
#responsePromise: Promise<Response>;
#responsePromiseResolver!: (response: Response) => void;
app!: Application;
res!: OpineResponse;
params!: ParamsDictionary;
query: unknown;
route: unknown;
url: string;
originalUrl!: string;
baseUrl!: string;
proto: string;
method: string;
headers: Headers;
parsedBody?: unknown;
_parsedBody?: boolean | undefined;
_parsedUrl?: ParsedURL | undefined;
_parsedOriginalUrl?: ParsedURL | undefined;
next?: NextFunction | undefined;
param!: (
name: string,
defaultValue?: string | undefined,
) => string | undefined;
constructor(request: Request, connInfo: ConnInfo) {
this.#request = request;
this.#connInfo = connInfo;
this.#responsePromise = new Promise((resolve) => {
this.#responsePromiseResolver = resolve;
});
const { pathname, search, hash } = new URL(request.url);
this.url = `${pathname}${search}${hash}`;
this.proto = parseUrl(this)?.protocol ?? "";
this.method = request.method;
this.headers = new Headers(this.#request.headers);
}
respond(response: OpineResponse) {
const bodyInit = isDenoReader(response.body)
? readableStreamFromReader(response.body)
: response.body;
this.#responsePromiseResolver(new Response(bodyInit, response));
}
/**
* Check if the given `type(s)` is acceptable, returning
* the best match when true, otherwise `undefined`, in which
* case you should respond with 406 "Not Acceptable".
*
* The `type` value may be a single MIME type string
* such as "application/json", an extension name
* such as "json", a comma-delimited list such as "json, html, text/plain",
* an argument list such as `"json", "html", "text/plain"`,
* or an array `["json", "html", "text/plain"]`. When a list
* or array is given, the _best_ match, if any is returned.
*
* Examples:
*
* // Accept: text/html
* req.accepts('html');
* // => "html"
*
* // Accept: text/*, application/json
* req.accepts('html');
* // => "html"
* req.accepts('text/html');
* // => "text/html"
* req.accepts('json, text');
* // => "json"
* req.accepts('application/json');
* // => "application/json"
*
* // Accept: text/*, application/json
* req.accepts('image/png');
* req.accepts('png');
* // => undefined
*
* // Accept: text/*;q=.5, application/json
* req.accepts(['html', 'json']);
* req.accepts('html', 'json');
* req.accepts('html, json');
* // => "json"
*
* @param {string|string[]} type
* @return {string|string[]|false}
* @public
*/
accepts(this: OpineRequest, ...args: [string[]] | string[]) {
const accept = new Accepts(this.headers);
return accept.types.call(accept, args.flat(1));
}
/**
* Check if the given `charset`s are acceptable,
* otherwise you should respond with 406 "Not Acceptable".
*
* @param {string|string[]} ...charset
* @return {string|string[]|false}
* @public
*/
acceptsCharsets(
this: OpineRequest,
...args: [string[]] | string[]
) {
const accept = new Accepts(this.headers);
return accept.charsets.call(accept, args.flat(1));
}
/**
* Check if the given `encoding`s are accepted.
*
* @param {string|string[]} ...encoding
* @return {string|string[]|false}
* @public
*/
acceptsEncodings(
this: OpineRequest,
...args: [string[]] | string[]
) {
const accept = new Accepts(this.headers);
return accept.encodings.call(accept, args.flat(1));
}
/**
* Check if the given `lang`s are acceptable,
* otherwise you should respond with 406 "Not Acceptable".
*
* @param {string|string[]} ...lang
* @return {string|string[]|false}
* @public
*/
acceptsLanguages(
this: OpineRequest,
...args: [string[]] | string[]
) {
const accept = new Accepts(this.headers);
return accept.languages.call(accept, args.flat(1));
}
/**
* Return request header.
*
* The `Referrer` header field is special-cased,
* both `Referrer` and `Referer` are interchangeable.
*
* Examples:
*
* req.get('Content-Type');
* // => "text/plain"
*
* req.get('content-type');
* // => "text/plain"
*
* req.get('Something');
* // => undefined
*
* Aliased as `req.header()`.
*
* @param {string} name
* @return {string}
* @public
*/
get(name: string): string | undefined {
const lc = name.toLowerCase();
switch (lc) {
case "referer":
case "referrer":
return this.headers.get("referrer") ||
this.headers.get("referer") || undefined;
default:
return this.headers.get(lc) || undefined;
}
}
/**
* Parse Range header field, capping to the given `size`.
*
* Unspecified ranges such as "0-" require knowledge of your resource length. In
* the case of a byte range this is of course the total number of bytes. If the
* Range header field is not given `undefined` is returned, `-1` when unsatisfiable,
* and `-2` when syntactically invalid.
*
* When ranges are returned, the array has a "type" property which is the type of
* range that is required (most commonly, "bytes"). Each array element is an object
* with a "start" and "end" property for the portion of the range.
*
* The "combine" option can be set to `true` and overlapping & adjacent ranges
* will be combined into a single range.
*
* NOTE: remember that ranges are inclusive, so for example "Range: users=0-3"
* should respond with 4 users when available, not 3.
*
* @param {number} size
* @param {object} [options]
* @param {boolean} [options.combine=false]
* @return {number|number[]|undefined}
* @public
*/
range(
size: number,
options?: RangeParserOptions,
): RangeParserRanges | RangeParserResult | undefined {
const range = this.get("Range");
if (!range) return;
return parseRange(size, range, options) as
| RangeParserRanges
| RangeParserResult;
}
/**
* Check if the incoming request contains the "Content-Type"
* header field, and it contains the give mime `type`.
*
* Examples:
*
* // With Content-Type: text/html; charset=utf-8
* req.is('html');
* req.is('text/html');
* req.is('text/*');
* // => true
*
* // When Content-Type is application/json
* req.is('json');
* req.is('application/json');
* req.is('application/*');
* // => true
*
* req.is('html');
* // => false
*
* @param {String|Array} types...
* @return {String|false|null}
* @public
*/
is(this: OpineRequest, types: string | string[]) {
let arr = types;
// support flattened arguments
if (!Array.isArray(types)) {
arr = new Array(arguments.length);
for (let i = 0; i < arr.length; i++) {
arr[i] = arguments[i];
}
}
return typeofrequest(this.headers, arr as string[]);
}
upgrade(): WebSocket {
const { socket, response } = Deno.upgradeWebSocket(this.#request);
this.#responsePromiseResolver(response);
return socket;
}
get #body() {
const streamReader = this.#request.body?.getReader();
return streamReader ? readerFromStreamReader(streamReader) : emptyReader();
}
get body() {
return this.parsedBody ?? this.#body;
}
set body(value: unknown) {
this.parsedBody = value;
}
get raw() {
return this.#body;
}
get conn() {
return this.#connInfo;
}
/**
* Returns a promise that resolves to the response to the request.
*/
get finalResponse() {
return this.#responsePromise;
}
/**
* Return the protocol string "http" or "https"
* when requested with TLS. When the "trust proxy"
* setting trusts the socket address, the
* "X-Forwarded-Proto" header field will be trusted
* and used if present.
*
* If you're running behind a reverse proxy that
* supplies https for you this may be enabled.
*
* @return {string}
* @public
*/
get protocol() {
const proto = this.proto.includes("https") ? "https" : "http";
const trust = this.app.get("trust proxy fn");
const { hostname: remoteAddress } = this.conn
.remoteAddr as Deno.NetAddr;
if (!trust(remoteAddress, 0)) {
return proto;
}
// Note: X-Forwarded-Proto is normally only ever a
// single value, but this is to be safe.
const header = this.get("X-Forwarded-Proto") ?? proto;
const index = header.indexOf(",");
return index !== -1 ? header.substring(0, index).trim() : header.trim();
}
/**
* Short-hand for:
*
* req.protocol === 'https'
*
* @return {Boolean}
* @public
*/
get secure() {
return this.protocol === "https";
}
/**
* Return the remote address from the trusted proxy.
*
* The is the remote address on the socket unless
* "trust proxy" is set.
*
* @return {string}
* @public
*/
get ip(): string {
const trust = this.app.get("trust proxy fn");
return proxyaddr(this, trust);
}
/**
* When "trust proxy" is set, trusted proxy addresses + client.
*
* For example if the value were "client, proxy1, proxy2"
* you would receive the array `["client", "proxy1", "proxy2"]`
* where "proxy2" is the furthest down-stream and "proxy1" and
* "proxy2" were trusted.
*
* @return {Array}
* @public
*/
get ips() {
const trust = this.app.get("trust proxy fn");
const addrs = all(this, trust);
// Reverse the order (to farthest -> closest)
// and remove socket address
addrs.reverse().pop();
return addrs;
}
/**
* Return subdomains as an array.
*
* Subdomains are the dot-separated parts of the host before the main domain of
* the app. By default, the domain of the app is assumed to be the last two
* parts of the host. This can be changed by setting "subdomain offset".
*
* For example, if the domain is "deno.dinosaurs.example.com":
* If "subdomain offset" is not set, req.subdomains is `["dinosaurs", "deno"]`.
* If "subdomain offset" is 3, req.subdomains is `["deno"]`.
*
* @return {Array}
* @public
*/
get subdomains() {
const hostname = this.hostname;
if (!hostname) return [];
const offset = this.app.get("subdomain offset");
const subdomains = !isIP(hostname)
? hostname.split(".").reverse()
: [hostname];
return subdomains.slice(offset);
}
/**
* Returns the pathname of the URL.
*
* @return {string}
* @public
*/
get path(): string {
return parseUrl(this)?.pathname ?? "";
}
/**
* Parse the "Host" header field to a hostname.
*
* When the "trust proxy" setting trusts the socket
* address, the "X-Forwarded-Host" header field will
* be trusted.
*
* @return {string}
* @public
*/
get hostname(): string | undefined {
const trust = this.app.get("trust proxy fn");
let host = this.get("X-Forwarded-Host");
const { hostname: remoteAddress } = this.conn
.remoteAddr as Deno.NetAddr;
if (!host || !trust(remoteAddress, 0)) {
host = this.get("Host");
} else if (host.indexOf(",") !== -1) {
// Note: X-Forwarded-Host is normally only ever a
// single value, but this is to be safe.
host = host.substring(0, host.indexOf(",")).trimRight();
}
if (!host) {
return undefined;
}
// IPv6 literal support
const offset = host[0] === "[" ? host.indexOf("]") + 1 : 0;
const index = host.indexOf(":", offset);
return index !== -1 ? host.substring(0, index) : host;
}
/**
* Check if the request is fresh, aka
* Last-Modified and/or the ETag
* still match.
*
* @return {boolean}
* @public
*/
get fresh() {
const method = this.method;
const res = this.res as OpineResponse;
const status = res.status as number;
// GET or HEAD for weak freshness validation only
if ("GET" !== method && "HEAD" !== method) {
return false;
}
// 2xx or 304 as per rfc2616 14.26
if ((status >= 200 && status < 300) || 304 === status) {
return fresh(Object.fromEntries(this.headers), {
"etag": res.get("ETag"),
"last-modified": res.get("Last-Modified"),
});
}
return false;
}
/**
* Check if the request is stale, aka
* "Last-Modified" and / or the "ETag" for the
* resource has changed.
*
* @return {Boolean}
* @public
*/
get stale(): boolean {
return !this.fresh;
}
/**
* Check if the request was an _XMLHttpRequest_.
*
* @return {Boolean}
* @public
*/
get xhr() {
const val = this.get("X-Requested-With") || "";
return val.toLowerCase() === "xmlhttprequest";
}
} | the_stack |
import React from 'react';
import Form from 'antd/es/form';
import { Button, Input, Radio, Row, Col } from 'antd';
import { PlusOutlined, MinusCircleOutlined } from '@ant-design/icons';
import { useIntl } from 'umi';
import PanelSection from '@/components/PanelSection';
import {
FORM_ITEM_WITHOUT_LABEL,
SCHEME_REWRITE,
URI_REWRITE_TYPE,
HOST_REWRITE_TYPE,
} from '@/pages/Route/constants';
const removeBtnStyle = {
marginLeft: 20,
display: 'flex',
alignItems: 'center',
};
/**
* https://apisix.apache.org/docs/apisix/plugins/proxy-rewrite
* UI for ProxyRewrite plugin
*/
const ProxyRewrite: React.FC<RouteModule.Step1PassProps> = ({ form, disabled }) => {
const { formatMessage } = useIntl();
const getUriRewriteItems = () => {
switch (form.getFieldValue('URIRewriteType')) {
case URI_REWRITE_TYPE.STATIC:
return (
<Form.Item
label={formatMessage({ id: 'page.route.form.itemLabel.newPath' })}
name={['proxyRewrite', 'uri']}
rules={[
{
required: true,
message: `${formatMessage({ id: 'component.global.pleaseEnter' })} ${formatMessage({
id: 'page.route.form.itemLabel.newPath',
})}`,
},
]}
>
<Input
placeholder={`${formatMessage({
id: 'component.global.pleaseEnter',
})} ${formatMessage({ id: 'page.route.form.itemLabel.newPath' })}`}
disabled={disabled}
/>
</Form.Item>
);
case URI_REWRITE_TYPE.REGEXP:
return (
<Form.List name={['proxyRewrite', 'regex_uri']} initialValue={['', '']}>
{(fields) =>
fields.map((field, index) => {
switch (index) {
case 0:
return (
<Form.Item
label={formatMessage({ id: 'page.route.form.itemLabel.regex' })}
name={field.name}
key={field.name}
rules={[
{
required: true,
message: `${formatMessage({
id: 'component.global.pleaseEnter',
})} ${formatMessage({ id: 'page.route.form.itemLabel.regex' })}`,
},
]}
>
<Input
placeholder={`${formatMessage({
id: 'component.global.pleaseEnter',
})} ${formatMessage({ id: 'page.route.form.itemLabel.regex' })}`}
disabled={disabled}
/>
</Form.Item>
);
case 1:
return (
<Form.Item
label={formatMessage({ id: 'page.route.form.itemLabel.template' })}
name={field.name}
key={field.name}
rules={[
{
required: true,
message: `${formatMessage({
id: 'component.global.pleaseEnter',
})} ${formatMessage({ id: 'page.route.form.itemLabel.template' })}`,
},
]}
>
<Input
placeholder={`${formatMessage({
id: 'component.global.pleaseEnter',
})} ${formatMessage({ id: 'page.route.form.itemLabel.template' })}`}
disabled={disabled}
/>
</Form.Item>
);
default:
return null;
}
})
}
</Form.List>
);
case URI_REWRITE_TYPE.KEEP:
default:
return null;
}
};
const getHostRewriteItems = () => {
switch (form.getFieldValue('hostRewriteType')) {
case HOST_REWRITE_TYPE.REWRITE:
return (
<Form.Item
label={formatMessage({ id: 'page.route.form.itemLabel.newHost' })}
name={['proxyRewrite', 'host']}
rules={[
{
required: true,
message: `${formatMessage({ id: 'component.global.pleaseEnter' })} ${formatMessage({
id: 'page.route.form.itemLabel.newHost',
})}`,
},
]}
>
<Input
placeholder={`${formatMessage({
id: 'component.global.pleaseEnter',
})} ${formatMessage({ id: 'page.route.form.itemLabel.newHost' })}`}
disabled={disabled}
/>
</Form.Item>
);
case HOST_REWRITE_TYPE.KEEP:
default:
return null;
}
};
const SchemeComponent: React.FC = () => {
const options = [
{
value: SCHEME_REWRITE.KEEP,
label: formatMessage({ id: 'page.route.radio.staySame' }),
},
{
value: SCHEME_REWRITE.HTTP,
label: SCHEME_REWRITE.HTTP.toLocaleUpperCase(),
},
{
value: SCHEME_REWRITE.HTTPS,
label: SCHEME_REWRITE.HTTPS.toLocaleUpperCase(),
},
];
return (
<Form.Item
label={formatMessage({ id: 'page.route.form.itemLabel.scheme' })}
name={['proxyRewrite', 'scheme']}
>
<Radio.Group disabled={disabled}>
{options.map((item) => (
<Radio value={item.value} key={item.value}>
{item.label}
</Radio>
))}
</Radio.Group>
</Form.Item>
);
};
const URIRewriteType: React.FC = () => {
const options = [
{
value: URI_REWRITE_TYPE.KEEP,
label: formatMessage({ id: 'page.route.radio.staySame' }),
},
{
value: URI_REWRITE_TYPE.STATIC,
label: formatMessage({ id: 'page.route.radio.static' }),
dataCypress: 'uri-static',
},
{
value: URI_REWRITE_TYPE.REGEXP,
label: formatMessage({ id: 'page.route.radio.regex' }),
},
];
return (
<React.Fragment>
<Form.Item
label={formatMessage({ id: 'page.route.form.itemLabel.URIRewriteType' })}
name="URIRewriteType"
>
<Radio.Group disabled={disabled}>
{options.map((item) => (
<Radio data-cy={item.dataCypress} value={item.value} key={item.value}>
{item.label}
</Radio>
))}
</Radio.Group>
</Form.Item>
<Form.Item
shouldUpdate={(prevValues, curValues) =>
prevValues.URIRewriteType !== curValues.URIRewriteType
}
noStyle
>
{() => {
return getUriRewriteItems();
}}
</Form.Item>
</React.Fragment>
);
};
const HostRewriteType: React.FC = () => {
const options = [
{
label: formatMessage({ id: 'page.route.radio.staySame' }),
value: HOST_REWRITE_TYPE.KEEP,
dataCypress: 'host-keep',
},
{
label: formatMessage({ id: 'page.route.radio.static' }),
value: HOST_REWRITE_TYPE.REWRITE,
dataCypress: 'host-static',
},
];
return (
<React.Fragment>
<Form.Item
label={formatMessage({ id: 'page.route.form.itemLabel.hostRewriteType' })}
name="hostRewriteType"
>
<Radio.Group disabled={disabled}>
{options.map((item) => (
<Radio data-cy={item.dataCypress} value={item.value} key={item.value}>
{item.label}
</Radio>
))}
</Radio.Group>
</Form.Item>
<Form.Item
shouldUpdate={(prevValues, curValues) =>
prevValues.hostRewriteType !== curValues.hostRewriteType
}
noStyle
>
{() => {
return getHostRewriteItems();
}}
</Form.Item>
</React.Fragment>
);
};
const Headers: React.FC = () => {
return (
<Form.List name={['proxyRewrite', 'kvHeaders']} initialValue={[{}]}>
{(fields, { add, remove }) => (
<>
<Form.Item
label={formatMessage({ id: 'page.route.form.itemLabel.headerRewrite' })}
style={{ marginBottom: 0 }}
>
{fields.map((field, index) => (
<Row gutter={12} key={index} style={{ marginBottom: 10 }}>
<Col span={5}>
<Form.Item
name={[field.name, 'key']}
fieldKey={[field.fieldKey, 'key']}
noStyle
>
<Input
placeholder={`${formatMessage({
id: 'component.global.pleaseEnter',
})} ${formatMessage({ id: 'page.route.parameterName' })}`}
disabled={disabled}
/>
</Form.Item>
</Col>
<Col span={5}>
<Form.Item
name={[field.name, 'value']}
fieldKey={[field.fieldKey, 'value']}
noStyle
>
<Input
placeholder={`${formatMessage({
id: 'component.global.pleaseEnter',
})} ${formatMessage({ id: 'page.route.value' })}`}
disabled={disabled}
/>
</Form.Item>
</Col>
{!disabled && fields.length > 1 && (
<Col style={{ ...removeBtnStyle, marginLeft: -5 }}>
<MinusCircleOutlined
className="dynamic-delete-button"
onClick={() => remove(field.name)}
/>
</Col>
)}
</Row>
))}
</Form.Item>
<Form.Item {...FORM_ITEM_WITHOUT_LABEL}>
<Button
data-cy="create-new-rewrite-header"
type="dashed"
disabled={disabled}
onClick={() => add()}
icon={<PlusOutlined />}
>
{formatMessage({ id: 'component.global.add' })}
</Button>
</Form.Item>
</>
)}
</Form.List>
);
};
return (
<PanelSection title={formatMessage({ id: 'page.route.panelSection.title.requestOverride' })}>
<SchemeComponent />
<URIRewriteType />
<HostRewriteType />
<Headers />
</PanelSection>
);
};
export default ProxyRewrite; | the_stack |
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types";
import { CloudSearchClient } from "./CloudSearchClient";
import {
BuildSuggestersCommand,
BuildSuggestersCommandInput,
BuildSuggestersCommandOutput,
} from "./commands/BuildSuggestersCommand";
import {
CreateDomainCommand,
CreateDomainCommandInput,
CreateDomainCommandOutput,
} from "./commands/CreateDomainCommand";
import {
DefineAnalysisSchemeCommand,
DefineAnalysisSchemeCommandInput,
DefineAnalysisSchemeCommandOutput,
} from "./commands/DefineAnalysisSchemeCommand";
import {
DefineExpressionCommand,
DefineExpressionCommandInput,
DefineExpressionCommandOutput,
} from "./commands/DefineExpressionCommand";
import {
DefineIndexFieldCommand,
DefineIndexFieldCommandInput,
DefineIndexFieldCommandOutput,
} from "./commands/DefineIndexFieldCommand";
import {
DefineSuggesterCommand,
DefineSuggesterCommandInput,
DefineSuggesterCommandOutput,
} from "./commands/DefineSuggesterCommand";
import {
DeleteAnalysisSchemeCommand,
DeleteAnalysisSchemeCommandInput,
DeleteAnalysisSchemeCommandOutput,
} from "./commands/DeleteAnalysisSchemeCommand";
import {
DeleteDomainCommand,
DeleteDomainCommandInput,
DeleteDomainCommandOutput,
} from "./commands/DeleteDomainCommand";
import {
DeleteExpressionCommand,
DeleteExpressionCommandInput,
DeleteExpressionCommandOutput,
} from "./commands/DeleteExpressionCommand";
import {
DeleteIndexFieldCommand,
DeleteIndexFieldCommandInput,
DeleteIndexFieldCommandOutput,
} from "./commands/DeleteIndexFieldCommand";
import {
DeleteSuggesterCommand,
DeleteSuggesterCommandInput,
DeleteSuggesterCommandOutput,
} from "./commands/DeleteSuggesterCommand";
import {
DescribeAnalysisSchemesCommand,
DescribeAnalysisSchemesCommandInput,
DescribeAnalysisSchemesCommandOutput,
} from "./commands/DescribeAnalysisSchemesCommand";
import {
DescribeAvailabilityOptionsCommand,
DescribeAvailabilityOptionsCommandInput,
DescribeAvailabilityOptionsCommandOutput,
} from "./commands/DescribeAvailabilityOptionsCommand";
import {
DescribeDomainEndpointOptionsCommand,
DescribeDomainEndpointOptionsCommandInput,
DescribeDomainEndpointOptionsCommandOutput,
} from "./commands/DescribeDomainEndpointOptionsCommand";
import {
DescribeDomainsCommand,
DescribeDomainsCommandInput,
DescribeDomainsCommandOutput,
} from "./commands/DescribeDomainsCommand";
import {
DescribeExpressionsCommand,
DescribeExpressionsCommandInput,
DescribeExpressionsCommandOutput,
} from "./commands/DescribeExpressionsCommand";
import {
DescribeIndexFieldsCommand,
DescribeIndexFieldsCommandInput,
DescribeIndexFieldsCommandOutput,
} from "./commands/DescribeIndexFieldsCommand";
import {
DescribeScalingParametersCommand,
DescribeScalingParametersCommandInput,
DescribeScalingParametersCommandOutput,
} from "./commands/DescribeScalingParametersCommand";
import {
DescribeServiceAccessPoliciesCommand,
DescribeServiceAccessPoliciesCommandInput,
DescribeServiceAccessPoliciesCommandOutput,
} from "./commands/DescribeServiceAccessPoliciesCommand";
import {
DescribeSuggestersCommand,
DescribeSuggestersCommandInput,
DescribeSuggestersCommandOutput,
} from "./commands/DescribeSuggestersCommand";
import {
IndexDocumentsCommand,
IndexDocumentsCommandInput,
IndexDocumentsCommandOutput,
} from "./commands/IndexDocumentsCommand";
import {
ListDomainNamesCommand,
ListDomainNamesCommandInput,
ListDomainNamesCommandOutput,
} from "./commands/ListDomainNamesCommand";
import {
UpdateAvailabilityOptionsCommand,
UpdateAvailabilityOptionsCommandInput,
UpdateAvailabilityOptionsCommandOutput,
} from "./commands/UpdateAvailabilityOptionsCommand";
import {
UpdateDomainEndpointOptionsCommand,
UpdateDomainEndpointOptionsCommandInput,
UpdateDomainEndpointOptionsCommandOutput,
} from "./commands/UpdateDomainEndpointOptionsCommand";
import {
UpdateScalingParametersCommand,
UpdateScalingParametersCommandInput,
UpdateScalingParametersCommandOutput,
} from "./commands/UpdateScalingParametersCommand";
import {
UpdateServiceAccessPoliciesCommand,
UpdateServiceAccessPoliciesCommandInput,
UpdateServiceAccessPoliciesCommandOutput,
} from "./commands/UpdateServiceAccessPoliciesCommand";
/**
* <fullname>Amazon CloudSearch Configuration Service</fullname>
* <p>You use the Amazon CloudSearch configuration service to create, configure, and manage search domains.
* Configuration service requests are submitted using the AWS Query protocol. AWS Query requests
* are HTTP or HTTPS requests submitted via HTTP GET or POST with a query parameter named Action.</p>
* <p>The endpoint for configuration service requests is region-specific: cloudsearch.<i>region</i>.amazonaws.com.
* For example, cloudsearch.us-east-1.amazonaws.com. For a current list of supported regions and endpoints,
* see <a href="http://docs.aws.amazon.com/general/latest/gr/rande.html#cloudsearch_region" target="_blank">Regions and Endpoints</a>.</p>
*/
export class CloudSearch extends CloudSearchClient {
/**
* <p>Indexes the search suggestions. For more information, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/getting-suggestions.html#configuring-suggesters">Configuring Suggesters</a> in the <i>Amazon CloudSearch Developer Guide</i>.</p>
*/
public buildSuggesters(
args: BuildSuggestersCommandInput,
options?: __HttpHandlerOptions
): Promise<BuildSuggestersCommandOutput>;
public buildSuggesters(
args: BuildSuggestersCommandInput,
cb: (err: any, data?: BuildSuggestersCommandOutput) => void
): void;
public buildSuggesters(
args: BuildSuggestersCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: BuildSuggestersCommandOutput) => void
): void;
public buildSuggesters(
args: BuildSuggestersCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: BuildSuggestersCommandOutput) => void),
cb?: (err: any, data?: BuildSuggestersCommandOutput) => void
): Promise<BuildSuggestersCommandOutput> | void {
const command = new BuildSuggestersCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Creates a new search domain. For more information,
* see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/creating-domains.html" target="_blank">Creating a Search Domain</a> in the <i>Amazon CloudSearch Developer Guide</i>.</p>
*/
public createDomain(
args: CreateDomainCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateDomainCommandOutput>;
public createDomain(args: CreateDomainCommandInput, cb: (err: any, data?: CreateDomainCommandOutput) => void): void;
public createDomain(
args: CreateDomainCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateDomainCommandOutput) => void
): void;
public createDomain(
args: CreateDomainCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateDomainCommandOutput) => void),
cb?: (err: any, data?: CreateDomainCommandOutput) => void
): Promise<CreateDomainCommandOutput> | void {
const command = new CreateDomainCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Configures an analysis scheme that can be applied to a <code>text</code> or <code>text-array</code> field to define language-specific text processing options. For more information, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-analysis-schemes.html" target="_blank">Configuring Analysis Schemes</a> in the <i>Amazon CloudSearch Developer Guide</i>.</p>
*/
public defineAnalysisScheme(
args: DefineAnalysisSchemeCommandInput,
options?: __HttpHandlerOptions
): Promise<DefineAnalysisSchemeCommandOutput>;
public defineAnalysisScheme(
args: DefineAnalysisSchemeCommandInput,
cb: (err: any, data?: DefineAnalysisSchemeCommandOutput) => void
): void;
public defineAnalysisScheme(
args: DefineAnalysisSchemeCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DefineAnalysisSchemeCommandOutput) => void
): void;
public defineAnalysisScheme(
args: DefineAnalysisSchemeCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DefineAnalysisSchemeCommandOutput) => void),
cb?: (err: any, data?: DefineAnalysisSchemeCommandOutput) => void
): Promise<DefineAnalysisSchemeCommandOutput> | void {
const command = new DefineAnalysisSchemeCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Configures an <code><a>Expression</a></code> for the search domain. Used to create new expressions and modify existing ones. If the expression exists, the new configuration replaces the old one. For more information, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-expressions.html" target="_blank">Configuring Expressions</a> in the <i>Amazon CloudSearch Developer Guide</i>.</p>
*/
public defineExpression(
args: DefineExpressionCommandInput,
options?: __HttpHandlerOptions
): Promise<DefineExpressionCommandOutput>;
public defineExpression(
args: DefineExpressionCommandInput,
cb: (err: any, data?: DefineExpressionCommandOutput) => void
): void;
public defineExpression(
args: DefineExpressionCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DefineExpressionCommandOutput) => void
): void;
public defineExpression(
args: DefineExpressionCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DefineExpressionCommandOutput) => void),
cb?: (err: any, data?: DefineExpressionCommandOutput) => void
): Promise<DefineExpressionCommandOutput> | void {
const command = new DefineExpressionCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Configures an <code><a>IndexField</a></code> for the search domain. Used to create new fields and modify existing ones. You must specify the name of the domain you are configuring and an index field configuration. The index field configuration specifies a unique name, the index field type, and the options you want to configure for the field. The options you can specify depend on the <code><a>IndexFieldType</a></code>. If the field exists, the new configuration replaces the old one. For more information, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-index-fields.html" target="_blank">Configuring Index Fields</a> in the <i>Amazon CloudSearch Developer Guide</i>. </p>
*/
public defineIndexField(
args: DefineIndexFieldCommandInput,
options?: __HttpHandlerOptions
): Promise<DefineIndexFieldCommandOutput>;
public defineIndexField(
args: DefineIndexFieldCommandInput,
cb: (err: any, data?: DefineIndexFieldCommandOutput) => void
): void;
public defineIndexField(
args: DefineIndexFieldCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DefineIndexFieldCommandOutput) => void
): void;
public defineIndexField(
args: DefineIndexFieldCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DefineIndexFieldCommandOutput) => void),
cb?: (err: any, data?: DefineIndexFieldCommandOutput) => void
): Promise<DefineIndexFieldCommandOutput> | void {
const command = new DefineIndexFieldCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Configures a suggester for a domain. A suggester enables you to display possible matches before users finish typing their queries. When you configure a suggester, you must specify the name of the text field you want to search for possible matches and a unique name for the suggester. For more information, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/getting-suggestions.html" target="_blank">Getting Search Suggestions</a> in the <i>Amazon CloudSearch Developer Guide</i>.</p>
*/
public defineSuggester(
args: DefineSuggesterCommandInput,
options?: __HttpHandlerOptions
): Promise<DefineSuggesterCommandOutput>;
public defineSuggester(
args: DefineSuggesterCommandInput,
cb: (err: any, data?: DefineSuggesterCommandOutput) => void
): void;
public defineSuggester(
args: DefineSuggesterCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DefineSuggesterCommandOutput) => void
): void;
public defineSuggester(
args: DefineSuggesterCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DefineSuggesterCommandOutput) => void),
cb?: (err: any, data?: DefineSuggesterCommandOutput) => void
): Promise<DefineSuggesterCommandOutput> | void {
const command = new DefineSuggesterCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deletes an analysis scheme. For more information, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-analysis-schemes.html" target="_blank">Configuring Analysis Schemes</a> in the <i>Amazon CloudSearch Developer Guide</i>. </p>
*/
public deleteAnalysisScheme(
args: DeleteAnalysisSchemeCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteAnalysisSchemeCommandOutput>;
public deleteAnalysisScheme(
args: DeleteAnalysisSchemeCommandInput,
cb: (err: any, data?: DeleteAnalysisSchemeCommandOutput) => void
): void;
public deleteAnalysisScheme(
args: DeleteAnalysisSchemeCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteAnalysisSchemeCommandOutput) => void
): void;
public deleteAnalysisScheme(
args: DeleteAnalysisSchemeCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteAnalysisSchemeCommandOutput) => void),
cb?: (err: any, data?: DeleteAnalysisSchemeCommandOutput) => void
): Promise<DeleteAnalysisSchemeCommandOutput> | void {
const command = new DeleteAnalysisSchemeCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Permanently deletes a search domain and all of its data. Once a domain has been deleted, it cannot be recovered. For more information,
* see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/deleting-domains.html" target="_blank">Deleting a Search Domain</a> in the <i>Amazon CloudSearch Developer Guide</i>. </p>
*/
public deleteDomain(
args: DeleteDomainCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteDomainCommandOutput>;
public deleteDomain(args: DeleteDomainCommandInput, cb: (err: any, data?: DeleteDomainCommandOutput) => void): void;
public deleteDomain(
args: DeleteDomainCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteDomainCommandOutput) => void
): void;
public deleteDomain(
args: DeleteDomainCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteDomainCommandOutput) => void),
cb?: (err: any, data?: DeleteDomainCommandOutput) => void
): Promise<DeleteDomainCommandOutput> | void {
const command = new DeleteDomainCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Removes an <code><a>Expression</a></code> from the search domain. For more information, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-expressions.html" target="_blank">Configuring Expressions</a> in the <i>Amazon CloudSearch Developer Guide</i>.</p>
*/
public deleteExpression(
args: DeleteExpressionCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteExpressionCommandOutput>;
public deleteExpression(
args: DeleteExpressionCommandInput,
cb: (err: any, data?: DeleteExpressionCommandOutput) => void
): void;
public deleteExpression(
args: DeleteExpressionCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteExpressionCommandOutput) => void
): void;
public deleteExpression(
args: DeleteExpressionCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteExpressionCommandOutput) => void),
cb?: (err: any, data?: DeleteExpressionCommandOutput) => void
): Promise<DeleteExpressionCommandOutput> | void {
const command = new DeleteExpressionCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Removes an <code><a>IndexField</a></code> from the search domain. For more information, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-index-fields.html" target="_blank">Configuring Index Fields</a> in the <i>Amazon CloudSearch Developer Guide</i>.</p>
*/
public deleteIndexField(
args: DeleteIndexFieldCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteIndexFieldCommandOutput>;
public deleteIndexField(
args: DeleteIndexFieldCommandInput,
cb: (err: any, data?: DeleteIndexFieldCommandOutput) => void
): void;
public deleteIndexField(
args: DeleteIndexFieldCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteIndexFieldCommandOutput) => void
): void;
public deleteIndexField(
args: DeleteIndexFieldCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteIndexFieldCommandOutput) => void),
cb?: (err: any, data?: DeleteIndexFieldCommandOutput) => void
): Promise<DeleteIndexFieldCommandOutput> | void {
const command = new DeleteIndexFieldCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deletes a suggester. For more information, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/getting-suggestions.html" target="_blank">Getting Search Suggestions</a> in the <i>Amazon CloudSearch Developer Guide</i>.</p>
*/
public deleteSuggester(
args: DeleteSuggesterCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteSuggesterCommandOutput>;
public deleteSuggester(
args: DeleteSuggesterCommandInput,
cb: (err: any, data?: DeleteSuggesterCommandOutput) => void
): void;
public deleteSuggester(
args: DeleteSuggesterCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteSuggesterCommandOutput) => void
): void;
public deleteSuggester(
args: DeleteSuggesterCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteSuggesterCommandOutput) => void),
cb?: (err: any, data?: DeleteSuggesterCommandOutput) => void
): Promise<DeleteSuggesterCommandOutput> | void {
const command = new DeleteSuggesterCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Gets the analysis schemes configured for a domain. An analysis scheme defines language-specific text processing options for a <code>text</code> field. Can be limited to specific analysis schemes by name. By default, shows all analysis schemes and includes any pending changes to the configuration. Set the <code>Deployed</code> option to <code>true</code> to show the active configuration and exclude pending changes. For more information, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-analysis-schemes.html" target="_blank">Configuring Analysis Schemes</a> in the <i>Amazon CloudSearch Developer Guide</i>.</p>
*/
public describeAnalysisSchemes(
args: DescribeAnalysisSchemesCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeAnalysisSchemesCommandOutput>;
public describeAnalysisSchemes(
args: DescribeAnalysisSchemesCommandInput,
cb: (err: any, data?: DescribeAnalysisSchemesCommandOutput) => void
): void;
public describeAnalysisSchemes(
args: DescribeAnalysisSchemesCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeAnalysisSchemesCommandOutput) => void
): void;
public describeAnalysisSchemes(
args: DescribeAnalysisSchemesCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeAnalysisSchemesCommandOutput) => void),
cb?: (err: any, data?: DescribeAnalysisSchemesCommandOutput) => void
): Promise<DescribeAnalysisSchemesCommandOutput> | void {
const command = new DescribeAnalysisSchemesCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Gets the availability options configured for a domain. By default, shows the configuration with any pending changes. Set the <code>Deployed</code> option to <code>true</code> to show the active configuration and exclude pending changes. For more information, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-availability-options.html" target="_blank">Configuring Availability Options</a> in the <i>Amazon CloudSearch Developer Guide</i>.</p>
*/
public describeAvailabilityOptions(
args: DescribeAvailabilityOptionsCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeAvailabilityOptionsCommandOutput>;
public describeAvailabilityOptions(
args: DescribeAvailabilityOptionsCommandInput,
cb: (err: any, data?: DescribeAvailabilityOptionsCommandOutput) => void
): void;
public describeAvailabilityOptions(
args: DescribeAvailabilityOptionsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeAvailabilityOptionsCommandOutput) => void
): void;
public describeAvailabilityOptions(
args: DescribeAvailabilityOptionsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeAvailabilityOptionsCommandOutput) => void),
cb?: (err: any, data?: DescribeAvailabilityOptionsCommandOutput) => void
): Promise<DescribeAvailabilityOptionsCommandOutput> | void {
const command = new DescribeAvailabilityOptionsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Returns the domain's endpoint options, specifically whether all requests to the domain must arrive over HTTPS. For more information, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-domain-endpoint-options.html" target="_blank">Configuring Domain Endpoint Options</a> in the <i>Amazon CloudSearch Developer Guide</i>.</p>
*/
public describeDomainEndpointOptions(
args: DescribeDomainEndpointOptionsCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeDomainEndpointOptionsCommandOutput>;
public describeDomainEndpointOptions(
args: DescribeDomainEndpointOptionsCommandInput,
cb: (err: any, data?: DescribeDomainEndpointOptionsCommandOutput) => void
): void;
public describeDomainEndpointOptions(
args: DescribeDomainEndpointOptionsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeDomainEndpointOptionsCommandOutput) => void
): void;
public describeDomainEndpointOptions(
args: DescribeDomainEndpointOptionsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeDomainEndpointOptionsCommandOutput) => void),
cb?: (err: any, data?: DescribeDomainEndpointOptionsCommandOutput) => void
): Promise<DescribeDomainEndpointOptionsCommandOutput> | void {
const command = new DescribeDomainEndpointOptionsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Gets information about the search domains owned by this account. Can be limited to specific domains. Shows
* all domains by default. To get the number of searchable documents in a domain, use the console or submit a <code>matchall</code> request to your domain's search endpoint: <code>q=matchall&q.parser=structured&size=0</code>. For more information,
* see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/getting-domain-info.html" target="_blank">Getting Information about a Search Domain</a> in the <i>Amazon CloudSearch Developer Guide</i>.</p>
*/
public describeDomains(
args: DescribeDomainsCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeDomainsCommandOutput>;
public describeDomains(
args: DescribeDomainsCommandInput,
cb: (err: any, data?: DescribeDomainsCommandOutput) => void
): void;
public describeDomains(
args: DescribeDomainsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeDomainsCommandOutput) => void
): void;
public describeDomains(
args: DescribeDomainsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeDomainsCommandOutput) => void),
cb?: (err: any, data?: DescribeDomainsCommandOutput) => void
): Promise<DescribeDomainsCommandOutput> | void {
const command = new DescribeDomainsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Gets the expressions configured for the search domain. Can be limited to specific expressions by name. By default, shows all expressions and includes any pending changes to the configuration. Set the <code>Deployed</code> option to <code>true</code> to show the active configuration and exclude pending changes. For more information, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-expressions.html" target="_blank">Configuring Expressions</a> in the <i>Amazon CloudSearch Developer Guide</i>.</p>
*/
public describeExpressions(
args: DescribeExpressionsCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeExpressionsCommandOutput>;
public describeExpressions(
args: DescribeExpressionsCommandInput,
cb: (err: any, data?: DescribeExpressionsCommandOutput) => void
): void;
public describeExpressions(
args: DescribeExpressionsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeExpressionsCommandOutput) => void
): void;
public describeExpressions(
args: DescribeExpressionsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeExpressionsCommandOutput) => void),
cb?: (err: any, data?: DescribeExpressionsCommandOutput) => void
): Promise<DescribeExpressionsCommandOutput> | void {
const command = new DescribeExpressionsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Gets information about the index fields configured for the search domain.
* Can be limited to specific fields by name. By default, shows all fields and includes any pending changes to the configuration. Set the <code>Deployed</code> option to <code>true</code> to show the active configuration and exclude pending changes. For more information,
* see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/getting-domain-info.html" target="_blank">Getting Domain Information</a> in the <i>Amazon CloudSearch Developer Guide</i>.</p>
*/
public describeIndexFields(
args: DescribeIndexFieldsCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeIndexFieldsCommandOutput>;
public describeIndexFields(
args: DescribeIndexFieldsCommandInput,
cb: (err: any, data?: DescribeIndexFieldsCommandOutput) => void
): void;
public describeIndexFields(
args: DescribeIndexFieldsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeIndexFieldsCommandOutput) => void
): void;
public describeIndexFields(
args: DescribeIndexFieldsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeIndexFieldsCommandOutput) => void),
cb?: (err: any, data?: DescribeIndexFieldsCommandOutput) => void
): Promise<DescribeIndexFieldsCommandOutput> | void {
const command = new DescribeIndexFieldsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Gets the scaling parameters configured for a domain. A domain's scaling parameters specify the desired search instance type and replication count. For more information, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-scaling-options.html" target="_blank">Configuring Scaling Options</a> in the <i>Amazon CloudSearch Developer Guide</i>.</p>
*/
public describeScalingParameters(
args: DescribeScalingParametersCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeScalingParametersCommandOutput>;
public describeScalingParameters(
args: DescribeScalingParametersCommandInput,
cb: (err: any, data?: DescribeScalingParametersCommandOutput) => void
): void;
public describeScalingParameters(
args: DescribeScalingParametersCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeScalingParametersCommandOutput) => void
): void;
public describeScalingParameters(
args: DescribeScalingParametersCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeScalingParametersCommandOutput) => void),
cb?: (err: any, data?: DescribeScalingParametersCommandOutput) => void
): Promise<DescribeScalingParametersCommandOutput> | void {
const command = new DescribeScalingParametersCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Gets information about the access policies that control access to the domain's document and search endpoints. By default, shows the configuration with any pending changes. Set the <code>Deployed</code> option to <code>true</code> to show the active configuration and exclude pending changes. For more information,
* see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-access.html" target="_blank">Configuring Access for a Search Domain</a> in the <i>Amazon CloudSearch Developer Guide</i>.</p>
*/
public describeServiceAccessPolicies(
args: DescribeServiceAccessPoliciesCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeServiceAccessPoliciesCommandOutput>;
public describeServiceAccessPolicies(
args: DescribeServiceAccessPoliciesCommandInput,
cb: (err: any, data?: DescribeServiceAccessPoliciesCommandOutput) => void
): void;
public describeServiceAccessPolicies(
args: DescribeServiceAccessPoliciesCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeServiceAccessPoliciesCommandOutput) => void
): void;
public describeServiceAccessPolicies(
args: DescribeServiceAccessPoliciesCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeServiceAccessPoliciesCommandOutput) => void),
cb?: (err: any, data?: DescribeServiceAccessPoliciesCommandOutput) => void
): Promise<DescribeServiceAccessPoliciesCommandOutput> | void {
const command = new DescribeServiceAccessPoliciesCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Gets the suggesters configured for a domain. A suggester enables you to display possible matches before users finish typing their queries. Can be limited to specific suggesters by name. By default, shows all suggesters and includes any pending changes to the configuration. Set the <code>Deployed</code> option to <code>true</code> to show the active configuration and exclude pending changes. For more information, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/getting-suggestions.html" target="_blank">Getting Search Suggestions</a> in the <i>Amazon CloudSearch Developer Guide</i>.</p>
*/
public describeSuggesters(
args: DescribeSuggestersCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeSuggestersCommandOutput>;
public describeSuggesters(
args: DescribeSuggestersCommandInput,
cb: (err: any, data?: DescribeSuggestersCommandOutput) => void
): void;
public describeSuggesters(
args: DescribeSuggestersCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeSuggestersCommandOutput) => void
): void;
public describeSuggesters(
args: DescribeSuggestersCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeSuggestersCommandOutput) => void),
cb?: (err: any, data?: DescribeSuggestersCommandOutput) => void
): Promise<DescribeSuggestersCommandOutput> | void {
const command = new DescribeSuggestersCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Tells the search domain to start indexing its documents using the latest indexing options. This operation must be invoked to activate options whose <a>OptionStatus</a> is <code>RequiresIndexDocuments</code>.</p>
*/
public indexDocuments(
args: IndexDocumentsCommandInput,
options?: __HttpHandlerOptions
): Promise<IndexDocumentsCommandOutput>;
public indexDocuments(
args: IndexDocumentsCommandInput,
cb: (err: any, data?: IndexDocumentsCommandOutput) => void
): void;
public indexDocuments(
args: IndexDocumentsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: IndexDocumentsCommandOutput) => void
): void;
public indexDocuments(
args: IndexDocumentsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: IndexDocumentsCommandOutput) => void),
cb?: (err: any, data?: IndexDocumentsCommandOutput) => void
): Promise<IndexDocumentsCommandOutput> | void {
const command = new IndexDocumentsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Lists all search domains owned by an account.</p>
*/
public listDomainNames(
args: ListDomainNamesCommandInput,
options?: __HttpHandlerOptions
): Promise<ListDomainNamesCommandOutput>;
public listDomainNames(
args: ListDomainNamesCommandInput,
cb: (err: any, data?: ListDomainNamesCommandOutput) => void
): void;
public listDomainNames(
args: ListDomainNamesCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListDomainNamesCommandOutput) => void
): void;
public listDomainNames(
args: ListDomainNamesCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListDomainNamesCommandOutput) => void),
cb?: (err: any, data?: ListDomainNamesCommandOutput) => void
): Promise<ListDomainNamesCommandOutput> | void {
const command = new ListDomainNamesCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Configures the availability options for a domain. Enabling the Multi-AZ option expands an Amazon CloudSearch domain to an additional Availability Zone in the same Region to increase fault tolerance in the event of a service disruption. Changes to the Multi-AZ option can take about half an hour to become active. For more information, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-availability-options.html" target="_blank">Configuring Availability Options</a> in the <i>Amazon CloudSearch Developer Guide</i>.</p>
*/
public updateAvailabilityOptions(
args: UpdateAvailabilityOptionsCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateAvailabilityOptionsCommandOutput>;
public updateAvailabilityOptions(
args: UpdateAvailabilityOptionsCommandInput,
cb: (err: any, data?: UpdateAvailabilityOptionsCommandOutput) => void
): void;
public updateAvailabilityOptions(
args: UpdateAvailabilityOptionsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateAvailabilityOptionsCommandOutput) => void
): void;
public updateAvailabilityOptions(
args: UpdateAvailabilityOptionsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateAvailabilityOptionsCommandOutput) => void),
cb?: (err: any, data?: UpdateAvailabilityOptionsCommandOutput) => void
): Promise<UpdateAvailabilityOptionsCommandOutput> | void {
const command = new UpdateAvailabilityOptionsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Updates the domain's endpoint options, specifically whether all requests to the domain must arrive over HTTPS. For more information, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-domain-endpoint-options.html" target="_blank">Configuring Domain Endpoint Options</a> in the <i>Amazon CloudSearch Developer Guide</i>.</p>
*/
public updateDomainEndpointOptions(
args: UpdateDomainEndpointOptionsCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateDomainEndpointOptionsCommandOutput>;
public updateDomainEndpointOptions(
args: UpdateDomainEndpointOptionsCommandInput,
cb: (err: any, data?: UpdateDomainEndpointOptionsCommandOutput) => void
): void;
public updateDomainEndpointOptions(
args: UpdateDomainEndpointOptionsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateDomainEndpointOptionsCommandOutput) => void
): void;
public updateDomainEndpointOptions(
args: UpdateDomainEndpointOptionsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateDomainEndpointOptionsCommandOutput) => void),
cb?: (err: any, data?: UpdateDomainEndpointOptionsCommandOutput) => void
): Promise<UpdateDomainEndpointOptionsCommandOutput> | void {
const command = new UpdateDomainEndpointOptionsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Configures scaling parameters for a domain. A domain's scaling parameters specify the desired search instance type and replication count. Amazon CloudSearch will still automatically scale your domain based on the volume of data and traffic, but not below the desired instance type and replication count. If the Multi-AZ option is enabled, these values control the resources used per Availability Zone. For more information, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-scaling-options.html" target="_blank">Configuring Scaling Options</a> in the <i>Amazon CloudSearch Developer Guide</i>. </p>
*/
public updateScalingParameters(
args: UpdateScalingParametersCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateScalingParametersCommandOutput>;
public updateScalingParameters(
args: UpdateScalingParametersCommandInput,
cb: (err: any, data?: UpdateScalingParametersCommandOutput) => void
): void;
public updateScalingParameters(
args: UpdateScalingParametersCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateScalingParametersCommandOutput) => void
): void;
public updateScalingParameters(
args: UpdateScalingParametersCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateScalingParametersCommandOutput) => void),
cb?: (err: any, data?: UpdateScalingParametersCommandOutput) => void
): Promise<UpdateScalingParametersCommandOutput> | void {
const command = new UpdateScalingParametersCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Configures the access rules that control access to the domain's document and search endpoints.
* For more information, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-access.html" target="_blank">
* Configuring Access for an Amazon CloudSearch Domain</a>.</p>
*/
public updateServiceAccessPolicies(
args: UpdateServiceAccessPoliciesCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateServiceAccessPoliciesCommandOutput>;
public updateServiceAccessPolicies(
args: UpdateServiceAccessPoliciesCommandInput,
cb: (err: any, data?: UpdateServiceAccessPoliciesCommandOutput) => void
): void;
public updateServiceAccessPolicies(
args: UpdateServiceAccessPoliciesCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateServiceAccessPoliciesCommandOutput) => void
): void;
public updateServiceAccessPolicies(
args: UpdateServiceAccessPoliciesCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateServiceAccessPoliciesCommandOutput) => void),
cb?: (err: any, data?: UpdateServiceAccessPoliciesCommandOutput) => void
): Promise<UpdateServiceAccessPoliciesCommandOutput> | void {
const command = new UpdateServiceAccessPoliciesCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
} | the_stack |
'use strict';
import { DebugProtocolVariable, DebugProtocolVariableContainer, Uri } from 'vscode';
import { IServerState } from '../../../datascience-ui/interactive-common/mainState';
import type { KernelMessage } from '@jupyterlab/services';
import {
CommonActionType,
ILoadIPyWidgetClassFailureAction,
IVariableExplorerHeight,
LoadIPyWidgetClassLoadAction,
NotifyIPyWidgeWidgetVersionNotSupportedAction
} from '../../../datascience-ui/interactive-common/redux/reducers/types';
import { NativeKeyboardCommandTelemetry, NativeMouseCommandTelemetry } from '../constants';
import { WidgetScriptSource } from '../ipywidgets/types';
import { KernelConnectionMetadata } from '../jupyter/kernels/types';
import { CssMessages, IGetCssRequest, IGetCssResponse, SharedMessages } from '../messages';
import {
ICell,
IJupyterVariable,
IJupyterVariablesRequest,
IJupyterVariablesResponse,
KernelSocketOptions
} from '../types';
import { BaseReduxActionPayload } from './types';
export enum InteractiveWindowMessages {
FinishCell = 'finish_cell',
RestartKernel = 'restart_kernel',
Interrupt = 'interrupt',
SettingsUpdated = 'settings_updated',
Started = 'started',
ConvertUriForUseInWebViewRequest = 'ConvertUriForUseInWebViewRequest',
ConvertUriForUseInWebViewResponse = 'ConvertUriForUseInWebViewResponse',
Activate = 'activate',
ShowDataViewer = 'show_data_explorer',
GetVariablesRequest = 'get_variables_request',
GetVariablesResponse = 'get_variables_response',
VariableExplorerToggle = 'variable_explorer_toggle',
SetVariableExplorerHeight = 'set_variable_explorer_height',
VariableExplorerHeightResponse = 'variable_explorer_height_response',
ForceVariableRefresh = 'force_variable_refresh',
UpdateVariableViewExecutionCount = 'update_variable_view_execution_count',
Sync = 'sync_message_used_to_broadcast_and_sync_editors',
OpenLink = 'open_link',
SavePng = 'save_png',
NotebookClose = 'close',
NativeCommand = 'native_command',
VariablesComplete = 'variables_complete',
ExecutionRendered = 'rendered_execution',
SelectKernel = 'select_kernel',
SelectJupyterServer = 'select_jupyter_server',
UpdateModel = 'update_model',
ReceivedUpdateModel = 'received_update_model',
OpenSettings = 'open_settings',
IPyWidgetLoadSuccess = 'ipywidget_load_success',
IPyWidgetLoadFailure = 'ipywidget_load_failure',
IPyWidgetRenderFailure = 'ipywidget_render_failure',
IPyWidgetUnhandledKernelMessage = 'ipywidget_unhandled_kernel_message',
IPyWidgetWidgetVersionNotSupported = 'ipywidget_widget_version_not_supported',
KernelIdle = 'kernel_idle',
GetHTMLByIdRequest = 'get_html_by_id_request',
GetHTMLByIdResponse = 'get_html_by_id_response'
}
export enum IPyWidgetMessages {
IPyWidgets_IsReadyRequest = 'IPyWidgets_IsReadyRequest',
IPyWidgets_Ready = 'IPyWidgets_Ready',
IPyWidgets_onRestartKernel = 'IPyWidgets_onRestartKernel',
IPyWidgets_onKernelChanged = 'IPyWidgets_onKernelChanged',
IPyWidgets_updateRequireConfig = 'IPyWidgets_updateRequireConfig',
/**
* UI sends a request to extension to determine whether we have the source for any of the widgets.
*/
IPyWidgets_WidgetScriptSourceRequest = 'IPyWidgets_WidgetScriptSourceRequest',
/**
* Extension sends response to the request with yes/no.
*/
IPyWidgets_WidgetScriptSourceResponse = 'IPyWidgets_WidgetScriptSource_Response',
IPyWidgets_msg = 'IPyWidgets_msg',
IPyWidgets_binary_msg = 'IPyWidgets_binary_msg',
// Message was received by the widget kernel and added to the msgChain queue for processing
IPyWidgets_msg_received = 'IPyWidgets_msg_received',
// IOPub message was fully handled by the widget kernel
IPyWidgets_iopub_msg_handled = 'IPyWidgets_iopub_msg_handled',
IPyWidgets_kernelOptions = 'IPyWidgets_kernelOptions',
IPyWidgets_registerCommTarget = 'IPyWidgets_registerCommTarget',
IPyWidgets_RegisterMessageHook = 'IPyWidgets_RegisterMessageHook',
// Message sent when the extension has finished an operation requested by the kernel UI for processing a message
IPyWidgets_ExtensionOperationHandled = 'IPyWidgets_ExtensionOperationHandled',
IPyWidgets_RemoveMessageHook = 'IPyWidgets_RemoveMessageHook',
IPyWidgets_MessageHookCall = 'IPyWidgets_MessageHookCall',
IPyWidgets_MessageHookResult = 'IPyWidgets_MessageHookResult',
IPyWidgets_mirror_execute = 'IPyWidgets_mirror_execute'
}
export enum SysInfoReason {
Start,
Restart,
Interrupt,
New,
Connect
}
export interface IFinishCell {
cell: ICell;
notebookIdentity: Uri;
}
export interface ISubmitNewCell {
code: string;
id: string;
}
export interface IShowDataViewer {
variable: IJupyterVariable;
columnSize: number;
}
export interface IShowDataViewerFromVariablePanel {
container: DebugProtocolVariableContainer | undefined;
variable: DebugProtocolVariable;
}
export interface INotebookIdentity {
resource: Uri;
type: 'interactive' | 'native';
}
export interface INativeCommand {
command: NativeKeyboardCommandTelemetry | NativeMouseCommandTelemetry;
}
export interface INotebookModelChange {
oldDirty: boolean;
newDirty: boolean;
source: 'undo' | 'user' | 'redo';
}
export interface INotebookModelSaved extends INotebookModelChange {
kind: 'save';
}
export interface INotebookModelSavedAs extends INotebookModelChange {
kind: 'saveAs';
target: Uri;
sourceUri: Uri;
}
export interface INotebookModelRemoveAllChange extends INotebookModelChange {
kind: 'remove_all';
oldCells: ICell[];
newCellId: string;
}
export interface INotebookModelModifyChange extends INotebookModelChange {
kind: 'modify';
newCells: ICell[];
oldCells: ICell[];
}
export interface INotebookModelCellExecutionCountChange extends INotebookModelChange {
kind: 'updateCellExecutionCount';
cellId: string;
executionCount?: number;
}
export interface INotebookModelClearChange extends INotebookModelChange {
kind: 'clear';
oldCells: ICell[];
}
export interface INotebookModelSwapChange extends INotebookModelChange {
kind: 'swap';
firstCellId: string;
secondCellId: string;
}
export interface INotebookModelRemoveChange extends INotebookModelChange {
kind: 'remove';
cell: ICell;
index: number;
}
export interface INotebookModelInsertChange extends INotebookModelChange {
kind: 'insert';
cell: ICell;
index: number;
codeCellAboveId?: string;
}
export interface INotebookModelAddChange extends INotebookModelChange {
kind: 'add';
cell: ICell;
fullText: string;
currentText: string;
}
export interface INotebookModelChangeTypeChange extends INotebookModelChange {
kind: 'changeCellType';
cell: ICell;
}
export interface IEditorPosition {
/**
* line number (starts at 1)
*/
readonly lineNumber: number;
/**
* column (the first character in a line is between column 1 and column 2)
*/
readonly column: number;
}
export interface IEditorRange {
/**
* Line number on which the range starts (starts at 1).
*/
readonly startLineNumber: number;
/**
* Column on which the range starts in line `startLineNumber` (starts at 1).
*/
readonly startColumn: number;
/**
* Line number on which the range ends.
*/
readonly endLineNumber: number;
/**
* Column on which the range ends in line `endLineNumber`.
*/
readonly endColumn: number;
}
export interface IEditorContentChange {
/**
* The range that got replaced.
*/
readonly range: IEditorRange;
/**
* The offset of the range that got replaced.
*/
readonly rangeOffset: number;
/**
* The length of the range that got replaced.
*/
readonly rangeLength: number;
/**
* The new text for the range.
*/
readonly text: string;
/**
* The cursor position to be set after the change
*/
readonly position: IEditorPosition;
}
export interface INotebookModelEditChange extends INotebookModelChange {
kind: 'edit';
forward: IEditorContentChange[];
reverse: IEditorContentChange[];
id: string;
}
export interface INotebookModelVersionChange extends INotebookModelChange {
kind: 'version';
kernelConnection?: KernelConnectionMetadata;
}
export type NotebookModelChange =
| INotebookModelSaved
| INotebookModelSavedAs
| INotebookModelModifyChange
| INotebookModelRemoveAllChange
| INotebookModelClearChange
| INotebookModelSwapChange
| INotebookModelRemoveChange
| INotebookModelInsertChange
| INotebookModelAddChange
| INotebookModelEditChange
| INotebookModelVersionChange
| INotebookModelChangeTypeChange
| INotebookModelCellExecutionCountChange;
// Map all messages to specific payloads
export class IInteractiveWindowMapping {
public [IPyWidgetMessages.IPyWidgets_kernelOptions]: KernelSocketOptions;
public [IPyWidgetMessages.IPyWidgets_WidgetScriptSourceRequest]: { moduleName: string; moduleVersion: string };
public [IPyWidgetMessages.IPyWidgets_WidgetScriptSourceResponse]: WidgetScriptSource;
public [IPyWidgetMessages.IPyWidgets_Ready]: never | undefined;
public [IPyWidgetMessages.IPyWidgets_onRestartKernel]: never | undefined;
public [IPyWidgetMessages.IPyWidgets_onKernelChanged]: never | undefined;
public [IPyWidgetMessages.IPyWidgets_registerCommTarget]: string;
public [IPyWidgetMessages.IPyWidgets_binary_msg]:
| ((ArrayBuffer | ArrayBufferView)[] | undefined)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
| { id: string; data: any };
public [IPyWidgetMessages.IPyWidgets_msg]: { id: string; data: string };
public [IPyWidgetMessages.IPyWidgets_msg_received]: { id: string };
public [IPyWidgetMessages.IPyWidgets_iopub_msg_handled]: { id: string };
public [IPyWidgetMessages.IPyWidgets_RegisterMessageHook]: string;
public [IPyWidgetMessages.IPyWidgets_ExtensionOperationHandled]: { id: string; type: IPyWidgetMessages };
public [IPyWidgetMessages.IPyWidgets_RemoveMessageHook]: { hookMsgId: string; lastHookedMsgId: string | undefined };
public [IPyWidgetMessages.IPyWidgets_MessageHookCall]: {
requestId: string;
parentId: string;
msg: KernelMessage.IIOPubMessage;
};
public [IPyWidgetMessages.IPyWidgets_MessageHookResult]: {
requestId: string;
parentId: string;
msgType: string;
result: boolean;
};
public [IPyWidgetMessages.IPyWidgets_mirror_execute]: { id: string; msg: KernelMessage.IExecuteRequestMsg };
public [InteractiveWindowMessages.ForceVariableRefresh]: never | undefined;
public [InteractiveWindowMessages.UpdateVariableViewExecutionCount]: { executionCount: number };
public [InteractiveWindowMessages.FinishCell]: IFinishCell;
public [InteractiveWindowMessages.RestartKernel]: never | undefined;
public [InteractiveWindowMessages.SelectKernel]: IServerState | undefined;
public [InteractiveWindowMessages.SelectJupyterServer]: never | undefined;
public [InteractiveWindowMessages.OpenSettings]: string | undefined;
public [InteractiveWindowMessages.Interrupt]: never | undefined;
public [InteractiveWindowMessages.SettingsUpdated]: string;
public [InteractiveWindowMessages.Started]: never | undefined;
public [InteractiveWindowMessages.Activate]: never | undefined;
public [InteractiveWindowMessages.ShowDataViewer]: IShowDataViewer;
public [InteractiveWindowMessages.GetVariablesRequest]: IJupyterVariablesRequest;
public [InteractiveWindowMessages.GetVariablesResponse]: IJupyterVariablesResponse;
public [InteractiveWindowMessages.VariableExplorerToggle]: boolean;
public [InteractiveWindowMessages.SetVariableExplorerHeight]: IVariableExplorerHeight;
public [InteractiveWindowMessages.VariableExplorerHeightResponse]: IVariableExplorerHeight;
public [CssMessages.GetCssRequest]: IGetCssRequest;
public [CssMessages.GetCssResponse]: IGetCssResponse;
public [InteractiveWindowMessages.OpenLink]: string | undefined;
public [InteractiveWindowMessages.SavePng]: string | undefined;
public [InteractiveWindowMessages.NotebookClose]: INotebookIdentity;
public [InteractiveWindowMessages.Sync]: {
type: InteractiveWindowMessages | SharedMessages | CommonActionType;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
payload: BaseReduxActionPayload<any>;
};
public [InteractiveWindowMessages.NativeCommand]: INativeCommand;
public [InteractiveWindowMessages.VariablesComplete]: never | undefined;
public [InteractiveWindowMessages.ExecutionRendered]: never | undefined;
public [InteractiveWindowMessages.UpdateModel]: NotebookModelChange;
public [InteractiveWindowMessages.ReceivedUpdateModel]: never | undefined;
public [SharedMessages.UpdateSettings]: string;
public [SharedMessages.LocInit]: string;
public [InteractiveWindowMessages.IPyWidgetLoadSuccess]: LoadIPyWidgetClassLoadAction;
public [InteractiveWindowMessages.IPyWidgetLoadFailure]: ILoadIPyWidgetClassFailureAction;
public [InteractiveWindowMessages.IPyWidgetWidgetVersionNotSupported]: NotifyIPyWidgeWidgetVersionNotSupportedAction;
public [InteractiveWindowMessages.ConvertUriForUseInWebViewRequest]: Uri;
public [InteractiveWindowMessages.ConvertUriForUseInWebViewResponse]: { request: Uri; response: Uri };
public [InteractiveWindowMessages.IPyWidgetRenderFailure]: Error;
public [InteractiveWindowMessages.IPyWidgetUnhandledKernelMessage]: KernelMessage.IMessage;
public [InteractiveWindowMessages.KernelIdle]: never | undefined;
public [InteractiveWindowMessages.GetHTMLByIdRequest]: string;
public [InteractiveWindowMessages.GetHTMLByIdResponse]: string;
} | the_stack |
import * as api from '@cmt/api';
import * as cache from '@cmt/cache';
import {
CodeModelConfiguration,
CodeModelContent,
CodeModelFileGroup,
CodeModelProject,
CodeModelTarget,
CodeModelToolchain
} from '@cmt/drivers/codeModel';
import * as logging from '@cmt/logging';
import { fs } from '@cmt/pr';
import * as path from 'path';
import * as nls from 'vscode-nls';
import rollbar from '@cmt/rollbar';
import { removeEmpty } from '@cmt/util';
export interface ApiVersion {
major: number;
minor: number;
}
export namespace Index {
export interface GeneratorInformation {
name: string;
platform?: string;
}
export interface CMake {
generator: GeneratorInformation;
}
export interface ObjectKind {
kind: string;
version: ApiVersion;
jsonFile: string;
}
export interface IndexFile {
cmake: CMake;
objects: ObjectKind[];
}
}
export namespace Cache {
export interface CacheContent {
version: ApiVersion;
entries: CMakeCacheEntry[];
}
export interface CacheEntryProperties {
name: string;
value: string;
}
export interface CMakeCacheEntry {
name: string;
properties: CacheEntryProperties[];
type: string;
value: string;
}
}
export namespace CodeModelKind {
export interface PathInfo {
build: string;
source: string;
}
export interface DirectoryMetadata {
source: string;
build: string;
hasInstallRule: boolean;
}
export interface ProjectMetadata {
name: string;
targetIndexes?: number[];
directoryIndexes: number[];
}
export interface Configuration {
name: string;
targets: Target[];
directories: DirectoryMetadata[];
projects: ProjectMetadata[];
}
export interface Content {
version: ApiVersion;
paths: PathInfo;
configurations: Configuration[];
}
export interface Target {
name: string;
type: string;
jsonFile: string;
}
export interface PreprocessorDefinitionMetadata {
define: string;
}
export interface IncludeMetadata {
path: string;
}
export interface SysRoot {
path: string;
}
export interface CompileCommandFragments {
fragment: string;
}
export interface CompileGroup {
language: string;
includes: IncludeMetadata[];
defines: PreprocessorDefinitionMetadata[];
compileCommandFragments: CompileCommandFragments[];
sourceIndexes: number[];
sysroot: SysRoot;
}
export interface ArtifactPath {
path: string;
}
export interface TargetSourcefile {
path: string;
compileGroupIndex?: number;
isGenerated?: boolean;
}
export interface TargetObject {
name: string;
type: string;
artifacts: ArtifactPath[];
nameOnDisk: string;
paths: PathInfo;
sources: TargetSourcefile[];
compileGroups?: CompileGroup[];
}
}
export namespace Toolchains {
export interface Content {
version: ApiVersion;
toolchains: Toolchain[];
}
export interface Toolchain {
language: string;
compiler: Compiler;
sourceFileExtensions?: string[];
}
export interface Compiler {
path?: string;
id?: string;
version?: string;
target?: string;
implicit: ImplicitCompilerInfo;
}
export interface ImplicitCompilerInfo {
includeDirectories?: string[];
linkDirectories?: string[];
linkFrameworkDirectories?: string[];
linkLibraries?: string[];
}
}
nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })();
const localize: nls.LocalizeFunc = nls.loadMessageBundle();
const log = logging.createLogger('cmakefileapi-parser');
/**
* Attempt to read from a file path. Log a message if it's not readable.
*/
async function tryReadFile(file: string): Promise<string | undefined> {
const fileInfo = await fs.stat(file);
if (fileInfo.isFile()) {
return fs.readFile(file);
} else {
log.debug(localize('path.not.a.file', 'Unable to read {0} because it is not a file. Code model information is incomplete or corrupt. You may need to delete the cache and reconfigure.', `"${file}"`));
return undefined;
}
}
export async function createQueryFileForApi(apiPath: string): Promise<string> {
const queryPath = path.join(apiPath, 'query', 'client-vscode');
const queryFilePath = path.join(queryPath, 'query.json');
const requests = { requests: [{ kind: 'cache', version: 2 }, { kind: 'codemodel', version: 2 }, { kind: 'toolchains', version: 1 }] };
try {
await fs.mkdir_p(queryPath);
await fs.writeFile(queryFilePath, JSON.stringify(requests));
} catch (e: any) {
rollbar.exception(localize('failed.writing.to.file', 'Failed writing to file {0}', queryFilePath), e);
throw e;
}
return queryFilePath;
}
export async function loadIndexFile(replyPath: string): Promise<Index.IndexFile | null> {
log.debug(`Read reply folder: ${replyPath}`);
if (!await fs.exists(replyPath)) {
return null;
}
const files = await fs.readdir(replyPath);
log.debug(`Found index files: ${JSON.stringify(files)}`);
const indexFiles = files.filter(filename => filename.startsWith('index-')).sort();
if (indexFiles.length === 0) {
throw Error('No index file found.');
}
const indexFilePath = path.join(replyPath, indexFiles[indexFiles.length - 1]);
const fileContent = await tryReadFile(indexFilePath);
if (!fileContent) {
return null;
}
return JSON.parse(fileContent.toString()) as Index.IndexFile;
}
export async function loadCacheContent(filename: string): Promise<Map<string, api.CacheEntry>> {
const fileContent = await tryReadFile(filename);
if (!fileContent) {
return new Map();
}
const cmakeCacheContent = JSON.parse(fileContent.toString()) as Cache.CacheContent;
const expectedVersion = { major: 2, minor: 0 };
const detectedVersion = cmakeCacheContent.version;
if (detectedVersion.major !== expectedVersion.major || detectedVersion.minor < expectedVersion.minor) {
log.warning(localize(
'cache.object.version',
'Cache object version ({0}.{1}) of cmake-file-api is unexpected. Expecting ({2}.{3}). IntelliSense configuration may be incorrect.',
detectedVersion.major,
detectedVersion.minor,
expectedVersion.major,
expectedVersion.minor));
}
return convertFileApiCacheToExtensionCache(cmakeCacheContent);
}
function findPropertyValue(cacheElement: Cache.CMakeCacheEntry, name: string): string {
const propertyElement = cacheElement.properties.find(prop => prop.name === name);
return propertyElement ? propertyElement.value : '';
}
function convertFileApiCacheToExtensionCache(cmakeCacheContent: Cache.CacheContent): Map<string, api.CacheEntry> {
return cmakeCacheContent.entries.reduce((acc, el) => {
const fileApiToExtensionCacheMap: { [key: string]: api.CacheEntryType | undefined } = {
BOOL: api.CacheEntryType.Bool,
STRING: api.CacheEntryType.String,
PATH: api.CacheEntryType.Path,
FILEPATH: api.CacheEntryType.FilePath,
INTERNAL: api.CacheEntryType.Internal,
UNINITIALIZED: api.CacheEntryType.Uninitialized,
STATIC: api.CacheEntryType.Static
};
const type = fileApiToExtensionCacheMap[el.type];
if (type === undefined) {
log.warning(localize('cache.entry.unknowntype', 'Unknown cache entry type: {0}.', el.type));
return acc;
}
const helpString = findPropertyValue(el, 'HELPSTRING');
const advanced = findPropertyValue(el, 'ADVANCED');
acc.set(el.name, new cache.Entry(el.name, el.value, type, helpString, advanced === '1'));
return acc;
}, new Map<string, api.CacheEntry>());
}
export async function loadCodeModelContent(filename: string): Promise<CodeModelKind.Content | null> {
const fileContent = await tryReadFile(filename);
if (!fileContent) {
return null;
}
const codemodel = JSON.parse(fileContent.toString()) as CodeModelKind.Content;
const expectedVersion = { major: 2, minor: 0 };
const detectedVersion = codemodel.version;
if (detectedVersion.major !== expectedVersion.major || detectedVersion.minor < expectedVersion.minor) {
log.warning(localize(
'code.model.version',
'Code model version ({0}.{1}) of cmake-file-api is unexpected. Expecting ({2}.{3}). IntelliSense configuration may be incorrect.',
detectedVersion.major,
detectedVersion.minor,
expectedVersion.major,
expectedVersion.minor));
}
return codemodel;
}
export async function loadTargetObject(filename: string): Promise<CodeModelKind.TargetObject | null> {
const fileContent = await tryReadFile(filename);
if (!fileContent) {
return null;
}
return JSON.parse(fileContent.toString()) as CodeModelKind.TargetObject;
}
async function convertTargetObjectFileToExtensionTarget(buildDirectory: string, filePath: string): Promise<api.Target | null> {
const targetObject = await loadTargetObject(filePath);
if (!targetObject) {
return null;
}
let executablePath;
if (targetObject.artifacts) {
executablePath = targetObject.artifacts.find(artifact => artifact.path.endsWith(targetObject.nameOnDisk));
if (executablePath) {
executablePath = convertToAbsolutePath(executablePath.path, buildDirectory);
}
}
return {
name: targetObject.name,
filepath: executablePath,
targetType: targetObject.type,
type: 'rich' as 'rich'
} as api.RichTarget;
}
export async function loadAllTargetsForBuildTypeConfiguration(replyPath: string, buildDirectory: string, configuration: CodeModelKind.Configuration): Promise<{ name: string; targets: api.Target[] }> {
const metaTargets = [];
if (configuration.directories[0].hasInstallRule) {
metaTargets.push({
type: 'rich' as 'rich',
name: 'install',
filepath: 'A special target to install all available targets',
targetType: 'META'
});
}
const targetsList = await Promise.all(configuration.targets.map(t => convertTargetObjectFileToExtensionTarget(buildDirectory, path.join(replyPath, t.jsonFile))));
return {
name: configuration.name,
targets: [...metaTargets, ...removeEmpty(targetsList)]
};
}
export async function loadConfigurationTargetMap(replyPath: string, codeModelFileName: string): Promise<Map<string, api.Target[]>> {
const codeModelContent = await loadCodeModelContent(path.join(replyPath, codeModelFileName));
if (!codeModelContent) {
return new Map();
}
const buildDirectory = codeModelContent.paths.build;
const targets = await Promise.all(codeModelContent.configurations.map(
config => loadAllTargetsForBuildTypeConfiguration(replyPath, buildDirectory, config)));
return targets.reduce((acc, el) => {
acc.set(el.name, el.targets);
return acc;
}, new Map<string, api.Target[]>());
}
function convertToAbsolutePath(inputPath: string, basePath: string) {
// Prepend the base path to the input path if the input path is relative.
const absolutePath = path.isAbsolute(inputPath) ? inputPath : path.join(basePath, inputPath);
return path.normalize(absolutePath);
}
function convertToExtCodeModelFileGroup(targetObject: CodeModelKind.TargetObject, rootPaths: CodeModelKind.PathInfo): CodeModelFileGroup[] {
const fileGroup: CodeModelFileGroup[] = !targetObject.compileGroups ? [] : targetObject.compileGroups.map(group => {
const compileFlags = group.compileCommandFragments ? group.compileCommandFragments.map(frag => frag.fragment).join(' ') : '';
return {
isGenerated: false,
sources: [],
language: group.language,
includePath: group.includes ? group.includes : [],
compileFlags,
defines: group.defines ? group.defines.map(define => define.define) : []
};
});
// Collection all without compilegroup like headers
const defaultIndex = fileGroup.push({ sources: [], isGenerated: false } as CodeModelFileGroup) - 1;
const targetRootSource = convertToAbsolutePath(targetObject.paths.source, rootPaths.source);
targetObject.sources.forEach(sourceFile => {
const fileAbsolutePath = convertToAbsolutePath(sourceFile.path, rootPaths.source);
const fileRelativePath = path.relative(targetRootSource, fileAbsolutePath).replace('\\', '/');
if (sourceFile.compileGroupIndex !== undefined) {
fileGroup[sourceFile.compileGroupIndex].sources.push(fileRelativePath);
} else {
fileGroup[defaultIndex].sources.push(fileRelativePath);
if (!!sourceFile.isGenerated) {
fileGroup[defaultIndex].isGenerated = sourceFile.isGenerated;
}
}
});
return fileGroup;
}
async function loadCodeModelTarget(rootPaths: CodeModelKind.PathInfo, jsonFile: string): Promise<CodeModelTarget | null> {
const targetObject = await loadTargetObject(jsonFile);
if (!targetObject) {
return null;
}
const fileGroups = convertToExtCodeModelFileGroup(targetObject, rootPaths);
// This implementation expects that there is only one sysroot in a target.
// The ServerAPI only has provided one sysroot. In the FileAPI,
// each compileGroup has its separate sysroot.
let sysroot;
if (targetObject.compileGroups) {
const allSysroots = removeEmpty(targetObject.compileGroups.map(x => !!x.sysroot ? x.sysroot.path : undefined));
sysroot = allSysroots.length !== 0 ? allSysroots[0] : undefined;
}
return {
name: targetObject.name,
type: targetObject.type,
sourceDirectory: convertToAbsolutePath(targetObject.paths.source, rootPaths.source),
fullName: targetObject.nameOnDisk,
artifacts: targetObject.artifacts ? targetObject.artifacts.map(
a => convertToAbsolutePath(path.join(targetObject.paths.build, a.path), rootPaths.build))
: [],
fileGroups,
sysroot
} as CodeModelTarget;
}
export async function loadProject(rootPaths: CodeModelKind.PathInfo, replyPath: string, projectIndex: number, configuration: CodeModelKind.Configuration) {
const project = configuration.projects[projectIndex];
const projectPaths = {
build: project.directoryIndexes
? path.join(rootPaths.build, configuration.directories[project.directoryIndexes[0]].build)
: rootPaths.build,
source: project.directoryIndexes
? path.join(rootPaths.source, configuration.directories[project.directoryIndexes[0]].source)
: rootPaths.source
};
const targets = await Promise.all((project.targetIndexes || []).map(targetIndex => loadCodeModelTarget(rootPaths, path.join(replyPath, configuration.targets[targetIndex].jsonFile))));
return { name: project.name, targets, sourceDirectory: projectPaths.source } as CodeModelProject;
}
export async function loadConfig(paths: CodeModelKind.PathInfo, replyPath: string, configuration: CodeModelKind.Configuration) {
const projects = await Promise.all((configuration.projects).map((_, index) => loadProject(paths, replyPath, index, configuration)));
return { name: configuration.name, projects } as CodeModelConfiguration;
}
export async function loadExtCodeModelContent(replyPath: string, codeModelFileName: string): Promise<CodeModelContent | null> {
const codeModelContent = await loadCodeModelContent(path.join(replyPath, codeModelFileName));
if (!codeModelContent) {
return null;
}
const configurations = await Promise.all(codeModelContent.configurations.map(config_element => loadConfig(codeModelContent.paths, replyPath, config_element)));
return { configurations } as CodeModelContent;
}
export async function loadToolchains(filename: string): Promise<Map<string, CodeModelToolchain>> {
const fileContent = await tryReadFile(filename);
if (!fileContent) {
return new Map();
}
const toolchains = JSON.parse(fileContent.toString()) as Toolchains.Content;
const expectedVersion = { major: 1, minor: 0 };
const detectedVersion = toolchains.version;
if (detectedVersion.major !== expectedVersion.major || detectedVersion.minor < expectedVersion.minor) {
log.warning(localize(
'toolchains.object.version',
'Toolchains object version ({0}.{1}) of cmake-file-api is unexpected. Expecting ({2}.{3}). IntelliSense configuration may be incorrect.',
detectedVersion.major,
detectedVersion.minor,
expectedVersion.major,
expectedVersion.minor));
}
return toolchains.toolchains.reduce((acc, el) => {
if (el.compiler.path) {
if (el.compiler.target) {
acc.set(el.language, { path: el.compiler.path, target: el.compiler.target });
} else {
acc.set(el.language, { path: el.compiler.path });
}
}
return acc;
}, new Map<string, CodeModelToolchain>());
} | the_stack |
namespace com.keyman.text {
export class InputProcessor {
public static readonly DEFAULT_OPTIONS: ProcessorInitOptions = {
baseLayout: 'us'
}
private kbdProcessor: KeyboardProcessor;
private lngProcessor: prediction.LanguageProcessor;
constructor(options?: ProcessorInitOptions) {
if(!options) {
options = InputProcessor.DEFAULT_OPTIONS;
}
this.kbdProcessor = new KeyboardProcessor(options);
this.lngProcessor = new prediction.LanguageProcessor();
}
public get languageProcessor(): prediction.LanguageProcessor {
return this.lngProcessor;
}
public get keyboardProcessor(): KeyboardProcessor {
return this.kbdProcessor;
}
public get keyboardInterface(): text.KeyboardInterface {
return this.keyboardProcessor.keyboardInterface;
}
public get activeKeyboard(): keyboards.Keyboard {
return this.keyboardInterface.activeKeyboard;
}
public set activeKeyboard(keyboard: keyboards.Keyboard) {
this.keyboardInterface.activeKeyboard = keyboard;
// All old deadkeys and keyboard-specific cache should immediately be invalidated
// on a keyboard change.
this.resetContext();
}
public get activeModel(): prediction.ModelSpec {
return this.languageProcessor.activeModel;
}
/**
* Simulate a keystroke according to the touched keyboard button element
*
* Handles default output and keyboard processing for both OSK and physical keystrokes.
*
* @param {Object} keyEvent The abstracted KeyEvent to use for keystroke processing
* @param {Object} outputTarget The OutputTarget receiving the KeyEvent
* @returns {Object} A RuleBehavior object describing the cumulative effects of
* all matched keyboard rules.
*/
processKeyEvent(keyEvent: KeyEvent, outputTarget: OutputTarget): RuleBehavior {
let formFactor = keyEvent.device.formFactor;
let fromOSK = keyEvent.isSynthetic;
// The default OSK layout for desktop devices does not include nextlayer info, relying on modifier detection here.
// It's the OSK equivalent to doModifierPress on 'desktop' form factors.
if((formFactor == utils.FormFactor.Desktop || !this.activeKeyboard || this.activeKeyboard.usesDesktopLayoutOnDevice(keyEvent.device)) && fromOSK) {
// If it's a desktop OSK style and this triggers a layer change,
// a modifier key was clicked. No output expected, so it's safe to instantly exit.
if(this.keyboardProcessor.selectLayer(keyEvent)) {
return new RuleBehavior();
}
}
// Will handle keystroke-based non-layer change modifier & state keys, mapping them through the physical keyboard's version
// of state management. `doModifierPress` must always run.
if(this.keyboardProcessor.doModifierPress(keyEvent, outputTarget, !fromOSK)) {
// If run on a desktop platform, we know that modifier & state key presses may not
// produce output, so we may make an immediate return safely.
if(!fromOSK) {
return new RuleBehavior();
}
}
// If suggestions exist AND space is pressed, accept the suggestion and do not process the keystroke.
// If a suggestion was just accepted AND backspace is pressed, revert the change and do not process the backspace.
// We check the first condition here, while the prediction UI handles the second through the try__() methods below.
if(this.languageProcessor.isActive) {
// The following code relies on JS's logical operator "short-circuit" properties to prevent unwanted triggering of the second condition.
// Can the suggestion UI revert a recent suggestion? If so, do that and swallow the backspace.
if((keyEvent.kName == "K_BKSP" || keyEvent.Lcode == Codes.keyCodes["K_BKSP"]) && this.languageProcessor.tryRevertSuggestion()) {
return new RuleBehavior();
// Can the suggestion UI accept an existing suggestion? If so, do that and swallow the space character.
} else if((keyEvent.kName == "K_SPACE" || keyEvent.Lcode == Codes.keyCodes["K_SPACE"]) && this.languageProcessor.tryAcceptSuggestion('space')) {
return new RuleBehavior();
}
}
// // ...end I3363 (Build 301)
// Create a "mock" backup of the current outputTarget in its pre-input state.
// Current, long-existing assumption - it's DOM-backed.
let preInputMock = Mock.from(outputTarget);
// We presently need the true keystroke to run on the FULL context. That index is still
// needed for some indexing operations when comparing two different output targets.
let ruleBehavior = this.keyboardProcessor.processKeystroke(keyEvent, outputTarget);
// Swap layer as appropriate.
if(keyEvent.kNextLayer) {
this.keyboardProcessor.selectLayer(keyEvent);
}
// Should we swallow any further processing of keystroke events for this keydown-keypress sequence?
if(ruleBehavior != null) {
let alternates: Alternate[];
// If we're performing a 'default command', it's not a standard 'typing' event - don't do fat-finger stuff.
// Also, don't do fat-finger stuff if predictive text isn't enabled.
if(this.languageProcessor.isActive && !ruleBehavior.triggersDefaultCommand) {
let keyDistribution = keyEvent.keyDistribution;
// We don't need to track absolute indexing during alternate-generation;
// only position-relative, so it's better to use a sliding window for context
// when making alternates. (Slightly worse for short text, matters greatly
// for long text.)
let contextWindow = new ContextWindow(preInputMock, ContextWindow.ENGINE_RULE_WINDOW);
let windowedMock = contextWindow.toMock();
// Note - we don't yet do fat-fingering with longpress keys.
if(keyDistribution && keyEvent.kbdLayer) {
// Tracks a 'deadline' for fat-finger ops, just in case both context is long enough
// and device is slow enough that the calculation takes too long.
//
// Consider use of https://developer.mozilla.org/en-US/docs/Web/API/Performance/now instead?
// Would allow finer-tuned control.
let TIMEOUT_THRESHOLD: number = Number.MAX_VALUE;
let _globalThis = com.keyman.utils.getGlobalObject();
let timer: () => number;
// Available by default on `window` in browsers, but _not_ on `global` in Node,
// surprisingly. Since we can't use code dependent on `require` statements
// at present, we have to condition upon it actually existing.
if(_globalThis['performance'] && _globalThis['performance']['now']) {
timer = function() {
return _globalThis['performance']['now']();
};
TIMEOUT_THRESHOLD = timer() + 16; // + 16ms.
} // else {
// We _could_ just use Date.now() as a backup... but that (probably) only matters
// when unit testing. So... we actually don't _need_ time thresholding when in
// a Node environment.
// }
// Tracks a minimum probability for keystroke probability. Anything less will not be
// included in alternate calculations.
//
// Seek to match SearchSpace.EDIT_DISTANCE_COST_SCALE from the predictive-text engine.
// Reasoning for the selected value may be seen there. Short version - keystrokes
// that _appear_ very precise may otherwise not even consider directly-neighboring keys.
let KEYSTROKE_EPSILON = Math.exp(-5);
// Sort the distribution into probability-descending order.
keyDistribution.sort((a, b) => b.p - a.p);
let activeLayout = this.activeKeyboard.layout(keyEvent.device.formFactor);
alternates = [];
let totalMass = 0; // Tracks sum of non-error probabilities.
for(let pair of keyDistribution) {
if(pair.p < KEYSTROKE_EPSILON) {
break;
} else if(timer && timer() >= TIMEOUT_THRESHOLD) {
// Note: it's always possible that the thread _executing_ our JS
// got paused by the OS, even if JS itself is single-threaded.
//
// The case where `alternates` is initialized (line 167) but empty
// (because of net-zero loop iterations) MUST be handled.
break;
}
let mock = Mock.from(windowedMock);
let altKey = activeLayout.getLayer(keyEvent.kbdLayer).getKey(pair.keyId);
if(!altKey) {
console.warn("Potential fat-finger key could not be found in layer!");
continue;
}
let altEvent = altKey.constructKeyEvent(this.keyboardProcessor, keyEvent.device);
let alternateBehavior = this.keyboardProcessor.processKeystroke(altEvent, mock);
// If alternateBehavior.beep == true, ignore it. It's a disallowed key sequence,
// so we expect users to never intend their use.
//
// Also possible that this set of conditions fail for all evaluated alternates.
if(alternateBehavior && !alternateBehavior.beep && pair.p > 0) {
let transform: Transform = alternateBehavior.transcription.transform;
// Ensure that the alternate's token id matches that of the current keystroke, as we only
// record the matched rule's context (since they match)
transform.id = ruleBehavior.transcription.token;
alternates.push({sample: transform, 'p': pair.p});
totalMass += pair.p;
}
}
// Renormalizes the distribution, as any error (beep) results
// will result in a distribution that doesn't sum to 1 otherwise.
// All `.p` values are strictly positive, so totalMass is
// guaranteed to be > 0 if the array has entries.
alternates.forEach(function(alt) {
alt.p /= totalMass;
});
}
}
// Now that we've done all the keystroke processing needed, ensure any extra effects triggered
// by the actual keystroke occur.
ruleBehavior.finalize(this.keyboardProcessor, outputTarget);
// -- All keystroke (and 'alternate') processing is now complete. Time to finalize everything! --
// Notify the ModelManager of new input - it's predictive text time!
if(alternates && alternates.length > 0) {
ruleBehavior.transcription.alternates = alternates;
}
// Yes, even for ruleBehavior.triggersDefaultCommand. Those tend to change the context.
ruleBehavior.predictionPromise = this.languageProcessor.predict(ruleBehavior.transcription);
// Text did not change (thus, no text "input") if we tabbed or merely moved the caret.
if(!ruleBehavior.triggersDefaultCommand) {
// For DOM-aware targets, this will trigger a DOM event page designers may listen for.
outputTarget.doInputEvent();
}
}
return ruleBehavior;
}
public resetContext(outputTarget?: OutputTarget) {
this.keyboardProcessor.resetContext();
this.languageProcessor.invalidateContext(outputTarget);
}
}
}
(function () {
let ns = com.keyman.text;
// Let the InputProcessor be available both in the browser and in Node.
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
module.exports = ns.InputProcessor;
//@ts-ignore
ns.InputProcessor.com = com; // Export the root namespace so that all InputProcessor classes are accessible by unit tests.
}
}()); | the_stack |
import { Container, ContainerConfig } from './container';
import { UIInstanceManager } from '../uimanager';
import { Label, LabelConfig } from './label';
import { ComponentConfig, Component } from './component';
import { ControlBar } from './controlbar';
import { EventDispatcher } from '../eventdispatcher';
import { DOM, Size } from '../dom';
import { PlayerAPI, SubtitleCueEvent } from 'bitmovin-player';
import { i18n } from '../localization/i18n';
import { VttUtils } from '../vttutils';
import { VTTProperties } from 'bitmovin-player/types/subtitles/vtt/API';
/**
* Overlays the player to display subtitles.
*/
export class SubtitleOverlay extends Container<ContainerConfig> {
private subtitleManager: ActiveSubtitleManager;
private previewSubtitleActive: boolean;
private previewSubtitle: SubtitleLabel;
private preprocessLabelEventCallback = new EventDispatcher<SubtitleCueEvent, SubtitleLabel>();
private subtitleContainerManager: SubtitleRegionContainerManager;
private static readonly CLASS_CONTROLBAR_VISIBLE = 'controlbar-visible';
private static readonly CLASS_CEA_608 = 'cea608';
// The number of rows in a cea608 grid
private static readonly CEA608_NUM_ROWS = 15;
// The number of columns in a cea608 grid
private static readonly CEA608_NUM_COLUMNS = 32;
// The offset in percent for one row (which is also the height of a row)
private static readonly CEA608_ROW_OFFSET = 100 / SubtitleOverlay.CEA608_NUM_ROWS;
// The offset in percent for one column (which is also the width of a column)
private static readonly CEA608_COLUMN_OFFSET = 100 / SubtitleOverlay.CEA608_NUM_COLUMNS;
constructor(config: ContainerConfig = {}) {
super(config);
this.previewSubtitleActive = false;
this.previewSubtitle = new SubtitleLabel({ text: i18n.getLocalizer('subtitle.example') });
this.config = this.mergeConfig(config, {
cssClass: 'ui-subtitle-overlay',
}, this.config);
}
configure(player: PlayerAPI, uimanager: UIInstanceManager): void {
super.configure(player, uimanager);
let subtitleManager = new ActiveSubtitleManager();
this.subtitleManager = subtitleManager;
this.subtitleContainerManager = new SubtitleRegionContainerManager(this);
player.on(player.exports.PlayerEvent.CueEnter, (event: SubtitleCueEvent) => {
const label = this.generateLabel(event);
subtitleManager.cueEnter(event, label);
this.preprocessLabelEventCallback.dispatch(event, label);
if (this.previewSubtitleActive) {
this.subtitleContainerManager.removeLabel(this.previewSubtitle);
}
this.show();
this.subtitleContainerManager.addLabel(label, this.getDomElement().size());
this.updateComponents();
});
player.on(player.exports.PlayerEvent.CueUpdate, (event: SubtitleCueEvent) => {
const label = this.generateLabel(event);
const labelToReplace = subtitleManager.cueUpdate(event, label);
this.preprocessLabelEventCallback.dispatch(event, label);
if (labelToReplace) {
this.subtitleContainerManager.replaceLabel(labelToReplace, label);
}
});
player.on(player.exports.PlayerEvent.CueExit, (event: SubtitleCueEvent) => {
let labelToRemove = subtitleManager.cueExit(event);
if (labelToRemove) {
this.subtitleContainerManager.removeLabel(labelToRemove);
this.updateComponents();
}
if (!subtitleManager.hasCues) {
if (!this.previewSubtitleActive) {
this.hide();
} else {
this.subtitleContainerManager.addLabel(this.previewSubtitle);
this.updateComponents();
}
}
});
let subtitleClearHandler = () => {
this.hide();
this.subtitleContainerManager.clear();
subtitleManager.clear();
this.removeComponents();
this.updateComponents();
};
player.on(player.exports.PlayerEvent.AudioChanged, subtitleClearHandler);
player.on(player.exports.PlayerEvent.SubtitleEnabled, subtitleClearHandler);
player.on(player.exports.PlayerEvent.SubtitleDisabled, subtitleClearHandler);
player.on(player.exports.PlayerEvent.Seek, subtitleClearHandler);
player.on(player.exports.PlayerEvent.TimeShift, subtitleClearHandler);
player.on(player.exports.PlayerEvent.PlaybackFinished, subtitleClearHandler);
player.on(player.exports.PlayerEvent.SourceUnloaded, subtitleClearHandler);
uimanager.onComponentShow.subscribe((component: Component<ComponentConfig>) => {
if (component instanceof ControlBar) {
this.getDomElement().addClass(this.prefixCss(SubtitleOverlay.CLASS_CONTROLBAR_VISIBLE));
}
});
uimanager.onComponentHide.subscribe((component: Component<ComponentConfig>) => {
if (component instanceof ControlBar) {
this.getDomElement().removeClass(this.prefixCss(SubtitleOverlay.CLASS_CONTROLBAR_VISIBLE));
}
});
this.configureCea608Captions(player, uimanager);
// Init
subtitleClearHandler();
}
generateLabel(event: SubtitleCueEvent): SubtitleLabel {
// Sanitize cue data (must be done before the cue ID is generated in subtitleManager.cueEnter / update)
if (event.position) {
// Sometimes the positions are undefined, we assume them to be zero
event.position.row = event.position.row || 0;
event.position.column = event.position.column || 0;
}
const label = new SubtitleLabel({
// Prefer the HTML subtitle text if set, else try generating a image tag as string from the image attribute,
// else use the plain text
text: event.html || ActiveSubtitleManager.generateImageTagText(event.image) || event.text,
vtt: event.vtt,
region: event.region,
regionStyle: event.regionStyle,
});
return label;
}
configureCea608Captions(player: PlayerAPI, uimanager: UIInstanceManager): void {
// The calculated font size
let fontSize = 0;
// The required letter spacing spread the text characters evenly across the grid
let fontLetterSpacing = 0;
// Flag telling if a font size calculation is required of if the current values are valid
let fontSizeCalculationRequired = true;
// Flag telling if the CEA-608 mode is enabled
let enabled = false;
const updateCEA608FontSize = () => {
const dummyLabel = new SubtitleLabel({ text: 'X' });
dummyLabel.getDomElement().css({
// By using a large font size we do not need to use multiple letters and can get still an
// accurate measurement even though the returned size is an integer value
'font-size': '200px',
'line-height': '200px',
'visibility': 'hidden',
});
this.addComponent(dummyLabel);
this.updateComponents();
this.show();
const dummyLabelCharWidth = dummyLabel.getDomElement().width();
const dummyLabelCharHeight = dummyLabel.getDomElement().height();
const fontSizeRatio = dummyLabelCharWidth / dummyLabelCharHeight;
this.removeComponent(dummyLabel);
this.updateComponents();
if (!this.subtitleManager.hasCues) {
this.hide();
}
// We subtract 1px here to avoid line breaks at the right border of the subtitle overlay that can happen
// when texts contain whitespaces. It's probably some kind of pixel rounding issue in the browser's
// layouting, but the actual reason could not be determined. Aiming for a target width - 1px would work in
// most browsers, but Safari has a "quantized" font size rendering with huge steps in between so we need
// to subtract some more pixels to avoid line breaks there as well.
const subtitleOverlayWidth = this.getDomElement().width() - 10;
const subtitleOverlayHeight = this.getDomElement().height();
// The size ratio of the letter grid
const fontGridSizeRatio = (dummyLabelCharWidth * SubtitleOverlay.CEA608_NUM_COLUMNS) /
(dummyLabelCharHeight * SubtitleOverlay.CEA608_NUM_ROWS);
// The size ratio of the available space for the grid
const subtitleOverlaySizeRatio = subtitleOverlayWidth / subtitleOverlayHeight;
if (subtitleOverlaySizeRatio > fontGridSizeRatio) {
// When the available space is wider than the text grid, the font size is simply
// determined by the height of the available space.
fontSize = subtitleOverlayHeight / SubtitleOverlay.CEA608_NUM_ROWS;
// Calculate the additional letter spacing required to evenly spread the text across the grid's width
const gridSlotWidth = subtitleOverlayWidth / SubtitleOverlay.CEA608_NUM_COLUMNS;
const fontCharWidth = fontSize * fontSizeRatio;
fontLetterSpacing = gridSlotWidth - fontCharWidth;
} else {
// When the available space is not wide enough, texts would vertically overlap if we take
// the height as a base for the font size, so we need to limit the height. We do that
// by determining the font size by the width of the available space.
fontSize = subtitleOverlayWidth / SubtitleOverlay.CEA608_NUM_COLUMNS / fontSizeRatio;
fontLetterSpacing = 0;
}
// Update font-size of all active subtitle labels
for (let label of this.getComponents()) {
if (label instanceof SubtitleLabel) {
label.getDomElement().css({
'font-size': `${fontSize}px`,
'letter-spacing': `${fontLetterSpacing}px`,
});
}
}
};
player.on(player.exports.PlayerEvent.PlayerResized, () => {
if (enabled) {
updateCEA608FontSize();
} else {
fontSizeCalculationRequired = true;
}
});
this.preprocessLabelEventCallback.subscribe((event: SubtitleCueEvent, label: SubtitleLabel) => {
const isCEA608 = event.position != null;
if (!isCEA608) {
// Skip all non-CEA608 cues
return;
}
if (!enabled) {
enabled = true;
this.getDomElement().addClass(this.prefixCss(SubtitleOverlay.CLASS_CEA_608));
// We conditionally update the font size by this flag here to avoid updating every time a subtitle
// is added into an empty overlay. Because we reset the overlay when all subtitles are gone, this
// would trigger an unnecessary update every time, but it's only required under certain conditions,
// e.g. after the player size has changed.
if (fontSizeCalculationRequired) {
updateCEA608FontSize();
fontSizeCalculationRequired = false;
}
}
label.getDomElement().css({
'left': `${event.position.column * SubtitleOverlay.CEA608_COLUMN_OFFSET}%`,
'top': `${event.position.row * SubtitleOverlay.CEA608_ROW_OFFSET}%`,
'font-size': `${fontSize}px`,
'letter-spacing': `${fontLetterSpacing}px`,
});
});
const reset = () => {
this.getDomElement().removeClass(this.prefixCss(SubtitleOverlay.CLASS_CEA_608));
enabled = false;
};
player.on(player.exports.PlayerEvent.CueExit, () => {
if (!this.subtitleManager.hasCues) {
// Disable CEA-608 mode when all subtitles are gone (to allow correct formatting and
// display of other types of subtitles, e.g. the formatting preview subtitle)
reset();
}
});
player.on(player.exports.PlayerEvent.SourceUnloaded, reset);
player.on(player.exports.PlayerEvent.SubtitleEnabled, reset);
player.on(player.exports.PlayerEvent.SubtitleDisabled, reset);
}
enablePreviewSubtitleLabel(): void {
if (!this.subtitleManager.hasCues) {
this.previewSubtitleActive = true;
this.subtitleContainerManager.addLabel(this.previewSubtitle);
this.updateComponents();
this.show();
}
}
removePreviewSubtitleLabel(): void {
if (this.previewSubtitleActive) {
this.previewSubtitleActive = false;
this.subtitleContainerManager.removeLabel(this.previewSubtitle);
this.updateComponents();
}
}
}
interface ActiveSubtitleCue {
event: SubtitleCueEvent;
label: SubtitleLabel;
}
interface ActiveSubtitleCueMap {
[id: string]: ActiveSubtitleCue[];
}
interface SubtitleLabelConfig extends LabelConfig {
vtt?: VTTProperties;
region?: string;
regionStyle?: string;
}
export class SubtitleLabel extends Label<SubtitleLabelConfig> {
constructor(config: SubtitleLabelConfig = {}) {
super(config);
this.config = this.mergeConfig(config, {
cssClass: 'ui-subtitle-label',
}, this.config);
}
get vtt(): VTTProperties {
return this.config.vtt;
}
get region(): string {
return this.config.region;
}
get regionStyle(): string {
return this.config.regionStyle;
}
}
class ActiveSubtitleManager {
private activeSubtitleCueMap: ActiveSubtitleCueMap;
private activeSubtitleCueCount: number;
constructor() {
this.activeSubtitleCueMap = {};
this.activeSubtitleCueCount = 0;
}
/**
* Calculates a unique ID for a subtitle cue, which is needed to associate an CueEnter with its CueExit
* event so we can remove the correct subtitle in CueExit when multiple subtitles are active at the same time.
* The start time plus the text should make a unique identifier, and in the only case where a collision
* can happen, two similar texts will be displayed at a similar time and a similar position (or without position).
* The start time should always be known, because it is required to schedule the CueEnter event. The end time
* must not necessarily be known and therefore cannot be used for the ID.
* @param event
* @return {string}
*/
private static calculateId(event: SubtitleCueEvent): string {
let id = event.start + '-' + event.text;
if (event.position) {
id += '-' + event.position.row + '-' + event.position.column;
}
return id;
}
cueEnter(event: SubtitleCueEvent, label: SubtitleLabel): void {
this.addCueToMap(event, label);
}
cueUpdate(event: SubtitleCueEvent, label: SubtitleLabel): SubtitleLabel | undefined {
const labelToReplace = this.popCueFromMap(event);
if (labelToReplace) {
this.addCueToMap(event, label);
return labelToReplace;
}
return undefined;
}
private addCueToMap(event: SubtitleCueEvent, label: SubtitleLabel): void {
let id = ActiveSubtitleManager.calculateId(event);
// Create array for id if it does not exist
this.activeSubtitleCueMap[id] = this.activeSubtitleCueMap[id] || [];
// Add cue
this.activeSubtitleCueMap[id].push({ event, label });
this.activeSubtitleCueCount++;
}
private popCueFromMap(event: SubtitleCueEvent): SubtitleLabel | undefined {
let id = ActiveSubtitleManager.calculateId(event);
let activeSubtitleCues = this.activeSubtitleCueMap[id];
if (activeSubtitleCues && activeSubtitleCues.length > 0) {
// Remove cue
/* We apply the FIFO approach here and remove the oldest cue from the associated id. When there are multiple cues
* with the same id, there is no way to know which one of the cues is to be deleted, so we just hope that FIFO
* works fine. Theoretically it can happen that two cues with colliding ids are removed at different times, in
* the wrong order. This rare case has yet to be observed. If it ever gets an issue, we can take the unstable
* cue end time (which can change between CueEnter and CueExit IN CueUpdate) and use it as an
* additional hint to try and remove the correct one of the colliding cues.
*/
let activeSubtitleCue = activeSubtitleCues.shift();
this.activeSubtitleCueCount--;
return activeSubtitleCue.label;
}
}
static generateImageTagText(imageData: string): string | undefined {
if (!imageData) {
return;
}
const imgTag = new DOM('img', {
src: imageData,
});
imgTag.css('width', '100%');
return imgTag.get(0).outerHTML; // return the html as string
}
/**
* Returns the label associated with an already added cue.
* @param event
* @return {SubtitleLabel}
*/
getCues(event: SubtitleCueEvent): SubtitleLabel[] | undefined {
let id = ActiveSubtitleManager.calculateId(event);
let activeSubtitleCues = this.activeSubtitleCueMap[id];
if (activeSubtitleCues && activeSubtitleCues.length > 0) {
return activeSubtitleCues.map((cue) => cue.label);
}
}
/**
* Removes the subtitle cue from the manager and returns the label that should be removed from the subtitle overlay,
* or null if there is no associated label existing (e.g. because all labels have been {@link #clear cleared}.
* @param event
* @return {SubtitleLabel|null}
*/
cueExit(event: SubtitleCueEvent): SubtitleLabel {
return this.popCueFromMap(event);
}
/**
* Returns the number of active subtitle cues.
* @return {number}
*/
get cueCount(): number {
// We explicitly count the cues to save an Array.reduce on every cueCount call (which can happen frequently)
return this.activeSubtitleCueCount;
}
/**
* Returns true if there are active subtitle cues, else false.
* @return {boolean}
*/
get hasCues(): boolean {
return this.cueCount > 0;
}
/**
* Removes all subtitle cues from the manager.
*/
clear(): void {
this.activeSubtitleCueMap = {};
this.activeSubtitleCueCount = 0;
}
}
export class SubtitleRegionContainerManager {
private subtitleRegionContainers: { [regionName: string]: SubtitleRegionContainer } = {};
/**
* @param subtitleOverlay Reference to the subtitle overlay for adding and removing the containers.
*/
constructor(private subtitleOverlay: SubtitleOverlay) {
this.subtitleOverlay = subtitleOverlay;
}
private getRegion(label: SubtitleLabel): { regionContainerId: string, regionName: string } {
if (label.vtt) {
return {
regionContainerId: label.vtt.region && label.vtt.region.id ? label.vtt.region.id : 'vtt',
regionName: 'vtt',
};
}
return {
regionContainerId: label.region || 'default',
regionName: label.region || 'default',
};
}
/**
* Creates and wraps a subtitle label into a container div based on the subtitle region.
* If the subtitle has positioning information it is added to the container.
* @param label The subtitle label to wrap
*/
addLabel(label: SubtitleLabel, overlaySize?: Size): void {
const { regionContainerId, regionName } = this.getRegion(label);
const cssClasses = [`subtitle-position-${regionName}`];
if (label.vtt && label.vtt.region) {
cssClasses.push(`vtt-region-${label.vtt.region.id}`);
}
if (!this.subtitleRegionContainers[regionContainerId]) {
const regionContainer = new SubtitleRegionContainer({
cssClasses,
});
this.subtitleRegionContainers[regionContainerId] = regionContainer;
if (label.regionStyle) {
regionContainer.getDomElement().attr('style', label.regionStyle);
} else if (label.vtt && !label.vtt.region) {
/**
* If there is no region present to wrap the Cue Box, the Cue box becomes the
* region itself. Therefore the positioning values have to come from the box.
*/
regionContainer.getDomElement().css('position', 'static');
} else {
// getDomElement needs to be called at least once to ensure the component exists
regionContainer.getDomElement();
}
for (const regionContainerId in this.subtitleRegionContainers) {
this.subtitleOverlay.addComponent(this.subtitleRegionContainers[regionContainerId]);
}
}
this.subtitleRegionContainers[regionContainerId].addLabel(label, overlaySize);
}
replaceLabel(previousLabel: SubtitleLabel, newLabel: SubtitleLabel): void {
const { regionContainerId } = this.getRegion(previousLabel);
this.subtitleRegionContainers[regionContainerId].removeLabel(previousLabel);
this.subtitleRegionContainers[regionContainerId].addLabel(newLabel);
}
/**
* Removes a subtitle label from a container.
*/
removeLabel(label: SubtitleLabel): void {
let regionContainerId;
if (label.vtt) {
regionContainerId = label.vtt.region && label.vtt.region.id ? label.vtt.region.id : 'vtt';
} else {
regionContainerId = label.region || 'default';
}
this.subtitleRegionContainers[regionContainerId].removeLabel(label);
// Remove container if no more labels are displayed
if (this.subtitleRegionContainers[regionContainerId].isEmpty()) {
this.subtitleOverlay.removeComponent(this.subtitleRegionContainers[regionContainerId]);
delete this.subtitleRegionContainers[regionContainerId];
}
}
/**
* Removes all subtitle containers.
*/
clear(): void {
for (const regionName in this.subtitleRegionContainers) {
this.subtitleOverlay.removeComponent(this.subtitleRegionContainers[regionName]);
}
this.subtitleRegionContainers = {};
}
}
export class SubtitleRegionContainer extends Container<ContainerConfig> {
private labelCount = 0;
constructor(config: ContainerConfig = {}) {
super(config);
this.config = this.mergeConfig(config, {
cssClass: 'subtitle-region-container',
}, this.config);
}
addLabel(labelToAdd: SubtitleLabel, overlaySize?: Size) {
this.labelCount++;
if (labelToAdd.vtt) {
if (labelToAdd.vtt.region && overlaySize) {
VttUtils.setVttRegionStyles(this, labelToAdd.vtt.region, overlaySize);
}
VttUtils.setVttCueBoxStyles(labelToAdd, overlaySize);
}
this.addComponent(labelToAdd);
this.updateComponents();
}
removeLabel(labelToRemove: SubtitleLabel): void {
this.labelCount--;
this.removeComponent(labelToRemove);
this.updateComponents();
}
public isEmpty(): boolean {
return this.labelCount === 0;
}
} | the_stack |
import { FivGalleryToolbar } from './gallery-toolbar/gallery-toolbar.component';
import { IonSlides, DomController, Platform } from '@ionic/angular';
import { FivOverlay } from './../overlay/overlay.component';
import {
Component,
ViewChild,
ElementRef,
Renderer2,
ContentChildren,
QueryList,
AfterContentInit,
forwardRef,
HostListener,
Inject,
ChangeDetectorRef,
TemplateRef,
Input,
Output,
EventEmitter,
OnDestroy,
ViewChildren
} from '@angular/core';
import {
style,
animate,
AnimationBuilder,
trigger,
transition,
useAnimation
} from '@angular/animations';
import { Key } from './keycodes.enum';
import { DOCUMENT } from '@angular/common';
import { Navigateable } from '../interfaces';
import { FivGalleryImage } from './gallery-image/gallery-image.component';
import { from, Subject, zip, of } from 'rxjs';
import { mergeMap, takeUntil, tap } from 'rxjs/operators';
import {
tween,
fromTo,
getPosition,
setPosition,
RectPosition,
fromToPixels,
easeOutSine
} from '@fivethree/ngx-rxjs-animations';
import { fade } from '../animations/animations';
import { ImageService } from './image.service';
@Component({
selector: 'fiv-gallery',
templateUrl: './gallery.component.html',
styleUrls: ['./gallery.component.scss'],
animations: [
trigger('scale', [
transition('void => *', [
style({ opacity: 0, transform: 'scale(0)' }),
animate('125ms', style({ opacity: 1, transform: 'scale(1)' }))
]),
transition('* => void', [
style({ opacity: 1, transform: 'scale(1)' }),
animate('125ms', style({ opacity: 0, transform: 'scale(0)' }))
])
]),
trigger('slideUp', [
transition('void => *', [
style({ opacity: 0, transform: 'translateY(100%)' }),
animate('75ms', style({ opacity: 1, transform: 'translateY(0%)' }))
]),
transition('* => void', [
style({ opacity: 1, transform: 'translateY(0%)' }),
animate('75ms', style({ opacity: 0, transform: 'translateY(100%)' }))
])
]),
trigger('slideDown', [
transition('* => void', [
style({ opacity: 0, transform: 'translateY(0%)' }),
animate('75ms', style({ opacity: 1, transform: 'translateY(-100%)' }))
]),
transition('void => *', [
style({ opacity: 1, transform: 'translateY(-100%)' }),
animate('75ms', style({ opacity: 0, transform: 'translateY(0%)' }))
])
]),
trigger('fade', [
transition(
'* => void',
useAnimation(fade, {
params: {
fromOpacity: 1,
toOpacity: 0,
time: '240ms'
}
})
),
transition(
'void => *',
useAnimation(fade, {
params: {
fromOpacity: 0,
toOpacity: 1,
time: '240ms'
}
})
)
])
]
})
export class FivGallery implements AfterContentInit, OnDestroy, Navigateable {
@ViewChild('overlay', { static: false }) overlay: FivOverlay;
@ViewChild('morphOverlay', { static: false }) morphOverlay: FivOverlay;
@ViewChild('viewer', { static: false }) viewer: ElementRef;
@ViewChild('morph', { static: false }) morphImage: ElementRef;
@ViewChild('slider', { static: false, read: ElementRef }) swiper: ElementRef;
@ViewChild('slider', { static: false }) slides: IonSlides;
@ViewChildren('slideImage') slideImages: QueryList<ElementRef>;
@ContentChildren(
forwardRef(() => FivGalleryImage),
{ descendants: true }
)
images: QueryList<FivGalleryImage>;
@ContentChildren(FivGalleryToolbar) toolbars: QueryList<FivGalleryToolbar>;
topToolbar: TemplateRef<any>;
bottomToolbar: TemplateRef<any>;
// properties for the slides
initialImage: FivGalleryImage;
activeIndex = 0;
inFullscreen = false;
zoomedIn = false;
controlsVisible = true;
slidesLoaded = false;
morphing = false;
backdrop = false;
backdropColor = '#000000ee';
@Input() pagerVisible = true;
@Input() ambient = false;
@Output() willOpen = new EventEmitter<FivGalleryImage>();
@Output() willClose = new EventEmitter<FivGalleryImage>();
@Output() didOpen = new EventEmitter<FivGalleryImage>();
@Output() didClose = new EventEmitter<FivGalleryImage>();
@Output() backdropChange = new EventEmitter<FivGalleryImage>();
$onDestroy = new Subject();
constructor(
private domCtrl: DomController,
private renderer: Renderer2,
private animation: AnimationBuilder,
private change: ChangeDetectorRef,
private platform: Platform,
private imageService: ImageService,
@Inject(DOCUMENT) private document: any
) {}
ngAfterContentInit(): void {
this.updateImagesIndex();
this.setupToolbars();
this.subscribeToImageEvents();
}
ngOnDestroy(): void {
this.$onDestroy.next();
}
subscribeToImageEvents() {
from(this.images.map(image => image.click))
.pipe(
mergeMap((value: EventEmitter<FivGalleryImage>) => value),
takeUntil<FivGalleryImage>(this.$onDestroy)
)
.subscribe(image => {
this.open(image);
});
}
updateImagesIndex() {
this.images.forEach((img, i) => {
img.index = i;
});
}
setupToolbars() {
this.toolbars.forEach(toolbar => {
if (toolbar.position === 'top') {
this.topToolbar = toolbar.content;
} else {
this.bottomToolbar = toolbar.content;
}
});
}
open(initial: FivGalleryImage) {
this.willOpen.emit(initial);
this.activeIndex = initial.index;
this.morphing = true;
this.overlay.show(50000);
this.initialImage = initial;
this.updateBackdrop(this.activeIndex);
this.initialImage.originalSrc = initial.src;
setTimeout(() => {
//wait a little for ripple
this.backdrop = true;
this.showControls();
this.morphIn();
}, 300);
}
morphIn() {
this.morphOverlay.show(49999);
const f = getPosition(this.initialImage.thumbnail);
const t = this.calculateImagePosition();
const tweenDone = new Subject();
tween(easeOutSine, 320)
.pipe(
fromToPixels(this.morphImage, f.top, t.top, 'top'),
fromToPixels(this.morphImage, f.left, t.left, 'left'),
fromToPixels(this.morphImage, f.height, t.height, 'height'),
fromToPixels(this.morphImage, f.width, t.width, 'width')
)
.subscribe({
complete: () => {
tweenDone.next();
}
});
zip(tweenDone, !this.slidesLoaded ? this.slides.ionSlidesDidLoad : of(true))
.pipe(
tap(() => {
this.morphing = false;
this.morphOverlay.hide();
this.didOpen.emit(this.initialImage);
this.swiper.nativeElement.swiper.on('click', () => {
this.handleSingleTap();
});
}),
takeUntil(this.$onDestroy)
)
.subscribe();
}
dismiss() {
this.close(false);
}
close(emit = true) {
if (emit) {
this.willClose.emit(this.initialImage);
}
this.backdrop = false;
const sameAsInitial =
this.images.toArray()[this.activeIndex].index === this.initialImage.index;
if (sameAsInitial) {
this.morphBack();
} else {
this.slideOut();
}
this.resetSlides(0);
if (this.inFullscreen) {
this.closeFullscreen();
}
this.slidesLoaded = false;
}
morphBack() {
const f = getPosition(this.getActiveImage());
const t = getPosition(this.initialImage.thumbnail);
this.overlay.hide();
this.morphOverlay.show();
tween(easeOutSine, 240)
.pipe(
fromToPixels(this.morphImage, f.top, t.top, 'top'),
fromToPixels(this.morphImage, f.left, t.left, 'left'),
fromToPixels(this.morphImage, f.height, t.height, 'height'),
fromToPixels(this.morphImage, f.width, t.width, 'width')
)
.subscribe({
complete: () => {
this.morphOverlay.hide();
this.didClose.emit(this.initialImage);
this.initialImage = null;
}
});
}
slideOut() {
this.overlay.hide();
this.morphOverlay.show();
this.morphImage.nativeElement.src = this.getActiveImage().nativeElement.src;
setPosition(this.morphImage, getPosition(this.getActiveImage()));
tween(easeOutSine, 240)
.pipe(
fromTo(
this.morphImage,
'transform',
0,
100,
(t: number) => `translateY(${t}%)`
)
)
.subscribe({
complete: () => {
this.morphImage.nativeElement.style.transform = '';
this.morphOverlay.hide();
this.didClose.emit(this.initialImage);
this.initialImage = null;
}
});
}
getActiveImage() {
return this.slideImages.toArray()[this.activeIndex];
}
transformSlides(progress: number) {
if (this.controlsVisible) {
this.hideControls();
}
this.domCtrl.write(() => {
this.renderer.setStyle(
this.viewer.nativeElement,
'transform',
`translateY(${progress * 120}px)`
);
});
}
resetSlides(progress: number) {
const reset = this.animation.build([
style({ transform: `translateY(${progress * 120}px)` }),
animate('150ms', style({ transform: `translateY(0px)` }))
]);
const animation = reset.create(this.viewer.nativeElement);
animation.play();
animation.onDone(() => {
animation.destroy();
this.transformSlides(0);
this.showControls();
});
}
slideDidChange() {
this.activeIndex = this.swiper.nativeElement.swiper.activeIndex;
}
ionSlideNextStart() {
if (this.slidesLoaded) {
this.updateBackdrop(this.activeIndex + 1);
}
}
ionSlidePrevStart() {
if (this.slidesLoaded) {
this.updateBackdrop(this.activeIndex - 1);
}
}
updateBackdrop(index: number) {
this.backdropColor = this.ambient
? this.imageService.getAverageRGB(
this.images.toArray()[index].thumbnail.nativeElement
)
: '#000000ee';
this.backdropChange.emit();
}
onSlidesLoad() {
this.slidesLoaded = true;
}
calculateImagePosition(): RectPosition {
const nH = this.initialImage.thumbnail.nativeElement.naturalHeight;
const nW = this.initialImage.thumbnail.nativeElement.naturalWidth;
let height = Math.min(nH, this.platform.height());
let width = Math.min(nW, this.platform.width());
const ratio = nW / nH;
if (ratio * height < width) {
width = height * ratio;
} else {
height = width / ratio;
}
const top = this.platform.height() / 2 - height / 2;
const left = this.platform.width() / 2 - width / 2;
const p = {
height: height,
width: width,
left: left,
top: top
};
return p;
}
fullscreen() {
if (this.inFullscreen) {
this.closeFullscreen();
} else {
this.openFullscreen();
}
}
openFullscreen() {
const elem = document.documentElement;
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem['mozRequestFullScreen']) {
/* Firefox */
elem['mozRequestFullScreen']();
} else if (elem['webkitRequestFullscreen']) {
/* Chrome, Safari and Opera */
elem['webkitRequestFullscreen']();
} else if (elem['msRequestFullscreen']) {
/* IE/Edge */
elem['msRequestFullscreen']();
}
this.inFullscreen = true;
}
closeFullscreen() {
this.inFullscreen = false;
if (this.document.exitFullscreen) {
this.document.exitFullscreen();
} else if (this.document.mozCancelFullScreen) {
/* Firefox */
this.document.mozCancelFullScreen();
} else if (this.document.webkitExitFullscreen) {
/* Chrome, Safari and Opera */
this.document.webkitExitFullscreen();
} else if (this.document.msExitFullscreen) {
/* IE/Edge */
this.document.msExitFullscreen();
}
}
zoom() {
if (this.zoomedIn) {
this.zoomOut();
} else {
this.zoomIn();
}
}
zoomIn() {
this.swiper.nativeElement.swiper.zoom.in();
this.zoomedIn = true;
}
zoomOut() {
this.swiper.nativeElement.swiper.zoom.out();
this.zoomedIn = false;
}
handleSingleTap() {
this.controlsVisible = !this.controlsVisible;
this.change.detectChanges();
}
hideControls() {
this.controlsVisible = false;
this.change.detectChanges();
}
showControls() {
this.controlsVisible = true;
this.change.detectChanges();
}
@HostListener('window:keyup', ['$event'])
keyEvent(event: KeyboardEvent) {
if (this.slidesLoaded && !this.morphing) {
this.handleKeyboardEvents(event);
}
}
handleKeyboardEvents(event: KeyboardEvent) {
if (event.key === 'ArrowRight') {
this.next();
return;
}
if (event.key === 'ArrowLeft') {
this.prev();
return;
}
if (event.key === 'ArrowDown' || event.key === 'Escape') {
this.close();
return;
}
}
next() {
if (this.slides && this.slidesLoaded) {
this.slides.slideNext();
}
}
prev() {
if (this.slides && this.slidesLoaded) {
this.slides.slidePrev();
}
}
}
export class Position {
top: number;
left: number;
height: number;
width: number;
translate?: number;
} | the_stack |
import createDebugLogger from "debug"
import EventEmitter from "events"
import format from "pg-format"
import TypedEventEmitter from "typed-emitter"
// Need to require `pg` like this to avoid ugly error message (see #15)
import pg = require("pg")
const connectionLogger = createDebugLogger("pg-listen:connection")
const notificationLogger = createDebugLogger("pg-listen:notification")
const paranoidLogger = createDebugLogger("pg-listen:paranoid")
const subscriptionLogger = createDebugLogger("pg-listen:subscription")
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))
interface PgNotification {
processId: number,
channel: string,
payload?: string
}
export interface PgParsedNotification {
processId: number,
channel: string,
payload?: any
}
interface PgListenEvents {
connected: () => void,
error: (error: Error) => void,
notification: (notification: PgParsedNotification) => void,
reconnect: (attempt: number) => void
}
type EventsToEmitterHandlers<Events extends Record<string, any>> = {
[channelName in keyof Events]: (payload: Events[channelName]) => void
}
export interface Options {
/**
* Using native PG client? Defaults to false.
*/
native?: boolean
/**
* Interval in ms to run a trivial query on the DB to see if
* the database connection still works.
* Defaults to 30s.
*/
paranoidChecking?: number | false
/**
* How much time to wait between reconnection attempts (if failed).
* Can also be a callback returning a delay in milliseconds.
* Defaults to 500 ms.
*/
retryInterval?: number | ((attempt: number) => number)
/**
* How many attempts to reconnect after connection loss.
* Defaults to no limit, but a default retryTimeout is set.
*/
retryLimit?: number
/**
* Timeout in ms after which to stop retrying and just fail. Defaults to 3000 ms.
*/
retryTimeout?: number
/**
* Custom function to control how the payload data is stringified on `.notify()`.
* Use together with the `serialize` option. Defaults to `JSON.parse`.
*/
parse?: (serialized: string) => any
/**
* Custom function to control how the payload data is stringified on `.notify()`.
* Use together with the `parse` option. Defaults to `JSON.stringify`.
*/
serialize?: (data: any) => string
}
function connect(connectionConfig: pg.ClientConfig | undefined, emitter: TypedEventEmitter<PgListenEvents>, options: Options) {
connectionLogger("Creating PostgreSQL client for notification streaming")
const { retryInterval = 500, retryLimit = Infinity, retryTimeout = 3000 } = options
const effectiveConnectionConfig: pg.ClientConfig = { ...connectionConfig, keepAlive: true }
const Client = options.native && pg.native ? pg.native.Client : pg.Client
const dbClient = new Client(effectiveConnectionConfig)
const getRetryInterval = typeof retryInterval === "function" ? retryInterval : () => retryInterval
const reconnect = async (onAttempt: (attempt: number) => void): Promise<pg.Client> => {
connectionLogger("Reconnecting to PostgreSQL for notification streaming")
const startTime = Date.now()
for (let attempt = 1; attempt < retryLimit || !retryLimit; attempt++) {
connectionLogger(`PostgreSQL reconnection attempt #${attempt}...`)
onAttempt(attempt)
try {
const newClient = new Client(effectiveConnectionConfig)
const connecting = new Promise((resolve, reject) => {
newClient.once("connect", resolve)
newClient.once("end", () => reject(Error("Connection ended.")))
newClient.once("error", reject)
})
await Promise.all([
newClient.connect(),
connecting
])
connectionLogger("PostgreSQL reconnection succeeded")
return newClient
} catch (error) {
connectionLogger("PostgreSQL reconnection attempt failed:", error)
await delay(getRetryInterval(attempt - 1))
if (retryTimeout && (Date.now() - startTime) > retryTimeout) {
throw new Error(`Stopping PostgreSQL reconnection attempts after ${retryTimeout}ms timeout has been reached.`)
}
}
}
throw new Error("Reconnecting notification client to PostgreSQL database failed.")
}
return {
dbClient,
reconnect
}
}
function forwardDBNotificationEvents (
dbClient: pg.Client,
emitter: TypedEventEmitter<PgListenEvents>,
parse: (stringifiedData: string) => any
) {
const onNotification = (notification: PgNotification) => {
notificationLogger(`Received PostgreSQL notification on "${notification.channel}":`, notification.payload)
let payload
try {
payload = notification.payload ? parse(notification.payload) : undefined
} catch (error) {
error.message = `Error parsing PostgreSQL notification payload: ${error.message}`
return emitter.emit("error", error)
}
emitter.emit("notification", {
processId: notification.processId,
channel: notification.channel,
payload
})
}
dbClient.on("notification", onNotification)
return function cancelNotificationForwarding () {
dbClient.removeListener("notification", onNotification)
}
}
function scheduleParanoidChecking (dbClient: pg.Client, intervalTime: number, reconnect: () => Promise<void>) {
const scheduledCheck = async () => {
try {
await dbClient.query("SELECT pg_backend_pid()")
paranoidLogger("Paranoid connection check ok")
} catch (error) {
paranoidLogger("Paranoid connection check failed")
connectionLogger("Paranoid connection check failed:", error)
await reconnect()
}
}
const interval = setInterval(scheduledCheck, intervalTime)
return function unschedule () {
clearInterval(interval)
}
}
export interface Subscriber<Events extends Record<string, any> = { [channel: string]: any }> {
/** Emits events: "error", "notification" & "redirect" */
events: TypedEventEmitter<PgListenEvents>;
/** For convenience: Subscribe to distinct notifications here, event name = channel name */
notifications: TypedEventEmitter<EventsToEmitterHandlers<Events>>;
/** Don't forget to call this asyncronous method before doing your thing */
connect(): Promise<void>;
close(): Promise<void>;
getSubscribedChannels(): string[];
listenTo(channelName: string): Promise<pg.QueryResult> | undefined;
notify<EventName extends keyof Events>(
channelName: any extends Events[EventName] ? EventName : void extends Events[EventName] ? never : EventName,
payload: Events[EventName] extends void ? never : Events[EventName]
): Promise<pg.QueryResult>;
notify<EventName extends keyof Events>(
channelName: void extends Events[EventName] ? EventName : never
): Promise<pg.QueryResult>;
unlisten(channelName: string): Promise<pg.QueryResult> | undefined;
unlistenAll(): Promise<pg.QueryResult>;
}
function createPostgresSubscriber<Events extends Record<string, any> = { [channel: string]: any }> (
connectionConfig?: pg.ClientConfig,
options: Options = {}
): Subscriber<Events> {
const {
paranoidChecking = 30000,
parse = JSON.parse,
serialize = JSON.stringify
} = options
const emitter = new EventEmitter() as TypedEventEmitter<PgListenEvents>
emitter.setMaxListeners(0) // unlimited listeners
const notificationsEmitter = new EventEmitter() as TypedEventEmitter<EventsToEmitterHandlers<Events>>
notificationsEmitter.setMaxListeners(0) // unlimited listeners
emitter.on("notification", (notification: PgParsedNotification) => {
notificationsEmitter.emit<any>(notification.channel, notification.payload)
})
const { dbClient: initialDBClient, reconnect } = connect(connectionConfig, emitter, options)
let closing = false
let dbClient = initialDBClient
let reinitializingRightNow = false
let subscribedChannels: Set<string> = new Set()
let cancelEventForwarding: () => void = () => undefined
let cancelParanoidChecking: () => void = () => undefined
const initialize = (client: pg.Client) => {
// Wire the DB client events to our exposed emitter's events
cancelEventForwarding = forwardDBNotificationEvents(client, emitter, parse)
dbClient.on("error", (error: any) => {
if (!reinitializingRightNow) {
connectionLogger("DB Client error:", error)
reinitialize()
}
})
dbClient.on("end", () => {
if (!reinitializingRightNow) {
connectionLogger("DB Client connection ended")
reinitialize()
}
})
if (paranoidChecking) {
cancelParanoidChecking = scheduleParanoidChecking(client, paranoidChecking, reinitialize)
}
}
// No need to handle errors when calling `reinitialize()`, it handles its errors itself
const reinitialize = async () => {
if (reinitializingRightNow || closing) {
return
}
reinitializingRightNow = true
try {
cancelParanoidChecking()
cancelEventForwarding()
dbClient.removeAllListeners()
dbClient.once("error", error => connectionLogger(`Previous DB client errored after reconnecting already:`, error))
dbClient.end()
dbClient = await reconnect(attempt => emitter.emit("reconnect", attempt))
initialize(dbClient)
const subscribedChannelsArray = Array.from(subscribedChannels)
if (subscriptionLogger.enabled) {
subscriptionLogger(`Re-subscribing to channels: ${subscribedChannelsArray.join(", ")}`)
}
await Promise.all(subscribedChannelsArray.map(
channelName => dbClient.query(`LISTEN ${format.ident(channelName)}`)
))
emitter.emit("connected")
} catch (error) {
error.message = `Re-initializing the PostgreSQL notification client after connection loss failed: ${error.message}`
connectionLogger(error.stack || error)
emitter.emit("error", error)
} finally {
reinitializingRightNow = false
}
}
// TODO: Maybe queue outgoing notifications while reconnecting
return {
/** Emits events: "error", "notification" & "redirect" */
events: emitter,
/** For convenience: Subscribe to distinct notifications here, event name = channel name */
notifications: notificationsEmitter,
/** Don't forget to call this asyncronous method before doing your thing */
async connect () {
initialize(dbClient)
await dbClient.connect()
emitter.emit("connected")
},
close () {
connectionLogger("Closing PostgreSQL notification listener.")
closing = true
cancelParanoidChecking()
return dbClient.end()
},
getSubscribedChannels () {
return Array.from(subscribedChannels)
},
listenTo (channelName: string) {
if (subscribedChannels.has(channelName)) {
return
}
subscriptionLogger(`Subscribing to PostgreSQL notification "${channelName}"`)
subscribedChannels.add(channelName)
return dbClient.query(`LISTEN ${format.ident(channelName)}`)
},
notify (channelName: string, payload?: any) {
notificationLogger(`Sending PostgreSQL notification to "${channelName}":`, payload)
if (payload !== undefined) {
const serialized = serialize(payload)
return dbClient.query(`NOTIFY ${format.ident(channelName)}, ${format.literal(serialized)}`)
} else {
return dbClient.query(`NOTIFY ${format.ident(channelName)}`)
}
},
unlisten (channelName: string) {
if (!subscribedChannels.has(channelName)) {
return
}
subscriptionLogger(`Unsubscribing from PostgreSQL notification "${channelName}"`)
subscribedChannels.delete(channelName)
return dbClient.query(`UNLISTEN ${format.ident(channelName)}`)
},
unlistenAll () {
subscriptionLogger("Unsubscribing from all PostgreSQL notifications.")
subscribedChannels = new Set()
return dbClient.query(`UNLISTEN *`)
}
}
}
export default createPostgresSubscriber | the_stack |
import { createSelector } from "reselect";
import { IRootState } from "../../shared/store";
import { IDescriptor, IInspectorState } from "../model/types";
import { Descriptor } from "photoshop/dist/types/UXP";
import { Helpers } from "../classes/Helpers";
import { cloneDeep } from "lodash";
export const all = (state:IRootState):IInspectorState => state.inspector;
export const getMainTabID = createSelector([all], s => s.activeSection);
export const getModeTabID = createSelector([all], s => s.inspector.activeTab);
export const getSelectedTargetReference = createSelector([all], s => s.selectedReferenceType);
export const getFilterBySelectedReferenceType = createSelector([all], s => s.filterBySelectedReferenceType);
export const getTargetReference = createSelector([all], s => s.targetReference);
export const getAutoUpdate = createSelector([all],s=>s.settings.autoUpdateInspector);
export const getAllDescriptors = createSelector([all], s => s.descriptors);
export const getSelectedDescriptors = createSelector([all], s => s.descriptors.filter((d) => d.selected === true));
export const getSelectedDescriptorsUUID = createSelector([getSelectedDescriptors], s => s.map(d => d.id));
export const getPropertySettings = createSelector([all],s=>s.settings.properties);
export const getLockedSelection = createSelector([getSelectedDescriptors], s => s.some(d => d.locked));
export const getPinnedSelection = createSelector([getSelectedDescriptors], s => s.some(d => d.pinned));
export const getRemovableSelection = createSelector([getLockedSelection], s => !s);
export const getActiveTargetReference = createSelector([getTargetReference, getSelectedTargetReference], (targets, selected) => {
const result = targets?.find(item => item.type === selected);
return (result || null);
});
export const getInspectorSettings = createSelector([all], (s) => {
return s.settings;
});
export const getFontSizeSettings = createSelector([getInspectorSettings], (s) => {
return s.fontSize;
});
export const getLeftColumnWidth = createSelector([getInspectorSettings], (s) => {
return s.leftColumnWidthPx;
});
export const getNeverRecordActionNames = createSelector([getInspectorSettings], s => s.neverRecordActionNames);
// will exclude undefined objects in array
export const getActiveTargetReferenceForAM = createSelector([getTargetReference, getSelectedTargetReference], (targets, selected) => {
const result = targets?.find(item => item.type === selected);
if (!result) { return null; }
const newRes = {
...result,
data: result.data.filter(ref => ref.content.value !== ""),
};
return (newRes || null);
});
export const getAddAllowed = createSelector([getActiveTargetReference], s => {
if (s) {
if (s.type === "generator") {
return true;
}
if (s.type === "listener") {
return false;
}
for (const key in s.data) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if ((s.data as any)[key] === "undefined") {
return false;
}
}
return true;
}
return false;
});
export const getDescriptorsListView = createSelector([getAllDescriptors, getActiveTargetReference, getFilterBySelectedReferenceType,getInspectorSettings], (allDesc, activeRefFilter, rootFilter,settings) => {
const pinned = allDesc.filter(i => i.pinned);
const notPinned = allDesc.filter(i => !i.pinned);
let reordered = [...notPinned, ...pinned];
const { searchTerm } = settings;
if (searchTerm) {
reordered = reordered.filter(item => (item.title.toLowerCase().includes(searchTerm.toLowerCase())));
}
/*
if (rootFilter === "off" && activeRefFilter?.type !== "listener") {
// handle this!!
return reordered;
}
*/
//let filtered: IDescriptor[] = reordered;
let filtered = reordered.filter((desc: IDescriptor) => {
if (rootFilter === "off") {
return true;
}
const origRefFilter = desc.originalReference;
if (activeRefFilter?.type !== origRefFilter.type) {
return false;
}
if (activeRefFilter?.type !== "listener") {
for (let i = 0, len = activeRefFilter.data.length; i < len; i++) {
if (activeRefFilter.data[i].content.filterBy === "off") {
return true;
}
if (activeRefFilter.data[i].content.value !== origRefFilter.data[i].content.value) {
return false;
}
}
}
return true;
});
if (activeRefFilter?.type === "listener") {
if (settings.listenerFilterType === "exclude" && settings.listenerExclude.join(";").trim().length) {
filtered = filtered.filter(item =>
!settings.listenerExclude.some(str => (item.originalData as Descriptor)?._obj?.includes(str.trim())),
);
} else if (settings.listenerFilterType === "include" && settings.listenerInclude.join(";").trim().length) {
filtered = filtered.filter(item =>
settings.listenerInclude.some(str => (item.originalData as Descriptor)?._obj?.includes(str.trim())),
);
}
}
console.log("!!!");
if (settings.groupDescriptors === "strict") {
filtered = cloneDeep(filtered);
filtered.reverse();
// group (remove) duplicates
for (let i = 0; i < filtered.length-1; i++) {
const element = filtered[i];
for (let j = i+1; j < filtered.length; j++) {
const next = filtered[j];
if (next.crc === element.crc) {
filtered.splice(j, 1);
j -= 1;
element.groupCount = (!element.groupCount) ? 2 : element.groupCount+1;
}
}
}
filtered.reverse();
}
return filtered;
});
export const getActiveReferenceProperty = createSelector([getActiveTargetReference], (t) => {
return t?.data.find(i => i.subType === "property")?.content;
});
export const getActiveReferenceGuide = createSelector([getActiveTargetReference], (t) => {
return t?.data.find(i => i.subType === "guide")?.content;
});
export const getActiveReferencePath = createSelector([getActiveTargetReference], (t) => {
return t?.data.find(i => i.subType === "path")?.content;
});
export const getActiveReferenceChannel = createSelector([getActiveTargetReference], (t) => {
return t?.data.find(i => i.subType === "channel")?.content;
});
export const getActiveReferenceActionSet = createSelector([getActiveTargetReference], (t) => {
return t?.data.find(i => i.subType === "actionset")?.content;
});
export const getActiveReferenceActionItem = createSelector([getActiveTargetReference], (t) => {
return t?.data.find(i => i.subType === "action")?.content;
});
export const getActiveReferenceCommand = createSelector([getActiveTargetReference], (t) => {
return t?.data.find(i => i.subType === "command")?.content;
});
export const getActiveReferenceHistory = createSelector([getActiveTargetReference], (t) => {
return t?.data.find(i => i.subType === "history")?.content;
});
export const getActiveReferenceSnapshot = createSelector([getActiveTargetReference], (t) => {
return t?.data.find(i => i.subType === "snapshot")?.content;
});
export const getActiveDescriptors = createSelector([all], s => {
const selected = s.descriptors.filter(d => d.selected);
return selected;
});
export const getAutoActiveDescriptor = createSelector([getActiveDescriptors, getDescriptorsListView], (activeDescs, view) => {
const list = view;//.filter(item => !item.pinned);
if (activeDescs.length === 0) {
if (list.length) {
return list[list.length-1];
}
}
return null;
});
export const getSecondaryAutoActiveDescriptor = createSelector([getActiveDescriptors, getDescriptorsListView], (activeDescs, view) => {
const list = view;//.filter(item => !item.pinned);
if (activeDescs.length === 0) {
if (list.length >= 2) {
return list[list.length-2];
}
}
return null;
});
export const getAutoSelectedUUIDs = createSelector([getAutoActiveDescriptor, getSecondaryAutoActiveDescriptor,getModeTabID], (first,second,mode) => {
const f = first?.id;
const s = (mode==="difference") ? second?.id : null;
const result: string[] = [];
if (f) { result.push(f); }
if (s) { result.push(s); }
return result;
});
export const getHasAutoActiveDescriptor = createSelector([getAutoActiveDescriptor], d => {
return !!d;
});
/*
export const getPlayableReference = createSelector([getActiveDescriptorCalculatedReference], (reference) => {
if (selected.length > 1) {
return "Select 1 descriptor";
} else if (selected.length === 1) {
return JSON.stringify(selected[0].calculatedReference, null, 3);
} else if (autoActive) {
return JSON.stringify(autoActive.calculatedReference, null, 3);
} else {
return "Add some descriptor";
}
});*/
export const getActiveDescriptorOriginalReference = createSelector([getActiveDescriptors, getAutoActiveDescriptor], (selected, autoActive) => {
if (selected.length > 1) {
return "Select 1 descriptor";
} else if (selected.length === 1) {
return JSON.stringify(selected[0].originalReference, null, 3);
} else if (autoActive) {
return JSON.stringify(autoActive.originalReference, null, 3);
} else {
return "Add some descriptor";
}
});
export const getActiveTargetReferenceListenerCategory = createSelector([getActiveTargetReference], (t) => {
if (!t) { return null;}
const result = t.data.find(i => i.subType === "listenerCategory")?.content;
return (result===undefined) ? null : result;
});
export const getActiveTargetDocument = createSelector([getActiveTargetReference], (t) => {
if (!t) { return null;}
const result = t.data.find(i => i.subType === "document")?.content;
return (result===undefined) ? null : result;
});
export const getActiveTargetLayer = createSelector([getActiveTargetReference], (t) => {
if (!t) { return null;}
const result = t.data.find(i => i.subType === "layer")?.content;
return (result===undefined) ? null : result;
});
export const getReplayEnabled = createSelector([getActiveDescriptors], (selected) => {
if (selected.length < 1) {
return false;
}
if (selected.some(item => item.originalReference.data.some(subitem => subitem.content.value === "reply" || subitem.content.value === "dispatch"))) {
return false;
}
return true;
});
export const getRanameEnabled = createSelector([getDescriptorsListView], (all) => {
const selected = all.filter(d => d.selected);
if (selected?.length !== 1) {
return false;
}
return (!selected[0].groupCount || selected[0].groupCount === 1);
});
/*export const getColumnSizesPercentage = createSelector([getInspectorSettings], (s) => {
debugger;
const leftColumnPerc = Helpers.pxToPanelWidthPercentage("inspector", s.leftColumnWidthPx);
return [leftColumnPerc,100-leftColumnPerc] as [number,number];
});*/ | the_stack |
import { css, html, BaseCustomWebComponentConstructorAppend } from '@node-projects/base-custom-webcomponent';
import { ITreeView } from './ITreeView';
import { IDesignItem } from '../../item/IDesignItem';
import { ISelectionChangedEvent } from '../../services/selectionService/ISelectionChangedEvent';
import { NodeType } from '../../item/NodeType';
import { assetsPath } from '../../../Constants';
export class TreeViewExtended extends BaseCustomWebComponentConstructorAppend implements ITreeView {
private _treeDiv: HTMLTableElement;
private _tree: Fancytree.Fancytree;
private _filter: HTMLInputElement;
static override readonly style = css`
* {
touch-action: none;
}
span.drag-source {
border: 1px solid grey;
border-radius: 3px;
padding: 2px;
background-color: silver;
}
span.fancytree-node.fancytree-drag-source {
outline: 1px dotted grey;
}
span.fancytree-node.fancytree-drop-accept {
outline: 1px dotted green;
}
span.fancytree-node.fancytree-drop-reject {
outline: 1px dotted red;
}
#tree ul {
border: none;
}
#tree ul:focus {
outline: none;
}
span.fancytree-title {
align-items: center;
flex-direction: row;
display: inline-flex;
}
td {
white-space: nowrap;
}
td:nth-child(n+2) {
text-align: center;
}
td > img {
vertical-align: middle;
}
table.fancytree-ext-table tbody tr.fancytree-selected {
background-color: #bebebe;
}
`;
static override readonly template = html`
<div style="height: 100%;">
<input id="input" style="width: 100%; height:21px;" placeholder="Filter..." autocomplete="off">
<div style="height: calc(100% - 23px); overflow: auto;">
<table id="treetable" style="min-width: 100%;">
<colgroup>
<col width="*">
<col width="25px">
<col width="25px">
<col width="25px">
</colgroup>
<thead style="display: none;">
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
</table>
</div>
</div>`;
constructor() {
super();
let externalCss = document.createElement('style');
externalCss.innerHTML = '@import url("./node_modules/jquery.fancytree/dist/skin-win8/ui.fancytree.css");';
this.shadowRoot.appendChild(externalCss);
this._filter = this._getDomElement<HTMLInputElement>('input');
this._filter.onkeyup = () => {
let match = this._filter.value;
this._tree.filterNodes((node) => {
return new RegExp(match, "i").test(node.title);
})
}
this._treeDiv = this._getDomElement<HTMLTableElement>('treetable');
/*this._treeDiv = document.createElement('div');
this._treeDiv.style.height = 'calc(100% - 21px)'
this._treeDiv.style.overflow = 'auto';
this._treeDiv.setAttribute('id', 'tree');
this.shadowRoot.appendChild(this._treeDiv);*/
}
_showHideAtDesignTimeState(img: HTMLImageElement, designItem: IDesignItem) {
if (designItem.hideAtDesignTime)
img.src = assetsPath + "images/treeview/eyeclose.png";
else
img.src = assetsPath + "images/treeview/eyeopen.png";
}
_switchHideAtDesignTimeState(img: HTMLImageElement, designItem: IDesignItem) {
designItem.hideAtDesignTime = !designItem.hideAtDesignTime;
this._showHideAtDesignTimeState(img, designItem);
}
_showLockAtDesignTimeState(img: HTMLImageElement, designItem: IDesignItem) {
if (designItem.lockAtDesignTime)
img.src = assetsPath + "images/treeview/lock.png";
else
img.src = assetsPath + "images/treeview/dot.png";
}
_switchLockAtDesignTimeState(img: HTMLImageElement, designItem: IDesignItem) {
designItem.lockAtDesignTime = !designItem.lockAtDesignTime;
this._showLockAtDesignTimeState(img, designItem);
}
_showHideAtRunTimeState(img: HTMLImageElement, designItem: IDesignItem) {
if (designItem.hideAtRunTime)
img.src = assetsPath + "images/treeview/eyeclose.png";
else
img.src = assetsPath + "images/treeview/eyeopen.png";
}
_switchHideAtRunTimeState(img: HTMLImageElement, designItem: IDesignItem) {
designItem.hideAtRunTime = !designItem.hideAtRunTime;
this._showHideAtRunTimeState(img, designItem);
}
async ready() {
//this._treeDiv.classList.add('fancytree-connectors');
$(this._treeDiv).fancytree(<Fancytree.FancytreeOptions>{
icon: true, //atm, maybe if we include icons for specific elements
extensions: ['childcounter', 'dnd5', 'multi', 'filter', 'table'],
quicksearch: true,
source: [],
table: {
indentation: 20, // indent 20px per node level
nodeColumnIdx: 0, // render the node title into the 2nd column
checkboxColumnIdx: 0, // render the checkboxes into the 1st column
},
activate: (event, data) => {
let node = data.node;
let designItem: IDesignItem = node.data.ref;
if (designItem)
designItem.instanceServiceContainer.selectionService.setSelectedElements([designItem]);
},
createNode: (event, data) => {
let node = data.node;
if (node.tr.children[1]) {
let designItem: IDesignItem = node.data.ref;
if (designItem.nodeType === NodeType.Element && designItem !== designItem.instanceServiceContainer.contentService.rootDesignItem) {
/*
let toolTipImg: HTMLImageElement;
(<HTMLElement>node.tr.children[0]).onmouseenter = (e) => {
toolTipImg = document.createElement("img");
Screenshot.takeScreenshot(designItem.element).then(x => { if (toolTipImg) toolTipImg.src = x; });
toolTipImg.style.position = 'absolute';
let r = node.tr.children[0].getBoundingClientRect();
toolTipImg.style.left = (e.x + 5 - r.left) + 'px';
toolTipImg.style.top = (e.y + 5 - r.top) + 'px';
(<HTMLElement>node.tr.children[0]).appendChild(toolTipImg);
}
(<HTMLElement>node.tr.children[0]).onmousemove = (e) => {
if (toolTipImg) {
let r = node.tr.children[0].getBoundingClientRect();
toolTipImg.style.left = (e.x + 5 - r.left) + 'px';
toolTipImg.style.top = (e.y + 5 - r.top) + 'px';
}
}
(<HTMLElement>node.tr.children[0]).onmouseout = (e) => {
if (toolTipImg) {
toolTipImg.parentNode?.removeChild(toolTipImg);
toolTipImg = null;
}
}
*/
let img = document.createElement('img');
this._showHideAtDesignTimeState(img, designItem);
img.onclick = () => this._switchHideAtDesignTimeState(img, designItem);
node.tr.children[1].appendChild(img);
let imgL = document.createElement('img');
this._showLockAtDesignTimeState(imgL, designItem);
imgL.onclick = () => this._switchLockAtDesignTimeState(imgL, designItem);
node.tr.children[2].appendChild(imgL);
let imgH = document.createElement('img');
this._showHideAtRunTimeState(imgH, designItem);
imgH.onclick = () => this._switchHideAtRunTimeState(imgH, designItem);
node.tr.children[3].appendChild(imgH);
}
}
},
dnd5: {
dropMarkerParent: this.shadowRoot,
preventRecursion: true, // Prevent dropping nodes on own descendants
preventVoidMoves: false,
dropMarkerOffsetX: -24,
dropMarkerInsertOffsetX: -16,
dragStart: (node, data) => {
/* This function MUST be defined to enable dragging for the tree.
*
* Return false to cancel dragging of node.
* data.dataTransfer.setData() and .setDragImage() is available
* here.
*/
// Set the allowed effects (i.e. override the 'effectAllowed' option)
data.effectAllowed = "all";
// Set a drop effect (i.e. override the 'dropEffectDefault' option)
// data.dropEffect = "link";
data.dropEffect = "copy";
// We could use a custom image here:
// data.dataTransfer.setDragImage($("<div>TEST</div>").appendTo("body")[0], -10, -10);
// data.useDefaultImage = false;
// Return true to allow the drag operation
return true;
},
// dragDrag: function(node, data) {
// logLazy("dragDrag", null, 2000,
// "T1: dragDrag: " + "data: " + data.dropEffect + "/" + data.effectAllowed +
// ", dataTransfer: " + data.dataTransfer.dropEffect + "/" + data.dataTransfer.effectAllowed );
// },
// dragEnd: function(node, data) {
// node.debug( "T1: dragEnd: " + "data: " + data.dropEffect + "/" + data.effectAllowed +
// ", dataTransfer: " + data.dataTransfer.dropEffect + "/" + data.dataTransfer.effectAllowed, data);
// alert("T1: dragEnd")
// },
// --- Drop-support:
dragEnter: (node, data) => {
// data.dropEffect = "copy";
return true;
},
dragOver: (node, data) => {
// Assume typical mapping for modifier keys
data.dropEffect = data.dropEffectSuggested;
// data.dropEffect = "move";
},
dragDrop: (node, data) => {
/* This function MUST be defined to enable dropping of items on
* the tree.
*/
let newNode,
transfer = data.dataTransfer,
sourceNodes = data.otherNodeList,
mode = data.dropEffect;
if (data.hitMode === "after") {
// If node are inserted directly after tagrget node one-by-one,
// this would reverse them. So we compensate:
sourceNodes.reverse();
}
if (data.otherNode) {
// Drop another Fancytree node from same frame (maybe a different tree however)
//let sameTree = (data.otherNode.tree === data.tree);
if (mode === "move") {
data.otherNode.moveTo(node, data.hitMode);
} else {
newNode = data.otherNode.copyTo(node, data.hitMode);
if (mode === "link") {
newNode.setTitle("Link to " + newNode.title);
} else {
newNode.setTitle("Copy of " + newNode.title);
}
}
} else if (data.otherNodeData) {
// Drop Fancytree node from different frame or window, so we only have
// JSON representation available
//@ts-ignore
node.addChild(data.otherNodeData, data.hitMode);
} else if (data.files.length) {
// Drop files
for (let i = 0; i < data.files.length; i++) {
let file = data.files[i];
node.addNode({ title: "'" + file.name + "' (" + file.size + " bytes)" }, data.hitMode);
// var url = "'https://example.com/upload",
// formData = new FormData();
// formData.append("file", transfer.files[0])
// fetch(url, {
// method: "POST",
// body: formData
// }).then(function() { /* Done. Inform the user */ })
// .catch(function() { /* Error. Inform the user */ });
}
} else {
// Drop a non-node
node.addNode({ title: transfer.getData("text") }, data.hitMode);
}
node.setExpanded();
},
},
multi: {
mode: ""
},
filter: {
autoApply: true, // Re-apply last filter if lazy data is loaded
autoExpand: false, // Expand all branches that contain matches while filtered
counter: true, // Show a badge with number of matching child nodes near parent icons
fuzzy: true, // Match single characters in order, e.g. 'fb' will match 'FooBar'
hideExpandedCounter: true, // Hide counter badge if parent is expanded
hideExpanders: false, // Hide expanders if all child nodes are hidden by filter
highlight: true, // Highlight matches by wrapping inside <mark> tags
leavesOnly: false, // Match end nodes only
nodata: true, // Display a 'no data' status node if result is empty
mode: "hide" // Grayout unmatched nodes (pass "hide" to remove unmatched node instead)
},
childcounter: {
deep: true,
hideZeros: true,
hideExpanded: true
},
loadChildren: (event, data) => {
// update node and parent counters after lazy loading
//@ts-ignore
data.node.updateCounters();
}
});
//@ts-ignore
this._tree = $.ui.fancytree.getTree(this._treeDiv);
this._treeDiv.children[0].classList.add('fancytree-connectors');
}
public createTree(rootItem: IDesignItem): void {
if (this._tree) {
this._recomputeTree(rootItem);
}
}
public selectionChanged(event: ISelectionChangedEvent) {
if (event.selectedElements.length > 0) {
this._highlight(event.selectedElements);
}
}
private _recomputeTree(rootItem: IDesignItem): void {
this._tree.getRootNode().removeChildren();
this._getChildren(rootItem, null);
this._tree.expandAll();
//@ts-ignore
this._tree.getRootNode().updateCounters();
}
private _getChildren(item: IDesignItem, currentNode: Fancytree.FancytreeNode): any {
if (currentNode == null) {
currentNode = this._tree.getRootNode();
}
const newNode = currentNode.addChildren({
title: item.nodeType === NodeType.Element ? item.name + " " + (item.id ? ('#' + item.id) : '') : '<small><small><small>#' + (item.nodeType === NodeType.TextNode ? 'text' : 'comment') + ' </small></small></small> ' + item.content,
folder: item.children.length > 0 ? true : false,
//@ts-ignore
ref: item
});
for (let i of item.children()) {
if (i.nodeType !== NodeType.TextNode || i.content?.trim()) {
this._getChildren(i, newNode);
}
}
}
private _highlight(activeElements: IDesignItem[]) {
if (activeElements != null) {
this._tree.visit((node) => {
//@ts-ignore
if (activeElements.indexOf(node.data.ref) >= 0) {
node.setSelected(true);
} else {
node.setSelected(false);
}
});
}
}
}
customElements.define('node-projects-tree-view-extended', TreeViewExtended); | the_stack |
import {assert} from '../../platform/chai-web.js';
import {Manifest} from '../../runtime/manifest.js';
import {Dictionary} from '../../utils/lib-utils.js';
import {SchemaGraph, SchemaNode} from '../schema2graph.js';
interface NodeInfo {
name: string; // generated class name
parents: string; // parent class names, sorted and stringified
children: string; // child class names, sorted and stringified
added: string; // addedFields list, sorted and stringified
}
function convert(graph: SchemaGraph) {
const nodes: NodeInfo[] = [];
const aliases: Dictionary<string[]> = {};
const fullName = (node: SchemaNode) => node.sources[0].fullName;
for (const node of graph.walk()) {
nodes.push({
name: fullName(node),
parents: node.parents.map(p => fullName(p)).sort().join(', '),
children: node.children.map(p => fullName(p)).sort().join(', '),
added: node.addedFields.sort().join(', ')
});
if (node.sources.length) {
aliases[fullName(node)] = [...node.sources.map(p => p.fullName)].sort();
}
}
return {nodes, aliases};
}
describe('schema2graph', () => {
it('empty graph', async () => {
const manifest = await Manifest.parse(`
particle E
root: consumes Slot
tile: provides Slot
`);
const graph = new SchemaGraph(manifest.particles[0]);
assert.isEmpty([...graph.walk()]);
});
it('linear graph', async () => {
const manifest = await Manifest.parse(`
particle L
h1: reads * {a: Text} // 1 -> 2 -> 3
h2: reads * {a: Text, b: Text}
h3: reads * {a: Text, b: Text, c: Text}
`);
const res = convert(new SchemaGraph(manifest.particles[0]));
assert.deepStrictEqual(res.nodes, [
{name: 'L_H1', parents: '', children: 'L_H2', added: 'a'},
{name: 'L_H2', parents: 'L_H1', children: 'L_H3', added: 'b'},
{name: 'L_H3', parents: 'L_H2', children: '', added: 'c'},
]);
assert.deepStrictEqual(res.aliases, {
'L_H1': ['L_H1'],
'L_H2': ['L_H2'],
'L_H3': ['L_H3']
});
});
it('diamond graph', async () => {
const manifest = await Manifest.parse(`
particle D
h1: reads * {a: Text} // 1
h2: reads * {a: Text, b: Text} // 2 3
h3: reads * {a: Text, c: Text} // 4
h4: reads * {a: Text, b: Text, c: Text}
`);
const res = convert(new SchemaGraph(manifest.particles[0]));
assert.deepStrictEqual(res.nodes, [
{name: 'D_H1', parents: '', children: 'D_H2, D_H3', added: 'a'},
{name: 'D_H2', parents: 'D_H1', children: 'D_H4', added: 'b'},
{name: 'D_H3', parents: 'D_H1', children: 'D_H4', added: 'c'},
{name: 'D_H4', parents: 'D_H2, D_H3', children: '', added: ''},
]);
assert.deepStrictEqual(res.aliases, {
'D_H1': ['D_H1'],
'D_H2': ['D_H2'],
'D_H3': ['D_H3'],
'D_H4': ['D_H4']
});
});
it('aliased schemas', async () => {
const manifest = await Manifest.parse(`
particle A
h1: reads * {a: Text} // 1
h2: reads * {a: Text, b: Text} // 2 3
h3: reads * {a: Text, c: Text} // 4
h4: reads * {a: Text, b: Text, c: Text}
d2: reads * {a: Text, b: Text}
d4: reads * {a: Text, b: Text, c: Text}
`);
const res = convert(new SchemaGraph(manifest.particles[0]));
assert.deepStrictEqual(res.nodes, [
{name: 'A_H1', parents: '', children: 'A_H2, A_H3', added: 'a'},
{name: 'A_H2', parents: 'A_H1', children: 'A_H4', added: 'b'},
{name: 'A_H3', parents: 'A_H1', children: 'A_H4', added: 'c'},
{name: 'A_H4', parents: 'A_H2, A_H3', children: '', added: ''},
]);
assert.deepStrictEqual(res.aliases, {
'A_H1': ['A_H1'],
'A_H2': ['A_D2', 'A_H2'],
'A_H3': ['A_H3'],
'A_H4': ['A_D4', 'A_H4'],
});
});
it('pyramid and vee as separate graphs', async () => {
const manifest = await Manifest.parse(`
particle S
p0: reads * {a: Text} // 0
p1: reads * {a: Text, b: Text} // 1 2
p2: reads * {a: Text, c: Text} // 3 4
p3: reads * {a: Text, b: Text, d: Text}
p4: reads * {a: Text, c: Text, e: Text}
v5: reads * {w: URL} // 5 6
v6: reads * {x: URL} // 7 8
v7: reads * {w: URL, y: URL} // 9
v8: reads * {x: URL, z: URL}
v9: reads * {w: URL, y: URL, x: URL, z: URL}
`);
const res = convert(new SchemaGraph(manifest.particles[0]));
// Traversal is breadth-first; nodes within a row are in the same order as in the manifest.
assert.deepStrictEqual(res.nodes, [
{name: 'S_P0', parents: '', children: 'S_P1, S_P2', added: 'a'},
{name: 'S_V5', parents: '', children: 'S_V7', added: 'w'},
{name: 'S_V6', parents: '', children: 'S_V8', added: 'x'},
{name: 'S_P1', parents: 'S_P0', children: 'S_P3', added: 'b'},
{name: 'S_P2', parents: 'S_P0', children: 'S_P4', added: 'c'},
{name: 'S_V7', parents: 'S_V5', children: 'S_V9', added: 'y'},
{name: 'S_V8', parents: 'S_V6', children: 'S_V9', added: 'z'},
{name: 'S_P3', parents: 'S_P1', children: '', added: 'd'},
{name: 'S_P4', parents: 'S_P2', children: '', added: 'e'},
{name: 'S_V9', parents: 'S_V7, S_V8', children: '', added: ''},
]);
assert.deepStrictEqual(res.aliases, {
'S_P0': ['S_P0'],
'S_V5': ['S_V5'],
'S_V6': ['S_V6'],
'S_P1': ['S_P1'],
'S_P2': ['S_P2'],
'S_V7': ['S_V7'],
'S_V8': ['S_V8'],
'S_P3': ['S_P3'],
'S_P4': ['S_P4'],
'S_V9': ['S_V9']
});
});
it('mesh graph', async () => {
// 1:a 2:b
// | \/ |
// | /\ |
// 3:abc 4:abd
// \ /
// 5:abcde
const manifest = await Manifest.parse(`
particle M
h1: reads * {a: Text}
h2: reads * {b: Text}
h3: reads * {a: Text, b: Text, c: Text}
h4: reads * {a: Text, b: Text, d: Text}
h5: reads * {a: Text, b: Text, c: Text, d: Text, e: Text}
`);
const res = convert(new SchemaGraph(manifest.particles[0]));
assert.deepStrictEqual(res.nodes, [
{name: 'M_H1', parents: '', children: 'M_H3, M_H4', added: 'a'},
{name: 'M_H2', parents: '', children: 'M_H3, M_H4', added: 'b'},
{name: 'M_H3', parents: 'M_H1, M_H2', children: 'M_H5', added: 'c'},
{name: 'M_H4', parents: 'M_H1, M_H2', children: 'M_H5', added: 'd'},
{name: 'M_H5', parents: 'M_H3, M_H4', children: '', added: 'e'},
]);
assert.deepStrictEqual(res.aliases, {
'M_H1': ['M_H1'],
'M_H2': ['M_H2'],
'M_H3': ['M_H3'],
'M_H4': ['M_H4'],
'M_H5': ['M_H5']
});
});
it('jump graph', async () => {
// Check that a descendant connection that jumps past multiple levels of the
// graph doesn't cause incorrect ordering.
//
// 1:a 2:x
// | |
// 3:ab |
// | |
// 4:abc |
// \ |
// 5:abcx
const manifest = await Manifest.parse(`
particle J
h1: reads * {a: Text}
h2: reads * {x: Text}
h3: reads * {a: Text, b: Text}
h4: reads * {a: Text, b: Text, c: Text}
h5: reads * {a: Text, b: Text, c: Text, x: Text}
`);
const res = convert(new SchemaGraph(manifest.particles[0]));
assert.deepStrictEqual(res.nodes, [
{name: 'J_H1', parents: '', children: 'J_H3', added: 'a'},
{name: 'J_H2', parents: '', children: 'J_H5', added: 'x'},
{name: 'J_H3', parents: 'J_H1', children: 'J_H4', added: 'b'},
{name: 'J_H4', parents: 'J_H3', children: 'J_H5', added: 'c'},
{name: 'J_H5', parents: 'J_H2, J_H4', children: '', added: ''},
]);
assert.deepStrictEqual(res.aliases, {
'J_H1': ['J_H1'],
'J_H2': ['J_H2'],
'J_H3': ['J_H3'],
'J_H4': ['J_H4'],
'J_H5': ['J_H5']
});
});
it('unconnected graph with aliased schema', async () => {
// Use more realistic field names and connection types, and check that schema names are
// ignored outside of the more-specific-than comparison.
const manifest = await Manifest.parse(`
particle Test
name: reads Widget {t: Text}
age: writes Data {n: Number}
moniker: reads [Thing Product {z: Text}]
oldness: reads writes [Data {n: Number}]
mainAddress: writes &* {u: URL}
`);
const res = convert(new SchemaGraph(manifest.particles[0]));
assert.deepStrictEqual(res.nodes, [
{name: 'Test_Name', parents: '', children: '', added: 't'},
{name: 'Test_Age', parents: '', children: '', added: 'n'},
{name: 'Test_Moniker', parents: '', children: '', added: 'z'},
{name: 'Test_MainAddress', parents: '', children: '', added: 'u'},
]);
assert.deepStrictEqual(res.aliases, {
'Test_Name': ['Test_Name'],
'Test_Age': ['Test_Age', 'Test_Oldness'],
'Test_Moniker': ['Test_Moniker'],
'Test_MainAddress': ['Test_MainAddress']
});
});
it('collections and handle-level references do not affect the graph', async () => {
const manifest = await Manifest.parse(`
particle W
h1: reads &* {a: Text}
h2: reads [* {a: Text, b: Text}]
h3: reads [&* {a: Text, b: Text, c: Text}]
h4: reads * {a: Text, b: Text, r: [&* {d: Text}]}
`);
const res = convert(new SchemaGraph(manifest.particles[0]));
assert.deepStrictEqual(res.nodes, [
{name: 'W_H1', parents: '', children: 'W_H2', added: 'a'},
{name: 'W_H4_R', parents: '', children: '', added: 'd'},
{name: 'W_H2', parents: 'W_H1', children: 'W_H3, W_H4', added: 'b'},
{name: 'W_H3', parents: 'W_H2', children: '', added: 'c'},
{name: 'W_H4', parents: 'W_H2', children: '', added: 'r'},
]);
assert.deepStrictEqual(res.aliases, {
'W_H1': ['W_H1'],
'W_H4_R': ['W_H4_R'],
'W_H2': ['W_H2'],
'W_H3': ['W_H3'],
'W_H4': ['W_H4']
});
});
it('complex graph', async () => {
// Handles are declared in a different order from their graph "position" but
// named using their numeric order in which their classes are generated.
//
// 1:a
// |
// 3:ab 2:d
// / \ / \
// 6:abc 5:abd 4:dx
// / \ /
// 8:abcy 7:abcd
// |
// 9:abcde
const manifest = await Manifest.parse(`
particle X
h4: reads * {d: Text, x: Text}
h8: reads * {a: Text, b: Text, c: Text, y: Text}
h1: reads * {a: Text}
h6: reads * {a: Text, b: Text, c: Text}
h9: reads * {a: Text, b: Text, c: Text, d: Text, e: Text}
h2: reads * {d: Text}
h7: reads * {a: Text, b: Text, c: Text, d: Text}
h5: reads * {a: Text, b: Text, d: Text}
h3: reads * {a: Text, b: Text}
`);
const res = convert(new SchemaGraph(manifest.particles[0]));
assert.deepStrictEqual(res.nodes, [
{name: 'X_H1', parents: '', children: 'X_H3', added: 'a'},
{name: 'X_H2', parents: '', children: 'X_H4, X_H5', added: 'd'},
{name: 'X_H3', parents: 'X_H1', children: 'X_H5, X_H6', added: 'b'},
{name: 'X_H4', parents: 'X_H2', children: '', added: 'x'},
{name: 'X_H5', parents: 'X_H2, X_H3', children: 'X_H7', added: ''},
{name: 'X_H6', parents: 'X_H3', children: 'X_H7, X_H8', added: 'c'},
{name: 'X_H7', parents: 'X_H5, X_H6', children: 'X_H9', added: ''},
{name: 'X_H8', parents: 'X_H6', children: '', added: 'y'},
{name: 'X_H9', parents: 'X_H7', children: '', added: 'e'},
]);
assert.deepStrictEqual(res.aliases, {
'X_H1': ['X_H1'],
'X_H2': ['X_H2'],
'X_H3': ['X_H3'],
'X_H4': ['X_H4'],
'X_H5': ['X_H5'],
'X_H6': ['X_H6'],
'X_H7': ['X_H7'],
'X_H8': ['X_H8'],
'X_H9': ['X_H9']
});
});
it('nested schemas use camel-cased path names', async () => {
const manifest = await Manifest.parse(`
particle Names
data: reads * {outer: &* {t: Text, inner: &* {u: URL}}}
dupe: reads * {t: Text, inner: &* {u: URL}}
`);
const graph = new SchemaGraph(manifest.particles[0]);
const res = convert(graph);
assert.deepStrictEqual(res.nodes.map(x => x.name), [
'Names_Data_Outer_Inner', 'Names_Data_Outer', 'Names_Data'
]);
assert.deepStrictEqual(res.aliases, {
'Names_Data': ['Names_Data'],
'Names_Data_Outer': ['Names_Data_Outer', 'Names_Dupe'],
'Names_Data_Outer_Inner': ['Names_Data_Outer_Inner', 'Names_Dupe_Inner'],
});
});
it('aliased nested schemas', async () => {
// The handle schemas form a linear chain (h1 -> h2 -> h3) and the reference schemas
// create a separate, single class with two aliases.
const manifest = await Manifest.parse(`
particle N
h1: reads * {a: Text}
h2: reads * {a: Text, r: &* {b: Text}}
h3: reads * {a: Text, r: &* {b: Text}, c: Text}
`);
const res = convert(new SchemaGraph(manifest.particles[0]));
assert.deepStrictEqual(res.nodes, [
{name: 'N_H1', parents: '', children: 'N_H2', added: 'a'},
{name: 'N_H2_R', parents: '', children: '', added: 'b'},
{name: 'N_H2', parents: 'N_H1', children: 'N_H3', added: 'r'},
{name: 'N_H3', parents: 'N_H2', children: '', added: 'c'},
]);
assert.deepStrictEqual(res.aliases, {
'N_H1': ['N_H1'],
'N_H2_R': ['N_H2_R', 'N_H3_R'],
'N_H2': ['N_H2'],
'N_H3': ['N_H3']
});
});
it('all shared nested schemas are aliased appropriately', async () => {
// For h1: fields r and s both have multiply-nested references leading to the same innermost
// schema '* {a: Text}'. We want a common class name for each level of the nesting stack, with
// type aliases set up for both "sides" of the reference chain. h2 and h3 also end up using
// the same innermost schema, so they should also have aliases set up.
const manifest = await Manifest.parse(`
particle Q
h1: reads * {r: &* {t: &* {u: &* {a: Text}}}, \
s: &* {t: &* {u: &* {a: Text}}}}
h2: reads * {a: Text}
h3: reads * {v: &* {a: Text}}
`);
const res = convert(new SchemaGraph(manifest.particles[0]));
assert.deepStrictEqual(res.nodes, [
{name: 'Q_H1_R_T_U', parents: '', children: '', added: 'a'},
{name: 'Q_H3', parents: '', children: '', added: 'v'},
{name: 'Q_H1_R_T', parents: '', children: '', added: 'u'},
{name: 'Q_H1_R', parents: '', children: '', added: 't'},
{name: 'Q_H1', parents: '', children: '', added: 'r, s'},
]);
assert.deepStrictEqual(res.aliases, {
'Q_H1_R_T_U': ['Q_H1_R_T_U', 'Q_H1_S_T_U', 'Q_H2', 'Q_H3_V'],
'Q_H3': ['Q_H3'],
'Q_H1_R_T': ['Q_H1_R_T', 'Q_H1_S_T'],
'Q_H1_R': ['Q_H1_R', 'Q_H1_S'],
'Q_H1': ['Q_H1']
});
});
it('diamond graph using nested schemas', async () => {
// 1:a 3:rs
// / \
// 3R:ab 3S:ac
// \ /
// 2:abc
const manifest = await Manifest.parse(`
particle I
h1: reads * {a: Text}
h2: reads * {a: Text, b: Text, c: Text}
h3: reads * {r: &* {a: Text, b: Text}, s: &* {a: Text, c: Text}}
`);
const res = convert(new SchemaGraph(manifest.particles[0]));
assert.deepStrictEqual(res.nodes, [
{name: 'I_H1', parents: '', children: 'I_H3_R, I_H3_S', added: 'a'},
{name: 'I_H3_R', parents: 'I_H1', children: 'I_H2', added: 'b'},
{name: 'I_H3_S', parents: 'I_H1', children: 'I_H2', added: 'c'},
{name: 'I_H3', parents: '', children: '', added: 'r, s'},
{name: 'I_H2', parents: 'I_H3_R, I_H3_S', children: '', added: ''},
]);
assert.deepStrictEqual(res.aliases, {
'I_H1': ['I_H1'],
'I_H3_R': ['I_H3_R'],
'I_H3_S': ['I_H3_S'],
'I_H3': ['I_H3'],
'I_H2': ['I_H2']
});
});
it('deeply nested schemas', async () => {
const manifest = await Manifest.parse(`
particle Y
h1: reads * {r: &* {a: Text}}
h2: reads * {a: Text, s: &* {a: Text}}
h3: reads * {t: &* {b: Text, u: &* {b: Text, c: Text, v: &* {d: Text}}}}
h4: reads * {a: Text, d: Text, e: Text}
h5: reads * {b: Text, c: Text, v: &* {d: Text}}
`);
const res = convert(new SchemaGraph(manifest.particles[0]));
assert.deepStrictEqual(res.nodes, [
{name: 'Y_H1_R', parents: '', children: 'Y_H2, Y_H4', added: 'a'},
{name: 'Y_H3_T_U_V', parents: '', children: 'Y_H4', added: 'd'},
{name: 'Y_H1', parents: '', children: '', added: 'r'},
{name: 'Y_H2', parents: 'Y_H1_R', children: '', added: 's'},
{name: 'Y_H4', parents: 'Y_H1_R, Y_H3_T_U_V', children: '', added: 'e'},
{name: 'Y_H3_T_U', parents: '', children: '', added: 'b, c, v'},
{name: 'Y_H3_T', parents: '', children: '', added: 'b, u'},
{name: 'Y_H3', parents: '', children: '', added: 't'},
]);
assert.deepStrictEqual(res.aliases, {
'Y_H1_R': ['Y_H1_R', 'Y_H2_S'],
'Y_H3_T_U_V': ['Y_H3_T_U_V', 'Y_H5_V'],
'Y_H1': ['Y_H1'],
'Y_H2': ['Y_H2'],
'Y_H4': ['Y_H4'],
'Y_H3_T_U': ['Y_H3_T_U', 'Y_H5'],
'Y_H3_T': ['Y_H3_T'],
'Y_H3': ['Y_H3']
});
});
it('nested schema matching one further down the graph outputs in correct order', async () => {
// 1:a
// / \
// 3:ab 2:ar
// |
// 4:abc == 2R:abc
const manifest = await Manifest.parse(`
particle V
h1: reads * {a: Text}
h2: reads * {a: Text, r: &* {a: Text, b: Text, c: Text}}
h3: reads * {a: Text, b: Text}
h4: reads * {a: Text, b: Text, c: Text}
`);
const res = convert(new SchemaGraph(manifest.particles[0]));
assert.deepStrictEqual(res.nodes, [
{name: 'V_H1', parents: '', children: 'V_H2, V_H3', added: 'a'},
{name: 'V_H3', parents: 'V_H1', children: 'V_H2_R', added: 'b'},
{name: 'V_H2_R', parents: 'V_H3', children: '', added: 'c'},
{name: 'V_H2', parents: 'V_H1', children: '', added: 'r'},
]);
assert.deepStrictEqual(res.aliases, {
'V_H1': ['V_H1'],
'V_H3': ['V_H3'],
'V_H2_R': ['V_H2_R', 'V_H4'],
'V_H2': ['V_H2']
});
});
it('nested schemas with various descendant patterns', async () => {
const manifest = await Manifest.parse(`
particle R
// Starting node with a reference
h1: reads * {r: &* {a: Text}}
// Starting node with a reference descending from h1
h2: reads * {s: &* {a: Text, b: Text}}
// Separate starting node
k1: reads * {i: &* {n: Number}}
// Descendant node with multiple independent references
h3: reads * {r: &* {a: Text}, t: &* {c: Text}, u: &* {d: Text}}
// Descendant node with co-descendant reference
h4: reads * {r: &* {a: Text}, v: &* {a: Text, e: Text}}
// Separate starting node with co-descendant reference
k2: reads * {j: &* {n: Number, o: Number}}
`);
const res = convert(new SchemaGraph(manifest.particles[0]));
assert.deepStrictEqual(res.nodes, [
{name: 'R_H1_R', parents: '', children: 'R_H2_S, R_H4_V', added: 'a'},
{name: 'R_K1_I', parents: '', children: 'R_K2_J', added: 'n'},
{name: 'R_H3_T', parents: '', children: '', added: 'c'},
{name: 'R_H3_U', parents: '', children: '', added: 'd'},
{name: 'R_H1', parents: '', children: 'R_H3, R_H4', added: 'r'},
{name: 'R_H2_S', parents: 'R_H1_R', children: '', added: 'b'},
{name: 'R_H4_V', parents: 'R_H1_R', children: '', added: 'e'},
{name: 'R_H2', parents: '', children: '', added: 's'},
{name: 'R_K1', parents: '', children: '', added: 'i'},
{name: 'R_K2_J', parents: 'R_K1_I', children: '', added: 'o'},
{name: 'R_K2', parents: '', children: '', added: 'j'},
{name: 'R_H3', parents: 'R_H1', children: '', added: 't, u'},
{name: 'R_H4', parents: 'R_H1', children: '', added: 'v'},
]);
assert.deepStrictEqual(res.aliases, {
'R_H1_R': ['R_H1_R', 'R_H3_R', 'R_H4_R'],
'R_K1_I': ['R_K1_I'],
'R_H3_T': ['R_H3_T'],
'R_H3_U': ['R_H3_U'],
'R_H1': ['R_H1'],
'R_H2_S': ['R_H2_S'],
'R_H4_V': ['R_H4_V'],
'R_H2': ['R_H2'],
'R_K1': ['R_K1'],
'R_K2_J': ['R_K2_J'],
'R_K2': ['R_K2'],
'R_H3': ['R_H3'],
'R_H4': ['R_H4']
});
});
it('schemas in singletons and collections of tuples', async () => {
const manifest = await Manifest.parse(`
particle R
s: reads (&Product {name: Text}, &Review {author: Text, content: Text})
c: reads [(&Product {name: Text, price: Number}, &Review {author: Text})]
`);
const res = convert(new SchemaGraph(manifest.particles[0]));
assert.deepStrictEqual(res.nodes, [
{name: 'R_S_0', parents: '', children: 'R_C_0', added: 'name'},
{name: 'R_C_1', parents: '', children: 'R_S_1', added: 'author'},
{name: 'R_C_0', parents: 'R_S_0', children: '', added: 'price'},
{name: 'R_S_1', parents: 'R_C_1', children: '', added: 'content'},
]);
assert.deepStrictEqual(res.aliases, {
'R_C_0': ['R_C_0'],
'R_C_1': ['R_C_1'],
'R_S_0': ['R_S_0'],
'R_S_1': ['R_S_1'],
});
});
it('schemas in tuples and references are analyzed', async () => {
const manifest = await Manifest.parse(`
particle R
tuple: reads [(
&Product {name: Text, price: Number},
&Review {content: Text, author: &Person {name: Text}}
)]
ref: reads [Product {
name: Text,
price: Number,
review: &Review {
content: Text,
author: &Person {
name: Text
}
}
}]
`);
const res = convert(new SchemaGraph(manifest.particles[0]));
assert.deepStrictEqual(res.nodes, [
{name: 'R_Tuple_0', parents: '', children: 'R_Ref', added: 'name, price'},
{name: 'R_Tuple_1_Author', parents: '', children: '', added: 'name'},
{name: 'R_Tuple_1', parents: '', children: '', added: 'author, content'},
{name: 'R_Ref', parents: 'R_Tuple_0', children: '', added: 'review'},
]);
assert.deepStrictEqual(res.aliases, {
'R_Ref': ['R_Ref'],
'R_Tuple_0': ['R_Tuple_0'],
'R_Tuple_1': ['R_Ref_Review', 'R_Tuple_1'],
'R_Tuple_1_Author': ['R_Ref_Review_Author', 'R_Tuple_1_Author'],
});
});
it('constrained variables are distinct from conventional schemas', async () => {
const manifest = await Manifest.parse(`
particle T
h1: reads * {a: Text} // 1
h2: reads ~a with {a: Text} // 2
`);
const res = convert(new SchemaGraph(manifest.particles[0]));
assert.deepStrictEqual(res.nodes, [
{name: 'T_H1', parents: '', children: '', added: 'a'},
{name: 'T_H2', parents: '', children: '', added: 'a'},
]);
assert.deepStrictEqual(res.aliases, {
'T_H1': ['T_H1'],
'T_H2': ['T_H2'],
});
});
it('variables with no constraints are not empty', async () => {
const manifest = await Manifest.parse(`
particle T
h1: reads ~a // 1
h2: reads ~a // 1
`);
const res = convert(new SchemaGraph(manifest.particles[0]));
assert.deepStrictEqual(res.nodes, [
{name: 'T_H1', parents: '', children: '', added: ''},
]);
assert.deepStrictEqual(res.aliases, {
'T_H1': ['T_H1', 'T_H2'],
});
});
it('distinct variables with the same constraint should be distinct', async () => {
const manifest = await Manifest.parse(`
particle T
h1: reads ~a with {foo: Text} // 1
h2: reads ~b with {foo: Text} // 2
`);
const res = convert(new SchemaGraph(manifest.particles[0]));
assert.deepStrictEqual(res.nodes, [
{name: 'T_H1', parents: '', children: '', added: 'foo'},
{name: 'T_H2', parents: '', children: '', added: 'foo'},
]);
assert.deepStrictEqual(res.aliases, {
'T_H1': ['T_H1'],
'T_H2': ['T_H2'],
});
});
it('variables are aliased correctly within a scope', async () => {
// Type variables with the same name in a particle scope should be treated
// as the same type, even with constraints applied.
// Variables with different names but the same constraints should be distinct.
const manifest = await Manifest.parse(`
particle T
h1: reads ~a with {a: Text} // 1
h2: reads ~b // 2
h3: reads ~c // 3
h4: reads ~d with {a: Text} // 4
h5: writes ~a // 1
h6: writes ~b with {b: Number} // 2
h7: writes ~c // 3
h8: writes ~d // 4
`);
const res = convert(new SchemaGraph(manifest.particles[0]));
assert.deepStrictEqual(res.nodes, [
{name: 'T_H1', parents: '', children: '', added: 'a'},
{name: 'T_H2', parents: '', children: '', added: 'b'},
{name: 'T_H3', parents: '', children: '', added: ''},
{name: 'T_H4', parents: '', children: '', added: 'a'},
]);
assert.deepStrictEqual(res.aliases, {
'T_H1': ['T_H1', 'T_H5'],
'T_H2': ['T_H2', 'T_H6'],
'T_H3': ['T_H3', 'T_H7'],
'T_H4': ['T_H4', 'T_H8'],
});
});
it('type variables aggregate all constraints', async () => {
const manifest = await Manifest.parse(`
particle T
h1: reads ~a with {a: Text} // 1
h2: reads ~a with {b: Number} // 1
h3: writes ~a with {c: Text} // 1
`);
const res = convert(new SchemaGraph(manifest.particles[0]));
assert.deepStrictEqual(res.nodes, [
{name: 'T_H1', parents: '', children: '', added: 'a, b, c'},
]);
assert.deepStrictEqual(res.aliases, {
'T_H1': ['T_H1', 'T_H2', 'T_H3'],
});
});
it('variables can be nested in collections, tuples, or references', async () => {
const manifest = await Manifest.parse(`
particle T
// Singleton constraint definition, usage in collection
h1: reads ~a with {foo: Text}
h2: writes [~a]
// Collection constraint definition, usage in reference
h3: reads [~b with {bar: Number}]
h4: writes &~b
// Usage in tuple, tuple constraint definition
h5: reads (&~b, &~c with {baz: URL})
h6: writes [(&~d with {foobar: Boolean}, &~c)]
`);
const res = convert(new SchemaGraph(manifest.particles[0]));
assert.deepStrictEqual(res.nodes, [
{name: 'T_H1', parents: '', children: '', added: 'foo'},
{name: 'T_H3', parents: '', children: '', added: 'bar'},
{name: 'T_H5_1', parents: '', children: '', added: 'baz'},
{name: 'T_H6_0', parents: '', children: '', added: 'foobar'},
]);
assert.deepStrictEqual(res.aliases, {
'T_H1': ['T_H1', 'T_H2'],
'T_H3': ['T_H3', 'T_H4', 'T_H5_0'],
'T_H5_1': ['T_H5_1', 'T_H6_1'],
'T_H6_0': ['T_H6_0'],
});
});
it('constrained variables should create distinct nested types, even when concrete', async () => {
const manifest = await Manifest.parse(`
particle T
foo: reads ~a with Person {
name: Text,
friends: [&Friend {
name: Text,
friendshipEstablished: Boolean
}]
}
bar: writes ~a
baz: reads Friend {
name: Text,
friendshipEstablished: Boolean
}
`);
const res = convert(new SchemaGraph(manifest.particles[0]));
assert.deepStrictEqual(res.nodes, [
{name: 'T_Foo_Friends', parents: '', children: '', added: 'friendshipEstablished, name'},
{name: 'T_Baz', parents: '', children: '', added: 'friendshipEstablished, name'},
{name: 'T_Foo', parents: '', children: '', added: 'friends, name'},
]);
assert.deepStrictEqual(res.aliases, {
'T_Foo': ['T_Bar', 'T_Foo'],
'T_Foo_Friends': ['T_Bar_Friends', 'T_Foo_Friends'],
'T_Baz': ['T_Baz']
});
});
it('duplicate nested inline entities', async () => {
const manifest = await Manifest.parse(`
schema Tea
name: Text
variety: Text
schema Container
id: Text
favTea: inline Tea
contents: [inline Tea]
particle Foo
data: reads [Container]
`);
const res = convert(new SchemaGraph(manifest.particles[0]));
assert.deepStrictEqual(res.nodes, [
{name: 'Foo_Data_FavTea', parents: '', children: '', added: 'name, variety'},
{name: 'Foo_Data', parents: '', children: '', added: 'contents, favTea, id'},
]);
assert.deepStrictEqual(res.aliases, {
'Foo_Data_FavTea': ['Foo_Data_Contents', 'Foo_Data_FavTea'],
'Foo_Data': ['Foo_Data'],
});
});
}); | the_stack |
import { QuickInputButtons, QuickPickItem, Uri, window } from 'vscode';
import { ContextKeys, GlyphChars } from '../../constants';
import { Container } from '../../container';
import { getContext } from '../../context';
import { StashApplyError, StashApplyErrorReason } from '../../git/errors';
import { GitReference, GitStashCommit, GitStashReference, Repository } from '../../git/models';
import { Logger } from '../../logger';
import { Messages } from '../../messages';
import { QuickPickItemOfT } from '../../quickpicks/items/common';
import { FlagsQuickPickItem } from '../../quickpicks/items/flags';
import { formatPath } from '../../system/formatPath';
import { pad } from '../../system/string';
import { ViewsWithRepositoryFolders } from '../../views/viewBase';
import { GitActions } from '../gitCommands.actions';
import { getSteps } from '../gitCommands.utils';
import {
appendReposToTitle,
AsyncStepResultGenerator,
PartialStepState,
pickRepositoryStep,
pickStashStep,
QuickCommand,
QuickCommandButtons,
QuickPickStep,
StepGenerator,
StepResult,
StepResultGenerator,
StepSelection,
StepState,
} from '../quickCommand';
interface Context {
repos: Repository[];
associatedView: ViewsWithRepositoryFolders;
readonly: boolean;
title: string;
}
interface ApplyState {
subcommand: 'apply';
repo: string | Repository;
reference: GitStashReference;
}
interface DropState {
subcommand: 'drop';
repo: string | Repository;
reference: GitStashReference;
}
interface ListState {
subcommand: 'list';
repo: string | Repository;
reference: GitStashReference | GitStashCommit;
}
interface PopState {
subcommand: 'pop';
repo: string | Repository;
reference: GitStashReference;
}
type PushFlags = '--include-untracked' | '--keep-index';
interface PushState {
subcommand: 'push';
repo: string | Repository;
message?: string;
uris?: Uri[];
flags: PushFlags[];
}
type State = ApplyState | DropState | ListState | PopState | PushState;
type StashStepState<T extends State> = SomeNonNullable<StepState<T>, 'subcommand'>;
type ApplyStepState<T extends ApplyState = ApplyState> = StashStepState<ExcludeSome<T, 'repo', string>>;
type DropStepState<T extends DropState = DropState> = StashStepState<ExcludeSome<T, 'repo', string>>;
type ListStepState<T extends ListState = ListState> = StashStepState<ExcludeSome<T, 'repo', string>>;
type PopStepState<T extends PopState = PopState> = StashStepState<ExcludeSome<T, 'repo', string>>;
type PushStepState<T extends PushState = PushState> = StashStepState<ExcludeSome<T, 'repo', string>>;
const subcommandToTitleMap = new Map<State['subcommand'], string>([
['apply', 'Apply'],
['drop', 'Drop'],
['list', 'List'],
['pop', 'Pop'],
['push', 'Push'],
]);
function getTitle(title: string, subcommand: State['subcommand'] | undefined) {
return subcommand == null ? title : `${subcommandToTitleMap.get(subcommand)} ${title}`;
}
export interface StashGitCommandArgs {
readonly command: 'stash';
confirm?: boolean;
state?: Partial<State>;
}
export class StashGitCommand extends QuickCommand<State> {
private subcommand: State['subcommand'] | undefined;
constructor(container: Container, args?: StashGitCommandArgs) {
super(container, 'stash', 'stash', 'Stash', {
description: 'shelves (stashes) local changes to be reapplied later',
});
let counter = 0;
if (args?.state?.subcommand != null) {
counter++;
switch (args.state.subcommand) {
case 'apply':
case 'drop':
case 'pop':
if (args.state.reference != null) {
counter++;
}
break;
case 'push':
if (args.state.message != null) {
counter++;
}
break;
}
}
if (args?.state?.repo != null) {
counter++;
}
this.initialState = {
counter: counter,
confirm: args?.confirm,
...args?.state,
};
}
override get canConfirm(): boolean {
return this.subcommand != null && this.subcommand !== 'list';
}
override get canSkipConfirm(): boolean {
return this.subcommand === 'drop' ? false : super.canSkipConfirm;
}
override get skipConfirmKey() {
return `${this.key}${this.subcommand == null ? '' : `-${this.subcommand}`}:${this.pickedVia}`;
}
protected async *steps(state: PartialStepState<State>): StepGenerator {
const context: Context = {
repos: this.container.git.openRepositories,
associatedView: this.container.stashesView,
readonly:
getContext<boolean>(ContextKeys.Readonly, false) ||
getContext<boolean>(ContextKeys.Untrusted, false) ||
getContext<boolean>(ContextKeys.HasVirtualFolders, false),
title: this.title,
};
let skippedStepTwo = false;
while (this.canStepsContinue(state)) {
context.title = this.title;
if (context.readonly) {
state.subcommand = 'list';
}
if (state.counter < 1 || state.subcommand == null) {
this.subcommand = undefined;
const result = yield* this.pickSubcommandStep(state);
// Always break on the first step (so we will go back)
if (result === StepResult.Break) break;
state.subcommand = result;
}
this.subcommand = state.subcommand;
context.title = getTitle(this.title, state.subcommand);
if (state.counter < 2 || state.repo == null || typeof state.repo === 'string') {
skippedStepTwo = false;
if (context.repos.length === 1) {
skippedStepTwo = true;
state.counter++;
state.repo = context.repos[0];
} else {
const result = yield* pickRepositoryStep(state, context);
if (result === StepResult.Break) continue;
state.repo = result;
}
}
switch (state.subcommand) {
case 'apply':
case 'pop':
yield* this.applyOrPopCommandSteps(state as ApplyStepState | PopStepState, context);
break;
case 'drop':
yield* this.dropCommandSteps(state as DropStepState, context);
break;
case 'list':
yield* this.listCommandSteps(state as ListStepState, context);
break;
case 'push':
yield* this.pushCommandSteps(state as PushStepState, context);
break;
default:
QuickCommand.endSteps(state);
break;
}
// If we skipped the previous step, make sure we back up past it
if (skippedStepTwo) {
state.counter--;
}
}
return state.counter < 0 ? StepResult.Break : undefined;
}
private *pickSubcommandStep(state: PartialStepState<State>): StepResultGenerator<State['subcommand']> {
const step = QuickCommand.createPickStep<QuickPickItemOfT<State['subcommand']>>({
title: this.title,
placeholder: `Choose a ${this.label} command`,
items: [
{
label: 'apply',
description: 'integrates changes from the specified stash into the current branch',
picked: state.subcommand === 'apply',
item: 'apply',
},
{
label: 'drop',
description: 'deletes the specified stash',
picked: state.subcommand === 'drop',
item: 'drop',
},
{
label: 'list',
description: 'lists the saved stashes',
picked: state.subcommand === 'list',
item: 'list',
},
{
label: 'pop',
description:
'integrates changes from the specified stash into the current branch and deletes the stash',
picked: state.subcommand === 'pop',
item: 'pop',
},
{
label: 'push',
description:
'saves your local changes to a new stash and discards them from the working tree and index',
picked: state.subcommand === 'push',
item: 'push',
},
],
buttons: [QuickInputButtons.Back],
});
const selection: StepSelection<typeof step> = yield step;
return QuickCommand.canPickStepContinue(step, state, selection) ? selection[0].item : StepResult.Break;
}
private async *applyOrPopCommandSteps(state: ApplyStepState | PopStepState, context: Context): StepGenerator {
while (this.canStepsContinue(state)) {
if (state.counter < 3 || state.reference == null) {
const result: StepResult<GitStashReference> = yield* pickStashStep(state, context, {
stash: await this.container.git.getStash(state.repo.path),
placeholder: (context, stash) =>
stash == null
? `No stashes found in ${state.repo.formattedName}`
: 'Choose a stash to apply to your working tree',
picked: state.reference?.ref,
});
// Always break on the first step (so we will go back)
if (result === StepResult.Break) break;
state.reference = result;
}
if (this.confirm(state.confirm)) {
const result = yield* this.applyOrPopCommandConfirmStep(state, context);
if (result === StepResult.Break) continue;
state.subcommand = result;
}
QuickCommand.endSteps(state);
try {
void (await state.repo.stashApply(
// pop can only take a stash index, e.g. `stash@{1}`
state.subcommand === 'pop' ? `stash@{${state.reference.number}}` : state.reference.ref,
{ deleteAfter: state.subcommand === 'pop' },
));
} catch (ex) {
Logger.error(ex, context.title);
if (StashApplyError.is(ex, StashApplyErrorReason.WorkingChanges)) {
void window.showWarningMessage(
'Unable to apply stash. Your working tree changes would be overwritten. Please commit or stash your changes before trying again',
);
} else {
void Messages.showGenericErrorMessage(ex.message);
}
}
}
}
private *applyOrPopCommandConfirmStep(
state: ApplyStepState | PopStepState,
context: Context,
): StepResultGenerator<'apply' | 'pop'> {
const step = this.createConfirmStep<QuickPickItem & { item: 'apply' | 'pop' }>(
appendReposToTitle(`Confirm ${context.title}`, state, context),
[
{
label: context.title,
detail:
state.subcommand === 'pop'
? `Will delete ${GitReference.toString(
state.reference,
)} and apply the changes to the working tree`
: `Will apply the changes from ${GitReference.toString(
state.reference,
)} to the working tree`,
item: state.subcommand,
},
// Alternate confirmation (if pop then apply, and vice versa)
{
label: getTitle(this.title, state.subcommand === 'pop' ? 'apply' : 'pop'),
detail:
state.subcommand === 'pop'
? `Will apply the changes from ${GitReference.toString(
state.reference,
)} to the working tree`
: `Will delete ${GitReference.toString(
state.reference,
)} and apply the changes to the working tree`,
item: state.subcommand === 'pop' ? 'apply' : 'pop',
},
],
undefined,
{
placeholder: `Confirm ${context.title}`,
additionalButtons: [QuickCommandButtons.RevealInSideBar],
onDidClickButton: (quickpick, button) => {
if (button === QuickCommandButtons.RevealInSideBar) {
void GitActions.Stash.reveal(state.reference, {
select: true,
expand: true,
});
}
},
},
);
const selection: StepSelection<typeof step> = yield step;
return QuickCommand.canPickStepContinue(step, state, selection) ? selection[0].item : StepResult.Break;
}
private async *dropCommandSteps(state: DropStepState, context: Context): StepGenerator {
while (this.canStepsContinue(state)) {
if (state.counter < 3 || state.reference == null) {
const result: StepResult<GitStashReference> = yield* pickStashStep(state, context, {
stash: await this.container.git.getStash(state.repo.path),
placeholder: (context, stash) =>
stash == null ? `No stashes found in ${state.repo.formattedName}` : 'Choose a stash to delete',
picked: state.reference?.ref,
});
// Always break on the first step (so we will go back)
if (result === StepResult.Break) break;
state.reference = result;
}
const result = yield* this.dropCommandConfirmStep(state, context);
if (result === StepResult.Break) continue;
QuickCommand.endSteps(state);
try {
// drop can only take a stash index, e.g. `stash@{1}`
void (await state.repo.stashDelete(`stash@{${state.reference.number}}`, state.reference.ref));
} catch (ex) {
Logger.error(ex, context.title);
void Messages.showGenericErrorMessage('Unable to delete stash');
return;
}
}
}
private *dropCommandConfirmStep(state: DropStepState, context: Context): StepResultGenerator<void> {
const step = this.createConfirmStep(
appendReposToTitle(`Confirm ${context.title}`, state, context),
[
{
label: context.title,
detail: `Will delete ${GitReference.toString(state.reference)}`,
},
],
undefined,
{
placeholder: `Confirm ${context.title}`,
additionalButtons: [QuickCommandButtons.RevealInSideBar],
onDidClickButton: (quickpick, button) => {
if (button === QuickCommandButtons.RevealInSideBar) {
void GitActions.Stash.reveal(state.reference, {
select: true,
expand: true,
});
}
},
},
);
const selection: StepSelection<typeof step> = yield step;
return QuickCommand.canPickStepContinue(step, state, selection) ? undefined : StepResult.Break;
}
private async *listCommandSteps(state: ListStepState, context: Context): StepGenerator {
context.title = 'Stashes';
while (this.canStepsContinue(state)) {
if (state.counter < 3 || state.reference == null) {
const result: StepResult<GitStashCommit> = yield* pickStashStep(state, context, {
stash: await this.container.git.getStash(state.repo.path),
placeholder: (context, stash) =>
stash == null ? `No stashes found in ${state.repo.formattedName}` : 'Choose a stash',
picked: state.reference?.ref,
});
// Always break on the first step (so we will go back)
if (result === StepResult.Break) break;
state.reference = result;
}
const result = yield* getSteps(
this.container,
{
command: 'show',
state: {
repo: state.repo,
reference: state.reference,
},
},
this.pickedVia,
);
state.counter--;
if (result === StepResult.Break) {
QuickCommand.endSteps(state);
}
}
}
private async *pushCommandSteps(state: PushStepState, context: Context): StepGenerator {
if (state.flags == null) {
state.flags = [];
}
while (this.canStepsContinue(state)) {
if (state.counter < 3 || state.message == null) {
const result = yield* this.pushCommandInputMessageStep(state, context);
// Always break on the first step (so we will go back)
if (result === StepResult.Break) break;
state.message = result;
}
if (this.confirm(state.confirm)) {
const result = yield* this.pushCommandConfirmStep(state, context);
if (result === StepResult.Break) continue;
state.flags = result;
}
QuickCommand.endSteps(state);
try {
void (await state.repo.stashSave(state.message, state.uris, {
includeUntracked: state.flags.includes('--include-untracked'),
keepIndex: state.flags.includes('--keep-index'),
}));
} catch (ex) {
Logger.error(ex, context.title);
const msg: string = ex?.message ?? ex?.toString() ?? '';
if (msg.includes('newer version of Git')) {
void window.showErrorMessage(`Unable to stash changes. ${msg}`);
return;
}
void Messages.showGenericErrorMessage('Unable to stash changes');
return;
}
}
}
private async *pushCommandInputMessageStep(
state: PushStepState,
context: Context,
): AsyncStepResultGenerator<string> {
const step = QuickCommand.createInputStep({
title: appendReposToTitle(
context.title,
state,
context,
state.uris != null
? `${pad(GlyphChars.Dot, 2, 2)}${
state.uris.length === 1
? formatPath(state.uris[0], { fileOnly: true })
: `${state.uris.length} files`
}`
: undefined,
),
placeholder: 'Please provide a stash message',
value: state.message,
prompt: 'Enter stash message',
});
const value: StepSelection<typeof step> = yield step;
if (
!QuickCommand.canStepContinue(step, state, value) ||
!(await QuickCommand.canInputStepContinue(step, state, value))
) {
return StepResult.Break;
}
return value;
}
private *pushCommandConfirmStep(state: PushStepState, context: Context): StepResultGenerator<PushFlags[]> {
const step: QuickPickStep<FlagsQuickPickItem<PushFlags>> = this.createConfirmStep(
appendReposToTitle(`Confirm ${context.title}`, state, context),
state.uris == null || state.uris.length === 0
? [
FlagsQuickPickItem.create<PushFlags>(state.flags, [], {
label: context.title,
detail: 'Will stash uncommitted changes',
}),
FlagsQuickPickItem.create<PushFlags>(state.flags, ['--include-untracked'], {
label: `${context.title} & Include Untracked`,
description: '--include-untracked',
detail: 'Will stash uncommitted changes, including untracked files',
}),
FlagsQuickPickItem.create<PushFlags>(state.flags, ['--keep-index'], {
label: `${context.title} & Keep Staged`,
description: '--keep-index',
detail: 'Will stash uncommitted changes, but will keep staged files intact',
}),
]
: [
FlagsQuickPickItem.create<PushFlags>(state.flags, [], {
label: context.title,
detail: `Will stash changes from ${
state.uris.length === 1
? formatPath(state.uris[0], { fileOnly: true })
: `${state.uris.length} files`
}`,
}),
FlagsQuickPickItem.create<PushFlags>(state.flags, ['--keep-index'], {
label: `${context.title} & Keep Staged`,
detail: `Will stash changes from ${
state.uris.length === 1
? formatPath(state.uris[0], { fileOnly: true })
: `${state.uris.length} files`
}, but will keep staged files intact`,
}),
],
undefined,
{ placeholder: `Confirm ${context.title}` },
);
const selection: StepSelection<typeof step> = yield step;
return QuickCommand.canPickStepContinue(step, state, selection) ? selection[0].item : StepResult.Break;
}
} | the_stack |
import type { ASTVisitor } from '../language/visitor';
import type { ASTNode, FieldNode } from '../language/ast';
import { Kind } from '../language/kinds';
import { isNode } from '../language/ast';
import { getEnterLeaveForKind } from '../language/visitor';
import type { Maybe } from '../jsutils/Maybe';
import type { GraphQLSchema } from '../type/schema';
import type { GraphQLDirective } from '../type/directives';
import type {
GraphQLType,
GraphQLInputType,
GraphQLOutputType,
GraphQLCompositeType,
GraphQLField,
GraphQLArgument,
GraphQLInputField,
GraphQLEnumValue,
} from '../type/definition';
import {
isObjectType,
isInterfaceType,
isEnumType,
isInputObjectType,
isListType,
isCompositeType,
isInputType,
isOutputType,
getNullableType,
getNamedType,
} from '../type/definition';
import {
SchemaMetaFieldDef,
TypeMetaFieldDef,
TypeNameMetaFieldDef,
} from '../type/introspection';
import { typeFromAST } from './typeFromAST';
/**
* TypeInfo is a utility class which, given a GraphQL schema, can keep track
* of the current field and type definitions at any point in a GraphQL document
* AST during a recursive descent by calling `enter(node)` and `leave(node)`.
*/
export class TypeInfo {
private _schema: GraphQLSchema;
private _typeStack: Array<Maybe<GraphQLOutputType>>;
private _parentTypeStack: Array<Maybe<GraphQLCompositeType>>;
private _inputTypeStack: Array<Maybe<GraphQLInputType>>;
private _fieldDefStack: Array<Maybe<GraphQLField<unknown, unknown>>>;
private _defaultValueStack: Array<Maybe<unknown>>;
private _directive: Maybe<GraphQLDirective>;
private _argument: Maybe<GraphQLArgument>;
private _enumValue: Maybe<GraphQLEnumValue>;
private _getFieldDef: GetFieldDefFn;
constructor(
schema: GraphQLSchema,
/**
* Initial type may be provided in rare cases to facilitate traversals
* beginning somewhere other than documents.
*/
initialType?: Maybe<GraphQLType>,
/** @deprecated will be removed in 17.0.0 */
getFieldDefFn?: GetFieldDefFn,
) {
this._schema = schema;
this._typeStack = [];
this._parentTypeStack = [];
this._inputTypeStack = [];
this._fieldDefStack = [];
this._defaultValueStack = [];
this._directive = null;
this._argument = null;
this._enumValue = null;
this._getFieldDef = getFieldDefFn ?? getFieldDef;
if (initialType) {
if (isInputType(initialType)) {
this._inputTypeStack.push(initialType);
}
if (isCompositeType(initialType)) {
this._parentTypeStack.push(initialType);
}
if (isOutputType(initialType)) {
this._typeStack.push(initialType);
}
}
}
get [Symbol.toStringTag]() {
return 'TypeInfo';
}
getType(): Maybe<GraphQLOutputType> {
if (this._typeStack.length > 0) {
return this._typeStack[this._typeStack.length - 1];
}
}
getParentType(): Maybe<GraphQLCompositeType> {
if (this._parentTypeStack.length > 0) {
return this._parentTypeStack[this._parentTypeStack.length - 1];
}
}
getInputType(): Maybe<GraphQLInputType> {
if (this._inputTypeStack.length > 0) {
return this._inputTypeStack[this._inputTypeStack.length - 1];
}
}
getParentInputType(): Maybe<GraphQLInputType> {
if (this._inputTypeStack.length > 1) {
return this._inputTypeStack[this._inputTypeStack.length - 2];
}
}
getFieldDef(): Maybe<GraphQLField<unknown, unknown>> {
if (this._fieldDefStack.length > 0) {
return this._fieldDefStack[this._fieldDefStack.length - 1];
}
}
getDefaultValue(): Maybe<unknown> {
if (this._defaultValueStack.length > 0) {
return this._defaultValueStack[this._defaultValueStack.length - 1];
}
}
getDirective(): Maybe<GraphQLDirective> {
return this._directive;
}
getArgument(): Maybe<GraphQLArgument> {
return this._argument;
}
getEnumValue(): Maybe<GraphQLEnumValue> {
return this._enumValue;
}
enter(node: ASTNode) {
const schema = this._schema;
// Note: many of the types below are explicitly typed as "unknown" to drop
// any assumptions of a valid schema to ensure runtime types are properly
// checked before continuing since TypeInfo is used as part of validation
// which occurs before guarantees of schema and document validity.
switch (node.kind) {
case Kind.SELECTION_SET: {
const namedType: unknown = getNamedType(this.getType());
this._parentTypeStack.push(
isCompositeType(namedType) ? namedType : undefined,
);
break;
}
case Kind.FIELD: {
const parentType = this.getParentType();
let fieldDef;
let fieldType: unknown;
if (parentType) {
fieldDef = this._getFieldDef(schema, parentType, node);
if (fieldDef) {
fieldType = fieldDef.type;
}
}
this._fieldDefStack.push(fieldDef);
this._typeStack.push(isOutputType(fieldType) ? fieldType : undefined);
break;
}
case Kind.DIRECTIVE:
this._directive = schema.getDirective(node.name.value);
break;
case Kind.OPERATION_DEFINITION: {
const rootType = schema.getRootType(node.operation);
this._typeStack.push(isObjectType(rootType) ? rootType : undefined);
break;
}
case Kind.INLINE_FRAGMENT:
case Kind.FRAGMENT_DEFINITION: {
const typeConditionAST = node.typeCondition;
const outputType: unknown = typeConditionAST
? typeFromAST(schema, typeConditionAST)
: getNamedType(this.getType());
this._typeStack.push(isOutputType(outputType) ? outputType : undefined);
break;
}
case Kind.VARIABLE_DEFINITION: {
const inputType: unknown = typeFromAST(schema, node.type);
this._inputTypeStack.push(
isInputType(inputType) ? inputType : undefined,
);
break;
}
case Kind.ARGUMENT: {
let argDef;
let argType: unknown;
const fieldOrDirective = this.getDirective() ?? this.getFieldDef();
if (fieldOrDirective) {
argDef = fieldOrDirective.args.find(
(arg) => arg.name === node.name.value,
);
if (argDef) {
argType = argDef.type;
}
}
this._argument = argDef;
this._defaultValueStack.push(argDef ? argDef.defaultValue : undefined);
this._inputTypeStack.push(isInputType(argType) ? argType : undefined);
break;
}
case Kind.LIST: {
const listType: unknown = getNullableType(this.getInputType());
const itemType: unknown = isListType(listType)
? listType.ofType
: listType;
// List positions never have a default value.
this._defaultValueStack.push(undefined);
this._inputTypeStack.push(isInputType(itemType) ? itemType : undefined);
break;
}
case Kind.OBJECT_FIELD: {
const objectType: unknown = getNamedType(this.getInputType());
let inputFieldType: GraphQLInputType | undefined;
let inputField: GraphQLInputField | undefined;
if (isInputObjectType(objectType)) {
inputField = objectType.getFields()[node.name.value];
if (inputField) {
inputFieldType = inputField.type;
}
}
this._defaultValueStack.push(
inputField ? inputField.defaultValue : undefined,
);
this._inputTypeStack.push(
isInputType(inputFieldType) ? inputFieldType : undefined,
);
break;
}
case Kind.ENUM: {
const enumType: unknown = getNamedType(this.getInputType());
let enumValue;
if (isEnumType(enumType)) {
enumValue = enumType.getValue(node.value);
}
this._enumValue = enumValue;
break;
}
}
}
leave(node: ASTNode) {
switch (node.kind) {
case Kind.SELECTION_SET:
this._parentTypeStack.pop();
break;
case Kind.FIELD:
this._fieldDefStack.pop();
this._typeStack.pop();
break;
case Kind.DIRECTIVE:
this._directive = null;
break;
case Kind.OPERATION_DEFINITION:
case Kind.INLINE_FRAGMENT:
case Kind.FRAGMENT_DEFINITION:
this._typeStack.pop();
break;
case Kind.VARIABLE_DEFINITION:
this._inputTypeStack.pop();
break;
case Kind.ARGUMENT:
this._argument = null;
this._defaultValueStack.pop();
this._inputTypeStack.pop();
break;
case Kind.LIST:
case Kind.OBJECT_FIELD:
this._defaultValueStack.pop();
this._inputTypeStack.pop();
break;
case Kind.ENUM:
this._enumValue = null;
break;
}
}
}
type GetFieldDefFn = (
schema: GraphQLSchema,
parentType: GraphQLType,
fieldNode: FieldNode,
) => Maybe<GraphQLField<unknown, unknown>>;
/**
* Not exactly the same as the executor's definition of getFieldDef, in this
* statically evaluated environment we do not always have an Object type,
* and need to handle Interface and Union types.
*/
function getFieldDef(
schema: GraphQLSchema,
parentType: GraphQLType,
fieldNode: FieldNode,
): Maybe<GraphQLField<unknown, unknown>> {
const name = fieldNode.name.value;
if (
name === SchemaMetaFieldDef.name &&
schema.getQueryType() === parentType
) {
return SchemaMetaFieldDef;
}
if (name === TypeMetaFieldDef.name && schema.getQueryType() === parentType) {
return TypeMetaFieldDef;
}
if (name === TypeNameMetaFieldDef.name && isCompositeType(parentType)) {
return TypeNameMetaFieldDef;
}
if (isObjectType(parentType) || isInterfaceType(parentType)) {
return parentType.getFields()[name];
}
}
/**
* Creates a new visitor instance which maintains a provided TypeInfo instance
* along with visiting visitor.
*/
export function visitWithTypeInfo(
typeInfo: TypeInfo,
visitor: ASTVisitor,
): ASTVisitor {
return {
enter(...args) {
const node = args[0];
typeInfo.enter(node);
const fn = getEnterLeaveForKind(visitor, node.kind).enter;
if (fn) {
const result = fn.apply(visitor, args);
if (result !== undefined) {
typeInfo.leave(node);
if (isNode(result)) {
typeInfo.enter(result);
}
}
return result;
}
},
leave(...args) {
const node = args[0];
const fn = getEnterLeaveForKind(visitor, node.kind).leave;
let result;
if (fn) {
result = fn.apply(visitor, args);
}
typeInfo.leave(node);
return result;
},
};
} | the_stack |
import { autoBindMethodsForReact } from 'class-autobind-decorator';
import classnames from 'classnames';
import React, { PureComponent } from 'react';
import { AUTOBIND_CFG } from '../../../common/constants';
import { database as db } from '../../../common/database';
import { Project } from '../../../models/project';
import type { Workspace } from '../../../models/workspace';
import type { StatusCandidate } from '../../../sync/types';
import { interceptAccessError } from '../../../sync/vcs/util';
import { VCS } from '../../../sync/vcs/vcs';
import { Modal } from '../base/modal';
import { ModalBody } from '../base/modal-body';
import { ModalHeader } from '../base/modal-header';
import { PromptButton } from '../base/prompt-button';
import { SyncPullButton } from '../sync-pull-button';
interface Props {
workspace: Workspace;
project: Project;
syncItems: StatusCandidate[];
vcs: VCS;
}
interface State {
error: string;
newBranchName: string;
currentBranch: string;
branches: string[];
remoteBranches: string[];
}
@autoBindMethodsForReact(AUTOBIND_CFG)
export class SyncBranchesModal extends PureComponent<Props, State> {
modal: Modal | null = null;
state: State = {
error: '',
newBranchName: '',
branches: [],
remoteBranches: [],
currentBranch: '',
};
_setModalRef(m: Modal) {
this.modal = m;
}
async _handleCheckout(branch: string) {
const { vcs, syncItems } = this.props;
try {
const delta = await vcs.checkout(syncItems, branch);
// @ts-expect-error -- TSCONVERSION
await db.batchModifyDocs(delta);
await this.refreshState();
} catch (err) {
console.log('Failed to checkout', err.stack);
this.setState({
error: err.message,
});
}
}
async _handleMerge(branch: string) {
const { vcs, syncItems } = this.props;
const delta = await vcs.merge(syncItems, branch);
try {
// @ts-expect-error -- TSCONVERSION
await db.batchModifyDocs(delta);
await this.refreshState();
} catch (err) {
console.log('Failed to merge', err.stack);
this.setState({
error: err.message,
});
}
}
async _handleRemoteDelete(branch: string) {
const { vcs } = this.props;
try {
await vcs.removeRemoteBranch(branch);
await this.refreshState();
} catch (err) {
console.log('Failed to remote delete', err.stack);
this.setState({
error: err.message,
});
}
}
async _handleDelete(branch: string) {
const { vcs } = this.props;
try {
await vcs.removeBranch(branch);
await this.refreshState();
} catch (err) {
console.log('Failed to delete', err.stack);
this.setState({
error: err.message,
});
}
}
async _handleCreate(e: React.SyntheticEvent<HTMLFormElement>) {
e.preventDefault();
const { vcs, syncItems } = this.props;
try {
// Create new branch
const { newBranchName } = this.state;
await vcs.fork(newBranchName);
// Checkout new branch
const delta = await vcs.checkout(syncItems, newBranchName);
// @ts-expect-error -- TSCONVERSION
await db.batchModifyDocs(delta);
// Clear branch name and refresh things
await this.refreshState({
newBranchName: '',
});
} catch (err) {
console.log('Failed to create', err.stack);
this.setState({
error: err.message,
});
}
}
_updateNewBranchName(e: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) {
this.setState({ newBranchName: e.currentTarget.value });
}
_handleClearError() {
this.setState({ error: '' });
}
async refreshState(newState?: Record<string, any>) {
const { vcs } = this.props;
try {
const currentBranch = await vcs.getBranch();
const branches = (await vcs.getBranches()).sort();
this.setState({
branches,
currentBranch,
error: '',
...newState,
});
const remoteBranches = await interceptAccessError({
callback: async () => (await vcs.getRemoteBranches()).filter(b => !branches.includes(b)).sort(),
action: 'get',
resourceName: 'remote',
resourceType: 'branches',
});
this.setState({
remoteBranches,
});
} catch (err) {
console.log('Failed to refresh', err.stack);
this.setState({
error: err.message,
});
}
}
hide() {
this.modal?.hide();
}
async show(options: { onHide: (...args: any[]) => any }) {
this.modal &&
this.modal.show({
onHide: options.onHide,
});
await this.refreshState();
}
render() {
const { vcs, project } = this.props;
const { branches, remoteBranches, currentBranch, newBranchName, error } = this.state;
return (
<Modal ref={this._setModalRef}>
<ModalHeader>Branches</ModalHeader>
<ModalBody className="wide pad">
{error && (
<p className="notice error margin-bottom-sm no-margin-top">
<button className="pull-right icon" onClick={this._handleClearError}>
<i className="fa fa-times" />
</button>
{error}
</p>
)}
<form onSubmit={this._handleCreate}>
<div className="form-row">
<div className="form-control form-control--outlined">
<label>
New Branch Name
<input
type="text"
onChange={this._updateNewBranchName}
placeholder="testing-branch"
value={newBranchName}
/>
</label>
</div>
<div className="form-control form-control--no-label width-auto">
<button type="submit" className="btn btn--clicky" disabled={!newBranchName}>
Create
</button>
</div>
</div>
</form>
<div className="pad-top">
<table className="table--fancy table--outlined">
<thead>
<tr>
<th className="text-left">Branches</th>
<th className="text-right"> </th>
</tr>
</thead>
<tbody>
{branches.map(name => (
<tr key={name} className="table--no-outline-row">
<td>
<span
className={classnames({
bold: name === currentBranch,
})}
>
{name}
</span>
{name === currentBranch ? (
<span className="txt-sm space-left">(current)</span>
) : null}
{name === 'master' && <i className="fa fa-lock space-left faint" />}
</td>
<td className="text-right">
<PromptButton
className="btn btn--micro btn--outlined space-left"
doneMessage="Merged"
disabled={name === currentBranch}
onClick={() => this._handleMerge(name)}
>
Merge
</PromptButton>
<PromptButton
className="btn btn--micro btn--outlined space-left"
doneMessage="Deleted"
disabled={name === currentBranch || name === 'master'}
onClick={() => this._handleDelete(name)}
>
Delete
</PromptButton>
<button
className="btn btn--micro btn--outlined space-left"
disabled={name === currentBranch}
onClick={() => this._handleCheckout(name)}
>
Checkout
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
{remoteBranches.length > 0 && (
<div className="pad-top">
<table className="table--fancy table--outlined">
<thead>
<tr>
<th className="text-left">Remote Branches</th>
<th className="text-right"> </th>
</tr>
</thead>
<tbody>
{remoteBranches.map(name => (
<tr key={name} className="table--no-outline-row">
<td>
{name}
{name === 'master' && <i className="fa fa-lock space-left faint" />}
</td>
<td className="text-right">
{name !== 'master' && (
<PromptButton
className="btn btn--micro btn--outlined space-left"
doneMessage="Deleted"
disabled={name === currentBranch}
onClick={() => this._handleRemoteDelete(name)}
>
Delete
</PromptButton>
)}
<SyncPullButton
className="btn btn--micro btn--outlined space-left"
branch={name}
project={project}
onPull={this.refreshState}
disabled={name === currentBranch}
vcs={vcs}
>
Fetch
</SyncPullButton>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</ModalBody>
</Modal>
);
}
} | the_stack |
import { BigNumber } from "bignumber.js";
import type { BitcoinLikeNetworkParameters } from "./types";
import { BitcoinLikeFeePolicy, BitcoinLikeSigHashType } from "./types";
export const getNetworkParameters = (
networkName: string
): BitcoinLikeNetworkParameters => {
if (networkName === "bitcoin") {
return {
identifier: "btc",
P2PKHVersion: Buffer.from([0x00]),
P2SHVersion: Buffer.from([0x05]),
xpubVersion: Buffer.from([0x04, 0x88, 0xb2, 0x1e]),
feePolicy: BitcoinLikeFeePolicy.PER_BYTE,
dustAmount: new BigNumber(546),
messagePrefix: "Bitcoin signed message:\n",
usesTimestampedTransaction: false,
timestampDelay: new BigNumber(0),
sigHash: BitcoinLikeSigHashType.SIGHASH_ALL,
additionalBIPs: [],
};
} else if (networkName === "bitcoin_testnet") {
return {
identifier: "btc_testnet",
P2PKHVersion: Buffer.from([0x6f]),
P2SHVersion: Buffer.from([0xc4]),
xpubVersion: Buffer.from([0x04, 0x35, 0x87, 0xcf]),
feePolicy: BitcoinLikeFeePolicy.PER_BYTE,
dustAmount: new BigNumber(546),
messagePrefix: "Bitcoin signed Message:\n",
usesTimestampedTransaction: false,
timestampDelay: new BigNumber(0),
sigHash: BitcoinLikeSigHashType.SIGHASH_ALL,
additionalBIPs: [],
};
} else if (networkName === "bitcoin_cash") {
return {
identifier: "abc",
P2PKHVersion: Buffer.from([0x00]),
P2SHVersion: Buffer.from([0x05]),
xpubVersion: Buffer.from([0x04, 0x88, 0xb2, 0x1e]),
feePolicy: BitcoinLikeFeePolicy.PER_BYTE,
dustAmount: new BigNumber(5430),
messagePrefix: "Bitcoin signed Message:\n",
usesTimestampedTransaction: false,
timestampDelay: new BigNumber(0),
sigHash:
BitcoinLikeSigHashType.SIGHASH_ALL |
BitcoinLikeSigHashType.SIGHASH_FORKID,
additionalBIPs: [],
};
} else if (networkName === "bitcoin_gold") {
return {
identifier: "btg",
P2PKHVersion: Buffer.from([0x26]),
P2SHVersion: Buffer.from([0x17]),
xpubVersion: Buffer.from([0x04, 0x88, 0xb2, 0x1e]),
feePolicy: BitcoinLikeFeePolicy.PER_BYTE,
dustAmount: new BigNumber(5430),
messagePrefix: "Bitcoin gold signed Message:\n",
usesTimestampedTransaction: false,
timestampDelay: new BigNumber(0),
sigHash:
BitcoinLikeSigHashType.SIGHASH_ALL |
BitcoinLikeSigHashType.SIGHASH_FORKID,
additionalBIPs: [],
};
} else if (networkName === "zcash") {
return {
identifier: "zec",
P2PKHVersion: Buffer.from([0x1c, 0xb8]),
P2SHVersion: Buffer.from([0x1c, 0xbd]),
xpubVersion: Buffer.from([0x04, 0x88, 0xb2, 0x1e]),
feePolicy: BitcoinLikeFeePolicy.PER_BYTE,
dustAmount: new BigNumber(10000),
messagePrefix: "Zcash Signed Message:\n",
usesTimestampedTransaction: false,
timestampDelay: new BigNumber(0),
sigHash: BitcoinLikeSigHashType.SIGHASH_ALL,
additionalBIPs: ["ZIP"],
};
} else if (networkName === "zencash") {
return {
identifier: "zen",
P2PKHVersion: Buffer.from([0x20, 0x89]),
P2SHVersion: Buffer.from([0x20, 0x96]),
xpubVersion: Buffer.from([0x04, 0x88, 0xb2, 0x1e]),
feePolicy: BitcoinLikeFeePolicy.PER_BYTE,
dustAmount: new BigNumber(10000),
messagePrefix: "Zencash Signed Message:\n",
usesTimestampedTransaction: false,
timestampDelay: new BigNumber(0),
sigHash: BitcoinLikeSigHashType.SIGHASH_ALL,
additionalBIPs: ["BIP115"],
};
} else if (networkName === "litecoin") {
return {
identifier: "ltc",
P2PKHVersion: Buffer.from([0x30]),
P2SHVersion: Buffer.from([0x32]),
xpubVersion: Buffer.from([0x01, 0x9d, 0xa4, 0x62]),
feePolicy: BitcoinLikeFeePolicy.PER_BYTE,
dustAmount: new BigNumber(10000),
messagePrefix: "Litecoin Signed Message:\n",
usesTimestampedTransaction: false,
timestampDelay: new BigNumber(0),
sigHash: BitcoinLikeSigHashType.SIGHASH_ALL,
additionalBIPs: [],
};
} else if (networkName === "peercoin") {
return {
identifier: "ppc",
P2PKHVersion: Buffer.from([0x37]),
P2SHVersion: Buffer.from([0x75]),
xpubVersion: Buffer.from([0xe6, 0xe8, 0xe9, 0xe5]),
feePolicy: BitcoinLikeFeePolicy.PER_BYTE,
dustAmount: new BigNumber(10000),
messagePrefix: "PPCoin Signed Message:\n",
usesTimestampedTransaction: true,
timestampDelay: new BigNumber(0),
sigHash: BitcoinLikeSigHashType.SIGHASH_ALL,
additionalBIPs: [],
};
} else if (networkName === "digibyte") {
return {
identifier: "dgb",
P2PKHVersion: Buffer.from([0x1e]),
P2SHVersion: Buffer.from([0x3f]),
xpubVersion: Buffer.from([0x04, 0x88, 0xb2, 0x1e]),
feePolicy: BitcoinLikeFeePolicy.PER_BYTE,
dustAmount: new BigNumber(10000),
messagePrefix: "DigiByte Signed Message:\n",
usesTimestampedTransaction: false,
timestampDelay: new BigNumber(0),
sigHash: BitcoinLikeSigHashType.SIGHASH_ALL,
additionalBIPs: [],
};
} else if (networkName === "hcash") {
return {
identifier: "hsr",
P2PKHVersion: Buffer.from([0x28]),
P2SHVersion: Buffer.from([0x78]),
xpubVersion: Buffer.from([0x04, 0x88, 0xc2, 0x1e]),
feePolicy: BitcoinLikeFeePolicy.PER_BYTE,
dustAmount: new BigNumber(10000),
messagePrefix: "HShare Signed Message:\n",
usesTimestampedTransaction: true,
timestampDelay: new BigNumber(0),
sigHash: BitcoinLikeSigHashType.SIGHASH_ALL,
additionalBIPs: [],
};
} else if (networkName === "qtum") {
return {
identifier: "qtum",
P2PKHVersion: Buffer.from([0x3a]),
P2SHVersion: Buffer.from([0x32]),
xpubVersion: Buffer.from([0x04, 0x88, 0xb2, 0x1e]),
feePolicy: BitcoinLikeFeePolicy.PER_BYTE,
dustAmount: new BigNumber(10000),
messagePrefix: "Qtum Signed Message:\n",
usesTimestampedTransaction: false,
timestampDelay: new BigNumber(0),
sigHash: BitcoinLikeSigHashType.SIGHASH_ALL,
additionalBIPs: [],
};
} else if (networkName === "stealthcoin") {
return {
identifier: "xst",
P2PKHVersion: Buffer.from([0x3e]),
P2SHVersion: Buffer.from([0x55]),
xpubVersion: Buffer.from([0x8f, 0x62, 0x4b, 0x66]),
feePolicy: BitcoinLikeFeePolicy.PER_BYTE,
dustAmount: new BigNumber(10000),
messagePrefix: "StealthCoin Signed Message:\n",
usesTimestampedTransaction: false,
// Used to depend on "version", cf. https://github.com/LedgerHQ/lib-ledger-core/blob/fc9d762b83fc2b269d072b662065747a64ab2816/core/src/wallet/bitcoin/networks.cpp#L250
timestampDelay: new BigNumber(15),
sigHash: BitcoinLikeSigHashType.SIGHASH_ALL,
additionalBIPs: [],
};
} else if (networkName === "vertcoin") {
return {
identifier: "vtc",
P2PKHVersion: Buffer.from([0x47]),
P2SHVersion: Buffer.from([0x05]),
xpubVersion: Buffer.from([0x04, 0x88, 0xb2, 0x1e]),
feePolicy: BitcoinLikeFeePolicy.PER_BYTE,
dustAmount: new BigNumber(10000),
messagePrefix: "VertCoin Signed Message:\n",
usesTimestampedTransaction: false,
timestampDelay: new BigNumber(0),
sigHash: BitcoinLikeSigHashType.SIGHASH_ALL,
additionalBIPs: [],
};
} else if (networkName === "viacoin") {
return {
identifier: "via",
P2PKHVersion: Buffer.from([0x47]),
P2SHVersion: Buffer.from([0x21]),
xpubVersion: Buffer.from([0x04, 0x88, 0xb2, 0x1e]),
feePolicy: BitcoinLikeFeePolicy.PER_BYTE,
dustAmount: new BigNumber(10000),
messagePrefix: "ViaCoin Signed Message:\n",
usesTimestampedTransaction: false,
timestampDelay: new BigNumber(0),
sigHash: BitcoinLikeSigHashType.SIGHASH_ALL,
additionalBIPs: [],
};
} else if (networkName === "dash") {
return {
identifier: "dash",
P2PKHVersion: Buffer.from([0x4c]),
P2SHVersion: Buffer.from([0x01]),
xpubVersion: Buffer.from([0x02, 0xfe, 0x52, 0xf8]),
feePolicy: BitcoinLikeFeePolicy.PER_BYTE,
dustAmount: new BigNumber(10000),
messagePrefix: "DarkCoin Signed Message:\n",
usesTimestampedTransaction: false,
timestampDelay: new BigNumber(0),
sigHash: BitcoinLikeSigHashType.SIGHASH_ALL,
additionalBIPs: [],
};
} else if (networkName === "dogecoin") {
return {
identifier: "doge",
P2PKHVersion: Buffer.from([0x1e]),
P2SHVersion: Buffer.from([0x16]),
xpubVersion: Buffer.from([0x02, 0xfa, 0xca, 0xfd]),
feePolicy: BitcoinLikeFeePolicy.PER_BYTE,
dustAmount: new BigNumber(10000),
messagePrefix: "DogeCoin Signed Message:\n",
usesTimestampedTransaction: false,
timestampDelay: new BigNumber(0),
sigHash: BitcoinLikeSigHashType.SIGHASH_ALL,
additionalBIPs: [],
};
} else if (networkName === "stratis") {
return {
identifier: "strat",
P2PKHVersion: Buffer.from([0x3f]),
P2SHVersion: Buffer.from([0x7d]),
xpubVersion: Buffer.from([0x04, 0x88, 0xc2, 0x1e]),
feePolicy: BitcoinLikeFeePolicy.PER_BYTE,
dustAmount: new BigNumber(10000),
messagePrefix: "Stratis Signed Message:\n",
usesTimestampedTransaction: true,
timestampDelay: new BigNumber(15),
sigHash: BitcoinLikeSigHashType.SIGHASH_ALL,
additionalBIPs: [],
};
} else if (networkName === "komodo") {
return {
identifier: "kmd",
P2PKHVersion: Buffer.from([0x3c]),
P2SHVersion: Buffer.from([0x55]),
xpubVersion: Buffer.from([0xf9, 0xee, 0xe4, 0x8d]),
feePolicy: BitcoinLikeFeePolicy.PER_BYTE,
dustAmount: new BigNumber(10000),
messagePrefix: "Komodo Signed Message:\n",
usesTimestampedTransaction: false,
timestampDelay: new BigNumber(0),
sigHash: BitcoinLikeSigHashType.SIGHASH_ALL,
additionalBIPs: [],
};
} else if (networkName === "poswallet") {
return {
identifier: "posw",
P2PKHVersion: Buffer.from([0x37]),
P2SHVersion: Buffer.from([0x55]),
xpubVersion: Buffer.from([0x04, 0x88, 0xb2, 0x1e]),
feePolicy: BitcoinLikeFeePolicy.PER_BYTE,
dustAmount: new BigNumber(10000),
messagePrefix: "PosWallet Signed Message:\n",
usesTimestampedTransaction: true,
timestampDelay: new BigNumber(0),
sigHash: BitcoinLikeSigHashType.SIGHASH_ALL,
additionalBIPs: [],
};
} else if (networkName === "pivx") {
return {
identifier: "pivx",
P2PKHVersion: Buffer.from([0x1e]),
P2SHVersion: Buffer.from([0x0d]),
xpubVersion: Buffer.from([0x02, 0x2d, 0x25, 0x33]),
feePolicy: BitcoinLikeFeePolicy.PER_BYTE,
dustAmount: new BigNumber(10000),
messagePrefix: "DarkNet Signed Message:\n",
usesTimestampedTransaction: false,
timestampDelay: new BigNumber(0),
sigHash: BitcoinLikeSigHashType.SIGHASH_ALL,
additionalBIPs: [],
};
} else if (networkName === "clubcoin") {
return {
identifier: "club",
P2PKHVersion: Buffer.from([0x1c]),
P2SHVersion: Buffer.from([0x55]),
xpubVersion: Buffer.from([0x04, 0x88, 0xb2, 0x1e]),
feePolicy: BitcoinLikeFeePolicy.PER_BYTE,
dustAmount: new BigNumber(10000),
messagePrefix: "Clubcoin Signed Message:\n",
usesTimestampedTransaction: true,
timestampDelay: new BigNumber(0),
sigHash: BitcoinLikeSigHashType.SIGHASH_ALL,
additionalBIPs: [],
};
} else if (networkName === "decred") {
return {
identifier: "dcr",
P2PKHVersion: Buffer.from([0x07, 0x3f]),
P2SHVersion: Buffer.from([0x07, 0x1a]),
xpubVersion: Buffer.from([0x02, 0xfd, 0xa9, 0x26]),
feePolicy: BitcoinLikeFeePolicy.PER_BYTE,
dustAmount: new BigNumber(10000),
messagePrefix: "Decred Signed Message:\n",
usesTimestampedTransaction: false,
timestampDelay: new BigNumber(0),
sigHash: BitcoinLikeSigHashType.SIGHASH_ALL,
additionalBIPs: [],
};
} else if (networkName === "stakenet") {
return {
identifier: "xsn",
P2PKHVersion: Buffer.from([0x4c]),
P2SHVersion: Buffer.from([0x10]),
xpubVersion: Buffer.from([0x04, 0x88, 0xb2, 0x1e]),
feePolicy: BitcoinLikeFeePolicy.PER_BYTE,
dustAmount: new BigNumber(10000),
messagePrefix: "Stakenet Signed Message:\n",
usesTimestampedTransaction: false,
timestampDelay: new BigNumber(0),
sigHash: BitcoinLikeSigHashType.SIGHASH_ALL,
additionalBIPs: [],
};
}
throw new Error("No network parameters set for " + networkName);
}; | the_stack |
import React, { useState, useMemo, useEffect } from "react";
import { OrgComponent } from "@ui_types";
import { Model, Api, Rbac } from "@core/types";
import { Link } from "react-router-dom";
import * as g from "@core/lib/graph";
import * as R from "ramda";
import { stripUndefinedRecursive } from "@core/lib/utils/object";
import { SvgImage, SmallLoader } from "@images";
import { MIN_ACTION_DELAY_MS } from "@constants";
import { wait } from "@core/lib/utils/wait";
import { logAndAlertError } from "@ui_lib/errors";
export const ManageEnvParentEnvironments: OrgComponent<
{ appId: string } | { blockId: string }
> = (props) => {
const { graph, graphUpdatedAt } = props.core;
const envParentId =
"appId" in props.routeParams
? props.routeParams.appId
: props.routeParams.blockId;
const currentUserId = props.ui.loadedAccountId!;
const {
baseEnvironmentsByRoleId,
baseEnvironmentSettingsByRoleId,
environmentRoles,
environmentRolesById,
} = useMemo(() => {
const baseEnvironments = g.authz.getVisibleBaseEnvironments(
graph,
currentUserId,
envParentId
);
const baseEnvironmentsByRoleId = R.indexBy(
R.prop("environmentRoleId"),
baseEnvironments
);
const environmentRoles = g.graphTypes(graph).environmentRoles;
return {
baseEnvironmentsByRoleId,
baseEnvironmentSettingsByRoleId: R.mapObjIndexed(
(environment) => (environment.isSub ? {} : environment.settings),
baseEnvironmentsByRoleId
),
environmentRoles,
environmentRolesById: R.indexBy(R.prop("id"), environmentRoles),
};
}, [graphUpdatedAt, envParentId, currentUserId]);
const [addingEnvironmentsByRoleId, setAddingEnvironmentsByRoleId] = useState<
Record<string, boolean>
>({});
const [removingEnvironmentsByRoleId, setRemovingEnvironmentsByRoleId] =
useState<Record<string, boolean>>({});
const [
updatingEnvironmentSettingsByRoleId,
setUpdatingEnvironmentSettingsByRoleId,
] = useState<Record<string, boolean>>({});
const [
environmentSettingsByRoleIdState,
setEnvironmentSettingsByRoleIdState,
] = useState(baseEnvironmentSettingsByRoleId);
const [awaitingMinDelayByRoleId, setAwaitingMinDelayByRoleId] = useState<
Record<string, boolean>
>({});
useEffect(() => {
setAddingEnvironmentsByRoleId({});
setRemovingEnvironmentsByRoleId({});
setUpdatingEnvironmentSettingsByRoleId({});
setEnvironmentSettingsByRoleIdState(baseEnvironmentSettingsByRoleId);
}, [envParentId]);
const environmentSettingsUpdated = (roleId: string) => {
const environment = baseEnvironmentsByRoleId[roleId];
if (
!environment ||
environment.isSub ||
!environmentSettingsByRoleIdState[roleId]
) {
return false;
}
const settings = environment.settings;
return !R.equals(
stripUndefinedRecursive(settings),
stripUndefinedRecursive(environmentSettingsByRoleIdState[roleId])
);
};
const dispatchEnvironmentSettingsUpdate = () => {
for (let roleId in environmentSettingsByRoleIdState) {
if (
updatingEnvironmentSettingsByRoleId[roleId] ||
!environmentSettingsUpdated(roleId)
) {
continue;
}
setUpdatingEnvironmentSettingsByRoleId({
...updatingEnvironmentSettingsByRoleId,
[roleId]: true,
});
setAwaitingMinDelayByRoleId({
...awaitingMinDelayByRoleId,
[roleId]: true,
});
wait(MIN_ACTION_DELAY_MS).then(() =>
setAwaitingMinDelayByRoleId({
...awaitingMinDelayByRoleId,
[roleId]: false,
})
);
const environment = baseEnvironmentsByRoleId[roleId];
props
.dispatch({
type: Api.ActionType.UPDATE_ENVIRONMENT_SETTINGS,
payload: {
id: environment.id,
settings: environmentSettingsByRoleIdState[roleId],
},
})
.then((res) => {
if (!res.success) {
logAndAlertError(
`There was a problem updating environment settings.`,
(res.resultAction as any)?.payload
);
}
});
}
};
useEffect(() => {
dispatchEnvironmentSettingsUpdate();
}, [JSON.stringify(environmentSettingsByRoleIdState)]);
useEffect(() => {
for (let roleId in environmentSettingsByRoleIdState) {
if (
updatingEnvironmentSettingsByRoleId[roleId] &&
!awaitingMinDelayByRoleId[roleId]
) {
setUpdatingEnvironmentSettingsByRoleId(
R.omit([roleId], updatingEnvironmentSettingsByRoleId)
);
}
}
}, [
JSON.stringify(baseEnvironmentSettingsByRoleId),
JSON.stringify(awaitingMinDelayByRoleId),
]);
useEffect(() => {
const toOmitAdding = Object.keys(addingEnvironmentsByRoleId).filter(
(roleId) => baseEnvironmentsByRoleId[roleId]
);
const awaitingMinDelay = Object.values(awaitingMinDelayByRoleId).some(
Boolean
);
if (toOmitAdding.length > 0 && !awaitingMinDelay) {
setAddingEnvironmentsByRoleId(
R.omit(toOmitAdding, addingEnvironmentsByRoleId)
);
}
const toOmitRemoving = Object.keys(removingEnvironmentsByRoleId).filter(
(roleId) => !baseEnvironmentsByRoleId[roleId]
);
if (toOmitRemoving.length > 0 && !awaitingMinDelay) {
setRemovingEnvironmentsByRoleId(
R.omit(toOmitRemoving, removingEnvironmentsByRoleId)
);
}
}, [
JSON.stringify(baseEnvironmentsByRoleId),
JSON.stringify(awaitingMinDelayByRoleId),
]);
const renderEnvironmentRoleSettings = (role: Rbac.EnvironmentRole) => {
let included: boolean;
let includedEnvironment: Model.Environment | undefined;
let removing = false;
let adding = false;
if (removingEnvironmentsByRoleId[role.id]) {
included = false;
removing = true;
} else if (addingEnvironmentsByRoleId[role.id]) {
included = true;
adding = true;
} else {
includedEnvironment = baseEnvironmentsByRoleId[role.id];
included = Boolean(includedEnvironment);
}
const updatingSettings = Boolean(
updatingEnvironmentSettingsByRoleId[role.id]
);
const updating = removing || adding || updatingSettings;
let autoCommitOption: "inherit" | "overrideTrue" | "overrideFalse";
const autoCommit = environmentSettingsByRoleIdState[role.id]?.autoCommit;
if (typeof autoCommit == "undefined") {
autoCommitOption = "inherit";
} else {
autoCommitOption = autoCommit ? "overrideTrue" : "overrideFalse";
}
return (
<div>
<h4>
{role.name} {updating ? <SmallLoader /> : ""}
</h4>
<div
className={
"field checkbox" +
(included ? " selected" : "") +
(updating ? " disabled" : "")
}
onClick={() => {
if (updating) {
return;
}
if (!awaitingMinDelayByRoleId[role.id]) {
setAwaitingMinDelayByRoleId({
...awaitingMinDelayByRoleId,
[role.id]: true,
});
wait(MIN_ACTION_DELAY_MS).then(() =>
setAwaitingMinDelayByRoleId({
...awaitingMinDelayByRoleId,
[role.id]: false,
})
);
}
if (included && includedEnvironment) {
setRemovingEnvironmentsByRoleId({
...removingEnvironmentsByRoleId,
[role.id]: true,
});
props
.dispatch({
type: Api.ActionType.DELETE_ENVIRONMENT,
payload: { id: includedEnvironment.id },
})
.then((res) => {
if (!res.success) {
logAndAlertError(
`There was a problem deleting the environment.`,
(res.resultAction as any)?.payload
);
}
});
} else {
setAddingEnvironmentsByRoleId({
...addingEnvironmentsByRoleId,
[role.id]: true,
});
props
.dispatch({
type: Api.ActionType.CREATE_ENVIRONMENT,
payload: { envParentId, environmentRoleId: role.id },
})
.then((res) => {
if (!res.success) {
logAndAlertError(
`There was a problem adding the environment.`,
(res.resultAction as any)?.payload
);
}
});
}
}}
>
<label>Include environment</label>
<input type="checkbox" checked={included} disabled={updating} />
</div>
{/* {includedEnvironment ? (
<div className="field">
<label>Auto-Commit On Change?</label>
<div className="select">
<select
value={autoCommitOption}
disabled={updating}
onChange={(e) => {
let val: boolean | undefined;
if (e.target.value == "inherit") {
val = undefined;
} else {
val = e.target.value == "overrideTrue";
}
setEnvironmentSettingsByRoleIdState({
...environmentSettingsByRoleIdState,
[role.id]: stripUndefinedRecursive({
...environmentSettingsByRoleIdState[role.id],
autoCommit: val,
}),
});
}}
>
<option value="inherit">
Inherit from org settings (
{environmentRolesById[role.id].settings?.autoCommit
? "Yes"
: "No"}
)
</option>
<option value="overrideTrue">Yes</option>
<option value="overrideFalse">No</option>
</select>
<SvgImage type="down-caret" />
</div>
</div>
) : (
""
)} */}
</div>
);
};
return (
<div>
<div>
<h3>
Manage <strong>Environments</strong>
</h3>
{environmentRoles.map(renderEnvironmentRoleSettings)}
</div>
{g.authz.hasOrgPermission(
graph,
currentUserId,
"org_manage_environment_roles"
) ? (
<div className="buttons">
<Link
className="primary"
to={props.match.url.replace(
/\/settings$/,
"/settings/environment-role-form"
)}
>
Add Base Environment
</Link>
<Link
className="tertiary"
to={props.orgRoute("/my-org/environment-settings")}
>
Manage Org Environments
</Link>
</div>
) : (
""
)}
</div>
);
}; | the_stack |
type MatrixMapAxisFunction<T, R = any, M = T> = (value: T, i: number, matrix?: Matrix<M>) => R
type MatrixMapFunction<V, M = any, R = any> = (value: V, x: number, y: number, matrix?: Matrix<M>) => R
type MatrixReduceFunction<A, T = any> = (acc: A, el: T, x: number, y: number, matrix?: Matrix<T>) => A
export const MatrixDeserializers = {
json: v => {
try {
return JSON.parse(v)
} catch (e) {
return v
}
},
number: v => Number(v),
string: v => v,
}
export const MatrixSerializer = {
number: (v: number) => String(v),
string: (v: string) => v,
json: v => {
if (typeof v === 'number' || typeof v === 'string') return v
try {
return JSON.parse(v)
} catch (e) {
return v
}
},
}
const defaultSerializeOptions = {
headerDelimiter: ',',
metaDelimiter: ';',
delimiter: '',
deserializer: MatrixDeserializers.json,
serializer: MatrixSerializer.json,
}
type SerializeOptions = typeof defaultSerializeOptions
const HEIGHTS = 'x0123456789abcdefghijklmnopqrstuvwyz'
export class Matrix<T = any> {
static NEIGHBORS = {
TOP_LEFT: { x: -1, y: -1 },
TOP: { x: 0, y: -1 },
TOP_RIGHT: { x: 1, y: -1 },
RIGHT: { x: 1, y: 0 },
BOTTOM_RIGHT: { x: 1, y: 1 },
BOTTOM: { x: 0, y: 1 },
BOTTOM_LEFT: { x: -1, y: 1 },
LEFT: { x: -1, y: 0 },
CENTER: { x: 0, y: 0 },
}
static NEIGHBORS_ALL = [
Matrix.NEIGHBORS.TOP_LEFT,
Matrix.NEIGHBORS.TOP,
Matrix.NEIGHBORS.TOP_RIGHT,
Matrix.NEIGHBORS.RIGHT,
Matrix.NEIGHBORS.BOTTOM_RIGHT,
Matrix.NEIGHBORS.BOTTOM,
Matrix.NEIGHBORS.BOTTOM_LEFT,
Matrix.NEIGHBORS.LEFT,
]
static NEIGHBORS_ADJACENT = [
Matrix.NEIGHBORS.TOP,
Matrix.NEIGHBORS.RIGHT,
Matrix.NEIGHBORS.BOTTOM,
Matrix.NEIGHBORS.LEFT,
]
static NEIGHBORS_DIAGONAL = [
Matrix.NEIGHBORS.TOP_LEFT,
Matrix.NEIGHBORS.TOP_RIGHT,
Matrix.NEIGHBORS.BOTTOM_RIGHT,
Matrix.NEIGHBORS.BOTTOM_LEFT,
]
constructor(
public width: number = 3,
public height: number = width,
public data: T[] = new Array(width * height).fill(null),
public meta = [],
) {
this.data = data.slice(0, width * height)
}
*rowsEntries(start = 0, end = this.height - 1): Generator<[number, T[]]> {
for (let i = start; i <= end; i++) {
yield [i, this.getRow(i)]
}
}
*columnsEntries(): Generator<[number, T[]]> {
for (let i = 0; i < this.width; i++) {
yield [i, this.getCol(i)]
}
}
/**
* Retorna o índice pela linha e coluna
* @param x Coluna
* @param y Linha
*/
getIndexOf(x: number, y: number) {
return y * this.width + x
}
/**
* Retorna a linha e coluna pelo índice
* @param index Índice
*/
getCoords(index: number) {
return {
x: index % this.width,
y: Math.floor(index / this.width),
}
}
/**
* Retorna um valor pela linha e coluna
* @param x Coluna
* @param y Linha
* @param defaultValue Valor padrão caso não seja definido
*/
get(x: number, y: number, defaultValue: any = null): T {
if (x < 0 || y < 0 || x >= this.width || y >= this.height) return defaultValue
const index = this.getIndexOf(x, y)
return index >= this.data.length ? defaultValue : this.data[index]
}
/**
* Define um valor pela linha e coluna
* @param x Coluna
* @param y Linha
* @param value Novo valor
*/
set(x: number, y: number, value: T): Matrix<T> {
const index = this.getIndexOf(x, y)
this.data[index] = value
return this
}
/**
* Retorna uma coluna inteira
* @param x Índice da coluna
*/
getCol(x: number): T[] {
if (x >= this.width) throw new Error(`Invalid column!`)
return this.data.filter((_, index) => {
return (index - x) % this.width === 0
})
}
/**
* Retorna uma linha inteira
* @param y Índice da linha
*/
getRow(y: number): T[] {
if (y >= this.height) throw new Error(`Invalid row!`)
const start = y * this.width
const end = start + this.width
return this.data.slice(start, end)
}
/**
* Preenche a matrix com um valor
* @param value valor a ser preenchido
*/
fill(value: T | MatrixMapFunction<T>): this {
if (typeof value === 'function') {
this.data = this.map(value as MatrixMapFunction<T>).data
} else {
this.data = new Array(this.width * this.height).fill(value)
}
return this
}
/**
* Retorna uma string única contendo a matriz
*/
toLegacyString() {
return this.mapRows((lin, nlin) => lin.map((val: any) => HEIGHTS[val]).join('')).join('\n')
}
/**
* Mapeia todas as linhas da matriz
* @param cb Callback de mapeamento
*/
mapRows<R>(cb: MatrixMapAxisFunction<T[], R, T>): R[] {
const maped = []
for (let y = 0; y < this.height; y++) {
maped[y] = cb(this.getRow(y), y, this)
}
return maped
}
/**
* Mapeia todas as colunas da matriz
* @param cb Callback de mapeamento
*/
mapCols<C>(cb: MatrixMapAxisFunction<T[], C, T>): C[] {
const maped = []
for (let x = 0; x < this.width; x++) {
maped[x] = cb(this.getCol(x), x, this)
}
return maped
}
/**
* Mapeia todos os itens da matriz
* @param cb Callback de mapeamento
*/
map<M>(cb: (value: T, x: number, y: number, matrix: this) => M): Matrix<M> {
return Matrix.fromArray(
this.data.map((value, index) => {
const { x, y } = this.getCoords(index)
return cb(value, x, y, this)
}),
this.width,
this.height,
)
}
/**
* Cria uma nova matriz apartir desta
*/
clone(): Matrix<T> {
return Matrix.from<T>(this.data, this.width, this.height)
}
/**
* Retorna se todos os elementos passaram em um teste
* @param cb Callback de teste
*/
every(cb: (value: T, x: number, y: number, matrix: this) => boolean): boolean {
return this.data.every((value, index) => {
const { x, y } = this.getCoords(index)
return cb(value, x, y, this)
})
}
/**
* Retorna se alguns elementos passaram em um teste
* @param cb Callback de teste
*/
some(cb: (value: T, x: number, y: number, matrix: this) => boolean): boolean {
return this.data.some((value, index) => {
const { x, y } = this.getCoords(index)
return cb(value, x, y, this)
})
}
/**
* Retorna se algumas linhas passaram em um teste
* @param cb Callback de teste
*/
someRows(cb: (values: T[], y: number, matrix: this) => boolean): boolean {
for (let i = 0; i < this.height; i++) {
if (cb(this.getRow(i), i, this)) return true
}
return false
}
/**
* Retorna se algumas colunas passaram em um teste
* @param cb Callback de teste
*/
someColuns(cb: (values: T[], y: number, matrix: this) => boolean): boolean {
for (let i = 0; i < this.width; i++) {
if (cb(this.getCol(i), i, this)) return true
}
return false
}
/**
* Executa uma função para cada elemento
* @param cb Callback a ser executado para cada item
*/
forEach(cb: MatrixMapFunction<T, T, any>): void {
return this.data.forEach((value, index) => {
const { x, y } = this.getCoords(index)
return cb(value, x, y, this)
})
}
*entries(): Generator<[[number, number], T]> {
for (let y = 0; y < this.height; y++) {
for (let x = 0; x < this.width; x++) {
yield [[x, y], this.get(x, y)]
}
}
}
/**
* Executa uma função para cada linha
* @param cb Callback a ser executado para cada linha
*/
forEachRow(cb: MatrixMapAxisFunction<T[], void, any>): void {
for (let y = 0; y < this.height; y++) {
cb(this.getRow(y), +y, this)
}
}
/**
* Reduz o valor do array em outro valor
* @param cb Callback de redução
* @param initialValue Valor inicião
*/
reduce<U>(cb: MatrixReduceFunction<U, T>, initialValue?: U): U {
return this.data.reduce<U>((acc, value, index) => {
const { x, y } = this.getCoords(index)
return cb(acc, value, x, y, this)
}, initialValue)
}
/**
* Retorna os valores vizinhos à outro elemento pela linha e coluna
* @param x Coluna
* @param y Linha
*/
neighborsOf(x: number, y: number, items = Matrix.NEIGHBORS_ALL): T[] {
return items.map(r => this.get(x + r.x, y + r.y))
}
/**
* Cria uma nova matriz apartir de uma string codificada
* @param encodedMatrix String codificada
* @param param1 Opções de decodificação
*/
static parse<T>(
encodedMatrix: string,
{
metaDelimiter = defaultSerializeOptions.metaDelimiter,
headerDelimiter = defaultSerializeOptions.headerDelimiter,
deserializer = defaultSerializeOptions.deserializer,
delimiter = defaultSerializeOptions.delimiter,
} = {},
): Matrix<T> {
const [encodedHeader, encodedData] = encodedMatrix.split(metaDelimiter)
const [cols, rows, ...meta] = encodedHeader.split(headerDelimiter)
deserializer = deserializer || MatrixDeserializers.string
const data = encodedData.split(delimiter).map<T>(deserializer)
return this.fromArray<T>(data, +cols, +rows, meta.map(MatrixDeserializers.json))
}
/**
* Cria uma nova matrix a partir de um Array
* @param data Array
* @param [cols] Quantidade de colunas
* @param [rows] Quantidade de linhas
* @param [meta] Informações customizadas
*/
static fromArray<T = any>(data: T[], cols: number, rows: number, meta = []): Matrix<T> {
return new Matrix(cols, rows, data, meta)
}
/**
* Cria uma matriz a partir de uma string
* @param data String codificada
* @param options Opções de decodificação
*/
static from<T = any>(data: string, options?: SerializeOptions): Matrix<T>
/**
* Cria uma matriz a partir de um Array 1D
* @param data Array 1D
* @param cols Quantidade de colunas
* @param rows Quantidade de linhas
*/
static from<T = any>(data: T[], cols: number, rows: number): Matrix<T>
/**
* Cria uma matriz a partir de um Array 2D
* @param data Array 2D
*/
static from<T = any>(data: T[][]): Matrix<T>
/**
* Cria uma matriz a partir de outra matriz
* @param data Matrix a ser clonada
*/
static from<T = any>(data: Matrix): Matrix<T>
static from<T = any>(data, cols?, rows?, options?: SerializeOptions): Matrix<T> {
// Clone
if (data instanceof this) return data.clone()
// Encoded String
if (typeof data === 'string') {
options = cols || defaultSerializeOptions
return this.parse<T>(data, options)
}
// Array
if (Array.isArray(data)) {
// 2D Array
if (Array.isArray(data[0])) {
cols = data[0].length
rows = data.length
return this.fromArray<T>([].concat(...data), cols, rows)
}
// 1D Array
return new Matrix<T>(cols, rows, data)
}
throw new TypeError(`Type of data should be Array, Array2D, String or Matrix instance.`)
}
/**
* Codifica a matriz em uma string
* @param param0 Opções de codificação
*/
stringify({ headerDelimiter = ',', metaDelimiter = ':', delimiter = ',', serializer = v => v } = {}) {
return [
[this.width, this.height, ...this.meta.map(MatrixSerializer.json)].join(headerDelimiter),
this.data.map(serializer).join(delimiter),
].join(metaDelimiter)
}
toString() {
return `[Matrix ${this.width}x${this.height}] {\n ${this.mapRows(v => v.map(v => String(v || 0)).join(' ')).join(
'\n ',
)}\n}`
}
static fromLegacyString<T extends number>(map: string) {
map = map.replace(new RegExp(`[^${HEIGHTS}\n]|^\n+|\n+$`, 'gm'), '')
const { data, cols, rows } = map.split('').reduce(
(acc, char) => {
if (char === '\n') {
acc.rowCol = 0
acc.rows++
} else {
const i = HEIGHTS.indexOf(char) as T
acc.data.push(i)
acc.cols = Math.max(acc.cols, ++acc.rowCol)
acc.rows = Math.max(1, acc.rows)
}
return acc
},
{
data: [] as T[],
cols: 0,
rowCol: 0,
rows: 0,
},
)
return Matrix.from<T>(data, cols, rows)
}
} | the_stack |
import { request as http_request } from 'http';
import { AuthenticationProvider, encodeUriComponentStrict, SharedAccessSignature } from 'azure-iot-common';
import { SharedAccessKeyAuthenticationProvider } from './sak_authentication_provider';
import { HttpRequestOptions, RestApiClient } from 'azure-iot-http-base';
import * as url from 'url';
// tslint:disable-next-line:no-var-requires
const packageJson = require('../package.json');
/**
* @private
*
* The iotedged HTTP API version this code is built to work with.
*/
export const WORKLOAD_API_VERSION = '2018-06-28';
const DEFAULT_SIGN_ALGORITHM = 'HMACSHA256';
const DEFAULT_KEY_ID = 'primary';
/**
* @private
*
* This interface defines the configuration information that this class needs in order to be able to communicate with iotedged.
*/
export interface EdgedAuthConfig {
workloadUri: string;
deviceId: string;
moduleId: string;
iothubHostName: string;
authScheme: string;
gatewayHostName?: string;
generationId: string;
}
interface SignRequest {
keyId: string;
algo: string;
data: string;
}
interface SignResponse {
digest: string;
}
/**
* Provides an `AuthenticationProvider` implementation that delegates token generation to iotedged. This implementation is meant to be used when using the module client with Azure IoT Edge.
*
* This type inherits from `SharedAccessKeyAuthenticationProvider` and is functionally identical to that type except for the token generation part which it overrides by implementing the `_sign` method.
*/
export class IotEdgeAuthenticationProvider extends SharedAccessKeyAuthenticationProvider implements AuthenticationProvider {
private _restApiClient: RestApiClient;
private _workloadUri: url.UrlWithStringQuery;
/**
* @private
*
* Initializes a new instance of the IotEdgeAuthenticationProvider.
*
* @param _authConfig iotedged connection configuration information.
* @param tokenValidTimeInSeconds [optional] The number of seconds for which a token is supposed to be valid.
* @param tokenRenewalMarginInSeconds [optional] The number of seconds before the end of the validity period during which the `IotEdgeAuthenticationProvider` should renew the token.
*/
constructor(private _authConfig: EdgedAuthConfig, tokenValidTimeInSeconds?: number, tokenRenewalMarginInSeconds?: number) {
// Codes_SRS_NODE_IOTEDGED_AUTHENTICATION_PROVIDER_13_016: [ The constructor shall create the initial token value using the credentials parameter. ]
// Codes_SRS_NODE_IOTEDGED_AUTHENTICATION_PROVIDER_13_017: [ The constructor shall throw an ArgumentError if the tokenRenewalMarginInSeconds is less than or equal tokenValidTimeInSeconds. ]
super(
{
host: _authConfig && _authConfig.iothubHostName,
deviceId: _authConfig && _authConfig.deviceId,
moduleId: _authConfig && _authConfig.moduleId,
gatewayHostName: _authConfig && _authConfig.gatewayHostName
},
tokenValidTimeInSeconds,
tokenRenewalMarginInSeconds
);
// Codes_SRS_NODE_IOTEDGED_AUTHENTICATION_PROVIDER_13_001: [ The constructor shall throw a ReferenceError if the _authConfig parameter is falsy. ]
if (!this._authConfig) {
throw new ReferenceError('_authConfig cannot be \'' + _authConfig + '\'');
}
// Codes_SRS_NODE_IOTEDGED_AUTHENTICATION_PROVIDER_13_002: [ The constructor shall throw a ReferenceError if the _authConfig.workloadUri field is falsy. ]
if (!this._authConfig.workloadUri) {
throw new ReferenceError('_authConfig.workloadUri cannot be \'' + this._authConfig.workloadUri + '\'');
}
// Codes_SRS_NODE_IOTEDGED_AUTHENTICATION_PROVIDER_13_003: [ The constructor shall throw a ReferenceError if the _authConfig.moduleId field is falsy. ]
if (!this._authConfig.moduleId) {
throw new ReferenceError('_authConfig.moduleId cannot be \'' + this._authConfig.moduleId + '\'');
}
// Codes_SRS_NODE_IOTEDGED_AUTHENTICATION_PROVIDER_13_004: [ The constructor shall throw a ReferenceError if the _authConfig.generationId field is falsy. ]
if (!this._authConfig.generationId) {
throw new ReferenceError('_authConfig.generationId cannot be \'' + this._authConfig.generationId + '\'');
}
// Codes_SRS_NODE_IOTEDGED_AUTHENTICATION_PROVIDER_13_005: [ The constructor shall throw a TypeError if the _authConfig.workloadUri field is not a valid URI. ]
// Codes_SRS_NODE_IOTEDGED_AUTHENTICATION_PROVIDER_13_006: [ The constructor shall build a unix domain socket path host if the workload URI protocol is unix. ]
// Codes_SRS_NODE_IOTEDGED_AUTHENTICATION_PROVIDER_13_007: [ The constructor shall build a string host if the workload URI protocol is not unix. ]
this._workloadUri = url.parse(this._authConfig.workloadUri);
const config: RestApiClient.TransportConfig = {
host: this._workloadUri.protocol === 'unix:' ? { socketPath: this._workloadUri.pathname } : this._workloadUri.hostname,
tokenCredential: undefined
};
// TODO: The user agent string below needs to be constructed using the utils.getUserAgentString function.
// But that is an async function and since we can't do async things while initializing fields, one way to
// handle this might be to make this._restApiClient a lazily initialized object.
this._restApiClient = new RestApiClient(config, `${packageJson.name}/${packageJson.version}`);
}
public getTrustBundle(callback: (err?: Error, ca?: string) => void): void {
// Codes_SRS_NODE_IOTEDGED_AUTHENTICATION_PROVIDER_13_020: [ The getTrustBundle method shall throw a ReferenceError if the callback parameter is falsy or is not a function. ]
if (!callback || typeof callback !== 'function') {
throw new ReferenceError('callback cannot be \'' + callback + '\'');
}
// Codes_SRS_NODE_IOTEDGED_AUTHENTICATION_PROVIDER_13_022: [ The getTrustBundle method shall build the HTTP request path in the format /trust-bundle?api-version=2018-06-28. ]
const path = `/trust-bundle?api-version=${encodeUriComponentStrict(WORKLOAD_API_VERSION)}`;
// Codes_SRS_NODE_IOTEDGED_AUTHENTICATION_PROVIDER_13_021: [ The getTrustBundle method shall invoke this._restApiClient.executeApiCall to make the REST call on iotedged using the GET method. ]
// Codes_SRS_NODE_IOTEDGED_AUTHENTICATION_PROVIDER_13_023: [** The `getTrustBundle` method shall set the HTTP request option's `request` property to use the `http.request` object.
// Codes_SRS_NODE_IOTEDGED_AUTHENTICATION_PROVIDER_13_024: [** The `getTrustBundle` method shall set the HTTP request option's `port` property to use the workload URI's port if available.
this._restApiClient.executeApiCall('GET', path, null, null, this._getRequestOptions(), (err, ca) => {
if (err) {
callback(err);
} else {
callback(null, ca.certificate);
}
});
}
protected _sign(resourceUri: string, expiry: number, callback: (err: Error, signature?: string) => void): void {
// Codes_SRS_NODE_IOTEDGED_AUTHENTICATION_PROVIDER_13_009: [ The _sign method shall throw a ReferenceError if the callback parameter is falsy or is not a function. ]
if (!callback || typeof callback !== 'function') {
throw new ReferenceError('callback cannot be \'' + callback + '\'');
}
// Codes_SRS_NODE_IOTEDGED_AUTHENTICATION_PROVIDER_13_010: [ The _sign method invoke callback with a ReferenceError if the resourceUri parameter is falsy. ]
if (!resourceUri) {
callback(new ReferenceError('resourceUri cannot be \'' + resourceUri + '\''), null);
return;
}
// Codes_SRS_NODE_IOTEDGED_AUTHENTICATION_PROVIDER_13_011: [ The _sign method shall build the HTTP request path in the format /modules/<module id>/genid/<generation id>/sign?api-version=2018-06-28. ]
// the request path needs to look like this:
// /modules/<module id>/genid/<generation id>/sign?api-version=2018-06-28
const path = `/modules/${encodeUriComponentStrict(this._authConfig.moduleId)}/genid/${encodeUriComponentStrict(
this._authConfig.generationId
)}/sign?api-version=${encodeUriComponentStrict(WORKLOAD_API_VERSION)}`;
// Codes_SRS_NODE_IOTEDGED_AUTHENTICATION_PROVIDER_13_027: [** The `_sign` method shall use the `SharedAccessSignature.createWithSigningFunction` function to build the data buffer which is to be signed by iotedged.
SharedAccessSignature.createWithSigningFunction(this._credentials, expiry, (buffer, signCallback) => {
// Codes_SRS_NODE_IOTEDGED_AUTHENTICATION_PROVIDER_13_014: [ The _sign method shall build an object with the following schema as the HTTP request body as the sign request:
// interface SignRequest {
// keyId: string;
// algo: string;
// data: string;
// }
// ]
// Codes_SRS_NODE_IOTEDGED_AUTHENTICATION_PROVIDER_13_013: [ The _sign method shall build the sign request using the following values:
// const signRequest = {
// keyId: "primary"
// algo: "HMACSHA256"
// data: `${data}\n${expiry}`
// };
// ]
const signRequest: SignRequest = {
keyId: DEFAULT_KEY_ID,
algo: DEFAULT_SIGN_ALGORITHM,
data: buffer.toString('base64')
};
// Codes_SRS_NODE_IOTEDGED_AUTHENTICATION_PROVIDER_13_019: [ The _sign method shall invoke this._restApiClient.executeApiCall to make the REST call on iotedged using the POST method. ]
// Codes_SRS_NODE_IOTEDGED_AUTHENTICATION_PROVIDER_13_025: [** The `_sign` method shall set the HTTP request option's `request` property to use the `http.request` object.
// Codes_SRS_NODE_IOTEDGED_AUTHENTICATION_PROVIDER_13_026: [** The `_sign` method shall set the HTTP request option's `port` property to use the workload URI's port if available.
this._restApiClient.executeApiCall(
'POST',
path,
{ 'Content-Type': 'application/json' },
signRequest,
this._getRequestOptions(),
(err, body: SignResponse, _response) => {
if (err) {
signCallback(err, null);
} else {
// Codes_SRS_NODE_IOTEDGED_AUTHENTICATION_PROVIDER_13_015: [ The _sign method shall invoke callback when the signature is available. ]
signCallback(null, Buffer.from(body.digest, 'base64'));
}
});
}, (err, sas) => {
if (err) {
callback(err);
} else {
callback(null, sas.toString());
}
});
}
private _getRequestOptions(): HttpRequestOptions {
const requestOptions: HttpRequestOptions = {
request: http_request,
};
if (this._workloadUri.port) {
const port = parseInt(this._workloadUri.port);
if (!isNaN(port)) {
requestOptions.port = port;
}
}
return requestOptions;
}
} | the_stack |
import { BaseExtension } from '../baseExtension';
import { Extension } from '../extension';
import { ContentsIdDao } from '../contents/contentsIdDao';
import { IconTable } from './iconTable';
import { IconDao } from './iconDao';
import { StyleTable } from './styleTable';
import { StyleDao } from './styleDao';
import { StyleMappingTable } from './styleMappingTable';
import { StyleMappingDao } from './styleMappingDao';
import { UserMappingTable } from '../relatedTables/userMappingTable';
import { StyleTableReader } from './styleTableReader';
import { UserTableReader } from '../../user/userTableReader';
import { FeatureTable } from '../../features/user/featureTable';
import { FeatureStyles } from './featureStyles';
import { FeatureStyle } from './featureStyle';
import { Styles } from './styles';
import { Icons } from './icons';
import { IconRow } from './iconRow';
import { FeatureRow } from '../../features/user/featureRow';
import { RelatedTablesExtension } from '../relatedTables';
import { ContentsIdExtension } from '../contents';
import { GeoPackage } from '../../geoPackage';
import { ExtendedRelation } from '../relatedTables/extendedRelation';
import { StyleRow } from './styleRow';
import { StyleMappingRow } from './styleMappingRow';
import {UserCustomTableReader} from "../../user/custom/userCustomTableReader";
/**
* Style extension
* @param {module:geoPackage~GeoPackage} geoPackage GeoPackage object
* @extends BaseExtension
* @constructor
*/
export class FeatureStyleExtension extends BaseExtension {
relatedTablesExtension: RelatedTablesExtension;
contentsIdExtension: ContentsIdExtension;
public static readonly EXTENSION_NAME = 'nga_feature_style';
public static readonly EXTENSION_AUTHOR = 'nga';
public static readonly EXTENSION_NAME_NO_AUTHOR = 'feature_style';
public static readonly EXTENSION_DEFINITION =
'http://ngageoint.github.io/GeoPackage/docs/extensions/feature-style.html';
public static readonly TABLE_MAPPING_STYLE = FeatureStyleExtension.EXTENSION_AUTHOR + '_style_';
public static readonly TABLE_MAPPING_TABLE_STYLE = FeatureStyleExtension.EXTENSION_AUTHOR + '_style_default_';
public static readonly TABLE_MAPPING_ICON = FeatureStyleExtension.EXTENSION_AUTHOR + '_icon_';
public static readonly TABLE_MAPPING_TABLE_ICON = FeatureStyleExtension.EXTENSION_AUTHOR + '_icon_default_';
constructor(geoPackage: GeoPackage) {
super(geoPackage);
this.relatedTablesExtension = geoPackage.relatedTablesExtension;
this.contentsIdExtension = geoPackage.contentsIdExtension;
}
/**
* Get or create the metadata extension
* @param {module:features/user/featureTable|String} featureTable, defaults to null
* @return {Promise}
*/
getOrCreateExtension(featureTable: FeatureTable | string): Extension {
return this.getOrCreate(
FeatureStyleExtension.EXTENSION_NAME,
this.getFeatureTableName(featureTable),
null,
FeatureStyleExtension.EXTENSION_DEFINITION,
Extension.READ_WRITE,
);
}
/**
* Determine if the GeoPackage has the extension or has the extension for the feature table
* @param {module:features/user/featureTable|String} featureTable feature table
* @returns {Boolean}
*/
has(featureTable: FeatureTable | string): boolean {
return this.hasExtension(FeatureStyleExtension.EXTENSION_NAME, this.getFeatureTableName(featureTable), null);
}
/**
* Gets featureTables
* @returns {String[]}
*/
getTables(): string[] {
const tables = [];
if (this.extensionsDao.isTableExists()) {
const extensions = this.extensionsDao.queryAllByExtension(FeatureStyleExtension.EXTENSION_NAME);
for (let i = 0; i < extensions.length; i++) {
tables.push(extensions[i].table_name);
}
}
return tables;
}
/**
* Get the related tables extension
* @returns {module:extension/relatedTables~RelatedTablesExtension}
*/
getRelatedTables(): RelatedTablesExtension {
return this.relatedTablesExtension;
}
/**
* Get the contentsId extension
* @returns {module:extension/contents~ContentsIdExtension}
*/
getContentsId(): ContentsIdExtension {
return this.contentsIdExtension;
}
/**
* Create style, icon, table style, and table icon relationships for the
* feature table
* @param {module:features/user/featureTable|String} featureTable feature table
* @return {any}
*/
createRelationships(
featureTable: FeatureTable | string,
): {
styleRelationship: ExtendedRelation;
tableStyleRelationship: ExtendedRelation;
iconRelationship: ExtendedRelation;
tableIconRelationship: ExtendedRelation;
} {
return {
styleRelationship: this.createStyleRelationship(featureTable),
tableStyleRelationship: this.createTableStyleRelationship(featureTable),
iconRelationship: this.createIconRelationship(featureTable),
tableIconRelationship: this.createTableIconRelationship(featureTable),
};
}
/**
* Check if feature table has a style, icon, table style, or table icon
* relationships
* @param {module:features/user/featureTable|String} featureTable feature table
* @returns {boolean}
*/
hasRelationship(featureTable: string | FeatureTable): boolean {
return (
this.hasStyleRelationship(featureTable) ||
this.hasTableStyleRelationship(featureTable) ||
this.hasIconRelationship(featureTable) ||
this.hasTableIconRelationship(featureTable)
);
}
/**
* Create a style relationship for the feature table
* @param {module:features/user/featureTable|String} featureTable feature table
* @return {any}
*/
createStyleRelationship(featureTable: string | FeatureTable): ExtendedRelation {
return this._createStyleRelationship(
this.getMappingTableName(FeatureStyleExtension.TABLE_MAPPING_STYLE, featureTable),
this.getFeatureTableName(featureTable),
this.getFeatureTableName(featureTable),
StyleTable.TABLE_NAME,
);
}
/**
* Determine if a style relationship exists for the feature table
* @param {module:features/user/featureTable|String} featureTable feature table
* @returns {boolean}
*/
hasStyleRelationship(featureTable: string | FeatureTable): boolean {
return this._hasStyleRelationship(
this.getMappingTableName(FeatureStyleExtension.TABLE_MAPPING_STYLE, featureTable),
this.getFeatureTableName(featureTable),
StyleTable.TABLE_NAME,
);
}
/**
* Create a feature table style relationship
* @param {module:features/user/featureTable|String} featureTable feature table
* @return {ExtendedRelation}
*/
createTableStyleRelationship(featureTable: string | FeatureTable): ExtendedRelation {
return this._createStyleRelationship(
this.getMappingTableName(FeatureStyleExtension.TABLE_MAPPING_TABLE_STYLE, featureTable),
this.getFeatureTableName(featureTable),
ContentsIdDao.TABLE_NAME,
StyleTable.TABLE_NAME,
);
}
/**
* Determine if a feature table style relationship exists
* @param {module:features/user/featureTable|String} featureTable feature table
* @returns {boolean} true if relationship exists
*/
hasTableStyleRelationship(featureTable: string | FeatureTable): boolean {
return this._hasStyleRelationship(
this.getMappingTableName(FeatureStyleExtension.TABLE_MAPPING_TABLE_STYLE, featureTable),
ContentsIdDao.TABLE_NAME,
StyleTable.TABLE_NAME,
);
}
/**
* Create an icon relationship for the feature table
* @param {module:features/user/featureTable|String} featureTable feature table
* @return {ExtendedRelation}
*/
createIconRelationship(featureTable: string | FeatureTable): ExtendedRelation {
return this._createStyleRelationship(
this.getMappingTableName(FeatureStyleExtension.TABLE_MAPPING_ICON, featureTable),
this.getFeatureTableName(featureTable),
this.getFeatureTableName(featureTable),
IconTable.TABLE_NAME,
);
}
/**
* Determine if an icon relationship exists for the feature table
* @param {module:features/user/featureTable|String} featureTable feature table
* @returns {boolean} true if relationship exists
*/
hasIconRelationship(featureTable: string | FeatureTable): boolean {
return this._hasStyleRelationship(
this.getMappingTableName(FeatureStyleExtension.TABLE_MAPPING_ICON, featureTable),
this.getFeatureTableName(featureTable),
IconTable.TABLE_NAME,
);
}
/**
* Create a feature table icon relationship
* @param {module:features/user/featureTable|String} featureTable feature table
* @return {ExtendedRelation}
*/
createTableIconRelationship(featureTable: string | FeatureTable): ExtendedRelation {
return this._createStyleRelationship(
this.getMappingTableName(FeatureStyleExtension.TABLE_MAPPING_TABLE_ICON, featureTable),
this.getFeatureTableName(featureTable),
ContentsIdDao.TABLE_NAME,
IconTable.TABLE_NAME,
);
}
/**
* Determine if a feature table icon relationship exists
* @param {module:features/user/featureTable|String} featureTable feature table
* @returns {Boolean} true if relationship exists
*/
hasTableIconRelationship(featureTable: string | FeatureTable): boolean {
return this._hasStyleRelationship(
this.getMappingTableName(FeatureStyleExtension.TABLE_MAPPING_TABLE_ICON, featureTable),
ContentsIdDao.TABLE_NAME,
IconTable.TABLE_NAME,
);
}
/**
* Get the mapping table name
* @param tablePrefix table name prefix
* @param {module:features/user/featureTable|String} featureTable feature table name
* @returns {String} mapping table name
*/
getMappingTableName(tablePrefix: string, featureTable: string | FeatureTable): string {
return tablePrefix + this.getFeatureTableName(featureTable);
}
/**
* Check if the style extension relationship between a feature table and
* style extension table exists
* @param {String} mappingTableName mapping table name
* @param {String} baseTable base table name
* @param {String} relatedTable related table name
* @returns {boolean} true if relationship exists
*/
_hasStyleRelationship(mappingTableName: string, baseTable: string, relatedTable: string): boolean {
return this.relatedTablesExtension.hasRelations(baseTable, relatedTable, mappingTableName);
}
/**
* Create a style extension relationship between a feature table and style
* extension table
* @param {String} mappingTableName mapping table name
* @param {String} featureTable feature table
* @param {String} baseTable base table name
* @param {String} relatedTable related table name
* @return {ExtendedRelation}
* @private
*/
_createStyleRelationship(
mappingTableName: string,
featureTable: string,
baseTable: string,
relatedTable: string,
): ExtendedRelation {
if (!this._hasStyleRelationship(mappingTableName, baseTable, relatedTable)) {
// Create the extension
this.getOrCreateExtension(featureTable);
if (baseTable === ContentsIdDao.TABLE_NAME && !this.contentsIdExtension.has()) {
this.contentsIdExtension.getOrCreateExtension();
}
return this._handleCreateStyleRelationship(mappingTableName, baseTable, relatedTable);
} else {
const relationships = this.geoPackage.extendedRelationDao.getRelations(baseTable, relatedTable, mappingTableName);
// TODO this isn't quite right
return relationships[0];
}
}
/**
* Private function to aid in creation of the a style extension relationship between a feature table and style extension table
* @param {String} mappingTableName
* @param {String} baseTable
* @param {String} relatedTable
* @return {ExtendedRelation}
* @private
*/
_handleCreateStyleRelationship(
mappingTableName: string,
baseTable: string,
relatedTable: string,
): ExtendedRelation {
if (relatedTable === StyleTable.TABLE_NAME) {
return this.relatedTablesExtension.addAttributesRelationship(
this.geoPackage.relatedTablesExtension
.getRelationshipBuilder()
.setBaseTableName(baseTable)
.setUserMappingTable(StyleMappingTable.create(mappingTableName))
.setRelatedTable(StyleTable.create()),
);
} else {
return this.relatedTablesExtension.addMediaRelationship(
this.geoPackage.relatedTablesExtension
.getRelationshipBuilder()
.setBaseTableName(baseTable)
.setUserMappingTable(StyleMappingTable.create(mappingTableName))
.setRelatedTable(IconTable.create()),
);
}
}
/**
* Delete the style and icon table and row relationships for all feature
* tables
*/
deleteAllRelationships(): {
styleRelationships: number;
tableStyleRelationships: number;
iconRelationship: number;
tableIconRelationship: number;
} {
const removed = {
styleRelationships: 0,
tableStyleRelationships: 0,
iconRelationship: 0,
tableIconRelationship: 0,
};
const tables = this.getTables();
for (let i = 0; i < tables.length; i++) {
const {
styleRelationships,
tableStyleRelationships,
iconRelationship,
tableIconRelationship,
} = this.deleteRelationships(tables[i]);
removed.styleRelationships += styleRelationships;
removed.tableStyleRelationships += tableStyleRelationships;
removed.iconRelationship += iconRelationship;
removed.tableIconRelationship += tableIconRelationship;
}
return removed;
}
/**
* Delete the style and icon table and row relationships for the feature
* table
* @param {module:features/user/featureTable|String} featureTable feature table
*/
deleteRelationships(
featureTable: string | FeatureTable,
): {
styleRelationships: number;
tableStyleRelationships: number;
iconRelationship: number;
tableIconRelationship: number;
} {
return {
styleRelationships: this.deleteStyleRelationship(featureTable),
tableStyleRelationships: this.deleteTableStyleRelationship(featureTable),
iconRelationship: this.deleteIconRelationship(featureTable),
tableIconRelationship: this.deleteTableIconRelationship(featureTable),
};
}
/**
* Delete a style relationship for the feature table
* @param {module:features/user/featureTable|String} featureTable feature table
*/
deleteStyleRelationship(featureTable: string | FeatureTable): number {
return this._deleteStyleRelationship(
this.getMappingTableName(FeatureStyleExtension.TABLE_MAPPING_STYLE, featureTable),
featureTable,
);
}
/**
* Delete a table style relationship for the feature table
* @param {module:features/user/featureTable|String} featureTable feature table
*/
deleteTableStyleRelationship(featureTable: string | FeatureTable): number {
return this._deleteStyleRelationship(
this.getMappingTableName(FeatureStyleExtension.TABLE_MAPPING_TABLE_STYLE, featureTable),
featureTable,
);
}
/**
* Delete a icon relationship for the feature table
* @param {module:features/user/featureTable|String} featureTable feature table
*/
deleteIconRelationship(featureTable: string | FeatureTable): number {
return this._deleteStyleRelationship(
this.getMappingTableName(FeatureStyleExtension.TABLE_MAPPING_ICON, featureTable),
featureTable,
);
}
/**
* Delete a table icon relationship for the feature table
* @param {module:features/user/featureTable|String} featureTable feature table
*/
deleteTableIconRelationship(featureTable: string | FeatureTable): number {
return this._deleteStyleRelationship(
this.getMappingTableName(FeatureStyleExtension.TABLE_MAPPING_TABLE_ICON, featureTable),
featureTable,
);
}
/**
* Delete a style extension feature table relationship and the mapping table
* @param {String} mappingTableName
* @param {module:features/user/featureTable|String} featureTable feature table
* @private
*/
_deleteStyleRelationship(mappingTableName: string, featureTable: string | FeatureTable): number {
let removed = 0;
const relationships = this.geoPackage.extendedRelationDao.queryByMappingTableName(mappingTableName);
for (let i = 0; i < relationships.length; i++) {
removed += this.relatedTablesExtension.removeRelationship(relationships[i]);
}
if (!this.hasRelationship(featureTable)) {
if (this.extensionsDao.isTableExists()) {
this.extensionsDao.deleteByExtensionAndTableName(
FeatureStyleExtension.EXTENSION_NAME,
this.getFeatureTableName(featureTable),
);
}
}
return removed;
}
/**
* Get a Style Mapping DAO
* @param {module:features/user/featureTable|String} featureTable feature table
* @return {module:extension/style.StyleMappingDao} style mapping DAO
*/
getStyleMappingDao(featureTable: string | FeatureTable): StyleMappingDao {
return this._getMappingDao(FeatureStyleExtension.TABLE_MAPPING_STYLE, featureTable);
}
/**
* Get a Table Style Mapping DAO
* @param {module:features/user/featureTable|String} featureTable feature table
* @return {module:extension/style.StyleMappingDao} table style mapping DAO
*/
getTableStyleMappingDao(featureTable: string | FeatureTable): StyleMappingDao {
return this._getMappingDao(FeatureStyleExtension.TABLE_MAPPING_TABLE_STYLE, featureTable);
}
/**
* Get a Icon Mapping DAO
* @param {module:features/user/featureTable|String} featureTable feature table
* @return {module:extension/style.StyleMappingDao} icon mapping DAO
*/
getIconMappingDao(featureTable: FeatureTable | string): StyleMappingDao {
return this._getMappingDao(FeatureStyleExtension.TABLE_MAPPING_ICON, featureTable);
}
/**
* Get a Table Icon Mapping DAO
* @param {module:features/user/featureTable|String} featureTable feature table
* @return {module:extension/style.StyleMappingDao} table icon mapping DAO
*/
getTableIconMappingDao(featureTable: string | FeatureTable): StyleMappingDao {
return this._getMappingDao(FeatureStyleExtension.TABLE_MAPPING_TABLE_ICON, featureTable);
}
/**
* Get a Style Mapping DAO from a table name
* @param {String} tablePrefix table name prefix
* @param {module:features/user/featureTable|String} featureTable feature table
* @return {module:extension/style.StyleMappingDao} style mapping dao
* @private
*/
_getMappingDao(tablePrefix: string, featureTable: string | FeatureTable): StyleMappingDao {
const featureTableName = this.getFeatureTableName(featureTable);
const tableName = tablePrefix + featureTableName;
let dao = null;
if (this.geoPackage.isTable(tableName)) {
dao = new StyleMappingDao(
this.relatedTablesExtension.getUserDao(tableName),
this.geoPackage,
);
}
return dao;
}
/**
* Get a style DAO
* @return {module:extension/style.StyleDao} style DAO
*/
getStyleDao(): StyleDao {
let styleDao = null;
if (this.geoPackage.isTable(StyleTable.TABLE_NAME)) {
const contents = this.geoPackage.contentsDao.queryForId(StyleTable.TABLE_NAME);
if (contents) {
const reader = new StyleTableReader(contents.table_name);
const table = reader.readTable(this.geoPackage.connection) as StyleTable;
table.setContents(contents);
styleDao = new StyleDao(this.geoPackage, table);
}
}
return styleDao;
}
/**
* Get a icon DAO
* @return {module:extension/style.IconDao}
*/
getIconDao(): IconDao {
let iconDao = null;
if (this.geoPackage.isTable(IconTable.TABLE_NAME)) {
const reader = new UserCustomTableReader(IconTable.TABLE_NAME);
const userTable = reader.readTable(this.geoPackage.database);
const table = new IconTable(userTable.getTableName(), userTable.getUserColumns().getColumns(), IconTable.requiredColumns());
table.setContents(this.geoPackage.contentsDao.queryForId(IconTable.TABLE_NAME));
iconDao = new IconDao(this.geoPackage, table);
}
return iconDao;
}
/**
* Get the feature table default feature styles
* @param {module:features/user/featureTable|String} featureTable feature table
* @return {module:extension/style.FeatureStyles} table feature styles or null
*/
getTableFeatureStyles(featureTable: string | FeatureTable): FeatureStyles {
let featureStyles = null;
const id = this.contentsIdExtension.getIdByTableName(this.getFeatureTableName(featureTable));
if (id !== null) {
const styles = this.getTableStyles(featureTable);
const icons = this.getTableIcons(featureTable);
if (styles !== null || icons !== null) {
featureStyles = new FeatureStyles(styles, icons);
}
}
return featureStyles;
}
/**
* Get the default style of the feature table
* @param {module:features/user/featureTable|String} featureTable feature table
* @return {module:extension/style.StyleRow} style row
*/
getTableStyleDefault(featureTable: string | FeatureTable): StyleRow {
return this.getTableStyle(featureTable, null);
}
/**
* Get the style of the feature table and geometry type
* @param {module:features/user/featureTable|String} featureTable feature table
* @param {String} geometryType geometry type
* @return {module:extension/style.StyleRow} style row
*/
getTableStyle(featureTable: string | FeatureTable, geometryType: string): StyleRow {
let style = null;
const styles = this.getTableStyles(featureTable);
if (styles !== null) {
if (geometryType === null) {
style = styles.getDefault();
} else {
style = styles.getStyle(geometryType);
}
}
return style;
}
/**
* Get the feature table default styles
* @param {module:features/user/featureTable|String} featureTable feature table
* @return {module:extension/style.Styles} table styles or null
*/
getTableStyles(featureTable: string | FeatureTable): Styles {
let styles = null;
const id = this.contentsIdExtension.getIdByTableName(this.getFeatureTableName(featureTable));
if (id !== null) {
styles = this.getStyles(id, this.getTableStyleMappingDao(featureTable));
}
return styles;
}
/**
* Get the default icon of the feature table
* @param {module:features/user/featureTable|String} featureTable feature table
* @return {module:extension/style.IconRow} icon row
*/
getTableIconDefault(featureTable: string | FeatureTable): IconRow {
return this.getTableIcon(featureTable, null);
}
/**
* Get the icon of the feature table and geometry type
* @param {module:features/user/featureTable|String} featureTable feature table
* @param {String} geometryType geometry type
* @return {module:extension/style.IconRow} icon row
*/
getTableIcon(featureTable: string | FeatureTable, geometryType: string): IconRow {
let icon = null;
const icons = this.getTableIcons(featureTable);
if (icons !== null) {
if (geometryType === null) {
icon = icons.getDefault();
} else {
icon = icons.getIcon(geometryType);
}
}
return icon;
}
/**
* Get the feature table default icons
* @param {module:features/user/featureTable|String} featureTable feature table
* @return {module:extension/style.Icons} table icons or null
*/
getTableIcons(featureTable: string | FeatureTable): Icons {
let icons = null;
const id = this.contentsIdExtension.getIdByTableName(this.getFeatureTableName(featureTable));
if (id !== null) {
icons = this.getIcons(id, this.getTableIconMappingDao(featureTable));
}
return icons;
}
/**
* Gets Icons for featureId and mappingDao
* @param {Number} featureId
* @param mappingDao
* @returns {module:extension/style.Icons}
* @private
*/
getIcons(featureId: number, mappingDao: StyleMappingDao): Icons {
let icons = new Icons();
if (mappingDao !== null) {
const iconDao = this.getIconDao();
const styleMappingRows = mappingDao.queryByBaseId(featureId);
for (let i = 0; i < styleMappingRows.length; i++) {
const styleMappingRow = mappingDao.createObject(styleMappingRows[i]) as StyleMappingRow;
const iconRow = iconDao.queryForId(styleMappingRow.relatedId) as IconRow;
if (styleMappingRow.getGeometryTypeName() === null) {
icons.setDefault(iconRow);
} else {
icons.setIcon(iconRow, styleMappingRow.getGeometryTypeName());
}
}
}
if (icons.isEmpty()) {
icons = null;
}
return icons;
}
/**
* Gets Styles for featureId and mappingDao
* @param {Number} featureId
* @param {module:extension/style.StyleMappingDao} mappingDao
* @returns {module:extension/style.Styles}
*/
getStyles(featureId: number, mappingDao: StyleMappingDao): Styles {
let styles = new Styles();
if (mappingDao !== null) {
const styleDao = this.getStyleDao();
const styleMappingRows = mappingDao.queryByBaseId(featureId);
for (let i = 0; i < styleMappingRows.length; i++) {
const styleMappingRow = mappingDao.createObject(styleMappingRows[i]) as StyleMappingRow;
const styleRow = styleDao.queryForId(styleMappingRow.relatedId) as StyleRow;
if (styleMappingRow.getGeometryTypeName() === null) {
styles.setDefault(styleRow);
} else {
styles.setStyle(styleRow, styleMappingRow.getGeometryTypeName());
}
}
}
if (styles.isEmpty()) {
styles = null;
}
return styles;
}
/**
* Get the feature styles for the feature row
* @param {module:features/user/featureRow} featureRow feature row
* @return {module:extension/style.FeatureStyles} feature styles or null
*/
getFeatureStylesForFeatureRow(featureRow: FeatureRow): FeatureStyles {
return this.getFeatureStyles(featureRow.featureTable, featureRow.id);
}
/**
* Get the feature styles for the feature row
* @param {module:features/user/featureTable|String} featureTable feature table
* @param {Number} featureId feature id
* @return {module:extension/style.FeatureStyles} feature styles or null
*/
getFeatureStyles(featureTable: string | FeatureTable, featureId: number): FeatureStyles {
const styles = this.getStyles(featureId, this.getStyleMappingDao(featureTable));
const icons = this.getIcons(featureId, this.getIconMappingDao(featureTable));
let featureStyles = null;
if (styles !== null || icons !== null) {
featureStyles = new FeatureStyles(styles, icons);
}
return featureStyles;
}
/**
* Get the styles for the feature row
* @param {module:features/user/featureRow} featureRow feature row
* @return {module:extension/style.Styles} styles or null
*/
getStylesForFeatureRow(featureRow: FeatureRow): Styles {
return this.getStyles(featureRow.id, this.getStyleMappingDao(featureRow.featureTable.getTableName()));
}
/**
* Get the styles for the feature id
* @param {String} tableName table name
* @param {Number} featureId feature id
* @return {module:extension/style.Styles} styles or null
*/
getStylesForFeatureId(tableName: string, featureId: number): Styles {
return this.getStyles(featureId, this.getStyleMappingDao(tableName));
}
/**
* Get the icons for the feature row
* @param {module:features/user/featureRow} featureRow feature row
* @return {module:extension/style.Icons} icons or null
*/
getIconsForFeatureRow(featureRow: FeatureRow): Icons {
return this.getIcons(featureRow.id, this.getIconMappingDao(featureRow.featureTable.getTableName()));
}
/**
* Get the icons for the feature id
* @param {String} tableName table name
* @param {Number} featureId feature id
* @return {module:extension/style.Icons} icons or null
*/
getIconsForFeatureId(tableName: string, featureId: number): Icons {
return this.getIcons(featureId, this.getIconMappingDao(tableName));
}
/**
* Get the feature style (style and icon) of the feature row, searching in
* order: feature geometry type style or icon, feature default style or
* icon, table geometry type style or icon, table default style or icon
* @param {module:features/user/featureRow} featureRow feature row
* @return {module:extension/style.FeatureStyle} feature style
*/
getFeatureStyleForFeatureRow(featureRow: FeatureRow): FeatureStyle {
return new FeatureStyle(
this.getStyle(featureRow.featureTable.getTableName(), featureRow.id, featureRow.geometryType, true),
this.getIcon(featureRow.featureTable.getTableName(), featureRow.id, featureRow.geometryType, true),
);
}
/**
* Get the feature style (style and icon) of the feature, searching in
* order: feature geometry type style or icon, feature default style or
* icon, table geometry type style or icon, table default style or icon
* @param {module:features/user/featureRow} featureRow feature row
* @return {module:extension/style.FeatureStyle} feature style
*/
getFeatureStyleDefault(featureRow: FeatureRow): FeatureStyle {
return new FeatureStyle(
this.getStyle(featureRow.featureTable.getTableName(), featureRow.id, null, true),
this.getIcon(featureRow.featureTable.getTableName(), featureRow.id, null, true),
);
}
/**
* Get the icon of the feature, searching in order: feature geometry type
* icon, feature default icon, when tableIcon enabled continue searching:
* table geometry type icon, table default icon
* @param {module:features/user/featureTable|String} featureTable
* @param {Number} featureId
* @param {String} geometryType
* @param {Boolean} tableIcon
* @returns {module:extension/style.IconRow}
* @private
*/
getIcon(featureTable: string | FeatureTable, featureId: number, geometryType: string, tableIcon: boolean): IconRow {
let iconRow = null;
const icons = this.getIcons(featureId, this.getIconMappingDao(featureTable));
if (icons !== null) {
iconRow = icons.getIcon(geometryType);
}
if (iconRow === null && tableIcon) {
iconRow = this.getTableIcon(featureTable, geometryType);
}
return iconRow;
}
/**
* Get the style of the feature, searching in order: feature geometry type
* style, feature default style, when tableStyle enabled continue searching:
* table geometry type style, table default style
* @param {module:features/user/featureTable|String} featureTable
* @param {Number} featureId
* @param {String} geometryType
* @param {Boolean} tableStyle
* @returns {module:extension/style.StyleRow}
* @private
*/
getStyle(
featureTable: string | FeatureTable,
featureId: number,
geometryType: string,
tableStyle: boolean,
): StyleRow {
let styleRow = null;
const styles = this.getStyles(featureId, this.getStyleMappingDao(featureTable));
if (styles !== null) {
styleRow = styles.getStyle(geometryType);
}
if (styleRow === null && tableStyle) {
styleRow = this.getTableStyle(featureTable, geometryType);
}
return styleRow;
}
/**
* Set the feature table default feature styles
* @param {module:features/user/featureTable~FeatureTable|String} featureTable feature table
* @param {module:extension/style.FeatureStyles} featureStyles feature styles
* @return {any}
*/
setTableFeatureStyles(
featureTable: string | FeatureTable,
featureStyles?: FeatureStyles,
): {
tableStyles: {
styleDefault: number;
styles: number[];
};
tableIcons: {
iconDefault: number;
icons: number[];
};
deleted?: {
styles: number;
icons: number;
};
} {
if (featureStyles !== null) {
const tableStyles = this.setTableStyles(featureTable, featureStyles.styles);
const tableIcons = this.setTableIcons(featureTable, featureStyles.icons);
return {
tableStyles: tableStyles,
tableIcons: tableIcons,
};
} else {
return {
deleted: this.deleteTableFeatureStyles(featureTable),
tableStyles: undefined,
tableIcons: undefined,
};
}
}
/**
* Set the feature table default styles
* @param {module:features/user/featureTable~FeatureTable|String} featureTable feature table
* @param {module:extension/style.Styles} styles default styles
* @return {any}
*/
setTableStyles(
featureTable: string | FeatureTable,
styles?: Styles,
): { styleDefault: number; styles: number[]; deleted: number } {
const deleted = this.deleteTableStyles(featureTable);
if (styles !== null) {
let styleIdList = [];
let styleDefault = undefined;
if (styles.getDefault() !== null) {
styleDefault = this.setTableStyleDefault(featureTable, styles.getDefault());
}
const keys = Object.keys(styles.styles);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const value = styles.styles[key];
styleIdList.push(this.setTableStyle(featureTable, key, value));
}
return {
styleDefault,
styles: styleIdList,
deleted,
};
}
}
/**
* Set the feature table style default
* @param {module:features/user/featureTable~FeatureTable|String} featureTable feature table
* @param {module:extension/style.StyleRow} style style row
* @return {number}
*/
setTableStyleDefault(featureTable: string | FeatureTable, style: StyleRow): number {
return this.setTableStyle(featureTable, null, style);
}
/**
* Set the feature table style for the geometry type
* @param {module:features/user/featureTable~FeatureTable|String} featureTable feature table
* @param {String} geometryType geometry type
* @param {module:extension/style.StyleRow} style style row
* @return {number}
*/
setTableStyle(featureTable: string | FeatureTable, geometryType: string, style?: StyleRow): number {
this.deleteTableStyle(featureTable, geometryType);
if (style !== null) {
this.createTableStyleRelationship(featureTable);
const featureContentsId = this.contentsIdExtension.getOrCreateIdByTableName(
this.getFeatureTableName(featureTable),
);
const styleId = this.getOrInsertStyle(style);
const mappingDao = this.getTableStyleMappingDao(featureTable);
return this.insertStyleMapping(mappingDao, featureContentsId.id, styleId, geometryType);
}
}
/**
* Set the feature table default icons
* @param {module:features/user/featureTable~FeatureTable|String} featureTable feature table
* @param {module:extension/style.Icons} icons default icons
* @return {any}
*/
setTableIcons(
featureTable: string | FeatureTable,
icons?: Icons,
): { iconDefault: number; icons: number[]; deleted: number } {
const deleted = this.deleteTableIcons(featureTable);
if (icons !== null) {
let iconDefault = undefined;
let iconIdList= [];
if (icons.getDefault() !== null) {
iconDefault = this.setTableIconDefault(featureTable, icons.getDefault());
}
const keys = Object.keys(icons.icons);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const value = icons.icons[key];
iconIdList.push(this.setTableIcon(featureTable, key, value));
}
return {
iconDefault,
icons: iconIdList,
deleted,
};
}
}
/**
* Set the feature table icon default
* @param {module:features/user/featureTable~FeatureTable|String} featureTable feature table
* @param {module:extension/style.IconRow} icon icon row
* @return {number}
*/
setTableIconDefault(featureTable: string | FeatureTable, icon?: IconRow): number {
return this.setTableIcon(featureTable, null, icon);
}
/**
* Set the feature table icon for the geometry type
* @param {module:features/user/featureTable~FeatureTable|String} featureTable feature table
* @param {String} geometryType geometry type
* @param {module:extension/style.IconRow} icon icon row
* @return {number}
*/
setTableIcon(featureTable: string | FeatureTable, geometryType: string, icon?: IconRow): number {
this.deleteTableIcon(featureTable, geometryType);
if (icon !== null) {
this.createTableIconRelationship(featureTable);
const featureContentsId = this.contentsIdExtension.getOrCreateIdByTableName(
this.getFeatureTableName(featureTable),
);
const iconId = this.getOrInsertIcon(icon);
const mappingDao = this.getTableIconMappingDao(featureTable);
return this.insertStyleMapping(mappingDao, featureContentsId.id, iconId, geometryType);
}
}
/**
* Set the feature styles for the feature row
* @param {module:features/user/featureRow} featureRow feature row
* @param {module:extension/style.FeatureStyles} featureStyles feature styles
* @return {any}
*/
setFeatureStylesForFeatureRow(
featureRow: FeatureRow,
featureStyles: FeatureStyles,
): {
styles: { styleDefault: number; styles: number[] };
icons: {
iconDefault: number;
icons: number[];
deleted?: {
style: number;
icon: number;
};
};
} {
return this.setFeatureStyles(featureRow.featureTable.getTableName(), featureRow.id, featureStyles);
}
/**
* Set the feature styles for the feature table and feature id
* @param {module:features/user/featureTable~FeatureTable|String} featureTable feature table
* @param {Number} featureId feature id
* @param {module:extension/style.FeatureStyles} featureStyles feature styles
* @return {any}
*/
setFeatureStyles(
featureTable: string | FeatureTable,
featureId: number,
featureStyles?: FeatureStyles,
): {
styles: { styleDefault: number; styles: number[] };
icons: { iconDefault: number; icons: number[] };
deleted?: {
deletedStyles: number;
deletedIcons: number;
};
} {
if (featureStyles !== null) {
const styles = this.setStyles(featureTable, featureId, featureStyles.styles);
const icons = this.setIcons(featureTable, featureId, featureStyles.icons);
return {
styles,
icons,
};
} else {
const deletedStyles = this.deleteStyles(featureTable); //, featureId);
const deletedIcons = this.deleteIcons(featureTable); //, featureId);
return {
styles: undefined,
icons: undefined,
deleted: {
deletedStyles,
deletedIcons,
},
};
}
}
/**
* Set the feature style (style and icon) of the feature row
* @param {module:features/user/featureRow} featureRow feature row
* @param {module:extension/style.FeatureStyle} featureStyle feature style
* @return {any}
*/
setFeatureStyleForFeatureRow(
featureRow: FeatureRow,
featureStyle: FeatureStyle,
): {
style: number;
icon: number;
deleted?: {
style: number;
icon: number;
};
} {
return this.setFeatureStyleForFeatureRowAndGeometryType(featureRow, featureRow.geometryType, featureStyle);
}
/**
* Set the feature style (style and icon) of the feature row for the
* specified geometry type
* @param {module:features/user/featureRow} featureRow feature row
* @param {String} geometryType geometry type
* @param {module:extension/style.FeatureStyle} featureStyle feature style
* @return {any}
*/
setFeatureStyleForFeatureRowAndGeometryType(
featureRow: FeatureRow,
geometryType: string,
featureStyle: FeatureStyle,
): {
style: number;
icon: number;
deleted?: {
style: number;
icon: number;
};
} {
return this.setFeatureStyle(featureRow.featureTable.getTableName(), featureRow.id, geometryType, featureStyle);
}
/**
* Set the feature style default (style and icon) of the feature row
* @param {module:features/user/featureRow} featureRow feature row
* @param {module:extension/style.FeatureStyle} featureStyle feature style
* @return {any}
*/
setFeatureStyleDefaultForFeatureRow(
featureRow: FeatureRow,
featureStyle: FeatureStyle,
): {
style: number;
icon: number;
deleted?: {
style: number;
icon: number;
};
} {
return this.setFeatureStyle(featureRow.featureTable.getTableName(), featureRow.id, null, featureStyle);
}
/**
* Set the feature style (style and icon) of the feature
* @param {module:features/user/featureTable~FeatureTable|String} featureTable feature table
* @param {Number} featureId feature id
* @param {String} geometryType geometry type
* @param {module:extension/style.FeatureStyle} featureStyle feature style
* @return {any}
*/
setFeatureStyle(
featureTable: string | FeatureTable,
featureId: number,
geometryType: string,
featureStyle?: FeatureStyle,
): {
style: number;
icon: number;
deleted?: {
style: number;
icon: number;
};
} {
if (featureStyle !== null) {
return {
style: this.setStyle(featureTable, featureId, geometryType, featureStyle.style),
icon: this.setIcon(featureTable, featureId, geometryType, featureStyle.icon),
}
} else {
return {
style: undefined,
icon: undefined,
deleted: {
style: this.deleteStyle(featureTable, featureId, geometryType),
icon: this.deleteIcon(featureTable, featureId, geometryType),
},
};
}
}
/**
* Set the feature style (style and icon) of the feature
* @param {module:features/user/featureTable~FeatureTable|String} featureTable feature table
* @param {Number} featureId feature id
* @param {module:extension/style.FeatureStyle} featureStyle feature style
* @return {object}
*/
setFeatureStyleDefault(
featureTable: string | FeatureTable,
featureId: number,
featureStyle: FeatureStyle,
): {
style: number;
icon: number;
deleted?: {
style: number;
icon: number;
};
} {
return this.setFeatureStyle(featureTable, featureId, null, featureStyle);
}
/**
* Set the styles for the feature row
* @param {module:features/user/featureRow} featureRow feature row
* @param {module:extension/style.Styles} styles styles
* @return {Promise}
*/
setStylesForFeatureRow(
featureRow: FeatureRow,
styles: Styles,
): { styleDefault: number; styles: number[]; deleted: number } {
return this.setStyles(featureRow.featureTable.getTableName(), featureRow.id, styles);
}
/**
* Set the styles for the feature table and feature id
* @param {module:features/user/featureTable~FeatureTable|String} featureTable feature table
* @param {Number} featureId feature id
* @param {module:extension/style.Styles} styles styles
* @return {Promise}
*/
setStyles(
featureTable: string | FeatureTable,
featureId: number,
styles?: Styles,
): { styleDefault: number; styles: number[]; deleted: number } {
const deleted = this.deleteStylesForFeatureId(featureTable, featureId);
if (styles !== null) {
let styleIds = [];
let styleDefault = undefined;
if (styles.getDefault() !== null) {
styleDefault = this.setStyleDefault(featureTable, featureId, styles.getDefault());
}
const keys = Object.keys(styles.styles);
for (let i = 0; i < keys.length; i++) {
styleIds.push(this.setStyle(featureTable, featureId, keys[i], styles.styles[keys[i]]));
}
return {
styleDefault,
styles: styleIds,
deleted,
};
} else {
return {
styleDefault: undefined,
styles: undefined,
deleted,
};
}
}
/**
* Set the style of the feature row
* @param {module:features/user/featureRow} featureRow feature row
* @param {module:extension/style.StyleRow} style style row
* @return {Promise}
*/
setStyleForFeatureRow(featureRow: FeatureRow, style: StyleRow): number {
return this.setStyleForFeatureRowAndGeometryType(featureRow, featureRow.geometryType, style);
}
/**
* Set the style of the feature row for the specified geometry type
* @param {module:features/user/featureRow} featureRow feature row
* @param {String} geometryType geometry type
* @param {module:extension/style.StyleRow} style style row
* @return {Promise}
*/
setStyleForFeatureRowAndGeometryType(
featureRow: FeatureRow,
geometryType: string,
style: StyleRow,
): number {
return this.setStyle(featureRow.featureTable.getTableName(), featureRow.id, geometryType, style);
}
/**
* Set the default style of the feature row
* @param {module:features/user/featureRow} featureRow feature row
* @param {module:extension/style.StyleRow} style style row
* @return {Promise}
*/
setStyleDefaultForFeatureRow(featureRow: FeatureRow, style: StyleRow): number {
return this.setStyle(featureRow.featureTable.getTableName(), featureRow.id, null, style);
}
/**
* Set the style of the feature
* @param {module:features/user/featureTable~FeatureTable|String} featureTable feature table
* @param {Number} featureId feature id
* @param {String} geometryType geometry type
* @param {module:extension/style.StyleRow} style style row
* @return {number}
*/
setStyle(
featureTable: string | FeatureTable,
featureId: number,
geometryType: string,
style: StyleRow,
): number {
this.deleteStyle(featureTable, featureId, geometryType);
if (style !== null) {
this.createStyleRelationship(featureTable);
const styleId = this.getOrInsertStyle(style);
const mappingDao = this.getStyleMappingDao(featureTable);
return this.insertStyleMapping(mappingDao, featureId, styleId, geometryType);
}
}
/**
* Set the default style of the feature
* @param {module:features/user/featureTable~FeatureTable|String} featureTable feature table
* @param {Number} featureId feature id
* @param {module:extension/style.StyleRow} style style row
* @return {number}
*/
setStyleDefault(featureTable: string | FeatureTable, featureId: number, style: StyleRow): number {
return this.setStyle(featureTable, featureId, null, style);
}
/**
* Set the icons for the feature row
* @param {module:features/user/featureRow} featureRow feature row
* @param {module:extension/style.Icons} icons icons
* @return {Promise}
*/
setIconsForFeatureRow(
featureRow: FeatureRow,
icons: Icons,
): { iconDefault: number; icons: number[]; deleted: number } {
return this.setIcons(featureRow.featureTable.getTableName(), featureRow.id, icons);
}
/**
* Set the icons for the feature table and feature id
* @param {module:features/user/featureTable~FeatureTable|String} featureTable feature table
* @param {Number} featureId feature id
* @param {module:extension/style.Icons} icons icons
* @return {Promise}
*/
setIcons(
featureTable: string | FeatureTable,
featureId: number,
icons?: Icons,
): { iconDefault: number; icons: number[]; deleted: number } {
const deleted = this.deleteIconsForFeatureId(featureTable, featureId);
if (icons !== null) {
if (icons.getDefault() !== null) {
this.setIconDefault(featureTable, featureId, icons.getDefault());
}
const keys = Object.keys(icons.icons);
for (let i = 0; i < keys.length; i++) {
this.setIcon(featureTable, featureId, keys[i], icons.icons[keys[i]]);
}
return {
iconDefault: undefined,
icons: undefined,
deleted,
};
} else {
return {
iconDefault: undefined,
icons: undefined,
deleted,
};
}
}
/**
* Set the icon of the feature row
* @param {module:features/user/featureRow} featureRow feature row
* @param {module:extension/style.IconRow} icon icon row
* @return {number}
*/
setIconForFeatureRow(featureRow: FeatureRow, icon: IconRow): number {
return this.setIconForFeatureRowAndGeometryType(featureRow, featureRow.geometryType, icon);
}
/**
* Set the icon of the feature row for the specified geometry type
* @param {module:features/user/featureRow} featureRow feature row
* @param {String} geometryType geometry type
* @param {module:extension/style.IconRow} icon icon row
* @return {number}
*/
setIconForFeatureRowAndGeometryType(
featureRow: FeatureRow,
geometryType: string,
icon: IconRow,
): number {
return this.setIcon(featureRow.featureTable.getTableName(), featureRow.id, geometryType, icon);
}
/**
* Set the default icon of the feature row
* @param {module:features/user/featureRow} featureRow feature row
* @param {module:extension/style.IconRow} icon icon row
* @return {number}
*/
setIconDefaultForFeatureRow(featureRow: FeatureRow, icon: IconRow): number {
return this.setIcon(featureRow.featureTable.getTableName(), featureRow.id, null, icon);
}
/**
* Get the icon of the feature, searching in order: feature geometry type
* icon, feature default icon, table geometry type icon, table default icon
* @param {module:features/user/featureTable~FeatureTable|String} featureTable feature table
* @param {Number} featureId feature id
* @param {String} geometryType geometry type
* @param {module:extension/style.IconRow} icon icon row
* @return {number}
*/
setIcon(
featureTable: string | FeatureTable,
featureId: number,
geometryType: string,
icon?: IconRow,
): number {
this.deleteIcon(featureTable, featureId, geometryType);
if (icon !== null) {
this.createIconRelationship(featureTable);
const iconId = this.getOrInsertIcon(icon);
const mappingDao = this.getIconMappingDao(featureTable);
return this.insertStyleMapping(mappingDao, featureId, iconId, geometryType);
}
}
/**
* Set the default icon of the feature
* @param {module:features/user/featureTable|String} featureTable feature table
* @param {Number} featureId feature id
* @param {module:extension/style.IconRow} icon icon row
* @return {number}
*/
setIconDefault(featureTable: string | FeatureTable, featureId: number, icon: IconRow): number {
return this.setIcon(featureTable, featureId, null, icon);
}
/**
* Get the style id, either from the existing style or by inserting a new one
* @param {module:extension/style.StyleRow} style style row
* @return {Number} style id
*/
getOrInsertStyle(style: StyleRow): number {
let styleId;
if (style.hasId()) {
styleId = style.id;
} else {
const styleDao = this.getStyleDao();
if (styleDao !== null) {
styleId = styleDao.create(style);
style.id = styleId;
}
}
return styleId;
}
/**
* Get the icon id, either from the existing icon or by inserting a new one
* @param {module:extension/style.IconRow} icon icon row
* @return {Number} icon id
*/
getOrInsertIcon(icon: IconRow): number {
let iconId: number;
if (icon.hasId()) {
iconId = icon.id;
} else {
const iconDao = this.getIconDao();
if (iconDao != null) {
iconId = iconDao.create(icon);
icon.id = iconId;
}
}
return iconId;
}
/**
* Insert a style mapping row
* @param {module:extension/style.StyleMappingDao} mappingDao mapping dao
* @param {Number} baseId base id, either contents id or feature id
* @param {Number} relatedId related id, either style or icon id
* @param {String} geometryType geometry type or null
*/
insertStyleMapping(mappingDao: StyleMappingDao, baseId: number, relatedId: number, geometryType?: string): number {
const row = mappingDao.newRow();
row.baseId = baseId;
row.relatedId = relatedId;
row.setGeometryTypeName(geometryType);
return mappingDao.create(row);
}
/**
* Delete all feature styles including table styles, table icons, style, and icons
* @param {module:features/user/featureTable~FeatureTable|String} featureTable feature table
*/
deleteAllFeatureStyles(
featureTable: string | FeatureTable,
): {
tableStyles: {
styles: number;
icons: number;
};
styles: {
styles: number;
icons: number;
};
} {
return {
tableStyles: this.deleteTableFeatureStyles(featureTable),
styles: this.deleteFeatureStyles(featureTable),
};
}
/**
* Delete all styles including table styles and feature row style
* @param {module:features/user/featureTable|String} featureTable feature table
*/
deleteAllStyles(
featureTable: string | FeatureTable,
): {
tableStyles: number;
styles: number;
} {
return {
tableStyles: this.deleteTableStyles(featureTable),
styles: this.deleteStyles(featureTable),
};
}
/**
* Delete all icons including table icons and feature row icons
* @param {module:features/user/featureTable|String} featureTable feature table
*/
deleteAllIcons(
featureTable: string | FeatureTable,
): {
tableIcons: number;
icons: number;
} {
return {
tableIcons: this.deleteTableIcons(featureTable),
icons: this.deleteIcons(featureTable),
};
}
/**
* Delete the feature table feature styles
* @param {module:features/user/featureTable|String} featureTable feature table
*/
deleteTableFeatureStyles(
featureTable: string | FeatureTable,
): {
styles: number;
icons: number;
} {
return {
styles: this.deleteTableStyles(featureTable),
icons: this.deleteTableIcons(featureTable),
};
}
/**
* Delete the feature table styles
* @param {module:features/user/featureTable|String} featureTable feature table
*/
deleteTableStyles(featureTable: string | FeatureTable): number {
return this.deleteTableMappings(this.getTableStyleMappingDao(featureTable), featureTable);
}
/**
* Delete the feature table default style
* @param {module:features/user/featureTable|String} featureTable feature table
*/
deleteTableStyleDefault(featureTable: string | FeatureTable): number {
return this.deleteTableStyle(featureTable, null);
}
/**
* Delete the feature table style for the geometry type
* @param {module:features/user/featureTable|String} featureTable feature table
* @param {String} geometryType geometry type
*/
deleteTableStyle(featureTable: string | FeatureTable, geometryType: string): number {
return this.deleteTableMapping(this.getTableStyleMappingDao(featureTable), featureTable, geometryType);
}
/**
* Delete the feature table icons
* @param {module:features/user/featureTable|String} featureTable feature table
*/
deleteTableIcons(featureTable: string | FeatureTable): number {
return this.deleteTableMappings(this.getTableIconMappingDao(featureTable), featureTable);
}
/**
* Delete the feature table default icon
* @param {module:features/user/featureTable|String} featureTable feature table
*/
deleteTableIconDefault(featureTable: string | FeatureTable): number {
return this.deleteTableIcon(featureTable, null);
}
/**
* Delete the feature table icon for the geometry type
* @param {module:features/user/featureTable|String} featureTable feature table
* @param {String} geometryType geometry type
*/
deleteTableIcon(featureTable: string | FeatureTable, geometryType: string): number {
return this.deleteTableMapping(this.getTableIconMappingDao(featureTable), featureTable, geometryType);
}
/**
* Delete the table style mappings
* @param {module:extension/style.StyleMappingDao} mappingDao mapping dao
* @param {module:features/user/featureTable|String} featureTable feature table
*/
deleteTableMappings(mappingDao: StyleMappingDao, featureTable: string | FeatureTable): number {
if (mappingDao !== null) {
const featureContentsId = this.contentsIdExtension.getIdByTableName(this.getFeatureTableName(featureTable));
if (featureContentsId !== null) {
return mappingDao.deleteByBaseId(featureContentsId);
}
}
return 0;
}
/**
* Delete the table style mapping with the geometry type value
* @param {module:extension/style.StyleMappingDao} mappingDao mapping dao
* @param {module:features/user/featureTable|String} featureTable feature table
* @param {String} geometryType geometry type
*/
deleteTableMapping(mappingDao: StyleMappingDao, featureTable: string | FeatureTable, geometryType: string): number {
if (mappingDao !== null) {
const featureContentsId = this.contentsIdExtension.getIdByTableName(this.getFeatureTableName(featureTable));
if (featureContentsId !== null) {
return mappingDao.deleteByBaseIdAndGeometryType(featureContentsId, geometryType);
}
}
return 0;
}
/**
* Delete all feature styles
* @param {module:features/user/featureTable|String} featureTable feature table
*/
deleteFeatureStyles(
featureTable: string | FeatureTable,
): {
styles: number;
icons: number;
} {
return {
styles: this.deleteStyles(featureTable),
icons: this.deleteIcons(featureTable),
};
}
/**
* Delete all styles
* @param {module:features/user/featureTable|String} featureTable feature table
*/
deleteStyles(featureTable: string | FeatureTable): number {
return this.deleteMappings(this.getStyleMappingDao(featureTable));
}
/**
* Delete feature row styles
* @param {module:features/user/featureRow} featureRow feature row
*/
deleteStylesForFeatureRow(featureRow: FeatureRow): number {
return this.deleteStylesForFeatureId(featureRow.featureTable.getTableName(), featureRow.id);
}
/**
* Delete feature row styles
* @param {module:features/user/featureTable|String} featureTable feature table
* @param {Number} featureId feature id
*/
deleteStylesForFeatureId(featureTable: string | FeatureTable, featureId: number): number {
return this.deleteMappingsForFeatureId(this.getStyleMappingDao(featureTable), featureId);
}
/**
* Delete the feature row default style
* @param {module:features/user/featureRow} featureRow feature row
*/
deleteStyleDefaultForFeatureRow(featureRow: FeatureRow): number {
return this.deleteStyleForFeatureRowAndGeometryType(featureRow, null);
}
/**
* Delete the feature row default style
* @param {module:features/user/featureTable|String} featureTable feature table
* @param {Number} featureId feature id
*/
deleteStyleDefault(featureTable: string | FeatureTable, featureId: number): number {
return this.deleteStyle(featureTable, featureId, null);
}
/**
* Delete the feature row style for the feature row geometry type
* @param {module:features/user/featureRow} featureRow feature row
*/
deleteStyleForFeatureRow(featureRow: FeatureRow): number {
return this.deleteStyleForFeatureRowAndGeometryType(featureRow, featureRow.geometryType);
}
/**
* Delete the feature row style for the geometry type
* @param {module:features/user/featureRow} featureRow feature row
* @param {String} geometryType geometry type
*/
deleteStyleForFeatureRowAndGeometryType(featureRow: FeatureRow, geometryType: string): number {
return this.deleteStyle(featureRow.featureTable, featureRow.id, geometryType);
}
/**
* Delete the feature row style for the geometry type
* @param {module:features/user/featureTable|String} featureTable feature table
* @param {Number} featureId feature id
* @param {String} geometryType geometry type
*/
deleteStyle(featureTable: string | FeatureTable, featureId: number, geometryType: string): number {
return this.deleteMapping(this.getStyleMappingDao(featureTable), featureId, geometryType);
}
/**
* Delete the style row and associated mappings by style row
* @param {module:features/user/featureTable|String} featureTable feature table
* @param {module:extension/style.StyleRow} styleRow style row
*/
deleteStyleAndMappingsByStyleRow(featureTable: string | FeatureTable, styleRow: StyleRow): number {
return this.deleteStyleAndMappingsByStyleRowId(featureTable, styleRow.id);
}
/**
* Delete the style row and associated mappings by style row id
* @param {module:features/user/featureTable|String} featureTable feature table
* @param {Number} styleRowId style row id
*/
deleteStyleAndMappingsByStyleRowId(featureTable: string | FeatureTable, styleRowId: number): number {
this.getStyleDao().deleteById(styleRowId);
this.getStyleMappingDao(featureTable).deleteByRelatedId(styleRowId);
return this.getTableStyleMappingDao(featureTable).deleteByRelatedId(styleRowId);
}
/**
* Delete all icons
* @param {module:features/user/featureTable|String} featureTable feature table
*/
deleteIcons(featureTable: string | FeatureTable): number {
return this.deleteMappings(this.getIconMappingDao(featureTable));
}
/**
* Delete feature row icons
* @param {module:features/user/featureRow} featureRow feature row
*/
deleteIconsForFeatureRow(featureRow: FeatureRow): number {
return this.deleteIconsForFeatureId(featureRow.featureTable.getTableName(), featureRow.id);
}
/**
* Delete feature row icons
* @param {module:features/user/featureTable|String} featureTable feature table
* @param {Number} featureId feature id
*/
deleteIconsForFeatureId(featureTable: string | FeatureTable, featureId: number): number {
return this.deleteMappingsForFeatureId(this.getIconMappingDao(featureTable), featureId);
}
/**
* Delete the feature row default icon
* @param {module:features/user/featureRow} featureRow feature row
*/
deleteIconDefaultForFeatureRow(featureRow: FeatureRow): number {
return this.deleteIconDefault(featureRow.featureTable.getTableName(), featureRow.id);
}
/**
* Delete the feature row default icon
* @param {module:features/user/featureTable|String} featureTable feature table
* @param {Number} featureId feature id
*/
deleteIconDefault(featureTable: FeatureTable | string, featureId: number): number {
return this.deleteIcon(featureTable, featureId, null);
}
/**
* Delete the feature row icon for the feature row geometry type
* @param {module:features/user/featureRow} featureRow feature row
*/
deleteIconForFeatureRow(featureRow: FeatureRow): number {
return this.deleteIconForFeatureRowAndGeometryType(featureRow, featureRow.geometryType);
}
/**
* Delete the feature row icon for the geometry type
* @param {module:features/user/featureRow} featureRow feature row
* @param {String} geometryType geometry type
*/
deleteIconForFeatureRowAndGeometryType(featureRow: FeatureRow, geometryType: string): number {
return this.deleteIcon(featureRow.featureTable, featureRow.id, geometryType);
}
/**
* Delete the feature row icon for the geometry type
* @param {module:features/user/featureTable|String} featureTable feature table
* @param {Number} featureId feature id
* @param {String} geometryType geometry type
*/
deleteIcon(featureTable: FeatureTable | string, featureId: number, geometryType: string): number {
return this.deleteMapping(this.getIconMappingDao(featureTable), featureId, geometryType);
}
/**
* Delete the icon row and associated mappings by icon row
* @param {module:features/user/featureTable|String} featureTable feature table
* @param {module:extension/style.IconRow} iconRow icon row
*/
deleteIconAndMappingsByIconRow(featureTable: FeatureTable | string, iconRow: IconRow): number {
return this.deleteIconAndMappingsByIconRowId(featureTable, iconRow.id);
}
/**
* Delete the icon row and associated mappings by icon row id
* @param {module:features/user/featureTable|String} featureTable feature table
* @param {Number} iconRowId icon row id
*/
deleteIconAndMappingsByIconRowId(featureTable: FeatureTable | string, iconRowId: number): number {
this.getIconDao().deleteById(iconRowId);
this.getIconMappingDao(featureTable).deleteByRelatedId(iconRowId);
return this.getTableIconMappingDao(featureTable).deleteByRelatedId(iconRowId);
}
/**
* Delete all style mappings
* @param {module:extension/style.StyleMappingDao} mappingDao mapping dao
*/
deleteMappings(mappingDao?: StyleMappingDao): number {
if (mappingDao !== null) {
return mappingDao.deleteAll();
}
return 0;
}
/**
* Delete the style mappings
* @param {module:extension/style.StyleMappingDao} mappingDao mapping dao
* @param {Number} featureId feature id
*/
deleteMappingsForFeatureId(mappingDao?: StyleMappingDao, featureId?: number): number {
if (mappingDao !== null && featureId) {
return mappingDao.deleteByBaseId(featureId);
}
return 0;
}
/**
* Delete the style mapping with the geometry type value
* @param {module:extension/style.StyleMappingDao} mappingDao mapping dao
* @param {Number} featureId feature id
* @param {String} geometryType geometry type
*/
deleteMapping(mappingDao?: StyleMappingDao, featureId?: number, geometryType?: string): number {
if (mappingDao !== null) {
return mappingDao.deleteByBaseIdAndGeometryType(featureId, geometryType);
}
return 0;
}
/**
* Get all the unique style row ids the table maps to
* @param {module:features/user/featureTable|String} featureTable feature table
* @return style row ids
*/
getAllTableStyleIds(featureTable: FeatureTable | string): number[] {
let styleIds = null;
const mappingDao = this.getTableStyleMappingDao(featureTable);
if (mappingDao !== null) {
styleIds = mappingDao.uniqueRelatedIds().map(row => row['related_id']);
}
return styleIds;
}
/**
* Get all the unique icon row ids the table maps to
* @param {module:features/user/featureTable|String} featureTable feature table
* @return icon row ids
*/
getAllTableIconIds(featureTable: FeatureTable | string): number[] {
let styleIds = null;
const mappingDao = this.getTableIconMappingDao(featureTable);
if (mappingDao !== null) {
styleIds = mappingDao.uniqueRelatedIds().map(row => row['related_id']);
}
return styleIds;
}
/**
* Get all the unique style row ids the features map to
* @param {module:features/user/featureTable|String} featureTable feature table
* @return {Number[]} style row ids
*/
getAllStyleIds(featureTable: FeatureTable | string): number[] {
let styleIds = null;
const mappingDao = this.getStyleMappingDao(featureTable);
if (mappingDao !== null) {
styleIds = mappingDao.uniqueRelatedIds().map(row => row['related_id']);
}
return styleIds;
}
/**
* Get all the unique icon row ids the features map to
* @param {module:features/user/featureTable|String} featureTable feature table
* @return {Number[]} icon row ids
*/
getAllIconIds(featureTable: FeatureTable | string): number[] {
let styleIds = null;
const mappingDao = this.getIconMappingDao(featureTable);
if (mappingDao !== null) {
styleIds = mappingDao.uniqueRelatedIds().map(row => row['related_id']);
}
return styleIds;
}
/**
* Get name of feature table
* @param featureTable
* @returns {String}
*/
getFeatureTableName(featureTable: FeatureTable | string): string {
return featureTable instanceof FeatureTable ? featureTable.getTableName() : featureTable;
}
/**
* Remove all traces of the extension
*/
removeExtension(): number {
this.deleteAllRelationships();
this.geoPackage.deleteTable(StyleTable.TABLE_NAME);
this.geoPackage.deleteTable(IconTable.TABLE_NAME);
if (this.extensionsDao.isTableExists()) {
return this.extensionsDao.deleteByExtension(FeatureStyleExtension.EXTENSION_NAME);
}
return 0;
}
} | the_stack |
import { convertToNext } from '../../../../../src/check/arbitrary/definition/Converters';
import { Arbitrary } from '../../../../../src/check/arbitrary/definition/Arbitrary';
import { NextArbitrary } from '../../../../../src/check/arbitrary/definition/NextArbitrary';
import { Shrinkable } from '../../../../../src/check/arbitrary/definition/Shrinkable';
import { Random } from '../../../../../src/random/generator/Random';
import { NextValue } from '../../../../../src/check/arbitrary/definition/NextValue';
import { ConverterToNext } from '../../../../../src/check/arbitrary/definition/ConverterToNext';
import { Stream } from '../../../../../src/stream/Stream';
import { ConverterFromNext } from '../../../../../src/check/arbitrary/definition/ConverterFromNext';
import * as stubRng from '../../../stubs/generators';
const mrngNoCall = stubRng.mutable.nocall();
describe('ConverterToNext', () => {
describe('isConverterToNext', () => {
it('should detect its own instances', () => {
// Arrange
class MyArbitrary extends Arbitrary<number> {
generate(_mrng: Random): Shrinkable<number, number> {
throw new Error('Method not implemented.');
}
}
const originalInstance = new MyArbitrary();
// Act
const transformedInstance = convertToNext(originalInstance);
// Assert
expect(ConverterToNext.isConverterToNext(transformedInstance)).toBe(true);
});
it('should not flag NextArbitrary as one of its instances', () => {
// Arrange
class MyNextArbitrary extends NextArbitrary<number> {
generate(_mrng: Random): NextValue<number> {
throw new Error('Method not implemented.');
}
canShrinkWithoutContext(_value: unknown): _value is number {
throw new Error('Method not implemented.');
}
shrink(_value: number, _context?: unknown): Stream<NextValue<number>> {
throw new Error('Method not implemented.');
}
}
const originalInstance = new MyNextArbitrary();
// Act / Assert
expect(ConverterToNext.isConverterToNext(originalInstance)).toBe(false);
});
});
describe('generate', () => {
it('should be able to generate values using the underlying Arbitrary', () => {
// Arrange
const expectedValue = 1;
const generate = jest.fn().mockReturnValueOnce(new Shrinkable(expectedValue));
const withBias = jest.fn();
class MyArbitrary extends Arbitrary<number> {
generate = generate;
withBias = withBias;
}
const originalInstance = new MyArbitrary();
// Act
const transformedInstance = new ConverterToNext(originalInstance);
const out = transformedInstance.generate(mrngNoCall, undefined);
// Assert
expect(out.value).toBe(expectedValue);
expect(generate).toHaveBeenCalledTimes(1);
expect(generate).toHaveBeenCalledWith(mrngNoCall);
expect(withBias).not.toHaveBeenCalled();
});
it('should be able to generate biased values using the underlying Arbitrary', () => {
// Arrange
const expectedBiasedFactor = 42;
const expectedValue = 1;
const generate = jest.fn().mockReturnValueOnce(new Shrinkable(expectedValue));
const withBias = jest.fn();
class MyArbitrary extends Arbitrary<number> {
generate = generate;
withBias = withBias;
}
const originalInstance = new MyArbitrary();
withBias.mockReturnValue(originalInstance);
// Act
const transformedInstance = new ConverterToNext(originalInstance);
const out = transformedInstance.generate(mrngNoCall, expectedBiasedFactor);
// Assert
expect(out.value).toBe(expectedValue);
expect(generate).toHaveBeenCalledTimes(1);
expect(generate).toHaveBeenCalledWith(mrngNoCall);
expect(withBias).toHaveBeenCalledTimes(1);
expect(withBias).toHaveBeenCalledWith(expectedBiasedFactor);
});
});
describe('shrink', () => {
it('should be able to shrink values using the returned Shrinkable', () => {
// Arrange
const expectedShrunkValues = [2, 3, 4];
const shrink = jest
.fn<Stream<Shrinkable<number, number>>, any[]>()
.mockReturnValueOnce(Stream.of(...expectedShrunkValues.map((v) => new Shrinkable(v))));
const generate = jest.fn().mockReturnValueOnce(new Shrinkable(1, shrink));
class MyArbitrary extends Arbitrary<number> {
generate = generate;
}
const originalInstance = new MyArbitrary();
// Act
const transformedInstance = new ConverterToNext(originalInstance);
const out = transformedInstance.generate(mrngNoCall, undefined);
const outShrink = transformedInstance.shrink(out.value, out.context);
// Assert
expect([...outShrink].map((v) => v.value)).toEqual(expectedShrunkValues);
expect(generate).toHaveBeenCalledTimes(1);
expect(shrink).toHaveBeenCalledTimes(1);
});
it('should be able to shrink values using the returned Shrinkable even deeper', () => {
// Arrange
const expectedShrunkValues = [5, 6];
const shrinkLvl2 = jest
.fn<Stream<Shrinkable<number, number>>, any[]>()
.mockReturnValueOnce(Stream.of(...expectedShrunkValues.map((v) => new Shrinkable(v))));
const shrinkLvl1 = jest
.fn<Stream<Shrinkable<number, number>>, any[]>()
.mockReturnValueOnce(Stream.of(...[2, 3, 4].map((v) => new Shrinkable(v, shrinkLvl2))));
const generate = jest.fn().mockReturnValueOnce(new Shrinkable(1, shrinkLvl1));
class MyArbitrary extends Arbitrary<number> {
generate = generate;
}
const originalInstance = new MyArbitrary();
// Act
const transformedInstance = new ConverterToNext(originalInstance);
const out = transformedInstance.generate(mrngNoCall, undefined);
const outShrinkLvl1 = transformedInstance.shrink(out.value, out.context);
const firstShrunkValue = outShrinkLvl1.getNthOrLast(0)!;
const outShrinkLvl2 = transformedInstance.shrink(firstShrunkValue.value, firstShrunkValue.context);
// Assert
expect([...outShrinkLvl2].map((v) => v.value)).toEqual(expectedShrunkValues);
expect(generate).toHaveBeenCalledTimes(1);
expect(shrinkLvl1).toHaveBeenCalledTimes(1);
expect(shrinkLvl2).toHaveBeenCalledTimes(1);
});
});
describe('filter', () => {
it('should call filter directly on the passed instance and convert its result', () => {
// Arrange
const generate = jest.fn();
const filter = jest.fn();
class MyArbitrary extends Arbitrary<number> {
generate = generate;
filter = filter;
}
const originalInstance = new MyArbitrary();
const filteredInstance = new MyArbitrary();
filter.mockReturnValue(filteredInstance);
const predicate = () => true;
// Act
const transformedInstance = new ConverterToNext(originalInstance);
const transformedInstanceFiltered = transformedInstance.filter(predicate);
// Assert
expect(filter).toHaveBeenCalledTimes(1);
expect(filter).toHaveBeenCalledWith(predicate);
expect(ConverterToNext.isConverterToNext(transformedInstanceFiltered)).toBe(true);
expect((transformedInstanceFiltered as ConverterToNext<number>).arb).toBe(filteredInstance);
});
it('should unwrap instances of ConverterFromNext returned by filter', () => {
// Arrange
const generate = jest.fn();
const canShrinkWithoutContext = jest.fn();
const shrink = jest.fn();
const filter = jest.fn();
class MyArbitrary extends Arbitrary<number> {
generate = generate;
filter = filter;
}
class MyNextArbitrary extends NextArbitrary<number> {
generate = generate;
canShrinkWithoutContext = canShrinkWithoutContext as any as (v: unknown) => v is number;
shrink = shrink;
}
const originalInstance = new MyArbitrary();
const filteredInstanceNext = new MyNextArbitrary();
filter.mockReturnValue(new ConverterFromNext(filteredInstanceNext));
const predicate = () => true;
// Act
const transformedInstance = new ConverterToNext(originalInstance);
const transformedInstanceFiltered = transformedInstance.filter(predicate);
// Assert
expect(ConverterToNext.isConverterToNext(transformedInstanceFiltered)).toBe(false);
expect(transformedInstanceFiltered).toBe(filteredInstanceNext);
});
});
describe('map', () => {
it('should call map directly on the passed instance and convert its result', () => {
// Arrange
const generate = jest.fn();
const map = jest.fn();
class MyArbitrary extends Arbitrary<number> {
generate = generate;
map = map;
}
const originalInstance = new MyArbitrary();
const mappedInstance = new MyArbitrary();
map.mockReturnValue(mappedInstance);
const mapper = () => 0;
// Act
const transformedInstance = new ConverterToNext(originalInstance);
const transformedInstanceMapped = transformedInstance.map(mapper);
// Assert
expect(map).toHaveBeenCalledTimes(1);
expect(map).toHaveBeenCalledWith(mapper);
expect(ConverterToNext.isConverterToNext(transformedInstanceMapped)).toBe(true);
expect((transformedInstanceMapped as ConverterToNext<number>).arb).toBe(mappedInstance);
});
it('should unwrap instances of ConverterFromNext returned by map', () => {
// Arrange
const generate = jest.fn();
const canShrinkWithoutContext = jest.fn();
const shrink = jest.fn();
const map = jest.fn();
class MyArbitrary extends Arbitrary<number> {
generate = generate;
map = map;
}
class MyNextArbitrary extends NextArbitrary<number> {
generate = generate;
canShrinkWithoutContext = canShrinkWithoutContext as any as (v: unknown) => v is number;
shrink = shrink;
map = map;
}
const originalInstance = new MyArbitrary();
const mappedInstanceNext = new MyNextArbitrary();
map.mockReturnValue(new ConverterFromNext(mappedInstanceNext));
const mapper = () => 0;
// Act
const transformedInstance = new ConverterToNext(originalInstance);
const transformedInstanceMapped = transformedInstance.map(mapper);
// Assert
expect(ConverterToNext.isConverterToNext(transformedInstanceMapped)).toBe(false);
expect(transformedInstanceMapped).toBe(mappedInstanceNext);
});
});
describe('chain', () => {
it('should call map directly on the passed instance and convert its result', () => {
// Arrange
const generate = jest.fn();
const chain = jest.fn();
class MyArbitrary extends Arbitrary<number> {
generate = generate;
chain = chain;
}
const originalInstance = new MyArbitrary();
const chainedInstance = new MyArbitrary();
const outChainedInstance = new MyArbitrary();
const outChainedInstanceNext = new ConverterToNext(outChainedInstance);
chain.mockReturnValue(chainedInstance);
const chainer = () => outChainedInstanceNext;
// Act
const transformedInstance = new ConverterToNext(originalInstance);
const transformedInstanceMapped = transformedInstance.chain(chainer);
// Assert
expect(chain).toHaveBeenCalledTimes(1);
expect(ConverterToNext.isConverterToNext(transformedInstanceMapped)).toBe(true);
expect((transformedInstanceMapped as ConverterToNext<number>).arb).toBe(chainedInstance);
});
});
describe('noShrink', () => {
it('should call noShrink directly on the passed instance and convert its result', () => {
// Arrange
const generate = jest.fn();
const noShrink = jest.fn();
class MyArbitrary extends Arbitrary<number> {
generate = generate;
noShrink = noShrink;
}
const originalInstance = new MyArbitrary();
const noShrinkInstance = new MyArbitrary();
noShrink.mockReturnValue(noShrinkInstance);
// Act
const transformedInstance = new ConverterToNext(originalInstance);
const transformedInstanceNoShrink = transformedInstance.noShrink();
// Assert
expect(noShrink).toHaveBeenCalledTimes(1);
expect(ConverterToNext.isConverterToNext(transformedInstanceNoShrink)).toBe(true);
expect((transformedInstanceNoShrink as ConverterToNext<number>).arb).toBe(noShrinkInstance);
});
});
describe('noBias', () => {
it('should call noBias directly on the passed instance and convert its result', () => {
// Arrange
const generate = jest.fn();
const noBias = jest.fn();
class MyArbitrary extends Arbitrary<number> {
generate = generate;
noBias = noBias;
}
const originalInstance = new MyArbitrary();
const noBiasInstance = new MyArbitrary();
noBias.mockReturnValue(noBiasInstance);
// Act
const transformedInstance = new ConverterToNext(originalInstance);
const transformedInstanceNoBias = transformedInstance.noBias();
// Assert
expect(noBias).toHaveBeenCalledTimes(1);
expect(ConverterToNext.isConverterToNext(transformedInstanceNoBias)).toBe(true);
expect((transformedInstanceNoBias as ConverterToNext<number>).arb).toBe(noBiasInstance);
});
});
}); | the_stack |
namespace ts {
export function transformECMAScriptModule(context: TransformationContext) {
const {
factory,
getEmitHelperFactory: emitHelpers,
} = context;
const host = context.getEmitHost();
const resolver = context.getEmitResolver();
const compilerOptions = context.getCompilerOptions();
const languageVersion = getEmitScriptTarget(compilerOptions);
const previousOnEmitNode = context.onEmitNode;
const previousOnSubstituteNode = context.onSubstituteNode;
context.onEmitNode = onEmitNode;
context.onSubstituteNode = onSubstituteNode;
context.enableEmitNotification(SyntaxKind.SourceFile);
context.enableSubstitution(SyntaxKind.Identifier);
let helperNameSubstitutions: ESMap<string, Identifier> | undefined;
let currentSourceFile: SourceFile | undefined;
let importRequireStatements: [ImportDeclaration, VariableStatement] | undefined;
return chainBundle(context, transformSourceFile);
function transformSourceFile(node: SourceFile) {
if (node.isDeclarationFile) {
return node;
}
if (isExternalModule(node) || compilerOptions.isolatedModules) {
currentSourceFile = node;
importRequireStatements = undefined;
let result = updateExternalModule(node);
currentSourceFile = undefined;
if (importRequireStatements) {
result = factory.updateSourceFile(
result,
setTextRange(factory.createNodeArray(insertStatementsAfterCustomPrologue(result.statements.slice(), importRequireStatements)), result.statements),
);
}
if (!isExternalModule(node) || some(result.statements, isExternalModuleIndicator)) {
return result;
}
return factory.updateSourceFile(
result,
setTextRange(factory.createNodeArray([...result.statements, createEmptyExports(factory)]), result.statements),
);
}
return node;
}
function updateExternalModule(node: SourceFile) {
const externalHelpersImportDeclaration = createExternalHelpersImportDeclarationIfNeeded(factory, emitHelpers(), node, compilerOptions);
if (externalHelpersImportDeclaration) {
const statements: Statement[] = [];
const statementOffset = factory.copyPrologue(node.statements, statements);
append(statements, externalHelpersImportDeclaration);
addRange(statements, visitNodes(node.statements, visitor, isStatement, statementOffset));
return factory.updateSourceFile(
node,
setTextRange(factory.createNodeArray(statements), node.statements));
}
else {
return visitEachChild(node, visitor, context);
}
}
function visitor(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.ImportEqualsDeclaration:
// Though an error in es2020 modules, in node-flavor es2020 modules, we can helpfully transform this to a synthetic `require` call
// To give easy access to a synchronous `require` in node-flavor esm. We do the transform even in scenarios where we error, but `import.meta.url`
// is available, just because the output is reasonable for a node-like runtime.
return getEmitScriptTarget(compilerOptions) >= ModuleKind.ES2020 ? visitImportEqualsDeclaration(node as ImportEqualsDeclaration) : undefined;
case SyntaxKind.ExportAssignment:
return visitExportAssignment(node as ExportAssignment);
case SyntaxKind.ExportDeclaration:
const exportDecl = (node as ExportDeclaration);
return visitExportDeclaration(exportDecl);
}
return node;
}
/**
* Creates a `require()` call to import an external module.
*
* @param importNode The declaration to import.
*/
function createRequireCall(importNode: ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration) {
const moduleName = getExternalModuleNameLiteral(factory, importNode, Debug.checkDefined(currentSourceFile), host, resolver, compilerOptions);
const args: Expression[] = [];
if (moduleName) {
args.push(moduleName);
}
if (!importRequireStatements) {
const createRequireName = factory.createUniqueName("_createRequire", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel);
const importStatement = factory.createImportDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
factory.createImportClause(
/*isTypeOnly*/ false,
/*name*/ undefined,
factory.createNamedImports([
factory.createImportSpecifier(/*isTypeOnly*/ false, factory.createIdentifier("createRequire"), createRequireName)
])
),
factory.createStringLiteral("module")
);
const requireHelperName = factory.createUniqueName("__require", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel);
const requireStatement = factory.createVariableStatement(
/*modifiers*/ undefined,
factory.createVariableDeclarationList(
[
factory.createVariableDeclaration(
requireHelperName,
/*exclamationToken*/ undefined,
/*type*/ undefined,
factory.createCallExpression(factory.cloneNode(createRequireName), /*typeArguments*/ undefined, [
factory.createPropertyAccessExpression(factory.createMetaProperty(SyntaxKind.ImportKeyword, factory.createIdentifier("meta")), factory.createIdentifier("url"))
])
)
],
/*flags*/ languageVersion >= ScriptTarget.ES2015 ? NodeFlags.Const : NodeFlags.None
)
);
importRequireStatements = [importStatement, requireStatement];
}
const name = importRequireStatements[1].declarationList.declarations[0].name;
Debug.assertNode(name, isIdentifier);
return factory.createCallExpression(factory.cloneNode(name), /*typeArguments*/ undefined, args);
}
/**
* Visits an ImportEqualsDeclaration node.
*
* @param node The node to visit.
*/
function visitImportEqualsDeclaration(node: ImportEqualsDeclaration): VisitResult<Statement> {
Debug.assert(isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
let statements: Statement[] | undefined;
statements = append(statements,
setOriginalNode(
setTextRange(
factory.createVariableStatement(
/*modifiers*/ undefined,
factory.createVariableDeclarationList(
[
factory.createVariableDeclaration(
factory.cloneNode(node.name),
/*exclamationToken*/ undefined,
/*type*/ undefined,
createRequireCall(node)
)
],
/*flags*/ languageVersion >= ScriptTarget.ES2015 ? NodeFlags.Const : NodeFlags.None
)
),
node),
node
)
);
statements = appendExportsOfImportEqualsDeclaration(statements, node);
return singleOrMany(statements);
}
function appendExportsOfImportEqualsDeclaration(statements: Statement[] | undefined, node: ImportEqualsDeclaration) {
if (hasSyntacticModifier(node, ModifierFlags.Export)) {
statements = append(statements, factory.createExportDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
node.isTypeOnly,
factory.createNamedExports([factory.createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, idText(node.name))])
));
}
return statements;
}
function visitExportAssignment(node: ExportAssignment): VisitResult<ExportAssignment> {
// Elide `export=` as it is not legal with --module ES6
return node.isExportEquals ? undefined : node;
}
function visitExportDeclaration(node: ExportDeclaration) {
// `export * as ns` only needs to be transformed in ES2015
if (compilerOptions.module !== undefined && compilerOptions.module > ModuleKind.ES2015) {
return node;
}
// Either ill-formed or don't need to be tranformed.
if (!node.exportClause || !isNamespaceExport(node.exportClause) || !node.moduleSpecifier) {
return node;
}
const oldIdentifier = node.exportClause.name;
const synthName = factory.getGeneratedNameForNode(oldIdentifier);
const importDecl = factory.createImportDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
factory.createImportClause(
/*isTypeOnly*/ false,
/*name*/ undefined,
factory.createNamespaceImport(
synthName
)
),
node.moduleSpecifier,
node.assertClause
);
setOriginalNode(importDecl, node.exportClause);
const exportDecl = isExportNamespaceAsDefaultDeclaration(node) ? factory.createExportDefault(synthName) : factory.createExportDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
/*isTypeOnly*/ false,
factory.createNamedExports([factory.createExportSpecifier(/*isTypeOnly*/ false, synthName, oldIdentifier)]),
);
setOriginalNode(exportDecl, node);
return [importDecl, exportDecl];
}
//
// Emit Notification
//
/**
* Hook for node emit.
*
* @param hint A hint as to the intended usage of the node.
* @param node The node to emit.
* @param emit A callback used to emit the node in the printer.
*/
function onEmitNode(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void {
if (isSourceFile(node)) {
if ((isExternalModule(node) || compilerOptions.isolatedModules) && compilerOptions.importHelpers) {
helperNameSubstitutions = new Map<string, Identifier>();
}
previousOnEmitNode(hint, node, emitCallback);
helperNameSubstitutions = undefined;
}
else {
previousOnEmitNode(hint, node, emitCallback);
}
}
//
// Substitutions
//
/**
* Hooks node substitutions.
*
* @param hint A hint as to the intended usage of the node.
* @param node The node to substitute.
*/
function onSubstituteNode(hint: EmitHint, node: Node) {
node = previousOnSubstituteNode(hint, node);
if (helperNameSubstitutions && isIdentifier(node) && getEmitFlags(node) & EmitFlags.HelperName) {
return substituteHelperName(node);
}
return node;
}
function substituteHelperName(node: Identifier): Expression {
const name = idText(node);
let substitution = helperNameSubstitutions!.get(name);
if (!substitution) {
helperNameSubstitutions!.set(name, substitution = factory.createUniqueName(name, GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel));
}
return substitution;
}
}
} | the_stack |
import * as pathModule from 'path'
import { existsSync, writeFileSync } from 'fs'
import { log } from '../../utils/log'
import {
fromRoot,
getPackages,
readFileJSON,
readPackageJSON,
relativeToRoot,
writeFileJSON,
writePackageJSON
} from '../../utils'
import { LernaListItem, PackageJSON, TSConfig } from '../../types'
import { flatMapSlow } from '../../utils/flatMapSlow'
import { cmd } from '../../utils/cmd'
const OVER_RIDE_UP_KEEP = '$overRideUpKeep'
const PACKAGE_LOCATION = pathModule.resolve(__dirname, '../../..')
const PACKAGE_FOLDER_NAME = pathModule.basename(PACKAGE_LOCATION)
const STATIC_SHARED_DUPLICATED_PATH = 'templates/static-shared-duplicated'
const CREATE_IF_DONT_EXIST_PATH = 'templates/create-if-dont-exist'
const IDE_TSCONFIG = 'tsconfig.json'
const BUILD_TSCONFIG = 'tsconfig.build.json'
const REFERENCES_TSCONFIG = 'tsconfig.references.json'
const UPKEEP_JSON_OPTS = { prefix: '// GENERATED BY UPKEEP\n' }
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const copydir: any = require('copy-dir')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const deepMerge: any = require('deepmerge')
function checkDependencies(
subPackage: LernaListItem,
rootPackageJSON: PackageJSON,
depsTypes = ['devDependencies']
) {
const packageJSONPath = `${subPackage.location}/package.json`
const subPackageJSON = readPackageJSON(packageJSONPath)
let changed = false
for (const depsType of depsTypes) {
if (!subPackageJSON[depsType]) {
subPackageJSON[depsType] = {}
changed = true
}
const subPackageDeps = subPackageJSON[depsType]
// if (!subPackageDeps) {
// continue
// }
const rootPackageDepsForType = rootPackageJSON[depsType] ?? {}
Object.keys(rootPackageDepsForType).forEach(depKey => {
const rootVer = rootPackageDepsForType[depKey]
const subPackageVer = subPackageDeps[depKey]
if (!subPackageVer) {
changed = true
log(subPackage.name, 'adding root version', depKey, rootVer)
subPackageDeps[depKey] = rootVer
} else if (subPackageVer !== rootVer) {
changed = true
log(subPackage.name, 'list', depKey, 'in root package.json')
log(subPackage.name, 'removing', depKey, subPackageVer)
log(subPackage.name, 'using root version', depKey, rootVer)
subPackageDeps[depKey] = rootVer
}
})
// Object.keys(subPackageDeps).forEach(depKey => {
// // const rootPackageDepsForType = rootPackageJSON[depsType]
// // if (rootPackageDepsForType && rootPackageDepsForType[depKey]) {
// // log(
// // 'subpackage',
// // subPackageJSON.name,
// // `has redundant ${depsType} from root`,
// // depKey
// // )
// // log('root version', rootPackageDepsForType[depKey])
// // log('subpackage version', subPackageDeps[depKey])
// // log('removing')
// // delete subPackageDeps[depKey]
// // removed = true
// // }
// })
}
if (changed) {
writePackageJSON(packageJSONPath, subPackageJSON)
}
}
function setCommonScriptsAndMergeOverrides(
rootPackageJSON: PackageJSON,
subPackage: LernaListItem,
subPackageJSON: PackageJSON
) {
const folderName = getPackageFolder(subPackage)
if (
!rootPackageJSON.repository ||
!rootPackageJSON.repository.url ||
rootPackageJSON.repository.type !== 'git'
) {
throw new Error('expecting git url for repository in root package.json')
}
const githubPath = rootPackageJSON.repository.url.split(':')[1].slice(0, -4)
let updated: PackageJSON = {
...subPackageJSON,
version: '0.0.0',
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
homepage: `https://github.com/${githubPath}/tree/main/packages/${folderName}`,
keywords: rootPackageJSON.keywords,
repository: rootPackageJSON.repository,
main: './build',
types: './build',
private: rootPackageJSON.upkeep?.privatePackages ?? undefined,
author: rootPackageJSON.author,
license: rootPackageJSON.license,
$schema: `../${PACKAGE_FOLDER_NAME}/resources/package-json-schema-nested-overrides.json`,
scripts: {
...(subPackageJSON.scripts || {}),
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
postinstall: undefined!,
precommit: 'echo lint-staged runs from root',
prettier:
"prettier --write '*.{ts,tsx,js,html,jsx,md}' '{src,test}/**/*.{ts,tsx,js,html,jsx,md}'",
format: 'yarn prettier && LINT_FIX=1 yarn lint:all --fix --quiet',
'build:ts': 'tsc --build tsconfig.build.json',
'build:ts:watch': 'yarn build:ts --watch',
'build:ts:verbose': 'yarn build:ts --verbose',
'clean:build': 'rimraf build',
// example of deleting an old script
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
root: undefined!,
upkeep: 'cd ../.. && yarn upkeep',
'lint:all': "yarn lint 'src/**/*.{ts,tsx}' 'test/**/*.{ts,tsx}'",
lint: 'eslint --cache --cache-location ../../node_modules/.cache/eslint',
test: 'jest --passWithNoTests',
'test:coverage': 'yarn test --verbose --coverage'
}
}
// We don't want this
delete updated['lint-staged']
if (updated[OVER_RIDE_UP_KEEP]) {
const overrides = updated[OVER_RIDE_UP_KEEP]
updated = deepMerge(updated, overrides, {
// Overwrite existing values completely
arrayMerge: (_: any, src: any) => src
})
}
writePackageJSON(`${subPackage.location}/package.json`, updated)
return updated
}
function getPackageFolder(li: LernaListItem) {
// TODO: pathModule.basename
const path = li.location.split('/')
return path[path.length - 1]
}
function upKeepTypeScriptBuildConfig(subPackage: LernaListItem) {
const tsconfig: TSConfig = {
extends: '../../tsconfig.build.settings.json',
compilerOptions: {
composite: true,
outDir: './build',
tsBuildInfoFile: './build/tsconfig.build.tsbuildinfo',
rootDir: 'src'
},
include: ['src']
}
if (subPackage.dependencies.length) {
tsconfig.references = subPackage.dependencies.map(li => {
const packageFolder = getPackageFolder(li)
return { path: `../${packageFolder}/tsconfig.build.json` }
})
}
writeFileJSON(
`${subPackage.location}/tsconfig.build.json`,
tsconfig,
UPKEEP_JSON_OPTS
)
}
interface UpkeepStaticSharedDuplicatedParameters {
subPackage: LernaListItem
path: string
cover: boolean
}
function copyTemplatesDir({
subPackage,
path,
cover
}: UpkeepStaticSharedDuplicatedParameters) {
copydir.sync(`${PACKAGE_LOCATION}/${path}`, subPackage.location, {
// TODO: elegant convention
utimes: true,
mode: true,
cover
})
}
function upKeepIDETsConfigPaths(subPackages: LernaListItem[]) {
const path = fromRoot(IDE_TSCONFIG)
const tsconfig = readFileJSON<TSConfig>(path)
tsconfig.compilerOptions = tsconfig.compilerOptions || {}
const paths: Record<string, string[]> = {}
subPackages.forEach(li => {
const packagePath = `packages/${getPackageFolder(li)}`
const path = `${packagePath}/src`
paths[li.name] = [path]
const subPackageJSON = readPackageJSON(`${li.location}/package.json`)
// Handle any @ns/package/derp redirects
if (subPackageJSON.subpackages) {
subPackageJSON.subpackages.forEach(name => {
const folderPath = pathModule.join(fromRoot(path), name)
const tsPath = pathModule.join(fromRoot(path), `${name}.ts`)
let isFolder = true
if (existsSync(folderPath)) {
// folder
paths[`${li.name}/${name}`] = [`${path}/${name}`]
} else if (existsSync(tsPath)) {
isFolder = false
paths[`${li.name}/${name}`] = [`${path}/${name}.ts`]
} else {
throw new Error()
}
cmd(`rm -rf ${packagePath}/${name}`, { cwd: fromRoot('.') })
cmd(`mkdir ${packagePath}/${name}`, { cwd: fromRoot('.') })
writeFileJSON(`${packagePath}/${name}/package.json`, {
name: `${li.name}/${name}`,
private: true,
version: '0.0.0',
main: `../build/${isFolder ? name : `${name}.js`}`,
types: `../build/${isFolder ? name : `${name}.d.ts`}`
})
})
}
})
tsconfig.compilerOptions.paths = paths
writeFileJSON(path, tsconfig, UPKEEP_JSON_OPTS)
}
function upKeepStaticSharedTemplates(subPackage: LernaListItem) {
copyTemplatesDir({
subPackage,
path: STATIC_SHARED_DUPLICATED_PATH,
cover: true
})
}
function copyInDefaultFiles(subPackage: LernaListItem) {
copyTemplatesDir({
subPackage,
path: CREATE_IF_DONT_EXIST_PATH,
cover: false
})
}
function upKeepReferencesTsConfig(subPackages: LernaListItem[]) {
const tsconfig: TSConfig = {
files: [],
references: subPackages.map(li => ({
path: pathModule.join(relativeToRoot(li.location), BUILD_TSCONFIG)
}))
}
writeFileJSON(fromRoot(REFERENCES_TSCONFIG), tsconfig, UPKEEP_JSON_OPTS)
}
function createDefaultReadmeFile(subPackage: LernaListItem) {
const path = pathModule.join(subPackage.location, 'README.md')
const words = subPackage.name.slice(1).split(/[/-]/)
const toTitle = (w: string) => w.charAt(0).toUpperCase() + w.slice(1)
const titleCase = words.map(toTitle).join(' ')
const README = `# ${titleCase}
A work in progress. You probably don't want this.
`
if (!existsSync(path)) {
writeFileSync(path, README)
}
}
function upKeepIntelliJExcludes(subPackages: LernaListItem[]) {
const exclude = '<excludeFolder url="file://$MODULE_DIR$/%PATH%"/>'
const xml = `<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output/>
<content url="file://$MODULE_DIR$">
%EXCLUDES%
</content>
<orderEntry type="inheritedJdk"/>
<orderEntry type="sourceFolder" forTests="false"/>
</component>
</module>
`
const root = fromRoot('.')
const moduleName = pathModule.basename(root)
const path = fromRoot(`./.idea/${moduleName}.iml`)
const locations = subPackages.map(li => li.location).concat(root)
if (existsSync(path)) {
const excludes = flatMapSlow(locations, li => {
return ['dist', 'build', 'coverage'].map(folder => {
const from = pathModule.join(li, folder)
const replacement = pathModule.relative(root, from)
return exclude.replace(/%PATH%/, replacement)
})
}).join('\n')
writeFileSync(path, xml.replace(/%EXCLUDES%/, excludes))
} else if (existsSync(fromRoot('./.idea'))) {
console.warn('warning: IDEA user expecting to exist', path)
}
}
export function doUpKeep() {
log({ upKeeping: true })
const subPackages = getPackages()
const rootPackageJSON = readPackageJSON(fromRoot('package.json'))
for (const subPackage of subPackages) {
// Do last, TODO: nothing should mutate package.json
checkDependencies(subPackage, rootPackageJSON)
const subPackageJSON = readPackageJSON(
`${subPackage.location}/package.json`
)
setCommonScriptsAndMergeOverrides(
rootPackageJSON,
subPackage,
subPackageJSON
)
upKeepTypeScriptBuildConfig(subPackage)
upKeepStaticSharedTemplates(subPackage)
copyInDefaultFiles(subPackage)
createDefaultReadmeFile(subPackage)
}
upKeepIDETsConfigPaths(subPackages)
upKeepReferencesTsConfig(subPackages)
upKeepIntelliJExcludes(subPackages)
// Not using "manual" dependabot configuration currently.
// The .dependabot/config.yml removed from repo.
// upKeepDependabotConfiguration(subPackages)
log({ upKeepingDone: true })
} | the_stack |
import { applyPairs, extend, identity, inherit, mapObj, noop, Obj, omit, tail, values, copy } from '../common/common';
import { isArray, isDefined, isFunction, isString } from '../common/predicates';
import { stringify } from '../common/strings';
import { is, pattern, pipe, prop, val } from '../common/hof';
import { StateDeclaration } from './interface';
import { StateObject } from './stateObject';
import { StateMatcher } from './stateMatcher';
import { Param } from '../params/param';
import { UrlMatcherFactory } from '../url/urlMatcherFactory';
import { UrlMatcher } from '../url/urlMatcher';
import { Resolvable } from '../resolve/resolvable';
import { services } from '../common/coreservices';
import { ResolvePolicy } from '../resolve/interface';
import { ParamDeclaration } from '../params';
import { ParamFactory } from '../url';
const parseUrl = (url: string): any => {
if (!isString(url)) return false;
const root = url.charAt(0) === '^';
return { val: root ? url.substring(1) : url, root };
};
/**
* A function that builds the final value for a specific field on a [[StateObject]].
*
* A series of builder functions for a given field are chained together.
* The final value returned from the chain of builders is applied to the built [[StateObject]].
* Builder functions should call the [[parent]] function either first or last depending on the desired composition behavior.
*
* @param state the _partially built_ [[StateObject]]. The [[StateDeclaration]] can be inspected via [[StateObject.self]]
* @param parent the previous builder function in the series.
*/
export type BuilderFunction = (state: StateObject, parent?: BuilderFunction) => any;
interface Builders {
[key: string]: BuilderFunction[];
name: BuilderFunction[];
parent: BuilderFunction[];
data: BuilderFunction[];
url: BuilderFunction[];
navigable: BuilderFunction[];
params: BuilderFunction[];
views: BuilderFunction[];
path: BuilderFunction[];
includes: BuilderFunction[];
resolvables: BuilderFunction[];
}
function nameBuilder(state: StateObject) {
return state.name;
}
function selfBuilder(state: StateObject) {
state.self.$$state = () => state;
return state.self;
}
function dataBuilder(state: StateObject) {
if (state.parent && state.parent.data) {
state.data = state.self.data = inherit(state.parent.data, state.data);
}
return state.data;
}
const getUrlBuilder = ($urlMatcherFactoryProvider: UrlMatcherFactory, root: () => StateObject) =>
function urlBuilder(stateObject: StateObject) {
let stateDec: StateDeclaration = stateObject.self;
// For future states, i.e., states whose name ends with `.**`,
// match anything that starts with the url prefix
if (stateDec && stateDec.url && stateDec.name && stateDec.name.match(/\.\*\*$/)) {
const newStateDec: StateDeclaration = {};
copy(stateDec, newStateDec);
newStateDec.url += '{remainder:any}'; // match any path (.*)
stateDec = newStateDec;
}
const parent = stateObject.parent;
const parsed = parseUrl(stateDec.url);
const url = !parsed ? stateDec.url : $urlMatcherFactoryProvider.compile(parsed.val, { state: stateDec });
if (!url) return null;
if (!$urlMatcherFactoryProvider.isMatcher(url)) throw new Error(`Invalid url '${url}' in state '${stateObject}'`);
return parsed && parsed.root ? url : ((parent && parent.navigable) || root()).url.append(<UrlMatcher>url);
};
const getNavigableBuilder = (isRoot: (state: StateObject) => boolean) =>
function navigableBuilder(state: StateObject) {
return !isRoot(state) && state.url ? state : state.parent ? state.parent.navigable : null;
};
const getParamsBuilder = (paramFactory: ParamFactory) =>
function paramsBuilder(state: StateObject): { [key: string]: Param } {
const makeConfigParam = (config: ParamDeclaration, id: string) => paramFactory.fromConfig(id, null, state.self);
const urlParams: Param[] = (state.url && state.url.parameters({ inherit: false })) || [];
const nonUrlParams: Param[] = values(mapObj(omit(state.params || {}, urlParams.map(prop('id'))), makeConfigParam));
return urlParams
.concat(nonUrlParams)
.map((p) => [p.id, p])
.reduce(applyPairs, {});
};
function pathBuilder(state: StateObject) {
return state.parent ? state.parent.path.concat(state) : /*root*/ [state];
}
function includesBuilder(state: StateObject) {
const includes = state.parent ? extend({}, state.parent.includes) : {};
includes[state.name] = true;
return includes;
}
/**
* This is a [[StateBuilder.builder]] function for the `resolve:` block on a [[StateDeclaration]].
*
* When the [[StateBuilder]] builds a [[StateObject]] object from a raw [[StateDeclaration]], this builder
* validates the `resolve` property and converts it to a [[Resolvable]] array.
*
* resolve: input value can be:
*
* {
* // analyzed but not injected
* myFooResolve: function() { return "myFooData"; },
*
* // function.toString() parsed, "DependencyName" dep as string (not min-safe)
* myBarResolve: function(DependencyName) { return DependencyName.fetchSomethingAsPromise() },
*
* // Array split; "DependencyName" dep as string
* myBazResolve: [ "DependencyName", function(dep) { return dep.fetchSomethingAsPromise() },
*
* // Array split; DependencyType dep as token (compared using ===)
* myQuxResolve: [ DependencyType, function(dep) { return dep.fetchSometingAsPromise() },
*
* // val.$inject used as deps
* // where:
* // corgeResolve.$inject = ["DependencyName"];
* // function corgeResolve(dep) { dep.fetchSometingAsPromise() }
* // then "DependencyName" dep as string
* myCorgeResolve: corgeResolve,
*
* // inject service by name
* // When a string is found, desugar creating a resolve that injects the named service
* myGraultResolve: "SomeService"
* }
*
* or:
*
* [
* new Resolvable("myFooResolve", function() { return "myFooData" }),
* new Resolvable("myBarResolve", function(dep) { return dep.fetchSomethingAsPromise() }, [ "DependencyName" ]),
* { provide: "myBazResolve", useFactory: function(dep) { dep.fetchSomethingAsPromise() }, deps: [ "DependencyName" ] }
* ]
*/
export function resolvablesBuilder(state: StateObject): Resolvable[] {
interface Tuple {
token: any;
val: any;
deps: any[];
policy: ResolvePolicy;
}
/** convert resolve: {} and resolvePolicy: {} objects to an array of tuples */
const objects2Tuples = (resolveObj: Obj, resolvePolicies: { [key: string]: ResolvePolicy }) =>
Object.keys(resolveObj || {}).map((token) => ({
token,
val: resolveObj[token],
deps: undefined,
policy: resolvePolicies[token],
}));
/** fetch DI annotations from a function or ng1-style array */
const annotate = (fn: Function) => {
const $injector = services.$injector;
// ng1 doesn't have an $injector until runtime.
// If the $injector doesn't exist, use "deferred" literal as a
// marker indicating they should be annotated when runtime starts
return fn['$inject'] || ($injector && $injector.annotate(fn, $injector.strictDi)) || <any>'deferred';
};
/** true if the object has both `token` and `resolveFn`, and is probably a [[ResolveLiteral]] */
const isResolveLiteral = (obj: any) => !!(obj.token && obj.resolveFn);
/** true if the object looks like a provide literal, or a ng2 Provider */
const isLikeNg2Provider = (obj: any) =>
!!((obj.provide || obj.token) && (obj.useValue || obj.useFactory || obj.useExisting || obj.useClass));
/** true if the object looks like a tuple from obj2Tuples */
const isTupleFromObj = (obj: any) =>
!!(obj && obj.val && (isString(obj.val) || isArray(obj.val) || isFunction(obj.val)));
/** extracts the token from a Provider or provide literal */
const getToken = (p: any) => p.provide || p.token;
// prettier-ignore: Given a literal resolve or provider object, returns a Resolvable
const literal2Resolvable = pattern([
[prop('resolveFn'), (p) => new Resolvable(getToken(p), p.resolveFn, p.deps, p.policy)],
[prop('useFactory'), (p) => new Resolvable(getToken(p), p.useFactory, p.deps || p.dependencies, p.policy)],
[prop('useClass'), (p) => new Resolvable(getToken(p), () => new (<any>p.useClass)(), [], p.policy)],
[prop('useValue'), (p) => new Resolvable(getToken(p), () => p.useValue, [], p.policy, p.useValue)],
[prop('useExisting'), (p) => new Resolvable(getToken(p), identity, [p.useExisting], p.policy)],
]);
// prettier-ignore
const tuple2Resolvable = pattern([
[pipe(prop('val'), isString), (tuple: Tuple) => new Resolvable(tuple.token, identity, [tuple.val], tuple.policy)],
[pipe(prop('val'), isArray), (tuple: Tuple) => new Resolvable(tuple.token, tail(<any[]>tuple.val), tuple.val.slice(0, -1), tuple.policy)],
[pipe(prop('val'), isFunction), (tuple: Tuple) => new Resolvable(tuple.token, tuple.val, annotate(tuple.val), tuple.policy)],
]);
// prettier-ignore
const item2Resolvable = <(obj: any) => Resolvable>pattern([
[is(Resolvable), (r: Resolvable) => r],
[isResolveLiteral, literal2Resolvable],
[isLikeNg2Provider, literal2Resolvable],
[isTupleFromObj, tuple2Resolvable],
[val(true), (obj: any) => { throw new Error('Invalid resolve value: ' + stringify(obj)); }, ],
]);
// If resolveBlock is already an array, use it as-is.
// Otherwise, assume it's an object and convert to an Array of tuples
const decl = state.resolve;
const items: any[] = isArray(decl) ? decl : objects2Tuples(decl, state.resolvePolicy || {});
return items.map(item2Resolvable);
}
/**
* A internal global service
*
* StateBuilder is a factory for the internal [[StateObject]] objects.
*
* When you register a state with the [[StateRegistry]], you register a plain old javascript object which
* conforms to the [[StateDeclaration]] interface. This factory takes that object and builds the corresponding
* [[StateObject]] object, which has an API and is used internally.
*
* Custom properties or API may be added to the internal [[StateObject]] object by registering a decorator function
* using the [[builder]] method.
*/
export class StateBuilder {
/** An object that contains all the BuilderFunctions registered, key'd by the name of the State property they build */
private builders: Builders;
constructor(private matcher: StateMatcher, urlMatcherFactory: UrlMatcherFactory) {
const self = this;
const root = () => matcher.find('');
const isRoot = (state: StateObject) => state.name === '';
function parentBuilder(state: StateObject) {
if (isRoot(state)) return null;
return matcher.find(self.parentName(state)) || root();
}
this.builders = {
name: [nameBuilder],
self: [selfBuilder],
parent: [parentBuilder],
data: [dataBuilder],
// Build a URLMatcher if necessary, either via a relative or absolute URL
url: [getUrlBuilder(urlMatcherFactory, root)],
// Keep track of the closest ancestor state that has a URL (i.e. is navigable)
navigable: [getNavigableBuilder(isRoot)],
params: [getParamsBuilder(urlMatcherFactory.paramFactory)],
// Each framework-specific ui-router implementation should define its own `views` builder
// e.g., src/ng1/statebuilders/views.ts
views: [],
// Keep a full path from the root down to this state as this is needed for state activation.
path: [pathBuilder],
// Speed up $state.includes() as it's used a lot
includes: [includesBuilder],
resolvables: [resolvablesBuilder],
};
}
/**
* Registers a [[BuilderFunction]] for a specific [[StateObject]] property (e.g., `parent`, `url`, or `path`).
* More than one BuilderFunction can be registered for a given property.
*
* The BuilderFunction(s) will be used to define the property on any subsequently built [[StateObject]] objects.
*
* @param property The name of the State property being registered for.
* @param fn The BuilderFunction which will be used to build the State property
* @returns a function which deregisters the BuilderFunction
*/
builder(property: string, fn: BuilderFunction): Function;
/**
* Gets the registered builder functions for a given property of [[StateObject]].
*
* @param property The name of the State property being registered for.
* @returns the registered builder(s).
* note: for backwards compatibility, this may be a single builder or an array of builders
*/
builder(property: string): BuilderFunction | BuilderFunction[];
builder(name: string, fn?: BuilderFunction): any {
const builders = this.builders;
const array = builders[name] || [];
// Backwards compat: if only one builder exists, return it, else return whole arary.
if (isString(name) && !isDefined(fn)) return array.length > 1 ? array : array[0];
if (!isString(name) || !isFunction(fn)) return;
builders[name] = array;
builders[name].push(fn);
return () => builders[name].splice(builders[name].indexOf(fn, 1)) && null;
}
/**
* Builds all of the properties on an essentially blank State object, returning a State object which has all its
* properties and API built.
*
* @param state an uninitialized State object
* @returns the built State object
*/
build(state: StateObject): StateObject {
const { matcher, builders } = this;
const parent = this.parentName(state);
if (parent && !matcher.find(parent, undefined, false)) {
return null;
}
for (const key in builders) {
if (!builders.hasOwnProperty(key)) continue;
const chain = builders[key].reduce(
(parentFn: BuilderFunction, step: BuilderFunction) => (_state) => step(_state, parentFn),
noop
);
state[key] = chain(state);
}
return state;
}
parentName(state: StateObject) {
// name = 'foo.bar.baz.**'
const name = state.name || '';
// segments = ['foo', 'bar', 'baz', '.**']
const segments = name.split('.');
// segments = ['foo', 'bar', 'baz']
const lastSegment = segments.pop();
// segments = ['foo', 'bar'] (ignore .** segment for future states)
if (lastSegment === '**') segments.pop();
if (segments.length) {
if (state.parent) {
throw new Error(`States that specify the 'parent:' property should not have a '.' in their name (${name})`);
}
// 'foo.bar'
return segments.join('.');
}
if (!state.parent) return '';
return isString(state.parent) ? state.parent : state.parent.name;
}
name(state: StateObject) {
const name = state.name;
if (name.indexOf('.') !== -1 || !state.parent) return name;
const parentName = isString(state.parent) ? state.parent : state.parent.name;
return parentName ? parentName + '.' + name : name;
}
} | the_stack |
* Enables unmute.
* @param context A reference to the web audio context to "unmute".
*/
function unmute(context:AudioContext):void
{
// Determine page visibility api
type PageVisibilityAPI = { hidden:string, visibilitychange:string };
let pageVisibilityAPI:PageVisibilityAPI;
if (document.hidden !== undefined) pageVisibilityAPI = { hidden:"hidden", visibilitychange:"visibilitychange" };
else if ((<any>document).webkitHidden !== undefined) pageVisibilityAPI = { hidden:"webkitHidden", visibilitychange:"webkitvisibilitychange" };
else if ((<any>document).mozHidden !== undefined) pageVisibilityAPI = { hidden:"mozHidden", visibilitychange:"mozvisibilitychange" };
else if ((<any>document).msHidden !== undefined) pageVisibilityAPI = { hidden:"msHidden", visibilitychange:"msvisibilitychange" };
// Determine if ios
let ua:string = navigator.userAgent.toLowerCase();
let isIOS:boolean = (
(ua.indexOf("iphone") >= 0 && ua.indexOf("like iphone") < 0) ||
(ua.indexOf("ipad") >= 0 && ua.indexOf("like ipad") < 0) ||
(ua.indexOf("ipod") >= 0 && ua.indexOf("like ipod") < 0) ||
(ua.indexOf("mac os x") >= 0 && navigator.maxTouchPoints > 0) // New ipads show up as macs in user agent, but they have a touch screen
);
// Track page state
let isPageActive:boolean = true;
let isPageVisible:boolean = true;
let iosIsPageFocused:boolean = true; // iOS has a buggy page visibility API, luckily it dispatches blur and focus events on the window when vis change events should fire.
// Track desired audio state
let suspendAudio:boolean = false;
let audioUnlockingEvents:string[] = ["click", "contextmenu", "auxclick", "dblclick", "mousedown", "mouseup", "touchend", "keydown", "keyup"];
// Track web audio state
let contextUnlockingEnabled:boolean = false;
// Track html audio state
let tag:HTMLAudioElement;
let tagUnlockingEnabled:boolean = false;
let tagPendingChange:boolean = false;
function contextStateCheck(tryResuming:boolean):void
{
if (context.state == "running")
{
// No need to watch for unlocking events while running
toggleContextUnlocking(false);
// Check if our state matches
if (suspendAudio)
{
// We want to be suspended, we can suspend at any time
context.suspend().then(context_promiseHandler, context_promiseHandler);
}
}
else if (context.state != "closed")
{
// Interrupted or suspended, check if our state matches
if (!suspendAudio)
{
// We want to be running
toggleContextUnlocking(true);
if (tryResuming) context.resume().then(context_promiseHandler, context_promiseHandler);
}
else
{
// We don't want to be running, so no need to watch for unlocking events
toggleContextUnlocking(false);
}
}
}
function toggleContextUnlocking(enable:boolean):void
{
if (contextUnlockingEnabled === enable) return;
contextUnlockingEnabled = enable;
for (let evt of audioUnlockingEvents)
{
if (enable) window.addEventListener(evt, context_unlockingEvent, <any>{ capture: true, passive: true });
else window.removeEventListener(evt, context_unlockingEvent, <any>{ capture: true, passive: true });
}
}
function context_statechange():void
{
contextStateCheck(true);
}
function context_promiseHandler():void
{
contextStateCheck(false);
}
function context_unlockingEvent():void
{
contextStateCheck(true);
}
function tagStateCheck(tryChange:boolean):void
{
// We have a pending state change, let that resolve first
if (tagPendingChange) return;
if (!tag.paused)
{
// No need to watch for unlocking events while running
toggleTagUnlocking(false);
// Check if our state matches
if (suspendAudio)
{
// We want to be suspended, we can suspend at any time
tag.pause(); // instant action, so no need to set as pending
}
}
else
{
// Tag isn't playing, check if our state matches
if (!suspendAudio)
{
// We want to be running
if (tryChange)
{
// Try forcing a change, so stop watching for unlocking events while attempt is in progress
toggleTagUnlocking(false);
// Attempt to play
tagPendingChange = true;
let p:Promise<void>;
try
{
p = tag.play();
if (p) p.then(tag_promiseHandler, tag_promiseHandler);
else
{
tag.addEventListener("playing", tag_promiseHandler);
tag.addEventListener("abort", tag_promiseHandler);
tag.addEventListener("error", tag_promiseHandler);
}
}
catch (err)
{
tag_promiseHandler();
}
}
else
{
// We're not going to try resuming this time, but make sure unlocking events are enabled
toggleTagUnlocking(true);
}
}
else
{
// We don't want to be running, so no need to watch for unlocking events
toggleTagUnlocking(false);
}
}
}
function toggleTagUnlocking(enable:boolean):void
{
if (tagUnlockingEnabled === enable) return;
tagUnlockingEnabled = enable;
for (let evt of audioUnlockingEvents)
{
if (enable) window.addEventListener(evt, tag_unlockingEvent, <any>{ capture: true, passive: true });
else window.removeEventListener(evt, tag_unlockingEvent, <any>{ capture: true, passive: true });
}
}
function tag_promiseHandler():void
{
tag.removeEventListener("playing", tag_promiseHandler);
tag.removeEventListener("abort", tag_promiseHandler);
tag.removeEventListener("error", tag_promiseHandler);
// Tag started playing, so we're not suspended
tagPendingChange = false;
tagStateCheck(false);
}
function tag_unlockingEvent():void
{
tagStateCheck(true);
}
/**
* Called when the page becomes active.
*/
function pageActivated():void
{
suspendAudio = false;
if (tag) tagStateCheck(true); // tag first to ensure media channel start first
contextStateCheck(true);
}
/**
* Called when the page becomes inactive.
*/
function pageDeactivated():void
{
suspendAudio = true;
contextStateCheck(true); // context first to be sure it stops before the tag
if (tag) tagStateCheck(true);
}
/**
* Updates page active state.
*/
function pageStateCheck():void
{
if (isPageVisible && iosIsPageFocused)
{
if (!isPageActive)
{
isPageActive = true;
pageActivated();
}
}
else
{
if (isPageActive)
{
isPageActive = false;
pageDeactivated();
}
}
}
/**
* Handle visibility api events.
*/
function doc_visChange():void
{
if (pageVisibilityAPI)
{
if ((<any>document)[pageVisibilityAPI.hidden] == isPageActive)
{
isPageVisible = !(<any>document)[pageVisibilityAPI.hidden];
pageStateCheck();
}
}
}
/**
* Handles blur events (ios only).
*/
function win_focusChange(evt?:Event):void
{
if (evt && evt.target !== window) return;
if (document.hasFocus())
{
if (iosIsPageFocused) return;
iosIsPageFocused = true;
pageStateCheck();
}
else
{
if (!iosIsPageFocused) return;
iosIsPageFocused = false;
pageStateCheck();
}
}
/**
* A utility function for decompressing the base64 silence string.
* @param c The number of times the string is repeated in the string segment.
* @param a The string to repeat.
*/
function poorManHuffman(c:number, a:string):string { let e:string; for (e = a; c > 1; c--) e += a; return e; }
// Watch for tag state changes and check initial state
if (isIOS)
{
// Is ios, we need to play an html track in the background and disable the widget
// NOTE: media widget / airplay MUST be disabled with this super gross hack to create the audio tag, setting the attribute in js doesn't work
let tmp:HTMLDivElement = document.createElement("div");
tmp.innerHTML = "<audio x-webkit-airplay='deny'></audio>";
tag = <any>tmp.children.item(0);
tag.controls = false;
(<any>tag).disableRemotePlayback = true; // Airplay like controls on other devices, prevents casting of the tag
tag.preload = "auto";
// Set the src to a short bit of url encoded as a silent mp3
// NOTE The silence MP3 must be high quality, when web audio sounds are played in parallel the web audio sound is mixed to match the bitrate of the html sound
// 0.01 seconds of silence VBR220-260 Joint Stereo 859B
//tag.src = "data:audio/mpeg;base64,//uQxAAAAAAAAAAAAAAAAAAAAAAAWGluZwAAAA8AAAACAAACcQCAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICA//////////////////////////////////////////////////////////////////8AAABhTEFNRTMuMTAwA8MAAAAAAAAAABQgJAUHQQAB9AAAAnGMHkkIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//sQxAADgnABGiAAQBCqgCRMAAgEAH///////////////7+n/9FTuQsQH//////2NG0jWUGlio5gLQTOtIoeR2WX////X4s9Atb/JRVCbBUpeRUq//////////////////9RUi0f2jn/+xDECgPCjAEQAABN4AAANIAAAAQVTEFNRTMuMTAwVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVQ==";
// The str below is a "compressed" version using poor mans huffman encoding, saves about 0.5kb
tag.src = "data:audio/mpeg;base64,//uQx" + poorManHuffman(23, "A") + "WGluZwAAAA8AAAACAAACcQCA" + poorManHuffman(16, "gICA") + poorManHuffman(66, "/") + "8AAABhTEFNRTMuMTAwA8MAAAAAAAAAABQgJAUHQQAB9AAAAnGMHkkI" + poorManHuffman(320, "A") + "//sQxAADgnABGiAAQBCqgCRMAAgEAH" + poorManHuffman(15, "/") + "7+n/9FTuQsQH//////2NG0jWUGlio5gLQTOtIoeR2WX////X4s9Atb/JRVCbBUpeRUq" + poorManHuffman(18, "/") + "9RUi0f2jn/+xDECgPCjAEQAABN4AAANIAAAAQVTEFNRTMuMTAw" + poorManHuffman(97, "V") + "Q==";
tag.loop = true;
tag.load();
// Try to play right off the bat
tagStateCheck(true);
}
// Watch for context state changes and check initial state
context.onstatechange = context_statechange; // NOTE: the onstatechange callback property is more widely supported than the statechange event context.addEventListener("statechange", context_statechange);
contextStateCheck(false);
// Watch for page state changes and check initial page state
if (pageVisibilityAPI) document.addEventListener(pageVisibilityAPI.visibilitychange, doc_visChange, true);
if (isIOS)
{
// Watch for blur / focus events on ios because it doesn't dispatch vis change events properly
window.addEventListener("focus", win_focusChange, true);
window.addEventListener("blur", win_focusChange, true);
}
doc_visChange();
if (isIOS) win_focusChange();
} | the_stack |
import { HttpClient, HttpResponse, HttpEvent } from '@angular/common/http';
import { Inject, Injectable, Optional } from '@angular/core';
import { APIClientInterface } from './api-client.interface';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { USE_DOMAIN, USE_HTTP_OPTIONS, APIClient } from './api-client.service';
import { DefaultHttpOptions, HttpOptions } from './types';
import * as models from './models';
import * as guards from './guards';
@Injectable()
export class GuardedAPIClient extends APIClient implements APIClientInterface {
constructor(
readonly httpClient: HttpClient,
@Optional() @Inject(USE_DOMAIN) domain?: string,
@Optional() @Inject(USE_HTTP_OPTIONS) options?: DefaultHttpOptions,
) {
super(httpClient, domain, options);
}
/**
* Get items list
* Response generated for [ 200 ] HTTP response code.
*/
getItems(
args: Exclude<APIClientInterface['getItemsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.ItemList>;
getItems(
args: Exclude<APIClientInterface['getItemsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.ItemList>>;
getItems(
args: Exclude<APIClientInterface['getItemsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.ItemList>>;
getItems(
args: Exclude<APIClientInterface['getItemsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.ItemList | HttpResponse<models.ItemList> | HttpEvent<models.ItemList>> {
return super.getItems(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isItemList(res) || console.error(`TypeGuard for response 'models.ItemList' caught inconsistency.`, res)));
}
/**
* Get item models list
* Response generated for [ 200 ] HTTP response code.
*/
getItemModels(
args: Exclude<APIClientInterface['getItemModelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<object>;
getItemModels(
args: Exclude<APIClientInterface['getItemModelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<object>>;
getItemModels(
args: Exclude<APIClientInterface['getItemModelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<object>>;
getItemModels(
args: Exclude<APIClientInterface['getItemModelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<object | HttpResponse<object> | HttpEvent<object>> {
return super.getItemModels(args, requestHttpOptions, observe)
.pipe(tap((res: any) => typeof res === 'object' || console.error(`TypeGuard for response 'object' caught inconsistency.`, res)));
}
/**
* Response generated for [ 200 ] HTTP response code.
*/
getPetsId(
args: Exclude<APIClientInterface['getPetsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Pet[]>;
getPetsId(
args: Exclude<APIClientInterface['getPetsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Pet[]>>;
getPetsId(
args: Exclude<APIClientInterface['getPetsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Pet[]>>;
getPetsId(
args: Exclude<APIClientInterface['getPetsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Pet[] | HttpResponse<models.Pet[]> | HttpEvent<models.Pet[]>> {
return super.getPetsId(args, requestHttpOptions, observe)
.pipe(tap((res: any) => ( Array.isArray(res) && res.every((item: any) => guards.isPet(item)) ) || console.error(`TypeGuard for response 'models.Pet[]' caught inconsistency.`, res)));
}
/**
* Response generated for [ 200 ] HTTP response code.
*/
deletePetsId(
args: Exclude<APIClientInterface['deletePetsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deletePetsId(
args: Exclude<APIClientInterface['deletePetsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deletePetsId(
args: Exclude<APIClientInterface['deletePetsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deletePetsId(
args: Exclude<APIClientInterface['deletePetsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.deletePetsId(args, requestHttpOptions, observe);
}
/**
* Get details of the game.
* Default id param should be overridden to string
* Response generated for [ 200 ] HTTP response code.
*/
getPetsWithDefaultIdParamId(
args: Exclude<APIClientInterface['getPetsWithDefaultIdParamIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Pet>;
getPetsWithDefaultIdParamId(
args: Exclude<APIClientInterface['getPetsWithDefaultIdParamIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Pet>>;
getPetsWithDefaultIdParamId(
args: Exclude<APIClientInterface['getPetsWithDefaultIdParamIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Pet>>;
getPetsWithDefaultIdParamId(
args: Exclude<APIClientInterface['getPetsWithDefaultIdParamIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Pet | HttpResponse<models.Pet> | HttpEvent<models.Pet>> {
return super.getPetsWithDefaultIdParamId(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isPet(res) || console.error(`TypeGuard for response 'models.Pet' caught inconsistency.`, res)));
}
/**
* Default id param should be number and not string
* Response generated for [ 200 ] HTTP response code.
*/
patchPetsWithDefaultIdParamId(
args: Exclude<APIClientInterface['patchPetsWithDefaultIdParamIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
patchPetsWithDefaultIdParamId(
args: Exclude<APIClientInterface['patchPetsWithDefaultIdParamIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
patchPetsWithDefaultIdParamId(
args: Exclude<APIClientInterface['patchPetsWithDefaultIdParamIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
patchPetsWithDefaultIdParamId(
args: Exclude<APIClientInterface['patchPetsWithDefaultIdParamIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.patchPetsWithDefaultIdParamId(args, requestHttpOptions, observe);
}
/**
* Response generated for [ 200 ] HTTP response code.
*/
getCustomers(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<(models.Customer[]) | null>;
getCustomers(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<(models.Customer[]) | null>>;
getCustomers(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<(models.Customer[]) | null>>;
getCustomers(
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<(models.Customer[]) | null | HttpResponse<(models.Customer[]) | null> | HttpEvent<(models.Customer[]) | null>> {
return super.getCustomers(requestHttpOptions, observe)
.pipe(tap((res: any) => (res == null || ( Array.isArray(res) && res.every((item: any) => guards.isCustomer(item)) )) || console.error(`TypeGuard for response '(models.Customer[]) | null' caught inconsistency.`, res)));
}
/**
* Response generated for [ 200 ] HTTP response code.
*/
getDictionaries(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Dictionary>;
getDictionaries(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Dictionary>>;
getDictionaries(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Dictionary>>;
getDictionaries(
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Dictionary | HttpResponse<models.Dictionary> | HttpEvent<models.Dictionary>> {
return super.getDictionaries(requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isDictionary(res) || console.error(`TypeGuard for response 'models.Dictionary' caught inconsistency.`, res)));
}
/**
* Response generated for [ 200 ] HTTP response code.
*/
getFileId(
args: Exclude<APIClientInterface['getFileIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<File>;
getFileId(
args: Exclude<APIClientInterface['getFileIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<File>>;
getFileId(
args: Exclude<APIClientInterface['getFileIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<File>>;
getFileId(
args: Exclude<APIClientInterface['getFileIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<File | HttpResponse<File> | HttpEvent<File>> {
return super.getFileId(args, requestHttpOptions, observe)
.pipe(tap((res: any) => res instanceof File || console.error(`TypeGuard for response 'File' caught inconsistency.`, res)));
}
/**
* Response generated for [ 200 ] HTTP response code.
*/
getRandomObject(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<object>;
getRandomObject(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<object>>;
getRandomObject(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<object>>;
getRandomObject(
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<object | HttpResponse<object> | HttpEvent<object>> {
return super.getRandomObject(requestHttpOptions, observe)
.pipe(tap((res: any) => typeof res === 'object' || console.error(`TypeGuard for response 'object' caught inconsistency.`, res)));
}
/**
* Response generated for [ 200 ] HTTP response code.
*/
getRandomModel(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<object>;
getRandomModel(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<object>>;
getRandomModel(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<object>>;
getRandomModel(
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<object | HttpResponse<object> | HttpEvent<object>> {
return super.getRandomModel(requestHttpOptions, observe)
.pipe(tap((res: any) => typeof res === 'object' || console.error(`TypeGuard for response 'object' caught inconsistency.`, res)));
}
/**
* Response generated for [ 200 ] HTTP response code.
*/
getRandomString(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<string>;
getRandomString(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<string>>;
getRandomString(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<string>>;
getRandomString(
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<string | HttpResponse<string> | HttpEvent<string>> {
return super.getRandomString(requestHttpOptions, observe)
.pipe(tap((res: any) => typeof res === 'string' || console.error(`TypeGuard for response 'string' caught inconsistency.`, res)));
}
/**
* Response generated for [ 200 ] HTTP response code.
*/
getDictionary(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<{ [key: string]: number }>;
getDictionary(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<{ [key: string]: number }>>;
getDictionary(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<{ [key: string]: number }>>;
getDictionary(
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<{ [key: string]: number } | HttpResponse<{ [key: string]: number }> | HttpEvent<{ [key: string]: number }>> {
return super.getDictionary(requestHttpOptions, observe)
.pipe(tap((res: any) => Object.values(res).every((value: any) => typeof value === 'number') || console.error(`TypeGuard for response '{ [key: string]: number }' caught inconsistency.`, res)));
}
/**
* Response generated for [ 200 ] HTTP response code.
*/
getArrayOfDictionaries(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<{ [key: string]: number }[]>;
getArrayOfDictionaries(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<{ [key: string]: number }[]>>;
getArrayOfDictionaries(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<{ [key: string]: number }[]>>;
getArrayOfDictionaries(
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<{ [key: string]: number }[] | HttpResponse<{ [key: string]: number }[]> | HttpEvent<{ [key: string]: number }[]>> {
return super.getArrayOfDictionaries(requestHttpOptions, observe)
.pipe(tap((res: any) => ( Array.isArray(res) && res.every((item: any) => Object.values(item).every((value: any) => typeof value === 'number')) ) || console.error(`TypeGuard for response '{ [key: string]: number }[]' caught inconsistency.`, res)));
}
/**
* Commits a transaction, while optionally updating documents.
* Response generated for [ 200 ] HTTP response code.
*/
firestoreProjectsDatabasesDocumentsCommit(
args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsCommitParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Dictionary>;
firestoreProjectsDatabasesDocumentsCommit(
args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsCommitParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Dictionary>>;
firestoreProjectsDatabasesDocumentsCommit(
args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsCommitParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Dictionary>>;
firestoreProjectsDatabasesDocumentsCommit(
args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsCommitParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Dictionary | HttpResponse<models.Dictionary> | HttpEvent<models.Dictionary>> {
return super.firestoreProjectsDatabasesDocumentsCommit(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isDictionary(res) || console.error(`TypeGuard for response 'models.Dictionary' caught inconsistency.`, res)));
}
/**
* Create a custom Blob.
* Response generated for [ 201 ] HTTP response code.
*/
postReposOwnerRepoGitBlobs(
args: Exclude<APIClientInterface['postReposOwnerRepoGitBlobsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Blob[]>;
postReposOwnerRepoGitBlobs(
args: Exclude<APIClientInterface['postReposOwnerRepoGitBlobsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Blob[]>>;
postReposOwnerRepoGitBlobs(
args: Exclude<APIClientInterface['postReposOwnerRepoGitBlobsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Blob[]>>;
postReposOwnerRepoGitBlobs(
args: Exclude<APIClientInterface['postReposOwnerRepoGitBlobsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Blob[] | HttpResponse<models.Blob[]> | HttpEvent<models.Blob[]>> {
return super.postReposOwnerRepoGitBlobs(args, requestHttpOptions, observe)
.pipe(tap((res: any) => ( Array.isArray(res) && res.every((item: any) => guards.isBlob(item)) ) || console.error(`TypeGuard for response 'models.Blob[]' caught inconsistency.`, res)));
}
/**
* Get standard File
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoGitBlobsShaCode(
args: Exclude<APIClientInterface['getReposOwnerRepoGitBlobsShaCodeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<File>;
getReposOwnerRepoGitBlobsShaCode(
args: Exclude<APIClientInterface['getReposOwnerRepoGitBlobsShaCodeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<File>>;
getReposOwnerRepoGitBlobsShaCode(
args: Exclude<APIClientInterface['getReposOwnerRepoGitBlobsShaCodeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<File>>;
getReposOwnerRepoGitBlobsShaCode(
args: Exclude<APIClientInterface['getReposOwnerRepoGitBlobsShaCodeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<File | HttpResponse<File> | HttpEvent<File>> {
return super.getReposOwnerRepoGitBlobsShaCode(args, requestHttpOptions, observe)
.pipe(tap((res: any) => res instanceof File || console.error(`TypeGuard for response 'File' caught inconsistency.`, res)));
}
} | the_stack |
module TDev {
export interface JsonProgress {
kind: string;
userid: string;
progressid: string;
//guid?: string;
index: number;
completed?: number;
}
export interface JsonProgressStep {
index: number;
text: string;
count: number;
minDuration?: number;
medDuration?: number;
medModalDuration?: number;
medPlayDuration?: number;
}
export interface JsonProgressStats {
kind: string; // progressstats
publicationId: string;
count: number;
steps: JsonProgressStep[];
}
export interface JsonCapability
{
name: string;
iconurl: string;
}
export interface JsonIdObject
{
kind:string;
id:string; // id
url:string; // website for human consumption
}
export interface JsonPublication extends JsonIdObject
{
time:number;// time when publication was created
userid:string; // user id of user who published
userscore : number;
username:string;
userhaspicture:boolean;
}
// lite only
export interface JsonNotification extends JsonPubOnPub
{
notificationkind: string;
// if publicationkind == 'review', this will hold the script data
supplementalid: string;
supplementalkind: string;
supplementalname: string;
}
export interface JsonDocument
{
url:string; // website for human consumption
kind:string;
name: string; // document name
abstract: string; // document description
mimetype: string; // mimetype of document given by url
views: number; // approximate number of document views
thumburl: string;
}
export interface JsonArt extends JsonPublication
{
name: string;
description: string;
// if picture
pictureurl: string;
mediumthumburl: string;
thumburl: string;
flags: string[];
// if sound
wavurl: string;
aacurl: string;
bloburl?: string;
arttype?: string;
}
export interface JsonUser extends JsonIdObject
{
name:string; // user name
about:string; // user's about-me text
features:number; // number of features used by that user
receivedpositivereviews: number; // number of ♥ given to this user's scripts and comments
activedays: number;
subscribers:number; // number of users subscribed to this user
score:number; // overall score of this user
haspicture:boolean; // whether this use has a picture
isadult?:boolean;
}
export interface JsonScore {
points: number;
}
export interface JsonReceivedPositiveReviewsScore extends JsonScore {
scripts : JsonScript[];
}
export interface JsonFeature {
name:string;
title:string;
text:string;
count:number;
}
export interface JsonLanguageFeaturesScore extends JsonScore {
features: JsonFeature[];
}
export interface JsonUserScore
{
receivedPositiveReviews : JsonReceivedPositiveReviewsScore;
receivedSubscriptions : JsonScore;
languageFeatures : JsonLanguageFeaturesScore;
activeDays : JsonScore;
}
export interface JsonGroup extends JsonPublication {
name: string;
description: string;
isrestricted : boolean;
isclass: boolean;
pictureid : string;
comments : number;
positivereviews : number;
subscribers: number;
}
export interface JsonCode {
kind: string; // “code”
time: number; // creation time in seconds since 1970
expiration: number; // in seconds since 1970
userid: string; // creator
username: string;
userscore: number;
userhaspicture: boolean;
verb: string; // “JoinGroup” for group invitation codes
data: string; // groupid for group invitation codes
credit?: number;
}
export interface JsonScriptMeta {
youtube?: string;
instagram?: string;
}
export interface JsonScript extends JsonPublication
{
name:string;
description:string;
icon:string; // script icon name
iconbackground:string; // script icon background color in HTML notation
iconurl: string; // script icon picture url (obsolete)
iconArtId?: string; // art id for script icon
splashArtId?: string; // art id for script splash screen
positivereviews:number; // number of users who added ♥ to this script
cumulativepositivereviews:number;
comments:number; // number of discussion threads
subscribers:number;
capabilities:JsonCapability[]; // array of capabilities used by this script; each capability has two fields: name, iconurl
flows:any[]; // ???
haserrors:boolean; // whether this script has any compilation errors
rootid:string; // refers to the earliest script along the chain of script bases
baseid?:string; // lite
updateid:string; // refers to the latest published successor (along any path) of that script with the same name and from the same user
updatetime:number;
ishidden:boolean; // whether the user has indicated that this script should be hidden
islibrary:boolean; // whether the user has indicated that this script is a reusable library
useCppCompiler: boolean; // whether th euser has indicated that this script requires to use the C++ compiler
installations:number; // an approximation of how many TouchDevelop users have currently installed this script
runs:number; // an estimate of how often users have run this script
platforms:string[];
userplatform?:string[];
screenshotthumburl:string;
screenshoturl:string;
mergeids:string[];
editor?: string; // convention where empty means touchdevelop, for backwards compatibility
meta?: JsonScriptMeta; // only in lite, bag of metadata
updateroot: string; // lite-only
unmoderated?: boolean;
noexternallinks?:boolean;
promo?:any;
lastpointer?:string;
}
export interface JsonHistoryItem
{
kind: string; // InstalledScriptHistory
time: number; // seconds since 1970; indicates when code was backed up
historyid: string; // identifier of this item
scriptstatus: string; // “published”, “unpublished”
scriptname: string; // script name, mined from the script code
scriptdescription: string; // script description, mined from the script code
scriptid: string; // publication id if scriptstatus==”published”
scriptsize?: number;
isactive: boolean; // whether this history item is the currently active backup
meta: any;
entryNo?: number; // assigned when the thing is displayed
}
export function getScriptHeartCount(j:JsonScript)
{
if (!j) return -1;
if (j.updateid && j.updateid == j.id) return j.cumulativepositivereviews;
else return j.positivereviews || 0;
}
// in-memory patch of cached script information which will be overriden on the next sync
export function patchScriptHeartCount(j: JsonScript, d : number)
{
if (!j) return -1;
if (j.updateid && j.updateid == j.id) j.cumulativepositivereviews = d;
else j.positivereviews = d;
}
export interface JsonPubOnPub extends JsonPublication
{
publicationid:string; // script id that is being commented on
publicationname:string; // script name
publicationkind:string; //
}
export interface JsonPointer extends JsonPublication
{
path: string; // "td/contents"
scriptid: string; // where is it pointing to
artid: string; // where is it pointing to
redirect: string; // full URL or /something/on/the/same/host
description: string; // set to script title from the client
htmlartid:string;
scriptname: string;
scriptdescription: string;
breadcrumbtitle: string;
parentpath: string;
oldscriptid?:string;
}
export interface JsonComment extends JsonPubOnPub
{
text:string; // comment text
nestinglevel:number; // 0 or 1
positivereviews:number; // number of users who added ♥ to this comment
comments:number; // number of nested replies available for this comment
assignedtoid?: string;
resolved?: string;
}
export interface JsonAbuseReport extends JsonPubOnPub
{
text:string; // report text
resolution:string;
publicationuserid:string;
// this are available to moderators only
usernumreports?:number;
publicationnumabuses?:number;
publicationusernumabuses?:number;
}
export interface JsonChannel extends JsonPublication
{
name: string;
description:string;
pictureid : string;
comments : number;
positivereviews : number;
}
export interface JsonReview extends JsonPubOnPub
{
ispositive: boolean;
}
export interface JsonRelease extends JsonPublication
{
name: string;
releaseid:string;
labels:JsonReleaseLabel[];
buildnumber: number;
version: string;
commit: string;
branch: string;
}
export interface JsonReleaseLabel
{
name: string;
userid: string;
time: number;
releaseid: string;
}
export interface JsonEtag
{
id:string;
kind:string;
ETag:string;
}
export interface JsonList
{
items:JsonIdObject[];
etags:JsonEtag[];
continuation:string;
}
export interface JsonTag extends JsonIdObject
{
time:number;
name:string;
category:string;
description:string;
instances:number;
topscreenshotids:string[];
}
export interface JsonScreenShot extends JsonPubOnPub
{
pictureurl:string; // screenshot picture url
thumburl:string; // screenshot picture thumb url
}
export interface JsonVideoSource {
// poster to display the video
poster?: string;
// locale of this video source
srclang: string;
// video url
src: string;
// video mime type
type: string;
}
export interface JsonVideoTrack {
// local of this track
srclang: string;
// url of the track
src: string;
// kind, by default subtitles
kind?: string;
// label shown to user
label?: string;
}
// information to create a localized video with cc
export interface JsonVideo {
// poster to display the video
poster: string;
// closed caption tracks
tracks?: JsonVideoTrack[];
// localized video streams
sources: JsonVideoSource[];
}
export interface CanDeleteResponse {
publicationkind: string;
publicationname: string;
publicationuserid: string;
candelete:boolean;
candeletekind:boolean;
canmanage:boolean;
hasabusereports:boolean;
}
export interface SocialNetwork {
id: string;
name: string;
description: string;
parseIds: (text: string, inmeta?:boolean) => string[];
idToUrl: (id: string) => string;
idToHTMLAsync?: (id: string) => Promise; // HTMLElement;
}
var oembedCache: StringMap<HTML.OEmbed> = {};
var _socialNetworks: SocialNetwork[] = [
{
id: "art",
name: "TouchDevelop Art",
description: lf("Cover art ({0}/...)", Cloud.config.primaryCdnUrl),
parseIds: text => {
var links = [];
if (text)
text.replace(/https?:\/\/.*\/pub\/([a-z]+)/gi,(m, id) => {
var ytid = id;
links.push(id)
});
return links;
},
idToUrl: id => Cloud.config.primaryCdnUrl + "/pub/" + id,
idToHTMLAsync: id => Promise.as(HTML.mkImg(Cloud.config.primaryCdnUrl + "/pub/" + id, '', lf("open")))
}, {
id: "youtube",
name: "YouTube",
description: lf("YouTube video (https://youtu.be/...)"),
parseIds: text => {
var links = [];
if (text)
text.replace(/https?:\/\/(youtu\.be\/([^\s]+))|(www\.youtube\.com\/watch\?v=([^\s]+))/gi,(m, m2, id1, m3, id2) => {
var ytid = id1 || id2;
links.push(ytid);
});
return links;
},
idToUrl: id => 'https://youtu.be/' + id,
idToHTMLAsync: id => Promise.as(HTML.mkYouTubePlayer(id))
}, {
id: "videoptr",
name: "TouchDevelop Video",
description: lf("Touch Develop video (/td/videos/...)"),
parseIds: (text, ismeta) => {
var pref = Cloud.getServiceUrl().replace(/(test|stage|live)/, "www")
var m = /^(https:\/\/[^\/]+)\/(\S+)/.exec(text)
if (!ismeta && (!m || m[1] != pref)) return []
if (m)
text = m[2]
text = text.replace(/^\/+/, "")
text = text.replace(/^embed\//, "")
text = text.replace(/[^a-z0-9-\/]/g, "-")
return [text]
},
idToUrl: id => Cloud.getServiceUrl().replace(/(test|stage|live)/, "www") + "/embed/" + id,
idToHTMLAsync: id => {
id = id.replace(/[^a-z0-9-\/]/g, "-")
return Promise.as(HTML.mkLazyVideoPlayer(
Util.fmt("{0}/{1}/thumb", Cloud.getServiceUrl(), id),
Util.fmt("{0}/embed/{1}", Cloud.getServiceUrl(), id)))
}
}, {
id: "bbc",
name: "BBC Video",
description: lf("BBC video (https://files.microbit.co.uk/clips/...)"),
parseIds: (text, ismeta) => {
var m = /^(https:\/\/[^\/]+)\/(.*)/.exec(text)
if (!ismeta && (!m || m[1] != "https://files.microbit.co.uk")) return []
if (m)
text = m[2]
text = text.replace(/^\/+/, "")
text = text.replace(/^clips\//, "")
text = text.replace(/[^a-z0-9-\/]/g, "-")
return [text]
},
idToUrl: id => "https://files.microbit.co.uk/clips/" + id,
idToHTMLAsync: id => {
id = id.replace(/[^a-z0-9-\/]/g, "-")
return Promise.as(HTML.mkLazyVideoPlayer(
Util.fmt("https://files.microbit.co.uk/clips/{0}/thumb", id),
Util.fmt("https://files.microbit.co.uk/clips/{0}/embed", id)))
}
}, {
id: "vimeo",
name: "Vimeo",
description: lf("vimeo video (https://vimeo.com/...)"),
parseIds: text => {
var links = [];
if (text)
text.replace(/https?:\/\/vimeo\.com\/\S*?(\d{6,})/gi,(m, id) => {
links.push(id);
});
return links;
},
idToUrl: id => "https://vimeo.com/" + id,
idToHTMLAsync: (id: string): Promise => {
return Promise.as(HTML.mkLazyVideoPlayer(
Util.fmt("{0}/thumbnail/512/vimeo/{1:uri}", Cloud.getServiceUrl(), id),
"https://player.vimeo.com/video/" + id))
},
}, {
id: "instagram",
name: "Instagram",
description: lf("Instagram photo (https://instagram.com/p/...)"),
parseIds: text => {
var links = [];
if (text)
text.replace(/https?:\/\/instagram\.com\/p\/([a-z0-9]+)\/?/gi,(m, id) => {
links.push(id);
});
return links;
},
idToUrl: id => 'https://instagram.com/p/' + id + '/',
/* CORS issue
idToHTMLAsync: id => Util.httpGetJsonAsync('https://api.instagram.com/oembed?omit_script=true&url=https://instagram.com/p/' + id + '/')
.then(oembed => HTML.mkOEmbed('https://instagram.com/p/' + id + '/', oembed),
e => {
Util.log('oembed error:' + e);
return null;
})
*/
},
{
id: "vine",
name: "Vine",
description: lf("Vine animation (https://vine.co/v/...)"),
parseIds: text => {
var links = [];
if (text)
text.replace(/https?:\/\/vine\.co\/v\/([a-z0-9]+)\/?/gi,(m, id) => {
links.push(id);
});
return links;
},
idToUrl: id => 'https://vine.co/v/' + id,
/* CORS issue
idToHTMLAsync: id => Util.httpGetJsonAsync('https://vine.co/oembed.json?omit_script=true&url=https://vine.co/v/' + id)
.then(oembed => HTML.mkOEmbed('https://vine.co/v/' + id, oembed),
e => {
Util.log('oembed error:' + e);
return null;
})
*/
},
{
id: "twitter",
name: "Twitter",
description: lf("Twitter picture or tweet (https://twitter.com/.../status/...)"),
parseIds: text => {
var links = [];
if (text)
text.replace(/https:\/\/twitter\.com\/[^\/]+\/status\/[0-9]+\/?/gi,(m) => {
links.push(m);
});
return links;
},
idToUrl: id => id,
/* CORS issue
idToHTMLAsync: id => Util.httpGetJsonAsync('https://vine.co/oembed.json?omit_script=true&url=https://vine.co/v/' + id)
.then(oembed => HTML.mkOEmbed('https://vine.co/v/' + id, oembed),
e => {
Util.log('oembed error:' + e);
return null;
})
*/
},
];
export function socialNetworks(widgets : Cloud.EditorWidgets) : SocialNetwork[] {
if (!Cloud.hasPermission("post-script-meta"))
return [];
return _socialNetworks.filter(sn => !!widgets["socialNetwork" + sn.id]);
}
export class MdComments
{
public userid:string;
public scriptid: string;
public print = false;
public showCopy = true;
public useSVG = true;
public useExternalLinks = false;
public blockExternalLinks:boolean = undefined;
public pointerHelp = true;
public allowLinks = true;
public allowImages = true;
public allowVideos = true;
public designTime = false;
public forWeb = false;
public relativeLinks = false;
private currComment:AST.Comment;
constructor(public renderer:Renderer = null, private libName:string = null)
{
}
public serviceUrlOr(path:string, local:string)
{
if (this.useExternalLinks)
return this.relativeLinks ? path : Cloud.getServiceUrl() + path
else
return local
}
public topicLink(id:string)
{
return this.serviceUrlOr(Cloud.config.topicPath, Cloud.config.topicPath) + MdComments.shrink(id);
}
public appLink(id:string)
{
return this.serviceUrlOr("/app/", "") + id
}
static shrink(s:string)
{
return s ? s.replace(/[^A-Za-z0-9]/g, "").toLowerCase() : "";
}
static error(msg:string)
{
return "<span class='md-error'>" + Util.htmlEscape(msg) + " </span>";
}
static proxyVideos(v: JsonVideo) {
v.poster = HTML.proxyResource(v.poster);
v.sources.forEach(s => {
s.poster = HTML.proxyResource(s.poster);
s.src = HTML.proxyResource(s.src);
})
v.tracks.forEach(t => {
t.src = HTML.proxyResource(t.src);
})
}
static attachVideoHandlers(e: HTMLElement, autoPlay: boolean): void {
if (!Browser.directionAuto) {
Util.toArray(e.getElementsByClassName('md-tutorial')).forEach((v: HTMLElement) => dirAuto(v));
Util.toArray(e.getElementsByClassName('md-box-avatar-body')).forEach((v: HTMLElement) => dirAuto(v));
}
/*
var sns = socialNetworks(widgets).filter(sn => !!sn.idToHTMLAsync);
Util.toArray(e.getElementsByTagName('a')).forEach((v: HTMLAnchorElement) => {
sns.forEach(sn => sn.parseIds(v.href).forEach(id => {
v.style.display = 'none';
sn.idToHTMLAsync(id).done(pl => v.parentElement.insertBefore(pl, v));
}));
});
*/
Util.toArray(e.getElementsByClassName('md-video-link')).forEach((v: HTMLElement) => {
if (v.hasAttribute("data-playerurl")) v.withClick(() => v.innerHTML = HTML.mkVideoIframe(v.getAttribute("data-playerurl")));
else if (v.hasAttribute("data-video")) {
var lang = Util.getTranslationLanguage();
var jsvideo = <JsonVideo>JSON.parse(decodeURIComponent(v.getAttribute("data-video")));
if (!jsvideo) {
v.setChildren(div('', lf(":( invalid in video information")));
return;
}
// proxy all video resources
MdComments.proxyVideos(jsvideo);
var jssource = MdComments.findBestSource(jsvideo.sources);
if (!jssource) {
v.setChildren(div('', lf(":( could not find any video source")));
return;
}
var video = <HTMLVideoElement>createElement("video");
(<any>video).crossOrigin = "anonymous";
video.width = 300;
video.height = 150;
video.controls = true;
video.autoplay = autoPlay; // option?
video.preload = autoPlay ? "auto" : "none";
video.poster = jssource.poster || jsvideo.poster;
var source = <HTMLSourceElement>createElement("source");
source.src = jssource.src;
source.type = jssource.type;
video.appendChild(source);
if (jsvideo.tracks && jsvideo.tracks.length > 0) {
Util.log('loading tracks');
// dynamic tracks?
if (!Browser.videoTracks) {
var jstrack = MdComments.findBestTrack(jsvideo.tracks);
Util.log('best track: ' + jstrack.label);
Util.httpGetTextAsync(jstrack.src)
.done(wtt => {
var cues = HTML.parseWtt(wtt);
Util.log('found {0} cues', cues.length);
if (cues.length > 0) {
if (video.addTextTrack) {
var track = video.addTextTrack(jstrack.kind || "subtitles", jstrack.label || jstrack.srclang, jstrack.srclang);
cues.forEach(cue => track.addCue((<any>TextTrackCue)(cue.startTime, cue.endTime, cue.message)));
track.mode = track.SHOWING;
}
else {
var caption = <HTMLSpanElement>document.createElement('span');
caption.className = 'videoCaption';
var lastCue = undefined;
video.ontimeupdate = ev => {
var t = video.currentTime;
// shortcut
if (lastCue && lastCue.startTime <= t && t <= lastCue.endTime) return;
lastCue = undefined;
var i = 0;
while (i < cues.length) {
if (cues[i].startTime <= t && t <= cues[i].endTime) {
lastCue = cues[i];
break;
}
if (cues[i].endTime > t) break;
i++;
}
if (lastCue) {
caption.innerText = lastCue.message;
caption.style.opacity = "1.0";
}
else {
caption.style.opacity = "0.0";
}
};
v.classList.add('videoOuter');
v.setChildren([video, caption]);
}
}
}, e => {
// silently fail
Util.log('wtt: failed to load caption: ' + ((<any>e).message || ""));
});
} else {
video.appendChildren(jsvideo.tracks.map((jstrack, i) => {
var track = <HTMLTrackElement>createElement("track");
if (i == 0) track.default = true;
track.src = jstrack.src;
track.kind = jstrack.kind || "subtitles";
if (jstrack.srclang)
track.srclang = jstrack.srclang;
track.label = jstrack.label || jstrack.srclang;
return track
}));
}
}
v.setChildren(video);
} else if (v.hasAttribute("data-videosrc")) {
var vtid = v.getAttribute("data-videosrc");
var pid = v.getAttribute("data-videoposter");
if (autoPlay) {
var video = <HTMLVideoElement>createElement("video");
(<any>video).crossOrigin = "anonymous";
video.width = 300;
video.height = 150;
video.controls = true;
video.autoplay = true;
video.src = decodeURI(vtid);
video.poster = decodeURI(pid);
v.setChildren(video);
} else {
v.withClick(() => {
var video = <HTMLVideoElement>createElement("video");
(<any>video).crossOrigin = "anonymous";
video.width = 300;
video.height = 150;
video.controls = true;
video.autoplay = true;
video.src = decodeURI(vtid);
video.poster = decodeURI(pid);
v.setChildren(video);
v.withClick(() => { });
});
}
}
});
}
static findBestSource(sources: JsonVideoSource[]): JsonVideoSource {
if (!sources) return undefined;
var lang = Util.getTranslationLanguage() || "en";
var video: JsonVideoSource = sources.filter(t => t.srclang == lang)[0];
if (video) return video;
lang = lang.substr(0, 2);
video = sources.filter(t => t.srclang == lang)[0];
if (video) return video;
// bail out
return sources[0];
}
static findBestTrack(tracks: JsonVideoTrack[]): JsonVideoTrack {
if (!tracks) return undefined;
var lang = Util.getTranslationLanguage() || "en";
var track: JsonVideoTrack = tracks.filter(t => t.srclang == lang)[0];
if (track) return track;
lang = lang.substr(0, 2);
track = tracks.filter(t => t.srclang == lang)[0];
if (track) return track;
return tracks[0];
}
private sig(arg: string, full = false) {
var t = HelpTopic.findById(arg)
if (t && t.isPropertyHelp()) {
return t.getSig(this, full)
}
var m = arg.split(/->/);
var property: IProperty = undefined;
if (m) {
// find type / property
var kindName = m[0];
var propertyName = m[1];
if (kindName && propertyName) {
if (Script) {
var lib = Script.librariesAndThis().filter(lib => lib.getName() == kindName)[0];
if (lib) {
var action = lib.getPublicActions().filter(action => action.getName() == propertyName)[0];
if (action) {
// bingo!
var r = "<div class=notranslate translate=no dir=ltr style='display:inline-block'><div class='md-snippet'>";
r += this.renderer.renderPropertySig(action, false, true, false);
r += "</div></div>";
return r;
}
}
}
}
}
return lf("could not find decl '{0}'", m);
}
private apiList(arg:string)
{
var prefix = ""
var m = /^([^:]*):(.*)/.exec(arg)
if (m) {
prefix = m[1]
arg = m[2]
}
var res = ""
arg.split(/,/).forEach((t) => {
if (/^\s*$/.test(t)) return;
var id = prefix + "_" + t;
var topic = HelpTopic.findById(id)
if (!topic)
res += MdComments.error("no such topic: " + id)
else if (topic.isPropertyHelp())
res += topic.renderLink(this, true);
else {
var st = topic.getSubTopics();
if (st.length > 0) {
res += st.map((t) => t.renderLink(this, true)).join("");
} else {
res += MdComments.error(id + " is neither property nor type");
}
}
})
return res;
}
static findArtStringResource(app : TDev.AST.App, id: string): string {
var artVar = app ? app.resources().filter((r) => MdComments.shrink(r.getName()) == MdComments.shrink(id))[0] : null;
if (artVar && artVar.url) {
return TDev.RT.String_.valueFromArtUrl(artVar.url);
}
return undefined;
}
static findArtId(id : string) : string {
var artVar = Script ? Script.resources().filter((r) => MdComments.shrink(r.getName()) == MdComments.shrink(id))[0] : null;
Cloud.config.altCdnUrls.forEach(artHost => {
var artPref = artHost + "/pub/"
if (artVar && artVar.url && artVar.url.slice(0, artPref.length) == artPref) {
var newId = artVar.url.slice(artPref.length)
if (/^\w+$/.test(newId)) id = newId;
}
})
return id;
}
private defaultRepl(macro:string, arg:string) : string
{
if (macro == "var") {
switch (arg) {
case "userid": return this.userid || Cloud.getUserId();
case "apihelp":
return MdComments.error("var:apihelp no longer supported");
default: return MdComments.error("unknown variable " + arg);
}
} else if (macro == "pic") {
var m = /^((https:\/\/[^:]+)|([\w ]+))(:(\d+)x(\d+))?(:.*)?/i.exec(arg);
if (m) {
var url = m[2];
var artId = m[3];
var width = parseFloat(m[5] || "12");
var height = parseFloat(m[6] || "12");
if (width > 40) {
height = 40 / width * height;
width = 40;
}
if (height > 40) {
width = 40 / height * width;
height = 40;
}
var caption = m[7];
if (caption) caption = caption.slice(1)
else caption = ""
if (artId && !url) {
artId = MdComments.findArtId(artId);
url = Cloud.artUrl(artId);
} else if (!Cloud.isArtUrl(url)) {
url = "no-such-image";
}
url = Cloud.toCdnUrl(url);
url = HTML.proxyResource(url);
var r = "<div class='md-img'><div class='md-img-inner'>";
r += Util.fmt("<img src=\"{0:q}\" alt='{1:q}'", url, caption);
if (m[6] || (!this.forWeb && !this.print))
r += Util.fmt(" style='height:{0}em'", height);
r += "/></div>";
// Used as alt-text now.
//if (caption) {
// r += "<div class='md-caption'>" + this.formatText(caption.slice(1)) + "</div>";
//}
r += "</div>";
return r;
} else {
m = /^(:(\d+)x(\d+))?(:.*)?/.exec(arg);
if (!m)
return MdComments.error(lf("invalid picture id"));
}
} else if (macro == "pici") {
var args = arg.split(/:/)
var artId = MdComments.findArtId(args[0]);
var width = args[1] ? parseFloat(args[1]) : 0
if (!width) width = 2
var r = Util.fmt("<img class='md-img-inline' src='{0}' style='width:{1}em' alt='picture' />", Cloud.artUrl(artId), width);
return r;
} else if (macro == "snippet") {
var args = arg.split(/:/)
if (args.length != 3) return MdComments.error(lf("invalid snippet"));
var editor = args[0];
var renderer = Cloud.config.scriptRenderers[editor];
if (!renderer) return MdComments.error(lf("unknown editor"));
var scriptid = args[1];
var h = parseFloat(args[2]) || 1;
var r = Util.fmt('<div class="md-iframe-wrapper" style="height:{1}em;"><iframe src="{0}" frameborder="0" sandbox="allow-scripts allow-same-origin" scrollbars="no" style="height:{1}em;"></iframe></div>', renderer(scriptid), h);
return r;
} else if (macro == "hex") {
var args = arg.split(':');
if (args.length != 2)
return MdComments.error(lf("missing script title: {hex:id:title}"));
return Util.fmt("<a href=\"{0:q}\" target=\"_blank\">{1:q}</a>", "/api/" + MdComments.shrink(args[0]) + "/hex?applyupdates=true", args[1]);
} else if (macro == "decl" || macro == "decl*") {
var decl = !Script ? null : !arg ? Script : Script.things.filter((t) => t.getName() == arg)[0];
if (this.currComment && this.currComment.mdDecl)
decl = this.currComment.mdDecl;
if (!decl) return MdComments.error(lf("no such decl {0}", arg));
return this.mkDeclSnippet(decl, macro == "decl*");
} else if (macro == "imports") {
if (!Script) return MdComments.error(lf("import can only be used from a script context"));
var r = "";
[
{ name: 'npm', url: 'https://www.npmjs.com/package/{0:q}', pkgs: Script.imports.npmModules },
{ name: 'cordova', url: 'http://plugins.cordova.io/#/package/{0:q}/', pkgs: Script.imports.cordovaPlugins },
{ name: 'bower', url: 'https://www.npmjs.com/package/{0:q}/', pkgs: Script.imports.bowerModules },
{ name: 'client', url: '{0}', pkgs: Script.imports.clientScripts },
{ name: 'pip', url: 'https://pypi.python.org/pypi/{0:q}/', pkgs: Script.imports.pipPackages },
{ name: 'touchdevelop', url: '#pub:{0:q}', pkgs: Script.imports.touchDevelopPlugins }
].forEach(imports => {
var keys = Object.keys(imports.pkgs);
if (keys.length > 0) {
keys.forEach(key => {
var url = Util.fmt(imports.url, key);
var ver = imports.pkgs[key];
r += Util.fmt("<li>{3}: <a target='blank' href='{1}'>{0:q}{2}</a></li>\n", key, url, ver ? " " + ver : "", imports.name);
});
}
});
if (!r) return this.designTime ? "{imports}" : "";
else return "<h3>" + lf("imports") + "</h3><ul>" + r + "</ul>";
} else if (macro == "stlaunch") {
if (!this.scriptid) return "";
return "<h2>" + lf("follow tutorial online") + "</h2><div class='md-box-print print-big'>" + lf("Follow this tutorial online at <b>{1}/{0:q}</b>", this.scriptid, Cloud.config.shareUrl) + ".</div>";
} else if (macro == "stcmd") {
var mrun = /^run(:(.*))?/.exec(arg)
if (mrun) return Util.fmt("<b>Run your program: {0:q}</b>", mrun[2] || "");
var mcomp = /^compile(:(.*))?/.exec(arg)
if (mcomp) return Util.fmt("<b>Compile your program: {0:q}</b>", mcomp[2] || "");
return Util.fmt("<b>tutorial command: {0:q}</b>", arg)
} else if (macro == "adddecl") {
return this.designTime ? Util.fmt("<b>Add the declaration:</b>") : ""
} else if (macro == "stcode") {
return "<b>(code of the step)</b>";
} else if (macro == "internalstepid") {
return Util.fmt("<h1 class='stepid'>{0:q}</h1>", arg)
} else if (macro == "follow") {
return Util.fmt("<!-- FOLLOW --><a href=\"{0:q}\">{1:q}</a>",
this.appLink("#hub:follow-tile:" + MdComments.shrink(arg)),
arg)
} else if (macro == "topictile") {
return Util.fmt("<!-- FOLLOW --><a href=\"{0:q}\">{1:q}</a>",
this.appLink("#topic-tile:" + MdComments.shrink(arg)),
arg)
} else if (macro == "pub") {
var args = arg.split(':');
if (args.length != 2)
return MdComments.error(lf("missing publication title: {pub:id:title}"));
return Util.fmt("<!-- FOLLOW --><a href=\"{0:q}\">{1:q}</a>",
this.appLink("#pub:" + MdComments.shrink(args[0])),
args[1])
} else if (macro == "section") {
var mm = /^([^:;]+)[;:](.*)/.exec(arg)
var sectName = mm ? mm[1] : arg
var output = Util.fmt("--------------------------- <b>{0:q}</b> ---------------------------", sectName)
if (mm) {
mm[2].split(';').forEach(a => {
output += Util.fmt("<div class='md-section'>;; {0:q}</div>", a)
})
}
return output;
} else if (macro == "hide" || macro == "priority" || macro == "template" || macro == "highlight" ||
macro == 'box' || macro == "code" || macro == "widgets" || macro == "templatename" ||
macro == "hints" || macro == "pichints" || macro == "enum" || macro == "language" || macro == "weight" || macro == "namespace" ||
macro == "parenttopic" || macro == "docflags" || macro == "stprecise" || macro == "flags" || macro == "action" ||
macro == "topic" || macro == "breadcrumbtitle" ||
macro == "stvalidator" || macro == "stnoprofile" || macro == "stauto" || macro == "sthints" ||
macro == "stcode" || macro == "storder" || macro == "stdelete" || macro == "stcheckpoint" || macro == "sthashtags" ||
macro == "stnocheers" || macro == "steditormode" || macro == "stnexttutorials" || macro == "stmoretutorials" ||
macro == "translations" || macro == "stpixeltracking" || macro == "steventhubstracking" || macro == "icon" || macro == "help"
) {
if (this.designTime)
return "{" + macro + (arg ? ":" + Util.htmlEscape(arg) : "") + "}";
else return "";
} else if (macro == "api") {
return this.apiList(arg);
} else if (macro == "sig") {
return this.sig(arg);
} else if (macro == "fullsig") {
return this.sig(arg, true);
} else if (macro == "youtube") {
if (!this.allowVideos) return "";
if (this.blockExternal()) return this.blockLink("")
if (!arg)
return MdComments.error("youtube: missing video id");
else {
return Util.fmt("<div class='md-video-link' data-playerurl='{0:q}'>{1}</div>",
Util.fmt("//www.youtube-nocookie.com/embed/{0:uri}?modestbranding=1&autoplay=1&autohide=1", arg),
SVG.getVideoPlay(Util.fmt('https://img.youtube.com/vi/{0:q}/hqdefault.jpg', arg))
);
}
} else if (macro == "videoptr") {
if (!this.allowVideos) return "";
if (this.blockExternal()) return this.blockLink("")
if (!arg)
return MdComments.error("videoptr: missing video id");
else {
var prefix = this.relativeLinks ? "" : Cloud.getServiceUrl();
var args = arg.split(/:/);
if (!/^[a-z0-9\-\/@]+$/.test(args[0]))
return MdComments.error("videoptr: invalid pointer path");
var id = args[0].replace(/^\/+/, "")
var url = Util.fmt("{0}/{1}/sd", prefix, id);
var playerUrl = Util.fmt("{0}/embed/{1}", prefix, id);
var posterUrl = Util.fmt("{0}/{1}/thumb", prefix, id);
if (Cloud.config.anonToken) {
var suff = "?anon_token=" + encodeURIComponent(Cloud.config.anonToken)
url += suff
posterUrl += suff
}
var alt = args.slice(1).join(":") || ""
// TODO: support looping
// return Util.fmt("<div class='md-video-link' data-videoposter='{0:url}' data-videosrc='{1:url}'>{2}</div>", posterUrl, url, SVG.getVideoPlay(posterUrl));
return Util.fmt("<div class='md-video-link' data-videoposter='{0:url}' data-playerurl='{1:url}' data-alt='{3:q}'>{2}</div>",
posterUrl, playerUrl, SVG.getVideoPlay(posterUrl, alt), alt);
}
} else if (macro == "bbc") {
if (!this.allowVideos) return "";
if (this.blockExternal()) return this.blockLink("")
var args = arg.split(/:/);
var id = args[0]
var caption = args.slice(1).join(":")
if (!id)
return MdComments.error("bbc: missing video id");
else {
return Util.fmt("<div class='md-video-link' data-playerurl='{0:q}' data-alt='{2:q}'>{1}</div>",
Util.fmt("https://files.microbit.co.uk/clips/{0:uri}/embed", id),
SVG.getVideoPlay(Util.fmt('https://files.microbit.co.uk/clips/{0:uri}/thumb', id), caption),
caption);
}
} else if (macro == "vimeo") {
if (!this.allowVideos) return "";
if (Cloud.isRestricted())
return MdComments.error("vimeo not allowed");
if (!arg)
return MdComments.error("vimeo: missing video id");
if (this.blockExternal()) return this.blockLink("")
var args = arg.split(/:/);
if (!/^\d+$/.test(args[0]))
return MdComments.error("vimeo: video id should be a number");
else {
var prefix = this.relativeLinks ? "" : Cloud.getServiceUrl();
var url = Util.fmt("{0}/vimeo/{1:uri}/sd", prefix, args[0]);
var posterUrl = Util.fmt("{0}/vimeo/{1:uri}/thumb512", prefix, args[0]);
// TODO: support looping
return Util.fmt("<div class='md-video-link' data-videoposter='{0:url}' data-videosrc='{1:url}'>{2}</div>", posterUrl, url, SVG.getVideoPlay(posterUrl));
}
} else if (macro == "channel9") {
if (!this.allowVideos) return "";
if (this.blockExternal()) return this.blockLink("")
if (!arg)
return MdComments.error("channel9: missing MP4 url");
var video = arg.replace(/^http:\/\/video/, 'https://sec');
var poster = video.replace(/\.mp4$/, '_512.jpg');
return Util.fmt("<div class='md-video-link' data-videoposter='{0:url}' data-videosrc='{1:url}'>{2}</div>",
poster,
video,
SVG.getVideoPlay(poster))
} else if (macro == "video") {
if (!this.allowVideos) return "";
if (this.blockExternal()) return this.blockLink("")
if (!arg)
return MdComments.error("video: missing video preview and url");
var res = MdComments.findArtStringResource(Script, arg);
if (res) return MdComments.expandJsonVideo(res);
var urls = arg.split(',');
if (urls.length != 2)
return MdComments.error("video: must have <preview url>,<mp4 url> arguments");
else {
return Util.fmt("<div class='md-video-link' data-videoposter='{0:url}' data-videosrc='{1:url}'>{2}</div>",
urls[0],
urls[1],
SVG.getVideoPlay(urls[0]))
}
} else if (macro == "cap") {
if (!arg)
return MdComments.error("cap: requires a comma separated list of required capabilities");
var required = AST.App.fromCapabilityList(arg.split(/,/));
var current = PlatformCapabilityManager.current();
var missing = required & ~current;
if (!missing)
return "";
else
return "<div class='md-tutorial md-warning'>" +
"<strong>" + lf("This code might not work on your current device") + "</strong>: " + lf("missing {0} capabilities.", AST.App.capabilityName(missing)) +
"</div>";
} else if (macro == "webonly") {
if (this.designTime)
return MdComments.error("{webonly} macro doesn't do anything anymore")
else
return "";
} else if (macro == "bigbutton") {
if (!arg) return MdComments.error("bigbutton: requires <text>,<url> arguments");
var ms = arg.split(',');
if (ms.length != 2) return MdComments.error(lf("bigbutton: must have <text>,<url> arguments"));
return this.blockLink(ms[1]) || Util.fmt("<a class='md-bigbutton' target='_blank' rel='nofollow' href='{0:url}'>{1:q}</a>", ms[1], ms[0]);
} else if (macro == "shim" || macro == "asm") {
if (this.designTime || macro == "asm") return "{" + macro + ":" + Util.htmlEscape(arg) + "}";
if (!arg) return "";
else
return Util.fmt("<b>{0:q}</b> <span class='font-family: monospace'>{1:q}</span>",
lf("compiles to C++ function:"), arg);
} else {
return null;
}
}
static expandJsonVideo(res: string) {
var video : JsonVideo;
try { video = <JsonVideo>JSON.parse(res); } catch (e) {}
if (!video) return MdComments.error("video: missing data");
var source = MdComments.findBestSource(video.sources);
if (!source) return MdComments.error('videoset: missing sources');
var poster = source.poster || video.poster;
if (!poster) return MdComments.error('video: missing poster');
// encode all stream for later use
return Util.fmt("<div class='md-video-link' data-video='{0:uri}'>{1}</div>",
JSON.stringify(video),
SVG.getVideoPlay(poster))
}
private blockExternal()
{
if (this.blockExternalLinks === undefined)
this.blockExternalLinks = !!(Cloud.isRestricted() && !Cloud.hasPermission("external-links"));
return this.blockExternalLinks
}
private blockLink(href:string)
{
if (!this.blockExternal()) return null
// TODO check if the link is external?
return MdComments.error(lf("sorry, external link not allowed"))
}
private expandInline(s:string, allowStyle = false, allowRepl = true):string
{
var inp = s;
var outp = "";
var applySpan = (rx:RegExp, repl:(m:RegExpExecArray)=>string) =>
{
var m = rx.exec(inp);
if (m) {
inp = inp.slice(m[0].length);
outp += repl(m);
return true;
}
return false;
}
var replace = (tag:string) => {
return (m:RegExpExecArray) => "<" + tag + ">" + this.expandInline(m[1]) + "</" + tag + ">";
}
var getReplCode = (m:RegExpExecArray) => {
var s = m[2]
if (m[1].length == 1) {
s = s.replace(/->/g, "\u2192");
s = s.replace(/(^|\s)(\w+)\u2192/, (m, pr, w) => {
switch (w) {
case "code": return pr + AST.codeSymbol;
case "data": return pr + AST.dataSymbol;
case "art": return pr + AST.artSymbol;
case "libs": return pr + AST.libSymbol;
case "records": return pr + AST.recordSymbol;
default: return m;
}
});
}
var inner = this.expandInline(s, false, false)
// ensure symbols render properly
inner = inner.replace(/[\u25b7\u25f3\u273f\u267B\u2339]/, '<span class="symbol">$&</span>');
return inner
}
var replCode = (m:RegExpExecArray) => {
var inner = getReplCode(m)
if (this.allowLinks && m[1].length == 1)
inner = inner.replace(/(^|[\s\(,])([\u2192\w ]+)($|[\s\(,])/g, (all, before, topic, after) => {
if (HelpTopic.findById(topic))
return before + "<a class='md-code-link' href='" + this.topicLink(topic) + "'>" + topic + "</a>" + after;
else
return all;
})
return "<code class=notranslate translate=no dir=ltr>" + inner + "</code>";
}
var replUI = (m:RegExpExecArray) => {
var inner = getReplCode(m)
return "<code class='md-ui' translate=no dir=ltr>" + inner + "</code>";
}
var quote = Util.htmlEscape;
while (inp) {
if (allowRepl &&
applySpan(/^\{([\w\*]+)(:([^{}]*))?\}/, (m) => {
if (!this.allowImages) return "";
var res = this.defaultRepl(m[1].toLowerCase(), m[3])
if (res == null) return MdComments.error("unknown macro '" + m[1] + "'")
else return res;
}))
continue;
if (applySpan(/^\&(\w+|#\d+);/, (m) => m[0]) ||
(allowStyle && applySpan(/^<br\s*\/>/, m => "<br/>"))||
applySpan(/^([<>&])/, (m) => Util.htmlEscape(m[1])) ||
applySpan(/^\t/, (m) => MdComments.error("<tab>")) ||
false)
continue;
if (allowStyle && (
applySpan(/^(``)(.+?)``/, replCode) ||
applySpan(/^(``)\[(.+?)\]``/, replUI) ||
applySpan(/^(`)\[(.+?)\]`/, replUI) ||
applySpan(/^(`)([^\n`]+)`/, replCode) ||
applySpan(/^\*\*(.+?)\*\*/, replace("strong")) ||
applySpan(/^\*([^\n\*]+)\*/, replace("em")) ||
applySpan(/^__(.+?)__/, replace("strong")) ||
applySpan(/^_([^\n_]+)_/, replace("em")) ||
(this.allowLinks && applySpan(/^(http|https|ftp):\/\/[^\s]*/gi, (m) => {
var msg = this.blockLink(str)
if (msg) return msg
var str = m[0];
var suff = ""
var mm = /(.*?)([,\.;:\)]+)$/.exec(str);
if (mm) {
str = mm[1]
suff = mm[2];
}
str = this.expandInline(str);
str = str.replace(/"/g, """);
return "<a href=\"" + quote(str) + "\" target='_blank' rel='nofollow'>" + str + "</a>" + suff;
})) ||
false))
continue;
var tdev = this.serviceUrlOr("/", "")
if (allowRepl && (
applySpan(/^\{\#(\w+)\}/g, (m) => "<a name='" + quote(m[1]) + "'></a>") ||
applySpan(/^\[([^\[\]]*)\]\s*\(([^ \(\)\s]+)\)/, (m) => {
var name = m[1];
var href = m[2];
var acls = '';
var additions = ""
if (!name) {
name = href.replace(/^\//, "");
if (this.pointerHelp)
name = name.replace(/^[\w\/]+\//, "")
}
if (this.pointerHelp && /^\/[\w\-\/]+(#\w+)?$/.test(href))
href = href
else if (/^\/\w+(->\w+)?(#\w+)?$/.test(href))
href = this.topicLink(href.slice(1));
else if (/^\/script:\w+$/.test(href)) {
acls = 'md-link';
href = (this.useExternalLinks ? tdev + href.slice(8) : "#" + href.slice(1));
}
else if (/^#[\w\-]+:[\w,\-:]*$/.test(href))
href = (this.useExternalLinks ? tdev + "/app/#" : "#") + href.slice(1);
else if (/^#[\w\-]+$/.test(href))
href = (this.useExternalLinks ? "#" : "#goto:") + href.slice(1);
else if (/^(http|https|ftp):\/\//.test(href) || /^mailto:/.test(href)) {
var msg = this.blockLink(href)
if (msg) return msg
href = href; // OK
acls = "md-link md-external-link";
additions = " rel=\"nofollow\" target=\"_blank\"";
if (!this.useExternalLinks && this.allowLinks)
name += " \u2197";
}
else
return MdComments.error("invalid link '" + href + "'");
if (this.allowLinks)
return "<a class=\"" + acls + "\" href=\"" + quote(href) + "\"" + additions + ">" + this.expandInline(name) + "</a>";
else
return this.expandInline(name);
}) ||
false))
continue;
if (applySpan(/^(\s+)/, (m) => m[0]) ||
applySpan(/^(\w+\s*|.)/, (m) => m[0]))
continue;
}
return outp;
}
public formatInline(s: string)
{
var prev = this.allowLinks;
var prevI = this.allowImages;
var prevV = this.allowVideos;
this.allowLinks = false;
this.allowImages = false;
this.allowVideos = false;
try {
return this.expandInline(s, true, true);
} finally {
this.allowLinks = prev;
this.allowImages = prevI;
this.allowVideos = prevV;
}
}
public formatTextNoLinks(s: string)
{
var prev = this.allowLinks;
this.allowLinks = false;
try {
return this.formatText(s)
} finally {
this.allowLinks = prev;
}
}
public formatText(s: string, comment:AST.Comment = null)
{
if (!s) return s;
this.init();
var start = "";
var final = "";
var wrap = (tag:string, end = "") => {
if (!end) end = "/" + tag;
return (m, s) => {
if (start != "") return m;
start = "<" + tag + ">";
final = "<" + end + ">";
return s;
}
}
if (/^ /.test(s)) return "<pre>" + Util.htmlEscape(s.slice(4)) + "</pre>";
if (/^-{5,}\s*$/.test(s)) return this.designTime ? s : "<hr/>";
if (/^\*{5,}\s*$/.test(s)) return this.designTime ? s : "<div style='page-break-after:always'></div>";
s = s.replace(/^#\s+(.*)/, wrap("h1"));
s = s.replace(/^##\s+(.*)/, wrap("h2"));
s = s.replace(/^###\s+(.*)/, wrap("h3"));
s = s.replace(/^####\s+(.*)/, wrap("h4"));
s = s.replace(/^>\s+(.*)/, wrap("blockquote"));
s = s.replace(/^[-+*]\s+(.*)/, wrap("ul><li", "/li></ul"));
s = s.replace(/^\d+\.\s+(.*)/, wrap("ol><li", "/li></ol"));
wrap("div class='md-para'", "/div")("", "");
var prevComment = this.currComment;
try {
this.currComment = comment;
return start + this.expandInline(s, true, true) + final
} finally {
this.currComment = prevComment;
}
}
private mkCopyButton(tp:string, dt:string)
{
var r = Util.fmt("<button class='{0} copy-button' data-type='{1:q}' data-data='{2:q}'>",
this.useSVG ? "code-button" : "wall-button", tp, dt);
if (!this.useSVG)
r += "copy";
else
r += Util.fmt('<div class="code-button-frame">{0}</div>', SVG.getIconSVGCore("copy,currentColor"));
r += "</button>";
return r;
}
private depthLimit = 0;
public mkDeclSnippet(decl:AST.Decl, skipComments = false, formatComments = false, cls = 'md-snippet', addDepth = 0)
{
if (this.depthLimit < 0 || !this.renderer) return "<div class='md-message'>[" + Util.htmlEscape(decl.getName()) + " goes here]</div>";
var r = "<div class=notranslate translate=no dir=ltr><div class='" + cls + "'>";
var prev = this.renderer.formatComments;
var prevSc = this.renderer.skipComments;
var prevMd = this.renderer.mdComments
try {
this.depthLimit += addDepth - 1;
this.renderer.mdComments = this;
this.renderer.formatComments = formatComments;
this.renderer.skipComments = skipComments;
r += this.renderer.renderDecl(decl);
} finally {
this.depthLimit -= addDepth - 1;
this.renderer.formatComments = prev;
this.renderer.skipComments = prevSc;
this.renderer.mdComments = prevMd;
}
if (this.showCopy && !formatComments)
r += this.mkCopyButton("decls", decl.serialize());
r += "</div></div>";
return r;
}
private mkSnippet(stmts:AST.Stmt[])
{
if (!this.renderer) return "<div class='md-message'>[inline snippet goes here]</div>";
var r = "<div class=notranslate translate=no dir=ltr><div class='md-snippet'>";
r += this.renderer.renderSnippet(stmts);
if (this.showCopy) {
var block = new AST.Block();
block.stmts = stmts; // don't use setChildren(), that would override the parent
var d = block.serialize()
// OK, this is a hack...
if (this.libName)
d = d.replace(/code\u2192/g, '@\\u267b ->' + AST.Lexer.quoteId(this.libName) + '->');
r += this.mkCopyButton("block", d);
}
r += "</div></div>";
return r;
}
private init()
{
if (!this.renderer) return;
if (this.libName) {
this.renderer.codeReplacement = '<span class="id symbol">' + AST.libSymbol + '</span>\u200A' + this.libName + '\u200A';
if (this.showCopy)
this.renderer.codeReplacement += '\u2192\u00A0';
} else {
this.renderer.codeReplacement = null;
}
}
public extract(a:AST.Action)
{
return this.extractStmts(a.body.stmts)
}
public extractStmts(stmts:AST.Stmt[])
{
this.init();
var output = "";
var currBox = null;
for (var i = 0; i < stmts.length; ) {
var cmt = stmts[i].docText()
if (cmt != null) {
var m = /^\s*\{hide(:[^{}]*)?\}\s*$/.exec(cmt);
if (m) {
if (m[1]) output += this.formatText(m[1]);
var j = i + 1;
while (j < stmts.length) {
if (/^\s*\{\/hide\}\s*$/.test(stmts[j].docText())) {
j++;
break;
}
j++;
}
i = j;
} else if (i == 0 && cmt == '{var:apihelp}') {
i++;
} else if ((m = /^```` bitmatrix((.|\n)*)````$/.exec(cmt)) != null) {
var bits = m[1];
output += "<div class='md-para'>" + this.renderer.renderBitmatrix(bits, { cls: 'docs', height:7 }) + "</div>";
i++;
} else if ((m = /^\s*(\{code\}|````)\s*$/.exec(cmt)) != null) {
var j = i + 1;
var seenStmt = false;
while (j < stmts.length) {
if (/^\s*(\{\/code\}|````)\s*$/.test(stmts[j].docText()))
break;
j++;
}
output += this.mkSnippet(stmts.slice(i + 1, j));
i = j + 1;
} else if ((m = /^\s*\{section:(.*)\}\s*$/.exec(cmt)) != null) {
var mm = /^([^:;]+)[;:](.*)/.exec(m[1])
var sectName = mm ? mm[1] : m[1]
output += Util.fmt("<hr class='md-section' data-name='{0:uri}' data-arguments='{1:uri}' />", sectName, mm ? mm[2] : "")
i++;
} else if ((m = /^\s*\{box:([^{}]*)\}\s*$/.exec(cmt)) != null) {
if (currBox) output += "</div>";
var parts = m[1].split(':');
var boxClass = parts[0];
var boxDir = "";
var boxHd = "";
var boxFt = "";
var boxCss = "md-box";
switch (boxClass) {
case "card":
boxHd = "<h3 class='md-box-header'>" + this.expandInline(parts.slice(1).join(':'), true, false) + "</h3>";
break;
case "hint":
boxHd = "<div class='md-box-header'>" + lf("hint") + "</div>";
break;
case "exercise":
boxHd = "<div class='md-box-header'>" + lf("exercise") + "</div>";
break;
case "example":
boxHd = "<div class='md-box-header'>" + lf("example") + "</div>";
break;
case "nointernet":
boxHd = "<div class='md-box-header'>" + lf("no internet?") + "</div>";
break;
case "portrait":
boxHd = "<div class='md-box-header-print'>" + lf("device in portrait") +"</div>";
boxCss = "";
break;
case "landscape":
boxHd = "<div class='md-box-header-print'>" + lf("device in landscape") + "</div>";
boxCss = "";
break;
case "print":
case "screen":
case "block":
boxHd = "";
boxCss = "";
break;
case "avatar":
var artId = MdComments.findArtId(parts[1]);
boxHd = Util.fmt("<img class='md-box-avatar-img' src='{0}' /><div class='md-box-avatar-body' dir='auto'>", Cloud.artUrl(artId));
boxFt = '</div>';
boxCss = '';
boxClass = 'avatar';
boxDir = "dir='ltr'";
break;
case "column":
boxHd = "";
boxCss = "col-xs-12 col-sm-6 col-md-4";
break;
default:
boxHd = MdComments.error("no such box type " + m[1] + ", use hint, exercise, example or nointernet")
boxClass = 'hint'
break;
}
currBox = boxClass;
output += Util.fmt("<div class='{0} md-box-{1}' {2}>{3}", boxCss, boxClass, boxDir, boxHd)
i++;
} else if (/^\s*\{\/box(:[^{}]*)?\}\s*$/.test(cmt)) {
if (currBox) {
output += boxFt + "</div>";
currBox = null;
} else {
output += MdComments.error("no box to close")
}
i++;
} else {
output += this.formatText(cmt);
i++;
}
} else {
var j = i;
while (j < stmts.length) {
if (stmts[j].docText() != null) break;
j++;
}
output += this.mkSnippet(stmts.slice(i, j));
i = j;
}
}
if (currBox) output += "</div>";
var fixMultiline = (s:string) => {
s = s.replace(/(<\/ul><ul>|<\/ol><ol>|<\/pre><pre>|<\/div><!-- HL --><div class='code-highlight'>)/g, "");
s = s.replace(/<ul><li><!-- FOLLOW -->/g, "<ul class='tutorial-list'><li>")
return s;
}
output = fixMultiline(output);
return "<div class='md-tutorial' dir='auto'>" + output + "</div>";
}
static splitDivs(tut:string)
{
var splits:string[] = []
var leftovers = tut.replace(/([^<]+|<[^<>]+>)/g, (m, g) => {
splits.push(g)
return ""
})
Util.assert(!leftovers, "should be nothing left: " + leftovers)
if (/<div.*md-tutorial.*>/.test(splits[0]) &&
/<\/div>/.test(splits.peek())) {
splits.shift()
splits.pop()
}
var stack:string[] = []
var output:string[] = []
var curr = ""
var norm = (s:string) => s.toLowerCase().replace(/\s*/g, "")
splits.forEach(s => {
curr += s
if (norm(s) == stack.peek())
stack.pop()
else {
var m = /<([a-z0-9\-]+)(\s|>)/i.exec(s)
if (m && /^(div|p|ul|ol|h[1-9]|blockquote)$/i.test(m[1]))
stack.push(norm("</" + m[1] + ">"))
}
if (stack.length == 0) {
output.push(curr)
curr = ""
}
})
if (curr) output.push(curr)
return output
}
}
export interface HelpTopicJson
{
name: string;
id: string;
rootid: string;
description: string;
icon:string;
iconbackground:string;
iconArtId?:string;
time?:number;
userid?:string;
text: string;
priority:number;
platforms?:string[];
parentTopic?:string;
screenshot?: string;
helpPath?: string;
}
export interface HelpTopicInfoJson {
title: string;
description: string;
body: string[];
translations?: StringMap<string>; // locale -> script id
manual?: boolean;
}
export class HelpTopic
{
private searchCache:string;
public app:AST.App;
private apiKind:Kind;
private apiProperty:IProperty;
private subTopics:StringMap<HelpTopic>;
private initPromise:Promise;
public id:string;
public fromJson:JsonScript;
public isBuiltIn = false;
public isTutorial(): boolean {
return this.hashTags()
&& /#(stepbystep|hourofcode)\b/i.test(this.allHashTags)
&& !/template|notes/i.test(this.json.name);
}
public isHourOfCode(): boolean {
return this.hashTags() && /#HourOfCode\b/i.test(this.allHashTags);
}
private translatedTopic: HelpTopicInfoJson;
public nestingLevel:number;
public parentTopic:HelpTopic = null;
public childTopics:HelpTopic[] = [];
static contextTopics:HelpTopic[] = [];
static getScriptAsync:(id:string)=>Promise;
static _topics:HelpTopic[] = [];
static _initalized = false;
constructor(public json:HelpTopicJson)
{
this.id = MdComments.shrink(this.json.name);
}
static fromJsonScript(e:JsonScript)
{
var t = new HelpTopic({
name: e.name,
id: e.id,
description: e.description,
icon: e.icon,
iconbackground: e.iconbackground,
iconArtId: e.iconArtId,
userid: e.userid,
time:e.time,
text: null,
rootid: e.rootid,
platforms: e.platforms,
priority: 20000,
});
t.id = e.id;
t.hashTags();
t.fromJson = e;
return t;
}
static fromScriptText(id:string, text:string)
{
var app = AST.Parser.parseScript(text);
var t = HelpTopic.fromScript(app, false);
if (id) {
t.id = id;
t.json.id = id;
}
return t;
}
static fromScript(app:AST.App, useApp = true)
{
var t = new HelpTopic({
name: app.getName(),
id: "none",
description: app.getDescription(),
icon: SVG.justName(app.iconPath()),
iconbackground: app.htmlColor(),
text: app.serialize(),
rootid: "none",
priority: 20000
})
if (useApp) {
t.app = app;
t.initPromise = Promise.as();
}
return t;
}
static lookupHelpPath(topic:string)
{
topic = topic.toLowerCase().replace(/^#/, "")
var paths = Cloud.config.specHelpPaths;
if (paths)
for (var i = topic.length; i >= 2; --i)
if (paths.hasOwnProperty(topic.slice(0, i)))
return paths[topic.slice(0, i)]
return null
}
static justHelpPath(topic:string)
{
if (!topic) return null;
var path = HelpTopic.lookupHelpPath(topic)
if (!path) return null;
var t = new HelpTopic({
name: path,
id: "",
description: "",
icon: "Recycle",
iconbackground: "#008800",
text: "",
rootid: "none",
priority: 20000,
helpPath: path,
})
t.id = path
return t;
}
static forLibraryAction(act:AST.LibraryRefAction)
{
var t = new HelpTopic({
name: act.getName(),
id: "",
description: act.getDescription(),
icon: "Recycle",
iconbackground: "#008800",
text: "",
rootid: "none",
priority: 20000,
helpPath: act.getHelpPath()
})
t.apiProperty = act
t.apiKind = api.core.Nothing
t.app = act.parentLibrary().resolved
t.id = Util.tagify(t.app.getName() + " " + act.getName())
t.json.description += " #" + t.id
return t;
}
static getAll() : HelpTopic[]
{
if (!HelpTopic._initalized) {
HelpTopic._initalized = true;
var bestForTag:StringMap<HelpTopic> = {}
HelpTopic._topics = [];
api.getKinds().forEach((k:Kind) => {
if (k.isPrivate || k instanceof ThingSetKind || (k.isData && k.getContexts() == KindContext.None)) return;
var tagName = Util.toHashTag(k.getName());
var topic:HelpTopic = bestForTag[MdComments.shrink(tagName)]
if (!topic) {
topic = new HelpTopic({
name: k.getName(),
id: "",
description: "",
icon: SVG.justName(k.icon()) || "Document",
iconbackground: "#7d26cd",
priority: 11000,
rootid: "none",
text: ""
})
topic.hashTagsCache = ["#docs", tagName]
HelpTopic._topics.push(topic);
}
topic.id = MdComments.shrink(tagName.replace(/^#/, ""));
topic.json.name = k.getName();
topic.json.description = k.getHelp(false)
topic.json.parentTopic = "api"
topic.apiKind = k;
var outerTopic = topic;
outerTopic.subTopics = {};
k.listProperties().forEach((prop) => {
if (!prop.isBrowsable()) return;
var propname = prop.parentKind.getName() + prop.getArrow() + prop.getName();
var tagName = "#" + prop.helpTopic();
var topic:HelpTopic = bestForTag[MdComments.shrink(tagName)]
if (!topic) {
var j = outerTopic.json;
topic = new HelpTopic({
name: propname,
id: "",
rootid: "none",
description: "",
icon: j.icon,
iconbackground: j.iconbackground,
priority: 10000 + j.priority,
text: ""
});
topic.hashTagsCache = ["#docs", tagName]
HelpTopic._topics.push(topic);
}
topic.id = MdComments.shrink(tagName.replace(/^#/, ""));
topic.json.name = propname;
topic.json.description = prop.getDescription(true)
// they clash for "unknown -> :="
if (outerTopic.id != topic.id)
topic.json.parentTopic = outerTopic.id
outerTopic.subTopics[topic.id] = topic;
topic.apiKind = k;
topic.apiProperty = prop;
})
})
HelpTopic._topics.sort((a, b) => {
var d = a.json.priority - b.json.priority
if (d) return d;
return Util.stringCompare(a.json.name, b.json.name);
})
HelpTopic._topics.forEach((t) => t.isBuiltIn = true)
HelpTopic.topicCache = {}
HelpTopic.topicByScriptId = {}
HelpTopic._topics.forEach((t) => {
HelpTopic.topicByScriptId[t.json.id] = t
HelpTopic.topicCache[t.id] = t
})
var workSet:StringMap<number> = {}
var getNesting = (t:HelpTopic) => {
if (workSet.hasOwnProperty(t.id) && workSet[t.id]) workSet[t.id] = 2
if (t.nestingLevel !== undefined) return t.nestingLevel
t.nestingLevel = 0
if (t.json.parentTopic && HelpTopic.topicCache.hasOwnProperty(t.json.parentTopic)) {
var par = HelpTopic.topicCache[t.json.parentTopic]
workSet[t.id] = 1
var pn = getNesting(par)
if (workSet[t.id] == 1) {
t.parentTopic = par
t.nestingLevel = getNesting(par) + 1
t.parentTopic.childTopics.push(t)
} else {
if (dbg)
Util.log("DOCERR: cycle in help topics involving " + t.id)
}
workSet[t.id] = 0
} else {
if (dbg) {
if (t.json.parentTopic)
Util.log("DOCERR: parent topic " + t.json.parentTopic + " doesn't exists (in '" + t.json.name + "' /" + t.json.id + ")")
else
Util.log("DOCERR: no parent topic set for '" + t.json.name + "' /" + t.json.id)
}
}
return t.nestingLevel
}
HelpTopic._topics.forEach(getNesting)
HelpTopic._topics.forEach(t => {
if (t.childTopics.length > 0)
t.childTopics.sort((a, b) => Util.stringCompare(a.json.name, b.json.name))
})
}
return HelpTopic._topics;
}
public renderLink(mdcmt:MdComments, withKind = false)
{
var p = this.apiProperty;
var r = "";
r += Util.fmt("<a href='{0:q}' id='{1:q}' class='md-api-entry-link'><div class='md-api-entry'>",
mdcmt.topicLink(this.id), p ? MdComments.shrink(p.getName()) : MdComments.shrink(this.id))
if (this.json.text)
r += "<div class='md-more'>more info</div>"
if (mdcmt.renderer)
r += mdcmt.renderer.renderPropertySig(p, false, withKind);
else
r += Renderer.tdiv("signature", "function " + p.getName()) // we shouldn't really get here
r += "<div class='nopara'>" + mdcmt.formatTextNoLinks(p.getDescription()) + "</div>";
r += "</div></a>";
return r;
}
public isBetterThan(other:HelpTopic)
{
var d = this.hashTags().length - other.hashTags().length;
if (d != 0) return d < 0;
d = this.json.priority - other.json.priority;
if (d != 0) return d < 0;
return Util.stringCompare(this.id, other.id) < 0;
}
public updateKey()
{
var j = this.fromJson
if (j)
return j.rootid + ":" + j.userid + ":" + j.name
return this.json.rootid + ":jeiv:" + this.json.name
}
private allHashTags: string;
private hashTagsCache:string[];
public hashTags()
{
if (!this.hashTagsCache) {
var r = this.hashTagsCache = [];
var ht = "";
this.json.description = this.json.description.replace(/(#\w+)/g, (m, h) => { r.push(m); ht += " " + m; return "" })
this.allHashTags = ht;
}
return this.hashTagsCache;
}
public translations(): StringMap<string> {
var m = /\{translations:([^\}]+)\}/i.exec(this.json.text);
if (!m) return undefined;
var res = MdComments.findArtStringResource(this.app, m[1]);
if (!res) return undefined;
var r: StringMap<string> = {};
res.split('\n')
.map(p => p.split('='))
.forEach(parts => r[parts[0].toLowerCase()] = parts[1]);
return r;
}
public templateHashTags() : string[] {
var m = /\{sthashtags:([^\}]+)\}/i.exec(this.json.text);
if (m) return m[1].split(',');
else return [];
}
public templateEditorMode(): string {
var m = /\{steditormode:([^\}]+)\}/i.exec(this.json.text);
if (m) return m[1].trim().toLowerCase();
return "";
}
public eventHubsTracking(): { namespace: string; hub: string; token: string; } {
var m = /\{steventhubstracking:([^\:]+):([^\:]+):([^\}]+)\}/i.exec(this.json.text);
if (m) return { namespace: m[1], hub: m[2], token: m[3] };
return undefined;
}
public pixelTrackingUrl(): string {
var m = /\{stpixeltracking:([^\}]+)\}/i.exec(this.json.text);
if (m) return m[1];
return "";
}
public nextTutorials(): string[] {
var m = /\{stnexttutorials:([^\}]+)\}/i.exec(this.json.text);
if (m) return m[1].split(',');
return [];
}
public moreTutorials(): string {
var m = /\{stmoretutorials:([^\}]+)\}/i.exec(this.json.text);
if (m) return m[1];
return undefined;
}
private translateAsync(to: string): Promise { // of HelpTopicInfoJson
if (this.translatedTopic) return Promise.as(this.translatedTopic);
if (!to || /^en/i.test(to) || Cloud.isOffline()) return Promise.as(undefined);
tick(Ticks.translateDocTopic, to);
return this.translateToScriptAsync(to, this.json.id);
}
private translateToScriptAsync(to: string, tutorialId: string): Promise { // translated topic
// unpublished tutorial
if (!tutorialId ||
// cloud config not set
!Cloud.config.translateCdnUrl || !Cloud.config.translateApiUrl)
return Promise.as(this.translatedTopic = <HelpTopicInfoJson>{ body: undefined });
return ProgressOverlay.lockAndShowAsync(lf("translating topic...") + (dbg ? tutorialId : ""))
.then(() => {
var blobUrl = HTML.proxyResource(Cloud.config.translateCdnUrl + "/docs/" + to + "/" + tutorialId);
return Util.httpGetJsonAsync(blobUrl).then((blob) => {
this.translatedTopic = blob;
return this.translatedTopic;
}, e => {
// requestion translation
Util.log('requesting topic translation');
var url = Cloud.config.translateApiUrl + '/translate_doc?scriptId=' + tutorialId + '&to=' + to;
return Util.httpGetJsonAsync(url).then((js) => {
this.translatedTopic = js.info;
return this.translatedTopic;
}, e => {
Util.log('tutorial topic failed, ' + e);
return this.translatedTopic = <HelpTopicInfoJson>{ body : undefined };
});
});
}).then(() => ProgressOverlay.hide(), e => () => ProgressOverlay.hide());
}
public forSearch()
{
if (!this.searchCache) {
var j = this.json;
var c = j.name + " " + j.description;
if (this.apiProperty) {
c += " " + this.apiProperty.parentKind.toString();
this.apiProperty.getParameters().forEach((p) => {
c += " " + p.getName() + " " + p.getKind().toString();
})
c += " " + this.apiProperty.getResult().getKind().toString();
c += " " + this.apiProperty.getDescription();
} else if (this.apiKind) {
c += " " + this.apiKind.toString();
c += " " + this.apiKind.getDescription();
}
if (j.text) c += " " + j.text;
this.searchCache = c.toLowerCase();
}
return this.searchCache;
}
public reloadAppAsync()
{
var j = this.json;
var loadScript = (id) => {
if (id == "") {
if (j.text == null && j.id)
return HelpTopic.getScriptAsync(j.id).then((text) => {
j.text = text;
return text;
})
else
return Promise.as(j.text);
} else {
return HelpTopic.getScriptAsync(id);
}
}
return TDev.AST.loadScriptAsync(loadScript).then((tcRes:AST.LoadScriptResult) => {
var s = Script;
setGlobalScript(tcRes.prevScript);
if (this.fromJson)
s.blockExternalLinks = this.fromJson.noexternallinks;
return s;
})
}
public initAsync() : Promise // of app
{
if (!this.json.text && !this.json.id)
return Promise.as(this.app);
if (this.initPromise) return this.initPromise;
this.initPromise = this.reloadAppAsync()
.then(s => { this.app = s; return s });
return this.initPromise
}
public isApiHelp()
{
return !!this.apiProperty
}
public getSig(mdcmt : MdComments, full: boolean) : string
{
var ch = "<div class='md-api-header md-tutorial'>" +
(new Renderer()).renderPropertySig(this.apiProperty, true) +
(!full ? "" :
"<div class='md-prop-desc'>" +
mdcmt.formatText(this.apiProperty.getDescription()) +
"</div>") +
"</div>";
if (full) {
var cap = this.apiProperty.getCapability();
ch += "<div class='md-tutorial'>" +
"<ul>" +
(cap == PlatformCapability.None ? "" :
"<li>" + lf("<strong>required platform:</strong>") + " " + Util.htmlEscape(AST.App.capabilityName(cap))) +
(!this.apiProperty.isBeta() ? "" :
"<li>" + lf("<strong>feature in beta testing:</strong> the syntax and semantics is subject to change")) +
(this.apiProperty.isImplementedAnywhere() ? "" :
"<li><strong>" + lf("API not implemented") + "</strong>, sorry ") +
"</ul>" +
"</div>";
}
if (mdcmt.useExternalLinks)
ch = ch.replace(/#topic(:|%3a)/g, Cloud.config.rootUrl + Cloud.config.topicPath);
return ch;
}
private renderCore(mdcmt : MdComments) : string
{
if (!mdcmt) {
var rend = new Renderer();
rend.stringLimit = 90;
mdcmt = new MdComments(rend, null);
if (this.app)
mdcmt.blockExternalLinks = this.app.blockExternalLinks
}
var ch = ""
if (this.apiProperty)
ch += this.getSig(mdcmt, true);
if (this.app) {
var acts:AST.Action[] = <AST.Action[]> this.app.orderedThings().filter((a) => a instanceof AST.Action);
var noTutorial = acts.some(a => a.getName() == "this is no tutorial")
if (this.apiProperty instanceof AST.LibraryRefAction) {
acts = acts.filter(a => a.getName() == "docs " + this.apiProperty.getName())
} else {
if (this.isTutorial())
acts = acts.filter(a => /^main$/.test(a.getName()));
else {
acts = acts.filter((a) => a.isNormalAction() && /^example/.test(a.getName()))
if (acts.length == 0 && this.app.mainAction()) acts = [this.app.mainAction()];
}
}
acts.forEach((a) => {
ch += mdcmt.extract(a);
})
var tutorialSteps = noTutorial ? [] : AST.Step.splitActions(this.app);
if (tutorialSteps.length > 0 && mdcmt.forWeb)
ch = ch.replace(/<\/div>$/, "<hr class='md-section' data-name='startTutorial' data-arguments='' /></div>")
if (mdcmt.print) {
if (tutorialSteps.length > 0) {
tutorialSteps.forEach((s) => {
if (s.printOut) {
ch += mdcmt.mkDeclSnippet(s.printOut, false, true, "tutorial-step", 1);
}
})
var finalAct = this.app.actions().filter(a => a.getName() == "final")[0];
if (finalAct)
ch += mdcmt.extract(finalAct)
}
}
}
if (this.apiKind && !this.apiProperty) {
var r = this.getSubTopics().map((st) => st.renderLink(mdcmt))
ch += "<div class='md-tutorial'>" + r.join('') + "</div>";
}
if (this.id == "api") {
var r: string[] = [];
var kindTopics = HelpTopic.getAll().filter(st => st.apiKind && !st.apiProperty);
kindTopics.sort((a, b) => Util.stringCompare(a.id, b.id))
r.push('<h3>' + lf("services") + '</h3>');
kindTopics.filter(st => !st.apiKind.isData && !st.apiKind.isObsolete).forEach((st) => HelpTopic.renderKindDecl(r,st, mdcmt));
r.push('<h3>' + lf("types") + '</h3>');
kindTopics.filter(st => st.apiKind.isData && !st.apiKind.isAction && !st.apiKind.isObsolete).forEach((st) => HelpTopic.renderKindDecl(r, st, mdcmt));
r.push('<h3>' + lf("function types") + '</h3>');
kindTopics.filter(st => st.apiKind.isData && st.apiKind.isAction && !st.apiKind.isObsolete).forEach((st) => HelpTopic.renderKindDecl(r, st, mdcmt));
ch += "<div class='md-tutorial'>" + r.join('') + "</div>";
}
return ch;
}
public isPropertyHelp() { return !!this.apiProperty; }
public getSubTopics():HelpTopic[]
{
var names = Object.keys(this.subTopics);
names.sort(Util.stringCompare);
return names.map((k) => this.subTopics[k])
}
private renderTranslated() {
if (this.translatedTopic && this.translatedTopic.body) {
var ch = "<div class='md-tutorial' dir='auto'>" +
this.translatedTopic.body.join('\n') +
"</div>";
return ch;
}
return undefined;
}
public renderAsync(mdcmt : MdComments = null) : Promise // string
{
return this.initAsync().then(() => {
var prevScript = Script;
try {
setGlobalScript(this.app);
return this.renderCore(mdcmt);
} finally {
setGlobalScript(prevScript);
}
})
}
public docInfoAsync() : Promise // of HelpTopicInfoJson
{
var md = new TDev.MdComments(new TDev.CopyRenderer());
md.useSVG = false;
md.showCopy = false;
// md.useExternalLinks = true;
var ht = this
return this.renderAsync(md)
.then(text => {
var r = <HelpTopicInfoJson>{
title: "<h1>" + TDev.Util.htmlEscape(ht.json.name) + "</h1>",
description: ht.isApiHelp() ? "" : "<p>" + TDev.Util.htmlEscape(ht.json.description) + "</p>",
body: MdComments.splitDivs(text),
}
var translations = ht.translations();
if (translations) r.translations = translations;
return r;
})
}
public renderHeader()
{
var r = div(null);
this.initAsync().done(() => {
var appName = this.app.getName().replace(/ tutorial$/, "");
// remove any text before ':'
var i = appName.indexOf(':');
if (i > 0) appName = appName.substr(i+1);
else appName = lf("tutorial: ") + appName;
r.setChildren(appName)
})
return r;
}
public render(whenDone:(e:HTMLElement)=>void)
{
var d = div(null);
d.style.marginRight = "0.2em";
this.translateAsync(Util.getTranslationLanguage())
.then(() => this.renderAsync())
.done((text) => {
var translatedDocs = this.renderTranslated();
if (!translatedDocs)
Browser.setInnerHTML(d, text);
else if (this.translatedTopic && this.translatedTopic.manual) {
Browser.setInnerHTML(d, translatedDocs);
} else {
var elementDiv = <HTMLDivElement>div('');
Browser.setInnerHTML(elementDiv, text);
var trElementDiv = <HTMLDivElement>div('');
Browser.setInnerHTML(trElementDiv, translatedDocs);
var trNotice = div('translate-notice', lf("Translations by Microsoft® Translator, tap to see original..."))
.withClick(() => {
trElementDiv.style.display = 'none';
elementDiv.style.display = 'block';
Util.seeTranslatedText(false);
});
trElementDiv.insertBefore(trNotice, trElementDiv.firstElementChild);
var elNotice = div('translate-notice', lf("tap to translate with Microsoft® Translator..."))
.withClick(() => {
elementDiv.style.display = 'none';
trElementDiv.style.display = 'block';
Util.seeTranslatedText(true);
})
elementDiv.insertBefore(elNotice, elementDiv.firstElementChild);
if (Util.seeTranslatedText())
elementDiv.style.display = 'none';
else
trElementDiv.style.display = 'none';
d.setChildren([elementDiv, trElementDiv]);
}
HTML.fixWp8Links(d);
whenDone(d);
})
return d;
}
static printManyAsync(topics:HelpTopic[])
{
return Promise.join(topics.map(t => t.printedAsync())).then(arr =>
HelpTopic.printText(arr.join("<div style='page-break-after:always'></div>\n"), "Help"))
}
public printedAsync(newsletter = false)
{
var r = new CopyRenderer();
var md = new MdComments(r);
md.scriptid = this.json.id;
md.useSVG = false;
md.useExternalLinks = true;
md.showCopy = false;
md.print = true;
return this.renderAsync(md).then((text) => {
if (newsletter)
return CopyRenderer.inlineStyles(text);
else
return (
"<h1>" + Util.htmlEscape(this.json.name) + "</h1>" +
text)
})
}
static printText(text:string, title:string)
{
try {
var w = window.open("about:blank", "tdTopic" + Util.guidGen());
var html = "<!DOCTYPE html><html><head>" + CopyRenderer.css
+ "<title>" + Util.htmlEscape(title) + "</title>"
+ "<meta name='microsoft' content='notranslateclasses stmt keyword'/>"
+ "</head><body onload='try { window.print(); } catch(ex) {}'>"
+ text
+ "</body></html>";
w.document.write(html);
w.document.close();
} catch(e) {
ModalDialog.info(":( can't print from here", lf("Your browser might have blocked the print page or try to print from another device..."));
}
}
public print()
{
this.printedAsync().done(text => HelpTopic.printText(text, this.json.name))
}
static renderKindDecl(r : string[], st : HelpTopic, mdcmt:MdComments) {
var j = st.json;
var n = j.name;
if (!st.apiKind.isData) n = n.toLowerCase();
r.push("<div class='api-kind'><a href='" + mdcmt.topicLink(st.id) + "'>");
r.push("<div class='api-kind-inner'>");
// without SVG we don't do any icons at the moment; in future see below
if (mdcmt.useSVG)
r.push("<span class='api-icon' style='background:" + j.iconbackground + "'>" +
(mdcmt.useSVG ? SVG.getIconSVGCore(j.icon + ",white") :
"<img src='/replaceicons/" + j.icon + ".png' alt='" + j.icon + "'>") + "</span>");
r.push("<div class='api-names'><div class='api-name'>" + Util.htmlEscape(n) + "</div>");
r.push("<div class='api-desc'>" + Util.htmlEscape(j.description) + "</div>");
r.push("</div></div></a></div>");
}
static topicCache:StringMap<HelpTopic>;
static topicByScriptId:StringMap<HelpTopic>;
static findById(id:string):HelpTopic
{
// deprecated in lite
if (Cloud.isRestricted()) return null;
// make sure things are initialized
HelpTopic.getAll();
if (id)
id = id.replace(/^t:/, "")
id = MdComments.shrink(id)
if (HelpTopic.topicCache.hasOwnProperty(id))
return HelpTopic.topicCache[id];
return null;
}
}
} | the_stack |
export namespace TenantManagementModels {
/**
*
* @export
* @class RequiredError
* @extends {Error}
*/
export class RequiredError extends Error {
name: "RequiredError" = "RequiredError";
constructor(public field: string, msg?: string) {
super(msg);
}
}
/**
*
* @export
* @interface ErrorResponse
*/
export interface ErrorResponse {
/**
*
* @type {string}
* @memberof ErrorResponse
*/
errorMessage?: string;
/**
*
* @type {string}
* @memberof ErrorResponse
*/
errorType?: ErrorResponse.ErrorTypeEnum;
/**
*
* @type {Array<FieldError>}
* @memberof ErrorResponse
*/
fieldErrors?: Array<FieldError>;
/**
*
* @type {string}
* @memberof ErrorResponse
*/
logref?: string;
}
/**
* @export
* @namespace ErrorResponse
*/
export namespace ErrorResponse {
/**
* @export
* @enum {string}
*/
export enum ErrorTypeEnum {
FIELDERROR = <any>"FIELD_ERROR",
UNEXPECTEDERROR = <any>"UNEXPECTED_ERROR",
INVALIDSTATE = <any>"INVALID_STATE",
PARSINGERROR = <any>"PARSING_ERROR",
}
}
/**
*
* @export
* @interface FieldError
*/
export interface FieldError {
/**
*
* @type {string}
* @memberof FieldError
*/
errorMessage?: string;
/**
*
* @type {string}
* @memberof FieldError
*/
errorType?: FieldError.ErrorTypeEnum;
/**
*
* @type {string}
* @memberof FieldError
*/
field?: string;
}
/**
* @export
* @namespace FieldError
*/
export namespace FieldError {
/**
* @export
* @enum {string}
*/
export enum ErrorTypeEnum {
INVALIDINPUT = <any>"INVALID_INPUT",
VALIDATIONERROR = <any>"VALIDATION_ERROR",
NOTALLOWED = <any>"NOT_ALLOWED",
UNIQUECONSTRAINTERROR = <any>"UNIQUE_CONSTRAINT_ERROR",
}
}
/**
*
* @export
* @interface LegalConfiguration
*/
export interface LegalConfiguration {
/**
*
* @type {Array<Region>}
* @memberof LegalConfiguration
*/
regions: Array<Region>;
}
/**
*
* @export
* @interface LegalConfigurationResource
*/
export interface LegalConfigurationResource {
/**
*
* @type {Array<RegionResource>}
* @memberof LegalConfigurationResource
*/
regions?: Array<RegionResource>;
}
/**
*
* @export
* @interface Link
*/
export interface Link {
/**
*
* @type {string}
* @memberof Link
*/
name: string;
/**
*
* @type {string}
* @memberof Link
*/
value: string;
}
/**
*
* @export
* @interface LinkCollection
*/
export interface LinkCollection {
/**
*
* @type {string}
* @memberof LinkCollection
*/
id: string;
/**
*
* @type {string}
* @memberof LinkCollection
*/
type: LinkCollection.TypeEnum;
/**
*
* @type {number}
* @memberof LinkCollection
*/
sorting?: number;
/**
*
* @type {{ [key: string]: Link; }}
* @memberof LinkCollection
*/
languages: { [key: string]: Link };
}
/**
* @export
* @namespace LinkCollection
*/
export namespace LinkCollection {
/**
* @export
* @enum {string}
*/
export enum TypeEnum {
Www = <any>"www",
Phone = <any>"phone",
Mail = <any>"mail",
}
}
/**
* Legal Info
*
* ! Fix: This was manually created in 3.12.0 as MindSphere has a copy/paste error
* ! saying that LegalInfo methods return LegalConfiguration
*
* @export
* @interface LegalInfo
*/
export interface LegalInfo {
[key: string]: LegalInfoLink[];
}
/**
* Legal Info Link
*
* ! Fix: This was manually created in 3.12.0 as MindSphere has a copy/paste error
* ! saying that LegalInfo methods return LegalConfiguration
*
* @export
* @interface LegalInfoLink
*/
export interface LegalInfoLink {
id: string;
type: string;
name: string;
value: string;
}
/**
*
* @export
* @interface MdspError
*/
export interface MdspError {
/**
*
* @type {string}
* @memberof MdspError
*/
code?: string;
/**
*
* @type {string}
* @memberof MdspError
*/
logref?: string;
/**
*
* @type {string}
* @memberof MdspError
*/
message?: string;
}
/**
*
* @export
* @interface MdspErrors
*/
export interface MdspErrors {
/**
*
* @type {Array<MdspError>}
* @memberof MdspErrors
*/
errors?: Array<MdspError>;
}
/**
*
* @export
* @interface PageSubtenantResource
*/
export interface PageSubtenantResource {
/**
*
* @type {Array<SubtenantResource>}
* @memberof PageSubtenantResource
*/
content?: Array<SubtenantResource>;
/**
*
* @type {boolean}
* @memberof PageSubtenantResource
*/
first?: boolean;
/**
*
* @type {boolean}
* @memberof PageSubtenantResource
*/
last?: boolean;
/**
*
* @type {number}
* @memberof PageSubtenantResource
*/
number?: number;
/**
*
* @type {number}
* @memberof PageSubtenantResource
*/
numberOfElements?: number;
/**
*
* @type {number}
* @memberof PageSubtenantResource
*/
size?: number;
/**
*
* @type {Sort}
* @memberof PageSubtenantResource
*/
sort?: Sort;
/**
*
* @type {number}
* @memberof PageSubtenantResource
*/
totalElements?: number;
/**
*
* @type {number}
* @memberof PageSubtenantResource
*/
totalPages?: number;
}
/**
*
* @export
* @interface Region
*/
export interface Region {
/**
*
* @type {string}
* @memberof Region
*/
regionId?: string;
/**
*
* @type {string}
* @memberof Region
*/
regionName: string;
/**
*
* @type {Array<string>}
* @memberof Region
*/
regionCountries?: Array<string>;
/**
*
* @type {Array<LinkCollection>}
* @memberof Region
*/
links?: Array<LinkCollection>;
}
/**
*
* @export
* @interface RegionResource
*/
export interface RegionResource {
/**
*
* @type {number}
* @memberof RegionResource
*/
ETag?: number;
/**
*
* @type {Array<LinkCollection>}
* @memberof RegionResource
*/
links?: Array<LinkCollection>;
/**
*
* @type {Array<string>}
* @memberof RegionResource
*/
regionCountries?: Array<string>;
/**
*
* @type {string}
* @memberof RegionResource
*/
regionId?: string;
/**
*
* @type {string}
* @memberof RegionResource
*/
regionName?: string;
}
/**
*
* @export
* @interface Sort
*/
export interface Sort {
/**
*
* @type {boolean}
* @memberof Sort
*/
sorted?: boolean;
/**
*
* @type {boolean}
* @memberof Sort
*/
unsorted?: boolean;
/**
*
* @type {boolean}
* @memberof Sort
*/
empty?: boolean;
}
/**
*
* @export
* @interface Subtenant
*/
export interface Subtenant {
/**
* A universally unique identifier.
* @type {string}
* @memberof Subtenant
*/
id: string;
/**
*
* @type {string}
* @memberof Subtenant
*/
displayName: string;
/**
*
* @type {string}
* @memberof Subtenant
*/
description: string;
}
/**
*
* @export
* @interface SubtenantResource
*/
export interface SubtenantResource {
/**
*
* @type {number}
* @memberof SubtenantResource
*/
ETag?: number;
/**
*
* @type {string}
* @memberof SubtenantResource
*/
description?: string;
/**
*
* @type {string}
* @memberof SubtenantResource
*/
displayName?: string;
/**
*
* @type {string}
* @memberof SubtenantResource
*/
entityId?: string;
/**
*
* @type {string}
* @memberof SubtenantResource
*/
id?: string;
}
/**
*
* @export
* @interface SubtenantUpdateProperties
*/
export interface SubtenantUpdateProperties {
/**
*
* @type {string}
* @memberof SubtenantUpdateProperties
*/
displayName?: string;
/**
*
* @type {string}
* @memberof SubtenantUpdateProperties
*/
description?: string;
}
/**
*
* @export
* @interface TenantInfo
*/
export interface TenantInfo {
/**
*
* @type {number}
* @memberof TenantInfo
*/
ETag?: number;
/**
*
* @type {boolean}
* @memberof TenantInfo
*/
allowedToCreateSubtenant?: boolean;
/**
*
* @type {string}
* @memberof TenantInfo
*/
companyName?: string;
/**
*
* @type {string}
* @memberof TenantInfo
*/
country?: string;
/**
*
* @type {string}
* @memberof TenantInfo
*/
displayName?: string;
/**
*
* @type {string}
* @memberof TenantInfo
*/
name?: string;
/**
*
* @type {string}
* @memberof TenantInfo
*/
prefix?: string;
/**
*
* @type {string}
* @memberof TenantInfo
*/
type?: TenantInfo.TypeEnum;
}
/**
* @export
* @namespace TenantInfo
*/
export namespace TenantInfo {
/**
* @export
* @enum {string}
*/
export enum TypeEnum {
DEVELOPER = <any>"DEVELOPER",
OPERATOR = <any>"OPERATOR",
USER = <any>"USER",
CUSTOMER = <any>"CUSTOMER",
}
}
/**
*
* @export
* @interface TenantInfoUpdateProperties
*/
export interface TenantInfoUpdateProperties {
/**
*
* @type {string}
* @memberof TenantInfoUpdateProperties
*/
companyName?: string;
/**
*
* @type {string}
* @memberof TenantInfoUpdateProperties
*/
displayName?: string;
}
/**
*
* @export
* @interface UploadedFileResource
*/
export interface UploadedFileResource {
/**
*
* @type {number}
* @memberof UploadedFileResource
*/
size?: number;
/**
*
* @type {string}
* @memberof UploadedFileResource
*/
name?: string;
}
} | the_stack |
import * as Gdk from "@gi-types/gdk";
import * as GObject from "@gi-types/gobject";
import * as GLib from "@gi-types/glib";
import * as Graphene from "@gi-types/graphene";
import * as cairo from "@gi-types/cairo";
import * as Pango from "@gi-types/pango";
export function serialization_error_quark(): GLib.Quark;
export function transform_parse(string: string): [boolean, Transform];
export type ParseErrorFunc = (start: ParseLocation, end: ParseLocation, error: GLib.Error) => void;
export namespace BlendMode {
export const $gtype: GObject.GType<BlendMode>;
}
export enum BlendMode {
DEFAULT = 0,
MULTIPLY = 1,
SCREEN = 2,
OVERLAY = 3,
DARKEN = 4,
LIGHTEN = 5,
COLOR_DODGE = 6,
COLOR_BURN = 7,
HARD_LIGHT = 8,
SOFT_LIGHT = 9,
DIFFERENCE = 10,
EXCLUSION = 11,
COLOR = 12,
HUE = 13,
SATURATION = 14,
LUMINOSITY = 15,
}
export namespace Corner {
export const $gtype: GObject.GType<Corner>;
}
export enum Corner {
TOP_LEFT = 0,
TOP_RIGHT = 1,
BOTTOM_RIGHT = 2,
BOTTOM_LEFT = 3,
}
export namespace GLUniformType {
export const $gtype: GObject.GType<GLUniformType>;
}
export enum GLUniformType {
NONE = 0,
FLOAT = 1,
INT = 2,
UINT = 3,
BOOL = 4,
VEC2 = 5,
VEC3 = 6,
VEC4 = 7,
}
export namespace RenderNodeType {
export const $gtype: GObject.GType<RenderNodeType>;
}
export enum RenderNodeType {
NOT_A_RENDER_NODE = 0,
CONTAINER_NODE = 1,
CAIRO_NODE = 2,
COLOR_NODE = 3,
LINEAR_GRADIENT_NODE = 4,
REPEATING_LINEAR_GRADIENT_NODE = 5,
RADIAL_GRADIENT_NODE = 6,
REPEATING_RADIAL_GRADIENT_NODE = 7,
CONIC_GRADIENT_NODE = 8,
BORDER_NODE = 9,
TEXTURE_NODE = 10,
INSET_SHADOW_NODE = 11,
OUTSET_SHADOW_NODE = 12,
TRANSFORM_NODE = 13,
OPACITY_NODE = 14,
COLOR_MATRIX_NODE = 15,
REPEAT_NODE = 16,
CLIP_NODE = 17,
ROUNDED_CLIP_NODE = 18,
SHADOW_NODE = 19,
BLEND_NODE = 20,
CROSS_FADE_NODE = 21,
TEXT_NODE = 22,
BLUR_NODE = 23,
DEBUG_NODE = 24,
GL_SHADER_NODE = 25,
}
export namespace ScalingFilter {
export const $gtype: GObject.GType<ScalingFilter>;
}
export enum ScalingFilter {
LINEAR = 0,
NEAREST = 1,
TRILINEAR = 2,
}
export class SerializationError extends GLib.Error {
static $gtype: GObject.GType<SerializationError>;
constructor(options: { message: string; code: number });
constructor(copy: SerializationError);
// Properties
static UNSUPPORTED_FORMAT: number;
static UNSUPPORTED_VERSION: number;
static INVALID_DATA: number;
// Members
static quark(): GLib.Quark;
}
export namespace TransformCategory {
export const $gtype: GObject.GType<TransformCategory>;
}
export enum TransformCategory {
UNKNOWN = 0,
ANY = 1,
"3D" = 2,
"2D" = 3,
"2D_AFFINE" = 4,
"2D_TRANSLATE" = 5,
IDENTITY = 6,
}
export module BlendNode {
export interface ConstructorProperties extends RenderNode.ConstructorProperties {
[key: string]: any;
}
}
export class BlendNode extends RenderNode {
static $gtype: GObject.GType<BlendNode>;
constructor(properties?: Partial<BlendNode.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<BlendNode.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](bottom: RenderNode, top: RenderNode, blend_mode: BlendMode): BlendNode;
// Members
get_blend_mode(): BlendMode;
get_bottom_child(): RenderNode;
get_top_child(): RenderNode;
}
export module BlurNode {
export interface ConstructorProperties extends RenderNode.ConstructorProperties {
[key: string]: any;
}
}
export class BlurNode extends RenderNode {
static $gtype: GObject.GType<BlurNode>;
constructor(properties?: Partial<BlurNode.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<BlurNode.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](child: RenderNode, radius: number): BlurNode;
// Members
get_child(): RenderNode;
get_radius(): number;
}
export module BorderNode {
export interface ConstructorProperties extends RenderNode.ConstructorProperties {
[key: string]: any;
}
}
export class BorderNode extends RenderNode {
static $gtype: GObject.GType<BorderNode>;
constructor(properties?: Partial<BorderNode.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<BorderNode.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](outline: RoundedRect, border_width: number[], border_color: Gdk.RGBA[]): BorderNode;
// Members
get_colors(): Gdk.RGBA;
get_outline(): RoundedRect;
get_widths(): number[];
}
export module CairoNode {
export interface ConstructorProperties extends RenderNode.ConstructorProperties {
[key: string]: any;
}
}
export class CairoNode extends RenderNode {
static $gtype: GObject.GType<CairoNode>;
constructor(properties?: Partial<CairoNode.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<CairoNode.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](bounds: Graphene.Rect): CairoNode;
// Members
get_draw_context(): cairo.Context;
get_surface(): cairo.Surface;
}
export module CairoRenderer {
export interface ConstructorProperties extends Renderer.ConstructorProperties {
[key: string]: any;
}
}
export class CairoRenderer extends Renderer {
static $gtype: GObject.GType<CairoRenderer>;
constructor(properties?: Partial<CairoRenderer.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<CairoRenderer.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](): CairoRenderer;
}
export module ClipNode {
export interface ConstructorProperties extends RenderNode.ConstructorProperties {
[key: string]: any;
}
}
export class ClipNode extends RenderNode {
static $gtype: GObject.GType<ClipNode>;
constructor(properties?: Partial<ClipNode.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<ClipNode.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](child: RenderNode, clip: Graphene.Rect): ClipNode;
// Members
get_child(): RenderNode;
get_clip(): Graphene.Rect;
}
export module ColorMatrixNode {
export interface ConstructorProperties extends RenderNode.ConstructorProperties {
[key: string]: any;
}
}
export class ColorMatrixNode extends RenderNode {
static $gtype: GObject.GType<ColorMatrixNode>;
constructor(properties?: Partial<ColorMatrixNode.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<ColorMatrixNode.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](child: RenderNode, color_matrix: Graphene.Matrix, color_offset: Graphene.Vec4): ColorMatrixNode;
// Members
get_child(): RenderNode;
get_color_matrix(): Graphene.Matrix;
get_color_offset(): Graphene.Vec4;
}
export module ColorNode {
export interface ConstructorProperties extends RenderNode.ConstructorProperties {
[key: string]: any;
}
}
export class ColorNode extends RenderNode {
static $gtype: GObject.GType<ColorNode>;
constructor(properties?: Partial<ColorNode.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<ColorNode.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](rgba: Gdk.RGBA, bounds: Graphene.Rect): ColorNode;
// Members
get_color(): Gdk.RGBA;
}
export module ConicGradientNode {
export interface ConstructorProperties extends RenderNode.ConstructorProperties {
[key: string]: any;
}
}
export class ConicGradientNode extends RenderNode {
static $gtype: GObject.GType<ConicGradientNode>;
constructor(properties?: Partial<ConicGradientNode.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<ConicGradientNode.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](
bounds: Graphene.Rect,
center: Graphene.Point,
rotation: number,
color_stops: ColorStop[]
): ConicGradientNode;
// Members
get_center(): Graphene.Point;
get_color_stops(): ColorStop[];
get_n_color_stops(): number;
get_rotation(): number;
}
export module ContainerNode {
export interface ConstructorProperties extends RenderNode.ConstructorProperties {
[key: string]: any;
}
}
export class ContainerNode extends RenderNode {
static $gtype: GObject.GType<ContainerNode>;
constructor(properties?: Partial<ContainerNode.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<ContainerNode.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](children: RenderNode[]): ContainerNode;
// Members
get_child(idx: number): RenderNode;
get_n_children(): number;
}
export module CrossFadeNode {
export interface ConstructorProperties extends RenderNode.ConstructorProperties {
[key: string]: any;
}
}
export class CrossFadeNode extends RenderNode {
static $gtype: GObject.GType<CrossFadeNode>;
constructor(properties?: Partial<CrossFadeNode.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<CrossFadeNode.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](start: RenderNode, end: RenderNode, progress: number): CrossFadeNode;
// Members
get_end_child(): RenderNode;
get_progress(): number;
get_start_child(): RenderNode;
}
export module DebugNode {
export interface ConstructorProperties extends RenderNode.ConstructorProperties {
[key: string]: any;
}
}
export class DebugNode extends RenderNode {
static $gtype: GObject.GType<DebugNode>;
constructor(properties?: Partial<DebugNode.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<DebugNode.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](child: RenderNode, message: string): DebugNode;
// Members
get_child(): RenderNode;
get_message(): string;
}
export module GLRenderer {
export interface ConstructorProperties extends Renderer.ConstructorProperties {
[key: string]: any;
}
}
export class GLRenderer extends Renderer {
static $gtype: GObject.GType<GLRenderer>;
constructor(properties?: Partial<GLRenderer.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<GLRenderer.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](): GLRenderer;
}
export module GLShader {
export interface ConstructorProperties extends GObject.Object.ConstructorProperties {
[key: string]: any;
resource: string;
source: GLib.Bytes;
}
}
export class GLShader extends GObject.Object {
static $gtype: GObject.GType<GLShader>;
constructor(properties?: Partial<GLShader.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<GLShader.ConstructorProperties>, ...args: any[]): void;
// Properties
resource: string;
source: GLib.Bytes;
// Constructors
static new_from_bytes(sourcecode: GLib.Bytes | Uint8Array): GLShader;
static new_from_resource(resource_path: string): GLShader;
// Members
compile(renderer: Renderer): boolean;
find_uniform_by_name(name: string): number;
get_arg_bool(args: GLib.Bytes | Uint8Array, idx: number): boolean;
get_arg_float(args: GLib.Bytes | Uint8Array, idx: number): number;
get_arg_int(args: GLib.Bytes | Uint8Array, idx: number): number;
get_arg_uint(args: GLib.Bytes | Uint8Array, idx: number): number;
get_arg_vec2(args: GLib.Bytes | Uint8Array, idx: number, out_value: Graphene.Vec2): void;
get_arg_vec3(args: GLib.Bytes | Uint8Array, idx: number, out_value: Graphene.Vec3): void;
get_arg_vec4(args: GLib.Bytes | Uint8Array, idx: number, out_value: Graphene.Vec4): void;
get_args_size(): number;
get_n_textures(): number;
get_n_uniforms(): number;
get_resource(): string;
get_source(): GLib.Bytes;
get_uniform_name(idx: number): string;
get_uniform_offset(idx: number): number;
get_uniform_type(idx: number): GLUniformType;
}
export module GLShaderNode {
export interface ConstructorProperties extends RenderNode.ConstructorProperties {
[key: string]: any;
}
}
export class GLShaderNode extends RenderNode {
static $gtype: GObject.GType<GLShaderNode>;
constructor(properties?: Partial<GLShaderNode.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<GLShaderNode.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](
shader: GLShader,
bounds: Graphene.Rect,
args: GLib.Bytes | Uint8Array,
children: RenderNode[]
): GLShaderNode;
// Members
get_args(): GLib.Bytes;
get_child(idx: number): RenderNode;
get_n_children(): number;
get_shader(): GLShader;
}
export module InsetShadowNode {
export interface ConstructorProperties extends RenderNode.ConstructorProperties {
[key: string]: any;
}
}
export class InsetShadowNode extends RenderNode {
static $gtype: GObject.GType<InsetShadowNode>;
constructor(properties?: Partial<InsetShadowNode.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<InsetShadowNode.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](
outline: RoundedRect,
color: Gdk.RGBA,
dx: number,
dy: number,
spread: number,
blur_radius: number
): InsetShadowNode;
// Members
get_blur_radius(): number;
get_color(): Gdk.RGBA;
get_dx(): number;
get_dy(): number;
get_outline(): RoundedRect;
get_spread(): number;
}
export module LinearGradientNode {
export interface ConstructorProperties extends RenderNode.ConstructorProperties {
[key: string]: any;
}
}
export class LinearGradientNode extends RenderNode {
static $gtype: GObject.GType<LinearGradientNode>;
constructor(properties?: Partial<LinearGradientNode.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<LinearGradientNode.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](
bounds: Graphene.Rect,
start: Graphene.Point,
end: Graphene.Point,
color_stops: ColorStop[]
): LinearGradientNode;
// Members
get_color_stops(): ColorStop[];
get_end(): Graphene.Point;
get_n_color_stops(): number;
get_start(): Graphene.Point;
}
export module OpacityNode {
export interface ConstructorProperties extends RenderNode.ConstructorProperties {
[key: string]: any;
}
}
export class OpacityNode extends RenderNode {
static $gtype: GObject.GType<OpacityNode>;
constructor(properties?: Partial<OpacityNode.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<OpacityNode.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](child: RenderNode, opacity: number): OpacityNode;
// Members
get_child(): RenderNode;
get_opacity(): number;
}
export module OutsetShadowNode {
export interface ConstructorProperties extends RenderNode.ConstructorProperties {
[key: string]: any;
}
}
export class OutsetShadowNode extends RenderNode {
static $gtype: GObject.GType<OutsetShadowNode>;
constructor(properties?: Partial<OutsetShadowNode.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<OutsetShadowNode.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](
outline: RoundedRect,
color: Gdk.RGBA,
dx: number,
dy: number,
spread: number,
blur_radius: number
): OutsetShadowNode;
// Members
get_blur_radius(): number;
get_color(): Gdk.RGBA;
get_dx(): number;
get_dy(): number;
get_outline(): RoundedRect;
get_spread(): number;
}
export module RadialGradientNode {
export interface ConstructorProperties extends RenderNode.ConstructorProperties {
[key: string]: any;
}
}
export class RadialGradientNode extends RenderNode {
static $gtype: GObject.GType<RadialGradientNode>;
constructor(properties?: Partial<RadialGradientNode.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<RadialGradientNode.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](
bounds: Graphene.Rect,
center: Graphene.Point,
hradius: number,
vradius: number,
start: number,
end: number,
color_stops: ColorStop[]
): RadialGradientNode;
// Members
get_center(): Graphene.Point;
get_color_stops(): ColorStop[];
get_end(): number;
get_hradius(): number;
get_n_color_stops(): number;
get_start(): number;
get_vradius(): number;
}
export module RenderNode {
export interface ConstructorProperties {
[key: string]: any;
}
}
export abstract class RenderNode {
static $gtype: GObject.GType<RenderNode>;
constructor(properties?: Partial<RenderNode.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<RenderNode.ConstructorProperties>, ...args: any[]): void;
// Members
draw(cr: cairo.Context): void;
get_bounds(): Graphene.Rect;
get_node_type(): RenderNodeType;
ref(): RenderNode;
serialize(): GLib.Bytes;
unref(): void;
write_to_file(filename: string): boolean;
static deserialize(bytes: GLib.Bytes | Uint8Array): RenderNode | null;
}
export module Renderer {
export interface ConstructorProperties extends GObject.Object.ConstructorProperties {
[key: string]: any;
realized: boolean;
surface: Gdk.Surface;
}
}
export abstract class Renderer extends GObject.Object {
static $gtype: GObject.GType<Renderer>;
constructor(properties?: Partial<Renderer.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<Renderer.ConstructorProperties>, ...args: any[]): void;
// Properties
realized: boolean;
surface: Gdk.Surface;
// Constructors
static new_for_surface(surface: Gdk.Surface): Renderer;
// Members
get_surface(): Gdk.Surface | null;
is_realized(): boolean;
realize(surface: Gdk.Surface): boolean;
render(root: RenderNode, region?: cairo.Region | null): void;
render_texture(root: RenderNode, viewport?: Graphene.Rect | null): Gdk.Texture;
unrealize(): void;
}
export module RepeatNode {
export interface ConstructorProperties extends RenderNode.ConstructorProperties {
[key: string]: any;
}
}
export class RepeatNode extends RenderNode {
static $gtype: GObject.GType<RepeatNode>;
constructor(properties?: Partial<RepeatNode.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<RepeatNode.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](bounds: Graphene.Rect, child: RenderNode, child_bounds?: Graphene.Rect | null): RepeatNode;
// Members
get_child(): RenderNode;
get_child_bounds(): Graphene.Rect;
}
export module RepeatingLinearGradientNode {
export interface ConstructorProperties extends RenderNode.ConstructorProperties {
[key: string]: any;
}
}
export class RepeatingLinearGradientNode extends RenderNode {
static $gtype: GObject.GType<RepeatingLinearGradientNode>;
constructor(properties?: Partial<RepeatingLinearGradientNode.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<RepeatingLinearGradientNode.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](
bounds: Graphene.Rect,
start: Graphene.Point,
end: Graphene.Point,
color_stops: ColorStop[]
): RepeatingLinearGradientNode;
}
export module RepeatingRadialGradientNode {
export interface ConstructorProperties extends RenderNode.ConstructorProperties {
[key: string]: any;
}
}
export class RepeatingRadialGradientNode extends RenderNode {
static $gtype: GObject.GType<RepeatingRadialGradientNode>;
constructor(properties?: Partial<RepeatingRadialGradientNode.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<RepeatingRadialGradientNode.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](
bounds: Graphene.Rect,
center: Graphene.Point,
hradius: number,
vradius: number,
start: number,
end: number,
color_stops: ColorStop[]
): RepeatingRadialGradientNode;
}
export module RoundedClipNode {
export interface ConstructorProperties extends RenderNode.ConstructorProperties {
[key: string]: any;
}
}
export class RoundedClipNode extends RenderNode {
static $gtype: GObject.GType<RoundedClipNode>;
constructor(properties?: Partial<RoundedClipNode.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<RoundedClipNode.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](child: RenderNode, clip: RoundedRect): RoundedClipNode;
// Members
get_child(): RenderNode;
get_clip(): RoundedRect;
}
export module ShadowNode {
export interface ConstructorProperties extends RenderNode.ConstructorProperties {
[key: string]: any;
}
}
export class ShadowNode extends RenderNode {
static $gtype: GObject.GType<ShadowNode>;
constructor(properties?: Partial<ShadowNode.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<ShadowNode.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](child: RenderNode, shadows: Shadow[]): ShadowNode;
// Members
get_child(): RenderNode;
get_n_shadows(): number;
get_shadow(i: number): Shadow;
}
export module TextNode {
export interface ConstructorProperties extends RenderNode.ConstructorProperties {
[key: string]: any;
}
}
export class TextNode extends RenderNode {
static $gtype: GObject.GType<TextNode>;
constructor(properties?: Partial<TextNode.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<TextNode.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](font: Pango.Font, glyphs: Pango.GlyphString, color: Gdk.RGBA, offset: Graphene.Point): TextNode;
// Members
get_color(): Gdk.RGBA;
get_font(): Pango.Font;
get_glyphs(): Pango.GlyphInfo[];
get_num_glyphs(): number;
get_offset(): Graphene.Point;
has_color_glyphs(): boolean;
}
export module TextureNode {
export interface ConstructorProperties extends RenderNode.ConstructorProperties {
[key: string]: any;
}
}
export class TextureNode extends RenderNode {
static $gtype: GObject.GType<TextureNode>;
constructor(properties?: Partial<TextureNode.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<TextureNode.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](texture: Gdk.Texture, bounds: Graphene.Rect): TextureNode;
// Members
get_texture(): Gdk.Texture;
}
export module TransformNode {
export interface ConstructorProperties extends RenderNode.ConstructorProperties {
[key: string]: any;
}
}
export class TransformNode extends RenderNode {
static $gtype: GObject.GType<TransformNode>;
constructor(properties?: Partial<TransformNode.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<TransformNode.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](child: RenderNode, transform: Transform): TransformNode;
// Members
get_child(): RenderNode;
get_transform(): Transform;
}
export module VulkanRenderer {
export interface ConstructorProperties extends Renderer.ConstructorProperties {
[key: string]: any;
}
}
export class VulkanRenderer extends Renderer {
static $gtype: GObject.GType<VulkanRenderer>;
constructor(properties?: Partial<VulkanRenderer.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<VulkanRenderer.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](): VulkanRenderer;
}
export class ColorStop {
static $gtype: GObject.GType<ColorStop>;
constructor(
properties?: Partial<{
offset?: number;
color?: Gdk.RGBA;
}>
);
constructor(copy: ColorStop);
// Fields
offset: number;
color: Gdk.RGBA;
}
export class ParseLocation {
static $gtype: GObject.GType<ParseLocation>;
constructor(
properties?: Partial<{
bytes?: number;
chars?: number;
lines?: number;
line_bytes?: number;
line_chars?: number;
}>
);
constructor(copy: ParseLocation);
// Fields
bytes: number;
chars: number;
lines: number;
line_bytes: number;
line_chars: number;
}
export class RoundedRect {
static $gtype: GObject.GType<RoundedRect>;
constructor(copy: RoundedRect);
// Fields
bounds: Graphene.Rect;
corner: Graphene.Size[];
// Members
contains_point(point: Graphene.Point): boolean;
contains_rect(rect: Graphene.Rect): boolean;
init(
bounds: Graphene.Rect,
top_left: Graphene.Size,
top_right: Graphene.Size,
bottom_right: Graphene.Size,
bottom_left: Graphene.Size
): RoundedRect;
init_copy(src: RoundedRect): RoundedRect;
init_from_rect(bounds: Graphene.Rect, radius: number): RoundedRect;
intersects_rect(rect: Graphene.Rect): boolean;
is_rectilinear(): boolean;
normalize(): RoundedRect;
offset(dx: number, dy: number): RoundedRect;
shrink(top: number, right: number, bottom: number, left: number): RoundedRect;
}
export class ShaderArgsBuilder {
static $gtype: GObject.GType<ShaderArgsBuilder>;
constructor(shader: GLShader, initial_values?: GLib.Bytes | null);
constructor(copy: ShaderArgsBuilder);
// Constructors
static ["new"](shader: GLShader, initial_values?: GLib.Bytes | null): ShaderArgsBuilder;
// Members
ref(): ShaderArgsBuilder;
set_bool(idx: number, value: boolean): void;
set_float(idx: number, value: number): void;
set_int(idx: number, value: number): void;
set_uint(idx: number, value: number): void;
set_vec2(idx: number, value: Graphene.Vec2): void;
set_vec3(idx: number, value: Graphene.Vec3): void;
set_vec4(idx: number, value: Graphene.Vec4): void;
to_args(): GLib.Bytes;
unref(): void;
}
export class Shadow {
static $gtype: GObject.GType<Shadow>;
constructor(
properties?: Partial<{
color?: Gdk.RGBA;
dx?: number;
dy?: number;
radius?: number;
}>
);
constructor(copy: Shadow);
// Fields
color: Gdk.RGBA;
dx: number;
dy: number;
radius: number;
}
export class Transform {
static $gtype: GObject.GType<Transform>;
constructor();
constructor(copy: Transform);
// Constructors
static ["new"](): Transform;
// Members
equal(second?: Transform | null): boolean;
get_category(): TransformCategory;
invert(): Transform | null;
matrix(matrix: Graphene.Matrix): Transform;
perspective(depth: number): Transform;
print(string: GLib.String): void;
ref(): Transform;
rotate(angle: number): Transform;
rotate_3d(angle: number, axis: Graphene.Vec3): Transform;
scale(factor_x: number, factor_y: number): Transform;
scale_3d(factor_x: number, factor_y: number, factor_z: number): Transform;
to_2d(): [number, number, number, number, number, number];
to_affine(): [number, number, number, number];
to_matrix(): Graphene.Matrix;
to_string(): string;
to_translate(): [number, number];
transform(other?: Transform | null): Transform;
transform_bounds(rect: Graphene.Rect): Graphene.Rect;
transform_point(point: Graphene.Point): Graphene.Point;
translate(point: Graphene.Point): Transform;
translate_3d(point: Graphene.Point3D): Transform;
unref(): void;
static parse(string: string): [boolean, Transform];
} | the_stack |
import React, { ReactNode } from "react";
import { Redirect, RouteComponentProps } from "react-router-dom";
import { ServiceFactory } from "../../factories/serviceFactory";
import { TrytesHelper } from "../../helpers/trytesHelper";
import { ProtocolVersion } from "../../models/db/protocolVersion";
import { NetworkService } from "../../services/networkService";
import { TangleCacheService } from "../../services/tangleCacheService";
import AsyncComponent from "../components/AsyncComponent";
import Spinner from "../components/Spinner";
import "./Search.scss";
import { SearchRouteProps } from "./SearchRouteProps";
import { SearchState } from "./SearchState";
/**
* Component which will show the search page.
*/
class Search extends AsyncComponent<RouteComponentProps<SearchRouteProps>, SearchState> {
/**
* API Client for tangle requests.
*/
private readonly _tangleCacheService: TangleCacheService;
/**
* Create a new instance of Search.
* @param props The props.
*/
constructor(props: RouteComponentProps<SearchRouteProps>) {
super(props);
const networkService = ServiceFactory.get<NetworkService>("network");
const protocolVersion: ProtocolVersion =
(props.match.params.network && networkService.get(props.match.params.network)?.protocolVersion) || "og";
this._tangleCacheService = ServiceFactory.get<TangleCacheService>("tangle-cache");
this.state = {
protocolVersion,
statusBusy: true,
status: "",
completion: "",
redirect: "",
invalidError: ""
};
}
/**
* The component mounted.
*/
public componentDidMount(): void {
super.componentDidMount();
window.scrollTo(0, 0);
this.updateState();
}
/**
* The component was updated.
* @param prevProps The previous properties.
*/
public componentDidUpdate(prevProps: RouteComponentProps<SearchRouteProps>): void {
if (this.props.location.pathname !== prevProps.location.pathname) {
this.updateState();
}
}
/**
* Render the component.
* @returns The node to render.
*/
public render(): ReactNode {
return this.state.redirect ? (
<Redirect to={this.state.redirect} />
)
: (
<div className="search">
<div className="wrapper">
<div className="inner">
<h1 className="margin-b-s">
Search
</h1>
{!this.state.completion && this.state.status && (
<div className="card">
<div className="card--header">
<h2>Searching</h2>
</div>
<div className="card--content middle row">
{this.state.statusBusy && (<Spinner />)}
<p className="status">
{this.state.status}
</p>
</div>
</div>
)}
{this.state.completion === "notFound" && (
<div className="card">
<div className="card--header">
<h2>Not found</h2>
</div>
<div className="card--content">
{this.state.protocolVersion === "chrysalis" && (
<React.Fragment>
<p>
We could not find any messages, addresses, outputs, milestones
or indexes for the query.
</p>
<br />
<div className="card--value">
<ul>
<li>
<span>Query</span>
<span>{this.props.match.params.query}</span>
</li>
</ul>
</div>
<br />
<p>The following formats are supported:</p>
<br />
<ul>
<li>
<span>Messages</span>
<span>64 Hex characters</span>
</li>
<li>
<span>Message using Transaction Id</span>
<span>64 Hex characters</span>
</li>
<li>
<span>Addresses</span>
<span>64 Hex characters or Bech32 Format</span>
</li>
<li>
<span>Outputs</span>
<span>68 Hex characters</span>
</li>
<li>
<span>Milestone Index</span>
<span>Numeric</span>
</li>
<li>
<span>Indexes</span>
<span>Maximum 64 UTF-8 chars or maximum 128 hex chars</span>
</li>
</ul>
<br />
<p>Please perform another search with a valid hash.</p>
</React.Fragment>
)}
{this.state.protocolVersion === "og" && (
<React.Fragment>
<p>
We could not find any transactions, bundles, addresses or tags
with the provided input.
</p>
<br />
<p className="card--value">
Query: {this.props.match.params.query}
</p>
</React.Fragment>
)}
</div>
</div>
)}
{this.state.completion === "invalid" && (
<div className="card">
<div className="card--header">
<h2>Incorrect query format</h2>
</div>
<div className="card--content">
{this.state.protocolVersion === "og" && (
<React.Fragment>
<p className="danger">
The supplied hash does not appear to be valid, {
this.state.invalidError
}.
</p>
<br />
<p>The following formats are supported:</p>
<br />
<ul>
<li>
<span>Tags</span>
<span><= 27 Trytes</span>
</li>
<li>
<span>Transactions</span>
<span>81 Trytes</span>
</li>
<li>
<span>Bundles</span>
<span>81 Trytes</span>
</li>
<li>
<span>Addresses</span>
<span>81 Trytes or 90 Trytes</span>
</li>
</ul>
<br />
<p>Please perform another search with a valid hash.</p>
</React.Fragment>
)}
{this.state.protocolVersion === "chrysalis" && (
<p className="danger">
{this.state.invalidError}.
</p>
)}
</div>
</div>
)}
</div>
</div>
</div >
);
}
/**
* Update the state of the component.
*/
private updateState(): void {
const query = (this.props.match.params.query ?? "").trim();
let status = "";
let statusBusy = false;
let completion = "";
let redirect = "";
let invalidError = "";
if (query.length > 0) {
if (this.state.protocolVersion === "og") {
if (TrytesHelper.isTrytes(query)) {
if (query.length <= 27) {
redirect = `/${this.props.match.params.network}/tag/${query}`;
} else if (query.length === 90) {
redirect = `/${this.props.match.params.network}/address/${query}`;
} else if (query.length === 81) {
status = "Detecting hash type...";
statusBusy = true;
if (this._isMounted) {
setImmediate(
async () => {
if (this._isMounted) {
const { hashType } = await this._tangleCacheService.findTransactionHashes(
this.props.match.params.network,
undefined,
query
);
if (hashType) {
let ht = "";
if (hashType === "addresses") {
ht = "address";
} else if (hashType === "bundles") {
ht = "bundle";
} else if (hashType === "transaction") {
ht = "transaction";
}
this.setState({
status: "",
statusBusy: false,
redirect: `/${this.props.match.params.network}/${ht}/${query}`
});
} else {
this.setState({
completion: "notFound",
status: "",
statusBusy: false
});
}
}
});
}
} else {
invalidError = `the hash length ${query.length} is not valid`;
completion = "invalid";
}
} else {
invalidError = "the hash is not in trytes format";
completion = "invalid";
}
} else if (this.state.protocolVersion === "chrysalis") {
status = "Detecting query type...";
statusBusy = true;
if (this._isMounted) {
setImmediate(
async () => {
if (this._isMounted) {
const response = await this._tangleCacheService.search(
this.props.match.params.network,
query
);
if (response) {
let objType = "";
let objParam = query;
if (response.message) {
objType = "message";
} else if (response.address) {
objType = "addr";
} else if (response.indexMessageIds) {
objType = "indexed";
} else if (response.output) {
objType = "message";
objParam = response.output.messageId;
} else if (response.milestone) {
objType = "milestone";
}
this.setState({
status: "",
statusBusy: false,
redirect: `/${this.props.match.params.network}/${objType}/${objParam}`
});
} else {
this.setState({
completion: "notFound",
status: "",
statusBusy: false
});
}
}
});
}
}
} else {
invalidError = "the query is empty";
completion = "invalid";
}
this.setState({
statusBusy,
status,
completion,
redirect,
invalidError
});
}
}
export default Search; | the_stack |
import { useState, useEffect } from "react";
import { useDebounce } from "use-debounce";
import useAlgolia from "use-algolia";
import _find from "lodash/find";
import _get from "lodash/get";
import _pick from "lodash/pick";
import createPersistedState from "use-persisted-state";
import { useSnackbar } from "notistack";
import { Button } from "@mui/material";
import MultiSelect, { MultiSelectProps } from "@rowy/multiselect";
import Loading from "@src/components/Loading";
import InlineOpenInNewIcon from "@src/components/InlineOpenInNewIcon";
import { useProjectContext } from "@src/contexts/ProjectContext";
import { runRoutes } from "@src/constants/runRoutes";
import { WIKI_LINKS } from "@src/constants/externalLinks";
const useAlgoliaSearchKeys = createPersistedState(
"__ROWY__ALGOLIA_SEARCH_KEYS"
);
const useAlgoliaAppId = createPersistedState("__ROWY__ALGOLIA_APP_ID");
export type ConnectTableValue = {
docPath: string;
snapshot: Record<string, any>;
};
const replacer = (data: any) => (m: string, key: string) => {
const objKey = key.split(":")[0];
const defaultValue = key.split(":")[1] || "";
return _get(data, objKey, defaultValue);
};
export interface IConnectTableSelectProps {
value: ConnectTableValue[] | ConnectTableValue | null;
onChange: (value: ConnectTableValue[] | ConnectTableValue | null) => void;
column: any;
config: {
filters: string;
primaryKeys: string[];
secondaryKeys?: string[];
snapshotFields?: string[];
trackedFields?: string[];
multiple?: boolean;
searchLabel?: string;
[key: string]: any;
};
disabled?: boolean;
/** Optional style overrides for root MUI `TextField` component */
className?: string;
row: any;
/** Override any props of the root MUI `TextField` component */
TextFieldProps?: MultiSelectProps<ConnectTableValue[]>["TextFieldProps"];
onClose?: MultiSelectProps<ConnectTableValue[]>["onClose"];
/** Load the Algolia index before the MultiSelect onOpen function is triggered */
loadBeforeOpen?: boolean;
}
export default function ConnectTableSelect({
value = [],
onChange,
column,
row,
config,
disabled,
className,
TextFieldProps = {},
onClose,
loadBeforeOpen,
}: IConnectTableSelectProps) {
const { enqueueSnackbar } = useSnackbar();
const { rowyRun } = useProjectContext();
const [algoliaAppId, setAlgoliaAppId] = useAlgoliaAppId<string | undefined>(
undefined
);
useEffect(() => {
if (!algoliaAppId && rowyRun) {
rowyRun({ route: runRoutes.algoliaAppId }).then(
({ success, appId, message }) => {
if (success) setAlgoliaAppId(appId);
else
enqueueSnackbar(
message.replace("not setup", "not set up") +
": Failed to get app ID",
{
variant: "error",
action: (
<Button
href={WIKI_LINKS.fieldTypesConnectTable}
target="_blank"
rel="noopener noreferrer"
>
Docs
<InlineOpenInNewIcon />
</Button>
),
}
);
}
);
}
}, []);
const filters = config.filters
? config.filters.replace(/\{\{(.*?)\}\}/g, replacer(row))
: "";
const algoliaIndex = config.index;
const [algoliaSearchKeys, setAlgoliaSearchKeys] = useAlgoliaSearchKeys<any>(
{}
);
const [algoliaState, requestDispatch, , setAlgoliaConfig] = useAlgolia(
"",
"",
// Don’t choose the index until the user opens the dropdown if !loadBeforeOpen
loadBeforeOpen ? algoliaIndex : "",
{ filters }
);
const setAlgoliaSearchKey = async (algoliaIndex: string) => {
const requestedAt = Date.now() / 1000;
if (
algoliaSearchKeys &&
(algoliaSearchKeys?.[algoliaIndex] as any)?.key &&
requestedAt <
(algoliaSearchKeys?.[algoliaIndex] as any).requestedAt + 3600
) {
//'use existing key'
setAlgoliaConfig({
appId: algoliaAppId,
indexName: algoliaIndex,
searchKey: (algoliaSearchKeys?.[algoliaIndex] as any).key,
});
} else {
//'get new key'
if (rowyRun) {
const resp = await rowyRun({
route: runRoutes.algoliaSearchKey,
params: [algoliaIndex as string],
});
const { key } = resp;
if (key) {
const newKey = {
key,
requestedAt,
};
setAlgoliaSearchKeys(
algoliaSearchKeys
? { ...algoliaSearchKeys, [algoliaIndex]: newKey }
: { [algoliaIndex]: newKey }
);
setAlgoliaConfig({ indexName: algoliaIndex, searchKey: key });
}
}
}
};
useEffect(() => {
setAlgoliaSearchKey(algoliaIndex);
}, [algoliaIndex]);
const options = algoliaState.hits.map((hit) => ({
label: config.primaryKeys?.map((key: string) => hit[key]).join(" "),
value: hit.objectID,
}));
// Store a local copy of the value so the dropdown doesn’t automatically close
// when the user selects a new item and we allow for multiple selections
let initialLocalValue: any;
if (config.multiple !== false) {
initialLocalValue = Array.isArray(value)
? value
: value?.docPath
? [value]
: [];
} else {
initialLocalValue = Array.isArray(value)
? value[0]
: value?.docPath
? value
: null;
}
const [localValue, setLocalValue] = useState(initialLocalValue);
// Pass objectID[] | objectID | null to MultiSelect
const sanitisedValue =
config.multiple !== false
? localValue.map((item) => item.docPath.split("/").pop())
: localValue?.docPath?.split("/").pop() ?? null;
const handleChange = (_newValue: string[] | string | null) => {
let newLocalValue: any;
if (config.multiple !== false && Array.isArray(_newValue)) {
newLocalValue = (_newValue as string[])
.map((objectID) => {
const docPath = `${algoliaIndex}/${objectID}`;
// Try to find the snapshot from the current Algolia query
const match = _find(algoliaState.hits, { objectID });
// If not found and this objectID is already in the previous value,
// use that previous value’s snapshot
// Else return null
if (!match) {
const existingMatch = _find(localValue, { docPath });
if (existingMatch) return existingMatch;
else return null;
}
const { _highlightResult, ...snapshot } = match;
// Use snapshotFields to limit snapshots
let partialSnapshot = snapshot;
if (
Array.isArray(config.snapshotFields) &&
config.snapshotFields.length > 0
)
partialSnapshot = _pick(snapshot, config.snapshotFields);
return { snapshot: partialSnapshot, docPath };
})
.filter((x) => x !== null);
} else if (config.multiple === false && typeof _newValue === "string") {
const docPath = `${algoliaIndex}/${_newValue}`;
// Try to find the snapshot from the current Algolia query
const match = _find(algoliaState.hits, { objectID: _newValue });
// If not found and this objectID is the previous value, use that or null
if (!match) {
if (localValue?.docPath === docPath) newLocalValue = localValue;
else newLocalValue = null;
} else {
const { _highlightResult, ...snapshot } = match;
// Use snapshotFields to limit snapshots
let partialSnapshot = snapshot;
if (
Array.isArray(config.snapshotFields) &&
config.snapshotFields.length > 0
)
partialSnapshot = _pick(snapshot, config.snapshotFields);
newLocalValue = { snapshot: partialSnapshot, docPath };
}
} else if (config.multiple === false && _newValue === null) {
newLocalValue = null;
}
// Store in `localValue` until user closes dropdown and triggers `handleSave`
setLocalValue(newLocalValue);
// If !multiple, we MUST change the value (bypassing localValue),
// otherwise `setLocalValue` won’t be called in time for the new
// `localValue` to be read by `handleSave` because this component is
// unmounted before `handleSave` is called
if (config.multiple === false) onChange(newLocalValue);
};
// Save when user closes dropdown
const handleSave = () => {
if (config.multiple !== false) onChange(localValue);
if (onClose) onClose();
};
// Change MultiSelect input field to search Algolia directly
const [search, setSearch] = useState("");
const [debouncedSearch] = useDebounce(search, 1000);
useEffect(() => {
requestDispatch({ query: debouncedSearch });
}, [debouncedSearch]);
return (
<MultiSelect
value={sanitisedValue}
onChange={handleChange}
onOpen={() => {
setAlgoliaConfig({ indexName: algoliaIndex });
requestDispatch({ filters });
}}
onClose={handleSave}
options={options}
TextFieldProps={{
className,
hiddenLabel: true,
SelectProps: {
renderValue: () => {
if (Array.isArray(localValue)) {
if (localValue.length !== 1)
return `${localValue.length} selected`;
return config.primaryKeys
?.map((key: string) => localValue[0]?.snapshot?.[key])
.join(" ");
} else {
if (!localValue?.snapshot) return "0 selected";
return config.primaryKeys
?.map((key: string) => localValue?.snapshot?.[key])
.join(" ");
}
},
},
...TextFieldProps,
}}
label={column?.name}
labelPlural={config.searchLabel}
multiple={config.multiple !== false}
{...({
AutocompleteProps: {
loading: algoliaState.loading,
loadingText: <Loading />,
inputValue: search,
onInputChange: (_, value, reason) => {
if (reason === "input") setSearch(value);
},
filterOptions: () => options,
},
} as any)}
countText={
Array.isArray(localValue)
? `${localValue.length} of ${algoliaState.response?.nbHits ?? "?"}`
: undefined
}
disabled={disabled}
/>
);
} | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { AssessmentsMetadata } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { SecurityCenter } from "../securityCenter";
import {
SecurityAssessmentMetadataResponse,
AssessmentsMetadataListNextOptionalParams,
AssessmentsMetadataListOptionalParams,
AssessmentsMetadataListBySubscriptionNextOptionalParams,
AssessmentsMetadataListBySubscriptionOptionalParams,
AssessmentsMetadataListResponse,
AssessmentsMetadataGetOptionalParams,
AssessmentsMetadataGetResponse,
AssessmentsMetadataListBySubscriptionResponse,
AssessmentsMetadataGetInSubscriptionOptionalParams,
AssessmentsMetadataGetInSubscriptionResponse,
AssessmentsMetadataCreateInSubscriptionOptionalParams,
AssessmentsMetadataCreateInSubscriptionResponse,
AssessmentsMetadataDeleteInSubscriptionOptionalParams,
AssessmentsMetadataListNextResponse,
AssessmentsMetadataListBySubscriptionNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing AssessmentsMetadata operations. */
export class AssessmentsMetadataImpl implements AssessmentsMetadata {
private readonly client: SecurityCenter;
/**
* Initialize a new instance of the class AssessmentsMetadata class.
* @param client Reference to the service client
*/
constructor(client: SecurityCenter) {
this.client = client;
}
/**
* Get metadata information on all assessment types
* @param options The options parameters.
*/
public list(
options?: AssessmentsMetadataListOptionalParams
): PagedAsyncIterableIterator<SecurityAssessmentMetadataResponse> {
const iter = this.listPagingAll(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listPagingPage(options);
}
};
}
private async *listPagingPage(
options?: AssessmentsMetadataListOptionalParams
): AsyncIterableIterator<SecurityAssessmentMetadataResponse[]> {
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?: AssessmentsMetadataListOptionalParams
): AsyncIterableIterator<SecurityAssessmentMetadataResponse> {
for await (const page of this.listPagingPage(options)) {
yield* page;
}
}
/**
* Get metadata information on all assessment types in a specific subscription
* @param options The options parameters.
*/
public listBySubscription(
options?: AssessmentsMetadataListBySubscriptionOptionalParams
): PagedAsyncIterableIterator<SecurityAssessmentMetadataResponse> {
const iter = this.listBySubscriptionPagingAll(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listBySubscriptionPagingPage(options);
}
};
}
private async *listBySubscriptionPagingPage(
options?: AssessmentsMetadataListBySubscriptionOptionalParams
): AsyncIterableIterator<SecurityAssessmentMetadataResponse[]> {
let result = await this._listBySubscription(options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listBySubscriptionNext(continuationToken, options);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listBySubscriptionPagingAll(
options?: AssessmentsMetadataListBySubscriptionOptionalParams
): AsyncIterableIterator<SecurityAssessmentMetadataResponse> {
for await (const page of this.listBySubscriptionPagingPage(options)) {
yield* page;
}
}
/**
* Get metadata information on all assessment types
* @param options The options parameters.
*/
private _list(
options?: AssessmentsMetadataListOptionalParams
): Promise<AssessmentsMetadataListResponse> {
return this.client.sendOperationRequest({ options }, listOperationSpec);
}
/**
* Get metadata information on an assessment type
* @param assessmentMetadataName The Assessment Key - Unique key for the assessment type
* @param options The options parameters.
*/
get(
assessmentMetadataName: string,
options?: AssessmentsMetadataGetOptionalParams
): Promise<AssessmentsMetadataGetResponse> {
return this.client.sendOperationRequest(
{ assessmentMetadataName, options },
getOperationSpec
);
}
/**
* Get metadata information on all assessment types in a specific subscription
* @param options The options parameters.
*/
private _listBySubscription(
options?: AssessmentsMetadataListBySubscriptionOptionalParams
): Promise<AssessmentsMetadataListBySubscriptionResponse> {
return this.client.sendOperationRequest(
{ options },
listBySubscriptionOperationSpec
);
}
/**
* Get metadata information on an assessment type in a specific subscription
* @param assessmentMetadataName The Assessment Key - Unique key for the assessment type
* @param options The options parameters.
*/
getInSubscription(
assessmentMetadataName: string,
options?: AssessmentsMetadataGetInSubscriptionOptionalParams
): Promise<AssessmentsMetadataGetInSubscriptionResponse> {
return this.client.sendOperationRequest(
{ assessmentMetadataName, options },
getInSubscriptionOperationSpec
);
}
/**
* Create metadata information on an assessment type in a specific subscription
* @param assessmentMetadataName The Assessment Key - Unique key for the assessment type
* @param assessmentMetadata AssessmentMetadata object
* @param options The options parameters.
*/
createInSubscription(
assessmentMetadataName: string,
assessmentMetadata: SecurityAssessmentMetadataResponse,
options?: AssessmentsMetadataCreateInSubscriptionOptionalParams
): Promise<AssessmentsMetadataCreateInSubscriptionResponse> {
return this.client.sendOperationRequest(
{ assessmentMetadataName, assessmentMetadata, options },
createInSubscriptionOperationSpec
);
}
/**
* Delete metadata information on an assessment type in a specific subscription, will cause the
* deletion of all the assessments of that type in that subscription
* @param assessmentMetadataName The Assessment Key - Unique key for the assessment type
* @param options The options parameters.
*/
deleteInSubscription(
assessmentMetadataName: string,
options?: AssessmentsMetadataDeleteInSubscriptionOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ assessmentMetadataName, options },
deleteInSubscriptionOperationSpec
);
}
/**
* ListNext
* @param nextLink The nextLink from the previous successful call to the List method.
* @param options The options parameters.
*/
private _listNext(
nextLink: string,
options?: AssessmentsMetadataListNextOptionalParams
): Promise<AssessmentsMetadataListNextResponse> {
return this.client.sendOperationRequest(
{ nextLink, options },
listNextOperationSpec
);
}
/**
* ListBySubscriptionNext
* @param nextLink The nextLink from the previous successful call to the ListBySubscription method.
* @param options The options parameters.
*/
private _listBySubscriptionNext(
nextLink: string,
options?: AssessmentsMetadataListBySubscriptionNextOptionalParams
): Promise<AssessmentsMetadataListBySubscriptionNextResponse> {
return this.client.sendOperationRequest(
{ nextLink, options },
listBySubscriptionNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const listOperationSpec: coreClient.OperationSpec = {
path: "/providers/Microsoft.Security/assessmentMetadata",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SecurityAssessmentMetadataResponseList
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion10],
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const getOperationSpec: coreClient.OperationSpec = {
path:
"/providers/Microsoft.Security/assessmentMetadata/{assessmentMetadataName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SecurityAssessmentMetadataResponse
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion10],
urlParameters: [Parameters.$host, Parameters.assessmentMetadataName],
headerParameters: [Parameters.accept],
serializer
};
const listBySubscriptionOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/providers/Microsoft.Security/assessmentMetadata",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SecurityAssessmentMetadataResponseList
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion10],
urlParameters: [Parameters.$host, Parameters.subscriptionId],
headerParameters: [Parameters.accept],
serializer
};
const getInSubscriptionOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/providers/Microsoft.Security/assessmentMetadata/{assessmentMetadataName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SecurityAssessmentMetadataResponse
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion10],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.assessmentMetadataName
],
headerParameters: [Parameters.accept],
serializer
};
const createInSubscriptionOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/providers/Microsoft.Security/assessmentMetadata/{assessmentMetadataName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.SecurityAssessmentMetadataResponse
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.assessmentMetadata,
queryParameters: [Parameters.apiVersion10],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.assessmentMetadataName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const deleteInSubscriptionOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/providers/Microsoft.Security/assessmentMetadata/{assessmentMetadataName}",
httpMethod: "DELETE",
responses: {
200: {},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion10],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.assessmentMetadataName
],
headerParameters: [Parameters.accept],
serializer
};
const listNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SecurityAssessmentMetadataResponseList
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion10],
urlParameters: [Parameters.$host, Parameters.nextLink],
headerParameters: [Parameters.accept],
serializer
};
const listBySubscriptionNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SecurityAssessmentMetadataResponseList
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion10],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import Vue, { ComponentOptions, CreateElement, VueConstructor } from 'vue';
import { PropsDefinition } from 'vue/types/options';
import { CombinedVueInstance } from 'vue/types/vue';
import { ScopedSlotReturnValue } from 'vue/types/vnode';
import { createNamespace, createBrandName, isServer } from '../../utils';
import { ByComponentOptions } from '../../utils/create/component';
import { clamp, getCorrectIndexInArray } from '../../utils/math';
import { preventDefault, on, off } from '../../utils/dom/event';
import { raf } from '../../utils/dom/raf';
import { PopupMixin } from '../../mixins/popup';
import { PopupMixinProps, PopupMixinPropsInit, PopupMixinInstance } from '../../mixins/popup/type';
import { BindEventMixin } from '../../mixins/bind-event';
const closeIcon = require(`!html-loader!../../../svg/close-one.svg`);
declare const h: CreateElement;
const MIN_DISTANCE_CLOSE = 50;
const MIN_DISTANCE_SWITCH = 10;
const [createComponent, bem] = createNamespace('image-preview');
export interface ImagePreviewData {
moving: boolean;
zooming: boolean;
toggleZooming: boolean;
switching: boolean;
/** Index of current image */
currentIndex: number;
/** Position X of current image */
currentX: number;
/** Position Y of current image */
currentY: number;
/** Translate Z of current image before close */
currentZ: number;
/** Opacity of current image before close */
currentOpacity: number;
/** Index of adjacent image (previous or next to current image) */
adjacentIndex: number;
/** Position X of adjacent image */
adjacentX: number;
/** Scale ratio while zooming */
scale: number;
}
export type ImagePreviewCloseButtonPosition =
| 'top-left'
| 'top-right'
| 'bottom-left'
| 'bottom-right';
const CLOSE_ICON_POSITIONS: ImagePreviewCloseButtonPosition[] = [
'top-left',
'top-right',
'bottom-left',
'bottom-right',
];
export interface ImagePreviewPropsDeclare {
/**
* The string array of image URLs.
*/
images: string[];
/**
* The index number for first showing.
* @default 0
*/
startIndex?: number;
/**
* The duration (millisecond) for swipe motion.
* @default 200
*/
swipeDuration?: number;
/**
* Toggle loop or not for swipe.
* @default true
*/
loop?: boolean;
/**
* Set maximum zoom scale.
* @default 3
*/
maxZoom?: number;
/**
* Set minimum zoom scale.
* @default 1
*/
minZoom?: number;
/**
* Just be closed via .close() or not.
* @alpha Probably be removed in future.
*/
asyncClose?: boolean;
/**
* Close on backward (history popstate).
* @default false
*/
closeOnPopstate?: boolean;
/**
* Show close button or not.
* @default false
*/
showCloseButton?: boolean;
/**
* The position of close button.
* @default 'top-right'
*/
closeButtonPosition?: ImagePreviewCloseButtonPosition;
/**
* Show images swipe indicators or not.
* @default true
*/
showIndicators?: boolean;
}
export interface ImagePreviewProps extends ImagePreviewPropsDeclare, PopupMixinProps {}
export interface ImagePreviewPropsInit
extends Required<ImagePreviewPropsDeclare>,
PopupMixinPropsInit {
// override portal mixin
appendToBody: boolean;
// override popup mixin
overlay: boolean;
closeOnClickOverlay: boolean;
}
export interface ImagePreviewMethods {
handlePopstate(isBind: boolean): void;
moveStart(event: TouchEvent): void;
move(event: TouchEvent): void;
movePend(event: TouchEvent): void;
resetMove(): void;
zoomStart(event: TouchEvent): void;
zoom(event: TouchEvent): void;
zoomPend(event: TouchEvent): void;
toggleZoom(): void;
switch(): void;
detectDoubleClick(event: TouchEvent): boolean;
onTouchStart(event: TouchEvent): void;
onTouchMove(event: TouchEvent): void;
onTouchEnd(event: TouchEvent): void;
}
export interface ImagePreviewEvents {
onChange?(activeIndex: number): void;
onScale?(scale: number): void;
onOpen?(event?: Event): void;
onOpened?(event?: Event): void;
onClose?(event?: Event): void;
onClosed?(event?: Event): void;
}
export interface ImagePreviewScopedSlots {
close?: (props: {
onClose: any;
position: ImagePreviewCloseButtonPosition;
}) => ScopedSlotReturnValue;
indicators?: (props: { active: number }) => ScopedSlotReturnValue;
}
// non-reactive
export interface ImagePreviewDataExtra {
bindStatus: boolean;
swipeWidth: number;
swipeHeight: number;
currentWidth: number;
currentHeight: number;
edgeLeft: number;
edgeRight: number;
edgeTop: number;
edgeBottom: number;
startCurrentX: number;
startCurrentY: number;
startScale: number;
swipeTimer: number | undefined;
lastClickTime: number | undefined;
lastDoubleClickTime: number | undefined;
onOpen(event?: Event): void;
onOpened(event?: Event): void;
onClose(event?: Event): void;
onClosed(event?: Event): void;
$refs: {
swipe: HTMLDivElement;
current?: HTMLImageElement;
};
$scopedSlots: ImagePreviewScopedSlots;
}
type ImagePreviewInstance = CombinedVueInstance<
PopupMixinInstance,
ImagePreviewData,
ImagePreviewMethods,
{},
ImagePreviewPropsInit
> &
ImagePreviewDataExtra;
const componentOptions: ComponentOptions<
Vue,
() => ImagePreviewData,
ImagePreviewMethods,
{},
PropsDefinition<ImagePreviewProps>
> = {
mixins: [
PopupMixin,
BindEventMixin(function (this: ImagePreviewInstance, _bind, isBind) {
this.handlePopstate(isBind && this.closeOnPopstate);
}),
],
data() {
return {
moving: false,
zooming: false,
toggleZooming: false,
switching: false,
currentIndex: 0,
currentX: 0,
currentY: 0,
currentZ: 0,
currentOpacity: 1,
adjacentIndex: -1,
adjacentX: 0,
scale: 1,
lastScale: 1,
};
},
props: {
images: {
type: Array,
required: true,
validator: value => {
return Array.isArray(value) && value.every(i => typeof i === 'string');
},
},
startIndex: {
type: Number,
default: 0,
},
swipeDuration: {
type: Number,
default: 200,
},
loop: {
type: Boolean,
default: true,
},
maxZoom: {
type: Number,
default: 3,
},
minZoom: {
type: Number,
default: 1,
},
asyncClose: {
type: Boolean,
default: false,
},
closeOnPopstate: {
type: Boolean,
default: true,
},
showCloseButton: {
type: Boolean,
default: false,
},
closeButtonPosition: {
type: String as () => ImagePreviewCloseButtonPosition,
default: 'top-right',
validator: value => !!value && CLOSE_ICON_POSITIONS.includes(value),
},
showIndicators: {
type: Boolean,
default: true,
},
// override portal mixin
appendToBody: {
type: Boolean,
default: true,
},
// override popup mixin
overlay: {
type: Boolean,
default: true,
},
overlayStyle: {
type: Object,
default() {
return {
backgroundColor: '#000',
};
},
},
},
watch: {
value(this: ImagePreviewInstance, value) {
if (value) {
this.onOpen();
} else {
this.onClose();
}
},
closeOnPopstate(this: ImagePreviewInstance, val) {
this.handlePopstate(val);
},
},
created(this: ImagePreviewInstance) {
this.currentIndex = clamp(this.startIndex, 0, this.images.length);
this.bindStatus = false;
this.swipeWidth = 0;
this.swipeHeight = 0;
this.currentWidth = 0;
this.currentHeight = 0;
this.startCurrentY = 0;
this.startCurrentX = 0;
this.startScale = 1;
const createEmitter = (eventName: string) => (event?: Event) => this.$emit(eventName, event);
this.onOpen = createEmitter('open');
this.onOpened = createEmitter('opened');
this.onClose = createEmitter('close');
const onClosed = createEmitter('closed');
this.onClosed = event => {
this.resetMove();
onClosed(event);
};
},
methods: {
handlePopstate(this: ImagePreviewInstance, isBind) {
if (this.$isServer) {
return;
}
if (this.bindStatus !== isBind) {
this.bindStatus = isBind;
const action = isBind ? on : off;
action(window, 'popstate', () => {
this.close();
});
}
},
moveStart(this: ImagePreviewInstance, _event) {
const {
scale,
$refs: { swipe, current },
} = this;
const swipeWidth = swipe.clientWidth;
const swipeHeight = swipe.clientHeight;
const currentWidth = (current && current.clientWidth * scale) || 0;
const currentHeight = (current && current.clientHeight * scale) || 0;
const edgeLeft = ((swipeWidth - currentWidth) / 2) * (swipeWidth < currentWidth ? 1 : -1);
const edgeRight = -edgeLeft;
const edgeTop = ((swipeHeight - currentHeight) / 2) * (swipeHeight < currentHeight ? 1 : -1);
const edgeBottom = -edgeTop;
this.swipeWidth = swipeWidth;
this.swipeHeight = swipeHeight;
this.currentWidth = currentWidth;
this.currentHeight = currentHeight;
this.edgeLeft = edgeLeft;
this.edgeRight = edgeRight;
this.edgeTop = edgeTop;
this.edgeBottom = edgeBottom;
raf(() => {
this.moving = true;
});
},
move(this: ImagePreviewInstance) {
const {
deltaX,
deltaY,
direction,
currentIndex,
swipeWidth,
swipeHeight,
edgeLeft,
edgeRight,
edgeTop,
edgeBottom,
startCurrentX,
startCurrentY,
images: { length },
loop,
} = this;
if (this.zooming) {
const currentX = clamp(deltaX + startCurrentX, edgeLeft, edgeRight);
const currentY = clamp(deltaY + startCurrentY, edgeTop, edgeBottom);
raf(() => {
this.currentX = currentX;
this.currentY = currentY;
});
return;
}
if (this.moving) {
let currentX = startCurrentX + deltaX;
let currentY = startCurrentY + deltaY;
let currentZ = 0;
let currentOpacity = 1;
let adjacentIndex = -1;
let adjacentX = 0;
switch (direction) {
case 'vertical':
currentX = 0;
currentZ = -Math.abs(currentY);
currentOpacity = clamp((swipeHeight + currentZ * 2) / swipeHeight, 0, 1);
break;
case 'horizontal':
currentY = 0;
default:
if (deltaX > 0) {
adjacentIndex = getCorrectIndexInArray(length, currentIndex - 1);
adjacentX = currentX - swipeWidth;
} else {
adjacentIndex = getCorrectIndexInArray(length, currentIndex + 1);
adjacentX = currentX + swipeWidth;
}
break;
}
const outOfRange =
!loop &&
((currentX > 0 && adjacentIndex > currentIndex) ||
(currentX < 0 && adjacentIndex < currentIndex));
if (outOfRange || adjacentIndex === currentIndex) {
adjacentIndex = -1;
adjacentX = 0;
}
raf(() => {
this.currentX = currentX;
this.currentY = currentY;
this.currentZ = currentZ;
this.currentOpacity = currentOpacity;
this.adjacentIndex = adjacentIndex;
this.adjacentX = adjacentX;
});
}
},
movePend(this: ImagePreviewInstance, _event) {
raf(() => {
this.startCurrentX = this.currentX;
this.startCurrentY = this.currentY;
});
},
resetMove(this: ImagePreviewInstance) {
raf(() => {
this.currentX = 0;
this.currentY = 0;
this.currentZ = 0;
this.currentOpacity = 1;
this.adjacentIndex = -1;
this.adjacentX = 0;
this.startCurrentX = 0;
this.startCurrentY = 0;
this.scale = 1;
});
},
zoomStart(this: ImagePreviewInstance, _event) {
raf(() => {
this.moving = false;
this.zooming = true;
this.scale = this.startScale;
this.startCurrentX = this.currentX;
this.startCurrentY = this.currentY;
});
},
zoom(this: ImagePreviewInstance, _event) {
const scale = clamp(
(this.startScale * this.scaleDistance) / this.startScaleDistance,
this.minZoom,
this.maxZoom,
);
raf(() => {
this.scale = scale;
this.$emit('scale', scale);
});
},
zoomPend(this: ImagePreviewInstance, _event) {
raf(() => {
this.startScale = this.scale;
});
},
toggleZoom(this: ImagePreviewInstance) {
const { zooming } = this;
raf(() => {
this.toggleZooming = true;
this.currentY = 0;
this.currentX = 0;
this.adjacentIndex = -1;
this.scale = zooming ? 1 : this.maxZoom;
this.startScale = this.scale;
});
this.swipeTimer = window.setTimeout(
() =>
raf(() => {
this.zooming = !zooming;
this.toggleZooming = false;
}),
this.swipeDuration,
);
},
switch(this: ImagePreviewInstance) {
const {
currentIndex: adjacentIndex,
currentX,
adjacentIndex: currentIndex,
swipeWidth,
swipeDuration,
} = this;
raf(() => {
this.moving = false;
this.switching = true;
this.currentIndex = currentIndex;
this.currentY = 0;
this.currentX = 0;
this.adjacentIndex = adjacentIndex;
this.adjacentX = currentX > 0 ? swipeWidth : -swipeWidth;
this.$emit('change', currentIndex);
});
this.swipeTimer = window.setTimeout(
() =>
raf(() => {
this.switching = false;
this.adjacentIndex = -1;
this.startCurrentX = 0;
this.startCurrentY = 0;
}),
swipeDuration,
);
},
detectDoubleClick(this: ImagePreviewInstance, event): boolean {
if (event.touches.length !== 0) {
return false;
}
const { lastClickTime, lastDoubleClickTime } = this;
const currentClickTime = Date.now();
this.lastClickTime = currentClickTime;
if (lastDoubleClickTime && currentClickTime - lastDoubleClickTime < 200) {
return false;
}
if (lastClickTime && currentClickTime - lastClickTime < 200) {
this.lastDoubleClickTime = currentClickTime;
return true;
}
return false;
},
onTouchStart(this: ImagePreviewInstance, event) {
preventDefault(event);
this.touchStart(event);
if (this.toggleZooming || this.switching) {
return;
}
// if (event.touches.length === 2 && !this.moving) {
// this.zoomStart(event);
// return;
// }
if (event.touches.length === 1) {
this.moveStart(event);
return;
}
},
onTouchMove(this: ImagePreviewInstance, event) {
preventDefault(event);
this.touchMove(event);
if (this.toggleZooming || this.switching) {
return;
}
// if (event.touches.length > 1 && this.zooming) {
// this.zoom(event);
// return;
// }
if (event.touches.length === 1 && this.moving) {
this.move(event);
return;
}
},
onTouchEnd(this: ImagePreviewInstance, event) {
preventDefault(event);
const {
toggleZooming,
switching,
adjacentIndex,
direction,
currentX,
currentY,
asyncClose,
} = this;
const {
touches: { length },
} = event;
if (toggleZooming || switching) {
return;
}
// if (this.detectDoubleClick(event)) {
// this.toggleZoom();
// return;
// }
// if (length === 1 && this.zooming) {
// this.zoomPend(event);
// return;
// }
if (length > 0) {
return;
}
// if (zooming) {
// this.movePend(event);
// return;
// }
if (
adjacentIndex > -1 &&
direction === 'horizontal' &&
Math.abs(currentX) >= MIN_DISTANCE_SWITCH
) {
this.switch();
return;
}
if (
!asyncClose &&
((direction === 'vertical' && Math.abs(currentY) >= MIN_DISTANCE_CLOSE) || direction === '')
) {
this.close();
return;
}
this.resetMove();
},
},
render(this: ImagePreviewInstance) {
if (!this.shouldRender) {
return h();
}
const brandName = createBrandName();
const {
value,
toggleZooming,
switching,
currentIndex,
currentX,
currentY,
currentZ,
currentOpacity,
adjacentIndex,
adjacentX,
scale,
images,
swipeDuration,
showCloseButton,
closeButtonPosition,
showIndicators,
} = this;
const changing = switching || toggleZooming;
const classes = [bem(), { changing }];
const itemClasses = bem('item');
const imageClasses = bem('image');
const currentItemStyle = {
top: `${currentY}px`,
left: `${currentX}px`,
'transition-duration': (changing && `${swipeDuration}ms`) || null,
};
const adjacentItemStyle = {
left: `${adjacentX}px`,
'transition-duration': (changing && `${swipeDuration}ms`) || null,
};
const currentImageStyle = {
opacity: (currentOpacity < 1 && currentOpacity) || null,
transform:
(scale !== 1 && `scale(${scale})`) ||
(currentZ !== 0 && `perspective(400px) translate3d(0,0,${currentZ}px)`) ||
null,
'transition-duration': (toggleZooming && `${swipeDuration}ms`) || null,
};
const {
$scopedSlots: {
close = ({ onClose, position }) => (
<button key="close" class={bem('close-button', position)} onClick={onClose}>
<i class={bem('close-icon')} domPropsInnerHTML={closeIcon} />
</button>
),
indicators = ({ active }) => (
<div key="indicators" class={bem('indicators')}>
{images.map((_image, index) => (
<i class={bem('indicator-item', { active: index === active })} />
))}
</div>
),
},
} = this;
return (
<transition
name={`${brandName}fade`}
onAfterEnter={this.onOpened}
onAfterLeave={this.onClosed}
>
<div v-show={value} class={classes}>
<div
key="swipe"
ref="swipe"
class={bem('swipe')}
onTouchstart={this.onTouchStart}
onTouchmove={this.onTouchMove}
onTouchend={this.onTouchEnd}
onTouchcancel={this.onTouchEnd}
>
{images.map((image, index) => (
<div
key={image}
class={itemClasses}
style={
(index === currentIndex && currentItemStyle) ||
(index === adjacentIndex && adjacentItemStyle) ||
undefined
}
>
<img
ref={index === currentIndex ? 'current' : undefined}
src={image}
class={imageClasses}
style={(index === currentIndex && currentImageStyle) || undefined}
/>
</div>
))}
</div>
{!!showCloseButton && close({ onClose: this.close, position: closeButtonPosition })}
{!!showIndicators && indicators({ active: currentIndex })}
</div>
</transition>
);
},
};
const byComponentOptions = createComponent<
ImagePreviewProps,
ImagePreviewEvents,
ImagePreviewScopedSlots
>(componentOptions as any);
const { install: installComponent } = byComponentOptions as ByComponentOptions;
let $$Vue: VueConstructor | undefined;
export type InvokeImagePreviewOptions = ImagePreviewProps &
ImagePreviewEvents &
ImagePreviewScopedSlots;
declare module 'vue/types/vue' {
interface Vue {
$imagePreview(options: InvokeImagePreviewOptions): ImagePreviewInstance | undefined;
}
interface VueConstructor<V extends Vue = Vue> {
$imagePreview(options: InvokeImagePreviewOptions): ImagePreviewInstance | undefined;
}
}
function install(this: ComponentOptions<Vue>, $Vue: VueConstructor) {
if ($$Vue && $$Vue === $Vue) {
return;
}
$$Vue = $Vue;
function invokeImagePreview(
options: InvokeImagePreviewOptions,
): ImagePreviewInstance | undefined {
if (isServer) {
return undefined;
}
const handler = () => {};
const {
onChange = handler,
onScale = handler,
onOpen = handler,
onOpened = handler,
onClose = handler,
onClosed = handler,
close,
indicators,
...props
} = options;
const container = new $Vue({
el: document.createElement('div'),
data() {
return { value: false };
},
render(this: { value: boolean }, h) {
return h(componentOptions, {
ref: 'instance',
props: {
...props,
value: this.value,
lazyRender: false,
},
scopedSlots: { close, indicators },
on: {
input: (value: boolean) => (this.value = value),
change: onChange,
scale: onScale,
open: onOpen,
opened: onOpened,
close: onClose,
closed: [onClosed, () => container.$destroy()],
},
});
},
});
const instance = container.$refs.instance as ImagePreviewInstance;
instance.$emit('input', true);
return instance;
}
installComponent!.call(this, $Vue as VueConstructor);
Object.defineProperty($Vue.prototype, '$imagePreview', {
configurable: false,
value: invokeImagePreview,
});
Object.defineProperty($Vue, '$imagePreview', {
configurable: false,
value: invokeImagePreview,
});
}
(byComponentOptions as ByComponentOptions).install = install;
export default byComponentOptions; | the_stack |
import assert from '../../harness/wrapped-assert';
import {SlowBuffer} from 'buffer';
export default function() {
// counter to ensure unique value is always copied
var cntr = 0;
var b = new Buffer(1024); // safe constructor
assert.strictEqual(1024, b.length, 'Buffer length mismatch: 1024 != ' + b.length);
b[0] = -1;
assert.strictEqual(b[0], 255);
for (var i = 0; i < 1024; i++) {
b[i] = i % 256;
}
for (var i = 0; i < 1024; i++) {
assert.strictEqual(i % 256, b[i]);
}
var c = new Buffer(512);
assert.strictEqual(512, c.length, 'Buffer length mismatch: 512 != ' + c.length);
// First check Buffer#fill() works as expected.
assert.throws(function() {
new Buffer(8).fill('a', -1);
});
assert.throws(function() {
new Buffer(8).fill('a', 0, 9);
});
// Make sure this doesn't hang indefinitely.
new Buffer(8).fill('');
var buf = new Buffer(64);
buf.fill(10);
for (var i = 0; i < buf.length; i++)
assert.equal(buf[i], 10);
buf.fill(11, 0, buf.length >> 1);
for (var i = 0; i < buf.length >> 1; i++)
assert.equal(buf[i], 11);
for (var i = (buf.length >> 1) + 1; i < buf.length; i++)
assert.equal(buf[i], 10);
buf.fill('h');
for (var i = 0; i < buf.length; i++)
assert.equal('h'.charCodeAt(0), buf[i]);
buf.fill(0);
for (var i = 0; i < buf.length; i++)
assert.equal(0, buf[i]);
buf.fill(null);
for (var i = 0; i < buf.length; i++)
assert.equal(0, buf[i]);
buf.fill(1, 16, 32);
for (var i = 0; i < 16; i++)
assert.equal(0, buf[i]);
for (; i < 32; i++)
assert.equal(1, buf[i]);
for (; i < buf.length; i++)
assert.equal(0, buf[i]);
var buf = new Buffer(10);
buf.fill('abc');
assert.equal(buf.toString(), 'abcabcabca');
buf.fill('է');
assert.equal(buf.toString(), 'էէէէէ');
// copy 512 bytes, from 0 to 512.
b.fill(++cntr);
c.fill(++cntr);
var copied = b.copy(c, 0, 0, 512);
assert.strictEqual(512, copied, 'Expected 512 copied bytes, got: ' + copied);
for (var i = 0; i < c.length; i++) {
assert.strictEqual(b[i], c[i]);
}
// copy c into b, without specifying sourceEnd
b.fill(++cntr);
c.fill(++cntr);
var copied = c.copy(b, 0, 0);
assert.strictEqual(c.length, copied,
'Expected ' + c.length + ' copied bytes w/o sourceEnd, got: ' + copied);
for (var i = 0; i < c.length; i++) {
assert.strictEqual(c[i], b[i]);
}
// copy c into b, without specifying sourceStart
b.fill(++cntr);
c.fill(++cntr);
var copied = c.copy(b, 0);
assert.strictEqual(c.length, copied,
'Expected ' + c.length + ' copied bytes w/o sourceStart, got: ' + copied);
for (var i = 0; i < c.length; i++) {
assert.strictEqual(c[i], b[i]);
}
// copy longer buffer b to shorter c without targetStart
b.fill(++cntr);
c.fill(++cntr);
var copied = b.copy(c);
assert.strictEqual(c.length, copied,
'Expected ' + c.length + ' copied bytes w/o targetStart, got: ' + copied);
for (var i = 0; i < c.length; i++) {
assert.strictEqual(b[i], c[i]);
}
// copy starting near end of b to c
b.fill(++cntr);
c.fill(++cntr);
var copied = b.copy(c, 0, b.length - Math.floor(c.length / 2));
var expected = Math.floor(c.length / 2);
assert.strictEqual(expected, copied,
'Expected ' + expected + ' copied bytes, got: ' + copied);
for (var i = 0; i < Math.floor(c.length / 2); i++) {
assert.strictEqual(b[b.length - Math.floor(c.length / 2) + i], c[i]);
}
for (var i = Math.floor(c.length /2) + 1; i < c.length; i++) {
assert.strictEqual(c[c.length-1], c[i]);
}
// try to copy 513 bytes, and check we don't overrun c
b.fill(++cntr);
c.fill(++cntr);
var copied = b.copy(c, 0, 0, 513);
assert.strictEqual(c.length, copied,
'Expected ' + c.length + ' copied bytes (no overrun), got: ' + copied);
for (var i = 0; i < c.length; i++) {
assert.strictEqual(b[i], c[i]);
}
// copy 768 bytes from b into b
b.fill(++cntr);
b.fill(++cntr, 256);
var copied = b.copy(b, 0, 256, 1024);
assert.strictEqual(768, copied,
'Expected 728 copied bytes (same buffer), got: ' + copied);
for (var i = 0; i < b.length; i++) {
assert.strictEqual(cntr, b[i]);
}
// copy string longer than buffer length (failure will segfault)
var bb = new Buffer(10);
bb.fill('hello crazy world');
var caught_error: NodeJS.ErrnoException = null;
// try to copy from before the beginning of b
caught_error = null;
try {
var copied = b.copy(c, 0, 100, 10);
} catch (err) {
caught_error = err;
}
// copy throws at negative sourceStart
assert.throws(function() {
new Buffer(5).copy(new Buffer(5), 0, -1);
}, RangeError);
// check sourceEnd resets to targetEnd if former is greater than the latter
b.fill(++cntr);
c.fill(++cntr);
var copied = b.copy(c, 0, 0, 1025);
for (var i = 0; i < c.length; i++) {
assert.strictEqual(b[i], c[i]);
}
// throw with negative sourceEnd
assert.throws(function() {
b.copy(c, 0, 0, -1);
}, RangeError);
// when sourceStart is greater than sourceEnd, zero copied
assert.equal(b.copy(c, 0, 100, 10), 0);
// when targetStart > targetLength, zero copied
assert.equal(b.copy(c, 512, 0, 10), 0);
// invalid encoding for Buffer.toString
caught_error = null;
try {
b.toString('invalid');
} catch (err) {
caught_error = err;
}
assert.strictEqual('Unknown encoding: invalid', caught_error.message);
// invalid encoding for Buffer.write
caught_error = null;
try {
b.write('test string', 0, 5, 'invalid');
} catch (err) {
caught_error = err;
}
assert.strictEqual('Unknown encoding: invalid', caught_error.message);
// try to create 0-length buffers
(<any>Buffer)('');
new Buffer('', 'ascii');
new Buffer('', 'binary');
new Buffer(0);
// try to write a 0-length string beyond the end of b
assert.throws(function() {
b.write('', 2048);
}, RangeError);
// throw when writing to negative offset
assert.throws(function() {
b.write('a', -1);
}, RangeError);
// throw when writing past bounds from the pool
assert.throws(function() {
b.write('a', 2048);
}, RangeError);
// throw when writing to negative offset
assert.throws(function() {
b.write('a', -1);
}, RangeError);
// try to copy 0 bytes worth of data into an empty buffer
b.copy(new Buffer(0), 0, 0, 0);
// try to copy 0 bytes past the end of the target buffer
b.copy(new Buffer(0), 1, 1, 1);
b.copy(new Buffer(1), 1, 1, 1);
// try to copy 0 bytes from past the end of the source buffer
b.copy(new Buffer(1), 0, 2048, 2048);
// try to toString() a 0-length slice of a buffer, both within and without the
// valid buffer range
assert.equal(new Buffer('abc').toString('ascii', 0, 0), '');
assert.equal(new Buffer('abc').toString('ascii', -100, -100), '');
assert.equal(new Buffer('abc').toString('ascii', 100, 100), '');
// try toString() with a object as a encoding
assert.equal(new Buffer('abc').toString(<any>{toString: function() {
return 'ascii';
}}), 'abc');
// testing for smart defaults and ability to pass string values as offset
// BFS: Yeah, we're not going to support out-of-order arguments and numeric
// values as strings.
var writeTest = new Buffer('abcdes');
writeTest.write('n', <any> 'ascii');
writeTest.write('o', 1, <any> 'ascii');
writeTest.write('d', 2, <any> 'ascii');
writeTest.write('e', 3, <any> 'ascii');
writeTest.write('j', 4, <any> 'ascii');
assert.equal(writeTest.toString(), 'nodejs');
// ASCII slice test
var asciiString = 'hello world';
var offset = 100;
for (var i = 0; i < asciiString.length; i++) {
b[i] = asciiString.charCodeAt(i);
}
var asciiSlice = b.toString('ascii', 0, asciiString.length);
assert.equal(asciiString, asciiSlice);
var written = b.write(asciiString, offset, <any> 'ascii');
assert.equal(asciiString.length, written);
var asciiSlice = b.toString('ascii', offset, offset + asciiString.length);
assert.equal(asciiString, asciiSlice);
var sliceA = b.slice(offset, offset + asciiString.length);
var sliceB = b.slice(offset, offset + asciiString.length);
for (var i = 0; i < asciiString.length; i++) {
assert.equal(sliceA[i], sliceB[i]);
}
// UTF-8 slice test
var utf8String = '¡hέlló wôrld!';
var offset = 100;
b.write(utf8String, 0, Buffer.byteLength(utf8String), 'utf8');
var utf8Slice = b.toString('utf8', 0, Buffer.byteLength(utf8String));
assert.equal(utf8String, utf8Slice);
var written = b.write(utf8String, offset, <any> 'utf8');
assert.equal(Buffer.byteLength(utf8String), written);
utf8Slice = b.toString('utf8', offset, offset + Buffer.byteLength(utf8String));
assert.equal(utf8String, utf8Slice);
var sliceA = b.slice(offset, offset + Buffer.byteLength(utf8String));
var sliceB = b.slice(offset, offset + Buffer.byteLength(utf8String));
for (var i = 0; i < Buffer.byteLength(utf8String); i++) {
assert.equal(sliceA[i], sliceB[i]);
}
var slice = b.slice(100, 150);
assert.equal(50, slice.length);
for (var i = 0; i < 50; i++) {
assert.equal(b[100 + i], slice[i]);
}
// make sure only top level parent propagates from allocPool
// BFS: Doesn't matter.
/*var b = new Buffer(5);
var c = b.slice(0, 4);
var d = c.slice(0, 2);
assert.equal(b.parent, c.parent);
assert.equal(b.parent, d.parent);
// also from a non-pooled instance
var b = new SlowBuffer(5);
var c = b.slice(0, 4);
var d = c.slice(0, 2);*/
{
// Bug regression test
var testValue = '\u00F6\u65E5\u672C\u8A9E'; // ö日本語
var buffer = new Buffer(32);
var size = buffer.write(testValue, 0, <any> 'utf8');
let slice = buffer.toString('utf8', 0, size);
assert.equal(slice, testValue);
}
// Test triple slice
var a = new Buffer(8);
for (var i = 0; i < 8; i++) a[i] = i;
var b = a.slice(4, 8);
assert.equal(4, b[0]);
assert.equal(5, b[1]);
assert.equal(6, b[2]);
assert.equal(7, b[3]);
var c = b.slice(2, 4);
assert.equal(6, c[0]);
assert.equal(7, c[1]);
var d = new Buffer([23, 42, 255]);
assert.equal(d.length, 3);
assert.equal(d[0], 23);
assert.equal(d[1], 42);
assert.equal(d[2], 255);
// BFS: Changed deepEqual -> equal on toJSON.
function equalCheck(b1: Buffer, b2: Buffer) {
assert.equal(JSON.stringify(b1), JSON.stringify(b2));
}
equalCheck(d, new Buffer(d));
var e = new Buffer('über');
equalCheck(e, new Buffer([195, 188, 98, 101, 114]));
var f = new Buffer('über', 'ascii');
assert.equal(4, f.length, 'f.length: ' + f.length + ' (should be 4)');
equalCheck(f, new Buffer([252, 98, 101, 114]));
['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) {
var f = new Buffer('über', encoding);
assert.equal(8, f.length, 'f.length: ' + f.length + ' (should be 8)');
equalCheck(f, new Buffer([252, 0, 98, 0, 101, 0, 114, 0]));
var f = new Buffer('привет', encoding);
assert.equal(12, f.length, 'f.length: ' + f.length + ' (should be 12)');
equalCheck(f, new Buffer([63, 4, 64, 4, 56, 4, 50, 4, 53, 4, 66, 4]));
assert.equal(f.toString(encoding), 'привет');
var f = new Buffer([0, 0, 0, 0, 0]);
assert.equal(f.length, 5);
var size = f.write('あいうえお', <any> encoding);
assert.equal(size, 4, 'expected 4 bytes written to buffer, got: ' + size);
equalCheck(f, new Buffer([0x42, 0x30, 0x44, 0x30, 0x00]));
});
var f = new Buffer('\uD83D\uDC4D', 'utf-16le'); // THUMBS UP SIGN (U+1F44D)
assert.equal(4, f.length, 'f.length: ' + f.length + ' (should be 4)');
equalCheck(f, new Buffer('3DD84DDC', 'hex'));
var arrayIsh = {0: 0, 1: 1, 2: 2, 3: 3, length: 4};
var g = new Buffer(<any> arrayIsh);
equalCheck(g, new Buffer([0, 1, 2, 3]));
// BFS: We don't support these types of shenanigans.
//var strArrayIsh = {0: '0', 1: '1', 2: '2', 3: '3', length: 4};
//g = new Buffer(strArrayIsh);
//equalCheck(g, new Buffer([0, 1, 2, 3]));
//
// Test toString('base64')
//
assert.equal('TWFu', (new Buffer('Man')).toString('base64'));
{
// test that regular and URL-safe base64 both work
let expected = [0xff, 0xff, 0xbe, 0xff, 0xef, 0xbf, 0xfb, 0xef, 0xff];
equalCheck(new Buffer('//++/++/++//', 'base64'), new Buffer(expected));
equalCheck(new Buffer('__--_--_--__', 'base64'), new Buffer(expected));
}
{
// big example
let quote = 'Man is distinguished, not only by his reason, but by this ' +
'singular passion from other animals, which is a lust ' +
'of the mind, that by a perseverance of delight in the continued ' +
'and indefatigable generation of knowledge, exceeds the short ' +
'vehemence of any carnal pleasure.';
let expected = 'TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24s' +
'IGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltY' +
'WxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZX' +
'JzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmR' +
'lZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo' +
'ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=';
assert.equal(expected, (new Buffer(quote)).toString('base64'));
b = new Buffer(1024);
var bytesWritten = b.write(expected, 0, <any> 'base64');
assert.equal(quote.length, bytesWritten);
assert.equal(quote, b.toString('ascii', 0, quote.length));
// check that the base64 decoder ignores whitespace
var expectedWhite = expected.slice(0, 60) + ' \n' +
expected.slice(60, 120) + ' \n' +
expected.slice(120, 180) + ' \n' +
expected.slice(180, 240) + ' \n' +
expected.slice(240, 300) + '\n' +
expected.slice(300, 360) + '\n';
b = new Buffer(1024);
bytesWritten = b.write(expectedWhite, 0, <any> 'base64');
assert.equal(quote.length, bytesWritten);
assert.equal(quote, b.toString('ascii', 0, quote.length));
// check that the base64 decoder on the constructor works
// even in the presence of whitespace.
b = new Buffer(expectedWhite, 'base64');
assert.equal(quote.length, b.length);
assert.equal(quote, b.toString('ascii', 0, quote.length));
// check that the base64 decoder ignores illegal chars
var expectedIllegal = expected.slice(0, 60) + ' \x80' +
expected.slice(60, 120) + ' \xff' +
expected.slice(120, 180) + ' \x00' +
expected.slice(180, 240) + ' \x98' +
expected.slice(240, 300) + '\x03' +
expected.slice(300, 360);
b = new Buffer(expectedIllegal, 'base64');
assert.equal(quote.length, b.length);
assert.equal(quote, b.toString('ascii', 0, quote.length));
}
assert.equal(new Buffer('', 'base64').toString(), '');
assert.equal(new Buffer('K', 'base64').toString(), '');
// multiple-of-4 with padding
assert.equal(new Buffer('Kg==', 'base64').toString(), '*');
assert.equal(new Buffer('Kio=', 'base64').toString(), '**');
assert.equal(new Buffer('Kioq', 'base64').toString(), '***');
assert.equal(new Buffer('KioqKg==', 'base64').toString(), '****');
assert.equal(new Buffer('KioqKio=', 'base64').toString(), '*****');
assert.equal(new Buffer('KioqKioq', 'base64').toString(), '******');
assert.equal(new Buffer('KioqKioqKg==', 'base64').toString(), '*******');
assert.equal(new Buffer('KioqKioqKio=', 'base64').toString(), '********');
assert.equal(new Buffer('KioqKioqKioq', 'base64').toString(), '*********');
assert.equal(new Buffer('KioqKioqKioqKg==', 'base64').toString(),
'**********');
assert.equal(new Buffer('KioqKioqKioqKio=', 'base64').toString(),
'***********');
assert.equal(new Buffer('KioqKioqKioqKioq', 'base64').toString(),
'************');
assert.equal(new Buffer('KioqKioqKioqKioqKg==', 'base64').toString(),
'*************');
assert.equal(new Buffer('KioqKioqKioqKioqKio=', 'base64').toString(),
'**************');
assert.equal(new Buffer('KioqKioqKioqKioqKioq', 'base64').toString(),
'***************');
assert.equal(new Buffer('KioqKioqKioqKioqKioqKg==', 'base64').toString(),
'****************');
assert.equal(new Buffer('KioqKioqKioqKioqKioqKio=', 'base64').toString(),
'*****************');
assert.equal(new Buffer('KioqKioqKioqKioqKioqKioq', 'base64').toString(),
'******************');
assert.equal(new Buffer('KioqKioqKioqKioqKioqKioqKg==', 'base64').toString(),
'*******************');
assert.equal(new Buffer('KioqKioqKioqKioqKioqKioqKio=', 'base64').toString(),
'********************');
// no padding, not a multiple of 4
assert.equal(new Buffer('Kg', 'base64').toString(), '*');
assert.equal(new Buffer('Kio', 'base64').toString(), '**');
assert.equal(new Buffer('KioqKg', 'base64').toString(), '****');
assert.equal(new Buffer('KioqKio', 'base64').toString(), '*****');
assert.equal(new Buffer('KioqKioqKg', 'base64').toString(), '*******');
assert.equal(new Buffer('KioqKioqKio', 'base64').toString(), '********');
assert.equal(new Buffer('KioqKioqKioqKg', 'base64').toString(), '**********');
assert.equal(new Buffer('KioqKioqKioqKio', 'base64').toString(), '***********');
assert.equal(new Buffer('KioqKioqKioqKioqKg', 'base64').toString(),
'*************');
assert.equal(new Buffer('KioqKioqKioqKioqKio', 'base64').toString(),
'**************');
assert.equal(new Buffer('KioqKioqKioqKioqKioqKg', 'base64').toString(),
'****************');
assert.equal(new Buffer('KioqKioqKioqKioqKioqKio', 'base64').toString(),
'*****************');
assert.equal(new Buffer('KioqKioqKioqKioqKioqKioqKg', 'base64').toString(),
'*******************');
assert.equal(new Buffer('KioqKioqKioqKioqKioqKioqKio', 'base64').toString(),
'********************');
// handle padding graciously, multiple-of-4 or not
assert.equal(new Buffer('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw==',
'base64').length, 32);
assert.equal(new Buffer('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw=',
'base64').length, 32);
assert.equal(new Buffer('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw',
'base64').length, 32);
assert.equal(new Buffer('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg==',
'base64').length, 31);
assert.equal(new Buffer('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg=',
'base64').length, 31);
assert.equal(new Buffer('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg',
'base64').length, 31);
// This string encodes single '.' character in UTF-16
var dot = new Buffer('//4uAA==', 'base64');
assert.equal(dot[0], 0xff);
assert.equal(dot[1], 0xfe);
assert.equal(dot[2], 0x2e);
assert.equal(dot[3], 0x00);
assert.equal(dot.toString('base64'), '//4uAA==');
// Writing base64 at a position > 0 should not mangle the result.
//
// https://github.com/joyent/node/issues/402
var segments = ['TWFkbmVzcz8h', 'IFRoaXM=', 'IGlz', 'IG5vZGUuanMh'];
var buf = new Buffer(64);
var pos = 0;
for (var i = 0; i < segments.length; ++i) {
pos += b.write(segments[i], pos, <any> 'base64');
}
assert.equal(b.toString('binary', 0, pos), 'Madness?! This is node.js!');
// Creating buffers larger than pool size.
var l = (<any> Buffer).poolSize + 5;
var s = '';
for (i = 0; i < l; i++) {
s += 'h';
}
var b = new Buffer(s);
for (i = 0; i < l; i++) {
assert.equal('h'.charCodeAt(0), b[i]);
}
var sb = b.toString();
assert.equal(sb.length, s.length);
assert.equal(sb, s);
// Single argument slice
b = new Buffer('abcde');
assert.equal('bcde', b.slice(1).toString());
// slice(0,0).length === 0
assert.equal(0, new Buffer('hello').slice(0, 0).length);
// test hex toString
var hexb = new Buffer(256);
for (var i = 0; i < 256; i++) {
hexb[i] = i;
}
var hexStr = hexb.toString('hex');
assert.equal(hexStr,
'000102030405060708090a0b0c0d0e0f' +
'101112131415161718191a1b1c1d1e1f' +
'202122232425262728292a2b2c2d2e2f' +
'303132333435363738393a3b3c3d3e3f' +
'404142434445464748494a4b4c4d4e4f' +
'505152535455565758595a5b5c5d5e5f' +
'606162636465666768696a6b6c6d6e6f' +
'707172737475767778797a7b7c7d7e7f' +
'808182838485868788898a8b8c8d8e8f' +
'909192939495969798999a9b9c9d9e9f' +
'a0a1a2a3a4a5a6a7a8a9aaabacadaeaf' +
'b0b1b2b3b4b5b6b7b8b9babbbcbdbebf' +
'c0c1c2c3c4c5c6c7c8c9cacbcccdcecf' +
'd0d1d2d3d4d5d6d7d8d9dadbdcdddedf' +
'e0e1e2e3e4e5e6e7e8e9eaebecedeeef' +
'f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff');
var hexb2 = new Buffer(hexStr, 'hex');
for (var i = 0; i < 256; i++) {
assert.equal(hexb2[i], hexb[i]);
}
// test an invalid slice end.
var b = new Buffer([1, 2, 3, 4, 5]);
var b2 = b.toString('hex', 1, 10000);
var b3 = b.toString('hex', 1, 5);
var b4 = b.toString('hex', 1);
assert.equal(b2, b3);
assert.equal(b2, b4);
function buildBuffer(data: number[]) {
if (Array.isArray(data)) {
var buffer = new Buffer(data.length);
data.forEach(function(v, k) {
buffer[k] = v;
});
return buffer;
}
return null;
}
var x = buildBuffer([0x81, 0xa3, 0x66, 0x6f, 0x6f, 0xa3, 0x62, 0x61, 0x72]);
assert.equal('<Buffer 81 a3 66 6f 6f a3 62 61 72>', (<any> x).inspect());
var z = x.slice(4);
assert.equal(5, z.length);
assert.equal(0x6f, z[0]);
assert.equal(0xa3, z[1]);
assert.equal(0x62, z[2]);
assert.equal(0x61, z[3]);
assert.equal(0x72, z[4]);
var z = x.slice(0);
assert.equal(z.length, x.length);
var z = x.slice(0, 4);
assert.equal(4, z.length);
assert.equal(0x81, z[0]);
assert.equal(0xa3, z[1]);
var z = x.slice(0, 9);
assert.equal(9, z.length);
var z = x.slice(1, 4);
assert.equal(3, z.length);
assert.equal(0xa3, z[0]);
var z = x.slice(2, 4);
assert.equal(2, z.length);
assert.equal(0x66, z[0]);
assert.equal(0x6f, z[1]);
assert.equal(0, new Buffer('hello').slice(0, 0).length);
['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) {
var b = new Buffer(10);
b.write('あいうえお', <any> encoding);
assert.equal(b.toString(encoding), 'あいうえお');
});
// Binary encoding should write only one byte per character.
var b = new Buffer(<any>[0xde, 0xad, 0xbe, 0xef]);
var s = String.fromCharCode(0xffff);
b.write(s, 0, <any> 'binary');
assert.equal(0xff, b[0]);
assert.equal(0xad, b[1]);
assert.equal(0xbe, b[2]);
assert.equal(0xef, b[3]);
s = String.fromCharCode(0xaaee);
b.write(s, 0, <any> 'binary');
assert.equal(0xee, b[0]);
assert.equal(0xad, b[1]);
assert.equal(0xbe, b[2]);
assert.equal(0xef, b[3]);
// This should not segfault the program.
// JV: Disabled because it does not pass with feross/buffer.
/*assert.throws(function() {
new Buffer('"pong"', 0, 6, 8031, '127.0.0.1');
});*/
// #1210 Test UTF-8 string includes null character
var buf = new Buffer('\0');
assert.equal(buf.length, 1);
buf = new Buffer('\0\0');
assert.equal(buf.length, 2);
buf = new Buffer(2);
var written = buf.write(''); // 0byte
assert.equal(written, 0);
written = buf.write('\0'); // 1byte (v8 adds null terminator)
assert.equal(written, 1);
written = buf.write('a\0'); // 1byte * 2
assert.equal(written, 2);
written = buf.write('あ'); // 3bytes
assert.equal(written, 0);
written = buf.write('\0あ'); // 1byte + 3bytes
assert.equal(written, 1);
written = buf.write('\0\0あ'); // 1byte * 2 + 3bytes
assert.equal(written, 2);
buf = new Buffer(10);
written = buf.write('あいう'); // 3bytes * 3 (v8 adds null terminator)
assert.equal(written, 9);
written = buf.write('あいう\0'); // 3bytes * 3 + 1byte
assert.equal(written, 10);
// #243 Test write() with maxLength
var buf = new Buffer(4);
buf.fill(0xFF);
var written = buf.write('abcd', 1, 2, 'utf8');
assert.equal(written, 2);
assert.equal(buf[0], 0xFF);
assert.equal(buf[1], 0x61);
assert.equal(buf[2], 0x62);
assert.equal(buf[3], 0xFF);
buf.fill(0xFF);
written = buf.write('abcd', 1, 4);
assert.equal(written, 3);
assert.equal(buf[0], 0xFF);
assert.equal(buf[1], 0x61);
assert.equal(buf[2], 0x62);
assert.equal(buf[3], 0x63);
buf.fill(0xFF);
written = buf.write('abcd', 1, 2, 'utf8'); // legacy style
assert.equal(written, 2);
assert.equal(buf[0], 0xFF);
assert.equal(buf[1], 0x61);
assert.equal(buf[2], 0x62);
assert.equal(buf[3], 0xFF);
buf.fill(0xFF);
written = buf.write('abcdef', 1, 2, 'hex');
assert.equal(written, 2);
assert.equal(buf[0], 0xFF);
assert.equal(buf[1], 0xAB);
assert.equal(buf[2], 0xCD);
assert.equal(buf[3], 0xFF);
['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) {
buf.fill(0xFF);
written = buf.write('abcd', 0, 2, encoding);
assert.equal(written, 2);
assert.equal(buf[0], 0x61);
assert.equal(buf[1], 0x00);
assert.equal(buf[2], 0xFF);
assert.equal(buf[3], 0xFF);
});
// test offset returns are correct
var b = new Buffer(16);
assert.equal(4, b.writeUInt32LE(0, 0));
assert.equal(6, b.writeUInt16LE(0, 4));
assert.equal(7, b.writeUInt8(0, 6));
assert.equal(8, b.writeInt8(0, 7));
assert.equal(16, b.writeDoubleLE(0, 8));
// test unmatched surrogates not producing invalid utf8 output
// ef bf bd = utf-8 representation of unicode replacement character
// see https://codereview.chromium.org/121173009/
buf = new Buffer('ab\ud800cd', 'utf8');
assert.equal(buf[0], 0x61);
assert.equal(buf[1], 0x62);
assert.equal(buf[2], 0xef);
assert.equal(buf[3], 0xbf);
assert.equal(buf[4], 0xbd);
assert.equal(buf[5], 0x63);
assert.equal(buf[6], 0x64);
// test for buffer overrun
buf = new Buffer([0, 0, 0, 0, 0]); // length: 5
var sub = buf.slice(0, 4); // length: 4
written = sub.write('12345', <any> 'binary');
assert.equal(written, 4);
assert.equal(buf[4], 0);
// Check for fractional length args, junk length args, etc.
// https://github.com/joyent/node/issues/1758
// BFS: NOPE
//Buffer(3.3).toString(); // throws bad argument error in commit 43cb4ec
//assert.equal(Buffer(-1).length, 0);
//assert.equal(Buffer(NaN).length, 0);
//assert.equal(Buffer(3.3).length, 4);
//assert.equal(Buffer({length: 3.3}).length, 4);
//assert.equal(Buffer({length: 'BAM'}).length, 0);
// Make sure that strings are not coerced to numbers.
assert.equal(new Buffer('99').length, 2);
assert.equal((<any> Buffer)('13.37').length, 5);
// Ensure that the length argument is respected.
'ascii utf8 hex base64 binary'.split(' ').forEach(function(enc) {
assert.equal(new Buffer(1).write('aaaaaa', 0, 1, enc), 1);
});
// Regression test, guard against buffer overrun in the base64 decoder.
var a = new Buffer(3);
var b = new Buffer('xxx');
a.write('aaaaaaaa', <any> 'base64');
assert.equal(b.toString(), 'xxx');
// issue GH-3416
(<any> Buffer)(new Buffer(0), 0, 0);
[ 'hex',
'utf8',
'utf-8',
'ascii',
'binary',
'base64',
'ucs2',
'ucs-2',
'utf16le',
'utf-16le' ].forEach(function(enc) {
assert.equal(Buffer.isEncoding(enc), true);
});
[ 'utf9',
'utf-7',
'Unicode-FTW',
'new gnu gun' ].forEach(function(enc) {
assert.equal(Buffer.isEncoding(enc), false);
});
// GH-5110
(function () {
var buffer = new Buffer('test'),
string = JSON.stringify(buffer);
assert.equal(string, '{"type":"Buffer","data":[116,101,115,116]}');
equalCheck(buffer, JSON.parse(string, function(key, value) {
return value && value.type === 'Buffer'
? new Buffer(value.data)
: value;
}));
})();
// issue GH-7849
(function() {
var buf = new Buffer('test');
var json = JSON.stringify(buf);
var obj = JSON.parse(json);
var copy = new Buffer(obj);
assert(buf.equals(copy));
})();
// issue GH-4331
// BFS: Disabled; Opera incorrectly throws a TypeError rather than a RangeError
// when you try to allocate an ArrayBuffer of this size.
assert.throws(function() {
new Buffer(0xFFFFFFFFF);
}, RangeError);
// attempt to overflow buffers, similar to previous bug in array buffers
assert.throws(function() {
var buf = new Buffer(8);
buf.readFloatLE(0xffffffff);
}, RangeError);
assert.throws(function() {
var buf = new Buffer(8);
buf.writeFloatLE(0.0, 0xffffffff);
}, RangeError);
assert.throws(function() {
var buf = new Buffer(8);
buf.readFloatLE(0xffffffff);
}, RangeError);
assert.throws(function() {
var buf = new Buffer(8);
buf.writeFloatLE(0.0, 0xffffffff);
}, RangeError);
// ensure negative values can't get past offset
assert.throws(function() {
var buf = new Buffer(8);
buf.readFloatLE(-1);
}, RangeError);
assert.throws(function() {
var buf = new Buffer(8);
buf.writeFloatLE(0.0, -1);
}, RangeError);
assert.throws(function() {
var buf = new Buffer(8);
buf.readFloatLE(-1);
}, RangeError);
assert.throws(function() {
var buf = new Buffer(8);
buf.writeFloatLE(0.0, -1);
}, RangeError);
// offset checks
var buf = new Buffer(0);
assert.throws(function() { buf.readUInt8(0); }, RangeError);
assert.throws(function() { buf.readInt8(0); }, RangeError);
var buf = new Buffer([0xFF]);
assert.equal(buf.readUInt8(0), 255);
assert.equal(buf.readInt8(0), -1);
[16, 32].forEach(function(bits) {
var buf = new Buffer(bits / 8 - 1);
assert.throws(function() { (<any>buf)['readUInt' + bits + 'BE'](0); },
RangeError,
'readUInt' + bits + 'BE');
assert.throws(function() { (<any>buf)['readUInt' + bits + 'LE'](0); },
RangeError,
'readUInt' + bits + 'LE');
assert.throws(function() { (<any>buf)['readInt' + bits + 'BE'](0); },
RangeError,
'readInt' + bits + 'BE()');
assert.throws(function() { (<any>buf)['readInt' + bits + 'LE'](0); },
RangeError,
'readInt' + bits + 'LE()');
});
[16, 32].forEach(function(bits) {
var buf = new Buffer([0xFF, 0xFF, 0xFF, 0xFF]);
assert.equal((<any>buf)['readUInt' + bits + 'BE'](0),
(0xFFFFFFFF >>> (32 - bits)));
assert.equal((<any>buf)['readUInt' + bits + 'LE'](0),
(0xFFFFFFFF >>> (32 - bits)));
assert.equal((<any>buf)['readInt' + bits + 'BE'](0),
(0xFFFFFFFF >> (32 - bits)));
assert.equal((<any>buf)['readInt' + bits + 'LE'](0),
(0xFFFFFFFF >> (32 - bits)));
});
// test for common read(U)IntLE/BE
(function() {
var buf = new Buffer([0x01, 0x02, 0x03, 0x04, 0x05, 0x06]);
assert.equal(buf.readUIntLE(0, 1), 0x01);
assert.equal(buf.readUIntBE(0, 1), 0x01);
assert.equal(buf.readUIntLE(0, 3), 0x030201);
assert.equal(buf.readUIntBE(0, 3), 0x010203);
assert.equal(buf.readUIntLE(0, 5), 0x0504030201);
assert.equal(buf.readUIntBE(0, 5), 0x0102030405);
assert.equal(buf.readUIntLE(0, 6), 0x060504030201);
assert.equal(buf.readUIntBE(0, 6), 0x010203040506);
assert.equal(buf.readIntLE(0, 1), 0x01);
assert.equal(buf.readIntBE(0, 1), 0x01);
assert.equal(buf.readIntLE(0, 3), 0x030201);
assert.equal(buf.readIntBE(0, 3), 0x010203);
assert.equal(buf.readIntLE(0, 5), 0x0504030201);
assert.equal(buf.readIntBE(0, 5), 0x0102030405);
assert.equal(buf.readIntLE(0, 6), 0x060504030201);
assert.equal(buf.readIntBE(0, 6), 0x010203040506);
})();
// test for common write(U)IntLE/BE
(function() {
var buf = new Buffer(3);
buf.writeUIntLE(0x123456, 0, 3);
assert.deepEqual(buf.toJSON().data, [0x56, 0x34, 0x12]);
assert.equal(buf.readUIntLE(0, 3), 0x123456);
buf = new Buffer(3);
buf.writeUIntBE(0x123456, 0, 3);
assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56]);
assert.equal(buf.readUIntBE(0, 3), 0x123456);
buf = new Buffer(3);
buf.writeIntLE(0x123456, 0, 3);
assert.deepEqual(buf.toJSON().data, [0x56, 0x34, 0x12]);
assert.equal(buf.readIntLE(0, 3), 0x123456);
buf = new Buffer(3);
buf.writeIntBE(0x123456, 0, 3);
assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56]);
assert.equal(buf.readIntBE(0, 3), 0x123456);
buf = new Buffer(3);
buf.writeIntLE(-0x123456, 0, 3);
assert.deepEqual(buf.toJSON().data, [0xaa, 0xcb, 0xed]);
assert.equal(buf.readIntLE(0, 3), -0x123456);
buf = new Buffer(3);
buf.writeIntBE(-0x123456, 0, 3);
assert.deepEqual(buf.toJSON().data, [0xed, 0xcb, 0xaa]);
assert.equal(buf.readIntBE(0, 3), -0x123456);
buf = new Buffer(5);
buf.writeUIntLE(0x1234567890, 0, 5);
assert.deepEqual(buf.toJSON().data, [0x90, 0x78, 0x56, 0x34, 0x12]);
assert.equal(buf.readUIntLE(0, 5), 0x1234567890);
buf = new Buffer(5);
buf.writeUIntBE(0x1234567890, 0, 5);
assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56, 0x78, 0x90]);
assert.equal(buf.readUIntBE(0, 5), 0x1234567890);
buf = new Buffer(5);
buf.writeIntLE(0x1234567890, 0, 5);
assert.deepEqual(buf.toJSON().data, [0x90, 0x78, 0x56, 0x34, 0x12]);
assert.equal(buf.readIntLE(0, 5), 0x1234567890);
buf = new Buffer(5);
buf.writeIntBE(0x1234567890, 0, 5);
assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56, 0x78, 0x90]);
assert.equal(buf.readIntBE(0, 5), 0x1234567890);
buf = new Buffer(5);
buf.writeIntLE(-0x1234567890, 0, 5);
assert.deepEqual(buf.toJSON().data, [0x70, 0x87, 0xa9, 0xcb, 0xed]);
assert.equal(buf.readIntLE(0, 5), -0x1234567890);
buf = new Buffer(5);
buf.writeIntBE(-0x1234567890, 0, 5);
assert.deepEqual(buf.toJSON().data, [0xed, 0xcb, 0xa9, 0x87, 0x70]);
assert.equal(buf.readIntBE(0, 5), -0x1234567890);
})();
// test Buffer slice
(function() {
var buf = new Buffer('0123456789');
assert.equal(buf.slice(-10, 10), '0123456789');
assert.equal(buf.slice(-20, 10), '0123456789');
assert.equal(buf.slice(-20, -10), '');
assert.equal(buf.slice(), '0123456789');
assert.equal(buf.slice(0), '0123456789');
assert.equal(buf.slice(0, 0), '');
assert.equal(buf.slice(undefined), '0123456789');
assert.equal(buf.slice(<any> 'foobar'), '0123456789');
assert.equal(buf.slice(undefined, undefined), '0123456789');
assert.equal(buf.slice(2), '23456789');
assert.equal(buf.slice(5), '56789');
assert.equal(buf.slice(10), '');
assert.equal(buf.slice(5, 8), '567');
assert.equal(buf.slice(8, -1), '8');
assert.equal(buf.slice(-10), '0123456789');
assert.equal(buf.slice(0, -9), '0');
assert.equal(buf.slice(0, -10), '');
assert.equal(buf.slice(0, -1), '012345678');
assert.equal(buf.slice(2, -2), '234567');
assert.equal(buf.slice(0, 65536), '0123456789');
assert.equal(buf.slice(65536, 0), '');
assert.equal(buf.slice(-5, -8), '');
assert.equal(buf.slice(-5, -3), '56');
assert.equal(buf.slice(-10, 10), '0123456789');
for (var i = 0, s = buf.toString(); i < buf.length; ++i) {
assert.equal(buf.slice(i), s.slice(i));
assert.equal(buf.slice(0, i), s.slice(0, i));
assert.equal(buf.slice(-i), s.slice(-i));
assert.equal(buf.slice(0, -i), s.slice(0, -i));
}
var utf16Buf = new Buffer('0123456789', 'utf16le');
assert.deepEqual(utf16Buf.slice(0, 6), (<any> Buffer)('012', 'utf16le'));
assert.equal((<any>buf).slice('0', '1'), '0');
assert.equal((<any>buf).slice('-5', '10'), '56789');
assert.equal((<any>buf).slice('-10', '10'), '0123456789');
assert.equal((<any>buf).slice('-10', '-5'), '01234');
assert.equal((<any>buf).slice('-10', '-0'), '');
assert.equal((<any>buf).slice('111'), '');
assert.equal((<any>buf).slice('0', '-111'), '');
// try to slice a zero length Buffer
// see https://github.com/joyent/node/issues/5881
(<any> SlowBuffer)(0).slice(0, 1);
})();
// Regression test for #5482: should throw but not assert in C++ land.
assert.throws(function() {
new Buffer('', 'buffer');
}, TypeError);
// Regression test for #6111. Constructing a buffer from another buffer
// should a) work, and b) not corrupt the source buffer.
(function() {
var a = [0];
for (var i = 0; i < 7; ++i) a = a.concat(a);
a = a.map(function(_, i) { return i; });
var b = new Buffer(a);
var c = new Buffer(b);
assert.equal(b.length, a.length);
assert.equal(c.length, a.length);
for (var i = 0, k = a.length; i < k; ++i) {
assert.equal(a[i], i);
assert.equal(b[i], i);
assert.equal(c[i], i);
}
})();
assert.throws(function() {
new Buffer((-1 >>> 0) + 1);
}, RangeError);
assert.throws(function() {
new SlowBuffer((-1 >>> 0) + 1);
}, RangeError);
// Test Compare
var b = new Buffer(1).fill('a');
var c = new Buffer(1).fill('c');
var d = new Buffer(2).fill('aa');
assert.equal(b.compare(c), -1);
assert.equal(c.compare(d), 1);
assert.equal(d.compare(b), 1);
assert.equal(b.compare(d), -1);
assert.equal(b.compare(b), 0);
assert.equal(Buffer.compare(b, c), -1);
assert.equal(Buffer.compare(c, d), 1);
assert.equal(Buffer.compare(d, b), 1);
assert.equal(Buffer.compare(b, d), -1);
assert.equal(Buffer.compare(c, c), 0);
assert.equal(Buffer.compare(new Buffer(0), new Buffer(0)), 0);
assert.equal(Buffer.compare(new Buffer(0), new Buffer(1)), -1);
assert.equal(Buffer.compare(new Buffer(1), new Buffer(0)), 1);
assert.throws(function() {
var b = new Buffer(1);
Buffer.compare(b, <any> 'abc');
});
assert.throws(function() {
var b = new Buffer(1);
Buffer.compare(<any> 'abc', b);
});
assert.throws(function() {
var b = new Buffer(1);
b.compare(<any> 'abc');
});
// Test Equals
var b = new Buffer(5).fill('abcdf');
var c = new Buffer(5).fill('abcdf');
var d = new Buffer(5).fill('abcde');
var e = new Buffer(6).fill('abcdef');
assert.ok(b.equals(c));
assert.ok(!c.equals(d));
assert.ok(!d.equals(e));
assert.ok(d.equals(d));
assert.throws(function() {
var b = new Buffer(1);
b.equals(<any> 'abc');
});
// Regression test for https://github.com/nodejs/node/issues/649.
// BFS: Let's not allocate something huge.
// assert.throws(function() { Buffer(1422561062959).toString('utf8'); });
// BFS: Irrelevant.
// var ps = Buffer.poolSize;
// Buffer.poolSize = 0;
// assert.equal(Buffer(1).parent, undefined);
// Buffer.poolSize = ps;
// Test Buffer.copy() segfault
assert.throws(function() {
(<any> new Buffer(10)).copy();
});
assert.throws(function() {
new (<any> Buffer)();
});
// BFS: Who cares about the message?
//, /must start with number, buffer, array or string/);
assert.throws(function() {
new Buffer(null);
});
// BFS: Who cares about the message?
//, /must start with number, buffer, array or string/);
}; | the_stack |
import {Request} from '../lib/request';
import {Response} from '../lib/response';
import {AWSError} from '../lib/error';
import {Service} from '../lib/service';
import {ServiceConfigurationOptions} from '../lib/service';
import {ConfigBase as Config} from '../lib/config';
interface Blob {}
declare class Mobile extends Service {
/**
* Constructs a service object. This object has one method for each API operation.
*/
constructor(options?: Mobile.Types.ClientConfiguration)
config: Config & Mobile.Types.ClientConfiguration;
/**
* Creates an AWS Mobile Hub project.
*/
createProject(params: Mobile.Types.CreateProjectRequest, callback?: (err: AWSError, data: Mobile.Types.CreateProjectResult) => void): Request<Mobile.Types.CreateProjectResult, AWSError>;
/**
* Creates an AWS Mobile Hub project.
*/
createProject(callback?: (err: AWSError, data: Mobile.Types.CreateProjectResult) => void): Request<Mobile.Types.CreateProjectResult, AWSError>;
/**
* Delets a project in AWS Mobile Hub.
*/
deleteProject(params: Mobile.Types.DeleteProjectRequest, callback?: (err: AWSError, data: Mobile.Types.DeleteProjectResult) => void): Request<Mobile.Types.DeleteProjectResult, AWSError>;
/**
* Delets a project in AWS Mobile Hub.
*/
deleteProject(callback?: (err: AWSError, data: Mobile.Types.DeleteProjectResult) => void): Request<Mobile.Types.DeleteProjectResult, AWSError>;
/**
* Get the bundle details for the requested bundle id.
*/
describeBundle(params: Mobile.Types.DescribeBundleRequest, callback?: (err: AWSError, data: Mobile.Types.DescribeBundleResult) => void): Request<Mobile.Types.DescribeBundleResult, AWSError>;
/**
* Get the bundle details for the requested bundle id.
*/
describeBundle(callback?: (err: AWSError, data: Mobile.Types.DescribeBundleResult) => void): Request<Mobile.Types.DescribeBundleResult, AWSError>;
/**
* Gets details about a project in AWS Mobile Hub.
*/
describeProject(params: Mobile.Types.DescribeProjectRequest, callback?: (err: AWSError, data: Mobile.Types.DescribeProjectResult) => void): Request<Mobile.Types.DescribeProjectResult, AWSError>;
/**
* Gets details about a project in AWS Mobile Hub.
*/
describeProject(callback?: (err: AWSError, data: Mobile.Types.DescribeProjectResult) => void): Request<Mobile.Types.DescribeProjectResult, AWSError>;
/**
* Generates customized software development kit (SDK) and or tool packages used to integrate mobile web or mobile app clients with backend AWS resources.
*/
exportBundle(params: Mobile.Types.ExportBundleRequest, callback?: (err: AWSError, data: Mobile.Types.ExportBundleResult) => void): Request<Mobile.Types.ExportBundleResult, AWSError>;
/**
* Generates customized software development kit (SDK) and or tool packages used to integrate mobile web or mobile app clients with backend AWS resources.
*/
exportBundle(callback?: (err: AWSError, data: Mobile.Types.ExportBundleResult) => void): Request<Mobile.Types.ExportBundleResult, AWSError>;
/**
* Exports project configuration to a snapshot which can be downloaded and shared. Note that mobile app push credentials are encrypted in exported projects, so they can only be shared successfully within the same AWS account.
*/
exportProject(params: Mobile.Types.ExportProjectRequest, callback?: (err: AWSError, data: Mobile.Types.ExportProjectResult) => void): Request<Mobile.Types.ExportProjectResult, AWSError>;
/**
* Exports project configuration to a snapshot which can be downloaded and shared. Note that mobile app push credentials are encrypted in exported projects, so they can only be shared successfully within the same AWS account.
*/
exportProject(callback?: (err: AWSError, data: Mobile.Types.ExportProjectResult) => void): Request<Mobile.Types.ExportProjectResult, AWSError>;
/**
* List all available bundles.
*/
listBundles(params: Mobile.Types.ListBundlesRequest, callback?: (err: AWSError, data: Mobile.Types.ListBundlesResult) => void): Request<Mobile.Types.ListBundlesResult, AWSError>;
/**
* List all available bundles.
*/
listBundles(callback?: (err: AWSError, data: Mobile.Types.ListBundlesResult) => void): Request<Mobile.Types.ListBundlesResult, AWSError>;
/**
* Lists projects in AWS Mobile Hub.
*/
listProjects(params: Mobile.Types.ListProjectsRequest, callback?: (err: AWSError, data: Mobile.Types.ListProjectsResult) => void): Request<Mobile.Types.ListProjectsResult, AWSError>;
/**
* Lists projects in AWS Mobile Hub.
*/
listProjects(callback?: (err: AWSError, data: Mobile.Types.ListProjectsResult) => void): Request<Mobile.Types.ListProjectsResult, AWSError>;
/**
* Update an existing project.
*/
updateProject(params: Mobile.Types.UpdateProjectRequest, callback?: (err: AWSError, data: Mobile.Types.UpdateProjectResult) => void): Request<Mobile.Types.UpdateProjectResult, AWSError>;
/**
* Update an existing project.
*/
updateProject(callback?: (err: AWSError, data: Mobile.Types.UpdateProjectResult) => void): Request<Mobile.Types.UpdateProjectResult, AWSError>;
}
declare namespace Mobile {
export type AttributeKey = string;
export type AttributeValue = string;
export type Attributes = {[key: string]: AttributeValue};
export type Boolean = boolean;
export type BundleDescription = string;
export interface BundleDetails {
bundleId?: BundleId;
title?: BundleTitle;
version?: BundleVersion;
description?: BundleDescription;
iconUrl?: IconUrl;
availablePlatforms?: Platforms;
}
export type BundleId = string;
export type BundleList = BundleDetails[];
export type BundleTitle = string;
export type BundleVersion = string;
export type ConsoleUrl = string;
export type Contents = Buffer|Uint8Array|Blob|string;
export interface CreateProjectRequest {
/**
* Name of the project.
*/
name?: ProjectName;
/**
* Default region where project resources should be created.
*/
region?: ProjectRegion;
/**
* ZIP or YAML file which contains configuration settings to be used when creating the project. This may be the contents of the file downloaded from the URL provided in an export project operation.
*/
contents?: Contents;
/**
* Unique identifier for an exported snapshot of project configuration. This snapshot identifier is included in the share URL when a project is exported.
*/
snapshotId?: SnapshotId;
}
export interface CreateProjectResult {
/**
* Detailed information about the created AWS Mobile Hub project.
*/
details?: ProjectDetails;
}
export type _Date = Date;
export interface DeleteProjectRequest {
/**
* Unique project identifier.
*/
projectId: ProjectId;
}
export interface DeleteProjectResult {
/**
* Resources which were deleted.
*/
deletedResources?: Resources;
/**
* Resources which were not deleted, due to a risk of losing potentially important data or files.
*/
orphanedResources?: Resources;
}
export interface DescribeBundleRequest {
/**
* Unique bundle identifier.
*/
bundleId: BundleId;
}
export interface DescribeBundleResult {
/**
* The details of the bundle.
*/
details?: BundleDetails;
}
export interface DescribeProjectRequest {
/**
* Unique project identifier.
*/
projectId: ProjectId;
/**
* If set to true, causes AWS Mobile Hub to synchronize information from other services, e.g., update state of AWS CloudFormation stacks in the AWS Mobile Hub project.
*/
syncFromResources?: Boolean;
}
export interface DescribeProjectResult {
details?: ProjectDetails;
}
export type DownloadUrl = string;
export type ErrorMessage = string;
export interface ExportBundleRequest {
/**
* Unique bundle identifier.
*/
bundleId: BundleId;
/**
* Unique project identifier.
*/
projectId?: ProjectId;
/**
* Developer desktop or target application platform.
*/
platform?: Platform;
}
export interface ExportBundleResult {
/**
* URL which contains the custom-generated SDK and tool packages used to integrate the client mobile app or web app with the AWS resources created by the AWS Mobile Hub project.
*/
downloadUrl?: DownloadUrl;
}
export interface ExportProjectRequest {
/**
* Unique project identifier.
*/
projectId: ProjectId;
}
export interface ExportProjectResult {
/**
* URL which can be used to download the exported project configuation file(s).
*/
downloadUrl?: DownloadUrl;
/**
* URL which can be shared to allow other AWS users to create their own project in AWS Mobile Hub with the same configuration as the specified project. This URL pertains to a snapshot in time of the project configuration that is created when this API is called. If you want to share additional changes to your project configuration, then you will need to create and share a new snapshot by calling this method again.
*/
shareUrl?: ShareUrl;
/**
* Unique identifier for the exported snapshot of the project configuration. This snapshot identifier is included in the share URL.
*/
snapshotId?: SnapshotId;
}
export type Feature = string;
export type IconUrl = string;
export interface ListBundlesRequest {
/**
* Maximum number of records to list in a single response.
*/
maxResults?: MaxResults;
/**
* Pagination token. Set to null to start listing bundles from start. If non-null pagination token is returned in a result, then pass its value in here in another request to list more bundles.
*/
nextToken?: NextToken;
}
export interface ListBundlesResult {
/**
* A list of bundles.
*/
bundleList?: BundleList;
/**
* Pagination token. If non-null pagination token is returned in a result, then pass its value in another request to fetch more entries.
*/
nextToken?: NextToken;
}
export interface ListProjectsRequest {
/**
* Maximum number of records to list in a single response.
*/
maxResults?: MaxResults;
/**
* Pagination token. Set to null to start listing projects from start. If non-null pagination token is returned in a result, then pass its value in here in another request to list more projects.
*/
nextToken?: NextToken;
}
export interface ListProjectsResult {
projects?: ProjectSummaries;
nextToken?: NextToken;
}
export type MaxResults = number;
export type NextToken = string;
export type Platform = "OSX"|"WINDOWS"|"LINUX"|"OBJC"|"SWIFT"|"ANDROID"|"JAVASCRIPT"|string;
export type Platforms = Platform[];
export interface ProjectDetails {
name?: ProjectName;
projectId?: ProjectId;
region?: ProjectRegion;
state?: ProjectState;
/**
* Date the project was created.
*/
createdDate?: _Date;
/**
* Date of the last modification of the project.
*/
lastUpdatedDate?: _Date;
/**
* Website URL for this project in the AWS Mobile Hub console.
*/
consoleUrl?: ConsoleUrl;
resources?: Resources;
}
export type ProjectId = string;
export type ProjectName = string;
export type ProjectRegion = string;
export type ProjectState = "NORMAL"|"SYNCING"|"IMPORTING"|string;
export type ProjectSummaries = ProjectSummary[];
export interface ProjectSummary {
/**
* Name of the project.
*/
name?: ProjectName;
/**
* Unique project identifier.
*/
projectId?: ProjectId;
}
export interface Resource {
type?: ResourceType;
name?: ResourceName;
arn?: ResourceArn;
feature?: Feature;
attributes?: Attributes;
}
export type ResourceArn = string;
export type ResourceName = string;
export type ResourceType = string;
export type Resources = Resource[];
export type ShareUrl = string;
export type SnapshotId = string;
export interface UpdateProjectRequest {
/**
* ZIP or YAML file which contains project configuration to be updated. This should be the contents of the file downloaded from the URL provided in an export project operation.
*/
contents?: Contents;
/**
* Unique project identifier.
*/
projectId: ProjectId;
}
export interface UpdateProjectResult {
/**
* Detailed information about the updated AWS Mobile Hub project.
*/
details?: ProjectDetails;
}
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
export type apiVersion = "2017-07-01"|"latest"|string;
export interface ClientApiVersions {
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
apiVersion?: apiVersion;
}
export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions;
/**
* Contains interfaces for use with the Mobile client.
*/
export import Types = Mobile;
}
export = Mobile; | the_stack |
import { Agent, AgentId } from '../../service/Agent';
import { AgentPod, Event } from '../../service/AgentPod';
import { NetworkAgent, ConnectionId,
NetworkEventType, ConnectionStatusChangeEvent,
ConnectionStatus, MessageReceivedEvent, Endpoint } from '../network/NetworkAgent';
import { RNGImpl } from 'crypto/random';
import { HMACImpl } from 'crypto/hmac';
import { ChaCha20Impl } from 'crypto/ciphers';
import { Identity } from 'data/identity';
import { Hash, Hashing, LiteralContext,
HashedObject } from 'data/model';
import { Strings } from 'util/strings';
import { Logger, LogLevel } from 'util/logging';
/*
* SecureNetworkAgent: Verify that the other end of a connection is in possession of
* a given Identity (a key pair whose public part, when joined with
* some additional information, hashes to a given value) and use
* the key pair to securely send a secret that can be used later to
* send encrypted messages (and of course also implement the recipient
* side of this exchange).
*
*/
/* The methods sendIdentityChallenge and answerIdentityChallenge must be called locally
* by the agent(s) that need to secure the connections on both ends.
*
* Once the authentication is done, which will be notified via an event, the method
* sendSecureMessage can be used to send a message, that will show up as a local event
* for the target agent on the receiving end of the connection.
*
*/
type Status = IdHolderStatus | IdChallengerStatus;
enum IdHolderStatus {
ExpectingChallenge = 'expecting-challenge',
ReceivedUnexpectedChallenge = 'received-unexpected-challenge',
ReceivedUnexpectedIdentityRequest = 'received-unexpected-identity-request',
SentIdentity = 'sent-identity',
SentChallengeAnswer = 'sent-challenge-answer',
IdentityVerified = 'identity-verified',
IdentityRejected = 'identity-rejected'
};
enum IdChallengerStatus {
WaitingToChallenge = 'waiting-to-challenge',
SentIdentityRequest = 'sent-identity-request',
SentChallenge = 'sent-challenge',
IdentityVerified = 'identity-verified',
IdentityRejected = 'identity-rejected'
}
// The following state machine models conneciton validation:
// id holder:
// nil -> 'received-unexpected-identity-request' on 'request-identity' message reception
// nil -> 'received-unexpected-challenge' on 'send-challenge' message reception
// nil -> 'expecting-challenge' on answerIdentityChallenge() call
// 'expecting-challenge' -> 'sent-identity' on 'request-identity' message reception
// 'sent-identity' -> 'sent-challenge-answer' on 'send-challenge' message reception
// 'expecting-challenge' -> 'sent-challenge-answer' on 'send-challenge' message reception
// 'sent-challenge-answer' -> 'identity-verified' on 'challenge-result' message reception (accepted)
// 'sent-challenge-answer' -> 'identity-rejected' on 'challenge-result' message reception (rejected)
// id challenger:
// nil -> 'waiting-to-challenge' on sendIdentityChallenge() call (connection not ready yet)
// nil -> 'sent-identity-request' on sendIdentityChallenge() call, without identity (connected)
// nil -> 'sent-challenge' on sendIdentityChallenge() call, with identity (connected)
// 'waiting-to-challenge' -> 'sent-identity-request' on connection ready, no identity
// 'waiting-to-challenge' -> 'sent-challenge' on connection ready, identity present
// 'sent-identity-request' -> 'sent-challenge' on 'send-identity' message reception
// 'sent-challente' -> 'identity-verified' on 'answer-challenge' message reception (accepted)
// 'sent-challenge' -> 'identity-rejected' on 'answer-challenge' message reception (rejected)
enum MessageType {
RequestIdentity = 'request-identity',
SendIdentity = 'send-identity',
SendChallenge = 'send-challenge',
AnswerChallenge = 'answer-challenge',
ChallengeResult = 'challenge-result',
SecureMessage = 'secure-message',
};
type ControlMessage = IdHolderMessage | IdChallengerMessage | SecureMessage;
type IdHolderMessage = SendIdentityMessage | AnswerChallengeMessage;
type IdChallengerMessage = RequestIdentityMessage | SendChallengeMessage | ChallengeResultMessage;
type RequestIdentityMessage = {
type: MessageType.RequestIdentity,
identityHash: Hash
}
type SendIdentityMessage = {
type: MessageType.SendIdentity,
identityHash: Hash,
identity: LiteralContext
}
type SendChallengeMessage = {
type: MessageType.SendChallenge,
identityHash: Hash,
encrypedSecret: Array<string>,
}
type AnswerChallengeMessage = {
type: MessageType.AnswerChallenge,
identityHash: Hash,
secretHash: Hash
}
type ChallengeResultMessage = {
type: MessageType.ChallengeResult,
identityHash: Hash,
result: boolean
}
type SecureMessage = {
type: MessageType.SecureMessage,
identityHash: Hash,
payload: string,
nonce: string,
hmac: string,
id?: string, // optional id, used for fragmenting large messages
fragSeq?: number, // sequence number on a large message fragment
fragCount?: number // total number of fragments in a large message
};
type SecureMessagePayload = {
senderIdentityHash: Hash,
agentId: AgentId
content: any
};
enum SecureNetworkEventType {
SecureMessageReceived = 'secure-message-received',
ConnectionIdentityAuth = 'connection-identity-auth'
}
type SecureMessageReceivedEvent = {
type: SecureNetworkEventType.SecureMessageReceived,
content: {
connId: ConnectionId,
sender: Hash,
recipient: Hash,
payload: any
}
};
type PartialMessage = {
created: number,
updated: number,
connId: ConnectionId,
recipient: Hash,
fragCount: number,
fragments: Map<number, string>
};
enum IdentityAuthStatus {
Accepted = 'accepted',
Rejected = 'rejected',
Requested = 'requested'
};
enum IdentityLocation {
Local = 'local',
Remote = 'remote'
}
type ConnectionIdentityAuthEvent = {
type: SecureNetworkEventType.ConnectionIdentityAuth,
content: {
connId: ConnectionId,
identityLocation: IdentityLocation,
identityHash: Hash,
identity?: Identity,
status: IdentityAuthStatus
}
};
class OneWaySecuredConnection {
static Separator = '__';
connId : ConnectionId;
status? : Status;
timeout? : number;
identityHash : Hash;
identity? : Identity;
secret? : string;
encryptedSecret? : Array<string>;
constructor(connectionId: ConnectionId, identityHash: Hash) {
this.connId = connectionId;
this.identityHash = identityHash;
}
verified() {
return this.status === IdHolderStatus.IdentityVerified;
}
generateSecret() {
this.secret = new RNGImpl().randomHexString(256);
// use 256 bits so it can be use as a ChaCha20 key
}
async encryptSecret() {
if (this.secret === undefined) {
throw new Error('Attempted to encrypt connection secret before generating it.');
}
if (this.identity === undefined) {
throw new Error('Attempted to encrypt connection secret, but identity is missing.');
}
const encryptedSecret = new Array<string>();
for (const chunk of Strings.chunk(this.secret, 32)) {
encryptedSecret.push(await this.identity.encrypt(chunk) as string)
}
this.encryptedSecret = encryptedSecret;
}
async decryptSecret() {
if (this.identity === undefined) {
throw new Error('Secured connection cannot decrypt received secret: identity is missing');
}
if (!this.identity.hasKeyPair()) {
throw new Error('Secured connection cannot decrypt received secret: using an identity without a key pair');
}
if (this.encryptedSecret === undefined) {
throw new Error('Secured connection cannot decrypt received secret: it is missing');
}
const chunks = new Array<string>();
for (const encryptedChunk of this.encryptedSecret) {
chunks.push(await this.identity.decrypt(encryptedChunk));
}
this.secret = Strings.unchunk(chunks);
}
computeSecretHash() {
if (this.secret === undefined) {
throw new Error('Cannot hash secret: it is missing');
}
return Hashing.forString(this.secret);
}
setTimeout(seconds: number) {
this.timeout = new Date().getTime() + seconds * 1000;
}
encode() {
return OneWaySecuredConnection.encode(this.connId, this.identityHash);
}
static encode(connectionId: ConnectionId, identity: Hash) {
return connectionId + OneWaySecuredConnection.Separator + identity;
}
static decode(encoded: string) {
const parts = encoded.split(OneWaySecuredConnection.Separator);
return new OneWaySecuredConnection(parts[0], parts[1]);
}
}
class ConnectionSecuredForReceiving extends OneWaySecuredConnection {
status?: IdHolderStatus;
constructor(connectionId: ConnectionId, identityHash: Hash) {
super(connectionId, identityHash);
}
}
class ConnectionSecuredForSending extends OneWaySecuredConnection {
status?: IdChallengerStatus;
constructor(connectionId: ConnectionId, identityHash: Hash) {
super(connectionId, identityHash);
}
}
const DEFAULT_TIMEOUT = 15;
const MAX_PAYLOAD_SIZE = 32 * 1024;
const MAX_MESSAGE_FRAGMENTS = 64;
const FRAGMENT_ASSEMBLY_TIMEOUT_FREQ = 2;
class SecureNetworkAgent implements Agent {
static logger = new Logger(SecureNetworkAgent.name, LogLevel.INFO);
static Id = 'secure-connection-agent';
remoteIdentities : Map<string, ConnectionSecuredForSending>;
localIdentities : Map<string, ConnectionSecuredForReceiving>;
messageFragments : Map<string, PartialMessage>;
fragmentAssemblyInterval?: number;
pod?: AgentPod;
private checkFragmentAssemblyInterval() {
if (this.messageFragments.size === 0) {
if (this.fragmentAssemblyInterval !== undefined) {
clearInterval(this.fragmentAssemblyInterval)
}
} else {
if (this.fragmentAssemblyInterval === undefined) {
setInterval(this.fragmentAssemblyTimeouts, FRAGMENT_ASSEMBLY_TIMEOUT_FREQ * 1000);
}
}
}
fragmentAssemblyTimeouts() {
const toRemove = new Array<string>();
for (const [id, partialMsg] of this.messageFragments.entries()) {
const timeout = Math.max(8000, 250 * partialMsg.fragCount) + partialMsg.created;
const updateTimeout = Math.max(timeout, 6000 + partialMsg.updated);
const now = Date.now();
if (now > timeout || now > updateTimeout) {
toRemove.push(id);
SecureNetworkAgent.logger.warning('Removed message ' + id + ' due to re-assembly timeout!');
}
}
for (const id of toRemove) {
this.messageFragments.delete(id);
}
if (toRemove.length > 0) {
this.checkFragmentAssemblyInterval();
}
}
constructor() {
this.remoteIdentities = new Map();
this.localIdentities = new Map();
this.messageFragments = new Map();
this.fragmentAssemblyInterval = undefined;
this.fragmentAssemblyTimeouts = this.fragmentAssemblyTimeouts.bind(this);
}
getAgentId(): string {
return SecureNetworkAgent.Id;
}
ready(pod: AgentPod): void {
this.pod = pod;
}
receiveLocalEvent(ev: Event): void {
if (ev.type === NetworkEventType.ConnectionStatusChange) {
let connEv = ev as ConnectionStatusChangeEvent;
if (connEv.content.status === ConnectionStatus.Closed) {
this.removeIdentitiesForConnection(ev.content.connId);
} else if (connEv.content.status === ConnectionStatus.Ready) {
for (const secured of this.remoteIdentities.values()) {
if (secured.connId === connEv.content.localEndpoint &&
secured.status === IdChallengerStatus.WaitingToChallenge) {
this.sendChallengeMessage(secured);
}
}
}
} else if (ev.type === NetworkEventType.MessageReceived) {
let msgEv = ev as MessageReceivedEvent;
this.receiveMessage(msgEv.content.connectionId , msgEv.content.source, msgEv.content.destination, msgEv.content.content);
}
}
// for identity holder:
secureForReceiving(connId: ConnectionId, localIdentity: Identity, timeout=DEFAULT_TIMEOUT) {
SecureNetworkAgent.logger.trace('Asked to verify ' + connId + ' for receiving with ' + localIdentity.hash());
const identityHash = localIdentity.hash();
let secured = this.getOrCreateConnectionSecuredForReceiving(connId, identityHash);
secured.identity = localIdentity;
secured.setTimeout(timeout);
if (secured.status === IdHolderStatus.ReceivedUnexpectedIdentityRequest) {
this.sendIdentity(connId, localIdentity, identityHash);
secured.status = IdHolderStatus.SentIdentity;
} else if (secured.status === IdHolderStatus.ReceivedUnexpectedChallenge) {
secured.decryptSecret().then(() => {
//TODO: see if we have introduced a race condition by making decryptSecret async.
this.answerReceivedChallenge(connId, identityHash, secured.computeSecretHash());
secured.status = IdHolderStatus.SentChallengeAnswer;
})
} else if (secured.status === undefined) {
secured.status = IdHolderStatus.ExpectingChallenge;
} // else, negotiation is already running, just let it run its course
}
// for identity challenger:
secureForSending(connId: ConnectionId, remoteIdentityHash: Hash, remoteIdentity?: Identity, timeout=DEFAULT_TIMEOUT) {
let connInfo = this.getNetworkAgent().getConnectionInfo(connId);
if (connInfo?.status !== ConnectionStatus.Closed) {
let secured = this.getOrCreateConnectionSecuredForSending(connId, remoteIdentityHash);
secured.setTimeout(timeout);
if (secured.identity === undefined) {
secured.identity = remoteIdentity;
}
if (connInfo?.status === ConnectionStatus.Ready) {
if (secured.status === undefined || secured.status === 'identity-rejected') {
this.sendChallengeMessage(secured);
} // else, negotiation is already running, just let it run its course
} else if (connInfo?.status === ConnectionStatus.Received ||
connInfo?.status === ConnectionStatus.Establishing) {
secured.status = IdChallengerStatus.WaitingToChallenge;
}
}
}
private sendChallengeMessage(secured: ConnectionSecuredForSending) {
if (secured.identity === undefined) {
this.sendIdentityRequest(secured.connId, secured.identityHash);
secured.status = IdChallengerStatus.SentIdentityRequest;
SecureNetworkAgent.logger.trace('Sent identity request for ' + secured.identityHash + ' through connection ' + secured.connId);
} else {
SecureNetworkAgent.logger.trace('Sending identity challenge for ' + secured.identityHash + ' through connection ' + secured.connId);
secured.generateSecret();
//TODO: see if we have introduced a race condition by making encryptSecret async
secured.encryptSecret().then(() => {
this.sendKnownIdentityChallenge(secured.connId, secured.identityHash, secured.encryptedSecret as Array<string>);
secured.status = IdChallengerStatus.SentChallenge;
});
}
}
// query for already verified local or remote identities
getLocalVerifiedIdentity(connId: ConnectionId, identityHash: Hash) : Identity | undefined {
return this.getVerifiedIdentity(connId, identityHash, true);
}
getRemoteVerifiedIdentity(connId: ConnectionId, identityHash: Hash) : Identity | undefined {
return this.getVerifiedIdentity(connId, identityHash, false);
}
// messaging, usable once both supplied identities (sender & recipient)
// have been verified on that connection
sendSecurely(connId: ConnectionId, sender: Hash, recipient: Hash, agentId: AgentId, content: any) {
let remote = this.getConnectionSecuredForSending(connId, recipient);
let local = this.getConnectionSecuredForReceiving(connId, sender);
if (remote?.verified() && local?.verified()) {
let secureMessagePayload: SecureMessagePayload = {
senderIdentityHash: sender,
agentId: agentId,
content: content
};
let plaintext = JSON.stringify(secureMessagePayload);
let nonce = new RNGImpl().randomHexString(96);
let payload = new ChaCha20Impl().encryptHex(plaintext, remote.secret as string, nonce);
let hmac = new HMACImpl().hmacSHA256hex(payload, local.secret as string);
if (plaintext.length < MAX_PAYLOAD_SIZE) {
let secureMessage: SecureMessage = {
type: MessageType.SecureMessage,
identityHash: recipient,
nonce: nonce,
payload: payload,
hmac: hmac
};
this.getNetworkAgent().sendMessage(connId, SecureNetworkAgent.Id, secureMessage);
} else {
let chunks = Strings.chunk(payload, MAX_PAYLOAD_SIZE);
let msgId = new RNGImpl().randomHexString(128);
let seq = 0;
if (chunks.length <= MAX_MESSAGE_FRAGMENTS) {
for (const chunk of chunks) {
let secureMessage: SecureMessage = {
type: MessageType.SecureMessage,
identityHash: recipient,
nonce: nonce,
payload: chunk,
hmac: hmac,
id: msgId,
fragSeq: seq,
fragCount: chunks.length
};
this.getNetworkAgent().sendMessage(connId, SecureNetworkAgent.Id, secureMessage);
seq = seq + 1;
}
} else {
SecureNetworkAgent.logger.error('Cannot send message! It needs ' + chunks.length + ' fragments and the max allowed is ' + MAX_MESSAGE_FRAGMENTS + '.');
}
}
} else {
throw new Error('Connection ' + connId + ' still has not verified both sender ' + sender + ' and recipient ' + recipient + '.');
}
}
// incoming message processing
receiveMessage(connId: ConnectionId, source: Endpoint, destination: Endpoint, content: any): void {
source; destination;
let controlMessage = content as ControlMessage;
let identityHash = controlMessage.identityHash;
SecureNetworkAgent.logger.trace(() => 'Received message ' + JSON.stringify(content));
// for id holder:
if (controlMessage.type === MessageType.RequestIdentity) {
let secured = this.getOrCreateConnectionSecuredForReceiving(connId, identityHash);
if (secured.status === IdHolderStatus.ExpectingChallenge) {
this.sendIdentity(connId, secured.identity as Identity, identityHash);
secured.status = IdHolderStatus.SentIdentity;
} else if (secured.status === undefined) {
secured.status = IdHolderStatus.ReceivedUnexpectedIdentityRequest;
this.sendAuthEvent(connId, IdentityLocation.Local, identityHash, IdentityAuthStatus.Requested, secured.identity);
}
} else if (controlMessage.type === MessageType.SendChallenge) {
let sendChallengeMessage = content as SendChallengeMessage;
let secured = this.getOrCreateConnectionSecuredForReceiving(connId, identityHash);
if (secured.status === IdHolderStatus.ExpectingChallenge ||
secured.status === IdHolderStatus.SentIdentity) {
secured.encryptedSecret = sendChallengeMessage.encrypedSecret;
secured.decryptSecret().then(() => {
//TODO: see if we have introduced a race condition by making decryptSecret async.
this.answerReceivedChallenge(connId, identityHash, secured.computeSecretHash());
secured.status = IdHolderStatus.SentChallengeAnswer;
});
} else if (secured.status === undefined) {
secured.encryptedSecret = sendChallengeMessage.encrypedSecret;
secured.status = IdHolderStatus.ReceivedUnexpectedChallenge;
this.sendAuthEvent(connId, IdentityLocation.Local, identityHash, IdentityAuthStatus.Requested, secured.identity);
}
} else if (controlMessage.type === MessageType.ChallengeResult) {
let challengeResultMessage = content as ChallengeResultMessage;
let secured = this.getOrCreateConnectionSecuredForReceiving(connId, identityHash);
if (secured.status === IdHolderStatus.SentChallengeAnswer) {
if (challengeResultMessage.result) {
secured.status = IdHolderStatus.IdentityVerified;
} else {
secured.status = IdHolderStatus.IdentityRejected;
}
const authStatus: IdentityAuthStatus =
challengeResultMessage.result? IdentityAuthStatus.Accepted : IdentityAuthStatus.Rejected;
this.sendAuthEvent(connId, IdentityLocation.Local, secured.identityHash, authStatus, secured.identity);
}
}
// for id challenger:
else if (controlMessage.type === MessageType.SendIdentity) {
let sendIdentityMessage = content as SendIdentityMessage;
let secured = this.getOrCreateConnectionSecuredForSending(connId, identityHash);
if (secured.status === IdChallengerStatus.SentIdentityRequest) {
let identity = HashedObject.fromLiteralContext(sendIdentityMessage.identity);
if (identity.hash() === identityHash && identity instanceof Identity) {
secured.identity = identity;
secured.generateSecret();
//TODO: see if we have introduced a race condition by making encryptSecret async
secured.encryptSecret().then(() => {
this.sendKnownIdentityChallenge(connId, identityHash, secured.encryptedSecret as Array<string>);
secured.status = IdChallengerStatus.SentChallenge;
});
} else {
secured.status = IdChallengerStatus.IdentityRejected;
}
}
} else if (controlMessage.type === MessageType.AnswerChallenge) {
let answerChallengeMessage = content as AnswerChallengeMessage;
let secured = this.getOrCreateConnectionSecuredForSending(connId, identityHash);
if (secured.status === IdChallengerStatus.SentChallenge) {
let accepted = answerChallengeMessage.secretHash === secured.computeSecretHash();
if (accepted) {
this.sendChallengeResult(connId, identityHash, true);
secured.status = IdChallengerStatus.IdentityVerified;
} else {
this.sendChallengeResult(connId, identityHash, false);
secured.status = IdChallengerStatus.IdentityRejected;
}
const authStatus:IdentityAuthStatus = accepted? IdentityAuthStatus.Accepted : IdentityAuthStatus.Rejected;
this.sendAuthEvent(connId, IdentityLocation.Remote, secured.identityHash, authStatus, secured.identity);
}
}
// for both:
else if (controlMessage.type === MessageType.SecureMessage) {
let secureMessage = content as SecureMessage;
let local = this.getConnectionSecuredForReceiving(connId, secureMessage.identityHash);
if (local?.verified()) {
let cyphertext: string|undefined = undefined;
if (secureMessage.id === undefined) {
cyphertext = secureMessage.payload;
} else {
if (secureMessage.fragSeq !== undefined && secureMessage.fragCount !== undefined &&
secureMessage.fragCount <= MAX_MESSAGE_FRAGMENTS && secureMessage.fragSeq % 1 === 0 &&
0 <= secureMessage.fragSeq && secureMessage.fragSeq < secureMessage.fragCount) {
let partialMsg = this.messageFragments.get(secureMessage.id);
if (partialMsg === undefined) {
partialMsg = {
created: Date.now(),
updated: Date.now(),
connId: connId,
recipient: secureMessage.identityHash,
fragCount: secureMessage.fragCount,
fragments: new Map()
};
this.messageFragments.set(secureMessage.id, partialMsg);
this.checkFragmentAssemblyInterval();
} else {
partialMsg.updated = Date.now();
}
if (partialMsg.connId === connId &&
partialMsg.recipient === secureMessage.identityHash &&
partialMsg.fragCount === secureMessage.fragCount &&
secureMessage.fragSeq < secureMessage.fragCount) {
partialMsg.fragments.set(secureMessage.fragSeq, secureMessage.payload);
if (partialMsg.fragments.size === partialMsg.fragCount) {
const chunks = new Array<string>();
for (let i=0; i<partialMsg.fragCount; i++) {
const chunk = partialMsg.fragments.get(i);
if (chunk !== undefined) {
chunks.push(chunk);
}
}
if (chunks.length === partialMsg.fragCount) {
cyphertext = Strings.unchunk(chunks);
this.messageFragments.delete(secureMessage.id);
this.checkFragmentAssemblyInterval();
} else {
SecureNetworkAgent.logger.warning('Error reassembling msg ' + secureMessage.id);
}
}
}
} else {
SecureNetworkAgent.logger.warning('Incomplete message fragment: seq or fragments fields are missing or incorrect for ' + secureMessage.id + ': fragCount=' + secureMessage.fragCount + ', fragSeq=' + secureMessage.fragSeq + ' (sender is ' + source + ')');
}
}
if (cyphertext !== undefined) {
let payload = new ChaCha20Impl().decryptHex(cyphertext, local.secret as string, secureMessage.nonce);
let secureMessagePayload = JSON.parse(payload) as SecureMessagePayload;
let remote = this.getConnectionSecuredForSending(connId, secureMessagePayload.senderIdentityHash);
if (remote?.verified()) {
let hmac = new HMACImpl().hmacSHA256hex(cyphertext, remote.secret as string)
if (secureMessage.hmac === hmac) {
let agent = this.pod?.getAgent(secureMessagePayload.agentId);
if (agent !== undefined) {
let event: SecureMessageReceivedEvent = {
type: SecureNetworkEventType.SecureMessageReceived,
content: {
connId: connId,
sender: secureMessagePayload.senderIdentityHash,
recipient: secureMessage.identityHash,
payload: secureMessagePayload.content
}
};
agent.receiveLocalEvent(event);
}
} else {
SecureNetworkAgent.logger.warning('HMAC mismatch on received message on connection ' + connId);
}
}
}
}
};
}
shutdown() {
}
private sendAuthEvent(connId: ConnectionId, identityLocation: IdentityLocation, identityHash: Hash, status: IdentityAuthStatus, identity?: Identity) {
let ev: ConnectionIdentityAuthEvent = {
type: SecureNetworkEventType.ConnectionIdentityAuth,
content: {
connId: connId,
identityLocation: identityLocation,
identityHash: identityHash,
identity: identity,
status: status
}
};
this.pod?.broadcastEvent(ev);
}
private sendIdentity(connId: ConnectionId, identity: Identity, identityHash?: Hash) {
if (identityHash === undefined) {
identityHash = identity.hash();
}
let content: SendIdentityMessage = {
type: MessageType.SendIdentity,
identityHash: identityHash,
identity: identity.toLiteralContext()
};
SecureNetworkAgent.logger.trace('Sending id ' + identityHash + ' on ' + connId);
this.sendControlMessage(connId, content);
}
private answerReceivedChallenge(connId: ConnectionId, identityHash: Hash, secretHash: Hash) {
let content: AnswerChallengeMessage = {
type: MessageType.AnswerChallenge,
identityHash: identityHash,
secretHash: secretHash
};
this.sendControlMessage(connId, content);
}
private sendIdentityRequest(connId: ConnectionId, identityHash: Hash) {
let content: RequestIdentityMessage = {
type: MessageType.RequestIdentity,
identityHash: identityHash
};
this.sendControlMessage(connId, content);
}
private sendKnownIdentityChallenge(connId: ConnectionId, identityHash: Hash, encryptedSecret: Array<string>) {
let content: SendChallengeMessage = {
type: MessageType.SendChallenge,
identityHash: identityHash,
encrypedSecret: encryptedSecret
};
this.sendControlMessage(connId, content);
}
private sendChallengeResult(connId: ConnectionId, identityHash: Hash, verified: boolean) {
let content: ChallengeResultMessage = {
type: MessageType.ChallengeResult,
identityHash: identityHash,
result: verified
};
this.sendControlMessage(connId, content);
}
private sendControlMessage(connId: ConnectionId, content: ControlMessage) {
this.getNetworkAgent().sendMessage(connId, SecureNetworkAgent.Id, content);
}
private getOrCreateConnectionSecuredForSending(connId: ConnectionId, identityHash: Hash): ConnectionSecuredForSending {
return this.getOneWaySecuredConnection(connId, identityHash, false, true) as ConnectionSecuredForSending;
}
private getOrCreateConnectionSecuredForReceiving(connId: ConnectionId, identityHash: Hash): ConnectionSecuredForReceiving {
return this.getOneWaySecuredConnection(connId, identityHash, true, true) as ConnectionSecuredForReceiving;
}
private getConnectionSecuredForSending(connId: ConnectionId, identityHash: Hash): ConnectionSecuredForSending {
return this.getOneWaySecuredConnection(connId, identityHash, false, false) as ConnectionSecuredForSending;
}
private getConnectionSecuredForReceiving(connId: ConnectionId, identityHash: Hash): ConnectionSecuredForReceiving {
return this.getOneWaySecuredConnection(connId, identityHash, true, false) as ConnectionSecuredForReceiving;
}
private getOneWaySecuredConnection(connId: ConnectionId, identityHash: Hash, sender: boolean, create: boolean) {
let key = OneWaySecuredConnection.encode(connId, identityHash);
let map: Map<string, OneWaySecuredConnection>;
if (sender) {
map = this.localIdentities;
} else {
map = this.remoteIdentities;
}
let secured = map.get(key);
if (create && secured === undefined) {
if (sender) {
secured = new ConnectionSecuredForReceiving(connId, identityHash);
} else {
secured = new ConnectionSecuredForSending(connId, identityHash);
}
secured.setTimeout(DEFAULT_TIMEOUT);
map.set(key, secured);
}
return secured;
}
private getVerifiedIdentity(connId: ConnectionId, identityHash: Hash, local: boolean) : Identity | undefined {
let sid = this.getOneWaySecuredConnection(connId, identityHash, local, false);
let identity: Identity | undefined = undefined;
if (sid !== undefined && sid.verified()) {
identity = sid.identity;
}
return identity;
}
private removeIdentitiesForConnection(id: ConnectionId) {
for(const verifiedIdentities of [this.remoteIdentities, this.localIdentities]) {
const toRemove = new Array<string>();
for (const [k, v] of verifiedIdentities.entries()) {
if (v.connId === id) {
toRemove.push(k);
}
}
for (const k of toRemove) {
SecureNetworkAgent.logger.trace('Removing identity' + verifiedIdentities.get(k)?.identityHash + ' from connection ' + id + ': it is being closed.')
verifiedIdentities.delete(k);
}
}
}
private getNetworkAgent() {
return (this.pod as AgentPod).getAgent(NetworkAgent.AgentId) as NetworkAgent;
}
}
export { SecureNetworkAgent as SecureNetworkAgent, SecureNetworkEventType, SecureMessageReceivedEvent, ConnectionIdentityAuthEvent, IdentityLocation, IdentityAuthStatus } | the_stack |
import Conditions from '../../../../../resources/conditions';
import NetRegexes from '../../../../../resources/netregexes';
import { Responses } from '../../../../../resources/responses';
import ZoneId from '../../../../../resources/zone_id';
import { RaidbossData } from '../../../../../types/data';
import { TriggerSet } from '../../../../../types/trigger';
export interface Data extends RaidbossData {
dynamo?: boolean;
seenIntermission?: boolean;
tethers?: string[];
}
const triggerSet: TriggerSet<Data> = {
zoneId: ZoneId.TheSwallowsCompass,
timelineFile: 'swallows_compass.txt',
triggers: [
{
id: 'Swallows Compass Tengu Clout',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '2B95', source: 'Otengu', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '2B95', source: 'Otengu', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '2B95', source: 'Ô-Tengu', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '2B95', source: 'オオテング', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '2B95', source: '大天狗', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '2B95', source: '대텐구', capture: false }),
response: Responses.aoe(),
},
{
id: 'Swallows Compass Tengu Might',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '2B94', source: 'Otengu' }),
netRegexDe: NetRegexes.startsUsing({ id: '2B94', source: 'Otengu' }),
netRegexFr: NetRegexes.startsUsing({ id: '2B94', source: 'Ô-Tengu' }),
netRegexJa: NetRegexes.startsUsing({ id: '2B94', source: 'オオテング' }),
netRegexCn: NetRegexes.startsUsing({ id: '2B94', source: '大天狗' }),
netRegexKo: NetRegexes.startsUsing({ id: '2B94', source: '대텐구' }),
response: Responses.tankBuster(),
},
{
id: 'Swallows Compass Tengu Wile',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '2B97', source: 'Otengu', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '2B97', source: 'Otengu', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '2B97', source: 'Ô-Tengu', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '2B97', source: 'オオテング', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '2B97', source: '大天狗', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '2B97', source: '대텐구', capture: false }),
response: Responses.lookAway(),
},
{
// 7201 is Tengu Ember.
id: 'Swallows Compass Ember Spawn',
type: 'AddedCombatant',
netRegex: NetRegexes.addedCombatantFull({ npcNameId: '7201', capture: false }),
suppressSeconds: 5,
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Avoid Fire Orbs',
de: 'Weiche den Feuerorbs aus',
fr: 'Évitez les orbes de feu',
ja: '火の玉を避ける',
cn: '躲避小火球',
ko: '불구슬 피하기',
},
},
},
{
id: 'Swallows Compass Flames Of Hate',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '2898', source: 'Tengu Ember', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '2898', source: 'Tengu-Glut', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '2898', source: 'Tengu-Bi', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '2898', source: '天狗火', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '2898', source: '天狗火', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '2898', source: '텐구불', capture: false }),
suppressSeconds: 5,
alertText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Away From Fireballs',
de: 'Weg von den Feuerkugeln',
fr: 'Éloignez-vous des boules de feu',
ja: '(大きい)火の玉を避ける',
cn: '远离大火球',
ko: '불구슬 피하기',
},
},
},
{
id: 'Swallows Compass Right Palm',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '2B9D', source: 'Daidarabotchi', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '2B9D', source: 'Daidarabotchi', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '2B9D', source: 'Daidarabotchi', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '2B9D', source: 'ダイダラボッチ', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '2B9D', source: '大太法师', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '2B9D', source: '다이다라봇치', capture: false }),
response: Responses.goLeft(),
},
{
id: 'Swallows Compass Left Palm',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '2B9E', source: 'Daidarabotchi', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '2B9E', source: 'Daidarabotchi', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '2B9E', source: 'Daidarabotchi', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '2B9E', source: 'ダイダラボッチ', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '2B9E', source: '大太法师', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '2B9E', source: '다이다라봇치', capture: false }),
response: Responses.goRight(),
},
{
id: 'Swallows Compass Mountain Falls',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '0087' }),
condition: Conditions.targetIsYou(),
response: Responses.spread(),
},
{
id: 'Swallows Compass Mirage',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '0001' }),
condition: Conditions.targetIsYou(),
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: '5x Puddles on YOU',
de: '5x Flächen auf DIR',
fr: '5x Zones au sol sur VOUS',
ja: '自分に追尾AoE',
cn: '5连追踪AOE点名',
ko: '5회 장판 대상자',
},
},
},
{
id: 'Swallows Compass Mythmaker',
type: 'Ability',
netRegex: NetRegexes.ability({ id: '2BA3', source: 'Daidarabotchi', capture: false }),
netRegexDe: NetRegexes.ability({ id: '2BA3', source: 'Daidarabotchi', capture: false }),
netRegexFr: NetRegexes.ability({ id: '2BA3', source: 'Daidarabotchi', capture: false }),
netRegexJa: NetRegexes.ability({ id: '2BA3', source: 'ダイダラボッチ', capture: false }),
netRegexCn: NetRegexes.ability({ id: '2BA3', source: '大太法师', capture: false }),
netRegexKo: NetRegexes.ability({ id: '2BA3', source: '다이다라봇치', capture: false }),
response: Responses.aoe(),
},
{
id: 'Swallows Compass Six Fulms Under',
type: 'GainsEffect',
netRegex: NetRegexes.gainsEffect({ effectId: '237' }),
condition: Conditions.targetIsYou(),
suppressSeconds: 2, // If the user stays in, they will get more reminders.
alarmText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'OUT OF THE LAKE',
de: 'RAUS AUS DEM SEE',
fr: 'SORTEZ DU LAC',
ja: '青いエリアを踏まない',
cn: '不要踩进水坑',
ko: '물웅덩이에서 벗어나기',
},
},
},
{
id: 'Swallows Compass Short End',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: ['2BA6', '2D07'], source: ['Qitian Dasheng', 'Shadow Of The Sage'] }),
netRegexDe: NetRegexes.startsUsing({ id: ['2BA6', '2D07'], source: ['Qitian Dasheng', 'Schatten Des Weisen'] }),
netRegexFr: NetRegexes.startsUsing({ id: ['2BA6', '2D07'], source: ['Qitian Dasheng', 'Ombre De Qitian Dasheng'] }),
netRegexJa: NetRegexes.startsUsing({ id: ['2BA6', '2D07'], source: ['セイテンタイセイ', 'セイテンタイセイの影'] }),
netRegexCn: NetRegexes.startsUsing({ id: ['2BA6', '2D07'], source: ['齐天大圣', '齐天大圣的幻影'] }),
netRegexKo: NetRegexes.startsUsing({ id: ['2BA6', '2D07'], source: ['제천대성', '제천대성의 분신'] }),
suppressSeconds: 5,
response: Responses.tankBuster(),
},
{
id: 'Swallows Compass Mount Huaguo',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: ['2BAA', '2D08'], source: ['Qitian Dasheng', 'Shadow Of The Sage'], capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: ['2BAA', '2D08'], source: ['Qitian Dasheng', 'Schatten Des Weisen'], capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: ['2BAA', '2D08'], source: ['Qitian Dasheng', 'Ombre De Qitian Dasheng'], capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: ['2BAA', '2D08'], source: ['セイテンタイセイ', 'セイテンタイセイの影'], capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: ['2BAA', '2D08'], source: ['齐天大圣', '齐天大圣的幻影'], capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: ['2BAA', '2D08'], source: ['제천대성', '제천대성의 분신'], capture: false }),
suppressSeconds: 5,
response: Responses.aoe(),
},
{
// Both Ends has a number of different possibilities for how it's used.
// It can be alone, or it can be accompanied by the other form,
// or it can be alongside Five-Fingered Punishment.
// If there's a blue one on the field, we want to be in, no matter what.
// If there's no blue, we want to be away from red.
// In order to avoid collisions and confusion, we collect first.
id: 'Swallows Compass Both Ends Collect',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: ['2BA9', '2BAF'], source: ['Qitian Dasheng', 'Shadow Of The Sage'], capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: ['2BA9', '2BAF'], source: ['Qitian Dasheng', 'Schatten Des Weisen'], capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: ['2BA9', '2BAF'], source: ['Qitian Dasheng', 'Ombre De Qitian Dasheng'], capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: ['2BA9', '2BAF'], source: ['セイテンタイセイ', 'セイテンタイセイの影'], capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: ['2BA9', '2BAF'], source: ['齐天大圣', '齐天大圣的幻影'], capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: ['2BA9', '2BAF'], source: ['제천대성', '제천대성의 분신'], capture: false }),
run: (data) => data.dynamo = true,
},
{
// 2BA8,2BAE is red, chariot, 2BA9,2BAF is blue, dynamo.
id: 'Swallows Compass Both Ends Call',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: ['2BA8', '2BA9', '2BAE', '2BAF'], source: ['Qitian Dasheng', 'Shadow Of The Sage'], capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: ['2BA8', '2BA9', '2BAE', '2BAF'], source: ['Qitian Dasheng', 'Schatten Des Weisen'], capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: ['2BA8', '2BA9', '2BAE', '2BAF'], source: ['Qitian Dasheng', 'Ombre De Qitian Dasheng'], capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: ['2BA8', '2BA9', '2BAE', '2BAF'], source: ['セイテンタイセイ', 'セイテンタイセイの影'], capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: ['2BA8', '2BA9', '2BAE', '2BAF'], source: ['齐天大圣', '齐天大圣的幻影'], capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: ['2BA8', '2BA9', '2BAE', '2BAF'], source: ['제천대성', '제천대성의 분신'], capture: false }),
delaySeconds: 0.5,
suppressSeconds: 5,
alertText: (data, _matches, output) => {
if (data.dynamo)
return output.dynamo!();
return output.chariot!();
},
run: (data) => delete data.dynamo,
outputStrings: {
dynamo: {
en: 'Close to blue staff',
de: 'Nahe am blauen Stab',
fr: 'Rapprochez-vous du bâton bleu',
ja: '如意棒に近づく',
cn: '靠近蓝色大圣',
ko: '파랑 지팡이 근처로',
},
chariot: {
en: 'Away from red staff',
de: 'Weg vom roten Stab',
fr: 'Éloignez-vous du bâton rouge',
ja: '如意棒から離れる',
cn: '远离红色大圣',
ko: '빨강 지팡이에서 떨어지기',
},
},
},
{
id: 'Swallows Compass Five Fingered Punishment',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '003E' }),
response: Responses.stackMarkerOn('info'), // Info rather than alert to avoid collision with Both Ends.
},
{
// The Long end is a knockback in phase 1, but not in phase 2.
// Using the source name for tethers runs into localizing issues,
// so we just track the phase instead.
// The ability use here is unnamed, the teleport to the center to begin the intermission.
id: 'Swallows Compass Intermission Tracking',
type: 'Ability',
netRegex: NetRegexes.ability({ id: '2CC7', source: 'Qitian Dasheng', capture: false }),
netRegexDe: NetRegexes.ability({ id: '2CC7', source: 'Qitian Dasheng', capture: false }),
netRegexFr: NetRegexes.ability({ id: '2CC7', source: 'Qitian Dasheng', capture: false }),
netRegexJa: NetRegexes.ability({ id: '2CC7', source: 'セイテンタイセイ', capture: false }),
netRegexCn: NetRegexes.ability({ id: '2CC7', source: '齐天大圣', capture: false }),
netRegexKo: NetRegexes.ability({ id: '2CC7', source: '제천대성', capture: false }),
run: (data) => data.seenIntermission = true,
},
{
// Either one or two tethers can be present for Long End.
// We have to handle both possibilities, so we collect targets first for later analysis.
id: 'Swallows Compass Long End Collect',
type: 'Tether',
netRegex: NetRegexes.tether({ id: '0029' }),
run: (data, matches) => {
data.tethers ??= [];
data.tethers.push(matches.target);
},
},
{
id: 'Swallows Compass Long End Call',
type: 'Tether',
netRegex: NetRegexes.tether({ id: '0029', capture: false }),
delaySeconds: 0.5,
alertText: (data, _matches, output) => {
if (data.tethers?.includes(data.me)) {
if (data.seenIntermission)
return output.target!();
return output.knockback!();
}
return output.avoid!();
},
run: (data) => delete data.tethers,
outputStrings: {
target: {
en: 'Laser on YOU',
de: 'Laser auf DIR',
fr: 'Laser sur VOUS',
ja: '自分にレーザー',
cn: '直线激光点名',
ko: '레이저 대상자',
},
knockback: {
en: 'Knockback laser on YOU',
de: 'Rückstoßlaser auf DIR',
fr: 'Poussée laser sur VOUS',
ja: '自分にノックバックレーザー',
cn: '击退激光点名',
ko: '넉백 레이저 대상자',
},
avoid: {
en: 'Avoid tethers',
de: 'Vermeide die Verbindungen',
fr: 'Évitez les liens',
ja: '線から離れる',
cn: '远离连线',
ko: '선 피하기',
},
},
},
],
timelineReplace: [
{
'locale': 'de',
'replaceSync': {
'Daidarabotchi': 'Daidarabotchi',
'Otengu': 'Otengu',
'Qitian Dasheng': 'Qitian Dasheng',
'Serenity': 'Die Stille',
'Shadow Of The Sage': 'Schatten des Weisen',
'Tengu Ember': 'Tengu-Glut',
'The Dragon\'s Mouth': 'Maul des Drachen',
'The Heart Of The Dragon': 'Herz des Drachen',
},
'replaceText': {
'Both Ends': 'Beide Enden',
'Clout Of The Tengu': 'Atem des Tengu',
'Equal Of Heaven': 'Dem Himmel gleich',
'Five-Fingered Punishment': 'Strafende Finger',
'Flames Of Hate': 'Flammen des Hasses',
'Greater Palm': 'Große Handfläche',
'Might Of The Tengu': 'Fäuste des Tengu',
'Mirage': 'Mirage',
'Mount Huaguo': 'Huaguo',
'Mountain Falls': 'Bergrutsch',
'Mythmaker': 'Erdrütteln',
'Second Heaven': 'Dreiunddreißig Himmel',
'Splitting Hairs': 'Haarspalterei',
'The Long End': 'Langes Ende',
'The Short End': 'Kurzes Ende',
'Tributary': 'Großer Fall',
'Wile Of The Tengu': 'Tricks des Tengu',
'Yama-Kagura': 'Yamakagura',
},
},
{
'locale': 'fr',
'replaceSync': {
'Daidarabotchi': 'Daidarabotchi',
'Otengu': 'ô-tengu',
'Qitian Dasheng': 'Qitian Dasheng',
'Serenity': 'Sanctuaire de Jade',
'Shadow Of The Sage': 'ombre de Qitian Dasheng',
'Tengu Ember': 'tengu-bi',
'The Dragon\'s Mouth': 'Porte de Dairyu',
'The Heart Of The Dragon': 'Salle des Alignements',
},
'replaceText': {
'\\?': ' ?',
'Both Ends': 'Coup de bâton tournicotant',
'Clout Of The Tengu': 'Tengu-kaze',
'Equal Of Heaven': 'Égal des Cieux',
'Five-Fingered Punishment': 'Mont Wuxing',
'Flames Of Hate': 'Rancune furieuse',
'Greater Palm': 'Paume colossale',
'Might Of The Tengu': 'Tengu-tsubute',
'Mirage': 'Mirage',
'Mount Huaguo': 'Mont Haguo',
'Mountain Falls': 'Raz-de-montagne',
'Mythmaker': 'Grand bouleversement',
'Second Heaven': 'Trayastrimsha',
'Splitting Hairs': 'Dédoublement',
'The Long End': 'Coup de bâton long',
'The Short End': 'Coup de bâton court',
'Tributary': 'Cascade colossale',
'Wile Of The Tengu': 'Malice de tengu',
'Yama-Kagura': 'Yama-kagura',
},
},
{
'locale': 'ja',
'replaceSync': {
'Daidarabotchi': 'ダイダラボッチ',
'Otengu': 'オオテング',
'Qitian Dasheng': 'セイテンタイセイ',
'Serenity': '玉聖祠',
'Shadow Of The Sage': 'セイテンタイセイの影',
'Tengu Ember': '天狗火',
'The Dragon\'s Mouth': '大龍関門',
'The Heart Of The Dragon': '龍脈之間',
},
'replaceText': {
'Both Ends': '如意大旋風',
'Clout Of The Tengu': '天狗風',
'Equal Of Heaven': '斉天撃',
'Five-Fingered Punishment': '五行山',
'Flames Of Hate': '怨念の炎',
'Greater Palm': '大掌底',
'Might Of The Tengu': '天狗礫',
'Mirage': '蜃気楼',
'Mount Huaguo': '花果山',
'Mountain Falls': '山津波',
'Mythmaker': '驚天動地',
'Second Heaven': '三十三天',
'Splitting Hairs': '地サツ数',
'The Long End': '如意剛力突',
'The Short End': '如意烈風突',
'Tributary': '大瀑布',
'Wile Of The Tengu': '天狗の仕業',
'Yama-Kagura': '山神楽',
},
},
{
'locale': 'cn',
'replaceSync': {
'Daidarabotchi': '大太法师',
'Otengu': '大天狗',
'Qitian Dasheng': '齐天大圣',
'Serenity': '玉圣祠',
'Shadow Of The Sage': '齐天大圣的幻影',
'Tengu Ember': '天狗火',
'The Dragon\'s Mouth': '大龙关门',
'The Heart Of The Dragon': '龙脉之间',
},
'replaceText': {
'Both Ends': '如意大旋风',
'Clout Of The Tengu': '天狗风',
'Equal Of Heaven': '齐天击',
'Five-Fingered Punishment': '五行山',
'Flames Of Hate': '怨念之火',
'Greater Palm': '掌击',
'Might Of The Tengu': '天狗碾',
'Mirage': 'Mirage',
'Mount Huaguo': '花果山',
'Mountain Falls': '泥石流',
'Mythmaker': '惊天动地',
'Second Heaven': '三十三天',
'Splitting Hairs': '地煞数',
'The Long End': '如意刚力突',
'The Short End': '如意烈风突',
'Tributary': '大瀑布',
'Wile Of The Tengu': '天狗妙计',
'Yama-Kagura': '山神乐',
},
},
{
'locale': 'ko',
'replaceSync': {
'Daidarabotchi': '다이다라봇치',
'Otengu': '대텐구',
'Qitian Dasheng': '제천대성',
'Serenity': '옥성 사당',
'Shadow Of The Sage': '제천대성의 분신',
'Tengu Ember': '텐구불',
'The Dragon\'s Mouth': '대룡 관문',
'The Heart Of The Dragon': '용맥의 방',
},
'replaceText': {
'Both Ends': '여의 대선풍',
'Clout Of The Tengu': '회오리바람',
'Equal Of Heaven': '제천격',
'Five-Fingered Punishment': '오행산',
'Flames Of Hate': '원념의 불꽃',
'Greater Palm': '큰 손바닥',
'Might Of The Tengu': '돌팔매',
'Mirage': 'Mirage',
'Mount Huaguo': '화과산',
'Mountain Falls': '산해일',
'Mythmaker': '경천동지',
'Second Heaven': '삼십삼천',
'Splitting Hairs': '분신술',
'The Long End': '여의 강력 찌르기',
'The Short End': '여의 열풍 찌르기',
'Tributary': '대폭포',
'Wile Of The Tengu': '텐구의 소행',
'Yama-Kagura': '산타령',
},
},
],
};
export default triggerSet; | the_stack |
import { Monsters } from 'oldschooljs';
import itemID from '../util/itemID';
export interface SlayerTaskUnlocks {
id: SlayerTaskUnlocksEnum;
name: string;
desc?: string;
slayerPointCost: number;
item?: number;
haveOne?: boolean;
canBeRemoved?: boolean;
aliases?: string[];
extendID?: number[];
extendMult?: number;
}
export enum SlayerTaskUnlocksEnum {
Dummy = 0,
// Not in use, but in theory gives 10% boost
GargoyleSmasher,
// Slayer helm unlock
MalevolentMasquerade,
// Create slayer rings
RingBling,
// Unlock Red Dragons (not in use)
SeeingRed,
// Unlock mith Dragons (not in use)
IHopeYouMithMe,
// Unlock aviansies (not in use)
WatchTheBirdie,
// TzHaar unlock (not in use)
HotStuff,
// Lizardman unlock (not in use)
ReptileGotRipped,
// Unlock boss tasks. Definitely will use this one for the preroll.
LikeABoss,
// Unlock superiors
BiggerAndBadder,
KingBlackBonnet,
KalphiteKhat,
UnholyHelmet,
DarkMantle,
UndeadHead,
UseMoreHead,
TwistedVision,
StopTheWyvern,
Basilocked,
ActualVampyreSlayer,
// Extension Unlocks
NeedMoreDarkness,
AnkouVeryMuch,
SuqANotherOne,
FireAndDarkness,
PedalToTheMetals,
IReallyMithYou,
AdamindSomeMore,
RUUUUUNE,
SpiritualFervour,
BirdsOfAFeather,
GreaterChallenge,
ItsDarkInHere,
BleedMeDry,
SmellYaLater,
Horrorific,
ToDustYouShallReturn,
WyverNotherOne,
GetSmashed,
NechsPlease,
AugmentMyAbbies,
KrackOn,
GetScabarightOnIt,
WyverNotherTwo,
Basilonger,
MoreAtStake,
// Item Purchases:
SlayerRing,
HerbSack,
RunePouch,
DoubleTrouble,
BroaderFletching
}
export const SlayerRewardsShop: SlayerTaskUnlocks[] = [
{
id: SlayerTaskUnlocksEnum.MalevolentMasquerade,
name: 'Malevolent Masquerade',
desc: 'Unlocks ability to create Slayer helmets.',
slayerPointCost: 400,
canBeRemoved: false,
aliases: ['slayer helm', 'slayer helmet']
},
{
id: SlayerTaskUnlocksEnum.RingBling,
name: 'Ring Bling',
desc: 'Unlocks ability to create Slayer rings.',
slayerPointCost: 300,
canBeRemoved: false,
aliases: ['slayer ring', 'slayer rings']
},
{
id: SlayerTaskUnlocksEnum.SeeingRed,
name: 'Seeing Red',
desc: 'Allows slayer masters to assign Red dragons.',
slayerPointCost: 50,
canBeRemoved: true,
aliases: ['red dragon', 'red dragons']
},
{
id: SlayerTaskUnlocksEnum.IHopeYouMithMe,
name: 'I hope you mith me!',
desc: 'Unlocks the ability to receive Mithril dragons as a task.',
slayerPointCost: 80,
canBeRemoved: true,
aliases: ['mithril dragons', 'mithril dragon']
},
{
id: SlayerTaskUnlocksEnum.WatchTheBirdie,
name: 'Watch the birdie',
desc: 'Unlocks the ability to receive Aviansies as a task.',
slayerPointCost: 80,
canBeRemoved: true,
aliases: ['aviansie', 'aviansies']
},
{
id: SlayerTaskUnlocksEnum.HotStuff,
name: 'Hot Stuff',
desc: 'Unlocks the ability to receive TzHaar as a task.',
slayerPointCost: 100,
canBeRemoved: true,
aliases: ['tzhaar', 'unlock tzhaar', 'jad', 'jad tasks', 'jad task']
},
{
id: SlayerTaskUnlocksEnum.ReptileGotRipped,
name: 'Reptile got Ripped',
desc: 'Unlocks the ability to receive Lizardmen as a task.',
slayerPointCost: 75,
canBeRemoved: true,
aliases: ['lizardmen', 'lizardman', 'unlock lizardmen', 'unlock lizardman', 'shamans', 'unlock shamans']
},
{
id: SlayerTaskUnlocksEnum.LikeABoss,
name: 'Like a Boss',
desc: 'Unlocks boss tasks from high level slayer masters.',
slayerPointCost: 200,
canBeRemoved: true,
aliases: ['boss tasks', 'unlock boss tasks']
},
{
id: SlayerTaskUnlocksEnum.BiggerAndBadder,
name: 'Bigger and Badder',
desc: 'Unlocks superiors.',
slayerPointCost: 150,
canBeRemoved: true,
aliases: ['superiors', 'superior']
},
{
id: SlayerTaskUnlocksEnum.KingBlackBonnet,
name: 'King Black Bonnet',
desc: 'Unlocks ability to create the Black slayer helmet.',
slayerPointCost: 1000,
canBeRemoved: false,
aliases: ['kbd slayer helmet', 'black slayer helmet']
},
{
id: SlayerTaskUnlocksEnum.KalphiteKhat,
name: 'Kalphite Khat',
desc: 'Unlocks ability to create the Green slayer helmet.',
slayerPointCost: 1000,
canBeRemoved: false,
aliases: ['green slayer helmet', 'kq slayer helmet']
},
{
id: SlayerTaskUnlocksEnum.UnholyHelmet,
name: 'Unholy Helmet',
desc: 'Unlocks ability to create the Red slayer helmet.',
slayerPointCost: 1000,
canBeRemoved: false,
aliases: ['red slayer helmet', 'abyssal slayer helmet']
},
{
id: SlayerTaskUnlocksEnum.DarkMantle,
name: 'Dark Mantle',
desc: 'Unlocks ability to create the Purple slayer helmet.',
slayerPointCost: 1000,
canBeRemoved: false,
aliases: ['purple slayer helmet', 'skotizo slayer helmet']
},
{
id: SlayerTaskUnlocksEnum.UndeadHead,
name: 'Undead Head',
desc: 'Unlocks ability to create the Turquoise slayer helmet.',
slayerPointCost: 1000,
canBeRemoved: false,
aliases: ['vorkath slayer helmet', 'turquoise slayer helmet', 'blue slayer helmet']
},
{
id: SlayerTaskUnlocksEnum.UseMoreHead,
name: 'Use More Head',
desc: 'Unlocks ability to create the Hydra slayer helmet.',
slayerPointCost: 1000,
canBeRemoved: false,
aliases: ['hydra slayer helmet', 'alchemical slayer helmet']
},
{
id: SlayerTaskUnlocksEnum.TwistedVision,
name: 'Twisted Vision',
desc: 'Unlocks ability to create the Twisted slayer helmet.',
slayerPointCost: 1000,
canBeRemoved: false,
aliases: ['twisted slayer helmet', 'horny slayer helmet']
},
{
id: SlayerTaskUnlocksEnum.StopTheWyvern,
name: 'Stop The Wyvern',
desc: 'Prevents slayer masters from assigning Fossil island wyverns.',
slayerPointCost: 500,
canBeRemoved: true,
aliases: ['block fossil island wyverns', 'fossil island wyverns']
},
{
id: SlayerTaskUnlocksEnum.Basilocked,
name: 'Basilocked',
desc: 'Unlocks the ability for Konar, Duradel and Nieve to assign Basilisks',
slayerPointCost: 80,
canBeRemoved: true,
aliases: ['basilisks', 'basilisk']
},
{
id: SlayerTaskUnlocksEnum.ActualVampyreSlayer,
name: 'Actual Vampyre Slayer',
desc: 'Unlocks the ability for Konar, Duradel, Nieve and Chaeldar to assign Vampyres',
slayerPointCost: 80,
canBeRemoved: true,
aliases: ['vampyre slayer', 'vampire slayer', 'actual vampire slayer', 'vampyres', 'vampires']
},
{
id: SlayerTaskUnlocksEnum.SlayerRing,
name: 'Slayer ring',
desc: 'Purchase 1 Slayer ring (8)',
slayerPointCost: 75,
item: itemID('Slayer ring (8)'),
haveOne: false,
aliases: ['slayer ring 8', 'slayer ring (8)']
},
{
id: SlayerTaskUnlocksEnum.HerbSack,
name: 'Herb sack',
desc: 'Purchase 1 Herb sack',
slayerPointCost: 750,
item: itemID('Herb sack'),
haveOne: true,
aliases: ['herbs sack', 'herb bag']
},
{
id: SlayerTaskUnlocksEnum.RunePouch,
name: 'Rune pouch',
desc: 'Purchase 1 Rune pouch',
slayerPointCost: 750,
item: itemID('Rune pouch'),
haveOne: true,
aliases: ['rune sack', 'runes pouch']
},
{
id: SlayerTaskUnlocksEnum.NeedMoreDarkness,
name: 'Need more darkness',
desc: 'Extends Dark beast tasks.',
slayerPointCost: 100,
extendID: [Monsters.DarkBeast.id],
extendMult: 9,
canBeRemoved: true,
aliases: ['extend dark beasts']
},
{
id: SlayerTaskUnlocksEnum.AnkouVeryMuch,
name: 'Ankou very much',
desc: 'Extends Ankou tasks.',
slayerPointCost: 100,
extendID: [Monsters.Ankou.id],
extendMult: 2,
canBeRemoved: true,
aliases: ['extend ankous', 'extend ankou']
},
{
id: SlayerTaskUnlocksEnum.SuqANotherOne,
name: 'Suq-a-nother one',
desc: 'Extends Suqah tasks.',
slayerPointCost: 100,
extendID: [Monsters.Suqah.id],
extendMult: 3,
canBeRemoved: true,
aliases: ['suqanother one', 'suq a nother one', 'extend suqahs']
},
{
id: SlayerTaskUnlocksEnum.FireAndDarkness,
name: 'Fire & Darkness',
desc: 'Extend Black dragon tasks.',
slayerPointCost: 50,
extendID: [Monsters.BlackDragon.id],
extendMult: 3,
canBeRemoved: true,
aliases: ['fire and darkness', 'extend black dragons', 'extend black drags']
},
{
id: SlayerTaskUnlocksEnum.PedalToTheMetals,
name: 'Pedal to the metals',
desc: 'Extends Bronze, Iron, and Steel dragon tasks.',
slayerPointCost: 100,
extendID: [Monsters.BronzeDragon.id, Monsters.IronDragon.id, Monsters.SteelDragon.id],
extendMult: 3,
canBeRemoved: true,
aliases: ['extend metal dragons', 'extend steel dragons', 'extend bronze dragons', 'extend iron dragons']
},
{
id: SlayerTaskUnlocksEnum.IReallyMithYou,
name: 'I really mith you',
desc: 'Extends Mithril dragon tasks.',
slayerPointCost: 120,
extendID: [Monsters.MithrilDragon.id],
extendMult: 4,
canBeRemoved: true,
aliases: ['extend mith dragons', 'extend mithril dragons', 'extend mith drags']
},
{
id: SlayerTaskUnlocksEnum.AdamindSomeMore,
name: 'Adamind some more',
desc: 'Extends Adamant dragon tasks.',
slayerPointCost: 100,
extendID: [Monsters.AdamantDragon.id],
extendMult: 5,
canBeRemoved: true,
aliases: ['extend addy dragons', 'extend adamant dragons']
},
{
id: SlayerTaskUnlocksEnum.RUUUUUNE,
name: 'RUUUUUNE',
desc: 'Extends Rune dragon tasks.',
slayerPointCost: 100,
extendID: [Monsters.RuneDragon.id],
extendMult: 9,
canBeRemoved: true,
aliases: ['rune', 'extend rune dragons', 'extend rune dragon']
},
{
id: SlayerTaskUnlocksEnum.SpiritualFervour,
name: 'Spiritual fervour',
desc: 'Extends Spiritual creature tasks.',
slayerPointCost: 100,
extendID: [Monsters.SpiritualRanger.id],
extendMult: 1.4,
canBeRemoved: true,
aliases: ['extend spiritual creatures', 'extend spirituals']
},
{
id: SlayerTaskUnlocksEnum.BirdsOfAFeather,
name: 'Birds of a feather',
desc: 'Extends Aviansie tasks.',
slayerPointCost: 100,
extendID: [Monsters.Aviansie.id],
extendMult: 1.33,
canBeRemoved: true,
aliases: ['extend aviansies', 'extend birds']
},
{
id: SlayerTaskUnlocksEnum.GreaterChallenge,
name: 'Greater challenge',
desc: 'Extends Greater demons tasks.',
slayerPointCost: 100,
extendID: [Monsters.GreaterDemon.id],
extendMult: 1.4,
canBeRemoved: true,
aliases: ['extend greaters', 'extend greater demons']
},
{
id: SlayerTaskUnlocksEnum.ItsDarkInHere,
name: 'Its Dark In Here',
desc: 'Extends Black demon beast tasks.',
slayerPointCost: 100,
extendID: [Monsters.BlackDemon.id],
extendMult: 1.4,
canBeRemoved: true,
aliases: ['extend black demons']
},
{
id: SlayerTaskUnlocksEnum.BleedMeDry,
name: 'Bleed me dry',
desc: 'Extends Bloodveld tasks.',
slayerPointCost: 75,
extendID: [Monsters.Bloodveld.id],
extendMult: 1.4,
canBeRemoved: true,
aliases: ['extend bloodvelds']
},
{
id: SlayerTaskUnlocksEnum.SmellYaLater,
name: 'Smell ya later',
desc: 'Extends Aberrant spectre tasks',
slayerPointCost: 100,
extendID: [Monsters.AberrantSpectre.id],
extendMult: 1.4,
canBeRemoved: true,
aliases: ['extend aberrant spectres', 'extend abby specs']
},
{
id: SlayerTaskUnlocksEnum.Horrorific,
name: 'Horrorific',
desc: 'Extends Cave horrors task',
slayerPointCost: 100,
extendID: [Monsters.CaveHorror.id],
extendMult: 1.5,
canBeRemoved: true,
aliases: ['extend cave horrors']
},
{
id: SlayerTaskUnlocksEnum.ToDustYouShallReturn,
name: 'To dust you shall return',
desc: 'Extends Dust devils task',
slayerPointCost: 100,
extendID: [Monsters.DustDevil.id],
extendMult: 1.7,
canBeRemoved: true,
aliases: ['extend dusties', 'extend dust devils']
},
{
id: SlayerTaskUnlocksEnum.WyverNotherOne,
name: 'Wyver-nother one',
desc: 'Extends Skeletal wyvern tasks.',
slayerPointCost: 100,
extendID: [Monsters.SkeletalWyvern.id],
extendMult: 2,
canBeRemoved: true,
aliases: ['extend wyverns', 'extend skeletal wyverns']
},
{
id: SlayerTaskUnlocksEnum.GetSmashed,
name: 'Get smashed',
desc: 'Extends Gargoyle tasks.',
slayerPointCost: 100,
extendID: [Monsters.Gargoyle.id],
extendMult: 1.5,
canBeRemoved: true,
aliases: ['extend gargs', 'extend gargoyles']
},
{
id: SlayerTaskUnlocksEnum.NechsPlease,
name: 'Nechs please',
desc: 'Extends Nechryael tasks',
slayerPointCost: 100,
extendID: [Monsters.Nechryael.id],
extendMult: 1.5,
canBeRemoved: true,
aliases: ['extend nechs', 'extend nechryaels']
},
{
id: SlayerTaskUnlocksEnum.AugmentMyAbbies,
name: 'Augment my Abbies',
desc: 'Extends Abyssal demon tasks.',
slayerPointCost: 100,
extendID: [Monsters.AbyssalDemon.id],
extendMult: 1.5,
canBeRemoved: true,
aliases: ['augment my abbys', 'extend abby demons', 'extend abyssal demons']
},
{
id: SlayerTaskUnlocksEnum.KrackOn,
name: 'Krack On',
desc: 'Extends Cave Kraken tasks.',
slayerPointCost: 100,
extendID: [Monsters.CaveKraken.id],
extendMult: 1.67,
canBeRemoved: true,
aliases: ['extend cave kraken', 'extend kraken']
},
{
id: SlayerTaskUnlocksEnum.GetScabarightOnIt,
name: 'Get Scabaright on it',
desc: 'Extends Scabarite tasks',
slayerPointCost: 50,
extendID: [Monsters.ScarabMage.id],
extendMult: 3,
canBeRemoved: true,
aliases: ['extend scabarites', 'extend scarabs', 'extend scarabites']
},
{
id: SlayerTaskUnlocksEnum.WyverNotherTwo,
name: 'Wyver-nother two',
desc: 'Extends Fossil island wyvrns.',
slayerPointCost: 100,
extendID: [Monsters.FossilIslandWyvernSpitting.id],
extendMult: 1.5,
canBeRemoved: true,
aliases: ['extend fossil island wyverns', 'extend fossil wyverns']
},
{
id: SlayerTaskUnlocksEnum.Basilonger,
name: 'Basilonger',
desc: 'Extends Basilisk tasks.',
slayerPointCost: 100,
extendID: [Monsters.Basilisk.id],
extendMult: 1.4,
canBeRemoved: true,
aliases: ['extend basilisks', 'extend basilisk']
},
{
id: SlayerTaskUnlocksEnum.MoreAtStake,
name: 'More at stake',
desc: 'Extends Vampyre tasks',
slayerPointCost: 100,
extendID: [Monsters.FeralVampyre.id],
extendMult: 1.5,
canBeRemoved: true,
aliases: ['extend vampyres', 'extend vampires']
},
{
id: SlayerTaskUnlocksEnum.DoubleTrouble,
name: 'Double Trouble',
desc: 'Each Grotesque Guardians kc gives 2 kc to your slayer task',
slayerPointCost: 500,
canBeRemoved: true,
aliases: ['double trouble', 'double garg kc', 'double grotesque kc', '2x groteque kc', '2x ggs kc']
},
{
id: SlayerTaskUnlocksEnum.BroaderFletching,
name: 'Broader fletching',
desc: 'Unlocks ability to fletch broad ammunition',
slayerPointCost: 300,
canBeRemoved: false,
aliases: ['broad bolts', 'broads', 'broad arrows', 'fletching', 'broad fletching']
}
]; | the_stack |
import { assert } from '@firebase/util';
import { ReferenceConstructor } from '../api/Reference';
import { AckUserWrite } from './operation/AckUserWrite';
import { ListenComplete } from './operation/ListenComplete';
import { Merge } from './operation/Merge';
import {
newOperationSourceServer,
newOperationSourceServerTaggedQuery,
newOperationSourceUser,
Operation
} from './operation/Operation';
import { Overwrite } from './operation/Overwrite';
import { ChildrenNode } from './snap/ChildrenNode';
import { Node } from './snap/Node';
import {
SyncPoint,
syncPointAddEventRegistration,
syncPointApplyOperation,
syncPointGetCompleteServerCache,
syncPointGetCompleteView,
syncPointGetQueryViews,
syncPointGetView,
syncPointHasCompleteView,
syncPointIsEmpty,
syncPointRemoveEventRegistration,
syncPointViewExistsForQuery,
syncPointViewForQuery
} from './SyncPoint';
import { ImmutableTree } from './util/ImmutableTree';
import {
newEmptyPath,
newRelativePath,
Path,
pathGetFront,
pathIsEmpty
} from './util/Path';
import { each, errorForServerCode } from './util/util';
import { CacheNode } from './view/CacheNode';
import { Event } from './view/Event';
import { EventRegistration, QueryContext } from './view/EventRegistration';
import { View, viewGetCompleteNode, viewGetServerCache } from './view/View';
import {
newWriteTree,
WriteTree,
writeTreeAddMerge,
writeTreeAddOverwrite,
writeTreeCalcCompleteEventCache,
writeTreeChildWrites,
writeTreeGetWrite,
WriteTreeRef,
writeTreeRefChild,
writeTreeRemoveWrite
} from './WriteTree';
let referenceConstructor: ReferenceConstructor;
export function syncTreeSetReferenceConstructor(
val: ReferenceConstructor
): void {
assert(
!referenceConstructor,
'__referenceConstructor has already been defined'
);
referenceConstructor = val;
}
function syncTreeGetReferenceConstructor(): ReferenceConstructor {
assert(referenceConstructor, 'Reference.ts has not been loaded');
return referenceConstructor;
}
export interface ListenProvider {
startListening(
query: QueryContext,
tag: number | null,
hashFn: () => string,
onComplete: (a: string, b?: unknown) => Event[]
): Event[];
stopListening(a: QueryContext, b: number | null): void;
}
/**
* Static tracker for next query tag.
*/
let syncTreeNextQueryTag_ = 1;
/**
* SyncTree is the central class for managing event callback registration, data caching, views
* (query processing), and event generation. There are typically two SyncTree instances for
* each Repo, one for the normal Firebase data, and one for the .info data.
*
* It has a number of responsibilities, including:
* - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).
* - Applying and caching data changes for user set(), transaction(), and update() calls
* (applyUserOverwrite(), applyUserMerge()).
* - Applying and caching data changes for server data changes (applyServerOverwrite(),
* applyServerMerge()).
* - Generating user-facing events for server and user changes (all of the apply* methods
* return the set of events that need to be raised as a result).
* - Maintaining the appropriate set of server listens to ensure we are always subscribed
* to the correct set of paths and queries to satisfy the current set of user event
* callbacks (listens are started/stopped using the provided listenProvider).
*
* NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual
* events are returned to the caller rather than raised synchronously.
*
*/
export class SyncTree {
/**
* Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.
*/
syncPointTree_: ImmutableTree<SyncPoint> = new ImmutableTree<SyncPoint>(null);
/**
* A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).
*/
pendingWriteTree_: WriteTree = newWriteTree();
readonly tagToQueryMap: Map<number, string> = new Map();
readonly queryToTagMap: Map<string, number> = new Map();
/**
* @param listenProvider_ - Used by SyncTree to start / stop listening
* to server data.
*/
constructor(public listenProvider_: ListenProvider) {}
}
/**
* Apply the data changes for a user-generated set() or transaction() call.
*
* @returns Events to raise.
*/
export function syncTreeApplyUserOverwrite(
syncTree: SyncTree,
path: Path,
newData: Node,
writeId: number,
visible?: boolean
): Event[] {
// Record pending write.
writeTreeAddOverwrite(
syncTree.pendingWriteTree_,
path,
newData,
writeId,
visible
);
if (!visible) {
return [];
} else {
return syncTreeApplyOperationToSyncPoints_(
syncTree,
new Overwrite(newOperationSourceUser(), path, newData)
);
}
}
/**
* Apply the data from a user-generated update() call
*
* @returns Events to raise.
*/
export function syncTreeApplyUserMerge(
syncTree: SyncTree,
path: Path,
changedChildren: { [k: string]: Node },
writeId: number
): Event[] {
// Record pending merge.
writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);
const changeTree = ImmutableTree.fromObject(changedChildren);
return syncTreeApplyOperationToSyncPoints_(
syncTree,
new Merge(newOperationSourceUser(), path, changeTree)
);
}
/**
* Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().
*
* @param revert - True if the given write failed and needs to be reverted
* @returns Events to raise.
*/
export function syncTreeAckUserWrite(
syncTree: SyncTree,
writeId: number,
revert: boolean = false
) {
const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);
const needToReevaluate = writeTreeRemoveWrite(
syncTree.pendingWriteTree_,
writeId
);
if (!needToReevaluate) {
return [];
} else {
let affectedTree = new ImmutableTree<boolean>(null);
if (write.snap != null) {
// overwrite
affectedTree = affectedTree.set(newEmptyPath(), true);
} else {
each(write.children, (pathString: string) => {
affectedTree = affectedTree.set(new Path(pathString), true);
});
}
return syncTreeApplyOperationToSyncPoints_(
syncTree,
new AckUserWrite(write.path, affectedTree, revert)
);
}
}
/**
* Apply new server data for the specified path..
*
* @returns Events to raise.
*/
export function syncTreeApplyServerOverwrite(
syncTree: SyncTree,
path: Path,
newData: Node
): Event[] {
return syncTreeApplyOperationToSyncPoints_(
syncTree,
new Overwrite(newOperationSourceServer(), path, newData)
);
}
/**
* Apply new server data to be merged in at the specified path.
*
* @returns Events to raise.
*/
export function syncTreeApplyServerMerge(
syncTree: SyncTree,
path: Path,
changedChildren: { [k: string]: Node }
): Event[] {
const changeTree = ImmutableTree.fromObject(changedChildren);
return syncTreeApplyOperationToSyncPoints_(
syncTree,
new Merge(newOperationSourceServer(), path, changeTree)
);
}
/**
* Apply a listen complete for a query
*
* @returns Events to raise.
*/
export function syncTreeApplyListenComplete(
syncTree: SyncTree,
path: Path
): Event[] {
return syncTreeApplyOperationToSyncPoints_(
syncTree,
new ListenComplete(newOperationSourceServer(), path)
);
}
/**
* Apply a listen complete for a tagged query
*
* @returns Events to raise.
*/
export function syncTreeApplyTaggedListenComplete(
syncTree: SyncTree,
path: Path,
tag: number
): Event[] {
const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
if (queryKey) {
const r = syncTreeParseQueryKey_(queryKey);
const queryPath = r.path,
queryId = r.queryId;
const relativePath = newRelativePath(queryPath, path);
const op = new ListenComplete(
newOperationSourceServerTaggedQuery(queryId),
relativePath
);
return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
} else {
// We've already removed the query. No big deal, ignore the update
return [];
}
}
/**
* Remove event callback(s).
*
* If query is the default query, we'll check all queries for the specified eventRegistration.
* If eventRegistration is null, we'll remove all callbacks for the specified query/queries.
*
* @param eventRegistration - If null, all callbacks are removed.
* @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
* @returns Cancel events, if cancelError was provided.
*/
export function syncTreeRemoveEventRegistration(
syncTree: SyncTree,
query: QueryContext,
eventRegistration: EventRegistration | null,
cancelError?: Error
): Event[] {
// Find the syncPoint first. Then deal with whether or not it has matching listeners
const path = query._path;
const maybeSyncPoint = syncTree.syncPointTree_.get(path);
let cancelEvents: Event[] = [];
// A removal on a default query affects all queries at that location. A removal on an indexed query, even one without
// other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and
// not loadsAllData().
if (
maybeSyncPoint &&
(query._queryIdentifier === 'default' ||
syncPointViewExistsForQuery(maybeSyncPoint, query))
) {
const removedAndEvents = syncPointRemoveEventRegistration(
maybeSyncPoint,
query,
eventRegistration,
cancelError
);
if (syncPointIsEmpty(maybeSyncPoint)) {
syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);
}
const removed = removedAndEvents.removed;
cancelEvents = removedAndEvents.events;
// We may have just removed one of many listeners and can short-circuit this whole process
// We may also not have removed a default listener, in which case all of the descendant listeners should already be
// properly set up.
//
// Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of
// queryId === 'default'
const removingDefault =
-1 !==
removed.findIndex(query => {
return query._queryParams.loadsAllData();
});
const covered = syncTree.syncPointTree_.findOnPath(
path,
(relativePath, parentSyncPoint) =>
syncPointHasCompleteView(parentSyncPoint)
);
if (removingDefault && !covered) {
const subtree = syncTree.syncPointTree_.subtree(path);
// There are potentially child listeners. Determine what if any listens we need to send before executing the
// removal
if (!subtree.isEmpty()) {
// We need to fold over our subtree and collect the listeners to send
const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);
// Ok, we've collected all the listens we need. Set them up.
for (let i = 0; i < newViews.length; ++i) {
const view = newViews[i],
newQuery = view.query;
const listener = syncTreeCreateListenerForView_(syncTree, view);
syncTree.listenProvider_.startListening(
syncTreeQueryForListening_(newQuery),
syncTreeTagForQuery_(syncTree, newQuery),
listener.hashFn,
listener.onComplete
);
}
} else {
// There's nothing below us, so nothing we need to start listening on
}
}
// If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query
// The above block has us covered in terms of making sure we're set up on listens lower in the tree.
// Also, note that if we have a cancelError, it's already been removed at the provider level.
if (!covered && removed.length > 0 && !cancelError) {
// If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one
// default. Otherwise, we need to iterate through and cancel each individual query
if (removingDefault) {
// We don't tag default listeners
const defaultTag: number | null = null;
syncTree.listenProvider_.stopListening(
syncTreeQueryForListening_(query),
defaultTag
);
} else {
removed.forEach((queryToRemove: QueryContext) => {
const tagToRemove = syncTree.queryToTagMap.get(
syncTreeMakeQueryKey_(queryToRemove)
);
syncTree.listenProvider_.stopListening(
syncTreeQueryForListening_(queryToRemove),
tagToRemove
);
});
}
}
// Now, clear all of the tags we're tracking for the removed listens
syncTreeRemoveTags_(syncTree, removed);
} else {
// No-op, this listener must've been already removed
}
return cancelEvents;
}
/**
* Apply new server data for the specified tagged query.
*
* @returns Events to raise.
*/
export function syncTreeApplyTaggedQueryOverwrite(
syncTree: SyncTree,
path: Path,
snap: Node,
tag: number
): Event[] {
const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
if (queryKey != null) {
const r = syncTreeParseQueryKey_(queryKey);
const queryPath = r.path,
queryId = r.queryId;
const relativePath = newRelativePath(queryPath, path);
const op = new Overwrite(
newOperationSourceServerTaggedQuery(queryId),
relativePath,
snap
);
return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
} else {
// Query must have been removed already
return [];
}
}
/**
* Apply server data to be merged in for the specified tagged query.
*
* @returns Events to raise.
*/
export function syncTreeApplyTaggedQueryMerge(
syncTree: SyncTree,
path: Path,
changedChildren: { [k: string]: Node },
tag: number
): Event[] {
const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
if (queryKey) {
const r = syncTreeParseQueryKey_(queryKey);
const queryPath = r.path,
queryId = r.queryId;
const relativePath = newRelativePath(queryPath, path);
const changeTree = ImmutableTree.fromObject(changedChildren);
const op = new Merge(
newOperationSourceServerTaggedQuery(queryId),
relativePath,
changeTree
);
return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
} else {
// We've already removed the query. No big deal, ignore the update
return [];
}
}
/**
* Add an event callback for the specified query.
*
* @returns Events to raise.
*/
export function syncTreeAddEventRegistration(
syncTree: SyncTree,
query: QueryContext,
eventRegistration: EventRegistration
): Event[] {
const path = query._path;
let serverCache: Node | null = null;
let foundAncestorDefaultView = false;
// Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
// Consider optimizing this once there's a better understanding of what actual behavior will be.
syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {
const relativePath = newRelativePath(pathToSyncPoint, path);
serverCache =
serverCache || syncPointGetCompleteServerCache(sp, relativePath);
foundAncestorDefaultView =
foundAncestorDefaultView || syncPointHasCompleteView(sp);
});
let syncPoint = syncTree.syncPointTree_.get(path);
if (!syncPoint) {
syncPoint = new SyncPoint();
syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
} else {
foundAncestorDefaultView =
foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);
serverCache =
serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
}
let serverCacheComplete;
if (serverCache != null) {
serverCacheComplete = true;
} else {
serverCacheComplete = false;
serverCache = ChildrenNode.EMPTY_NODE;
const subtree = syncTree.syncPointTree_.subtree(path);
subtree.foreachChild((childName, childSyncPoint) => {
const completeCache = syncPointGetCompleteServerCache(
childSyncPoint,
newEmptyPath()
);
if (completeCache) {
serverCache = serverCache.updateImmediateChild(
childName,
completeCache
);
}
});
}
const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);
if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {
// We need to track a tag for this query
const queryKey = syncTreeMakeQueryKey_(query);
assert(
!syncTree.queryToTagMap.has(queryKey),
'View does not exist, but we have a tag'
);
const tag = syncTreeGetNextQueryTag_();
syncTree.queryToTagMap.set(queryKey, tag);
syncTree.tagToQueryMap.set(tag, queryKey);
}
const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);
let events = syncPointAddEventRegistration(
syncPoint,
query,
eventRegistration,
writesCache,
serverCache,
serverCacheComplete
);
if (!viewAlreadyExists && !foundAncestorDefaultView) {
const view = syncPointViewForQuery(syncPoint, query);
events = events.concat(syncTreeSetupListener_(syncTree, query, view));
}
return events;
}
/**
* Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a
* listener above it, we will get a false "null". This shouldn't be a problem because transactions will always
* have a listener above, and atomic operations would correctly show a jitter of <increment value> ->
* <incremented total> as the write is applied locally and then acknowledged at the server.
*
* Note: this method will *include* hidden writes from transaction with applyLocally set to false.
*
* @param path - The path to the data we want
* @param writeIdsToExclude - A specific set to be excluded
*/
export function syncTreeCalcCompleteEventCache(
syncTree: SyncTree,
path: Path,
writeIdsToExclude?: number[]
): Node {
const includeHiddenSets = true;
const writeTree = syncTree.pendingWriteTree_;
const serverCache = syncTree.syncPointTree_.findOnPath(
path,
(pathSoFar, syncPoint) => {
const relativePath = newRelativePath(pathSoFar, path);
const serverCache = syncPointGetCompleteServerCache(
syncPoint,
relativePath
);
if (serverCache) {
return serverCache;
}
}
);
return writeTreeCalcCompleteEventCache(
writeTree,
path,
serverCache,
writeIdsToExclude,
includeHiddenSets
);
}
export function syncTreeGetServerValue(
syncTree: SyncTree,
query: QueryContext
): Node | null {
const path = query._path;
let serverCache: Node | null = null;
// Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
// Consider optimizing this once there's a better understanding of what actual behavior will be.
syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {
const relativePath = newRelativePath(pathToSyncPoint, path);
serverCache =
serverCache || syncPointGetCompleteServerCache(sp, relativePath);
});
let syncPoint = syncTree.syncPointTree_.get(path);
if (!syncPoint) {
syncPoint = new SyncPoint();
syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
} else {
serverCache =
serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
}
const serverCacheComplete = serverCache != null;
const serverCacheNode: CacheNode | null = serverCacheComplete
? new CacheNode(serverCache, true, false)
: null;
const writesCache: WriteTreeRef | null = writeTreeChildWrites(
syncTree.pendingWriteTree_,
query._path
);
const view: View = syncPointGetView(
syncPoint,
query,
writesCache,
serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE,
serverCacheComplete
);
return viewGetCompleteNode(view);
}
/**
* A helper method that visits all descendant and ancestor SyncPoints, applying the operation.
*
* NOTES:
* - Descendant SyncPoints will be visited first (since we raise events depth-first).
*
* - We call applyOperation() on each SyncPoint passing three things:
* 1. A version of the Operation that has been made relative to the SyncPoint location.
* 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.
* 3. A snapshot Node with cached server data, if we have it.
*
* - We concatenate all of the events returned by each SyncPoint and return the result.
*/
function syncTreeApplyOperationToSyncPoints_(
syncTree: SyncTree,
operation: Operation
): Event[] {
return syncTreeApplyOperationHelper_(
operation,
syncTree.syncPointTree_,
/*serverCache=*/ null,
writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath())
);
}
/**
* Recursive helper for applyOperationToSyncPoints_
*/
function syncTreeApplyOperationHelper_(
operation: Operation,
syncPointTree: ImmutableTree<SyncPoint>,
serverCache: Node | null,
writesCache: WriteTreeRef
): Event[] {
if (pathIsEmpty(operation.path)) {
return syncTreeApplyOperationDescendantsHelper_(
operation,
syncPointTree,
serverCache,
writesCache
);
} else {
const syncPoint = syncPointTree.get(newEmptyPath());
// If we don't have cached server data, see if we can get it from this SyncPoint.
if (serverCache == null && syncPoint != null) {
serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
}
let events: Event[] = [];
const childName = pathGetFront(operation.path);
const childOperation = operation.operationForChild(childName);
const childTree = syncPointTree.children.get(childName);
if (childTree && childOperation) {
const childServerCache = serverCache
? serverCache.getImmediateChild(childName)
: null;
const childWritesCache = writeTreeRefChild(writesCache, childName);
events = events.concat(
syncTreeApplyOperationHelper_(
childOperation,
childTree,
childServerCache,
childWritesCache
)
);
}
if (syncPoint) {
events = events.concat(
syncPointApplyOperation(syncPoint, operation, writesCache, serverCache)
);
}
return events;
}
}
/**
* Recursive helper for applyOperationToSyncPoints_
*/
function syncTreeApplyOperationDescendantsHelper_(
operation: Operation,
syncPointTree: ImmutableTree<SyncPoint>,
serverCache: Node | null,
writesCache: WriteTreeRef
): Event[] {
const syncPoint = syncPointTree.get(newEmptyPath());
// If we don't have cached server data, see if we can get it from this SyncPoint.
if (serverCache == null && syncPoint != null) {
serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
}
let events: Event[] = [];
syncPointTree.children.inorderTraversal((childName, childTree) => {
const childServerCache = serverCache
? serverCache.getImmediateChild(childName)
: null;
const childWritesCache = writeTreeRefChild(writesCache, childName);
const childOperation = operation.operationForChild(childName);
if (childOperation) {
events = events.concat(
syncTreeApplyOperationDescendantsHelper_(
childOperation,
childTree,
childServerCache,
childWritesCache
)
);
}
});
if (syncPoint) {
events = events.concat(
syncPointApplyOperation(syncPoint, operation, writesCache, serverCache)
);
}
return events;
}
function syncTreeCreateListenerForView_(
syncTree: SyncTree,
view: View
): { hashFn(): string; onComplete(a: string, b?: unknown): Event[] } {
const query = view.query;
const tag = syncTreeTagForQuery_(syncTree, query);
return {
hashFn: () => {
const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;
return cache.hash();
},
onComplete: (status: string): Event[] => {
if (status === 'ok') {
if (tag) {
return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);
} else {
return syncTreeApplyListenComplete(syncTree, query._path);
}
} else {
// If a listen failed, kill all of the listeners here, not just the one that triggered the error.
// Note that this may need to be scoped to just this listener if we change permissions on filtered children
const error = errorForServerCode(status, query);
return syncTreeRemoveEventRegistration(
syncTree,
query,
/*eventRegistration*/ null,
error
);
}
}
};
}
/**
* Return the tag associated with the given query.
*/
function syncTreeTagForQuery_(
syncTree: SyncTree,
query: QueryContext
): number | null {
const queryKey = syncTreeMakeQueryKey_(query);
return syncTree.queryToTagMap.get(queryKey);
}
/**
* Given a query, computes a "queryKey" suitable for use in our queryToTagMap_.
*/
function syncTreeMakeQueryKey_(query: QueryContext): string {
return query._path.toString() + '$' + query._queryIdentifier;
}
/**
* Return the query associated with the given tag, if we have one
*/
function syncTreeQueryKeyForTag_(
syncTree: SyncTree,
tag: number
): string | null {
return syncTree.tagToQueryMap.get(tag);
}
/**
* Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.
*/
function syncTreeParseQueryKey_(queryKey: string): {
queryId: string;
path: Path;
} {
const splitIndex = queryKey.indexOf('$');
assert(
splitIndex !== -1 && splitIndex < queryKey.length - 1,
'Bad queryKey.'
);
return {
queryId: queryKey.substr(splitIndex + 1),
path: new Path(queryKey.substr(0, splitIndex))
};
}
/**
* A helper method to apply tagged operations
*/
function syncTreeApplyTaggedOperation_(
syncTree: SyncTree,
queryPath: Path,
operation: Operation
): Event[] {
const syncPoint = syncTree.syncPointTree_.get(queryPath);
assert(syncPoint, "Missing sync point for query tag that we're tracking");
const writesCache = writeTreeChildWrites(
syncTree.pendingWriteTree_,
queryPath
);
return syncPointApplyOperation(syncPoint, operation, writesCache, null);
}
/**
* This collapses multiple unfiltered views into a single view, since we only need a single
* listener for them.
*/
function syncTreeCollectDistinctViewsForSubTree_(
subtree: ImmutableTree<SyncPoint>
): View[] {
return subtree.fold<View[]>((relativePath, maybeChildSyncPoint, childMap) => {
if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {
const completeView = syncPointGetCompleteView(maybeChildSyncPoint);
return [completeView];
} else {
// No complete view here, flatten any deeper listens into an array
let views: View[] = [];
if (maybeChildSyncPoint) {
views = syncPointGetQueryViews(maybeChildSyncPoint);
}
each(childMap, (_key: string, childViews: View[]) => {
views = views.concat(childViews);
});
return views;
}
});
}
/**
* Normalizes a query to a query we send the server for listening
*
* @returns The normalized query
*/
function syncTreeQueryForListening_(query: QueryContext): QueryContext {
if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {
// We treat queries that load all data as default queries
// Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits
// from Query
return new (syncTreeGetReferenceConstructor())(query._repo, query._path);
} else {
return query;
}
}
function syncTreeRemoveTags_(syncTree: SyncTree, queries: QueryContext[]) {
for (let j = 0; j < queries.length; ++j) {
const removedQuery = queries[j];
if (!removedQuery._queryParams.loadsAllData()) {
// We should have a tag for this
const removedQueryKey = syncTreeMakeQueryKey_(removedQuery);
const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);
syncTree.queryToTagMap.delete(removedQueryKey);
syncTree.tagToQueryMap.delete(removedQueryTag);
}
}
}
/**
* Static accessor for query tags.
*/
function syncTreeGetNextQueryTag_(): number {
return syncTreeNextQueryTag_++;
}
/**
* For a given new listen, manage the de-duplication of outstanding subscriptions.
*
* @returns This method can return events to support synchronous data sources
*/
function syncTreeSetupListener_(
syncTree: SyncTree,
query: QueryContext,
view: View
): Event[] {
const path = query._path;
const tag = syncTreeTagForQuery_(syncTree, query);
const listener = syncTreeCreateListenerForView_(syncTree, view);
const events = syncTree.listenProvider_.startListening(
syncTreeQueryForListening_(query),
tag,
listener.hashFn,
listener.onComplete
);
const subtree = syncTree.syncPointTree_.subtree(path);
// The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we
// may need to shadow other listens as well.
if (tag) {
assert(
!syncPointHasCompleteView(subtree.value),
"If we're adding a query, it shouldn't be shadowed"
);
} else {
// Shadow everything at or below this location, this is a default listener.
const queriesToStop = subtree.fold<QueryContext[]>(
(relativePath, maybeChildSyncPoint, childMap) => {
if (
!pathIsEmpty(relativePath) &&
maybeChildSyncPoint &&
syncPointHasCompleteView(maybeChildSyncPoint)
) {
return [syncPointGetCompleteView(maybeChildSyncPoint).query];
} else {
// No default listener here, flatten any deeper queries into an array
let queries: QueryContext[] = [];
if (maybeChildSyncPoint) {
queries = queries.concat(
syncPointGetQueryViews(maybeChildSyncPoint).map(
view => view.query
)
);
}
each(childMap, (_key: string, childQueries: QueryContext[]) => {
queries = queries.concat(childQueries);
});
return queries;
}
}
);
for (let i = 0; i < queriesToStop.length; ++i) {
const queryToStop = queriesToStop[i];
syncTree.listenProvider_.stopListening(
syncTreeQueryForListening_(queryToStop),
syncTreeTagForQuery_(syncTree, queryToStop)
);
}
}
return events;
} | the_stack |
(function () {
'use strict';
const content = window.framework.findContentDiv();
(<HTMLElement>content.querySelector('.notification-bar')).style.display = 'none';
const mdFileUrl: string = window.framework.getContentLocation() === '/' ? '../../../docs/PTUIControlsConversationControl.md' : 'Content/websdk/docs/PTUIControlsConversationControl.md';
content.querySelector('zero-md').setAttribute('file', mdFileUrl);
var app = window.framework.application,
renderedConversations = [], // Represents **rendered** conversations
listeners = [],
listeningForIncoming = false,
callButton = <HTMLInputElement>content.querySelector('.call'),
// listenButton = <HTMLInputElement>content.querySelector('.incoming'),
step = 1, // Keep track of what UI section to dislpay
ccNumber = 1;
window.framework.bindInputToEnter(<HTMLInputElement>content.querySelector('.sip1'));
window.framework.bindInputToEnter(<HTMLInputElement>content.querySelector('.sip2'));
(<HTMLElement>content.querySelector('#conversationcontrol')).style.display = 'none';
function cleanUI() {
(<HTMLInputElement>content.querySelector('.sip1')).value = '';
(<HTMLInputElement>content.querySelector('.sip2')).value = '';
(<HTMLElement>content.querySelector('.conversationContainer')).innerHTML = '';
(<HTMLElement>content.querySelector('#conversationcontrol')).style.display = 'none';
callButton.innerHTML = 'Create Control';
callButton.disabled = false;
// listenButton.innerHTML = 'Start Listening';
// listenButton.disabled = false;
(<HTMLInputElement>content.querySelector('.endAllConvs')).style.display = 'none';
(<HTMLInputElement>content.querySelector('.sip1')).value = '';
(<HTMLInputElement>content.querySelector('.sip2')).value = '';
}
function cleanupConversations() {
for (const rc of renderedConversations) {
cleanupConversation(rc);
}
renderedConversations = [];
}
function cleanupConversation(conversation) {
if (conversation.state() !== 'Disconnected') {
conversation.leave();
}
}
function reset(bySample: Boolean) {
window.framework.hideNotificationBar();
content.querySelector('.notification-bar').innerHTML = '<br/> <div class="mui--text-subhead"><b>Events Timeline</b></div> <br/>'
ccNumber = 1;
gotoStep(1);
// remove any outstanding event listeners
for (var i = 0; i < listeners.length; i++) {
listeners[i].dispose();
}
listeners = [];
listeningForIncoming = false;
cleanCCs(bySample);
}
function cleanCCs(bySample: Boolean) {
if (renderedConversations.length > 0) {
if (bySample) {
cleanupConversations();
cleanUI();
} else {
const result = window.confirm('Leaving this sample will end the conversation. Do you really want to leave?');
if (result) {
cleanupConversations();
cleanUI();
}
return result;
}
} else {
cleanUI();
}
}
function startOutgoingCall() {
(<HTMLInputElement>content.querySelector('.call')).disabled = true;
const conversationsManager = app.conversationsManager;
const id1 = window.framework.updateUserIdInput((<HTMLInputElement>content.querySelector('.sip1')).value);
const id2 = window.framework.updateUserIdInput((<HTMLInputElement>content.querySelector('.sip2')).value);
var participants = [];
if (id1 !== '') {
participants.push(id1);
}
if (id2 !== '') {
participants.push(id2);
}
if (!id1 && !id2) {
window.framework.showNotificationBar();
window.framework.addNotification('error', 'Must specify at least 1 SIP Address');
return;
}
createCC({
participants: participants,
modalities: ['Chat']
}, 'Outgoing');
}
function listenForIncoming() {
if (listeningForIncoming)
return;
listeningForIncoming = true;
// listenButton.disabled = true;
// listenButton.innerHTML= 'Listening...';
// Render incoming call with Conversation control
listeners.push(app.conversationsManager.conversations.added((conv) => {
var chatState = conv.selfParticipant.chat.state;
var audioState = conv.selfParticipant.audio.state;
if (chatState() != 'Notified' && audioState() != 'Notified') {
listeners.push(chatState.when('Notified', () => startIncomingCall(conv)));
listeners.push(audioState.when('Notified', () => startIncomingCall(conv)));
// This is probably a leftover disconnected conversation; don't render
// it yet, but listen in case the modalities become Notified again.
return;
}
startIncomingCall(conv);
}));
}
function startIncomingCall(conv) {
// Only allow start if not already in 'conversations'
for (const rc of renderedConversations) {
if (rc === conv)
return;
}
// Avoid rendering twice if both audio and chat are notified simultaneously
renderedConversations.push(conv);
// Options for renderConversation
var options: any = {}
if (conv.isGroupConversation()) {
options.conversationId = conv.uri();
} else {
var participants = [];
participants.push(conv.participants(0).person.id());
options.participants = participants;
}
options.modalities = ['Chat']; // TODO: adding audio or video causes renderConversation to fail
createCC(options, 'Incoming');
}
function createCC(options, direction) {
window.framework.showNotificationBar();
window.framework.addNotification('info', 'Creating Control...');
const div = document.createElement('div');
var control = <HTMLElement>content.querySelector('.conversationContainer');
control.appendChild(document.createTextNode('Conversation Control #' + ccNumber));
ccNumber++;
control.appendChild(div);
const divider = document.createElement('div');
divider.className = 'mui-divider';
control.appendChild(divider);
(<HTMLElement>content.querySelector('#conversationcontrol')).style.display = 'block';
window.framework.api.renderConversation(div, options).then(conv => {
if (direction === 'Outgoing')
renderedConversations.push(conv);
listeners.push(conv.selfParticipant.chat.state.when('Connected', () => {
window.framework.addNotification('success', 'Connected to Chat');
}));
listeners.push(conv.participants.added(p => {
window.framework.addNotification('info', p.person.displayName() + ' has joined the conversation');
}));
listeners.push(conv.state.changed((newValue, reason, oldValue) => {
window.framework.addNotification('info', 'Conversation state changed from ' + oldValue + ' to ' + newValue);
if (newValue === 'Connected' || newValue === 'Conferenced') {
enableInCall(conv);
}
if (newValue === 'Disconnected' && (
oldValue === 'Connected' || oldValue === 'Connecting' ||
oldValue === 'Conferenced' || oldValue === 'Conferencing')) {
window.framework.addNotification('info', 'Conversation disconnected');
checkRestart();
}
}));
window.framework.addNotification('success', 'Control Created');
(<HTMLInputElement>content.querySelector('.call')).disabled = false;
(<HTMLInputElement>content.querySelector('.sip1')).value = '';
// Decide whether to start or accept
startOrAcceptModalities(conv, options);
}, error => {
window.framework.addNotification('error', 'Failed to create conversation control');
});
}
function startOrAcceptModalities(conv, options) {
const chatState = conv.selfParticipant.chat.state,
audioState = conv.selfParticipant.audio.state,
videoState = conv.selfParticipant.video.state;
if (chatState() == 'Notified' || audioState() == 'Notified') {
if (chatState() == 'Notified')
monitor(conv.chatService.accept(), 'chatService', 'accept');
if (videoState() == 'Notified')
monitor(conv.videoService.accept(), 'videoService', 'accept');
else if (audioState() == 'Notified')
monitor(conv.audioService.accept(), 'audioService', 'accept');
}
else {
if (options.modalities.indexOf('Chat') >= 0)
monitor(conv.chatService.start(), 'chatService', 'start');
if (options.modalities.indexOf('Video') >= 0)
monitor(conv.videoService.start(), 'videoService', 'start');
else if (options.modalities.indexOf('Audio') >= 0)
monitor(conv.audioService.start(), 'audioService', 'start');
}
}
function endCall(conversation) {
window.framework.addNotification('info', 'Ending conversation ...');
conversation.leave().then(() => {
window.framework.addNotification('success', 'Conversation ended.');
cleanCCs(true);
allowRestart();
}, error => {
window.framework.addNotification('error', 'End Conversation: ' + (error ? error.message : ''));
});
}
function checkRestart() {
for (const rc of renderedConversations) {
if (rc.state() !== 'Disconnected')
return;
}
allowRestart();
}
function allowRestart() {
const resetButton = <HTMLInputElement>content.querySelector('.restart');
gotoStep(2);
window.framework.addEventListener(resetButton, 'click', reset);
}
function enableInCall(conv) {
const endCallButton = <HTMLInputElement>content.querySelector('.endAllConvs');
endCallButton.style.display = 'block';
window.framework.addEventListener(endCallButton, 'click', () => endCall(conv));
}
function gotoStep(n) {
// console.log('step: ' + n);
disableStep(step);
step = n;
enableStep(step);
}
function enableStep(n) {
(<HTMLElement>content.querySelector('#step' + n)).style.display = 'block';
}
function disableStep(n) {
(<HTMLElement>content.querySelector('#step' + n)).style.display = 'none';
}
function monitor(dfd, service, method) {
dfd.then(() => {
window.framework.addNotification('success', service + ' ' + method + 'ed successfully. Call connected');
}, error => {
window.framework.addNotification('error', service + ':' + method + ' - ' + (error ? error.message : 'unknown'));
});
}
window.framework.registerNavigation(reset);
window.framework.addEventListener(callButton, 'click', startOutgoingCall);
// window.framework.addEventListener(listenButton, 'click', listenForIncoming);
})(); | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace FormGoal_Information {
interface tab__242FCD83_2A50_478E_922A_F4641920DDE0_Sections {
_8ECDE6CB_085B_46D1_97A9_E357C5799076: DevKit.Controls.Section;
}
interface tab__349A439D_6ED5_BAE8_7C7D_3721869367CA_Sections {
_3A5C2DC2_2EE7_848C_83EB_A2B1E4D1C703: DevKit.Controls.Section;
}
interface tab_general_Sections {
information: DevKit.Controls.Section;
}
interface tab_notes_Sections {
notes: DevKit.Controls.Section;
}
interface tab__242FCD83_2A50_478E_922A_F4641920DDE0 extends DevKit.Controls.ITab {
Section: tab__242FCD83_2A50_478E_922A_F4641920DDE0_Sections;
}
interface tab__349A439D_6ED5_BAE8_7C7D_3721869367CA extends DevKit.Controls.ITab {
Section: tab__349A439D_6ED5_BAE8_7C7D_3721869367CA_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 {
_242FCD83_2A50_478E_922A_F4641920DDE0: tab__242FCD83_2A50_478E_922A_F4641920DDE0;
_349A439D_6ED5_BAE8_7C7D_3721869367CA: tab__349A439D_6ED5_BAE8_7C7D_3721869367CA;
general: tab_general;
notes: tab_notes;
}
interface Body {
Tab: Tabs;
/** Shows the actual value (Decimal type) achieved towards the target as of the last rolled-up date. This field appears when the metric type of the goal is Amount and the amount data type is Decimal. */
ActualDecimal: DevKit.Controls.Decimal;
/** Shows the actual value (integer) achieved towards the target as of the last rolled-up date. This field appears when the metric type of the goal is Amount or Count and the amount data type is Integer. */
ActualInteger: DevKit.Controls.Integer;
/** Shows the actual value (Money type) achieved towards the target as of the last rolled-up date. This field appears when the metric type of the goal is Amount and the amount data type is Money. */
ActualMoney: DevKit.Controls.Money;
/** Select whether only the goal owner's records, or all records, should be rolled up for goal results. */
ConsiderOnlyGoalOwnersRecords: DevKit.Controls.Boolean;
/** Indicates a placeholder rollup field for a decimal value to track a third category of results other than actuals and in-progress results. */
CustomRollupFieldDecimal: DevKit.Controls.Decimal;
/** Indicates a placeholder rollup field for an integer value to track a third category of results other than actuals and in-progress results. */
CustomRollupFieldInteger: DevKit.Controls.Integer;
/** Indicates a placeholder rollup field for a money value to track a third category of results other than actuals and in-progress results. */
CustomRollupFieldMoney: DevKit.Controls.Money;
/** Select the fiscal period for the goal. */
FiscalPeriod: DevKit.Controls.OptionSet;
/** Select the fiscal year for the goal that's being tracked. */
FiscalYear: DevKit.Controls.OptionSet;
/** Enter the date when the goal ends. */
GoalEndDate: DevKit.Controls.Date;
/** Choose the user or team responsible for meeting the goal. */
GoalOwnerId: DevKit.Controls.Lookup;
/** Enter the date and time when the period for tracking the goal begins. */
GoalStartDate: DevKit.Controls.Date;
/** Shows the in-progress value (decimal) against the target. This value could contribute to a goal, but is not counted yet as actual. */
InProgressDecimal: DevKit.Controls.Decimal;
/** Shows the in-progress value (integer) against the target. This value could contribute to a goal, but is not counted yet as actual. */
InProgressInteger: DevKit.Controls.Integer;
/** Shows the in-progress value (money) against the target. This value could contribute to a goal, but is not counted yet as actual. */
InProgressMoney: DevKit.Controls.Money;
/** Select whether the goal period is a fiscal period or custom period. */
IsFiscalPeriodGoal: DevKit.Controls.Boolean;
/** Shows the date and time when the goal was last rolled up. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
LastRolledupDate: DevKit.Controls.DateTime;
/** Choose the metric for the goal. This metric determines how the goal is tracked. */
MetricId: DevKit.Controls.Lookup;
participatingrecordcontrol: DevKit.Controls.ActionCards;
notescontrol: DevKit.Controls.Note;
/** Enter the user or team who is assigned to manage the record. This field is updated every time the record is assigned to a different user. */
OwnerId: DevKit.Controls.Lookup;
/** Choose a parent goal if the current goal is a child goal. This sets up a parent-child relationship for reporting and analytics. */
ParentGoalId: DevKit.Controls.Lookup;
/** Shows the percentage achieved against the target goal. */
Percentage: DevKit.Controls.Decimal;
/** Shows the percentage achieved against the target goal. */
Percentage_1: DevKit.Controls.Decimal;
/** Shows the percentage achieved against the target goal. */
Percentage_2: DevKit.Controls.Decimal;
/** Select whether the data should be rolled up only from the child goals. */
RollupOnlyFromChildGoals: DevKit.Controls.Boolean;
/** Choose the query that will be used to calculate the actual data for the goal (decimal). */
RollUpQueryActualDecimalId: DevKit.Controls.Lookup;
/** Choose the query that will be used to calculate the actual data for the goal (integer). */
RollupQueryActualIntegerId: DevKit.Controls.Lookup;
/** Choose the query that will be used to calculate the actual data for the goal (money). */
RollUpQueryActualMoneyId: DevKit.Controls.Lookup;
/** Choose the query that will be used to calculate data for the custom rollup field (decimal). */
RollUpQueryCustomDecimalId: DevKit.Controls.Lookup;
/** Choose the query that will be used to calculate data for the custom rollup field (integer). */
RollUpQueryCustomIntegerId: DevKit.Controls.Lookup;
/** Choose the query that will be used to calculate data for the custom rollup field (money). */
RollUpQueryCustomMoneyId: DevKit.Controls.Lookup;
/** Choose the query that will be used to calculate data for the in-progress rollup field (decimal). */
RollUpQueryInprogressDecimalId: DevKit.Controls.Lookup;
/** Choose the query that will be used to calculate data for the in-progress rollup field (integer). */
RollUpQueryInprogressIntegerId: DevKit.Controls.Lookup;
/** Choose the query that will be used to calculate data for the in-progress rollup field (money). */
RollUpQueryInprogressMoneyId: DevKit.Controls.Lookup;
/** Select a stretch target (decimal) of the goal to define a higher or difficult level of goal than the usual ones. */
StretchTargetDecimal: DevKit.Controls.Decimal;
/** Select the stretch target (integer) of the goal to define a higher or difficult level of goal than the usual ones. */
StretchTargetInteger: DevKit.Controls.Integer;
/** Select stretch target (money) of the goal to define a higher or difficult level of goal than the usual ones. */
StretchTargetMoney: DevKit.Controls.Money;
/** Select a goal target of the decimal type to use for tracking data that include partial numbers, such as pounds sold of a product sold by weight. */
TargetDecimal: DevKit.Controls.Decimal;
/** Select a goal target of the integer type to use for tracking anything countable in whole numbers, such as units sold. */
TargetInteger: DevKit.Controls.Integer;
/** Select a goal target (money) to track a monetary amount such as revenue from a product. */
TargetMoney: DevKit.Controls.Money;
/** Type a title or name that describes the goal. */
Title: DevKit.Controls.String;
}
interface Footer extends DevKit.Controls.IFooter {
/** Shows whether the goal is open, completed, or canceled. Completed and canceled goals are read-only and can't be edited. */
StateCode: DevKit.Controls.OptionSet;
}
interface Grid {
child_goals: DevKit.Controls.Grid;
}
}
class FormGoal_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Goal_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 Goal_Information */
Body: DevKit.FormGoal_Information.Body;
/** The Footer section of form Goal_Information */
Footer: DevKit.FormGoal_Information.Footer;
/** The Grid of form Goal_Information */
Grid: DevKit.FormGoal_Information.Grid;
}
class GoalApi {
/**
* DynamicsCrm.DevKit GoalApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Shows the actual value (Decimal type) achieved towards the target as of the last rolled-up date. This field appears when the metric type of the goal is Amount and the amount data type is Decimal. */
ActualDecimal: DevKit.WebApi.DecimalValue;
/** Shows the actual value (integer) achieved towards the target as of the last rolled-up date. This field appears when the metric type of the goal is Amount or Count and the amount data type is Integer. */
ActualInteger: DevKit.WebApi.IntegerValue;
/** Shows the actual value (Money type) achieved towards the target as of the last rolled-up date. This field appears when the metric type of the goal is Amount and the amount data type is Money. */
ActualMoney: DevKit.WebApi.MoneyValue;
/** Shows the actual value (money type) in base currency to track goal results against the target. */
ActualMoney_Base: DevKit.WebApi.MoneyValueReadonly;
/** Actual Value of the goal. */
ActualString: DevKit.WebApi.StringValueReadonly;
/** Data type of the amount. */
AmountDataType: DevKit.WebApi.OptionSetValue;
/** Shows the expected amount for actual value (decimal type) against the target goal. */
ComputedTargetAsOfTodayDecimal: DevKit.WebApi.DecimalValueReadonly;
/** Shows the expected amount for actual value (integer type) against the target goal as of the current date. */
ComputedTargetAsOfTodayInteger: DevKit.WebApi.IntegerValueReadonly;
/** Shows the expected amount for actual value (money type) against the target goal as of the current date. */
ComputedTargetAsOfTodayMoney: DevKit.WebApi.MoneyValueReadonly;
/** Shows the expected amount in base currency for actual value (money type) against the target goal as of the current date. */
ComputedTargetAsOfTodayMoney_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the expected value for percentage achieved against the target goal as of the current date. */
ComputedTargetAsOfTodayPercentageAchieved: DevKit.WebApi.DecimalValueReadonly;
/** Select whether only the goal owner's records, or all records, should be rolled up for goal results. */
ConsiderOnlyGoalOwnersRecords: DevKit.WebApi.BooleanValue;
/** Shows who created the record. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who created the record on behalf of another user. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Indicates a placeholder rollup field for a decimal value to track a third category of results other than actuals and in-progress results. */
CustomRollupFieldDecimal: DevKit.WebApi.DecimalValue;
/** Indicates a placeholder rollup field for an integer value to track a third category of results other than actuals and in-progress results. */
CustomRollupFieldInteger: DevKit.WebApi.IntegerValue;
/** Indicates a placeholder rollup field for a money value to track a third category of results other than actuals and in-progress results. */
CustomRollupFieldMoney: DevKit.WebApi.MoneyValue;
/** Indicates a placeholder rollup field for a money value in base currency to track a third category of results other than actuals and in-progress results. */
CustomRollupFieldMoney_Base: DevKit.WebApi.MoneyValueReadonly;
/** Placeholder rollup field for the goal. */
CustomRollupFieldString: DevKit.WebApi.StringValueReadonly;
/** Depth of the goal in the tree. */
Depth: DevKit.WebApi.IntegerValueReadonly;
/** The default image for the entity. */
EntityImage: DevKit.WebApi.StringValue;
EntityImage_Timestamp: DevKit.WebApi.BigIntValueReadonly;
EntityImage_URL: DevKit.WebApi.StringValueReadonly;
/** For internal use only. */
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;
/** Select the fiscal period for the goal. */
FiscalPeriod: DevKit.WebApi.OptionSetValue;
/** Select the fiscal year for the goal that's being tracked. */
FiscalYear: DevKit.WebApi.OptionSetValue;
/** Enter the date when the goal ends. */
GoalEndDate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Unique identifier of the goal. */
GoalId: DevKit.WebApi.GuidValue;
/** Choose the user or team responsible for meeting the goal. */
goalownerid_systemuser: DevKit.WebApi.LookupValue;
/** Choose the user or team responsible for meeting the goal. */
goalownerid_team: DevKit.WebApi.LookupValue;
/** Enter the date and time when the period for tracking the goal begins. */
GoalStartDate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Unique identifier of the goal that caused an error in the rollup of the goal hierarchy. */
GoalWithErrorId: DevKit.WebApi.LookupValue;
/** Sequence number of the import that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Shows the in-progress value (decimal) against the target. This value could contribute to a goal, but is not counted yet as actual. */
InProgressDecimal: DevKit.WebApi.DecimalValue;
/** Shows the in-progress value (integer) against the target. This value could contribute to a goal, but is not counted yet as actual. */
InProgressInteger: DevKit.WebApi.IntegerValue;
/** Shows the in-progress value (money) against the target. This value could contribute to a goal, but is not counted yet as actual. */
InProgressMoney: DevKit.WebApi.MoneyValue;
/** Shows the in-progress value (money) in base currency to track goal results against the target. */
InProgressMoney_Base: DevKit.WebApi.MoneyValueReadonly;
/** In-progress value of the goal. */
InProgressString: DevKit.WebApi.StringValueReadonly;
/** Indicates whether the metric type is Count or Amount. */
IsAmount: DevKit.WebApi.BooleanValue;
/** Select whether the goal period is a fiscal period or custom period. */
IsFiscalPeriodGoal: DevKit.WebApi.BooleanValue;
/** Select whether the system rollup fields are updated. If set to Yes, the next system rollup will not update the values of the rollup fields with the system calculated values. */
IsOverridden: DevKit.WebApi.BooleanValue;
/** Indicates whether the values of system rollup fields can be updated. */
IsOverride: DevKit.WebApi.BooleanValue;
/** Shows the date and time when the goal was last rolled up. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
LastRolledupDate_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Choose the metric for the goal. This metric determines how the goal is tracked. */
MetricId: DevKit.WebApi.LookupValue;
/** Shows who last updated the record. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who last updated the record on behalf of another user. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** 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 of the team who owns the goal. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the user who owns the record. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** Choose a parent goal if the current goal is a child goal. This sets up a parent-child relationship for reporting and analytics. */
ParentGoalId: DevKit.WebApi.LookupValue;
/** Shows the percentage achieved against the target goal. */
Percentage: DevKit.WebApi.DecimalValue;
/** Error code associated with rollup. */
RollupErrorCode: DevKit.WebApi.IntegerValue;
/** Select whether the data should be rolled up only from the child goals. */
RollupOnlyFromChildGoals: DevKit.WebApi.BooleanValue;
/** Choose the query that will be used to calculate the actual data for the goal (decimal). */
RollUpQueryActualDecimalId: DevKit.WebApi.LookupValue;
/** Choose the query that will be used to calculate the actual data for the goal (integer). */
RollupQueryActualIntegerId: DevKit.WebApi.LookupValue;
/** Choose the query that will be used to calculate the actual data for the goal (money). */
RollUpQueryActualMoneyId: DevKit.WebApi.LookupValue;
/** Choose the query that will be used to calculate data for the custom rollup field (decimal). */
RollUpQueryCustomDecimalId: DevKit.WebApi.LookupValue;
/** Choose the query that will be used to calculate data for the custom rollup field (integer). */
RollUpQueryCustomIntegerId: DevKit.WebApi.LookupValue;
/** Choose the query that will be used to calculate data for the custom rollup field (money). */
RollUpQueryCustomMoneyId: DevKit.WebApi.LookupValue;
/** Choose the query that will be used to calculate data for the in-progress rollup field (decimal). */
RollUpQueryInprogressDecimalId: DevKit.WebApi.LookupValue;
/** Choose the query that will be used to calculate data for the in-progress rollup field (integer). */
RollUpQueryInprogressIntegerId: DevKit.WebApi.LookupValue;
/** Choose the query that will be used to calculate data for the in-progress rollup field (money). */
RollUpQueryInprogressMoneyId: DevKit.WebApi.LookupValue;
/** Shows whether the goal is open, completed, or canceled. Completed and canceled goals are read-only and can't be edited. */
StateCode: DevKit.WebApi.OptionSetValue;
/** Select the goal's status. */
StatusCode: DevKit.WebApi.OptionSetValue;
/** Select a stretch target (decimal) of the goal to define a higher or difficult level of goal than the usual ones. */
StretchTargetDecimal: DevKit.WebApi.DecimalValue;
/** Select the stretch target (integer) of the goal to define a higher or difficult level of goal than the usual ones. */
StretchTargetInteger: DevKit.WebApi.IntegerValue;
/** Select stretch target (money) of the goal to define a higher or difficult level of goal than the usual ones. */
StretchTargetMoney: DevKit.WebApi.MoneyValue;
/** Shows the stretch target (money) in base currency to indicate a higher or difficult level of goal than the usual ones. */
StretchTargetMoney_Base: DevKit.WebApi.MoneyValueReadonly;
/** Stretch target value for all data types. */
StretchTargetString: DevKit.WebApi.StringValueReadonly;
/** Select a goal target of the decimal type to use for tracking data that include partial numbers, such as pounds sold of a product sold by weight. */
TargetDecimal: DevKit.WebApi.DecimalValue;
/** Select a goal target of the integer type to use for tracking anything countable in whole numbers, such as units sold. */
TargetInteger: DevKit.WebApi.IntegerValue;
/** Select a goal target (money) to track a monetary amount such as revenue from a product. */
TargetMoney: DevKit.WebApi.MoneyValue;
/** Shows the goal target of the money type in base currency. */
TargetMoney_Base: DevKit.WebApi.MoneyValueReadonly;
/** Target value of the goal. */
TargetString: DevKit.WebApi.StringValueReadonly;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Type a title or name that describes the goal. */
Title: DevKit.WebApi.StringValue;
/** Choose the local currency for the record to make sure budgets are reported in the correct currency. */
TransactionCurrencyId: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the goal tree. */
TreeId: DevKit.WebApi.GuidValueReadonly;
/** Time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
/** Version number of the goal. */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
}
}
declare namespace OptionSet {
namespace Goal {
enum AmountDataType {
/** 1 */
Decimal,
/** 2 */
Integer,
/** 0 */
Money
}
enum FiscalPeriod {
/** 301 */
Annual,
/** 104 */
April,
/** 108 */
August,
/** 112 */
December,
/** 102 */
February,
/** 101 */
January,
/** 107 */
July,
/** 106 */
June,
/** 103 */
March,
/** 105 */
May,
/** 111 */
November,
/** 110 */
October,
/** 401 */
P1,
/** 410 */
P10,
/** 411 */
P11,
/** 412 */
P12,
/** 413 */
P13,
/** 402 */
P2,
/** 403 */
P3,
/** 404 */
P4,
/** 405 */
P5,
/** 406 */
P6,
/** 407 */
P7,
/** 408 */
P8,
/** 409 */
P9,
/** 1 */
Quarter_1,
/** 2 */
Quarter_2,
/** 3 */
Quarter_3,
/** 4 */
Quarter_4,
/** 201 */
Semester_1,
/** 202 */
Semester_2,
/** 109 */
September
}
enum FiscalYear {
/** 1970 */
FY1970,
/** 1971 */
FY1971,
/** 1972 */
FY1972,
/** 1973 */
FY1973,
/** 1974 */
FY1974,
/** 1975 */
FY1975,
/** 1976 */
FY1976,
/** 1977 */
FY1977,
/** 1978 */
FY1978,
/** 1979 */
FY1979,
/** 1980 */
FY1980,
/** 1981 */
FY1981,
/** 1982 */
FY1982,
/** 1983 */
FY1983,
/** 1984 */
FY1984,
/** 1985 */
FY1985,
/** 1986 */
FY1986,
/** 1987 */
FY1987,
/** 1988 */
FY1988,
/** 1989 */
FY1989,
/** 1990 */
FY1990,
/** 1991 */
FY1991,
/** 1992 */
FY1992,
/** 1993 */
FY1993,
/** 1994 */
FY1994,
/** 1995 */
FY1995,
/** 1996 */
FY1996,
/** 1997 */
FY1997,
/** 1998 */
FY1998,
/** 1999 */
FY1999,
/** 2000 */
FY2000,
/** 2001 */
FY2001,
/** 2002 */
FY2002,
/** 2003 */
FY2003,
/** 2004 */
FY2004,
/** 2005 */
FY2005,
/** 2006 */
FY2006,
/** 2007 */
FY2007,
/** 2008 */
FY2008,
/** 2009 */
FY2009,
/** 2010 */
FY2010,
/** 2011 */
FY2011,
/** 2012 */
FY2012,
/** 2013 */
FY2013,
/** 2014 */
FY2014,
/** 2015 */
FY2015,
/** 2016 */
FY2016,
/** 2017 */
FY2017,
/** 2018 */
FY2018,
/** 2019 */
FY2019,
/** 2020 */
FY2020,
/** 2021 */
FY2021,
/** 2022 */
FY2022,
/** 2023 */
FY2023,
/** 2024 */
FY2024,
/** 2025 */
FY2025,
/** 2026 */
FY2026,
/** 2027 */
FY2027,
/** 2028 */
FY2028,
/** 2029 */
FY2029,
/** 2030 */
FY2030,
/** 2031 */
FY2031,
/** 2032 */
FY2032,
/** 2033 */
FY2033,
/** 2034 */
FY2034,
/** 2035 */
FY2035,
/** 2036 */
FY2036,
/** 2037 */
FY2037,
/** 2038 */
FY2038
}
enum StateCode {
/** 0 */
Active,
/** 1 */
Inactive
}
enum StatusCode {
/** 1 */
Closed,
/** 2 */
Discarded,
/** 0 */
Open
}
enum RollupState {
/** 0 - Attribute value is yet to be calculated */
NotCalculated,
/** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */
Calculated,
/** 2 - Attribute value calculation lead to overflow error */
OverflowError,
/** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */
OtherError,
/** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */
RetryLimitExceeded,
/** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */
HierarchicalRecursionLimitReached,
/** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */
LoopDetected
}
}
}
//{'JsForm':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { setupTestBed, IdentityUserService, AlfrescoApiService, IdentityUserModel } from '@alfresco/adf-core';
import { StartTaskCloudComponent } from './start-task-cloud.component';
import { of, throwError } from 'rxjs';
import { taskDetailsMock } from '../mock/task-details.mock';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { ProcessServiceCloudTestingModule } from './../../../testing/process-service-cloud.testing.module';
import { FormDefinitionSelectorCloudService } from '../../../form/services/form-definition-selector-cloud.service';
import { TaskCloudService } from '../../services/task-cloud.service';
import { StartTaskCloudRequestModel } from '../models/start-task-cloud-request.model';
import { TranslateModule } from '@ngx-translate/core';
describe('StartTaskCloudComponent', () => {
let component: StartTaskCloudComponent;
let fixture: ComponentFixture<StartTaskCloudComponent>;
let service: TaskCloudService;
let identityService: IdentityUserService;
let formDefinitionSelectorCloudService: FormDefinitionSelectorCloudService;
let element: HTMLElement;
let createNewTaskSpy: jasmine.Spy;
let alfrescoApiService: AlfrescoApiService;
const mock: any = {
oauth2Auth: {
callCustomApi: () => Promise.resolve(taskDetailsMock)
},
isEcmLoggedIn() {
return false;
},
reply: jasmine.createSpy('reply')
};
const mockUser: IdentityUserModel = {username: 'currentUser', firstName: 'Test', lastName: 'User', email: 'currentUser@test.com'};
setupTestBed({
imports: [
TranslateModule.forRoot(),
ProcessServiceCloudTestingModule
],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
});
beforeEach(() => {
fixture = TestBed.createComponent(StartTaskCloudComponent);
component = fixture.componentInstance;
element = fixture.nativeElement;
service = TestBed.inject(TaskCloudService);
identityService = TestBed.inject(IdentityUserService);
alfrescoApiService = TestBed.inject(AlfrescoApiService);
formDefinitionSelectorCloudService = TestBed.inject(FormDefinitionSelectorCloudService);
spyOn(alfrescoApiService, 'getInstance').and.returnValue(mock);
createNewTaskSpy = spyOn(service, 'createNewTask').and.returnValue(of(taskDetailsMock as any));
spyOn(identityService, 'getCurrentUserInfo').and.returnValue(mockUser);
spyOn(formDefinitionSelectorCloudService, 'getForms').and.returnValue(of([]));
fixture.detectChanges();
});
describe('create task', () => {
it('should create new task when start button is clicked', async () => {
const successSpy = spyOn(component.success, 'emit');
component.taskForm.controls['name'].setValue('fakeName');
fixture.detectChanges();
const createTaskButton = element.querySelector<HTMLElement>('#button-start');
createTaskButton.click();
fixture.detectChanges();
await fixture.whenStable();
expect(createNewTaskSpy).toHaveBeenCalled();
expect(successSpy).toHaveBeenCalled();
});
it('should send on success event when the task is started', async () => {
const successSpy = spyOn(component.success, 'emit');
component.taskForm.controls['name'].setValue('fakeName');
component.assigneeName = 'fake-assignee';
fixture.detectChanges();
await fixture.whenStable();
const createTaskButton = element.querySelector<HTMLElement>('#button-start');
createTaskButton.click();
fixture.detectChanges();
await fixture.whenStable();
expect(successSpy).toHaveBeenCalledWith(taskDetailsMock);
});
it('should send on success event when only name is given', async () => {
const successSpy = spyOn(component.success, 'emit');
component.taskForm.controls['name'].setValue('fakeName');
fixture.detectChanges();
await fixture.whenStable();
const createTaskButton = element.querySelector<HTMLElement>('#button-start');
createTaskButton.click();
fixture.detectChanges();
await fixture.whenStable();
expect(successSpy).toHaveBeenCalled();
});
it('should not emit success event when data not present', () => {
const successSpy = spyOn(component.success, 'emit');
component.taskForm.controls['name'].setValue('');
fixture.detectChanges();
const createTaskButton = element.querySelector<HTMLElement>('#button-start');
createTaskButton.click();
expect(createNewTaskSpy).not.toHaveBeenCalled();
expect(successSpy).not.toHaveBeenCalled();
});
it('should not start task to the logged in user when invalid assignee is selected', (done) => {
component.taskForm.controls['name'].setValue('fakeName');
component.appName = 'fakeAppName';
fixture.detectChanges();
const assigneeInput = element.querySelector<HTMLElement>('input.adf-cloud-input');
assigneeInput.nodeValue = 'a';
fixture.detectChanges();
const createTaskButton = element.querySelector<HTMLElement>('#button-start');
createTaskButton.click();
fixture.detectChanges();
fixture.whenStable().then(() => {
const taskRequest = new StartTaskCloudRequestModel({ name: 'fakeName', assignee: 'currentUser', candidateGroups: []});
expect(createNewTaskSpy).toHaveBeenCalledWith(taskRequest, 'fakeAppName');
done();
});
});
it('should not start task to the logged in user when assignee is not selected', (done) => {
component.taskForm.controls['name'].setValue('fakeName');
component.appName = 'fakeAppName';
fixture.detectChanges();
const createTaskButton = element.querySelector<HTMLElement>('#button-start');
createTaskButton.click();
fixture.detectChanges();
fixture.whenStable().then(() => {
const taskRequest = new StartTaskCloudRequestModel({ name: 'fakeName', assignee: 'currentUser', candidateGroups: []});
expect(createNewTaskSpy).toHaveBeenCalledWith(taskRequest, 'fakeAppName');
done();
});
});
});
it('should show logged in user as assignee by default', () => {
fixture.detectChanges();
const assignee = fixture.nativeElement.querySelector('[data-automation-id="adf-people-cloud-chip-currentUser"]');
expect(assignee).toBeDefined();
expect(assignee.innerText).toContain('Test User');
});
it('should show start task button', () => {
component.taskForm.controls['name'].setValue('fakeName');
fixture.detectChanges();
const startButton = element.querySelector('#button-start');
expect(startButton).toBeDefined();
expect(startButton.textContent).toContain('ADF_CLOUD_TASK_LIST.START_TASK.FORM.ACTION.START');
});
it('should disable start button if name is empty', () => {
component.taskForm.controls['name'].setValue('');
fixture.detectChanges();
const createTaskButton = fixture.nativeElement.querySelector('#button-start');
expect(createTaskButton.disabled).toBeTruthy();
});
it('should cancel start task on cancel button click', () => {
fixture.detectChanges();
const emitSpy = spyOn(component.cancel, 'emit');
const cancelTaskButton = fixture.nativeElement.querySelector('#button-cancel');
cancelTaskButton.click();
expect(emitSpy).not.toBeNull();
expect(emitSpy).toHaveBeenCalled();
});
it('should enable start button if name is filled out', () => {
component.taskForm.controls['name'].setValue('fakeName');
fixture.detectChanges();
const createTaskButton = fixture.nativeElement.querySelector('#button-start');
expect(createTaskButton.disabled).toBeFalsy();
});
it('should emit error when there is an error while creating task', () => {
component.taskForm.controls['name'].setValue('fakeName');
const errorSpy = spyOn(component.error, 'emit');
createNewTaskSpy.and.returnValue(throwError({}));
component.appName = 'fakeAppName';
fixture.detectChanges();
const assigneeInput = element.querySelector<HTMLElement>('input.adf-cloud-input');
assigneeInput.nodeValue = 'a';
fixture.detectChanges();
const createTaskButton = element.querySelector<HTMLElement>('#button-start');
createTaskButton.click();
fixture.detectChanges();
expect(errorSpy).toHaveBeenCalled();
});
it('should emit error when task name exceeds maximum length', () => {
component.maxNameLength = 2;
component.ngOnInit();
fixture.detectChanges();
const name = component.taskForm.controls['name'];
name.setValue('task');
fixture.detectChanges();
expect(name.valid).toBeFalsy();
name.setValue('ta');
fixture.detectChanges();
expect(name.valid).toBeTruthy();
});
it('should emit error when task name field is empty', () => {
fixture.detectChanges();
const name = component.taskForm.controls['name'];
name.setValue('');
fixture.detectChanges();
expect(name.valid).toBeFalsy();
name.setValue('task');
fixture.detectChanges();
expect(name.valid).toBeTruthy();
});
it('should emit error when description have only white spaces', () => {
fixture.detectChanges();
const description = component.taskForm.controls['description'];
description.setValue(' ');
fixture.detectChanges();
expect(description.valid).toBeFalsy();
description.setValue('');
fixture.detectChanges();
expect(description.valid).toBeTruthy();
});
}); | the_stack |
import { ChangeDetectorRef, Component, EventEmitter, Input, OnInit, Output, ViewChild } from "@angular/core";
import {
BackendApiService,
NFTBidEntryResponse,
NFTEntryResponse,
PostEntryResponse,
ProfileEntryResponse,
} from "../../backend-api.service";
import { GlobalVarsService } from "../../global-vars.service";
import { ActivatedRoute, Router } from "@angular/router";
import { Location } from "@angular/common";
import { IAdapter, IDatasource } from "ngx-ui-scroll";
import * as _ from "lodash";
import { InfiniteScroller } from "../../infinite-scroller";
import { of, Subscription } from "rxjs";
import { SwalHelper } from "../../../lib/helpers/swal-helper";
@Component({
selector: "creator-profile-nfts",
templateUrl: "./creator-profile-nfts.component.html",
styleUrls: ["./creator-profile-nfts.component.scss"],
})
export class CreatorProfileNftsComponent implements OnInit {
static PAGE_SIZE = 10;
static BUFFER_SIZE = 5;
static WINDOW_VIEWPORT = true;
static PADDING = 0.5;
@Input() profile: ProfileEntryResponse;
@Input() afterCommentCreatedCallback: any = null;
@Input() showProfileAsReserved: boolean;
nftResponse: { NFTEntryResponses: NFTEntryResponse[]; PostEntryResponse: PostEntryResponse }[];
myBids: NFTBidEntryResponse[];
lastPage = null;
isLoading = true;
loadingNewSelection = false;
static FOR_SALE = "For Sale";
static MY_BIDS = "My Bids";
static MY_GALLERY = "Gallery";
static TRANSFERABLE = "Transferable";
static MY_PENDING_TRANSFERS = "Pending Transfers";
tabs = [CreatorProfileNftsComponent.FOR_SALE, CreatorProfileNftsComponent.MY_GALLERY];
activeTab: string;
nftTabMap = {
my_bids: CreatorProfileNftsComponent.MY_BIDS,
for_sale: CreatorProfileNftsComponent.FOR_SALE,
my_gallery: CreatorProfileNftsComponent.MY_GALLERY,
transferable: CreatorProfileNftsComponent.TRANSFERABLE,
my_pending_transfers: CreatorProfileNftsComponent.MY_PENDING_TRANSFERS,
};
nftTabInverseMap = {
[CreatorProfileNftsComponent.FOR_SALE]: "for_sale",
[CreatorProfileNftsComponent.MY_BIDS]: "my_bids",
[CreatorProfileNftsComponent.MY_GALLERY]: "my_gallery",
[CreatorProfileNftsComponent.TRANSFERABLE]: "transferable",
[CreatorProfileNftsComponent.MY_PENDING_TRANSFERS]: "my_pending_transfers",
};
CreatorProfileNftsComponent = CreatorProfileNftsComponent;
@Output() blockUser = new EventEmitter();
constructor(
private globalVars: GlobalVarsService,
private backendApi: BackendApiService,
private route: ActivatedRoute,
private cdr: ChangeDetectorRef,
private router: Router,
private location: Location
) {}
ngOnInit(): void {
if (this.profileBelongsToLoggedInUser()) {
this.tabs.push(
CreatorProfileNftsComponent.MY_BIDS,
CreatorProfileNftsComponent.MY_PENDING_TRANSFERS,
CreatorProfileNftsComponent.TRANSFERABLE
);
}
this.route.queryParams.subscribe((queryParams) => {
if (queryParams.nftTab && queryParams.nftTab in this.nftTabMap) {
if (
(queryParams.nftTab === this.nftTabInverseMap[CreatorProfileNftsComponent.MY_BIDS] ||
queryParams.nftTab === this.nftTabInverseMap[CreatorProfileNftsComponent.TRANSFERABLE] ||
queryParams.nftTab === this.nftTabInverseMap[CreatorProfileNftsComponent.MY_PENDING_TRANSFERS]) &&
this.globalVars.loggedInUser?.PublicKeyBase58Check !== this.profile.PublicKeyBase58Check
) {
this.updateNFTTabParam(CreatorProfileNftsComponent.MY_GALLERY);
} else {
this.onActiveTabChange(this.nftTabMap[queryParams.nftTab]);
}
}
});
if (!this.activeTab) {
this.isLoading = true;
let defaultTab = this.profileBelongsToLoggedInUser()
? CreatorProfileNftsComponent.MY_BIDS
: CreatorProfileNftsComponent.MY_GALLERY;
this.onActiveTabChange(defaultTab);
}
}
getNFTBids(): Subscription {
return this.backendApi
.GetNFTBidsForUser(
this.globalVars.localNode,
this.profile.PublicKeyBase58Check,
this.globalVars.loggedInUser?.PublicKeyBase58Check
)
.subscribe(
(res: {
PublicKeyBase58CheckToProfileEntryResponse: { [k: string]: ProfileEntryResponse };
PostHashHexToPostEntryResponse: { [k: string]: PostEntryResponse };
NFTBidEntries: NFTBidEntryResponse[];
}) => {
_.forIn(res.PostHashHexToPostEntryResponse, (value, key) => {
value.ProfileEntryResponse =
res.PublicKeyBase58CheckToProfileEntryResponse[value.PosterPublicKeyBase58Check];
res.PostHashHexToPostEntryResponse[key] = value;
});
this.myBids = res.NFTBidEntries.map((bidEntry) => {
bidEntry.PostEntryResponse = res.PostHashHexToPostEntryResponse[bidEntry.PostHashHex];
return bidEntry;
});
this.lastPage = Math.floor(this.myBids.length / CreatorProfileNftsComponent.PAGE_SIZE);
return this.myBids;
}
);
}
getNFTs(isForSale: boolean | null = null, isPending: boolean | null = null): Subscription {
return this.backendApi
.GetNFTsForUser(
this.globalVars.localNode,
this.profile.PublicKeyBase58Check,
this.globalVars.loggedInUser?.PublicKeyBase58Check,
isForSale,
isPending
)
.subscribe(
(res: {
NFTsMap: { [k: string]: { PostEntryResponse: PostEntryResponse; NFTEntryResponses: NFTEntryResponse[] } };
}) => {
this.nftResponse = [];
for (const k in res.NFTsMap) {
const responseElement = res.NFTsMap[k];
// Exclude NFTs created by profile from Gallery and don't show pending NFTs in galley.
if (
this.activeTab === CreatorProfileNftsComponent.MY_GALLERY &&
(responseElement.PostEntryResponse.PosterPublicKeyBase58Check === this.profile.PublicKeyBase58Check ||
responseElement.NFTEntryResponses.filter((nftEntryResponse) => !nftEntryResponse.IsPending).length ===
0)
) {
continue;
}
this.nftResponse.push(responseElement);
}
this.lastPage = Math.floor(this.nftResponse.length / CreatorProfileNftsComponent.PAGE_SIZE);
return this.nftResponse;
}
);
}
getPage(page: number) {
if (this.lastPage != null && page > this.lastPage) {
return [];
}
const startIdx = page * CreatorProfileNftsComponent.PAGE_SIZE;
const endIdx = (page + 1) * CreatorProfileNftsComponent.PAGE_SIZE;
return new Promise((resolve, reject) => {
resolve(
this.activeTab === CreatorProfileNftsComponent.MY_BIDS
? this.myBids.slice(startIdx, Math.min(endIdx, this.myBids.length))
: this.nftResponse.slice(startIdx, Math.min(endIdx, this.nftResponse.length))
);
});
}
async _prependComment(uiPostParent, index, newComment) {
const uiPostParentHashHex = this.globalVars.getPostContentHashHex(uiPostParent);
await this.datasource.adapter.relax();
await this.datasource.adapter.update({
predicate: ({ $index, data, element }) => {
let currentPost = (data as any) as PostEntryResponse;
if ($index === index) {
newComment.parentPost = currentPost;
currentPost.Comments = currentPost.Comments || [];
currentPost.Comments.unshift(_.cloneDeep(newComment));
return [this.globalVars.incrementCommentCount(currentPost)];
} else if (this.globalVars.getPostContentHashHex(currentPost) === uiPostParentHashHex) {
// We also want to increment the comment count on any other notifications related to the same post hash hex.
return [this.globalVars.incrementCommentCount(currentPost)];
}
// Leave all other items in the datasource as is.
return true;
},
});
}
userBlocked() {
this.blockUser.emit();
}
profileBelongsToLoggedInUser(): boolean {
return (
this.globalVars.loggedInUser?.ProfileEntryResponse &&
this.globalVars.loggedInUser.ProfileEntryResponse.PublicKeyBase58Check === this.profile.PublicKeyBase58Check
);
}
infiniteScroller: InfiniteScroller = new InfiniteScroller(
CreatorProfileNftsComponent.PAGE_SIZE,
this.getPage.bind(this),
CreatorProfileNftsComponent.WINDOW_VIEWPORT,
CreatorProfileNftsComponent.BUFFER_SIZE,
CreatorProfileNftsComponent.PADDING
);
datasource: IDatasource<IAdapter<any>> = this.infiniteScroller.getDatasource();
onActiveTabChange(event): Subscription {
if (this.activeTab !== event) {
this.activeTab = event;
this.loadingNewSelection = true;
this.isLoading = true;
this.infiniteScroller.reset();
if (this.activeTab === CreatorProfileNftsComponent.MY_BIDS) {
return this.getNFTBids().add(() => {
this.resetDatasource(event);
});
} else {
return this.getNFTs(this.getIsForSaleValue(), this.getIsPendingValue()).add(() => {
this.resetDatasource(event);
});
}
} else {
return of("").subscribe((res) => res);
}
}
resetDatasource(event): void {
this.infiniteScroller.reset();
this.datasource.adapter.reset().then(() => {
this.loadingNewSelection = false;
this.isLoading = false;
this.updateNFTTabParam(event);
});
}
updateNFTTabParam(event): void {
// Update query params to reflect current tab
const urlTree = this.router.createUrlTree([], {
queryParams: { nftTab: this.nftTabInverseMap[event] || "for_sale", tab: "nfts" },
queryParamsHandling: "merge",
preserveFragment: true,
});
this.location.go(urlTree.toString());
}
cancelBid(bidEntry: NFTBidEntryResponse): void {
SwalHelper.fire({
target: this.globalVars.getTargetComponentSelector(),
title: "Cancel Bid",
html: `Are you sure you'd like to cancel this bid?`,
showCancelButton: true,
customClass: {
confirmButton: "btn btn-light",
cancelButton: "btn btn-light no",
},
reverseButtons: true,
}).then((res) => {
if (res.isConfirmed) {
this.backendApi
.CreateNFTBid(
this.globalVars.localNode,
this.globalVars.loggedInUser.PublicKeyBase58Check,
bidEntry.PostEntryResponse.PostHashHex,
bidEntry.SerialNumber,
0,
this.globalVars.defaultFeeRateNanosPerKB
)
.subscribe(
() => {
return this.datasource.adapter.remove({
predicate: ({ data }) => {
const currBidEntry = (data as any) as NFTBidEntryResponse;
return (
currBidEntry.SerialNumber === bidEntry.SerialNumber &&
currBidEntry.BidAmountNanos === currBidEntry.BidAmountNanos &&
currBidEntry.PostEntryResponse.PostHashHex === bidEntry.PostEntryResponse.PostHashHex
);
},
});
},
(err) => {
console.error(err);
}
);
}
});
}
getIsForSaleValue(): boolean | null {
if (this.activeTab === CreatorProfileNftsComponent.FOR_SALE) {
return true;
} else if (this.activeTab === CreatorProfileNftsComponent.TRANSFERABLE) {
return false;
} else {
return null;
}
}
getIsPendingValue(): boolean | null {
if (this.activeTab === CreatorProfileNftsComponent.MY_PENDING_TRANSFERS) {
return true;
} else if (
this.activeTab === CreatorProfileNftsComponent.MY_GALLERY ||
this.activeTab === CreatorProfileNftsComponent.TRANSFERABLE
) {
return false;
} else {
return null;
}
}
} | the_stack |
'use strict';
import * as net from 'net';
import * as util from 'util';
import * as path from 'path';
import * as events from 'events';
// var xml2js = require('xml2js');
// import * as stream from 'stream';
import * as coqXml from './xml-protocol/coq-xml';
import * as vscode from 'vscode-languageserver';
import * as coqProto from './coq-proto';
import {ChildProcess, exec, spawn} from 'child_process';
import {CoqTopSettings, LtacProfTactic, LtacProfResults} from '../protocol';
import * as fs from 'fs';
import * as os from 'os';
import * as xmlTypes from './xml-protocol/CoqXmlProtocolTypes';
import {AnnotatedText, normalizeText, textToDisplayString} from '../util/AnnotatedText';
import {createDeserializer} from './xml-protocol/deserialize';
import * as coqtop from './CoqTop';
export {Interrupted, CoqtopSpawnError, CallFailure,
InitResult, AddResult, EditAtFocusResult, EditAtResult, ProofView,
NoProofTag, ProofModeTag, NoProofResult, ProofModeResult, GoalResult} from './CoqTop';
import {Interrupted, CoqtopSpawnError, CallFailure,
InitResult, AddResult, EditAtFocusResult, EditAtResult, ProofView,
NoProofTag, ProofModeTag, NoProofResult, ProofModeResult, GoalResult} from './CoqTop';
import {IdeSlave as IdeSlave8, IdeSlaveState} from './IdeSlave8';
export class CoqTop extends IdeSlave8 implements coqtop.CoqTop {
private mainChannelServer: net.Server;
private mainChannelServer2: net.Server;
private controlChannelServer: net.Server;
private controlChannelServer2: net.Server;
// private mainChannelR : net.Socket;
// private mainChannelW : net.Socket;
// private controlChannelW : net.Socket;
// private controlChannelR : net.Socket;
// private console: vscode.RemoteConsole;
private coqtopProc : ChildProcess = null;
// private parser : coqXml.XmlStream;
// private callbacks: EventCallbacks;
private readyToListen: Thenable<void>[];
private settings : CoqTopSettings;
private scriptFile : string;
private projectRoot: string;
// private supportsInterruptCall = false;
private coqtopVersion : string;
private sockets : net.Socket[] = [];
constructor(settings : CoqTopSettings, scriptFile: string, projectRoot: string, console: vscode.RemoteConsole) {
super(console);
this.settings = settings;
this.scriptFile = scriptFile;
this.projectRoot = projectRoot;
// this.console = console;
// this.callbacks = callbacks;
this.mainChannelServer = net.createServer();
this.mainChannelServer2 = net.createServer();
this.controlChannelServer = net.createServer();
this.controlChannelServer2 = net.createServer();
this.mainChannelServer.maxConnections = 1;
this.mainChannelServer2.maxConnections = 1;
this.controlChannelServer.maxConnections = 1;
this.controlChannelServer2.maxConnections = 1;
this.readyToListen = [
this.startListening(this.mainChannelServer),
this.startListening(this.mainChannelServer2),
this.startListening(this.controlChannelServer),
this.startListening(this.controlChannelServer2)
];
// this.resetCoq(coqPath);
}
public /* override */ dispose() {
if(this.isRunning() && this.callbacks.onClosed) {
this.callbacks.onClosed(false);
}
super.dispose();
this.sockets.forEach(s => s.destroy());
this.sockets = [];
if(this.coqtopProc) {
try {
this.coqtopProc.kill();
if(this.coqtopProc.connected)
this.coqtopProc.disconnect();
} catch(e) {}
this.coqtopProc = null;
}
this.coqtopProc = null;
}
public isRunning() : boolean {
return this.coqtopProc != null;
}
public async startCoq() : Promise<InitResult> {
if(this.state !== IdeSlaveState.Disconnected)
throw new CoqtopSpawnError(this.coqtopBin, "coqtop is already started");
this.console.log('starting coqtop');
this.coqtopVersion = await coqtop.detectVersion(this.coqtopBin, this.projectRoot, this.console);
if(this.coqtopVersion)
this.console.log(`Detected coqtop version ${this.coqtopVersion}`)
else
this.console.warn(`Could not detect coqtop version`)
const wrapper = this.findWrapper();
if (wrapper !== null)
await this.setupCoqTop(wrapper);
else
await this.setupCoqTopReadAndWritePorts();
return await this.coqInit();
}
protected async /* override */ checkState() : Promise<void> {
if(this.coqtopProc === null)
this.startCoq();
super.checkState();
}
private startListening(server: net.Server) : Promise<void> {
const port = 0;
const host = 'localhost';
return new Promise<void>((resolve,reject) => {
server.listen({port: port, host: host}, (err:any) => {
if (err)
reject(err);
else {
this.console.log(`Listening at ${server.address().address}:${server.address().port}`);
resolve();
}
});
});
}
private acceptConnection(server: net.Server, name:string) : Promise<net.Socket> {
return new Promise<net.Socket>((resolve) => {
server.once('connection', (socket:net.Socket) => {
this.sockets.push(socket);
this.console.log(`Client connected on ${name} (port ${socket.localPort})`);
// socket.setEncoding('utf8');
// // if (dataHandler)
// socket.on('data', (data:string) => dataHandler(data));
// socket.on('error', (err:any) => this.onCoqTopError(err.toString() + ` (${name})`));
resolve(socket);
});
});
}
private findWrapper() : string|null {
const autoWrapper = path.join(__dirname, '../../../', 'coqtopw.exe');
if(this.settings.wrapper && this.settings.wrapper !== "" && fs.existsSync(this.settings.wrapper))
return this.settings.wrapper;
else if(this.settings.autoUseWrapper && os.platform() === 'win32' && fs.existsSync(autoWrapper))
return autoWrapper;
else
return null;
}
public getVersion() {
return this.coqtopVersion;
}
// public async resetCoq(settings?: CoqTopSettings) : Promise<InitResult> {
// if(settings)
// this.settings = settings;
// this.console.log('reset');
// this.cleanup(undefined);
// this.coqtopVersion = await coqtop.detectVersion(this.coqtopBin, this.projectRoot, this.console);
// if(this.coqtopVersion)
// this.console.log(`Detected coqtop version ${this.coqtopVersion}`)
// else
// this.console.warn(`Could not detect coqtop version`)
// const wrapper = this.findWrapper();
// if (wrapper !== null)
// await this.setupCoqTop(wrapper);
// else
// await this.setupCoqTopReadAndWritePorts();
// return await this.coqInit();
// }
private async setupCoqTop(wrapper: string|null) : Promise<void> {
await Promise.all(this.readyToListen);
var mainAddr = this.mainChannelServer.address();
var controlAddr = this.controlChannelServer.address();
var mainAddressArg = mainAddr.address + ':' + mainAddr.port;
var controlAddressArg = controlAddr.address + ':' + controlAddr.port;
try {
const scriptUri = decodeURIComponent(this.scriptFile);
if(wrapper !== null) {
const traceFile = (scriptUri.startsWith("file:///") && this.settings.traceXmlProtocol)
? scriptUri.substring("file:///".length) + ".coq-trace.xml"
: undefined;
this.startCoqTop(this.spawnCoqTopWrapper(wrapper, mainAddressArg, controlAddressArg, traceFile));
} else
this.startCoqTop(this.spawnCoqTop(mainAddressArg, controlAddressArg));
} catch(error) {
this.console.error('Could not spawn coqtop: ' + error);
throw new CoqtopSpawnError(this.coqtopBin, error);
}
let channels = await Promise.all([
this.acceptConnection(this.mainChannelServer, 'main channel'), //, 'main channel R', (data) => this.onMainChannelR(data)),
this.acceptConnection(this.controlChannelServer, 'control channel'),
]);
this.connect(this.coqtopVersion, channels[0], channels[0], channels[1], channels[1])
}
/** Start coqtop.
* Use two ports: one for reading & one for writing; i.e. HOST:READPORT:WRITEPORT
*/
private async setupCoqTopReadAndWritePorts() : Promise<void> {
await Promise.all(this.readyToListen);
var mainAddr = this.mainChannelServer.address();
var mainPortW = this.mainChannelServer2.address().port;
var controlAddr = this.controlChannelServer.address();
var controlPortW = this.controlChannelServer2.address().port;
var mainAddressArg = mainAddr.address + ':' + mainAddr.port + ':' + mainPortW;
var controlAddressArg = controlAddr.address + ':' + controlAddr.port + ':' + controlPortW;
try {
this.startCoqTop(this.spawnCoqTop(mainAddressArg, controlAddressArg));
} catch(error) {
this.console.error('Could not spawn coqtop: ' + error);
throw new CoqtopSpawnError(this.coqtopBin, error);
}
let channels = await Promise.all([
this.acceptConnection(this.mainChannelServer, 'main channel R'), //, 'main channel R', (data) => this.onMainChannelR(data)),
this.acceptConnection(this.mainChannelServer2, 'main channel W'),
this.acceptConnection(this.controlChannelServer, 'control channel R'),
this.acceptConnection(this.controlChannelServer2, 'control channel W'),
]);
this.connect(this.coqtopVersion, channels[0], channels[1], channels[2], channels[3])
}
private startCoqTop(process : ChildProcess) {
this.coqtopProc = process;
this.console.log(`coqtop started with pid ${this.coqtopProc.pid}`);
this.coqtopProc.stdout.on('data', (data:string) => this.coqtopOut(data))
this.coqtopProc.on('exit', (code:number) => {
this.console.log('coqtop exited with code: ' + code);
if(this.isRunning() && this.callbacks.onClosed)
this.callbacks.onClosed(false, 'coqtop closed with code: ' + code);
this.dispose();
});
this.coqtopProc.stderr.on('data', (data:string) => {
this.console.log('coqtop-stderr: ' + data);
});
this.coqtopProc.on('close', (code:number) => {
this.console.log('coqtop closed with code: ' + code);
if(this.isRunning() && this.callbacks.onClosed)
this.callbacks.onClosed(false, 'coqtop closed with code: ' + code);
this.dispose();
});
this.coqtopProc.on('error', (code:number) => {
this.console.log('coqtop could not be started: ' + code);
if(this.isRunning() && this.callbacks.onClosed)
this.callbacks.onClosed(true, 'coqtop closed with code: ' + code);
this.dispose();
});
// this.coqtopProc.stdin.write('\n');
}
private coqtopOut(data:string) {
this.console.log('coqtop-stdout:' + data);
}
private get coqtopBin() {
return path.join(this.settings.binPath.trim(), 'coqtop');
}
private spawnCoqTop(mainAddr : string, controlAddr: string) {
var coqtopModule = this.coqtopBin;
// var coqtopModule = 'cmd';
var args = [
// '/D /C', this.coqPath + '/coqtop.exe',
'-main-channel', mainAddr,
'-control-channel', controlAddr,
'-ideslave',
'-async-proofs', 'on'
].concat(this.settings.args);
this.console.log('exec: ' + coqtopModule + ' ' + args.join(' '));
return spawn(coqtopModule, args, {detached: false, cwd: this.projectRoot});
}
private spawnCoqTopWrapper(wrapper: string, mainAddr : string, controlAddr: string, traceFile?: string) : ChildProcess {
this.useInterruptMessage = true;
var coqtopModule = wrapper;
var args = [
// '/D /C', this.coqPath + '/coqtop.exe',
'-coqtopbin', this.coqtopBin,
'-main-channel', mainAddr,
'-control-channel', controlAddr,
'-ideslave',
'-async-proofs', 'on'
]
.concat(traceFile ? ['-tracefile', traceFile] : [])
.concat(this.settings.args);
this.console.log('exec: ' + coqtopModule + ' ' + args.join(' '));
return spawn(coqtopModule, args, {detached: false, cwd: this.projectRoot});
}
public /* override */ async coqInterrupt() : Promise<boolean> {
if(!this.coqtopProc)
return false;
else if(!super.coqInterrupt()) {
this.console.log('--------------------------------');
this.console.log('Sending SIGINT');
this.coqtopProc.kill("SIGINT");
return true;
}
}
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.