text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import {
HeaderParamExistingKeyOptionalParams,
HeaderResponseExistingKeyOptionalParams,
HeaderResponseExistingKeyResponse,
HeaderParamProtectedKeyOptionalParams,
HeaderResponseProtectedKeyOptionalParams,
HeaderResponseProtectedKeyResponse,
HeaderParamIntegerOptionalParams,
HeaderResponseIntegerOptionalParams,
HeaderResponseIntegerResponse,
HeaderParamLongOptionalParams,
HeaderResponseLongOptionalParams,
HeaderResponseLongResponse,
HeaderParamFloatOptionalParams,
HeaderResponseFloatOptionalParams,
HeaderResponseFloatResponse,
HeaderParamDoubleOptionalParams,
HeaderResponseDoubleOptionalParams,
HeaderResponseDoubleResponse,
HeaderParamBoolOptionalParams,
HeaderResponseBoolOptionalParams,
HeaderResponseBoolResponse,
HeaderParamStringOptionalParams,
HeaderResponseStringOptionalParams,
HeaderResponseStringResponse,
HeaderParamDateOptionalParams,
HeaderResponseDateOptionalParams,
HeaderResponseDateResponse,
HeaderParamDatetimeOptionalParams,
HeaderResponseDatetimeOptionalParams,
HeaderResponseDatetimeResponse,
HeaderParamDatetimeRfc1123OptionalParams,
HeaderResponseDatetimeRfc1123OptionalParams,
HeaderResponseDatetimeRfc1123Response,
HeaderParamDurationOptionalParams,
HeaderResponseDurationOptionalParams,
HeaderResponseDurationResponse,
HeaderParamByteOptionalParams,
HeaderResponseByteOptionalParams,
HeaderResponseByteResponse,
HeaderParamEnumOptionalParams,
HeaderResponseEnumOptionalParams,
HeaderResponseEnumResponse,
HeaderCustomRequestIdOptionalParams
} from "../models";
/** Interface representing a Header. */
export interface Header {
/**
* Send a post request with header value "User-Agent": "overwrite"
* @param userAgent Send a post request with header value "User-Agent": "overwrite"
* @param options The options parameters.
*/
paramExistingKey(
userAgent: string,
options?: HeaderParamExistingKeyOptionalParams
): Promise<void>;
/**
* Get a response with header value "User-Agent": "overwrite"
* @param options The options parameters.
*/
responseExistingKey(
options?: HeaderResponseExistingKeyOptionalParams
): Promise<HeaderResponseExistingKeyResponse>;
/**
* Send a post request with header value "Content-Type": "text/html"
* @param contentType Send a post request with header value "Content-Type": "text/html"
* @param options The options parameters.
*/
paramProtectedKey(
contentType: string,
options?: HeaderParamProtectedKeyOptionalParams
): Promise<void>;
/**
* Get a response with header value "Content-Type": "text/html"
* @param options The options parameters.
*/
responseProtectedKey(
options?: HeaderResponseProtectedKeyOptionalParams
): Promise<HeaderResponseProtectedKeyResponse>;
/**
* Send a post request with header values "scenario": "positive", "value": 1 or "scenario": "negative",
* "value": -2
* @param scenario Send a post request with header values "scenario": "positive" or "negative"
* @param value Send a post request with header values 1 or -2
* @param options The options parameters.
*/
paramInteger(
scenario: string,
value: number,
options?: HeaderParamIntegerOptionalParams
): Promise<void>;
/**
* Get a response with header value "value": 1 or -2
* @param scenario Send a post request with header values "scenario": "positive" or "negative"
* @param options The options parameters.
*/
responseInteger(
scenario: string,
options?: HeaderResponseIntegerOptionalParams
): Promise<HeaderResponseIntegerResponse>;
/**
* Send a post request with header values "scenario": "positive", "value": 105 or "scenario":
* "negative", "value": -2
* @param scenario Send a post request with header values "scenario": "positive" or "negative"
* @param value Send a post request with header values 105 or -2
* @param options The options parameters.
*/
paramLong(
scenario: string,
value: number,
options?: HeaderParamLongOptionalParams
): Promise<void>;
/**
* Get a response with header value "value": 105 or -2
* @param scenario Send a post request with header values "scenario": "positive" or "negative"
* @param options The options parameters.
*/
responseLong(
scenario: string,
options?: HeaderResponseLongOptionalParams
): Promise<HeaderResponseLongResponse>;
/**
* Send a post request with header values "scenario": "positive", "value": 0.07 or "scenario":
* "negative", "value": -3.0
* @param scenario Send a post request with header values "scenario": "positive" or "negative"
* @param value Send a post request with header values 0.07 or -3.0
* @param options The options parameters.
*/
paramFloat(
scenario: string,
value: number,
options?: HeaderParamFloatOptionalParams
): Promise<void>;
/**
* Get a response with header value "value": 0.07 or -3.0
* @param scenario Send a post request with header values "scenario": "positive" or "negative"
* @param options The options parameters.
*/
responseFloat(
scenario: string,
options?: HeaderResponseFloatOptionalParams
): Promise<HeaderResponseFloatResponse>;
/**
* Send a post request with header values "scenario": "positive", "value": 7e120 or "scenario":
* "negative", "value": -3.0
* @param scenario Send a post request with header values "scenario": "positive" or "negative"
* @param value Send a post request with header values 7e120 or -3.0
* @param options The options parameters.
*/
paramDouble(
scenario: string,
value: number,
options?: HeaderParamDoubleOptionalParams
): Promise<void>;
/**
* Get a response with header value "value": 7e120 or -3.0
* @param scenario Send a post request with header values "scenario": "positive" or "negative"
* @param options The options parameters.
*/
responseDouble(
scenario: string,
options?: HeaderResponseDoubleOptionalParams
): Promise<HeaderResponseDoubleResponse>;
/**
* Send a post request with header values "scenario": "true", "value": true or "scenario": "false",
* "value": false
* @param scenario Send a post request with header values "scenario": "true" or "false"
* @param value Send a post request with header values true or false
* @param options The options parameters.
*/
paramBool(
scenario: string,
value: boolean,
options?: HeaderParamBoolOptionalParams
): Promise<void>;
/**
* Get a response with header value "value": true or false
* @param scenario Send a post request with header values "scenario": "true" or "false"
* @param options The options parameters.
*/
responseBool(
scenario: string,
options?: HeaderResponseBoolOptionalParams
): Promise<HeaderResponseBoolResponse>;
/**
* Send a post request with header values "scenario": "valid", "value": "The quick brown fox jumps over
* the lazy dog" or "scenario": "null", "value": null or "scenario": "empty", "value": ""
* @param scenario Send a post request with header values "scenario": "valid" or "null" or "empty"
* @param options The options parameters.
*/
paramString(
scenario: string,
options?: HeaderParamStringOptionalParams
): Promise<void>;
/**
* Get a response with header values "The quick brown fox jumps over the lazy dog" or null or ""
* @param scenario Send a post request with header values "scenario": "valid" or "null" or "empty"
* @param options The options parameters.
*/
responseString(
scenario: string,
options?: HeaderResponseStringOptionalParams
): Promise<HeaderResponseStringResponse>;
/**
* Send a post request with header values "scenario": "valid", "value": "2010-01-01" or "scenario":
* "min", "value": "0001-01-01"
* @param scenario Send a post request with header values "scenario": "valid" or "min"
* @param value Send a post request with header values "2010-01-01" or "0001-01-01"
* @param options The options parameters.
*/
paramDate(
scenario: string,
value: Date,
options?: HeaderParamDateOptionalParams
): Promise<void>;
/**
* Get a response with header values "2010-01-01" or "0001-01-01"
* @param scenario Send a post request with header values "scenario": "valid" or "min"
* @param options The options parameters.
*/
responseDate(
scenario: string,
options?: HeaderResponseDateOptionalParams
): Promise<HeaderResponseDateResponse>;
/**
* Send a post request with header values "scenario": "valid", "value": "2010-01-01T12:34:56Z" or
* "scenario": "min", "value": "0001-01-01T00:00:00Z"
* @param scenario Send a post request with header values "scenario": "valid" or "min"
* @param value Send a post request with header values "2010-01-01T12:34:56Z" or "0001-01-01T00:00:00Z"
* @param options The options parameters.
*/
paramDatetime(
scenario: string,
value: Date,
options?: HeaderParamDatetimeOptionalParams
): Promise<void>;
/**
* Get a response with header values "2010-01-01T12:34:56Z" or "0001-01-01T00:00:00Z"
* @param scenario Send a post request with header values "scenario": "valid" or "min"
* @param options The options parameters.
*/
responseDatetime(
scenario: string,
options?: HeaderResponseDatetimeOptionalParams
): Promise<HeaderResponseDatetimeResponse>;
/**
* Send a post request with header values "scenario": "valid", "value": "Wed, 01 Jan 2010 12:34:56 GMT"
* or "scenario": "min", "value": "Mon, 01 Jan 0001 00:00:00 GMT"
* @param scenario Send a post request with header values "scenario": "valid" or "min"
* @param options The options parameters.
*/
paramDatetimeRfc1123(
scenario: string,
options?: HeaderParamDatetimeRfc1123OptionalParams
): Promise<void>;
/**
* Get a response with header values "Wed, 01 Jan 2010 12:34:56 GMT" or "Mon, 01 Jan 0001 00:00:00 GMT"
* @param scenario Send a post request with header values "scenario": "valid" or "min"
* @param options The options parameters.
*/
responseDatetimeRfc1123(
scenario: string,
options?: HeaderResponseDatetimeRfc1123OptionalParams
): Promise<HeaderResponseDatetimeRfc1123Response>;
/**
* Send a post request with header values "scenario": "valid", "value": "P123DT22H14M12.011S"
* @param scenario Send a post request with header values "scenario": "valid"
* @param value Send a post request with header values "P123DT22H14M12.011S"
* @param options The options parameters.
*/
paramDuration(
scenario: string,
value: string,
options?: HeaderParamDurationOptionalParams
): Promise<void>;
/**
* Get a response with header values "P123DT22H14M12.011S"
* @param scenario Send a post request with header values "scenario": "valid"
* @param options The options parameters.
*/
responseDuration(
scenario: string,
options?: HeaderResponseDurationOptionalParams
): Promise<HeaderResponseDurationResponse>;
/**
* Send a post request with header values "scenario": "valid", "value": "啊齄丂狛狜隣郎隣兀﨩"
* @param scenario Send a post request with header values "scenario": "valid"
* @param value Send a post request with header values "啊齄丂狛狜隣郎隣兀﨩"
* @param options The options parameters.
*/
paramByte(
scenario: string,
value: Uint8Array,
options?: HeaderParamByteOptionalParams
): Promise<void>;
/**
* Get a response with header values "啊齄丂狛狜隣郎隣兀﨩"
* @param scenario Send a post request with header values "scenario": "valid"
* @param options The options parameters.
*/
responseByte(
scenario: string,
options?: HeaderResponseByteOptionalParams
): Promise<HeaderResponseByteResponse>;
/**
* Send a post request with header values "scenario": "valid", "value": "GREY" or "scenario": "null",
* "value": null
* @param scenario Send a post request with header values "scenario": "valid" or "null" or "empty"
* @param options The options parameters.
*/
paramEnum(
scenario: string,
options?: HeaderParamEnumOptionalParams
): Promise<void>;
/**
* Get a response with header values "GREY" or null
* @param scenario Send a post request with header values "scenario": "valid" or "null" or "empty"
* @param options The options parameters.
*/
responseEnum(
scenario: string,
options?: HeaderResponseEnumOptionalParams
): Promise<HeaderResponseEnumResponse>;
/**
* Send x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the header of the request
* @param options The options parameters.
*/
customRequestId(options?: HeaderCustomRequestIdOptionalParams): Promise<void>;
} | the_stack |
import { AzureLogger } from "@azure/logger";
import { AbortController } from "@azure/abort-controller";
import { assert } from "chai";
import * as sinon from "sinon";
import {
createPipelineRequest,
SendRequest,
PipelineResponse,
createHttpHeaders,
RestError,
retryPolicy,
} from "../src";
describe("retryPolicy", function () {
afterEach(function () {
sinon.restore();
});
it("It should allow passing custom retry strategies", async () => {
const request = createPipelineRequest({
url: "https://bing.com",
});
const testError = new RestError("Test Error!", { code: "ENOENT" });
const successResponse: PipelineResponse = {
headers: createHttpHeaders(),
request,
status: 200,
};
const policy = retryPolicy([
{
name: "testRetryStrategy",
retry({ responseError }) {
if (responseError?.code !== "ENOENT") {
return { skipStrategy: true };
}
return {
retryAfterInMs: 100,
};
},
},
]);
const next = sinon.stub<Parameters<SendRequest>, ReturnType<SendRequest>>();
next.onFirstCall().rejects(testError);
next.onSecondCall().resolves(successResponse);
const clock = sinon.useFakeTimers();
const promise = policy.sendRequest(request, next);
assert.isTrue(next.calledOnce);
// allow the delay to occur
const time = await clock.nextAsync();
// should be at least the standard delay
assert.isAtLeast(time, 100);
assert.isTrue(next.calledTwice);
const result = await promise;
assert.strictEqual(result, successResponse);
});
it("It should give up after the default maxRetries is reached", async () => {
const request = createPipelineRequest({
url: "https://bing.com",
});
const testError = new RestError("Test Error!", { code: "ENOENT" });
const policy = retryPolicy([
{
name: "testRetryStrategy",
retry({ responseError }) {
if (responseError?.code !== "ENOENT") {
return { skipStrategy: true };
}
return {
retryAfterInMs: 100,
};
},
},
]);
const next = sinon.stub<Parameters<SendRequest>, ReturnType<SendRequest>>();
next.rejects(testError);
const clock = sinon.useFakeTimers();
let catchCalled = false;
const promise = policy.sendRequest(request, next);
promise.catch((e) => {
catchCalled = true;
assert.strictEqual(e, testError);
});
await clock.runAllAsync();
// should be one more than the default retry count
assert.strictEqual(next.callCount, 11);
assert.isTrue(catchCalled);
});
it("It should give up after maxRetries is changed", async () => {
const request = createPipelineRequest({
url: "https://bing.com",
});
const testError = new RestError("Test Error!", { code: "ENOENT" });
const policy = retryPolicy(
[
{
name: "testRetryStrategy",
retry({ responseError }) {
if (responseError?.code !== "ENOENT") {
return { skipStrategy: true };
}
return {
retryAfterInMs: 100,
};
},
},
],
{
maxRetries: 10,
}
);
const next = sinon.stub<Parameters<SendRequest>, ReturnType<SendRequest>>();
next.rejects(testError);
const clock = sinon.useFakeTimers();
let catchCalled = false;
const promise = policy.sendRequest(request, next);
promise.catch((e) => {
catchCalled = true;
assert.strictEqual(e, testError);
});
await clock.runAllAsync();
// should be one more than the default retry count
assert.strictEqual(next.callCount, 11);
assert.isTrue(catchCalled);
});
it("It should allow redirecting on the next retry", async () => {
const request = createPipelineRequest({
url: "https://bing.com",
});
const testError = new RestError("Test Error!", { code: "ENOENT" });
const policy = retryPolicy([
{
name: "testRetryStrategy",
retry({ responseError }) {
if (responseError?.code !== "ENOENT") {
return { skipStrategy: true };
}
return {
redirectTo: "https://not-bing.com",
};
},
},
]);
const next = sinon.stub<Parameters<SendRequest>, ReturnType<SendRequest>>();
next.rejects(testError);
const clock = sinon.useFakeTimers();
let catchCalled = false;
const promise = policy.sendRequest(request, next);
promise.catch((e) => {
catchCalled = true;
assert.strictEqual(e, testError);
});
await clock.runAllAsync();
// should be one more than the default retry count
assert.strictEqual(next.callCount, 11);
assert.isTrue(catchCalled);
assert.strictEqual(request.url, "https://not-bing.com");
});
it("It should allow throwing new errors", async () => {
const request = createPipelineRequest({
url: "https://bing.com",
});
const testError = new RestError("Test Error!", { code: "ENOENT" });
const retryError = new RestError("Test Retry Error!");
const policy = retryPolicy([
{
name: "testRetryStrategy",
retry({ responseError }) {
if (responseError?.code !== "ENOENT") {
return { skipStrategy: true };
}
return {
errorToThrow: retryError,
};
},
},
]);
const next = sinon.stub<Parameters<SendRequest>, ReturnType<SendRequest>>();
next.rejects(testError);
const clock = sinon.useFakeTimers();
let catchCalled = false;
const promise = policy.sendRequest(request, next);
promise.catch((e) => {
catchCalled = true;
assert.strictEqual(e, retryError);
});
await clock.runAllAsync();
// should be one more than the default retry count
assert.strictEqual(next.callCount, 1);
assert.isTrue(catchCalled);
});
function makeTestLogger(): { logger: AzureLogger; params: { info: string[]; error: string[] } } {
const logParams: {
info: string[];
error: string[];
} = {
info: [],
error: [],
};
const logger: AzureLogger = {
info(...params) {
logParams.info.push(params.join(" "));
},
error(...params) {
logParams.error.push(params.join(" "));
},
} as AzureLogger;
return {
logger,
params: logParams,
};
}
it("It should log consistent messages", async () => {
const request = createPipelineRequest({
url: "https://bing.com",
});
const testError = new RestError("Test Error!", { code: "ENOENT" });
const policyLogger = makeTestLogger();
const strategyLogger = makeTestLogger();
const policy = retryPolicy(
[
{
name: "testRetryStrategy",
logger: strategyLogger.logger,
retry({ responseError }) {
if (responseError?.code !== "ENOENT") {
return { skipStrategy: true };
}
return {
retryAfterInMs: 100,
};
},
},
],
{
logger: policyLogger.logger,
}
);
const next = sinon.stub<Parameters<SendRequest>, ReturnType<SendRequest>>();
next.rejects(testError);
const clock = sinon.useFakeTimers();
let catchCalled = false;
const promise = policy.sendRequest(request, next);
promise.catch((e) => {
catchCalled = true;
assert.strictEqual(e, testError);
});
await clock.runAllAsync();
// should be one more than the default retry count
assert.strictEqual(next.callCount, 11);
assert.isTrue(catchCalled);
assert.deepEqual(
policyLogger.params.info.map((x) => x.replace(/ request .*/g, " request [Request Id]")),
[
"Retry 0: Attempting to send request [Request Id]",
"Retry 0: Processing 1 retry strategies.",
"Retry 1: Attempting to send request [Request Id]",
"Retry 1: Processing 1 retry strategies.",
"Retry 2: Attempting to send request [Request Id]",
"Retry 2: Processing 1 retry strategies.",
"Retry 3: Attempting to send request [Request Id]",
"Retry 3: Processing 1 retry strategies.",
"Retry 4: Attempting to send request [Request Id]",
"Retry 4: Processing 1 retry strategies.",
"Retry 5: Attempting to send request [Request Id]",
"Retry 5: Processing 1 retry strategies.",
"Retry 6: Attempting to send request [Request Id]",
"Retry 6: Processing 1 retry strategies.",
"Retry 7: Attempting to send request [Request Id]",
"Retry 7: Processing 1 retry strategies.",
"Retry 8: Attempting to send request [Request Id]",
"Retry 8: Processing 1 retry strategies.",
"Retry 9: Attempting to send request [Request Id]",
"Retry 9: Processing 1 retry strategies.",
"Retry 10: Attempting to send request [Request Id]",
"Retry 10: Maximum retries reached. Returning the last received response, or throwing the last received error.",
]
);
assert.deepEqual(
policyLogger.params.error.map((x) => x.replace(/ request .*/g, " request [Request Id]")),
[
"Retry 0: Received an error from request [Request Id]",
"Retry 1: Received an error from request [Request Id]",
"Retry 2: Received an error from request [Request Id]",
"Retry 3: Received an error from request [Request Id]",
"Retry 4: Received an error from request [Request Id]",
"Retry 5: Received an error from request [Request Id]",
"Retry 6: Received an error from request [Request Id]",
"Retry 7: Received an error from request [Request Id]",
"Retry 8: Received an error from request [Request Id]",
"Retry 9: Received an error from request [Request Id]",
"Retry 10: Received an error from request [Request Id]",
]
);
assert.deepEqual(strategyLogger.params, {
info: [
"Retry 0: Processing retry strategy testRetryStrategy.",
"Retry 0: Retry strategy testRetryStrategy retries after 100",
"Retry 1: Processing retry strategy testRetryStrategy.",
"Retry 1: Retry strategy testRetryStrategy retries after 100",
"Retry 2: Processing retry strategy testRetryStrategy.",
"Retry 2: Retry strategy testRetryStrategy retries after 100",
"Retry 3: Processing retry strategy testRetryStrategy.",
"Retry 3: Retry strategy testRetryStrategy retries after 100",
"Retry 4: Processing retry strategy testRetryStrategy.",
"Retry 4: Retry strategy testRetryStrategy retries after 100",
"Retry 5: Processing retry strategy testRetryStrategy.",
"Retry 5: Retry strategy testRetryStrategy retries after 100",
"Retry 6: Processing retry strategy testRetryStrategy.",
"Retry 6: Retry strategy testRetryStrategy retries after 100",
"Retry 7: Processing retry strategy testRetryStrategy.",
"Retry 7: Retry strategy testRetryStrategy retries after 100",
"Retry 8: Processing retry strategy testRetryStrategy.",
"Retry 8: Retry strategy testRetryStrategy retries after 100",
"Retry 9: Processing retry strategy testRetryStrategy.",
"Retry 9: Retry strategy testRetryStrategy retries after 100",
],
error: [],
});
});
it("It should log when the policy requirements are unmet", async () => {
const request = createPipelineRequest({
url: "https://bing.com",
});
const testError = new RestError("Test Error!", { code: "NOT-ENOENT" });
const policyLogger = makeTestLogger();
const strategyLogger = makeTestLogger();
const policy = retryPolicy(
[
{
name: "testRetryStrategy",
logger: strategyLogger.logger,
retry({ responseError }) {
if (responseError?.code !== "ENOENT") {
return { skipStrategy: true };
}
return {
retryAfterInMs: 100,
};
},
},
],
{
logger: policyLogger.logger,
}
);
const next = sinon.stub<Parameters<SendRequest>, ReturnType<SendRequest>>();
next.rejects(testError);
const clock = sinon.useFakeTimers();
let catchCalled = false;
const promise = policy.sendRequest(request, next);
promise.catch((e) => {
catchCalled = true;
assert.strictEqual(e, testError);
});
await clock.runAllAsync();
// should be one more than the default retry count
assert.strictEqual(next.callCount, 11);
assert.isTrue(catchCalled);
assert.deepEqual(
policyLogger.params.info.map((x) => x.replace(/ request .*/g, " request [Request Id]")),
[
"Retry 0: Attempting to send request [Request Id]",
"Retry 0: Processing 1 retry strategies.",
"Retry 1: Attempting to send request [Request Id]",
"Retry 1: Processing 1 retry strategies.",
"Retry 2: Attempting to send request [Request Id]",
"Retry 2: Processing 1 retry strategies.",
"Retry 3: Attempting to send request [Request Id]",
"Retry 3: Processing 1 retry strategies.",
"Retry 4: Attempting to send request [Request Id]",
"Retry 4: Processing 1 retry strategies.",
"Retry 5: Attempting to send request [Request Id]",
"Retry 5: Processing 1 retry strategies.",
"Retry 6: Attempting to send request [Request Id]",
"Retry 6: Processing 1 retry strategies.",
"Retry 7: Attempting to send request [Request Id]",
"Retry 7: Processing 1 retry strategies.",
"Retry 8: Attempting to send request [Request Id]",
"Retry 8: Processing 1 retry strategies.",
"Retry 9: Attempting to send request [Request Id]",
"Retry 9: Processing 1 retry strategies.",
"Retry 10: Attempting to send request [Request Id]",
"Retry 10: Maximum retries reached. Returning the last received response, or throwing the last received error.",
]
);
assert.deepEqual(
policyLogger.params.error.map((x) => x.replace(/ request .*/g, " request [Request Id]")),
[
"Retry 0: Received an error from request [Request Id]",
"Retry 1: Received an error from request [Request Id]",
"Retry 2: Received an error from request [Request Id]",
"Retry 3: Received an error from request [Request Id]",
"Retry 4: Received an error from request [Request Id]",
"Retry 5: Received an error from request [Request Id]",
"Retry 6: Received an error from request [Request Id]",
"Retry 7: Received an error from request [Request Id]",
"Retry 8: Received an error from request [Request Id]",
"Retry 9: Received an error from request [Request Id]",
"Retry 10: Received an error from request [Request Id]",
]
);
assert.deepEqual(strategyLogger.params, {
info: [
"Retry 0: Processing retry strategy testRetryStrategy.",
"Retry 0: Skipped.",
"Retry 1: Processing retry strategy testRetryStrategy.",
"Retry 1: Skipped.",
"Retry 2: Processing retry strategy testRetryStrategy.",
"Retry 2: Skipped.",
"Retry 3: Processing retry strategy testRetryStrategy.",
"Retry 3: Skipped.",
"Retry 4: Processing retry strategy testRetryStrategy.",
"Retry 4: Skipped.",
"Retry 5: Processing retry strategy testRetryStrategy.",
"Retry 5: Skipped.",
"Retry 6: Processing retry strategy testRetryStrategy.",
"Retry 6: Skipped.",
"Retry 7: Processing retry strategy testRetryStrategy.",
"Retry 7: Skipped.",
"Retry 8: Processing retry strategy testRetryStrategy.",
"Retry 8: Skipped.",
"Retry 9: Processing retry strategy testRetryStrategy.",
"Retry 9: Skipped.",
],
error: [],
});
});
it("It should log when the abort controller aborts", async () => {
const request = createPipelineRequest({
url: "https://bing.com",
});
const abortController = new AbortController();
request.abortSignal = abortController.signal;
const testError = new RestError("Test Error!", { code: "ENOENT" });
const policyLogger = makeTestLogger();
const strategyLogger = makeTestLogger();
const policy = retryPolicy(
[
{
name: "testRetryStrategy",
logger: strategyLogger.logger,
retry() {
return {
retryAfterInMs: 100,
};
},
},
],
{
logger: policyLogger.logger,
}
);
const next = sinon.stub<Parameters<SendRequest>, ReturnType<SendRequest>>();
next.rejects(testError);
abortController.abort();
let catchCalled = false;
const promise = policy.sendRequest(request, next);
await promise.catch((e) => {
catchCalled = true;
assert.strictEqual(e.name, "AbortError");
});
// should be one more than the default retry count
assert.strictEqual(next.callCount, 1);
assert.isTrue(catchCalled);
assert.deepEqual(
policyLogger.params.info.map((x) => x.replace(/ request .*/g, " request [Request Id]")),
["Retry 0: Attempting to send request [Request Id]"]
);
assert.deepEqual(
policyLogger.params.error.map((x) => x.replace(/ request .*/g, " request [Request Id]")),
["Retry 0: Received an error from request [Request Id]", "Retry 0: Request aborted."]
);
assert.deepEqual(strategyLogger.params, {
info: [],
error: [],
});
});
it("It should log when the retry strategy throws with an error", async () => {
const request = createPipelineRequest({
url: "https://bing.com",
});
const testError = new RestError("Test Error!", { code: "ENOENT" });
const retryError = new RestError("Test Retry Error!");
const policyLogger = makeTestLogger();
const strategyLogger = makeTestLogger();
const policy = retryPolicy(
[
{
name: "testRetryStrategy",
logger: strategyLogger.logger,
retry({ responseError }) {
if (responseError?.code !== "ENOENT") {
return { skipStrategy: true };
}
return {
errorToThrow: retryError,
};
},
},
],
{
logger: policyLogger.logger,
}
);
const next = sinon.stub<Parameters<SendRequest>, ReturnType<SendRequest>>();
next.rejects(testError);
const clock = sinon.useFakeTimers();
let catchCalled = false;
const promise = policy.sendRequest(request, next);
promise.catch((e) => {
catchCalled = true;
assert.strictEqual(e, retryError);
});
await clock.runAllAsync();
// should be one more than the default retry count
assert.strictEqual(next.callCount, 1);
assert.isTrue(catchCalled);
assert.deepEqual(
policyLogger.params.info.map((x) => x.replace(/ request .*/g, " request [Request Id]")),
[
"Retry 0: Attempting to send request [Request Id]",
"Retry 0: Processing 1 retry strategies.",
]
);
assert.deepEqual(
policyLogger.params.error.map((x) => x.replace(/ request .*/g, " request [Request Id]")),
["Retry 0: Received an error from request [Request Id]"]
);
assert.deepEqual(strategyLogger.params, {
info: ["Retry 0: Processing retry strategy testRetryStrategy."],
error: [
"Retry 0: Retry strategy testRetryStrategy throws error: RestError: Test Retry Error!",
],
});
});
it("It should log when the retry strategy redirects to another URL", async () => {
const request = createPipelineRequest({
url: "https://bing.com",
});
const testError = new RestError("Test Error!", { code: "ENOENT" });
const policyLogger = makeTestLogger();
const strategyLogger = makeTestLogger();
const policy = retryPolicy(
[
{
name: "testRetryStrategy",
logger: strategyLogger.logger,
retry({ responseError }) {
if (responseError?.code !== "ENOENT") {
return { skipStrategy: true };
}
return {
redirectTo: "https://not-bing.com",
};
},
},
],
{
logger: policyLogger.logger,
}
);
const next = sinon.stub<Parameters<SendRequest>, ReturnType<SendRequest>>();
next.rejects(testError);
const clock = sinon.useFakeTimers();
let catchCalled = false;
const promise = policy.sendRequest(request, next);
promise.catch((e) => {
catchCalled = true;
assert.strictEqual(e, testError);
});
await clock.runAllAsync();
// should be one more than the default retry count
assert.strictEqual(next.callCount, 11);
assert.isTrue(catchCalled);
assert.strictEqual(request.url, "https://not-bing.com");
assert.deepEqual(
policyLogger.params.info.map((x) => x.replace(/ request .*/g, " request [Request Id]")),
[
"Retry 0: Attempting to send request [Request Id]",
"Retry 0: Processing 1 retry strategies.",
"Retry 1: Attempting to send request [Request Id]",
"Retry 1: Processing 1 retry strategies.",
"Retry 2: Attempting to send request [Request Id]",
"Retry 2: Processing 1 retry strategies.",
"Retry 3: Attempting to send request [Request Id]",
"Retry 3: Processing 1 retry strategies.",
"Retry 4: Attempting to send request [Request Id]",
"Retry 4: Processing 1 retry strategies.",
"Retry 5: Attempting to send request [Request Id]",
"Retry 5: Processing 1 retry strategies.",
"Retry 6: Attempting to send request [Request Id]",
"Retry 6: Processing 1 retry strategies.",
"Retry 7: Attempting to send request [Request Id]",
"Retry 7: Processing 1 retry strategies.",
"Retry 8: Attempting to send request [Request Id]",
"Retry 8: Processing 1 retry strategies.",
"Retry 9: Attempting to send request [Request Id]",
"Retry 9: Processing 1 retry strategies.",
"Retry 10: Attempting to send request [Request Id]",
"Retry 10: Maximum retries reached. Returning the last received response, or throwing the last received error.",
]
);
assert.deepEqual(
policyLogger.params.error.map((x) => x.replace(/ request .*/g, " request [Request Id]")),
[
"Retry 0: Received an error from request [Request Id]",
"Retry 1: Received an error from request [Request Id]",
"Retry 2: Received an error from request [Request Id]",
"Retry 3: Received an error from request [Request Id]",
"Retry 4: Received an error from request [Request Id]",
"Retry 5: Received an error from request [Request Id]",
"Retry 6: Received an error from request [Request Id]",
"Retry 7: Received an error from request [Request Id]",
"Retry 8: Received an error from request [Request Id]",
"Retry 9: Received an error from request [Request Id]",
"Retry 10: Received an error from request [Request Id]",
]
);
assert.deepEqual(strategyLogger.params, {
info: [
"Retry 0: Processing retry strategy testRetryStrategy.",
"Retry 0: Retry strategy testRetryStrategy redirects to https://not-bing.com",
"Retry 1: Processing retry strategy testRetryStrategy.",
"Retry 1: Retry strategy testRetryStrategy redirects to https://not-bing.com",
"Retry 2: Processing retry strategy testRetryStrategy.",
"Retry 2: Retry strategy testRetryStrategy redirects to https://not-bing.com",
"Retry 3: Processing retry strategy testRetryStrategy.",
"Retry 3: Retry strategy testRetryStrategy redirects to https://not-bing.com",
"Retry 4: Processing retry strategy testRetryStrategy.",
"Retry 4: Retry strategy testRetryStrategy redirects to https://not-bing.com",
"Retry 5: Processing retry strategy testRetryStrategy.",
"Retry 5: Retry strategy testRetryStrategy redirects to https://not-bing.com",
"Retry 6: Processing retry strategy testRetryStrategy.",
"Retry 6: Retry strategy testRetryStrategy redirects to https://not-bing.com",
"Retry 7: Processing retry strategy testRetryStrategy.",
"Retry 7: Retry strategy testRetryStrategy redirects to https://not-bing.com",
"Retry 8: Processing retry strategy testRetryStrategy.",
"Retry 8: Retry strategy testRetryStrategy redirects to https://not-bing.com",
"Retry 9: Processing retry strategy testRetryStrategy.",
"Retry 9: Retry strategy testRetryStrategy redirects to https://not-bing.com",
],
error: [],
});
});
}); | the_stack |
import { OverlayContainer } from '@angular/cdk/overlay';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { Component, ViewChild } from '@angular/core';
import {
waitForAsync,
ComponentFixture,
inject,
TestBed,
} from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import {
DtUiTestConfiguration,
DT_UI_TEST_CONFIG,
} from '@dynatrace/barista-components/core';
import { DtIconModule } from '@dynatrace/barista-components/icon';
import { DtOverlayModule } from '@dynatrace/barista-components/overlay';
import { createComponent, dispatchFakeEvent } from '@dynatrace/testing/browser';
import { DtSunburstChart } from './sunburst-chart';
import { sunburstChartMock } from './sunburst-chart.mock';
import { DtSunburstChartModule } from './sunburst-chart.module';
import {
DtSunburstChartHoverData,
DtSunburstChartNode,
DtSunburstChartNodeSlice,
} from './sunburst-chart.util';
describe('DtSunburstChart', () => {
let fixture: ComponentFixture<TestApp>;
let rootComponent: TestApp;
let component: DtSunburstChart;
let overlayContainer: OverlayContainer;
let overlayContainerElement: HTMLElement;
const overlayConfig: DtUiTestConfiguration = {
attributeName: 'dt-ui-test-id',
constructOverlayAttributeValue(attributeName: string): string {
return `${attributeName}-overlay`;
},
};
let selectedChangeSpy;
let selectSpy;
const selectors = {
overlay: '.dt-overlay-container',
sunburst: 'dt-sunburst-chart',
segment: '[dt-sunburst-chart-segment]',
slice: '.dt-sunburst-chart-slice',
sliceLabel: '.dt-sunburst-chart-slice-label',
selectedSlice: '.dt-sunburst-chart-slice-current',
sliceValue: '.dt-sunburst-chart-slice-value',
selectedLabel: '.dt-sunburst-chart-selected-label',
selectedValue: '.dt-sunburst-chart-selected-value',
};
describe('Default', () => {
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
HttpClientTestingModule,
DtIconModule.forRoot({ svgIconLocation: `{{name}}.svg` }),
DtSunburstChartModule,
],
declarations: [TestApp],
providers: [{ provide: DT_UI_TEST_CONFIG, useValue: overlayConfig }],
});
TestBed.compileComponents();
fixture = createComponent(TestApp);
rootComponent = fixture.componentInstance;
component = fixture.debugElement.query(
By.directive(DtSunburstChart),
).componentInstance;
selectedChangeSpy = jest.spyOn(component.selectedChange, 'emit');
selectSpy = jest.spyOn(component, '_select');
}),
);
describe('Series', () => {
it('should render after change', () => {
rootComponent.series = sunburstChartMock;
fixture.detectChanges();
const slices = fixture.debugElement.queryAll(By.css(selectors.slice));
expect(slices.length).toEqual(2);
expect(slices[0].nativeElement.getAttribute('d')).toBe(
'M5.75583995599256e-15,-94A94,94,0,1,1,5.75583995599256e-15,94L4.0413344371862654e-15,66A66,66,0,1,0,4.0413344371862654e-15,-66Z',
);
});
});
describe('Selected', () => {
it('should have no selection by default', () => {
expect(component.selected).toEqual([]);
});
it('should find filled nodes when input', () => {
rootComponent.series = sunburstChartMock;
rootComponent.selected = [sunburstChartMock[0]];
fixture.detectChanges();
expect(component.selected).toEqual([
{
children: [
{
ariaLabel: 'Blue in Purple is 1',
color: '#fff29a',
depth: 1,
id: '0.0',
label: 'Blue',
value: 1,
valueRelative: 0.125,
origin: expect.any(Object),
},
{
ariaLabel: 'Red in Purple is 3',
color: '#fff29a',
depth: 1,
id: '0.1',
label: 'Red',
value: 3,
valueRelative: 0.375,
origin: expect.any(Object),
},
],
ariaLabel: 'Purple is 4',
color: '#fff29a',
depth: 2,
id: '0',
label: 'Purple',
value: 4,
valueRelative: 0.5,
origin: expect.any(Object),
},
]);
});
});
describe('Value Display Mode', () => {
it('should be ABSOLUTE by default', () => {
fixture.detectChanges();
const actual = fixture.debugElement.query(
By.css(selectors.selectedValue),
);
expect(actual.nativeElement.textContent).not.toContain('%');
});
it('should switch to percentage display when set', () => {
rootComponent.valueDisplayMode = 'percent';
fixture.detectChanges();
const actual = fixture.debugElement.query(
By.css(selectors.selectedValue),
);
expect(actual.nativeElement.textContent).toContain('%');
});
});
describe('Select', () => {
it('should emit empty selection', () => {
component._select();
expect(selectedChangeSpy).toHaveBeenCalledWith([]);
});
it('should emit selected nodes', () => {
const selected = {
data: {
origin: sunburstChartMock[1].children[0],
ariaLabel: 'Yellow in green is 3',
active: false,
childre: [],
color: '',
colorHover: '',
depth: 1,
id: '1.1',
isCurrent: false,
label: 'Yellow',
showLabel: false,
value: 3,
valueRelative: 0.375,
visible: true,
},
endAngle: 0,
index: 0,
labelPosition: [0, 0],
padAngle: 0,
path: '',
showLabel: true,
startAngle: 0,
tooltipPosition: [0, 0],
value: 3,
} as DtSunburstChartNodeSlice;
rootComponent.series = sunburstChartMock;
fixture.detectChanges();
const expected = [
sunburstChartMock[1],
sunburstChartMock[1].children[0],
];
component._select(undefined, selected);
expect(selectedChangeSpy).toHaveBeenCalledWith(expected);
});
it('should render', () => {
rootComponent.series = sunburstChartMock;
fixture.detectChanges();
const firstSegment = fixture.debugElement.query(
By.css(selectors.segment),
);
dispatchFakeEvent(firstSegment.nativeNode, 'click');
fixture.detectChanges();
const selectedSlice = fixture.debugElement.query(
By.css(selectors.selectedSlice),
);
expect(selectedSlice.nativeElement.getAttribute('d')).toBe(
'M6.490628035480972e-15,-106A106,106,0,1,1,6.490628035480972e-15,106L4.0413344371862654e-15,66A66,66,0,1,0,4.0413344371862654e-15,-66Z',
);
});
it('should clean selection on click outside', () => {
const sunburst = fixture.debugElement.query(By.css(selectors.sunburst));
dispatchFakeEvent(sunburst.nativeNode, 'click');
expect(selectSpy).toHaveBeenCalled();
});
});
describe('Template', () => {
beforeEach(function (): void {
rootComponent.series = sunburstChartMock;
fixture.detectChanges();
});
it('should show generic label when nothing selected', () => {
const actual = fixture.debugElement.query(
By.css(selectors.selectedLabel),
);
expect(actual.nativeElement.textContent.trim()).toBe('All');
});
it('should show specific label when selected', () => {
rootComponent.selected = [sunburstChartMock[0]];
fixture.detectChanges();
const actual = fixture.debugElement.query(
By.css(selectors.selectedLabel),
);
expect(actual.nativeElement.textContent.trim()).toBe('Purple');
});
it('should show slice label when nothing selected', () => {
rootComponent.selected = [sunburstChartMock[0]];
fixture.detectChanges();
const actualLabel = fixture.debugElement.queryAll(
By.css(selectors.sliceLabel),
);
const actualValue = fixture.debugElement.queryAll(
By.css(selectors.sliceValue),
);
expect(actualLabel.length).toBe(sunburstChartMock.length);
expect(actualValue.length).toBe(sunburstChartMock.length);
});
it('should show slice label when selected', () => {
rootComponent.selected = [sunburstChartMock[0]];
fixture.detectChanges();
const actualLabel = fixture.debugElement.queryAll(
By.css(selectors.sliceLabel),
);
const actualValue = fixture.debugElement.queryAll(
By.css(selectors.sliceValue),
);
expect(actualLabel.length).toBe(2);
expect(actualValue.length).toBe(2);
});
it('should show absolute values', () => {
rootComponent.valueDisplayMode = 'absolute';
fixture.detectChanges();
const actualSelected = fixture.debugElement.query(
By.css(selectors.selectedValue),
);
const actualSlice = fixture.debugElement.query(
By.css(selectors.sliceValue),
);
expect(actualSelected.nativeElement.textContent).not.toContain('%');
expect(actualSlice.nativeElement.textContent).not.toContain('%');
});
it('should show percent values', () => {
rootComponent.valueDisplayMode = 'percent';
fixture.detectChanges();
const actualSelected = fixture.debugElement.query(
By.css(selectors.selectedValue),
);
const actualSlice = fixture.debugElement.query(
By.css(selectors.sliceValue),
);
expect(actualSelected.nativeElement.textContent).toContain('%');
expect(actualSlice.nativeElement.textContent).toContain('%');
});
it('should show first level slices if nothing selected', () => {
const actual = fixture.debugElement.queryAll(By.css(selectors.slice));
expect(actual.length).toBe(sunburstChartMock.length);
});
it('should show slices when selected', () => {
rootComponent.selected = [sunburstChartMock[0]];
fixture.detectChanges();
const actual = fixture.debugElement.queryAll(By.css(selectors.slice));
expect(actual.length).toBe(4);
});
});
describe('Hover events', () => {
beforeEach(function (): void {
rootComponent.series = sunburstChartMock;
fixture.detectChanges();
});
it('Should emit hover info when hover events start on a slice', () => {
const firstSegment = fixture.debugElement.query(
By.css(selectors.segment),
);
dispatchFakeEvent(firstSegment.nativeElement, 'mouseenter');
expect(rootComponent.hoverStart).toMatchObject({
name: sunburstChartMock[0].label,
color: '#fff29a',
isCurrent: false,
active: false,
value: 0.5,
});
});
it('Should emit hover info when hover events end on a slice', () => {
const firstSegment = fixture.debugElement.query(
By.css(selectors.segment),
);
dispatchFakeEvent(firstSegment.nativeElement, 'mouseleave');
expect(rootComponent.hoverEnd).toMatchObject({
name: sunburstChartMock[0].label,
color: '#fff29a',
isCurrent: false,
active: false,
value: 0.5,
});
});
});
});
describe('Overlay', () => {
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
HttpClientTestingModule,
DtIconModule.forRoot({ svgIconLocation: `{{name}}.svg` }),
DtSunburstChartModule,
DtOverlayModule,
NoopAnimationsModule,
],
declarations: [TestWithOverlayApp],
providers: [{ provide: DT_UI_TEST_CONFIG, useValue: overlayConfig }],
});
TestBed.compileComponents();
}),
);
beforeEach(inject([OverlayContainer], (oc: OverlayContainer) => {
overlayContainer = oc;
overlayContainerElement = oc.getContainerElement();
fixture = createComponent(TestWithOverlayApp);
rootComponent = fixture.componentInstance;
component = fixture.debugElement.query(
By.directive(DtSunburstChart),
).componentInstance;
selectedChangeSpy = jest.spyOn(component.selectedChange, 'emit');
selectSpy = jest.spyOn(component, '_select');
rootComponent.series = sunburstChartMock;
fixture.detectChanges();
}));
it('should have an overlay container defined', () => {
expect(overlayContainer).toBeDefined();
});
it('should display and hide an overlay when called', () => {
component.openOverlay(component.slices[0]);
fixture.detectChanges();
let overlayPane = overlayContainerElement.querySelector(
selectors.overlay,
);
expect(overlayPane).toBeDefined();
const overlayContent = (overlayPane!.textContent ?? '').trim();
expect(overlayContent).toBe('Purple');
component.closeOverlay();
fixture.detectChanges();
// we cannot check if it disappeared because of the animation, so let's check for an alternative
expect(
overlayPane?.attributes.getNamedItem('attr.aria-hidden'),
).toBeTruthy();
});
});
});
/** Test component that contains an DtSunburstChart. */
@Component({
selector: 'dt-test-app',
template: `
<dt-sunburst-chart
[series]="series"
[selected]="selected"
[valueDisplayMode]="valueDisplayMode"
[noSelectionLabel]="noSelectionLabel"
(hoverStart)="hoverStart = $event"
(hoverEnd)="hoverEnd = $event"
>
</dt-sunburst-chart>
`,
})
class TestApp {
series: DtSunburstChartNode[] = [];
selected: DtSunburstChartNode[] = [];
noSelectionLabel = 'All';
valueDisplayMode;
@ViewChild(DtSunburstChart) sunburstChart: DtSunburstChart;
hoverStart: DtSunburstChartHoverData;
hoverEnd: DtSunburstChartHoverData;
}
/** Test component that contains an DtSunburstChart with overlay. */
@Component({
selector: 'dt-test-with-overlay-app',
template: `
<dt-sunburst-chart
[series]="series"
[selected]="selected"
[valueDisplayMode]="valueDisplayMode"
[noSelectionLabel]="noSelectionLabel"
(hoverStart)="hoverStart = $event"
(hoverEnd)="hoverEnd = $event"
>
<ng-template dtSunburstChartOverlay let-tooltip>
<div>
{{ tooltip.label }}
</div>
</ng-template>
</dt-sunburst-chart>
`,
})
class TestWithOverlayApp {
series: DtSunburstChartNode[] = [];
selected: DtSunburstChartNode[] = [];
noSelectionLabel = 'All';
valueDisplayMode;
@ViewChild(DtSunburstChart) sunburstChart: DtSunburstChart;
hoverStart: DtSunburstChartHoverData;
hoverEnd: DtSunburstChartHoverData;
} | the_stack |
import { expect } from "chai";
import { Geometry } from "../../Geometry";
import { Angle } from "../../geometry3d/Angle";
import { GrowableFloat64Array } from "../../geometry3d/GrowableFloat64Array";
import { GrowableXYArray } from "../../geometry3d/GrowableXYArray";
import { GrowableXYZArray } from "../../geometry3d/GrowableXYZArray";
import { Matrix3d } from "../../geometry3d/Matrix3d";
import { Point2dArrayCarrier } from "../../geometry3d/Point2dArrayCarrier";
// import { ClusterableArray } from "../numerics/ClusterableArray";
// import { prettyPrint } from "./testFunctions";
import { Point2d, Vector2d } from "../../geometry3d/Point2dVector2d";
import { Point3dArrayCarrier } from "../../geometry3d/Point3dArrayCarrier";
import { Point3d, Vector3d } from "../../geometry3d/Point3dVector3d";
import { Range2d } from "../../geometry3d/Range";
import { Transform } from "../../geometry3d/Transform";
import { Sample } from "../../serialization/GeometrySamples";
import { Checker } from "../Checker";
/* eslint-disable no-console */
describe("GrowableXYArray", () => {
it("PointMoments", () => {
const ck = new Checker();
for (let n = 3; n < 100; n *= 2) {
const pointA = new GrowableXYArray();
const pointB = [];
ck.testExactNumber(pointA.length, 0);
// load pointB
for (let i = 0; i < n; i++) {
pointB.push(Point2d.create(Math.cos(i * i), i + 0.25));
// pointB.push(Point2d.create(i, i + 0.25));
// pointB.push(Point2d.create(-i, i + 0.25));
}
// verify undefined returns from empty array
ck.testUndefined(pointA.front());
ck.testUndefined(pointA.back());
ck.testFalse(pointA.isIndexValid(4));
for (const p of pointB) {
pointA.push(p);
ck.testPoint2d(p, pointA.back() as Point2d);
ck.testPoint2d(pointB[0], pointA.front() as Point2d);
}
for (let i = 0; i < n; i++)
ck.testPoint2d(pointB[i], pointA.getPoint2dAtUncheckedPointIndex(i));
ck.testExactNumber(pointA.length, pointB.length, "array lengths");
let lengthA = 0;
for (let i = 0; i + 1 < n; i++) {
lengthA += pointA.getPoint2dAtUncheckedPointIndex(i).distance(pointA.getPoint2dAtUncheckedPointIndex(i + 1));
}
const lengthA1 = pointA.sumLengths();
ck.testCoordinate(lengthA, lengthA1, "polyline length");
ck.testExactNumber(pointA.length, n);
// we are confident that all x coordinates are distinct ...
const sortOrder = pointA.sortIndicesLexical();
for (let i = 1; i < sortOrder.length; i++) {
const a = sortOrder[i - 1];
const b = sortOrder[i];
ck.testTrue(pointA.compareLexicalBlock(a, b) < 0, " confirm lexical sort order");
ck.testTrue(pointA.component(a, 0) <= pointA.component(b, 0), "confirm sort order x");
}
}
ck.checkpoint("GrowablePoint2dArray.HelloWorld");
expect(ck.getNumErrors()).equals(0);
});
it("CloneExtractAndPop", () => {
const ck = new Checker();
const n = 11;
const pointA3d = Sample.createGrowableArrayCirclePoints(1.0, n, false);
const pointAXY = GrowableXYArray.create(pointA3d);
const pointBXY = pointAXY.clone();
const pointC = pointAXY.getPoint2dArray();
const pointD = GrowableXYArray.create(pointC);
const eps = 1.0e-16; // ugh ..
ck.testTrue(pointAXY.isAlmostEqual(pointBXY, eps));
ck.testTrue(pointAXY.isAlmostEqual(pointD, eps));
expect(ck.getNumErrors()).equals(0);
const xyBuffer = pointAXY.float64Data();
for (let i = 0; i < n; i++) {
ck.testTrue(Geometry.isSamePoint2d(
pointAXY.getPoint2dAtUncheckedPointIndex(i), Point2d.create(xyBuffer[2 * i], xyBuffer[2 * i + 1])));
}
pointD.clear();
ck.testExactNumber(0, pointD.length);
for (let i = 1; i <= 2 * n; i++) {
pointBXY.pop();
ck.testExactNumber(Math.max(0, n - i), pointBXY.length);
}
expect(ck.getNumErrors()).equals(0);
});
it("Transfer", () => {
const ck = new Checker();
const n = 11;
const pointA = GrowableXYArray.create(Sample.createGrowableArrayCirclePoints(1.0, n, false));
const pointB = new GrowableXYArray(10);
ck.testFalse(pointA.isAlmostEqual(pointB), "isAlmostEqual detects length");
ck.testFalse(GrowableXYArray.isAlmostEqual(pointA, pointB), "static isAlmostEqual");
ck.testUndefined(pointA.getPoint2dAtCheckedPointIndex(-5));
for (let i = 0; i < pointA.length; i++) {
pointB.pushXY(100, 100);
const xy = pointA.getPoint2dAtCheckedPointIndex(i)!;
pointB.transferFromGrowableXYArray(i, pointA, i);
ck.testExactNumber(0, pointB.distanceIndexToPoint(i, xy)!);
}
const z0 = 5.0;
const pointA3d = pointA.getPoint3dArray(z0);
for (let i = 0; i < pointA3d.length; i++) {
const xyz = pointA3d[i];
const xy = pointA.getPoint2dAtUncheckedPointIndex(i);
ck.testExactNumber(z0, xyz.z);
ck.testExactNumber(xyz.x, xy.x);
ck.testExactNumber(xyz.y, xy.y);
}
const vector = Vector3d.create(3, 9);
const transform = Transform.createTranslation(vector);
const pointE = pointA.clone();
const eps = 1.0e-16;
const pointF = pointA.clone();
for (let i = 0; i < pointE.length; i++) {
const xy = pointE.getPoint2dAtCheckedPointIndex(i)!.plus(vector);
pointE.setAtCheckedPointIndex(i, xy);
pointF.setXYZAtCheckedPointIndex(i, xy.x, xy.y);
}
const pointG = pointA.clone();
pointG.multiplyTransformInPlace(transform);
ck.testFalse(pointA.isAlmostEqual(pointG), "isAlmostEqual detects change");
ck.testFalse(GrowableXYArray.isAlmostEqual(pointA, pointG), "static isAlmostEqual");
ck.testTrue(pointE.isAlmostEqual(pointF, 10 * eps));
ck.testTrue(pointE.isAlmostEqual(pointG, 10 * eps));
expect(ck.getNumErrors()).equals(0);
});
it("Transform", () => {
const ck = new Checker();
const n = 11;
const pointA = GrowableXYArray.create(Sample.createGrowableArrayCirclePoints(1.0, n, false));
const pointB = pointA.clone();
const rangeA = Range2d.createNull();
pointA.extendRange(rangeA);
const transform = Transform.createRowValues(
1, 2, 4, 3,
2, 5, 4, -3,
0.2, 0.3, 0.4, 0.5);
const rangeB = Range2d.createNull();
const rangeC = Range2d.createNull();
pointB.multiplyTransformInPlace(transform);
pointA.extendRange(rangeC, transform);
pointB.extendRange(rangeB);
ck.testRange2d(rangeB, rangeC, "transformed array range");
const transformG0 = Transform.createOriginAndMatrix(Point3d.createZero(), transform.matrix);
const pointG1 = pointB.clone();
const pointG2 = pointB.clone();
pointG1.multiplyMatrix3dInPlace(transform.matrix);
pointG2.multiplyTransformInPlace(transformG0);
ck.testTrue(pointG1.isAlmostEqual(pointG2, 1.0e-16));
const pointH1 = pointB.clone();
const pointH2 = pointB.clone();
const factor = 2.3423478238907987;
pointH1.scaleInPlace(factor);
pointH2.multiplyMatrix3dInPlace(Matrix3d.createScale(factor, factor, factor));
ck.testTrue(pointH1.isAlmostEqual(pointH2));
expect(ck.getNumErrors()).equals(0);
});
it("AreaXY", () => {
const ck = new Checker();
for (const n of [4, 9, 64]) {
const r = 1.0;
const circlePoints = Sample.createGrowableArrayCirclePoints(r, n, true);
const pointA = GrowableXYArray.create(circlePoints);
const areaA = pointA.areaXY();
const areaB = circlePoints.areaXY();
ck.testCoordinate(areaA, areaB, "areaXY versus 3d array");
const radians = Math.PI / n; // half the triangle angles
ck.testCoordinate(areaA, n * r * r * Math.cos(radians) * Math.sin(radians));
}
expect(ck.getNumErrors()).equals(0);
});
it("Wrap", () => {
const ck = new Checker();
const numWrap = 3;
for (let n = 5; n < 100; n *= 2) {
const pointA3d = Sample.createGrowableArrayCirclePoints(1.0, n, false);
const pointA = GrowableXYArray.create(pointA3d);
pointA.pushWrap(numWrap);
ck.testExactNumber(n + numWrap, pointA.length, "pushWrap increases length");
for (let i = 0; i < numWrap; i++) {
ck.testPoint2d(pointA.getPoint2dAtUncheckedPointIndex(i), pointA.getPoint2dAtUncheckedPointIndex(n + i), "wrapped point");
}
let numDup = 0;
const sortOrder = pointA.sortIndicesLexical();
for (let i = 0; i + 1 < pointA.length; i++) {
const k0 = sortOrder[i];
const k1 = sortOrder[i + 1];
if (pointA.getPoint2dAtUncheckedPointIndex(k0).isAlmostEqual(pointA.getPoint2dAtUncheckedPointIndex(k1))) {
ck.testLT(k0, k1, "lexical sort preserves order for duplicates");
numDup++;
} else {
const s = pointA.compareLexicalBlock(k0, k1);
ck.testExactNumber(-1, s);
const s1 = pointA.compareLexicalBlock(k1, k0);
ck.testExactNumber(1, s1);
}
}
ck.testExactNumber(numWrap, numDup, "confirm numWrap duplicates");
}
ck.checkpoint("GrowablePoint2dArray.Wrap");
expect(ck.getNumErrors()).equals(0);
});
/** Basic output testing on appendages, sorting, transforming of a known inverse, and testing recognition of plane proximity within correct tolerance */
it("BlackBoxTests", () => {
const ck = new Checker();
const arr = new GrowableXYArray();
arr.ensureCapacity(9);
arr.push(Point2d.create(1, 2));
arr.push(Point2d.create(4, 5));
arr.push(Point2d.create(7, 8));
arr.resize(2);
ck.testExactNumber(arr.length, 2);
ck.testTrue(arr.compareLexicalBlock(0, 1) < 0 && arr.compareLexicalBlock(1, 0) > 0);
const point = Point2d.create();
arr.getPoint2dAtCheckedPointIndex(1, point);
const vector = arr.getVector2dAtCheckedVectorIndex(1)!;
ck.testTrue(point.isAlmostEqual(vector));
ck.testPoint2d(point, Point2d.create(4, 5));
const transform = Transform.createOriginAndMatrix(Point3d.create(0, 0), Matrix3d.createRowValues(
2, 1, 0,
2, 0, 0,
2, 0, 1,
));
const noInverseTransform = Transform.createOriginAndMatrix(Point3d.create(0, 0), Matrix3d.createRowValues(
1, 6, 4,
2, 4, -1,
-1, 2, 5,
));
ck.testTrue(arr.tryTransformInverseInPlace(transform));
ck.testFalse(arr.tryTransformInverseInPlace(noInverseTransform));
ck.testPoint2d(arr.getPoint2dAtUncheckedPointIndex(0), Point2d.create(1, -1));
arr.resize(1);
expect(ck.getNumErrors()).equals(0);
});
it("IndexedXYCollection", () => {
const ck = new Checker();
const points = Sample.createFractalDiamondConvexPattern(1, -0.5);
const frame = Transform.createFixedPointAndMatrix(Point3d.create(1, 2, 0),
Matrix3d.createRotationAroundVector(Vector3d.create(0, 0, 1), Angle.createDegrees(15.7))!);
frame.multiplyPoint3dArrayInPlace(points);
const points2d = [];
for (const p of points)
points2d.push(Point2d.create(p.x, p.y));
const gPoints = new GrowableXYArray();
gPoints.pushAllXYAndZ(points);
const iPoints = new Point2dArrayCarrier(points2d);
const iOrigin = iPoints.getPoint2dAtCheckedPointIndex(0)!;
const gOrigin = gPoints.getPoint2dAtCheckedPointIndex(0)!;
ck.testPoint2d(iOrigin, gOrigin, "point 0 access");
for (let i = 1; i + 1 < points.length; i++) {
const j = i + 1;
const pointIA = iPoints.getPoint2dAtCheckedPointIndex(i)!;
const pointGA = gPoints.getPoint2dAtCheckedPointIndex(i)!;
const pointIB = iPoints.getPoint2dAtCheckedPointIndex(j)!;
const pointGB = gPoints.getPoint2dAtCheckedPointIndex(j)!;
const vectorIA = iPoints.vectorIndexIndex(i, j)!;
const vectorGA = gPoints.vectorIndexIndex(i, j)!;
const vectorIA1 = iPoints.vectorXAndYIndex(pointIA, j)!;
const vectorGA1 = gPoints.vectorXAndYIndex(pointIA, j)!;
ck.testVector2d(vectorIA1, vectorGA1, "vectorXYAndZIndex");
ck.testPoint2d(pointIA, pointGA, "atPoint2dIndex");
ck.testVector2d(vectorIA, pointIA.vectorTo(pointIB));
ck.testVector2d(vectorGA, pointIA.vectorTo(pointGB));
ck.testCoordinate(
iPoints.crossProductIndexIndexIndex(0, i, j)!,
gPoints.crossProductIndexIndexIndex(0, i, j)!);
ck.testCoordinate(
iPoints.crossProductXAndYIndexIndex(iOrigin, i, j)!,
gPoints.crossProductXAndYIndexIndex(gOrigin, i, j)!);
ck.testVector2d(
iPoints.getVector2dAtCheckedVectorIndex(i)!,
gPoints.getVector2dAtCheckedVectorIndex(i)!,
"atVector2dIndex");
}
expect(ck.getNumErrors()).equals(0);
});
it("resizeAndBoundsChecks", () => {
const ck = new Checker();
const points = Sample.createFractalDiamondConvexPattern(1, -0.5);
const xyPoints = new GrowableXYArray(points.length); // just enough so we know the initial capacity.
for (const p of points)
xyPoints.push(p);
ck.testTrue(GrowableXYArray.isAlmostEqual(xyPoints, xyPoints), "isAlmostEqual duplicate pair");
ck.testTrue(GrowableXYArray.isAlmostEqual(undefined, undefined), "isAlmostEqual undefined pair");
ck.testFalse(GrowableXYArray.isAlmostEqual(undefined, xyPoints), "isAlmostEqual one undefined");
ck.testFalse(GrowableXYArray.isAlmostEqual(xyPoints, undefined), "isAlmostEqual one undefined");
const n0 = xyPoints.length;
ck.testExactNumber(n0, points.length);
const deltaN = 5;
const n1 = n0 + deltaN;
xyPoints.resize(n1);
ck.testExactNumber(n1, xyPoints.length);
const n2 = n0 - deltaN;
xyPoints.resize(n2); // blow away some points.
ck.testUndefined(xyPoints.getVector2dAtCheckedVectorIndex(-4));
ck.testUndefined(xyPoints.getVector2dAtCheckedVectorIndex(n2));
// verify duplicate methods ....
for (let i0 = 3; i0 < n2; i0 += 5) {
for (let i1 = 0; i1 < n2; i1 += 3) {
const vectorA = points[i0].vectorTo(points[i1]);
const vectorB = xyPoints.vectorIndexIndex(i0, i1);
if (vectorB)
ck.testVector2d(Vector2d.create(vectorA.x, vectorA.y), vectorB);
else
ck.announceError("vectorIndexIndex?", i0, i1, vectorA, vectorB);
}
}
const spacePoint = Point2d.create(1, 4);
for (let i0 = 2; i0 < n2; i0 += 6) {
const distance0 = xyPoints.distanceIndexToPoint(i0, spacePoint);
const distance1 = xyPoints.getPoint2dAtCheckedPointIndex(i0)!.distance(spacePoint);
const vectorI0 = xyPoints.vectorXAndYIndex(spacePoint, i0);
if (ck.testPointer(vectorI0) && distance0 !== undefined) {
ck.testCoordinate(vectorI0.magnitude(), distance0)!;
ck.testCoordinate(distance0, distance1);
}
}
ck.testUndefined(xyPoints.distance(-1, 0), "distance to invalid indexA");
ck.testUndefined(xyPoints.distance(0, -1), "distance to invalid indexB");
const point0 = xyPoints.getPoint2dAtCheckedPointIndex(0)!;
for (let i = 1; i < xyPoints.length; i++) {
ck.testExactNumber(xyPoints.distance(0, i)!, xyPoints.distanceIndexToPoint(i, point0)!);
}
ck.testUndefined(xyPoints.distanceIndexToPoint(-1, spacePoint), "distance to invalid indexA");
ck.testFalse(xyPoints.setXYZAtCheckedPointIndex(-5, 1, 2), "negative index for setCoordinates");
ck.testFalse(xyPoints.setXYZAtCheckedPointIndex(100, 1, 2), "huge index for setCoordinates");
ck.testFalse(xyPoints.setAtCheckedPointIndex(-5, spacePoint), "negative index for setAt");
ck.testFalse(xyPoints.setAtCheckedPointIndex(100, spacePoint), "huge index for setAt");
ck.testUndefined(xyPoints.vectorXAndYIndex(spacePoint, -5), "negative index for vectorXYAndZIndex");
expect(ck.getNumErrors()).equals(0);
});
it("transferAndSet", () => {
const ck = new Checker();
const points = Sample.createFractalDiamondConvexPattern(1, -0.5);
const array0 = new GrowableXYArray(points.length); // just enough so we know the initial capacity.
for (const p of points)
array0.push(p);
const n0 = array0.length;
const array1 = new GrowableXYArray();
// transfers with bad source index
ck.testExactNumber(0, array1.pushFromGrowableXYArray(array0, -1), "invalid source index for pushFromGrowable");
ck.testExactNumber(0, array1.pushFromGrowableXYArray(array0, n0 + 1), "invalid source index for pushFromGrowable");
// Any transfer into empty array is bad . ..
ck.testFalse(array1.transferFromGrowableXYArray(-1, array0, 1), "invalid source index transferFromGrowable");
ck.testFalse(array1.transferFromGrowableXYArray(0, array0, 1), "invalid source index transferFromGrowable");
ck.testFalse(array1.transferFromGrowableXYArray(100, array0, 1), "invalid source index transferFromGrowable");
ck.testUndefined(array1.crossProductIndexIndexIndex(-1, 0, 1), "bad index0 for cross product");
ck.testUndefined(array1.crossProductIndexIndexIndex(0, 100, 1), "bad index1 for cross product");
ck.testUndefined(array1.crossProductIndexIndexIndex(0, 1, 100), "bad index2 for cross product");
const spacePoint = Point2d.create(1, 2);
ck.testUndefined(array1.crossProductXAndYIndexIndex(spacePoint, -1, 0), "bad indexA for cross product");
ck.testUndefined(array1.crossProductXAndYIndexIndex(spacePoint, 0, -1), "bad indexB for cross product");
const resultA = Point2d.create();
const interpolationFraction = 0.321;
for (let k = 1; k + 2 < n0; k++) {
ck.testExactNumber(1, array1.pushFromGrowableXYArray(array0, k), "transformFromGrowable");
ck.testUndefined(array1.interpolate(-1, 0.3, k), "interpolate with bad index");
ck.testUndefined(array1.interpolate(100, 0.3, k), "interpolate with bad index");
ck.testUndefined(array1.vectorIndexIndex(-1, k), "invalid index vectorIndexIndex");
ck.testUndefined(array1.vectorIndexIndex(k, -1), "invalid index vectorIndexIndex");
ck.testUndefined(array1.interpolate(k, 0.3, n0 + 1), "interpolate with bad index");
ck.testUndefined(array1.interpolate(k, 0.3, n0 + 3), "interpolate with bad index");
const k1 = (2 * k) % n0; // this should be a valid index !!!
if (ck.testTrue(array0.isIndexValid(k1)
&& ck.testPointer(array0.interpolate(k, interpolationFraction, k1, resultA)))) {
const k2 = (2 * k + 1) % n0;
const point0 = array0.getPoint2dAtUncheckedPointIndex(k);
const point1 = array0.getPoint2dAtUncheckedPointIndex(k1);
const resultB = point0.interpolate(interpolationFraction, point1);
ck.testPoint2d(resultA, resultB, "compare interpolation paths");
const crossA = array0.crossProductIndexIndexIndex(k, k1, k2);
const crossB = array0.crossProductXAndYIndexIndex(point0, k1, k2);
if (ck.testIsFinite(crossA) && crossA !== undefined && ck.testIsFinite(crossB) && crossB !== undefined) {
ck.testCoordinate(crossA, crossB, "cross products to indexed points");
}
}
}
// bad transfers when the dest is not empty . . .
ck.testFalse(array1.transferFromGrowableXYArray(-1, array0, 1), "invalid source index transferFromGrowable");
ck.testFalse(array1.transferFromGrowableXYArray(100, array0, 1), "invalid source index transferFromGrowable");
expect(ck.getNumErrors()).equals(0);
});
it("Compress", () => {
const ck = new Checker();
const data = new GrowableFloat64Array();
data.compressAdjacentDuplicates(); // nothing happens on empty array.
const n0 = 22;
for (let i = 0; i < n0; i++) {
const c = Math.cos(i * i);
let n = 1;
if (c < -0.6)
n = 3;
else if (c > 0.1) {
if (c < 0.8)
n = 2;
else
n = 4;
}
for (let k = 0; k < n; k++)
data.push(i);
}
const n1 = data.length;
data.compressAdjacentDuplicates(0.0001);
ck.testExactNumber(n0, data.length, "compressed array big length", n1);
expect(ck.getNumErrors()).equals(0);
});
it("LoadFromArray", () => {
const ck = new Checker();
const n = 5;
const pointA = GrowableXYZArray.create(Sample.createGrowableArrayCirclePoints(1.0, n, false));
const pointB = GrowableXYZArray.create(pointA.float64Data());
const dataC = [];
for (const x of pointA.float64Data()) dataC.push(x);
const pointC = GrowableXYZArray.create(dataC);
ck.testTrue(GrowableXYZArray.isAlmostEqual(pointA, pointB));
ck.testTrue(GrowableXYZArray.isAlmostEqual(pointA, pointC));
ck.testExactNumber(pointA.length, pointB.length);
ck.testExactNumber(pointA.length, pointC.length);
// GrowableXYZArray might hold some additional points exceeding the actual point length
// Make sure that there are no hidden points
ck.testUndefined(pointA.component(n, 0));
ck.testUndefined(pointB.component(n, 0));
ck.testUndefined(pointC.component(n, 0));
expect(ck.getNumErrors()).equals(0);
});
it("MethodsImplementedByInterface", () => {
const ck = new Checker();
const growablePoints = new GrowableXYZArray();
growablePoints.pushFrom([[0, 1, 2], [2, 3, 1], [-2, 3, 9]]);
const simplePoints = growablePoints.getPoint3dArray();
const wrapper = new Point3dArrayCarrier(simplePoints);
let i = 0;
for (const p of wrapper.points) {
ck.testPoint3d(p, simplePoints[i], "wrapper vs simple");
ck.testPoint3d(p, growablePoints.getPoint3dAtUncheckedPointIndex(i), "wrapper vs growable");
i++;
}
const growableRange = growablePoints.getRange();
const wrapperRange = wrapper.getRange();
ck.testRange3d(growableRange, wrapperRange, "growable vs wrapper");
});
it("removeClosurePoints", () => {
const ck = new Checker();
const origin = Point3d.create(1, 2, 3);
const points = Sample.createSquareWave(origin, 2, 1, 3, 3, 5); // This has a single closure point !!
const wrapper = new Point3dArrayCarrier(points);
const originalCount = wrapper.length;
const originalTrim = originalCount - 1;
GrowableXYZArray.removeClosure(wrapper);
ck.testExactNumber(originalTrim, points.length, "original closure point=>no change");
GrowableXYZArray.removeClosure(wrapper);
ck.testExactNumber(originalTrim, points.length, "no closure point=>no change");
for (const numAdd of [1, 3]) {
for (let i = 0; i < numAdd; i++)
wrapper.push(origin);
ck.testExactNumber(originalTrim + numAdd, wrapper.length, `after adding ${numAdd} closure points`);
GrowableXYZArray.removeClosure(wrapper);
ck.testExactNumber(originalTrim, wrapper.length, `after removeClosure ${numAdd}`);
}
});
}); | the_stack |
import { URI, UriComponents } from 'vs/base/common/uri';
import { Event, Emitter } from 'vs/base/common/event';
import { IDisposable, DisposableStore, combinedDisposable } from 'vs/base/common/lifecycle';
import { ISCMService, ISCMRepository, ISCMProvider, ISCMResource, ISCMResourceGroup, ISCMResourceDecorations, IInputValidation, ISCMViewService, InputValidationType } from 'vs/workbench/contrib/scm/common/scm';
import { ExtHostContext, MainThreadSCMShape, ExtHostSCMShape, SCMProviderFeatures, SCMRawResourceSplices, SCMGroupFeatures, MainContext, IExtHostContext } from '../common/extHost.protocol';
import { Command } from 'vs/editor/common/modes';
import { extHostNamedCustomer } from 'vs/workbench/api/common/extHostCustomers';
import { ISplice, Sequence } from 'vs/base/common/sequence';
import { CancellationToken } from 'vs/base/common/cancellation';
class MainThreadSCMResourceGroup implements ISCMResourceGroup {
readonly elements: ISCMResource[] = [];
private readonly _onDidSplice = new Emitter<ISplice<ISCMResource>>();
readonly onDidSplice = this._onDidSplice.event;
get hideWhenEmpty(): boolean { return !!this.features.hideWhenEmpty; }
private readonly _onDidChange = new Emitter<void>();
readonly onDidChange: Event<void> = this._onDidChange.event;
constructor(
private readonly sourceControlHandle: number,
private readonly handle: number,
public provider: ISCMProvider,
public features: SCMGroupFeatures,
public label: string,
public id: string
) { }
toJSON(): any {
return {
$mid: 4,
sourceControlHandle: this.sourceControlHandle,
groupHandle: this.handle
};
}
splice(start: number, deleteCount: number, toInsert: ISCMResource[]) {
this.elements.splice(start, deleteCount, ...toInsert);
this._onDidSplice.fire({ start, deleteCount, toInsert });
}
$updateGroup(features: SCMGroupFeatures): void {
this.features = { ...this.features, ...features };
this._onDidChange.fire();
}
$updateGroupLabel(label: string): void {
this.label = label;
this._onDidChange.fire();
}
}
class MainThreadSCMResource implements ISCMResource {
constructor(
private readonly proxy: ExtHostSCMShape,
private readonly sourceControlHandle: number,
private readonly groupHandle: number,
private readonly handle: number,
readonly sourceUri: URI,
readonly resourceGroup: ISCMResourceGroup,
readonly decorations: ISCMResourceDecorations,
readonly contextValue: string | undefined,
readonly command: Command | undefined
) { }
open(preserveFocus: boolean): Promise<void> {
return this.proxy.$executeResourceCommand(this.sourceControlHandle, this.groupHandle, this.handle, preserveFocus);
}
toJSON(): any {
return {
$mid: 3,
sourceControlHandle: this.sourceControlHandle,
groupHandle: this.groupHandle,
handle: this.handle
};
}
}
class MainThreadSCMProvider implements ISCMProvider {
private static ID_HANDLE = 0;
private _id = `scm${MainThreadSCMProvider.ID_HANDLE++}`;
get id(): string { return this._id; }
readonly groups = new Sequence<MainThreadSCMResourceGroup>();
private readonly _groupsByHandle: { [handle: number]: MainThreadSCMResourceGroup; } = Object.create(null);
// get groups(): ISequence<ISCMResourceGroup> {
// return {
// elements: this._groups,
// onDidSplice: this._onDidSplice.event
// };
// // return this._groups
// // .filter(g => g.resources.elements.length > 0 || !g.features.hideWhenEmpty);
// }
private readonly _onDidChangeResources = new Emitter<void>();
readonly onDidChangeResources: Event<void> = this._onDidChangeResources.event;
private features: SCMProviderFeatures = {};
get handle(): number { return this._handle; }
get label(): string { return this._label; }
get rootUri(): URI | undefined { return this._rootUri; }
get contextValue(): string { return this._contextValue; }
get commitTemplate(): string { return this.features.commitTemplate || ''; }
get acceptInputCommand(): Command | undefined { return this.features.acceptInputCommand; }
get statusBarCommands(): Command[] | undefined { return this.features.statusBarCommands; }
get count(): number | undefined { return this.features.count; }
private readonly _onDidChangeCommitTemplate = new Emitter<string>();
readonly onDidChangeCommitTemplate: Event<string> = this._onDidChangeCommitTemplate.event;
private readonly _onDidChangeStatusBarCommands = new Emitter<Command[]>();
get onDidChangeStatusBarCommands(): Event<Command[]> { return this._onDidChangeStatusBarCommands.event; }
private readonly _onDidChange = new Emitter<void>();
readonly onDidChange: Event<void> = this._onDidChange.event;
constructor(
private readonly proxy: ExtHostSCMShape,
private readonly _handle: number,
private readonly _contextValue: string,
private readonly _label: string,
private readonly _rootUri: URI | undefined
) { }
$updateSourceControl(features: SCMProviderFeatures): void {
this.features = { ...this.features, ...features };
this._onDidChange.fire();
if (typeof features.commitTemplate !== 'undefined') {
this._onDidChangeCommitTemplate.fire(this.commitTemplate!);
}
if (typeof features.statusBarCommands !== 'undefined') {
this._onDidChangeStatusBarCommands.fire(this.statusBarCommands!);
}
}
$registerGroups(_groups: [number /*handle*/, string /*id*/, string /*label*/, SCMGroupFeatures][]): void {
const groups = _groups.map(([handle, id, label, features]) => {
const group = new MainThreadSCMResourceGroup(
this.handle,
handle,
this,
features,
label,
id
);
this._groupsByHandle[handle] = group;
return group;
});
this.groups.splice(this.groups.elements.length, 0, groups);
}
$updateGroup(handle: number, features: SCMGroupFeatures): void {
const group = this._groupsByHandle[handle];
if (!group) {
return;
}
group.$updateGroup(features);
}
$updateGroupLabel(handle: number, label: string): void {
const group = this._groupsByHandle[handle];
if (!group) {
return;
}
group.$updateGroupLabel(label);
}
$spliceGroupResourceStates(splices: SCMRawResourceSplices[]): void {
for (const [groupHandle, groupSlices] of splices) {
const group = this._groupsByHandle[groupHandle];
if (!group) {
console.warn(`SCM group ${groupHandle} not found in provider ${this.label}`);
continue;
}
// reverse the splices sequence in order to apply them correctly
groupSlices.reverse();
for (const [start, deleteCount, rawResources] of groupSlices) {
const resources = rawResources.map(rawResource => {
const [handle, sourceUri, icons, tooltip, strikeThrough, faded, contextValue, command] = rawResource;
const icon = icons[0];
const iconDark = icons[1] || icon;
const decorations = {
icon: icon ? URI.revive(icon) : undefined,
iconDark: iconDark ? URI.revive(iconDark) : undefined,
tooltip,
strikeThrough,
faded
};
return new MainThreadSCMResource(
this.proxy,
this.handle,
groupHandle,
handle,
URI.revive(sourceUri),
group,
decorations,
contextValue || undefined,
command
);
});
group.splice(start, deleteCount, resources);
}
}
this._onDidChangeResources.fire();
}
$unregisterGroup(handle: number): void {
const group = this._groupsByHandle[handle];
if (!group) {
return;
}
delete this._groupsByHandle[handle];
this.groups.splice(this.groups.elements.indexOf(group), 1);
this._onDidChangeResources.fire();
}
async getOriginalResource(uri: URI): Promise<URI | null> {
if (!this.features.hasQuickDiffProvider) {
return null;
}
const result = await this.proxy.$provideOriginalResource(this.handle, uri, CancellationToken.None);
return result && URI.revive(result);
}
toJSON(): any {
return {
$mid: 5,
handle: this.handle
};
}
dispose(): void {
}
}
@extHostNamedCustomer(MainContext.MainThreadSCM)
export class MainThreadSCM implements MainThreadSCMShape {
private readonly _proxy: ExtHostSCMShape;
private _repositories = new Map<number, ISCMRepository>();
private _repositoryDisposables = new Map<number, IDisposable>();
private readonly _disposables = new DisposableStore();
constructor(
extHostContext: IExtHostContext,
@ISCMService private readonly scmService: ISCMService,
@ISCMViewService private readonly scmViewService: ISCMViewService
) {
this._proxy = extHostContext.getProxy(ExtHostContext.ExtHostSCM);
}
dispose(): void {
this._repositories.forEach(r => r.dispose());
this._repositories.clear();
this._repositoryDisposables.forEach(d => d.dispose());
this._repositoryDisposables.clear();
this._disposables.dispose();
}
$registerSourceControl(handle: number, id: string, label: string, rootUri: UriComponents | undefined): void {
const provider = new MainThreadSCMProvider(this._proxy, handle, id, label, rootUri ? URI.revive(rootUri) : undefined);
const repository = this.scmService.registerSCMProvider(provider);
this._repositories.set(handle, repository);
const disposable = combinedDisposable(
Event.filter(this.scmViewService.onDidFocusRepository, r => r === repository)(_ => this._proxy.$setSelectedSourceControl(handle)),
repository.input.onDidChange(({ value }) => this._proxy.$onInputBoxValueChange(handle, value))
);
if (this.scmViewService.focusedRepository === repository) {
setTimeout(() => this._proxy.$setSelectedSourceControl(handle), 0);
}
if (repository.input.value) {
setTimeout(() => this._proxy.$onInputBoxValueChange(handle, repository.input.value), 0);
}
this._repositoryDisposables.set(handle, disposable);
}
$updateSourceControl(handle: number, features: SCMProviderFeatures): void {
const repository = this._repositories.get(handle);
if (!repository) {
return;
}
const provider = repository.provider as MainThreadSCMProvider;
provider.$updateSourceControl(features);
}
$unregisterSourceControl(handle: number): void {
const repository = this._repositories.get(handle);
if (!repository) {
return;
}
this._repositoryDisposables.get(handle)!.dispose();
this._repositoryDisposables.delete(handle);
repository.dispose();
this._repositories.delete(handle);
}
$registerGroups(sourceControlHandle: number, groups: [number /*handle*/, string /*id*/, string /*label*/, SCMGroupFeatures][], splices: SCMRawResourceSplices[]): void {
const repository = this._repositories.get(sourceControlHandle);
if (!repository) {
return;
}
const provider = repository.provider as MainThreadSCMProvider;
provider.$registerGroups(groups);
provider.$spliceGroupResourceStates(splices);
}
$updateGroup(sourceControlHandle: number, groupHandle: number, features: SCMGroupFeatures): void {
const repository = this._repositories.get(sourceControlHandle);
if (!repository) {
return;
}
const provider = repository.provider as MainThreadSCMProvider;
provider.$updateGroup(groupHandle, features);
}
$updateGroupLabel(sourceControlHandle: number, groupHandle: number, label: string): void {
const repository = this._repositories.get(sourceControlHandle);
if (!repository) {
return;
}
const provider = repository.provider as MainThreadSCMProvider;
provider.$updateGroupLabel(groupHandle, label);
}
$spliceResourceStates(sourceControlHandle: number, splices: SCMRawResourceSplices[]): void {
const repository = this._repositories.get(sourceControlHandle);
if (!repository) {
return;
}
const provider = repository.provider as MainThreadSCMProvider;
provider.$spliceGroupResourceStates(splices);
}
$unregisterGroup(sourceControlHandle: number, handle: number): void {
const repository = this._repositories.get(sourceControlHandle);
if (!repository) {
return;
}
const provider = repository.provider as MainThreadSCMProvider;
provider.$unregisterGroup(handle);
}
$setInputBoxValue(sourceControlHandle: number, value: string): void {
const repository = this._repositories.get(sourceControlHandle);
if (!repository) {
return;
}
repository.input.setValue(value, false);
}
$setInputBoxPlaceholder(sourceControlHandle: number, placeholder: string): void {
const repository = this._repositories.get(sourceControlHandle);
if (!repository) {
return;
}
repository.input.placeholder = placeholder;
}
$setInputBoxVisibility(sourceControlHandle: number, visible: boolean): void {
const repository = this._repositories.get(sourceControlHandle);
if (!repository) {
return;
}
repository.input.visible = visible;
}
$setInputBoxFocus(sourceControlHandle: number): void {
const repository = this._repositories.get(sourceControlHandle);
if (!repository) {
return;
}
repository.input.setFocus();
}
$showValidationMessage(sourceControlHandle: number, message: string, type: InputValidationType) {
const repository = this._repositories.get(sourceControlHandle);
if (!repository) {
return;
}
repository.input.showValidationMessage(message, type);
}
$setValidationProviderIsEnabled(sourceControlHandle: number, enabled: boolean): void {
const repository = this._repositories.get(sourceControlHandle);
if (!repository) {
return;
}
if (enabled) {
repository.input.validateInput = async (value, pos): Promise<IInputValidation | undefined> => {
const result = await this._proxy.$validateInput(sourceControlHandle, value, pos);
return result && { message: result[0], type: result[1] };
};
} else {
repository.input.validateInput = async () => undefined;
}
}
} | the_stack |
import { SignedOrder } from '@0x/types';
import { from, HttpLink, split } from '@apollo/client';
import {
ApolloClient,
ApolloQueryResult,
FetchResult,
InMemoryCache,
NormalizedCacheObject,
OperationVariables,
QueryOptions,
} from '@apollo/client/core';
import { ApolloLink } from '@apollo/client/link/core';
import { WebSocketLink } from '@apollo/client/link/ws';
import { getMainDefinition } from '@apollo/client/utilities';
import { SubscriptionClient } from 'subscriptions-transport-ws';
import * as ws from 'ws';
import * as Observable from 'zen-observable';
import {
addOrdersMutation,
addOrdersMutationV4,
orderEventsSubscription,
orderQuery,
orderQueryV4,
ordersQuery,
ordersQueryV4,
statsQuery,
} from './queries';
import {
AddOrdersOpts,
AddOrdersResponse,
AddOrdersResponseV4,
AddOrdersResults,
convertFilterValue,
fromStringifiedAddOrdersResults,
fromStringifiedAddOrdersResultsV4,
fromStringifiedOrderEvent,
fromStringifiedOrderWithMetadata,
fromStringifiedOrderWithMetadataV4,
fromStringifiedStats,
OrderEvent,
OrderEventResponse,
OrderQuery,
OrderResponse,
OrderResponseV4,
OrdersResponse,
OrdersResponseV4,
OrderWithMetadata,
OrderWithMetadataV4,
SignedOrderV4,
Stats,
StatsResponse,
StringifiedOrderWithMetadata,
StringifiedOrderWithMetadataV4,
StringifiedSignedOrder,
StringifiedSignedOrderV4,
toStringifiedSignedOrder,
toStringifiedSignedOrderV4,
} from './types';
export { SignedOrder } from '@0x/types';
export { ApolloQueryResult, QueryOptions } from '@apollo/client/core';
export {
AcceptedOrderResult,
AddOrdersResults,
FilterKind,
OrderEvent,
OrderEventEndState,
OrderField,
OrderFilter,
OrderQuery,
OrderSort,
OrderWithMetadata,
OrderWithMetadataV4,
RejectedOrderCode,
RejectedOrderResult,
SortDirection,
Stats,
} from './types';
export { Observable };
const defaultOrderQueryLimit = 100;
export interface LinkConfig {
httpUrl?: string;
webSocketUrl?: string;
}
export class MeshGraphQLClient {
// NOTE(jalextowle): BrowserLink doesn't support subscriptions at this time.
private readonly _subscriptionClient?: SubscriptionClient;
private readonly _client: ApolloClient<NormalizedCacheObject>;
private readonly _onReconnectedCallbacks: (() => void)[] = [];
constructor(linkConfig: LinkConfig) {
let link: ApolloLink;
if (!linkConfig.httpUrl || !linkConfig.webSocketUrl) {
throw new Error(
'mesh-graphql-client: Both "httpUrl" and "webSocketUrl" must be provided in "linkConfig" if a network link is used',
);
}
// Set up an apollo client with WebSocket and HTTP links. This allows
// us to use the appropriate transport based on the type of the query.
const httpLink = new HttpLink({
uri: linkConfig.httpUrl,
});
const wsSubClient = new SubscriptionClient(
linkConfig.webSocketUrl,
{
reconnect: true,
},
// Use ws in Node.js and native WebSocket in browsers.
(process as any).browser ? undefined : ws,
);
const wsLink = new WebSocketLink(wsSubClient);
// HACK(kimpers): See https://github.com/apollographql/apollo-client/issues/5115#issuecomment-572318778
// @ts-ignore at the time of writing the field is private and untyped
const subscriptionClient = wsLink.subscriptionClient as SubscriptionClient;
subscriptionClient.onReconnected(() => {
for (const cb of this._onReconnectedCallbacks) {
cb();
}
});
const splitLink = split(
({ query }) => {
const definition = getMainDefinition(query);
return definition.kind === 'OperationDefinition' && definition.operation === 'subscription';
},
wsLink,
httpLink,
);
link = from([splitLink]);
this._subscriptionClient = wsSubClient;
this._client = new ApolloClient({
cache: new InMemoryCache({
resultCaching: false,
// This custom merge function is required for our orderEvents subscription.
// See https://www.apollographql.com/docs/react/caching/cache-field-behavior/#the-merge-function
typePolicies: {
Subscription: {
fields: {
orderEvents: {
merge(existing: OrderEvent[] = [], incoming: OrderEvent[]): OrderEvent[] {
return [...existing, ...incoming];
},
},
},
},
},
// Stop apollo client from injecting `__typename` fields. These extra fields mess up our tests.
addTypename: false,
}),
link,
});
}
public async getStatsAsync(): Promise<Stats> {
const resp: ApolloQueryResult<StatsResponse> = await this._client.query({
fetchPolicy: 'no-cache',
query: statsQuery,
});
if (resp.data === undefined) {
throw new Error('received no data');
}
const stats = resp.data.stats;
return fromStringifiedStats(stats);
}
public async addOrdersAsync(
orders: SignedOrder[],
pinned: boolean = true,
opts?: AddOrdersOpts,
): Promise<AddOrdersResults<OrderWithMetadata, SignedOrder>> {
const resp: FetchResult<AddOrdersResponse<
StringifiedOrderWithMetadata,
StringifiedSignedOrder
>> = await this._client.mutate({
mutation: addOrdersMutation,
variables: {
orders: orders.map(toStringifiedSignedOrder),
pinned,
opts: {
keepCancelled: false,
keepExpired: false,
keepFullyFilled: false,
keepUnfunded: false,
...opts,
},
},
});
if (resp.data == null) {
throw new Error('received no data');
}
const results = resp.data.addOrders;
return fromStringifiedAddOrdersResults(results);
}
public async addOrdersV4Async(
orders: SignedOrderV4[],
pinned: boolean = true,
opts?: AddOrdersOpts,
): Promise<AddOrdersResults<OrderWithMetadataV4, SignedOrderV4>> {
const resp: FetchResult<AddOrdersResponseV4<
StringifiedOrderWithMetadataV4,
StringifiedSignedOrderV4
>> = await this._client.mutate({
mutation: addOrdersMutationV4,
variables: {
orders: orders.map(toStringifiedSignedOrderV4),
pinned,
opts: {
keepCancelled: false,
keepExpired: false,
keepFullyFilled: false,
keepUnfunded: false,
...opts,
},
},
});
if (resp.data == null) {
throw new Error('received no data');
}
const results = resp.data.addOrdersV4;
return fromStringifiedAddOrdersResultsV4(results);
}
public async getOrderAsync(hash: string): Promise<OrderWithMetadata | null> {
const resp: ApolloQueryResult<OrderResponse> = await this._client.query({
query: orderQuery,
fetchPolicy: 'no-cache',
variables: {
hash,
},
});
if (resp.data == null) {
throw new Error('received no data');
}
if (resp.data.order == null) {
return null;
}
return fromStringifiedOrderWithMetadata(resp.data.order);
}
public async getOrderV4Async(hash: string): Promise<OrderWithMetadataV4 | null> {
const resp: ApolloQueryResult<OrderResponseV4> = await this._client.query({
query: orderQueryV4,
fetchPolicy: 'no-cache',
variables: {
hash,
},
});
if (resp.data == null) {
throw new Error('received no data');
}
if (resp.data.orderv4 == null) {
return null;
}
return fromStringifiedOrderWithMetadataV4(resp.data.orderv4);
}
public async findOrdersAsync(
query: OrderQuery = { sort: [], filters: [], limit: defaultOrderQueryLimit },
): Promise<OrderWithMetadata[]> {
const resp: ApolloQueryResult<OrdersResponse> = await this._client.query({
query: ordersQuery,
fetchPolicy: 'no-cache',
variables: {
sort: query.sort || [],
filters: query.filters?.map(convertFilterValue) || [],
limit: query.limit || defaultOrderQueryLimit,
},
});
if (resp.data == null) {
throw new Error('received no data');
}
return resp.data.orders.map(fromStringifiedOrderWithMetadata);
}
public async findOrdersV4Async(
query: OrderQuery = { sort: [], filters: [], limit: defaultOrderQueryLimit },
): Promise<OrderWithMetadataV4[]> {
const resp: ApolloQueryResult<OrdersResponseV4> = await this._client.query({
query: ordersQueryV4,
fetchPolicy: 'no-cache',
variables: {
sort: query.sort || [],
filters: query.filters?.map(convertFilterValue) || [],
limit: query.limit || defaultOrderQueryLimit,
},
});
if (resp.data == null) {
throw new Error('received no data');
}
return resp.data.ordersv4.map(fromStringifiedOrderWithMetadataV4);
}
public onReconnected(cb: () => void): void {
this._onReconnectedCallbacks.push(cb);
}
public onOrderEvents(): Observable<OrderEvent[]> {
if (this._subscriptionClient !== undefined) {
// NOTE(jalextowle): We must use a variable here because Typescript
// thinks that this._subscriptionClient can become undefined between
// Observable events.
const subscriptionClient = this._subscriptionClient;
// We handle incomingObservable and return a new outgoingObservable. This
// can be thought of as "wrapping" the observable and we do it for two reasons:
//
// 1. Convert FetchResult<OrderEventResponse> to OrderEvent[]
// 2. Handle errors and disconnects from the underlying websocket transport. If we don't
// do this, Apollo Client just ignores them completely and acts like everything is fine :(
//
const incomingObservable = this._client.subscribe({
fetchPolicy: 'no-cache',
query: orderEventsSubscription,
}) as Observable<FetchResult<OrderEventResponse>>;
const outgoingObservable = new Observable<OrderEvent[]>((observer) => {
subscriptionClient.onError((err: ErrorEvent) => {
observer.error(new Error(err.message));
});
subscriptionClient.onDisconnected((event: Event) => {
observer.error(new Error('WebSocket connection lost'));
});
incomingObservable.subscribe({
next: (result: FetchResult<OrderEventResponse>) => {
if (result.errors != null && result.errors.length > 0) {
result.errors.forEach((err) => observer.error(err));
} else if (result.data == null) {
observer.error(new Error('received no data'));
} else {
observer.next(result.data.orderEvents.map(fromStringifiedOrderEvent));
}
},
error: (err) => observer.error(err),
complete: () => observer.complete(),
});
});
return outgoingObservable;
} else {
throw new Error(
'mesh-graphql-client: Browser GraphQl API does not support subscriptions. Please use the legacy API to listen to events and errors',
);
}
}
public async rawQueryAsync<T = any, TVariables = OperationVariables>(
options: QueryOptions<TVariables>,
): Promise<ApolloQueryResult<T>> {
if (!this._subscriptionClient) {
throw new Error('mesh-graphql-client: Raw queries are not currently supported by browser nodes');
}
return this._client.query<T>(options);
}
} | the_stack |
import create from 'zustand'
import { persist } from 'zustand/middleware'
const createPersistantStore = (initialValue: string | null) => {
let state = initialValue
const getItem = (): string | null => {
getItemSpy()
return state
}
const setItem = (name: string, newState: string) => {
setItemSpy(name, newState)
state = newState
}
const removeItem = (name: string) => {
removeItemSpy(name)
state = null
}
const getItemSpy = jest.fn()
const setItemSpy = jest.fn()
const removeItemSpy = jest.fn()
return {
storage: { getItem, setItem, removeItem },
getItemSpy,
setItemSpy,
}
}
describe('persist middleware with sync configuration', () => {
const consoleError = console.error
afterEach(() => {
console.error = consoleError
})
it('can rehydrate state', () => {
const storage = {
getItem: (name: string) =>
JSON.stringify({
state: { count: 42, name },
version: 0,
}),
setItem: () => {},
removeItem: () => {},
}
const onRehydrateStorageSpy = jest.fn()
const useStore = create(
persist(
() => ({
count: 0,
name: 'empty',
}),
{
name: 'test-storage',
getStorage: () => storage,
onRehydrateStorage: () => onRehydrateStorageSpy,
}
)
)
expect(useStore.getState()).toEqual({ count: 42, name: 'test-storage' })
expect(onRehydrateStorageSpy).toBeCalledWith(
{ count: 42, name: 'test-storage' },
undefined
)
})
it('can throw rehydrate error', () => {
const storage = {
getItem: () => {
throw new Error('getItem error')
},
setItem: () => {},
removeItem: () => {},
}
const spy = jest.fn()
create(
persist(() => ({ count: 0 }), {
name: 'test-storage',
getStorage: () => storage,
onRehydrateStorage: () => spy,
})
)
expect(spy).toBeCalledWith(undefined, new Error('getItem error'))
})
it('can persist state', () => {
const { storage, setItemSpy } = createPersistantStore(null)
const createStore = () => {
const onRehydrateStorageSpy = jest.fn()
const useStore = create(
persist(() => ({ count: 0 }), {
name: 'test-storage',
getStorage: () => storage,
onRehydrateStorage: () => onRehydrateStorageSpy,
})
)
return { useStore, onRehydrateStorageSpy }
}
// Initialize from empty storage
const { useStore, onRehydrateStorageSpy } = createStore()
expect(useStore.getState()).toEqual({ count: 0 })
expect(onRehydrateStorageSpy).toBeCalledWith({ count: 0 }, undefined)
// Write something to the store
useStore.setState({ count: 42 })
expect(useStore.getState()).toEqual({ count: 42 })
expect(setItemSpy).toBeCalledWith(
'test-storage',
JSON.stringify({ state: { count: 42 }, version: 0 })
)
// Create the same store a second time and check if the persisted state
// is loaded correctly
const {
useStore: useStore2,
onRehydrateStorageSpy: onRehydrateStorageSpy2,
} = createStore()
expect(useStore2.getState()).toEqual({ count: 42 })
expect(onRehydrateStorageSpy2).toBeCalledWith({ count: 42 }, undefined)
})
it('can migrate persisted state', () => {
const setItemSpy = jest.fn()
const onRehydrateStorageSpy = jest.fn()
const migrateSpy = jest.fn(() => ({ count: 99 }))
const storage = {
getItem: () =>
JSON.stringify({
state: { count: 42 },
version: 12,
}),
setItem: setItemSpy,
removeItem: () => {},
}
const useStore = create(
persist(() => ({ count: 0 }), {
name: 'test-storage',
version: 13,
getStorage: () => storage,
onRehydrateStorage: () => onRehydrateStorageSpy,
migrate: migrateSpy,
})
)
expect(useStore.getState()).toEqual({ count: 99 })
expect(migrateSpy).toBeCalledWith({ count: 42 }, 12)
expect(setItemSpy).toBeCalledWith(
'test-storage',
JSON.stringify({
state: { count: 99 },
version: 13,
})
)
expect(onRehydrateStorageSpy).toBeCalledWith({ count: 99 }, undefined)
})
it('can correclty handle a missing migrate function', () => {
console.error = jest.fn()
const onRehydrateStorageSpy = jest.fn()
const storage = {
getItem: () =>
JSON.stringify({
state: { count: 42 },
version: 12,
}),
setItem: (_: string, _value: string) => {},
removeItem: () => {},
}
const useStore = create(
persist(() => ({ count: 0 }), {
name: 'test-storage',
version: 13,
getStorage: () => storage,
onRehydrateStorage: () => onRehydrateStorageSpy,
})
)
expect(useStore.getState()).toEqual({ count: 0 })
expect(console.error).toHaveBeenCalled()
expect(onRehydrateStorageSpy).toBeCalledWith({ count: 0 }, undefined)
})
it('can throw migrate error', () => {
const onRehydrateStorageSpy = jest.fn()
const storage = {
getItem: () =>
JSON.stringify({
state: {},
version: 12,
}),
setItem: () => {},
removeItem: () => {},
}
const useStore = create(
persist(() => ({ count: 0 }), {
name: 'test-storage',
version: 13,
getStorage: () => storage,
migrate: () => {
throw new Error('migrate error')
},
onRehydrateStorage: () => onRehydrateStorageSpy,
})
)
expect(useStore.getState()).toEqual({ count: 0 })
expect(onRehydrateStorageSpy).toBeCalledWith(
undefined,
new Error('migrate error')
)
})
it('gives the merged state to onRehydrateStorage', () => {
const onRehydrateStorageSpy = jest.fn()
const storage = {
getItem: () =>
JSON.stringify({
state: { count: 1 },
version: 0,
}),
setItem: () => {},
removeItem: () => {},
}
const unstorableMethod = () => {}
const useStore = create(
persist(() => ({ count: 0, unstorableMethod }), {
name: 'test-storage',
getStorage: () => storage,
onRehydrateStorage: () => onRehydrateStorageSpy,
})
)
const expectedState = { count: 1, unstorableMethod }
expect(useStore.getState()).toEqual(expectedState)
expect(onRehydrateStorageSpy).toBeCalledWith(expectedState, undefined)
})
it('can custom merge the stored state', () => {
const storage = {
getItem: () =>
JSON.stringify({
state: {
count: 1,
actions: {},
},
version: 0,
}),
setItem: () => {},
removeItem: () => {},
}
const unstorableMethod = () => {}
const useStore = create(
persist(() => ({ count: 0, actions: { unstorableMethod } }), {
name: 'test-storage',
getStorage: () => storage,
merge: (_persistedState, currentState) => {
const persistedState = _persistedState as any
delete persistedState.actions
return {
...currentState,
...persistedState,
}
},
})
)
expect(useStore.getState()).toEqual({
count: 1,
actions: {
unstorableMethod,
},
})
})
it("can merge the state when the storage item doesn't have a version", () => {
const storage = {
getItem: () =>
JSON.stringify({
state: {
count: 1,
},
}),
setItem: () => {},
removeItem: () => {},
}
const useStore = create(
persist(() => ({ count: 0 }), {
name: 'test-storage',
getStorage: () => storage,
deserialize: (str) => JSON.parse(str),
})
)
expect(useStore.getState()).toEqual({
count: 1,
})
})
it('can filter the persisted value', () => {
const setItemSpy = jest.fn()
const storage = {
getItem: () => '',
setItem: setItemSpy,
removeItem: () => {},
}
const useStore = create(
persist(
() => ({
object: {
first: '0',
second: '1',
},
array: [
{
value: '0',
},
{
value: '1',
},
{
value: '2',
},
],
}),
{
name: 'test-storage',
getStorage: () => storage,
partialize: (state) => {
return {
object: {
first: state.object.first,
},
array: state.array.filter((e) => e.value !== '1'),
}
},
}
)
)
useStore.setState({})
expect(setItemSpy).toBeCalledWith(
'test-storage',
JSON.stringify({
state: {
object: {
first: '0',
},
array: [
{
value: '0',
},
{
value: '2',
},
],
},
version: 0,
})
)
})
it('can change the options through the api', () => {
const setItemSpy = jest.fn()
const storage = {
getItem: () => null,
setItem: setItemSpy,
removeItem: () => {},
}
const useStore = create(
persist(() => ({ count: 0 }), {
name: 'test-storage',
getStorage: () => storage,
})
)
useStore.setState({})
expect(setItemSpy).toBeCalledWith(
'test-storage',
'{"state":{"count":0},"version":0}'
)
useStore.persist.setOptions({
name: 'test-storage-2',
partialize: (state) =>
Object.fromEntries(
Object.entries(state).filter(([key]) => key !== 'count')
),
})
useStore.setState({})
expect(setItemSpy).toBeCalledWith(
'test-storage-2',
'{"state":{},"version":0}'
)
})
it('can clear the storage through the api', () => {
const removeItemSpy = jest.fn()
const storage = {
getItem: () => null,
setItem: () => {},
removeItem: removeItemSpy,
}
const useStore = create(
persist(() => ({ count: 0 }), {
name: 'test-storage',
getStorage: () => storage,
})
)
useStore.persist.clearStorage()
expect(removeItemSpy).toBeCalledWith('test-storage')
})
it('can manually rehydrate through the api', () => {
const storageValue = '{"state":{"count":1},"version":0}'
const storage = {
getItem: () => '',
setItem: () => {},
removeItem: () => {},
}
const useStore = create(
persist(() => ({ count: 0 }), {
name: 'test-storage',
getStorage: () => storage,
})
)
storage.getItem = () => storageValue
useStore.persist.rehydrate()
expect(useStore.getState()).toEqual({
count: 1,
})
})
it('can check if the store has been hydrated through the api', async () => {
const storage = {
getItem: () => null,
setItem: () => {},
removeItem: () => {},
}
const useStore = create(
persist(() => ({ count: 0 }), {
name: 'test-storage',
getStorage: () => storage,
})
)
expect(useStore.persist.hasHydrated()).toBe(true)
await useStore.persist.rehydrate()
expect(useStore.persist.hasHydrated()).toBe(true)
})
it('can wait for rehydration through the api', async () => {
const storageValue1 = '{"state":{"count":1},"version":0}'
const storageValue2 = '{"state":{"count":2},"version":0}'
const onHydrateSpy1 = jest.fn()
const onHydrateSpy2 = jest.fn()
const onFinishHydrationSpy1 = jest.fn()
const onFinishHydrationSpy2 = jest.fn()
const storage = {
getItem: () => '',
setItem: () => {},
removeItem: () => {},
}
const useStore = create(
persist(() => ({ count: 0 }), {
name: 'test-storage',
getStorage: () => storage,
})
)
const hydrateUnsub1 = useStore.persist.onHydrate(onHydrateSpy1)
useStore.persist.onHydrate(onHydrateSpy2)
const finishHydrationUnsub1 = useStore.persist.onFinishHydration(
onFinishHydrationSpy1
)
useStore.persist.onFinishHydration(onFinishHydrationSpy2)
storage.getItem = () => storageValue1
await useStore.persist.rehydrate()
expect(onHydrateSpy1).toBeCalledWith({ count: 0 })
expect(onHydrateSpy2).toBeCalledWith({ count: 0 })
expect(onFinishHydrationSpy1).toBeCalledWith({ count: 1 })
expect(onFinishHydrationSpy2).toBeCalledWith({ count: 1 })
hydrateUnsub1()
finishHydrationUnsub1()
storage.getItem = () => storageValue2
await useStore.persist.rehydrate()
expect(onHydrateSpy1).not.toBeCalledTimes(2)
expect(onHydrateSpy2).toBeCalledWith({ count: 1 })
expect(onFinishHydrationSpy1).not.toBeCalledTimes(2)
expect(onFinishHydrationSpy2).toBeCalledWith({ count: 2 })
})
}) | the_stack |
import BN from 'bn.js';
import BigNumber from 'bignumber.js';
import {
PromiEvent,
TransactionReceipt,
EventResponse,
EventData,
Web3ContractContext,
} from 'ethereum-abi-types-generator';
export interface CallOptions {
from?: string;
gasPrice?: string;
gas?: number;
}
export interface SendOptions {
from: string;
value?: number | string | BN | BigNumber;
gasPrice?: string;
gas?: number;
}
export interface EstimateGasOptions {
from?: string;
value?: number | string | BN | BigNumber;
gas?: number;
}
export interface MethodPayableReturnContext {
send(options: SendOptions): PromiEvent<TransactionReceipt>;
send(
options: SendOptions,
callback: (error: Error, result: any) => void
): PromiEvent<TransactionReceipt>;
estimateGas(options: EstimateGasOptions): Promise<number>;
estimateGas(
options: EstimateGasOptions,
callback: (error: Error, result: any) => void
): Promise<number>;
encodeABI(): string;
}
export interface MethodConstantReturnContext<TCallReturn> {
call(): Promise<TCallReturn>;
call(options: CallOptions): Promise<TCallReturn>;
call(
options: CallOptions,
callback: (error: Error, result: TCallReturn) => void
): Promise<TCallReturn>;
encodeABI(): string;
}
export interface MethodReturnContext extends MethodPayableReturnContext {}
export type ContractContext = Web3ContractContext<
FarmHeroChef,
FarmHeroChefMethodNames,
FarmHeroChefEventsContext,
FarmHeroChefEvents
>;
export type FarmHeroChefEvents =
| 'Compound'
| 'Deposit'
| 'DepositNTF'
| 'EmergencyWithdraw'
| 'EmergencyWithdrawNFT'
| 'FeeExclude'
| 'OwnershipTransferred'
| 'Paused'
| 'SkipEOA'
| 'Unpaused'
| 'Withdraw'
| 'WithdrawNFT';
export interface FarmHeroChefEventsContext {
Compound(
parameters: {
filter?: { user?: string | string[]; pid?: string | string[] };
fromBlock?: number;
toBlock?: 'latest' | number;
topics?: string[];
},
callback?: (error: Error, event: EventData) => void
): EventResponse;
Deposit(
parameters: {
filter?: { user?: string | string[]; pid?: string | string[] };
fromBlock?: number;
toBlock?: 'latest' | number;
topics?: string[];
},
callback?: (error: Error, event: EventData) => void
): EventResponse;
DepositNTF(
parameters: {
filter?: { user?: string | string[]; pid?: string | string[] };
fromBlock?: number;
toBlock?: 'latest' | number;
topics?: string[];
},
callback?: (error: Error, event: EventData) => void
): EventResponse;
EmergencyWithdraw(
parameters: {
filter?: { user?: string | string[]; pid?: string | string[] };
fromBlock?: number;
toBlock?: 'latest' | number;
topics?: string[];
},
callback?: (error: Error, event: EventData) => void
): EventResponse;
EmergencyWithdrawNFT(
parameters: {
filter?: { user?: string | string[]; pid?: string | string[] };
fromBlock?: number;
toBlock?: 'latest' | number;
topics?: string[];
},
callback?: (error: Error, event: EventData) => void
): EventResponse;
FeeExclude(
parameters: {
filter?: { user?: string | string[] };
fromBlock?: number;
toBlock?: 'latest' | number;
topics?: string[];
},
callback?: (error: Error, event: EventData) => void
): EventResponse;
OwnershipTransferred(
parameters: {
filter?: {
previousOwner?: string | string[];
newOwner?: string | string[];
};
fromBlock?: number;
toBlock?: 'latest' | number;
topics?: string[];
},
callback?: (error: Error, event: EventData) => void
): EventResponse;
Paused(
parameters: {
filter?: {};
fromBlock?: number;
toBlock?: 'latest' | number;
topics?: string[];
},
callback?: (error: Error, event: EventData) => void
): EventResponse;
SkipEOA(
parameters: {
filter?: { user?: string | string[] };
fromBlock?: number;
toBlock?: 'latest' | number;
topics?: string[];
},
callback?: (error: Error, event: EventData) => void
): EventResponse;
Unpaused(
parameters: {
filter?: {};
fromBlock?: number;
toBlock?: 'latest' | number;
topics?: string[];
},
callback?: (error: Error, event: EventData) => void
): EventResponse;
Withdraw(
parameters: {
filter?: { user?: string | string[]; pid?: string | string[] };
fromBlock?: number;
toBlock?: 'latest' | number;
topics?: string[];
},
callback?: (error: Error, event: EventData) => void
): EventResponse;
WithdrawNFT(
parameters: {
filter?: { user?: string | string[]; pid?: string | string[] };
fromBlock?: number;
toBlock?: 'latest' | number;
topics?: string[];
},
callback?: (error: Error, event: EventData) => void
): EventResponse;
}
export type FarmHeroChefMethodNames =
| 'HERO'
| 'HEROMaxSupply'
| 'HERORewardPerSecond'
| 'add'
| 'burnAddress'
| 'calculateReward'
| 'communityAddress'
| 'communityRate'
| 'compound'
| 'compoundNotFee'
| 'compoundPaused'
| 'deposit'
| 'depositNFT'
| 'ecosystemAddress'
| 'ecosystemRate'
| 'emergencyWithdraw'
| 'emergencyWithdrawNFT'
| 'epochDuration'
| 'epochReduceRate'
| 'epochReward'
| 'epochsLeft'
| 'epochsPassed'
| 'erc20PoolRate'
| 'erc721PoolRate'
| 'feeAddress'
| 'feeExclude'
| 'heroDistribution'
| 'inCaseTokensGetStuck'
| 'initialize'
| 'massUpdatePools'
| 'nftRewardRate'
| 'onERC721Received'
| 'owner'
| 'pause'
| 'paused'
| 'pendingHERO'
| 'playerBook'
| 'poolExistence'
| 'poolInfo'
| 'poolLength'
| 'referralRate'
| 'referrals'
| 'renounceOwnership'
| 'reservedNFTFarmingAddress'
| 'reservedNFTFarmingRate'
| 'rewardDistribution'
| 'set'
| 'setAddresses'
| 'setCompoundNotFee'
| 'setCompoundPaused'
| 'setEpochDuration'
| 'setEpochReduceRate'
| 'setFeeExclude'
| 'setHEROMaxSupply'
| 'setHeroDistribution'
| 'setNftRewardRate'
| 'setPlaybook'
| 'setRates'
| 'setReferralRate'
| 'setRewardDistribution'
| 'setSkipEOA'
| 'setTotalEpoch'
| 'setWithdrawFee'
| 'skipEOA'
| 'stakedWantTokens'
| 'startAt'
| 'startTime'
| 'teamAddress'
| 'teamRate'
| 'totalAllocPoint'
| 'totalEpoch'
| 'transferOwnership'
| 'unpause'
| 'updatePool'
| 'userInfo'
| 'withdraw'
| 'withdrawAll'
| 'withdrawFee'
| 'withdrawNFT';
export interface PoolInfoResponse {
want: string;
poolType: string;
allocPoint: string;
lastRewardTime: string;
accHEROPerShare: string;
strat: string;
}
export interface UserInfoResponse {
shares: string;
rewardDebt: string;
gracePeriod: string;
lastDepositBlock: string;
}
export interface FarmHeroChef {
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
HERO(): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
HEROMaxSupply(): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
HERORewardPerSecond(): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param _allocPoint Type: uint256, Indexed: false
* @param _want Type: address, Indexed: false
* @param _poolType Type: uint8, Indexed: false
* @param _withUpdate Type: bool, Indexed: false
* @param _strat Type: address, Indexed: false
*/
add(
_allocPoint: string,
_want: string,
_poolType: string | number,
_withUpdate: boolean,
_strat: string
): MethodReturnContext;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
burnAddress(): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
* @param _before Type: uint256, Indexed: false
* @param _now Type: uint256, Indexed: false
*/
calculateReward(_before: string, _now: string): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
communityAddress(): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
communityRate(): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param _pid Type: uint256, Indexed: false
*/
compound(_pid: string): MethodReturnContext;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
compoundNotFee(): MethodConstantReturnContext<boolean>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
compoundPaused(): MethodConstantReturnContext<boolean>;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param _pid Type: uint256, Indexed: false
* @param _wantAmt Type: uint256, Indexed: false
* @param _referName Type: string, Indexed: false
*/
deposit(_pid: string, _wantAmt: string, _referName: string): MethodReturnContext;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param _pid Type: uint256, Indexed: false
* @param _tokenIds Type: uint256[], Indexed: false
* @param _referName Type: string, Indexed: false
*/
depositNFT(_pid: string, _tokenIds: string[], _referName: string): MethodReturnContext;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
ecosystemAddress(): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
ecosystemRate(): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param _pid Type: uint256, Indexed: false
*/
emergencyWithdraw(_pid: string): MethodReturnContext;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param _pid Type: uint256, Indexed: false
* @param _tokenIds Type: uint256[], Indexed: false
*/
emergencyWithdrawNFT(_pid: string, _tokenIds: string[]): MethodReturnContext;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
epochDuration(): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
epochReduceRate(): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
* @param _epoch Type: uint256, Indexed: false
*/
epochReward(_epoch: string): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
epochsLeft(): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
* @param _time Type: uint256, Indexed: false
*/
epochsPassed(_time: string): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
erc20PoolRate(): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
erc721PoolRate(): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
feeAddress(): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
* @param parameter0 Type: address, Indexed: false
*/
feeExclude(parameter0: string): MethodConstantReturnContext<boolean>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
heroDistribution(): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param _token Type: address, Indexed: false
* @param _amount Type: uint256, Indexed: false
*/
inCaseTokensGetStuck(_token: string, _amount: string): MethodReturnContext;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param _hero Type: address, Indexed: false
* @param _heroRewardPerSecond Type: uint256, Indexed: false
* @param _disAddresses Type: address[], Indexed: false
*/
initialize(
_hero: string,
_heroRewardPerSecond: string,
_disAddresses: string[]
): MethodReturnContext;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
*/
massUpdatePools(): MethodReturnContext;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
nftRewardRate(): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param operator Type: address, Indexed: false
* @param from Type: address, Indexed: false
* @param tokenId Type: uint256, Indexed: false
* @param data Type: bytes, Indexed: false
*/
onERC721Received(
operator: string,
from: string,
tokenId: string,
data: string | number[]
): MethodReturnContext;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
owner(): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
*/
pause(): MethodReturnContext;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
paused(): MethodConstantReturnContext<boolean>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
* @param _pid Type: uint256, Indexed: false
* @param _user Type: address, Indexed: false
*/
pendingHERO(_pid: string, _user: string): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
playerBook(): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
* @param parameter0 Type: address, Indexed: false
*/
poolExistence(parameter0: string): MethodConstantReturnContext<boolean>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
* @param parameter0 Type: uint256, Indexed: false
*/
poolInfo(parameter0: string): MethodConstantReturnContext<PoolInfoResponse>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
poolLength(): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
referralRate(): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
* @param parameter0 Type: address, Indexed: false
*/
referrals(parameter0: string): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
*/
renounceOwnership(): MethodReturnContext;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
reservedNFTFarmingAddress(): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
reservedNFTFarmingRate(): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
rewardDistribution(): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param _pid Type: uint256, Indexed: false
* @param _allocPoint Type: uint256, Indexed: false
* @param _withUpdate Type: bool, Indexed: false
*/
set(_pid: string, _allocPoint: string, _withUpdate: boolean): MethodReturnContext;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param _reservedNFTFarmingAddress Type: address, Indexed: false
* @param _teamAddress Type: address, Indexed: false
* @param _communityAddress Type: address, Indexed: false
* @param _ecosystemAddress Type: address, Indexed: false
*/
setAddresses(
_reservedNFTFarmingAddress: string,
_teamAddress: string,
_communityAddress: string,
_ecosystemAddress: string
): MethodReturnContext;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param _notFee Type: bool, Indexed: false
*/
setCompoundNotFee(_notFee: boolean): MethodReturnContext;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param _paused Type: bool, Indexed: false
*/
setCompoundPaused(_paused: boolean): MethodReturnContext;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param _epochDuration Type: uint256, Indexed: false
*/
setEpochDuration(_epochDuration: string): MethodReturnContext;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param _epochReduceRate Type: uint256, Indexed: false
*/
setEpochReduceRate(_epochReduceRate: string): MethodReturnContext;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param _user Type: address, Indexed: false
*/
setFeeExclude(_user: string): MethodReturnContext;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param _supply Type: uint256, Indexed: false
*/
setHEROMaxSupply(_supply: string): MethodReturnContext;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param _heroDistribution Type: address, Indexed: false
*/
setHeroDistribution(_heroDistribution: string): MethodReturnContext;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param _rate Type: uint256, Indexed: false
*/
setNftRewardRate(_rate: string): MethodReturnContext;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param _playerBook Type: address, Indexed: false
* @param _referralRate Type: uint256, Indexed: false
*/
setPlaybook(_playerBook: string, _referralRate: string): MethodReturnContext;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param _teamRate Type: uint256, Indexed: false
* @param _communityRate Type: uint256, Indexed: false
* @param _ecosystemRate Type: uint256, Indexed: false
* @param _reservedNFTFarmingRate Type: uint256, Indexed: false
*/
setRates(
_teamRate: string,
_communityRate: string,
_ecosystemRate: string,
_reservedNFTFarmingRate: string
): MethodReturnContext;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param _referralRate Type: uint256, Indexed: false
*/
setReferralRate(_referralRate: string): MethodReturnContext;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param _rewardDistribution Type: address, Indexed: false
*/
setRewardDistribution(_rewardDistribution: string): MethodReturnContext;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param _user Type: address, Indexed: false
*/
setSkipEOA(_user: string): MethodReturnContext;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param _totalEpoch Type: uint256, Indexed: false
*/
setTotalEpoch(_totalEpoch: string): MethodReturnContext;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param _feeAddress Type: address, Indexed: false
* @param _enable Type: bool, Indexed: false
*/
setWithdrawFee(_feeAddress: string, _enable: boolean): MethodReturnContext;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
* @param parameter0 Type: address, Indexed: false
*/
skipEOA(parameter0: string): MethodConstantReturnContext<boolean>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
* @param _pid Type: uint256, Indexed: false
* @param _user Type: address, Indexed: false
*/
stakedWantTokens(_pid: string, _user: string): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param _startTime Type: uint256, Indexed: false
*/
startAt(_startTime: string): MethodReturnContext;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
startTime(): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
teamAddress(): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
teamRate(): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
* @param parameter0 Type: uint8, Indexed: false
*/
totalAllocPoint(parameter0: string | number): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
totalEpoch(): MethodConstantReturnContext<string>;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param newOwner Type: address, Indexed: false
*/
transferOwnership(newOwner: string): MethodReturnContext;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
*/
unpause(): MethodReturnContext;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param _pid Type: uint256, Indexed: false
*/
updatePool(_pid: string): MethodReturnContext;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
* @param parameter0 Type: uint256, Indexed: false
* @param parameter1 Type: address, Indexed: false
*/
userInfo(parameter0: string, parameter1: string): MethodConstantReturnContext<UserInfoResponse>;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param _pid Type: uint256, Indexed: false
* @param _wantAmt Type: uint256, Indexed: false
*/
withdraw(_pid: string, _wantAmt: string): MethodReturnContext;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param _pid Type: uint256, Indexed: false
*/
withdrawAll(_pid: string): MethodReturnContext;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
withdrawFee(): MethodConstantReturnContext<boolean>;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param _pid Type: uint256, Indexed: false
* @param _tokenIds Type: uint256[], Indexed: false
*/
withdrawNFT(_pid: string, _tokenIds: string[]): MethodReturnContext;
} | the_stack |
import { Url } from './../../shared/Utilities/url';
import { SpecPickerComponent } from './../spec-picker/spec-picker.component';
import { SiteService } from 'app/shared/services/site.service';
import { Subscription } from 'rxjs/Subscription';
import { DashboardType } from 'app/tree-view/models/dashboard-type';
import { LogicAppsComponent } from './../../logic-apps/logic-apps.component';
import { Dom } from './../../shared/Utilities/dom';
import { LogService } from './../../shared/services/log.service';
import { ScenarioService } from './../../shared/services/scenario/scenario.service';
import { SiteConfigComponent } from './../site-config/site-config.component';
import { DirtyStateEvent } from './../../shared/models/broadcast-event';
import { SiteConfigStandaloneComponent } from './../site-config-standalone/site-config-standalone.component';
import { SwaggerDefinitionComponent } from './../swagger-definition/swagger-definition.component';
import { FunctionRuntimeComponent } from './../function-runtime/function-runtime.component';
import { BroadcastEvent } from 'app/shared/models/broadcast-event';
import { SiteManageComponent } from './../site-manage/site-manage.component';
import { TabInfo } from './site-tab/tab-info';
import { SiteSummaryComponent } from './../site-summary/site-summary.component';
import { SiteData } from './../../tree-view/models/tree-view-info';
import { Component, OnDestroy, ElementRef, ViewChild, Injector } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { Subject } from 'rxjs/Subject';
import { PortalService } from './../../shared/services/portal.service';
import { PortalResources } from './../../shared/models/portal-resources';
import { AiService } from './../../shared/services/ai.service';
import { SiteTabIds, ScenarioIds, LogCategories, KeyCodes } from './../../shared/models/constants';
import { AppNode } from './../../tree-view/app-node';
import { GlobalStateService } from '../../shared/services/global-state.service';
import { TreeViewInfo } from '../../tree-view/models/tree-view-info';
import { ArmObj } from '../../shared/models/arm/arm-obj';
import { Site } from '../../shared/models/arm/site';
import { PartSize } from '../../shared/models/portal';
import { NavigableComponent, ExtendedTreeViewInfo } from '../../shared/components/navigable-component';
import { DeploymentCenterComponent } from 'app/site/deployment-center/deployment-center.component';
import { Observable } from 'rxjs/Observable';
import { ConsoleComponent } from '../console/console.component';
import { AppLogStreamComponent } from '../log-stream/log-stream.component';
import { QuickstartComponent } from '../quickstart/quickstart.component';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'site-dashboard',
templateUrl: './site-dashboard.component.html',
styleUrls: ['./site-dashboard.component.scss'],
})
export class SiteDashboardComponent extends NavigableComponent implements OnDestroy {
// We keep a static copy of all the tabs that are open becuase we want to reopen them
// if a user changes apps or navigates away and comes back. But we also create an instance
// copy because the template can't reference static properties
private static _tabInfos: TabInfo[] = [];
public tabInfos: TabInfo[] = SiteDashboardComponent._tabInfos;
@ViewChild('siteTabs')
groupElements: ElementRef;
public dynamicTabIds: (string | null)[] = [null, null];
public site: ArmObj<Site>;
public viewInfoStream: Subject<TreeViewInfo<SiteData>>;
public Resources = PortalResources;
private _currentTabId: string;
private _prevTabId: string;
private _currentTabIndex: number;
private _openTabSubscription: Subscription;
private _closeTabSubscription: Subscription;
private _openTroubleshoot: boolean;
constructor(
private _globalStateService: GlobalStateService,
private _aiService: AiService,
private _portalService: PortalService,
private _translateService: TranslateService,
private _scenarioService: ScenarioService,
private _logService: LogService,
private _siteService: SiteService,
public router: Router,
public route: ActivatedRoute,
injector: Injector
) {
super('site-dashboard', injector, DashboardType.AppDashboard);
this._broadcastService
.getEvents<DirtyStateEvent>(BroadcastEvent.DirtyStateChange)
.takeUntil(this.ngUnsubscribe)
.subscribe(event => {
if (!event.dirty && !event.reason) {
this.tabInfos.forEach(t => (t.dirty = false));
} else {
const info = this.tabInfos.find(t => t.id === event.reason);
if (info) {
info.dirty = event.dirty;
}
}
});
if (this.tabInfos.length === 0) {
// Setup initial tabs without inputs immediate so that they load right away
this.tabInfos = [this._getTabInfo(SiteTabIds.overview, true /* active */, null)];
if (this._scenarioService.checkScenario(ScenarioIds.addSiteConfigTab).status === 'enabled') {
this.tabInfos.push(this._getTabInfo(SiteTabIds.standaloneConfig, false /* active */, null));
}
if (this._scenarioService.checkScenario(ScenarioIds.addSiteFeaturesTab).status === 'enabled') {
this.tabInfos.push(this._getTabInfo(SiteTabIds.platformFeatures, false /* active */, null));
}
}
const activeTab = this.tabInfos.find(info => info.active);
if (activeTab) {
this._currentTabId = activeTab.id;
this._currentTabIndex = this.tabInfos.findIndex(info => info.active);
}
}
setup(navigationEvents: Observable<ExtendedTreeViewInfo>): Observable<any> {
return super
.setup(navigationEvents)
.switchMap(viewInfo => {
// ellhamai - This is a not-so-great workaround for the fact that we can't have deep links for
// child blades of Function apps due to the fact that we've overridden the normal portal
// asset registration. The way this works is if we see this query string in the URL,
// then we'll open a child blade for troubleshoot. The crappy part about this is that we don't have access to
// remove the query string from the page's URL so to get around this we remove it from our
// internal routing for the iframe (see end of setup function for this logic). This works
// fine so long as the user never closes the functions blade, but if they refresh or reopen
// the blade, then we'll automatically open the troubleshoot blade again for the first app they load.
this._openTroubleshoot = Url.getParameterByName(null, 'appsvc.troubleshoot') === 'true';
if (this._openTroubleshoot) {
this._portalService.openFrameBlade(
{
detailBlade: 'SCIFrameBlade',
detailBladeInputs: {
id: viewInfo.resourceId,
},
},
'site-dashboard'
);
}
if (this._globalStateService.showTryView) {
this._globalStateService.setDisabledMessage(this._translateService.instant(PortalResources.try_appDisabled));
}
viewInfo.data.siteTabRevealedTraceKey = this._aiService.startTrace();
viewInfo.data.siteTabFullReadyTraceKey = this._aiService.startTrace();
if (!this._openTabSubscription) {
this._openTabSubscription = this._broadcastService
.getEvents<string>(BroadcastEvent.OpenTab)
.takeUntil(this.ngUnsubscribe)
.subscribe(tabId => {
if (tabId) {
this.openFeature(tabId);
this._broadcastService.broadcastEvent<string>(BroadcastEvent.OpenTab, null);
}
});
}
if (!this._closeTabSubscription) {
this._closeTabSubscription = this._broadcastService
.getEvents<string>(BroadcastEvent.CloseTab)
.takeUntil(this.ngUnsubscribe)
.subscribe(tabId => {
if (tabId) {
this.closeFeature(tabId);
this._broadcastService.broadcastEvent<string>(BroadcastEvent.CloseTab, null);
}
});
}
return this._siteService.getSite(viewInfo.resourceId);
})
.do(r => {
if (!r.isSuccessful) {
let message = this._translateService.instant(PortalResources.siteDashboard_getAppError).format(this.viewInfo.siteDescriptor.site);
if (r.error.result && r.error.result.status === 404) {
message = this._translateService.instant(PortalResources.siteDashboard_appNotFound).format(this.viewInfo.siteDescriptor.site);
}
this._logService.error(LogCategories.siteDashboard, '/site-dashboard', r.error.result);
this._globalStateService.setDisabledMessage(message);
return;
}
this.site = r.result;
this._broadcastService.clearAllDirtyStates();
this._logService.verbose(LogCategories.siteDashboard, `Received new input, updating tabs`);
for (let i = 0; i < this.tabInfos.length; i++) {
const info = this.tabInfos[i];
if (info.active) {
this._logService.debug(LogCategories.siteDashboard, `Updating inputs for active tab '${info.id}'`);
// We're not recreating the active tab so that it doesn't flash in the UI
// All Tabs have `viewInfoInput`
// Tabs that inherit from FunctionAppContextComponent like FunctionRuntimeComponent have viewInfoComponent_viewInfo
const tabInfo = this._getTabInfo(info.id, false /* active */, {
viewInfoInput: this.viewInfo,
});
this.tabInfos[i].componentInput = tabInfo.componentInput;
} else {
// Just to be extra safe, we create new component instances for tabs that
// aren't visible to be sure that we can't accidentally load them with the wrong
// input in the future. This also helps to dispose of other unused components
// when we switch apps.
this.tabInfos[i] = this._getTabInfo(info.id, false /* active */, {
viewInfoInput: this.viewInfo,
});
this._logService.debug(LogCategories.siteDashboard, `Creating new component for inactive tab '${info.id}'`);
}
}
const appNode = <AppNode>this.viewInfo.node;
if (appNode.openTabId) {
this.openFeature(appNode.openTabId);
appNode.openTabId = null;
}
if (this._openTroubleshoot) {
const queryObj = Url.getQueryStringObj();
delete queryObj['appsvc.troubleshoot'];
const id = `/resources${this.viewInfo.resourceId}`.toLowerCase().replace('/providers/microsoft.web', '');
this.router.navigate([id], { relativeTo: this.route, queryParams: queryObj });
}
});
}
ngOnDestroy() {
super.ngOnDestroy();
// Save current set of tabs
SiteDashboardComponent._tabInfos = this.tabInfos;
}
private _selectTabId(id: string) {
this.selectTab(this.tabInfos.find(i => i.id === id));
}
selectTab(info: TabInfo) {
this._logService.verbose(LogCategories.siteDashboard, `Select Tab - ${info.id}`);
this._aiService.trackEvent('/sites/open-tab', { name: info.id });
this.tabInfos.forEach(t => (t.active = t.id === info.id));
this.viewInfo.data.siteTabRevealedTraceKey = this._aiService.startTrace();
this.viewInfo.data.siteTabFullReadyTraceKey = this._aiService.startTrace();
this._prevTabId = this._currentTabId;
this._currentTabId = info.id;
this._currentTabIndex = this.tabInfos.findIndex(i => i.id === info.id);
}
closeTab(info: TabInfo) {
this._logService.verbose(LogCategories.siteDashboard, `Close Tab - ${info.id}`);
const tabIndexToClose = this.tabInfos.findIndex(i => i.id === info.id);
if (tabIndexToClose >= 0) {
this.tabInfos.splice(tabIndexToClose, 1);
// Only need to worry about opening a new tab if the tab being closed is the current one.
if (info.id === this._currentTabId) {
if (this._prevTabId) {
this._selectTabId(this._prevTabId);
} else {
this._selectTabId(SiteTabIds.overview);
}
// Even though you are not opening a new tab, you still must update the _currentTabIndex value
// to deal with a possible shift in position of the current tab
} else {
this._currentTabIndex = this.tabInfos.findIndex(i => i.id === this._currentTabId);
}
// If you close the previous tab, then this will make sure that you don't go back to it
// if you close the current tab.
if (info.id === this._prevTabId) {
this._prevTabId = null;
}
}
}
openFeature(featureId: string) {
this._prevTabId = this._currentTabId;
let tabInfo = this.tabInfos.find(t => t.id === featureId);
if (!tabInfo) {
tabInfo = this._getTabInfo(featureId, true /* active */, { viewInfoInput: this.viewInfo });
this.tabInfos.push(tabInfo);
}
this.selectTab(tabInfo);
}
closeFeature(featureId: string) {
let tabInfo = this.tabInfos.find(t => t.id === featureId);
if (!tabInfo) {
tabInfo = this._getTabInfo(featureId, true /* active */, { viewInfoInput: this.viewInfo });
this.tabInfos.push(tabInfo);
}
this.closeTab(tabInfo);
}
pinPart() {
this._portalService.pinPart({
partSize: PartSize.Normal,
partInput: {
id: this.viewInfo.resourceId,
},
});
}
keypress(event: KeyboardEvent) {
if (event.keyCode === KeyCodes.enter) {
this.pinPart();
}
}
private _getTabInfo(tabId: string, active: boolean, input: { viewInfoInput: TreeViewInfo<SiteData> }): TabInfo {
const info = {
title: '',
id: tabId,
active: active,
closeable: true,
iconUrl: null,
dirty: false,
componentFactory: null,
componentInput: input
? Object.assign({}, input, { viewInfo: input.viewInfoInput, viewInfoComponent_viewInfo: input.viewInfoInput })
: {},
};
switch (tabId) {
case SiteTabIds.overview:
info.title = this._translateService.instant(PortalResources.tab_overview);
info.componentFactory = SiteSummaryComponent;
info.closeable = false;
break;
case SiteTabIds.platformFeatures:
info.title = this._translateService.instant(PortalResources.tab_features);
info.componentFactory = SiteManageComponent;
info.closeable = false;
break;
case SiteTabIds.functionRuntime:
info.title = this._translateService.instant(PortalResources.tab_functionSettings);
info.iconUrl = 'image/functions.svg';
info.componentFactory = FunctionRuntimeComponent;
break;
case SiteTabIds.apiDefinition:
info.title = this._translateService.instant(PortalResources.tab_api_definition);
info.iconUrl = 'image/api-definition.svg';
info.componentFactory = SwaggerDefinitionComponent;
break;
case SiteTabIds.standaloneConfig:
info.title = this._translateService.instant(PortalResources.tab_configuration);
info.componentFactory = SiteConfigStandaloneComponent;
info.closeable = false;
break;
case SiteTabIds.applicationSettings:
info.title = this._translateService.instant(PortalResources.tab_applicationSettings);
info.iconUrl = 'image/application-settings.svg';
info.componentFactory = SiteConfigComponent;
info.closeable = true;
break;
case SiteTabIds.logicApps:
info.title = this._translateService.instant(PortalResources.tab_logicApps);
info.iconUrl = 'image/logicapp.svg';
info.componentFactory = LogicAppsComponent;
info.closeable = true;
break;
case SiteTabIds.console:
info.title = this._translateService.instant(PortalResources.feature_consoleName);
info.iconUrl = 'image/console.svg';
info.componentFactory = ConsoleComponent;
info.closeable = true;
break;
case SiteTabIds.logStream:
info.title = this._translateService.instant(PortalResources.feature_logStreamingName);
info.iconUrl = 'image/log-stream.svg';
info.componentFactory = AppLogStreamComponent;
info.closeable = true;
break;
case SiteTabIds.continuousDeployment:
info.title = this._translateService.instant(PortalResources.deploymentCenter);
info.iconUrl = 'image/deployment-source.svg';
info.componentFactory = DeploymentCenterComponent;
break;
case SiteTabIds.scaleUp:
info.title = this._translateService.instant('Scale up');
info.iconUrl = 'image/scale-up.svg';
info.componentFactory = SpecPickerComponent;
(<any>info.componentInput) = {
viewInfoInput: {
resourceId: this.site.properties.serverFarmId,
},
};
break;
case SiteTabIds.quickstart:
info.title = this._translateService.instant(PortalResources.quickstart);
info.iconUrl = 'image/quickstart.svg';
info.componentFactory = QuickstartComponent;
break;
}
return info;
}
_getTabElements() {
return this.groupElements.nativeElement.children;
}
_clearFocusOnTab(elements: HTMLCollection, index: number) {
const oldFeature = Dom.getTabbableControl(<HTMLElement>elements[index]);
Dom.clearFocus(oldFeature);
}
_setFocusOnTab(elements: HTMLCollection, index: number) {
let finalIndex = -1;
let destFeature: Element;
// Wrap around logic for navigating through a tab list
if (elements.length > 0) {
if (index > 0 && index < elements.length) {
finalIndex = index;
} else if (index === -1) {
finalIndex = elements.length - 1;
} else {
finalIndex = 0;
}
destFeature = elements[finalIndex];
}
this._currentTabIndex = finalIndex;
if (destFeature) {
const newFeature = Dom.getTabbableControl(<HTMLElement>destFeature);
Dom.setFocus(<HTMLElement>newFeature);
}
}
onKeyPress(event: KeyboardEvent, info: TabInfo) {
if (event.keyCode === KeyCodes.enter || event.keyCode === KeyCodes.space) {
this.selectTab(info);
event.preventDefault();
} else if (event.keyCode === KeyCodes.arrowRight) {
const tabElements = this._getTabElements();
this._clearFocusOnTab(tabElements, this._currentTabIndex);
this._setFocusOnTab(tabElements, this._currentTabIndex + 1);
event.preventDefault();
} else if (event.keyCode === KeyCodes.arrowLeft) {
const tabElements = this._getTabElements();
this._clearFocusOnTab(tabElements, this._currentTabIndex);
this._setFocusOnTab(tabElements, this._currentTabIndex - 1);
event.preventDefault();
} else if (event.keyCode === KeyCodes.delete) {
if (info.closeable) {
this.closeTab(info);
// Allow page to re-render tabs before setting focus on new one
setTimeout(() => {
const tabElements = this._getTabElements();
this._setFocusOnTab(tabElements, this._currentTabIndex);
}, 0);
}
}
}
} | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement, Operator } from "../shared";
/**
* Statement provider for service [glue](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsglue.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Glue extends PolicyStatement {
public servicePrefix = 'glue';
/**
* Statement provider for service [glue](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsglue.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 one or more partitions
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-partitions.html#aws-glue-api-catalog-partitions-BatchCreatePartition
*/
public toBatchCreatePartition() {
return this.to('BatchCreatePartition');
}
/**
* Grants permission to delete one or more connections
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-connections.html#aws-glue-api-catalog-connections-BatchDeleteConnection
*/
public toBatchDeleteConnection() {
return this.to('BatchDeleteConnection');
}
/**
* Grants permission to delete one or more partitions
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-partitions.html#aws-glue-api-catalog-partitions-BatchDeletePartition
*/
public toBatchDeletePartition() {
return this.to('BatchDeletePartition');
}
/**
* Grants permission to delete one or more tables
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-tables.html#aws-glue-api-catalog-tables-BatchDeleteTable
*/
public toBatchDeleteTable() {
return this.to('BatchDeleteTable');
}
/**
* Grants permission to delete one or more versions of a table
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-tables.html#aws-glue-api-catalog-tables-DeleteTableVersion
*/
public toBatchDeleteTableVersion() {
return this.to('BatchDeleteTableVersion');
}
/**
* Grants permission to retrieve one or more crawlers
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-crawling.html#aws-glue-api-crawler-crawling-BatchGetCrawlers
*/
public toBatchGetCrawlers() {
return this.to('BatchGetCrawlers');
}
/**
* Grants permission to retrieve one or more development endpoints
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-dev-endpoint.html#aws-glue-api-dev-endpoint-BatchGetDevEndpoints
*/
public toBatchGetDevEndpoints() {
return this.to('BatchGetDevEndpoints');
}
/**
* Grants permission to retrieve one or more jobs
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-job.html#aws-glue-api-jobs-job-BatchGetJobs
*/
public toBatchGetJobs() {
return this.to('BatchGetJobs');
}
/**
* Grants permission to retrieve one or more partitions
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-partitions.html#aws-glue-api-catalog-partitions-BatchGetPartition
*/
public toBatchGetPartition() {
return this.to('BatchGetPartition');
}
/**
* Grants permission to retrieve one or more triggers
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-trigger.html#aws-glue-api-jobs-trigger-BatchGetTriggers
*/
public toBatchGetTriggers() {
return this.to('BatchGetTriggers');
}
/**
* Grants permission to retrieve one or more workflows
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-workflow.html#aws-glue-api-workflow-BatchGetWorkflows
*/
public toBatchGetWorkflows() {
return this.to('BatchGetWorkflows');
}
/**
* Grants permission to stop one or more job runs for a job
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-runs.html#aws-glue-api-jobs-runs-BatchStopStartJobRun
*/
public toBatchStopJobRun() {
return this.to('BatchStopJobRun');
}
/**
* Grants permission to stop a running ML Task Run
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-machine-learning-api.html#aws-glue-api-machine-learning-api-CancelMLTaskRun
*/
public toCancelMLTaskRun() {
return this.to('CancelMLTaskRun');
}
/**
* Grants permission to retrieve a check the validity of schema version
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-schema-registry-api.html#aws-glue-api-schema-registry-api-CheckSchemaVersionValidity
*/
public toCheckSchemaVersionValidity() {
return this.to('CheckSchemaVersionValidity');
}
/**
* Grants permission to create a classifier
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-classifiers.html#aws-glue-api-crawler-classifiers-CreateClassifier
*/
public toCreateClassifier() {
return this.to('CreateClassifier');
}
/**
* Grants permission to create a connection
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-connections.html#aws-glue-api-catalog-connections-CreateConnection
*/
public toCreateConnection() {
return this.to('CreateConnection');
}
/**
* Grants permission to create a crawler
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-crawling.html#aws-glue-api-crawler-crawling-CreateCrawler
*/
public toCreateCrawler() {
return this.to('CreateCrawler');
}
/**
* Grants permission to create a database
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-databases.html#aws-glue-api-catalog-databases-CreateDatabase
*/
public toCreateDatabase() {
return this.to('CreateDatabase');
}
/**
* Grants permission to create a development endpoint
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-dev-endpoint.html#aws-glue-api-dev-endpoint-CreateDevEndpoint
*/
public toCreateDevEndpoint() {
return this.to('CreateDevEndpoint');
}
/**
* Grants permission to create a job
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
* - .ifVpcIds()
* - .ifSubnetIds()
* - .ifSecurityGroupIds()
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-job.html#aws-glue-api-jobs-job-CreateJob
*/
public toCreateJob() {
return this.to('CreateJob');
}
/**
* Grants permission to create an ML Transform
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-machine-learning-api.html#aws-glue-api-machine-learning-api-CreateMLTransform
*/
public toCreateMLTransform() {
return this.to('CreateMLTransform');
}
/**
* Grants permission to create a partition
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-partitions.html#aws-glue-api-catalog-partitions-CreatePartition
*/
public toCreatePartition() {
return this.to('CreatePartition');
}
/**
* Grants permission to create a new schema registry
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-schema-registry-api.html#aws-glue-api-schema-registry-api-CreateRegistry
*/
public toCreateRegistry() {
return this.to('CreateRegistry');
}
/**
* Grants permission to create a new schema container
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-schema-registry-api.html#aws-glue-api-schema-registry-api-CreateSchema
*/
public toCreateSchema() {
return this.to('CreateSchema');
}
/**
* Grants permission to create a script
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-etl-script-generation.html#aws-glue-api-etl-script-generation-CreateScript
*/
public toCreateScript() {
return this.to('CreateScript');
}
/**
* Grants permission to create a security configuration
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-security.html#aws-glue-api-jobs-security-CreateSecurityConfiguration
*/
public toCreateSecurityConfiguration() {
return this.to('CreateSecurityConfiguration');
}
/**
* Grants permission to create a table
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-tables.html#aws-glue-api-catalog-tables-CreateTable
*/
public toCreateTable() {
return this.to('CreateTable');
}
/**
* Grants permission to create a trigger
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-trigger.html#aws-glue-api-jobs-trigger-CreateTrigger
*/
public toCreateTrigger() {
return this.to('CreateTrigger');
}
/**
* Grants permission to create a function definition
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-functions.html#aws-glue-api-catalog-functions-CreateUserDefinedFunction
*/
public toCreateUserDefinedFunction() {
return this.to('CreateUserDefinedFunction');
}
/**
* Grants permission to create a workflow
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-workflow.html#aws-glue-api-workflow-CreateWorkflow
*/
public toCreateWorkflow() {
return this.to('CreateWorkflow');
}
/**
* Grants permission to delete a classifier
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-classifiers.html#aws-glue-api-crawler-classifiers-DeleteClassifier
*/
public toDeleteClassifier() {
return this.to('DeleteClassifier');
}
/**
* Grants permission to delete a connection
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-connections.html#aws-glue-api-catalog-connections-DeleteConnection
*/
public toDeleteConnection() {
return this.to('DeleteConnection');
}
/**
* Grants permission to delete a crawler
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-crawling.html#aws-glue-api-crawler-crawling-DeleteCrawler
*/
public toDeleteCrawler() {
return this.to('DeleteCrawler');
}
/**
* Grants permission to delete a database
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-databases.html#aws-glue-api-catalog-databases-DeleteDatabase
*/
public toDeleteDatabase() {
return this.to('DeleteDatabase');
}
/**
* Grants permission to delete a development endpoint
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-dev-endpoint.html#aws-glue-api-dev-endpoint-DeleteDevEndpoint
*/
public toDeleteDevEndpoint() {
return this.to('DeleteDevEndpoint');
}
/**
* Grants permission to delete a job
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-job.html#aws-glue-api-jobs-job-DeleteJob
*/
public toDeleteJob() {
return this.to('DeleteJob');
}
/**
* Grants permission to delete an ML Transform
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-machine-learning-api.html#aws-glue-api-machine-learning-api-DeleteMLTransform
*/
public toDeleteMLTransform() {
return this.to('DeleteMLTransform');
}
/**
* Grants permission to delete a partition
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-partitions.html#aws-glue-api-catalog-partitions-DeletePartition
*/
public toDeletePartition() {
return this.to('DeletePartition');
}
/**
* Grants permission to delete a schema registry
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-schema-registry-api.html#aws-glue-api-schema-registry-api-DeleteRegistry
*/
public toDeleteRegistry() {
return this.to('DeleteRegistry');
}
/**
* Grants permission to delete a resource policy
*
* Access Level: Permissions management
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-security.html#aws-glue-api-jobs-security-DeleteResourcePolicy
*/
public toDeleteResourcePolicy() {
return this.to('DeleteResourcePolicy');
}
/**
* Grants permission to delete a schema container
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-schema-registry-api.html#aws-glue-api-schema-registry-api-DeleteSchema
*/
public toDeleteSchema() {
return this.to('DeleteSchema');
}
/**
* Grants permission to delete a range of schema versions
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-schema-registry-api.html#aws-glue-api-schema-registry-api-DeleteSchemaVersions
*/
public toDeleteSchemaVersions() {
return this.to('DeleteSchemaVersions');
}
/**
* Grants permission to delete a security configuration
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-security.html#aws-glue-api-jobs-security-DeleteSecurityConfiguration
*/
public toDeleteSecurityConfiguration() {
return this.to('DeleteSecurityConfiguration');
}
/**
* Grants permission to delete a table
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-tables.html#aws-glue-api-catalog-tables-DeleteTable
*/
public toDeleteTable() {
return this.to('DeleteTable');
}
/**
* Grants permission to delete a version of a table
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-tables.html#aws-glue-api-catalog-tables-DeleteTableVersion
*/
public toDeleteTableVersion() {
return this.to('DeleteTableVersion');
}
/**
* Grants permission to delete a trigger
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-trigger.html#aws-glue-api-jobs-trigger-DeleteTrigger
*/
public toDeleteTrigger() {
return this.to('DeleteTrigger');
}
/**
* Grants permission to delete a function definition
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-functions.html#aws-glue-api-catalog-functions-DeleteUserDefinedFunction
*/
public toDeleteUserDefinedFunction() {
return this.to('DeleteUserDefinedFunction');
}
/**
* Grants permission to delete a workflow
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-workflow.html#aws-glue-api-workflow-DeleteWorkflow
*/
public toDeleteWorkflow() {
return this.to('DeleteWorkflow');
}
/**
* Grants permission to retrieve the catalog import status
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-migration.html#aws-glue-api-catalog-migration-GetCatalogImportStatus
*/
public toGetCatalogImportStatus() {
return this.to('GetCatalogImportStatus');
}
/**
* Grants permission to retrieve a classifier
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-classifiers.html#aws-glue-api-crawler-classifiers-GetClassifier
*/
public toGetClassifier() {
return this.to('GetClassifier');
}
/**
* Grants permission to list all classifiers
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-classifiers.html#aws-glue-api-crawler-classifiers-GetClassifiers
*/
public toGetClassifiers() {
return this.to('GetClassifiers');
}
/**
* Grants permission to retrieve a connection
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-connections.html#aws-glue-api-catalog-connections-GetConnection
*/
public toGetConnection() {
return this.to('GetConnection');
}
/**
* Grants permission to retrieve a list of connections
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-connections.html#aws-glue-api-catalog-connections-GetConnections
*/
public toGetConnections() {
return this.to('GetConnections');
}
/**
* Grants permission to retrieve a crawler
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-crawling.html#aws-glue-api-crawler-crawling-GetCrawler
*/
public toGetCrawler() {
return this.to('GetCrawler');
}
/**
* Grants permission to retrieve metrics about crawlers
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-crawling.html#aws-glue-api-crawler-crawling-GetCrawlerMetrics
*/
public toGetCrawlerMetrics() {
return this.to('GetCrawlerMetrics');
}
/**
* Grants permission to retrieve all crawlers
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-crawling.html#aws-glue-api-crawler-crawling-GetCrawlers
*/
public toGetCrawlers() {
return this.to('GetCrawlers');
}
/**
* Grants permission to retrieve catalog encryption settings
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-security.html#aws-glue-api-jobs-security-GetDataCatalogEncryptionSettings
*/
public toGetDataCatalogEncryptionSettings() {
return this.to('GetDataCatalogEncryptionSettings');
}
/**
* Grants permission to retrieve a database
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-databases.html#aws-glue-api-catalog-databases-GetDatabase
*/
public toGetDatabase() {
return this.to('GetDatabase');
}
/**
* Grants permission to retrieve all databases
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-databases.html#aws-glue-api-catalog-databases-GetDatabases
*/
public toGetDatabases() {
return this.to('GetDatabases');
}
/**
* Grants permission to transform a script into a directed acyclic graph (DAG)
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-etl-script-generation.html#aws-glue-api-etl-script-generation-GetDataflowGraph
*/
public toGetDataflowGraph() {
return this.to('GetDataflowGraph');
}
/**
* Grants permission to retrieve a development endpoint
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-dev-endpoint.html#aws-glue-api-dev-endpoint-GetDevEndpoint
*/
public toGetDevEndpoint() {
return this.to('GetDevEndpoint');
}
/**
* Grants permission to retrieve all development endpoints
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-dev-endpoint.html#aws-glue-api-dev-endpoint-GetDevEndpoints
*/
public toGetDevEndpoints() {
return this.to('GetDevEndpoints');
}
/**
* Grants permission to retrieve a job
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-job.html#aws-glue-api-jobs-job-GetJob
*/
public toGetJob() {
return this.to('GetJob');
}
/**
* Grants permission to retrieve a job bookmark
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-runs.html#aws-glue-api-jobs-job-GetJobBookmark
*/
public toGetJobBookmark() {
return this.to('GetJobBookmark');
}
/**
* Grants permission to retrieve a job run
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-runs.html#aws-glue-api-jobs-runs-GetJobRun
*/
public toGetJobRun() {
return this.to('GetJobRun');
}
/**
* Grants permission to retrieve all job runs of a job
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-runs.html#aws-glue-api-jobs-runs-GetJobRuns
*/
public toGetJobRuns() {
return this.to('GetJobRuns');
}
/**
* Grants permission to retrieve all current jobs
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-job.html#aws-glue-api-jobs-job-GetJobs
*/
public toGetJobs() {
return this.to('GetJobs');
}
/**
* Grants permission to retrieve an ML Task Run
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-machine-learning-api.html#aws-glue-api-machine-learning-api-GetMLTaskRun
*/
public toGetMLTaskRun() {
return this.to('GetMLTaskRun');
}
/**
* Grants permission to retrieve all ML Task Runs
*
* Access Level: List
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-machine-learning-api.html#aws-glue-api-machine-learning-api-GetMLTaskRuns
*/
public toGetMLTaskRuns() {
return this.to('GetMLTaskRuns');
}
/**
* Grants permission to retrieve an ML Transform
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-machine-learning-api.html#aws-glue-api-machine-learning-api-GetMLTransform
*/
public toGetMLTransform() {
return this.to('GetMLTransform');
}
/**
* Grants permission to retrieve all ML Transforms
*
* Access Level: List
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-machine-learning-api.html#aws-glue-api-machine-learning-api-GetMLTransforms
*/
public toGetMLTransforms() {
return this.to('GetMLTransforms');
}
/**
* Grants permission to create a mapping
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-etl-script-generation.html#aws-glue-api-etl-script-generation-GetMapping
*/
public toGetMapping() {
return this.to('GetMapping');
}
/**
* Grants permission to retrieve a partition
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-partitions.html#aws-glue-api-catalog-partitions-GetPartition
*/
public toGetPartition() {
return this.to('GetPartition');
}
/**
* Grants permission to retrieve the partitions of a table
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-partitions.html#aws-glue-api-catalog-partitions-GetPartitions
*/
public toGetPartitions() {
return this.to('GetPartitions');
}
/**
* Grants permission to retrieve a mapping for a script
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-etl-script-generation.html#aws-glue-api-etl-script-generation-GetPlan
*/
public toGetPlan() {
return this.to('GetPlan');
}
/**
* Grants permission to retrieve a schema registry
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-schema-registry-api.html#aws-glue-api-schema-registry-api-GetRegistry
*/
public toGetRegistry() {
return this.to('GetRegistry');
}
/**
* Grants permission to retrieve resource policies
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-security.html#aws-glue-api-jobs-security-GetResourcePolicies
*/
public toGetResourcePolicies() {
return this.to('GetResourcePolicies');
}
/**
* Grants permission to retrieve a resource policy
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-security.html#aws-glue-api-jobs-security-GetResourcePolicy
*/
public toGetResourcePolicy() {
return this.to('GetResourcePolicy');
}
/**
* Grants permission to retrieve a schema container
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-schema-registry-api.html#aws-glue-api-schema-registry-api-GetSchema
*/
public toGetSchema() {
return this.to('GetSchema');
}
/**
* Grants permission to retrieve a schema version based on schema definition
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-schema-registry-api.html#aws-glue-api-schema-registry-api-GetSchemaByDefinition
*/
public toGetSchemaByDefinition() {
return this.to('GetSchemaByDefinition');
}
/**
* Grants permission to retrieve a schema version
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-schema-registry-api.html#aws-glue-api-schema-registry-api-GetSchemaVersion
*/
public toGetSchemaVersion() {
return this.to('GetSchemaVersion');
}
/**
* Grants permission to compare two schema versions in schema registry
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-schema-registry-api.html#aws-glue-api-schema-registry-api-GetSchemaVersionsDiff
*/
public toGetSchemaVersionsDiff() {
return this.to('GetSchemaVersionsDiff');
}
/**
* Grants permission to retrieve a security configuration
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-security.html#aws-glue-api-jobs-security-GetSecurityConfiguration
*/
public toGetSecurityConfiguration() {
return this.to('GetSecurityConfiguration');
}
/**
* Grants permission to retrieve one or more security configurations
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-security.html#aws-glue-api-jobs-security-GetSecurityConfigurations
*/
public toGetSecurityConfigurations() {
return this.to('GetSecurityConfigurations');
}
/**
* Grants permission to retrieve a table
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-tables.html#aws-glue-api-catalog-tables-GetTable
*/
public toGetTable() {
return this.to('GetTable');
}
/**
* Grants permission to retrieve a version of a table
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-tables.html#aws-glue-api-catalog-tables-GetTableVersion
*/
public toGetTableVersion() {
return this.to('GetTableVersion');
}
/**
* Grants permission to retrieve a list of versions of a table
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-tables.html#aws-glue-api-catalog-tables-GetTableVersions
*/
public toGetTableVersions() {
return this.to('GetTableVersions');
}
/**
* Grants permission to retrieve the tables in a database
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-tables.html#aws-glue-api-catalog-tables-GetTables
*/
public toGetTables() {
return this.to('GetTables');
}
/**
* Grants permission to retrieve all tags associated with a resource
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-tags.html#aws-glue-api-tags-UntagResource
*/
public toGetTags() {
return this.to('GetTags');
}
/**
* Grants permission to retrieve a trigger
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-trigger.html#aws-glue-api-jobs-trigger-GetTrigger
*/
public toGetTrigger() {
return this.to('GetTrigger');
}
/**
* Grants permission to retrieve the triggers associated with a job
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-trigger.html#aws-glue-api-jobs-trigger-GetTriggers
*/
public toGetTriggers() {
return this.to('GetTriggers');
}
/**
* Grants permission to retrieve a function definition.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-functions.html#aws-glue-api-catalog-functions-GetUserDefinedFunction
*/
public toGetUserDefinedFunction() {
return this.to('GetUserDefinedFunction');
}
/**
* Grants permission to retrieve multiple function definitions
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-functions.html#aws-glue-api-catalog-functions-GetUserDefinedFunctions
*/
public toGetUserDefinedFunctions() {
return this.to('GetUserDefinedFunctions');
}
/**
* Grants permission to retrieve a workflow
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-workflow.html#aws-glue-api-workflow-GetWorkflow
*/
public toGetWorkflow() {
return this.to('GetWorkflow');
}
/**
* Grants permission to retrieve a workflow run
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-workflow.html#aws-glue-api-workflow-GetWorkflowRun
*/
public toGetWorkflowRun() {
return this.to('GetWorkflowRun');
}
/**
* Grants permission to retrieve workflow run properties
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-workflow.html#aws-glue-api-workflow-GetWorkflowRunProperties
*/
public toGetWorkflowRunProperties() {
return this.to('GetWorkflowRunProperties');
}
/**
* Grants permission to retrieve all runs of a workflow
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-workflow.html#aws-glue-api-workflow-GetWorkflowRuns
*/
public toGetWorkflowRuns() {
return this.to('GetWorkflowRuns');
}
/**
* Grants permission to import an Athena data catalog into AWS Glue
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-migration.html#aws-glue-api-catalog-migration-ImportCatalogToGlue
*/
public toImportCatalogToGlue() {
return this.to('ImportCatalogToGlue');
}
/**
* Grants permission to retrieve all crawlers
*
* Access Level: List
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-crawling.html#aws-glue-api-crawler-crawling-ListCrawlers
*/
public toListCrawlers() {
return this.to('ListCrawlers');
}
/**
* Grants permission to retrieve all development endpoints
*
* Access Level: List
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-dev-endpoint.html#aws-glue-api-dev-endpoint-ListDevEndpoints
*/
public toListDevEndpoints() {
return this.to('ListDevEndpoints');
}
/**
* Grants permission to retrieve all current jobs
*
* Access Level: List
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-job.html#aws-glue-api-jobs-job-ListJobs
*/
public toListJobs() {
return this.to('ListJobs');
}
/**
* Grants permission to retrieve all ML Transforms
*
* Access Level: List
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-machine-learning-api.html#aws-glue-api-machine-learning-api-ListMLTransforms
*/
public toListMLTransforms() {
return this.to('ListMLTransforms');
}
/**
* Grants permission to retrieve a list of schema registries
*
* Access Level: List
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-schema-registry-api.html#aws-glue-api-schema-registry-api-ListRegistries
*/
public toListRegistries() {
return this.to('ListRegistries');
}
/**
* Grants permission to retrieve a list of schema versions
*
* Access Level: List
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-schema-registry-api.html#aws-glue-api-schema-registry-api-ListSchemaVersions
*/
public toListSchemaVersions() {
return this.to('ListSchemaVersions');
}
/**
* Grants permission to retrieve a list of schema containers
*
* Access Level: List
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-schema-registry-api.html#aws-glue-api-schema-registry-api-ListSchemas
*/
public toListSchemas() {
return this.to('ListSchemas');
}
/**
* Grants permission to retrieve all triggers
*
* Access Level: List
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-trigger.html#aws-glue-api-jobs-trigger-ListTriggers
*/
public toListTriggers() {
return this.to('ListTriggers');
}
/**
* Grants permission to retrieve all workflows
*
* Access Level: List
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-workflow.html#aws-glue-api-workflow-ListWorkflows
*/
public toListWorkflows() {
return this.to('ListWorkflows');
}
/**
* Grants permission to notify an event to the event-driven workflow
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/starting-workflow-eventbridge.html
*/
public toNotifyEvent() {
return this.to('NotifyEvent');
}
/**
* Grants permission to update catalog encryption settings
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-security.html#aws-glue-api-jobs-security-PutDataCatalogEncryptionSettings
*/
public toPutDataCatalogEncryptionSettings() {
return this.to('PutDataCatalogEncryptionSettings');
}
/**
* Grants permission to update a resource policy
*
* Access Level: Permissions management
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-security.html#aws-glue-api-jobs-security-PutResourcePolicy
*/
public toPutResourcePolicy() {
return this.to('PutResourcePolicy');
}
/**
* Grants permission to add metadata to schema version
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-schema-registry-api.html#aws-glue-api-schema-registry-api-PutSchemaVersionMetadata
*/
public toPutSchemaVersionMetadata() {
return this.to('PutSchemaVersionMetadata');
}
/**
* Grants permission to update workflow run properties
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-workflow.html#aws-glue-api-workflow-PutWorkflowRunProperties
*/
public toPutWorkflowRunProperties() {
return this.to('PutWorkflowRunProperties');
}
/**
* Grants permission to fetch metadata for a schema version
*
* Access Level: List
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-schema-registry-api.html#aws-glue-api-schema-registry-api-QuerySchemaVersionMetadata
*/
public toQuerySchemaVersionMetadata() {
return this.to('QuerySchemaVersionMetadata');
}
/**
* Grants permission to create a new schema version
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-schema-registry-api.html#aws-glue-api-schema-registry-api-RegisterSchemaVersion
*/
public toRegisterSchemaVersion() {
return this.to('RegisterSchemaVersion');
}
/**
* Grants permission to remove metadata from schema version
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-schema-registry-api.html#aws-glue-api-schema-registry-api-RemoveSchemaVersionMetadata
*/
public toRemoveSchemaVersionMetadata() {
return this.to('RemoveSchemaVersionMetadata');
}
/**
* Grants permission to reset a job bookmark
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-runs.html#aws-glue-api-jobs-runs-ResetJobBookmark
*/
public toResetJobBookmark() {
return this.to('ResetJobBookmark');
}
/**
* Grants permission to resume a workflow run
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-workflow.html#aws-glue-api-workflow-ResumeWorkflowRun
*/
public toResumeWorkflowRun() {
return this.to('ResumeWorkflowRun');
}
/**
* Grants permission to retrieve the tables in the catalog
*
* Access Level: Read
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-tables.html#aws-glue-api-catalog-tables-SearchTables
*/
public toSearchTables() {
return this.to('SearchTables');
}
/**
* Grants permission to start a crawler
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-crawling.html#aws-glue-api-crawler-crawling-StartCrawler
*/
public toStartCrawler() {
return this.to('StartCrawler');
}
/**
* Grants permission to change the schedule state of a crawler to SCHEDULED
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-scheduler.html#aws-glue-api-crawler-scheduler-StartCrawlerSchedule
*/
public toStartCrawlerSchedule() {
return this.to('StartCrawlerSchedule');
}
/**
* Grants permission to start an Export Labels ML Task Run
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-machine-learning-api.html#aws-glue-api-machine-learning-api-StartExportLabelsTaskRun
*/
public toStartExportLabelsTaskRun() {
return this.to('StartExportLabelsTaskRun');
}
/**
* Grants permission to start an Import Labels ML Task Run
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-machine-learning-api.html#aws-glue-api-machine-learning-api-StartImportLabelsTaskRun
*/
public toStartImportLabelsTaskRun() {
return this.to('StartImportLabelsTaskRun');
}
/**
* Grants permission to start running a job
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-runs.html#aws-glue-api-jobs-runs-StartJobRun
*/
public toStartJobRun() {
return this.to('StartJobRun');
}
/**
* Grants permission to start an Evaluation ML Task Run
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-machine-learning-api.html#aws-glue-api-machine-learning-api-StartMLEvaluationTaskRun
*/
public toStartMLEvaluationTaskRun() {
return this.to('StartMLEvaluationTaskRun');
}
/**
* Grants permission to start a Labeling Set Generation ML Task Run
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-machine-learning-api.html#aws-glue-api-machine-learning-api-StartMLLabelingSetGenerationTaskRun
*/
public toStartMLLabelingSetGenerationTaskRun() {
return this.to('StartMLLabelingSetGenerationTaskRun');
}
/**
* Grants permission to start a trigger
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-trigger.html#aws-glue-api-jobs-trigger-StartTrigger
*/
public toStartTrigger() {
return this.to('StartTrigger');
}
/**
* Grants permission to start running a workflow
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-workflow.html#aws-glue-api-workflow-StartWorkflowRun
*/
public toStartWorkflowRun() {
return this.to('StartWorkflowRun');
}
/**
* Grants permission to stop a running crawler
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-crawling.html#aws-glue-api-crawler-crawling-StopCrawler
*/
public toStopCrawler() {
return this.to('StopCrawler');
}
/**
* Grants permission to set the schedule state of a crawler to NOT_SCHEDULED
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-scheduler.html#aws-glue-api-crawler-scheduler-StopCrawlerSchedule
*/
public toStopCrawlerSchedule() {
return this.to('StopCrawlerSchedule');
}
/**
* Grants permission to stop a trigger
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-trigger.html#aws-glue-api-jobs-trigger-StopTrigger
*/
public toStopTrigger() {
return this.to('StopTrigger');
}
/**
* Grants permission to stop a workflow run
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-workflow.html#aws-glue-api-workflow-StopWorkflowRun
*/
public toStopWorkflowRun() {
return this.to('StopWorkflowRun');
}
/**
* Grants permission to add tags to a resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
* - .ifAwsRequestTag()
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-tags.html#aws-glue-api-tags-TagResource
*/
public toTagResource() {
return this.to('TagResource');
}
/**
* Grants permission to remove tags associated with a resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-tags.html#aws-glue-api-tags-UntagResource
*/
public toUntagResource() {
return this.to('UntagResource');
}
/**
* Grants permission to update a classifier
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-classifiers.html#aws-glue-api-crawler-classifiers-UpdateClassifier
*/
public toUpdateClassifier() {
return this.to('UpdateClassifier');
}
/**
* Grants permission to update a connection
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-connections.html#aws-glue-api-catalog-connections-UpdateConnection
*/
public toUpdateConnection() {
return this.to('UpdateConnection');
}
/**
* Grants permission to update a crawler
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-crawling.html#aws-glue-api-crawler-crawling-UpdateCrawler
*/
public toUpdateCrawler() {
return this.to('UpdateCrawler');
}
/**
* Grants permission to update the schedule of a crawler
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-scheduler.html#aws-glue-api-crawler-scheduler-UpdateCrawlerSchedule
*/
public toUpdateCrawlerSchedule() {
return this.to('UpdateCrawlerSchedule');
}
/**
* Grants permission to update a database
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-databases.html#aws-glue-api-catalog-databases-UpdateDatabase
*/
public toUpdateDatabase() {
return this.to('UpdateDatabase');
}
/**
* Grants permission to update a development endpoint
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-dev-endpoint.html#aws-glue-api-dev-endpoint-UpdateDevEndpoint
*/
public toUpdateDevEndpoint() {
return this.to('UpdateDevEndpoint');
}
/**
* Grants permission to update a job
*
* Access Level: Write
*
* Possible conditions:
* - .ifVpcIds()
* - .ifSubnetIds()
* - .ifSecurityGroupIds()
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-job.html#aws-glue-api-jobs-job-UpdateJob
*/
public toUpdateJob() {
return this.to('UpdateJob');
}
/**
* Grants permission to update an ML Transform
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-machine-learning-api.html#aws-glue-api-machine-learning-api-UpdateMLTransform
*/
public toUpdateMLTransform() {
return this.to('UpdateMLTransform');
}
/**
* Grants permission to update a partition
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-partitions.html#aws-glue-api-catalog-partitions-UpdatePartition
*/
public toUpdatePartition() {
return this.to('UpdatePartition');
}
/**
* Grants permission to update a schema registry
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-schema-registry-api.html#aws-glue-api-schema-registry-api-UpdateRegistry
*/
public toUpdateRegistry() {
return this.to('UpdateRegistry');
}
/**
* Grants permission to update a schema container
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-schema-registry-api.html#aws-glue-api-schema-registry-api-UpdateSchema
*/
public toUpdateSchema() {
return this.to('UpdateSchema');
}
/**
* Grants permission to update a table
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-tables.html#aws-glue-api-catalog-tables-UpdateTable
*/
public toUpdateTable() {
return this.to('UpdateTable');
}
/**
* Grants permission to update a trigger
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-trigger.html#aws-glue-api-jobs-trigger-UpdateTrigger
*/
public toUpdateTrigger() {
return this.to('UpdateTrigger');
}
/**
* Grants permission to update a function definition
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-functions.html#aws-glue-api-catalog-functions-UpdateUserDefinedFunction
*/
public toUpdateUserDefinedFunction() {
return this.to('UpdateUserDefinedFunction');
}
/**
* Grants permission to update a workflow
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-workflow.html#aws-glue-api-workflow-UpdateWorkflow
*/
public toUpdateWorkflow() {
return this.to('UpdateWorkflow');
}
/**
* Grants permission to use an ML Transform from within a Glue ETL Script
*
* Access Level: Write
*
* https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-machine-learning-api.html
*/
public toUseMLTransforms() {
return this.to('UseMLTransforms');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"BatchCreatePartition",
"BatchDeleteConnection",
"BatchDeletePartition",
"BatchDeleteTable",
"BatchDeleteTableVersion",
"BatchStopJobRun",
"CancelMLTaskRun",
"CreateClassifier",
"CreateConnection",
"CreateCrawler",
"CreateDatabase",
"CreateDevEndpoint",
"CreateJob",
"CreateMLTransform",
"CreatePartition",
"CreateRegistry",
"CreateSchema",
"CreateScript",
"CreateSecurityConfiguration",
"CreateTable",
"CreateTrigger",
"CreateUserDefinedFunction",
"CreateWorkflow",
"DeleteClassifier",
"DeleteConnection",
"DeleteCrawler",
"DeleteDatabase",
"DeleteDevEndpoint",
"DeleteJob",
"DeleteMLTransform",
"DeletePartition",
"DeleteRegistry",
"DeleteSchema",
"DeleteSchemaVersions",
"DeleteSecurityConfiguration",
"DeleteTable",
"DeleteTableVersion",
"DeleteTrigger",
"DeleteUserDefinedFunction",
"DeleteWorkflow",
"ImportCatalogToGlue",
"NotifyEvent",
"PutDataCatalogEncryptionSettings",
"PutSchemaVersionMetadata",
"PutWorkflowRunProperties",
"RegisterSchemaVersion",
"RemoveSchemaVersionMetadata",
"ResetJobBookmark",
"ResumeWorkflowRun",
"StartCrawler",
"StartCrawlerSchedule",
"StartExportLabelsTaskRun",
"StartImportLabelsTaskRun",
"StartJobRun",
"StartMLEvaluationTaskRun",
"StartMLLabelingSetGenerationTaskRun",
"StartTrigger",
"StartWorkflowRun",
"StopCrawler",
"StopCrawlerSchedule",
"StopTrigger",
"StopWorkflowRun",
"UpdateClassifier",
"UpdateConnection",
"UpdateCrawler",
"UpdateCrawlerSchedule",
"UpdateDatabase",
"UpdateDevEndpoint",
"UpdateJob",
"UpdateMLTransform",
"UpdatePartition",
"UpdateRegistry",
"UpdateSchema",
"UpdateTable",
"UpdateTrigger",
"UpdateUserDefinedFunction",
"UpdateWorkflow",
"UseMLTransforms"
],
"Read": [
"BatchGetCrawlers",
"BatchGetDevEndpoints",
"BatchGetJobs",
"BatchGetPartition",
"BatchGetTriggers",
"BatchGetWorkflows",
"CheckSchemaVersionValidity",
"GetCatalogImportStatus",
"GetClassifier",
"GetClassifiers",
"GetConnection",
"GetConnections",
"GetCrawler",
"GetCrawlerMetrics",
"GetCrawlers",
"GetDataCatalogEncryptionSettings",
"GetDatabase",
"GetDatabases",
"GetDataflowGraph",
"GetDevEndpoint",
"GetDevEndpoints",
"GetJob",
"GetJobBookmark",
"GetJobRun",
"GetJobRuns",
"GetJobs",
"GetMLTaskRun",
"GetMLTransform",
"GetMapping",
"GetPartition",
"GetPartitions",
"GetPlan",
"GetRegistry",
"GetResourcePolicies",
"GetResourcePolicy",
"GetSchema",
"GetSchemaByDefinition",
"GetSchemaVersion",
"GetSchemaVersionsDiff",
"GetSecurityConfiguration",
"GetSecurityConfigurations",
"GetTable",
"GetTableVersion",
"GetTableVersions",
"GetTables",
"GetTags",
"GetTrigger",
"GetTriggers",
"GetUserDefinedFunction",
"GetUserDefinedFunctions",
"GetWorkflow",
"GetWorkflowRun",
"GetWorkflowRunProperties",
"GetWorkflowRuns",
"SearchTables"
],
"Permissions management": [
"DeleteResourcePolicy",
"PutResourcePolicy"
],
"List": [
"GetMLTaskRuns",
"GetMLTransforms",
"ListCrawlers",
"ListDevEndpoints",
"ListJobs",
"ListMLTransforms",
"ListRegistries",
"ListSchemaVersions",
"ListSchemas",
"ListTriggers",
"ListWorkflows",
"QuerySchemaVersionMetadata"
],
"Tagging": [
"TagResource",
"UntagResource"
]
};
/**
* Adds a resource of type catalog to the statement
*
* https://docs.aws.amazon.com/glue/latest/dg/glue-specifying-resource-arns.html
*
* @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`.
*/
public onCatalog(account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:glue:${Region}:${Account}:catalog';
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 database to the statement
*
* https://docs.aws.amazon.com/glue/latest/dg/glue-specifying-resource-arns.html
*
* @param databaseName - Identifier for the databaseName.
* @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`.
*/
public onDatabase(databaseName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:glue:${Region}:${Account}:database/${DatabaseName}';
arn = arn.replace('${DatabaseName}', databaseName);
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 table to the statement
*
* https://docs.aws.amazon.com/glue/latest/dg/glue-specifying-resource-arns.html
*
* @param databaseName - Identifier for the databaseName.
* @param tableName - Identifier for the tableName.
* @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`.
*/
public onTable(databaseName: string, tableName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:glue:${Region}:${Account}:table/${DatabaseName}/${TableName}';
arn = arn.replace('${DatabaseName}', databaseName);
arn = arn.replace('${TableName}', tableName);
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 tableversion to the statement
*
* https://docs.aws.amazon.com/glue/latest/dg/glue-specifying-resource-arns.html
*
* @param databaseName - Identifier for the databaseName.
* @param tableName - Identifier for the tableName.
* @param tableVersionName - Identifier for the tableVersionName.
* @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`.
*/
public onTableversion(databaseName: string, tableName: string, tableVersionName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:glue:${Region}:${Account}:tableVersion/${DatabaseName}/${TableName}/${TableVersionName}';
arn = arn.replace('${DatabaseName}', databaseName);
arn = arn.replace('${TableName}', tableName);
arn = arn.replace('${TableVersionName}', tableVersionName);
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 connection to the statement
*
* https://docs.aws.amazon.com/glue/latest/dg/glue-specifying-resource-arns.html
*
* @param connectionName - Identifier for the connectionName.
* @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`.
*/
public onConnection(connectionName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:glue:${Region}:${Account}:connection/${ConnectionName}';
arn = arn.replace('${ConnectionName}', connectionName);
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 userdefinedfunction to the statement
*
* https://docs.aws.amazon.com/glue/latest/dg/glue-specifying-resource-arns.html
*
* @param databaseName - Identifier for the databaseName.
* @param userDefinedFunctionName - Identifier for the userDefinedFunctionName.
* @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`.
*/
public onUserdefinedfunction(databaseName: string, userDefinedFunctionName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:glue:${Region}:${Account}:userDefinedFunction/${DatabaseName}/${UserDefinedFunctionName}';
arn = arn.replace('${DatabaseName}', databaseName);
arn = arn.replace('${UserDefinedFunctionName}', userDefinedFunctionName);
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 devendpoint to the statement
*
* https://docs.aws.amazon.com/glue/latest/dg/glue-specifying-resource-arns.html
*
* @param devEndpointName - Identifier for the devEndpointName.
* @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 onDevendpoint(devEndpointName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:glue:${Region}:${Account}:devEndpoint/${DevEndpointName}';
arn = arn.replace('${DevEndpointName}', devEndpointName);
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 job to the statement
*
* https://docs.aws.amazon.com/glue/latest/dg/glue-specifying-resource-arns.html
*
* @param jobName - Identifier for the jobName.
* @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 onJob(jobName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:glue:${Region}:${Account}:job/${JobName}';
arn = arn.replace('${JobName}', jobName);
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 trigger to the statement
*
* https://docs.aws.amazon.com/glue/latest/dg/glue-specifying-resource-arns.html
*
* @param triggerName - Identifier for the triggerName.
* @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 onTrigger(triggerName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:glue:${Region}:${Account}:trigger/${TriggerName}';
arn = arn.replace('${TriggerName}', triggerName);
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 crawler to the statement
*
* https://docs.aws.amazon.com/glue/latest/dg/glue-specifying-resource-arns.html
*
* @param crawlerName - Identifier for the crawlerName.
* @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 onCrawler(crawlerName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:glue:${Region}:${Account}:crawler/${CrawlerName}';
arn = arn.replace('${CrawlerName}', crawlerName);
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 workflow to the statement
*
* https://docs.aws.amazon.com/glue/latest/dg/glue-specifying-resource-arns.html
*
* @param workflowName - Identifier for the workflowName.
* @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 onWorkflow(workflowName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:glue:${Region}:${Account}:workflow/${WorkflowName}';
arn = arn.replace('${WorkflowName}', workflowName);
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 mlTransform to the statement
*
* https://docs.aws.amazon.com/glue/latest/dg/glue-specifying-resource-arns.html
*
* @param transformId - Identifier for the transformId.
* @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 onMlTransform(transformId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:glue:${Region}:${Account}:mlTransform/${TransformId}';
arn = arn.replace('${TransformId}', transformId);
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 registry to the statement
*
* https://docs.aws.amazon.com/glue/latest/dg/glue-specifying-resource-arns.html
*
* @param registryName - Identifier for the registryName.
* @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 onRegistry(registryName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:glue:${Region}:${Account}:registry/${RegistryName}';
arn = arn.replace('${RegistryName}', registryName);
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 schema to the statement
*
* https://docs.aws.amazon.com/glue/latest/dg/glue-specifying-resource-arns.html
*
* @param schemaName - Identifier for the schemaName.
* @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 onSchema(schemaName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:glue:${Region}:${Account}:schema/${SchemaName}';
arn = arn.replace('${SchemaName}', schemaName);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Filters access by the service from which the credentials of the request is issued
*
* https://docs.aws.amazon.com/glue/latest/dg/using-identity-based-policies.html#glue-identity-based-policy-condition-keys
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifCredentialIssuingService(value: string | string[], operator?: Operator | string) {
return this.if(`CredentialIssuingService`, value, operator || 'StringLike');
}
/**
* Filters access by the service from which the credentials of the request is obtained by assuming the customer role
*
* https://docs.aws.amazon.com/glue/latest/dg/using-identity-based-policies.html#glue-identity-based-policy-condition-keys
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifRoleAssumedBy(value: string | string[], operator?: Operator | string) {
return this.if(`RoleAssumedBy`, value, operator || 'StringLike');
}
/**
* Filters access by the ID of security groups configured for the Glue job
*
* https://docs.aws.amazon.com/glue/latest/dg/using-identity-based-policies.html#glue-identity-based-policy-condition-keys
*
* Applies to actions:
* - .toCreateJob()
* - .toUpdateJob()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifSecurityGroupIds(value: string | string[], operator?: Operator | string) {
return this.if(`SecurityGroupIds`, value, operator || 'StringLike');
}
/**
* Filters access by the ID of subnets configured for the Glue job
*
* https://docs.aws.amazon.com/glue/latest/dg/using-identity-based-policies.html#glue-identity-based-policy-condition-keys
*
* Applies to actions:
* - .toCreateJob()
* - .toUpdateJob()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifSubnetIds(value: string | string[], operator?: Operator | string) {
return this.if(`SubnetIds`, value, operator || 'StringLike');
}
/**
* Filters access by the ID of the VPC configured for the Glue job
*
* https://docs.aws.amazon.com/glue/latest/dg/using-identity-based-policies.html#glue-identity-based-policy-condition-keys
*
* Applies to actions:
* - .toCreateJob()
* - .toUpdateJob()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifVpcIds(value: string | string[], operator?: Operator | string) {
return this.if(`VpcIds`, value, operator || 'StringLike');
}
} | the_stack |
import { I18nHtml } from "@kie-tooling-core/i18n/dist/react-components";
import { Alert } from "@patternfly/react-core/dist/js/components/Alert";
import { Button, ButtonVariant } from "@patternfly/react-core/dist/js/components/Button";
import { Form, FormGroup } from "@patternfly/react-core/dist/js/components/Form";
import { InputGroup, InputGroupText } from "@patternfly/react-core/dist/js/components/InputGroup";
import { List, ListComponent, ListItem, OrderType } from "@patternfly/react-core/dist/js/components/List";
import { Spinner } from "@patternfly/react-core/dist/js/components/Spinner";
import { Text, TextContent, TextVariants } from "@patternfly/react-core/dist/js/components/Text";
import { TextInput } from "@patternfly/react-core/dist/js/components/TextInput";
import { Wizard, WizardContextConsumer, WizardFooter } from "@patternfly/react-core/dist/js/components/Wizard";
import { ExternalLinkAltIcon } from "@patternfly/react-icons/dist/js/icons/external-link-alt-icon";
import { TimesIcon } from "@patternfly/react-icons/dist/js/icons/times-icon";
import * as React from "react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useKieToolingExtendedServices } from "../kieToolingExtendedServices/KieToolingExtendedServicesContext";
import { useOnlineI18n } from "../i18n";
import { useSettings, useSettingsDispatch } from "./SettingsContext";
import {
isConfigValid,
isHostValid,
isNamespaceValid,
isTokenValid,
OpenShiftSettingsConfig,
saveConfigCookie,
} from "../openshift/OpenShiftSettingsConfig";
import { KieToolingExtendedServicesStatus } from "../kieToolingExtendedServices/KieToolingExtendedServicesStatus";
import { DEVELOPER_SANDBOX_GET_STARTED_URL } from "../openshift/OpenShiftService";
import { OpenShiftSettingsTabMode } from "./OpenShiftSettingsTab";
import { OpenShiftInstanceStatus } from "../openshift/OpenShiftInstanceStatus";
enum WizardStepIds {
NAMESPACE = "NAMESPACE",
CREDENTIALS = "CREDENTIALS",
CONNECT = "CONNECT",
}
export function OpenShiftSettingsTabWizardConfig(props: {
setMode: React.Dispatch<React.SetStateAction<OpenShiftSettingsTabMode>>;
}) {
const kieToolingExtendedServices = useKieToolingExtendedServices();
const { i18n } = useOnlineI18n();
const settings = useSettings();
const settingsDispatch = useSettingsDispatch();
const [config, setConfig] = useState(settings.openshift.config);
const [isConfigValidated, setConfigValidated] = useState(false);
const [isSaveLoading, setSaveLoading] = useState(false);
const [isConnectLoading, setConnectLoading] = useState(false);
const onClearHost = useCallback(() => setConfig({ ...config, host: "" }), [config]);
const onClearNamespace = useCallback(() => setConfig({ ...config, namespace: "" }), [config]);
const onClearToken = useCallback(() => setConfig({ ...config, token: "" }), [config]);
const isNamespaceValidated = useMemo(() => {
return isNamespaceValid(config.namespace);
}, [config.namespace]);
const isHostValidated = useMemo(() => {
return isHostValid(config.host);
}, [config.host]);
const isTokenValidated = useMemo(() => {
return isTokenValid(config.token);
}, [config.token]);
useEffect(() => {
setConfigValidated(isConfigValid(config));
}, [config]);
useEffect(() => {
if (kieToolingExtendedServices.status !== KieToolingExtendedServicesStatus.RUNNING) {
return;
}
setConfig(settings.openshift.config);
}, [settings.openshift.config, kieToolingExtendedServices.status]);
const onClose = useCallback(() => {
props.setMode(OpenShiftSettingsTabMode.SIMPLE);
}, []);
const resetConfig = useCallback((config: OpenShiftSettingsConfig) => {
setConfigValidated(false);
setSaveLoading(false);
setConnectLoading(false);
setConfig(config);
}, []);
const onNamespaceInputChanged = useCallback((newValue: string) => {
setConfig((c) => ({ ...c, namespace: newValue }));
}, []);
const onHostInputChanged = useCallback((newValue: string) => {
setConfig((c) => ({ ...c, host: newValue }));
}, []);
const onTokenInputChanged = useCallback((newValue: string) => {
setConfig((c) => ({ ...c, token: newValue }));
}, []);
const onStepChanged = useCallback(
async ({ id }) => {
if (id === WizardStepIds.CONNECT) {
setConnectLoading(true);
setConfigValidated(await settingsDispatch.openshift.service.onCheckConfig(config));
setConnectLoading(false);
}
},
[config, settingsDispatch.openshift.service]
);
const onFinish = useCallback(async () => {
if (isSaveLoading) {
return;
}
setSaveLoading(true);
const isConfigOk = await settingsDispatch.openshift.service.onCheckConfig(config);
if (isConfigOk) {
settingsDispatch.openshift.setConfig(config);
saveConfigCookie(config);
settingsDispatch.openshift.setStatus(OpenShiftInstanceStatus.CONNECTED);
}
setConfigValidated(isConfigOk);
setSaveLoading(false);
if (!isConfigOk) {
return;
}
resetConfig(config);
}, [config, isSaveLoading, resetConfig, settingsDispatch.openshift]);
const wizardSteps = useMemo(
() => [
{
id: WizardStepIds.NAMESPACE,
name: i18n.dmnDevSandbox.configWizard.steps.first.name,
component: (
<div>
<Text component={TextVariants.p}>{i18n.dmnDevSandbox.configWizard.steps.first.introduction}</Text>
<List component={ListComponent.ol} type={OrderType.number} className="pf-u-mt-md">
<ListItem>
<TextContent>
<Text component={TextVariants.p}>
<a href={DEVELOPER_SANDBOX_GET_STARTED_URL} target={"_blank"}>
{i18n.dmnDevSandbox.configWizard.steps.first.goToGetStartedPage}
<ExternalLinkAltIcon className="pf-u-mx-sm" />
</a>
</Text>
</TextContent>
</ListItem>
<ListItem>
<TextContent>
<Text component={TextVariants.p}>{i18n.dmnDevSandbox.configWizard.steps.first.followSteps}</Text>
</TextContent>
</ListItem>
<ListItem>
<TextContent>
<Text component={TextVariants.p}>{i18n.dmnDevSandbox.configWizard.steps.first.informNamespace}</Text>
</TextContent>
</ListItem>
</List>
<Form isHorizontal={true} className="pf-u-mt-md" onSubmit={(e) => e.preventDefault()}>
<FormGroup
fieldId={"dmn-dev-sandbox-config-namespace"}
label={i18n.terms.namespace}
validated={isNamespaceValidated ? "success" : "error"}
helperTextInvalid={i18n.dmnDevSandbox.common.requiredField}
>
<InputGroup>
<TextInput
autoFocus={true}
autoComplete={"off"}
isRequired
type="text"
id="namespace-field"
name="namespace-field"
aria-label="namespace field"
value={config.namespace}
placeholder={i18n.dmnDevSandbox.configWizard.steps.first.namespacePlaceholder}
onChange={onNamespaceInputChanged}
/>
<InputGroupText>
<Button isSmall variant="plain" aria-label="Clear namespace button" onClick={onClearNamespace}>
<TimesIcon />
</Button>
</InputGroupText>
</InputGroup>
</FormGroup>
</Form>
<Text className="pf-u-my-md" component={TextVariants.p}>
{i18n.dmnDevSandbox.configWizard.steps.first.inputReason}
</Text>
</div>
),
},
{
id: WizardStepIds.CREDENTIALS,
name: i18n.dmnDevSandbox.configWizard.steps.second.name,
component: (
<div>
<Text component={TextVariants.p}>{i18n.dmnDevSandbox.configWizard.steps.second.introduction}</Text>
<List className="pf-u-my-md" component={ListComponent.ol} type={OrderType.number}>
<ListItem>
<TextContent>
<Text component={TextVariants.p}>
<I18nHtml>{i18n.dmnDevSandbox.configWizard.steps.second.accessLoginCommand}</I18nHtml>
</Text>
</TextContent>
</ListItem>
<ListItem>
<TextContent>
<Text component={TextVariants.p}>
<I18nHtml>{i18n.dmnDevSandbox.configWizard.steps.second.accessDisplayToken}</I18nHtml>
</Text>
</TextContent>
</ListItem>
<ListItem>
<TextContent>
<Text component={TextVariants.p}>
<I18nHtml>{i18n.dmnDevSandbox.configWizard.steps.second.copyInformation}</I18nHtml>
</Text>
</TextContent>
</ListItem>
</List>
<Form isHorizontal={true} className="pf-u-mt-md">
<FormGroup
fieldId={"dmn-dev-sandbox-config-host"}
label={i18n.terms.host}
validated={isHostValidated ? "success" : "error"}
helperTextInvalid={i18n.dmnDevSandbox.common.requiredField}
>
<InputGroup>
<TextInput
autoFocus={true}
autoComplete={"off"}
isRequired
type="text"
id="host-field"
name="host-field"
aria-label="Host field"
value={config.host}
placeholder={i18n.dmnDevSandbox.configWizard.steps.second.hostPlaceholder}
onChange={onHostInputChanged}
tabIndex={1}
/>
<InputGroupText>
<Button isSmall variant="plain" aria-label="Clear host button" onClick={onClearHost}>
<TimesIcon />
</Button>
</InputGroupText>
</InputGroup>
</FormGroup>
<FormGroup
fieldId={"dmn-dev-sandbox-config-token"}
label={i18n.terms.token}
validated={isTokenValidated ? "success" : "error"}
helperTextInvalid={i18n.dmnDevSandbox.common.requiredField}
>
<InputGroup>
<TextInput
autoComplete={"off"}
isRequired
type="text"
id="token-field"
name="token-field"
aria-label="Token field"
value={config.token}
placeholder={i18n.dmnDevSandbox.configWizard.steps.second.tokenPlaceholder}
onChange={onTokenInputChanged}
tabIndex={2}
/>
<InputGroupText>
<Button isSmall variant="plain" aria-label="Clear host button" onClick={onClearToken}>
<TimesIcon />
</Button>
</InputGroupText>
</InputGroup>
</FormGroup>
</Form>
<Text className="pf-u-my-md" component={TextVariants.p}>
{i18n.dmnDevSandbox.configWizard.steps.second.inputReason}
</Text>
</div>
),
},
{
id: WizardStepIds.CONNECT,
name: i18n.dmnDevSandbox.configWizard.steps.final.name,
component: (
<>
{isConnectLoading && (
<div className="kogito--editor__dmn-dev-sandbox-wizard-loading-spinner">
<Spinner isSVG size="xl" />
</div>
)}
{!isConnectLoading && isConfigValidated && (
<div>
<Alert
variant={"default"}
isInline={true}
title={i18n.dmnDevSandbox.configWizard.steps.final.connectionSuccess}
/>
<Text className="pf-u-mt-md" component={TextVariants.p}>
{i18n.dmnDevSandbox.configWizard.steps.final.introduction}
</Text>
<Text className="pf-u-mt-md" component={TextVariants.p}>
{i18n.dmnDevSandbox.configWizard.steps.final.configNote}
</Text>
</div>
)}
{!isConnectLoading && !isConfigValidated && (
<div>
<Alert
variant={"danger"}
isInline={true}
title={i18n.dmnDevSandbox.configWizard.steps.final.connectionError}
/>
<Text className="pf-u-mt-md" component={TextVariants.p}>
{i18n.dmnDevSandbox.configWizard.steps.final.connectionErrorLong}
</Text>
<Text className="pf-u-mt-md" component={TextVariants.p}>
{i18n.dmnDevSandbox.configWizard.steps.final.possibleErrorReasons.introduction}
</Text>
<List className="pf-u-my-md">
<ListItem>
<TextContent>
<Text component={TextVariants.p}>
{i18n.dmnDevSandbox.configWizard.steps.final.possibleErrorReasons.emptyField}
</Text>
</TextContent>
</ListItem>
<ListItem>
<TextContent>
<Text component={TextVariants.p}>
{i18n.dmnDevSandbox.configWizard.steps.final.possibleErrorReasons.instanceExpired}
</Text>
</TextContent>
</ListItem>
<ListItem>
<TextContent>
<Text component={TextVariants.p}>
{i18n.dmnDevSandbox.configWizard.steps.final.possibleErrorReasons.tokenExpired}
</Text>
</TextContent>
</ListItem>
</List>
<Text className="pf-u-mt-md" component={TextVariants.p}>
{i18n.dmnDevSandbox.configWizard.steps.final.checkInfo}
</Text>
</div>
)}
</>
),
},
],
[
i18n,
isNamespaceValidated,
config,
onNamespaceInputChanged,
onClearNamespace,
isHostValidated,
onHostInputChanged,
onClearHost,
isTokenValidated,
onTokenInputChanged,
onClearToken,
isConnectLoading,
isConfigValidated,
]
);
const wizardFooter = useMemo(
() => (
<WizardFooter>
<WizardContextConsumer>
{({ activeStep, goToStepByName, goToStepById, onNext, onBack }) => {
if (activeStep.name !== i18n.dmnDevSandbox.configWizard.steps.final.name) {
return (
<>
<Button variant="primary" onClick={onNext}>
{i18n.terms.next}
</Button>
<Button
variant="secondary"
onClick={onBack}
isDisabled={activeStep.name === i18n.dmnDevSandbox.configWizard.steps.first.name}
>
{i18n.terms.back}
</Button>
<Button variant="link" onClick={onClose}>
{i18n.terms.cancel}
</Button>
</>
);
}
// Final step buttons
return (
<>
<Button
id="dmn-dev-sandbox-config-continue-editing-button"
onClick={() => onFinish()}
isDisabled={!isConfigValidated}
variant={ButtonVariant.primary}
isLoading={isSaveLoading}
spinnerAriaValueText={isSaveLoading ? "Loading" : undefined}
>
{isSaveLoading ? i18n.dmnDevSandbox.common.saving : i18n.terms.save}
</Button>
<Button variant="secondary" onClick={onBack}>
{i18n.terms.back}
</Button>
<Button variant="link" onClick={onClose}>
{i18n.terms.cancel}
</Button>
</>
);
}}
</WizardContextConsumer>
</WizardFooter>
),
[i18n, isConfigValidated, isSaveLoading, onClose, onFinish]
);
return <Wizard steps={wizardSteps} footer={wizardFooter} onNext={onStepChanged} onGoToStep={onStepChanged} />;
} | the_stack |
export enum MessageDirection {
SEND = 1,
RECEIVE
}
/**
* 会话类型
*/
export enum ConversationType {
PRIVATE = 1,
DISCUSSION,
GROUP,
CHATROOM,
CUSTOMER_SERVICE,
SYSTEM,
APP_SERVICE,
PUBLIC_SERVICE,
PUSH_SERVICE
}
/**
* 发送状态
*/
export enum SentStatus {
SENDING = 10,
FAILED = 20,
SENT = 30,
RECEIVED = 40,
READ = 50,
DESTROYED = 60,
CANCELED = 70
}
/**
* 用户信息
*/
export interface UserInfo {
userId: string;
name: string;
portraitUrl: string;
extra: string;
}
/**
* 消息提醒类型
*/
export enum MentionedType {
/**
* 提醒所有
*/
ALL = 1,
/**
* 部分提醒
*/
PART
}
/**
* 提醒信息
*/
export interface MentionedInfo {
type: MentionedType;
userIdList: string[];
mentionedContent: string;
}
/**
* 消息内容
*/
export interface MessageContent {
objectName?: ObjectName;
userInfo?: UserInfo;
mentionedInfo?: MentionedInfo;
}
/**
* 消息对象名称
*/
export enum ObjectName {
/**
* 文本消息
*/
Text = "RC:TxtMsg",
/**
* 文件消息
*/
File = "RC:FileMsg",
/**
* 图片消息
*/
Image = "RC:ImgMsg",
/**
* GIF 图片消息
*/
GIF = "RC:GIFMsg",
/**
* 位置信息
*/
Location = "RC:LBSMsg",
/**
* 语音消息
*/
Voice = "RC:VcMsg",
/**
* 高质量语音消息
*/
HQVoice = "RC:HQVCMsg",
/**
* 小视频消息
*/
Sight = "RC:SightMsg",
/**
* 命令消息
*/
Command = "RC:CmdMsg",
/**
* 公众服务单图文消息
*/
PublicServiceRich = "RC:PSImgTxtMsg",
/**
* 公众服务多图文消息
*/
PublicServiceMultiRich = "RC:PSMultiImgTxtMsg",
/**
* 好友通知消息
*/
ContactNotification = "RC:ContactNtf",
/**
* 资料通知消息
*/
ProfileNotification = "RC:ProfileNtf",
/**
* 通用命令通知消息
*/
CommandNotification = "RC:CmdNtf",
/**
* 提示条通知消息
*/
InformationNotification = "RC:InfoNtf",
/**
* 群组通知消息
*/
GroupNotification = "RC:GrpNtf",
/**
* 已读通知消息
*/
ReadReceipt = "RC:ReadNtf",
/**
* 公众服务命令消息
*/
PublicServiceCommand = "RC:PSCmd",
/**
* 对方正在输入状态消息
*/
TypingStatus = "RC:TypSts",
/**
* 群消息已读状态回执
*/
ReadReceiptResponse = "RC:RRRspMsg"
}
/**
* 消息对象名称枚举
*/
export enum MessageObjectNames {
text = "RC:TxtMsg",
image = "RC:ImgMsg",
file = "RC:FileMsg",
location = "RC:LocMsg",
voice = "RC:VcMsg"
}
/**
* 文本消息
*/
export interface TextMessage extends MessageContent {
objectName: ObjectName.Text;
content: string;
extra?: string;
}
/**
* 图片消息
*/
export interface ImageMessage extends MessageContent {
objectName: ObjectName.Image;
local: string;
remote?: string;
thumbnail?: string;
isFull?: string;
extra?: string;
}
/**
* GIF 图片消息
*/
export interface GIFMessage extends MessageContent {
objectName: ObjectName.GIF;
local: string;
remote?: string;
width: number;
height: number;
gifDataSize: number;
extra?: string;
}
/**
* 文件消息
*/
export interface FileMessage extends MessageContent {
objectName: ObjectName.File;
local: string;
remote?: string;
name?: string;
size?: number;
fileType?: string;
extra?: string;
}
/**
* 位置消息
*/
export interface LocationMessage extends MessageContent {
objectName: ObjectName.Location;
name: string;
latitude: number;
longitude: number;
thumbnail?: string;
extra?: string;
}
/**
* 语音消息
*/
export interface VoiceMessage extends MessageContent {
objectName: ObjectName.Voice;
data: string;
local: string;
duration: number;
}
/**
* 高质量语音消息
*/
export interface HQVoiceMessage extends MessageContent {
objectName: ObjectName.HQVoice;
local: string;
remote?: string;
duration: number;
}
/**
* 命令消息
*/
export interface CommandMessage extends MessageContent {
objectName: ObjectName.Command;
name: string;
data: string;
}
/**
* 命令通知消息
*/
export interface CommandNotificationMessage extends MessageContent {
objectName: ObjectName.CommandNotification;
name: string;
data: string;
}
/**
* 好友通知消息
*/
export interface ContactNotificationMessage extends MessageContent {
objectName: ObjectName.ContactNotification;
sourceUserId: string;
targetUserId: string;
message: string;
operation: string;
extra: string;
}
/**
* 资料通知消息
*/
export interface ProfileNotificationMessage extends MessageContent {
objectName: ObjectName.ProfileNotification;
data: string;
operation: string;
extra: string;
}
/**
* 提示条通知消息
*/
export interface InfomationNotificationMessage extends MessageContent {
objectName: ObjectName.InformationNotification;
message: string;
extra: string;
}
/**
* 群组通知消息
*/
export interface GroupNotificationMessage extends MessageContent {
objectName: ObjectName.GroupNotification;
/**
* 群组通知的操作名称
*/
operation: string;
/**
* 操作者 ID
*/
operatorUserId: string;
/**
* 操作数据
*/
data: string;
/**
* 消息内容
*/
message: string;
/**
* 额外数据
*/
extra: string;
}
/**
* 已读通知消息
*/
export interface ReadReceiptMessage extends MessageContent {
objectName: ObjectName.ReadReceipt;
type: number; // TODO: 需要定义枚举类型 ReadReceiptType
messageUId: string;
lastMessageSendTime: number;
}
/**
* 已读通知消息
*/
export interface PublicServiceCommandMessage extends MessageContent {
objectName: ObjectName.PublicServiceCommand;
extra: string;
}
/**
* 撤回通知消息
*/
export interface RecallNotificationMessage extends MessageContent {
/**
* 撤回消息的用户 ID
*/
operatorId: string;
/**
* 撤回时间
*/
recallTime: number;
/**
* 原消息对象名称
*/
originalObjectName: string;
/**
* 是否管理员操作
*/
isAdmin: string;
}
/**
* 输入状态消息
*/
export interface TypingStatusMessage extends MessageContent {
objectName: ObjectName.TypingStatus;
data: string;
typingContentType: string;
}
/**
* 消息
*/
export interface Message {
/**
* 会话类型
*/
conversationType: ConversationType;
/**
* 消息对象名称
*/
objectName: string;
/**
* 消息 ID
*/
messageId: number;
/**
* 消息 UID
*/
messageUId: string;
/**
* 消息方向
*/
messageDirection: MessageDirection;
/**
* 发送者 ID
*/
senderUserId: string;
/**
* 发送时间
*/
sentTime: number;
/**
* 目标 ID
*/
targetId: string;
/**
* 消息接收时间
*/
receivedTime: number;
/**
* 消息内容
*/
content: MessageContent;
/**
* 附加信息
*/
extra?: string;
}
/**
* 收到的消息
*/
export interface ReceiveMessage {
/**
* 消息数据
*/
message: Message;
/**
* 剩余未接收的消息数量
*/
left: number;
}
/**
* 连接错误代码
*/
export enum ConnectErrorCode {
RC_NET_CHANNEL_INVALID = 30001,
RC_NET_UNAVAILABLE = 30002,
RC_NAVI_REQUEST_FAIL = 30004,
RC_NAVI_RESPONSE_ERROR = 30007,
RC_NODE_NOT_FOUND = 30008,
RC_SOCKET_NOT_CONNECTED = 30010,
RC_SOCKET_DISCONNECTED = 30011,
RC_PING_SEND_FAIL = 30012,
RC_PONG_RECV_FAIL = 30013,
RC_MSG_SEND_FAIL = 30014,
RC_CONN_OVERFREQUENCY = 30015,
RC_CONN_ACK_TIMEOUT = 31000,
RC_CONN_PROTO_VERSION_ERROR = 31001,
RC_CONN_ID_REJECT = 31002,
RC_CONN_SERVER_UNAVAILABLE = 31003,
RC_CONN_TOKEN_INCORRECT = 31004,
RC_CONN_NOT_AUTHRORIZED = 31005,
RC_CONN_REDIRECTED = 31006,
RC_CONN_PACKAGE_NAME_INVALID = 31007,
RC_CONN_APP_BLOCKED_OR_DELETED = 31008,
RC_CONN_USER_BLOCKED = 31009,
RC_DISCONN_KICK = 31010,
RC_CONN_OTHER_DEVICE_LOGIN = 31023,
RC_CONN_REFUSED = 32061,
RC_CLIENT_NOT_INIT = 33001,
RC_INVALID_PARAMETER = 33003,
RC_CONNECTION_EXIST = 34001,
RC_BACKGROUND_CONNECT = 34002,
RC_INVALID_ARGUMENT = -1000
}
/**
* 错误代码
*/
export enum ErrorCode {
PARAMETER_ERROR = -3,
ERRORCODE_UNKNOWN = -1,
REJECTED_BY_BLACKLIST = 405,
ERRORCODE_TIMEOUT = 5004,
SEND_MSG_FREQUENCY_OVERRUN = 20604,
NOT_IN_DISCUSSION = 21406,
NOT_IN_GROUP = 22406,
FORBIDDEN_IN_GROUP = 22408,
NOT_IN_CHATROOM = 23406,
FORBIDDEN_IN_CHATROOM = 23408,
KICKED_FROM_CHATROOM = 23409,
CHATROOM_NOT_EXIST = 23410,
CHATROOM_IS_FULL = 23411,
PARAMETER_INVALID_CHATROOM = 23412,
ROAMING_SERVICE_UNAVAILABLE_CHATROOM = 23414,
CHANNEL_INVALID = 30001,
NETWORK_UNAVAILABLE = 30002,
MSG_RESPONSE_TIMEOUT = 30003,
CLIENT_NOT_INIT = 33001,
DATABASE_ERROR = 33002,
INVALID_PARAMETER = 33003,
MSG_ROAMING_SERVICE_UNAVAILABLE = 33007,
INVALID_PUBLIC_NUMBER = 29201,
MSG_SIZE_OUT_OF_LIMIT = 30016,
RECALLMESSAGE_PARAMETER_INVALID = 25101,
PUSHSETTING_PARAMETER_INVALID = 26001,
OPERATION_BLOCKED = 20605,
OPERATION_NOT_SUPPORT = 20606,
MSG_BLOCKED_SENSITIVE_WORD = 21501,
MSG_REPLACED_SENSITIVE_WORD = 21502,
SIGHT_MSG_DURATION_LIMIT_EXCEED = 34002
}
/**
* iOS 连接状态
*/
export enum ConnectionStatusIOS {
UNKNOWN = -1,
Connected = 0,
NETWORK_UNAVAILABLE = 1,
AIRPLANE_MODE = 2,
Cellular_2G = 3,
Cellular_3G_4G = 4,
WIFI = 5,
KICKED_OFFLINE_BY_OTHER_CLIENT = 6,
LOGIN_ON_WEB = 7,
SERVER_INVALID = 8,
VALIDATE_INVALID = 9,
Connecting = 10,
Unconnected = 11,
SignUp = 12,
TOKEN_INCORRECT = 31004,
DISCONN_EXCEPTION = 31011
}
/**
* Android 连接状态
*/
export enum ConnectionStatusAndroid {
NETWORK_UNAVAILABLE = -1,
CONNECTED,
CONNECTING,
DISCONNECTED,
KICKED_OFFLINE_BY_OTHER_CLIENT,
TOKEN_INCORRECT,
SERVER_INVALID
}
/**
* 连接状态
*/
export type ConnectionStatus = ConnectionStatusIOS | ConnectionStatusAndroid;
/**
* 要发送的消息
*/
export interface SentMessage {
/**
* 会话类型
*/
conversationType: ConversationType;
/**
* 目标 ID
*/
targetId: string;
/**
* 消息内容
*/
content: MessageContent;
/**
* 推送内容,用于显示
*/
pushContent: string;
/**
* 推送数据,不显示
*/
pushData: string;
}
/**
* 会话信息
*/
export interface Conversation {
conversationType: ConversationType;
conversationTitle: string;
isTop: boolean;
unreadMessageCount: number;
draft: string;
targetId: string;
objectName: string;
latestMessageId: number;
latestMessage: MessageContent;
receivedStatus: number;
receivedTime: number;
sentStatus: SentStatus;
senderUserId: string;
hasUnreadMentioned: boolean;
mentionedCount: number;
}
/**
* 搜索类型
*/
export enum SearchType {
/**
* 精准
*/
EXACT,
/**
* 模糊
*/
FUZZY
}
/**
* 公共服务类型
*/
export enum PublicServiceType {
/**
* 应用公众服务
*/
APP_PUBLIC_SERVICE = 7,
/**
* 公共服务号
*/
PUBLIC_SERVICE = 8
}
/**
* 公众服务菜单类型
*/
export enum PublicServiceMenuItemType {
/**
* 作为分组包含子菜单的菜单
*/
GROUP,
/**
* 查看事件菜单
*/
VIEW,
/**
* 点击事件菜单
*/
CLICK
}
/**
* 公众服务菜单项
*/
export interface PublicServiceMenuItem {
/**
* 菜单项 ID
*/
id: string;
/**
* 菜单项名称
*/
name: string;
/**
* 菜单项 URL
*/
url: string;
/**
* 菜单项类型
*/
type: PublicServiceMenuItemType;
}
/**
* 公众服务描述
*/
export interface PublicServiceProfile {
id: string;
/**
* 服务名称
*/
name: string;
/**
* 服务描述
*/
introduction: string;
/**
* 头像连接
*/
portraitUrl: string;
/**
* 是否设置为所有用户均关注
*/
isGlobal: boolean;
/**
* 用户是否已关注
*/
followed: boolean;
/**
* 类型
*/
type: PublicServiceType | ConversationType;
/**
* 菜单
*/
menu: PublicServiceMenuItem[];
}
/**
* 输入状态
*/
export interface TypingStatus {
conversationType: ConversationType;
targetId: string;
userId: string;
sentTime: number;
typingContentType: string;
}
/**
* 消息回执请求信息
*/
export interface ReceiptRequest {
conversationType: ConversationType;
targetId: string;
messageUId: string;
}
/**
* 消息回执响应信息
*/
export interface ReceiptResponse {
conversationType: ConversationType;
targetId: string;
messageUId: string;
users: { [key: string]: number };
}
/**
* 搜索会话结果
*/
export interface SearchConversationResult {
conversation: Conversation;
matchCount: number;
}
/**
* 时间戳排序方式
*/
export enum TimestampOrder {
/**
* 按时间戳倒序排序
*/
DESC,
/**
* 按时间戳顺序排序
*/
ASC
}
/**
* 聊天室成员排序,按加入时间
*/
export enum ChatRoomMemberOrder {
/**
* 生序
*/
ASC = 1,
/**
* 降序
*/
DESC
}
/**
* 聊天室成员信息
*/
export interface MemberInfo {
userId: string;
joinTime: number;
}
/**
* 聊天室信息
*/
export interface ChatRoomInfo {
targetId: string;
memberOrder: ChatRoomMemberOrder;
totalMemberCount: number;
members: MemberInfo[];
}
/**
* 讨论组
*/
export interface Discussion {
id: string;
name: string;
creatorId: string;
memberIdList: string[];
isOpen: boolean;
}
/**
* 实时位置共享状态
*/
export enum RealTimeLocationStatus {
/**
* 初始状态
*/
IDLE,
/**
* 接收状态
*/
INCOMING,
/**
* 发起状态
*/
OUTGOING,
/**
* 已连接,正在共享的状态
*/
CONNECTED
}
/**
* 客服信息
*/
export interface CSInfo {
userId?: string;
nickName?: string;
loginName?: string;
name?: string;
grade?: string;
age?: string;
profession?: string;
portraitUrl?: string;
province?: string;
city?: string;
memo?: string;
mobileNo?: string;
email?: string;
address?: string;
QQ?: string;
weibo?: string;
weixin?: string;
page?: string;
referrer?: string;
enterUrl?: string;
skillId?: string;
listUrl?: string;
define?: string;
productId?: string;
}
/**
* 客服配置
*/
export interface CSConfig {
isBlack: boolean;
companyName: string;
companyUrl: string;
companyIcon: string;
announceClickUrl: string;
announceMsg: string;
leaveMessageNativeInfo: CSLeaveMessageItem[];
leaveMessageType: LeaveMessageType;
userTipTime: number;
userTipWord: string;
adminTipTime: number;
adminTipWord: string;
evaEntryPoint: CSEvaEntryPoint;
evaType: number;
robotSessionNoEva: boolean;
humanEvaluateItems: { value: number; description: string }[];
isReportResolveStatus: boolean;
isDisableLocation: boolean;
}
/**
* 留言消息类型
*/
export enum LeaveMessageType {
NATIVE,
WEB
}
/**
* 客服问题解决状态
*/
export enum CSResolveStatus {
UNRESOLVED,
RESOLVED,
RESOLVING
}
/**
* 客服评价时机
*/
export enum CSEvaEntryPoint {
LEAVE,
EXTENSION,
NONE,
END
}
/**
* 客服服务模式
*/
export enum CSMode {
NO_SERVICE,
ROBOT_ONLY,
HUMAN_ONLY,
ROBOT_FIRST
}
/**
* 客服留言
*/
export interface CSLeaveMessageItem {
name?: string;
title?: string;
type?: string;
defaultText?: string;
required?: boolean;
message?: string;
verification?: string;
max?: number;
}
/**
* 客服分组信息
*/
export interface CSGroupItem {
id: string;
name: string;
isOnline: boolean;
}
/**
* 推送语言
*/
export enum PushLanguage {
EN_US = 1,
ZH_CN
}
/**
* 推送提醒消息
*/
export interface PushNotificationMessage {
pushType: string;
pushId: string;
pushTitle: string;
pushFlag: string;
pushContent: string;
pushData: string;
objectName: string;
senderId: string;
senderName: string;
senderPortraitUrl: string;
targetId: string;
targetUserName: string;
conversationType: ConversationType;
extra: string;
} | the_stack |
import {getFixture} from '../../../../testing/dom';
import {verifyDefaultAdapter} from '../../../../testing/helpers/foundation';
import {setUpFoundationTest, setUpMdcTestEnvironment} from '../../../../testing/helpers/setup';
import {cssClasses, strings} from '../../constants';
import {MDCDismissibleDrawerFoundation} from '../foundation';
describe('MDCDismissibleDrawerFoundation', () => {
setUpMdcTestEnvironment();
const setupTest = () => {
const {foundation, mockAdapter} =
setUpFoundationTest(MDCDismissibleDrawerFoundation);
return {foundation, mockAdapter};
};
it('exports strings', () => {
expect('strings' in MDCDismissibleDrawerFoundation).toBe(true);
expect(MDCDismissibleDrawerFoundation.strings).toEqual(strings);
});
it('exports cssClasses', () => {
expect('cssClasses' in MDCDismissibleDrawerFoundation).toBe(true);
expect(MDCDismissibleDrawerFoundation.cssClasses).toEqual(cssClasses);
});
it('defaultAdapter returns a complete adapter implementation', () => {
verifyDefaultAdapter(MDCDismissibleDrawerFoundation, [
'hasClass',
'addClass',
'removeClass',
'elementHasClass',
'saveFocus',
'restoreFocus',
'focusActiveNavigationItem',
'notifyClose',
'notifyOpen',
'trapFocus',
'releaseFocus',
]);
});
it('#destroy cancels pending rAF for #open', () => {
const {foundation, mockAdapter} = setupTest();
foundation.open();
foundation.destroy();
expect(mockAdapter.addClass).not.toHaveBeenCalledWith(cssClasses.OPENING);
});
it('#destroy cancels pending setTimeout for #open', () => {
const {foundation, mockAdapter} = setupTest();
foundation.open();
jasmine.clock().tick(1);
foundation.destroy();
expect(mockAdapter.addClass).not.toHaveBeenCalledWith(cssClasses.OPENING);
});
it('#open does nothing if drawer is already open', () => {
const {foundation, mockAdapter} = setupTest();
mockAdapter.hasClass.withArgs(cssClasses.OPEN).and.returnValue(true);
foundation.open();
expect(mockAdapter.addClass).not.toHaveBeenCalledWith(jasmine.any(String));
});
it('#open does nothing if drawer is already opening', () => {
const {foundation, mockAdapter} = setupTest();
mockAdapter.hasClass.withArgs(cssClasses.OPENING).and.returnValue(true);
foundation.open();
expect(mockAdapter.addClass).not.toHaveBeenCalledWith(jasmine.any(String));
});
it('#open does nothing if drawer is closing', () => {
const {foundation, mockAdapter} = setupTest();
mockAdapter.hasClass.withArgs(cssClasses.CLOSING).and.returnValue(true);
foundation.open();
expect(mockAdapter.addClass).not.toHaveBeenCalledWith(jasmine.any(String));
});
it('#open adds appropriate classes and saves focus', () => {
const {foundation, mockAdapter} = setupTest();
foundation.open();
jasmine.clock().tick(50);
expect(mockAdapter.addClass).toHaveBeenCalledWith(cssClasses.OPEN);
expect(mockAdapter.addClass).toHaveBeenCalledWith(cssClasses.ANIMATE);
expect(mockAdapter.addClass).toHaveBeenCalledWith(cssClasses.OPENING);
expect(mockAdapter.saveFocus).toHaveBeenCalledTimes(1);
});
it('#close does nothing if drawer is already closed', () => {
const {foundation, mockAdapter} = setupTest();
mockAdapter.hasClass.withArgs(cssClasses.OPEN).and.returnValue(false);
foundation.close();
expect(mockAdapter.addClass).not.toHaveBeenCalledWith(jasmine.any(String));
});
it('#close does nothing if drawer is opening', () => {
const {foundation, mockAdapter} = setupTest();
mockAdapter.hasClass.withArgs(cssClasses.OPENING).and.returnValue(true);
foundation.close();
expect(mockAdapter.addClass).not.toHaveBeenCalledWith(jasmine.any(String));
});
it('#close does nothing if drawer is closing', () => {
const {foundation, mockAdapter} = setupTest();
mockAdapter.hasClass.withArgs(cssClasses.CLOSING).and.returnValue(true);
foundation.close();
expect(mockAdapter.addClass).not.toHaveBeenCalledWith(jasmine.any(String));
});
it('#close adds appropriate classes', () => {
const {foundation, mockAdapter} = setupTest();
mockAdapter.hasClass.withArgs(cssClasses.OPEN).and.returnValue(true);
foundation.close();
expect(mockAdapter.addClass).toHaveBeenCalledWith(cssClasses.CLOSING);
});
it(`#isOpen returns true when it has ${cssClasses.OPEN} class`, () => {
const {foundation, mockAdapter} = setupTest();
mockAdapter.hasClass.withArgs(cssClasses.OPEN).and.returnValue(true);
expect(foundation.isOpen()).toBe(true);
});
it(`#isOpen returns false when it lacks ${cssClasses.OPEN} class`, () => {
const {foundation, mockAdapter} = setupTest();
mockAdapter.hasClass.withArgs(cssClasses.OPEN).and.returnValue(false);
expect(foundation.isOpen()).toBe(false);
});
it(`#isOpening returns true when it has ${cssClasses.OPENING} class`, () => {
const {foundation, mockAdapter} = setupTest();
mockAdapter.hasClass.withArgs(cssClasses.ANIMATE).and.returnValue(true);
mockAdapter.hasClass.withArgs(cssClasses.OPENING).and.returnValue(true);
expect(foundation.isOpening()).toBe(true);
});
it('#isOpening returns true when drawer just start animate', () => {
const {foundation, mockAdapter} = setupTest();
mockAdapter.hasClass.withArgs(cssClasses.ANIMATE).and.returnValue(true);
mockAdapter.hasClass.withArgs(cssClasses.OPENING).and.returnValue(false);
expect(foundation.isOpening()).toBe(true);
});
it(`#isOpening returns false when it lacks ${cssClasses.OPENING} class`,
() => {
const {foundation, mockAdapter} = setupTest();
mockAdapter.hasClass.withArgs(cssClasses.ANIMATE).and.returnValue(false);
mockAdapter.hasClass.withArgs(cssClasses.OPENING).and.returnValue(false);
expect(foundation.isOpening()).toBe(false);
});
it(`#isClosing returns true when it has ${cssClasses.CLOSING} class`, () => {
const {foundation, mockAdapter} = setupTest();
mockAdapter.hasClass.withArgs(cssClasses.CLOSING).and.returnValue(true);
expect(foundation.isClosing()).toBe(true);
});
it(`#isClosing returns false when it lacks ${cssClasses.CLOSING} class`,
() => {
const {foundation, mockAdapter} = setupTest();
mockAdapter.hasClass.withArgs(cssClasses.CLOSING).and.returnValue(false);
expect(foundation.isClosing()).toBe(false);
});
it('#handleKeydown does nothing when event key is not the escape key', () => {
const {foundation, mockAdapter} = setupTest();
mockAdapter.hasClass.withArgs(cssClasses.OPEN).and.returnValue(true);
foundation.handleKeydown({key: 'Shift'} as KeyboardEvent);
expect(mockAdapter.addClass).not.toHaveBeenCalledWith(cssClasses.CLOSING);
});
it('#handleKeydown does nothing when event keyCode is not 27', () => {
const {foundation, mockAdapter} = setupTest();
mockAdapter.hasClass.withArgs(cssClasses.OPEN).and.returnValue(true);
foundation.handleKeydown({keyCode: 11} as KeyboardEvent);
expect(mockAdapter.addClass).not.toHaveBeenCalledWith(cssClasses.CLOSING);
});
it('#handleKeydown calls close when event key is the escape key', () => {
const {foundation, mockAdapter} = setupTest();
mockAdapter.hasClass.withArgs(cssClasses.OPEN).and.returnValue(true);
foundation.handleKeydown({key: 'Escape'} as KeyboardEvent);
expect(mockAdapter.addClass).toHaveBeenCalledWith(cssClasses.CLOSING);
});
it('#handleKeydown calls close when event keyCode is 27', () => {
const {foundation, mockAdapter} = setupTest();
mockAdapter.hasClass.withArgs(cssClasses.OPEN).and.returnValue(true);
foundation.handleKeydown({keyCode: 27} as KeyboardEvent);
expect(mockAdapter.addClass).toHaveBeenCalledWith(cssClasses.CLOSING);
});
it('#handleTransitionEnd removes all animating classes', () => {
const {foundation, mockAdapter} = setupTest();
const mockEventTarget = getFixture(`<div class="foo">bar</div>`);
mockAdapter.elementHasClass.withArgs(mockEventTarget, cssClasses.ROOT)
.and.returnValue(true);
foundation.handleTransitionEnd(
{target: mockEventTarget} as unknown as TransitionEvent);
expect(mockAdapter.removeClass).toHaveBeenCalledWith(cssClasses.ANIMATE);
expect(mockAdapter.removeClass).toHaveBeenCalledWith(cssClasses.OPENING);
expect(mockAdapter.removeClass).toHaveBeenCalledWith(cssClasses.CLOSING);
});
it('#handleTransitionEnd removes open class after closing, restores the focus and calls notifyClose',
() => {
const {foundation, mockAdapter} = setupTest();
const mockEventTarget = getFixture(`<div>root</div>`);
mockAdapter.elementHasClass.withArgs(mockEventTarget, cssClasses.ROOT)
.and.returnValue(true);
mockAdapter.hasClass.withArgs(cssClasses.CLOSING).and.returnValue(true);
foundation.handleTransitionEnd(
{target: mockEventTarget} as unknown as TransitionEvent);
expect(mockAdapter.removeClass).toHaveBeenCalledWith(cssClasses.OPEN);
expect(mockAdapter.restoreFocus).toHaveBeenCalledTimes(1);
expect(mockAdapter.notifyClose).toHaveBeenCalledTimes(1);
});
it(`#handleTransitionEnd doesn't remove open class after opening,
focuses on active navigation item and calls notifyOpen`,
() => {
const {foundation, mockAdapter} = setupTest();
const mockEventTarget = getFixture(`<div>root</div>`);
mockAdapter.elementHasClass.withArgs(mockEventTarget, cssClasses.ROOT)
.and.returnValue(true);
mockAdapter.hasClass.withArgs(cssClasses.CLOSING).and.returnValue(false);
foundation.handleTransitionEnd(
{target: mockEventTarget} as unknown as TransitionEvent);
expect(mockAdapter.removeClass)
.not.toHaveBeenCalledWith(cssClasses.OPEN);
expect(mockAdapter.focusActiveNavigationItem).toHaveBeenCalledTimes(1);
expect(mockAdapter.notifyOpen).toHaveBeenCalledTimes(1);
});
it('#handleTransitionEnd doesn\'t do anything if event is not triggered by root element',
() => {
const {foundation, mockAdapter} = setupTest();
const mockEventTarget = getFixture(`<div>child</div>`);
mockAdapter.elementHasClass.withArgs(mockEventTarget, cssClasses.ROOT)
.and.returnValue(false);
foundation.handleTransitionEnd(
{target: mockEventTarget} as unknown as TransitionEvent);
expect(mockAdapter.removeClass)
.not.toHaveBeenCalledWith(cssClasses.OPEN);
expect(mockAdapter.removeClass)
.not.toHaveBeenCalledWith(cssClasses.ANIMATE);
expect(mockAdapter.notifyOpen).not.toHaveBeenCalled();
expect(mockAdapter.notifyClose).not.toHaveBeenCalled();
});
it('#handleTransitionEnd doesn\'t do anything if event is emitted with a non-element target',
() => {
const {foundation, mockAdapter} = setupTest();
foundation.handleTransitionEnd({target: {}} as TransitionEvent);
expect(mockAdapter.elementHasClass)
.not.toHaveBeenCalledWith(jasmine.anything(), jasmine.any(String));
expect(mockAdapter.removeClass)
.not.toHaveBeenCalledWith(cssClasses.OPEN);
expect(mockAdapter.removeClass)
.not.toHaveBeenCalledWith(cssClasses.ANIMATE);
expect(mockAdapter.notifyOpen).not.toHaveBeenCalled();
expect(mockAdapter.notifyClose).not.toHaveBeenCalled();
});
it('#handleTransitionEnd restores the focus.', () => {
const {foundation, mockAdapter} = setupTest();
const mockEventTarget = getFixture(`<div class="foo">bar</div>`);
mockAdapter.elementHasClass.withArgs(mockEventTarget, cssClasses.ROOT)
.and.returnValue(true);
mockAdapter.hasClass.withArgs(cssClasses.CLOSING).and.returnValue(true);
foundation.handleTransitionEnd(
{target: mockEventTarget} as unknown as TransitionEvent);
expect(mockAdapter.restoreFocus).toHaveBeenCalled();
});
}); | the_stack |
import * as grpcProtoLoader from '@grpc/proto-loader';
import {execFile} from 'child_process';
import * as fs from 'fs';
import {GoogleAuth, GoogleAuthOptions} from 'google-auth-library';
import * as grpc from '@grpc/grpc-js';
import * as os from 'os';
import {join} from 'path';
import {OutgoingHttpHeaders} from 'http';
import * as path from 'path';
import * as protobuf from 'protobufjs';
import * as objectHash from 'object-hash';
import * as gax from './gax';
import {ClientOptions} from '@grpc/grpc-js/build/src/client';
const googleProtoFilesDir = path.join(__dirname, '..', '..', 'protos');
// INCLUDE_DIRS is passed to @grpc/proto-loader
const INCLUDE_DIRS: string[] = [];
INCLUDE_DIRS.push(googleProtoFilesDir);
// COMMON_PROTO_FILES logic is here for protobufjs loads (see
// GoogleProtoFilesRoot below)
import * as commonProtoFiles from './protosList.json';
// use the correct path separator for the OS we are running on
const COMMON_PROTO_FILES: string[] = commonProtoFiles.map(file =>
file.replace(/[/\\]/g, path.sep)
);
export interface GrpcClientOptions extends GoogleAuthOptions {
auth?: GoogleAuth;
grpc?: GrpcModule;
}
export interface MetadataValue {
equals: Function;
}
/*
* Async version of readFile.
*
* @returns {Promise} Contents of file at path.
*/
async function readFileAsync(path: string): Promise<string> {
return new Promise((resolve, reject) => {
fs.readFile(path, 'utf8', (err, content) => {
if (err) return reject(err);
else resolve(content);
});
});
}
/*
* Async version of execFile.
*
* @returns {Promise} stdout from command execution.
*/
async function execFileAsync(command: string, args: string[]): Promise<string> {
return new Promise((resolve, reject) => {
execFile(command, args, (err, stdout) => {
if (err) return reject(err);
else resolve(stdout);
});
});
}
export interface Metadata {
// eslint-disable-next-line @typescript-eslint/no-misused-new
new (): Metadata;
set: (key: {}, value?: {} | null) => void;
clone: () => Metadata;
value: MetadataValue;
get: (key: {}) => {};
}
export type GrpcModule = typeof grpc;
export interface ClientStubOptions {
protocol?: string;
servicePath?: string;
port?: number;
sslCreds?: grpc.ChannelCredentials;
[index: string]: string | number | undefined | {};
// For mtls:
cert?: string;
key?: string;
}
export class ClientStub extends grpc.Client {
[name: string]: Function;
}
export class GrpcClient {
auth: GoogleAuth;
grpc: GrpcModule;
grpcVersion: string;
fallback: boolean | 'rest' | 'proto';
private static protoCache = new Map<string, grpc.GrpcObject>();
/**
* Key for proto cache map. We are doing our best to make sure we respect
* the options, so if the same proto file is loaded with different set of
* options, the cache won't be used. Since some of the options are
* Functions (e.g. `enums: String` - see below in `loadProto()`),
* they will be omitted from the cache key. If the cache breaks anything
* for you, use the `ignoreCache` parameter of `loadProto()` to disable it.
*/
private static protoCacheKey(
filename: string | string[],
options: grpcProtoLoader.Options
) {
if (
!filename ||
(Array.isArray(filename) && (filename.length === 0 || !filename[0]))
) {
return undefined;
}
return JSON.stringify(filename) + ' ' + JSON.stringify(options);
}
/**
* In rare cases users might need to deallocate all memory consumed by loaded protos.
* This method will delete the proto cache content.
*/
static clearProtoCache() {
GrpcClient.protoCache.clear();
}
/**
* A class which keeps the context of gRPC and auth for the gRPC.
*
* @param {Object=} options - The optional parameters. It will be directly
* passed to google-auth-library library, so parameters like keyFile or
* credentials will be valid.
* @param {Object=} options.auth - An instance of google-auth-library.
* When specified, this auth instance will be used instead of creating
* a new one.
* @param {Object=} options.grpc - When specified, this will be used
* for the 'grpc' module in this context. By default, it will load the grpc
* module in the standard way.
* @constructor
*/
constructor(options: GrpcClientOptions = {}) {
this.auth = options.auth || new GoogleAuth(options);
this.fallback = false;
const minimumVersion = 10;
const major = Number(process.version.match(/^v(\d+)/)?.[1]);
if (Number.isNaN(major) || major < minimumVersion) {
const errorMessage =
`Node.js v${minimumVersion}.0.0 is a minimum requirement. To learn about legacy version support visit: ` +
'https://github.com/googleapis/google-cloud-node#supported-nodejs-versions';
throw new Error(errorMessage);
}
if ('grpc' in options) {
this.grpc = options.grpc!;
this.grpcVersion = '';
} else {
this.grpc = grpc;
this.grpcVersion = require('@grpc/grpc-js/package.json').version;
}
}
/**
* Creates a gRPC credentials. It asks the auth data if necessary.
* @private
* @param {Object} opts - options values for configuring credentials.
* @param {Object=} opts.sslCreds - when specified, this is used instead
* of default channel credentials.
* @return {Promise} The promise which will be resolved to the gRPC credential.
*/
async _getCredentials(opts: ClientStubOptions) {
if (opts.sslCreds) {
return opts.sslCreds;
}
const grpc = this.grpc;
const sslCreds =
opts.cert && opts.key
? grpc.credentials.createSsl(
null,
Buffer.from(opts.key),
Buffer.from(opts.cert)
)
: grpc.credentials.createSsl();
const client = await this.auth.getClient();
const credentials = grpc.credentials.combineChannelCredentials(
sslCreds,
grpc.credentials.createFromGoogleCredential(client)
);
return credentials;
}
private static defaultOptions() {
// This set of @grpc/proto-loader options
// 'closely approximates the existing behavior of grpc.load'
const includeDirs = INCLUDE_DIRS.slice();
const options = {
keepCase: false,
longs: String,
enums: String,
defaults: true,
oneofs: true,
includeDirs,
};
return options;
}
/**
* Loads the gRPC service from the proto file(s) at the given path and with the
* given options. Caches the loaded protos so the subsequent loads don't do
* any disk reads.
* @param filename The path to the proto file(s).
* @param options Options for loading the proto file.
* @param ignoreCache Defaults to `false`. Set it to `true` if the caching logic
* incorrectly decides that the options object is the same, or if you want to
* re-read the protos from disk for any other reason.
*/
loadFromProto(
filename: string | string[],
options: grpcProtoLoader.Options,
ignoreCache = false
) {
const cacheKey = GrpcClient.protoCacheKey(filename, options);
let grpcPackage = cacheKey
? GrpcClient.protoCache.get(cacheKey)
: undefined;
if (ignoreCache || !grpcPackage) {
const packageDef = grpcProtoLoader.loadSync(filename, options);
grpcPackage = this.grpc.loadPackageDefinition(packageDef);
if (cacheKey) {
GrpcClient.protoCache.set(cacheKey, grpcPackage);
}
}
return grpcPackage;
}
/**
* Load gRPC proto service from a filename looking in googleapis common protos
* when necessary. Caches the loaded protos so the subsequent loads don't do
* any disk reads.
* @param {String} protoPath - The directory to search for the protofile.
* @param {String|String[]} filename - The filename(s) of the proto(s) to be loaded.
* If omitted, protoPath will be treated as a file path to load.
* @param ignoreCache Defaults to `false`. Set it to `true` if the caching logic
* incorrectly decides that the options object is the same, or if you want to
* re-read the protos from disk for any other reason.
* @return {Object<string, *>} The gRPC loaded result (the toplevel namespace
* object).
*/
loadProto(
protoPath: string,
filename?: string | string[],
ignoreCache = false
) {
if (!filename) {
filename = path.basename(protoPath);
protoPath = path.dirname(protoPath);
}
if (Array.isArray(filename) && filename.length === 0) {
return {};
}
const options = GrpcClient.defaultOptions();
options.includeDirs.unshift(protoPath);
return this.loadFromProto(filename, options, ignoreCache);
}
static _resolveFile(protoPath: string, filename: string) {
if (fs.existsSync(path.join(protoPath, filename))) {
return path.join(protoPath, filename);
} else if (COMMON_PROTO_FILES.indexOf(filename) > -1) {
return path.join(googleProtoFilesDir, filename);
}
throw new Error(filename + ' could not be found in ' + protoPath);
}
loadProtoJSON(json: protobuf.INamespace, ignoreCache = false) {
const hash = objectHash(json).toString();
const cached = GrpcClient.protoCache.get(hash);
if (cached && !ignoreCache) {
return cached;
}
const options = GrpcClient.defaultOptions();
const packageDefinition = grpcProtoLoader.fromJSON(json, options);
const grpcPackage = this.grpc.loadPackageDefinition(packageDefinition);
GrpcClient.protoCache.set(hash, grpcPackage);
return grpcPackage;
}
metadataBuilder(headers: OutgoingHttpHeaders) {
const Metadata = this.grpc.Metadata;
const baseMetadata = new Metadata();
for (const key in headers) {
const value = headers[key];
if (Array.isArray(value)) {
value.forEach(v => baseMetadata.add(key, v));
} else {
baseMetadata.set(key, `${value}`);
}
}
return function buildMetadata(
abTests?: {},
moreHeaders?: OutgoingHttpHeaders
) {
// TODO: bring the A/B testing info into the metadata.
let copied = false;
let metadata = baseMetadata;
if (moreHeaders) {
for (const key in moreHeaders) {
if (key.toLowerCase() !== 'x-goog-api-client') {
if (!copied) {
copied = true;
metadata = metadata.clone();
}
const value = moreHeaders[key];
if (Array.isArray(value)) {
value.forEach(v => metadata.add(key, v));
} else {
metadata.set(key, `${value}`);
}
}
}
}
return metadata;
};
}
/**
* A wrapper of {@link constructSettings} function under the gRPC context.
*
* Most of parameters are common among constructSettings, please take a look.
* @param {string} serviceName - The fullly-qualified name of the service.
* @param {Object} clientConfig - A dictionary of the client config.
* @param {Object} configOverrides - A dictionary of overriding configs.
* @param {Object} headers - A dictionary of additional HTTP header name to
* its value.
* @return {Object} A mapping of method names to CallSettings.
*/
constructSettings(
serviceName: string,
clientConfig: gax.ClientConfig,
configOverrides: gax.ClientConfig,
headers: OutgoingHttpHeaders
) {
return gax.constructSettings(
serviceName,
clientConfig,
configOverrides,
this.grpc.status,
{metadataBuilder: this.metadataBuilder(headers)}
);
}
/**
* Creates a gRPC stub with current gRPC and auth.
* @param {function} CreateStub - The constructor function of the stub.
* @param {Object} options - The optional arguments to customize
* gRPC connection. This options will be passed to the constructor of
* gRPC client too.
* @param {string} options.servicePath - The name of the server of the service.
* @param {number} options.port - The port of the service.
* @param {grpcTypes.ClientCredentials=} options.sslCreds - The credentials to be used
* to set up gRPC connection.
* @param {string} defaultServicePath - The default service path.
* @return {Promise} A promise which resolves to a gRPC stub instance.
*/
async createStub(
CreateStub: typeof ClientStub,
options: ClientStubOptions,
customServicePath?: boolean
) {
// The following options are understood by grpc-gcp and need a special treatment
// (should be passed without a `grpc.` prefix)
const grpcGcpOptions = [
'grpc.callInvocationTransformer',
'grpc.channelFactoryOverride',
'grpc.gcpApiConfig',
];
const [cert, key] = await this._detectClientCertificate(options);
const servicePath = this._mtlsServicePath(
options.servicePath,
customServicePath,
cert && key
);
const opts = Object.assign({}, options, {cert, key, servicePath});
const serviceAddress = servicePath + ':' + opts.port;
const creds = await this._getCredentials(opts);
const grpcOptions: ClientOptions = {};
// @grpc/grpc-js limits max receive/send message length starting from v0.8.0
// https://github.com/grpc/grpc-node/releases/tag/%40grpc%2Fgrpc-js%400.8.0
// To keep the existing behavior and avoid libraries breakage, we pass -1 there as suggested.
grpcOptions['grpc.max_receive_message_length'] = -1;
grpcOptions['grpc.max_send_message_length'] = -1;
grpcOptions['grpc.initial_reconnect_backoff_ms'] = 1000;
Object.keys(opts).forEach(key => {
const value = options[key];
// the older versions had a bug which required users to call an option
// grpc.grpc.* to make it actually pass to gRPC as grpc.*, let's handle
// this here until the next major release
if (key.startsWith('grpc.grpc.')) {
key = key.replace(/^grpc\./, '');
}
if (key.startsWith('grpc.')) {
if (grpcGcpOptions.includes(key)) {
key = key.replace(/^grpc\./, '');
}
grpcOptions[key] = value as string | number;
}
if (key.startsWith('grpc-node.')) {
grpcOptions[key] = value as string | number;
}
});
const stub = new CreateStub(
serviceAddress,
creds,
grpcOptions as ClientOptions
);
return stub;
}
/**
* Detect mTLS client certificate based on logic described in
* https://google.aip.dev/auth/4114.
*
* @param {object} [options] - The configuration object.
* @returns {Promise} Resolves array of strings representing cert and key.
*/
async _detectClientCertificate(opts?: ClientOptions) {
const certRegex =
/(?<cert>-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----)/s;
const keyRegex =
/(?<key>-----BEGIN PRIVATE KEY-----.*?-----END PRIVATE KEY-----)/s;
// If GOOGLE_API_USE_CLIENT_CERTIFICATE is true...:
if (
typeof process !== 'undefined' &&
process?.env?.GOOGLE_API_USE_CLIENT_CERTIFICATE === 'true'
) {
if (opts?.cert && opts?.key) {
return [opts.cert, opts.key];
}
// If context aware metadata exists, run the cert provider command,
// parse the output to extract cert and key, and use this cert/key.
const metadataPath = join(
os.homedir(),
'.secureConnect',
'context_aware_metadata.json'
);
const metadata = JSON.parse(await readFileAsync(metadataPath));
if (!metadata.cert_provider_command) {
throw Error('no cert_provider_command found');
}
const stdout = await execFileAsync(
metadata.cert_provider_command[0],
metadata.cert_provider_command.slice(1)
);
const matchCert = stdout.toString().match(certRegex);
const matchKey = stdout.toString().match(keyRegex);
if (!(matchCert?.groups && matchKey?.groups)) {
throw Error('unable to parse certificate and key');
} else {
return [matchCert.groups.cert, matchKey.groups.key];
}
}
// If GOOGLE_API_USE_CLIENT_CERTIFICATE is not set or false,
// use no cert or key:
return [undefined, undefined];
}
/**
* Return service path, taking into account mTLS logic.
* See: https://google.aip.dev/auth/4114
*
* @param {string|undefined} servicePath - The path of the service.
* @param {string|undefined} customServicePath - Did the user provide a custom service URL.
* @param {boolean} hasCertificate - Was a certificate found.
* @returns {string} The DNS address for this service.
*/
_mtlsServicePath(
servicePath: string | undefined,
customServicePath: boolean | undefined,
hasCertificate: boolean
): string | undefined {
// If user provides a custom service path, return the current service
// path and do not attempt to add mtls subdomain:
if (customServicePath || !servicePath) return servicePath;
if (
typeof process !== 'undefined' &&
process?.env?.GOOGLE_API_USE_MTLS_ENDPOINT === 'never'
) {
// It was explicitly asked that mtls endpoint not be used:
return servicePath;
} else if (
(typeof process !== 'undefined' &&
process?.env?.GOOGLE_API_USE_MTLS_ENDPOINT === 'always') ||
hasCertificate
) {
// Either auto-detect or explicit setting of endpoint:
return servicePath.replace('googleapis.com', 'mtls.googleapis.com');
}
return servicePath;
}
/**
* Creates a 'bytelength' function for a given proto message class.
*
* See {@link BundleDescriptor} about the meaning of the return value.
*
* @param {function} message - a constructor function that is generated by
* protobuf.js. Assumes 'encoder' field in the message.
* @return {function(Object):number} - a function to compute the byte length
* for an object.
*/
static createByteLengthFunction(message: {
encode: (obj: {}) => {
finish: () => Array<{}>;
};
}) {
return function getByteLength(obj: {}) {
return message.encode(obj).finish().length;
};
}
}
export class GoogleProtoFilesRoot extends protobuf.Root {
constructor(...args: Array<{}>) {
super(...args);
}
// Causes the loading of an included proto to check if it is a common
// proto. If it is a common proto, use the bundled proto.
resolvePath(originPath: string, includePath: string) {
originPath = path.normalize(originPath);
includePath = path.normalize(includePath);
// Fully qualified paths don't need to be resolved.
if (path.isAbsolute(includePath)) {
if (!fs.existsSync(includePath)) {
throw new Error('The include `' + includePath + '` was not found.');
}
return includePath;
}
if (COMMON_PROTO_FILES.indexOf(includePath) > -1) {
return path.join(googleProtoFilesDir, includePath);
}
return GoogleProtoFilesRoot._findIncludePath(originPath, includePath);
}
static _findIncludePath(originPath: string, includePath: string) {
originPath = path.normalize(originPath);
includePath = path.normalize(includePath);
let current = originPath;
let found = fs.existsSync(path.join(current, includePath));
while (!found && current.length > 0) {
current = current.substring(0, current.lastIndexOf(path.sep));
found = fs.existsSync(path.join(current, includePath));
}
if (!found) {
throw new Error('The include `' + includePath + '` was not found.');
}
return path.join(current, includePath);
}
} | the_stack |
import hasProperty from './hasProperty'
type StyledSpan = {
type: 'span'
value: string
style: string
}
type PropertySpan = {
type: 'property'
key: Span
value: Span
}
type ListSpan = {
type: 'list'
value: Span[]
}
type Span = string | StyledSpan | PropertySpan | ListSpan
type PublicSpan = { value: string; style: string }
function getValue(span: Span): string {
if (typeof span === 'string') return span
switch (span.type) {
case 'property':
return getValue(span.key) + ': ' + getValue(span.value)
case 'span':
return span.value
case 'list':
return span.value.map(getValue).join(', ')
}
}
function mapValue(span: Span, f: (value: string) => string): Span {
if (typeof span === 'string') return f(span)
switch (span.type) {
case 'property':
return {
...span,
key: mapValue(span.key, f),
value: mapValue(span.value, f),
}
case 'span':
return {
...span,
value: f(span.value),
}
case 'list':
return {
...span,
value: span.value.map((value) => mapValue(value, f)),
}
}
}
function styled(value: string) {
return { style: '#333', value }
}
function toPublicSpans(span: Span): PublicSpan[] {
function convert(acc: PublicSpan[], span: Span) {
if (typeof span === 'string') {
acc.push(styled(span))
return
}
switch (span.type) {
case 'property':
convert(acc, span.key)
convert(acc, ': ')
convert(acc, span.value)
break
case 'span':
acc.push(span)
break
case 'list':
span.value.forEach((value) => {
convert(acc, value)
})
break
}
}
const output: PublicSpan[] = []
convert(output, span)
return output
}
function normalizeSpans(spans: Span | Span[]): Span[] {
if (Array.isArray(spans)) return spans
return [spans]
}
type Options = {
showHidden?: boolean
depth?: number
colors?: boolean
customInspect?: boolean
bracketSeparator?: string
maxLineLength?: number
}
type Context = Required<Options> & {
seen: unknown[]
stylize: (value: string, style: string) => Span
}
/**
* Print a value out in the best way possible for its type.
*
* @param {unknown} value The value to print out.
* @param {Options} options Optional options object that alters the output.
* @license MIT (© Joyent)
*/
function inspect(value: unknown, options: Options = {}): PublicSpan[] {
const ctx: Context = {
seen: [],
stylize: options.colors ? stylizeWithColor : stylizeNoColor,
showHidden: options.showHidden ?? false,
depth: options.depth ?? 2,
colors: options.colors ?? false,
customInspect: options.customInspect ?? true,
bracketSeparator: options.bracketSeparator ?? ' ',
maxLineLength: options.maxLineLength ?? 60,
}
try {
return toPublicSpans(formatValue(ctx, value, ctx.depth))
} catch {
return []
}
}
namespace inspect {
export let styles: Record<string, string>
}
export default inspect
inspect.styles = {
special: 'rgb(59, 108, 212)',
number: '#c92c2c',
boolean: '#c92c2c',
undefined: 'grey',
null: 'grey',
string: '#2e9f74',
date: '#2e9f74',
// "name": intentionally not styling
regexp: 'red',
}
function stylizeNoColor(str: string, _styleType: unknown): Span {
return str
}
function stylizeWithColor(str: string, styleType: string): Span {
let style = inspect.styles[styleType]
if (style) {
return { type: 'span', value: str, style }
} else {
return str
}
}
function isBoolean(arg: unknown): arg is boolean {
return typeof arg === 'boolean'
}
function isUndefined(arg: unknown): arg is undefined {
return arg === void 0
}
function isFunction(arg: unknown): arg is Function {
return typeof arg === 'function'
}
function isString(arg: unknown): arg is string {
return typeof arg === 'string'
}
function isNumber(arg: unknown): arg is number {
return typeof arg === 'number'
}
function isNull(arg: unknown): arg is null {
return arg === null
}
function isRegExp(re: unknown): re is RegExp {
return isObject(re) && objectToString(re) === '[object RegExp]'
}
function isObject(arg: unknown): arg is object {
return typeof arg === 'object' && arg !== null
}
function isError(e: unknown): e is Error {
return (
isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error)
)
}
function isDate(d: unknown): d is Date {
return isObject(d) && objectToString(d) === '[object Date]'
}
function objectToString(o: unknown): string {
return Object.prototype.toString.call(o)
}
function arrayToHash(array: any[]) {
let hash: Record<string, boolean> = {}
array.forEach((val) => {
hash[val] = true
})
return hash
}
function formatArray(
ctx: Context,
value: unknown[],
recurseTimes: number,
visibleKeys: Record<string, boolean>,
keys: string[]
): ListSpan {
let output: Span[] = []
for (let i = 0, l = value.length; i < l; ++i) {
if (hasProperty(value, String(i))) {
output.push(
...normalizeSpans(
formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)
)
)
} else {
output.push('')
}
}
keys.forEach((key) => {
if (!key.match(/^\d+$/)) {
output.push(
...normalizeSpans(
formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)
)
)
}
})
return { type: 'list', value: output }
}
function formatError(value: Error): string {
return '[' + Error.prototype.toString.call(value) + ']'
}
function formatValue(
ctx: Context,
value: unknown,
recurseTimes: number | null
): Span {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (
ctx.customInspect &&
isObject(value) &&
hasProperty(value, 'inspect') &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)
) {
let ret = value.inspect(recurseTimes, ctx)
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes)
}
return ret
}
// Primitive types cannot have properties
let primitive = formatPrimitive(ctx, value)
if (primitive) {
return primitive
}
// Look up the keys of the object.
let keys = objectKeys(value)
let visibleKeys = arrayToHash(keys)
try {
if (ctx.showHidden && Object.getOwnPropertyNames) {
keys = Object.getOwnPropertyNames(value)
}
} catch (e) {
// ignore
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (
isError(value) &&
(keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)
) {
return formatError(value)
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
let name = value.name ? ': ' + value.name : ''
return ctx.stylize('[Function' + name + ']', 'special')
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp')
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date')
}
if (isError(value)) {
return formatError(value)
}
}
let base = ''
let array = false
let braces: [string, string] = ['{', '}']
// Make Array say that they are Array
if (Array.isArray(value)) {
array = true
braces = ['[', ']']
}
// Make functions say that they are functions
if (isFunction(value)) {
let n = value.name ? ': ' + value.name : ''
base = '[Function' + n + ']'
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = RegExp.prototype.toString.call(value)
}
// Make dates with properties first say the date
if (isDate(value)) {
base = Date.prototype.toUTCString.call(value)
}
// Make error with message first say the error
if (isError(value)) {
base = formatError(value)
}
if (keys.length === 0 && (!array || (value as unknown[]).length == 0)) {
return braces[0] + base + braces[1]
}
if (recurseTimes === null || recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp')
} else {
return ctx.stylize('[Object]', 'special')
}
}
ctx.seen.push(value)
let output: Span[]
if (array) {
const group = formatArray(
ctx,
value as unknown[],
recurseTimes,
visibleKeys,
keys
)
output = reduceToSingleString(ctx, group, base, braces)
} else {
const list: ListSpan = {
type: 'list',
value: flatten(
keys.map((key) => {
return normalizeSpans(
formatProperty(ctx, value, recurseTimes, visibleKeys, key, array)
)
})
),
}
output = reduceToSingleString(ctx, list, base, braces)
}
ctx.seen.pop()
return {
type: 'list',
value: output,
}
}
function formatProperty(
ctx: Context,
value: unknown,
recurseTimes: number,
visibleKeys: Record<string, boolean>,
key: string,
array: boolean
): Span | Span[] {
let name: Span | undefined
let str: Span | undefined
let desc: any = { value: void 0 }
try {
// ie6 › navigator.toString
// throws Error: Object doesn't support this property or method
desc.value = (value as any)[key]
} catch (e) {
// ignore
}
try {
// ie10 › Object.getOwnPropertyDescriptor(window.location, 'hash')
// throws TypeError: Object doesn't support this action
if (Object.getOwnPropertyDescriptor) {
desc = Object.getOwnPropertyDescriptor(value, key) || desc
}
} catch (e) {
// ignore
}
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special')
} else {
str = ctx.stylize('[Getter]', 'special')
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special')
}
}
if (!hasProperty(visibleKeys, key)) {
name = '[' + key + ']'
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null)
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1)
}
// Add indentation
if (getValue(str).indexOf('\n') > -1) {
str = mapValue(str, (value) => value.replace('\n', '\n '))
}
} else {
str = ctx.stylize('[Circular]', 'special')
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str
}
let keyName = JSON.stringify('' + key)
if (keyName.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = ctx.stylize(keyName.substr(1, keyName.length - 2), 'name')
} else {
name = ctx.stylize(
keyName
.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'"),
'string'
)
}
}
return { type: 'property', key: name, value: str }
}
function formatPrimitive(ctx: Context, value: unknown): Span | undefined {
if (isUndefined(value)) return ctx.stylize('undefined', 'undefined')
if (isString(value)) {
let simple =
"'" +
JSON.stringify(value)
.replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') +
"'"
return ctx.stylize(simple, 'string')
}
if (isNumber(value)) return ctx.stylize('' + value, 'number')
if (isBoolean(value)) return ctx.stylize('' + value, 'boolean')
if (isNull(value)) return ctx.stylize('null', 'null')
}
function addSeparator<T>(array: T[], separator: T): T[] {
const output: T[] = []
array.forEach((item, index) => {
if (index !== 0) {
output.push(separator)
}
output.push(item)
})
return output
}
function reduceToSingleString(
ctx: Context,
output: ListSpan,
base: string,
braces: [string, string]
): Span[] {
base = base ? `${base} ` : ''
const length = output.value.reduce((prev: number, cur: Span) => {
return prev + getValue(cur).length + 1
}, 0)
if (length > ctx.maxLineLength) {
return [
base + braces[0] + '\n ',
...addSeparator(output.value, ',\n '),
'\n' + braces[1],
]
}
return [
base + braces[0] + ctx.bracketSeparator,
...addSeparator(output.value, ', '),
ctx.bracketSeparator + braces[1],
]
}
function flatten<T>(arrays: T[][]): T[] {
const output: T[] = []
arrays.forEach((array) => {
output.push(...array)
})
return output
}
/**
* Make sure `Object.keys` work for `undefined`
* values that are still there, like `document.all`.
* http://lists.w3.org/Archives/Public/public-html/2009Jun/0546.html
*/
function objectKeys(value: any): string[] {
try {
return Object.keys(value)
} catch {
return []
}
} | the_stack |
import browsePage from "../../support/pages/browse";
import detailPage from "../../support/pages/detail";
import {Application} from "../../support/application.config";
import {toolbar} from "../../support/components/common";
import "cypress-wait-until";
import detailPageNonEntity from "../../support/pages/detail-nonEntity";
import LoginPage from "../../support/pages/login";
describe("xml scenario for snippet view on browse documents page", () => {
let facets: string[] = ["collection", "flow"];
//login with valid account and go to /browse page
before(() => {
cy.visit("/");
cy.contains(Application.title);
cy.loginAsDeveloper().withRequest();
LoginPage.postLogin();
cy.waitForAsyncRequest();
});
beforeEach(() => {
cy.loginAsDeveloper().withRequest();
cy.waitForAsyncRequest();
});
afterEach(() => {
cy.resetTestUser();
cy.waitForAsyncRequest();
});
after(() => {
cy.resetTestUser();
cy.waitForAsyncRequest();
});
it("select Customer XML entity instances and verify entity, docs, hub/entity properties", () => {
cy.waitUntil(() => toolbar.getExploreToolbarIcon()).click();
cy.waitUntil(() => browsePage.getExploreButton()).click();
browsePage.clickFacetView();
browsePage.selectEntity("Customer");
browsePage.getSelectedEntity().should("contain", "Customer");
browsePage.getHubPropertiesExpanded();
browsePage.scrollSideBar();
browsePage.getFacetItemCheckbox("collection", "mapCustomersXML").scrollIntoView().click();
browsePage.getGreySelectedFacets("mapCustomersXML").should("exist");
browsePage.getFacetApplyButton().click();
browsePage.getTotalDocuments().should("be.gte", 5);
browsePage.getDocuments().each((item, i) => {
browsePage.getDocumentEntityName(i).should("exist");
browsePage.getDocumentPKey(i).should("exist");
browsePage.getDocumentPKeyValue(i).should("exist");
browsePage.getDocumentSnippet(i).should("exist");
browsePage.getDocumentCreatedOn(i).should("exist");
browsePage.getDocumentSources(i).should("exist");
browsePage.getDocumentRecordType(i).should("exist");
});
facets.forEach(function (item) {
browsePage.getFacet(item).should("exist");
browsePage.getFacetItems(item).should("exist");
});
browsePage.clickClearFacetSearchSelection("mapCustomersXML");
});
it("apply facet search and verify docs, hub/entity properties", () => {
browsePage.selectEntity("All Entities");
browsePage.getSelectedEntity().should("contain", "All Entities");
browsePage.getShowMoreLink("collection").click();
browsePage.getTotalDocuments().should("be.greaterThan", 25);
browsePage.scrollSideBar();
browsePage.getFacetItemCheckbox("collection", "mapCustomersXML").click();
browsePage.getSelectedFacets().should("exist");
browsePage.getGreySelectedFacets("mapCustomersXML").should("exist");
browsePage.getFacetApplyButton().should("exist");
browsePage.getClearGreyFacets().should("exist");
browsePage.getFacetApplyButton().click();
browsePage.getTotalDocuments().should("be.equal", 5);
browsePage.getClearAllFacetsButton().should("exist");
browsePage.getFacetSearchSelectionCount("collection").should("contain", "1");
browsePage.clickClearFacetSearchSelection("mapCustomersXML");
});
it("apply facet search and clear individual grey facet", () => {
browsePage.selectEntity("All Entities");
browsePage.getSelectedEntity().should("contain", "All Entities");
browsePage.getShowMoreLink("collection").click();
browsePage.getTotalDocuments().should("be.greaterThan", 25);
browsePage.showMoreCollection();
browsePage.scrollSideBar();
browsePage.getFacetItemCheckbox("collection", "mapCustomersXML").click();
browsePage.getGreySelectedFacets("mapCustomersXML").click();
browsePage.getTotalDocuments().should("be.greaterThan", 25);
});
it("apply facet search and clear all grey facets", () => {
browsePage.selectEntity("All Entities");
browsePage.getSelectedEntity().should("contain", "All Entities");
browsePage.getShowMoreLink("collection").click();
browsePage.getTotalDocuments().should("be.greaterThan", 25);
browsePage.showMoreCollection();
browsePage.getFacetItemCheckbox("collection", "Customer").click();
browsePage.scrollSideBar();
browsePage.getFacetItemCheckbox("collection", "mapCustomersXML").click();
browsePage.getGreySelectedFacets("Customer").should("exist");
browsePage.getGreySelectedFacets("mapCustomersXML").should("exist");
browsePage.getClearGreyFacets().click();
browsePage.getTotalDocuments().should("be.greaterThan", 25);
});
it("search for a simple text/query and verify content", () => {
browsePage.search("Randolph");
browsePage.getTotalDocuments().should("be.equal", 1);
browsePage.getDocumentEntityName(0).should("exist");
browsePage.getDocumentPKey(0).should("exist");
browsePage.getDocumentPKeyValue(0).should("exist");
browsePage.getDocumentSnippet(0).should("exist");
browsePage.getDocumentCreatedOn(0).should("exist");
browsePage.getDocumentSources(0).should("exist");
browsePage.getDocumentRecordType(0).should("exist");
browsePage.getDocumentRecordType(0).should("be.equal", "xml");
});
it("verify instance view of the document", () => {
browsePage.getSearchText().clear();
browsePage.waitForSpinnerToDisappear();
browsePage.search("Randolph");
browsePage.getTotalDocuments().should("be.equal", 1);
browsePage.getInstanceViewIcon().click();
detailPage.getInstanceView().should("exist");
detailPage.getDocumentEntity().should("contain", "Customer");
detailPage.getDocumentID().should("contain", "0");
detailPage.getDocumentTimestamp().should("exist");
detailPage.getDocumentSource().should("contain", "CustomerSourceName");
detailPage.getDocumentRecordType().should("contain", "xml");
detailPage.getDocumentTable().should("exist");
browsePage.backToResults();
cy.waitUntil(() => browsePage.getSearchText());
});
it("verify source view of the document", () => {
browsePage.getSearchText().clear();
browsePage.waitForSpinnerToDisappear();
browsePage.search("Randolph");
browsePage.getTotalDocuments().should("be.equal", 1);
browsePage.getSourceViewIcon().click();
detailPage.getSourceView().click();
detailPage.getDocumentXML().should("exist");
browsePage.backToResults();
cy.waitUntil(() => browsePage.getSearchText());
});
it("select Customer xml entity instances and verify table", () => {
browsePage.selectEntity("Customer");
browsePage.getSelectedEntity().should("contain", "Customer");
browsePage.getHubPropertiesExpanded();
browsePage.scrollSideBar();
cy.waitUntil(() => browsePage.getFacetItemCheckbox("collection", "mapCustomersXML")).click();
browsePage.getGreySelectedFacets("mapCustomersXML").should("exist");
browsePage.getFacetApplyButton().click();
browsePage.clickTableView();
browsePage.getTotalDocuments().should("be.gte", 5);
//check table rows
browsePage.getTableRows().should("have.length", 5);
//check table columns
browsePage.getTableColumns().should("have.length", 6);
browsePage.clickClearFacetSearchSelection("mapCustomersXML");
});
it("verify instance view of the document", () => {
browsePage.search("Bowman");
browsePage.getTotalDocuments().should("be.equal", 1);
browsePage.getTableViewInstanceIcon().click();
detailPage.getInstanceView().should("exist");
detailPage.getDocumentEntity().should("contain", "Customer");
detailPage.getDocumentID().should("contain", "203");
detailPage.getDocumentTimestamp().should("exist");
detailPage.getDocumentSource().should("contain", "CustomerSourceName");
detailPage.getDocumentRecordType().should("contain", "xml");
detailPage.getDocumentTable().should("exist");
browsePage.backToResults();
cy.waitUntil(() => browsePage.getSearchText());
});
it("verify source view of the document", () => {
browsePage.getSearchText().clear();
browsePage.waitForSpinnerToDisappear();
browsePage.search("Bowman");
browsePage.getTotalDocuments().should("be.equal", 1);
browsePage.getTableViewSourceIcon().click();
detailPage.getSourceView().click();
detailPage.getDocumentXML().should("exist");
browsePage.backToResults();
cy.waitUntil(() => browsePage.getSearchText());
browsePage.getSearchText().clear();
});
it("verify metadata view of the document", () => {
browsePage.getSearchText().clear();
browsePage.waitForSpinnerToDisappear();
browsePage.search("Bowman");
browsePage.getTotalDocuments().should("be.equal", 1);
browsePage.getTableViewSourceIcon().click();
detailPage.getMetadataView().click();
detailPage.getDocumentUri().should("exist");
detailPage.getDocumentQuality().should("exist");
detailPage.getDocumentCollections().should("exist");
detailPage.getDocumentPermissions().should("exist");
detailPage.getDocumentMetadataValues().should("exist");
detailPage.getDocumentProperties().should("not.exist");
detailPage.getDocumentNoPropertiesMessage().should("exist");
browsePage.backToResults();
cy.waitUntil(() => browsePage.getSearchText());
browsePage.getSearchText().clear();
});
it("verify record view of the XML document in non-entity detail page", () => {
browsePage.selectEntity("All Data");
cy.waitUntil(() => browsePage.getNavigationIconForDocument("/dictionary/first-names.xml")).click({force: true});
browsePage.waitForSpinnerToDisappear();
detailPageNonEntity.getRecordView().should("exist");
detailPage.getDocumentXML().should("exist");
detailPageNonEntity.getDocumentUri().should("contain", "/dictionary/first-names.xml");
detailPageNonEntity.getDocumentQuality().should("exist");
detailPageNonEntity.getSourceTable().should("exist");
detailPageNonEntity.getHistoryTable().should("exist");
detailPageNonEntity.getDocumentCollections().should("exist");
detailPageNonEntity.getDocumentPermissions().should("exist");
detailPageNonEntity.getDocumentMetadataValues().should("not.exist");
detailPageNonEntity.getDocumentProperties().should("not.exist");
detailPageNonEntity.getDocumentNoPropertiesMessage().should("exist");
detailPageNonEntity.clickBackButton();
browsePage.waitForSpinnerToDisappear();
cy.waitForAsyncRequest();
browsePage.getSelectedEntity().should("contain", "All Data");
});
it("verify metadata view of the document properties", () => {
browsePage.selectEntity("All Data");
browsePage.search("robert");
cy.waitUntil(() => browsePage.getNavigationIconForDocument("/thesaurus/nicknames.xml")).click({force: true});
browsePage.waitForSpinnerToDisappear();
detailPageNonEntity.getDocumentProperties().should("exist");
detailPageNonEntity.getDocumentNoPropertiesMessage().should("not.exist");
browsePage.backToResults();
cy.waitUntil(() => browsePage.getSearchText());
browsePage.getSearchText().clear();
browsePage.search("201");
cy.waitUntil(() => browsePage.getNavigationIconForDocument("/xml/customers/CustXMLDoc1.xml")).click({force: true});
browsePage.waitForSpinnerToDisappear();
detailPage.getMetadataView().click();
detailPage.getDocumentProperties().should("exist");
detailPage.getDocumentNoPropertiesMessage().should("not.exist");
});
}); | the_stack |
import { KubernetesObject } from 'kpt-functions';
import * as apisMetaV1 from './io.k8s.apimachinery.pkg.apis.meta.v1';
// CrossVersionObjectReference contains enough information to let you identify the referred resource.
export class CrossVersionObjectReference {
// API version of the referent
public apiVersion?: string;
// Kind of the referent; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds"
public kind: string;
// Name of the referent; More info: http://kubernetes.io/docs/user-guide/identifiers#names
public name: string;
constructor(desc: CrossVersionObjectReference) {
this.apiVersion = desc.apiVersion;
this.kind = desc.kind;
this.name = desc.name;
}
}
// configuration of a horizontal pod autoscaler.
export class HorizontalPodAutoscaler implements KubernetesObject {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
public apiVersion: string;
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
public kind: string;
// Standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
public metadata: apisMetaV1.ObjectMeta;
// behaviour of autoscaler. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status.
public spec?: HorizontalPodAutoscalerSpec;
// current information about the autoscaler.
public status?: HorizontalPodAutoscalerStatus;
constructor(desc: HorizontalPodAutoscaler.Interface) {
this.apiVersion = HorizontalPodAutoscaler.apiVersion;
this.kind = HorizontalPodAutoscaler.kind;
this.metadata = desc.metadata;
this.spec = desc.spec;
this.status = desc.status;
}
}
export function isHorizontalPodAutoscaler(
o: any
): o is HorizontalPodAutoscaler {
return (
o &&
o.apiVersion === HorizontalPodAutoscaler.apiVersion &&
o.kind === HorizontalPodAutoscaler.kind
);
}
export namespace HorizontalPodAutoscaler {
export const apiVersion = 'autoscaling/v1';
export const group = 'autoscaling';
export const version = 'v1';
export const kind = 'HorizontalPodAutoscaler';
// named constructs a HorizontalPodAutoscaler with metadata.name set to name.
export function named(name: string): HorizontalPodAutoscaler {
return new HorizontalPodAutoscaler({ metadata: { name } });
}
// configuration of a horizontal pod autoscaler.
export interface Interface {
// Standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
metadata: apisMetaV1.ObjectMeta;
// behaviour of autoscaler. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status.
spec?: HorizontalPodAutoscalerSpec;
// current information about the autoscaler.
status?: HorizontalPodAutoscalerStatus;
}
}
// list of horizontal pod autoscaler objects.
export class HorizontalPodAutoscalerList {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
public apiVersion: string;
// list of horizontal pod autoscaler objects.
public items: HorizontalPodAutoscaler[];
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
public kind: string;
// Standard list metadata.
public metadata?: apisMetaV1.ListMeta;
constructor(desc: HorizontalPodAutoscalerList) {
this.apiVersion = HorizontalPodAutoscalerList.apiVersion;
this.items = desc.items.map((i) => new HorizontalPodAutoscaler(i));
this.kind = HorizontalPodAutoscalerList.kind;
this.metadata = desc.metadata;
}
}
export function isHorizontalPodAutoscalerList(
o: any
): o is HorizontalPodAutoscalerList {
return (
o &&
o.apiVersion === HorizontalPodAutoscalerList.apiVersion &&
o.kind === HorizontalPodAutoscalerList.kind
);
}
export namespace HorizontalPodAutoscalerList {
export const apiVersion = 'autoscaling/v1';
export const group = 'autoscaling';
export const version = 'v1';
export const kind = 'HorizontalPodAutoscalerList';
// list of horizontal pod autoscaler objects.
export interface Interface {
// list of horizontal pod autoscaler objects.
items: HorizontalPodAutoscaler[];
// Standard list metadata.
metadata?: apisMetaV1.ListMeta;
}
}
// specification of a horizontal pod autoscaler.
export class HorizontalPodAutoscalerSpec {
// upper limit for the number of pods that can be set by the autoscaler; cannot be smaller than MinReplicas.
public maxReplicas: number;
// minReplicas is the lower limit for the number of replicas to which the autoscaler can scale down. It defaults to 1 pod. minReplicas is allowed to be 0 if the alpha feature gate HPAScaleToZero is enabled and at least one Object or External metric is configured. Scaling is active as long as at least one metric value is available.
public minReplicas?: number;
// reference to scaled resource; horizontal pod autoscaler will learn the current resource consumption and will set the desired number of pods by using its Scale subresource.
public scaleTargetRef: CrossVersionObjectReference;
// target average CPU utilization (represented as a percentage of requested CPU) over all the pods; if not specified the default autoscaling policy will be used.
public targetCPUUtilizationPercentage?: number;
constructor(desc: HorizontalPodAutoscalerSpec) {
this.maxReplicas = desc.maxReplicas;
this.minReplicas = desc.minReplicas;
this.scaleTargetRef = desc.scaleTargetRef;
this.targetCPUUtilizationPercentage = desc.targetCPUUtilizationPercentage;
}
}
// current status of a horizontal pod autoscaler
export class HorizontalPodAutoscalerStatus {
// current average CPU utilization over all pods, represented as a percentage of requested CPU, e.g. 70 means that an average pod is using now 70% of its requested CPU.
public currentCPUUtilizationPercentage?: number;
// current number of replicas of pods managed by this autoscaler.
public currentReplicas: number;
// desired number of replicas of pods managed by this autoscaler.
public desiredReplicas: number;
// last time the HorizontalPodAutoscaler scaled the number of pods; used by the autoscaler to control how often the number of pods is changed.
public lastScaleTime?: apisMetaV1.Time;
// most recent generation observed by this autoscaler.
public observedGeneration?: number;
constructor(desc: HorizontalPodAutoscalerStatus) {
this.currentCPUUtilizationPercentage = desc.currentCPUUtilizationPercentage;
this.currentReplicas = desc.currentReplicas;
this.desiredReplicas = desc.desiredReplicas;
this.lastScaleTime = desc.lastScaleTime;
this.observedGeneration = desc.observedGeneration;
}
}
// Scale represents a scaling request for a resource.
export class Scale implements KubernetesObject {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
public apiVersion: string;
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
public kind: string;
// Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata.
public metadata: apisMetaV1.ObjectMeta;
// defines the behavior of the scale. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status.
public spec?: ScaleSpec;
// current status of the scale. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status. Read-only.
public status?: ScaleStatus;
constructor(desc: Scale.Interface) {
this.apiVersion = Scale.apiVersion;
this.kind = Scale.kind;
this.metadata = desc.metadata;
this.spec = desc.spec;
this.status = desc.status;
}
}
export function isScale(o: any): o is Scale {
return o && o.apiVersion === Scale.apiVersion && o.kind === Scale.kind;
}
export namespace Scale {
export const apiVersion = 'autoscaling/v1';
export const group = 'autoscaling';
export const version = 'v1';
export const kind = 'Scale';
// named constructs a Scale with metadata.name set to name.
export function named(name: string): Scale {
return new Scale({ metadata: { name } });
}
// Scale represents a scaling request for a resource.
export interface Interface {
// Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata.
metadata: apisMetaV1.ObjectMeta;
// defines the behavior of the scale. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status.
spec?: ScaleSpec;
// current status of the scale. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status. Read-only.
status?: ScaleStatus;
}
}
// ScaleSpec describes the attributes of a scale subresource.
export class ScaleSpec {
// desired number of instances for the scaled object.
public replicas?: number;
}
// ScaleStatus represents the current status of a scale subresource.
export class ScaleStatus {
// actual number of observed instances of the scaled object.
public replicas: number;
// label query over pods that should match the replicas count. This is same as the label selector but in the string format to avoid introspection by clients. The string will be in the same format as the query-param syntax. More info about label selectors: http://kubernetes.io/docs/user-guide/labels#label-selectors
public selector?: string;
constructor(desc: ScaleStatus) {
this.replicas = desc.replicas;
this.selector = desc.selector;
}
} | the_stack |
import Point from '../geometry/Point';
import CellState from '../cell/CellState';
import InternalMouseEvent from '../event/InternalMouseEvent';
import ConnectionConstraint from '../other/ConnectionConstraint';
import Rectangle from '../geometry/Rectangle';
import { DIRECTION } from '../../util/Constants';
import { mixInto } from '../../util/Utils';
import { getRotatedPoint, toRadians } from '../../util/mathUtils';
import Cell from '../cell/Cell';
import CellArray from '../cell/CellArray';
import EventObject from '../event/EventObject';
import InternalEvent from '../event/InternalEvent';
import Dictionary from '../../util/Dictionary';
import { Graph } from '../Graph';
import ConnectionHandler from '../handler/ConnectionHandler';
declare module '../Graph' {
interface Graph {
constrainChildren: boolean;
constrainRelativeChildren: boolean;
disconnectOnMove: boolean;
cellsDisconnectable: boolean;
getOutlineConstraint: (
point: Point,
terminalState: CellState,
me: InternalMouseEvent
) => ConnectionConstraint | null;
getAllConnectionConstraints: (
terminal: CellState | null,
source: boolean
) => ConnectionConstraint[] | null;
getConnectionConstraint: (
edge: CellState,
terminal: CellState | null,
source: boolean
) => ConnectionConstraint;
setConnectionConstraint: (
edge: Cell,
terminal: Cell | null,
source: boolean,
constraint: ConnectionConstraint | null
) => void;
getConnectionPoint: (
vertex: CellState,
constraint: ConnectionConstraint,
round?: boolean
) => Point | null;
connectCell: (
edge: Cell,
terminal: Cell | null,
source: boolean,
constraint?: ConnectionConstraint | null
) => Cell;
cellConnected: (
edge: Cell,
terminal: Cell | null,
source: boolean,
constraint?: ConnectionConstraint | null
) => void;
disconnectGraph: (cells: CellArray) => void;
getConnections: (cell: Cell, parent?: Cell | null) => CellArray;
isConstrainChild: (cell: Cell) => boolean;
isConstrainChildren: () => boolean;
setConstrainChildren: (value: boolean) => void;
isConstrainRelativeChildren: () => boolean;
setConstrainRelativeChildren: (value: boolean) => void;
isDisconnectOnMove: () => boolean;
setDisconnectOnMove: (value: boolean) => void;
isCellDisconnectable: (cell: Cell, terminal: Cell | null, source: boolean) => boolean;
isCellsDisconnectable: () => boolean;
setCellsDisconnectable: (value: boolean) => void;
isValidSource: (cell: Cell | null) => boolean;
isValidTarget: (cell: Cell | null) => boolean;
isValidConnection: (source: Cell | null, target: Cell | null) => boolean;
setConnectable: (connectable: boolean) => void;
isConnectable: () => boolean;
}
}
type PartialGraph = Pick<Graph, 'getView' | 'getDataModel' | 'isPortsEnabled'>;
type PartialConnections = Pick<
Graph,
| 'constrainChildren'
| 'constrainRelativeChildren'
| 'disconnectOnMove'
| 'cellsDisconnectable'
| 'getOutlineConstraint'
| 'getAllConnectionConstraints'
| 'getConnectionConstraint'
| 'setConnectionConstraint'
| 'getConnectionPoint'
| 'connectCell'
| 'cellConnected'
| 'disconnectGraph'
| 'getConnections'
| 'isConstrainChild'
| 'isConstrainChildren'
| 'setConstrainChildren'
| 'isConstrainRelativeChildren'
| 'setConstrainRelativeChildren'
| 'isDisconnectOnMove'
| 'setDisconnectOnMove'
| 'isCellDisconnectable'
| 'isCellsDisconnectable'
| 'setCellsDisconnectable'
| 'isValidSource'
| 'isValidTarget'
| 'isValidConnection'
| 'setConnectable'
| 'isConnectable'
| 'setCellStyles'
| 'fireEvent'
| 'isPort'
| 'getTerminalForPort'
| 'isResetEdgesOnConnect'
| 'resetEdge'
| 'getEdges'
| 'isCellLocked'
| 'isAllowDanglingEdges'
| 'isConnectableEdges'
| 'getPlugin'
| 'batchUpdate'
>;
type PartialType = PartialGraph & PartialConnections;
// @ts-expect-error The properties of PartialGraph are defined elsewhere.
const ConnectionsMixin: PartialType = {
/*****************************************************************************
* Group: Cell connecting and connection constraints
*****************************************************************************/
/**
* Specifies if a child should be constrained inside the parent bounds after a
* move or resize of the child.
* @default true
*/
constrainChildren: true,
/**
* Specifies if child cells with relative geometries should be constrained
* inside the parent bounds, if {@link constrainChildren} is `true`, and/or the
* {@link maximumGraphBounds}.
* @default false
*/
constrainRelativeChildren: false,
/**
* Specifies if edges should be disconnected from their terminals when they
* are moved.
* @default true
*/
disconnectOnMove: true,
cellsDisconnectable: true,
/**
* Returns the constraint used to connect to the outline of the given state.
*/
getOutlineConstraint(point, terminalState, me) {
if (terminalState.shape) {
const bounds = <Rectangle>this.getView().getPerimeterBounds(terminalState);
const direction = terminalState.style.direction;
if (direction === DIRECTION.NORTH || direction === DIRECTION.SOUTH) {
bounds.x += bounds.width / 2 - bounds.height / 2;
bounds.y += bounds.height / 2 - bounds.width / 2;
const tmp = bounds.width;
bounds.width = bounds.height;
bounds.height = tmp;
}
const alpha = toRadians(terminalState.shape.getShapeRotation());
if (alpha !== 0) {
const cos = Math.cos(-alpha);
const sin = Math.sin(-alpha);
const ct = new Point(bounds.getCenterX(), bounds.getCenterY());
point = getRotatedPoint(point, cos, sin, ct);
}
let sx = 1;
let sy = 1;
let dx = 0;
let dy = 0;
// LATER: Add flipping support for image shapes
if (terminalState.cell.isVertex()) {
let flipH = terminalState.style.flipH;
let flipV = terminalState.style.flipV;
if (direction === DIRECTION.NORTH || direction === DIRECTION.SOUTH) {
const tmp = flipH;
flipH = flipV;
flipV = tmp;
}
if (flipH) {
sx = -1;
dx = -bounds.width;
}
if (flipV) {
sy = -1;
dy = -bounds.height;
}
}
point = new Point(
(point.x - bounds.x) * sx - dx + bounds.x,
(point.y - bounds.y) * sy - dy + bounds.y
);
const x =
bounds.width === 0
? 0
: Math.round(((point.x - bounds.x) * 1000) / bounds.width) / 1000;
const y =
bounds.height === 0
? 0
: Math.round(((point.y - bounds.y) * 1000) / bounds.height) / 1000;
return new ConnectionConstraint(new Point(x, y), false);
}
return null;
},
/**
* Returns an array of all {@link mxConnectionConstraints} for the given terminal. If
* the shape of the given terminal is a {@link mxStencilShape} then the constraints
* of the corresponding {@link mxStencil} are returned.
*
* @param terminal {@link CellState} that represents the terminal.
* @param source Boolean that specifies if the terminal is the source or target.
*/
getAllConnectionConstraints(terminal, source) {
if (terminal && terminal.shape && terminal.shape.stencil) {
return terminal.shape.stencil.constraints;
}
return null;
},
/**
* Returns an {@link ConnectionConstraint} that describes the given connection
* point. This result can then be passed to {@link getConnectionPoint}.
*
* @param edge {@link CellState} that represents the edge.
* @param terminal {@link CellState} that represents the terminal.
* @param source Boolean indicating if the terminal is the source or target.
*/
getConnectionConstraint(edge, terminal, source = false) {
let point: Point | null = null;
const x = edge.style[source ? 'exitX' : 'entryX'];
if (x !== undefined) {
const y = edge.style[source ? 'exitY' : 'entryY'];
if (y !== undefined) {
point = new Point(x, y);
}
}
let perimeter = false;
let dx = 0;
let dy = 0;
if (point) {
perimeter = edge.style[source ? 'exitPerimeter' : 'entryPerimeter'] || false;
// Add entry/exit offset
dx = <number>edge.style[source ? 'exitDx' : 'entryDx'];
dy = <number>edge.style[source ? 'exitDy' : 'entryDy'];
dx = Number.isFinite(dx) ? dx : 0;
dy = Number.isFinite(dy) ? dy : 0;
}
return new ConnectionConstraint(point, perimeter, null, dx, dy);
},
/**
* Sets the {@link ConnectionConstraint} that describes the given connection point.
* If no constraint is given then nothing is changed. To remove an existing
* constraint from the given edge, use an empty constraint instead.
*
* @param edge {@link mxCell} that represents the edge.
* @param terminal {@link mxCell} that represents the terminal.
* @param source Boolean indicating if the terminal is the source or target.
* @param constraint Optional {@link ConnectionConstraint} to be used for this
* connection.
*/
setConnectionConstraint(edge, terminal, source = false, constraint = null) {
if (constraint) {
this.batchUpdate(() => {
if (!constraint || !constraint.point) {
this.setCellStyles(source ? 'exitX' : 'entryX', null, new CellArray(edge));
this.setCellStyles(source ? 'exitY' : 'entryY', null, new CellArray(edge));
this.setCellStyles(source ? 'exitDx' : 'entryDx', null, new CellArray(edge));
this.setCellStyles(source ? 'exitDy' : 'entryDy', null, new CellArray(edge));
this.setCellStyles(
source ? 'exitPerimeter' : 'entryPerimeter',
null,
new CellArray(edge)
);
} else if (constraint.point) {
this.setCellStyles(
source ? 'exitX' : 'entryX',
constraint.point.x,
new CellArray(edge)
);
this.setCellStyles(
source ? 'exitY' : 'entryY',
constraint.point.y,
new CellArray(edge)
);
this.setCellStyles(
source ? 'exitDx' : 'entryDx',
constraint.dx,
new CellArray(edge)
);
this.setCellStyles(
source ? 'exitDy' : 'entryDy',
constraint.dy,
new CellArray(edge)
);
// Only writes 0 since 1 is default
if (!constraint.perimeter) {
this.setCellStyles(
source ? 'exitPerimeter' : 'entryPerimeter',
'0',
new CellArray(edge)
);
} else {
this.setCellStyles(
source ? 'exitPerimeter' : 'entryPerimeter',
null,
new CellArray(edge)
);
}
}
});
}
},
/**
* Returns the nearest point in the list of absolute points or the center
* of the opposite terminal.
*
* @param vertex {@link CellState} that represents the vertex.
* @param constraint {@link mxConnectionConstraint} that represents the connection point
* constraint as returned by {@link getConnectionConstraint}.
*/
getConnectionPoint(vertex, constraint, round = true) {
let point: Point | null = null;
if (constraint.point) {
const bounds = <Rectangle>this.getView().getPerimeterBounds(vertex);
const cx = new Point(bounds.getCenterX(), bounds.getCenterY());
const direction = vertex.style.direction;
let r1 = 0;
// Bounds need to be rotated by 90 degrees for further computation
if (vertex.style.anchorPointDirection) {
if (direction === DIRECTION.NORTH) {
r1 += 270;
} else if (direction === DIRECTION.WEST) {
r1 += 180;
} else if (direction === DIRECTION.SOUTH) {
r1 += 90;
}
// Bounds need to be rotated by 90 degrees for further computation
if (direction === DIRECTION.NORTH || direction === DIRECTION.SOUTH) {
bounds.rotate90();
}
}
const { scale } = this.getView();
point = new Point(
bounds.x + constraint.point.x * bounds.width + <number>constraint.dx * scale,
bounds.y + constraint.point.y * bounds.height + <number>constraint.dy * scale
);
// Rotation for direction before projection on perimeter
let r2 = vertex.style.rotation || 0;
if (constraint.perimeter) {
if (r1 !== 0) {
// Only 90 degrees steps possible here so no trig needed
let cos = 0;
let sin = 0;
if (r1 === 90) {
sin = 1;
} else if (r1 === 180) {
cos = -1;
} else if (r1 === 270) {
sin = -1;
}
point = <Point>getRotatedPoint(point, cos, sin, cx);
}
point = this.getView().getPerimeterPoint(vertex, point, false);
} else {
r2 += r1;
if (vertex.cell.isVertex()) {
let flipH = vertex.style.flipH;
let flipV = vertex.style.flipV;
if (direction === DIRECTION.NORTH || direction === DIRECTION.SOUTH) {
const temp = flipH;
flipH = flipV;
flipV = temp;
}
if (flipH) {
point.x = 2 * bounds.getCenterX() - point.x;
}
if (flipV) {
point.y = 2 * bounds.getCenterY() - point.y;
}
}
}
// Generic rotation after projection on perimeter
if (r2 !== 0 && point) {
const rad = toRadians(r2);
const cos = Math.cos(rad);
const sin = Math.sin(rad);
point = getRotatedPoint(point, cos, sin, cx);
}
}
if (round && point) {
point.x = Math.round(point.x);
point.y = Math.round(point.y);
}
return point;
},
/**
* Connects the specified end of the given edge to the given terminal
* using {@link cellConnected} and fires {@link InternalEvent.CONNECT_CELL} while the
* transaction is in progress. Returns the updated edge.
*
* @param edge {@link mxCell} whose terminal should be updated.
* @param terminal {@link mxCell} that represents the new terminal to be used.
* @param source Boolean indicating if the new terminal is the source or target.
* @param constraint Optional {@link ConnectionConstraint} to be used for this
* connection.
*/
connectCell(edge, terminal = null, source = false, constraint = null) {
this.batchUpdate(() => {
const previous = edge.getTerminal(source);
this.cellConnected(edge, terminal, source, constraint);
this.fireEvent(
new EventObject(
InternalEvent.CONNECT_CELL,
'edge',
edge,
'terminal',
terminal,
'source',
source,
'previous',
previous
)
);
});
return edge;
},
/**
* Sets the new terminal for the given edge and resets the edge points if
* {@link resetEdgesOnConnect} is true. This method fires
* {@link InternalEvent.CELL_CONNECTED} while the transaction is in progress.
*
* @param edge {@link mxCell} whose terminal should be updated.
* @param terminal {@link mxCell} that represents the new terminal to be used.
* @param source Boolean indicating if the new terminal is the source or target.
* @param constraint {@link mxConnectionConstraint} to be used for this connection.
*/
cellConnected(edge, terminal, source = false, constraint = null) {
this.batchUpdate(() => {
const previous = edge.getTerminal(source);
// Updates the constraint
this.setConnectionConstraint(edge, terminal, source, constraint);
// Checks if the new terminal is a port, uses the ID of the port in the
// style and the parent of the port as the actual terminal of the edge.
if (this.isPortsEnabled()) {
let id = null;
if (terminal && this.isPort(terminal)) {
id = terminal.getId();
terminal = this.getTerminalForPort(terminal, source);
}
// Sets or resets all previous information for connecting to a child port
const key = source ? 'sourcePort' : 'targetPort';
this.setCellStyles(key, id, new CellArray(edge));
}
this.getDataModel().setTerminal(edge, terminal, source);
if (this.isResetEdgesOnConnect()) {
this.resetEdge(edge);
}
this.fireEvent(
new EventObject(
InternalEvent.CELL_CONNECTED,
'edge',
edge,
'terminal',
terminal,
'source',
source,
'previous',
previous
)
);
});
},
/**
* Disconnects the given edges from the terminals which are not in the
* given array.
*
* @param cells Array of {@link Cell} to be disconnected.
*/
disconnectGraph(cells) {
this.batchUpdate(() => {
const { scale, translate: tr } = this.getView();
// Fast lookup for finding cells in array
const dict = new Dictionary<Cell, boolean>();
for (let i = 0; i < cells.length; i += 1) {
dict.put(cells[i], true);
}
for (const cell of cells) {
if (cell.isEdge()) {
let geo = cell.getGeometry();
if (geo) {
const state = this.getView().getState(cell);
const parent = cell.getParent();
const pstate = parent ? this.getView().getState(parent) : null;
if (state && pstate) {
geo = geo.clone();
const dx = -pstate.origin.x;
const dy = -pstate.origin.y;
const pts = state.absolutePoints;
let src = cell.getTerminal(true);
if (src && this.isCellDisconnectable(cell, src, true)) {
while (src && !dict.get(src)) {
src = src.getParent();
}
if (!src && pts[0]) {
geo.setTerminalPoint(
new Point(pts[0].x / scale - tr.x + dx, pts[0].y / scale - tr.y + dy),
true
);
this.getDataModel().setTerminal(cell, null, true);
}
}
let trg = cell.getTerminal(false);
if (trg && this.isCellDisconnectable(cell, trg, false)) {
while (trg && !dict.get(trg)) {
trg = trg.getParent();
}
if (!trg) {
const n = pts.length - 1;
const p = pts[n];
if (p) {
geo.setTerminalPoint(
new Point(p.x / scale - tr.x + dx, p.y / scale - tr.y + dy),
false
);
this.getDataModel().setTerminal(cell, null, false);
}
}
}
this.getDataModel().setGeometry(cell, geo);
}
}
}
}
});
},
/**
* Returns all visible edges connected to the given cell without loops.
*
* @param cell {@link mxCell} whose connections should be returned.
* @param parent Optional parent of the opposite end for a connection to be
* returned.
*/
getConnections(cell, parent = null) {
return this.getEdges(cell, parent, true, true, false);
},
/**
* Returns true if the given cell should be kept inside the bounds of its
* parent according to the rules defined by {@link getOverlap} and
* {@link isAllowOverlapParent}. This implementation returns false for all children
* of edges and {@link isConstrainChildren} otherwise.
*
* @param cell {@link mxCell} that should be constrained.
*/
isConstrainChild(cell) {
return (
this.isConstrainChildren() &&
!!cell.getParent() &&
!(<Cell>cell.getParent()).isEdge()
);
},
/**
* Returns {@link constrainChildren}.
*/
isConstrainChildren() {
return this.constrainChildren;
},
/**
* Sets {@link constrainChildren}.
*/
setConstrainChildren(value) {
this.constrainChildren = value;
},
/**
* Returns {@link constrainRelativeChildren}.
*/
isConstrainRelativeChildren() {
return this.constrainRelativeChildren;
},
/**
* Sets {@link constrainRelativeChildren}.
*/
setConstrainRelativeChildren(value) {
this.constrainRelativeChildren = value;
},
/*****************************************************************************
* Group: Graph behaviour
*****************************************************************************/
/**
* Returns {@link disconnectOnMove} as a boolean.
*/
isDisconnectOnMove() {
return this.disconnectOnMove;
},
/**
* Specifies if edges should be disconnected when moved. (Note: Cloned
* edges are always disconnected.)
*
* @param value Boolean indicating if edges should be disconnected
* when moved.
*/
setDisconnectOnMove(value) {
this.disconnectOnMove = value;
},
/**
* Returns true if the given cell is disconnectable from the source or
* target terminal. This returns {@link isCellsDisconnectable} for all given
* cells if {@link isCellLocked} does not return true for the given cell.
*
* @param cell {@link mxCell} whose disconnectable state should be returned.
* @param terminal {@link mxCell} that represents the source or target terminal.
* @param source Boolean indicating if the source or target terminal is to be
* disconnected.
*/
isCellDisconnectable(cell, terminal = null, source = false) {
return this.isCellsDisconnectable() && !this.isCellLocked(cell);
},
/**
* Returns {@link cellsDisconnectable}.
*/
isCellsDisconnectable() {
return this.cellsDisconnectable;
},
/**
* Sets {@link cellsDisconnectable}.
*/
setCellsDisconnectable(value) {
this.cellsDisconnectable = value;
},
/**
* Returns true if the given cell is a valid source for new connections.
* This implementation returns true for all non-null values and is
* called by is called by {@link isValidConnection}.
*
* @param cell {@link mxCell} that represents a possible source or null.
*/
isValidSource(cell) {
return (
(cell == null && this.isAllowDanglingEdges()) ||
(cell != null &&
(!cell.isEdge() || this.isConnectableEdges()) &&
cell.isConnectable())
);
},
/**
* Returns {@link isValidSource} for the given cell. This is called by
* {@link isValidConnection}.
*
* @param cell {@link mxCell} that represents a possible target or null.
*/
isValidTarget(cell) {
return this.isValidSource(cell);
},
/**
* Returns true if the given target cell is a valid target for source.
* This is a boolean implementation for not allowing connections between
* certain pairs of vertices and is called by {@link getEdgeValidationError}.
* This implementation returns true if {@link isValidSource} returns true for
* the source and {@link isValidTarget} returns true for the target.
*
* @param source {@link mxCell} that represents the source cell.
* @param target {@link mxCell} that represents the target cell.
*/
isValidConnection(source, target) {
return this.isValidSource(source) && this.isValidTarget(target);
},
/**
* Specifies if the graph should allow new connections. This implementation
* updates {@link ConnectionHandler.enabled} in {@link connectionHandler}.
*
* @param connectable Boolean indicating if new connections should be allowed.
*/
setConnectable(connectable) {
const connectionHandler = this.getPlugin('ConnectionHandler') as ConnectionHandler;
connectionHandler.setEnabled(connectable);
},
/**
* Returns true if the {@link connectionHandler} is enabled.
*/
isConnectable() {
const connectionHandler = this.getPlugin('ConnectionHandler') as ConnectionHandler;
return connectionHandler.isEnabled();
},
};
mixInto(Graph)(ConnectionsMixin); | the_stack |
import { BaseCommandName } from '../types/BaseCommandName';
import { Client } from '../client/Client';
import { Command } from '../command/Command';
import { GuildStorage } from '../storage/GuildStorage';
import { Message } from '../types/Message';
import { Time } from './Time';
/**
* Utility class containing handy static methods that can
* be used anywhere
* @module Util
*/
export class Util
{
/**
* Tangible representation of all base command names
* @static
* @name baseCommandNames
* @type {BaseCommandName[]}
*/
public static baseCommandNames: BaseCommandName[] = require('./static/baseCommandNames.json');
/**
* Return whether or not a command was called in the given
* message, the called command, the prefix used to call the
* command, and the name or alias of the command used to call it.
* >Returns everything it manages to determine up to the point of failure
* @static
* @method wasCommandCalled
* @param {Message} message Message to check
* @returns {Promise<Tuple<boolean, Command | null, string, string | null>>}
*/
public static async wasCommandCalled(message: Message): Promise<[boolean, Command | null, string, string | null]>
{
const client: Client = message.client as Client;
const dm: boolean = message.channel.type === 'dm';
const prefixes: string[] = [
`<@${client.user!.id}>`,
`<@!${client.user!.id}>`
];
const guildStorage: GuildStorage | undefined | null = !dm
? message.guild.storage || client.storage.guilds.get(message.guild.id)
: null;
if (!dm) prefixes.push(await guildStorage!.settings.get('prefix'));
else prefixes.push(await client.storage.get('defaultGuildSettings.prefix'));
let prefix: string | undefined = prefixes.find(a => message.content.trim().startsWith(a));
if (dm && typeof prefix === 'undefined') prefix = '';
if (!dm && typeof prefix === 'undefined') return [false, null, prefix!, null];
const commandName: string = message.content.trim().slice(prefix!.length)
.trim()
.split(' ')[0];
const command: Command | undefined = client.commands.resolve(commandName);
if (!command) return [false, null, prefix!, commandName];
if (command.disabled) return [false, command, prefix!, commandName];
return [true, command, prefix!, commandName];
}
/**
* Split args from the input by the given Command's argument separator
* @static
* @method parseArgs
* @param {string} input Input string to parse args from
* @param {Command} [command] Command object, used to determine the args separator.
* If none is given, `' '` will be used as the separator
* @returns {string[]}
*/
public static parseArgs(input: string, command?: Command): string[]
{
let delimiter: string | null = ' ';
let output: string[];
if (command && command.argOpts)
{
if (typeof command.argOpts.separator === 'undefined') delimiter = ' ';
else if (command.argOpts.separator === null) delimiter = null;
else delimiter = command.argOpts.separator;
}
if (delimiter === null) output = [input];
else if (delimiter === '') output = input.split(delimiter);
else output = input
.split(delimiter)
.map(a => a.trim())
.filter(a => a !== '');
return output!;
}
/**
* Pads the right side of a string with spaces to the given length
* @static
* @method padRight
* @param {string} text Text to pad
* @param {number} length Length to pad to
* @returns {string}
*/
public static padRight(text: string, length: number): string
{
const pad: number = Math.max(0, Math.min(length, length - text.length));
return `${text}${' '.repeat(pad)}`;
}
/**
* Returns the given string lowercased with any non
* alphanumeric chars removed
* @static
* @method normalize
* @param {string} text Text to normalize
* @returns {string}
*/
public static normalize(text: string): string
{
return text.toLowerCase().replace(/[^a-z0-9]+/g, '');
}
/**
* Returns the given string with special characters escaped
* @static
* @method escape
* @param {string} input String to escape
* @returns {string}
*/
public static escape(input: string): string
{
return input.replace(/[[\](){}|\\^$+\-*?.]/g, '\\$&');
}
/**
* Assigns the given value along the given nested path within
* the provided initial object
* @static
* @method assignNestedValue
* @param {any} obj Object to assign to
* @param {string[]} path Nested path to follow within the object
* @param {any} value Value to assign within the object
* @returns {void}
*/
public static assignNestedValue(obj: any, path: string[], value: any): void
{
if (typeof obj !== 'object' || obj instanceof Array)
throw new Error(`Initial input of type '${typeof obj}' is not valid for nested assignment`);
if (path.length === 0)
throw new Error('Missing nested assignment path');
const first: string = path.shift()!;
if (typeof obj[first] === 'undefined') obj[first] = {};
if (path.length > 1 && (typeof obj[first] !== 'object' || obj[first] instanceof Array))
throw new Error(`Target '${first}' is not valid for nested assignment.`);
if (path.length === 0) obj[first] = value;
else Util.assignNestedValue(obj[first], path, value);
}
/**
* Remove a value from within an object along a nested path
* @static
* @method removeNestedValue
* @param {any} obj Object to remove from
* @param {string[]} path Nested path to follow within the object
* @returns {void}
*/
public static removeNestedValue(obj: any, path: string[]): void
{
if (typeof obj !== 'object' || obj instanceof Array) return;
if (path.length === 0)
throw new Error('Missing nested assignment path');
const first: string = path.shift()!;
if (typeof obj[first] === 'undefined') return;
if (path.length > 1 && (typeof obj[first] !== 'object' || obj[first] instanceof Array))
return;
if (path.length === 0) delete obj[first];
else Util.removeNestedValue(obj[first], path);
}
/**
* Fetches a nested value from within an object via the
* provided path
* @static
* @method getNestedValue
* @param {any} obj Object to search
* @param {string[]} path Nested path to follow within the object
* @returns {any}
*/
public static getNestedValue(obj: any, path: string[]): any
{
if (typeof obj === 'undefined') return;
if (path.length === 0) return obj;
const first: string = path.shift()!;
if (typeof obj[first] === 'undefined') return;
if (path.length > 1 && (typeof obj[first] !== 'object' || obj[first] instanceof Array))
return;
return Util.getNestedValue(obj[first], path);
}
/**
* Converts a TypeScript-style argument list into a valid args data object
* for [resolve]{@link module:Middleware.resolve} and [expect]{@link module:Middleware.expect}.
* This can help if the object syntax for resolving/expecting Command
* arguments is too awkward or cluttered, or if a simpler syntax is
* overall preferred.
*
* Args marked with `?` (for example: `arg?: String`) are declared as
* optional and will be converted to `'[arg]': 'String'` at runtime.
* Normal args will convert to `'<arg>': 'String'`
*
* Example:
* ```
* `user: User, height: ['short', 'tall'], ...desc?: String`
* // becomes:
* { '<user>': 'User', '<height>': ['short', 'tall'], '[...desc]': 'String' }
* ```
* @static
* @method parseArgTypes
* @param {string} input Argument list string
* @returns {object}
*/
public static parseArgTypes(input: string): { [arg: string]: string | string[] }
{
const argStringRegex: RegExp = /(?:\.\.\.)?\w+\?? *: *(?:\[.*?\](?= *, *)|(?:\[.*?\] *$)|\w+)/g;
if (!argStringRegex.test(input))
throw new Error(`Input string is incorrectly formatted: ${input}`);
const output: { [arg: string]: string | string[] } = {};
const args: string[] = input.match(argStringRegex)!;
for (let arg of args)
{
const split: string[] = arg.split(':').map(a => a.trim());
let name: string = split.shift()!;
arg = split.join(':');
if (/(?:\.\.\.)?.+\?/.test(name)) name = `[${name.replace('?', '')}]`;
else name = `<${name}>`;
if (/\[ *(?:(?: *, *)?(['"])(\S+)\1)+ *\]|\[ *\]/.test(arg))
{
const data: string = arg.match(/\[(.*)\]/)![1];
if (!data) throw new Error('String literal array cannot be empty');
const values: string[] = data
.split(',')
.map(a => a.trim().slice(1, -1));
output[name] = values;
}
else output[name] = arg;
}
return output;
}
/**
* Parse a ratelimit Tuple from the given shorthand string
* @param {string} limitString Ratelimit string matching the regex `\d+\/\d+[s|m|h|d]`<br>
* **Example:** `1/10m` to limit a command to one use per 10 minutes
*/
public static parseRateLimit(limitString: string): [number, number]
{
const limitRegex: RegExp = /^(\d+)\/(\d+)(s|m|h|d)?$/;
if (!limitRegex.test(limitString))
throw new Error(`Failed to parse a ratelimit from '${limitString}'`);
const parsedLimit: RegExpExecArray = limitRegex.exec(limitString)!;
let [limit, duration]: [string | number, string | number] = parsedLimit.slice(1, 3) as [string, string];
const [post]: [string] = parsedLimit.slice(3, 4) as [string];
if (post) duration = Time.parseShorthand(duration + post)!;
else duration = parseInt(duration);
limit = parseInt(limit);
return [limit, duration];
}
/**
* Implementation of `performance-now`
* @static
* @method now
* @returns {number}
*/
public static now(): number
{
type NSFunction = (hr?: [number, number]) => number;
const ns: NSFunction = (hr = process.hrtime()) => hr[0] * 1e9 + hr[1];
return (ns() - (ns() - process.uptime() * 1e9)) / 1e6;
}
/**
* Flatten an array that may contain nested arrays
* @static
* @method flattenArray
* @param {any[]} array
* @returns {any[]}
*/
public static flattenArray<T>(array: (T | T[])[]): T[]
{
const result: T[] = [];
for (const item of array)
item instanceof Array
? result.push(...Util.flattenArray(item))
: result.push(item);
return result;
}
/**
* Emit a deprecation warning message for the given target
* @static
* @method emitDeprecationWarning
* @param {any} target Deprecation target
* @param {string} message Deprecation message
* @returns {void}
*/
public static emitDeprecationWarning(target: any, message: string): void
{
if (typeof target._warnCache === 'undefined')
Object.defineProperty(target, '_warnCache', { value: {} });
const warnCache: { [key: string]: boolean } = target._warnCache;
if (warnCache[message]) return;
warnCache[message] = true;
process.emitWarning(message, 'DeprecationWarning');
}
/**
* Attempts to lazy-load any of the given packages in order,
* returning the entire namespace of the first package to be
* loaded. Errors if no given package was found
* @returns {any} The first package namespace to be found
*/
public static lazyLoad<T>(...packages: string[]): T
{
let pkg!: T;
for (const p of packages)
{
try { pkg = require(p); }
catch {}
if (pkg) break;
}
if (!pkg) throw new Error(`Failed to lazy-load any of these packages: ${packages.join(', ')}`);
return pkg;
}
} | the_stack |
import { AbilitableManageProxyAbilities, NFTokenSafeTransferProxyAbilities, TokenTransferProxyAbilities,
XcertCreateProxyAbilities, XcertUpdateProxyAbilities } from '@0xcert/ethereum-proxy-contracts/src/core/types';
import { XcertAbilities } from '@0xcert/ethereum-xcert-contracts/src/core/types';
import { Spec } from '@specron/spec';
import { ActionsGatewayAbilities } from '../../../core/types';
import * as common from '../../helpers/common';
import { getSignature } from '../../helpers/signature';
/**
* Test definition.
* ERC20: ZXC, BNB, OMG, BAT, GNT
* ERC-721: Cat, Dog, Fox, Bee, Ant, Ape, Pig
*/
interface Data {
actionsGateway?: any;
tokenProxy?: any;
nftSafeProxy?: any;
updateProxy?: any;
createProxy?: any;
abilitableManageProxy?: any;
cat?: any;
dog?: any;
fox?: any;
owner?: string;
bob?: string;
jane?: string;
sara?: string;
ben?: string;
zeroAddress?: string;
zxc?: any;
gnt?: any;
bnb?: any;
id1?: string;
id2?: string;
id3?: string;
id4?: string;
digest1?: string;
digest2?: string;
digest3?: string;
}
const spec = new Spec<Data>();
spec.beforeEach(async (ctx) => {
const accounts = await ctx.web3.eth.getAccounts();
ctx.set('owner', accounts[0]);
ctx.set('bob', accounts[1]);
ctx.set('jane', accounts[2]);
ctx.set('sara', accounts[3]);
ctx.set('ben', accounts[4]);
ctx.set('zeroAddress', '0x0000000000000000000000000000000000000000');
});
spec.beforeEach(async (ctx) => {
ctx.set('id1', '0x0000000000000000000000000000000000000000000000000000000000000001');
ctx.set('id2', '0x0000000000000000000000000000000000000000000000000000000000000002');
ctx.set('id3', '0x0000000000000000000000000000000000000000000000000000000000000003');
ctx.set('id4', '0x0000000000000000000000000000000000000000000000000000000000000004');
ctx.set('digest1', '0x1e205550c221490347e5e2393a02e94d284bbe9903f023ba098355b8d75974c8');
ctx.set('digest2', '0x5e20552dc271490347e5e2391b02e94d684bbe9903f023fa098355bed7597434');
ctx.set('digest3', '0x53f0df2dc671410347e5eef91b02344d687bbe9903f456fa0983eebed7517521');
});
/**
* Cat
* Jane owns: #1, #4
* Bob owns: #2, #3
*/
spec.beforeEach(async (ctx) => {
const cat = await ctx.deploy({
src: '@0xcert/ethereum-erc721-contracts/build/nf-token-metadata-enumerable-mock.json',
contract: 'NFTokenMetadataEnumerableMock',
args: ['cat', 'CAT', 'https://0xcert.org/', '.json'],
});
await cat.instance.methods
.create(ctx.get('jane'), 1)
.send({
from: ctx.get('owner'),
gas: 4000000,
});
await cat.instance.methods
.create(ctx.get('jane'), 4)
.send({
from: ctx.get('owner'),
gas: 4000000,
});
await cat.instance.methods
.create(ctx.get('bob'), 2)
.send({
from: ctx.get('owner'),
gas: 4000000,
});
await cat.instance.methods
.create(ctx.get('bob'), 3)
.send({
from: ctx.get('owner'),
gas: 4000000,
});
ctx.set('cat', cat);
});
/**
* Dog
* Jane owns: #1, #2, #3
*/
spec.beforeEach(async (ctx) => {
const jane = ctx.get('jane');
const owner = ctx.get('owner');
const digest1 = ctx.get('digest1');
const digest2 = ctx.get('digest2');
const digest3 = ctx.get('digest3');
const dog = await ctx.deploy({
src: '@0xcert/ethereum-xcert-contracts/build/xcert-mock.json',
contract: 'XcertMock',
args: ['dog', 'DOG', 'https://0xcert.org/', '.json', '0xa65de9e6', ['0x0d04c3b8']],
});
await dog.instance.methods
.create(jane, 1, digest1)
.send({
from: owner,
});
await dog.instance.methods
.create(jane, 2, digest2)
.send({
from: owner,
});
await dog.instance.methods
.create(jane, 3, digest3)
.send({
from: owner,
});
ctx.set('dog', dog);
});
/**
* Fox
* Jane owns: #1
*/
spec.beforeEach(async (ctx) => {
const jane = ctx.get('jane');
const owner = ctx.get('owner');
const fox = await ctx.deploy({
src: '@0xcert/ethereum-xcert-contracts/build/xcert-mock.json',
contract: 'XcertMock',
args: ['fox', 'FOX', 'https://0xcert.org/', '.json', '0xa65de9e6', ['0x0d04c3b8']],
});
await fox.instance.methods
.create(jane, 1, '0x0')
.send({
from: owner,
});
ctx.set('fox', fox);
});
/**
* ZXC
* Jane owns: all
*/
spec.beforeEach(async (ctx) => {
const jane = ctx.get('jane');
const zxc = await ctx.deploy({
src: '@0xcert/ethereum-erc20-contracts/build/token-mock.json',
contract: 'TokenMock',
args: ['ERC20', 'ERC', 18, '300000000000000000000000000'],
from: jane,
});
ctx.set('zxc', zxc);
});
/**
* BNB
* Jane owns: all
*/
spec.beforeEach(async (ctx) => {
const jane = ctx.get('jane');
const bnb = await ctx.deploy({
src: '@0xcert/ethereum-erc20-contracts/build/token-mock.json',
contract: 'TokenMock',
args: ['ERC20', 'ERC', 18, '300000000000000000000000000'],
from: jane,
});
ctx.set('bnb', bnb);
});
/**
* GNT
* Bob owns: all
*/
spec.beforeEach(async (ctx) => {
const bob = ctx.get('bob');
const gnt = await ctx.deploy({
src: '@0xcert/ethereum-erc20-contracts/build/token-mock.json',
contract: 'TokenMock',
args: ['ERC20', 'ERC', 18, '300000000000000000000000000'],
from: bob,
});
ctx.set('gnt', gnt);
});
spec.beforeEach(async (ctx) => {
const tokenProxy = await ctx.deploy({
src: '@0xcert/ethereum-proxy-contracts/build/token-transfer-proxy.json',
contract: 'TokenTransferProxy',
});
ctx.set('tokenProxy', tokenProxy);
});
spec.beforeEach(async (ctx) => {
const nftSafeProxy = await ctx.deploy({
src: '@0xcert/ethereum-proxy-contracts/build/nftoken-safe-transfer-proxy.json',
contract: 'NFTokenSafeTransferProxy',
});
ctx.set('nftSafeProxy', nftSafeProxy);
});
spec.beforeEach(async (ctx) => {
const updateProxy = await ctx.deploy({
src: '@0xcert/ethereum-proxy-contracts/build/xcert-update-proxy.json',
contract: 'XcertUpdateProxy',
});
ctx.set('updateProxy', updateProxy);
});
spec.beforeEach(async (ctx) => {
const createProxy = await ctx.deploy({
src: '@0xcert/ethereum-proxy-contracts/build/xcert-create-proxy.json',
contract: 'XcertCreateProxy',
});
ctx.set('createProxy', createProxy);
});
spec.beforeEach(async (ctx) => {
const abilitableManageProxy = await ctx.deploy({
src: '@0xcert/ethereum-proxy-contracts/build/abilitable-manage-proxy.json',
contract: 'AbilitableManageProxy',
});
ctx.set('abilitableManageProxy', abilitableManageProxy);
});
spec.beforeEach(async (ctx) => {
const tokenProxy = ctx.get('tokenProxy');
const nftSafeProxy = ctx.get('nftSafeProxy');
const updateProxy = ctx.get('updateProxy');
const createProxy = ctx.get('createProxy');
const abilitableManageProxy = ctx.get('abilitableManageProxy');
const owner = ctx.get('owner');
const actionsGateway = await ctx.deploy({
src: './build/actions-gateway.json',
contract: 'ActionsGateway',
});
await actionsGateway.instance.methods.grantAbilities(owner, ActionsGatewayAbilities.SET_PROXIES).send();
await actionsGateway.instance.methods.addProxy(createProxy.receipt._address, 0).send({ from: owner });
await actionsGateway.instance.methods.addProxy(tokenProxy.receipt._address, 1).send({ from: owner });
await actionsGateway.instance.methods.addProxy(nftSafeProxy.receipt._address, 1).send({ from: owner });
await actionsGateway.instance.methods.addProxy(updateProxy.receipt._address, 2).send({ from: owner });
await actionsGateway.instance.methods.addProxy(abilitableManageProxy.receipt._address, 3).send({ from: owner });
ctx.set('actionsGateway', actionsGateway);
});
spec.beforeEach(async (ctx) => {
const tokenProxy = ctx.get('tokenProxy');
const nftSafeProxy = ctx.get('nftSafeProxy');
const updateProxy = ctx.get('updateProxy');
const createProxy = ctx.get('createProxy');
const abilitableManageProxy = ctx.get('abilitableManageProxy');
const actionsGateway = ctx.get('actionsGateway');
const owner = ctx.get('owner');
await tokenProxy.instance.methods.grantAbilities(actionsGateway.receipt._address, TokenTransferProxyAbilities.EXECUTE).send({ from: owner });
await nftSafeProxy.instance.methods.grantAbilities(actionsGateway.receipt._address, NFTokenSafeTransferProxyAbilities.EXECUTE).send({ from: owner });
await updateProxy.instance.methods.grantAbilities(actionsGateway.receipt._address, XcertUpdateProxyAbilities.EXECUTE).send({ from: owner });
await createProxy.instance.methods.grantAbilities(actionsGateway.receipt._address, XcertCreateProxyAbilities.EXECUTE).send({ from: owner });
await abilitableManageProxy.instance.methods.grantAbilities(actionsGateway.receipt._address, AbilitableManageProxyAbilities.EXECUTE).send({ from: owner });
});
spec.test('sucesfully executes multiple actions scenario #1', async (ctx) => {
// This test expects 3 signers (Owner, Jane, Bob) and signatures from all 3. Sara is the executor of the order.
// Actions defined in this test are as follows:
// - Owner creates dog #4 with Jane as receiver
// - Bob sends 3000 GNT to owner
// - Jane sends dog #1 to Bob
// - Jane sends dog #2 to Bob
// - Jane sends 1000 ZXC to Bob
// - Owner updates digest of dog #1
// - Owner grants create ability for dog to Bob
// - Jane sends fox #1 to Owner
const actionsGateway = ctx.get('actionsGateway');
const updateProxy = ctx.get('updateProxy');
const createProxy = ctx.get('createProxy');
const tokenProxy = ctx.get('tokenProxy');
const nftSafeProxy = ctx.get('nftSafeProxy');
const abilitableManageProxy = ctx.get('abilitableManageProxy');
const jane = ctx.get('jane');
const owner = ctx.get('owner');
const bob = ctx.get('bob');
const sara = ctx.get('sara');
const dog = ctx.get('dog');
const fox = ctx.get('fox');
const id = ctx.get('id1');
const id2 = ctx.get('id2');
const id4 = ctx.get('id4');
const digest1 = ctx.get('digest1');
const digest2 = ctx.get('digest2');
const zxc = ctx.get('zxc');
const gnt = ctx.get('gnt');
const gntAmountDec = 3000;
const gntAmountHex = '0x0000000000000000000000000000000000000000000000000000000000000BB8';
const zxcAmountDec = 1000;
const zxcAmountHex = '0x00000000000000000000000000000000000000000000000000000000000003E8';
const createAbility = '0x0000000000000000000000000000000000000000000000000000000000000010'; // create asset in hex uint256
const actions = [
{
proxyId: 0,
contractAddress: dog.receipt._address,
params: `${digest1}${id4.substring(2)}${jane.substring(2)}00`,
},
{
proxyId: 1,
contractAddress: gnt.receipt._address,
params: `${gntAmountHex}${owner.substring(2)}02`,
},
{
proxyId: 2,
contractAddress: dog.receipt._address,
params: `${id}${bob.substring(2)}01`,
},
{
proxyId: 2,
contractAddress: dog.receipt._address,
params: `${id2}${bob.substring(2)}01`,
},
{
proxyId: 1,
contractAddress: zxc.receipt._address,
params: `${zxcAmountHex}${bob.substring(2)}01`,
},
{
proxyId: 3,
contractAddress: dog.receipt._address,
params: `${digest2}${id.substring(2)}00`,
},
{
proxyId: 4,
contractAddress: dog.receipt._address,
params: `${createAbility}${bob.substring(2)}00`,
},
{
proxyId: 2,
contractAddress: fox.receipt._address,
params: `${id}${owner.substring(2)}01`,
},
];
const orderData = {
signers: [owner, jane, bob],
actions,
seed: common.getCurrentTime(),
expirationTimestamp: common.getCurrentTime() + 3600,
};
const createTuple = ctx.tuple(orderData);
const claim = await actionsGateway.instance.methods.getOrderDataClaim(createTuple).call();
const signature = await getSignature(ctx.web3, claim, owner);
const signature2 = await getSignature(ctx.web3, claim, jane);
const signature3 = await getSignature(ctx.web3, claim, bob);
const signatureDataTuple = ctx.tuple([signature, signature2, signature3]);
await dog.instance.methods.grantAbilities(createProxy.receipt._address, XcertAbilities.CREATE_ASSET).send({ from: owner });
await gnt.instance.methods.approve(tokenProxy.receipt._address, gntAmountDec).send({ from: bob });
await zxc.instance.methods.approve(tokenProxy.receipt._address, zxcAmountDec).send({ from: jane });
await dog.instance.methods.setApprovalForAll(nftSafeProxy.receipt._address, true).send({ from: jane });
await dog.instance.methods.grantAbilities(updateProxy.receipt._address, XcertAbilities.UPDATE_ASSET_IMPRINT).send({ from: owner });
await dog.instance.methods.grantAbilities(abilitableManageProxy.receipt._address, XcertAbilities.MANAGE_ABILITIES).send({ from: owner });
await fox.instance.methods.setApprovalForAll(nftSafeProxy.receipt._address, true).send({ from: jane });
const logs = await actionsGateway.instance.methods.perform(createTuple, signatureDataTuple).send({ from: sara });
ctx.not(logs.events.Perform, undefined);
const dog4Owner = await dog.instance.methods.ownerOf(id4).call();
ctx.is(dog4Owner, jane);
const ownerGntBalance = await gnt.instance.methods.balanceOf(owner).call();
ctx.is(ownerGntBalance, gntAmountDec.toString());
const dog1Owner = await dog.instance.methods.ownerOf(id).call();
ctx.is(dog1Owner, bob);
const dog2Owner = await dog.instance.methods.ownerOf(id2).call();
ctx.is(dog2Owner, bob);
const bobZxcBalance = await zxc.instance.methods.balanceOf(bob).call();
ctx.is(bobZxcBalance, zxcAmountDec.toString());
const dog1Digest = await dog.instance.methods.tokenURIIntegrity(id).call();
ctx.is(dog1Digest.digest, digest2);
const bobCreateDog = await dog.instance.methods.isAble(bob, XcertAbilities.CREATE_ASSET).call();
ctx.true(bobCreateDog);
const fox1Owner = await fox.instance.methods.ownerOf(id).call();
ctx.is(fox1Owner, owner);
});
spec.test('sucesfully executes multiple actions scenario #2', async (ctx) => {
// This test expects 3 signers (Owner, Jane, Bob) and signatures from all 3. Ben is the executor of the order.
// Actions defined in this test are as follows:
// - Owner creates fox #2 with Bob as receiver
// - Owner creates fox #3 with Jane as receiver
// - Owner creates fox #4 with Sara as receiver
// - Bob sends 3000 GNT to Sara
// - Jane sends 3000 ZXC to Sara
const actionsGateway = ctx.get('actionsGateway');
const createProxy = ctx.get('createProxy');
const tokenProxy = ctx.get('tokenProxy');
const jane = ctx.get('jane');
const owner = ctx.get('owner');
const bob = ctx.get('bob');
const sara = ctx.get('sara');
const ben = ctx.get('ben');
const fox = ctx.get('fox');
const id2 = ctx.get('id2');
const id3 = ctx.get('id3');
const id4 = ctx.get('id4');
const digest1 = ctx.get('digest1');
const digest2 = ctx.get('digest2');
const digest3 = ctx.get('digest3');
const zxc = ctx.get('zxc');
const gnt = ctx.get('gnt');
const gntAmountDec = 3000;
const gntAmountHex = '0x0000000000000000000000000000000000000000000000000000000000000BB8';
const zxcAmountDec = 3000;
const zxcAmountHex = '0x0000000000000000000000000000000000000000000000000000000000000BB8';
const actions = [
{
proxyId: 0,
contractAddress: fox.receipt._address,
params: `${digest2}${id2.substring(2)}${bob.substring(2)}00`,
},
{
proxyId: 0,
contractAddress: fox.receipt._address,
params: `${digest3}${id3.substring(2)}${jane.substring(2)}00`,
},
{
proxyId: 0,
contractAddress: fox.receipt._address,
params: `${digest1}${id4.substring(2)}${sara.substring(2)}00`,
},
{
proxyId: 1,
contractAddress: gnt.receipt._address,
params: `${gntAmountHex}${sara.substring(2)}02`,
},
{
proxyId: 1,
contractAddress: zxc.receipt._address,
params: `${zxcAmountHex}${sara.substring(2)}01`,
},
];
const orderData = {
signers: [owner, jane, bob],
actions,
seed: common.getCurrentTime(),
expirationTimestamp: common.getCurrentTime() + 3600,
};
const createTuple = ctx.tuple(orderData);
const claim = await actionsGateway.instance.methods.getOrderDataClaim(createTuple).call();
const signature = await getSignature(ctx.web3, claim, owner);
const signature2 = await getSignature(ctx.web3, claim, jane);
const signature3 = await getSignature(ctx.web3, claim, bob);
const signatureDataTuple = ctx.tuple([signature, signature2, signature3]);
await fox.instance.methods.grantAbilities(createProxy.receipt._address, XcertAbilities.CREATE_ASSET).send({ from: owner });
await gnt.instance.methods.approve(tokenProxy.receipt._address, gntAmountDec).send({ from: bob });
await zxc.instance.methods.approve(tokenProxy.receipt._address, zxcAmountDec).send({ from: jane });
const logs = await actionsGateway.instance.methods.perform(createTuple, signatureDataTuple).send({ from: ben });
ctx.not(logs.events.Perform, undefined);
const saraGntBalance = await gnt.instance.methods.balanceOf(sara).call();
ctx.is(saraGntBalance, gntAmountDec.toString());
const saraZxcBalance = await zxc.instance.methods.balanceOf(sara).call();
ctx.is(saraZxcBalance, zxcAmountDec.toString());
const fox2Owner = await fox.instance.methods.ownerOf(id2).call();
ctx.is(fox2Owner, bob);
const fox3Owner = await fox.instance.methods.ownerOf(id3).call();
ctx.is(fox3Owner, jane);
const fox4Owner = await fox.instance.methods.ownerOf(id4).call();
ctx.is(fox4Owner, sara);
});
/**
* owner, ben, bob, sara -> sara executes
* owner gives ben sign manage ability
* ben gives bob allow create ability
* ben gives sara allow create and allow update abilities
* bob creates fox 2 to himself
* sara creates fox 3 to bob
* sara updates fox 3
*/
spec.test('sucesfully executes multiple actions scenario #3', async (ctx) => {
// This test expects 4 signers (Owner, Ben, Bob, Sara) and signatures from first 3.
// Sara executes as the last signer which is why she does not need to sign.
// Actions defined in this test are as follows:
// - Owner grants allow manage ability to Ben
// - Ben grants allow create ability to Bob
// - Ben grants allow create and allow updates abilities to Sara
// - Bob creates fox #2 with himself as receiver
// - Sara creates fox #3 with Bob as receiver
// - Sara updates fox #3 digest
const actionsGateway = ctx.get('actionsGateway');
const updateProxy = ctx.get('updateProxy');
const createProxy = ctx.get('createProxy');
const abilitableManageProxy = ctx.get('abilitableManageProxy');
const owner = ctx.get('owner');
const bob = ctx.get('bob');
const sara = ctx.get('sara');
const ben = ctx.get('ben');
const fox = ctx.get('fox');
const id2 = ctx.get('id2');
const id3 = ctx.get('id3');
const digest1 = ctx.get('digest1');
const digest2 = ctx.get('digest2');
const digest3 = ctx.get('digest3');
const allowManageAbility = '0x0000000000000000000000000000000000000000000000000000000000000002'; // allow manage ability in hex uint256
const allowCreateAbility = '0x0000000000000000000000000000000000000000000000000000000000000200'; // allow create ability in hex uint256
const allowCreateAndAllowUpdateAbilities = '0x0000000000000000000000000000000000000000000000000000000000000600'; // allow create ability and allow update ability in hex uint256
const actions = [
{
proxyId: 4,
contractAddress: fox.receipt._address,
params: `${allowManageAbility}${ben.substring(2)}00`,
},
{
proxyId: 4,
contractAddress: fox.receipt._address,
params: `${allowCreateAbility}${bob.substring(2)}01`,
},
{
proxyId: 4,
contractAddress: fox.receipt._address,
params: `${allowCreateAndAllowUpdateAbilities}${sara.substring(2)}01`,
},
{
proxyId: 0,
contractAddress: fox.receipt._address,
params: `${digest2}${id2.substring(2)}${bob.substring(2)}02`,
},
{
proxyId: 0,
contractAddress: fox.receipt._address,
params: `${digest3}${id3.substring(2)}${bob.substring(2)}03`,
},
{
proxyId: 3,
contractAddress: fox.receipt._address,
params: `${digest1}${id3.substring(2)}03`,
},
];
const orderData = {
signers: [owner, ben, bob, sara],
actions,
seed: common.getCurrentTime(),
expirationTimestamp: common.getCurrentTime() + 3600,
};
const createTuple = ctx.tuple(orderData);
const claim = await actionsGateway.instance.methods.getOrderDataClaim(createTuple).call();
const signature = await getSignature(ctx.web3, claim, owner);
const signature2 = await getSignature(ctx.web3, claim, ben);
const signature3 = await getSignature(ctx.web3, claim, bob);
const signatureDataTuple = ctx.tuple([signature, signature2, signature3]);
await fox.instance.methods.grantAbilities(createProxy.receipt._address, XcertAbilities.CREATE_ASSET).send({ from: owner });
await fox.instance.methods.grantAbilities(abilitableManageProxy.receipt._address, XcertAbilities.MANAGE_ABILITIES).send({ from: owner });
await fox.instance.methods.grantAbilities(updateProxy.receipt._address, XcertAbilities.UPDATE_ASSET_IMPRINT).send({ from: owner });
const logs = await actionsGateway.instance.methods.perform(createTuple, signatureDataTuple).send({ from: sara });
ctx.not(logs.events.Perform, undefined);
const benAllowManageAbility = await fox.instance.methods.isAble(ben, XcertAbilities.ALLOW_MANAGE_ABILITIES).call();
ctx.true(benAllowManageAbility);
const bobAllowCreateAbility = await fox.instance.methods.isAble(bob, XcertAbilities.ALLOW_CREATE_ASSET).call();
ctx.true(bobAllowCreateAbility);
const saraAllowCreateAbility = await fox.instance.methods.isAble(sara, XcertAbilities.ALLOW_CREATE_ASSET).call();
ctx.true(saraAllowCreateAbility);
const saraAllowUpdateAbility = await fox.instance.methods.isAble(sara, XcertAbilities.ALLOW_UPDATE_ASSET_IMPRINT).call();
ctx.true(saraAllowUpdateAbility);
const fox2Owner = await fox.instance.methods.ownerOf(id2).call();
ctx.is(fox2Owner, bob);
const fox3Owner = await fox.instance.methods.ownerOf(id3).call();
ctx.is(fox3Owner, bob);
const fox3Digest = await fox.instance.methods.tokenURIIntegrity(id3).call();
ctx.is(fox3Digest.digest, digest1);
});
spec.test('sucesfully executes multiple actions scenario #4', async (ctx) => {
// This test expects 3 signers (Owner, Bob and unknown address represented as zero address) and signatures from all 3.
// Sara executes the order, unknown signer is automatically replaced with the address provided by the 3rd signature.
// Jane will be the 3rd "unknown" signer.
// Actions defined in this test are as follows:
// - Owner create fox #2 with unkown receiver.
// - Owner create fox #3 with unkown receiver.
// - Bob send 3000 GNT to unknown receiver
// - Owner grants revoke ability for fox to unkown receiver.
// - Unknown receiver sends 10000 ZXC to Sara.
const actionsGateway = ctx.get('actionsGateway');
const createProxy = ctx.get('createProxy');
const tokenProxy = ctx.get('tokenProxy');
const abilitableManageProxy = ctx.get('abilitableManageProxy');
const jane = ctx.get('jane');
const owner = ctx.get('owner');
const bob = ctx.get('bob');
const sara = ctx.get('sara');
const zeroAddress = ctx.get('zeroAddress');
const fox = ctx.get('fox');
const id2 = ctx.get('id2');
const id3 = ctx.get('id3');
const digest2 = ctx.get('digest2');
const digest3 = ctx.get('digest3');
const zxc = ctx.get('zxc');
const gnt = ctx.get('gnt');
const gntAmountDec = 3000;
const gntAmountHex = '0x0000000000000000000000000000000000000000000000000000000000000BB8';
const zxcAmountDec = 10000;
const zxcAmountHex = '0x0000000000000000000000000000000000000000000000000000000000002710';
const revokeAbility = '0x0000000000000000000000000000000000000000000000000000000000000020'; // create asset in hex uint256
const actions = [
{
proxyId: 0,
contractAddress: fox.receipt._address,
params: `${digest2}${id2.substring(2)}${zeroAddress.substring(2)}00`,
},
{
proxyId: 0,
contractAddress: fox.receipt._address,
params: `${digest3}${id3.substring(2)}${zeroAddress.substring(2)}00`,
},
{
proxyId: 1,
contractAddress: gnt.receipt._address,
params: `${gntAmountHex}${zeroAddress.substring(2)}01`,
},
{
proxyId: 4,
contractAddress: fox.receipt._address,
params: `${revokeAbility}${zeroAddress.substring(2)}00`,
},
{
proxyId: 1,
contractAddress: zxc.receipt._address,
params: `${zxcAmountHex}${sara.substring(2)}02`,
},
];
const orderData = {
signers: [owner, bob, zeroAddress],
actions,
seed: common.getCurrentTime(),
expirationTimestamp: common.getCurrentTime() + 3600,
};
const createTuple = ctx.tuple(orderData);
const claim = await actionsGateway.instance.methods.getOrderDataClaim(createTuple).call();
const signature = await getSignature(ctx.web3, claim, owner);
const signature2 = await getSignature(ctx.web3, claim, bob);
const signature3 = await getSignature(ctx.web3, claim, jane);
const signatureDataTuple = ctx.tuple([signature, signature2, signature3]);
await fox.instance.methods.grantAbilities(createProxy.receipt._address, XcertAbilities.CREATE_ASSET).send({ from: owner });
await gnt.instance.methods.approve(tokenProxy.receipt._address, gntAmountDec).send({ from: bob });
await zxc.instance.methods.approve(tokenProxy.receipt._address, zxcAmountDec).send({ from: jane });
await fox.instance.methods.grantAbilities(abilitableManageProxy.receipt._address, XcertAbilities.MANAGE_ABILITIES).send({ from: owner });
const logs = await actionsGateway.instance.methods.perform(createTuple, signatureDataTuple).send({ from: sara });
ctx.not(logs.events.Perform, undefined);
const fox2Owner = await fox.instance.methods.ownerOf(id2).call();
ctx.is(fox2Owner, jane);
const fox3Owner = await fox.instance.methods.ownerOf(id3).call();
ctx.is(fox3Owner, jane);
const janeGntBalance = await gnt.instance.methods.balanceOf(jane).call();
ctx.is(janeGntBalance, gntAmountDec.toString());
const janeRevokeAbility = await fox.instance.methods.isAble(jane, XcertAbilities.REVOKE_ASSET).call();
ctx.true(janeRevokeAbility);
const saraZxcBalance = await zxc.instance.methods.balanceOf(sara).call();
ctx.is(saraZxcBalance, zxcAmountDec.toString());
});
export default spec; | the_stack |
// merged imports from all files
import * as ts from 'typescript';
import * as monaco from '@fluentui/monaco-editor';
import CancellationToken = monaco.CancellationToken;
import IDisposable = monaco.IDisposable;
import IEvent = monaco.IEvent;
import IWorkerContext = monaco.worker.IWorkerContext;
import Position = monaco.Position;
import Range = monaco.Range;
import Thenable = monaco.Thenable;
import Uri = monaco.Uri;
// convenience re-export
export type EmitOutput = ts.EmitOutput;
// languageFeatures.d.ts
export declare function flattenDiagnosticMessageText(diag: string | ts.DiagnosticMessageChain | undefined, newLine: string, indent?: number): string;
export declare abstract class Adapter {
protected _worker: (first: Uri, ...more: Uri[]) => Promise<TypeScriptWorker>;
constructor(_worker: (first: Uri, ...more: Uri[]) => Promise<TypeScriptWorker>);
protected _textSpanToRange(model: monaco.editor.ITextModel, span: ts.TextSpan): monaco.IRange;
}
export declare class DiagnosticsAdapter extends Adapter {
private _defaults;
private _selector;
private _disposables;
private _listener;
constructor(_defaults: LanguageServiceDefaultsImpl, _selector: string, worker: (first: Uri, ...more: Uri[]) => Promise<TypeScriptWorker>);
dispose(): void;
private _doValidate;
private _convertDiagnostics;
private _convertRelatedInformation;
private _tsDiagnosticCategoryToMarkerSeverity;
}
export declare class SuggestAdapter extends Adapter implements monaco.languages.CompletionItemProvider {
get triggerCharacters(): string[];
provideCompletionItems(model: monaco.editor.ITextModel, position: Position, _context: monaco.languages.CompletionContext, token: CancellationToken): Promise<monaco.languages.CompletionList | undefined>;
resolveCompletionItem(model: monaco.editor.ITextModel, _position: Position, item: monaco.languages.CompletionItem, token: CancellationToken): Promise<monaco.languages.CompletionItem>;
private static convertKind;
}
export declare class SignatureHelpAdapter extends Adapter implements monaco.languages.SignatureHelpProvider {
signatureHelpTriggerCharacters: string[];
provideSignatureHelp(model: monaco.editor.ITextModel, position: Position, token: CancellationToken): Promise<monaco.languages.SignatureHelpResult | undefined>;
}
export declare class QuickInfoAdapter extends Adapter implements monaco.languages.HoverProvider {
provideHover(model: monaco.editor.ITextModel, position: Position, token: CancellationToken): Promise<monaco.languages.Hover | undefined>;
}
export declare class OccurrencesAdapter extends Adapter implements monaco.languages.DocumentHighlightProvider {
provideDocumentHighlights(model: monaco.editor.ITextModel, position: Position, token: CancellationToken): Promise<monaco.languages.DocumentHighlight[] | undefined>;
}
export declare class DefinitionAdapter extends Adapter {
provideDefinition(model: monaco.editor.ITextModel, position: Position, token: CancellationToken): Promise<monaco.languages.Definition | undefined>;
}
export declare class ReferenceAdapter extends Adapter implements monaco.languages.ReferenceProvider {
provideReferences(model: monaco.editor.ITextModel, position: Position, context: monaco.languages.ReferenceContext, token: CancellationToken): Promise<monaco.languages.Location[] | undefined>;
}
export declare class OutlineAdapter extends Adapter implements monaco.languages.DocumentSymbolProvider {
provideDocumentSymbols(model: monaco.editor.ITextModel, token: CancellationToken): Promise<monaco.languages.DocumentSymbol[] | undefined>;
}
export declare class Kind {
static unknown: string;
static keyword: string;
static script: string;
static module: string;
static class: string;
static interface: string;
static type: string;
static enum: string;
static variable: string;
static localVariable: string;
static function: string;
static localFunction: string;
static memberFunction: string;
static memberGetAccessor: string;
static memberSetAccessor: string;
static memberVariable: string;
static constructorImplementation: string;
static callSignature: string;
static indexSignature: string;
static constructSignature: string;
static parameter: string;
static typeParameter: string;
static primitiveType: string;
static label: string;
static alias: string;
static const: string;
static let: string;
static warning: string;
}
export declare abstract class FormatHelper extends Adapter {
protected static _convertOptions(options: monaco.languages.FormattingOptions): ts.FormatCodeOptions;
protected _convertTextChanges(model: monaco.editor.ITextModel, change: ts.TextChange): monaco.languages.TextEdit;
}
export declare class FormatAdapter extends FormatHelper implements monaco.languages.DocumentRangeFormattingEditProvider {
provideDocumentRangeFormattingEdits(model: monaco.editor.ITextModel, range: Range, options: monaco.languages.FormattingOptions, token: CancellationToken): Promise<monaco.languages.TextEdit[] | undefined>;
}
export declare class FormatOnTypeAdapter extends FormatHelper implements monaco.languages.OnTypeFormattingEditProvider {
get autoFormatTriggerCharacters(): string[];
provideOnTypeFormattingEdits(model: monaco.editor.ITextModel, position: Position, ch: string, options: monaco.languages.FormattingOptions, token: CancellationToken): Promise<monaco.languages.TextEdit[] | undefined>;
}
export declare class CodeActionAdaptor extends FormatHelper implements monaco.languages.CodeActionProvider {
provideCodeActions(model: monaco.editor.ITextModel, range: Range, context: monaco.languages.CodeActionContext, token: CancellationToken): Promise<monaco.languages.CodeActionList | undefined>;
private _tsCodeFixActionToMonacoCodeAction;
}
export declare class RenameAdapter extends Adapter implements monaco.languages.RenameProvider {
provideRenameEdits(model: monaco.editor.ITextModel, position: Position, newName: string, token: CancellationToken): Promise<monaco.languages.WorkspaceEdit & monaco.languages.Rejection | undefined>;
}
// monaco.contribution.d.ts
export interface IExtraLib {
content: string;
version: number;
}
export interface IExtraLibs {
[path: string]: IExtraLib;
}
export declare class LanguageServiceDefaultsImpl implements monaco.languages.typescript.LanguageServiceDefaults {
private _onDidChange;
private _onDidExtraLibsChange;
private _extraLibs;
private _eagerModelSync;
private _compilerOptions;
private _diagnosticsOptions;
private _onDidExtraLibsChangeTimeout;
constructor(compilerOptions: monaco.languages.typescript.CompilerOptions, diagnosticsOptions: monaco.languages.typescript.DiagnosticsOptions);
get onDidChange(): IEvent<void>;
get onDidExtraLibsChange(): IEvent<void>;
getExtraLibs(): IExtraLibs;
addExtraLib(content: string, _filePath?: string): IDisposable;
setExtraLibs(libs: { content: string; filePath?: string; }[]): void;
private _fireOnDidExtraLibsChangeSoon;
getCompilerOptions(): monaco.languages.typescript.CompilerOptions;
setCompilerOptions(options: monaco.languages.typescript.CompilerOptions): void;
getDiagnosticsOptions(): monaco.languages.typescript.DiagnosticsOptions;
setDiagnosticsOptions(options: monaco.languages.typescript.DiagnosticsOptions): void;
setMaximumWorkerIdleTime(value: number): void;
setEagerModelSync(value: boolean): void;
getEagerModelSync(): boolean;
}
// tsMode.d.ts
export declare function setupTypeScript(defaults: LanguageServiceDefaultsImpl): void;
export declare function setupJavaScript(defaults: LanguageServiceDefaultsImpl): void;
export declare function getJavaScriptWorker(): Promise<(first: Uri, ...more: Uri[]) => Promise<TypeScriptWorker>>;
export declare function getTypeScriptWorker(): Promise<(first: Uri, ...more: Uri[]) => Promise<TypeScriptWorker>>;
// tsWorker.d.ts
export declare class TypeScriptWorker implements ts.LanguageServiceHost {
private _ctx;
private _extraLibs;
private _languageService;
private _compilerOptions;
constructor(ctx: IWorkerContext, createData: ICreateData);
getCompilationSettings(): ts.CompilerOptions;
getScriptFileNames(): string[];
private _getModel;
getScriptVersion(fileName: string): string;
getScriptSnapshot(fileName: string): ts.IScriptSnapshot | undefined;
getScriptKind?(fileName: string): ts.ScriptKind;
getCurrentDirectory(): string;
getDefaultLibFileName(options: ts.CompilerOptions): string;
isDefaultLibFileName(fileName: string): boolean;
private static clearFiles;
getSyntacticDiagnostics(fileName: string): Promise<ts.Diagnostic[]>;
getSemanticDiagnostics(fileName: string): Promise<ts.Diagnostic[]>;
getSuggestionDiagnostics(fileName: string): Promise<ts.DiagnosticWithLocation[]>;
getCompilerOptionsDiagnostics(fileName: string): Promise<ts.Diagnostic[]>;
getCompletionsAtPosition(fileName: string, position: number): Promise<ts.CompletionInfo | undefined>;
getCompletionEntryDetails(fileName: string, position: number, entry: string): Promise<ts.CompletionEntryDetails | undefined>;
getSignatureHelpItems(fileName: string, position: number): Promise<ts.SignatureHelpItems | undefined>;
getQuickInfoAtPosition(fileName: string, position: number): Promise<ts.QuickInfo | undefined>;
getOccurrencesAtPosition(fileName: string, position: number): Promise<ReadonlyArray<ts.ReferenceEntry> | undefined>;
getDefinitionAtPosition(fileName: string, position: number): Promise<ReadonlyArray<ts.DefinitionInfo> | undefined>;
getReferencesAtPosition(fileName: string, position: number): Promise<ts.ReferenceEntry[] | undefined>;
getNavigationBarItems(fileName: string): Promise<ts.NavigationBarItem[]>;
getFormattingEditsForDocument(fileName: string, options: ts.FormatCodeOptions): Promise<ts.TextChange[]>;
getFormattingEditsForRange(fileName: string, start: number, end: number, options: ts.FormatCodeOptions): Promise<ts.TextChange[]>;
getFormattingEditsAfterKeystroke(fileName: string, postion: number, ch: string, options: ts.FormatCodeOptions): Promise<ts.TextChange[]>;
findRenameLocations(fileName: string, positon: number, findInStrings: boolean, findInComments: boolean, providePrefixAndSuffixTextForRename: boolean): Promise<readonly ts.RenameLocation[] | undefined>;
getRenameInfo(fileName: string, positon: number, options: ts.RenameInfoOptions): Promise<ts.RenameInfo>;
getEmitOutput(fileName: string): Promise<ts.EmitOutput>;
getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[], formatOptions: ts.FormatCodeOptions): Promise<ReadonlyArray<ts.CodeFixAction>>;
updateExtraLibs(extraLibs: IExtraLibs): void;
}
export interface ICreateData {
compilerOptions: ts.CompilerOptions;
extraLibs: IExtraLibs;
}
export declare function create(ctx: IWorkerContext, createData: ICreateData): TypeScriptWorker;
// workerManager.d.ts
export declare class WorkerManager {
private _modeId;
private _defaults;
private _configChangeListener;
private _updateExtraLibsToken;
private _extraLibsChangeListener;
private _worker;
private _client;
constructor(modeId: string, defaults: LanguageServiceDefaultsImpl);
private _stopWorker;
dispose(): void;
private _updateExtraLibs;
private _getClient;
getLanguageServiceWorker(...resources: Uri[]): Promise<TypeScriptWorker>;
} | the_stack |
import {
AfterContentInit,
ChangeDetectorRef,
ChangeDetectionStrategy,
Component,
ContentChild,
ContentChildren,
ElementRef,
EventEmitter,
OnChanges,
Input,
OnDestroy,
Output,
QueryList,
SimpleChanges,
ViewEncapsulation,
} from '@angular/core';
import {coerceBooleanProperty} from '@angular/cdk/coercion';
import {Platform} from '@angular/cdk/platform';
import {merge, Observable, Subscription, Subject} from 'rxjs';
import {startWith} from 'rxjs/operators';
import {MDCComponent} from '@angular-mdc/web/base';
import {MdcTabScroller, MdcTabScrollerAlignment} from '@angular-mdc/web/tab-scroller';
import {MdcTab, MdcTabInteractedEvent, MDC_TAB_BAR_PARENT_COMPONENT} from '@angular-mdc/web/tab';
import {MDCTabBarFoundation, MDCTabBarAdapter} from '@material/tab-bar';
export class MdcTabActivatedEvent {
constructor(
public source: MdcTabBar,
public index: number,
public tab: MdcTab) {}
}
@Component({
selector: '[mdcTabBar], mdc-tab-bar',
exportAs: 'mdcTabBar',
host: {
'role': 'tablist',
'class': 'mdc-tab-bar',
'(keydown)': '_onKeydown($event)'
},
template: '<ng-content></ng-content>',
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
providers: [{provide: MDC_TAB_BAR_PARENT_COMPONENT, useExisting: MdcTabBar}]
})
export class MdcTabBar extends MDCComponent<MDCTabBarFoundation> implements AfterContentInit, OnChanges, OnDestroy {
/** Emits whenever the component is destroyed. */
private _destroy = new Subject<void>();
private _initialized: boolean = false;
@Input()
get fade(): boolean {
return this._fade;
}
set fade(value: boolean) {
this._fade = coerceBooleanProperty(value);
this._syncTabs();
}
private _fade: boolean = false;
@Input()
get stacked(): boolean {
return this._stacked;
}
set stacked(value: boolean) {
this._stacked = coerceBooleanProperty(value);
this._syncTabs();
}
private _stacked: boolean = false;
@Input()
get fixed(): boolean {
return this._fixed;
}
set fixed(value: boolean) {
this._fixed = coerceBooleanProperty(value);
this._syncTabs();
}
private _fixed: boolean = false;
@Input()
get align(): MdcTabScrollerAlignment | null {
return this._align;
}
set align(value: MdcTabScrollerAlignment | null) {
this._align = value || 'start';
this._syncTabScroller();
}
private _align: MdcTabScrollerAlignment | null = null;
@Input()
get iconIndicator(): string | null {
return this._iconIndicator;
}
set iconIndicator(value: string | null) {
this._iconIndicator = value;
this._syncTabs();
}
private _iconIndicator: string | null = null;
@Input()
get useAutomaticActivation(): boolean {
return this._useAutomaticActivation;
}
set useAutomaticActivation(value: boolean) {
this._useAutomaticActivation = coerceBooleanProperty(value);
this._foundation.setUseAutomaticActivation(this._useAutomaticActivation);
}
private _useAutomaticActivation: boolean = true;
@Input()
get activeTabIndex(): number {
return this._activeTabIndex;
}
set activeTabIndex(value: number) {
if (this.activeTabIndex !== value) {
this._activeTabIndex = value;
this.activateTab(this.activeTabIndex);
}
}
private _activeTabIndex: number = 0;
@Input()
get focusOnActivate(): boolean {
return this._focusOnActivate;
}
set focusOnActivate(value: boolean) {
this._focusOnActivate = coerceBooleanProperty(value);
this._syncTabs();
}
private _focusOnActivate: boolean = true;
@Output() readonly activated: EventEmitter<MdcTabActivatedEvent> =
new EventEmitter<MdcTabActivatedEvent>();
@ContentChild(MdcTabScroller, {static: true}) tabScroller!: MdcTabScroller;
@ContentChildren(MdcTab, {descendants: true}) tabs!: QueryList<MdcTab>;
/** Subscription to changes in tabs. */
private _changeSubscription: Subscription | null = null;
/** Subscription to interaction events in tabs. */
private _tabInteractionSubscription: Subscription | null = null;
/** Combined stream of all of the tab interaction events. */
get tabInteractions(): Observable<MdcTabInteractedEvent> {
return merge(...this.tabs.map(tab => tab.interacted));
}
getDefaultFoundation() {
const adapter: MDCTabBarAdapter = {
scrollTo: (scrollX: number) => this.tabScroller.scrollTo(scrollX),
incrementScroll: (scrollXIncrement: number) => this.tabScroller.incrementScroll(scrollXIncrement),
getScrollPosition: () => this.tabScroller.getScrollPosition(),
getScrollContentWidth: () => this.tabScroller.getScrollContentWidth(),
getOffsetWidth: () => this._getHostElement().offsetWidth,
isRTL: () => this._platform.isBrowser ?
window.getComputedStyle(this._getHostElement()).getPropertyValue('direction') === 'rtl' : false,
setActiveTab: (index: number) => this.activateTab(index),
activateTabAtIndex: (index: number, clientRect?: ClientRect) => {
if (this._indexIsInRange(index)) {
this.tabs.toArray()[index].activate(clientRect);
}
},
deactivateTabAtIndex: (index: number) => {
if (this._indexIsInRange(index)) {
this.tabs.toArray()[index].deactivate();
}
},
focusTabAtIndex: (index: number) => this.tabs.toArray()[index].focus(),
getTabIndicatorClientRectAtIndex: (previousActiveIndex: number) => {
if (!this._platform.isBrowser) {
return {height: 0, width: 0, bottom: 0, top: 0, left: 0, right: 0};
}
if (!this._indexIsInRange(previousActiveIndex)) {
previousActiveIndex = this.activeTabIndex;
}
return this.tabs.toArray()[previousActiveIndex].computeIndicatorClientRect();
},
getTabDimensionsAtIndex: (index: number) => this.tabs.toArray()[index].computeDimensions(),
getPreviousActiveTabIndex: () => this.tabs.toArray().findIndex((_) => _.active),
getFocusedTabIndex: () =>
this._platform.isBrowser ? this.tabs.toArray().findIndex(tab =>
tab.elementRef.nativeElement === document.activeElement!) : -1,
getIndexOfTabById: (id: string) => this.tabs.toArray().findIndex(tab => id === tab.id),
getTabListLength: () => this.tabs.length,
notifyTabActivated: (index: number) =>
this.activated.emit({source: this, index: index, tab: this.tabs.toArray()[index]})
};
return new MDCTabBarFoundation(adapter);
}
constructor(
private _platform: Platform,
private _changeDetectorRef: ChangeDetectorRef,
public elementRef: ElementRef<HTMLElement>) {
super(elementRef);
}
ngOnChanges(changes: SimpleChanges) {
if (!this._initialized) {
return;
}
if (changes['align']) {
this._syncTabScroller();
}
}
ngAfterContentInit(): void {
this._initialized = true;
this._foundation.init();
// When the list changes, re-subscribe
this._changeSubscription = this.tabs.changes.pipe(startWith(null)).subscribe(() => {
Promise.resolve().then(() => {
if (this.tabs.length) {
this._syncTabs();
this._syncTabScroller();
this.activateTab(this.activeTabIndex);
this._resetTabSubscriptions();
}
});
});
}
ngOnDestroy(): void {
this._destroy.next();
this._destroy.complete();
if (this._changeSubscription) {
this._changeSubscription.unsubscribe();
}
this._dropSubscriptions();
}
private _syncTabs(): void {
if (!this.tabs) {
return;
}
this.tabs.forEach(tab => {
tab.stacked = this._stacked;
tab.fixed = this._fixed;
tab.tabIndicator.fade = this._fade;
tab.tabIndicator.icon = this._iconIndicator;
tab.focusOnActivate = this._focusOnActivate;
});
}
private _syncTabScroller(): void {
if (this.tabScroller) {
this.tabScroller.align = this.align;
}
}
private _resetTabSubscriptions(): void {
this._dropSubscriptions();
this._listenToTabInteraction();
}
private _dropSubscriptions(): void {
if (this._tabInteractionSubscription) {
this._tabInteractionSubscription.unsubscribe();
this._tabInteractionSubscription = null;
}
}
/** Listens to interaction events on each tab. */
private _listenToTabInteraction(): void {
this._tabInteractionSubscription = this.tabInteractions.subscribe(event => {
const previousTab = this.getActiveTab();
if (previousTab) {
previousTab.tabIndicator.active = false;
}
event.detail.tab.tabIndicator.active = true;
this._foundation.handleTabInteraction(event as any);
});
}
/** Activates the tab at the given index */
activateTab(index: number): void {
if (!this.tabs) {
return;
}
this.activeTabIndex = index;
if (this._platform.isBrowser) {
this._foundation.activateTab(index);
}
this._changeDetectorRef.markForCheck();
}
/** Scrolls the tab at the given index into view */
scrollIntoView(index: number): void {
this._foundation.scrollIntoView(index);
}
getActiveTabIndex(): number {
return this.tabs.toArray().findIndex((_) => _.active);
}
getActiveTab(): MdcTab | undefined {
return this.tabs.toArray().find((_) => _.active);
}
/** Returns an index for given tab */
getTabIndex(tab: MdcTab): number {
return this.tabs.toArray().indexOf(tab);
}
/** Disable or enable the tab at the given index */
disableTab(index: number, disabled: boolean): void {
if (!this.tabs) {
return;
}
this.tabs.toArray()[index].disabled = coerceBooleanProperty(disabled);
}
_onKeydown(evt: KeyboardEvent): void {
this._foundation.handleKeyDown(evt);
}
private _indexIsInRange(index: number): boolean {
return index >= 0 && index < this.tabs.length;
}
/** Retrieves the DOM element of the component host. */
private _getHostElement(): HTMLElement {
return this.elementRef.nativeElement;
}
} | the_stack |
import React, { ReactNode, Component } from 'react';
import cls from 'classnames';
import PropTypes from 'prop-types';
import { cssClasses, strings } from '@douyinfe/semi-foundation/progress/constants';
import '@douyinfe/semi-foundation/progress/progress.scss';
import { Animation } from '@douyinfe/semi-animation';
import { Motion } from '../_base/base';
const prefixCls = cssClasses.PREFIX;
export interface ProgressProps {
'aria-label'?: string | undefined;
'aria-labelledby'?: string | undefined;
'aria-valuetext'?: string | undefined;
className?: string;
direction?: 'horizontal' | 'vertical';
format?: (percent: number) => React.ReactNode;
id?: string;
motion?: Motion;
orbitStroke?: string;
percent?: number;
showInfo?: boolean;
size?: 'default' | 'small' | 'large';
stroke?: string;
strokeLinecap?: 'round' | 'square';
strokeWidth?: number;
style?: React.CSSProperties;
type?: 'line' | 'circle';
width?: number;
}
export interface ProgressState {
percentNumber: number;
}
class Progress extends Component<ProgressProps, ProgressState> {
static propTypes = {
'aria-label': PropTypes.string,
'aria-labelledby': PropTypes.string,
'aria-valuetext': PropTypes.string,
className: PropTypes.string,
direction: PropTypes.oneOf(strings.directions),
format: PropTypes.oneOfType([PropTypes.func, PropTypes.node]),
id: PropTypes.string,
motion: PropTypes.oneOfType([PropTypes.bool, PropTypes.func, PropTypes.object]),
orbitStroke: PropTypes.string,
percent: PropTypes.number,
scale: PropTypes.number,
showInfo: PropTypes.bool,
size: PropTypes.oneOf(strings.sizes),
stroke: PropTypes.string,
strokeLinecap: PropTypes.oneOf(strings.strokeLineCap),
strokeWidth: PropTypes.number,
style: PropTypes.object,
type: PropTypes.oneOf(strings.types),
width: PropTypes.number,
};
static defaultProps = {
className: '',
direction: strings.DEFAULT_DIRECTION,
format: (text: string): string => `${text}%`,
motion: true,
orbitStroke: 'var(--semi-color-fill-0)',
percent: 0,
showInfo: false,
size: strings.DEFAULT_SIZE,
stroke: 'var(--semi-color-success)',
strokeLinecap: strings.DEFAULT_LINECAP,
strokeWidth: 4,
style: {},
type: strings.DEFAULT_TYPE,
};
_mounted: boolean = true;
animation: Animation;
constructor(props: ProgressProps) {
super(props);
this._mounted = true;
this.state = {
percentNumber: this.props.percent // Specially used for animation of numbers
};
}
componentDidUpdate(prevProps: ProgressProps): void {
if (isNaN(this.props.percent) || isNaN(prevProps.percent)) {
throw new Error('[Semi Progress]:percent can not be NaN');
return;
}
if (prevProps.percent !== this.props.percent) {
if (!this.props.motion) {
// eslint-disable-next-line
this.setState({ percentNumber: this.props.percent });
return;
}
if (this.animation && this.animation.destroy) {
this.animation.destroy();
}
this.animation = new Animation({
from: { value: prevProps.percent },
to: { value: this.props.percent }
}, {
// easing: 'cubic-bezier(0, .68, .3, 1)'
easing: 'linear',
duration: 300
});
this.animation.on('frame', (props: any) => {
// prevent setState while component is unmounted but this timer is called
if (this._mounted === false) {
return;
}
// let percentNumber = Number.isInteger(props.value) ? props.value : Math.floor(props.value * 100) / 100;
const percentNumber = parseInt(props.value);
this.setState({ percentNumber });
});
this.animation.on('rest', () => {
// prevent setState while component is unmounted but this timer is called
if (this._mounted === false) {
return;
}
this.setState({ percentNumber: this.props.percent });
});
this.animation.start();
}
}
componentWillUnmount(): void {
this.animation && this.animation.destroy();
this._mounted = false;
}
renderCircleProgress(): ReactNode {
const { strokeLinecap, style, className, strokeWidth, format, size, stroke, showInfo, percent, orbitStroke, id } = this.props;
const ariaLabel = this.props['aria-label'];
const ariaLabelledBy = this.props['aria-labelledby'];
const ariaValueText = this.props['aria-valuetext'];
const { percentNumber } = this.state;
const classNames = {
wrapper: cls(`${prefixCls}-circle`, className),
svg: cls(`${prefixCls}-circle-ring`),
circle: cls(`${prefixCls}-circle-ring-inner`)
};
const perc = this.calcPercent(percent);
const percNumber = this.calcPercent(percentNumber);
let width;
if (this.props.width) {
width = this.props.width;
} else {
size === strings.DEFAULT_SIZE ? width = 72 : width = 24;
}
// cx, cy is circle center
const cy = width / 2;
const cx = width / 2;
const radius = (width - strokeWidth) / 2; // radius
const circumference = radius * 2 * Math.PI;
const strokeDashoffset = (1 - perc / 100) * circumference; // Offset
const strokeDasharray = `${circumference} ${circumference}`;
const text = format(percNumber);
return (
<div
id={id}
className={classNames.wrapper}
style={style}
role='progressbar'
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={percNumber}
aria-labelledby={ariaLabelledBy}
aria-label={ariaLabel}
aria-valuetext={ariaValueText}
>
<svg key={size} className={classNames.svg} height={width} width={width} aria-hidden>
<circle
strokeDashoffset={0}
strokeWidth={strokeWidth}
strokeDasharray={strokeDasharray}
strokeLinecap={strokeLinecap}
fill="transparent"
stroke={orbitStroke}
r={radius}
cx={cx}
cy={cy}
aria-hidden
/>
<circle
className={classNames.circle}
strokeDashoffset={strokeDashoffset}
strokeWidth={strokeWidth}
strokeDasharray={strokeDasharray}
strokeLinecap={strokeLinecap}
fill="transparent"
stroke={stroke}
r={radius}
cx={cx}
cy={cy}
aria-hidden
/>
</svg>
{showInfo && size !== 'small' ? (<span className={`${prefixCls}-circle-text`}>{text}</span>) : null}
</div>
);
}
calcPercent(percent: number): number {
let perc;
if (percent > 100) {
perc = 100;
} else if (percent < 0) {
perc = 0;
} else {
perc = percent;
}
return perc;
}
renderLineProgress(): ReactNode {
const { className, style, stroke, direction, format, showInfo, size, percent, orbitStroke, id } = this.props;
const ariaLabel = this.props['aria-label'];
const ariaLabelledBy = this.props['aria-labelledby'];
const ariaValueText = this.props['aria-valuetext'];
const { percentNumber } = this.state;
const progressWrapperCls = cls(prefixCls, className, {
[`${prefixCls}-horizontal`]: direction === strings.DEFAULT_DIRECTION,
[`${prefixCls}-vertical`]: direction !== strings.DEFAULT_DIRECTION,
[`${prefixCls}-large`]: size === 'large',
});
const progressTrackCls = cls({
[`${prefixCls}-track`]: true,
});
const innerCls = cls(`${prefixCls}-track-inner`);
const perc = this.calcPercent(percent);
const percNumber = this.calcPercent(percentNumber);
const innerStyle: Record<string, any> = {
background: stroke
};
if (direction === strings.DEFAULT_DIRECTION) {
innerStyle.width = `${perc}%`;
} else {
innerStyle.height = `${perc}%`;
}
const text = format(percNumber);
return (
<div
id={id}
className={progressWrapperCls}
style={style}
role='progressbar'
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={perc}
aria-labelledby={ariaLabelledBy}
aria-label={ariaLabel}
aria-valuetext={ariaValueText}
>
<div className={progressTrackCls} style={orbitStroke ? { backgroundColor: orbitStroke } : {}} aria-hidden>
<div className={innerCls} style={innerStyle} aria-hidden />
</div>
{showInfo ? <div className={`${prefixCls}-line-text`}>{text}</div> : null}
</div>
);
}
render(): ReactNode {
const { type } = this.props;
if (type === 'line') {
return this.renderLineProgress();
} else {
return this.renderCircleProgress();
}
}
}
export default Progress; | the_stack |
import { DebugElement, SimpleChange } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ActivitiContentService, AppConfigService, FormService, setupTestBed, AppsProcessService } from '@alfresco/adf-core';
import { of, throwError } from 'rxjs';
import { MatSelectChange } from '@angular/material/select';
import { ProcessInstanceVariable } from '../models/process-instance-variable.model';
import { ProcessService } from '../services/process.service';
import {
newProcess,
taskFormMock,
testProcessDef,
testMultipleProcessDefs,
testProcessDefWithForm,
testProcessDefinitions
} from '../../mock';
import { StartProcessInstanceComponent } from './start-process.component';
import { ProcessTestingModule } from '../../testing/process.testing.module';
import { By } from '@angular/platform-browser';
import { TranslateModule } from '@ngx-translate/core';
import { deployedApps } from '../../mock/apps-list.mock';
import { ProcessNamePipe } from '../../pipes/process-name.pipe';
import { ProcessInstance } from '../models/process-instance.model';
describe('StartFormComponent', () => {
let appConfig: AppConfigService;
let activitiContentService: ActivitiContentService;
let component: StartProcessInstanceComponent;
let fixture: ComponentFixture<StartProcessInstanceComponent>;
let processService: ProcessService;
let formService: FormService;
let appsProcessService: AppsProcessService;
let getDefinitionsSpy: jasmine.Spy;
let getStartFormDefinitionSpy: jasmine.Spy;
let startProcessSpy: jasmine.Spy;
let applyAlfrescoNodeSpy: jasmine.Spy;
let getDeployedApplicationsSpy: jasmine.Spy;
setupTestBed({
imports: [
TranslateModule.forRoot(),
ProcessTestingModule
]
});
const selectOptionByName = (name: string) => {
const selectElement = fixture.nativeElement.querySelector('button#adf-select-process-dropdown');
selectElement.click();
fixture.detectChanges();
const options: any = fixture.debugElement.queryAll(By.css('.mat-option-text'));
const currentOption = options.find( (option: DebugElement) => option.nativeElement.innerHTML.trim() === name );
if (currentOption) {
currentOption.nativeElement.click();
}
};
beforeEach(() => {
appConfig = TestBed.inject(AppConfigService);
activitiContentService = TestBed.inject(ActivitiContentService);
fixture = TestBed.createComponent(StartProcessInstanceComponent);
component = fixture.componentInstance;
processService = TestBed.inject(ProcessService);
formService = TestBed.inject(FormService);
appsProcessService = TestBed.inject(AppsProcessService);
getDefinitionsSpy = spyOn(processService, 'getProcessDefinitions').and.returnValue(of(testMultipleProcessDefs));
startProcessSpy = spyOn(processService, 'startProcess').and.returnValue(of(newProcess));
getStartFormDefinitionSpy = spyOn(formService, 'getStartFormDefinition').and.returnValue(of(taskFormMock));
applyAlfrescoNodeSpy = spyOn(activitiContentService, 'applyAlfrescoNode').and.returnValue(of({ id: 1234 }));
spyOn(activitiContentService, 'getAlfrescoRepositories').and.returnValue(of([{ id: '1', name: 'fake-repo-name'}]));
});
afterEach(() => {
fixture.destroy();
TestBed.resetTestingModule();
});
describe('first step', () => {
describe('without start form', () => {
beforeEach(() => {
fixture.detectChanges();
component.name = 'My new process';
const change = new SimpleChange(null, 123, true);
component.ngOnChanges({ 'appId': change });
fixture.detectChanges();
});
it('should enable start button when name and process filled out', async () => {
spyOn(component, 'loadProcessDefinitions').and.callThrough();
component.processNameInput.setValue('My Process');
component.processDefinitionInput.setValue(testProcessDef.name);
fixture.detectChanges();
await fixture.whenStable();
const startBtn = fixture.nativeElement.querySelector('#button-start');
expect(startBtn.disabled).toBe(false);
});
it('should have start button disabled when name not filled out', async () => {
spyOn(component, 'loadProcessDefinitions').and.callThrough();
component.processNameInput.setValue('');
component.processDefinitionInput.setValue(testProcessDef.name);
fixture.detectChanges();
await fixture.whenStable();
const startBtn = fixture.nativeElement.querySelector('#button-start');
expect(startBtn.disabled).toBe(true);
});
it('should have start button disabled when no process is selected', async () => {
component.selectedProcessDef = null;
fixture.detectChanges();
await fixture.whenStable();
const startBtn = fixture.nativeElement.querySelector('#button-start');
expect(startBtn.disabled).toBe(true);
});
it('should have start button disabled process name has a space as the first or last character.', async () => {
component.processNameInput.setValue(' Space in the beginning');
component.processDefinitionInput.setValue(testProcessDef.name);
fixture.detectChanges();
await fixture.whenStable();
const startBtn = fixture.nativeElement.querySelector('#button-start');
expect(startBtn.disabled).toBe(true);
component.processNameInput.setValue('Space in the end ');
fixture.detectChanges();
await fixture.whenStable();
expect(startBtn.disabled).toBe(true);
});
});
describe('with start form', () => {
beforeEach(() => {
fixture.detectChanges();
getDefinitionsSpy.and.returnValue(of(testProcessDefWithForm));
const change = new SimpleChange(null, 123, true);
component.ngOnChanges({ 'appId': change });
});
it('should initialize start form', async () => {
fixture.detectChanges();
await fixture.whenStable();
expect(component.startForm).toBeDefined();
expect(component.startForm).not.toBeNull();
});
it('should have labels for process name and type', async () => {
component.processDefinitionInput.setValue('My Default Name');
component.processNameInput.setValue('claim');
fixture.detectChanges();
await fixture.whenStable();
const inputLabelsNodes = document.querySelectorAll('.adf-start-process .adf-process-input-container mat-label');
expect(inputLabelsNodes.length).toBe(2);
});
it('should have floating labels for process name and type', async () => {
component.processDefinitionInput.setValue('My Default Name');
component.processNameInput.setValue('claim');
fixture.detectChanges();
await fixture.whenStable();
const inputLabelsNodes = document.querySelectorAll('.adf-start-process .adf-process-input-container');
inputLabelsNodes.forEach(labelNode => {
expect(labelNode.getAttribute('ng-reflect-float-label')).toBe('always');
});
});
it('should load start form from service', async () => {
fixture.detectChanges();
await fixture.whenStable();
expect(getStartFormDefinitionSpy).toHaveBeenCalled();
});
it('should have start button disabled if the process is not selected', async () => {
component.name = 'My new process';
fixture.detectChanges();
await fixture.whenStable();
const startBtn = fixture.nativeElement.querySelector('#button-start');
expect(startBtn).toBeNull();
});
it('should emit cancel event on cancel Button', async () => {
fixture.detectChanges();
await fixture.whenStable();
const cancelButton = fixture.nativeElement.querySelector('#cancel_process');
const cancelSpy: jasmine.Spy = spyOn(component.cancel, 'emit');
cancelButton.click();
fixture.detectChanges();
await fixture.whenStable();
expect(cancelSpy).toHaveBeenCalled();
});
it('should return true if startFrom defined', async () => {
component.name = 'my:process1';
fixture.detectChanges();
await fixture.whenStable();
expect(component.hasStartForm()).toBe(true);
});
});
describe('CS content connection', () => {
it('Should get the alfrescoRepositoryName from the config json', async () => {
appConfig.config = Object.assign(appConfig.config, {
'alfrescoRepositoryName': 'alfresco-123'
});
expect(component.getAlfrescoRepositoryName()).toBe('alfresco-123Alfresco');
});
it('Should take the alfrescoRepositoryName from the API when there is no alfrescoRepositoryName defined in config json', async () => {
fixture.detectChanges();
await fixture.whenStable();
expect(component.alfrescoRepositoryName).toBe('alfresco-1-fake-repo-name');
});
it('if values in input is a node should be linked in the process service', async () => {
component.values = {};
component.values['file'] = {
isFile: true,
name: 'example-file'
};
component.moveNodeFromCStoPS();
fixture.detectChanges();
await fixture.whenStable();
expect(component.movedNodeToPS.file[0].id).toBe(1234);
expect(applyAlfrescoNodeSpy).toHaveBeenCalled();
});
it('if values in input is a collection of nodes should be linked in the process service', async () => {
component.values = {};
component.values['file'] = [
{
isFile: true,
name: 'example-file-1'
},
{
isFile: true,
name: 'example-fil-2'
},
{
isFile: true,
name: 'example-file-3'
}
];
component.moveNodeFromCStoPS();
fixture.detectChanges();
await fixture.whenStable();
expect(component.movedNodeToPS.file.length).toBe(3);
expect(component.movedNodeToPS.file[0].id).toBe(1234);
expect(component.movedNodeToPS.file[1].id).toBe(1234);
expect(applyAlfrescoNodeSpy).toHaveBeenCalledTimes(3);
});
});
});
describe('process definitions list', () => {
beforeEach(() => {
fixture.detectChanges();
component.name = 'My new process';
component.appId = 123;
component.ngOnChanges({});
fixture.detectChanges();
});
it('should call service to fetch process definitions with appId', () => {
fixture.whenStable().then(() => {
expect(getDefinitionsSpy).toHaveBeenCalledWith(123);
});
});
it('should display the correct number of processes in the select list', () => {
fixture.whenStable().then(() => {
const selectElement = fixture.nativeElement.querySelector('mat-select');
expect(selectElement.children.length).toBe(1);
});
});
it('should display the option def details', () => {
component.processDefinitions = testMultipleProcessDefs;
fixture.detectChanges();
fixture.whenStable().then(() => {
const selectElement = fixture.nativeElement.querySelector('mat-select > .mat-select-trigger');
const optionElement = fixture.nativeElement.querySelectorAll('mat-option');
selectElement.click();
expect(selectElement).not.toBeNull();
expect(selectElement).toBeDefined();
expect(optionElement).not.toBeNull();
expect(optionElement).toBeDefined();
});
});
it('should show no process available message when no process definition is loaded', async () => {
getDefinitionsSpy = getDefinitionsSpy.and.returnValue(of([]));
component.appId = 123;
const change = new SimpleChange(null, 123, true);
component.ngOnChanges({ 'appId': change });
fixture.detectChanges();
await fixture.whenStable();
const noProcessElement = fixture.nativeElement.querySelector('.adf-empty-content__title');
expect(noProcessElement).not.toBeNull('Expected no available process message to be present');
expect(noProcessElement.innerText.trim()).toBe('ADF_PROCESS_LIST.START_PROCESS.NO_PROCESS_DEFINITIONS');
});
it('should select processDefinition based on processDefinition input', async () => {
getDefinitionsSpy = getDefinitionsSpy.and.returnValue(of(testMultipleProcessDefs));
component.appId = 123;
component.processNameInput.setValue('My Process 2');
component.processDefinitionInput.setValue('My Process 2');
fixture.detectChanges();
await fixture.whenStable();
expect(component.selectedProcessDef.name).toBe(JSON.parse(JSON.stringify(testMultipleProcessDefs[1])).name);
});
it('should select automatically the processDefinition if the app contain only one', async () => {
getDefinitionsSpy = getDefinitionsSpy.and.returnValue(of(testProcessDefinitions));
component.appId = 123;
const change = new SimpleChange(null, 123, true);
component.ngOnChanges({ 'appId': change });
fixture.detectChanges();
await fixture.whenStable();
expect(component.selectedProcessDef.name).toBe(JSON.parse(JSON.stringify(testProcessDefinitions[0])).name);
});
it('should not select automatically any processDefinition if the app contain multiple process and does not have any processDefinition as input', async () => {
getDefinitionsSpy = getDefinitionsSpy.and.returnValue(of(testMultipleProcessDefs));
component.appId = 123;
const change = new SimpleChange(null, 123, true);
component.ngOnChanges({ 'appId': change });
fixture.detectChanges();
await fixture.whenStable();
expect(component.selectedProcessDef.name).toBeNull();
});
describe('dropdown', () => {
it('should hide the process dropdown button if showSelectProcessDropdown is false', async () => {
fixture.detectChanges();
getDefinitionsSpy = getDefinitionsSpy.and.returnValue(of([testProcessDef]));
component.appId = 123;
component.showSelectProcessDropdown = false;
component.ngOnChanges({});
fixture.detectChanges();
await fixture.whenStable();
const selectElement = fixture.nativeElement.querySelector('button#adf-select-process-dropdown');
expect(selectElement).toBeNull();
});
it('should show the process dropdown button if showSelectProcessDropdown is false', async () => {
fixture.detectChanges();
getDefinitionsSpy = getDefinitionsSpy.and.returnValue(of(testMultipleProcessDefs));
component.appId = 123;
component.processDefinitionName = 'My Process 2';
component.showSelectProcessDropdown = true;
component.ngOnChanges({});
fixture.detectChanges();
await fixture.whenStable();
const selectElement = fixture.nativeElement.querySelector('button#adf-select-process-dropdown');
expect(selectElement).not.toBeNull();
});
it('should show the process dropdown button by default', async () => {
fixture.detectChanges();
await fixture.whenStable();
getDefinitionsSpy = getDefinitionsSpy.and.returnValue(of(testMultipleProcessDefs));
component.appId = 123;
component.processDefinitionName = 'My Process 2';
component.ngOnChanges({});
fixture.detectChanges();
await fixture.whenStable();
const selectElement = fixture.nativeElement.querySelector('button#adf-select-process-dropdown');
expect(selectElement).not.toBeNull();
});
});
});
describe('input changes', () => {
const change = new SimpleChange(123, 456, true);
beforeEach(async () => {
component.appId = 123;
fixture.detectChanges();
});
it('should reload processes when appId input changed', async () => {
component.appId = 456;
component.ngOnChanges({ appId: change });
fixture.detectChanges();
await fixture.whenStable();
expect(getDefinitionsSpy).toHaveBeenCalledWith(456);
});
it('should get current processDef', () => {
component.appId = 456;
component.ngOnChanges({ appId: change });
fixture.detectChanges();
expect(getDefinitionsSpy).toHaveBeenCalled();
expect(component.processDefinitions).toBe(testMultipleProcessDefs);
});
});
describe('start process', () => {
beforeEach(() => {
fixture.detectChanges();
component.name = 'My new process';
component.appId = 123;
component.ngOnChanges({});
});
it('should call service to start process if required fields provided', async () => {
component.processDefinitionSelectionChanged(testProcessDef);
component.startProcess();
fixture.detectChanges();
await fixture.whenStable();
expect(startProcessSpy).toHaveBeenCalled();
});
it('should avoid calling service to start process if required fields NOT provided', async () => {
component.name = '';
component.startProcess();
fixture.detectChanges();
await fixture.whenStable();
expect(startProcessSpy).not.toHaveBeenCalled();
});
it('should call service to start process with the correct parameters', async () => {
component.processDefinitionSelectionChanged(testProcessDef);
component.startProcess();
fixture.detectChanges();
await fixture.whenStable();
expect(startProcessSpy).toHaveBeenCalledWith('my:process1', 'My new process', undefined, undefined, undefined);
});
it('should call service to start process with the variables setted', async () => {
const inputProcessVariable: ProcessInstanceVariable[] = [];
const variable: ProcessInstanceVariable = {};
variable.name = 'nodeId';
variable.value = 'id';
inputProcessVariable.push(variable);
component.variables = inputProcessVariable;
component.processDefinitionSelectionChanged(testProcessDef);
component.startProcess();
fixture.detectChanges();
await fixture.whenStable();
expect(startProcessSpy).toHaveBeenCalledWith('my:process1', 'My new process', undefined, undefined, inputProcessVariable);
});
it('should output start event when process started successfully', async () => {
const emitSpy = spyOn(component.start, 'emit');
component.processDefinitionSelectionChanged(testProcessDef);
component.startProcess();
fixture.detectChanges();
await fixture.whenStable();
expect(emitSpy).toHaveBeenCalledWith(newProcess);
});
it('should emit start event when start select a process and add a name', (done) => {
const disposableStart = component.start.subscribe(() => {
disposableStart.unsubscribe();
done();
});
component.processDefinitionSelectionChanged(testProcessDef);
component.name = 'my:Process';
component.startProcess();
fixture.detectChanges();
});
it('should emit processDefinitionSelection event when a process definition is selected', (done) => {
component.processDefinitionSelection.subscribe((processDefinition) => {
expect(processDefinition).toEqual(testProcessDef);
done();
});
fixture.detectChanges();
selectOptionByName(testProcessDef.name);
});
it('should set the process name using the processName pipe when a process definition gets selected', () => {
const processNamePipe = TestBed.inject(ProcessNamePipe);
const processNamePipeTransformSpy = spyOn(processNamePipe, 'transform').and.returnValue('fake-transformed-name');
const expectedProcessInstanceDetails = new ProcessInstance({ processDefinitionName: testProcessDef.name });
getDefinitionsSpy = getDefinitionsSpy.and.returnValue(of(testMultipleProcessDefs));
component.appId = 123;
const appIdChange = new SimpleChange(null, 123, true);
component.ngOnChanges({ 'appId': appIdChange });
fixture.detectChanges();
selectOptionByName(testProcessDef.name);
expect(processNamePipeTransformSpy).toHaveBeenCalledWith(component.name, expectedProcessInstanceDetails);
expect(component.nameController.dirty).toBe(true);
expect(component.nameController.touched).toBe(true);
expect(component.nameController.value).toEqual('fake-transformed-name');
});
it('should not emit start event when start the process without select a process and name', () => {
component.name = null;
component.selectedProcessDef = null;
const startSpy: jasmine.Spy = spyOn(component.start, 'emit');
component.startProcess();
fixture.detectChanges();
expect(startSpy).not.toHaveBeenCalled();
});
it('should not emit start event when start the process without name', () => {
component.name = null;
const startSpy: jasmine.Spy = spyOn(component.start, 'emit');
component.startProcess();
fixture.detectChanges();
expect(startSpy).not.toHaveBeenCalled();
});
it('should not emit start event when start the process without select a process', () => {
component.selectedProcessDef = null;
const startSpy: jasmine.Spy = spyOn(component.start, 'emit');
component.startProcess();
fixture.detectChanges();
expect(startSpy).not.toHaveBeenCalled();
});
it('should able to start the process when the required fields are filled up', (done) => {
component.name = 'my:process1';
component.processDefinitionSelectionChanged(testProcessDef);
const disposableStart = component.start.subscribe(() => {
disposableStart.unsubscribe();
done();
});
component.startProcess();
});
});
describe('Select applications', () => {
const mockAppId = 3;
beforeEach(() => {
fixture.detectChanges();
component.name = 'My new process';
component.showSelectApplicationDropdown = true;
getDeployedApplicationsSpy = spyOn(appsProcessService, 'getDeployedApplications').and.returnValue(of(deployedApps));
});
it('Should be able to show application drop-down if showSelectApplicationDropdown set to true', () => {
getDefinitionsSpy.and.returnValue(of(testMultipleProcessDefs));
const change = new SimpleChange(null, 3, true);
component.ngOnChanges({ 'appId': change });
fixture.detectChanges();
const appsSelector = fixture.nativeElement.querySelector('[data-automation-id="adf-start-process-apps-drop-down"]');
const lableElement = fixture.nativeElement.querySelector('.adf-start-process-app-list .mat-form-field-label');
expect(appsSelector).not.toBeNull();
expect(lableElement.innerText).toEqual('ADF_PROCESS_LIST.START_PROCESS.FORM.LABEL.SELECT_APPLICATION');
expect(getDeployedApplicationsSpy).toHaveBeenCalled();
expect(component.applications.length).toBe(6);
expect(component.selectedApplication).toEqual(deployedApps[2]);
expect(component.selectedApplication.id).toEqual(component.appId);
expect(component.selectedApplication.name).toEqual('App3');
});
it('Should not be able to show application drop-down if showSelectApplicationDropdown set to false', () => {
component.showSelectApplicationDropdown = false;
fixture.detectChanges();
const appsSelector = fixture.nativeElement.querySelector('[data-automation-id="adf-start-process-apps-drop-down"]');
expect(appsSelector).toBeNull();
});
it('Should be able to list process-definition based on selected application', () => {
getDefinitionsSpy.and.returnValue(of(testMultipleProcessDefs));
const change = new SimpleChange(null, 3, true);
component.ngOnChanges({ 'appId': change });
fixture.detectChanges();
expect(component.appId).toBe(component.selectedApplication.id);
expect(component.selectedApplication).toEqual(deployedApps[2]);
expect(component.selectedApplication.name).toEqual('App3');
expect(getDefinitionsSpy).toHaveBeenCalledWith(mockAppId);
expect(component.processDefinitions.length).toEqual(2);
expect(component.processDefinitions[0].name).toEqual('My Process 1');
expect(component.processDefinitions[1].name).toEqual('My Process 2');
const changedAppId = 2;
getDefinitionsSpy.and.returnValue(of([ { id: 'my:process 3', name: 'My Process 3', hasStartForm: true } ]));
fixture.detectChanges();
const newApplication = <MatSelectChange> { value: deployedApps[1] };
component.onAppSelectionChange(newApplication);
fixture.detectChanges();
expect(component.selectedApplication).toEqual(deployedApps[1]);
expect(component.selectedApplication.name).toEqual('App2');
expect(getDefinitionsSpy).toHaveBeenCalledWith(changedAppId);
expect(component.processDefinitions.length).toEqual(1);
expect(component.processDefinitions[0].name).toEqual('My Process 3');
});
it('Should be able to pre-select an application if the list has one application', () => {
getDeployedApplicationsSpy.and.returnValues(of([deployedApps[0]]));
getDefinitionsSpy.and.returnValue(of(testMultipleProcessDefs));
const change = new SimpleChange(null, 123, true);
component.ngOnChanges({ 'appId': change });
fixture.detectChanges();
expect(getDeployedApplicationsSpy).toHaveBeenCalled();
expect(component.applications.length).toEqual(1);
expect(component.selectedApplication.name).toEqual('App1');
});
it('[C333511] Should be able to preselect single app deployed with single process and start event Form', async() => {
getDeployedApplicationsSpy.and.returnValues(of([deployedApps[0]]));
getDefinitionsSpy.and.returnValues(of(testProcessDefWithForm));
const change = new SimpleChange(null, 123, true);
component.appId = 123;
component.ngOnChanges({ 'appId': change });
fixture.detectChanges();
await fixture.whenStable();
const appsSelectElement = fixture.nativeElement.querySelector('[data-automation-id="adf-start-process-apps-drop-down"]');
const processDefinitionSelectInput = fixture.nativeElement.querySelector('#processDefinitionName');
const processNameInput = fixture.nativeElement.querySelector('#processName');
const cancelButton = fixture.nativeElement.querySelector('#cancel_process');
const startBtn = fixture.nativeElement.querySelector('[data-automation-id="adf-form-start process"]');
const adfStartForm = fixture.nativeElement.querySelector('adf-start-form');
expect(getDeployedApplicationsSpy).toHaveBeenCalled();
expect(getDefinitionsSpy).toHaveBeenCalled();
expect(component.applications.length).toEqual(1);
expect(component.processDefinitions.length).toEqual(1);
expect(component.selectedApplication.name).toEqual('App1');
expect(component.selectedProcessDef.name).toEqual('My Process 1');
expect(appsSelectElement).not.toBeNull();
expect(processDefinitionSelectInput).not.toBeNull();
expect(processNameInput).not.toBeNull();
expect(adfStartForm).not.toBeNull();
expect(startBtn).not.toBeNull();
expect(cancelButton).not.toBeNull();
});
it('[C333511] Should be able to preselect single app deployed with single process and no form', async() => {
getDeployedApplicationsSpy.and.returnValues(of([deployedApps[0]]));
getDefinitionsSpy.and.returnValues(of(testProcessDefinitions));
const change = new SimpleChange(null, 123, true);
component.appId = 123;
component.ngOnChanges({ 'appId': change });
fixture.detectChanges();
await fixture.whenStable();
const appsSelectElement = fixture.nativeElement.querySelector('[data-automation-id="adf-start-process-apps-drop-down"]');
const processDefinitionSelectInput = fixture.nativeElement.querySelector('#processDefinitionName');
const processNameInput = fixture.nativeElement.querySelector('#processName');
const cancelButton = fixture.nativeElement.querySelector('#cancel_process');
const startBtn = fixture.nativeElement.querySelector('#button-start');
const adfStartForm = fixture.nativeElement.querySelector('adf-start-form');
expect(getDeployedApplicationsSpy).toHaveBeenCalled();
expect(getDefinitionsSpy).toHaveBeenCalled();
expect(component.applications.length).toEqual(1);
expect(component.processDefinitions.length).toEqual(1);
expect(component.selectedApplication.name).toEqual('App1');
expect(component.selectedProcessDef.name).toEqual('My Process 1');
expect(appsSelectElement).not.toBeNull();
expect(processDefinitionSelectInput).not.toBeNull();
expect(processNameInput).not.toBeNull();
expect(adfStartForm).toBeNull();
expect(startBtn).not.toBeNull();
expect(cancelButton).not.toBeNull();
});
it('Should be able to pre-select an application from the apps based given appId', () => {
component.appId = 2;
const change = new SimpleChange(null, 2, true);
component.ngOnChanges({ 'appId': change });
fixture.detectChanges();
expect(getDeployedApplicationsSpy).toHaveBeenCalled();
expect(component.applications.length).toEqual(6);
expect(component.selectedApplication.id).toEqual(component.appId);
expect(component.selectedApplication.id).toEqual(2);
expect(component.selectedApplication.name).toEqual('App2');
});
it('Should be able to disable process name and definitions inputs if there is no application selected by default', () => {
component.appId = 12345;
const change = new SimpleChange(null, 12345, true);
component.ngOnChanges({ 'appId': change });
fixture.detectChanges();
expect(getDeployedApplicationsSpy).toHaveBeenCalled();
expect(component.applications.length).toEqual(6);
expect(component.selectedApplication).toBeUndefined();
const processDefinitionSelectInput = fixture.nativeElement.querySelector('#processDefinitionName');
const processNameInput = fixture.nativeElement.querySelector('#processName');
expect(processDefinitionSelectInput.disabled).toEqual(true);
expect(processNameInput.disabled).toEqual(true);
});
it('Should be able to enable process name and definitions inputs if the application selected by given appId', () => {
component.appId = 2;
const change = new SimpleChange(null, 2, true);
component.ngOnChanges({ 'appId': change });
fixture.detectChanges();
expect(getDeployedApplicationsSpy).toHaveBeenCalled();
expect(component.applications.length).toEqual(6);
expect(component.selectedApplication.id).toEqual(component.appId);
const processDefinitionSelectInput = fixture.nativeElement.querySelector('#processDefinitionName');
const processNameInput = fixture.nativeElement.querySelector('#processName');
expect(processDefinitionSelectInput.disabled).toEqual(false);
expect(processNameInput.disabled).toEqual(false);
});
it('Should be able to enable process name and definitions inputs when the application selected from the apps drop-down', () => {
component.appId = 12345;
const change = new SimpleChange(null, 12345, true);
component.ngOnChanges({ 'appId': change });
fixture.detectChanges();
expect(getDeployedApplicationsSpy).toHaveBeenCalled();
expect(component.applications.length).toEqual(6);
expect(component.selectedApplication).toBeUndefined();
const appsSelectElement = fixture.nativeElement.querySelector('[data-automation-id="adf-start-process-apps-drop-down"]');
const processDefinitionSelectInput = fixture.nativeElement.querySelector('#processDefinitionName');
const processNameInput = fixture.nativeElement.querySelector('#processName');
expect(processDefinitionSelectInput.disabled).toEqual(true);
expect(processNameInput.disabled).toEqual(true);
appsSelectElement.click();
fixture.detectChanges();
const sortOptions = document.querySelector('[data-automation-id="adf-start-process-apps-option-App2"]');
sortOptions.dispatchEvent(new Event('click'));
fixture.detectChanges();
expect(component.selectedApplication.id).toBe(2);
expect(component.selectedApplication.name).toBe('App2');
expect(processDefinitionSelectInput.disabled).toEqual(false);
expect(processNameInput.disabled).toEqual(false);
});
it('[C333521] Should be able to pre-select single deployed application with multiple processes', () => {
const singleDeployedApp = deployedApps[0];
const mockAppid = 1;
getDeployedApplicationsSpy.and.returnValues(of([singleDeployedApp]));
const change = new SimpleChange(null, mockAppid, true);
component.ngOnChanges({ 'appId': change });
fixture.detectChanges();
expect(getDeployedApplicationsSpy).toHaveBeenCalled();
expect(component.applications.length).toBe(1);
expect(component.selectedApplication).toEqual(singleDeployedApp);
expect(getDefinitionsSpy).toHaveBeenCalledWith(mockAppid);
expect(component.processDefinitions.length).toEqual(2);
const processDefWithStartForm = testMultipleProcessDefs[1];
component.processDefinitionSelectionChanged(processDefWithStartForm);
fixture.detectChanges();
const processWithStartForm = fixture.nativeElement.querySelector('adf-start-form');
expect(processWithStartForm).not.toBeNull();
expect(component.selectedProcessDef.hasStartForm).toEqual(processDefWithStartForm.hasStartForm);
const processDefWithNoStartForm = testMultipleProcessDefs[0];
component.processDefinitionSelectionChanged(processDefWithNoStartForm);
fixture.detectChanges();
const processWithNoStartForm = fixture.nativeElement.querySelector('adf-start-form');
expect(processWithNoStartForm).toBeNull();
expect(component.selectedProcessDef.hasStartForm).toEqual(processDefWithNoStartForm.hasStartForm);
});
it('[C333522] Should be able to list multiple deployed apps with multiple process', async() => {
const change = new SimpleChange(null, 123, true);
component.ngOnChanges({ 'appId': change });
fixture.detectChanges();
const application1 = deployedApps[0];
const application2 = deployedApps[1];
const application3 = deployedApps[2];
expect(component.applications.length).toBe(6);
const processDefWithStartForm = testProcessDefWithForm[0];
getDefinitionsSpy.and.returnValues(of([processDefWithStartForm]));
component.onAppSelectionChange(<MatSelectChange> { value: application1 });
fixture.detectChanges();
await fixture.whenStable();
const processWithStartForm = fixture.nativeElement.querySelector('adf-start-form');
expect(processWithStartForm).not.toBeNull();
expect(component.selectedApplication).toEqual(application1);
expect(getDefinitionsSpy).toHaveBeenCalledWith(application1.id);
expect(component.processDefinitions.length).toEqual(1);
expect(component.selectedProcessDef.name).toEqual(processDefWithStartForm.name);
expect(component.selectedProcessDef.hasStartForm).toEqual(processDefWithStartForm.hasStartForm);
getDefinitionsSpy.and.returnValues(of(testMultipleProcessDefs));
component.onAppSelectionChange(<MatSelectChange> { value: application2 });
fixture.detectChanges();
await fixture.whenStable();
expect(component.selectedApplication).toEqual(application2);
expect(getDefinitionsSpy).toHaveBeenCalledWith(application2.id);
expect(component.processDefinitions.length).toEqual(2);
const processDefWithNoStartForm = testMultipleProcessDefs[0];
getDefinitionsSpy.and.returnValues(of([processDefWithNoStartForm]));
component.onAppSelectionChange(<MatSelectChange> { value: application3 });
fixture.detectChanges();
await fixture.whenStable();
const processWithNoStartForm = fixture.nativeElement.querySelector('adf-start-form');
expect(processWithNoStartForm).toBeNull();
expect(component.selectedApplication).toEqual(application3);
expect(getDefinitionsSpy).toHaveBeenCalledWith(application3.id);
expect(component.processDefinitions.length).toEqual(1);
expect(component.selectedProcessDef.name).toEqual(processDefWithNoStartForm.name);
expect(component.selectedProcessDef.hasStartForm).toEqual(processDefWithNoStartForm.hasStartForm);
});
});
describe('Empty Template', () => {
it('[333510] Should be able to show empty template when no applications deployed', async() => {
getDeployedApplicationsSpy = spyOn(appsProcessService, 'getDeployedApplications').and.returnValue(of([]));
component.showSelectApplicationDropdown = true;
component.appId = 3;
component.ngOnInit();
fixture.detectChanges();
await fixture.whenStable();
const noProcessElement = fixture.nativeElement.querySelector('.adf-empty-content__title');
const appsSelectElement = fixture.nativeElement.querySelector('[data-automation-id="adf-start-process-apps-drop-down"]');
const processDefinitionSelectInput = fixture.nativeElement.querySelector('#processDefinitionName');
const processNameInput = fixture.nativeElement.querySelector('#processName');
const cancelButton = fixture.nativeElement.querySelector('#cancel_process');
const startBtn = fixture.nativeElement.querySelector('#button-start');
expect(appsSelectElement).toBeNull();
expect(processDefinitionSelectInput).toBeNull();
expect(processNameInput).toBeNull();
expect(startBtn).toBeNull();
expect(cancelButton).toBeNull();
expect(noProcessElement).not.toBeNull('Expected no available process message to be present');
expect(noProcessElement.innerText.trim()).toBe('ADF_PROCESS_LIST.START_PROCESS.NO_PROCESS_DEFINITIONS');
});
it('Should be able to show empty template if processDefinitions are empty', async() => {
getDefinitionsSpy.and.returnValue(of([]));
component.appId = 1;
component.ngOnInit();
fixture.detectChanges();
await fixture.whenStable();
const noProcessElement = fixture.nativeElement.querySelector('.adf-empty-content__title');
const processDefinitionSelectInput = fixture.nativeElement.querySelector('#processDefinitionName');
const processNameInput = fixture.nativeElement.querySelector('#processName');
const cancelButton = fixture.nativeElement.querySelector('#cancel_process');
const startBtn = fixture.nativeElement.querySelector('#button-start');
expect(processDefinitionSelectInput).toBeNull();
expect(processNameInput).toBeNull();
expect(startBtn).toBeNull();
expect(cancelButton).toBeNull();
expect(noProcessElement).not.toBeNull('Expected no available process message to be present');
expect(noProcessElement.innerText.trim()).toBe('ADF_PROCESS_LIST.START_PROCESS.NO_PROCESS_DEFINITIONS');
});
it('should show no process definition selected template if there is no process definition selected', async() => {
getDefinitionsSpy.and.returnValue(of(testMultipleProcessDefs));
getDeployedApplicationsSpy = spyOn(appsProcessService, 'getDeployedApplications').and.returnValue(of(deployedApps));
component.showSelectApplicationDropdown = true;
component.appId = 1234;
component.ngOnInit();
fixture.detectChanges();
await fixture.whenStable();
const noProcessElement = fixture.nativeElement.querySelector('.adf-empty-content__title');
expect(noProcessElement).not.toBeNull('Expected no available process message to be present');
expect(noProcessElement.innerText.trim()).toBe('ADF_PROCESS_LIST.START_PROCESS.NO_PROCESS_DEF_SELECTED');
});
it('should show no start form template if selected process definition does not have start form', async() => {
getDefinitionsSpy.and.returnValue(of(testMultipleProcessDefs));
getDeployedApplicationsSpy = spyOn(appsProcessService, 'getDeployedApplications').and.returnValue(of(deployedApps));
component.showSelectApplicationDropdown = true;
component.processDefinitionName = 'My Process 1';
component.appId = 3;
component.ngOnInit();
fixture.detectChanges();
await fixture.whenStable();
const noProcessElement = fixture.nativeElement.querySelector('.adf-empty-content__title');
expect(noProcessElement).not.toBeNull('Expected no available process message to be present');
expect(noProcessElement.innerText.trim()).toBe('ADF_PROCESS_LIST.START_PROCESS.NO_START_FORM');
});
});
describe('Error event', () => {
const processDefError = { message: 'Failed to load Process definitions' };
const applicationsError = { message: 'Failed to load applications' };
const startProcessError = { message: 'Failed to start process' };
beforeEach(() => {
fixture.detectChanges();
});
it('should emit error event in case loading process definitions failed', async() => {
const errorSpy = spyOn(component.error, 'emit');
getDefinitionsSpy.and.returnValue(throwError(processDefError));
component.appId = 3;
component.ngOnInit();
fixture.detectChanges();
await fixture.whenStable();
expect(errorSpy).toHaveBeenCalledWith(processDefError);
});
it('should emit error event in case loading applications failed', async() => {
const errorSpy = spyOn(component.error, 'emit');
getDeployedApplicationsSpy = spyOn(appsProcessService, 'getDeployedApplications').and.returnValue(throwError(applicationsError));
component.showSelectApplicationDropdown = true;
component.appId = 3;
component.ngOnInit();
fixture.detectChanges();
await fixture.whenStable();
expect(errorSpy).toHaveBeenCalledWith(applicationsError);
});
it('should emit error event in case start process failed', async() => {
const errorSpy = spyOn(component.error, 'emit');
getDefinitionsSpy.and.returnValue(of(testMultipleProcessDefs));
getDeployedApplicationsSpy = spyOn(appsProcessService, 'getDeployedApplications').and.returnValue(of(deployedApps));
startProcessSpy.and.returnValue(throwError(startProcessError));
component.showSelectApplicationDropdown = true;
component.processDefinitionName = 'My Process 1';
component.name = 'mock name';
component.appId = 3;
component.ngOnInit();
fixture.detectChanges();
await fixture.whenStable();
component.startProcess();
fixture.detectChanges();
expect(errorSpy).toHaveBeenCalledWith(startProcessError);
});
});
}); | the_stack |
import _ from 'lodash'
import { ObjectType, ElemID, BuiltinTypes, PrimitiveType, PrimitiveTypes, isObjectType, InstanceElement, isInstanceElement, CORE_ANNOTATIONS, DetailedChange, getChangeElement, INSTANCE_ANNOTATIONS, ReferenceExpression } from '@salto-io/adapter-api'
import { collections } from '@salto-io/lowerdash'
import { mockState } from '../common/state'
import { MergeResult } from '../../src/merger'
import { mergeWithHidden, handleHiddenChanges } from '../../src/workspace/hidden_values'
import { createInMemoryElementSource } from '../../src/workspace/elements_source'
const { awu } = collections.asynciterable
describe('mergeWithHidden', () => {
const getFieldType = (typeName: string, primitive: PrimitiveTypes): PrimitiveType => (
new PrimitiveType({
elemID: new ElemID('test', typeName),
primitive,
annotationRefsOrTypes: { hiddenAnno: BuiltinTypes.HIDDEN_STRING },
})
)
describe('when parent value is deleted in the workspace', () => {
let result: MergeResult
beforeEach(async () => {
const fieldType = getFieldType('text', PrimitiveTypes.STRING)
const mockObjType = new ObjectType({
elemID: new ElemID('test', 'type'),
fields: {
f1: {
refType: fieldType,
annotations: { hiddenAnno: 'asd' },
},
},
})
const workspaceObjType = mockObjType.clone()
delete workspaceObjType.fields.f1
result = await mergeWithHidden(
awu([fieldType, workspaceObjType]),
createInMemoryElementSource([fieldType, mockObjType])
)
})
it('should omit the hidden value', async () => {
const mergedWorkspaceObj = (await awu(result.merged.values())
.find(isObjectType)) as ObjectType
expect(mergedWorkspaceObj?.fields).not.toHaveProperty('f1')
})
})
describe('when field type is changed in the workspace', () => {
let result: MergeResult
beforeEach(async () => {
const workspaceFieldType = getFieldType('num', PrimitiveTypes.NUMBER)
const workspaceType = new ObjectType({
elemID: new ElemID('test', 'type'),
fields: {
test: { refType: workspaceFieldType },
},
})
const stateFieldType = getFieldType('text', PrimitiveTypes.STRING)
const stateType = new ObjectType({
...workspaceType,
fields: {
test: {
refType: stateFieldType,
annotations: { hiddenAnno: 'asd' },
},
},
})
result = await mergeWithHidden(
awu([workspaceFieldType, workspaceType]),
createInMemoryElementSource([stateFieldType, stateType])
)
})
it('should not have merge errors', async () => {
expect(await awu(result.errors.values()).flat().toArray()).toHaveLength(0)
})
it('should still add hidden annotations to the field', async () => {
const type = (await awu(result.merged.values()).find(isObjectType)) as ObjectType
expect(type?.fields.test.annotations).toHaveProperty('hiddenAnno', 'asd')
})
})
describe('hidden_string in instance annotation', () => {
let result: MergeResult
beforeEach(async () => {
const workspaceInstance = new InstanceElement(
'instance',
new ObjectType({
elemID: new ElemID('test', 'type'),
}),
)
const stateInstance = new InstanceElement(
'instance',
new ObjectType({
elemID: new ElemID('test', 'type'),
}),
{},
undefined,
{ [CORE_ANNOTATIONS.SERVICE_URL]: 'someUrl' }
)
result = await mergeWithHidden(
awu([workspaceInstance]),
createInMemoryElementSource([stateInstance])
)
})
it('should not have merge errors', async () => {
expect(await awu(result.errors.values()).flat().toArray()).toHaveLength(0)
})
it('should have the hidden_string value', async () => {
const instance = await awu(result.merged.values()).find(isInstanceElement)
expect(instance?.annotations?.[CORE_ANNOTATIONS.SERVICE_URL]).toBe('someUrl')
})
})
describe('hidden annotation in field', () => {
let result: MergeResult
beforeEach(async () => {
const workspaceObject = new ObjectType({
elemID: new ElemID('test', 'type'),
fields: {
field: {
refType: BuiltinTypes.STRING,
},
},
})
const stateObject = new ObjectType({
elemID: new ElemID('test', 'type'),
fields: {
field: {
refType: BuiltinTypes.STRING,
annotations: { [CORE_ANNOTATIONS.SERVICE_URL]: 'someUrl' },
},
},
})
result = await mergeWithHidden(
awu([workspaceObject]),
createInMemoryElementSource([stateObject])
)
})
it('should not have merge errors', async () => {
expect(await awu(result.errors.values()).flat().isEmpty()).toBeTruthy()
})
it('should have the hidden annotation value', async () => {
const object = await awu(result.merged.values()).find(isObjectType) as ObjectType
expect(object?.fields?.field?.annotations?.[CORE_ANNOTATIONS.SERVICE_URL]).toBe('someUrl')
})
})
})
describe('handleHiddenChanges', () => {
describe('hidden_string in instance annotations', () => {
let instance: InstanceElement
let instanceType: ObjectType
beforeEach(() => {
instanceType = new ObjectType({
elemID: new ElemID('test', 'type'),
fields: {
val: { refType: BuiltinTypes.STRING },
},
})
instance = new InstanceElement(
'instance',
instanceType,
{ val: 'asd' },
undefined,
{ [CORE_ANNOTATIONS.SERVICE_URL]: 'someUrl' }
)
})
describe('when adding the whole instance', () => {
let result: { visible: DetailedChange[]; hidden: DetailedChange[] }
let visibleInstance: InstanceElement
let hiddenInstance: InstanceElement
beforeEach(async () => {
const change: DetailedChange = {
id: instance.elemID,
action: 'add',
data: { after: instance },
}
result = await handleHiddenChanges(
[change],
mockState(),
createInMemoryElementSource(),
)
expect(result.visible).toHaveLength(1)
expect(result.hidden).toHaveLength(1)
visibleInstance = getChangeElement(result.visible[0])
hiddenInstance = getChangeElement(result.hidden[0])
})
it('should omit the hidden annotation from visible and add it to hidden', () => {
expect(visibleInstance.annotations).not.toHaveProperty(INSTANCE_ANNOTATIONS.SERVICE_URL)
expect(hiddenInstance.annotations).toHaveProperty(INSTANCE_ANNOTATIONS.SERVICE_URL)
})
it('should keep non hidden values in visible and omit them from hidden', () => {
expect(visibleInstance.value).toHaveProperty('val', 'asd')
expect(hiddenInstance.value).not.toHaveProperty('val', 'asd')
})
})
describe('when adding only the hidden annotation', () => {
let result: { visible: DetailedChange[]; hidden: DetailedChange[]}
beforeAll(async () => {
const change: DetailedChange = {
id: instance.elemID.createNestedID(INSTANCE_ANNOTATIONS.SERVICE_URL),
action: 'add',
data: { after: instance.annotations[INSTANCE_ANNOTATIONS.SERVICE_URL] },
}
result = await handleHiddenChanges(
[change],
mockState([instanceType, instance]),
createInMemoryElementSource(),
)
})
it('should not have a visible change', () => {
expect(result.visible).toHaveLength(0)
})
it('should have a hidden change', () => {
expect(result.hidden).toHaveLength(1)
expect(_.get(result.hidden[0].data, 'after')).toEqual('someUrl')
})
})
describe('when converting a remove change', () => {
const obj = new ObjectType({
elemID: new ElemID('salto', 'obj'),
})
const inst = new InstanceElement('hidden', obj, {}, [], {
[INSTANCE_ANNOTATIONS.HIDDEN]: true,
})
const change: DetailedChange = {
id: inst.elemID,
action: 'remove',
data: {
before: inst,
},
}
it('should return the entire change and both hidden and visible', async () => {
const res = (await handleHiddenChanges(
[change],
mockState([instanceType, instance]),
createInMemoryElementSource(),
))
expect(res.visible).toHaveLength(1)
expect(res.hidden).toHaveLength(1)
expect(res.hidden[0].id).toEqual(change.id)
expect(res.visible[0].id).toEqual(change.id)
})
})
})
describe('hidden annotation of field', () => {
let result: { visible: DetailedChange[]; hidden: DetailedChange[]}
beforeAll(async () => {
const object = new ObjectType({
elemID: new ElemID('test', 'type'),
fields: {
field: {
refType: BuiltinTypes.STRING,
annotations: { [CORE_ANNOTATIONS.SERVICE_URL]: 'someUrl' },
},
},
})
const change: DetailedChange = {
id: object.fields.field.elemID.createNestedID(CORE_ANNOTATIONS.SERVICE_URL),
action: 'add',
data: { after: 'someUrl' },
}
result = await handleHiddenChanges(
[change],
mockState([object]),
createInMemoryElementSource(),
)
})
it('should not have a visible change', () => {
expect(result.visible).toHaveLength(0)
})
it('should have a hidden change', () => {
expect(result.hidden).toHaveLength(1)
expect(_.get(result.hidden[0].data, 'after')).toEqual('someUrl')
})
})
describe('reference expression', () => {
let instance: InstanceElement
beforeEach(() => {
const refTargetType = new ObjectType({ elemID: new ElemID('test', 'refTarget') })
instance = new InstanceElement(
'instance',
new ObjectType({
elemID: new ElemID('test', 'type'),
fields: {
val: { refType: refTargetType },
ref: { refType: refTargetType },
},
}),
{ val: 'asd' },
)
})
describe('when adding a reference expression', () => {
let result: { visible: DetailedChange[]; hidden: DetailedChange[]}
let filteredValue: unknown
beforeEach(async () => {
const change: DetailedChange = {
id: instance.elemID.createNestedID('ref'),
action: 'add',
data: {
after: new ReferenceExpression(new ElemID('a', 'b')),
},
}
result = await handleHiddenChanges(
[change],
mockState([instance]),
createInMemoryElementSource(),
)
expect(result.visible).toHaveLength(1)
expect(result.hidden).toHaveLength(0)
filteredValue = getChangeElement(result.visible[0])
})
it('should keep the reference expression as-is', () => {
expect(filteredValue).toBeInstanceOf(ReferenceExpression)
})
})
describe('when converting a value to a reference expression', () => {
let result: { visible: DetailedChange[]; hidden: DetailedChange[]}
let filteredValue: unknown
beforeEach(async () => {
const change: DetailedChange = {
id: instance.elemID.createNestedID('val'),
action: 'modify',
data: {
before: 'asd',
after: new ReferenceExpression(new ElemID('a', 'b')),
},
}
result = await handleHiddenChanges(
[change],
mockState([instance]),
createInMemoryElementSource(),
)
expect(result.visible).toHaveLength(1)
expect(result.hidden).toHaveLength(0)
filteredValue = getChangeElement(result.visible[0])
})
it('should keep the updated value as a reference expression', () => {
expect(filteredValue).toBeInstanceOf(ReferenceExpression)
})
})
})
describe('undefined values', () => {
const workspaceInstance = new InstanceElement(
'instance',
new ObjectType({
elemID: new ElemID('test', 'type'),
}),
{ [CORE_ANNOTATIONS.GENERATED_DEPENDENCIES]: [{ reference: 'aaa', occurrences: undefined }] },
)
const change: DetailedChange = {
id: workspaceInstance.elemID,
action: 'add',
data: { after: workspaceInstance },
}
it('should not hide anything if there is no hidden part, even if nested values are undefined', async () => {
const result = await handleHiddenChanges(
[change],
mockState([]),
createInMemoryElementSource(),
)
expect(result.visible.length).toBe(1)
expect(result.hidden.length).toBe(0)
})
})
describe('with nested visible change', () => {
const type = new ObjectType({
elemID: new ElemID('test', 'type'),
fields: {
val: { refType: new ObjectType({
elemID: new ElemID('test', 'type'),
fields: { inner: { refType: BuiltinTypes.STRING } },
}) },
},
})
const stateInstance = new InstanceElement('instance', type, {})
const change: DetailedChange = {
id: stateInstance.elemID.createNestedID('val'),
action: 'add',
data: {
after: { inner: 'abc' },
},
}
it('should not have a hidden change', async () => {
const result = await handleHiddenChanges(
[change],
mockState([stateInstance]),
createInMemoryElementSource(),
)
expect(result.visible.length).toBe(1)
expect(result.hidden.length).toBe(0)
})
})
}) | the_stack |
import io from 'console-read-write'
import BN from 'bn.js'
import HDWalletProvider from '@truffle/hdwallet-provider'
import Web3 from 'web3'
import { Contract } from 'web3-eth-contract'
import { HttpProvider } from 'web3-core'
import { fromWei, toBN, toHex } from 'web3-utils'
import ow from 'ow'
import { ether, isSameAddress, sleep } from '@opengsn/common/dist/Utils'
// compiled folder populated by "preprocess"
import StakeManager from './compiled/StakeManager.json'
import RelayHub from './compiled/RelayHub.json'
import RelayRegistrar from './compiled/RelayRegistrar.json'
import Penalizer from './compiled/Penalizer.json'
import Paymaster from './compiled/TestPaymasterEverythingAccepted.json'
import Forwarder from './compiled/Forwarder.json'
import WrappedEthToken from './compiled/WrappedEthToken.json'
import { Address, IntString } from '@opengsn/common/dist/types/Aliases'
import { ContractInteractor } from '@opengsn/common/dist/ContractInteractor'
import { HttpClient } from '@opengsn/common/dist/HttpClient'
import { constants } from '@opengsn/common/dist/Constants'
import { RelayHubConfiguration } from '@opengsn/common/dist/types/RelayHubConfiguration'
import { registerForwarderForGsn } from '@opengsn/common/dist/EIP712/ForwarderUtil'
import { LoggerInterface } from '@opengsn/common/dist/LoggerInterface'
import { HttpWrapper } from '@opengsn/common/dist/HttpWrapper'
import { GSNContractsDeployment } from '@opengsn/common/dist/GSNContractsDeployment'
import { defaultEnvironment } from '@opengsn/common/dist/Environments'
import { PenalizerConfiguration } from '@opengsn/common/dist/types/PenalizerConfiguration'
import { KeyManager } from '@opengsn/relay/dist/KeyManager'
import { ServerConfigParams } from '@opengsn/relay/dist/ServerConfigParams'
import { Transaction, TypedTransaction } from '@ethereumjs/tx'
import { formatTokenAmount, toNumber } from '@opengsn/common'
export interface RegisterOptions {
/** ms to sleep if waiting for RelayServer to set its owner */
sleepMs: number
/** number of times to sleep before timeout */
sleepCount: number
from: Address
token?: Address
gasPrice?: string | BN
stake: string
wrap: boolean
funds: string | BN
relayUrl: string
unstakeDelay: string
}
export interface WithdrawOptions {
withdrawAmount: BN
keyManager: KeyManager
config: ServerConfigParams
broadcast: boolean
gasPrice?: BN
useAccountBalance: boolean
}
interface DeployOptions {
from: Address
gasPrice: string
gasLimit: number | IntString
deployPaymaster?: boolean
forwarderAddress?: string
relayHubAddress?: string
relayRegistryAddress?: string
stakeManagerAddress?: string
deployTestToken?: boolean
stakingTokenAddress?: string
minimumTokenStake: number | IntString
penalizerAddress?: string
burnAddress?: string
devAddress?: string
verbose?: boolean
skipConfirmation?: boolean
relayHubConfiguration: RelayHubConfiguration
penalizerConfiguration: PenalizerConfiguration
}
/**
* Must verify these parameters are passed to deploy script
*/
const DeployOptionsPartialShape = {
from: ow.string,
gasPrice: ow.string
}
interface RegistrationResult {
success: boolean
transactions?: string[]
error?: string
}
type WithdrawalResult = RegistrationResult
export interface SendOptions {
from: string
gasPrice: number | string | BN
gas: number | string | BN
value: number | string | BN
}
export class CommandsLogic {
private readonly contractInteractor: ContractInteractor
private readonly httpClient: HttpClient
private readonly web3: Web3
private deployment?: GSNContractsDeployment
constructor (
host: string,
logger: LoggerInterface,
deployment: GSNContractsDeployment,
mnemonic?: string
) {
let provider: HttpProvider | HDWalletProvider = new Web3.providers.HttpProvider(host, {
keepAlive: true,
timeout: 120000
})
if (mnemonic != null) {
// web3 defines provider type quite narrowly
provider = new HDWalletProvider(mnemonic, provider) as unknown as HttpProvider
}
this.httpClient = new HttpClient(new HttpWrapper(), logger)
const maxPageSize = Number.MAX_SAFE_INTEGER
const environment = defaultEnvironment
this.contractInteractor = new ContractInteractor({ provider, logger, deployment, maxPageSize, environment })
this.deployment = deployment
this.web3 = new Web3(provider)
}
async init (): Promise<this> {
await this.contractInteractor.init()
return this
}
async findWealthyAccount (requiredBalance = ether('2')): Promise<string> {
let accounts: string[] = []
try {
accounts = await this.web3.eth.getAccounts()
for (const account of accounts) {
const balance = new BN(await this.web3.eth.getBalance(account))
if (balance.gte(requiredBalance)) {
console.log(`Found funded account ${account}`)
return account
}
}
} catch (error) {
console.error('Failed to retrieve accounts and balances:', error)
}
throw new Error(`could not find unlocked account with sufficient balance; all accounts:\n - ${accounts.join('\n - ')}`)
}
async isRelayReady (relayUrl: string): Promise<boolean> {
const response = await this.httpClient.getPingResponse(relayUrl)
return response.ready
}
async waitForRelay (relayUrl: string, timeout = 60): Promise<void> {
console.error(`Will wait up to ${timeout}s for the relay to be ready`)
const endTime = Date.now() + timeout * 1000
while (Date.now() < endTime) {
let isReady = false
try {
isReady = await this.isRelayReady(relayUrl)
} catch (e: any) {
console.log(e.message)
}
if (isReady) {
return
}
await sleep(3000)
}
throw Error(`Relay not ready after ${timeout}s`)
}
async getPaymasterBalance (paymaster: Address): Promise<BN> {
if (this.deployment == null) {
throw new Error('Deployment is not initialized!')
}
return await this.contractInteractor.hubBalanceOf(paymaster)
}
/**
* Send enough ether from the {@param from} to the RelayHub to make {@param paymaster}'s gas deposit exactly {@param amount}.
* Does nothing if current paymaster balance exceeds amount.
* @param from
* @param paymaster
* @param amount
* @return deposit of the paymaster after
*/
async fundPaymaster (
from: Address, paymaster: Address, amount: string | BN
): Promise<BN> {
if (this.deployment == null) {
throw new Error('Deployment is not initialized!')
}
const currentBalance = await this.contractInteractor.hubBalanceOf(paymaster)
const targetAmount = new BN(amount)
if (currentBalance.lt(targetAmount)) {
const value = targetAmount.sub(currentBalance)
await this.contractInteractor.hubDepositFor(paymaster, {
value,
from
})
return targetAmount
} else {
return currentBalance
}
}
async registerRelay (options: RegisterOptions): Promise<RegistrationResult> {
const transactions: string[] = []
try {
console.log(`Registering GSN relayer at ${options.relayUrl}`)
const gasPrice = toHex(options.gasPrice ?? toBN(await this.getGasPrice()))
const sendOptions: any = {
chainId: toHex(await this.web3.eth.getChainId()),
from: options.from,
gas: 1e6,
gasPrice
}
const response = await this.httpClient.getPingResponse(options.relayUrl)
.catch((error: any) => {
console.error(error)
throw new Error('could contact not relayer, is it running?')
})
if (response.ready) {
return {
success: false,
error: 'Nothing to do. Relayer already registered'
}
}
const chainId = this.contractInteractor.chainId
if (response.chainId !== chainId.toString()) {
throw new Error(`wrong chain-id: Relayer on (${response.chainId}) but our provider is on (${chainId})`)
}
const relayAddress = response.relayManagerAddress
const relayHubAddress = response.relayHubAddress
const relayHub = await this.contractInteractor._createRelayHub(relayHubAddress)
const stakeManagerAddress = await relayHub.getStakeManager()
const stakeManager = await this.contractInteractor._createStakeManager(stakeManagerAddress)
const { stake, unstakeDelay, owner, token } = (await stakeManager.getStakeInfo(relayAddress))[0]
let stakingToken = options.token
if (stakingToken == null) {
stakingToken = await this._findFirstToken(relayHubAddress)
}
if (!(isSameAddress(token, stakingToken) || isSameAddress(token, constants.ZERO_ADDRESS))) {
throw new Error(`Cannot use token ${stakingToken}. Relayer already uses token: ${token}`)
}
const stakingTokenContract = await this.contractInteractor._createERC20(stakingToken)
const tokenDecimals = await stakingTokenContract.decimals()
const tokenSymbol = await stakingTokenContract.symbol()
const stakeParam = toBN(toNumber(options.stake) * Math.pow(10, tokenDecimals.toNumber()))
const formatToken = (val: any): string => formatTokenAmount(toBN(val.toString()), tokenDecimals, tokenSymbol)
console.log('current stake= ', formatToken(stake))
if (owner !== constants.ZERO_ADDRESS && !isSameAddress(owner, options.from)) {
throw new Error(`Already owned by ${owner}, our account=${options.from}`)
}
const bal = await this.contractInteractor.getBalance(relayAddress)
if (toBN(bal).gt(toBN(options.funds.toString()))) {
console.log('Relayer already funded')
} else {
console.log('Funding relayer')
const fundTx = await this.web3.eth.sendTransaction({
...sendOptions,
to: relayAddress,
value: options.funds
})
if (fundTx.transactionHash == null) {
return {
success: false,
error: `Fund transaction reverted: ${JSON.stringify(fundTx)}`
}
}
transactions.push(fundTx.transactionHash)
}
if (owner === constants.ZERO_ADDRESS) {
let i = 0
while (true) {
console.debug(`Waiting ${options.sleepMs}ms ${i}/${options.sleepCount} for relayer to set ${options.from} as owner`)
await sleep(options.sleepMs)
const newStakeInfo = (await stakeManager.getStakeInfo(relayAddress))[0]
if (newStakeInfo.owner !== constants.ZERO_ADDRESS && isSameAddress(newStakeInfo.owner, options.from)) {
console.log('RelayServer successfully set its owner on the StakeManager')
break
}
if (options.sleepCount === i++) {
throw new Error('RelayServer failed to set its owner on the StakeManager')
}
}
}
if (unstakeDelay.gte(toBN(options.unstakeDelay)) &&
stake.gte(stakeParam)
) {
console.log('Relayer already staked')
} else {
const config = await relayHub.getConfiguration()
const minimumStakeForToken = await relayHub.getMinimumStakePerToken(stakingToken)
if (minimumStakeForToken.gt(toBN(stakeParam.toString()))) {
throw new Error(`Given stake ${formatToken(stakeParam)} too low for the given hub ${formatToken(minimumStakeForToken)} and token ${stakingToken}`)
}
if (minimumStakeForToken.eqn(0)) {
throw new Error(`Selected token (${stakingToken}) is not allowed in the current RelayHub`)
}
if (config.minimumUnstakeDelay.gt(toBN(options.unstakeDelay))) {
throw new Error(`Given minimum unstake delay ${options.unstakeDelay.toString()} too low for the given hub ${config.minimumUnstakeDelay.toString()}`)
}
const stakeValue = stakeParam.sub(stake)
console.log(`Staking relayer ${formatToken(stakeValue)}`,
stake.toString() === '0' ? '' : ` (already has ${formatToken(stake)})`)
const tokenBalance = await stakingTokenContract.balanceOf(options.from)
if (tokenBalance.lt(stakeValue) && options.wrap) {
// default token is wrapped eth, so deposit eth to make then into tokens.
console.log(`Wrapping ${formatToken(stakeValue)}`)
let depositTx: any
try {
depositTx = await stakingTokenContract.deposit({
...sendOptions,
from: options.from,
value: stakeValue
}) as any
} catch (e) {
throw new Error('No deposit() method on default token. is it wrapped ETH?')
}
transactions.push(depositTx.transactionHash)
}
const currentAllowance = await stakingTokenContract.allowance(options.from, stakeManager.address)
console.log('Current allowance', formatToken(currentAllowance))
if (currentAllowance.lt(stakeValue)) {
console.log(`Approving ${formatToken(stakeValue)} to StakeManager`)
const approveTx = await stakingTokenContract.approve(stakeManager.address, stakeValue, {
...sendOptions,
from: options.from
})
// @ts-ignore
transactions.push(approveTx.transactionHash)
}
const stakeTx = await stakeManager
.stakeForRelayManager(stakingToken, relayAddress, options.unstakeDelay.toString(), stakeValue, {
...sendOptions
})
// @ts-ignore
transactions.push(stakeTx.transactionHash)
}
try {
await relayHub.verifyRelayManagerStaked(relayAddress)
console.log('Relayer already authorized')
} catch (e: any) {
// hide expected error
if (e.message.match(/not authorized/) == null) {
console.log('verifyRelayManagerStaked reverted with:', e.message)
}
console.log('Authorizing relayer for hub')
const authorizeTx = await stakeManager
.authorizeHubByOwner(relayAddress, relayHubAddress, sendOptions)
// @ts-ignore
transactions.push(authorizeTx.transactionHash)
}
await this.waitForRelay(options.relayUrl)
return {
success: true,
transactions
}
} catch (error: any) {
console.log(error)
return {
success: false,
transactions,
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
error: error.message
}
}
}
async _findFirstToken (relayHubAddress: string): Promise<string> {
const relayHub = await this.contractInteractor._createRelayHub(relayHubAddress)
const fromBlock = await relayHub.getCreationBlock()
const toBlock = Math.min(toNumber(fromBlock) + 5000, await this.contractInteractor.getBlockNumber())
const tokens = await this.contractInteractor.getPastEventsForHub([], { fromBlock, toBlock }, ['StakingTokenDataChanged'])
if (tokens.length === 0) {
throw new Error(`no registered staking tokens on relayhub ${relayHubAddress}`)
}
return tokens[0].returnValues.token
}
async displayManagerBalances (config: ServerConfigParams, keyManager: KeyManager): Promise<void> {
const relayManager = keyManager.getAddress(0)
console.log('relayManager is', relayManager)
const relayHub = await this.contractInteractor._createRelayHub(config.relayHubAddress)
const accountBalance = toBN(await this.contractInteractor.getBalance(relayManager))
console.log(`Relay manager account balance is ${fromWei(accountBalance)}eth`)
const hubBalance = await relayHub.balanceOf(relayManager)
console.log(`Relay manager hub balance is ${fromWei(hubBalance)}eth`)
}
async withdrawToOwner (options: WithdrawOptions): Promise<WithdrawalResult> {
const transactions: string[] = []
try {
console.log('Withdrawing from GSN relayer to owner')
const relayManager = options.keyManager.getAddress(0)
console.log('relayManager is', relayManager)
const relayHub = await this.contractInteractor._createRelayHub(options.config.relayHubAddress)
const stakeManagerAddress = await relayHub.getStakeManager()
const stakeManager = await this.contractInteractor._createStakeManager(stakeManagerAddress)
const { owner } = (await stakeManager.getStakeInfo(relayManager))[0]
if (owner.toLowerCase() !== options.config.ownerAddress.toLowerCase()) {
throw new Error(`Owner in relayHub ${owner} is different than in server config ${options.config.ownerAddress}`)
}
const nonce = await this.contractInteractor.getTransactionCount(relayManager)
const gasPrice = toHex(options.gasPrice ?? toBN(await this.getGasPrice()))
const gasLimit = 1e5
let txToSign: TypedTransaction
if (options.useAccountBalance) {
const balance = toBN(await this.contractInteractor.getBalance(relayManager))
console.log(`Relay manager account balance is ${fromWei(balance)}eth`)
if (balance.lt(options.withdrawAmount)) {
throw new Error('Relay manager account balance lower than withdrawal amount')
}
const web3TxData = {
to: options.config.ownerAddress,
value: options.withdrawAmount,
gas: gasLimit,
gasPrice,
nonce
}
console.log('Calling in view mode')
await this.contractInteractor.web3.eth.call({ ...web3TxData })
const txData = { ...web3TxData, gasLimit: web3TxData.gas }
// @ts-ignore
delete txData.gas
txToSign = new Transaction(txData, this.contractInteractor.getRawTxOptions())
} else {
const balance = await relayHub.balanceOf(relayManager)
console.log(`Relay manager hub balance is ${fromWei(balance)}eth`)
if (balance.lt(options.withdrawAmount)) {
throw new Error('Relay manager hub balance lower than withdrawal amount')
}
const method = relayHub.contract.methods.withdraw(owner, options.withdrawAmount)
const encodedCall = method.encodeABI()
txToSign = new Transaction({
to: options.config.relayHubAddress,
value: 0,
gasLimit,
gasPrice,
data: Buffer.from(encodedCall.slice(2), 'hex'),
nonce
}, this.contractInteractor.getRawTxOptions())
console.log('Calling in view mode')
await method.call({
from: relayManager,
to: options.config.relayHubAddress,
value: 0,
gas: gasLimit,
gasPrice
})
}
console.log('Signing tx', txToSign.toJSON())
const signedTx = options.keyManager.signTransaction(relayManager, txToSign)
console.log(`signed withdrawal hex tx: ${signedTx.rawTx}`)
if (options.broadcast) {
console.log('broadcasting tx')
const txHash = await this.contractInteractor.broadcastTransaction(signedTx.rawTx)
transactions.push(txHash)
}
return {
success: true,
transactions
}
} catch (e: any) {
return {
success: false,
transactions,
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
error: e.message
}
}
}
contract (file: any, address?: string): Contract {
const abi = file.abi ?? file
return new this.web3.eth.Contract(abi, address, { data: file.bytecode })
}
async deployGsnContracts (deployOptions: DeployOptions): Promise<GSNContractsDeployment> {
ow(deployOptions, ow.object.partialShape(DeployOptionsPartialShape))
const options: Required<SendOptions> = {
from: deployOptions.from,
gas: deployOptions.gasLimit,
value: 0,
gasPrice: deployOptions.gasPrice
}
const rrInstance = await this.getContractInstance(RelayRegistrar, {
arguments: []
}, deployOptions.relayRegistryAddress, { ...options }, deployOptions.skipConfirmation)
const sInstance = await this.getContractInstance(StakeManager, {
arguments: [defaultEnvironment.maxUnstakeDelay, defaultEnvironment.abandonmentDelay, defaultEnvironment.escheatmentDelay, deployOptions.burnAddress, deployOptions.devAddress]
}, deployOptions.stakeManagerAddress, { ...options }, deployOptions.skipConfirmation)
const pInstance = await this.getContractInstance(Penalizer, {
arguments: [
deployOptions.penalizerConfiguration.penalizeBlockDelay,
deployOptions.penalizerConfiguration.penalizeBlockExpiration
]
}, deployOptions.penalizerAddress, { ...options }, deployOptions.skipConfirmation)
const fInstance = await this.getContractInstance(Forwarder, {}, deployOptions.forwarderAddress, { ...options }, deployOptions.skipConfirmation)
// TODO: add support to passing '--batchGatewayAddress'
const batchGatewayAddress = constants.ZERO_ADDRESS
const rInstance = await this.getContractInstance(RelayHub, {
arguments: [
sInstance.options.address,
pInstance.options.address,
batchGatewayAddress,
rrInstance.options.address,
deployOptions.relayHubConfiguration
]
}, deployOptions.relayHubAddress, { ...options }, deployOptions.skipConfirmation)
if (!isSameAddress(await rInstance.methods.getRelayRegistrar().call(), rrInstance.options.address)) {
await rInstance.methods.setRegistrar(rrInstance.options.address).send({ ...options })
}
let pmInstance: Contract | undefined
if (deployOptions.deployPaymaster ?? false) {
pmInstance = await this.deployPaymaster({ ...options }, rInstance.options.address, fInstance, deployOptions.skipConfirmation)
}
await registerForwarderForGsn(fInstance, options)
let stakingTokenAddress = deployOptions.stakeManagerAddress ?? ''
let ttInstance: Contract | undefined
if (deployOptions.deployTestToken ?? false) {
ttInstance = await this.getContractInstance(WrappedEthToken, {}, undefined, { ...options }, deployOptions.skipConfirmation)
console.log('Setting minimum stake of 1 TestWeth on Hub')
await rInstance.methods.setMinimumStakes([ttInstance.options.address], [1e18.toString()]).send({ ...options })
stakingTokenAddress = ttInstance.options.address
}
const stakingContact = await this.contractInteractor._createERC20(stakingTokenAddress)
const tokenDecimals = await stakingContact.decimals()
const tokenSymbol = await stakingContact.symbol()
const formatToken = (val: any): string => formatTokenAmount(toBN(val.toString()), tokenDecimals, tokenSymbol)
console.log(`Setting minimum stake of ${formatToken(deployOptions.minimumTokenStake)}`)
await rInstance.methods.setMinimumStakes([stakingTokenAddress], [deployOptions.minimumTokenStake]).send({ ...options })
this.deployment = {
relayHubAddress: rInstance.options.address,
stakeManagerAddress: sInstance.options.address,
penalizerAddress: pInstance.options.address,
relayRegistrarAddress: rrInstance.options.address,
forwarderAddress: fInstance.options.address,
managerStakeTokenAddress: stakingTokenAddress,
paymasterAddress: pmInstance?.options.address ?? constants.ZERO_ADDRESS
}
await this.contractInteractor.initDeployment(this.deployment)
return this.deployment
}
private async getContractInstance (json: any, constructorArgs: any, address: Address | undefined, options: Required<SendOptions>, skipConfirmation: boolean = false): Promise<Contract> {
const contractName: string = json.contractName
let contractInstance
if (address == null) {
const sendMethod = this
.contract(json)
.deploy(constructorArgs)
const estimatedGasCost = await sendMethod.estimateGas()
const maxCost = toBN(options.gasPrice.toString()).mul(toBN(options.gas.toString()))
console.log(`Deploying ${contractName} contract with gas limit of ${options.gas.toLocaleString()} at ${fromWei(options.gasPrice.toString(), 'gwei')}gwei (estimated gas: ${estimatedGasCost.toLocaleString()}) and maximum cost of ~ ${fromWei(maxCost)} ETH`)
if (!skipConfirmation) {
await this.confirm()
}
// @ts-ignore - web3 refuses to accept string as gas limit, and max for a number in BN is 0x4000000 (~67M)
const deployPromise = sendMethod.send({ ...options })
// eslint-disable-next-line @typescript-eslint/no-floating-promises
deployPromise.on('transactionHash', function (hash) {
console.log(`Transaction broadcast: ${hash}`)
})
// eslint-disable-next-line @typescript-eslint/no-floating-promises
deployPromise.on('error', function (err: Error) {
console.debug(`tx error: ${err.message}`)
})
contractInstance = await deployPromise
console.log(`Deployed ${contractName} at address ${contractInstance.options.address}\n\n`)
} else {
console.log(`Using ${contractName} at given address ${address}\n\n`)
contractInstance = this.contract(json, address)
}
return contractInstance
}
async deployPaymaster (options: Required<SendOptions>, hub: Address, fInstance: Contract, skipConfirmation: boolean | undefined): Promise<Contract> {
const pmInstance = await this.getContractInstance(Paymaster, {}, undefined, { ...options }, skipConfirmation)
await pmInstance.methods.setRelayHub(hub).send(options)
await pmInstance.methods.setTrustedForwarder(fInstance.options.address).send(options)
return pmInstance
}
async confirm (): Promise<void> {
let input
while (true) {
console.log('Confirm (yes/no)?')
input = await io.read()
if (input === 'yes') {
return
} else if (input === 'no') {
throw new Error('User rejected')
}
}
}
async getGasPrice (): Promise<string> {
const gasPrice = await this.contractInteractor.getGasPrice()
console.log(`Using network gas price of ${fromWei(gasPrice, 'gwei')}`)
return gasPrice
}
} | the_stack |
import hl=require("../highLevelAST");
import ll=require("../lowLevelAST");
import hlImpl=require("../highLevelImpl");
import jsyaml=require("../jsyaml/jsyaml2lowLevel");
import def=require("raml-definition-system");
import ramlService=def
import json2lowlevel = require('../jsyaml/json2lowLevel');
import universes = require("../tools/universe")
import universeHelpers = require("../tools/universeHelpers")
import services=def
import parserCore = require("./parserCore")
import search = require("../../search/search-interface")
import RamlWrapper10 = require("../artifacts/raml10parser")
import RamlWrapper08 = require("../artifacts/raml08parser")
export class AttributeDefaultsCalculator {
/**
/**
*
* @param enabled - if false, defaults calculator will not return defaults from
* attrValueOrDefault method, only original values.
* @constructor
*/
constructor(private enabled : boolean, private toHighLevel=false) {
this.valueCalculators = [
new RequiredPropertyCalculator(),
new TypePropertyCalculator(),
new DisplayNamePropertyCalculator(),
new MediaTypeCalculator(),
new SecuredByPropertyCalculator(this.toHighLevel),
new ProtocolsPropertyCalculator(),
new VersionParamEnumCalculator()
];
}
valueCalculators:ValueCalculator[]
/**
* These calculators are only applied when default calculator is generally disabled (this.enabled==false)
* and should cover the cases when we -need- to insert some calculated value in any case
* and helpers should be avoided for some reason.
* @type {UnconditionalRequiredPropertyCalculator[]}
*/
unconditionalValueCalculators:ValueCalculator[] = [
new UnconditionalRequiredPropertyCalculator(),
];
/**
* Return attribute default value if defaults calculator is enabled.
* If attribute value is null or undefined, returns attribute default.
*/
attributeDefaultIfEnabled(node : hl.IHighLevelNode, attributeProperty : hl.IProperty) : any {
if (!this.enabled)
return this.getUnconditionalAttributeDefault(attributeProperty, node);
return this.getAttributeDefault(node, attributeProperty);
}
getUnconditionalAttributeDefault(attributeProperty: hl.IProperty, node : hl.IHighLevelNode) : any {
if (!node || !attributeProperty) return null;
for(var i = 0 ; i < this.unconditionalValueCalculators.length; i++){
var calculator = this.unconditionalValueCalculators[i];
if(calculator.matches(attributeProperty,node)){
var value = calculator.calculate(attributeProperty,node);
if(value != null){
return value;
}
}
}
return null;
}
/**
* Returns attribute default.
*/
getAttributeDefault(node : hl.IHighLevelNode, attributeProperty : hl.IProperty) : any {
if (!node || !attributeProperty) return null;
try {
return this.getAttributeDefault2(attributeProperty,node);
} catch (Error) {
console.log(Error)
return null;
}
}
getWrapperAttributeDefault(wrapperNode : parserCore.BasicNode, attributeName: string) {
var highLevelNode = wrapperNode.highLevel();
if (highLevelNode == null) return null;
var property = highLevelNode.definition().property(attributeName);
if (property == null) return null;
return this.getAttributeDefault(highLevelNode, property);
}
/**
* Returns attribute default.
* There are so many arguments instead of just providing a single AST node and getting
* anything we want from it as sometimes we create fake nodes in helpers and thus
* do not have actual high-level nodes at hands.
*/
getAttributeDefault2(attributeProperty: hl.IProperty, node : hl.IHighLevelNode) : any {
for(var i = 0 ; i < this.valueCalculators.length; i++){
var calculator = this.valueCalculators[i];
if(calculator.matches(attributeProperty,node)){
var value = calculator.calculate(attributeProperty,node);
if(value != null){
return value;
}
}
}
if(universeHelpers.isTypeProperty(attributeProperty)
&& node.attr("schema")
&& node.attr("schema").value()!=null){
return null;
}
//static values defined in definition system via defaultValue, defaultIntegerValue
// and defaultBooleanValue annotations.
if (attributeProperty.defaultValue() != null) {
return attributeProperty.defaultValue();
}
return null;
}
isEnabled() : boolean {
return this.enabled;
}
insertionKind(node : hl.IHighLevelNode, attributeProperty : hl.IProperty):InsertionKind{
for(var i = 0 ; i < this.valueCalculators.length; i++){
var calculator = this.valueCalculators[i];
if(calculator.matches(attributeProperty,node)){
return calculator.kind(node,attributeProperty);
}
}
if(attributeProperty.defaultValue() != null){
return InsertionKind.BY_DEFAULT;
}
return null;
}
}
export enum InsertionKind{
CALCULATED, BY_DEFAULT
}
export interface ValueCalculator{
calculate(attributeProperty: hl.IProperty, node:hl.IHighLevelNode):any;
matches(attributeProperty: hl.IProperty, node:hl.IHighLevelNode):boolean;
kind(node : hl.IHighLevelNode, attributeProperty : hl.IProperty):InsertionKind;
}
class MediaTypeCalculator implements ValueCalculator{
calculate(attributeProperty: hl.IProperty, node : hl.IHighLevelNode):any {
var root = search.declRoot(node);
if(root && universeHelpers.isApiSibling(root.definition())){
var defaultMediaTypeAttr = root.attr(universes.Universe10.Api.properties.mediaType.name);
if(defaultMediaTypeAttr){
return defaultMediaTypeAttr.value();
}
}
return null;
}
matches(attributeProperty: hl.IProperty, node : hl.IHighLevelNode):boolean{
if(!universeHelpers.isNameProperty(attributeProperty)){
return false;
}
var nodeDefinition = node.definition();
if(!nodeDefinition){
return false;
}
if(!(universeHelpers.isBodyLikeType(nodeDefinition)
|| universeHelpers.isTypeDeclarationSibling(nodeDefinition))){
return false;
}
var parentNode = node.parent();
if(parentNode==null){
return false;
}
var parentDefinition = parentNode.definition();
if(parentDefinition==null){
return false;
}
if(!(universeHelpers.isResponseType(parentDefinition)
|| universeHelpers.isMethodBaseSibling(parentDefinition))){
return false;
}
var ancestor = parentNode;
while(ancestor){
var aDef = ancestor.definition();
if(universeHelpers.isTraitType(aDef)){
return false;
}
if(universeHelpers.isResourceTypeType(aDef)){
return false;
}
ancestor = ancestor.parent();
}
return true;
}
kind(node : hl.IHighLevelNode, attributeProperty : hl.IProperty):InsertionKind{
return InsertionKind.CALCULATED;
}
}
class DisplayNamePropertyCalculator implements ValueCalculator{
calculate(attributeProperty: hl.IProperty, node : hl.IHighLevelNode):any {
var nodeDefinition = node.definition();
if(nodeDefinition==null){
return null;
}
var adapter = nodeDefinition.getAdapter(services.RAMLService);
var keyProperty = adapter.getKeyProp();
if (keyProperty != null) {
var attributeValue = node.attrValue(keyProperty.nameId());
if (attributeValue != null) {
return attributeValue;
}
else{
return new AttributeDefaultsCalculator(true).getAttributeDefault(node,keyProperty);
}
}
return null;
}
matches(attributeProperty: hl.IProperty, node : hl.IHighLevelNode):boolean{
var nodeDefinition = node.definition();
if(nodeDefinition==null){
return false;
}
return (universeHelpers.isTypeDeclarationSibling(nodeDefinition)
||nodeDefinition.isAssignableFrom(universes.Universe08.Parameter.name)
||universeHelpers.isResourceType(nodeDefinition))
&&universeHelpers.isDisplayNameProperty(attributeProperty);
}
kind(node : hl.IHighLevelNode, attributeProperty : hl.IProperty):InsertionKind{
return InsertionKind.CALCULATED;
}
}
class TypePropertyCalculator implements ValueCalculator{
calculate(attributeProperty: hl.IProperty, node : hl.IHighLevelNode):any {
if(node.attr("schema")&&node.attr("schema").value()!=null){
return null;//node.attr("schema").plainValue();
}
else if(node.lowLevel().children().filter(x=>x.key()=="properties").length) {
return "object";
}
else if(node.property() && node.property().nameId()=="body"){
return "any";
}
return "string";
}
matches(attributeProperty: hl.IProperty, node : hl.IHighLevelNode):boolean{
return universeHelpers.isTypeProperty(attributeProperty)
&& node.definition() != null
&& universeHelpers.isTypeDeclarationSibling(node.definition());
}
kind(node : hl.IHighLevelNode, attributeProperty : hl.IProperty):InsertionKind{
const schemaAttr = node.attr("schema");
if(schemaAttr && schemaAttr.value()){
return null;
}
return InsertionKind.BY_DEFAULT;
}
}
class RequiredPropertyCalculator implements ValueCalculator{
calculate(attributeProperty: hl.IProperty, node : hl.IHighLevelNode):any {
var nodeDefinition:hl.ITypeDefinition = node.definition();
var nodeProperty:hl.IProperty = node.property();
if (nodeDefinition == null) {
return null;
}
//if node key is ending with question mark, it optional, thus its "required" == false
var adapter = nodeDefinition.getAdapter(services.RAMLService);
var keyProperty = adapter.getKeyProp();
if (keyProperty != null) {
var attribute = node.attr(keyProperty.nameId());
if (attribute != null && attribute.optional()) {
return false;
}
}
if (nodeProperty != null) {
//the spec is unclear with regard to this parameter, but for now it looks like:
//for query string parameters, form parameters, and request and response headers the default is false
//for URI parameters the default is true
//for base URI parameters - unclear, but according to old JS parser behavior it looks like the default is true
//for all other entities we back drop to what definition system states
if (universeHelpers.isHeadersProperty(nodeProperty) ||
universeHelpers.isFormParametersProperty(nodeProperty) ||
universeHelpers.isQueryParametersProperty(nodeProperty)
) {
if (attributeProperty.domain().universe().version()=="RAML08"){
return false
}
return true;
} else if (universeHelpers.isUriParametersProperty(nodeProperty) ||
universeHelpers.isBaseUriParametersProperty(nodeProperty)) {
return true;
}
}
if (attributeProperty.defaultValue() != null) {
return attributeProperty.defaultValue();
}
return null;
}
matches(attributeProperty: hl.IProperty, node : hl.IHighLevelNode):boolean{
return universeHelpers.isRequiredProperty(attributeProperty);
}
kind(node : hl.IHighLevelNode, attributeProperty : hl.IProperty):InsertionKind{
if(universeHelpers.isRequiredProperty(attributeProperty)){
let nodeProp = node.property();
if(universeHelpers.isPropertiesProperty(nodeProp)
||universeHelpers.isHeadersProperty(nodeProp)
||universeHelpers.isBaseUriParametersProperty(nodeProp)
||universeHelpers.isUriParametersProperty(nodeProp)
||universeHelpers.isQueryParametersProperty(nodeProp)
){
if(node.lowLevel().optional()){
return null;
}
}
}
return InsertionKind.BY_DEFAULT;
}
}
class SecuredByPropertyCalculator implements ValueCalculator{
constructor(private toHighLevel = false){}
calculate(attributeProperty: def.IProperty, node : hl.IHighLevelNode):any {
if(universeHelpers.isApiSibling(node.definition())){
return null;
}
var values:any[];
//instanceof, but have to avoid direct usage of instanceof in JS.
var definition = node.definition();
if (universeHelpers.isMethodType(definition)) {
var resource = node.parent();
if (resource) {
let resourceSlave = resource.getLastSlaveCounterPart();
if (resourceSlave) resource = resourceSlave;
values = this.toHighLevel
? resource.attributes("securedBy")
: (<any>resource.wrapperNode()).securedBy();
}
}
if(!values || values.length == 0) {
while (node != null && !universeHelpers.isApiSibling(node.definition())) {
node = node.parent();
}
if(node){
let nodeSlave = node.getLastSlaveCounterPart();
if (nodeSlave) node = nodeSlave;
values = this.toHighLevel
? node.attributes("securedBy")
: (<any>node.wrapperNode()).securedBy();
}
}
if(values && values.length>0){
return values;
}
return null;
}
matches(attributeProperty: def.IProperty, node : hl.IHighLevelNode):boolean{
var nodeDefinition = node.definition();
if(nodeDefinition==null){
return false;
}
return universeHelpers.isSecuredByProperty(attributeProperty);
}
kind(node : hl.IHighLevelNode, attributeProperty : hl.IProperty):InsertionKind{
return InsertionKind.CALCULATED;
}
}
class ProtocolsPropertyCalculator implements ValueCalculator{
calculate(attributeProperty: def.IProperty, node : hl.IHighLevelNode):any {
while (node != null && !universeHelpers.isApiSibling(node.definition())) {
node = node.parent();
}
var result:string[];
var baseUriAttr = node.attr(universes.Universe10.Api.properties.baseUri.name);
if(baseUriAttr) {
var baseUri = baseUriAttr.value();
if (baseUri && typeof baseUri == "string") {
var ind = baseUri.indexOf('://');
if (ind >= 0) {
result = [baseUri.substring(0, ind).toUpperCase()];
}
if(!result){
result = [ 'HTTP' ];
}
}
}
return result;
}
matches(attributeProperty: def.IProperty, node : hl.IHighLevelNode):boolean{
if(!universeHelpers.isProtocolsProperty(attributeProperty)){
return false;
}
var nodeDefinition = node.definition();
var hasAppropriateLocation = false;
if(universeHelpers.isApiSibling(nodeDefinition)){
hasAppropriateLocation = true;
}
else if(universeHelpers.isResourceType(nodeDefinition)){
hasAppropriateLocation = true;
}
else if(universeHelpers.isMethodType(nodeDefinition)){
var parentNode = node.parent();
hasAppropriateLocation = parentNode && universeHelpers.isResourceType(parentNode.definition());
}
return hasAppropriateLocation;
}
kind(node : hl.IHighLevelNode, attributeProperty : hl.IProperty):InsertionKind{
return InsertionKind.CALCULATED;
}
}
class VersionParamEnumCalculator implements ValueCalculator{
calculate(attributeProperty: def.IProperty, node : hl.IHighLevelNode):any {
while (node != null && !universeHelpers.isApiSibling(node.definition())) {
node = node.parent();
}
var versionAttr = node.attr(universes.Universe10.Api.properties.version.name);
if(versionAttr) {
var versionValue = versionAttr.value();
if(versionValue && versionValue.trim()) {
return [versionValue];
}
}
return null;
}
matches(attributeProperty: def.IProperty, node : hl.IHighLevelNode):boolean{
if(!universeHelpers.isEnumProperty(attributeProperty)){
return false;
}
var nodeProperty = node.property();
if(!nodeProperty){
return false;
}
if(!universeHelpers.isBaseUriParametersProperty(nodeProperty)){
return false;
}
var nameAttr = node.attr(universes.Universe10.TypeDeclaration.properties.name.name);
var paramName = nameAttr && nameAttr.value();
if(paramName != 'version'){
return false;
}
return true;
}
kind(node : hl.IHighLevelNode, attributeProperty : hl.IProperty):InsertionKind{
return InsertionKind.CALCULATED;
}
}
/**
* This calculator inserts "required=false" if the key property ends with question mark.
* All other cases are handled in the regular RequiredPropertyCalculator
*/
class UnconditionalRequiredPropertyCalculator implements ValueCalculator{
calculate(attributeProperty: hl.IProperty, node : hl.IHighLevelNode):any {
var nodeDefinition:hl.ITypeDefinition = node.definition();
if (nodeDefinition == null) return null;
//if node key is ending with question mark, it optional, thus its "required" == false
var adapter = nodeDefinition.getAdapter(services.RAMLService);
if (adapter == null) return null;
var keyProperty = adapter.getKeyProp();
if (keyProperty == null) return null;
var attribute = node.attr(keyProperty.nameId());
if (attribute == null) return null;
if (attribute.optional()) return false;
return null;
}
matches(attributeProperty: hl.IProperty, node : hl.IHighLevelNode):boolean{
return universeHelpers.isRequiredProperty(attributeProperty);
}
kind(node : hl.IHighLevelNode, attributeProperty : hl.IProperty):InsertionKind{
return InsertionKind.BY_DEFAULT;
}
} | the_stack |
module Kiwi {
/**
* Each game contains a single Stage which controls the creation and
* management of main domElements required for a Kiwi game to work.
* This includes the Canvas and the rendering contexts,
* as well as the width/height of the game and the position it should be
* on the screen.
*
* @class Stage
* @namespace Kiwi
* @constructor
* @param game {Kiwi.Game} The game that this Stage belongs to.
* @param name {String} The name of the kiwi game.
* @param width {Number} The initial width of the game.
* @param height {Number} The initial heihgt of the game.
* @param scaleType {Number} The scale method that should be used for the game.
* @return {Kiwi.Stage}
*
*/
export class Stage {
constructor(game: Kiwi.Game, name: string, width: number, height: number, scaleType:number) {
this._game = game;
this.name = name;
this.domReady = false;
// Properties
this._alpha = 1;
this._x = 0;
this._y = 0;
this._width = width;
this._height = height;
this.color = "ffffff";
// CocoonJS should be black instead
if( this._game.deviceTargetOption === Kiwi.TARGET_COCOON) {
this.color = "000000";
}
this._scale = new Kiwi.Geom.Point(1, 1);
this._scaleType = scaleType;
this.onResize = new Kiwi.Signal();
this.onWindowResize = new Kiwi.Signal();
this.onFocus = new Kiwi.Signal();
this.onBlur = new Kiwi.Signal();
this.onVisibilityChange = new Kiwi.Signal();
this._renderer = null;
}
/**
* Returns the type of this object.
* @method objType
* @return {string} "Stage"
* @public
*/
public objType():string {
return "Stage";
}
/**
* The default width of the stage.
* @property DEFAULT_WIDTH
* @type number
* @default 800
* @public
* @static
*/
public static DEFAULT_WIDTH: number = 800;
/**
* The default height of the stage.
* @property DEFAULT_HEIGHT
* @type number
* @default 600
* @public
* @static
*/
public static DEFAULT_HEIGHT: number = 600;
/**
* The default scaling method used on Kiwi Games.
* This scaling method will set the container's width/height
* to static values.
*
* @property SCALE_NONE
* @type number
* @default 0
* @public
* @static
*/
public static SCALE_NONE: number = 0;
/**
* Scale Fit will scale the stage's width to fit its parents width.
* The height is then calculated to maintain the aspect ratio of the
* width/height of the Stage.
* @property SCALE_FIT
* @type number
* @default 1
* @public
* @static
*/
public static SCALE_FIT: number = 1;
/**
* Stretch will make the stage scale to fit its parents width/height
* (by using max/min height of 100%).
* If the parent doesn't have a height set then the height will be
* the height of the stage.
* @property SCALE_STRETCH
* @type number
* @default 2
* @public
* @static
*/
public static SCALE_STRETCH: number = 2;
/**
* Private property that holds the scaling method that should be
* applied to the container element.
* @property _scaleType
* @type number
* @default Kiwi.Stage.SCALE_NONE
* @private
*/
private _scaleType: number = Kiwi.Stage.SCALE_NONE;
/**
* Holds type of scaling that should be applied the container element.
* @property scaleType
* @type number
* @default Kiwi.Stage.SCALE_NONE
* @public
*/
public set scaleType(val: number) {
this._scaleType = val;
this._scaleContainer();
}
public get scaleType():number {
return this._scaleType;
}
/**
* The alpha of the stage.
* @property _alpha
* @type number
* @default 1
* @private
*/
private _alpha: number;
/**
* Sets the alpha of the container element.
* 0 = invisible, 1 = fully visible.
* Note: Because the alpha value is applied to the container,
* it will not work in CocoonJS.
*
* @property alpha
* @type number
* @default 1
* @public
*/
public get alpha():number {
return this._alpha;
}
public set alpha(value: number) {
if (this._game.deviceTargetOption === Kiwi.TARGET_BROWSER) {
this.container.style.opacity = String(Kiwi.Utils.GameMath.clamp(value, 1, 0));
}
// Doesn't work in cocoon
this._alpha = value;
}
/**
* The X coordinate of the stage.
* @property _x
* @type number
* @private
*/
private _x: number;
/**
* The X coordinate of the stage. This number should be the same
* as the stage's `left` property.
* @property x
* @type number
* @public
*/
public get x(): number {
return this._x;
}
public set x(value: number) {
if (this._game.deviceTargetOption === Kiwi.TARGET_BROWSER) {
this.container.style.left = String(value + "px");
} else if (this._game.deviceTargetOption === Kiwi.TARGET_COCOON) {
this.canvas.style.left = String(value + "px");
}
this._x = value;
}
/**
* The Y coordinate of the stage.
* @property _y
* @type number
* @private
*/
private _y: number;
/**
* Get the Y coordinate of the stage. This number should be the same
* as the stage's `top` property.
* @property y
* @type number
* @public
*/
public get y(): number {
return this._y;
}
public set y(value: number) {
if (this._game.deviceTargetOption === Kiwi.TARGET_BROWSER) {
this.container.style.top = String(value + "px");
} else if (this._game.deviceTargetOption === Kiwi.TARGET_COCOON) {
this.canvas.style.top = String(value + "px");
}
this._y = value;
}
/**
* The width of the stage.
* @property _width
* @type number
* @private
*/
private _width: number;
/**
* The width of the stage. This is READ ONLY.
* See the "resize" method if you need to modify this value.
* @property width
* @type number
* @public
* @readonly
*/
public get width(): number {
return this._width;
}
/**
* The height of the stage
* @property _height
* @type number
* @private
*/
private _height: number;
/**
* The height of the stage. This is READ ONLY.
* See the `resize` method if you need to modify this value.
* @property height
* @type number
* @public
* @readonly
*/
public get height(): number {
return this._height;
}
/**
* A `Signal` that dispatches an event when the stage gets resized.
* @property onResize
* @type Kiwi.Signal
* @public
*/
public onResize: Kiwi.Signal;
/**
* A Signal which dispatches events when the window is resized.
* Useful to detect if the screen is now in a "landscape" or "portrait"
* view on Mobile/Cocoon devices.
* @property onWindowResize
* @type Kiwi.Signal
* @public
*/
public onWindowResize: Kiwi.Signal;
/**
* Calculates and returns the amount that the container has been scaled
* by. Mainly used for re-calculating input coordinates.
* Note: For COCOONJS this returns 1 since COCOONJS translates the
* scale itself. This property is READ ONLY.
* @property scale
* @type Kiwi.Geom.Point
* @default 1
* @public
*/
private _scale: Kiwi.Geom.Point;
public get scale(): Kiwi.Geom.Point {
return this._scale;
}
/**
* Calculates and returns the amount that the container has been scaled
* by on the X axis.
* @property scaleX
* @type Number
* @default 1
* @public
*/
public get scaleX(): number {
return this._scale.x;
}
/**
* Calculates and returns the amount that the container has been scaled
* by on the Y axis.
* @property scaleY
* @type Number
* @default 1
* @public
*/
public get scaleY(): number {
return this._scale.y;
}
/**
* A point which determines the offset of this Stage
* @property offset
* @type Kiwi.Geom.Point
* @public
*/
public offset: Kiwi.Geom.Point = new Kiwi.Geom.Point();
/**
* The game this Stage belongs to
* @property _game
* @type Kiwi.Game
* @private
*/
private _game: Kiwi.Game;
/**
* The title of your stage
* @property name
* @type string
* @public
*/
public name: string;
/**
* Whether or not this Stage is DOM ready.
* @property domReady
* @type boolean
* @public
*/
public domReady: boolean;
/**
* The background color of the stage.
*
* @property _color
* @type Kiwi.Utils.Color
* @public
*/
public _color: Kiwi.Utils.Color = new Kiwi.Utils.Color();
/**
* Sets the background color of the stage.
*
* This can be any valid parameter for Kiwi.Utils.Color.
* If passing multiple parameters, do so in a single array.
*
* The default value is "ffffff" or pure white.
*
* Note for users of CocoonJS: When using the WebGL renderer,
* the stage color will fill all parts of the screen outside the canvas.
* Kiwi.js will automatically set the color to "000000" or pure black
* when using CocoonJS. If you change it, and your game does not fill
* the entire screen, the empty portions of the screen will also change
* color.
*
* @property color
* @type string
* @public
*/
public get color(): any {
return this._color.getHex();
}
public set color( val: any ) {
if ( !Kiwi.Utils.Common.isArray( val ) ) {
val = [ val ];
}
this._color.set.apply( this._color, val );
}
/**
* Allows the setting of the background color of the stage through
* component RGB colour values.
*
* This property is an Object Literal with "r", "g", "b" colour streams
* of values between 0 and 255.
*
* @property rgbColor
* @type Object
* @public
*/
public get rgbColor():any {
return { r: this._color.r * 255, g: this._color.g * 255, b: this._color.b * 255 };
}
public set rgbColor(val: any) {
this._color.r255 = val.r;
this._color.g255 = val.g;
this._color.b255 = val.b;
}
/**
* Allows the setting of the background color of the stage through
* component RGBA colour values.
*
* This property is an Object Literal with "r", "g", "b", "a" colour
* streams of values between 0 and 255.
*
* Note that the alpha value is from 0-255, not 0-1. This is to
* preserve compatibility with hex-style color values, e.g. "ff0000ff".
*
* @property rgbaColor
* @type Object
* @public
* @since 1.1.0
*/
public get rgbaColor():any {
return { r: this._color.r * 255, g: this._color.g * 255, b: this._color.b * 255, a: this._color.a * 255 };
}
public set rgbaColor(val: any) {
this._color.r255 = val.r;
this._color.g255 = val.g;
this._color.b255 = val.b;
this._color.a255 = val.a;
}
/**
* Get the normalized background color of the stage.
* Returns an object with rgba values, each being between 0 and 1.
* This is READ ONLY.
* @property normalizedColor
* @type string
* @public
*/
public get normalizedColor(): any {
return {
r: this._color.r,
g: this._color.g,
b: this._color.b,
a: this._color.a };
}
/**
* The webgl rendering context.
* @property gl
* @type WebGLRenderingContext
* @public
*/
public gl: WebGLRenderingContext;
/**
* The canvas rendering context.
* @property ctx
* @type CanvasRenderingContext2D
* @public
*/
public ctx: CanvasRenderingContext2D;
/**
* The canvas element that is being rendered on.
* @property canvas
* @type HTMLCanvasElement
* @public
*/
public canvas: HTMLCanvasElement;
/**
* The debugging canvas.
* @property debugCanvas
* @type HTMLCanvasElement
* @public
*/
public debugCanvas: HTMLCanvasElement;
/**
* The debug canvas rendering context.
* @property dctx
* @type CanvasRenderingContext2D
* @public
*/
public dctx: CanvasRenderingContext2D;
/**
* The parent div in which the layers and input live
* @property container
* @type HTMLDivElement
* @public
*/
public container:HTMLDivElement = null;
/**
* Stores the renderer created after context detection.
* @property _renderer
* @type any
* @private
* @since 1.1.0
*/
private _renderer: any;
/**
* Get the renderer associated with the canvas context.
* This is either a GLRenderManager or a CanvasRenderer.
* If the Kiwi.RENDERER_WEBGL renderer was requested
* but could not be created, it will fall back to CanvasRenderer.
* This is READ ONLY.
* @property renderer
* @type number
* @public
* @since 1.1.0
*/
public get renderer(): any {
return this._renderer;
}
/**
* Is executed when the DOM has loaded and the game is just starting.
* This is a internal method used by the core of Kiwi itself.
* @method boot
* @param dom {HTMLElement} The
* @public
*/
public boot(dom: Kiwi.System.Bootstrap) {
var self = this;
this.domReady = true;
this.container = dom.container;
if (this._game.deviceTargetOption === Kiwi.TARGET_BROWSER) {
this.offset = this.getOffsetPoint( this.container );
this._x = this.offset.x;
this._y = this.offset.y;
window.addEventListener("resize",(event: UIEvent) => this._windowResized(event), true);
this._createFocusEvents();
}
this._createCompositeCanvas();
if (this._game.deviceTargetOption === Kiwi.TARGET_COCOON) {
this._scaleContainer();
// Detect reorientation/resize
window.addEventListener("orientationchange", function( event:UIEvent ) {
return self._orientationChanged(event);
}, true);
} else {
this._calculateContainerScale();
}
}
/**
* Gets the x/y coordinate offset of any given valid DOM Element
* from the top/left position of the browser
* Based on jQuery offset https://github.com/jquery/jquery/blob/master/src/offset.js
* @method getOffsetPoint
* @param {Any} element
* @param {Kiwi.Geom.Point} output
* @return {Kiwi.Geom.Point}
* @public
*/
public getOffsetPoint(element, output: Kiwi.Geom.Point = new Kiwi.Geom.Point): Kiwi.Geom.Point {
var box = element.getBoundingClientRect();
var clientTop = element.clientTop || document.body.clientTop || 0;
var clientLeft = element.clientLeft || document.body.clientLeft || 0;
var scrollTop = window.pageYOffset || element.scrollTop || document.body.scrollTop;
var scrollLeft = window.pageXOffset || element.scrollLeft || document.body.scrollLeft;
return output.setTo(box.left + scrollLeft - clientLeft, box.top + scrollTop - clientTop);
}
/**
* Method that is fired when the window is resized.
* @method _windowResized
* @param event {UIEvent}
* @private
*/
private _windowResized(event:UIEvent) {
this._calculateContainerScale();
// Dispatch window resize event
this.onWindowResize.dispatch();
}
/**
* Method that is fired when the device is reoriented.
* @method _orientationChanged
* @param event {UIEvent}
* @private
* @since 1.1.1
*/
private _orientationChanged(event:UIEvent) {
this.onResize.dispatch(window.innerWidth, window.innerHeight);
}
/**
* Used to calculate new offset and scale for the stage.
* @method _calculateContainerScale
* @private
*/
private _calculateContainerScale() {
// Calculate the scale twice
// This will give the correct scale upon completion the second run
// Temporary fix until the Scale Manager is implemented
this._scaleContainer();
this._scaleContainer();
this.offset = this.getOffsetPoint(this.container);
this._scale.x = this._width / this.container.clientWidth;
this._scale.y = this._height / this.container.clientHeight;
}
/**
* Handles the creation of the canvas that the game will use and
* retrieves the context for the renderer.
*
* @method _createCompositeCanvas
* @private
*/
private _createCompositeCanvas() {
// If we are using cocoon then create a accelerated screen canvas
if (this._game.deviceTargetOption == Kiwi.TARGET_COCOON) {
this.canvas = <HTMLCanvasElement>document.createElement(navigator["isCocoonJS"] ? "screencanvas" : "canvas");
// Otherwise default to normal canvas
} else {
this.canvas = <HTMLCanvasElement>document.createElement("canvas");
this.canvas.style.width = "100%";
this.canvas.style.height = "100%";
}
this.canvas.id = this._game.id + "compositeCanvas";
this.canvas.style.position = "absolute";
this.canvas.width = this.width;
this.canvas.height = this.height;
// Get 2D or GL Context; do error detection
// and fallback to valid rendering context
if (this._game.renderOption === Kiwi.RENDERER_CANVAS) {
this.ctx = this.canvas.getContext("2d");
this.ctx.fillStyle = "#fff";
this.gl = null;
} else if (this._game.renderOption === Kiwi.RENDERER_WEBGL) {
this.gl = this.canvas.getContext("webgl");
if (!this.gl) {
this.gl = this.canvas.getContext("experimental-webgl");
if (!this.gl) {
Kiwi.Log.warn("Kiwi.Stage: WebGL rendering is not available despite the device apparently supporting it. Reverting to CANVAS.", "#renderer");
// Reset to canvas mode
this.ctx = this.canvas.getContext("2d");
this.ctx.fillStyle = "#fff";
this.gl = null;
} else {
Kiwi.Log.warn("Kiwi.Stage: 'webgl' context is not available. Using 'experimental-webgl'", "#renderer");
}
}
if ( this.gl ) {
// That is, WebGL was properly supported and created
this.gl.clearColor(1, 1, 1, 1);
this.gl.clear(this.gl.COLOR_BUFFER_BIT | this.gl.DEPTH_BUFFER_BIT);
this.ctx = null;
}
}
// Create render manager
// This is reported back to the Kiwi.Game that created the Stage.
if(this.ctx) {
this._renderer = new Kiwi.Renderers.CanvasRenderer(this._game);
} else if(this.gl) {
this._renderer = new Kiwi.Renderers.GLRenderManager(this._game);
}
if (this._game.deviceTargetOption === Kiwi.TARGET_BROWSER) {
this.container.appendChild(this.canvas);
} else {
document.body.appendChild(this.canvas);
}
}
/**
* Set the stage width and height for rendering purposes.
* This will not effect that "scaleType" that it has been set to.
*
* @method resize
* @param width {number} The new Stage width.
* @param height {number} The new Stage height.
* @public
*/
public resize(width: number, height: number) {
this.canvas.height = height;
this.canvas.width = width;
this._height = height;
this._width = width;
if (this._game.deviceTargetOption === Kiwi.TARGET_BROWSER) {
this._calculateContainerScale();
}
this.onResize.dispatch(this._width, this._height);
}
/**
* Sets the background color of the stage through component
* RGB colour values. Each parameter is a number between 0 and 255.
* This method also returns an Object Literal with "r", "g", "b"
* properties.
*
* @method setRGBColor
* @param r {Number} The red component. A value between 0 and 255.
* @param g {Number} The green component. A value between 0 and 255.
* @param b {Number} The blue component. A value between 0 and 255.
* @return {Object} A Object literal containing the r,g,b properties.
* @public
*/
public setRGBColor(r: number, g: number, b: number):any {
this.rgbColor = { r: r, g: g, b: b };
return this.rgbColor;
}
/**
* Creates a debug canvas and adds it above the regular game canvas.
* The debug canvas is not created by default (even with debugging on)
* and rendering/clearing of the canvas is upto the developer.
* The context for rendering can be access via the "dctx" property and
* you can use the "clearDebugCanvas" method to clear the canvas.
*
* @method createDebugCanvas
* @public
*/
public createDebugCanvas() {
if( Kiwi.Utils.Common.isUndefined(this.debugCanvas) == false ) return;
if (this._game.deviceTargetOption === Kiwi.TARGET_COCOON) {
// Not supported in CocoonJS only because we cannot add it to
// the container (as a container does not exist) and position
// will be hard.
Kiwi.Log.log("Debug canvas not supported in cocoon, creating canvas and context anyway", "#debug-canvas");
}
this.debugCanvas = <HTMLCanvasElement>document.createElement("canvas");
this.debugCanvas.id = this._game.id + "debugCanvas";
this.debugCanvas.style.position = "absolute";
this.debugCanvas.width = this.width;
this.debugCanvas.height = this.height;
this.debugCanvas.style.width = "100%";
this.debugCanvas.style.height = "100%";
this.dctx = this.debugCanvas.getContext("2d");
this.clearDebugCanvas();
if (this._game.deviceTargetOption === Kiwi.TARGET_BROWSER) {
this.container.appendChild(this.debugCanvas);
}
}
/**
* Clears the debug canvas and fills with either the color passed.
* If not colour is passed then Red at 20% opacity is used.
*
* @method clearDebugCanvas
* @param [color="rgba(255,0,0,0.2)"] {string} The debug color to rendering on the debug canvas.
* @public
*/
public clearDebugCanvas( color?:string ) {
this.dctx.fillStyle = color || "rgba(255,0,0,.2)";
this.dctx.clearRect(0, 0, this.width, this.height);
this.dctx.fillRect(0, 0, this.width, this.height)
}
/**
* Toggles the visibility of the debug canvas.
* @method toggleDebugCanvas
* @public
*/
public toggleDebugCanvas() {
this.debugCanvas.style.display = (this.debugCanvas.style.display === "none") ? "block" : "none";
}
/**
* Handles the scaling/sizing based upon the scaleType property.
* @method _scaleContainer
* @private
*/
private _scaleContainer() {
if (this._game.deviceTargetOption == Kiwi.TARGET_BROWSER) {
var clientWidth = this.container.clientWidth;
this.container.style.width = String(this._width + "px");
this.container.style.height = String(this._height + "px");
if (this._scaleType == Kiwi.Stage.SCALE_NONE) {
this.container.style.maxWidth = "";
this.container.style.minWidth = "";
}
// To Fit or STRETCH
if (this._scaleType == Kiwi.Stage.SCALE_STRETCH || this._scaleType == Kiwi.Stage.SCALE_FIT) {
this.container.style.minWidth = "100%";
this.container.style.maxWidth = "100%";
}
// If scale stretched then scale the containers height to 100%
// of its parent's.
if (this._scaleType == Kiwi.Stage.SCALE_STRETCH) {
this.container.style.minHeight = "100%";
this.container.style.maxHeight = "100%";
} else {
this.container.style.minHeight = "";
this.container.style.maxHeight = "";
}
// If it is SCALE to FIT then scale the containers height in
// ratio with the containers width.
if (this._scaleType == Kiwi.Stage.SCALE_FIT) {
this.container.style.height = String((clientWidth / this._width) * this._height) + "px";
}
}
if (this._game.deviceTargetOption == Kiwi.TARGET_COCOON) {
// This has no effect in WebGL, and is thus handled separately.
switch (this._scaleType) {
case Kiwi.Stage.SCALE_FIT:
this.canvas.style.cssText = "idtkscale:ScaleAspectFit";
break;
case Kiwi.Stage.SCALE_STRETCH:
this.canvas.style.cssText = "idtkscale:ScaleToFill";
break;
case Kiwi.Stage.SCALE_NONE:
this.canvas.style.cssText = "";
break;
}
}
}
/**
* Dispatches callbacks when the page containing this game gains focus.
*
* @property onFocus
* @type Kiwi.Signal
* @since 1.3.0
* @public
*/
public onFocus: Kiwi.Signal;
/**
* Dispatches callbacks when this page containing this game loses focus.
*
* @property onBlur
* @type Kiwi.Signal
* @since 1.3.0
* @public
*/
public onBlur: Kiwi.Signal;
/**
* Dispatches callbacks when the visiblity of the page changes.
*
* @property onVisibilityChange
* @type Kiwi.Signal
* @since 1.3.0
* @public
*/
public onVisibilityChange: Kiwi.Signal;
/**
* A flag indicating if the page is currently visible
* (using the Visiblity API).
* If the Visiblity API is unsupported this will remain set to true
* regardless of focus / blur events.
*
* @property visibility
* @type boolean
* @default true
* @readOnly
* @since 1.3.0
* @public
*/
public get visibility():boolean {
if (this._visibility) {
return !document[this._visibility];
}
return true;
}
/**
* Contains string used to access the `hidden` property on the document.
*
* @property _visibility
* @type String
* @default 'hidden'
* @since 1.3.0
* @private
*/
private _visibility: string;
/**
* Contains the bound version of the `_checkVisibility` method.
*
* @property _visibilityChange
* @type any
* @since 1.3.0
* @private
*/
private _visibilityChange: any;
/**
* Fired when the page visibility changes, or the page focus/blur
* events fire. In charge of firing the appropriate signals.
*
* @method _checkVisibility
* @param event {Any}
* @since 1.3.0
* @private
*/
private _checkVisibility(event) {
if (event.type === "focus" || event.type === "pageshow") {
this.onFocus.dispatch(event);
return;
} else if (event.type === "pagehide" || event.type === "blur") {
this.onBlur.dispatch(event);
return;
}
if (event.type === "visibilitychange" || event.type === "mozvisibilitychange" || event.type === "webkitvisibilitychange" || event.type === "msvisibilitychange") {
this.onVisibilityChange.dispatch();
return;
}
}
/**
* Adds the focus, blur, and visibility events to the document.
*
* @method _createFocusEvents
* @since 1.3.0
* @private
*/
private _createFocusEvents() {
this._visibility = "hidden";
this._visibilityChange = this._checkVisibility.bind(this);
if ("hidden" in document) {
document.addEventListener("visibilitychange", this._visibilityChange);
} else if ((this._visibility = "mozHidden") in document) {
document.addEventListener("mozvisibilitychange", this._visibilityChange);
} else if ((this._visibility = "webkitHidden") in document) {
document.addEventListener("webkitvisibilitychange", this._visibilityChange);
} else if ((this._visibility = "msHidden") in document) {
document.addEventListener("msvisibilitychange", this._visibilityChange);
} else {
// Not supported.
this._visibility = null;
}
window.addEventListener('pageshow', this._visibilityChange);
window.addEventListener('pagehide', this._visibilityChange);
window.addEventListener('focus', this._visibilityChange);
window.addEventListener('blur', this._visibilityChange);
}
}
} | the_stack |
'use strict';
import { ConfigurationChangeEvent, ConfigurationTarget } from 'vscode';
import { IApplicationShell, IWorkspaceService } from '../../common/application/types';
import '../../common/extensions';
import { traceError } from '../../common/logger';
import { IFileSystem } from '../../common/platform/types';
import { IPythonExecutionFactory } from '../../common/process/types';
import {
IConfigurationService,
IHttpClient,
IPersistentState,
IPersistentStateFactory,
WidgetCDNs
} from '../../common/types';
import { createDeferred, Deferred } from '../../common/utils/async';
import { Common, DataScience } from '../../common/utils/localize';
import { noop } from '../../common/utils/misc';
import { IInterpreterService } from '../../interpreter/contracts';
import { sendTelemetryEvent } from '../../telemetry';
import { getTelemetrySafeHashedString } from '../../telemetry/helpers';
import { Telemetry } from '../constants';
import { IKernel } from '../jupyter/kernels/types';
import { ILocalResourceUriConverter } from '../types';
import { CDNWidgetScriptSourceProvider } from './cdnWidgetScriptSourceProvider';
import { LocalWidgetScriptSourceProvider } from './localWidgetScriptSourceProvider';
import { RemoteWidgetScriptSourceProvider } from './remoteWidgetScriptSourceProvider';
import { IWidgetScriptSourceProvider, WidgetScriptSource } from './types';
const GlobalStateKeyToTrackIfUserConfiguredCDNAtLeastOnce = 'IPYWidgetCDNConfigured';
const GlobalStateKeyToNeverWarnAboutScriptsNotFoundOnCDN = 'IPYWidgetNotFoundOnCDN';
/**
* This class decides where to get widget scripts from.
* Whether its cdn or local or other, and also controls the order/priority.
* If user changes the order, this will react to those configuration setting changes.
* If user has not configured antying, user will be presented with a prompt.
*/
export class IPyWidgetScriptSourceProvider implements IWidgetScriptSourceProvider {
private readonly notifiedUserAboutWidgetScriptNotFound = new Set<string>();
private scriptProviders?: IWidgetScriptSourceProvider[];
private configurationPromise?: Deferred<void>;
private get configuredScriptSources(): readonly WidgetCDNs[] {
const settings = this.configurationSettings.getSettings(undefined);
return settings.widgetScriptSources;
}
private readonly userConfiguredCDNAtLeastOnce: IPersistentState<boolean>;
private readonly neverWarnAboutScriptsNotFoundOnCDN: IPersistentState<boolean>;
constructor(
private readonly kernel: IKernel,
private readonly localResourceUriConverter: ILocalResourceUriConverter,
private readonly fs: IFileSystem,
private readonly interpreterService: IInterpreterService,
private readonly appShell: IApplicationShell,
private readonly configurationSettings: IConfigurationService,
private readonly workspaceService: IWorkspaceService,
private readonly stateFactory: IPersistentStateFactory,
private readonly httpClient: IHttpClient,
private readonly factory: IPythonExecutionFactory
) {
this.userConfiguredCDNAtLeastOnce = this.stateFactory.createGlobalPersistentState<boolean>(
GlobalStateKeyToTrackIfUserConfiguredCDNAtLeastOnce,
false
);
this.neverWarnAboutScriptsNotFoundOnCDN = this.stateFactory.createGlobalPersistentState<boolean>(
GlobalStateKeyToNeverWarnAboutScriptsNotFoundOnCDN,
false
);
}
public initialize() {
this.workspaceService.onDidChangeConfiguration(this.onSettingsChagned.bind(this));
}
public dispose() {
this.disposeScriptProviders();
}
/**
* We know widgets are being used, at this point prompt user if required.
*/
public async getWidgetScriptSource(
moduleName: string,
moduleVersion: string
): Promise<Readonly<WidgetScriptSource>> {
await this.configureWidgets();
if (!this.scriptProviders) {
this.rebuildProviders();
}
// Get script sources in order, if one works, then get out.
const scriptSourceProviders = (this.scriptProviders || []).slice();
let found: WidgetScriptSource = { moduleName };
while (scriptSourceProviders.length) {
const scriptProvider = scriptSourceProviders.shift();
if (!scriptProvider) {
continue;
}
const source = await scriptProvider.getWidgetScriptSource(moduleName, moduleVersion);
// If we found the script source, then use that.
if (source.scriptUri) {
found = source;
break;
}
}
sendTelemetryEvent(Telemetry.HashedIPyWidgetNameUsed, undefined, {
hashedName: getTelemetrySafeHashedString(found.moduleName),
source: found.source,
cdnSearched: this.configuredScriptSources.length > 0
});
if (!found.scriptUri) {
traceError(`Script source for Widget ${moduleName}@${moduleVersion} not found`);
}
this.handleWidgetSourceNotFoundOnCDN(found).ignoreErrors();
return found;
}
private async handleWidgetSourceNotFoundOnCDN(widgetSource: WidgetScriptSource) {
// if widget exists nothing to do.
if (widgetSource.source === 'cdn' || this.neverWarnAboutScriptsNotFoundOnCDN.value === true) {
return;
}
if (
this.notifiedUserAboutWidgetScriptNotFound.has(widgetSource.moduleName) ||
this.configuredScriptSources.length === 0
) {
return;
}
this.notifiedUserAboutWidgetScriptNotFound.add(widgetSource.moduleName);
const selection = await this.appShell.showWarningMessage(
DataScience.widgetScriptNotFoundOnCDNWidgetMightNotWork().format(widgetSource.moduleName),
Common.ok(),
Common.doNotShowAgain(),
Common.reportThisIssue()
);
switch (selection) {
case Common.doNotShowAgain():
return this.neverWarnAboutScriptsNotFoundOnCDN.updateValue(true);
case Common.reportThisIssue():
return this.appShell.openUrl('https://aka.ms/CreatePVSCDataScienceIssue');
default:
noop();
}
}
private onSettingsChagned(e: ConfigurationChangeEvent) {
if (e.affectsConfiguration('jupyter.widgetScriptSources')) {
this.rebuildProviders();
}
}
private disposeScriptProviders() {
while (this.scriptProviders && this.scriptProviders.length) {
const item = this.scriptProviders.shift();
if (item) {
item.dispose();
}
}
}
private rebuildProviders() {
this.disposeScriptProviders();
const scriptProviders: IWidgetScriptSourceProvider[] = [];
// If we're allowed to use CDN providers, then use them, and use in order of preference.
if (this.configuredScriptSources.length > 0) {
scriptProviders.push(
new CDNWidgetScriptSourceProvider(this.configurationSettings, this.localResourceUriConverter, this.fs)
);
}
const connection = this.kernel.connection;
if (!connection) {
//
} else if (connection.localLaunch) {
scriptProviders.push(
new LocalWidgetScriptSourceProvider(
this.kernel,
this.localResourceUriConverter,
this.fs,
this.interpreterService,
this.factory
)
);
} else {
scriptProviders.push(new RemoteWidgetScriptSourceProvider(connection, this.httpClient));
}
this.scriptProviders = scriptProviders;
}
private async configureWidgets(): Promise<void> {
if (this.configuredScriptSources.length !== 0) {
return;
}
if (this.userConfiguredCDNAtLeastOnce.value) {
return;
}
if (this.configurationPromise) {
return this.configurationPromise.promise;
}
this.configurationPromise = createDeferred();
sendTelemetryEvent(Telemetry.IPyWidgetPromptToUseCDN);
const selection = await this.appShell.showInformationMessage(
DataScience.useCDNForWidgets(),
Common.ok(),
Common.cancel(),
Common.doNotShowAgain()
);
let selectionForTelemetry: 'ok' | 'cancel' | 'dismissed' | 'doNotShowAgain' = 'dismissed';
switch (selection) {
case Common.ok(): {
selectionForTelemetry = 'ok';
// always search local interpreter or attempt to fetch scripts from remote jupyter server as backups.
await Promise.all([
this.updateScriptSources(['jsdelivr.com', 'unpkg.com']),
this.userConfiguredCDNAtLeastOnce.updateValue(true)
]);
break;
}
case Common.doNotShowAgain(): {
selectionForTelemetry = 'doNotShowAgain';
// At a minimum search local interpreter or attempt to fetch scripts from remote jupyter server.
await Promise.all([this.updateScriptSources([]), this.userConfiguredCDNAtLeastOnce.updateValue(true)]);
break;
}
default:
selectionForTelemetry = selection === Common.cancel() ? 'cancel' : 'dismissed';
break;
}
sendTelemetryEvent(Telemetry.IPyWidgetPromptToUseCDNSelection, undefined, { selection: selectionForTelemetry });
this.configurationPromise.resolve();
}
private async updateScriptSources(scriptSources: WidgetCDNs[]) {
const targetSetting = 'widgetScriptSources';
await this.configurationSettings.updateSetting(
targetSetting,
scriptSources,
undefined,
ConfigurationTarget.Global
);
}
} | the_stack |
import { Game, GameObject, resource, RESOURCE_TYPE } from "@eva/eva.js";
import { RendererSystem } from "@eva/plugin-renderer";
import { Graphics, GraphicsSystem } from "@eva/plugin-renderer-graphics";
import { PhysicsSystem, Physics, PhysicsType } from "@eva/plugin-matterjs";
import { Text, TextSystem } from "@eva/plugin-renderer-text";
import { ImgSystem, Img } from "@eva/plugin-renderer-img";
import { EventSystem, Event } from "@eva/plugin-renderer-event";
declare const window: Window & {
game: Game
}
export const name = 'matter';
export async function init(canvas) {
let gameHeight = 750 * (window.innerHeight / window.innerWidth);
const fruitRadius = {
yingtao: {
radius: 30,
next: 'ningmeng',
grade: 10,
},
ningmeng: {
radius: 56,
next: 'yezi',
grade: 20,
},
mihoutao: {
radius: 56,
next: 'hamigua',
grade: 20,
},
fanqie: {
radius: 56,
next: 'hamigua',
grade: 20,
},
danqie: {
radius: 30,
grade: 10,
next: 'chengzi',
},
chengzi: {
radius: 56,
grade: 20,
next: 'hamigua',
},
yezi: {
radius: 108,
grade: 60,
next: 'xigua',
},
hamigua: {
radius: 100,
grade: 60,
next: 'xigua',
},
xigua: {
radius: 146,
grade: 100,
next: 'daxigua',
},
daxigua: {
grade: 200,
radius: 180,
next: '',
},
};
const canUseType = ['yingtao', 'ningmeng', 'mihoutao', 'fanqie', 'danqie', 'chengzi'];
let currentFruit = null;
let currentType = 'yingtao';
let gradePanel = null;
const bodyOptions = {
isStatic: false,
restitution: 0.4,
density: 0.002,
};
createGame();
function createGame() {
resource.addResource([
{
name: 'yingtao',
type: RESOURCE_TYPE.IMAGE,
src: {
image: {
type: 'png',
url: 'https://gw.alicdn.com/imgextra/i3/O1CN01RiTyaV1pYQK8i71zv_!!6000000005372-2-tps-30-30.png',
},
},
preload: true,
},
{
name: 'ningmeng',
type: RESOURCE_TYPE.IMAGE,
src: {
image: {
type: 'png',
url: 'https://gw.alicdn.com/imgextra/i2/O1CN01pshzAr24I8TR1vt2e_!!6000000007367-2-tps-56-56.png',
},
},
preload: true,
},
{
name: 'mihoutao',
type: RESOURCE_TYPE.IMAGE,
src: {
image: {
type: 'png',
url: 'https://gw.alicdn.com/imgextra/i2/O1CN01BhgdZQ1r2Tvs3S1W7_!!6000000005573-2-tps-55-55.png',
},
},
preload: true,
},
{
name: 'fanqie',
type: RESOURCE_TYPE.IMAGE,
src: {
image: {
type: 'png',
url: 'https://gw.alicdn.com/imgextra/i4/O1CN010ZcL7r1xz0EcnGC7S_!!6000000006513-2-tps-67-67.png',
},
},
preload: true,
},
{
name: 'danqie',
type: RESOURCE_TYPE.IMAGE,
src: {
image: {
type: 'png',
url: 'https://gw.alicdn.com/imgextra/i1/O1CN01wNvjVh1WHxNjIN8yp_!!6000000002764-2-tps-25-25.png',
},
},
preload: true,
},
{
name: 'chengzi',
type: RESOURCE_TYPE.IMAGE,
src: {
image: {
type: 'png',
url: 'https://gw.alicdn.com/imgextra/i4/O1CN01JFUmPy1Eg5A7IKTuF_!!6000000000380-2-tps-48-48.png',
},
},
preload: true,
},
{
name: 'yezi',
type: RESOURCE_TYPE.IMAGE,
src: {
image: {
type: 'png',
url: 'https://gw.alicdn.com/imgextra/i1/O1CN01WQ9kiI20RyWM3pIuQ_!!6000000006847-2-tps-107-107.png',
},
},
preload: true,
},
{
name: 'hamigua',
type: RESOURCE_TYPE.IMAGE,
src: {
image: {
type: 'png',
url: 'https://gw.alicdn.com/imgextra/i2/O1CN01AREV7q1eZplnDe4NN_!!6000000003886-2-tps-100-100.png',
},
},
preload: true,
},
{
name: 'xigua',
type: RESOURCE_TYPE.IMAGE,
src: {
image: {
type: 'png',
url: 'https://gw.alicdn.com/imgextra/i2/O1CN01B0Hc8G1VFNXOreNub_!!6000000002623-2-tps-146-146.png',
},
},
preload: true,
},
{
name: 'daxigua',
type: RESOURCE_TYPE.IMAGE,
src: {
image: {
type: 'png',
url: 'https://gw.alicdn.com/imgextra/i2/O1CN01q6KlMS1evMNxBcapP_!!6000000003933-2-tps-288-280.png',
},
},
preload: true,
},
]);
const game = new Game({
autoStart: true,
frameRate: 60,
systems: [
new RendererSystem({
transparent: true,
canvas,
backgroundColor: 0xfee79d,
width: 750,
height: gameHeight,
resolution: window.devicePixelRatio / 2,
}),
new ImgSystem(),
new GraphicsSystem(),
new PhysicsSystem({
resolution: window.devicePixelRatio / 2, // 保持RendererSystem的resolution一致
isTest: false, // 是否开启调试模式
element: document.getElementById('container'), // 调试模式下canvas节点的挂载点
world: {
gravity: {
y: 5, // 重力,
},
},
mouse: {
open: false
}
}),
new TextSystem(),
new EventSystem(),
],
});
window.game = game;
// 构建背景
// 构建背景
buildGame();
// 构建墙体
buildWall();
}
function buildGame() {
const background = new GameObject('background', {
position: {
x: 0,
y: 0,
},
size: {
width: 750,
height: gameHeight,
},
});
const { graphics } = background.addComponent(new Graphics());
graphics.beginFill(0xfee79d, 1);
graphics.drawRect(0, 0, background.transform.size.width, background.transform.size.height);
graphics.endFill();
window.game.scene.addChild(background);
gradePanel = new GameObject('grade', {
position: {
x: 50,
y: 150,
},
size: {
width: 300,
height: 100,
},
});
gradePanel.addComponent(
new Text({
text: '0',
style: {
fontSize: 66,
fontFamily: 'Arial',
fontWeight: 'bold',
fill: ['#ffffff'],
},
}),
);
const backPanel = new GameObject('grade', {
position: {
x: 50,
y: 100,
},
size: {
width: 300,
height: 100,
},
});
backPanel.addComponent(
new Text({
text: '返回',
style: {
fontSize: 40,
fontFamily: 'Arial',
fontWeight: 'bold',
fill: ['#ffffff'],
},
}),
);
const backEvt = backPanel.addComponent(new Event());
backEvt.on('tap', () => {
// xsand.goBack();
});
window.game.scene.addChild(backPanel);
window.game.scene.addChild(gradePanel);
// 创建水果
currentFruit = randomFruit('yingtao');
window.game.scene.addChild(currentFruit);
const evt = background.addComponent(new Event());
let touched = false;
const touchmoveFn = e => {
if (!touched && currentFruit && currentFruit.transform) {
currentFruit.transform.position.x = e.data.position.x;
}
};
const touchend = () => {
if (currentFruit && currentFruit.transform) {
const physics = currentFruit.addComponent(
new Physics({
type: PhysicsType.CIRCLE,
bodyOptions,
radius: fruitRadius[currentType].radius,
}),
);
physics.on('collisionStart', collisionStartFn);
}
};
evt.on('touchstart', e => {
// 更新水果的x坐标
touchmoveFn(e);
e.stopPropagation();
});
evt.on('touchmove', e => {
// 更新水果的x坐标
touchmoveFn(e);
e.stopPropagation();
});
evt.on('touchend', e => {
if (!touched) {
touched = true;
touchend();
setTimeout(() => {
touched = false;
newAFruit();
}, 1000);
}
e.stopPropagation();
});
}
function collisionStartFn(gameObjectA: GameObject, gameObjectB: GameObject) {
if (gameObjectA && gameObjectB && gameObjectA.name === gameObjectB.name) {
const TextCom = gradePanel.getComponent('Text');
TextCom.text = Number(TextCom.text) + fruitRadius[gameObjectA.name].grade * 2;
const nextType = fruitRadius[gameObjectA.name].next;
if (!nextType) {
return;
}
const newFruit = randomFruit(nextType);
newFruit.transform.position.x = gameObjectA.transform.position.x + gameObjectA.transform.size.width * 0.5;
newFruit.transform.position.y = gameObjectA.transform.position.y + gameObjectA.transform.size.height * 0.5;
const physics = newFruit.addComponent(
new Physics({
type: PhysicsType.CIRCLE,
bodyOptions,
radius: fruitRadius[nextType].radius,
}),
);
// @ts-ignore
window.game.scene.addChild(newFruit);
physics.on('collisionStart', collisionStartFn);
gameObjectA.destroy();
gameObjectB.destroy();
}
}
function newAFruit() {
const randomIndex = Math.floor(Math.random() * canUseType.length);
currentType = canUseType[randomIndex];
currentFruit = randomFruit(currentType);
window.game.scene.addChild(currentFruit);
}
function randomFruit(type) {
return buildFruit(type, 375, 150, fruitRadius[type].radius, type);
}
function buildWall() {
const bottomWall = createGameObjectAddGraphicsRect(375, gameHeight - 10, 750, 20, 0xff0000);
window.game.scene.addChild(bottomWall);
const leftWall = createGameObjectAddGraphicsRect(0, gameHeight / 2, 10, gameHeight, 0xff0000);
window.game.scene.addChild(leftWall);
const rightWall = createGameObjectAddGraphicsRect(750, gameHeight / 2, 10, gameHeight, 0xff0000);
window.game.scene.addChild(rightWall);
}
function createGameObjectAddGraphicsRect(x, y, width, height, color) {
const gameObject = new GameObject('gameObject', {
position: {
x,
y,
},
size: {
width,
height,
},
origin: {
x: 0.5,
y: 0.5,
},
});
const { graphics } = gameObject.addComponent(new Graphics());
graphics.beginFill(color, 1);
graphics.drawRect(0, 0, gameObject.transform.size.width, gameObject.transform.size.height);
graphics.endFill();
gameObject.addComponent(
new Physics({
type: PhysicsType.RECTANGLE,
bodyOptions: {
isStatic: true,
},
}),
);
return gameObject;
}
function buildFruit(name, x, y, radius, type) {
const gameObject = new GameObject(name, {
position: {
x,
y,
},
size: {
width: 2 * radius,
height: 2 * radius,
},
origin: {
x: 0.5,
y: 0.5,
},
});
gameObject.addComponent(
new Img({
resource: type,
}),
);
return gameObject;
}
} | the_stack |
import { FunctionFragment } from '@ethersproject/abi'
import { expect } from 'earljs'
import { Awaited } from 'earljs/dist/mocks/types'
import { BigNumber, BigNumberish, ethers } from 'ethers'
import { AssertTrue, IsExact, q18, typedAssert } from 'test-utils'
import { DataTypesInput } from '../types/DataTypesInput'
import { createNewBlockchain, deployContract } from './common'
type Struct1Struct = DataTypesInput.Struct1Struct
type Struct1StructOutput = DataTypesInput.Struct1StructOutput
type Struct2Struct = DataTypesInput.Struct2Struct
type Struct2StructOutput = DataTypesInput.Struct2StructOutput
type Struct3Struct = DataTypesInput.Struct3Struct
type Struct3StructOutput = DataTypesInput.Struct3StructOutput
describe('DataTypesInput', () => {
let contract!: DataTypesInput
let ganache: any
beforeEach(async () => {
const { ganache: _ganache, signer } = await createNewBlockchain()
ganache = _ganache
contract = await deployContract<DataTypesInput>(signer, 'DataTypesInput')
})
afterEach(() => ganache.close())
it('works', async () => {
typedAssert(await contract.input_uint8('42'), 42)
typedAssert(await contract.input_uint8(42), 42)
typedAssert(await contract.input_uint256(q18(1)), BigNumber.from(q18(1)))
typedAssert(await contract.input_uint256(1), BigNumber.from(1))
typedAssert(await contract.input_int8('42'), 42)
typedAssert(await contract.input_int8(42), 42)
typedAssert(await contract.input_int256(q18(1)), BigNumber.from(q18(1)))
typedAssert(await contract.input_int256(1), BigNumber.from('1'))
typedAssert(await contract.input_bool(true), true)
typedAssert(
await contract.input_address('0x70b144972C5Ef6CB941A5379240B74239c418CD4'),
'0x70b144972C5Ef6CB941A5379240B74239c418CD4',
)
typedAssert(await contract.functions.input_address('0x70b144972C5Ef6CB941A5379240B74239c418CD4'), [
'0x70b144972C5Ef6CB941A5379240B74239c418CD4',
])
typedAssert(
await contract.input_address('0x70b144972C5Ef6CB941A5379240B74239c418CD4'),
'0x70b144972C5Ef6CB941A5379240B74239c418CD4',
)
typedAssert(await contract.input_bytes1('0xaa'), '0xaa')
typedAssert(await contract.input_bytes1([0]), '0x00')
typedAssert(
await contract.input_bytes(ethers.utils.formatBytes32String('TypeChain')),
'0x54797065436861696e0000000000000000000000000000000000000000000000',
)
typedAssert(await contract.input_string('TypeChain'), 'TypeChain')
typedAssert(await contract.input_stat_array(['1', '2', '3']), [1, 2, 3])
typedAssert(await contract.input_stat_array([1, 2, 3]), [1, 2, 3])
// TODO: this reverts for some weird reason
// typedAssert(await contract.input_tuple('1', '2'), { 0: new BigNumber('1'), 1: new BigNumber('2') })
// typedAssert(await contract.input_tuple(1, 2), { 0: '1', 1: '2' })
expect(
await contract.input_struct({ uint256_0: BigNumber.from('1'), uint256_1: BigNumber.from('2') }),
).toLooseEqual(expect.a(Array))
typedAssert(await contract.input_struct({ uint256_0: BigNumber.from('1'), uint256_1: BigNumber.from('2') }), {
0: BigNumber.from('1'),
1: BigNumber.from('2'),
uint256_0: BigNumber.from('1'),
uint256_1: BigNumber.from('2'),
} as any)
typedAssert(await contract.input_enum('1'), 1)
typedAssert(await contract.input_enum(1), 1)
})
it('generates correct signature for tuples', () => {
const fragment: FunctionFragment = contract.interface.functions['input_struct((uint256,uint256))']
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
expect(fragment !== undefined).toEqual(true)
})
// tests: https://github.com/ethereum-ts/TypeChain/issues/232
// NOTE: typesAssert is too simple to tests type compatibility here so we can't use it
it('generates correct types for tuples', () => {
type ViewTupleType = Awaited<ReturnType<typeof contract.input_tuple>>
// eslint-disable-next-line @typescript-eslint/no-unused-vars
type _t1 = AssertTrue<IsExact<ViewTupleType, [BigNumber, BigNumber]>>
})
it('generates correct input types for array', () => {
type InputType = Parameters<typeof contract.input_uint_array>
// eslint-disable-next-line @typescript-eslint/no-unused-vars
type _t1 = AssertTrue<IsExact<InputType, [input1: BigNumberish[], overrides?: ethers.CallOverrides | undefined]>>
})
it('generates correct output types for array', () => {
type OutputType = Awaited<ReturnType<typeof contract.input_uint_array>>
// eslint-disable-next-line @typescript-eslint/no-unused-vars
type _t1 = AssertTrue<IsExact<OutputType, BigNumber[]>>
})
/**
* For structs
*/
it('generates correct types for input structs', () => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
type _t1 = AssertTrue<IsExact<Struct1Struct, { uint256_0: BigNumberish; uint256_1: BigNumberish }>>
})
it('generates correct types for output structs', () => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
type _t1 = AssertTrue<
IsExact<
Struct1StructOutput,
[BigNumber, BigNumber] & {
uint256_0: BigNumber
uint256_1: BigNumber
}
>
>
})
it('generates correct input types for structs with are only used as array in some function input/output', () => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
type _t1 = AssertTrue<IsExact<Struct3Struct, { input1: BigNumberish[] }>>
})
it('generates correct output types for structs with are only used as array in some function input/output', () => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
type _t1 = AssertTrue<
IsExact<
Struct3StructOutput,
[BigNumber[]] & {
input1: BigNumber[]
}
>
>
})
it('generates correct types for input complex structs', () => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
type _t1 = AssertTrue<
IsExact<Struct2Struct, { input1: BigNumberish; input2: { uint256_0: BigNumberish; uint256_1: BigNumberish } }>
>
})
it('generates correct types for output complex structs', () => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
type _t1 = AssertTrue<
IsExact<
Struct2StructOutput,
[
BigNumber,
[BigNumber, BigNumber] & {
uint256_0: BigNumber
uint256_1: BigNumber
},
] & {
input1: BigNumber
input2: [BigNumber, BigNumber] & {
uint256_0: BigNumber
uint256_1: BigNumber
}
}
>
>
})
/**
* For functions with struct parameters
*/
it('generates correct parameter types for function structs', () => {
type ViewStructType = Parameters<typeof contract.input_struct>
// eslint-disable-next-line @typescript-eslint/no-unused-vars
type _t1 = AssertTrue<
IsExact<ViewStructType, [input1: Struct1Struct, overrides?: ethers.CallOverrides | undefined]>
>
})
it('generates correct return types for function structs', () => {
type ViewStructType = Awaited<ReturnType<typeof contract.input_struct>>
// eslint-disable-next-line @typescript-eslint/no-unused-vars
type _t1 = AssertTrue<IsExact<ViewStructType, Struct1StructOutput>>
})
it('generates correct parameter types for function structs only used as array in some function input/output', () => {
type ViewStructType = Parameters<typeof contract.input_struct3_array>
// eslint-disable-next-line @typescript-eslint/no-unused-vars
type _t1 = AssertTrue<
IsExact<ViewStructType, [input1: Struct3Struct[], overrides?: ethers.CallOverrides | undefined]>
>
})
it('generates correct return types for function structs only used as array in some function input/output', () => {
type ViewStructType = Awaited<ReturnType<typeof contract.input_struct3_array>>
// eslint-disable-next-line @typescript-eslint/no-unused-vars
type _t1 = AssertTrue<IsExact<ViewStructType, Struct3StructOutput[]>>
})
it('generates correct parameter types for complex function structs', () => {
type ViewStructType = Parameters<typeof contract.input_struct2>
// eslint-disable-next-line @typescript-eslint/no-unused-vars
type _t1 = AssertTrue<
IsExact<ViewStructType, [input1: Struct2Struct, overrides?: ethers.CallOverrides | undefined]>
>
})
it('generates correct return types for complex function structs', () => {
type ViewStructType = Awaited<ReturnType<typeof contract.input_struct2>>
// eslint-disable-next-line @typescript-eslint/no-unused-vars
type _t1 = AssertTrue<IsExact<ViewStructType, Struct2StructOutput>>
})
it('generates correct parameter types for complex struct array', () => {
type ViewStructType = Parameters<typeof contract.input_struct2_array>
// eslint-disable-next-line @typescript-eslint/no-unused-vars
type _t1 = AssertTrue<
IsExact<ViewStructType, [input1: Struct2Struct[], overrides?: ethers.CallOverrides | undefined]>
>
})
it('generates correct return types for complex struct array', () => {
type ViewStructType = Awaited<ReturnType<typeof contract.input_struct2_array>>
// eslint-disable-next-line @typescript-eslint/no-unused-vars
type _t1 = AssertTrue<IsExact<ViewStructType, Struct2StructOutput[]>>
})
it('generates correct argument types for constant size struct array', () => {
type ViewStructType = Parameters<typeof contract.input_struct2_tuple>[0]
type _ = AssertTrue<IsExact<ViewStructType, [Struct2Struct, Struct2Struct, Struct2Struct]>>
})
it('generates correct return types for constant size struct array', () => {
type ViewStructType = Awaited<ReturnType<typeof contract.input_struct2_tuple>>
type _ = AssertTrue<IsExact<ViewStructType, [Struct2StructOutput, Struct2StructOutput, Struct2StructOutput]>>
})
it('output structs are compatible with input structs', async () => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const _result: Struct1Struct = await contract.input_struct({
uint256_0: 1,
uint256_1: 2,
})
})
it('structs with same name in different contract/library: input test', async () => {
type ViewFunctionInputType = Parameters<typeof contract.input_multiple_structs_with_same_name>
// eslint-disable-next-line @typescript-eslint/no-unused-vars
type _t1 = AssertTrue<
IsExact<
ViewFunctionInputType,
[info1: { a: BigNumberish; b: BigNumberish }, overrides?: ethers.CallOverrides | undefined]
>
>
type ViewFunctionOutputType = Awaited<ReturnType<typeof contract.input_multiple_structs_with_same_name>>
type _t2 = AssertTrue<
IsExact<
ViewFunctionOutputType,
[string, string] & {
a: string
b: string
}
>
>
})
// we skip this test as ts only about types
it.skip('prevents from using not existing methods', () => {
// @ts-expect-error
contract.not_existing(1)
// @ts-expect-error
contract.functions.not_existing(1)
})
}) | the_stack |
import {
addIcon,
MarkdownPostProcessor,
MarkdownPostProcessorContext,
MarkdownPreviewRenderer,
MarkdownRenderChild,
MarkdownRenderer,
MarkdownView,
normalizePath,
Notice,
Plugin,
TFile
} from "obsidian";
/* import { prettyPrint as html } from "html"; */
import { syntaxTree } from "@codemirror/language";
import {
ViewPlugin,
DecorationSet,
EditorView,
ViewUpdate,
Decoration
} from "@codemirror/view";
import { tokenClassNodeProp } from "@codemirror/stream-parser";
import {
Admonition,
ObsidianAdmonitionPlugin,
ISettingsData,
AdmonitionIconDefinition
} from "./@types";
import { getID, getMatches, getParametersFromSource } from "./util";
import {
ADMONITION_MAP,
ADD_ADMONITION_COMMAND_ICON,
REMOVE_ADMONITION_COMMAND_ICON,
ADD_COMMAND_NAME,
REMOVE_COMMAND_NAME
} from "./util";
/* import * as CodeMirror from "./codemirror/codemirror"; */
import type codemirror from "codemirror";
declare global {
interface Window {
CodeMirror: typeof codemirror;
}
}
//add commands to app interface
declare module "obsidian" {
interface App {
commands: {
commands: { [id: string]: Command };
editorCommands: { [id: string]: Command };
findCommand(id: string): Command;
};
}
interface MarkdownPreviewView {
renderer: MarkdownPreviewRenderer;
}
interface MarkdownPreviewRenderer {
onCheckboxClick: (evt: MouseEvent, el: HTMLInputElement) => void;
unregisterCodeBlockPostProcessor(lang: string): void;
}
}
Object.fromEntries =
Object.fromEntries ||
/** Polyfill taken from https://github.com/tc39/proposal-object-from-entries/blob/master/polyfill.js */
function <T = any>(
entries: Iterable<readonly [PropertyKey, T]>
): { [k: string]: T } {
const obj = {};
for (const pair of entries) {
if (Object(pair) !== pair) {
throw new TypeError(
"iterable for fromEntries should yield objects"
);
}
// Consistency with Map: contract is that entry has "0" and "1" keys, not
// that it is an array or iterable.
const { "0": key, "1": val } = pair;
Object.defineProperty(obj, key, {
configurable: true,
enumerable: true,
writable: true,
value: val
});
}
return obj;
};
import "./assets/main.css";
import AdmonitionSetting from "./settings";
import {
IconName,
COPY_BUTTON_ICON,
iconDefinitions,
getIconNode
} from "./util/icons";
import { InsertAdmonitionModal } from "./modal";
import { RangeSetBuilder, Range } from "@codemirror/rangeset";
import { StateEffect, StateField, SelectionRange } from "@codemirror/state";
const DEFAULT_APP_SETTINGS: ISettingsData = {
userAdmonitions: {},
syntaxHighlight: false,
copyButton: false,
version: "",
autoCollapse: false,
defaultCollapseType: "open",
syncLinks: true,
enableMarkdownProcessor: false,
injectColor: true,
parseTitles: true,
allowMSSyntax: true
};
export default class ObsidianAdmonition
extends Plugin
implements ObsidianAdmonitionPlugin
{
admonitions: { [admonitionType: string]: Admonition } = {};
data: ISettingsData;
postprocessors: Map<string, MarkdownPostProcessor> = new Map();
get types() {
return Object.keys(this.admonitions);
}
get admonitionArray() {
return Object.keys(this.admonitions).map((key) => {
return {
...this.admonitions[key],
type: key
};
});
}
async saveSettings() {
this.data.version = this.manifest.version;
await this.saveData(this.data);
}
async loadSettings() {
let data = Object.assign(
{},
DEFAULT_APP_SETTINGS,
await this.loadData()
);
this.data = data;
if (
this.data.userAdmonitions &&
(!this.data.version || Number(this.data.version.split(".")[0]) < 5)
) {
for (let admonition in this.data.userAdmonitions) {
if (
Object.prototype.hasOwnProperty.call(
this.data.userAdmonitions[admonition],
"type"
)
)
continue;
this.data.userAdmonitions[admonition] = {
...this.data.userAdmonitions[admonition],
icon: {
type: "font-awesome",
name: this.data.userAdmonitions[admonition]
.icon as unknown as IconName
}
};
}
}
this.admonitions = {
...ADMONITION_MAP,
...this.data.userAdmonitions
};
await this.saveSettings();
}
async addAdmonition(admonition: Admonition): Promise<void> {
this.data.userAdmonitions = {
...this.data.userAdmonitions,
[admonition.type]: admonition
};
this.admonitions = {
...ADMONITION_MAP,
...this.data.userAdmonitions
};
if (this.data.syntaxHighlight) {
this.turnOnSyntaxHighlighting([admonition.type]);
}
await this.saveSettings();
const processor = this.registerMarkdownCodeBlockProcessor(
`ad-${admonition.type}`,
(src, el, ctx) => this.postprocessor(admonition.type, src, el, ctx)
);
this.postprocessors.set(admonition.type, processor);
}
async removeAdmonition(admonition: Admonition) {
if (this.data.userAdmonitions[admonition.type]) {
delete this.data.userAdmonitions[admonition.type];
}
this.admonitions = {
...ADMONITION_MAP,
...this.data.userAdmonitions
};
if (this.data.syntaxHighlight) {
this.turnOffSyntaxHighlighting([admonition.type]);
}
if (admonition.command) {
this.unregisterCommandsFor(admonition);
}
if (this.postprocessors.has(admonition.type)) {
MarkdownPreviewRenderer.unregisterPostProcessor(
this.postprocessors.get(admonition.type)
);
//@ts-expect-error
MarkdownPreviewRenderer.unregisterCodeBlockPostProcessor(
`ad-${admonition.type}`
);
this.postprocessors.delete(admonition.type);
}
await this.saveSettings();
}
async onload(): Promise<void> {
console.log("Obsidian Admonition loaded");
await this.loadSettings();
this.addSettingTab(new AdmonitionSetting(this.app, this));
addIcon(ADD_COMMAND_NAME.toString(), ADD_ADMONITION_COMMAND_ICON);
addIcon(REMOVE_COMMAND_NAME.toString(), REMOVE_ADMONITION_COMMAND_ICON);
if (this.data.enableMarkdownProcessor) {
this.enableMarkdownProcessor();
}
Object.keys(this.admonitions).forEach((type) => {
const processor = this.registerMarkdownCodeBlockProcessor(
`ad-${type}`,
(src, el, ctx) => this.postprocessor(type, src, el, ctx)
);
this.postprocessors.set(type, processor);
if (this.admonitions[type].command) {
this.registerCommandsFor(this.admonitions[type]);
}
});
if (this.data.syntaxHighlight) {
this.turnOnSyntaxHighlighting();
}
/** Add generic commands. */
this.addCommand({
id: "collapse-admonitions",
name: "Collapse Admonitions in Note",
checkCallback: (checking) => {
// checking if the command should appear in the Command Palette
if (checking) {
// make sure the active view is a MarkdownView.
return !!this.app.workspace.getActiveViewOfType(
MarkdownView
);
}
let view = this.app.workspace.getActiveViewOfType(MarkdownView);
if (!view || !(view instanceof MarkdownView)) return;
let admonitions = view.contentEl.querySelectorAll(
"details[open].admonition-plugin"
);
for (let i = 0; i < admonitions.length; i++) {
let admonition = admonitions[i];
admonition.removeAttribute("open");
}
}
});
this.addCommand({
id: "open-admonitions",
name: "Open Admonitions in Note",
checkCallback: (checking) => {
// checking if the command should appear in the Command Palette
if (checking) {
// make sure the active view is a MarkdownView.
return !!this.app.workspace.getActiveViewOfType(
MarkdownView
);
}
let view = this.app.workspace.getActiveViewOfType(MarkdownView);
if (!view || !(view instanceof MarkdownView)) return;
let admonitions = view.contentEl.querySelectorAll(
"details:not([open]).admonition-plugin"
);
for (let i = 0; i < admonitions.length; i++) {
let admonition = admonitions[i];
admonition.setAttribute("open", "open");
}
}
});
this.addCommand({
id: "insert-admonition",
name: "Insert Admonition",
editorCallback: (editor, view) => {
let suggestor = new InsertAdmonitionModal(this, editor);
suggestor.open();
}
});
this.registerEvent(
this.app.metadataCache.on("resolve", (file) => {
if (!this.data.syncLinks) return;
if (this.app.workspace.getActiveFile() != file) return;
const view =
this.app.workspace.getActiveViewOfType(MarkdownView);
if (!view || !(view instanceof MarkdownView)) return;
const admonitionLinks =
view.contentEl.querySelectorAll<HTMLAnchorElement>(
".admonition:not(.admonition-plugin-async) a.internal-link"
);
this.addLinksToCache(admonitionLinks, file.path);
})
);
this.enableMSSyntax();
}
enableMSSyntax() {
this.registerMarkdownPostProcessor((el, ctx) => {
if (!this.data.allowMSSyntax) return;
if (el.firstChild.nodeName !== "BLOCKQUOTE") return;
const section = ctx.getSectionInfo(el);
if (!section) return;
const text = section.text.split("\n");
const firstLine = text[section.lineStart];
if (!/^> \[!.+\]/.test(firstLine)) return;
const [, type, title, col] =
firstLine.match(/^> \[!(\w+)(?:: (.+))?\](x|\+|\-)?/) ?? [];
if (!type || !this.admonitions[type]) return;
let collapse;
switch (col) {
case "+": {
collapse = "open";
break;
}
case "-": {
collapse = "closed";
break;
}
case "x": {
break;
}
default: {
collapse = this.data.autoCollapse
? this.data.defaultCollapseType
: null;
}
}
const admonition = this.getAdmonitionElement(
type,
title ??
this.admonitions[type].title ??
`${type[0].toUpperCase()}${type.slice(1).toLowerCase()}`,
this.admonitions[type].icon,
this.admonitions[type].color,
collapse
);
const content = text
.slice(section.lineStart + 1, section.lineEnd + 1)
.join("\n")
.replace(/> /g, "");
MarkdownRenderer.renderMarkdown(
content,
admonition
.createDiv("admonition-content-holder")
.createDiv("admonition-content"),
ctx.sourcePath,
null
);
el.firstElementChild.replaceWith(admonition);
});
type TokenSpec = {
from: number;
to: number;
loc: { from: number; to: number };
value: string;
index: number;
type: "replace";
};
class StatefulDecorationSet {
editor: EditorView;
cache: { [cls: string]: Decoration } = Object.create(null);
constructor(editor: EditorView) {
this.editor = editor;
}
async compute(tokens: TokenSpec[]) {
const replace: Range<Decoration>[] = [];
for (let token of tokens) {
/* let deco = this.cache[token.value];
if (!deco) {
deco = this.cache[token.value] = Decoration.widget({
inclusive: true,
loc: token.loc
});
}
replace.push(deco.range(token.from, token.to)); */
}
return Decoration.set(replace, true);
}
async updateDecos(tokens: TokenSpec[]): Promise<void> {
const replacers = await this.compute(tokens);
// if our compute function returned nothing and the state field still has decorations, clear them out
if (replace || this.editor.state.field(field).size) {
this.editor.dispatch({
effects: [replace.of(replacers ?? Decoration.none)]
});
}
}
}
const plugin = ViewPlugin.fromClass(
class {
manager: StatefulDecorationSet;
decorations: DecorationSet;
constructor(view: EditorView) {
this.manager = new StatefulDecorationSet(view);
this.decorations = this.build(view);
}
update(update: ViewUpdate) {
if (
update.docChanged ||
update.viewportChanged ||
update.selectionSet
) {
this.decorations = this.build(update.view);
}
}
destroy() {}
build(view: EditorView) {
const targetElements: TokenSpec[] = [];
const builder = new RangeSetBuilder<Decoration>();
for (let { from, to } of view.visibleRanges) {
const tree = syntaxTree(view.state);
tree.iterate({
from,
to,
enter: (type, from, to) => {
const tokenProps =
type.prop(tokenClassNodeProp);
const props = new Set(tokenProps?.split(" "));
if (
props.has("hmd-codeblock") &&
!props.has("formatting-code-block")
)
return;
const original = view.state.doc.sliceString(
from,
to
);
}
});
}
this.manager.updateDecos(targetElements);
return builder.finish();
}
},
{
decorations: (v) => v.decorations
}
);
////////////////
// Utility Code
////////////////
const replace = StateEffect.define<DecorationSet>();
const field = StateField.define<DecorationSet>({
create(): DecorationSet {
return Decoration.none;
},
update(deco, tr): DecorationSet {
return tr.effects.reduce((deco, effect) => {
if (effect.is(replace))
return effect.value.update({
filter: (_, __, decoration) => {
return !rangesInclude(
tr.newSelection.ranges,
decoration.spec.loc.from,
decoration.spec.loc.to
);
}
});
return deco;
}, deco.map(tr.changes));
},
provide: (field) => EditorView.decorations.from(field)
});
return [field, plugin];
}
enableMarkdownProcessor() {
if (!this.data.enableMarkdownProcessor) return;
const TYPE_REGEX = new RegExp(
`(!{3,}|\\?{3,}\\+?) ad-(${this.types.join("|")})(\\s[\\s\\S]+)?`
);
const END_REGEX = new RegExp(`\\-{3,} admonition`);
let push = false,
id: string;
const childMap: Map<
MarkdownRenderChild,
{ contentEl: HTMLElement; elements: Element[]; loaded: boolean }
> = new Map();
const elementMap: Map<Element, MarkdownRenderChild> = new Map();
const idMap: Map<string, MarkdownRenderChild> = new Map();
Object.values(this.admonitions)
.filter(({ command }) => command)
.forEach((admonition) => {
this.registerCommandsFor(admonition);
});
this.registerMarkdownPostProcessor(async (el, ctx) => {
if (!this.data.enableMarkdownProcessor) return;
if (END_REGEX.test(el.textContent) && push) {
push = false;
const lastElement = createDiv();
if (
id &&
idMap.has(id) &&
childMap.has(idMap.get(id)) &&
el.children[0].textContent.replace(END_REGEX, "").length
) {
lastElement.innerHTML = el.children[0].outerHTML.replace(
new RegExp(`(<br>)?\\n?${END_REGEX.source}`),
""
);
const contentEl = childMap.get(idMap.get(id)).contentEl;
if (contentEl)
contentEl.appendChild(lastElement.children[0]);
}
el.children[0].detach();
return;
}
if (!TYPE_REGEX.test(el.textContent) && !push) return;
if (!push) {
if (
!(
Array.from(el.children).find((e) =>
TYPE_REGEX.test(e.textContent)
) instanceof HTMLParagraphElement
)
)
return;
push = true;
let child = new MarkdownRenderChild(el);
id = getID();
idMap.set(id, child);
childMap.set(child, {
contentEl: null,
elements: [],
loaded: false
});
child.onload = async () => {
const source = el.textContent;
let [
,
col,
type,
title = type[0].toUpperCase() +
type.slice(1).toLowerCase()
]: string[] = source.match(TYPE_REGEX) ?? [];
if (!type) return;
let collapse;
if (/\?{3,}/.test(col)) {
collapse = /\+/.test(col) ? "open" : "closed";
}
if (
(title.trim() === "" || title === '""') &&
collapse !== undefined &&
collapse !== "none"
) {
title =
type[0].toUpperCase() + type.slice(1).toLowerCase();
new Notice(
"An admonition must have a title if it is collapsible."
);
}
const admonition = this.admonitions[type];
const admonitionElement =
await this.getAdmonitionElementAsync(
type,
title.trim(),
admonition.icon,
admonition.injectColor ?? this.data.injectColor
? admonition.color
: null,
collapse
);
const contentHolder = admonitionElement.createDiv(
"admonition-content-holder"
);
const contentEl =
contentHolder.createDiv("admonition-content");
child.containerEl.appendChild(admonitionElement);
for (let element of childMap.get(child)?.elements) {
contentEl.appendChild(element);
}
childMap.set(child, {
...childMap.get(child),
contentEl: contentEl,
loaded: true
});
};
child.onunload = () => {
idMap.delete(id);
childMap.delete(child);
};
ctx.addChild(child);
el.children[0].detach();
return;
}
if (id && idMap.get(id)) {
const child = idMap.get(id);
childMap.set(child, {
...childMap.get(child),
elements: [
...childMap.get(child).elements,
...Array.from(el.children)
]
});
elementMap.set(el, child);
if (childMap.get(child)?.loaded) {
for (let element of childMap.get(child)?.elements) {
childMap.get(child).contentEl.appendChild(element);
}
}
}
});
}
disableMarkdownProcessor() {
/* new Notice("The plugin must be reloaded for this to take effect."); */
Object.values(this.admonitions)
.filter(({ command }) => command)
.forEach((admonition) => {
this.registerCommandsFor(admonition);
});
}
unregisterCommandsFor(admonition: Admonition) {
admonition.command = false;
if (
this.app.commands.findCommand(
`obsidian-admonition:insert-${admonition.type}`
)
) {
delete this.app.commands.editorCommands[
`obsidian-admonition:insert-${admonition.type}`
];
delete this.app.commands.editorCommands[
`obsidian-admonition:insert-${admonition.type}-with-title`
];
delete this.app.commands.commands[
`obsidian-admonition:insert-${admonition.type}`
];
delete this.app.commands.commands[
`obsidian-admonition:insert-${admonition.type}-with-title`
];
}
}
registerCommandsFor(admonition: Admonition) {
admonition.command = true;
this.addCommand({
id: `insert-${admonition.type}`,
name: `Insert ${admonition.type}`,
editorCheckCallback: (checking, editor, view) => {
if (checking) return admonition.command;
if (admonition.command) {
try {
editor.getDoc().replaceSelection(
`\`\`\`ad-${admonition.type}
${editor.getDoc().getSelection()}
\`\`\`\n`
);
const cursor = editor.getCursor();
editor.setCursor(cursor.line - 2);
} catch (e) {
new Notice(
"There was an issue inserting the admonition."
);
}
}
}
});
this.addCommand({
id: `insert-${admonition.type}-with-title`,
name: `Insert ${admonition.type} With Title`,
editorCheckCallback: (checking, editor, view) => {
if (checking) return admonition.command;
if (admonition.command) {
try {
editor.getDoc().replaceSelection(
`\`\`\`ad-${admonition.type}
title:
${editor.getDoc().getSelection()}
\`\`\`\n`
);
const cursor = editor.getCursor();
editor.setCursor(cursor.line - 3);
} catch (e) {
new Notice(
"There was an issue inserting the admonition."
);
}
}
}
});
if (this.data.enableMarkdownProcessor) {
this.addCommand({
id: `insert-non-${admonition.type}`,
name: `Insert Non-codeblock ${admonition.type}`,
editorCheckCallback: (checking, editor, view) => {
if (checking)
return (
admonition.command &&
this.data.enableMarkdownProcessor
);
if (admonition.command) {
try {
editor.getDoc().replaceSelection(
`!!! ad-${admonition.type}\n
${editor.getDoc().getSelection()}\n--- admonition\n`
);
const cursor = editor.getCursor();
editor.setCursor(cursor.line - 2);
} catch (e) {
new Notice(
"There was an issue inserting the admonition."
);
}
}
}
});
}
}
turnOnSyntaxHighlighting(types: string[] = Object.keys(this.admonitions)) {
if (!this.data.syntaxHighlight) return;
types.forEach((type) => {
if (this.data.syntaxHighlight) {
/** Process from @deathau's syntax highlight plugin */
const [, cmPatchedType] = `${type}`.match(
/^([\w+#-]*)[^\n`]*$/
);
window.CodeMirror.defineMode(
`ad-${cmPatchedType}`,
(config, options) => {
return window.CodeMirror.getMode({}, "hypermd");
}
);
}
});
this.app.workspace.layoutReady
? this.layoutReady()
: this.app.workspace.onLayoutReady(this.layoutReady.bind(this));
}
turnOffSyntaxHighlighting(types: string[] = Object.keys(this.admonitions)) {
types.forEach((type) => {
if (window.CodeMirror.modes.hasOwnProperty(`ad-${type}`)) {
delete window.CodeMirror.modes[`ad-${type}`];
}
});
this.app.workspace.layoutReady
? this.layoutReady()
: this.app.workspace.onLayoutReady(this.layoutReady.bind(this));
}
layoutReady() {
// don't need the event handler anymore, get rid of it
this.app.workspace.off("layout-ready", this.layoutReady.bind(this));
this.refreshLeaves();
}
refreshLeaves() {
// re-set the editor mode to refresh the syntax highlighting
this.app.workspace.iterateCodeMirrors((cm) =>
cm.setOption("mode", cm.getOption("mode"))
);
}
async postprocessor(
type: string,
src: string,
el: HTMLElement,
ctx?: MarkdownPostProcessorContext
) {
if (!this.admonitions[type]) {
return;
}
try {
const sourcePath =
typeof ctx == "string"
? ctx
: ctx?.sourcePath ??
this.app.workspace.getActiveFile()?.path ??
"";
let { title, collapse, content, icon, color } =
getParametersFromSource(type, src, this.admonitions[type]);
let match = new RegExp(`^!!! ad-(${this.types.join("|")})$`, "gm");
let nestedAdmonitions = content.match(match) || [];
if (nestedAdmonitions.length) {
let matches = [getMatches(content, 0, nestedAdmonitions[0])];
for (let i = 1; i < nestedAdmonitions.length; i++) {
matches.push(
getMatches(
content,
matches[i - 1].end,
nestedAdmonitions[i]
)
);
}
let split = content.split("\n");
for (let m of matches.reverse()) {
split.splice(
m.start,
m.end - m.start + 1,
`\`\`\`ad-${m.type}\n${m.src}\n\`\`\``
);
}
content = split.join("\n");
}
if (this.data.autoCollapse && !collapse) {
collapse = this.data.defaultCollapseType ?? "open";
} else if (collapse && collapse.trim() === "none") {
collapse = "";
}
const id = getID();
/* const iconNode = icon ? this.admonitions[type].icon; */
const admonition = this.admonitions[type];
let admonitionElement = this.getAdmonitionElement(
type,
title,
iconDefinitions.find(({ name }) => icon === name) ??
admonition.icon,
color ??
(admonition.injectColor ?? this.data.injectColor
? admonition.color
: null),
collapse,
id
);
let markdownRenderChild = new MarkdownRenderChild(
admonitionElement
);
markdownRenderChild.containerEl = admonitionElement;
if (ctx && !(typeof ctx == "string")) {
/**
* Create a unloadable component.
*/
markdownRenderChild.onload = () => {
/* this.contextMap.set(id, ctx); */
};
markdownRenderChild.onunload = () => {
/* this.contextMap.delete(id); */
};
ctx.addChild(markdownRenderChild);
}
if (content && content.length) {
const contentHolder = admonitionElement.createDiv(
"admonition-content-holder"
);
const admonitionContent =
contentHolder.createDiv("admonition-content");
/**
* Render the content as markdown and append it to the admonition.
*/
if (/^`{3,}mermaid/m.test(content)) {
const wasCollapsed =
!admonitionElement.hasAttribute("open");
if (admonitionElement instanceof HTMLDetailsElement) {
admonitionElement.setAttribute("open", "open");
}
setImmediate(() => {
MarkdownRenderer.renderMarkdown(
content,
admonitionContent,
sourcePath,
markdownRenderChild
);
if (
admonitionElement instanceof HTMLDetailsElement &&
wasCollapsed
) {
admonitionElement.removeAttribute("open");
}
});
} else {
MarkdownRenderer.renderMarkdown(
content,
admonitionContent,
sourcePath,
markdownRenderChild
);
}
if (admonition.copy ?? this.data.copyButton) {
let copy = contentHolder
.createDiv("admonition-content-copy")
.appendChild(COPY_BUTTON_ICON.cloneNode(true));
copy.addEventListener("click", () => {
navigator.clipboard
.writeText(content.trim())
.then(async () => {
new Notice(
"Admonition content copied to clipboard."
);
});
});
}
const taskLists =
admonitionContent.querySelectorAll<HTMLInputElement>(
".task-list-item-checkbox"
);
if (taskLists?.length) {
const split = src.split("\n");
let slicer = 0;
taskLists.forEach((task) => {
const line = split
.slice(slicer)
.findIndex((l) => /^\- \[.\]/.test(l));
if (line == -1) return;
task.dataset.line = `${line + slicer + 1}`;
slicer = line + slicer + 1;
});
}
const links =
admonitionContent.querySelectorAll<HTMLAnchorElement>(
"a.internal-link"
);
this.addLinksToCache(links, sourcePath);
}
/**
* Replace the <pre> tag with the new admonition.
*/
const parent = el.parentElement;
if (parent && !parent.hasClass("admonition-content")) {
parent.addClass(
"admonition-parent",
`admonition-${type}-parent`
);
}
el.replaceWith(admonitionElement);
return admonitionElement;
} catch (e) {
console.error(e);
const pre = createEl("pre");
pre.createEl("code", {
attr: {
style: `color: var(--text-error) !important`
}
}).createSpan({
text:
"There was an error rendering the admonition:" +
"\n\n" +
src
});
el.replaceWith(pre);
}
}
async onunload() {
console.log("Obsidian Admonition unloaded");
this.turnOffSyntaxHighlighting();
}
addLinksToCache(
links: NodeListOf<HTMLAnchorElement>,
sourcePath: string
): void {
if (!this.data.syncLinks) return;
/* //@ts-expect-error
this.app.metadataCache.resolveLinks(sourcePath); */
for (let i = 0; i < links.length; i++) {
const a = links[i];
if (a.dataset.href) {
let file = this.app.metadataCache.getFirstLinkpathDest(
a.dataset.href,
""
);
let cache, path;
if (file && file instanceof TFile) {
cache = this.app.metadataCache.resolvedLinks;
path = file.path;
} else {
cache = this.app.metadataCache.unresolvedLinks;
path = a.dataset.href;
}
if (!cache[sourcePath]) {
cache[sourcePath] = {
[path]: 0
};
}
let resolved = cache[sourcePath];
if (!resolved[path]) {
resolved[path] = 0;
}
resolved[path] += 1;
cache[sourcePath] = resolved;
}
}
}
getAdmonitionElement(
type: string,
title: string,
icon: AdmonitionIconDefinition,
color?: string,
collapse?: string,
id?: string
): HTMLElement {
let admonition, titleEl;
let attrs: { style?: string; open?: string } = color
? {
style: `--admonition-color: ${color};`
}
: {};
if (collapse && collapse != "none") {
if (collapse === "open") {
attrs.open = "open";
}
admonition = createEl("details", {
cls: `admonition admonition-${type} admonition-plugin`,
attr: attrs
});
titleEl = admonition.createEl("summary", {
cls: `admonition-title ${
!title?.trim().length ? "no-title" : ""
}`
});
} else {
admonition = createDiv({
cls: `admonition admonition-${type} admonition-plugin`,
attr: attrs
});
titleEl = admonition.createDiv({
cls: `admonition-title ${
!title?.trim().length ? "no-title" : ""
}`
});
}
if (id) {
admonition.id = id;
}
if (title && title.trim().length) {
/**
* Title structure
* <div|summary>.admonition-title
* <element>.admonition-title-content - Rendered Markdown top-level element (e.g. H1/2/3 etc, p)
* div.admonition-title-icon
* svg
* div.admonition-title-markdown - Container of rendered markdown
* ...rendered markdown children...
*/
//get markdown
const markdownHolder = createDiv();
MarkdownRenderer.renderMarkdown(title, markdownHolder, "", null);
//admonition-title-content is first child of rendered markdown
const admonitionTitleContent =
markdownHolder.children[0]?.tagName === "P"
? createDiv()
: markdownHolder.children[0];
//get children of markdown element, then remove them
const markdownElements = Array.from(
markdownHolder.children[0]?.childNodes || []
);
admonitionTitleContent.innerHTML = "";
admonitionTitleContent.addClass("admonition-title-content");
//build icon element
const iconEl = admonitionTitleContent.createDiv(
"admonition-title-icon"
);
if (icon && icon.name && icon.type) {
iconEl.appendChild(getIconNode(icon));
}
//add markdown children back
const admonitionTitleMarkdown = admonitionTitleContent.createDiv(
"admonition-title-markdown"
);
for (let i = 0; i < markdownElements.length; i++) {
admonitionTitleMarkdown.appendChild(markdownElements[i]);
}
titleEl.appendChild(admonitionTitleContent || createDiv());
}
//add them to title element
if (collapse) {
titleEl.createDiv("collapser").createDiv("handle");
}
return admonition;
}
async getAdmonitionElementAsync(
type: string,
title: string,
icon: AdmonitionIconDefinition,
color?: string,
collapse?: string,
id?: string
): Promise<HTMLElement> {
let admonition,
titleEl,
attrs: { style?: string; open?: string } = color
? {
style: `--admonition-color: ${color};`
}
: {};
if (collapse) {
if (collapse === "open") {
attrs.open = "open";
}
admonition = createEl("details", {
cls: `admonition admonition-${type} admonition-plugin admonition-plugin-async`,
attr: attrs
});
titleEl = admonition.createEl("summary", {
cls: `admonition-title ${
!title.trim().length ? "no-title" : ""
}`
});
} else {
admonition = createDiv({
cls: `admonition admonition-${type} admonition-plugin`,
attr: attrs
});
titleEl = admonition.createDiv({
cls: `admonition-title ${
!title.trim().length ? "no-title" : ""
}`
});
}
if (id) {
admonition.id = id;
}
if (title && title.trim().length) {
//
// Title structure
// <div|summary>.admonition-title
// <element>.admonition-title-content - Rendered Markdown top-level element (e.g. H1/2/3 etc, p)
// div.admonition-title-icon
// svg
// div.admonition-title-markdown - Container of rendered markdown
// ...rendered markdown children...
//
//get markdown
if (this.data.parseTitles) {
const markdownHolder = createDiv();
await MarkdownRenderer.renderMarkdown(
title,
markdownHolder,
"",
null
);
//admonition-title-content is first child of rendered markdown
const admonitionTitleContent =
markdownHolder.children[0].tagName === "P"
? createDiv()
: markdownHolder.children[0];
//get children of markdown element, then remove them
const markdownElements = Array.from(
markdownHolder.children[0]?.childNodes || []
);
admonitionTitleContent.innerHTML = "";
admonitionTitleContent.addClass("admonition-title-content");
//build icon element
const iconEl = admonitionTitleContent.createDiv(
"admonition-title-icon"
);
if (icon && icon.name && icon.type) {
iconEl.appendChild(getIconNode(icon));
}
//add markdown children back
const admonitionTitleMarkdown =
admonitionTitleContent.createDiv(
"admonition-title-markdown"
);
for (let i = 0; i < markdownElements.length; i++) {
admonitionTitleMarkdown.appendChild(markdownElements[i]);
}
titleEl.appendChild(admonitionTitleContent || createDiv());
} else {
titleEl.appendChild(createDiv({ text: title }));
}
}
//add them to title element
if (collapse) {
titleEl.createDiv("collapser").createDiv("handle");
}
return admonition;
}
}
const rangesInclude = (
ranges: readonly SelectionRange[],
from: number,
to: number
) => {
for (const range of ranges) {
const { from: rFrom, to: rTo } = range;
if (rFrom >= from && rFrom <= to) return true;
if (rTo >= from && rTo <= to) return true;
if (rFrom < from && rTo > to) return true;
}
return false;
}; | the_stack |
import type { RawPlugins, RawSpecs } from '@bangle.dev/core';
import {
Command,
EditorState,
Fragment,
keymap,
Node,
Schema,
setBlockType,
textblockTypeInputRule,
TextSelection,
} from '@bangle.dev/pm';
import {
browser,
ContentNodeWithPos,
filter,
findChildren,
findParentNodeOfType,
insertEmpty,
createObject,
} from '@bangle.dev/utils';
import type Token from 'markdown-it/lib/token';
import type { MarkdownSerializerState } from 'prosemirror-markdown';
import {
copyEmptyCommand,
cutEmptyCommand,
jumpToEndOfNode,
jumpToStartOfNode,
moveNode,
} from '@bangle.dev/pm-commands';
export const spec = specFactory;
export const plugins = pluginsFactory;
export const commands = {
toggleHeading,
queryIsHeadingActive,
};
interface OptionsType {
levels: Array<number>;
}
export const defaultKeys: { [index: string]: string | undefined } = {
toH1: 'Shift-Ctrl-1',
toH2: 'Shift-Ctrl-2',
toH3: 'Shift-Ctrl-3',
toH4: 'Shift-Ctrl-4',
toH5: 'Shift-Ctrl-5',
toH6: 'Shift-Ctrl-6',
moveDown: 'Alt-ArrowDown',
moveUp: 'Alt-ArrowUp',
emptyCopy: 'Mod-c',
emptyCut: 'Mod-x',
insertEmptyParaAbove: 'Mod-Shift-Enter',
jumpToStartOfHeading: browser.mac ? 'Ctrl-a' : 'Ctrl-Home',
jumpToEndOfHeading: browser.mac ? 'Ctrl-e' : 'Ctrl-End',
insertEmptyParaBelow: 'Mod-Enter',
toggleCollapse: undefined,
};
const name = 'heading';
const defaultLevels = [1, 2, 3, 4, 5, 6];
const getTypeFromSchema = (schema: Schema) => schema.nodes[name];
const checkIsInHeading = (state: EditorState) => {
const type = getTypeFromSchema(state.schema);
return findParentNodeOfType(type)(state.selection);
};
const parseLevel = (levelStr: string | number) => {
const level = parseInt(levelStr as string, 10);
return Number.isNaN(level) ? undefined : level;
};
function specFactory({ levels = defaultLevels } = {}): RawSpecs {
if (levels.some((r) => typeof r !== 'number')) {
throw new Error('levels must be number');
}
const options: OptionsType = {
levels,
};
return {
type: 'node',
name,
schema: {
attrs: {
level: {
default: 1,
},
collapseContent: {
default: null,
},
},
content: 'inline*',
group: 'block',
defining: true,
draggable: false,
parseDOM: levels.map((level) => {
return {
tag: `h${level}`,
getAttrs: (dom: any) => {
const result = { level: parseLevel(level) };
const attrs = dom.getAttribute('data-bangle-attrs');
if (!attrs) {
return result;
}
const obj = JSON.parse(attrs);
return Object.assign({}, result, obj);
},
};
}),
toDOM: (node: Node) => {
const result: any = [`h${node.attrs.level}`, {}, 0];
if (node.attrs.collapseContent) {
result[1]['data-bangle-attrs'] = JSON.stringify({
collapseContent: node.attrs.collapseContent,
});
result[1]['class'] = 'bangle-heading-collapsed';
}
return result;
},
},
markdown: {
toMarkdown(state: MarkdownSerializerState, node: Node) {
state.write(state.repeat('#', node.attrs.level) + ' ');
state.renderInline(node);
state.closeBlock(node);
},
parseMarkdown: {
heading: {
block: name,
getAttrs: (tok: Token) => {
return { level: parseLevel(tok.tag.slice(1)) };
},
},
},
},
options,
};
}
function pluginsFactory({
markdownShortcut = true,
keybindings = defaultKeys,
}: {
markdownShortcut?: boolean;
keybindings?: {
[index: string]: string | undefined;
};
} = {}): RawPlugins {
return ({ schema, specRegistry }) => {
const { levels }: OptionsType = specRegistry.options[name];
const type = getTypeFromSchema(schema);
const levelBindings = Object.fromEntries(
levels.map((level: number) => [
keybindings[`toH${level}` as keyof typeof defaultKeys],
setBlockType(type, { level }),
]),
);
return [
keybindings &&
keymap({
...levelBindings,
...createObject([
[keybindings.moveUp, moveNode(type, 'UP')],
[keybindings.moveDown, moveNode(type, 'DOWN')],
[keybindings.jumpToStartOfHeading, jumpToStartOfNode(type)],
[keybindings.jumpToEndOfHeading, jumpToEndOfNode(type)],
[keybindings.emptyCopy, copyEmptyCommand(type)],
[keybindings.emptyCut, cutEmptyCommand(type)],
[keybindings.insertEmptyParaAbove, insertEmptyParaAbove()],
[keybindings.insertEmptyParaBelow, insertEmptyParaBelow()],
[keybindings.toggleCollapse, toggleHeadingCollapse()],
]),
}),
...(markdownShortcut ? levels : []).map((level: number) =>
textblockTypeInputRule(
new RegExp(`^(#{1,${level}})\\s$`),
type,
() => ({
level,
}),
),
),
];
};
}
export function toggleHeading(level = 3): Command {
return (state, dispatch) => {
if (queryIsHeadingActive(level)(state)) {
return setBlockType(state.schema.nodes.paragraph)(state, dispatch);
}
return setBlockType(state.schema.nodes[name], { level })(state, dispatch);
};
}
export function queryIsHeadingActive(level: number) {
return (state: EditorState) => {
const match = findParentNodeOfType(state.schema.nodes[name])(
state.selection,
);
if (!match) {
return false;
}
const { node } = match;
if (level == null) {
return true;
}
return node.attrs.level === level;
};
}
export function queryIsCollapseActive() {
return (state: EditorState) => {
const match = findParentNodeOfType(state.schema.nodes[name])(
state.selection,
);
if (!match || !isCollapsible(match)) {
return false;
}
return Boolean(match.node.attrs.collapseContent);
};
}
export function collapseHeading(): Command {
return (state, dispatch) => {
const match = findParentNodeOfType(state.schema.nodes[name])(
state.selection,
);
if (!match || !isCollapsible(match)) {
return false;
}
const isCollapsed = queryIsCollapseActive()(state);
if (isCollapsed) {
return false;
}
const result = findCollapseFragment(match.node, state.doc);
if (!result) {
return false;
}
const { fragment, start, end } = result;
let tr = state.tr.replaceWith(
start,
end,
state.schema.nodes[name].createChecked(
{
...match.node.attrs,
collapseContent: fragment.toJSON(),
},
match.node.content,
),
);
if (state.selection instanceof TextSelection) {
tr = tr.setSelection(TextSelection.create(tr.doc, state.selection.from));
}
if (dispatch) {
dispatch(tr);
}
return true;
};
}
export function uncollapseHeading(): Command {
return (state, dispatch) => {
const match = findParentNodeOfType(state.schema.nodes[name])(
state.selection,
);
if (!match || !isCollapsible(match)) {
return false;
}
const isCollapsed = queryIsCollapseActive()(state);
if (!isCollapsed) {
return false;
}
const frag = Fragment.fromJSON(
state.schema,
match.node.attrs.collapseContent,
);
let tr = state.tr.replaceWith(
match.pos,
match.pos + match.node.nodeSize,
Fragment.fromArray([
state.schema.nodes[name].createChecked(
{
...match.node.attrs,
collapseContent: null,
},
match.node.content,
),
]).append(frag),
);
if (state.selection instanceof TextSelection) {
tr = tr.setSelection(TextSelection.create(tr.doc, state.selection.from));
}
if (dispatch) {
dispatch(tr);
}
return true;
};
}
export function insertEmptyParaAbove() {
return filter(checkIsInHeading, (state, dispatch, view) => {
return insertEmpty(state.schema.nodes.paragraph, 'above', false)(
state,
dispatch,
view,
);
});
}
export function insertEmptyParaBelow() {
return filter(checkIsInHeading, (state, dispatch, view) => {
return insertEmpty(state.schema.nodes.paragraph, 'below', false)(
state,
dispatch,
view,
);
});
}
export function toggleHeadingCollapse(): Command {
return (state, dispatch) => {
const match = findParentNodeOfType(state.schema.nodes[name])(
state.selection,
);
if (!match || match.depth !== 1) {
return false;
}
const isCollapsed = queryIsCollapseActive()(state);
return isCollapsed
? uncollapseHeading()(state, dispatch)
: collapseHeading()(state, dispatch);
};
}
export function uncollapseAllHeadings(): Command {
return (state, dispatch) => {
const collapsibleNodes = listCollapsedHeading(state);
let tr = state.tr;
let offset = 0;
for (const { node, pos } of collapsibleNodes) {
let baseFrag = Fragment.fromJSON(
state.schema,
flattenFragmentJSON(node.attrs.collapseContent),
);
tr = tr.replaceWith(
offset + pos,
offset + pos + node.nodeSize,
Fragment.fromArray([
state.schema.nodes[name].createChecked(
{
...node.attrs,
collapseContent: null,
},
node.content,
),
]).append(baseFrag),
);
offset += baseFrag.size;
}
if (state.selection instanceof TextSelection) {
tr = tr.setSelection(TextSelection.create(tr.doc, state.selection.from));
}
if (dispatch) {
dispatch(tr);
}
return true;
};
}
export function listCollapsedHeading(state: EditorState) {
return findChildren(
state.doc,
(node) =>
node.type === state.schema.nodes[name] &&
Boolean(node.attrs.collapseContent),
false,
);
}
export function listCollapsibleHeading(state: EditorState) {
return findChildren(
state.doc,
(node) => node.type === state.schema.nodes[name],
false,
);
}
interface JSONObject {
[key: string]: any;
}
export const flattenFragmentJSON = (fragJSON: JSONObject[]) => {
let result: JSONObject[] = [];
fragJSON.forEach((nodeJSON: JSONObject) => {
if (nodeJSON.type === 'heading' && nodeJSON.attrs.collapseContent) {
const collapseContent = nodeJSON.attrs.collapseContent;
result.push({
...nodeJSON,
attrs: {
...nodeJSON.attrs,
collapseContent: null,
},
});
result.push(...flattenFragmentJSON(collapseContent));
} else {
result.push(nodeJSON);
}
});
return result;
};
// TODO
/**
*
* collapse all headings of given level
*/
// export function collapseHeadings(level) {}
/**
* Collapsible headings are only allowed at depth of 1
*/
function isCollapsible(match: ContentNodeWithPos) {
if (match.depth !== 1) {
return false;
}
return true;
}
function findCollapseFragment(matchNode: Node, doc: Node) {
// Find the last child that will be inside of the collapse
let start: { index: number; offset: number; node: Node } | undefined =
undefined;
let end: { index: number; offset: number; node: Node } | undefined =
undefined;
let isDone = false;
const breakCriteria = (node: Node) => {
if (node.type !== matchNode.type) {
return false;
}
if (node.attrs.level <= matchNode.attrs.level) {
return true;
}
return false;
};
doc.forEach((node, offset, index) => {
if (isDone) {
return;
}
if (node === matchNode) {
start = { index, offset, node };
return;
}
if (start) {
if (breakCriteria(node)) {
isDone = true;
return;
}
// Avoid including trailing empty nodes
// (like empty paragraphs inserted by trailing-node-plugins)
// This is done to prevent trailing-node from inserting a new empty node
// every time we toggle on off the collapse.
if (node.content.size !== 0) {
end = { index, offset, node };
}
}
});
if (!end) {
return null;
}
// We are not adding parents position (doc will be parent always) to
// the offsets since it will be 0
const slice = doc.slice(
start!.offset + start!.node.nodeSize,
// @ts-ignore end was incorrectly inferred as "never" here
end.offset + end.node.nodeSize,
);
return {
fragment: slice.content,
start: start!.offset,
// @ts-ignore end was incorrectly inferred as "never" here
end: end.offset + end.node.nodeSize,
};
} | the_stack |
import { Type } from '@angular/core';
import {
ComponentFixture,
discardPeriodicTasks,
fakeAsync,
tick,
} from '@angular/core/testing';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { createComponent as createComponentInner } from '@terminus/ngx-tools/testing';
import * as testComponents from '@terminus/ui/expansion-panel/testing';
// eslint-disable-next-line no-duplicate-imports
import {
getPanelActionRow,
getPanelBodyContentElement,
getPanelDebugElement,
getPanelElement,
getPanelInstance,
getTriggerDescriptionElement,
getTriggerElement,
getTriggerInstance,
getTriggerTitleElement,
togglePanel,
} from '@terminus/ui/expansion-panel/testing';
import { TsExpansionPanelModule } from './expansion-panel.module';
/**
* Create test host component
*
* @param component
*/
// eslint-disable-next-line max-len
const createComponent = <T>(component: Type<T>): ComponentFixture<T> => createComponentInner<T>(component, undefined, [TsExpansionPanelModule, NoopAnimationsModule]);
describe(`TsExpansionPanelComponent`, function() {
describe(`Single panel`, function() {
test(`should defer rendering content when ng-template is used`, fakeAsync(function() {
const fixture = createComponent<testComponents.DeferredContent>(testComponents.DeferredContent);
fixture.detectChanges();
const body = getPanelBodyContentElement(fixture);
expect(body.textContent).toEqual('');
togglePanel(fixture);
tick();
fixture.detectChanges();
expect(body.textContent?.trim()).toEqual('My content');
discardPeriodicTasks();
expect.assertions(2);
}));
test(`should be able to default to open`, function() {
const fixture = createComponent<testComponents.DefaultOpen>(testComponents.DefaultOpen);
fixture.detectChanges();
const triggerElement: HTMLElement = getTriggerElement(fixture);
const panelContainerElement: HTMLElement = getPanelElement(fixture);
const panel = getPanelInstance(fixture);
expect(panel.expanded).toEqual(true);
expect(panel.isExpanded).toEqual(true);
expect(triggerElement.classList).toContain('ts-expansion-panel__trigger--expanded');
expect(panelContainerElement.classList).toContain('ts-expansion-panel--expanded');
});
test(`should be able to disable the panel via input`, function() {
const fixture = createComponent<testComponents.DisabledPanel>(testComponents.DisabledPanel);
fixture.detectChanges();
const triggerElement: HTMLElement = getTriggerElement(fixture);
const panel = getPanelInstance(fixture);
expect(triggerElement.getAttribute('aria-disabled')).toEqual('true');
expect(panel.isDisabled).toEqual(true);
});
test(`should support an action row below panel content`, function() {
const fixture = createComponent<testComponents.ActionRow>(testComponents.ActionRow);
fixture.detectChanges();
const row = getPanelActionRow(fixture);
expect(row).toBeTruthy();
expect(row.textContent).toContain('Foo');
});
test(`should be able to programmatically open, close and toggle`, function() {
const fixture = createComponent<testComponents.ProgrammaticControl>(testComponents.ProgrammaticControl);
fixture.detectChanges();
const panel = getPanelInstance(fixture);
expect(panel.expanded).toEqual(false);
panel.open();
expect(panel.expanded).toEqual(true);
panel.close();
expect(panel.expanded).toEqual(false);
panel.toggle();
expect(panel.expanded).toEqual(true);
panel.toggle();
expect(panel.expanded).toEqual(false);
expect.assertions(5);
});
test(`should be able to programmatically control disabled panels`, function() {
const fixture = createComponent<testComponents.DisabledPanel>(testComponents.DisabledPanel);
fixture.detectChanges();
const panel = getPanelInstance(fixture);
const triggerElement: HTMLElement = getTriggerElement(fixture);
const panelContainerElement: HTMLElement = getPanelElement(fixture);
expect(panel.expanded).toEqual(false);
panel.expanded = true;
fixture.detectChanges();
expect(triggerElement.classList).toContain('ts-expansion-panel__trigger--expanded');
expect(panelContainerElement.classList).toContain('ts-expansion-panel--expanded');
});
test(`should call focus monitor when panel closes while it has focus`, function() {
const fixture = createComponent<testComponents.DefaultOpen>(testComponents.DefaultOpen);
fixture.detectChanges();
const trigger = getTriggerInstance(fixture);
const panel = getPanelInstance(fixture);
Object.defineProperties(panel, { contentContainsFocus: { get: () => true } });
trigger['focusMonitor'].focusVia = jest.fn();
panel.expanded = false;
fixture.detectChanges();
expect(trigger['focusMonitor'].focusVia).toHaveBeenCalled();
});
test(`should not have shadow when transparent mode is set`, () => {
const fixture = createComponent<testComponents.TransparentModePanel>(testComponents.TransparentModePanel);
fixture.detectChanges();
const triggerElement: HTMLElement = getTriggerElement(fixture);
const panelContainerElement: HTMLElement = getPanelElement(fixture);
expect(triggerElement.classList).toContain('ts-expansion-panel__trigger--transparent');
expect(panelContainerElement.classList).not.toContain('ts-expansion-panel--shadow');
});
describe(`Events`, function() {
test(`should emit opened and closed events`, function() {
const fixture = createComponent<testComponents.Events>(testComponents.Events);
fixture.detectChanges();
const host = fixture.componentInstance;
host.opened = jest.fn();
host.closed = jest.fn();
host.expandedChange = jest.fn();
togglePanel(fixture);
expect(host.opened).toHaveBeenCalledTimes(1);
expect(host.expandedChange).toHaveBeenCalledWith(true);
togglePanel(fixture);
expect(host.closed).toHaveBeenCalledTimes(1);
expect(host.expandedChange).toHaveBeenCalledWith(false);
});
test(`should emit events when animations finish`, function() {
const fixture = createComponent<testComponents.Events>(testComponents.Events);
fixture.detectChanges();
const host = fixture.componentInstance;
host.afterCollapse = jest.fn();
host.afterExpand = jest.fn();
togglePanel(fixture).then(() => {
expect(host.afterExpand).toHaveBeenCalledTimes(1);
});
togglePanel(fixture).then(() => {
expect(host.afterCollapse).toHaveBeenCalledTimes(1);
});
expect.assertions(2);
});
test(`should emit when destroyed`, function() {
const fixture = createComponent<testComponents.Events>(testComponents.Events);
fixture.detectChanges();
const host = fixture.componentInstance;
const panel = getPanelInstance(fixture);
host.destroyed = jest.fn();
panel.ngOnDestroy();
expect(host.destroyed).toHaveBeenCalledTimes(1);
});
});
});
describe(`Panel trigger`, function() {
test(`should support title and descriptions`, function() {
const fixture = createComponent<testComponents.TriggerTitleDescription>(testComponents.TriggerTitleDescription);
fixture.detectChanges();
const title = getTriggerTitleElement(fixture);
const description = getTriggerDescriptionElement(fixture);
expect(title.textContent?.trim()).toEqual('My title');
expect(description.textContent?.trim()).toEqual('My description');
});
test(`should have customizable collapsed and expanded heights`, fakeAsync(function() {
const fixture = createComponent<testComponents.CustomHeights>(testComponents.CustomHeights);
fixture.detectChanges();
const triggerElement: HTMLElement = getTriggerElement(fixture);
// Open the panel
togglePanel(fixture);
tick();
fixture.detectChanges();
expect(triggerElement.getAttribute('style')).toContain('height:66px');
// Close the panel
togglePanel(fixture);
tick();
fixture.detectChanges();
expect(triggerElement.getAttribute('style')).toContain('height:33px');
discardPeriodicTasks();
expect.assertions(2);
}));
test(`should be able to set custom heights & toggle visibility via provider configuration`, fakeAsync(function() {
const fixture = createComponent<testComponents.CustomDefaults>(testComponents.CustomDefaults);
fixture.detectChanges();
const triggerElement: HTMLElement = getTriggerElement(fixture);
// Open the panel
togglePanel(fixture);
tick();
fixture.detectChanges();
expect(triggerElement.getAttribute('style')).toContain('height:88px');
// Close the panel
togglePanel(fixture);
tick();
fixture.detectChanges();
expect(triggerElement.getAttribute('style')).toContain('height:55px');
const toggleIcon = triggerElement.querySelector('.ts-expansion-panel__indicator');
expect(toggleIcon).toBeNull();
discardPeriodicTasks();
expect.assertions(3);
}));
test(`should be able to hide the toggle icon`, function() {
const fixture = createComponent<testComponents.HideToggle>(testComponents.HideToggle);
fixture.detectChanges();
const triggerElement: HTMLElement = getTriggerElement(fixture);
const toggleIcon = triggerElement.querySelector('.ts-expansion-panel__indicator');
expect(toggleIcon).toBeNull();
});
test(`should pass program through to focus monitor`, function() {
const fixture = createComponent<testComponents.SinglePanel>(testComponents.SinglePanel);
fixture.detectChanges();
const trigger = getTriggerInstance(fixture);
trigger['focusMonitor'].focusVia = jest.fn();
trigger.focus();
expect(trigger['focusMonitor'].focusVia.mock.calls[0][1]).toEqual('program');
trigger.focus('keyboard');
expect(trigger['focusMonitor'].focusVia.mock.calls[1][1]).toEqual('keyboard');
});
});
describe(`Accessibility`, function() {
test(`should have the correct role and aria labels on triggers`, function() {
const fixture = createComponent<testComponents.SinglePanel>(testComponents.SinglePanel);
fixture.detectChanges();
const triggerElement = getTriggerElement(fixture);
expect(triggerElement.getAttribute('aria-controls')).toEqual(expect.stringContaining('cdk-accordion-child-'));
expect(triggerElement.getAttribute('role')).toEqual('button');
});
test(`should have the correct role and aria labels on panels`, function() {
const fixture = createComponent<testComponents.SinglePanel>(testComponents.SinglePanel);
fixture.detectChanges();
const panelDebugElement = getPanelDebugElement(fixture);
const panelElement = panelDebugElement.nativeElement.querySelector('.ts-expansion-panel__content');
expect(panelElement.getAttribute('role')).toEqual('region');
expect(panelElement.getAttribute('aria-labelledby')).toEqual(expect.stringContaining('ts-expansion-panel-trigger-'));
expect(panelElement.getAttribute('aria-hidden')).toEqual('true');
togglePanel(fixture);
expect(panelElement.getAttribute('aria-hidden')).toEqual('false');
});
});
describe(`contentContainsFocus`, function() {
test(`should return false if the panel doesn't exist`, function() {
const fixture = createComponent<testComponents.SinglePanel>(testComponents.SinglePanel);
fixture.detectChanges();
const panel = getPanelInstance(fixture);
panel.panelBody = undefined as any;
fixture.detectChanges();
expect(panel.contentContainsFocus).toEqual(false);
});
});
}); | the_stack |
import * as React from 'react'
import { useContext, useRef, useMemo } from 'react'
import { OneOrMore, UnknownProps } from '@react-spring/types'
import {
is,
toArray,
useForceUpdate,
useOnce,
usePrev,
each,
useLayoutEffect,
} from '@react-spring/shared'
import {
Change,
ControllerUpdate,
ItemKeys,
PickAnimated,
TransitionFn,
TransitionState,
TransitionTo,
UseTransitionProps,
} from '../types'
import { Valid } from '../types/common'
import {
callProp,
detachRefs,
getDefaultProps,
hasProps,
inferTo,
replaceRef,
} from '../helpers'
import { Controller, getSprings } from '../Controller'
import { SpringContext } from '../SpringContext'
import { SpringRef } from '../SpringRef'
import type { SpringRef as SpringRefType } from '../SpringRef'
import { TransitionPhase } from '../TransitionPhase'
declare function setTimeout(handler: Function, timeout?: number): number
declare function clearTimeout(timeoutId: number): void
export function useTransition<Item, Props extends object>(
data: OneOrMore<Item>,
props: () =>
| UseTransitionProps<Item>
| (Props & Valid<Props, UseTransitionProps<Item>>),
deps?: any[]
): PickAnimated<Props> extends infer State
? [TransitionFn<Item, PickAnimated<Props>>, SpringRefType<State>]
: never
export function useTransition<Item, Props extends object>(
data: OneOrMore<Item>,
props:
| UseTransitionProps<Item>
| (Props & Valid<Props, UseTransitionProps<Item>>)
): TransitionFn<Item, PickAnimated<Props>>
export function useTransition<Item, Props extends object>(
data: OneOrMore<Item>,
props:
| UseTransitionProps<Item>
| (Props & Valid<Props, UseTransitionProps<Item>>),
deps: any[] | undefined
): PickAnimated<Props> extends infer State
? [TransitionFn<Item, State>, SpringRefType<State>]
: never
export function useTransition(
data: unknown,
props: UseTransitionProps | (() => any),
deps?: any[]
): any {
const propsFn = is.fun(props) && props
const {
reset,
sort,
trail = 0,
expires = true,
onDestroyed,
ref: propsRef,
config: propsConfig,
}: UseTransitionProps<any> = propsFn ? propsFn() : props
// Return a `SpringRef` if a deps array was passed.
const ref = useMemo(
() => (propsFn || arguments.length == 3 ? SpringRef() : void 0),
[]
)
// Every item has its own transition.
const items = toArray(data)
const transitions: TransitionState[] = []
// The "onRest" callbacks need a ref to the latest transitions.
const usedTransitions = useRef<TransitionState[] | null>(null)
const prevTransitions = reset ? null : usedTransitions.current
useLayoutEffect(() => {
usedTransitions.current = transitions
})
// Destroy all transitions on dismount.
useOnce(
() => () =>
each(usedTransitions.current!, t => {
if (t.expired) {
clearTimeout(t.expirationId!)
}
detachRefs(t.ctrl, ref)
t.ctrl.stop(true)
})
)
// Keys help with reusing transitions between renders.
// The `key` prop can be undefined (which means the items themselves are used
// as keys), or a function (which maps each item to its key), or an array of
// keys (which are assigned to each item by index).
const keys = getKeys(items, propsFn ? propsFn() : props, prevTransitions)
// Expired transitions that need clean up.
const expired = (reset && usedTransitions.current) || []
useLayoutEffect(() =>
each(expired, ({ ctrl, item, key }) => {
detachRefs(ctrl, ref)
callProp(onDestroyed, item, key)
})
)
// Map old indices to new indices.
const reused: number[] = []
if (prevTransitions)
each(prevTransitions, (t, i) => {
// Expired transitions are not rendered.
if (t.expired) {
clearTimeout(t.expirationId!)
expired.push(t)
} else {
i = reused[i] = keys.indexOf(t.key)
if (~i) transitions[i] = t
}
})
// Mount new items with fresh transitions.
each(items, (item, i) => {
if (!transitions[i]) {
transitions[i] = {
key: keys[i],
item,
phase: TransitionPhase.MOUNT,
ctrl: new Controller(),
}
transitions[i].ctrl.item = item
}
})
// Update the item of any transition whose key still exists,
// and ensure leaving transitions are rendered until they finish.
if (reused.length) {
let i = -1
const { leave }: UseTransitionProps<any> = propsFn ? propsFn() : props
each(reused, (keyIndex, prevIndex) => {
const t = prevTransitions![prevIndex]
if (~keyIndex) {
i = transitions.indexOf(t)
transitions[i] = { ...t, item: items[keyIndex] }
} else if (leave) {
transitions.splice(++i, 0, t)
}
})
}
if (is.fun(sort)) {
transitions.sort((a, b) => sort(a.item, b.item))
}
// Track cumulative delay for the "trail" prop.
let delay = -trail
// Expired transitions use this to dismount.
const forceUpdate = useForceUpdate()
// These props are inherited by every phase change.
const defaultProps = getDefaultProps<UseTransitionProps>(props)
// Generate changes to apply in useEffect.
const changes = new Map<TransitionState, Change>()
each(transitions, (t, i) => {
const key = t.key
const prevPhase = t.phase
const p: UseTransitionProps<any> = propsFn ? propsFn() : props
let to: TransitionTo<any>
let phase: TransitionPhase
let propsDelay = callProp(p.delay || 0, key)
if (prevPhase == TransitionPhase.MOUNT) {
to = p.enter
phase = TransitionPhase.ENTER
} else {
const isLeave = keys.indexOf(key) < 0
if (prevPhase != TransitionPhase.LEAVE) {
if (isLeave) {
to = p.leave
phase = TransitionPhase.LEAVE
} else if ((to = p.update)) {
phase = TransitionPhase.UPDATE
} else return
} else if (!isLeave) {
to = p.enter
phase = TransitionPhase.ENTER
} else return
}
// When "to" is a function, it can return (1) an array of "useSpring" props,
// (2) an async function, or (3) an object with any "useSpring" props.
to = callProp(to, t.item, i)
to = is.obj(to) ? inferTo(to) : { to }
/**
* This would allow us to give different delays for phases.
* If we were to do this, we'd have to suffle the prop
* spreading below to set delay last.
* But if we were going to do that, we should consider letting
* the prop trail also be part of a phase.
*/
// if (to.delay) {
// phaseDelay = callProp(to.delay, key)
// }
if (!to.config) {
const config = propsConfig || defaultProps.config
to.config = callProp(config, t.item, i, phase)
}
delay += trail
// The payload is used to update the spring props once the current render is committed.
const payload: ControllerUpdate<UnknownProps> = {
...defaultProps,
// we need to add our props.delay value you here.
delay: propsDelay + delay,
ref: propsRef,
immediate: p.immediate,
// This prevents implied resets.
reset: false,
// Merge any phase-specific props.
...(to as any),
}
if (phase == TransitionPhase.ENTER && is.und(payload.from)) {
const p = propsFn ? propsFn() : props
// The `initial` prop is used on the first render of our parent component,
// as well as when `reset: true` is passed. It overrides the `from` prop
// when defined, and it makes `enter` instant when null.
const from = is.und(p.initial) || prevTransitions ? p.from : p.initial
payload.from = callProp(from, t.item, i)
}
const { onResolve } = payload
payload.onResolve = result => {
callProp(onResolve, result)
const transitions = usedTransitions.current!
const t = transitions.find(t => t.key === key)
if (!t) return
// Reset the phase of a cancelled enter/leave transition, so it can
// retry the animation on the next render.
if (result.cancelled && t.phase != TransitionPhase.UPDATE) {
/**
* @legacy Reset the phase of a cancelled enter/leave transition, so it can
* retry the animation on the next render.
*
* Note: leaving this here made the transitioned item respawn.
*/
// t.phase = prevPhase
return
}
if (t.ctrl.idle) {
const idle = transitions.every(t => t.ctrl.idle)
if (t.phase == TransitionPhase.LEAVE) {
const expiry = callProp(expires, t.item)
if (expiry !== false) {
const expiryMs = expiry === true ? 0 : expiry
t.expired = true
// Force update once the expiration delay ends.
if (!idle && expiryMs > 0) {
// The maximum timeout is 2^31-1
if (expiryMs <= 0x7fffffff)
t.expirationId = setTimeout(forceUpdate, expiryMs)
return
}
}
}
// Force update once idle and expired items exist.
if (idle && transitions.some(t => t.expired)) {
forceUpdate()
}
}
}
const springs = getSprings(t.ctrl, payload)
changes.set(t, { phase, springs, payload })
})
// The prop overrides from an ancestor.
const context = useContext(SpringContext)
const prevContext = usePrev(context)
const hasContext = context !== prevContext && hasProps(context)
// Merge the context into each transition.
useLayoutEffect(() => {
if (hasContext)
each(transitions, t => {
t.ctrl.start({ default: context })
})
}, [context])
useLayoutEffect(
() => {
each(changes, ({ phase, payload }, t) => {
const { ctrl } = t
t.phase = phase
// Attach the controller to our local ref.
ref?.add(ctrl)
// Merge the context into new items.
if (hasContext && phase == TransitionPhase.ENTER) {
ctrl.start({ default: context })
}
if (payload) {
// Update the injected ref if needed.
replaceRef(ctrl, payload.ref)
// When an injected ref exists, the update is postponed
// until the ref has its `start` method called.
if (ctrl.ref) {
ctrl.update(payload)
} else {
ctrl.start(payload)
}
}
})
},
reset ? void 0 : deps
)
const renderTransitions: TransitionFn = render => (
<>
{transitions.map((t, i) => {
const { springs } = changes.get(t) || t.ctrl
const elem: any = render({ ...springs }, t.item, t, i)
return elem && elem.type ? (
<elem.type
{...elem.props}
key={is.str(t.key) || is.num(t.key) ? t.key : t.ctrl.id}
ref={elem.ref}
/>
) : (
elem
)
})}
</>
)
return ref ? [renderTransitions, ref] : renderTransitions
}
/** Local state for auto-generated item keys */
let nextKey = 1
function getKeys(
items: readonly any[],
{ key, keys = key }: { key?: ItemKeys; keys?: ItemKeys },
prevTransitions: TransitionState[] | null
): readonly any[] {
if (keys === null) {
const reused = new Set()
return items.map(item => {
const t =
prevTransitions &&
prevTransitions.find(
t =>
t.item === item &&
t.phase !== TransitionPhase.LEAVE &&
!reused.has(t)
)
if (t) {
reused.add(t)
return t.key
}
return nextKey++
})
}
return is.und(keys) ? items : is.fun(keys) ? items.map(keys) : toArray(keys)
} | the_stack |
import { CPSFunction, Righto, RightoAfter } from '.';
/** Represents a type as either the type itself, a righto of the type, or a promise of the type */
type Flexible<T, ET = any> = T|Promise<T>|Righto<[T | undefined, ...any[]], ET>;
/** Accepts an array of types and returns a array of each type OR'd with eventual representations (Righto and promise) */
type ArgsAsFlexible<AT extends any[], ET> = {
[T in keyof AT]: Flexible<AT[T], ET>
};
/** Transforms an object type to unwrap its Righto typed properties */
type ResolvedObject<T> = {
[P in keyof T]: T[P] extends Righto<infer X> ? X[0] : T[P]
};
/** Recursively transforms an object type to unwrap its Righto typed properties into "unknown" */
type ResolvedObjectRecursive<T> = {
[P in keyof T]: T[P] extends Righto<infer X> ? X[0] :
T[P] extends object ? ResolvedObjectRecursive<T[P]> :
T[P]
};
/** Maps an array of types into their righto representations */
type RightoArrayFrom<T extends any[], ET> = {
[P in keyof T]: Righto<[T[P]], ET>
};
/**
* Constructor for a righto object. Accepts a CPS function to represent the async task, followed by the arguments to the CPS function excluding the callback.
* @example
* function divideNumbersAsync(a: number, b: number, callback: (error?: Error, result?: number) => void) {
* setTimeout(() => {
* if (b === 0) callback(new Error("Cannot divide by zero"));
* else callback(undefined, a / b);
* }, 1000);
* }
*
* let rResult = righto(divideNumbersAsync, 2, 1); // A righto object that will eventually resolve to 2
* rResult((err, result) => console.log(result)); // Will print '2' to the console
*
* // You can also pass eventuals as arguments to the CPS function and they will automatically be resolved
* let rResult2 = righto(divideNumbersAsync, 5, rResult); // A righto object that will eventually resolve to 2.5
* rResult2((err, result) => console.log(result)); // Will print '2.5' to the console
*/
declare function righto<AT extends any[], RT extends any[], ET = any>(fn: CPSFunction<AT, RT, ET>, ...args: ArgsAsFlexible<AT, ET>): Righto<RT, ET>;
// Righto constructor to allow for a single righto.after to appear before the function arguments
declare function righto<AT extends any[], RT extends any[], ET = any>(fn: CPSFunction<AT, RT, ET>, after: RightoAfter, ...args: ArgsAsFlexible<AT, ET>): Righto<RT, ET>;
// Righto constructor to allow for a single righto.after to appear after the function arguments
declare function righto<AT extends any[], RT extends any[], ET = any>(fn: CPSFunction<AT, RT, ET>, ...args: [...ArgsAsFlexible<AT, ET>, RightoAfter]): Righto<RT, ET>;
// Righto constructor to allow for two righto.after statements to appear, once before the argument list and once after
declare function righto<AT extends any[], RT extends any[], ET = any>(fn: CPSFunction<AT, RT, ET>, after: RightoAfter, ...args: [...ArgsAsFlexible<AT, ET>, RightoAfter]): Righto<RT, ET>;
// Library for function righto methods
declare namespace righto {
/** A callback function that accepts a single error argument, with any number of return arguments */
type ErrBack<RT extends any[] = [], ET = any> = (err?: ET, ...results: {[P in keyof RT]?: RT[P]}) => void;
/** Usually an async function that accepts any number of parameters, then returns a result or error through an ErrBack method */
type CPSFunction<AT extends any[], RT extends any[], ET> = (...args: [...AT, ErrBack<RT, ET>]) => void;
/** A righto that does not resolve to any value, used for introducing delays in righto argument chains */
type RightoAfter = Righto<[]>;
/** Represents a constructed righto object */
interface Righto<RT extends any[], ET = any> extends CPSFunction<[], RT, ET> {
get(prop: string|number|Righto<[string, ...any[]]>|Righto<[number, ...any[]]>): Righto<[any], ET>;
get<T>(fn: (x: RT[0]) => T): Righto<[T], ET>;
/** You can force a righto task for run at any time without dealing with the results (or error) by calling it with no arguments */
(): Righto<RT, ET>;
/** When true, this righto will print a graph trace if it rejects, highlighting the offending task. */
_traceOnError: boolean;
/** Prints a stack trace for this righto to the console. Only works if righto._debug was set to true *before* instantiating this righto */
_trace(): void;
}
/**
* Forks a righto into a callback suitable for the promise constructor
* @param righto Righto to fork
* @example
* var somePromise = new Promise(righto.fork(someRighto));
*/
function fork<RT extends any[]>(righto: Righto<RT>): (resolve: (x: RT[0]) => void, reject: (x: any) => void) => void;
/**
* Righto supports running a generator (or any nextable iterator):
* @param iterator The iterator to run
* @example
* var generated = righto.iterate(function*(a, b, c){
* var x = yield righto(function(done){
* setTimeout(function(){
* done(null, 'x');
* });
* });
*
* var y = yield righto(function(done){
* setTimeout(function(){
* done(null, 'y');
* });
* });
*
* return x + y + a + b + c;
* });
*
* var result = generated('a', 'b', 'c');
*
* result(function(error, result){
* result === 'xyabc';
* });
*/
function iterate<AT extends any[], RT, ET>(constructGenerator: (...args: AT) => Generator<Righto<[RT], ET>, RT, RT>): (...args: AT) => Righto<[RT], ET>;
/**
* You can pick and choose what results are used from a dependency like so:
* @param righto The righto to take results from
* @param args The (0-indexed) position of each argument to take
* @example
* var getBar = righto(bar, righto.take(getFoo, 0, 2)); // Take result 0, and result 2, from getFoo
* getBar(function(error, result){
* result -> 'first third';
* });
*/
function take<IDXS extends number[], ET>(righto: Righto<any[], ET>, ...args: IDXS): Righto<{[P in keyof IDXS]: any}, ET>;
/**
* Righto.reduce takes an Array of values (an an eventual that resolves to an array) as the first argument, resolves them from left-to-right,
* optionally passing the result of the last, and the next task to a reducer.
* When no reducer is passed, the tasks will be resolved in series, and the final tasks result will be passed as the result from reduce.
* If no tasks are passed, the final result will be undefined.
* @param values The rightos to reduce
* @example
* function a(callback){
* aCalled = true;
* t.pass('a called');
* callback(null, 1);
* }
* function b(callback){
* t.ok(aCalled, 'b called after a');
* callback(null, 2);
* }
* var result = righto.reduce([righto(a), righto(b)]);
* result(function(error, finalResult){
* // finalResult === 2
* });
*/
function reduce<RT, ET = any>(values: Array<Righto<[RT], ET>>): Righto<[RT], ET>;
/**
* Righto.reduce takes an Array of values (an an eventual that resolves to an array) as the first argument, resolves them from left-to-right,
* optionally passing the result of the last, and the next task to a reducer.
* When a reducer is used, a seed can optionally be passed as the third parameter.
* If no tasks are passed, the final result will be undefined.
* @param values The functions to reduce
* @param reducer The reducer function
* @param seed The initial value for the reducer function
* @example
* function a(last, callback){
* aCalled = true;
* t.pass('a called');
* callback(null, last);
* }
*
* function b(last, callback){
* t.ok(aCalled, 'b called after a');
* callback(null, last + 2);
* }
*
* // Passes previous eventual result to next reducer call.
* var result = righto.reduce(
* [a, b],
* function(result, next){ // Reducer
* return righto(next, result);
* },
* 5 // Seed
* );
*
* result(function(error, finalResult){
* // finalResult === 7
* });
*/
function reduce<RT, ET = any>(values: Array<CPSFunction<[RT], [RT], ET>>, reducer: (result: RT, next: CPSFunction<[RT], [RT], ET>) => Righto<[RT], ET>, seed?: RT): Righto<[RT], ET>;
/**
* righto.all takes N tasks, or an Array of tasks as the first argument, resolves them all in parallel, and results in an Array of results.
* @param tasks The tasks to resolve
* @example
* var task1 = righto(function(done){
* setTimeout(function(){
* done(null, 'a');
* }, 1000);
* });
*
* var task2 = righto(function(done){
* setTimeout(function(){
* done(null, 'b');
* }, 1000);
* });
*
* var task3 = righto(function(done){
* setTimeout(function(){
* done(null, 'c');
* }, 1000);
* });
*
* var all = righto.all([task1, task2, task3]);
*
* all(function(error, results){
* results; // -> ['a','b','c']
* });
*/
function all<RT, ET = any>(tasks: Array<Righto<[RT], ET>>): Righto<[RT[]], ET>;
function all(tasks: Array<Righto<any>>): Righto<[any[]]>;
/**
* Synchronous functions can be used to create righto tasks using righto.sync:
* @param fn Synchronous function
* @param after Optional null righto argument, used for passing in a righto.after object, if required
* @param args Arguments to synchronous function, as either resolved types or eventuals (righto or promise)
* @example
* var someNumber = righto(function(done){
* setTimeout(function(){
* done(null, 5);
* }, 1000);
* }
* function addFive(value){
* return value + 5;
* }
* var syncTask = righto.sync(addFive, someNumber);
* syncTask(function(error, result){
* result; // -> 10
* });
*/
function sync<AT extends any[], RT, ET = any>(fn: (...args: AT) => RT, ...args: ArgsAsFlexible<AT, ET>): Righto<[RT], ET>;
function sync<AT extends any[], RT, ET = any>(fn: (...args: AT) => RT, after: RightoAfter, ...args: ArgsAsFlexible<AT, ET>): Righto<[RT], ET>;
function sync<AT extends any[], RT, ET = any>(fn: (...args: AT) => RT, after: RightoAfter, ...args: [...ArgsAsFlexible<AT, ET>, RightoAfter]): Righto<[RT], ET>;
/**
* Anything can be converted to a righto with righto.from(anything);
* @param source The source object to create a righto from
* @example
* righto.from(someRighto); // Returns someRighto
* righto.from(somePromise); // Returns a new righto that resolves the promise
* righto.from(5); // Returns a new righto that resolves 5
*/
function from<T, ET = any>(source: Righto<[T], ET>|Promise<T>): Righto<[T], ET>;
function from<T>(source: T): Righto<[T], undefined>;
/**
* Sometimes it may be required to pass a resolvable (a righto, or promise) as an argument rather than passing the resolved value of the resolvable. you can do this using righto.value(resolvable)
* @param resolvable The resolvable to wrap
* @example
* var righto1 = righto(function(done){
* done(null, 5);
* });
*
* var rightoValue = righto.value(righto1);
*
* var righto2 = righto(function(value, done){
* // value === righto1
*
* value(function(error, x){
* // x === 5;
* });
*
* }, rightoValue);
*
* righto2();
*/
function value<T, ET = any>(resolvable: Righto<[T], ET>|Promise<T>): Righto<[Righto<[T], ET>], ET>;
/**
* You can resolve a task to an array containing either the error or results from a righto with righto.surely, which resolves to an array in the form of [error?, results...?].
* @param fn The function to process
* @param args The arguments to the function
* @example
* var errorOrX = righto.surely(function(done){
* done(new Error('borked'));
* });
*
* var errorOrY = righto.surely(function(done){
* done(null, 'y');
* });
*
* var z = righto(function([xError, x], [yError, y]){
*
* xError; // -> Error 'borked'
* x; // -> undefined
* yError; // -> null
* y; // -> 'y'
*
* }, errorOrX, errorOrY);
*
* z();
*/
function surely<AT extends any[], RT extends any[], ET>(fn: CPSFunction<AT, RT, ET>, ...args: ArgsAsFlexible<AT, ET>): Righto<[[ET, ...RT]], ET>;
/**
* Wrap a righto task with a handler that either forwards the successful result, or sends the rejected error through a handler to resolve the task.
* @param righto The righto that may throw an error
* @param handler The error handler
* @example
* function mightFail(callback){
* if(Math.random() > 0.5){
* callback('borked');
* }else{
* callback(null, 'result');
* }
* };
*
* function defaultString(error, callback){
* callback(null, '');
* }
*
* var maybeAString = righto(mightFail),
* aString = righto.handle(maybeAString, defaultString);
*
* aString(function(error, result){
* typeof result === 'string';
* });
*/
function handle<RT extends any[], ET>(righto: Righto<RT, ET>, handler: CPSFunction<[ET], RT, ET>): Righto<RT, ET>;
/**
* Sometimes you need a task to run after another has succeeded, but you don't need its results, righto.after(task1, task2, taskN...) can be used to achieve this.
* @param rightos The tasks to wait on
* @example
* function foo(callback){
* setTimeout(function(){
* callback(null, 'first result');
* }, 1000);
* }
* var getFoo = righto(foo);
* function bar(callback){
* callback(null, 'second result');
* }
* var getBar = righto(bar, righto.after(getFoo)); // wait for foo before running bar.
* getBar(function(error, result){
* result -> 'second result';
* });
*/
function after(...rightos: Array<Righto<any>>): RightoAfter;
/**
* Resolves an object to a new object where any righto values are resolved.
* @param obj Object to resolve
* @param recursive Whether or not to recursively resolve objects
* @example
* var foo = righto(function(callback){
* asyncify(function(){
* callback(null, 'foo');
* });
* });
* var bar = righto.resolve({foo: {bar: foo}}, true);
* bar(function(error, bar){
* bar; // -> {foo: {bar: 'foo'}}
* });
*/
function resolve<T, B extends boolean>(obj: T, recursive: B): B extends true ? ResolvedObjectRecursive<T> : ResolvedObject<T>;
function resolve<T>(obj: T): ResolvedObject<T>;
/**
* Occasionally you might want to mate a number of tasks into one task.
* For this, you can use righto.mate.
* @param rightos List of righto's to mate
* @example
* function getStuff(callback){
* // eventually...
* callback(null, 3);
* }
* var stuff = righto(getStuff);
* function getOtherStuff(callback){
* // eventually...
* callback(null, 7);
* }
* var otherStuff = righto(getOtherStuff);
* var stuffAndOtherStuff = righto.mate(stuff, otherStuff);
* stuffAndOtherStuff(function(error, stuff, otherStuff){
* error -> null
* stuff -> 3
* otherStuff -> 7
* });
*/
function mate<RT extends any[], ET>(...rightos: RightoArrayFrom<RT, ET>): Righto<RT, ET>;
/**
* A shorthand way to provide a failed result. This is handy for rejecting in .get methods.
* @param err The error to throw
* @example
* var something = someRighto.get(function(value){
* if(!value){
* return righto.fail('was falsey');
* }
* return value;
* });
*/
function fail<ET>(err: ET): Righto<[], ET>;
/**
* If you are using righto in an environment that supports proxies, you can use the proxy API
* @example
* var righto = require('righto').proxy;
*
* var foo = righto(function(done){
* setTimeout(function(){
* done(null, {foo: 'bar'});
* });
* });
*
* foo.bar(function(error, bar){
* bar === 'bar'
* });
*/
function proxy<AT extends any[]>(fn: CPSFunction<AT, any[], any>, ...args: AT): any;
/**
* Enables or disables debug logging. When true, stack traces can be retrieved from each righto object using [righto instance].trace();
* @example
* righto._debug = true;
* var someRighto = righto.from(a);
* someRighto.trace();
*/
let _debug: boolean;
/**
* You can globally tell righto to print a graph trace, highlighting the offending task, when a graph rejects.
*/
let _autotraceOnError: boolean;
/** Determines whether an object is a righto */
function isRighto(obj: any): boolean;
/** Determines whether an object supports the promise-like `x.then(y => ...)` resolution syntax */
function isThenable(obj: any): boolean;
/** Determines whether an object is a righto or thenable */
function isResolvable(obj: any): boolean;
}
export = righto; | the_stack |
import * as Models from './models';
import * as Parameters from './parameters';
import { Client } from '../clients';
import { Callback } from '../callback';
import { RequestConfig } from '../requestConfig';
export class IssueRemoteLinks {
constructor(private client: Client) {}
/**
* Returns the remote issue links for an issue. When a remote issue link global ID is provided the record with that
* global ID is returned, otherwise all remote issue links are returned. Where a global ID includes reserved URL
* characters these must be escaped in the request. For example, pass `system=http://www.mycompany.com/support&id=1`
* as `system%3Dhttp%3A%2F%2Fwww.mycompany.com%2Fsupport%26id%3D1`.
*
* This operation requires [issue linking to be active](https://confluence.atlassian.com/x/yoXKM).
*
* This operation can be accessed anonymously.
*
* **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:**
*
* - *Browse projects* [project permission](https://confluence.atlassian.com/x/yodKLg) for the project that the issue is in.
* - If [issue-level security](https://confluence.atlassian.com/x/J4lKLg) is configured, issue-level security permission
* to view the issue.
*/
async getRemoteIssueLinks<T = Models.RemoteIssueLink>(
parameters: Parameters.GetRemoteIssueLinks,
callback: Callback<T>
): Promise<void>;
/**
* Returns the remote issue links for an issue. When a remote issue link global ID is provided the record with that
* global ID is returned, otherwise all remote issue links are returned. Where a global ID includes reserved URL
* characters these must be escaped in the request. For example, pass `system=http://www.mycompany.com/support&id=1`
* as `system%3Dhttp%3A%2F%2Fwww.mycompany.com%2Fsupport%26id%3D1`.
*
* This operation requires [issue linking to be active](https://confluence.atlassian.com/x/yoXKM).
*
* This operation can be accessed anonymously.
*
* **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:**
*
* - *Browse projects* [project permission](https://confluence.atlassian.com/x/yodKLg) for the project that the issue is in.
* - If [issue-level security](https://confluence.atlassian.com/x/J4lKLg) is configured, issue-level security permission
* to view the issue.
*/
async getRemoteIssueLinks<T = Models.RemoteIssueLink>(
parameters: Parameters.GetRemoteIssueLinks,
callback?: never
): Promise<T>;
async getRemoteIssueLinks<T = Models.RemoteIssueLink>(
parameters: Parameters.GetRemoteIssueLinks,
callback?: Callback<T>,
): Promise<void | T> {
const config: RequestConfig = {
url: `/rest/api/2/issue/${parameters.issueIdOrKey}/remotelink`,
method: 'GET',
params: {
globalId: parameters.globalId,
},
};
return this.client.sendRequest(config, callback, { methodName: 'version2.issueRemoteLinks.getRemoteIssueLinks' });
}
/**
* Creates or updates a remote issue link for an issue.
*
* If a `globalId` is provided and a remote issue link with that global ID is found it is updated. Any fields without
* values in the request are set to null. Otherwise, the remote issue link is created.
*
* This operation requires [issue linking to be active](https://confluence.atlassian.com/x/yoXKM).
*
* This operation can be accessed anonymously.
*
* **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:**
*
* - *Browse projects* and *Link issues* [project permission](https://confluence.atlassian.com/x/yodKLg) for the project
* that the issue is in.
* - If [issue-level security](https://confluence.atlassian.com/x/J4lKLg) is configured, issue-level security permission
* to view the issue.
*/
async createOrUpdateRemoteIssueLink<T = Models.RemoteIssueLinkIdentifies>(
parameters: Parameters.CreateOrUpdateRemoteIssueLink,
callback: Callback<T>
): Promise<void>;
/**
* Creates or updates a remote issue link for an issue.
*
* If a `globalId` is provided and a remote issue link with that global ID is found it is updated. Any fields without
* values in the request are set to null. Otherwise, the remote issue link is created.
*
* This operation requires [issue linking to be active](https://confluence.atlassian.com/x/yoXKM).
*
* This operation can be accessed anonymously.
*
* **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:**
*
* - *Browse projects* and *Link issues* [project permission](https://confluence.atlassian.com/x/yodKLg) for the project
* that the issue is in.
* - If [issue-level security](https://confluence.atlassian.com/x/J4lKLg) is configured, issue-level security permission
* to view the issue.
*/
async createOrUpdateRemoteIssueLink<T = Models.RemoteIssueLinkIdentifies>(
parameters: Parameters.CreateOrUpdateRemoteIssueLink,
callback?: never
): Promise<T>;
async createOrUpdateRemoteIssueLink<T = Models.RemoteIssueLinkIdentifies>(
parameters: Parameters.CreateOrUpdateRemoteIssueLink,
callback?: Callback<T>,
): Promise<void | T> {
const config: RequestConfig = {
url: `/rest/api/2/issue/${parameters.issueIdOrKey}/remotelink`,
method: 'POST',
data: {
globalId: parameters.globalId,
application: parameters.application,
relationship: parameters.relationship,
object: parameters.object,
},
};
return this.client.sendRequest(config, callback, {
methodName: 'version2.issueRemoteLinks.createOrUpdateRemoteIssueLink',
});
}
/**
* Deletes the remote issue link from the issue using the link's global ID. Where the global ID includes reserved URL
* characters these must be escaped in the request. For example, pass `system=http://www.mycompany.com/support&id=1`
* as `system%3Dhttp%3A%2F%2Fwww.mycompany.com%2Fsupport%26id%3D1`.
*
* This operation requires [issue linking to be active](https://confluence.atlassian.com/x/yoXKM).
*
* This operation can be accessed anonymously.
*
* **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:**
*
* - *Browse projects* and *Link issues* [project permission](https://confluence.atlassian.com/x/yodKLg) for the project
* that the issue is in.
* - If [issue-level security](https://confluence.atlassian.com/x/J4lKLg) is implemented, issue-level security
* permission to view the issue.
*/
async deleteRemoteIssueLinkByGlobalId<T = void>(
parameters: Parameters.DeleteRemoteIssueLinkByGlobalId,
callback: Callback<T>
): Promise<void>;
/**
* Deletes the remote issue link from the issue using the link's global ID. Where the global ID includes reserved URL
* characters these must be escaped in the request. For example, pass `system=http://www.mycompany.com/support&id=1`
* as `system%3Dhttp%3A%2F%2Fwww.mycompany.com%2Fsupport%26id%3D1`.
*
* This operation requires [issue linking to be active](https://confluence.atlassian.com/x/yoXKM).
*
* This operation can be accessed anonymously.
*
* **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:**
*
* - *Browse projects* and *Link issues* [project permission](https://confluence.atlassian.com/x/yodKLg) for the project
* that the issue is in.
* - If [issue-level security](https://confluence.atlassian.com/x/J4lKLg) is implemented, issue-level security
* permission to view the issue.
*/
async deleteRemoteIssueLinkByGlobalId<T = void>(
parameters: Parameters.DeleteRemoteIssueLinkByGlobalId,
callback?: never
): Promise<T>;
async deleteRemoteIssueLinkByGlobalId<T = void>(
parameters: Parameters.DeleteRemoteIssueLinkByGlobalId,
callback?: Callback<T>,
): Promise<void | T> {
const config: RequestConfig = {
url: `/rest/api/2/issue/${parameters.issueIdOrKey}/remotelink`,
method: 'DELETE',
params: {
globalId: parameters.globalId,
},
};
return this.client.sendRequest(config, callback, {
methodName: 'version2.issueRemoteLinks.deleteRemoteIssueLinkByGlobalId',
});
}
/**
* Returns a remote issue link for an issue.
*
* This operation requires [issue linking to be active](https://confluence.atlassian.com/x/yoXKM).
*
* This operation can be accessed anonymously.
*
* **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:**
*
* - *Browse projects* [project permission](https://confluence.atlassian.com/x/yodKLg) for the project that the issue is in.
* - If [issue-level security](https://confluence.atlassian.com/x/J4lKLg) is configured, issue-level security permission
* to view the issue.
*/
async getRemoteIssueLinkById<T = Models.RemoteIssueLink>(
parameters: Parameters.GetRemoteIssueLinkById,
callback: Callback<T>
): Promise<void>;
/**
* Returns a remote issue link for an issue.
*
* This operation requires [issue linking to be active](https://confluence.atlassian.com/x/yoXKM).
*
* This operation can be accessed anonymously.
*
* **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:**
*
* - *Browse projects* [project permission](https://confluence.atlassian.com/x/yodKLg) for the project that the issue is in.
* - If [issue-level security](https://confluence.atlassian.com/x/J4lKLg) is configured, issue-level security permission
* to view the issue.
*/
async getRemoteIssueLinkById<T = Models.RemoteIssueLink>(
parameters: Parameters.GetRemoteIssueLinkById,
callback?: never
): Promise<T>;
async getRemoteIssueLinkById<T = Models.RemoteIssueLink>(
parameters: Parameters.GetRemoteIssueLinkById,
callback?: Callback<T>,
): Promise<void | T> {
const config: RequestConfig = {
url: `/rest/api/2/issue/${parameters.issueIdOrKey}/remotelink/${parameters.linkId}`,
method: 'GET',
};
return this.client.sendRequest(config, callback, {
methodName: 'version2.issueRemoteLinks.getRemoteIssueLinkById',
});
}
/**
* Updates a remote issue link for an issue.
*
* Note: Fields without values in the request are set to null.
*
* This operation requires [issue linking to be active](https://confluence.atlassian.com/x/yoXKM).
*
* This operation can be accessed anonymously.
*
* **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:**
*
* - *Browse projects* and *Link issues* [project permission](https://confluence.atlassian.com/x/yodKLg) for the project
* that the issue is in.
* - If [issue-level security](https://confluence.atlassian.com/x/J4lKLg) is configured, issue-level security permission
* to view the issue.
*/
async updateRemoteIssueLink<T = void>(
parameters: Parameters.UpdateRemoteIssueLink,
callback: Callback<T>
): Promise<void>;
/**
* Updates a remote issue link for an issue.
*
* Note: Fields without values in the request are set to null.
*
* This operation requires [issue linking to be active](https://confluence.atlassian.com/x/yoXKM).
*
* This operation can be accessed anonymously.
*
* **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:**
*
* - *Browse projects* and *Link issues* [project permission](https://confluence.atlassian.com/x/yodKLg) for the project
* that the issue is in.
* - If [issue-level security](https://confluence.atlassian.com/x/J4lKLg) is configured, issue-level security permission
* to view the issue.
*/
async updateRemoteIssueLink<T = void>(parameters: Parameters.UpdateRemoteIssueLink, callback?: never): Promise<T>;
async updateRemoteIssueLink<T = void>(
parameters: Parameters.UpdateRemoteIssueLink,
callback?: Callback<T>,
): Promise<void | T> {
const config: RequestConfig = {
url: `/rest/api/2/issue/${parameters.issueIdOrKey}/remotelink/${parameters.linkId}`,
method: 'PUT',
data: {
globalId: parameters.globalId,
application: parameters.application,
relationship: parameters.relationship,
object: parameters.object,
},
};
return this.client.sendRequest(config, callback, { methodName: 'version2.issueRemoteLinks.updateRemoteIssueLink' });
}
/**
* Deletes a remote issue link from an issue.
*
* This operation requires [issue linking to be active](https://confluence.atlassian.com/x/yoXKM).
*
* This operation can be accessed anonymously.
*
* **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:**
*
* - *Browse projects*, *Edit issues*, and *Link issues* [project permission](https://confluence.atlassian.com/x/yodKLg)
* for the project that the issue is in.
* - If [issue-level security](https://confluence.atlassian.com/x/J4lKLg) is configured, issue-level security permission
* to view the issue.
*/
async deleteRemoteIssueLinkById<T = void>(
parameters: Parameters.DeleteRemoteIssueLinkById,
callback: Callback<T>
): Promise<void>;
/**
* Deletes a remote issue link from an issue.
*
* This operation requires [issue linking to be active](https://confluence.atlassian.com/x/yoXKM).
*
* This operation can be accessed anonymously.
*
* **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:**
*
* - *Browse projects*, *Edit issues*, and *Link issues* [project permission](https://confluence.atlassian.com/x/yodKLg)
* for the project that the issue is in.
* - If [issue-level security](https://confluence.atlassian.com/x/J4lKLg) is configured, issue-level security permission
* to view the issue.
*/
async deleteRemoteIssueLinkById<T = void>(
parameters: Parameters.DeleteRemoteIssueLinkById,
callback?: never
): Promise<T>;
async deleteRemoteIssueLinkById<T = void>(
parameters: Parameters.DeleteRemoteIssueLinkById,
callback?: Callback<T>,
): Promise<void | T> {
const config: RequestConfig = {
url: `/rest/api/2/issue/${parameters.issueIdOrKey}/remotelink/${parameters.linkId}`,
method: 'DELETE',
};
return this.client.sendRequest(config, callback, {
methodName: 'version2.issueRemoteLinks.deleteRemoteIssueLinkById',
});
}
} | the_stack |
import BTree, {IMap} from '.';
import SortedArray from './sorted-array';
// Note: The `bintrees` package also includes a `BinTree` type which turned
// out to be an unbalanced binary tree. It is faster than `RBTree` for
// randomized data, but it becomes extremely slow when filled with sorted
// data, so it's not usually a good choice.
import {RBTree} from 'bintrees';
const SortedSet = require("collections/sorted-set"); // Bad type definition: missing 'length'
const SortedMap = require("collections/sorted-map"); // No type definitions available
const functionalTree = require("functional-red-black-tree"); // No type definitions available
class Timer {
start = Date.now();
ms() { return Date.now() - this.start; }
restart() { var ms = this.ms(); this.start += ms; return ms; }
}
function randInt(max: number) { return Math.random() * max | 0; }
function swap(keys: any[], i: number, j: number) {
var tmp = keys[i];
keys[i] = keys[j];
keys[j] = tmp;
}
function makeArray(size: number, randomOrder: boolean, spacing = 10) {
var keys: number[] = [], i, n;
for (i = 0, n = 0; i < size; i++, n += 1 + randInt(spacing))
keys[i] = n;
if (randomOrder)
for (i = 0; i < size; i++)
swap(keys, i, randInt(size));
return keys;
}
function measure<T=void>(message: (t:T) => string, callback: () => T, minMillisec: number = 600, log = console.log) {
var timer = new Timer(), counter = 0, ms;
do {
var result = callback();
counter++;
} while ((ms = timer.ms()) < minMillisec);
ms /= counter;
log((Math.round(ms * 10) / 10) + "\t" + message(result));
return result;
}
console.log("Benchmark results (milliseconds with integer keys/values)");
console.log("---------------------------------------------------------");
console.log();
console.log("### Insertions at random locations: sorted-btree vs the competition ###");
for (let size of [1000, 10000, 100000, 1000000]) {
console.log();
var keys = makeArray(size, true);
measure(map => `Insert ${map.size} pairs in sorted-btree's BTree`, () => {
let map = new BTree();
for (let k of keys)
map.set(k, k);
return map;
});
measure(map => `Insert ${map.size} pairs in sorted-btree's BTree set (no values)`, () => {
let map = new BTree();
for (let k of keys)
map.set(k, undefined);
return map;
});
measure(map => `Insert ${map.length} pairs in collections' SortedMap`, () => {
let map = new SortedMap();
for (let k of keys)
map.set(k, k);
return map;
});
measure(set => `Insert ${set.length} pairs in collections' SortedSet (no values)`, () => {
let set = new SortedSet();
for (let k of keys)
set.push(k);
return set;
});
measure(set => `Insert ${set.length} pairs in functional-red-black-tree`, () => {
let set = functionalTree();
for (let k of keys)
set = set.insert(k, k);
return set;
});
measure(set => `Insert ${set.size} pairs in bintrees' RBTree (no values)`, () => {
let set = new RBTree((a: any, b: any) => a - b);
for (let k of keys)
set.insert(k);
return set;
});
//measure(set => `Insert ${set.size} pairs in bintrees' BinTree (no values)`, () => {
// let set = new BinTree((a: any, b: any) => a - b);
// for (let k of keys)
// set.insert(k);
// return set;
//});
}
console.log();
console.log("### Insert in order, delete: sorted-btree vs the competition ###");
for (let size of [9999, 1000, 10000, 100000, 1000000]) {
var log = (size === 9999 ? () => {} : console.log);
log();
var keys = makeArray(size, false), i;
let btree = measure(tree => `Insert ${tree.size} sorted pairs in B+ tree`, () => {
let tree = new BTree();
for (let k of keys)
tree.set(k, k * 10);
return tree;
}, 600, log);
let btreeSet = measure(tree => `Insert ${tree.size} sorted keys in B+ tree set (no values)`, () => {
let tree = new BTree();
for (let k of keys)
tree.set(k, undefined);
return tree;
}, 600, log);
// Another tree for the bulk-delete test
let btreeSet2 = btreeSet.greedyClone();
let sMap = measure(map => `Insert ${map.length} sorted pairs in collections' SortedMap`, () => {
let map = new SortedMap();
for (let k of keys)
map.set(k, k * 10);
return map;
}, 600, log);
let sSet = measure(set => `Insert ${set.length} sorted keys in collections' SortedSet (no values)`, () => {
let set = new SortedSet();
for (let k of keys)
set.push(k);
return set;
}, 600, log);
let fTree = measure(map => `Insert ${map.length} sorted pairs in functional-red-black-tree`, () => {
let map = functionalTree();
for (let k of keys)
map = map.insert(k, k * 10);
return map;
}, 600, log);
let rbTree = measure(set => `Insert ${set.size} sorted keys in bintrees' RBTree (no values)`, () => {
let set = new RBTree((a: any, b: any) => a - b);
for (let k of keys)
set.insert(k);
return set;
}, 600, log);
//let binTree = measure(set => `Insert ${set.size} sorted keys in bintrees' BinTree (no values)`, () => {
// let set = new BinTree((a: any, b: any) => a - b);
// for (let k of keys)
// set.insert(k);
// return set;
//});
// Bug fix: can't use measure() for deletions because the
// trees aren't the same on the second iteration
var timer = new Timer();
for (i = 0; i < keys.length; i += 2)
btree.delete(keys[i]);
log(`${timer.restart()}\tDelete every second item in B+ tree`);
for (i = 0; i < keys.length; i += 2)
btreeSet.delete(keys[i]);
log(`${timer.restart()}\tDelete every second item in B+ tree set`);
btreeSet2.editRange(btreeSet2.minKey(), btreeSet2.maxKey(), true, (k,v,i) => {
if ((i & 1) === 0) return {delete:true};
});
log(`${timer.restart()}\tBulk-delete every second item in B+ tree set`);
for (i = 0; i < keys.length; i += 2)
sMap.delete(keys[i]);
log(`${timer.restart()}\tDelete every second item in collections' SortedMap`);
for (i = 0; i < keys.length; i += 2)
sSet.delete(keys[i]);
log(`${timer.restart()}\tDelete every second item in collections' SortedSet`);
for (i = 0; i < keys.length; i += 2)
fTree = fTree.remove(keys[i]);
log(`${timer.restart()}\tDelete every second item in functional-red-black-tree`);
for (i = 0; i < keys.length; i += 2)
rbTree.remove(keys[i]);
log(`${timer.restart()}\tDelete every second item in bintrees' RBTree`);
}
console.log();
console.log("### Insertions at random locations: sorted-btree vs Array vs Map ###");
for (let size of [9999, 1000, 10000, 100000, 1000000]) {
// Don't print anything in the first iteration (warm up the optimizer)
var log = (size === 9999 ? () => {} : console.log);
var keys = makeArray(size, true);
log();
if (size <= 100000) {
measure(list => `Insert ${list.size} pairs in sorted array`, () => {
let list = new SortedArray();
for (let k of keys)
list.set(k, k);
return list;
}, 600, log);
} else {
log(`SLOW!\tInsert ${size} pairs in sorted array`);
}
measure(tree => `Insert ${tree.size} pairs in B+ tree`, () => {
let tree = new BTree();
for (let k of keys)
tree.set(k, k);
return tree;
}, 600, log);
measure(map => `Insert ${map.size} pairs in ES6 Map (hashtable)`, () => {
let map = new Map();
for (let k of keys)
map.set(k, k);
return map;
}, 600, log);
}
console.log();
console.log("### Insert in order, scan, delete: sorted-btree vs Array vs Map ###");
for (let size of [1000, 10000, 100000, 1000000]) {
console.log();
var keys = makeArray(size, false), i;
var list = measure(list => `Insert ${list.size} sorted pairs in array`, () => {
let list = new SortedArray();
for (let k of keys)
list.set(k, k * 10);
return list;
});
let tree = measure(tree => `Insert ${tree.size} sorted pairs in B+ tree`, () => {
let tree = new BTree();
for (let k of keys)
tree.set(k, k * 10);
return tree;
});
let map = measure(map => `Insert ${map.size} sorted pairs in Map hashtable`, () => {
let map = new Map();
for (let k of keys)
map.set(k, k * 10);
return map;
});
measure(sum => `Sum of all values with forEach in sorted array: ${sum}`, () => {
var sum = 0;
list.getArray().forEach(pair => sum += pair[1]);
return sum;
});
measure(sum => `Sum of all values with forEachPair in B+ tree: ${sum}`, () => {
var sum = 0;
tree.forEachPair((k, v) => sum += v);
return sum;
});
measure(sum => `Sum of all values with forEach in B+ tree: ${sum}`, () => {
var sum = 0;
tree.forEach(v => sum += v);
return sum;
});
measure(sum => `Sum of all values with iterator in B+ tree: ${sum}`, () => {
var sum = 0;
// entries() (instead of values()) with reused pair should be fastest
// (not using for-of because tsc is in ES5 mode w/o --downlevelIteration)
for (var it = tree.entries(undefined, []), next = it.next(); !next.done; next = it.next())
sum += next.value[1];
return sum;
});
measure(sum => `Sum of all values with forEach in Map: ${sum}`, () => {
var sum = 0;
map.forEach(v => sum += v);
return sum;
});
if (keys.length <= 100000) {
measure(() => `Delete every second item in sorted array`, () => {
for (i = keys.length-1; i >= 0; i -= 2)
list.delete(keys[i]);
});
} else
console.log(`SLOW!\tDelete every second item in sorted array`);
measure(() => `Delete every second item in B+ tree`, () => {
for (i = keys.length-1; i >= 0; i -= 2)
tree.delete(keys[i]);
});
measure(() => `Delete every second item in Map hashtable`, () => {
for (i = keys.length-1; i >= 0; i -= 2)
map.delete(keys[i]);
});
}
console.log();
console.log("### Measure effect of max node size ###");
{
console.log();
var keys = makeArray(100000, true);
var timer = new Timer();
for (let nodeSize = 10; nodeSize <= 80; nodeSize += 2) {
let tree = new BTree([], undefined, nodeSize);
for (let i = 0; i < keys.length; i++)
tree.set(keys[i], undefined);
console.log(`${timer.restart()}\tInsert ${tree.size} keys in B+tree with node size ${tree.maxNodeSize}`);
}
}
console.log();
console.log("### Delta between B+ trees");
{
console.log();
const sizes = [100, 1000, 10000, 100000, 1000000];
sizes.forEach((size, i) => {
for (let j = i; j < sizes.length; j++) {
const tree = new BTree();
for (let k of makeArray(size, true))
tree.set(k, k * 10);
const otherSize = sizes[j];
const otherTree = new BTree();
for (let k of makeArray(otherSize, true))
otherTree.set(k, k * 10);
measure(() => `Delta between B+ trees with ${size} nodes and B+tree with ${otherSize} nodes`, () => {
tree.diffAgainst(otherTree);
});
}
})
console.log();
sizes.forEach((size, i) => {
for (let j = 0; j < sizes.length; j++) {
const otherSize = sizes[j];
const keys = makeArray(size + otherSize, true);
const tree = new BTree();
for (let k of keys.slice(0, size))
tree.set(k, k * 10);
const otherTree = tree.clone();
for (let k of keys.slice(size))
tree.set(k, k * 10);
measure(() => `Delta between B+ trees with ${size} nodes and cheap cloned B+tree with ${otherSize} additional nodes`, () => {
tree.diffAgainst(otherTree);
});
}
})
} | the_stack |
import { i18n } from '../model/i18n';
import { strings } from '../model/strings';
import { Utils } from './utils';
export interface ContextMenuOptions {
width?: number | "auto"
isSticky?: boolean
items: ContextMenuItemOptions[]
}
export interface ContextMenuItemOptions {
label: string
type?: ContextMenuItemType
markup?: string
icon?: string
cssIcon?: string
shortcut?: string
onClick?: () => void
enabled?: boolean | (() => boolean)
items?: ContextMenuItemOptions[]
}
export enum ContextMenuItemType {
separator,
label,
custom,
multiButton,
subMenu,
hoverMenu,
normal
}
export class ContextMenu{
position: boolean;
menuControl: HTMLElement;
/**
* Creates a new contextual menu
* @param {object} options options which build the menu e.g. position and items
* @param {number} options.width sets the width of the menu including children
* @param {boolean} options.isSticky sets how the menu apears, follow the mouse or sticky
* @param {Array<ContextMenuItem>} options.items sets the default items in the menu
*/
constructor(options: ContextMenuOptions, event?: Event){
ContextMenu.closeMenu();
this.position = options.isSticky != null ? options.isSticky : false;
this.menuControl = createElement(`<ul class='contextualJs contextualMenu'></ul>`);
if (options.width != "auto")
this.menuControl.style.width = (options.width != null ? options.width + 'px' : '200px');
options.items.forEach(i => {
let item = new ContextMenuItem(i);
this.menuControl.appendChild(item.element);
});
if (event){
event.stopPropagation()
document.body.appendChild(this.menuControl);
ContextMenu.positionMenu(this.position, event, this.menuControl);
}
document.addEventListener("click", e => {
this.catch(e);
});
document.addEventListener("auxclick", e => {
this.catch(e);
});
}
catch(e: MouseEvent) {
if(!(<HTMLElement>e.target).classList.contains('contextualJs')){
ContextMenu.closeMenu();
}
}
/**
* Adds item to this contextual menu instance
* @param {ContextMenuItem} item item to add to the contextual menu
*/
add(item: ContextMenuItem){
this.menuControl.appendChild(item.element);
}
/**
* Makes this contextual menu visible
*/
show(event: Event){
event.stopPropagation();
document.body.appendChild(this.menuControl);
ContextMenu.positionMenu(this.position, event, this.menuControl);
}
/**
* Hides this contextual menu
*/
hide(){
ContextMenu.closeMenu();
}
/**
* Toggle visibility of menu
*/
toggle(event: Event){
event.stopPropagation();
if(this.menuControl.parentElement != document.body){
document.body.appendChild(this.menuControl);
ContextMenu.positionMenu(this.position, event, this.menuControl);
}else{
ContextMenu.closeMenu();
}
}
static closeMenu() {
let openMenuItem = document.querySelector('.contextualMenu:not(.contextualMenuHidden)');
if (openMenuItem != null)
document.body.removeChild(openMenuItem);
}
static positionMenu(docked: boolean, event: Event, menu: HTMLElement) {
if (docked) {
let target = <HTMLElement>event.target;
menu.style.left = ((target.offsetLeft + menu.offsetWidth) >= window.innerWidth) ?
((target.offsetLeft - menu.offsetWidth) + target.offsetWidth)+"px"
: (target.offsetLeft)+"px";
menu.style.top = ((target.offsetTop + menu.offsetHeight) >= window.innerHeight) ?
(target.offsetTop - menu.offsetHeight)+"px"
: (target.offsetHeight + target.offsetTop)+"px";
} else {
let clientX = (<MouseEvent>event).clientX;
menu.style.left = ((clientX + menu.offsetWidth) >= window.innerWidth) ?
((clientX - menu.offsetWidth))+"px"
: (clientX)+"px";
let clientY = (<MouseEvent>event).clientY;
menu.style.top = ((clientY + menu.offsetHeight) >= window.innerHeight) ?
(clientY - menu.offsetHeight)+"px"
: (clientY)+"px";
}
}
static async editorContextMenu(event: Event, selectedText = "", text = "", element: HTMLInputElement = null): Promise<ContextMenu> {
const ctrl = (Utils.Platform.isMac ? "⌘" : "Ctrl");
const clipboardText = await navigator.clipboard.readText();
let items = [];
if (element)
items.push({ label: i18n(strings.cut), cssIcon: "icon-cut", shortcut: `${ctrl}+X`, enabled: (selectedText != ""), onClick: () => {
navigator.clipboard.writeText(selectedText);
element.value = text.substring(0, element.selectionStart) + text.substring(element.selectionEnd);
}});
items.push({ label: i18n(strings.copy), cssIcon: "icon-copy", shortcut: `${ctrl}+C`, enabled: (text != ""), onClick: () => {
navigator.clipboard.writeText(selectedText != "" ? selectedText : text);
}});
if (element)
items.push({ label: i18n(strings.paste), cssIcon: "icon-paste", shortcut: `${ctrl}+V`, enabled: (clipboardText != ""), onClick: () => {
element.value = text.substring(0, element.selectionStart) + clipboardText + text.substring(element.selectionEnd);
}});
return new ContextMenu({ items: items }, event);
}
}
export class ContextMenuItem{
element: HTMLElement;
constructor(options: ContextMenuItemOptions){
let enabled = true;
if (typeof options.enabled !== "undefined") {
if (typeof options.enabled === "boolean") {
enabled = options.enabled;
} else {
enabled = options.enabled();
}
}
switch(options.type){
case ContextMenuItemType.separator:
this.separator();
break;
case ContextMenuItemType.custom:
this.custom(options.markup);
break;
case ContextMenuItemType.multiButton:
this.multiButton(options.items);
break;
case ContextMenuItemType.subMenu:
this.subMenu(options.label, options.items, (options.icon !== undefined ? options.icon : ''), (options.cssIcon !== undefined ? options.cssIcon : ''), enabled);
break;
case ContextMenuItemType.hoverMenu:
this.hoverMenu(options.label, options.items, (options.icon !== undefined ? options.icon : ''), (options.cssIcon !== undefined ? options.cssIcon : ''), enabled);
break;
case ContextMenuItemType.label:
this.label(options.label, (options.icon !== undefined ? options.icon : ''), (options.cssIcon !== undefined ? options.cssIcon : ''));
break;
case ContextMenuItemType.normal:
default:
this.button(options.label, options.onClick, (options.shortcut !== undefined ? options.shortcut : ''), (options.icon !== undefined ? options.icon : ''), (options.cssIcon !== undefined ? options.cssIcon : ''), enabled);
}
}
label (label: string, icon = '', cssIcon = '') {
this.element = createElement( `
<li class='contextualJs contextualMenuItemOuter'>
<div class='contextualJs contextualMenuItem static'>
${icon != ''? `<img src='${icon}' class='contextualJs contextualMenuItemIcon'/>` : `<div class='contextualJs contextualMenuItemIcon ${cssIcon != '' ? cssIcon : ''}'></div>`}
<span class='contextualJs contextualMenuItemTitle'>${label}</span>
</div>
</li>`);
}
button(label: string, onClick: () => void, shortcut = '', icon = '', cssIcon = '', enabled = true){
this.element = createElement( `
<li class='contextualJs contextualMenuItemOuter'>
<div class='contextualJs contextualMenuItem ${enabled == true ? '' : 'disabled'}'>
${icon != ''? `<img src='${icon}' class='contextualJs contextualMenuItemIcon'/>` : `<div class='contextualJs contextualMenuItemIcon ${cssIcon != '' ? cssIcon : ''}'></div>`}
<span class='contextualJs contextualMenuItemTitle'>${label}</span>
<span class='contextualJs contextualMenuItemTip'>${shortcut == ''? '' : shortcut}</span>
</div>
</li>`);
if (enabled){
this.element.addEventListener('click', (e) => {
e.stopPropagation();
if (onClick) onClick();
ContextMenu.closeMenu();
}, false);
}
}
custom(markup: string){
this.element = createElement(`<li class='contextualJs contextualCustomEl'>${markup}</li>`);
}
hoverMenu(label: string, items?: ContextMenuItemOptions[], icon = '', cssIcon = '', enabled = true){
this.element = createElement(`
<li class='contextualJs contextualHoverMenuOuter'>
<div class='contextualJs contextualHoverMenuItem ${enabled == true ? '' : 'disabled'}'>
${icon != ''? `<img src='${icon}' class='contextualJs contextualMenuItemIcon'/>` : `<div class='contextualJs contextualMenuItemIcon ${cssIcon != '' ? cssIcon : ''}'></div>`}
<span class='contextualJs contextualMenuItemTitle'>${label}</span>
<span class='contextualJs contextualMenuItemOverflow'>></span>
</div>
<ul class='contextualJs contextualHoverMenu'>
</ul>
</li>
`);
let childMenu = this.element.querySelector('.contextualHoverMenu'),
menuItem = this.element.querySelector('.contextualHoverMenuItem');
if (items !== undefined) {
items.forEach(i => {
let item = new ContextMenuItem(i);
childMenu.appendChild(item.element);
});
}
if (enabled){
menuItem.addEventListener('mouseenter', () => {});
menuItem.addEventListener('mouseleave', () => {});
}
}
multiButton(items: ContextMenuItemOptions[]) {
this.element = createElement(`
<li class='contextualJs contextualMultiItem'>
</li>
`);
items.forEach(i => {
let item = new ContextMenuItem(i);
this.element.appendChild(item.element);
});
}
subMenu(label: string, items?: ContextMenuItemOptions[], icon = '', cssIcon = '', enabled = true) {
this.element = createElement( `
<li class='contextualJs contextualMenuItemOuter'>
<div class='contextualJs contextualMenuItem ${enabled == true ? '' : 'disabled'}'>
${icon != ''? `<img src='${icon}' class='contextualJs contextualMenuItemIcon'/>` : `<div class='contextualJs contextualMenuItemIcon ${cssIcon != '' ? cssIcon : ''}'></div>`}
<span class='contextualJs contextualMenuItemTitle'>${label}</span>
<span class='contextualJs contextualMenuItemOverflow'>
<span class='contextualJs contextualMenuItemOverflowLine'></span>
<span class='contextualJs contextualMenuItemOverflowLine'></span>
<span class='contextualJs contextualMenuItemOverflowLine'></span>
</span>
</div>
<ul class='contextualJs contextualSubMenu contextualMenuHidden'>
</ul>
</li>`);
let childMenu = this.element.querySelector('.contextualSubMenu'),
menuItem = this.element.querySelector('.contextualMenuItem');
if(items !== undefined) {
items.forEach(i => {
let item = new ContextMenuItem(i);
childMenu.appendChild(item.element);
});
}
if(enabled == true){
menuItem.addEventListener('click',() => {
menuItem.classList.toggle('SubMenuActive');
childMenu.classList.toggle('contextualMenuHidden');
}, false);
}
}
separator() {
this.element = createElement(`<li class='contextualJs contextualMenuSeparator'><span></span></li>`);
}
}
function createElement(html: string) {
var el = document.createElement('div');
el.innerHTML = html;
return <HTMLElement>el.firstElementChild;
} | the_stack |
import * as fs from "fs";
import * as _ from "lodash";
// External types
import { Reflection } from "typedoc";
/**
* The final documentation JSON will contain an array of sections,
* e.g. one for adapters, one for wrappers, etc. Each section will contain
* documentation for classes that belong to that section.
*/
interface Documentation {
sections: SectionDocumentation[];
interfaces: Interface[];
}
interface SectionDocumentation {
// The section title, e.g. "adapters".
title: string;
classes: ClassDocumentation[];
}
interface ClassDocumentation {
// The name of the class, e.g. "CollateralizedSimpleInterestLoanAdapter".
name: string;
methods: MethodDocumentation[];
}
interface MethodDocumentation {
// The method's name, e.g. "returnCollateral"
name: string;
// The description of the method, as provided in comments (doc block.)
description: string;
// An example of how to use the method.
example: string;
// The typescript-formatted parameters list, e.g. "agreementId: string".
params: string;
// The location of the method definition,
// e.g. "adapters/collateralized_simple_interest_loan_adapter.ts#L348"
source: string;
// The method's signature, in Typescript format,
// e.g. "canReturnCollateral(agreementId: string): Promise<boolean>"
signature: string;
interfaces: string[];
}
interface SectionToTypedocClasses {
// E.g. { "adapters": [], "wrappers": [], ... }
[sectionName: string]: any[];
}
interface SignatureParameter {
name: string;
type: ParameterType;
}
interface ParameterType {
name: string;
type: any;
elementType: any;
}
interface TypedocInput {
title: string;
children: Reflection[];
}
interface Interface {
id: number;
name: string;
kind: number;
kindString: string;
flags: any;
children: any[];
groups: any[];
sources: any[];
extendedTypes: any[];
}
/**
* Given a file path to a Typedoc JSON output file, the
* TypedocParser reads that file, generates a new more user-friendly
* documentation JSON file.
*
* Example:
*
* const parser = TypedocParser.new("input/0.0.51.json");
* await parser.parse();
* await parser.saveFile("output/0.0.51.json");
*/
class TypedocParser {
/**
* Given a typedoc representation of an object, returns true if that
* representation is of a class.
*
* @param typedocObj
* @returns {boolean}
*/
private static isClass(typedocObj): boolean {
// All class representations have child data.
if (!typedocObj.children) {
return false;
}
const firstChild = typedocObj.children[0];
// All class representations are referred to as "Class".
console.log(typedocObj.name);
return firstChild.kindString === "Class" && typedocObj.name !== '"index"' && typedocObj.name !== '"dharma"';
}
private static methodSignature(methodName: string, signature: any, params: string) {
const returnType = TypedocParser.returnType(signature);
if (params === "") {
return `${methodName}(): ${returnType}`;
}
return `${methodName}(
${params},
): ${returnType || "void"}`;
}
/**
* Given a set of signature parameters, returns a Typescript-style parameter signature.
*
* Examples:
* TypedocParser.paramsString(params);
* => "agreementId: string"
*
* @param {SignatureParameter[]} params
* @returns {string}
*/
private static paramsString(params: SignatureParameter[]) {
if (!params || !params.length) {
return "";
}
return _.map(params, (param) => {
// Handle case of array.
const isArray = param.type && param.type.type === "array";
if (isArray) {
return `${param.name}: ${param.type.elementType.name}`;
}
// Handle case of function param..
const isReflection = param.type && param.type.type === "reflection";
const paramType = isReflection ? "Function" : param.type.name;
return `${param.name}: ${paramType}`;
}).join(",<br/> ");
}
private static sectionName(classObj): string {
// E.g. "adapters" from Typedoc name "adapters/simple_interest_loan_adapter".
return classObj.name.split("/")[0].substr(1);
}
private static getClassMethods(classObj) {
return _.filter(classObj.children[0].children, (child) => {
return child.kindString === "Method";
});
}
private static isPromise(signature): boolean {
return signature.type.name === "Promise" &&
signature.type.typeArguments &&
signature.type.typeArguments.length;
}
private static returnType(signature) {
const isArray = signature.type.type && signature.type.type === "array";
// Deal with special case for arrays.
if (isArray) {
return `${signature.type.elementType.name}[]`;
}
const isPromise = TypedocParser.isPromise(signature);
let promiseTargetType: string;
if (isPromise) {
const typeArgs = signature.type.typeArguments;
const isArrayTarget = typeArgs && typeArgs[0].type === "array";
promiseTargetType = isArrayTarget ? `${typeArgs[0].elementType.name}[]` : typeArgs[0].name;
}
const promiseTarget = _.escape(isPromise ? `<${promiseTargetType}>` : "");
return signature.type.name + promiseTarget;
}
private static getExample(signature): string {
if (!(signature.comment && signature.comment.tags)) {
return "";
}
const example = _.find(signature.comment.tags, (tag) => tag.tag === "example");
const text = example.text;
if (text.startsWith("\n ")) {
return text.substr(2);
}
return text;
}
private static deepFilter(obj: any, predicate: (obj) => boolean) {
// Base case:
if (predicate(obj)) {
return [obj];
}
// Recursively:
return _.flatten(_.map(obj, (v) => {
return typeof v === "object" ? this.deepFilter(v, predicate) : [];
}));
}
private static interfacesInSignature(signature): string[] {
const params: SignatureParameter[] = signature.parameters;
const paramInterfaces = _.compact(
_.map(params, (param) => {
if (param.type.type === "reference") {
return param.type.name;
}
}),
);
return paramInterfaces || [];
}
// The path to the Typedoc input JSON file.
private readonly filePath;
// The typedoc JSON input, as read from the JSON file at `filePath`.
private input: TypedocInput;
// The documentation output, based on the Typedoc data.
private output: Documentation;
constructor(filePath: string) {
this.filePath = filePath;
}
public parse(): void {
// Read the contents of the Typedoc file.
this.readFile();
// Transform the Typedoc JSON into human-friendly output.
this.parseData();
}
/**
* Given a the desired output path, saves a file there containing
* the human-friendly JSON data.
*
* @param {string} outputPath
*/
public writeToFile(outputPath: string): void {
// Convert the documentation object into a string, so we can write it to a file.
const contents = JSON.stringify(this.output);
fs.writeFileSync(outputPath, contents);
}
private parseData(): void {
this.output = { sections: this.getSections(), interfaces: this.getInterfaces() };
}
private getSections(): SectionDocumentation[] {
const groupedClasses = this.classesPerSection();
return _.map(groupedClasses, this.getSectionData.bind(this));
}
private getInterfaces(): Interface[] {
return TypedocParser.deepFilter(
this.input,
(obj) => obj.kindString === "Interface" && obj.name !== "Interface",
);
}
private getSectionData(classes: object[], groupName: string): SectionDocumentation {
return {
title: groupName,
classes: this.getClassData(classes),
};
}
private classesPerSection(): SectionToTypedocClasses {
const allClasses = this.getClasses();
return _.groupBy(allClasses, TypedocParser.sectionName);
}
private getClasses(): object[] {
// Return all of the typedoc objects that refer to classes.
return _.filter(this.input.children, TypedocParser.isClass.bind(this));
}
private getClassData(classes): ClassDocumentation[] {
return classes.map((klass) => {
const name = klass.children[0].name;
return {
name,
methods: this.getMethodData(klass),
};
});
}
private getMethodData(classObj): MethodDocumentation[] {
const methods = TypedocParser.getClassMethods(classObj);
return _.map(methods, (method) => {
const signature = method.signatures[0];
const params = TypedocParser.paramsString(signature.parameters);
let description = "";
if (signature.comment) {
description = signature.comment.shortText;
if (signature.comment.text) {
description += `\n\n${signature.comment.text}`;
}
}
return {
name: method.name,
description,
example: TypedocParser.getExample(signature),
params,
interfaces: TypedocParser.interfacesInSignature(signature),
source: `${method.sources[0].fileName}#L${method.sources[0].line}`,
signature: TypedocParser.methodSignature(method.name, signature, params),
};
});
}
private readFile(): void {
const rawData = fs.readFileSync(this.filePath, "utf8");
this.input = JSON.parse(rawData);
}
}
module.exports = TypedocParser; | the_stack |
import * as React from 'react'
import {
SubscriptionCheckoutOptions,
UserPlan,
} from '@worldbrain/memex-common/lib/subscriptions/types'
import LoadingIndicator from 'src/common-ui/components/LoadingIndicator'
import {
SubscriptionOptionsContainer,
PricingGrid,
PricingGridCheck,
PricingGridPlanSpacer,
PricingGridPlanTitle,
PricingGridFeatureDescription,
Line,
ColThinker,
ColPioneer,
ColExplorer,
PriceInputBox,
PriceText,
PriceBox,
TimeButtonRight,
TimeButtonLeft,
TimeButtonBox,
LinkSpan,
} from 'src/authentication/components/Subscription/pricing.style'
import { PrimaryButton } from 'src/common-ui/components/primary-button'
import { withCurrentUser } from 'src/authentication/components/AuthConnector'
import { AuthContextInterface } from 'src/authentication/background/types'
interface Props extends AuthContextInterface {
openCheckoutBackupMonthly?: (
options?: Omit<SubscriptionCheckoutOptions, 'planId'>,
) => void
openCheckoutBackupYearly?: (
options?: Omit<SubscriptionCheckoutOptions, 'planId'>,
) => void
openPortal?: () => void
plans?: UserPlan[]
loadingMonthly: boolean
loadingYearly: boolean
loadingPortal: boolean
}
type Term = 'monthly' | 'annual'
interface State {
pioneerDonationAmount: number
term: Term
plan: string
}
export class SubscriptionInnerOptions extends React.Component<Props, State> {
state = {
pioneerDonationAmount: 5,
term: 'monthly' as Term,
plan: null,
}
async componentDidMount() {
if (
await this.props.currentUser?.authorizedPlans?.includes(
'pro-yearly',
)
) {
this.setState({ term: 'annual', pioneerDonationAmount: 50 })
}
if (
await this.props.currentUser?.authorizedFeatures?.includes('beta')
) {
this.setState({ plan: 'beta' })
} else if (
(await this.props.currentUser?.authorizedPlans?.includes(
'pro-monthly',
)) ||
(await this.props.currentUser?.authorizedPlans?.includes(
'pro-yearly',
))
) {
this.setState({ plan: 'pro' })
}
}
openCheckoutPioneer = () => {
const options = {
pioneerDonationAmount: this.state.pioneerDonationAmount,
}
if (this.state.term === 'monthly') {
this.props.openCheckoutBackupMonthly(options)
} else {
this.props.openCheckoutBackupYearly(options)
}
}
openCheckout = () => {
if (this.state.term === 'monthly') {
this.props.openCheckoutBackupMonthly()
} else {
this.props.openCheckoutBackupYearly()
}
}
pioneerDonationChanged = (e) => {
this.setState({
pioneerDonationAmount: Math.max(
parseInt(e.target.value, 10) ?? 1,
1,
),
})
}
toggleMonthly = (e) => {
this.setState({ term: 'monthly', pioneerDonationAmount: 5 })
}
toggleAnnual = (e) => {
this.setState({ term: 'annual', pioneerDonationAmount: 50 })
}
render() {
return (
<SubscriptionOptionsContainer>
<TimeButtonBox>
<TimeButtonLeft
active={this.state.term === 'monthly'}
onClick={this.toggleMonthly}
>
Monthly
</TimeButtonLeft>
<TimeButtonRight
active={this.state.term === 'annual'}
onClick={this.toggleAnnual}
>
Yearly
</TimeButtonRight>
</TimeButtonBox>
<PricingGrid>
<PricingGridPlanTitle> </PricingGridPlanTitle>
<PricingGridPlanSpacer />
<PricingGridPlanTitle> Explorer </PricingGridPlanTitle>
{this.props.currentUser?.authorizedPlans?.includes(
'pro-monthly',
) ||
this.props.currentUser?.authorizedPlans?.includes(
'pro-yearly',
) ? (
<PricingGridPlanTitle
active={this.state.plan === 'pro'}
>
{' '}
Thinker{' '}
</PricingGridPlanTitle>
) : (
<PricingGridPlanTitle> Thinker </PricingGridPlanTitle>
)}
{/*<ColPioneer>
{this.props.currentUser?.authorizedFeatures?.includes(
'beta',
) ? (
<PricingGridPlanTitle
active={this.state.plan === 'beta'}
>
{' '}
Pioneer{' '}
</PricingGridPlanTitle>
) : (
<PricingGridPlanTitle> Pioneer </PricingGridPlanTitle>
)}
*/}
<PricingGridFeatureDescription>
Search, Organise and Annotate
</PricingGridFeatureDescription>
<ColExplorer>
{' '}
<PricingGridCheck />{' '}
</ColExplorer>
<ColThinker>
{' '}
<PricingGridCheck
active={this.state.plan === 'pro'}
/>{' '}
</ColThinker>
{/*<ColPioneer>
{' '}
<PricingGridCheck
active={this.state.plan === 'beta'}
/>{' '}
</ColPioneer>
*/}
<Line />
<PricingGridFeatureDescription>
Mobile App for iOS and Android
</PricingGridFeatureDescription>
<ColExplorer>
{' '}
<PricingGridCheck />{' '}
</ColExplorer>
<ColThinker>
{' '}
<PricingGridCheck
active={this.state.plan === 'pro'}
/>{' '}
</ColThinker>
{/*<ColPioneer>
{' '}
<PricingGridCheck
active={this.state.plan === 'beta'}
/>{' '}
</ColPioneer>
*/}
<Line />
<PricingGridFeatureDescription>
Sync between mobile and desktop
</PricingGridFeatureDescription>
<ColThinker>
{' '}
<PricingGridCheck
active={this.state.plan === 'pro'}
/>{' '}
</ColThinker>
{/*<ColPioneer>
{' '}
<PricingGridCheck
active={this.state.plan === 'beta'}
/>{' '}
</ColPioneer>
*/}
<Line />
<PricingGridFeatureDescription>
Automatic backup to your favorite cloud
</PricingGridFeatureDescription>
<ColThinker>
{' '}
<PricingGridCheck
active={this.state.plan === 'pro'}
/>{' '}
</ColThinker>
{/*<ColPioneer>
{' '}
<PricingGridCheck
active={this.state.plan === 'beta'}
/>{' '}
</ColPioneer>
<Line />
<PricingGridFeatureDescription>
Early access to beta features
</PricingGridFeatureDescription>
{/*<ColPioneer>
{' '}
<PricingGridCheck
active={this.state.plan === 'beta'}
/>{' '}
</ColPioneer>
*/}
<Line />
{/*<PricingGridFeatureDescription
onClick={() =>
window.open('https://worldbrain.io/vision')
}
>
Support the development of an ethical business.{' '}
<LinkSpan>Learn more</LinkSpan>
</PricingGridFeatureDescription>
{/*<ColPioneer>
{' '}
<PricingGridCheck
active={this.state.plan === 'beta'}
/>{' '}
</ColPioneer>
*/}
<ColExplorer>
<PriceText> Free</PriceText>
</ColExplorer>
<ColThinker>
<PriceBox>
<PriceText>
{this.state.term === 'monthly' ? '3' : '30'}€
</PriceText>
</PriceBox>
</ColThinker>
{/*<ColPioneer>
<PriceBox>
<PriceText>
{this.state.term === 'monthly' ? '3' : '30'} +{' '}
</PriceText>
{this.state.term === 'monthly' ? (
<PriceInputBox
onChange={this.pioneerDonationChanged}
size={1}
>
<option value={5}>5</option>
<option value={8}>8</option>
<option value={10}>10</option>
<option value={15}>15</option>
<option value={50}>50</option>
</PriceInputBox>
) : (
<PriceInputBox
onChange={this.pioneerDonationChanged}
size={1}
>
<option value={50}>50</option>
<option value={80}>80</option>
<option value={100}>100</option>
<option value={150}>150</option>
<option value={500}>500</option>
</PriceInputBox>
)}
<PriceText>€</PriceText>
</PriceBox>
</ColPioneer>
*/}
<ColThinker>
{this.props.loadingMonthly ||
this.props.loadingYearly ||
this.props.loadingPortal ? (
<PrimaryButton onClick={null}>
<LoadingIndicator />
</PrimaryButton>
) : (
<div>
{this.state.plan !== 'pro' ? (
<PrimaryButton onClick={this.openCheckout}>
Upgrade
</PrimaryButton>
) : (
<div>
{this.state.term === 'annual' &&
this.props.currentUser?.authorizedPlans?.includes(
'pro-monthly',
) ? (
<PrimaryButton
onClick={this.openCheckout}
>
Upgrade
</PrimaryButton>
) : (
<PrimaryButton
onClick={this.props.openPortal}
>
Edit
</PrimaryButton>
)}
</div>
)}
</div>
)}
</ColThinker>
{/*<ColPioneer>
{this.props.loadingMonthly ||
this.props.loadingYearly ||
this.props.loadingPortal ? (
<PrimaryButton onClick={null}>
<LoadingIndicator />
</PrimaryButton>
) : (
<div>
{this.state.plan !== 'beta' ? (
<PrimaryButton
onClick={this.openCheckoutPioneer}
>
Upgrade
</PrimaryButton>
) : (
<div>
{this.state.term === 'annual' &&
this.props.currentUser?.authorizedPlans?.includes(
'pro-monthly',
) ? (
<PrimaryButton
onClick={
this.openCheckoutPioneer
}
>
Upgrade
</PrimaryButton>
) : (
<PrimaryButton
onClick={this.props.openPortal}
>
Edit
</PrimaryButton>
)}
</div>
)}
</div>
)}
</ColPioneer>
*/}
</PricingGrid>
</SubscriptionOptionsContainer>
)
}
}
export default withCurrentUser(SubscriptionInnerOptions) | the_stack |
import * as gregor1 from '../gregor1'
export type HasServerKeysRes = {
hasServerKeys: boolean
}
export type APIRes = {
status: string
body: string
httpStatus: number
appStatus: string
}
export enum MobileAppState {
FOREGROUND = 'foreground',
BACKGROUND = 'background',
INACTIVE = 'inactive',
BACKGROUNDACTIVE = 'backgroundactive',
}
export enum MobileNetworkState {
NONE = 'none',
WIFI = 'wifi',
CELLULAR = 'cellular',
UNKNOWN = 'unknown',
NOTAVAILABLE = 'notavailable',
}
export enum BoxAuditAttemptResult {
FAILURE_RETRYABLE = 'failure_retryable',
FAILURE_MALICIOUS_SERVER = 'failure_malicious_server',
OK_VERIFIED = 'ok_verified',
OK_NOT_ATTEMPTED_ROLE = 'ok_not_attempted_role',
OK_NOT_ATTEMPTED_OPENTEAM = 'ok_not_attempted_openteam',
OK_NOT_ATTEMPTED_SUBTEAM = 'ok_not_attempted_subteam',
}
export type AvatarUrl = string
export type AvatarFormat = string
export enum BlockType {
DATA = 'data',
MD = 'md',
GIT = 'git',
}
export type ChallengeInfo = {
now: number
challenge: string
}
export enum BlockStatus {
UNKNOWN = 'unknown',
LIVE = 'live',
ARCHIVED = 'archived',
}
export type BlockRefNonce = string | null
export type BlockPingResponse = {}
export type UsageStatRecord = {
write: number
archive: number
read: number
mdWrite: number
gitWrite: number
gitArchive: number
}
export type BotToken = string
export type Time = number
export type UnixTime = number
export type DurationSec = number
export type DurationMsec = number
export type StringKVPair = {
key: string
value: string
}
export type UID = string
export type VID = string
export type DeviceID = string
export type SigID = string
export type LeaseID = string
export type KID = string
export type PhoneNumber = string
export type RawPhoneNumber = string
export type LinkID = string
export type BinaryLinkID = Buffer
export type BinaryKID = Buffer
export type TLFID = string
export type TeamID = string
export type UserOrTeamID = string
export type GitRepoName = string
export type HashMeta = Buffer
export enum TeamType {
NONE = 'none',
LEGACY = 'legacy',
MODERN = 'modern',
}
export enum TLFVisibility {
ANY = 'any',
PUBLIC = 'public',
PRIVATE = 'private',
}
export type Seqno = number
export enum SeqType {
NONE = 'none',
PUBLIC = 'public',
PRIVATE = 'private',
SEMIPRIVATE = 'semiprivate',
USER_PRIVATE_HIDDEN = 'user_private_hidden',
TEAM_PRIVATE_HIDDEN = 'team_private_hidden',
}
export type Bytes32 = string | null
export type Text = {
data: string
markup: boolean
}
export type PGPIdentity = {
username: string
comment: string
email: string
}
export enum DeviceType {
DESKTOP = 'desktop',
MOBILE = 'mobile',
}
export type DeviceTypeV2 = string
export type Stream = {
fd: number
}
export enum LogLevel {
NONE = 'none',
DEBUG = 'debug',
INFO = 'info',
NOTICE = 'notice',
WARN = 'warn',
ERROR = 'error',
CRITICAL = 'critical',
FATAL = 'fatal',
}
export enum ClientType {
NONE = 'none',
CLI = 'cli',
GUI_MAIN = 'gui_main',
KBFS = 'kbfs',
GUI_HELPER = 'gui_helper',
}
export type KBFSPathInfo = {
standardPath: string
deeplinkPath: string
platformAfterMountPath: string
}
export type PerUserKeyGeneration = number
export enum UserOrTeamResult {
USER = 'user',
TEAM = 'team',
}
export enum MerkleTreeID {
MASTER = 'master',
KBFS_PUBLIC = 'kbfs_public',
KBFS_PRIVATE = 'kbfs_private',
KBFS_PRIVATETEAM = 'kbfs_privateteam',
}
/**
* SocialAssertionService is a service that can be used to assert proofs for a
* user.
*/
export type SocialAssertionService = string
export type FullName = string
export enum FullNamePackageVersion {
V0 = 'v0',
V1 = 'v1',
V2 = 'v2',
}
export type ImageCropRect = {
x0: number
y0: number
x1: number
y1: number
}
export enum IdentityVisibility {
PRIVATE = 'private',
PUBLIC = 'public',
}
export type SizedImage = {
path: string
width: number
}
export enum OfflineAvailability {
NONE = 'none',
BEST_EFFORT = 'best_effort',
}
export type UserReacji = {
name: string
customAddr?: string
customAddrNoAnim?: string
}
export enum ReacjiSkinTone {
NONE = 'none',
SKINTONE1 = 'skintone1',
SKINTONE2 = 'skintone2',
SKINTONE3 = 'skintone3',
SKINTONE4 = 'skintone4',
SKINTONE5 = 'skintone5',
}
export enum WotStatusType {
NONE = 'none',
PROPOSED = 'proposed',
ACCEPTED = 'accepted',
REJECTED = 'rejected',
REVOKED = 'revoked',
}
export type SessionStatus = {
sessionFor: string
loaded: boolean
cleared: boolean
saltOnly: boolean
expired: boolean
}
export type PlatformInfo = {
os: string
osVersion: string
arch: string
goVersion: string
}
export type LoadDeviceErr = {
where: string
desc: string
}
export type DirSizeInfo = {
numFiles: number
name: string
humanSize: string
}
export type KbClientStatus = {
version: string
}
export type KbServiceStatus = {
version: string
running: boolean
pid: string
log: string
ekLog: string
perfLog: string
}
export type KBFSStatus = {
version: string
installedVersion: string
running: boolean
pid: string
log: string
perfLog: string
mount: string
}
export type DesktopStatus = {
version: string
running: boolean
log: string
}
export type UpdaterStatus = {
log: string
}
export type StartStatus = {
log: string
}
export type GitStatus = {
log: string
perfLog: string
}
export type LogSendID = string
export type AllProvisionedUsernames = {
defaultUsername: string
provisionedUsernames: string[] | null
hasProvisionedUser: boolean
}
export enum ForkType {
NONE = 'none',
AUTO = 'auto',
WATCHDOG = 'watchdog',
LAUNCHD = 'launchd',
SYSTEMD = 'systemd',
}
export type ConfigValue = {
isNull: boolean
b?: boolean
i?: number
f?: number
s?: string
o?: string
}
export type OutOfDateInfo = {
upgradeTo: string
upgradeUri: string
customMessage: string
criticalClockSkew: number
}
export enum UpdateInfoStatus {
UP_TO_DATE = 'up_to_date',
NEED_UPDATE = 'need_update',
CRITICALLY_OUT_OF_DATE = 'critically_out_of_date',
}
export enum UpdateInfoStatus2 {
OK = 'ok',
SUGGESTED = 'suggested',
CRITICAL = 'critical',
}
export type UpdateDetails = {
message: string
}
export enum ProxyType {
No_Proxy = 'no_proxy',
HTTP_Connect = 'http_connect',
Socks = 'socks',
}
export enum StatusCode {
SCOk = 'scok',
SCInputError = 'scinputerror',
SCAssertionParseError = 'scassertionparseerror',
SCLoginRequired = 'scloginrequired',
SCBadSession = 'scbadsession',
SCBadLoginUserNotFound = 'scbadloginusernotfound',
SCBadLoginPassword = 'scbadloginpassword',
SCNotFound = 'scnotfound',
SCThrottleControl = 'scthrottlecontrol',
SCDeleted = 'scdeleted',
SCGeneric = 'scgeneric',
SCAlreadyLoggedIn = 'scalreadyloggedin',
SCExists = 'scexists',
SCCanceled = 'sccanceled',
SCInputCanceled = 'scinputcanceled',
SCBadUsername = 'scbadusername',
SCOffline = 'scoffline',
SCReloginRequired = 'screloginrequired',
SCResolutionFailed = 'scresolutionfailed',
SCProfileNotPublic = 'scprofilenotpublic',
SCIdentifyFailed = 'scidentifyfailed',
SCTrackingBroke = 'sctrackingbroke',
SCWrongCryptoFormat = 'scwrongcryptoformat',
SCDecryptionError = 'scdecryptionerror',
SCInvalidAddress = 'scinvalidaddress',
SCWrongCryptoMsgType = 'scwrongcryptomsgtype',
SCNoSession = 'scnosession',
SCAccountReset = 'scaccountreset',
SCIdentifiesFailed = 'scidentifiesfailed',
SCNoSpaceOnDevice = 'scnospaceondevice',
SCMerkleClientError = 'scmerkleclienterror',
SCMerkleUpdateRoot = 'scmerkleupdateroot',
SCBadEmail = 'scbademail',
SCRateLimit = 'scratelimit',
SCBadSignupUsernameTaken = 'scbadsignupusernametaken',
SCDuplicate = 'scduplicate',
SCBadInvitationCode = 'scbadinvitationcode',
SCBadSignupUsernameReserved = 'scbadsignupusernamereserved',
SCBadSignupTeamName = 'scbadsignupteamname',
SCFeatureFlag = 'scfeatureflag',
SCEmailTaken = 'scemailtaken',
SCEmailAlreadyAdded = 'scemailalreadyadded',
SCEmailLimitExceeded = 'scemaillimitexceeded',
SCEmailCannotDeletePrimary = 'scemailcannotdeleteprimary',
SCEmailUnknown = 'scemailunknown',
SCBotSignupTokenNotFound = 'scbotsignuptokennotfound',
SCNoUpdate = 'scnoupdate',
SCMissingResult = 'scmissingresult',
SCKeyNotFound = 'sckeynotfound',
SCKeyCorrupted = 'sckeycorrupted',
SCKeyInUse = 'sckeyinuse',
SCKeyBadGen = 'sckeybadgen',
SCKeyNoSecret = 'sckeynosecret',
SCKeyBadUIDs = 'sckeybaduids',
SCKeyNoActive = 'sckeynoactive',
SCKeyNoSig = 'sckeynosig',
SCKeyBadSig = 'sckeybadsig',
SCKeyBadEldest = 'sckeybadeldest',
SCKeyNoEldest = 'sckeynoeldest',
SCKeyDuplicateUpdate = 'sckeyduplicateupdate',
SCSibkeyAlreadyExists = 'scsibkeyalreadyexists',
SCDecryptionKeyNotFound = 'scdecryptionkeynotfound',
SCVerificationKeyNotFound = 'scverificationkeynotfound',
SCKeyNoPGPEncryption = 'sckeynopgpencryption',
SCKeyNoNaClEncryption = 'sckeynonaclencryption',
SCKeySyncedPGPNotFound = 'sckeysyncedpgpnotfound',
SCKeyNoMatchingGPG = 'sckeynomatchinggpg',
SCKeyRevoked = 'sckeyrevoked',
SCSigCannotVerify = 'scsigcannotverify',
SCSigWrongKey = 'scsigwrongkey',
SCSigOldSeqno = 'scsigoldseqno',
SCSigCreationDisallowed = 'scsigcreationdisallowed',
SCSigMissingRatchet = 'scsigmissingratchet',
SCSigBadTotalOrder = 'scsigbadtotalorder',
SCBadTrackSession = 'scbadtracksession',
SCDeviceBadName = 'scdevicebadname',
SCDeviceBadStatus = 'scdevicebadstatus',
SCDeviceNameInUse = 'scdevicenameinuse',
SCDeviceNotFound = 'scdevicenotfound',
SCDeviceMismatch = 'scdevicemismatch',
SCDeviceRequired = 'scdevicerequired',
SCDevicePrevProvisioned = 'scdeviceprevprovisioned',
SCDeviceNoProvision = 'scdevicenoprovision',
SCDeviceProvisionViaDevice = 'scdeviceprovisionviadevice',
SCRevokeCurrentDevice = 'screvokecurrentdevice',
SCRevokeLastDevice = 'screvokelastdevice',
SCDeviceProvisionOffline = 'scdeviceprovisionoffline',
SCRevokeLastDevicePGP = 'screvokelastdevicepgp',
SCStreamExists = 'scstreamexists',
SCStreamNotFound = 'scstreamnotfound',
SCStreamWrongKind = 'scstreamwrongkind',
SCStreamEOF = 'scstreameof',
SCStreamUnknown = 'scstreamunknown',
SCGenericAPIError = 'scgenericapierror',
SCAPINetworkError = 'scapinetworkerror',
SCTimeout = 'sctimeout',
SCKBFSClientTimeout = 'sckbfsclienttimeout',
SCProofError = 'scprooferror',
SCIdentificationExpired = 'scidentificationexpired',
SCSelfNotFound = 'scselfnotfound',
SCBadKexPhrase = 'scbadkexphrase',
SCNoUIDelegation = 'scnouidelegation',
SCNoUI = 'scnoui',
SCGPGUnavailable = 'scgpgunavailable',
SCInvalidVersionError = 'scinvalidversionerror',
SCOldVersionError = 'scoldversionerror',
SCInvalidLocationError = 'scinvalidlocationerror',
SCServiceStatusError = 'scservicestatuserror',
SCInstallError = 'scinstallerror',
SCLoadKextError = 'scloadkexterror',
SCLoadKextPermError = 'scloadkextpermerror',
SCGitInternal = 'scgitinternal',
SCGitRepoAlreadyExists = 'scgitrepoalreadyexists',
SCGitInvalidRepoName = 'scgitinvalidreponame',
SCGitCannotDelete = 'scgitcannotdelete',
SCGitRepoDoesntExist = 'scgitrepodoesntexist',
SCLoginStateTimeout = 'scloginstatetimeout',
SCChatInternal = 'scchatinternal',
SCChatRateLimit = 'scchatratelimit',
SCChatConvExists = 'scchatconvexists',
SCChatUnknownTLFID = 'scchatunknowntlfid',
SCChatNotInConv = 'scchatnotinconv',
SCChatBadMsg = 'scchatbadmsg',
SCChatBroadcast = 'scchatbroadcast',
SCChatAlreadySuperseded = 'scchatalreadysuperseded',
SCChatAlreadyDeleted = 'scchatalreadydeleted',
SCChatTLFFinalized = 'scchattlffinalized',
SCChatCollision = 'scchatcollision',
SCIdentifySummaryError = 'scidentifysummaryerror',
SCNeedSelfRekey = 'scneedselfrekey',
SCNeedOtherRekey = 'scneedotherrekey',
SCChatMessageCollision = 'scchatmessagecollision',
SCChatDuplicateMessage = 'scchatduplicatemessage',
SCChatClientError = 'scchatclienterror',
SCChatNotInTeam = 'scchatnotinteam',
SCChatStalePreviousState = 'scchatstalepreviousstate',
SCChatEphemeralRetentionPolicyViolatedError = 'scchatephemeralretentionpolicyviolatederror',
SCChatUsersAlreadyInConversationError = 'scchatusersalreadyinconversationerror',
SCChatBadConversationError = 'scchatbadconversationerror',
SCTeamBadMembership = 'scteambadmembership',
SCTeamSelfNotOwner = 'scteamselfnotowner',
SCTeamNotFound = 'scteamnotfound',
SCTeamExists = 'scteamexists',
SCTeamReadError = 'scteamreaderror',
SCTeamWritePermDenied = 'scteamwritepermdenied',
SCTeamBadGeneration = 'scteambadgeneration',
SCNoOp = 'scnoop',
SCTeamInviteBadCancel = 'scteaminvitebadcancel',
SCTeamInviteBadToken = 'scteaminvitebadtoken',
SCTeamBadNameReservedDB = 'scteambadnamereserveddb',
SCTeamTarDuplicate = 'scteamtarduplicate',
SCTeamTarNotFound = 'scteamtarnotfound',
SCTeamMemberExists = 'scteammemberexists',
SCTeamNotReleased = 'scteamnotreleased',
SCTeamPermanentlyLeft = 'scteampermanentlyleft',
SCTeamNeedRootId = 'scteamneedrootid',
SCTeamHasLiveChildren = 'scteamhaslivechildren',
SCTeamDeleteError = 'scteamdeleteerror',
SCTeamBadRootTeam = 'scteambadrootteam',
SCTeamNameConflictsWithUser = 'scteamnameconflictswithuser',
SCTeamDeleteNoUpPointer = 'scteamdeletenouppointer',
SCTeamNeedOwner = 'scteamneedowner',
SCTeamNoOwnerAllowed = 'scteamnoownerallowed',
SCTeamImplicitNoNonSbs = 'scteamimplicitnononsbs',
SCTeamImplicitBadHash = 'scteamimplicitbadhash',
SCTeamImplicitBadName = 'scteamimplicitbadname',
SCTeamImplicitClash = 'scteamimplicitclash',
SCTeamImplicitDuplicate = 'scteamimplicitduplicate',
SCTeamImplicitBadOp = 'scteamimplicitbadop',
SCTeamImplicitBadRole = 'scteamimplicitbadrole',
SCTeamImplicitNotFound = 'scteamimplicitnotfound',
SCTeamBadAdminSeqnoType = 'scteambadadminseqnotype',
SCTeamImplicitBadAdd = 'scteamimplicitbadadd',
SCTeamImplicitBadRemove = 'scteamimplicitbadremove',
SCTeamInviteTokenReused = 'scteaminvitetokenreused',
SCTeamKeyMaskNotFound = 'scteamkeymasknotfound',
SCTeamBanned = 'scteambanned',
SCTeamInvalidBan = 'scteaminvalidban',
SCTeamShowcasePermDenied = 'scteamshowcasepermdenied',
SCTeamProvisionalCanKey = 'scteamprovisionalcankey',
SCTeamProvisionalCannotKey = 'scteamprovisionalcannotkey',
SCTeamFTLOutdated = 'scteamftloutdated',
SCTeamStorageWrongRevision = 'scteamstoragewrongrevision',
SCTeamStorageBadGeneration = 'scteamstoragebadgeneration',
SCTeamStorageNotFound = 'scteamstoragenotfound',
SCTeamContactSettingsBlock = 'scteamcontactsettingsblock',
SCEphemeralKeyBadGeneration = 'scephemeralkeybadgeneration',
SCEphemeralKeyUnexpectedBox = 'scephemeralkeyunexpectedbox',
SCEphemeralKeyMissingBox = 'scephemeralkeymissingbox',
SCEphemeralKeyWrongNumberOfKeys = 'scephemeralkeywrongnumberofkeys',
SCEphemeralKeyMismatchedKey = 'scephemeralkeymismatchedkey',
SCEphemeralPairwiseMACsMissingUIDs = 'scephemeralpairwisemacsmissinguids',
SCEphemeralDeviceAfterEK = 'scephemeraldeviceafterek',
SCEphemeralMemberAfterEK = 'scephemeralmemberafterek',
SCEphemeralDeviceStale = 'scephemeraldevicestale',
SCEphemeralUserStale = 'scephemeraluserstale',
SCStellarError = 'scstellarerror',
SCStellarBadInput = 'scstellarbadinput',
SCStellarWrongRevision = 'scstellarwrongrevision',
SCStellarMissingBundle = 'scstellarmissingbundle',
SCStellarBadPuk = 'scstellarbadpuk',
SCStellarMissingAccount = 'scstellarmissingaccount',
SCStellarBadPrev = 'scstellarbadprev',
SCStellarWrongPrimary = 'scstellarwrongprimary',
SCStellarUnsupportedCurrency = 'scstellarunsupportedcurrency',
SCStellarNeedDisclaimer = 'scstellarneeddisclaimer',
SCStellarDeviceNotMobile = 'scstellardevicenotmobile',
SCStellarMobileOnlyPurgatory = 'scstellarmobileonlypurgatory',
SCStellarIncompatibleVersion = 'scstellarincompatibleversion',
SCNISTWrongSize = 'scnistwrongsize',
SCNISTBadMode = 'scnistbadmode',
SCNISTHashWrongSize = 'scnisthashwrongsize',
SCNISTSigWrongSize = 'scnistsigwrongsize',
SCNISTSigBadInput = 'scnistsigbadinput',
SCNISTSigBadUID = 'scnistsigbaduid',
SCNISTSigBadDeviceID = 'scnistsigbaddeviceid',
SCNISTSigBadNonce = 'scnistsigbadnonce',
SCNISTNoSigOrHash = 'scnistnosigorhash',
SCNISTExpired = 'scnistexpired',
SCNISTSigRevoked = 'scnistsigrevoked',
SCNISTKeyRevoked = 'scnistkeyrevoked',
SCNISTUserDeleted = 'scnistuserdeleted',
SCNISTNoDevice = 'scnistnodevice',
SCNISTSigCannot_verify = 'scnistsigcannot_verify',
SCNISTReplay = 'scnistreplay',
SCNISTSigBadLifetime = 'scnistsigbadlifetime',
SCNISTNotFound = 'scnistnotfound',
SCNISTBadClock = 'scnistbadclock',
SCNISTSigBadCtime = 'scnistsigbadctime',
SCBadSignupUsernameDeleted = 'scbadsignupusernamedeleted',
SCPhoneNumberUnknown = 'scphonenumberunknown',
SCPhoneNumberAlreadyVerified = 'scphonenumberalreadyverified',
SCPhoneNumberVerificationCodeExpired = 'scphonenumberverificationcodeexpired',
SCPhoneNumberWrongVerificationCode = 'scphonenumberwrongverificationcode',
SCPhoneNumberLimitExceeded = 'scphonenumberlimitexceeded',
SCNoPaperKeys = 'scnopaperkeys',
SCTeambotKeyGenerationExists = 'scteambotkeygenerationexists',
SCTeambotKeyOldBoxedGeneration = 'scteambotkeyoldboxedgeneration',
SCTeambotKeyBadGeneration = 'scteambotkeybadgeneration',
SCAirdropRegisterFailedMisc = 'scairdropregisterfailedmisc',
SCSimpleFSNameExists = 'scsimplefsnameexists',
SCSimpleFSDirNotEmpty = 'scsimplefsdirnotempty',
SCSimpleFSNotExist = 'scsimplefsnotexist',
SCSimpleFSNoAccess = 'scsimplefsnoaccess',
}
export type ED25519PublicKey = string | null
export type ED25519Signature = string | null
export type EncryptedBytes32 = string | null
export type BoxNonce = string | null
export type BoxPublicKey = string | null
export type RegisterAddressRes = {
type: string
family: string
}
export enum ExitCode {
OK = 'ok',
NOTOK = 'notok',
RESTART = 'restart',
}
export enum DbType {
MAIN = 'main',
CHAT = 'chat',
FS_BLOCK_CACHE = 'fs_block_cache',
FS_BLOCK_CACHE_META = 'fs_block_cache_meta',
FS_SYNC_BLOCK_CACHE = 'fs_sync_block_cache',
FS_SYNC_BLOCK_CACHE_META = 'fs_sync_block_cache_meta',
}
export type DbValue = Buffer
export enum OnLoginStartupStatus {
UNKNOWN = 'unknown',
DISABLED = 'disabled',
ENABLED = 'enabled',
}
export type FirstStepResult = {
valPlusTwo: number
}
export type EkGeneration = number
export enum TeamEphemeralKeyType {
TEAM = 'team',
TEAMBOT = 'teambot',
}
export enum FolderType {
UNKNOWN = 'unknown',
PRIVATE = 'private',
PUBLIC = 'public',
TEAM = 'team',
}
export enum FolderConflictType {
NONE = 'none',
IN_CONFLICT = 'in_conflict',
IN_CONFLICT_AND_STUCK = 'in_conflict_and_stuck',
CLEARED_CONFLICT = 'cleared_conflict',
}
export enum ConflictStateType {
NormalView = 'normalview',
ManualResolvingLocalView = 'manualresolvinglocalview',
}
export type FeaturedBot = {
botAlias: string
description: string
extendedDescription: string
extendedDescriptionRaw: string
botUsername: string
ownerTeam?: string
ownerUser?: string
rank: number
isPromoted: boolean
}
export type File = {
path: string
}
export type RepoID = string
export enum GitLocalMetadataVersion {
V1 = 'v1',
}
export enum GitPushType {
DEFAULT = 'default',
CREATEREPO = 'createrepo',
RENAMEREPO = 'renamerepo',
}
export enum GitRepoResultState {
ERR = 'err',
OK = 'ok',
}
export type GitTeamRepoSettings = {
channelName?: string
chatDisabled: boolean
}
export type SelectKeyRes = {
keyId: string
doSecretPush: boolean
}
export enum PushReason {
NONE = 'none',
RECONNECTED = 'reconnected',
NEW_DATA = 'new_data',
}
export type HomeScreenItemID = string
export enum HomeScreenItemType {
TODO = 'todo',
PEOPLE = 'people',
ANNOUNCEMENT = 'announcement',
}
export enum AppLinkType {
NONE = 'none',
PEOPLE = 'people',
CHAT = 'chat',
FILES = 'files',
WALLET = 'wallet',
GIT = 'git',
DEVICES = 'devices',
SETTINGS = 'settings',
TEAMS = 'teams',
}
export type HomeScreenAnnouncementID = number
export type HomeScreenAnnouncementVersion = number
export enum HomeScreenTodoType {
NONE = 'none',
BIO = 'bio',
PROOF = 'proof',
DEVICE = 'device',
FOLLOW = 'follow',
CHAT = 'chat',
PAPERKEY = 'paperkey',
TEAM = 'team',
FOLDER = 'folder',
GIT_REPO = 'git_repo',
TEAM_SHOWCASE = 'team_showcase',
AVATAR_USER = 'avatar_user',
AVATAR_TEAM = 'avatar_team',
ADD_PHONE_NUMBER = 'add_phone_number',
VERIFY_ALL_PHONE_NUMBER = 'verify_all_phone_number',
VERIFY_ALL_EMAIL = 'verify_all_email',
LEGACY_EMAIL_VISIBILITY = 'legacy_email_visibility',
ADD_EMAIL = 'add_email',
ANNONCEMENT_PLACEHOLDER = 'annoncement_placeholder',
}
export enum HomeScreenPeopleNotificationType {
FOLLOWED = 'followed',
FOLLOWED_MULTI = 'followed_multi',
CONTACT = 'contact',
CONTACT_MULTI = 'contact_multi',
}
export type Pics = {
square40: string
square200: string
square360: string
}
export type Identify3Assertion = string
export type Identify3GUIID = string
export enum Identify3RowState {
CHECKING = 'checking',
VALID = 'valid',
ERROR = 'error',
WARNING = 'warning',
REVOKED = 'revoked',
}
export enum Identify3RowColor {
BLUE = 'blue',
RED = 'red',
BLACK = 'black',
GREEN = 'green',
GRAY = 'gray',
YELLOW = 'yellow',
ORANGE = 'orange',
}
export enum Identify3ResultType {
OK = 'ok',
BROKEN = 'broken',
NEEDS_UPGRADE = 'needs_upgrade',
CANCELED = 'canceled',
}
export type TrackToken = string
export type SigVersion = number
export enum TrackDiffType {
NONE = 'none',
ERROR = 'error',
CLASH = 'clash',
REVOKED = 'revoked',
UPGRADED = 'upgraded',
NEW = 'new',
REMOTE_FAIL = 'remote_fail',
REMOTE_WORKING = 'remote_working',
REMOTE_CHANGED = 'remote_changed',
NEW_ELDEST = 'new_eldest',
NONE_VIA_TEMPORARY = 'none_via_temporary',
}
/**
* TrackStatus is a summary of this track before the track is approved by the
* user.
* NEW_*: New tracks
* UPDATE_*: Update to an existing track
* NEW_OK: Everything ok
* NEW_ZERO_PROOFS: User being tracked has no proofs
* NEW_FAIL_PROOFS: User being tracked has some failed proofs
* UPDATE_BROKEN: Previous tracking statement broken, this one will fix it.
* UPDATE_NEW_PROOFS: Previous tracking statement ok, but there are new proofs since previous tracking statement generated
* UPDATE_OK: No changes to previous tracking statement
*/
export enum TrackStatus {
NEW_OK = 'new_ok',
NEW_ZERO_PROOFS = 'new_zero_proofs',
NEW_FAIL_PROOFS = 'new_fail_proofs',
UPDATE_BROKEN_FAILED_PROOFS = 'update_broken_failed_proofs',
UPDATE_NEW_PROOFS = 'update_new_proofs',
UPDATE_OK = 'update_ok',
UPDATE_BROKEN_REVOKED = 'update_broken_revoked',
}
export enum IdentifyReasonType {
NONE = 'none',
ID = 'id',
TRACK = 'track',
ENCRYPT = 'encrypt',
DECRYPT = 'decrypt',
VERIFY = 'verify',
RESOURCE = 'resource',
BACKGROUND = 'background',
}
export type SigHint = {
remoteId: string
humanUrl: string
apiUrl: string
checkText: string
}
export enum CheckResultFreshness {
FRESH = 'fresh',
AGED = 'aged',
RANCID = 'rancid',
}
export type ConfirmResult = {
identityConfirmed: boolean
remoteConfirmed: boolean
expiringLocal: boolean
autoConfirmed: boolean
}
export enum DismissReasonType {
NONE = 'none',
HANDLED_ELSEWHERE = 'handled_elsewhere',
}
export enum IncomingShareType {
FILE = 'file',
TEXT = 'text',
IMAGE = 'image',
VIDEO = 'video',
}
/**
* Install status describes state of install for a component or service.
*/
export enum InstallStatus {
UNKNOWN = 'unknown',
ERROR = 'error',
NOT_INSTALLED = 'not_installed',
INSTALLED = 'installed',
}
export enum InstallAction {
UNKNOWN = 'unknown',
NONE = 'none',
UPGRADE = 'upgrade',
REINSTALL = 'reinstall',
INSTALL = 'install',
}
export type FuseMountInfo = {
path: string
fstype: string
output: string
}
export type InviteCounts = {
inviteCount: number
percentageChange: number
showNumInvites: boolean
showFire: boolean
tooltipMarkdown: string
}
export type EmailInvites = {
commaSeparatedEmailsFromUser?: string
emailsFromContacts?: EmailAddress[] | null
}
export enum FSStatusCode {
START = 'start',
FINISH = 'finish',
ERROR = 'error',
}
export enum FSNotificationType {
ENCRYPTING = 'encrypting',
DECRYPTING = 'decrypting',
SIGNING = 'signing',
VERIFYING = 'verifying',
REKEYING = 'rekeying',
CONNECTION = 'connection',
MD_READ_SUCCESS = 'md_read_success',
FILE_CREATED = 'file_created',
FILE_MODIFIED = 'file_modified',
FILE_DELETED = 'file_deleted',
FILE_RENAMED = 'file_renamed',
INITIALIZED = 'initialized',
SYNC_CONFIG_CHANGED = 'sync_config_changed',
}
export enum FSErrorType {
ACCESS_DENIED = 'access_denied',
USER_NOT_FOUND = 'user_not_found',
REVOKED_DATA_DETECTED = 'revoked_data_detected',
NOT_LOGGED_IN = 'not_logged_in',
TIMEOUT = 'timeout',
REKEY_NEEDED = 'rekey_needed',
BAD_FOLDER = 'bad_folder',
NOT_IMPLEMENTED = 'not_implemented',
OLD_VERSION = 'old_version',
OVER_QUOTA = 'over_quota',
NO_SIG_CHAIN = 'no_sig_chain',
TOO_MANY_FOLDERS = 'too_many_folders',
EXDEV_NOT_SUPPORTED = 'exdev_not_supported',
DISK_LIMIT_REACHED = 'disk_limit_reached',
DISK_CACHE_ERROR_LOG_SEND = 'disk_cache_error_log_send',
OFFLINE_ARCHIVED = 'offline_archived',
OFFLINE_UNSYNCED = 'offline_unsynced',
}
export type FSSyncStatusRequest = {
requestId: number
}
export type PassphraseStream = {
passphraseStream: Buffer
generation: number
}
export type SessionToken = string
export type CsrfToken = string
export type HelloRes = string
export type KVGetResult = {
teamName: string
namespace: string
entryKey: string
entryValue?: string | null
revision: number
}
export type KVPutResult = {
teamName: string
namespace: string
entryKey: string
revision: number
}
export type EncryptedKVEntry = {
v: number
e: Buffer
n: Buffer
}
export type KVListNamespaceResult = {
teamName: string
namespaces: string[] | null
}
export type KVListEntryKey = {
entryKey: string
revision: number
}
export type KVDeleteEntryResult = {
teamName: string
namespace: string
entryKey: string
revision: number
}
export enum ResetPromptType {
COMPLETE = 'complete',
ENTER_NO_DEVICES = 'enter_no_devices',
ENTER_FORGOT_PW = 'enter_forgot_pw',
ENTER_RESET_PW = 'enter_reset_pw',
}
export type ResetPromptInfo = {
hasWallet: boolean
}
export enum ResetPromptResponse {
NOTHING = 'nothing',
CANCEL_RESET = 'cancel_reset',
CONFIRM_RESET = 'confirm_reset',
}
export enum PassphraseRecoveryPromptType {
ENCRYPTED_PGP_KEYS = 'encrypted_pgp_keys',
}
export enum ResetMessage {
ENTERED_VERIFIED = 'entered_verified',
ENTERED_PASSWORDLESS = 'entered_passwordless',
REQUEST_VERIFIED = 'request_verified',
NOT_COMPLETED = 'not_completed',
CANCELED = 'canceled',
COMPLETED = 'completed',
RESET_LINK_SENT = 'reset_link_sent',
}
export type KBFSRootHash = Buffer
export type MerkleStoreSupportedVersion = number
export type MerkleStoreKitHash = string
export type MerkleStoreKit = string
export type MerkleStoreEntryString = string
export type KeyBundle = {
version: number
bundle: Buffer
}
export type MerkleRoot = {
version: number
root: Buffer
}
export type LockID = number
export type MDPriority = number
export type RekeyRequest = {
folderId: string
revision: number
}
export enum NetworkSource {
LOCAL = 'local',
REMOTE = 'remote',
}
export type ChatConversationID = Buffer
export type DeletedTeamInfo = {
teamName: string
deletedBy: string
id: gregor1.MsgID
}
export type WalletAccountInfo = {
accountId: string
numUnread: number
}
export type NotificationChannels = {
session: boolean
users: boolean
kbfs: boolean
kbfsdesktop: boolean
kbfslegacy: boolean
kbfssubscription: boolean
tracking: boolean
favorites: boolean
paperkeys: boolean
keyfamily: boolean
service: boolean
app: boolean
chat: boolean
pgp: boolean
kbfsrequest: boolean
badges: boolean
reachability: boolean
team: boolean
ephemeral: boolean
teambot: boolean
chatkbfsedits: boolean
chatdev: boolean
chatemoji: boolean
chatemojicross: boolean
deviceclone: boolean
chatattachments: boolean
wallet: boolean
audit: boolean
runtimestats: boolean
featuredBots: boolean
saltpack: boolean
}
export enum StatsSeverityLevel {
NORMAL = 'normal',
WARNING = 'warning',
SEVERE = 'severe',
}
export enum ProcessType {
MAIN = 'main',
KBFS = 'kbfs',
}
export enum PerfEventType {
NETWORK = 'network',
TEAMBOXAUDIT = 'teamboxaudit',
TEAMAUDIT = 'teamaudit',
USERCHAIN = 'userchain',
TEAMCHAIN = 'teamchain',
CLEARCONV = 'clearconv',
CLEARINBOX = 'clearinbox',
TEAMTREELOAD = 'teamtreeload',
}
export enum SaltpackOperationType {
ENCRYPT = 'encrypt',
DECRYPT = 'decrypt',
SIGN = 'sign',
VERIFY = 'verify',
}
export type HttpSrvInfo = {
address: string
token: string
}
export type TeamChangeSet = {
membershipChanged: boolean
keyRotated: boolean
renamed: boolean
misc: boolean
}
export enum AvatarUpdateType {
NONE = 'none',
USER = 'user',
TEAM = 'team',
}
export enum RuntimeGroup {
UNKNOWN = 'unknown',
LINUXLIKE = 'linuxlike',
DARWINLIKE = 'darwinlike',
WINDOWSLIKE = 'windowslike',
}
export type Feature = {
allow: boolean
defaultValue: boolean
readonly: boolean
label: string
}
export enum PassphraseType {
NONE = 'none',
PAPER_KEY = 'paper_key',
PASS_PHRASE = 'pass_phrase',
VERIFY_PASS_PHRASE = 'verify_pass_phrase',
}
export type GetPassphraseRes = {
passphrase: string
storeSecret: boolean
}
export enum SignMode {
ATTACHED = 'attached',
DETACHED = 'detached',
CLEAR = 'clear',
}
export type PGPEncryptOptions = {
recipients: string[] | null
noSign: boolean
noSelf: boolean
binaryOut: boolean
keyQuery: string
}
export type PGPDecryptOptions = {
assertSigned: boolean
signedBy: string
}
export type PGPVerifyOptions = {
signedBy: string
signature: Buffer
}
export type KeyInfo = {
fingerprint: string
key: string
desc: string
}
export type PGPQuery = {
secret: boolean
query: string
exactMatch: boolean
}
/**
* Export all pgp keys in lksec, then if doPurge is true, remove the keys from lksec.
*/
export type PGPPurgeRes = {
filenames: string[] | null
}
export enum FileType {
UNKNOWN = 'unknown',
DIRECTORY = 'directory',
FILE = 'file',
}
export enum ProofState {
NONE = 'none',
OK = 'ok',
TEMP_FAILURE = 'temp_failure',
PERM_FAILURE = 'perm_failure',
LOOKING = 'looking',
SUPERSEDED = 'superseded',
POSTED = 'posted',
REVOKED = 'revoked',
DELETED = 'deleted',
UNKNOWN_TYPE = 'unknown_type',
SIG_HINT_MISSING = 'sig_hint_missing',
UNCHECKED = 'unchecked',
}
/**
* 3: It's been found in the hunt, but not proven yet
* 1xx: Retryable soft errors; note that this will be put in the proof_cache, but won't
* be returned from the proof cache in most cases. Their freshness will always be
* RANCID.
* 2xx: Will likely result in a hard error, if repeated enough
* 3xx: Hard final errors
*/
export enum ProofStatus {
NONE = 'none',
OK = 'ok',
LOCAL = 'local',
FOUND = 'found',
BASE_ERROR = 'base_error',
HOST_UNREACHABLE = 'host_unreachable',
PERMISSION_DENIED = 'permission_denied',
FAILED_PARSE = 'failed_parse',
DNS_ERROR = 'dns_error',
AUTH_FAILED = 'auth_failed',
HTTP_429 = 'http_429',
HTTP_500 = 'http_500',
TIMEOUT = 'timeout',
INTERNAL_ERROR = 'internal_error',
UNCHECKED = 'unchecked',
MISSING_PVL = 'missing_pvl',
BASE_HARD_ERROR = 'base_hard_error',
NOT_FOUND = 'not_found',
CONTENT_FAILURE = 'content_failure',
BAD_USERNAME = 'bad_username',
BAD_REMOTE_ID = 'bad_remote_id',
TEXT_NOT_FOUND = 'text_not_found',
BAD_ARGS = 'bad_args',
CONTENT_MISSING = 'content_missing',
TITLE_NOT_FOUND = 'title_not_found',
SERVICE_ERROR = 'service_error',
TOR_SKIPPED = 'tor_skipped',
TOR_INCOMPATIBLE = 'tor_incompatible',
HTTP_300 = 'http_300',
HTTP_400 = 'http_400',
HTTP_OTHER = 'http_other',
EMPTY_JSON = 'empty_json',
DELETED = 'deleted',
SERVICE_DEAD = 'service_dead',
BAD_SIGNATURE = 'bad_signature',
BAD_API_URL = 'bad_api_url',
UNKNOWN_TYPE = 'unknown_type',
NO_HINT = 'no_hint',
BAD_HINT_TEXT = 'bad_hint_text',
INVALID_PVL = 'invalid_pvl',
}
export enum ProofType {
NONE = 'none',
KEYBASE = 'keybase',
TWITTER = 'twitter',
GITHUB = 'github',
REDDIT = 'reddit',
COINBASE = 'coinbase',
HACKERNEWS = 'hackernews',
FACEBOOK = 'facebook',
GENERIC_SOCIAL = 'generic_social',
GENERIC_WEB_SITE = 'generic_web_site',
DNS = 'dns',
PGP = 'pgp',
ROOTER = 'rooter',
}
export type SelectorEntry = {
isIndex: boolean
index: number
isKey: boolean
key: string
isAll: boolean
isContents: boolean
}
export type ParamProofUsernameConfig = {
re: string
min: number
max: number
}
export type ServiceDisplayConfig = {
creationDisabled: boolean
priority: number
key: string
group?: string
new: boolean
logoKey: string
}
export enum PromptOverwriteType {
SOCIAL = 'social',
SITE = 'site',
}
export enum ProvisionMethod {
DEVICE = 'device',
PAPER_KEY = 'paper_key',
PASSPHRASE = 'passphrase',
GPG_IMPORT = 'gpg_import',
GPG_SIGN = 'gpg_sign',
}
export enum GPGMethod {
GPG_NONE = 'gpg_none',
GPG_IMPORT = 'gpg_import',
GPG_SIGN = 'gpg_sign',
}
export enum ChooseType {
EXISTING_DEVICE = 'existing_device',
NEW_DEVICE = 'new_device',
}
/**
* SecretResponse should be returned by DisplayAndPromptSecret. Use either secret or phrase.
*/
export type SecretResponse = {
secret: Buffer
phrase: string
}
export enum Reachable {
UNKNOWN = 'unknown',
YES = 'yes',
NO = 'no',
}
export enum Outcome {
NONE = 'none',
FIXED = 'fixed',
IGNORED = 'ignored',
}
export enum RekeyEventType {
NONE = 'none',
NOT_LOGGED_IN = 'not_logged_in',
API_ERROR = 'api_error',
NO_PROBLEMS = 'no_problems',
LOAD_ME_ERROR = 'load_me_error',
CURRENT_DEVICE_CAN_REKEY = 'current_device_can_rekey',
DEVICE_LOAD_ERROR = 'device_load_error',
HARASS = 'harass',
NO_GREGOR_MESSAGES = 'no_gregor_messages',
}
export type SHA512 = Buffer
export enum ResetType {
NONE = 'none',
RESET = 'reset',
DELETE = 'delete',
}
export enum AuthenticityType {
SIGNED = 'signed',
REPUDIABLE = 'repudiable',
ANONYMOUS = 'anonymous',
}
export type SaltpackDecryptOptions = {
interactive: boolean
forceRemoteCheck: boolean
usePaperKey: boolean
}
export type SaltpackSignOptions = {
detached: boolean
binary: boolean
saltpackVersion: number
}
export type SaltpackVerifyOptions = {
signedBy: string
signature: Buffer
}
export type SaltpackEncryptResult = {
usedUnresolvedSbs: boolean
unresolvedSbsAssertion: string
}
export type SaltpackFrontendEncryptOptions = {
recipients: string[] | null
signed: boolean
includeSelf: boolean
}
export type SaltpackEncryptStringResult = {
usedUnresolvedSbs: boolean
unresolvedSbsAssertion: string
ciphertext: string
}
export type SaltpackEncryptFileResult = {
usedUnresolvedSbs: boolean
unresolvedSbsAssertion: string
filename: string
}
export enum SaltpackSenderType {
NOT_TRACKED = 'not_tracked',
UNKNOWN = 'unknown',
ANONYMOUS = 'anonymous',
TRACKING_BROKE = 'tracking_broke',
TRACKING_OK = 'tracking_ok',
SELF = 'self',
REVOKED = 'revoked',
EXPIRED = 'expired',
}
export type SecretEntryArg = {
desc: string
prompt: string
err: string
cancel: string
ok: string
reason: string
showTyping: boolean
}
export type SecretEntryRes = {
text: string
canceled: boolean
storeSecret: boolean
}
export type NaclSigningKeyPublic = string | null
export type NaclSigningKeyPrivate = string | null
export type NaclDHKeyPublic = string | null
export type NaclDHKeyPrivate = string | null
export type SignupRes = {
passphraseOk: boolean
postOk: boolean
writeOk: boolean
paperKey: string
}
export type SigTypes = {
track: boolean
proof: boolean
cryptocurrency: boolean
isSelf: boolean
}
export type OpID = string | null
export type KBFSRevision = number
export enum KBFSArchivedType {
REVISION = 'revision',
TIME = 'time',
TIME_STRING = 'time_string',
REL_TIME_STRING = 'rel_time_string',
}
export enum PathType {
LOCAL = 'local',
KBFS = 'kbfs',
KBFS_ARCHIVED = 'kbfs_archived',
}
export enum DirentType {
FILE = 'file',
DIR = 'dir',
SYM = 'sym',
EXEC = 'exec',
}
export enum PrefetchStatus {
NOT_STARTED = 'not_started',
IN_PROGRESS = 'in_progress',
COMPLETE = 'complete',
}
export enum RevisionSpanType {
DEFAULT = 'default',
LAST_FIVE = 'last_five',
}
export type ErrorNum = number
export enum OpenFlags {
READ = 'read',
REPLACE = 'replace',
EXISTING = 'existing',
WRITE = 'write',
APPEND = 'append',
DIRECTORY = 'directory',
}
export type Progress = number
export enum AsyncOps {
LIST = 'list',
LIST_RECURSIVE = 'list_recursive',
READ = 'read',
WRITE = 'write',
COPY = 'copy',
MOVE = 'move',
REMOVE = 'remove',
LIST_RECURSIVE_TO_DEPTH = 'list_recursive_to_depth',
GET_REVISIONS = 'get_revisions',
}
export enum ListFilter {
NO_FILTER = 'no_filter',
FILTER_ALL_HIDDEN = 'filter_all_hidden',
FILTER_SYSTEM_HIDDEN = 'filter_system_hidden',
}
export type SimpleFSQuotaUsage = {
usageBytes: number
archiveBytes: number
limitBytes: number
gitUsageBytes: number
gitArchiveBytes: number
gitLimitBytes: number
}
export enum FolderSyncMode {
DISABLED = 'disabled',
ENABLED = 'enabled',
PARTIAL = 'partial',
}
export enum KbfsOnlineStatus {
OFFLINE = 'offline',
TRYING = 'trying',
ONLINE = 'online',
}
export type FSSettings = {
spaceAvailableNotificationThreshold: number
sfmiBannerDismissed: boolean
syncOnCellular: boolean
}
export enum SubscriptionTopic {
FAVORITES = 'favorites',
JOURNAL_STATUS = 'journal_status',
ONLINE_STATUS = 'online_status',
DOWNLOAD_STATUS = 'download_status',
FILES_TAB_BADGE = 'files_tab_badge',
OVERALL_SYNC_STATUS = 'overall_sync_status',
SETTINGS = 'settings',
UPLOAD_STATUS = 'upload_status',
}
export enum PathSubscriptionTopic {
CHILDREN = 'children',
STAT = 'stat',
}
export enum FilesTabBadge {
NONE = 'none',
UPLOADING_STUCK = 'uploading_stuck',
AWAITING_UPLOAD = 'awaiting_upload',
UPLOADING = 'uploading',
}
export enum GUIViewType {
DEFAULT = 'default',
TEXT = 'text',
IMAGE = 'image',
AUDIO = 'audio',
VIDEO = 'video',
PDF = 'pdf',
}
export type SimpleFSSearchHit = {
path: string
}
export type TeambotKeyGeneration = number
export enum TeamRole {
NONE = 'none',
READER = 'reader',
WRITER = 'writer',
ADMIN = 'admin',
OWNER = 'owner',
BOT = 'bot',
RESTRICTEDBOT = 'restrictedbot',
}
export enum TeamApplication {
KBFS = 'kbfs',
CHAT = 'chat',
SALTPACK = 'saltpack',
GIT_METADATA = 'git_metadata',
SEITAN_INVITE_TOKEN = 'seitan_invite_token',
STELLAR_RELAY = 'stellar_relay',
KVSTORE = 'kvstore',
}
export enum TeamStatus {
NONE = 'none',
LIVE = 'live',
DELETED = 'deleted',
ABANDONED = 'abandoned',
}
export enum AuditMode {
STANDARD = 'standard',
JUST_CREATED = 'just_created',
SKIP = 'skip',
STANDARD_NO_HIDDEN = 'standard_no_hidden',
}
export type PerTeamKeyGeneration = number
export enum PTKType {
READER = 'reader',
}
export enum PerTeamSeedCheckVersion {
V1 = 'v1',
}
export type PerTeamSeedCheckValue = Buffer
export type PerTeamSeedCheckValuePostImage = Buffer
export type MaskB64 = Buffer
export type TeamInviteID = string
export type TeamInviteMaxUses = number
export type PerTeamKeySeed = string | null
export enum TeamMemberStatus {
ACTIVE = 'active',
RESET = 'reset',
DELETED = 'deleted',
}
export type UserVersionPercentForm = string
export enum RatchetType {
MAIN = 'main',
BLINDED = 'blinded',
SELF = 'self',
UNCOMMITTED = 'uncommitted',
}
export enum AuditVersion {
V0 = 'v0',
V1 = 'v1',
V2 = 'v2',
V3 = 'v3',
V4 = 'v4',
}
export enum TeamInviteCategory {
NONE = 'none',
UNKNOWN = 'unknown',
KEYBASE = 'keybase',
EMAIL = 'email',
SBS = 'sbs',
SEITAN = 'seitan',
PHONE = 'phone',
INVITELINK = 'invitelink',
}
export type TeamInviteSocialNetwork = string
export type TeamInviteName = string
export type TeamInviteDisplayName = string
export type TeamEncryptedKBFSKeyset = {
v: number
e: Buffer
n: Buffer
}
export type TeamEncryptedKBFSKeysetHash = string
export type BoxSummaryHash = string
export type TeamNamePart = string
export type SeitanAKey = string
export type SeitanIKey = string
export type SeitanIKeyInvitelink = string
export type SeitanPubKey = string
export type SeitanIKeyV2 = string
export enum SeitanKeyAndLabelVersion {
V1 = 'v1',
V2 = 'v2',
Invitelink = 'invitelink',
}
export enum SeitanKeyLabelType {
SMS = 'sms',
GENERIC = 'generic',
}
export type SeitanKeyLabelSms = {
f: string
n: string
}
export type SeitanKeyLabelGeneric = {
l: string
}
export type TeamBotSettings = {
cmds: boolean
mentions: boolean
triggers: string[] | null
convs: string[] | null
}
export type TeamRequestAccessResult = {
open: boolean
}
export type TeamAcceptOrRequestResult = {
wasToken: boolean
wasSeitan: boolean
wasTeamName: boolean
wasOpenTeam: boolean
}
export type BulkRes = {
malformed: string[] | null
}
export type ConflictGeneration = number
export type TeamOperation = {
manageMembers: boolean
manageSubteams: boolean
createChannel: boolean
chat: boolean
deleteChannel: boolean
renameChannel: boolean
renameTeam: boolean
editChannelDescription: boolean
editTeamDescription: boolean
setTeamShowcase: boolean
setMemberShowcase: boolean
setRetentionPolicy: boolean
setMinWriterRole: boolean
changeOpenTeam: boolean
leaveTeam: boolean
joinTeam: boolean
setPublicityAny: boolean
listFirst: boolean
changeTarsDisabled: boolean
deleteChatHistory: boolean
deleteOtherEmojis: boolean
deleteOtherMessages: boolean
deleteTeam: boolean
pinMessage: boolean
manageBots: boolean
manageEmojis: boolean
}
export type ProfileTeamLoadRes = {
loadTimeNsec: number
}
export enum RotationType {
VISIBLE = 'visible',
HIDDEN = 'hidden',
CLKR = 'clkr',
}
export type MemberEmail = {
email: string
role: string
}
export type MemberUsername = {
username: string
role: string
}
export type UserTeamVersion = number
export enum TeamTreeMembershipStatus {
OK = 'ok',
ERROR = 'error',
HIDDEN = 'hidden',
}
export type TeamTreeError = {
message: string
willSkipSubtree: boolean
willSkipAncestors: boolean
}
export type TeamTreeInitial = {
guid: number
}
/**
* Result from calling test(..).
*/
export type Test = {
reply: string
}
export enum TLFIdentifyBehavior {
UNSET = 'unset',
CHAT_CLI = 'chat_cli',
CHAT_GUI = 'chat_gui',
REMOVED_AND_UNUSED = 'removed_and_unused',
KBFS_REKEY = 'kbfs_rekey',
KBFS_QR = 'kbfs_qr',
CHAT_SKIP = 'chat_skip',
SALTPACK = 'saltpack',
CLI = 'cli',
GUI = 'gui',
DEFAULT_KBFS = 'default_kbfs',
KBFS_CHAT = 'kbfs_chat',
RESOLVE_AND_CHECK = 'resolve_and_check',
GUI_PROFILE = 'gui_profile',
KBFS_INIT = 'kbfs_init',
FS_GUI = 'fs_gui',
}
export type CanonicalTlfName = string
export enum PromptDefault {
NONE = 'none',
YES = 'yes',
NO = 'no',
}
export enum KeyType {
NONE = 'none',
NACL = 'nacl',
PGP = 'pgp',
}
export enum UPK2MinorVersion {
V0 = 'v0',
V1 = 'v1',
V2 = 'v2',
V3 = 'v3',
V4 = 'v4',
V5 = 'v5',
V6 = 'v6',
}
export type PGPFingerprint = string | null
export enum UPAKVersion {
V1 = 'v1',
V2 = 'v2',
}
export enum UPKLiteMinorVersion {
V0 = 'v0',
}
export type TrackProof = {
proofType: string
proofName: string
idString: string
}
export type WebProof = {
hostname: string
protocols: string[] | null
}
export type EmailAddress = string
/**
* PassphraseState values are used in .config.json, so should not be changed without a migration strategy
*/
export enum PassphraseState {
KNOWN = 'known',
RANDOM = 'random',
}
export enum UserBlockType {
CHAT = 'chat',
FOLLOW = 'follow',
}
export type UserBlockArg = {
username: string
setChatBlock?: boolean
setFollowBlock?: boolean
}
export type APIUserServiceID = string
export type ImpTofuSearchResult = {
assertion: string
assertionValue: string
assertionKey: string
label: string
prettyName: string
keybaseUsername: string
}
export type EmailOrPhoneNumberSearchResult = {
input: string
assertion: string
assertionValue: string
assertionKey: string
foundUser: boolean
username: string
fullName: string
}
export type UsernameVerificationType = string
export enum WotReactionType {
ACCEPT = 'accept',
REJECT = 'reject',
}
export type LockdownHistory = {
status: boolean
ctime: Time
deviceId: DeviceID
deviceName: string
}
export type TeamContactSettings = {
teamId: TeamID
enabled: boolean
}
export type AirdropDetails = {
uid: UID
kid: BinaryKID
vid: VID
vers: string
time: Time
}
export type BoxAuditAttempt = {
ctime: UnixTime
error?: string
result: BoxAuditAttemptResult
generation?: PerTeamKeyGeneration
rotated: boolean
}
export type LoadAvatarsRes = {
picmap: {[key: string]: {[key: string]: AvatarUrl}}
}
export type AvatarClearCacheMsg = {
name: string
formats: AvatarFormat[] | null
typ: AvatarUpdateType
}
export type BlockIdCombo = {
blockHash: string
chargedTo: UserOrTeamID
blockType: BlockType
}
export type GetBlockRes = {
blockKey: string
buf: Buffer
size: number
status: BlockStatus
}
export type GetBlockSizesRes = {
sizes: number[] | null
statuses: BlockStatus[] | null
}
export type UsageStat = {
bytes: UsageStatRecord
blocks: UsageStatRecord
mtime: Time
}
export type BotTokenInfo = {
botToken: BotToken
ctime: Time
}
export type Status = {
code: number
name: string
desc: string
fields: StringKVPair[] | null
}
export type UserVersion = {
uid: UID
eldestSeqno: Seqno
}
export type CompatibilityTeamID =
| {typ: TeamType.LEGACY; LEGACY: TLFID}
| {typ: TeamType.MODERN; MODERN: TeamID}
| {typ: Exclude<TeamType, TeamType.LEGACY | TeamType.MODERN>}
export type TeamIDWithVisibility = {
teamId: TeamID
visibility: TLFVisibility
}
export type PublicKey = {
kid: KID
pgpFingerprint: string
pgpIdentities: PGPIdentity[] | null
isSibkey: boolean
isEldest: boolean
parentId: string
deviceId: DeviceID
deviceDescription: string
deviceType: DeviceTypeV2
cTime: Time
eTime: Time
isRevoked: boolean
}
export type KeybaseTime = {
unix: Time
chain: Seqno
}
export type User = {
uid: UID
username: string
}
export type Device = {
type: DeviceTypeV2
name: string
deviceId: DeviceID
deviceNumberOfType: number
cTime: Time
mTime: Time
lastUsedTime: Time
encryptKey: KID
verifyKey: KID
status: number
}
export type UserVersionVector = {
id: number
sigHints: number
sigChain: number
cachedAt: Time
}
export type PerUserKey = {
gen: number
seqno: Seqno
sigKid: KID
encKid: KID
signedByKid: KID
}
export type UserOrTeamLite = {
id: UserOrTeamID
name: string
}
export type RemoteTrack = {
username: string
uid: UID
linkId: LinkID
}
/**
* SocialAssertion contains a service and username for that service, that
* together form an assertion about a user. It can either be a social
* assertion (like "facebook" or "twitter") or a server trust assertion (like
* "phone" or "email").
*
* If the assertion is for social network, resolving an assertion requires
* that the user posts a Keybase proof on the asserted service as the asserted
* user.
*
* For server trust assertion, we have to trust the server.
*/
export type SocialAssertion = {
user: string
service: SocialAssertionService
}
export type FullNamePackage = {
version: FullNamePackageVersion
fullName: FullName
eldestSeqno: Seqno
status: StatusCode
cachedAt: Time
}
export type PhoneLookupResult = {
uid: UID
username: string
ctime: UnixTime
}
export type UserReacjis = {
topReacjis: UserReacji[] | null
skinTone: ReacjiSkinTone
}
export type ClientDetails = {
pid: number
clientType: ClientType
argv: string[] | null
desc: string
version: string
}
export type Config = {
serverUri: string
socketFile: string
label: string
runMode: string
gpgExists: boolean
gpgPath: string
version: string
path: string
binaryRealpath: string
configPath: string
versionShort: string
versionFull: string
isAutoForked: boolean
forkType: ForkType
}
export type UpdateInfo = {
status: UpdateInfoStatus
message: string
}
export type UpdateInfo2 =
| {status: UpdateInfoStatus2.OK}
| {status: UpdateInfoStatus2.SUGGESTED; SUGGESTED: UpdateDetails}
| {status: UpdateInfoStatus2.CRITICAL; CRITICAL: UpdateDetails}
| {status: Exclude<UpdateInfoStatus2, UpdateInfoStatus2.OK | UpdateInfoStatus2.SUGGESTED | UpdateInfoStatus2.CRITICAL>}
export type ProxyData = {
addressWithPort: string
proxyType: ProxyType
certPinning: boolean
}
export type ContactComponent = {
label: string
phoneNumber?: RawPhoneNumber
email?: EmailAddress
}
export type ED25519SignatureInfo = {
sig: ED25519Signature
publicKey: ED25519PublicKey
}
export type CiphertextBundle = {
kid: KID
ciphertext: EncryptedBytes32
nonce: BoxNonce
publicKey: BoxPublicKey
}
export type UnboxAnyRes = {
kid: KID
plaintext: Bytes32
index: number
}
export type DbKey = {
dbType: DbType
objType: number
key: string
}
export type EmailLookupResult = {
email: EmailAddress
uid?: UID
}
export type EmailAddressVerifiedMsg = {
email: EmailAddress
}
export type EmailAddressChangedMsg = {
email: EmailAddress
}
export type DeviceEkMetadata = {
deviceEphemeralDhPublic: KID
hashMeta: HashMeta
generation: EkGeneration
ctime: Time
deviceCtime: Time
}
export type UserEkMetadata = {
userEphemeralDhPublic: KID
hashMeta: HashMeta
generation: EkGeneration
ctime: Time
}
export type UserEkBoxMetadata = {
box: string
recipientGeneration: EkGeneration
recipientDeviceId: DeviceID
}
export type TeamEkMetadata = {
teamEphemeralDhPublic: KID
hashMeta: HashMeta
generation: EkGeneration
ctime: Time
}
export type TeamEkBoxMetadata = {
box: string
recipientGeneration: EkGeneration
recipientUid: UID
}
export type TeambotEkMetadata = {
teambotDhPublic: KID
generation: EkGeneration
uid: UID
userEkGeneration: EkGeneration
hashMeta: HashMeta
ctime: Time
}
export type FolderHandle = {
name: string
folderType: FolderType
created: boolean
}
export type FeaturedBotsRes = {
bots: FeaturedBot[] | null
isLastPage: boolean
}
export type SearchRes = {
bots: FeaturedBot[] | null
isLastPage: boolean
}
export type ListResult = {
files: File[] | null
}
export type EncryptedGitMetadata = {
v: number
e: Buffer
n: BoxNonce
gen: PerTeamKeyGeneration
}
export type GitLocalMetadataV1 = {
repoName: GitRepoName
}
export type GitCommit = {
commitHash: string
message: string
authorName: string
authorEmail: string
ctime: Time
}
export type GitServerMetadata = {
ctime: Time
mtime: Time
lastModifyingUsername: string
lastModifyingDeviceId: DeviceID
lastModifyingDeviceName: string
}
export type GPGKey = {
algorithm: string
keyId: string
creation: string
expiration: string
identities: PGPIdentity[] | null
}
export type HomeScreenAnnouncement = {
id: HomeScreenAnnouncementID
version: HomeScreenAnnouncementVersion
appLink: AppLinkType
confirmLabel: string
dismissable: boolean
iconUrl: string
text: string
url: string
}
/**
* Most of TODO items do not carry additional data, but some do. e.g. TODO
* item to tell user to verify their email address will carry that email
* address.
*
* All new TODO data bundle types should be records rather than single fields
* to support adding new data to existing TODOs. If a legacy TODO (such as
* VERIFY_ALL_EMAIL) uses a single field, the "TodoExt" field should be used to
* introduce more data to the payload.
*/
export type HomeScreenTodo =
| {t: HomeScreenTodoType.VERIFY_ALL_PHONE_NUMBER; VERIFY_ALL_PHONE_NUMBER: PhoneNumber}
| {t: HomeScreenTodoType.VERIFY_ALL_EMAIL; VERIFY_ALL_EMAIL: EmailAddress}
| {t: HomeScreenTodoType.LEGACY_EMAIL_VISIBILITY; LEGACY_EMAIL_VISIBILITY: EmailAddress}
| {
t: Exclude<
HomeScreenTodoType,
HomeScreenTodoType.VERIFY_ALL_PHONE_NUMBER | HomeScreenTodoType.VERIFY_ALL_EMAIL | HomeScreenTodoType.LEGACY_EMAIL_VISIBILITY
>
}
export type VerifyAllEmailTodoExt = {
lastVerifyEmailDate: UnixTime
}
export type HomeScreenPeopleNotificationContact = {
resolveTime: Time
username: string
description: string
resolvedContactBlob: string
}
export type HomeUserSummary = {
uid: UID
username: string
bio: string
fullName: string
pics?: Pics
}
export type Identify3RowMeta = {
color: Identify3RowColor
label: string
}
export type Identify3Summary = {
guiId: Identify3GUIID
numProofsToCheck: number
}
export type TrackDiff = {
type: TrackDiffType
displayMarkup: string
}
export type TrackSummary = {
username: string
time: Time
isRemote: boolean
}
export type TrackOptions = {
localOnly: boolean
bypassConfirm: boolean
forceRetrack: boolean
expiringLocal: boolean
forPgpPull: boolean
sigVersion?: SigVersion
}
export type IdentifyReason = {
type: IdentifyReasonType
reason: string
resource: string
}
export type RemoteProof = {
proofType: ProofType
key: string
value: string
displayMarkup: string
sigId: SigID
mTime: Time
}
export type ProofResult = {
state: ProofState
status: ProofStatus
desc: string
}
export type Cryptocurrency = {
rowId: number
pkhash: Buffer
address: string
sigId: SigID
type: string
family: string
}
export type StellarAccount = {
accountId: string
federationAddress: string
sigId: SigID
hidden: boolean
}
export type UserTeamShowcase = {
fqName: string
open: boolean
teamIsShowcased: boolean
description: string
role: TeamRole
publicAdmins: string[] | null
numMembers: number
}
export type DismissReason = {
type: DismissReasonType
reason: string
resource: string
}
export type IncomingShareItem = {
type: IncomingShareType
originalPath: string
originalSize: number
scaledPath?: string
scaledSize?: number
thumbnailPath?: string
content?: string
}
export type KBFSTeamSettings = {
tlfId: TLFID
}
export type FSNotification = {
filename: string
status: string
statusCode: FSStatusCode
notificationType: FSNotificationType
errorType: FSErrorType
params: {[key: string]: string}
writerUid: UID
localTime: Time
folderType: FolderType
}
export type FSFolderWriterEdit = {
filename: string
notificationType: FSNotificationType
serverTime: Time
}
export type FSPathSyncStatus = {
folderType: FolderType
path: string
syncingBytes: number
syncingOps: number
syncedBytes: number
}
export type FSSyncStatus = {
totalSyncingBytes: number
syncingPaths: string[] | null
endEstimate?: Time
}
export type GcOptions = {
maxLooseRefs: number
pruneMinLooseObjects: number
pruneExpireTime: Time
maxObjectPacks: number
}
export type Hello2Res = {
encryptionKey: KID
sigPayload: HelloRes
deviceEkKid: KID
}
export type PerUserKeyBox = {
generation: PerUserKeyGeneration
box: string
receiverKid: KID
}
export type KVEntryID = {
teamId: TeamID
namespace: string
entryKey: string
}
export type KVListEntryResult = {
teamName: string
namespace: string
entryKeys: KVListEntryKey[] | null
}
export type ConfiguredAccount = {
username: string
fullname: FullName
hasStoredSecret: boolean
isCurrent: boolean
}
export type ResetPrompt = {t: ResetPromptType.COMPLETE; COMPLETE: ResetPromptInfo} | {t: Exclude<ResetPromptType, ResetPromptType.COMPLETE>}
export type KBFSRoot = {
treeId: MerkleTreeID
root: KBFSRootHash
}
export type MerkleStoreEntry = {
hash: MerkleStoreKitHash
entry: MerkleStoreEntryString
}
export type KeyHalf = {
user: UID
deviceKid: KID
key: Buffer
}
export type MDBlock = {
version: number
timestamp: Time
block: Buffer
}
export type PingResponse = {
timestamp: Time
}
export type KeyBundleResponse = {
writerBundle: KeyBundle
readerBundle: KeyBundle
}
export type LockContext = {
requireLockId: LockID
releaseAfterSuccess: boolean
}
export type FindNextMDResponse = {
kbfsRoot: MerkleRoot
merkleNodes: Buffer[] | null
rootSeqno: Seqno
rootHash: HashMeta
}
export type InstrumentationStat = {
tag: string
numCalls: number
ctime: Time
mtime: Time
avgDur: DurationMsec
maxDur: DurationMsec
minDur: DurationMsec
totalDur: DurationMsec
avgSize: number
maxSize: number
minSize: number
totalSize: number
}
export type TeamMemberOutReset = {
teamId: TeamID
teamname: string
username: string
uid: UID
id: gregor1.MsgID
}
export type ResetState = {
endTime: Time
active: boolean
}
export type WotUpdate = {
voucher: string
vouchee: string
status: WotStatusType
}
export type BadgeConversationInfo = {
convId: ChatConversationID
badgeCount: number
unreadMessages: number
}
export type DbStats = {
type: DbType
memCompActive: boolean
tableCompActive: boolean
}
export type ProcessRuntimeStats = {
type: ProcessType
cpu: string
resident: string
virt: string
free: string
goheap: string
goheapsys: string
goreleased: string
cpuSeverity: StatsSeverityLevel
residentSeverity: StatsSeverityLevel
}
export type PerfEvent = {
message: string
ctime: Time
eventType: PerfEventType
}
export type GUIEntryFeatures = {
showTyping: Feature
}
export type PGPSignOptions = {
keyQuery: string
mode: SignMode
binaryIn: boolean
binaryOut: boolean
}
export type PGPCreateUids = {
useDefault: boolean
ids: PGPIdentity[] | null
}
/**
* Phone number support for TOFU chats.
*/
export type UserPhoneNumber = {
phoneNumber: PhoneNumber
verified: boolean
superseded: boolean
visibility: IdentityVisibility
ctime: UnixTime
}
export type PhoneNumberLookupResult = {
phoneNumber: RawPhoneNumber
coercedPhoneNumber: PhoneNumber
err?: string
uid?: UID
}
export type PhoneNumberChangedMsg = {
phone: PhoneNumber
}
export type FileDescriptor = {
name: string
type: FileType
}
export type CheckProofStatus = {
found: boolean
status: ProofStatus
proofText: string
state: ProofState
}
export type StartProofResult = {
sigId: SigID
}
export type ParamProofJSON = {
sigHash: SigID
kbUsername: string
}
export type ParamProofServiceConfig = {
version: number
domain: string
displayName: string
description: string
username: ParamProofUsernameConfig
brandColor: string
prefillUrl: string
profileUrl: string
checkUrl: string
checkPath: SelectorEntry[] | null
avatarPath: SelectorEntry[] | null
}
export type ProveParameters = {
logoFull: SizedImage[] | null
logoBlack: SizedImage[] | null
logoWhite: SizedImage[] | null
title: string
subtext: string
suffix: string
buttonLabel: string
}
export type VerifySessionRes = {
uid: UID
sid: string
generated: number
lifetime: number
}
export type Reachability = {
reachable: Reachable
}
export type TLF = {
id: TLFID
name: string
writers: string[] | null
readers: string[] | null
isPrivate: boolean
}
export type RekeyEvent = {
eventType: RekeyEventType
interruptType: number
}
export type ResetMerkleRoot = {
hashMeta: HashMeta
seqno: Seqno
}
export type ResetPrev = {
eldestKid?: KID
publicSeqno: Seqno
reset: SHA512
}
export type SaltpackEncryptOptions = {
recipients: string[] | null
teamRecipients: string[] | null
authenticityType: AuthenticityType
useEntityKeys: boolean
useDeviceKeys: boolean
usePaperKeys: boolean
noSelfEncrypt: boolean
binary: boolean
saltpackVersion: number
noForcePoll: boolean
useKbfsKeysOnlyForTesting: boolean
}
export type SaltpackSender = {
uid: UID
username: string
fullname: string
senderType: SaltpackSenderType
}
export type SecretKeys = {
signing: NaclSigningKeyPrivate
encryption: NaclDHKeyPrivate
}
export type Session = {
uid: UID
username: string
token: string
deviceSubkeyKid: KID
deviceSibkeyKid: KID
}
export type Sig = {
seqno: Seqno
sigId: SigID
sigIdDisplay: string
type: string
cTime: Time
revoked: boolean
active: boolean
key: string
body: string
}
export type SigListArgs = {
sessionId: number
username: string
allKeys: boolean
types?: SigTypes
filterx: string
verbose: boolean
revoked: boolean
}
export type KBFSArchivedParam =
| {KBFSArchivedType: KBFSArchivedType.REVISION; REVISION: KBFSRevision}
| {KBFSArchivedType: KBFSArchivedType.TIME; TIME: Time}
| {KBFSArchivedType: KBFSArchivedType.TIME_STRING; TIME_STRING: string}
| {KBFSArchivedType: KBFSArchivedType.REL_TIME_STRING; REL_TIME_STRING: string}
| {
KBFSArchivedType: Exclude<
KBFSArchivedType,
KBFSArchivedType.REVISION | KBFSArchivedType.TIME | KBFSArchivedType.TIME_STRING | KBFSArchivedType.REL_TIME_STRING
>
}
export type KBFSPath = {
path: string
identifyBehavior?: TLFIdentifyBehavior
}
export type PrefetchProgress = {
start: Time
endEstimate: Time
bytesTotal: number
bytesFetched: number
}
export type FileContent = {
data: Buffer
progress: Progress
}
export type OpProgress = {
start: Time
endEstimate: Time
opType: AsyncOps
bytesTotal: number
bytesRead: number
bytesWritten: number
filesTotal: number
filesRead: number
filesWritten: number
}
export type FolderSyncConfig = {
mode: FolderSyncMode
paths: string[] | null
}
export type DownloadState = {
downloadId: string
progress: number
endEstimate: Time
localPath: string
error: string
done: boolean
canceled: boolean
}
export type GUIFileContext = {
viewType: GUIViewType
contentType: string
url: string
}
export type SimpleFSSearchResults = {
hits: SimpleFSSearchHit[] | null
nextResult: number
}
export type IndexProgressRecord = {
endEstimate: Time
bytesTotal: number
bytesSoFar: number
}
export type TeambotKeyMetadata = {
teambotDhPublic: KID
generation: TeambotKeyGeneration
uid: UID
pukGeneration: PerUserKeyGeneration
application: TeamApplication
}
export type PerTeamSeedCheck = {
version: PerTeamSeedCheckVersion
value: PerTeamSeedCheckValue
}
export type PerTeamSeedCheckPostImage = {
h: PerTeamSeedCheckValuePostImage
v: PerTeamSeedCheckVersion
}
export type TeamApplicationKey = {
application: TeamApplication
keyGeneration: PerTeamKeyGeneration
key: Bytes32
}
export type ReaderKeyMask = {
application: TeamApplication
generation: PerTeamKeyGeneration
mask: MaskB64
}
export type PerTeamKey = {
gen: PerTeamKeyGeneration
seqno: Seqno
sigKid: KID
encKid: KID
}
export type TeamMember = {
uid: UID
role: TeamRole
eldestSeqno: Seqno
status: TeamMemberStatus
botSettings?: TeamBotSettings
}
export type TeamMemberRole = {
uid: UID
username: string
fullName: FullName
role: TeamRole
}
export type TeamUsedInvite = {
inviteId: TeamInviteID
uv: UserVersionPercentForm
}
export type LinkTriple = {
seqno: Seqno
seqType: SeqType
linkId: LinkID
}
export type UpPointer = {
ourSeqno: Seqno
parentId: TeamID
parentSeqno: Seqno
deletion: boolean
}
export type DownPointer = {
id: TeamID
nameComponent: string
isDeleted: boolean
}
export type Signer = {
e: Seqno
k: KID
u: UID
}
export type Audit = {
time: Time
mms: Seqno
mcs: Seqno
mhs: Seqno
mmp: Seqno
}
export type Probe = {
i: number
t: Seqno
h: Seqno
}
export type TeamInviteType =
| {c: TeamInviteCategory.UNKNOWN; UNKNOWN: string}
| {c: TeamInviteCategory.SBS; SBS: TeamInviteSocialNetwork}
| {c: Exclude<TeamInviteCategory, TeamInviteCategory.UNKNOWN | TeamInviteCategory.SBS>}
export type TeamGetLegacyTLFUpgrade = {
encryptedKeyset: string
teamGeneration: PerTeamKeyGeneration
legacyGeneration: number
appType: TeamApplication
}
export type TeamLegacyTLFUpgradeChainInfo = {
keysetHash: TeamEncryptedKBFSKeysetHash
teamGeneration: PerTeamKeyGeneration
legacyGeneration: number
appType: TeamApplication
}
export type TeamNameLogPoint = {
lastPart: TeamNamePart
seqno: Seqno
}
export type TeamName = {
parts: TeamNamePart[] | null
}
export type TeamCLKRResetUser = {
uid: UID
userEldest: Seqno
memberEldest: Seqno
}
export type TeamResetUser = {
username: string
uid: UID
eldestSeqno: Seqno
isDelete: boolean
}
export type TeamChangeRow = {
id: TeamID
name: string
keyRotated: boolean
membershipChanged: boolean
latestSeqno: Seqno
latestHiddenSeqno: Seqno
latestOffchainVersion: Seqno
implicitTeam: boolean
misc: boolean
removedResetUsers: boolean
}
export type TeamExitRow = {
id: TeamID
}
export type TeamNewlyAddedRow = {
id: TeamID
name: string
}
export type TeamInvitee = {
inviteId: TeamInviteID
uid: UID
eldestSeqno: Seqno
role: TeamRole
}
export type TeamAccessRequest = {
uid: UID
eldestSeqno: Seqno
}
export type SeitanKeyLabel =
| {t: SeitanKeyLabelType.SMS; SMS: SeitanKeyLabelSms}
| {t: SeitanKeyLabelType.GENERIC; GENERIC: SeitanKeyLabelGeneric}
| {t: Exclude<SeitanKeyLabelType, SeitanKeyLabelType.SMS | SeitanKeyLabelType.GENERIC>}
export type TeamSeitanRequest = {
inviteId: TeamInviteID
uid: UID
eldestSeqno: Seqno
akey: SeitanAKey
role: TeamRole
ctime: number
}
export type TeamKBFSKeyRefresher = {
generation: number
appType: TeamApplication
}
export type ImplicitRole = {
role: TeamRole
ancestor: TeamID
}
export type TeamJoinRequest = {
name: string
username: string
fullName: FullName
ctime: UnixTime
}
export type TeamCreateResult = {
teamId: TeamID
chatSent: boolean
creatorAdded: boolean
}
export type TeamSettings = {
open: boolean
joinAs: TeamRole
}
export type TeamShowcase = {
isShowcased: boolean
description?: string
setByUid?: UID
anyMemberShowcase: boolean
}
export type UserRolePair = {
assertion: string
role: TeamRole
botSettings?: TeamBotSettings
}
export type TeamMemberToRemove = {
username: string
email: string
inviteId: TeamInviteID
allowInaction: boolean
}
export type UntrustedTeamExistsResult = {
exists: boolean
status: StatusCode
}
export type Invitelink = {
ikey: SeitanIKeyInvitelink
url: string
}
export type ImplicitTeamConflictInfo = {
generation: ConflictGeneration
time: Time
}
export type TeamRolePair = {
role: TeamRole
implicitRole: TeamRole
}
export type UserTeamVersionUpdate = {
version: UserTeamVersion
}
export type TeamTreeMembershipValue = {
role: TeamRole
joinTime?: Time
teamId: TeamID
}
export type TeamTreeMembershipsDoneResult = {
expectedCount: number
targetTeamId: TeamID
targetUsername: string
guid: number
}
export type TeamSearchItem = {
id: TeamID
name: string
description?: string
memberCount: number
lastActive: Time
isDemoted: boolean
inTeam: boolean
}
export type CryptKey = {
keyGeneration: number
key: Bytes32
}
export type TLFQuery = {
tlfName: string
identifyBehavior: TLFIdentifyBehavior
}
export type MerkleRootV2 = {
seqno: Seqno
hashMeta: HashMeta
}
export type SigChainLocation = {
seqno: Seqno
seqType: SeqType
}
export type UserSummary = {
uid: UID
username: string
fullName: string
linkId?: LinkID
}
export type Email = {
email: EmailAddress
isVerified: boolean
isPrimary: boolean
visibility: IdentityVisibility
lastVerifyEmailDate: UnixTime
}
export type InterestingPerson = {
uid: UID
username: string
fullname: string
serviceMap: {[key: string]: string}
}
export type CanLogoutRes = {
canLogout: boolean
reason: string
passphraseState: PassphraseState
}
export type UserPassphraseStateMsg = {
state: PassphraseState
}
export type UserBlockedRow = {
blockUid: UID
blockUsername: string
chat?: boolean
follow?: boolean
}
export type UserBlockState = {
blockType: UserBlockType
blocked: boolean
}
export type UserBlock = {
username: string
chatBlocked: boolean
followBlocked: boolean
createTime?: Time
modifyTime?: Time
}
export type TeamBlock = {
fqName: string
ctime: Time
}
export type APIUserKeybaseResult = {
username: string
uid: UID
pictureUrl?: string
fullName?: string
rawScore: number
stellar?: string
isFollowee: boolean
}
export type APIUserServiceResult = {
serviceName: APIUserServiceID
username: string
pictureUrl: string
bio: string
location: string
fullName: string
confirmed?: boolean
}
export type APIUserServiceSummary = {
serviceName: APIUserServiceID
username: string
}
export type WotProof = {
proofType: ProofType
nameOmitempty: string
usernameOmitempty: string
protocolOmitempty: string
hostnameOmitempty: string
domainOmitempty: string
}
export type GetLockdownResponse = {
history: LockdownHistory[] | null
status: boolean
}
export type ContactSettings = {
version?: number
allowFolloweeDegrees: number
allowGoodTeams: boolean
enabled: boolean
teams: TeamContactSettings[] | null
}
export type BlockReference = {
bid: BlockIdCombo
nonce: BlockRefNonce
chargedTo: UserOrTeamID
}
export type BlockIdCount = {
id: BlockIdCombo
liveCount: number
}
export type FolderUsageStat = {
folderId: string
stats: UsageStat
}
export type TeamIDAndName = {
id: TeamID
name: TeamName
}
export type RevokedKey = {
key: PublicKey
time: KeybaseTime
by: KID
}
export type CurrentStatus = {
configured: boolean
registered: boolean
loggedIn: boolean
sessionIsValid: boolean
user?: User
deviceName: string
}
export type ClientStatus = {
details: ClientDetails
connectionId: number
notificationChannels: NotificationChannels
}
export type BootstrapStatus = {
registered: boolean
loggedIn: boolean
uid: UID
username: string
deviceId: DeviceID
deviceName: string
fullname: FullName
userReacjis: UserReacjis
httpSrvInfo?: HttpSrvInfo
}
export type Contact = {
name: string
components: ContactComponent[] | null
}
export type ProcessedContact = {
contactIndex: number
contactName: string
component: ContactComponent
resolved: boolean
uid: UID
username: string
fullName: string
following: boolean
serviceMap: {[key: string]: string}
assertion: string
displayName: string
displayLabel: string
}
export type DeviceDetail = {
device: Device
eldest: boolean
provisioner?: Device
provisionedAt?: Time
revokedAt?: Time
revokedBy: KID
revokedByDevice?: Device
currentDevice: boolean
}
export type DeviceEkStatement = {
currentDeviceEkMetadata: DeviceEkMetadata
}
export type DeviceEk = {
seed: Bytes32
metadata: DeviceEkMetadata
}
export type UserEkStatement = {
currentUserEkMetadata: UserEkMetadata
}
export type UserEkBoxed = {
box: string
deviceEkGeneration: EkGeneration
metadata: UserEkMetadata
}
export type UserEk = {
seed: Bytes32
metadata: UserEkMetadata
}
export type UserEkReboxArg = {
userEkBoxMetadata: UserEkBoxMetadata
deviceId: DeviceID
deviceEkStatementSig: string
}
export type TeamEkStatement = {
currentTeamEkMetadata: TeamEkMetadata
}
export type TeamEkBoxed = {
box: string
userEkGeneration: EkGeneration
metadata: TeamEkMetadata
}
export type TeamEk = {
seed: Bytes32
metadata: TeamEkMetadata
}
export type TeambotEkBoxed = {
box: string
metadata: TeambotEkMetadata
}
export type TeambotEk = {
seed: Bytes32
metadata: TeambotEkMetadata
}
export type GitLocalMetadataVersioned =
| {version: GitLocalMetadataVersion.V1; V1: GitLocalMetadataV1}
| {version: Exclude<GitLocalMetadataVersion, GitLocalMetadataVersion.V1>}
export type GitRefMetadata = {
refName: string
commits: GitCommit[] | null
moreCommitsAvailable: boolean
isDelete: boolean
}
export type HomeScreenTodoExt =
| {t: HomeScreenTodoType.VERIFY_ALL_EMAIL; VERIFY_ALL_EMAIL: VerifyAllEmailTodoExt}
| {t: Exclude<HomeScreenTodoType, HomeScreenTodoType.VERIFY_ALL_EMAIL>}
export type HomeScreenPeopleNotificationFollowed = {
followTime: Time
followedBack: boolean
user: UserSummary
}
export type HomeScreenPeopleNotificationContactMulti = {
contacts: HomeScreenPeopleNotificationContact[] | null
numOthers: number
}
export type Identify3Row = {
guiId: Identify3GUIID
key: string
value: string
priority: number
siteUrl: string
siteIcon: SizedImage[] | null
siteIconDarkmode: SizedImage[] | null
siteIconFull: SizedImage[] | null
siteIconFullDarkmode: SizedImage[] | null
proofUrl: string
sigId: SigID
ctime: Time
state: Identify3RowState
metas: Identify3RowMeta[] | null
color: Identify3RowColor
kid?: KID
}
export type IdentifyOutcome = {
username: string
status?: Status
warnings: string[] | null
trackUsed?: TrackSummary
trackStatus: TrackStatus
numTrackFailures: number
numTrackChanges: number
numProofFailures: number
numRevoked: number
numProofSuccesses: number
revoked: TrackDiff[] | null
trackOptions: TrackOptions
forPgpPull: boolean
reason: IdentifyReason
}
export type IdentifyRow = {
rowId: number
proof: RemoteProof
trackDiff?: TrackDiff
}
export type IdentifyKey = {
pgpFingerprint: Buffer
kid: KID
trackDiff?: TrackDiff
breaksTracking: boolean
sigId: SigID
}
export type RevokedProof = {
proof: RemoteProof
diff: TrackDiff
snoozed: boolean
}
export type CheckResult = {
proofResult: ProofResult
time: Time
freshness: CheckResultFreshness
}
export type UserCard = {
unverifiedNumFollowing: number
unverifiedNumFollowers: number
uid: UID
fullName: string
location: string
bio: string
bioDecorated: string
website: string
twitter: string
teamShowcase: UserTeamShowcase[] | null
registeredForAirdrop: boolean
stellarHidden: boolean
blocked: boolean
hidFromFollowers: boolean
}
export type ServiceStatus = {
version: string
label: string
pid: string
lastExitStatus: string
bundleVersion: string
installStatus: InstallStatus
installAction: InstallAction
status: Status
}
export type FuseStatus = {
version: string
bundleVersion: string
kextId: string
path: string
kextStarted: boolean
installStatus: InstallStatus
installAction: InstallAction
mountInfos: FuseMountInfo[] | null
status: Status
}
export type ComponentResult = {
name: string
status: Status
exitCode: number
}
export type FSFolderWriterEditHistory = {
writerName: string
edits: FSFolderWriterEdit[] | null
deletes: FSFolderWriterEdit[] | null
}
export type FolderSyncStatus = {
localDiskBytesAvailable: number
localDiskBytesTotal: number
prefetchStatus: PrefetchStatus
prefetchProgress: PrefetchProgress
storedBytesTotal: number
outOfSyncSpace: boolean
}
export type MerkleRootAndTime = {
root: MerkleRootV2
updateTime: Time
fetchTime: Time
}
export type MetadataResponse = {
folderId: string
mdBlocks: MDBlock[] | null
}
export type BadgeState = {
newTlfs: number
rekeysNeeded: number
newFollowers: number
inboxVers: number
homeTodoItems: number
unverifiedEmails: number
unverifiedPhones: number
smallTeamBadgeCount: number
bigTeamBadgeCount: number
newTeamAccessRequestCount: number
newDevices: DeviceID[] | null
revokedDevices: DeviceID[] | null
conversations: BadgeConversationInfo[] | null
newGitRepoGlobalUniqueIDs: string[] | null
newTeams: TeamID[] | null
deletedTeams: DeletedTeamInfo[] | null
teamsWithResetUsers: TeamMemberOutReset[] | null
unreadWalletAccounts: WalletAccountInfo[] | null
wotUpdates: {[key: string]: WotUpdate}
resetState: ResetState
}
export type RuntimeStats = {
processStats: ProcessRuntimeStats[] | null
dbStats: DbStats[] | null
perfEvents: PerfEvent[] | null
convLoaderActive: boolean
selectiveSyncActive: boolean
}
export type GUIEntryArg = {
windowTitle: string
prompt: string
username: string
submitLabel: string
cancelLabel: string
retryLabel: string
type: PassphraseType
features: GUIEntryFeatures
}
/**
* PGPSigVerification is returned by pgpDecrypt and pgpVerify with information
* about the signature verification. If isSigned is false, there was no
* signature, and the rest of the fields should be ignored.
*/
export type PGPSigVerification = {
isSigned: boolean
verified: boolean
signer: User
signKey: PublicKey
warnings: string[] | null
}
export type Process = {
pid: string
command: string
fileDescriptors: FileDescriptor[] | null
}
export type ExternalServiceConfig = {
schemaVersion: number
display?: ServiceDisplayConfig
config?: ParamProofServiceConfig
}
export type ProblemTLF = {
tlf: TLF
score: number
solutionKids: KID[] | null
}
export type RevokeWarning = {
endangeredTlFs: TLF[] | null
}
export type ResetLink = {
ctime: UnixTime
merkleRoot: ResetMerkleRoot
prev: ResetPrev
resetSeqno: Seqno
type: ResetType
uid: UID
}
export type ResetSummary = {
ctime: UnixTime
merkleRoot: ResetMerkleRoot
resetSeqno: Seqno
eldestSeqno: Seqno
type: ResetType
}
export type SaltpackEncryptedMessageInfo = {
devices: Device[] | null
numAnonReceivers: number
receiverIsAnon: boolean
sender: SaltpackSender
}
export type SaltpackVerifyResult = {
signingKid: KID
sender: SaltpackSender
plaintext: string
verified: boolean
}
export type SaltpackVerifyFileResult = {
signingKid: KID
sender: SaltpackSender
verifiedFilename: string
verified: boolean
}
export type KBFSArchivedPath = {
path: string
archivedParam: KBFSArchivedParam
identifyBehavior?: TLFIdentifyBehavior
}
export type Dirent = {
time: Time
size: number
name: string
direntType: DirentType
lastWriterUnverified: User
writable: boolean
prefetchStatus: PrefetchStatus
prefetchProgress: PrefetchProgress
symlinkTarget: string
}
export type SimpleFSStats = {
processStats: ProcessRuntimeStats
blockCacheDbStats: string[] | null
syncCacheDbStats: string[] | null
runtimeDbStats: DbStats[] | null
}
export type DownloadInfo = {
downloadId: string
path: KBFSPath
filename: string
startTime: Time
isRegularDownload: boolean
}
export type DownloadStatus = {
regularDownloadIDs: string[] | null
states: DownloadState[] | null
}
export type UploadState = {
uploadId: string
targetPath: KBFSPath
error?: string
canceled: boolean
}
export type TeambotKeyBoxed = {
box: string
metadata: TeambotKeyMetadata
}
export type TeambotKey = {
seed: Bytes32
metadata: TeambotKeyMetadata
}
export type PerTeamKeyAndCheck = {
ptk: PerTeamKey
check: PerTeamSeedCheckPostImage
}
export type PerTeamKeySeedItem = {
seed: PerTeamKeySeed
generation: PerTeamKeyGeneration
seqno: Seqno
check?: PerTeamSeedCheck
}
export type TeamMembers = {
owners: UserVersion[] | null
admins: UserVersion[] | null
writers: UserVersion[] | null
readers: UserVersion[] | null
bots: UserVersion[] | null
restrictedBots: UserVersion[] | null
}
export type TeamMemberDetails = {
uv: UserVersion
username: string
fullName: FullName
needsPuk: boolean
status: TeamMemberStatus
joinTime?: Time
}
export type UntrustedTeamInfo = {
name: TeamName
inTeam: boolean
open: boolean
description: string
publicAdmins: string[] | null
numMembers: number
publicMembers: TeamMemberRole[] | null
}
export type TeamChangeReq = {
owners: UserVersion[] | null
admins: UserVersion[] | null
writers: UserVersion[] | null
readers: UserVersion[] | null
bots: UserVersion[] | null
restrictedBots: {[key: string]: TeamBotSettings}
none: UserVersion[] | null
completedInvites: {[key: string]: UserVersionPercentForm}
usedInvites: TeamUsedInvite[] | null
}
export type TeamPlusApplicationKeys = {
id: TeamID
name: string
implicit: boolean
public: boolean
application: TeamApplication
writers: UserVersion[] | null
onlyReaders: UserVersion[] | null
onlyRestrictedBots: UserVersion[] | null
applicationKeys: TeamApplicationKey[] | null
}
export type LinkTripleAndTime = {
triple: LinkTriple
time: Time
}
export type FastTeamSigChainState = {
id: TeamID
public: boolean
rootAncestor: TeamName
nameDepth: number
last?: LinkTriple
perTeamKeys: {[key: string]: PerTeamKey}
perTeamKeySeedsVerified: {[key: string]: PerTeamKeySeed}
downPointers: {[key: string]: DownPointer}
lastUpPointer?: UpPointer
perTeamKeyCTime: UnixTime
linkIDs: {[key: string]: LinkID}
merkleInfo: {[key: string]: MerkleRootV2}
}
export type AuditHistory = {
id: TeamID
public: boolean
priorMerkleSeqno: Seqno
version: AuditVersion
audits: Audit[] | null
preProbes: {[key: string]: Probe}
postProbes: {[key: string]: Probe}
tails: {[key: string]: LinkID}
hiddenTails: {[key: string]: LinkID}
preProbesToRetry: Seqno[] | null
postProbesToRetry: Seqno[] | null
skipUntil: Time
}
export type TeamInvite = {
role: TeamRole
id: TeamInviteID
type: TeamInviteType
name: TeamInviteName
inviter: UserVersion
maxUses?: TeamInviteMaxUses
etime?: UnixTime
}
export type TeamUsedInviteLogPoint = {
uv: UserVersion
logPoint: number
}
export type SubteamLogPoint = {
name: TeamName
seqno: Seqno
}
export type TeamCLKRMsg = {
teamId: TeamID
generation: PerTeamKeyGeneration
score: number
resetUsers: TeamCLKRResetUser[] | null
}
export type TeamMemberOutFromReset = {
teamId: TeamID
teamName: string
resetUser: TeamResetUser
}
export type TeamSBSMsg = {
teamId: TeamID
score: number
invitees: TeamInvitee[] | null
}
export type TeamOpenReqMsg = {
teamId: TeamID
tars: TeamAccessRequest[] | null
}
export type SeitanKeyAndLabelVersion1 = {
i: SeitanIKey
l: SeitanKeyLabel
}
export type SeitanKeyAndLabelVersion2 = {
k: SeitanPubKey
l: SeitanKeyLabel
}
export type SeitanKeyAndLabelInvitelink = {
i: SeitanIKeyInvitelink
l: SeitanKeyLabel
}
export type TeamSeitanMsg = {
teamId: TeamID
seitans: TeamSeitanRequest[] | null
}
export type TeamOpenSweepMsg = {
teamId: TeamID
resetUsers: TeamCLKRResetUser[] | null
}
/**
* * TeamRefreshData are needed or wanted data requirements that, if unmet, will cause
* * a refresh of the cache.
*/
export type TeamRefreshers = {
needKeyGeneration: PerTeamKeyGeneration
needApplicationsAtGenerations: {[key: string]: TeamApplication[] | null}
needApplicationsAtGenerationsWithKbfs: {[key: string]: TeamApplication[] | null}
wantMembers: UserVersion[] | null
wantMembersRole: TeamRole
needKbfsKeyGeneration: TeamKBFSKeyRefresher
}
export type FastTeamLoadArg = {
id: TeamID
public: boolean
assertTeamName?: TeamName
applications: TeamApplication[] | null
keyGenerationsNeeded: PerTeamKeyGeneration[] | null
needLatestKey: boolean
forceRefresh: boolean
hiddenChainIsOptional: boolean
}
export type FastTeamLoadRes = {
name: TeamName
applicationKeys: TeamApplicationKey[] | null
}
export type MemberInfo = {
uid: UID
teamId: TeamID
fqName: string
isImplicitTeam: boolean
isOpenTeam: boolean
role: TeamRole
implicit?: ImplicitRole
memberCount: number
allowProfilePromote: boolean
isMemberShowcased: boolean
}
export type AnnotatedMemberInfo = {
uid: UID
teamId: TeamID
username: string
fullName: string
fqName: string
isImplicitTeam: boolean
implicitTeamDisplayName: string
isOpenTeam: boolean
role: TeamRole
implicit?: ImplicitRole
needsPuk: boolean
memberCount: number
memberEldestSeqno: Seqno
allowProfilePromote: boolean
isMemberShowcased: boolean
status: TeamMemberStatus
}
export type TeamAddMemberResult = {
invited: boolean
user?: User
chatSending: boolean
}
export type TeamAddMembersResult = {
notAdded: User[] | null
}
export type TeamTreeEntry = {
name: TeamName
admin: boolean
}
export type SubteamListEntry = {
name: TeamName
teamId: TeamID
memberCount: number
}
export type TeamAndMemberShowcase = {
teamShowcase: TeamShowcase
isMemberShowcased: boolean
}
export type TeamRemoveMembersResult = {
failures: TeamMemberToRemove[] | null
}
export type TeamEditMembersResult = {
failures: UserRolePair[] | null
}
export type InviteLinkDetails = {
inviteId: TeamInviteID
inviterUid: UID
inviterUsername: string
inviterResetOrDel: boolean
teamIsOpen: boolean
teamId: TeamID
teamDesc: string
teamName: TeamName
teamNumMembers: number
teamAvatars: {[key: string]: AvatarUrl}
}
export type ImplicitTeamUserSet = {
keybaseUsers: string[] | null
unresolvedUsers: SocialAssertion[] | null
}
export type TeamProfileAddEntry = {
teamId: TeamID
teamName: TeamName
open: boolean
disabledReason: string
}
export type TeamRoleMapAndVersion = {
teams: {[key: string]: TeamRolePair}
userTeamVersion: UserTeamVersion
}
export type TeamTreeMembershipResult =
| {s: TeamTreeMembershipStatus.OK; OK: TeamTreeMembershipValue}
| {s: TeamTreeMembershipStatus.ERROR; ERROR: TeamTreeError}
| {s: TeamTreeMembershipStatus.HIDDEN}
| {s: Exclude<TeamTreeMembershipStatus, TeamTreeMembershipStatus.OK | TeamTreeMembershipStatus.ERROR | TeamTreeMembershipStatus.HIDDEN>}
export type TeamSearchExport = {
items: {[key: string]: TeamSearchItem}
suggested: TeamID[] | null
}
export type TeamSearchRes = {
results: TeamSearchItem[] | null
}
export type MerkleTreeLocation = {
leaf: UserOrTeamID
loc: SigChainLocation
}
export type SignatureMetadata = {
signingKid: KID
prevMerkleRootSigned: MerkleRootV2
firstAppearedUnverified: Seqno
time: Time
sigChainLocation: SigChainLocation
}
export type Proofs = {
social: TrackProof[] | null
web: WebProof[] | null
publicKeys: PublicKey[] | null
}
export type UserSummarySet = {
users: UserSummary[] | null
time: Time
version: number
}
export type UserSettings = {
emails: Email[] | null
phoneNumbers: UserPhoneNumber[] | null
}
export type ProofSuggestion = {
key: string
belowFold: boolean
profileText: string
profileIcon: SizedImage[] | null
profileIconDarkmode: SizedImage[] | null
pickerText: string
pickerSubtext: string
pickerIcon: SizedImage[] | null
pickerIconDarkmode: SizedImage[] | null
metas: Identify3RowMeta[] | null
}
export type NextMerkleRootRes = {
res?: MerkleRootV2
}
export type UserBlockedBody = {
blocks: UserBlockedRow[] | null
blockerUid: UID
blockerUsername: string
}
export type UserBlockedSummary = {
blocker: string
blocks: {[key: string]: UserBlockState[] | null}
}
export type Confidence = {
usernameVerifiedViaOmitempty: UsernameVerificationType
proofsOmitempty: WotProof[] | null
otherOmitempty: string
}
export type BlockReferenceCount = {
ref: BlockReference
liveCount: number
}
export type ReferenceCountRes = {
counts: BlockIdCount[] | null
}
export type BlockQuotaInfo = {
folders: FolderUsageStat[] | null
total: UsageStat
limit: number
gitLimit: number
}
export type UserPlusKeys = {
uid: UID
username: string
eldestSeqno: Seqno
status: StatusCode
deviceKeys: PublicKey[] | null
revokedDeviceKeys: RevokedKey[] | null
pgpKeyCount: number
uvv: UserVersionVector
deletedDeviceKeys: PublicKey[] | null
perUserKeys: PerUserKey[] | null
resets: ResetSummary[] | null
}
export type ExtendedStatus = {
standalone: boolean
passphraseStreamCached: boolean
tsecCached: boolean
deviceSigKeyCached: boolean
deviceEncKeyCached: boolean
paperSigKeyCached: boolean
paperEncKeyCached: boolean
storedSecret: boolean
secretPromptSkip: boolean
rememberPassphrase: boolean
device?: Device
deviceErr?: LoadDeviceErr
logDir: string
session?: SessionStatus
defaultUsername: string
provisionedUsernames: string[] | null
configuredAccounts: ConfiguredAccount[] | null
clients: ClientStatus[] | null
deviceEkNames: string[] | null
platformInfo: PlatformInfo
defaultDeviceId: DeviceID
localDbStats: string[] | null
localChatDbStats: string[] | null
localBlockCacheDbStats: string[] | null
localSyncCacheDbStats: string[] | null
cacheDirSizeInfo: DirSizeInfo[] | null
uiRouterMapping: {[key: string]: number}
}
export type ContactListResolutionResult = {
newlyResolved: ProcessedContact[] | null
resolved: ProcessedContact[] | null
}
export type TeamEphemeralKey =
| {keyType: TeamEphemeralKeyType.TEAM; TEAM: TeamEk}
| {keyType: TeamEphemeralKeyType.TEAMBOT; TEAMBOT: TeambotEk}
| {keyType: Exclude<TeamEphemeralKeyType, TeamEphemeralKeyType.TEAM | TeamEphemeralKeyType.TEAMBOT>}
export type TeamEphemeralKeyBoxed =
| {keyType: TeamEphemeralKeyType.TEAM; TEAM: TeamEkBoxed}
| {keyType: TeamEphemeralKeyType.TEAMBOT; TEAMBOT: TeambotEkBoxed}
| {keyType: Exclude<TeamEphemeralKeyType, TeamEphemeralKeyType.TEAM | TeamEphemeralKeyType.TEAMBOT>}
export type GitLocalMetadata = {
repoName: GitRepoName
refs: GitRefMetadata[] | null
pushType: GitPushType
previousRepoName: GitRepoName
}
export type HomeScreenItemDataExt =
| {t: HomeScreenItemType.TODO; TODO: HomeScreenTodoExt}
| {t: Exclude<HomeScreenItemType, HomeScreenItemType.TODO>}
export type HomeScreenPeopleNotificationFollowedMulti = {
followers: HomeScreenPeopleNotificationFollowed[] | null
numOthers: number
}
export type Identity = {
status?: Status
whenLastTracked: Time
proofs: IdentifyRow[] | null
cryptocurrency: Cryptocurrency[] | null
revoked: TrackDiff[] | null
revokedDetails: RevokedProof[] | null
breaksTracking: boolean
}
export type LinkCheckResult = {
proofId: number
proofResult: ProofResult
snoozedResult: ProofResult
torWarning: boolean
tmpTrackExpireTime: Time
cached?: CheckResult
diff?: TrackDiff
remoteDiff?: TrackDiff
hint?: SigHint
breaksTracking: boolean
}
export type ServicesStatus = {
service: ServiceStatus[] | null
kbfs: ServiceStatus[] | null
updater: ServiceStatus[] | null
}
export type InstallResult = {
componentResults: ComponentResult[] | null
status: Status
fatal: boolean
}
export type UninstallResult = {
componentResults: ComponentResult[] | null
status: Status
}
/**
* ProblemSet is for a particular (user,kid) that initiated a rekey problem.
* This problem consists of one or more problem TLFs, which are individually scored
* and have attendant solutions --- devices that if they came online can rekey and
* solve the ProblemTLF.
*/
export type ProblemSet = {
user: User
kid: KID
tlfs: ProblemTLF[] | null
}
export type SaltpackPlaintextResult = {
info: SaltpackEncryptedMessageInfo
plaintext: string
signed: boolean
}
export type SaltpackFileResult = {
info: SaltpackEncryptedMessageInfo
decryptedFilename: string
signed: boolean
}
export type Path =
| {PathType: PathType.LOCAL; LOCAL: string}
| {PathType: PathType.KBFS; KBFS: KBFSPath}
| {PathType: PathType.KBFS_ARCHIVED; KBFS_ARCHIVED: KBFSArchivedPath}
| {PathType: Exclude<PathType, PathType.LOCAL | PathType.KBFS | PathType.KBFS_ARCHIVED>}
export type DirentWithRevision = {
entry: Dirent
revision: KBFSRevision
}
export type SimpleFSListResult = {
entries: Dirent[] | null
progress: Progress
}
export type FolderSyncConfigAndStatus = {
config: FolderSyncConfig
status: FolderSyncStatus
}
export type TeamMembersDetails = {
owners: TeamMemberDetails[] | null
admins: TeamMemberDetails[] | null
writers: TeamMemberDetails[] | null
readers: TeamMemberDetails[] | null
bots: TeamMemberDetails[] | null
restrictedBots: TeamMemberDetails[] | null
}
export type FastTeamData = {
frozen: boolean
subversion: number
tombstoned: boolean
name: TeamName
chain: FastTeamSigChainState
perTeamKeySeedsUnverified: {[key: string]: PerTeamKeySeed}
maxContinuousPtkGeneration: PerTeamKeyGeneration
seedChecks: {[key: string]: PerTeamSeedCheck}
latestKeyGeneration: PerTeamKeyGeneration
readerKeyMasks: {[key: string]: {[key: string]: MaskB64}}
latestSeqnoHint: Seqno
cachedAt: Time
loadedLatest: boolean
}
export type HiddenTeamChainRatchetSet = {
ratchets: {[key: string]: LinkTripleAndTime}
}
export type HiddenTeamChainLink = {
m: MerkleRootV2
p: LinkTriple
s: Signer
k: {[key: string]: PerTeamKeyAndCheck}
}
export type UserLogPoint = {
role: TeamRole
sigMeta: SignatureMetadata
}
export type AnnotatedTeamUsedInviteLogPoint = {
username: string
teamUsedInviteLogPoint: TeamUsedInviteLogPoint
}
export type SeitanKeyAndLabel =
| {v: SeitanKeyAndLabelVersion.V1; V1: SeitanKeyAndLabelVersion1}
| {v: SeitanKeyAndLabelVersion.V2; V2: SeitanKeyAndLabelVersion2}
| {v: SeitanKeyAndLabelVersion.Invitelink; Invitelink: SeitanKeyAndLabelInvitelink}
| {v: Exclude<SeitanKeyAndLabelVersion, SeitanKeyAndLabelVersion.V1 | SeitanKeyAndLabelVersion.V2 | SeitanKeyAndLabelVersion.Invitelink>}
export type LoadTeamArg = {
id: TeamID
name: string
public: boolean
needAdmin: boolean
refreshUidMapper: boolean
refreshers: TeamRefreshers
forceFullReload: boolean
forceRepoll: boolean
staleOk: boolean
allowNameLookupBurstCache: boolean
skipNeedHiddenRotateCheck: boolean
auditMode: AuditMode
}
export type TeamList = {
teams: MemberInfo[] | null
}
export type TeamTreeResult = {
entries: TeamTreeEntry[] | null
}
export type SubteamListResult = {
entries: SubteamListEntry[] | null
}
/**
* * iTeams
*/
export type ImplicitTeamDisplayName = {
isPublic: boolean
writers: ImplicitTeamUserSet
readers: ImplicitTeamUserSet
conflictInfo?: ImplicitTeamConflictInfo
}
export type TeamRoleMapStored = {
data: TeamRoleMapAndVersion
cachedAt: Time
}
export type AnnotatedTeamMemberDetails = {
details: TeamMemberDetails
role: TeamRole
}
export type TeamTreeMembership = {
teamName: string
result: TeamTreeMembershipResult
targetTeamId: TeamID
targetUsername: string
guid: number
}
export type PublicKeyV2Base = {
kid: KID
isSibkey: boolean
isEldest: boolean
cTime: Time
eTime: Time
provisioning: SignatureMetadata
revocation?: SignatureMetadata
}
export type ProofSuggestionsRes = {
suggestions: ProofSuggestion[] | null
showMore: boolean
}
export type APIUserSearchResult = {
score: number
keybase?: APIUserKeybaseResult
service?: APIUserServiceResult
contact?: ProcessedContact
imptofu?: ImpTofuSearchResult
servicesSummary: {[key: string]: APIUserServiceSummary}
rawScore: number
}
export type NonUserDetails = {
isNonUser: boolean
assertionValue: string
assertionKey: string
description: string
contact?: ProcessedContact
service?: APIUserServiceResult
siteIcon: SizedImage[] | null
siteIconDarkmode: SizedImage[] | null
siteIconFull: SizedImage[] | null
siteIconFullDarkmode: SizedImage[] | null
}
export type WotVouch = {
status: WotStatusType
vouchProof: SigID
vouchee: UserVersion
voucheeUsername: string
voucher: UserVersion
voucherUsername: string
vouchTexts: string[] | null
vouchedAt: Time
confidence?: Confidence
}
export type DowngradeReferenceRes = {
completed: BlockReferenceCount[] | null
failed: BlockReference
}
export type UserPlusAllKeys = {
base: UserPlusKeys
pgpKeys: PublicKey[] | null
remoteTracks: RemoteTrack[] | null
}
export type FullStatus = {
username: string
configPath: string
curStatus: CurrentStatus
extStatus: ExtendedStatus
client: KbClientStatus
service: KbServiceStatus
kbfs: KBFSStatus
desktop: DesktopStatus
updater: UpdaterStatus
start: StartStatus
git: GitStatus
}
export type FolderNormalView = {
resolvingConflict: boolean
stuckInConflict: boolean
localViews: Path[] | null
}
export type FolderConflictManualResolvingLocalView = {
normalView: Path
}
export type GitRepoInfo = {
folder: FolderHandle
repoId: RepoID
localMetadata: GitLocalMetadata
serverMetadata: GitServerMetadata
repoUrl: string
globalUniqueId: string
canDelete: boolean
teamRepoSettings?: GitTeamRepoSettings
}
export type HomeScreenPeopleNotification =
| {t: HomeScreenPeopleNotificationType.FOLLOWED; FOLLOWED: HomeScreenPeopleNotificationFollowed}
| {t: HomeScreenPeopleNotificationType.FOLLOWED_MULTI; FOLLOWED_MULTI: HomeScreenPeopleNotificationFollowedMulti}
| {t: HomeScreenPeopleNotificationType.CONTACT; CONTACT: HomeScreenPeopleNotificationContact}
| {t: HomeScreenPeopleNotificationType.CONTACT_MULTI; CONTACT_MULTI: HomeScreenPeopleNotificationContactMulti}
| {
t: Exclude<
HomeScreenPeopleNotificationType,
| HomeScreenPeopleNotificationType.FOLLOWED
| HomeScreenPeopleNotificationType.FOLLOWED_MULTI
| HomeScreenPeopleNotificationType.CONTACT
| HomeScreenPeopleNotificationType.CONTACT_MULTI
>
}
export type IdentifyProofBreak = {
remoteProof: RemoteProof
lcr: LinkCheckResult
}
export type ProblemSetDevices = {
problemSet: ProblemSet
devices: Device[] | null
}
export type ListArgs = {
opId: OpID
path: Path
filter: ListFilter
}
export type ListToDepthArgs = {
opId: OpID
path: Path
filter: ListFilter
depth: number
}
export type RemoveArgs = {
opId: OpID
path: Path
recursive: boolean
}
export type ReadArgs = {
opId: OpID
path: Path
offset: number
size: number
}
export type WriteArgs = {
opId: OpID
path: Path
offset: number
}
export type CopyArgs = {
opId: OpID
src: Path
dest: Path
overwriteExistingFiles: boolean
}
export type MoveArgs = {
opId: OpID
src: Path
dest: Path
overwriteExistingFiles: boolean
}
export type GetRevisionsArgs = {
opId: OpID
path: Path
spanType: RevisionSpanType
}
export type GetRevisionsResult = {
revisions: DirentWithRevision[] | null
progress: Progress
}
export type HiddenTeamChain = {
id: TeamID
subversion: number
public: boolean
frozen: boolean
tombstoned: boolean
last: Seqno
lastFull: Seqno
latestSeqnoHint: Seqno
lastCommittedSeqno: Seqno
linkReceiptTimes: {[key: string]: Time}
lastPerTeamKeys: {[key: string]: Seqno}
outer: {[key: string]: LinkID}
inner: {[key: string]: HiddenTeamChainLink}
readerPerTeamKeys: {[key: string]: Seqno}
ratchetSet: HiddenTeamChainRatchetSet
cachedAt: Time
needRotate: boolean
merkleRoots: {[key: string]: MerkleRootV2}
}
export type AnnotatedTeamInvite = {
invite: TeamInvite
displayName: TeamInviteDisplayName
inviterUsername: string
inviteeUv: UserVersion
teamName: string
status?: TeamMemberStatus
usedInvites: AnnotatedTeamUsedInviteLogPoint[] | null
}
export type TeamSigChainState = {
reader: UserVersion
id: TeamID
implicit: boolean
public: boolean
rootAncestor: TeamName
nameDepth: number
nameLog: TeamNameLogPoint[] | null
lastSeqno: Seqno
lastLinkId: LinkID
lastHighSeqno: Seqno
lastHighLinkId: LinkID
parentId?: TeamID
userLog: {[key: string]: UserLogPoint[] | null}
subteamLog: {[key: string]: SubteamLogPoint[] | null}
perTeamKeys: {[key: string]: PerTeamKey}
maxPerTeamKeyGeneration: PerTeamKeyGeneration
perTeamKeyCTime: UnixTime
linkIDs: {[key: string]: LinkID}
stubbedLinks: {[key: string]: boolean}
activeInvites: {[key: string]: TeamInvite}
obsoleteInvites: {[key: string]: TeamInvite}
usedInvites: {[key: string]: TeamUsedInviteLogPoint[] | null}
open: boolean
openTeamJoinAs: TeamRole
bots: {[key: string]: TeamBotSettings}
tlfIDs: TLFID[] | null
tlfLegacyUpgrade: {[key: string]: TeamLegacyTLFUpgradeChainInfo}
headMerkle?: MerkleRootV2
merkleRoots: {[key: string]: MerkleRootV2}
}
export type LookupImplicitTeamRes = {
teamId: TeamID
name: TeamName
displayName: ImplicitTeamDisplayName
tlfId: TLFID
}
export type PublicKeyV2NaCl = {
base: PublicKeyV2Base
parent?: KID
deviceId: DeviceID
deviceDescription: string
deviceType: DeviceTypeV2
}
export type PublicKeyV2PGPSummary = {
base: PublicKeyV2Base
fingerprint: PGPFingerprint
identities: PGPIdentity[] | null
}
export type ConflictState =
| {conflictStateType: ConflictStateType.NormalView; NormalView: FolderNormalView}
| {conflictStateType: ConflictStateType.ManualResolvingLocalView; ManualResolvingLocalView: FolderConflictManualResolvingLocalView}
| {conflictStateType: Exclude<ConflictStateType, ConflictStateType.NormalView | ConflictStateType.ManualResolvingLocalView>}
export type GitRepoResult =
| {state: GitRepoResultState.ERR; ERR: string}
| {state: GitRepoResultState.OK; OK: GitRepoInfo}
| {state: Exclude<GitRepoResultState, GitRepoResultState.ERR | GitRepoResultState.OK>}
export type HomeScreenItemData =
| {t: HomeScreenItemType.TODO; TODO: HomeScreenTodo}
| {t: HomeScreenItemType.PEOPLE; PEOPLE: HomeScreenPeopleNotification}
| {t: HomeScreenItemType.ANNOUNCEMENT; ANNOUNCEMENT: HomeScreenAnnouncement}
| {t: Exclude<HomeScreenItemType, HomeScreenItemType.TODO | HomeScreenItemType.PEOPLE | HomeScreenItemType.ANNOUNCEMENT>}
export type IdentifyTrackBreaks = {
keys: IdentifyKey[] | null
proofs: IdentifyProofBreak[] | null
}
export type OpDescription =
| {asyncOp: AsyncOps.LIST; LIST: ListArgs}
| {asyncOp: AsyncOps.LIST_RECURSIVE; LIST_RECURSIVE: ListArgs}
| {asyncOp: AsyncOps.LIST_RECURSIVE_TO_DEPTH; LIST_RECURSIVE_TO_DEPTH: ListToDepthArgs}
| {asyncOp: AsyncOps.READ; READ: ReadArgs}
| {asyncOp: AsyncOps.WRITE; WRITE: WriteArgs}
| {asyncOp: AsyncOps.COPY; COPY: CopyArgs}
| {asyncOp: AsyncOps.MOVE; MOVE: MoveArgs}
| {asyncOp: AsyncOps.REMOVE; REMOVE: RemoveArgs}
| {asyncOp: AsyncOps.GET_REVISIONS; GET_REVISIONS: GetRevisionsArgs}
| {
asyncOp: Exclude<
AsyncOps,
| AsyncOps.LIST
| AsyncOps.LIST_RECURSIVE
| AsyncOps.LIST_RECURSIVE_TO_DEPTH
| AsyncOps.READ
| AsyncOps.WRITE
| AsyncOps.COPY
| AsyncOps.MOVE
| AsyncOps.REMOVE
| AsyncOps.GET_REVISIONS
>
}
export type TeamDetails = {
name: string
members: TeamMembersDetails
keyGeneration: PerTeamKeyGeneration
annotatedActiveInvites: {[key: string]: AnnotatedTeamInvite}
settings: TeamSettings
showcase: TeamShowcase
}
export type TeamData = {
v: number
frozen: boolean
tombstoned: boolean
secretless: boolean
name: TeamName
chain: TeamSigChainState
perTeamKeySeedsUnverified: {[key: string]: PerTeamKeySeedItem}
readerKeyMasks: {[key: string]: {[key: string]: MaskB64}}
latestSeqnoHint: Seqno
cachedAt: Time
tlfCryptKeys: {[key: string]: CryptKey[] | null}
}
export type AnnotatedTeamList = {
teams: AnnotatedMemberInfo[] | null
annotatedActiveInvites: {[key: string]: AnnotatedTeamInvite}
}
export type TeamDebugRes = {
chain: TeamSigChainState
}
export type AnnotatedTeam = {
teamId: TeamID
name: string
transitiveSubteamsUnverified: SubteamListResult
members: AnnotatedTeamMemberDetails[] | null
invites: AnnotatedTeamInvite[] | null
joinRequests: TeamJoinRequest[] | null
tarsDisabled: boolean
settings: TeamSettings
showcase: TeamShowcase
}
export type PublicKeyV2 =
| {keyType: KeyType.NACL; NACL: PublicKeyV2NaCl}
| {keyType: KeyType.PGP; PGP: PublicKeyV2PGPSummary}
| {keyType: Exclude<KeyType, KeyType.NACL | KeyType.PGP>}
export type UserPlusKeysV2 = {
uid: UID
username: string
eldestSeqno: Seqno
status: StatusCode
perUserKeys: PerUserKey[] | null
deviceKeys: {[key: string]: PublicKeyV2NaCl}
pgpKeys: {[key: string]: PublicKeyV2PGPSummary}
stellarAccountId?: string
remoteTracks: {[key: string]: RemoteTrack}
reset?: ResetSummary
unstubbed: boolean
}
export type UPKLiteV1 = {
uid: UID
username: string
eldestSeqno: Seqno
status: StatusCode
deviceKeys: {[key: string]: PublicKeyV2NaCl}
reset?: ResetSummary
}
/**
* Folder represents a favorite top-level folder in kbfs.
* This type is likely to change significantly as all the various parts are
* connected and tested.
*/
export type Folder = {
name: string
private: boolean
created: boolean
folderType: FolderType
teamId?: TeamID
resetMembers: User[] | null
mtime?: Time
conflictState?: ConflictState
syncConfig?: FolderSyncConfig
}
export type HomeScreenItem = {
badged: boolean
data: HomeScreenItemData
dataExt: HomeScreenItemDataExt
}
export type Identify2Res = {
upk: UserPlusKeys
identifiedAt: Time
trackBreaks?: IdentifyTrackBreaks
}
export type IdentifyLiteRes = {
ul: UserOrTeamLite
trackBreaks?: IdentifyTrackBreaks
}
export type ResolveIdentifyImplicitTeamRes = {
displayName: string
teamId: TeamID
writers: UserVersion[] | null
trackBreaks: {[key: string]: IdentifyTrackBreaks}
folderId: TLFID
}
export type TLFIdentifyFailure = {
user: User
breaks?: IdentifyTrackBreaks
}
export type UserPlusKeysV2AllIncarnations = {
current: UserPlusKeysV2
pastIncarnations: UserPlusKeysV2[] | null
uvv: UserVersionVector
seqnoLinkIDs: {[key: string]: LinkID}
minorVersion: UPK2MinorVersion
stale: boolean
}
export type UPKLiteV1AllIncarnations = {
current: UPKLiteV1
pastIncarnations: UPKLiteV1[] | null
seqnoLinkIDs: {[key: string]: LinkID}
minorVersion: UPKLiteMinorVersion
}
export type FavoritesResult = {
favoriteFolders: Folder[] | null
ignoredFolders: Folder[] | null
newFolders: Folder[] | null
}
export type HomeScreen = {
lastViewed: Time
version: number
visits: number
items: HomeScreenItem[] | null
followSuggestions: HomeUserSummary[] | null
announcementsVersion: number
}
export type Identify2ResUPK2 = {
upk: UserPlusKeysV2AllIncarnations
identifiedAt: Time
trackBreaks?: IdentifyTrackBreaks
}
export type FSEditListRequest = {
folder: Folder
requestId: number
}
export type FSFolderEditHistory = {
folder: Folder
serverTime: Time
history: FSFolderWriterEditHistory[] | null
}
export type FolderSyncConfigAndStatusWithFolder = {
folder: Folder
config: FolderSyncConfig
status: FolderSyncStatus
}
export type FolderWithFavFlags = {
folder: Folder
isFavorite: boolean
isIgnored: boolean
isNew: boolean
}
export type SimpleFSIndexProgress = {
overallProgress: IndexProgressRecord
currFolder: Folder
currProgress: IndexProgressRecord
foldersLeft: Folder[] | null
}
export type TLFBreak = {
breaks: TLFIdentifyFailure[] | null
}
/**
* * What we're storing for each user. At first it was UPAKs, as defined
* * in common.avdl. But going forward, we're going to use UserPlusKeysV2AllIncarnations.
*/
export type UPAKVersioned =
| {v: UPAKVersion.V1; V1: UserPlusAllKeys}
| {v: UPAKVersion.V2; V2: UserPlusKeysV2AllIncarnations}
| {v: Exclude<UPAKVersion, UPAKVersion.V1 | UPAKVersion.V2>}
export type SyncConfigAndStatusRes = {
folders: FolderSyncConfigAndStatusWithFolder[] | null
overallStatus: FolderSyncStatus
}
export type CanonicalTLFNameAndIDWithBreaks = {
tlfId: TLFID
canonicalName: CanonicalTlfName
breaks: TLFBreak
}
export type GetTLFCryptKeysRes = {
nameIdBreaks: CanonicalTLFNameAndIDWithBreaks
cryptKeys: CryptKey[] | null
} | the_stack |
import { expect } from 'chai';
import { ITelemetryBaseEvent, ITelemetryBaseLogger } from '@fluidframework/common-definitions';
import { v4 as uuidv4 } from 'uuid';
import { EditLog } from '../EditLog';
import { Change, ConstraintEffect, Insert, StablePlace, StableRange, Transaction } from '../default-edits';
import { CachingLogViewer, EditStatusCallback, LogViewer } from '../LogViewer';
import { Snapshot } from '../Snapshot';
import { EditId } from '../Identifiers';
import { assert, noop } from '../Common';
import { newEdit, Edit, EditStatus } from '../generic';
import {
initialSnapshot,
left,
leftTraitLabel,
leftTraitLocation,
makeEmptyNode,
right,
rightTraitLocation,
simpleTestTree,
simpleTreeSnapshot,
} from './utilities/TestUtilities';
import { MockTransaction } from './utilities/MockTransaction';
const simpleTreeNoTraits = { ...simpleTestTree, traits: {} };
const simpleSnapshotNoTraits = Snapshot.fromTree(simpleTreeNoTraits);
function getSimpleLog(numEdits: number = 2): EditLog<Change> {
const log = new EditLog<Change>();
for (let i = 0; i < numEdits; i++) {
log.addSequencedEdit(
newEdit(
i % 2 === 0
? Insert.create([left], StablePlace.atStartOf(leftTraitLocation))
: Insert.create([right], StablePlace.atStartOf(rightTraitLocation))
),
{ sequenceNumber: i + 1, referenceSequenceNumber: i }
);
}
return log;
}
function getSimpleLogWithLocalEdits(numSequencedEdits: number = 2): EditLog<Change> {
const logWithLocalEdits = getSimpleLog(numSequencedEdits);
logWithLocalEdits.addLocalEdit(newEdit(Insert.create([makeEmptyNode()], StablePlace.atEndOf(leftTraitLocation))));
logWithLocalEdits.addLocalEdit(newEdit(Insert.create([makeEmptyNode()], StablePlace.atEndOf(rightTraitLocation))));
logWithLocalEdits.addLocalEdit(newEdit(Insert.create([makeEmptyNode()], StablePlace.atStartOf(leftTraitLocation))));
return logWithLocalEdits;
}
function getSnapshotsForLog(log: EditLog<Change>, baseSnapshot: Snapshot): Snapshot[] {
const snapshots = [baseSnapshot];
for (let i = 0; i < log.length; i++) {
const edit = log.getEditInSessionAtIndex(i);
snapshots.push(new Transaction(snapshots[i]).applyChanges(edit.changes).view);
}
return snapshots;
}
function runLogViewerCorrectnessTests(
viewerCreator: (log: EditLog<Change>, baseSnapshot?: Snapshot) => LogViewer
): Mocha.Suite {
return describe('LogViewer', () => {
const log = getSimpleLog();
it('generates initialTree by default for the 0th revision', () => {
const viewer = viewerCreator(new EditLog());
const headSnapshot = viewer.getSnapshotInSession(0);
expect(headSnapshot.equals(initialSnapshot)).to.be.true;
});
it('can be constructed from a non-empty EditLog', () => {
const viewer = viewerCreator(log, simpleSnapshotNoTraits);
const headSnapshot = viewer.getSnapshotInSession(Number.POSITIVE_INFINITY);
expect(headSnapshot.equals(simpleTreeSnapshot)).to.be.true;
});
it('can generate all snapshots for an EditLog', () => {
const viewer = viewerCreator(log, simpleSnapshotNoTraits);
const initialSnapshot = viewer.getSnapshotInSession(0);
expect(initialSnapshot.equals(simpleSnapshotNoTraits)).to.be.true;
const leftOnlySnapshot = viewer.getSnapshotInSession(1);
expect(
leftOnlySnapshot.equals(Snapshot.fromTree({ ...simpleTestTree, traits: { [leftTraitLabel]: [left] } }))
).to.be.true;
const fullTreeSnapshot = viewer.getSnapshotInSession(2);
expect(fullTreeSnapshot.equals(simpleTreeSnapshot)).to.be.true;
});
it('produces correct snapshots when the log is mutated', () => {
const simpleLog = getSimpleLog();
const mutableLog = new EditLog<Change>();
const viewer = viewerCreator(mutableLog, simpleSnapshotNoTraits);
const snapshotsForLog = getSnapshotsForLog(simpleLog, simpleSnapshotNoTraits);
// This test takes an empty log (A) and a log with edits in it (B), and adds the edits from B to A.
// After each addition, the test code will iterate from [0, length_of_A] and get a snapshot for each revision via LogViewer
// and assert that none of the snapshots differ from those created via pure Transaction APIs.
for (let i = 0; i <= simpleLog.length; i++) {
for (let j = 0; j <= mutableLog.length; j++) {
const viewerSnapshot = viewer.getSnapshotInSession(j);
expect(viewerSnapshot.equals(snapshotsForLog[j])).to.be.true;
}
// Revisions are from [0, simpleLog.length], edits are at indices [0, simpleLog.length)
if (i < simpleLog.length) {
const edit = simpleLog.getEditInSessionAtIndex(i);
mutableLog.addSequencedEdit(edit, { sequenceNumber: i + 1, referenceSequenceNumber: i });
}
}
});
it('produces correct snapshots when local edits are shifted in the log due to sequenced edits being added', () => {
function getSnapshotsFromViewer(viewer: LogViewer, lastRevision: number): Snapshot[] {
const snapshots: Snapshot[] = [];
for (let i = 0; i <= lastRevision; i++) {
snapshots.push(viewer.getSnapshotInSession(i));
}
return snapshots;
}
function expectSnapshotsAreEqual(log: EditLog<Change>, viewer: LogViewer): void {
const snapshotsForLog = getSnapshotsForLog(log, simpleSnapshotNoTraits);
const snapshotsForViewer = getSnapshotsFromViewer(viewer, log.length);
expect(snapshotsForLog.length).to.equal(snapshotsForViewer.length);
for (let i = 0; i < snapshotsForLog.length; i++) {
expect(snapshotsForLog[i].equals(snapshotsForViewer[i])).to.be.true;
}
}
const logWithLocalEdits = getSimpleLogWithLocalEdits();
const viewer = viewerCreator(logWithLocalEdits, simpleSnapshotNoTraits);
expectSnapshotsAreEqual(logWithLocalEdits, viewer);
let seqNumber = 1;
// Sequence the existing local edits and ensure viewer generates the correct snapshots
while (logWithLocalEdits.numberOfLocalEdits > 0) {
// Add a remote sequenced edit
logWithLocalEdits.addSequencedEdit(
newEdit(Insert.create([makeEmptyNode()], StablePlace.atStartOf(rightTraitLocation))),
{ sequenceNumber: seqNumber, referenceSequenceNumber: seqNumber - 1 }
);
++seqNumber;
expectSnapshotsAreEqual(logWithLocalEdits, viewer);
// Sequence a local edit
logWithLocalEdits.addSequencedEdit(
logWithLocalEdits.getEditInSessionAtIndex(logWithLocalEdits.numberOfSequencedEdits),
{ sequenceNumber: seqNumber, referenceSequenceNumber: seqNumber - 1 }
);
++seqNumber;
expectSnapshotsAreEqual(logWithLocalEdits, viewer);
}
});
});
}
describe('CachingLogViewer', () => {
function getMockLogger(callback?: (event: ITelemetryBaseEvent) => void): ITelemetryBaseLogger {
return { send: callback ?? noop };
}
function getCachingLogViewerAssumeAppliedEdits(
log: EditLog<Change>,
baseSnapshot?: Snapshot,
editCallback?: EditStatusCallback,
logger?: ITelemetryBaseLogger,
knownRevisions?: [number, Snapshot][]
): CachingLogViewer<Change> {
return new CachingLogViewer(
log,
baseSnapshot,
knownRevisions?.map((pair) => [pair[0], { snapshot: pair[1], result: EditStatus.Applied }]),
/* expensiveValidation */ true,
editCallback,
logger ?? getMockLogger(),
Transaction.factory,
log.numberOfSequencedEdits
);
}
runLogViewerCorrectnessTests(getCachingLogViewerAssumeAppliedEdits);
it('detects non-integer revisions when setting snapshots', async () => {
expect(() =>
getCachingLogViewerAssumeAppliedEdits(getSimpleLog(), simpleSnapshotNoTraits, undefined, undefined, [
[2.4, simpleTreeSnapshot],
])
).to.throw('revision must be an integer');
});
it('detects out-of-bounds revisions when setting snapshots', async () => {
expect(() =>
getCachingLogViewerAssumeAppliedEdits(getSimpleLog(), simpleSnapshotNoTraits, undefined, undefined, [
[1000, simpleTreeSnapshot],
])
).to.throw('revision must correspond to the result of a SequencedEdit');
});
it('can be created with known revisions', async () => {
const log = getSimpleLog();
const snapshots = getSnapshotsForLog(log, simpleSnapshotNoTraits);
const viewer = getCachingLogViewerAssumeAppliedEdits(
log,
simpleSnapshotNoTraits,
undefined,
undefined,
Array.from(snapshots.keys()).map((revision) => [revision, snapshots[revision]])
);
for (let i = log.length; i >= 0; i--) {
const snapshot = snapshots[i];
expect(viewer.getSnapshotInSession(i).equals(snapshot)).to.be.true;
}
});
async function requestAllSnapshots(viewer: CachingLogViewer<Change>, log: EditLog<Change>): Promise<void> {
for (let i = 0; i <= log.length; i++) {
await viewer.getSnapshot(i);
}
}
it('caches snapshots for sequenced edits', async () => {
const log = getSimpleLog();
let editsProcessed = 0;
const viewer = getCachingLogViewerAssumeAppliedEdits(log, simpleSnapshotNoTraits, () => editsProcessed++);
assert(log.length < CachingLogViewer.sequencedCacheSizeMax);
await requestAllSnapshots(viewer, log);
expect(editsProcessed).to.equal(log.length);
// Ask for every snapshot; no edit application should occur, since the snapshots will be cached.
for (let i = 0; i <= log.length; i++) {
await viewer.getSnapshot(i);
}
expect(editsProcessed).to.equal(log.length);
});
it('caches edit results for sequenced edits', async () => {
const log = getSimpleLog(2);
// Add an invalid edit
log.addSequencedEdit(
newEdit([Change.constraint(StableRange.only(left), ConstraintEffect.InvalidAndDiscard, undefined, 0)]),
{ sequenceNumber: 3, referenceSequenceNumber: 2, minimumSequenceNumber: 2 }
);
let editsProcessed = 0;
const viewer = getCachingLogViewerAssumeAppliedEdits(log, simpleSnapshotNoTraits, () => editsProcessed++);
assert(log.length < CachingLogViewer.sequencedCacheSizeMax);
await requestAllSnapshots(viewer, log);
expect(editsProcessed).to.equal(log.length);
expect((await viewer.getEditResult(0)).status).equals(undefined);
expect((await viewer.getEditResult(1)).status).equals(EditStatus.Applied);
expect((await viewer.getEditResult(2)).status).equals(EditStatus.Applied);
expect((await viewer.getEditResult(3)).status).equals(EditStatus.Invalid);
expect(viewer.getEditResultInSession(0).status).equals(undefined);
expect(viewer.getEditResultInSession(1).status).equals(EditStatus.Applied);
expect(viewer.getEditResultInSession(2).status).equals(EditStatus.Applied);
expect(viewer.getEditResultInSession(3).status).equals(EditStatus.Invalid);
});
it('evicts least recently set cached snapshots for sequenced edits', async () => {
let editsProcessed = 0;
const log = getSimpleLog(CachingLogViewer.sequencedCacheSizeMax * 2);
const viewer = getCachingLogViewerAssumeAppliedEdits(log, simpleSnapshotNoTraits, () => editsProcessed++);
viewer.setMinimumSequenceNumber(log.length + 1); // simulate all edits being subject to eviction
await requestAllSnapshots(viewer, log);
expect(editsProcessed).to.equal(log.length);
editsProcessed = 0;
for (let i = CachingLogViewer.sequencedCacheSizeMax + 1; i <= log.length; i++) {
await viewer.getSnapshot(i);
}
expect(editsProcessed).to.equal(0);
await viewer.getSnapshot(CachingLogViewer.sequencedCacheSizeMax);
expect(editsProcessed).to.equal(CachingLogViewer.sequencedCacheSizeMax);
});
it('never evicts the snapshot for the most recent sequenced edit', async () => {
let editsProcessed = 0;
const log = getSimpleLog(CachingLogViewer.sequencedCacheSizeMax * 2);
const viewer = getCachingLogViewerAssumeAppliedEdits(log, simpleSnapshotNoTraits, () => editsProcessed++);
// Simulate all clients being caught up.
viewer.setMinimumSequenceNumber(log.numberOfSequencedEdits);
await requestAllSnapshots(viewer, log);
expect(editsProcessed).to.equal(log.length);
editsProcessed = 0;
for (let i = 0; i <= CachingLogViewer.sequencedCacheSizeMax; i++) {
await viewer.getSnapshot(i);
}
expect(editsProcessed).to.equal(CachingLogViewer.sequencedCacheSizeMax);
editsProcessed = 0;
await viewer.getSnapshot(log.numberOfSequencedEdits);
expect(editsProcessed).to.equal(0);
});
it('caches snapshots for local revisions', async () => {
const logWithLocalEdits = getSimpleLogWithLocalEdits();
let editsProcessed = 0;
const viewer = getCachingLogViewerAssumeAppliedEdits(
logWithLocalEdits,
simpleSnapshotNoTraits,
() => editsProcessed++
);
assert(logWithLocalEdits.length < CachingLogViewer.sequencedCacheSizeMax);
await requestAllSnapshots(viewer, logWithLocalEdits);
expect(editsProcessed).to.equal(logWithLocalEdits.length);
// Local edits should now be cached until next remote sequenced edit arrives
editsProcessed = 0;
for (let i = logWithLocalEdits.numberOfSequencedEdits + 1; i <= logWithLocalEdits.length; i++) {
await viewer.getSnapshot(i);
expect(editsProcessed).to.equal(0);
}
// Add a new local edit, and request the latest view.
// This should apply only a single edit, as the most recent HEAD should be cached.
editsProcessed = 0;
logWithLocalEdits.addLocalEdit(
newEdit(Insert.create([makeEmptyNode()], StablePlace.atEndOf(rightTraitLocation)))
);
await requestAllSnapshots(viewer, logWithLocalEdits);
expect(editsProcessed).to.equal(1);
editsProcessed = 0;
let seqNumber = 1;
while (logWithLocalEdits.numberOfLocalEdits > 0) {
logWithLocalEdits.addSequencedEdit(
logWithLocalEdits.getEditInSessionAtIndex(logWithLocalEdits.numberOfSequencedEdits),
{ sequenceNumber: seqNumber, referenceSequenceNumber: seqNumber - 1 }
);
++seqNumber;
await viewer.getSnapshot(logWithLocalEdits.numberOfSequencedEdits); // get the latest (just added) sequenced edit
await viewer.getSnapshot(Number.POSITIVE_INFINITY); // get the last snapshot, which is a local revision
expect(editsProcessed).to.equal(0);
}
});
it('invalidates cached snapshots for local revisions when remote edits are received', () => {
const logWithLocalEdits = getSimpleLogWithLocalEdits();
let editsProcessed = 0;
const viewer = getCachingLogViewerAssumeAppliedEdits(
logWithLocalEdits,
simpleSnapshotNoTraits,
() => editsProcessed++
);
// Request twice, should only process edits once
viewer.getSnapshotInSession(Number.POSITIVE_INFINITY);
viewer.getSnapshotInSession(Number.POSITIVE_INFINITY);
expect(editsProcessed).to.equal(logWithLocalEdits.length);
// Remote edit arrives
editsProcessed = 0;
logWithLocalEdits.addSequencedEdit(
newEdit(Insert.create([makeEmptyNode()], StablePlace.atEndOf(rightTraitLocation))),
{ sequenceNumber: 3, referenceSequenceNumber: 2, minimumSequenceNumber: 2 }
);
viewer.getSnapshotInSession(Number.POSITIVE_INFINITY);
expect(editsProcessed).to.equal(logWithLocalEdits.numberOfLocalEdits + 1);
});
// An arbitrary snapshot which can be used to check to see if it gets used when provided as a cached value.
const arbitrarySnapshot = Snapshot.fromTree(makeEmptyNode());
it('uses known editing result', () => {
const log = new EditLog<Change>();
const editsProcessed: boolean[] = [];
const viewer = getCachingLogViewerAssumeAppliedEdits(log, simpleSnapshotNoTraits, (_, _2, wasCached) =>
editsProcessed.push(wasCached)
);
const before = viewer.getSnapshotInSession(Number.POSITIVE_INFINITY);
const edit = newEdit([]);
log.addLocalEdit(edit);
viewer.setKnownEditingResult(edit, {
status: EditStatus.Applied,
changes: edit.changes,
before,
after: arbitrarySnapshot,
steps: [],
});
const after = viewer.getSnapshotInSession(Number.POSITIVE_INFINITY);
expect(editsProcessed).deep.equal([true]);
expect(after).equal(arbitrarySnapshot);
});
it('ignores known editing if for wrong before snapshot', () => {
const log = new EditLog<Change>();
const editsProcessed: boolean[] = [];
const viewer = getCachingLogViewerAssumeAppliedEdits(log, simpleSnapshotNoTraits, (_, _2, wasCached) =>
editsProcessed.push(wasCached)
);
const edit = newEdit([]);
log.addLocalEdit(edit);
viewer.setKnownEditingResult(edit, {
status: EditStatus.Applied,
changes: edit.changes,
before: arbitrarySnapshot,
after: arbitrarySnapshot,
steps: [],
});
const after = viewer.getSnapshotInSession(Number.POSITIVE_INFINITY);
expect(editsProcessed).deep.equal([false]);
expect(after).not.equal(arbitrarySnapshot);
});
it('ignores known editing if for wrong edit', () => {
const log = new EditLog<Change>();
const editsProcessed: boolean[] = [];
const viewer = getCachingLogViewerAssumeAppliedEdits(log, simpleSnapshotNoTraits, (_, _2, wasCached) =>
editsProcessed.push(wasCached)
);
const before = viewer.getSnapshotInSession(Number.POSITIVE_INFINITY);
const edit = newEdit([]);
log.addLocalEdit(edit);
viewer.setKnownEditingResult(newEdit([]), {
status: EditStatus.Applied,
changes: edit.changes,
before,
after: arbitrarySnapshot,
steps: [],
});
const after = viewer.getSnapshotInSession(Number.POSITIVE_INFINITY);
expect(editsProcessed).deep.equal([false]);
expect(after).not.equal(arbitrarySnapshot);
});
it('uses known editing result with multiple edits', () => {
const log = new EditLog<Change>();
const editsProcessed: boolean[] = [];
const viewer = getCachingLogViewerAssumeAppliedEdits(log, simpleSnapshotNoTraits, (_, _2, wasCached) =>
editsProcessed.push(wasCached)
);
const edit1 = newEdit([]);
const edit2 = newEdit([]);
const edit3 = newEdit([]);
log.addLocalEdit(edit1);
const before = viewer.getSnapshotInSession(Number.POSITIVE_INFINITY);
expect(editsProcessed).deep.equal([false]);
log.addLocalEdit(edit2);
viewer.setKnownEditingResult(edit2, {
status: EditStatus.Applied,
changes: edit2.changes,
before,
after: arbitrarySnapshot,
steps: [],
});
const after = viewer.getSnapshotInSession(Number.POSITIVE_INFINITY);
expect(editsProcessed).deep.equal([false, true]);
expect(after).equal(arbitrarySnapshot);
log.addLocalEdit(edit3);
viewer.getSnapshotInSession(Number.POSITIVE_INFINITY);
expect(editsProcessed).deep.equal([false, true, false]);
});
describe('Telemetry', () => {
function getViewer(): {
log: EditLog<Change>;
viewer: CachingLogViewer<Change>;
events: ITelemetryBaseEvent[];
} {
const log = getSimpleLog();
const events: ITelemetryBaseEvent[] = [];
const viewer = new CachingLogViewer(
log,
simpleSnapshotNoTraits,
[],
/* expensiveValidation */ true,
undefined,
getMockLogger((event) => events.push(event)),
Transaction.factory
);
return { log, viewer, events };
}
function addInvalidEdit(log: EditLog<Change>): Edit<Change> {
// Add a local edit that will be invalid (inserts a node at a location that doesn't exist)
const edit = newEdit(
Insert.create(
[makeEmptyNode()],
StablePlace.atEndOf({
parent: initialSnapshot.root,
label: leftTraitLabel,
})
)
);
log.addLocalEdit(edit);
return edit;
}
it('is logged for invalid locally generated edits when those edits are sequenced', async () => {
const { log, events, viewer } = getViewer();
const edit = addInvalidEdit(log);
await viewer.getSnapshot(Number.POSITIVE_INFINITY);
expect(events.length).equals(0, 'Invalid local edit should not log telemetry');
log.addSequencedEdit(edit, { sequenceNumber: 3, referenceSequenceNumber: 2 });
await viewer.getSnapshot(Number.POSITIVE_INFINITY);
expect(events.length).equals(1);
});
it('is only logged once upon first application for invalid locally generated edits', async () => {
const { log, events, viewer } = getViewer();
const numEdits = 10;
const localEdits = [...Array(numEdits).keys()].map(() => addInvalidEdit(log));
await viewer.getSnapshot(Number.POSITIVE_INFINITY);
expect(events.length).equals(0);
for (let i = 0; i < numEdits; i++) {
const localEdit = localEdits[i];
log.addSequencedEdit(localEdit, { sequenceNumber: i + 1, referenceSequenceNumber: 1 });
await viewer.getSnapshot(Number.POSITIVE_INFINITY);
expect(events.length).equals(i + 1);
const currentEvent = events[i];
expect(currentEvent.category).equals('generic');
expect(currentEvent.eventName).equals('InvalidSharedTreeEdit');
}
});
});
describe('Sequencing', () => {
function addFakeEdit(
logViewer: CachingLogViewer<unknown>,
sequenceNumber: number,
referenceSequenceNumber?: number
): Edit<unknown> {
const id = String(sequenceNumber ?? uuidv4()) as EditId;
const fakeChange = id;
const edit = { changes: [fakeChange], id };
logViewer.log.addSequencedEdit(edit, {
sequenceNumber,
referenceSequenceNumber: referenceSequenceNumber ?? sequenceNumber - 1,
});
return edit;
}
function minimalLogViewer(): CachingLogViewer<unknown> {
return new CachingLogViewer(
new EditLog(),
undefined,
[],
/* expensiveValidation */ true,
undefined,
getMockLogger(),
MockTransaction.factory
);
}
it('tracks the earliest sequenced edit in the session', () => {
const logViewer = minimalLogViewer();
expect(logViewer.earliestSequencedEditInSession()).undefined;
// Non-sequenced edit
logViewer.log.addLocalEdit({ id: uuidv4() as EditId, changes: [] });
expect(logViewer.earliestSequencedEditInSession()).undefined;
// First sequenced edit
const edit = addFakeEdit(logViewer, 123);
const expected = { edit, sequenceNumber: 123 };
expect(logViewer.earliestSequencedEditInSession()).deep.equals(expected);
// Non-sequenced edit
logViewer.log.addLocalEdit({ id: uuidv4() as EditId, changes: [] });
expect(logViewer.earliestSequencedEditInSession()).deep.equals(expected);
// Second sequenced edit
addFakeEdit(logViewer, 456);
expect(logViewer.earliestSequencedEditInSession()).deep.equals(expected);
});
it('can provide edit results for sequenced edits', () => {
const logViewer = minimalLogViewer();
expect(logViewer.getEditResultFromSequenceNumber(42)).undefined;
// Non-sequenced edit
logViewer.log.addLocalEdit({ id: uuidv4() as EditId, changes: [] });
expect(logViewer.getEditResultFromSequenceNumber(42)).undefined;
// First sequenced edit
const edit1 = addFakeEdit(logViewer, 123);
expect(logViewer.getEditResultFromSequenceNumber(42)).undefined;
const expected1 = {
id: edit1.id,
};
expect(logViewer.getEditResultFromSequenceNumber(123)).contains(expected1);
// Check that when no such sequence number exists, the closest earlier edit is returned
expect(logViewer.getEditResultFromSequenceNumber(124)).contains(expected1);
// Second sequenced edit
// Note that this edit is given a greater sequence number than simply incrementing after edit 1.
// This is deliberately done to simulate scenarios where a given DDS may not be sent all sequenced ops (because an other DDS
// might be receiving them).
const edit2 = addFakeEdit(logViewer, 456);
expect(logViewer.getEditResultFromSequenceNumber(123)).contains(expected1);
// Check that when no such sequence number exists, the closest earlier edit is returned
expect(logViewer.getEditResultFromSequenceNumber(124)).contains(expected1);
const expected2 = {
id: edit2.id,
};
expect(logViewer.getEditResultFromSequenceNumber(456)).contains(expected2);
// Check that when no such sequence number exists, the closest earlier edit is returned
expect(logViewer.getEditResultFromSequenceNumber(457)).contains(expected2);
});
it('can provide the reconciliation path for an edit', () => {
const logViewer = minimalLogViewer();
function expectReconciliationPath(edit: Edit<unknown>, path: Edit<unknown>[]) {
const actual = logViewer.reconciliationPathFromEdit(edit.id);
expect(actual.length).equals(path.length);
for (let i = 0; i < path.length; ++i) {
expect(actual[i].length).equals(1);
expect(actual[i][0].resolvedChange).equals(path[i].id);
}
}
// Non-sequenced edit
const nonSeqEdit = { id: uuidv4() as EditId, changes: [] };
logViewer.log.addLocalEdit(nonSeqEdit);
expectReconciliationPath(nonSeqEdit, []);
const edit1 = addFakeEdit(logViewer, 1001);
expectReconciliationPath(edit1, []);
// Note that this edit is given a greater sequence number than simply incrementing after edit 1.
// This is deliberately done to simulate scenarios where a given DDS may not be sent all sequenced ops (because an other DDS
// might be receiving them).
const edit2 = addFakeEdit(logViewer, 2001, 1001);
expectReconciliationPath(edit2, [edit1]);
const edit3 = addFakeEdit(logViewer, 3001, 2001);
expectReconciliationPath(edit3, [edit2]);
const edit4 = addFakeEdit(logViewer, 4001, 2500);
expectReconciliationPath(edit4, [edit2, edit3]);
const edit5 = addFakeEdit(logViewer, 5001, 500);
expectReconciliationPath(edit5, [edit1, edit2, edit3, edit4]);
});
});
}); | the_stack |
"use strict";
import { Socket } from "../node_modules/@types/socket.io";
import { User, Message } from "./user";
import { Game } from "./game";
import { Utils, Colors } from "./utils";
const grawlix = require("grawlix");
export class Server {
private _users: Array<User> = [];
private _games: Array<Game> = [];
private _debugMode: boolean = false;
private _lobbyChatCache: Array<Message> = [];
public constructor() {
this._games = [];
//join waiting users to games that need them
setInterval(this.joinGame.bind(this), 50);
}
public reloadClient(id: string) {
console.log("reloadClient");
let user = this.getUser(id);
if (user instanceof User) {
user.reloadClient();
console.log("called reload");
}
}
get games() {
return this._games;
}
public setDebug() {
this._debugMode = true;
}
public gameClick(id: string, gameId: string) {
let user = this.getUser(id);
if (user) {
user.gameClickedLast = gameId;
}
}
public get gameTypes() {
let gameTypes = [];
for (let i = 0; i < this.numberOfGames; i++) {
gameTypes.push(this._games[i].gameType);
}
return gameTypes;
}
public get inPlayArray() {
let inPlayArray = [];
for (let i = 0; i < this._games.length; i++) {
inPlayArray.push(this._games[i].inPlay);
}
return inPlayArray;
}
public get numberOfGames() {
return this._games.length;
}
public getGameById(uid: string): Game | undefined {
for (let i = 0; i < this._games.length; i++) {
if (this._games[i].uid == uid) {
return this._games[i];
}
}
return undefined;
}
public getIndexOfGameById(uid: string): number | undefined {
for (let i = 0; i < this._games.length; i++) {
if (this._games[i].uid == uid) {
return i;
}
}
return undefined;
}
public get usernameColorPairs() {
let usernameColorPairs = [];
for (let i = 0; i < this._games.length; i++) {
usernameColorPairs.push(this._games[i].usernameColorPairs);
}
return usernameColorPairs;
}
public addGame(game: Game) {
this._games.push(game);
for (let i = 0; i < this._users.length; i++) {
this._users[i].addNewGameToLobby(game.name, game.gameType, game.uid);
}
}
public removeGame(game: Game) {
let index = this._games.indexOf(game);
if (index != -1) {
for (let i = 0; i < this._users.length; i++) {
this._users[i].removeGameFromLobby(this._games[index].uid);
}
this._games.splice(index, 1);
}
}
public leaveGame(id: string) {
let user = this.getUser(id);
if (user instanceof User) {
if (user.registered && user.inGame) {
if (user.game != undefined) {
if (user.game.inPlay == false || user.game.inEndChat) {
user.game.kick(user);
user.resetAfterGame();
} else if (user.game.inPlay) {
//if game is in play, disconnect the player from the client
//without destroying its data (its role etc.)
user.disconnect();
user.game.disconnect(user);
let index = this._users.indexOf(user);
if (index != -1) {
this._users.splice(index, 1)[0];
}
user.reloadClient();
}
}
}
}
}
//join waiting players to games
private joinGame() {
this._users.forEach(user => {
if (user.registered && !user.inGame && user.gameClickedLast != "") {
let j = this.getIndexOfGameById(user.gameClickedLast);
if (j != undefined) {
//if game needs a player
if (this._games[j].playersWanted > 0) {
user.inGame = true;
user.game = this._games[j];
user.send(
"Hi, " +
user.username +
"! You have joined '" +
user.game.name +
"'.",
);
this._games[j].broadcast(user.username + " has joined the game");
if (this._games[j].minimumPlayersNeeded - 1 > 0) {
this._games[j].broadcast(
"The game will begin when at least " +
(this._games[j].minimumPlayersNeeded - 1).toString() +
" more players have joined",
);
//if just hit the minimum number of players
} else if (this._games[j].minimumPlayersNeeded - 1 == 0) {
this._games[j].broadcast(
'The game will start in 30 seconds. Type "/start" to start the game now',
);
}
this._games[j].addUser(user);
if (this._games[j].minimumPlayersNeeded > 0) {
user.send(
"The game will begin when at least " +
this._games[j].minimumPlayersNeeded.toString() +
" more players have joined",
);
//if just hit the minimum number of players
} else if (this._games[j].minimumPlayersNeeded == 0) {
user.send(
'The game will start in 30 seconds. Type "/start" to start the game now',
);
this._games[j].setAllTime(this._games[j].startWait, 10000);
}
}
}
}
});
}
private static cleanUpUsername(username: string) {
username = username.toLowerCase();
username = username.trim();
return username;
}
private validateUsername(user: User, username: string) {
let letters = /^([A-Za-z0-9]|\s)+$/;
for (let i = 0; i < this._users.length; i++) {
if (this._users[i].username == username) {
user.registrationError(
"This username has already been taken by someone",
);
return false;
}
}
if (username.length == 0) {
user.registrationError("Cannot be 0 letters long");
return false;
}
if (username.length > 12) {
user.registrationError("Must be no more than 12 letters long");
return false;
}
if (!letters.test(username)) {
user.registrationError(
"Can't contain punctuation/special characters",
);
return false;
}
if (grawlix.isObscene(username)) {
user.registrationError("Usernames can't contain profanity");
return false;
}
return true;
}
public addUser(
socket: Socket,
session: string,
id: string,
): string | undefined {
let output = undefined;
let newUser = new User(id, session);
if (!this._debugMode) {
let alreadyPlaying: boolean = false;
for (let i = 0; i < this._users.length; i++) {
if (this._users[i].registered && this._users[i].session == session) {
let thisUser = this._users[i];
alreadyPlaying = true;
if (this._users[i].socketCount < 3) {
console.log("added Socket");
this._users[i].addSocket(socket);
output = this._users[i].id;
//update lobby list for the client
for (let i = 0; i < this._users.length; i++) {
if (this._users[i].registered) {
socket.emit("addPlayerToLobbyList", this._users[i].username);
}
}
//send the client into the correct game or to the lobby
let game = this._users[i].game;
if (!this._users[i].inGame) {
socket.emit("transitionToLobby");
} else if (game != undefined) {
socket.emit("transitionToGame", game.name, game.uid, game.inPlay);
//send stored messages to the central and left boxes
for (let j = 0; j < this._users[i].cache.length; j++) {
socket.emit(
"message",
this._users[i].cache[j].msg,
this._users[i].cache[j].color,
);
}
for (let j = 0; j < this._users[i].leftCache.length; j++) {
socket.emit("leftMessage", this._users[i].leftCache[j]);
}
//send all players to user (only used in local mode)
let thisUser = this._users[i];
if (thisUser.game && thisUser.game.uid) {
let game = this.getGameById(thisUser.game.uid);
if (game) {
game.resendData(thisUser);
}
}
}
//send the client the correct time
socket.emit(
"setTime",
this._users[i].getTime(),
this._users[i].getWarn(),
);
//let the client know if they can vote at this time, or not.
if (thisUser.ifCanVote) {
thisUser.canVote();
thisUser.selectUser(thisUser.selectedUsername);
} else {
thisUser.cannotVote();
}
} else {
socket.emit(
"registrationError",
"You can't have more than 3 game tabs open at once.",
);
}
}
}
if (!alreadyPlaying) {
newUser.addSocket(socket);
this._users.push(newUser);
}
} else {
newUser.addSocket(socket);
this._users.push(newUser);
}
//update lobby chat for the client
for (let i = 0; i < this._lobbyChatCache.length; i++) {
socket.emit("lobbyMessage", this._lobbyChatCache[i]);
}
//update the games for the player as they have been absent for about 2 seconds, if they were reloading.
for (let j = 0; j < this._games.length; j++) {
this._users[this._users.length - 1].updateGameListing(
"Game " + (j + 1).toString(),
this._games[j].usernameColorPairs,
this._games[j].uid,
this._games[j].inPlay,
);
}
console.log("Player length on add: " + this._users.length);
return output;
}
private register(user: User, msg: string) {
if (!this._debugMode) {
if (user.cannotRegister) {
user.registrationError(
"You're already playing in a different tab, so you can't join again.",
);
return;
}
for (let i = 0; i < this._users.length; i++) {
if (this._users[i].inGame && this._users[i].session == user.session) {
user.send(
"You're already playing a game in a different tab, so you cannot join this one.",
undefined,
Colors.red,
);
user.banFromRegistering();
return;
}
}
}
let game = this.getGameById(user.gameClickedLast);
if (game != undefined) {
if (game.playersWanted == 0) {
user.send(
"This game is has already started, please join a different one.",
);
return;
}
}
msg = Server.cleanUpUsername(msg);
if (this.validateUsername(user, msg)) {
for (let i = 0; i < this._users.length; i++) {
if (this._users[i].registered) {
user.addPlayerToLobbyList(this._users[i].username);
}
}
user.setUsername(msg);
user.register();
for (let i = 0; i < this._users.length; i++) {
this._users[i].addPlayerToLobbyList(user.username);
}
}
}
public receiveLobbyMessage(id: string, msg: string) {
let user = this.getUser(id);
if (user instanceof User && user.registered) {
for (let i = 0; i < this._users.length; i++) {
this._users[i].lobbyMessage(
user.username + " : " + msg,
Colors.standardWhite,
);
}
this._lobbyChatCache.push([
{
text: user.username + " : " + msg,
color: Colors.standardWhite,
},
]);
if (this._lobbyChatCache.length > 50) {
this._lobbyChatCache.splice(0, 1);
}
}
}
public receive(id: string, msg: string) {
let user = this.getUser(id);
if (user != undefined) {
if (!user.registered) {
this.register(user, msg);
} else {
if (user.inGame) {
//if trying to sign in as admin
if (msg.slice(0, 1) == "!") {
if (user.verifyAsAdmin(msg)) {
user.send(
"You have been granted administrator access",
undefined,
Colors.green,
);
}
if (user.admin) {
if (user.game != undefined && user.game.isUser(id)) {
user.game.adminReceive(user, msg);
}
}
} else if (
msg[0] == "/" &&
user.game != undefined &&
!user.game.inPlay &&
user.startVote == false
) {
if (Utils.isCommand(msg, "/start")) {
user.startVote = true;
user.game.broadcast(
user.username +
' has voted to start the game immediately by typing "/start"',
);
}
} else if (user.game != undefined && this.validateMessage(msg)) {
msg = grawlix(msg, { style: "asterix" });
if (user.game.isUser(id)) {
user.game.receive(user, msg);
console.log("received by game");
}
}
}
}
} else {
console.log("Player: " + id.toString() + " is not defined");
}
}
public isUser(id: string): boolean {
for (let i = 0; i < this._users.length; i++) {
if (this._users[i].id == id) {
return true;
}
}
return false;
}
public getUser(id: string): User | undefined {
for (let i = 0; i < this._users.length; i++) {
if (this._users[i].id == id) {
return this._users[i];
}
}
console.log("Error: Server.getPlayer: No player found with given id");
return undefined;
}
private validateMessage(msg: string): boolean {
if (msg.trim() == "" || msg.length > 151) {
return false;
} else {
return true;
}
}
public markGameStatusInLobby(game: Game, status: string) {
for (let i = 0; i < this._users.length; i++) {
this._users[i].markGameStatusInLobby(game, status);
}
}
public listPlayerInLobby(username: string, color: Colors, game: Game) {
for (let i = 0; i < this._users.length; i++) {
this._users[i].addListingToGame(username, color, game);
//if the player is viewing the game, add joiner to their right bar
if (this._users[i].game != undefined && this._users[i].game == game) {
this._users[i].rightSend([{ text: username, color: color }]);
} else if (
!this._users[i].inGame &&
this._users[i].gameClickedLast == game.uid
) {
this._users[i].rightSend([{ text: username, color: color }]);
}
}
}
public unlistPlayerInLobby(username: string, game: Game) {
for (let i = 0; i < this._users.length; i++) {
this._users[i].removePlayerListingFromGame(username, game);
//if the player is viewing the game, remove leaver from their right bar
if (this._users[i].game == game) {
this._users[i].removeRight(username);
} else if (
!this._users[i].inGame &&
this._users[i].gameClickedLast == game.uid
) {
this._users[i].removeRight(username);
}
}
}
public removeSocketFromPlayer(id: string, socket: Socket) {
for (let i = 0; i < this._users.length; i++) {
if (this._users[i].id == id) {
this._users[i].removeSocket(socket);
}
}
}
public kick(id: string): void {
let user = this.getUser(id);
if (user instanceof User) {
//if player has no sockets (i.e no one is connected to this player)
if (user.socketCount == 0) {
let index = this._users.indexOf(user);
if (index !== -1) {
//if the player isn't in a game in play, remove them
if (!user.inGame || !user.registered) {
this._users.splice(index, 1)[0];
for (let i = 0; i < this._users.length; i++) {
this._users[i].removePlayerFromLobbyList(user.username);
}
} else if (
user.inGame &&
user.game != undefined &&
!user.game.inPlay
) {
for (let i = 0; i < this._users.length; i++) {
this._users[i].removePlayerFromLobbyList(user.username);
}
user.game.kick(user);
this._users.splice(index, 1)[0];
}
}
}
} else {
console.log(
"Error: Server.kick" +
": tried to kick player " +
"id" +
" but that player does not exist",
);
}
}
} | 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 PI extends Service {
/**
* Constructs a service object. This object has one method for each API operation.
*/
constructor(options?: PI.Types.ClientConfiguration)
config: Config & PI.Types.ClientConfiguration;
/**
* For a specific time period, retrieve the top N dimension keys for a metric.
*/
describeDimensionKeys(params: PI.Types.DescribeDimensionKeysRequest, callback?: (err: AWSError, data: PI.Types.DescribeDimensionKeysResponse) => void): Request<PI.Types.DescribeDimensionKeysResponse, AWSError>;
/**
* For a specific time period, retrieve the top N dimension keys for a metric.
*/
describeDimensionKeys(callback?: (err: AWSError, data: PI.Types.DescribeDimensionKeysResponse) => void): Request<PI.Types.DescribeDimensionKeysResponse, AWSError>;
/**
* Retrieve Performance Insights metrics for a set of data sources, over a time period. You can provide specific dimension groups and dimensions, and provide aggregation and filtering criteria for each group.
*/
getResourceMetrics(params: PI.Types.GetResourceMetricsRequest, callback?: (err: AWSError, data: PI.Types.GetResourceMetricsResponse) => void): Request<PI.Types.GetResourceMetricsResponse, AWSError>;
/**
* Retrieve Performance Insights metrics for a set of data sources, over a time period. You can provide specific dimension groups and dimensions, and provide aggregation and filtering criteria for each group.
*/
getResourceMetrics(callback?: (err: AWSError, data: PI.Types.GetResourceMetricsResponse) => void): Request<PI.Types.GetResourceMetricsResponse, AWSError>;
}
declare namespace PI {
export interface DataPoint {
/**
* The time, in epoch format, associated with a particular Value.
*/
Timestamp: ISOTimestamp;
/**
* The actual value associated with a particular Timestamp.
*/
Value: Double;
}
export type DataPointsList = DataPoint[];
export interface DescribeDimensionKeysRequest {
/**
* The AWS service for which Performance Insights will return metrics. The only valid value for ServiceType is: RDS
*/
ServiceType: ServiceType;
/**
* An immutable, AWS Region-unique identifier for a data source. Performance Insights gathers metrics from this data source. To use an Amazon RDS instance as a data source, you specify its DbiResourceId value - for example: db-FAIHNTYBKTGAUSUZQYPDS2GW4A
*/
Identifier: String;
/**
* The date and time specifying the beginning of the requested time series data. You can't specify a StartTime that's earlier than 7 days ago. The value specified is inclusive - data points equal to or greater than StartTime will be returned. The value for StartTime must be earlier than the value for EndTime.
*/
StartTime: ISOTimestamp;
/**
* The date and time specifying the end of the requested time series data. The value specified is exclusive - data points less than (but not equal to) EndTime will be returned. The value for EndTime must be later than the value for StartTime.
*/
EndTime: ISOTimestamp;
/**
* The name of a Performance Insights metric to be measured. Valid values for Metric are: db.load.avg - a scaled representation of the number of active sessions for the database engine. db.sampledload.avg - the raw number of active sessions for the database engine.
*/
Metric: String;
/**
* The granularity, in seconds, of the data points returned from Performance Insights. A period can be as short as one second, or as long as one day (86400 seconds). Valid values are: 1 (one second) 60 (one minute) 300 (five minutes) 3600 (one hour) 86400 (twenty-four hours) If you don't specify PeriodInSeconds, then Performance Insights will choose a value for you, with a goal of returning roughly 100-200 data points in the response.
*/
PeriodInSeconds?: Integer;
/**
* A specification for how to aggregate the data points from a query result. You must specify a valid dimension group. Performance Insights will return all of the dimensions within that group, unless you provide the names of specific dimensions within that group. You can also request that Performance Insights return a limited number of values for a dimension.
*/
GroupBy: DimensionGroup;
/**
* For each dimension specified in GroupBy, specify a secondary dimension to further subdivide the partition keys in the response.
*/
PartitionBy?: DimensionGroup;
/**
* One or more filters to apply in the request. Restrictions: Any number of filters by the same dimension, as specified in the GroupBy or Partition parameters. A single filter for any other dimension in this dimension group.
*/
Filter?: MetricQueryFilterMap;
/**
* The maximum number of items to return in the response. If more items exist than the specified MaxRecords value, a pagination token is included in the response so that the remaining results can be retrieved.
*/
MaxResults?: MaxResults;
/**
* An optional pagination token provided by a previous request. If this parameter is specified, the response includes only records beyond the token, up to the value specified by MaxRecords.
*/
NextToken?: String;
}
export interface DescribeDimensionKeysResponse {
/**
* The start time for the returned dimension keys, after alignment to a granular boundary (as specified by PeriodInSeconds). AlignedStartTime will be less than or equal to the value of the user-specified StartTime.
*/
AlignedStartTime?: ISOTimestamp;
/**
* The end time for the returned dimension keys, after alignment to a granular boundary (as specified by PeriodInSeconds). AlignedEndTime will be greater than or equal to the value of the user-specified Endtime.
*/
AlignedEndTime?: ISOTimestamp;
/**
* If PartitionBy was present in the request, PartitionKeys contains the breakdown of dimension keys by the specified partitions.
*/
PartitionKeys?: ResponsePartitionKeyList;
/**
* The dimension keys that were requested.
*/
Keys?: DimensionKeyDescriptionList;
/**
* An optional pagination token provided by a previous request. If this parameter is specified, the response includes only records beyond the token, up to the value specified by MaxRecords.
*/
NextToken?: String;
}
export interface DimensionGroup {
/**
* The name of the dimension group. Valid values are: db.user db.host db.sql db.sql_tokenized db.wait_event db.wait_event_type
*/
Group: String;
/**
* A list of specific dimensions from a dimension group. If this parameter is not present, then it signifies that all of the dimensions in the group were requested, or are present in the response. Valid values for elements in the Dimensions array are: db.user.id db.user.name db.host.id db.host.name db.sql.id db.sql.db_id db.sql.statement db.sql.tokenized_id db.sql_tokenized.id db.sql_tokenized.db_id db.sql_tokenized.statement db.wait_event.name db.wait_event.type db.wait_event_type.name
*/
Dimensions?: StringList;
/**
* The maximum number of items to fetch for this dimension group.
*/
Limit?: Limit;
}
export interface DimensionKeyDescription {
/**
* A map of name-value pairs for the dimensions in the group.
*/
Dimensions?: DimensionMap;
/**
* The aggregated metric value for the dimension(s), over the requested time range.
*/
Total?: Double;
/**
* If PartitionBy was specified, PartitionKeys contains the dimensions that were.
*/
Partitions?: MetricValuesList;
}
export type DimensionKeyDescriptionList = DimensionKeyDescription[];
export type DimensionMap = {[key: string]: String};
export type Double = number;
export interface GetResourceMetricsRequest {
/**
* The AWS service for which Performance Insights will return metrics. The only valid value for ServiceType is: RDS
*/
ServiceType: ServiceType;
/**
* An immutable, AWS Region-unique identifier for a data source. Performance Insights gathers metrics from this data source. To use an Amazon RDS instance as a data source, you specify its DbiResourceId value - for example: db-FAIHNTYBKTGAUSUZQYPDS2GW4A
*/
Identifier: String;
/**
* An array of one or more queries to perform. Each query must specify a Performance Insights metric, and can optionally specify aggregation and filtering criteria.
*/
MetricQueries: MetricQueryList;
/**
* The date and time specifying the beginning of the requested time series data. You can't specify a StartTime that's earlier than 7 days ago. The value specified is inclusive - data points equal to or greater than StartTime will be returned. The value for StartTime must be earlier than the value for EndTime.
*/
StartTime: ISOTimestamp;
/**
* The date and time specifiying the end of the requested time series data. The value specified is exclusive - data points less than (but not equal to) EndTime will be returned. The value for EndTime must be later than the value for StartTime.
*/
EndTime: ISOTimestamp;
/**
* The granularity, in seconds, of the data points returned from Performance Insights. A period can be as short as one second, or as long as one day (86400 seconds). Valid values are: 1 (one second) 60 (one minute) 300 (five minutes) 3600 (one hour) 86400 (twenty-four hours) If you don't specify PeriodInSeconds, then Performance Insights will choose a value for you, with a goal of returning roughly 100-200 data points in the response.
*/
PeriodInSeconds?: Integer;
/**
* The maximum number of items to return in the response. If more items exist than the specified MaxRecords value, a pagination token is included in the response so that the remaining results can be retrieved.
*/
MaxResults?: MaxResults;
/**
* An optional pagination token provided by a previous request. If this parameter is specified, the response includes only records beyond the token, up to the value specified by MaxRecords.
*/
NextToken?: String;
}
export interface GetResourceMetricsResponse {
/**
* The start time for the returned metrics, after alignment to a granular boundary (as specified by PeriodInSeconds). AlignedStartTime will be less than or equal to the value of the user-specified StartTime.
*/
AlignedStartTime?: ISOTimestamp;
/**
* The end time for the returned metrics, after alignment to a granular boundary (as specified by PeriodInSeconds). AlignedEndTime will be greater than or equal to the value of the user-specified Endtime.
*/
AlignedEndTime?: ISOTimestamp;
/**
* An immutable, AWS Region-unique identifier for a data source. Performance Insights gathers metrics from this data source. To use an Amazon RDS instance as a data source, you specify its DbiResourceId value - for example: db-FAIHNTYBKTGAUSUZQYPDS2GW4A
*/
Identifier?: String;
/**
* An array of metric results,, where each array element contains all of the data points for a particular dimension.
*/
MetricList?: MetricKeyDataPointsList;
/**
* An optional pagination token provided by a previous request. If this parameter is specified, the response includes only records beyond the token, up to the value specified by MaxRecords.
*/
NextToken?: String;
}
export type ISOTimestamp = Date;
export type Integer = number;
export type Limit = number;
export type MaxResults = number;
export interface MetricKeyDataPoints {
/**
* The dimension(s) to which the data points apply.
*/
Key?: ResponseResourceMetricKey;
/**
* An array of timestamp-value pairs, representing measurements over a period of time.
*/
DataPoints?: DataPointsList;
}
export type MetricKeyDataPointsList = MetricKeyDataPoints[];
export interface MetricQuery {
/**
* The name of a Performance Insights metric to be measured. Valid values for Metric are: db.load.avg - a scaled representation of the number of active sessions for the database engine. db.sampledload.avg - the raw number of active sessions for the database engine.
*/
Metric: String;
/**
* A specification for how to aggregate the data points from a query result. You must specify a valid dimension group. Performance Insights will return all of the dimensions within that group, unless you provide the names of specific dimensions within that group. You can also request that Performance Insights return a limited number of values for a dimension.
*/
GroupBy?: DimensionGroup;
/**
* One or more filters to apply in the request. Restrictions: Any number of filters by the same dimension, as specified in the GroupBy parameter. A single filter for any other dimension in this dimension group.
*/
Filter?: MetricQueryFilterMap;
}
export type MetricQueryFilterMap = {[key: string]: String};
export type MetricQueryList = MetricQuery[];
export type MetricValuesList = Double[];
export interface ResponsePartitionKey {
/**
* A dimension map that contains the dimension(s) for this partition.
*/
Dimensions: DimensionMap;
}
export type ResponsePartitionKeyList = ResponsePartitionKey[];
export interface ResponseResourceMetricKey {
/**
* The name of a Performance Insights metric to be measured. Valid values for Metric are: db.load.avg - a scaled representation of the number of active sessions for the database engine. db.sampledload.avg - the raw number of active sessions for the database engine.
*/
Metric: String;
/**
* The valid dimensions for the metric.
*/
Dimensions?: DimensionMap;
}
export type ServiceType = "RDS"|string;
export type String = string;
export type StringList = 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 = "2018-02-27"|"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 PI client.
*/
export import Types = PI;
}
export = PI; | the_stack |
import { PivotEngine, IDataOptions, IDataSet, IAxisSet, IPageSettings, ICustomProperties } from '../../src/base/engine';
import { pivot_dataset, pivot_undefineddata } from '../base/datasource.spec';
import { PivotUtil } from '../../src/base/util';
import { profile, inMB, getMemoryProfile } from '../common.spec';
describe('PivotView spec', () => {
/**
* Test case for PivotEngine
*/
describe('PivotEngine population', () => {
let pivotDataset: IDataSet[] = [
{ Amount: 100, Country: 'Canada', Date: 'FY 2005', Product: 'Bike', State: 'Califo' },
{ Amount: 200, Country: 'Canada', Date: 'FY 2006', Product: 'Van', State: 'Miyar' },
{ Amount: 100, Country: 'Canada', Date: 'FY 2005', Product: 'Tempo', State: 'Tada' },
{ Amount: 200, Country: 'Canada', Date: 'FY 2005', Product: 'Van', State: 'Basuva' }
];
beforeAll(() => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
});
describe('Check the Field List information', () => {
let dataSourceSettings: IDataOptions = {
dataSource: pivotDataset, rows: [{ name: 'Product' }],
columns: [{ name: 'Date' }], values: [{ name: 'Amount' }], filters: [{ name: 'State' }]
};
let pivotEngine: PivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
it('Ensure the field list data', () => {
expect(pivotEngine.fieldList).toBeTruthy;
});
it('String node type', () => {
expect(pivotEngine.fieldList.Country.type === 'string').toBeTruthy;
});
it('Number node type', () => {
expect(pivotEngine.fieldList.Amount.type === 'number').toBeTruthy;
});
it('Default sorting type of node', () => {
expect(pivotEngine.fieldList.Country.sort === 'Ascending').toBeTruthy;
});
});
describe('Initial data binding', () => {
let ds: IDataSet[] = pivot_dataset as IDataSet[];
let dataSourceSettings: IDataOptions = {
//filterSettings: [{ name: 'Date', type: 'exclude', items: ['FY 2006']}, {name: 'gender', type: 'include', items: ['Canada']}],
drilledMembers: [{ name: 'state', items: ['New Jercy'] }],
dataSource: ds,
rows: [{ name: 'company' }, { name: 'state' }],
columns: [{ name: 'name' }],
values: [{ name: 'balance' },
{ name: 'quantity' }], filters: [{ name: 'gender' }]
};
let pivotEngine: PivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
it('Ensure the initial biding', () => {
expect(pivotEngine.pivotValues.length).toBe(423);
expect(pivotEngine.pivotValues[2].length).toBe(843);
});
it('Ensure the initial biding with empty row', () => {
dataSourceSettings = {
dataSource: ds
};
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
expect(pivotEngine.pivotValues.length).toBe(2);
expect(pivotEngine.pivotValues[0].length).toBe(1);
});
});
describe('Sort settings', () => {
let ds: IDataSet[] = pivot_dataset as IDataSet[];
let dataSourceSettings: IDataOptions = {
sortSettings: [{ name: 'company', order: 'Descending' }],
dataSource: ds,
rows: [{ name: 'company' }, { name: 'state' }],
columns: [{ name: 'name' }],
values: [{ name: 'balance' },
{ name: 'quantity' }], filters: [{ name: 'gender' }]
};
let pivotEngine: PivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
it('company in decending order', () => {
expect((pivotEngine.pivotValues[2][0] as IDataSet).actualText).toBe('ZYTREX');
});
it('Disable the default sorting', () => {
dataSourceSettings.enableSorting = false;
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
expect((pivotEngine.pivotValues[3][0] as IDataSet).actualText).toBe('ICOLOGY');
});
it('Sorting with unavailable field', () => {
dataSourceSettings.sortSettings = [{ name: 'test', order: 'Descending' }];
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
expect((pivotEngine.pivotValues[3][0] as IDataSet).actualText).toBe('ICOLOGY');
});
it('Drilled members with unavailable field', () => {
dataSourceSettings.drilledMembers = [{ name: 'test', items: ['test', 'ACRUEX'] }];
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
expect((pivotEngine.pivotValues[3][0] as IDataSet).actualText).toBe('ICOLOGY');
});
});
describe('Expand all', () => {
let ds: IDataSet[] = pivot_dataset as IDataSet[];
let dataSourceSettings: IDataOptions = {
expandAll: false,
dataSource: ds,
rows: [{ name: 'company' }, { name: 'state' }],
columns: [{ name: 'name' }, { name: 'gender' }],
values: [{ name: 'balance' },
{ name: 'quantity' }], filters: [{ name: 'gender' }]
};
let timeStamp1: number = new Date().getTime();
let pivotEngine: PivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
let timeStamp2: number = new Date().getTime();
timeStamp1 = timeStamp2 - timeStamp1;
it('Expand all members', () => {
expect(pivotEngine.pivotValues.length === 1338 && pivotEngine.pivotValues[0].length === 3130).toBeTruthy;
});
it('Performance metrics', () => {
let timeStamp1: number = new Date().getTime();
let pivotEngine: PivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
let timeStamp2: number = new Date().getTime();
timeStamp1 = timeStamp2 - timeStamp1;
dataSourceSettings.expandAll = false;
let ctimeStamp1: number = new Date().getTime();
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
let ctimeStamp2: number = new Date().getTime();
ctimeStamp1 = ctimeStamp2 - ctimeStamp1;
expect(timeStamp1 < 1900 && ctimeStamp1 < 640).toBeTruthy;
});
});
describe('Number Format on value field', () => {
let ds: IDataSet[] = pivot_dataset as IDataSet[];
let dataSourceSettings: IDataOptions = {
expandAll: false,
formatSettings: [{ format: 'P2', name: 'balance', useGrouping: true },
{ name: 'quantity', skeleton: 'Ehms', type: 'date' }],
dataSource: ds,
rows: [{ name: 'state' }],
columns: [{ name: 'product' }],
values: [{ name: 'balance' }, { name: 'advance' },
{ name: 'quantity' }], filters: [{ name: 'gender' }]
};
let pivotEngine: PivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
it('For Percentage', () => {
expect((pivotEngine.pivotValues[2][1] as IDataSet).formattedText).toBe('2,146,222.00%');
expect((pivotEngine.pivotValues[3][1] as IDataSet).formattedText).toBe('2,894,924.00%');
});
it('For date/time/date-time', () => {
expect((pivotEngine.pivotValues[2][3] as IDataSet).value).toBe(126);
expect((pivotEngine.pivotValues[3][3] as IDataSet).value).toBe(178);
});
it('Without format', () => {
expect((pivotEngine.pivotValues[2][2] as IDataSet).formattedText).toBe('50089');
expect((pivotEngine.pivotValues[3][2] as IDataSet).formattedText).toBe('70839');
});
it('Format with unavailable field', () => {
dataSourceSettings.formatSettings = [{ format: 'P2', name: 'test', useGrouping: true }];
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
expect((pivotEngine.pivotValues[2][2] as IDataSet).formattedText).toBe('50089');
expect((pivotEngine.pivotValues[3][2] as IDataSet).formattedText).toBe('70839');
});
describe('With decimal separation', () => {
let ds: IDataSet[] = pivot_dataset as IDataSet[];
let dataSourceSettings: IDataOptions = {
expandAll: false,
formatSettings: [{ format: 'N2', name: 'balance' },
{ format: '$ ###.00', name: 'advance' }],
dataSource: ds,
rows: [{ name: 'state' }],
columns: [{ name: 'product' }],
values: [{ name: 'balance' }, { name: 'advance' },
{ name: 'quantity' }], filters: [{ name: 'gender' }]
};
let pivotEngine: PivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
it('For Numeric separation', () => {
expect((pivotEngine.pivotValues[2][1] as IDataSet).formattedText).toBe('21,462.22');
expect((pivotEngine.pivotValues[3][1] as IDataSet).formattedText).toBe('28,949.24');
});
it('For custom format with curreny', () => {
expect((pivotEngine.pivotValues[2][3] as IDataSet).formattedText).toBe('126');
expect((pivotEngine.pivotValues[3][3] as IDataSet).formattedText).toBe('178');
});
});
describe('With date and time', () => {
let ds: IDataSet[] = pivot_dataset as IDataSet[];
let dataSourceSettings: IDataOptions = {
expandAll: false,
formatSettings: [{ name: 'balance', skeleton: 'medium', type: 'date' },
{ name: 'advance', skeleton: 'short', type: 'time' },
{ name: 'quantity', format: 'dd/MM/yyyy-hh:mm', type: 'date' }],
dataSource: ds,
rows: [{ name: 'state' }],
columns: [{ name: 'product' }],
values: [{ name: 'balance' }, { name: 'advance' },
{ name: 'quantity' }],
filters: [{ name: 'gender' }]
};
let pivotEngine: PivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
it('For Date', () => {
expect((pivotEngine.pivotValues[2][1] as IDataSet).formattedText).toBe('Jan 1, 1970');
expect((pivotEngine.pivotValues[3][1] as IDataSet).formattedText).toBe('Jan 1, 1970');
});
it('For Time', () => {
expect((pivotEngine.pivotValues[2][2] as IDataSet).value).toBe(50089);
expect((pivotEngine.pivotValues[3][2] as IDataSet).value).toBe(70839);
});
it('For DateTime', () => {
expect((pivotEngine.pivotValues[2][3] as IDataSet).value).toBe(126);
expect((pivotEngine.pivotValues[3][3] as IDataSet).value).toBe(178);
});
});
});
describe('Number Format on row/column field', () => {
let ds: IDataSet[] = pivot_dataset as IDataSet[];
let dataSourceSettings: IDataOptions = {
expandAll: false,
formatSettings: [{ format: 'P2', name: 'balance', useGrouping: true },
{ name: 'quantity', skeleton: 'Ehms', type: 'date' }],
dataSource: ds,
rows: [{ name: 'quantity' }],
columns: [{ name: 'product' }],
values: [{ name: 'balance' }, { name: 'advance' },
], filters: [{ name: 'gender' }]
};
let pivotEngine: PivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
it('Date/time/date-time format', () => {
expect(((pivotEngine.pivotValues[2][0] as IDataSet).dateText.toString()).indexOf('1970/01/01/')).toBeGreaterThanOrEqual(0);
});
it('Percentage format', () => {
dataSourceSettings.rows = [{ name: 'state' }];
dataSourceSettings.columns = [{ name: 'balance' }];
dataSourceSettings.values = [{ name: 'advance' }, { name: 'quantity' }];
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
expect((pivotEngine.pivotValues[0][1] as IDataSet).formattedText).toBe('1015.32');
});
describe('With custom date and time', () => {
let ds: IDataSet[] = pivot_dataset as IDataSet[];
let dataSourceSettings: IDataOptions = {
expandAll: false,
formatSettings: [{ name: 'balance', skeleton: 'medium', type: 'date' },
{ name: 'advance', skeleton: 'short', type: 'time' },
{ name: 'quantity', skeleton: 'yMEd', type: 'date' },
{ name: 'date', format: '\'year:\'y \'month:\' MM', type: 'date' }
],
dataSource: ds,
rows: [{ name: 'quantity' }],
columns: [{ name: 'date' }],
values: [{ name: 'balance' }, { name: 'advance' },
],
filters: [{ name: 'gender' }]
};
let pivotEngine: PivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
it('For custom format', () => {
expect((pivotEngine.pivotValues[0][1] as IDataSet).formattedText).toBe('year:1970 month: 01');
expect((pivotEngine.pivotValues[0][3] as IDataSet).formattedText).toBe('year:1970 month: 02');
});
it('For additional format', () => {
expect((pivotEngine.pivotValues[2][0] as IDataSet).formattedText).toBe('Thu, 1/1/1970');
expect((pivotEngine.pivotValues[3][0] as IDataSet).formattedText).toBe('Thu, 1/1/1970');
});
});
});
describe('Paging', () => {
let ds: IDataSet[] = pivot_dataset as IDataSet[];
let dataSourceSettings: IDataOptions = {
dataSource: ds,
rows: [{ name: 'company' }],
columns: [{ name: 'name' }],
values: [{ name: 'balance' }, { name: 'quantity' }],
};
let pivotEngine: PivotEngine;
let pageSettings: IPageSettings = {
columnSize: 2,
rowSize: 2,
columnCurrentPage: 1,
rowCurrentPage: 1
};
let customProperties: ICustomProperties = {
mode: '',
savedFieldList: undefined,
pageSettings: pageSettings,
enableValueSorting: undefined,
isDrillThrough: undefined,
localeObj: undefined
};
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings, customProperties);
it('Ensure the page data', () => {
expect(pivotEngine.pivotValues.length === 8 && pivotEngine.pivotValues[2].length === 7).toBeTruthy;
});
it('Ensure the row data', () => {
expect((pivotEngine.pivotValues[2][0] as IAxisSet).formattedText === "ACCEL").toBeTruthy;
});
it('Ensure the column data', () => {
expect((pivotEngine.pivotValues[0][1] as IAxisSet).formattedText === "Abigail Petty").toBeTruthy;
});
it('Ensure the page data', () => {
let pageSettings: IPageSettings = {
columnSize: 4,
rowSize: 4,
columnCurrentPage: 2,
rowCurrentPage: 2
};
let customProperties: ICustomProperties = {
mode: '',
savedFieldList: undefined,
pageSettings: pageSettings,
enableValueSorting: undefined,
isDrillThrough: undefined,
localeObj: undefined
};
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings, customProperties);
expect(pivotEngine.pivotValues.length === 15 && pivotEngine.pivotValues[2].length === 15).toBeTruthy;
});
});
describe('ValueSorting', () => {
let ds: IDataSet[] = pivot_dataset as IDataSet[];
let dataSourceSettings: IDataOptions = {
dataSource: pivot_dataset as IDataSet[],
expandAll: false,
enableSorting: true,
allowMemberFilter: true,
sortSettings: [{ name: 'state', order: 'Descending' }],
formatSettings: [{ name: 'balance', format: 'C' }],
filterSettings: [
{
name: 'state', type: 'Include',
items: ['Delhi', 'Tamilnadu', 'New Jercy']
}
],
rows: [{ name: 'state' }, { name: 'product' }],
columns: [{ name: 'eyeColor' }],
values: [{ name: 'balance' }, { name: 'quantity' }],
valueSortSettings: {
headerText: 'Grand Total##balance',
headerDelimiter: '##',
sortOrder: 'Ascending'
}
};
let pivotEngine: PivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
it("Ensure the ascending data", () => {
expect((pivotEngine.pivotValues[2][0] as IDataSet).formattedText).toBe("Tamilnadu");
});
it("Ensure the descending data", () => {
dataSourceSettings.rows = [{ name: 'state' }, { name: 'product' }, { name: 'gender' }];
dataSourceSettings.valueSortSettings.sortOrder = 'Descending';
dataSourceSettings.expandAll = true;
let customProperties: ICustomProperties = {
savedFieldList: undefined,
enableValueSorting: true,
isDrillThrough: undefined,
localeObj: undefined
};
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings, customProperties);
expect((pivotEngine.pivotValues[2][0] as IDataSet).formattedText).toBe("New Jercy");
});
it("Ensure the sort data while single measure", () => {
dataSourceSettings.values.pop();
dataSourceSettings.valueSortSettings.headerText = "Grand Total";
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
expect((pivotEngine.pivotValues[2][0] as IDataSet).formattedText).toBe("Bike");
});
it("Value sorting with unavailable header", () => {
dataSourceSettings.valueSortSettings.headerText = "test";
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
expect((pivotEngine.pivotValues[2][0] as IDataSet).formattedText).toBe("Bike");
});
});
describe('enable/disable ValueSorting', () => {
let ds: IDataSet[] = pivot_dataset as IDataSet[];
let dataSourceSettings: IDataOptions = {
dataSource: pivot_dataset as IDataSet[],
expandAll: false,
enableSorting: true,
allowMemberFilter: true,
sortSettings: [{ name: 'state', order: 'Descending' }],
formatSettings: [{ name: 'balance', format: 'C' }],
filterSettings: [
{
name: 'state', type: 'Include',
items: ['Delhi', 'Tamilnadu', 'New Jercy']
}
],
rows: [{ name: 'state' }, { name: 'product' }],
columns: [{ name: 'eyeColor' }],
values: [{ name: 'balance' }, { name: 'quantity' }]
};
let customProperties: ICustomProperties = {
mode: '',
savedFieldList: undefined,
enableValueSorting: false,
isDrillThrough: undefined,
localeObj: undefined
};
let pivotEngine: PivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings, customProperties);
it("Disable value sorting", () => {
expect((pivotEngine.pivotValues[3][0] as IDataSet).formattedText).toBe("Delhi");
});
customProperties = {
mode: '',
savedFieldList: undefined,
enableValueSorting: true,
isDrillThrough: undefined,
localeObj: undefined
};
dataSourceSettings.valueSortSettings = {
headerText: 'Grand Total##balance',
headerDelimiter: '##',
sortOrder: 'Ascending'
};
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings, customProperties);
it("Ensure the Ascending data", () => {
expect((pivotEngine.pivotValues[2][0] as IDataSet).formattedText).toBe("New Jercy");
});
dataSourceSettings.valueSortSettings = {
headerText: 'Grand Total##balance',
headerDelimiter: '##',
sortOrder: 'Descending'
};
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings, customProperties);
it("Ensure the descending data ", () => {
expect((pivotEngine.pivotValues[3][0] as IDataSet).actualText).toBe("Delhi");
});
});
describe('exclude fields from fieldlist', () => {
let ds: IDataSet[] = pivot_dataset as IDataSet[];
let dataSourceSettings: IDataOptions = {
dataSource: pivot_dataset as IDataSet[],
expandAll: false,
enableSorting: true,
allowMemberFilter: true,
excludeFields: ['age', 'advance', 'guid', 'index', 'pno', 'phone', 'email'],
sortSettings: [{ name: 'state', order: 'Descending' }],
formatSettings: [{ name: 'balance', format: 'C' }],
filterSettings: [
{
name: 'state', type: 'Include',
items: ['Delhi', 'Tamilnadu', 'New Jercy']
}
],
rows: [{ name: 'state' }, { name: 'product' }],
columns: [{ name: 'eyeColor' }],
values: [{ name: 'balance' }, { name: 'quantity' }],
filters: []
};
let customProperties: ICustomProperties = {
mode: '',
savedFieldList: undefined,
enableValueSorting: true,
isDrillThrough: undefined,
localeObj: undefined
};
let pivotEngine: PivotEngine;
it("Ensure fields excluded from fieldlist", () => {
dataSourceSettings.excludeFields = ['age', 'advance', 'guid', 'index', 'pno', 'phone', 'email'];
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
expect((pivotEngine.fields.length)).toBeLessThanOrEqual(12);
});
it("Ensure exclude fields empty", () => {
dataSourceSettings.excludeFields = [];
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
expect((pivotEngine.fields.length)).toBeLessThanOrEqual(18);
});
it("add fields to exclude fields", () => {
dataSourceSettings.excludeFields = ['pno', 'email', 'guid'];
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
expect((pivotEngine.fields.length)).toBeGreaterThanOrEqual(15);
});
it("add fields to row and exclude fields", () => {
dataSourceSettings.excludeFields = ['pno', 'email', 'advance', 'phone'];
dataSourceSettings.rows = [{ name: 'state' }, { name: 'product' }, { name: 'pno' }];
dataSourceSettings.columns = [{ name: 'eyeColor' }, { name: 'email' }]
dataSourceSettings.values = [{ name: 'balance' }, { name: 'quantity' }, { name: 'advance' }],
dataSourceSettings.filters = [{ name: 'phone' }]
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
expect((pivotEngine.fields.length)).toBeGreaterThanOrEqual(14);
});
});
describe('Hide blank members', () => {
let ds: IDataSet[] = pivot_dataset as IDataSet[];
let dataSourceSettings: IDataOptions = {
dataSource: pivot_undefineddata as IDataSet[],
expandAll: false,
rows: [{ name: 'Country' }, { name: 'State' }],
columns: [{ name: 'Product' }, { name: 'Date' }],
values: [{ name: 'Amount' }, { name: 'Quantity' }],
showHeaderWhenEmpty: false,
allowMemberFilter: true,
allowLabelFilter: true,
allowValueFilter: true
};
let customProperties: ICustomProperties = {
mode: '',
savedFieldList: undefined,
enableValueSorting: false,
isDrillThrough: undefined,
localeObj: undefined
};
let pivotEngine: PivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings, customProperties);
it("Ensure initial rendering", () => {
expect((pivotEngine.pivotValues[3][0] as IDataSet).formattedText).toBe("Canada");
customProperties = {
mode: '',
savedFieldList: undefined,
enableValueSorting: true,
isDrillThrough: undefined,
localeObj: undefined
};
dataSourceSettings.valueSortSettings = {
headerText: 'Grand Total##Amount',
headerDelimiter: '##',
sortOrder: 'Ascending'
};
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings, customProperties);
});
it("With value sorting - Ascending", () => {
expect((pivotEngine.pivotValues[3][0] as IDataSet).actualText).toBe("United Kingdom");
dataSourceSettings.valueSortSettings = {
headerText: 'Grand Total##Amount',
headerDelimiter: '##',
sortOrder: 'Descending'
};
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings, customProperties);
});
it("With value sorting - Descending", () => {
expect((pivotEngine.pivotValues[3][0] as IDataSet).formattedText).toBe("United States");
dataSourceSettings.expandAll = true;
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings, customProperties);
});
it("Expand All", () => {
expect((pivotEngine.pivotValues[23][0] as IDataSet).hasChild).toBeFalsy;
dataSourceSettings.excludeFields = ['State', 'Date'];
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings, customProperties);
});
it("Exclude Fields", () => {
expect((pivotEngine.pivotValues[3][0] as IDataSet).hasChild).toBeFalsy;
dataSourceSettings.excludeFields = [];
dataSourceSettings.calculatedFieldSettings = [{ name: 'Total', formula: '"Sum(Amount)"+"Sum(Quantity)"' }];
dataSourceSettings.values = [{ name: 'Amount' }, { name: 'Quantity' }, { name: 'Total' }];
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings, customProperties);
});
it("Calculated Field", () => {
expect((pivotEngine.pivotValues[3][0] as IDataSet).hasChild).toBeFalsy;
dataSourceSettings.filterSettings = [{ name: 'Country', type: 'Value', condition: 'GreaterThan', value1: '500', measure: 'Amount' }];
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings, customProperties);
});
it('With value filters', () => {
expect(pivotEngine.pivotValues.length).toBe(6);
dataSourceSettings.filterSettings = [{ name: 'Product', type: 'Label', condition: 'Equals', value1: 'Van' }];
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings, customProperties);
});
it('With label filters', () => {
expect(pivotEngine.pivotValues.length).toBe(6);
dataSourceSettings.filterSettings = [{ name: 'Country', type: 'Include', items: ['France', 'Germany'] }];
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings, customProperties);
});
it('With Include filter', () => {
expect(pivotEngine.pivotValues.length).toBe(5);
dataSourceSettings.filterSettings = [{ name: 'Country', type: 'Exclude', items: ['France', 'Germany'] }];
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings, customProperties);
});
it('With Exclude filter', () => {
expect(pivotEngine.pivotValues.length).toBe(6);
dataSourceSettings.enableSorting = true;
dataSourceSettings.sortSettings = [{ name: 'Product', order: 'Descending' }];
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings, customProperties);
});
it('With sorting enabled', () => {
expect(pivotEngine.pivotValues.length).toBe(6);
dataSourceSettings.columns[0] = { name: 'Product', showNoDataItems: true };
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings, customProperties);
});
it('No data', () => {
expect(pivotEngine.pivotValues.length).toBe(6);
dataSourceSettings.filterSettings = [];
let customProperties: ICustomProperties = {
mode: '',
savedFieldList: undefined,
enableValueSorting: false,
isDrillThrough: undefined,
localeObj: undefined,
pageSettings: {
columnCurrentPage: 1,
rowCurrentPage: 1,
columnSize: 1,
rowSize: 1
}
};
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings, customProperties);
});
it('Virtual Scrolling', () => {
expect(pivotEngine.pivotValues.length).toBe(5);
});
});
});
/**
* Test case for common utility
*/
describe('Common Util', () => {
describe('Relational data handling', () => {
it('To check getType method - datetime', () => {
new PivotUtil();
let date: Date = new Date();
expect(PivotUtil.getType(date)).toEqual('datetime');
});
it('To check getType method - date', () => {
let date: Date = new Date();
date = new Date(date.toDateString());
expect(PivotUtil.getType(date)).toEqual('date');
});
});
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange);
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile());
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
});
}); | the_stack |
import $ from "jquery";
import React from "react";
//@ts-ignore
import dt from "datatables.net";
//@ts-ignore
import dtBs4 from "datatables.net-bs4";
//@ts-ignore
import dtReorder from "datatables.net-colreorder";
//@ts-ignore
import dtReorderBs4 from "datatables.net-colreorder-bs4";
//@ts-ignore
import dtButtons from "datatables.net-buttons";
//@ts-ignore
import dtButtonsBs4 from "datatables.net-buttons-bs4";
dt(window, $);
dtBs4(window, $);
dtReorder(window, $);
dtReorderBs4(window, $);
dtButtons(window, $);
dtButtonsBs4(window, $);
import { Datapoint } from "./types";
import style from "./hiplot.scss";
import { HiPlotPluginData } from "./plugin";
import _ from "underscore";
import { FilterType } from "./filters";
interface RowsDisplayTableState {
};
// DISPLAYS_DATA_DOC_BEGIN
// Corresponds to values in the dict of `exp.display_data(hip.Displays.TABLE)`
export interface TableDisplayData {
// Hidden columns, that won't appear in the table
hide: Array<string>;
// Default ordering of the rows in the table.
// To order by `loss` for instance, set it to [['loss', 'desc']]
order_by: Array<[string /* column name */, string /* "asc" or "desc" */]>;
// Ordering of the columns
order?: Array<string>;
};
// DISPLAYS_DATA_DOC_END
interface TablePluginProps extends HiPlotPluginData, TableDisplayData {
};
export class RowsDisplayTable extends React.Component<TablePluginProps, RowsDisplayTableState> {
table_ref: React.RefObject<HTMLTableElement> = React.createRef();
table_container: React.RefObject<HTMLDivElement> = React.createRef();
dt = null;
ordered_cols: Array<string> = [];
empty: boolean;
setSelected_debounced = _.debounce(this.setSelected, 150);
static defaultProps = {
hide: [],
order_by: [['uid', 'asc']],
};
constructor(props: TablePluginProps) {
super(props);
this.state = {};
}
componentDidMount() {
this.mountDt();
}
mountDt() {
if (!this.props.params_def["uid"]) {
return;
}
const dom = $(this.table_ref.current);
this.ordered_cols = ['uid'];
const me = this;
$.each(this.props.params_def, function(k: string, def) {
if (k == 'uid') {
return;
}
me.ordered_cols.push(k);
});
if (me.props.order) {
const columnOrderScore = function(col: string) {
const index = me.props.order.indexOf(col);
if (index == -1) {
return me.props.order.length;
}
return index;
}
me.ordered_cols.sort(function(a, b) {
// Return negative if `a` comes first
return columnOrderScore(a) - columnOrderScore(b);
});
}
me.ordered_cols.unshift('');
const uidColIndex = me.ordered_cols.indexOf('uid');
dom.empty();
var columns: Array<{[k: string]: any}> = this.ordered_cols.map(function(x) {
const pd = me.props.params_def[x];
return {
'title': x == '' ? '' : $("<span />").attr("class", pd.label_css).html(pd.label_html)[0].outerHTML,
'defaultContent': 'null',
'type': x == '' ? 'html' : (pd.numeric ? "num" : "string"),
'visible': !me.props.hide || !me.props.hide.includes(x),
'orderable': x != '', // Don't allow to sort by color
};
});
const order_by = this.props.order_by.map(function(col_otype: [string, string]): [number, string] {
const col_idx = me.ordered_cols.indexOf(col_otype[0]);
console.assert(
col_idx >= 0,
`TABLE: Column for ordering ${col_otype[0]} does not exist. Available columns: ${me.ordered_cols.join(",")}`
);
return [col_idx, col_otype[1]];
});
columns[0]['render'] = function(data, type, row, meta) {
if (!me.dt) {
return '';
}
const individualUidColIdx = me.dt.colReorder.order().indexOf(uidColIndex);
const color = me.props.get_color_for_row(me.props.dp_lookup[row[individualUidColIdx]], 1.0);
return `<span class="${style.colorBlock}" style="background-color: ${color}" />`;
};
this.dt = dom.DataTable({
columns: columns,
data: [],
order: order_by,
deferRender: true, // Create HTML elements only when displayed
headerCallback: function headerCallback(thead: HTMLTableRowElement, data: Array<Array<any>>, start: number, end: number, display) {
Array.from(thead.cells).forEach(function(th: HTMLElement, i) {
const col = th.innerText;
if (col != '' && me.dt === null && me.props.context_menu_ref !== undefined) {
th.addEventListener('contextmenu', e => {
me.props.context_menu_ref.current.show(e.pageX, e.pageY, col);
e.preventDefault();
e.stopPropagation();
});
}
});
},
//@ts-ignore
buttons: [
{
text: 'Select results',
className: 'btn-sm btn-outline-primary d-none',
action: this.setSelectedToSearchResult.bind(this)
}
],
//@ts-ignore
colReorder: true,
});
const btnsContainer = $(this.table_container.current).find('.col-md-6:eq(1)');
btnsContainer.addClass("btn-group");
this.dt.buttons().container().appendTo(btnsContainer);
btnsContainer.find(".dt-buttons").removeClass("btn-group");
dom.on( 'search.dt', function (this: RowsDisplayTable) {
if (!this.dt) {
return;
}
const node = this.dt.buttons()[0].node;
node.classList.remove("d-none");
node.classList.remove("btn-secondary");
const searchResults = this.dt.rows( { filter : 'applied'} );
if (this.dt.search() == "" || searchResults.nodes().length == 0) {
node.classList.add("d-none");
}
}.bind(this));
this.empty = true;
dom.find('tbody')
.on('mouseenter', 'td', function () {
if (!me.dt || me.empty) {
return;
}
const rowIdx = me.dt.cell(this).index().row;
const row = me.dt.row(rowIdx);
const individualUidColIdx = me.dt.colReorder.order().indexOf(uidColIndex);
dom.find(`.table-primary`).removeClass("table-primary");
$(row.nodes()).addClass("table-primary");
me.props.setHighlighted([me.props.dp_lookup[row.data()[individualUidColIdx]]]);
})
.on("mouseout", "td", function() {
if (!me.dt || me.empty) {
return;
}
const rowIdx = me.dt.cell(this).index().row;
$(me.dt.row(rowIdx).nodes()).removeClass("table-primary");
me.props.setHighlighted([]);
});
me.setSelected(me.props.rows_selected);
}
componentDidUpdate(prevProps: HiPlotPluginData): void {
/* Sometimes we need to redraw the entire table
* but this is super expensive, so let's do it only if
* strictly necessary
* aka when changing `numeric` status of a column
* or when we add/remove columns
*/
var shouldRemountTable = false;
if (prevProps.params_def != this.props.params_def) {
const k1: string[] = Object.keys(prevProps.params_def);
const k2: string[] = Object.keys(this.props.params_def);
k1.sort();
k2.sort();
if (k1.length != k2.length) {
shouldRemountTable = true;
}
else {
for (var i = 0; i < k1.length; ++i) {
if (k1[i] != k2[i] ||
prevProps.params_def[k1[i]].numeric != this.props.params_def[k2[i]].numeric) {
shouldRemountTable = true;
break;
}
}
}
}
if (shouldRemountTable) {
this.destroyDt();
this.mountDt();
}
else if (// Rows changed
prevProps.rows_selected != this.props.rows_selected ||
// Color changed - need redraw with the correct color
prevProps.colorby != this.props.colorby ||
// Color scale changed - need redraw with the correct color
prevProps.params_def != this.props.params_def
) {
this.setSelected_debounced(this.props.rows_selected);
}
}
setSelectedToSearchResult() {
const dt = this.dt;
if (!dt) {
return;
}
const searchResults = dt.rows( { filter : 'applied'} );
const uidIdx = this.ordered_cols.indexOf("uid");
var searchResultsDatapoints = [];
$.each(searchResults.data(), function(index, value) {
searchResultsDatapoints.push(this.props.dp_lookup[value[uidIdx]]);
}.bind(this));
var filter = {
type: FilterType.Search,
data: dt.search(),
};
if (this.props.rows_selected_filter) {
filter = {
type: FilterType.All,
data: [this.props.rows_selected_filter, filter]
};
}
this.props.setSelected(searchResultsDatapoints, filter);
}
setSelected(selected: Array<Datapoint>) {
const dt = this.dt;
if (!dt) {
return;
}
const ordered_cols = this.ordered_cols;
const ock = dt.colReorder.transpose(Array.from(Array(ordered_cols.length).keys()), 'toOriginal');
dt.clear();
dt.rows.add(selected.map(function(row) {
return ock.map(x => x == '' ? '' : row[ordered_cols[x]]);
}));
if (dt.search() == "") {
// Hack to redraw faster
dt.settings()[0].oFeatures.bFilter = false;
dt.draw();
dt.settings()[0].oFeatures.bFilter = true;
}
else {
dt.draw();
}
this.empty = selected.length == 0;
}
render() {
return (
<div className={`${style.wrap} container-fluid ${style["horizontal-scrollable"]}`}>
<div className={"row"}>
<div ref={this.table_container} className={`col-md-12 sample-table-container`}>
<table ref={this.table_ref} className="table-hover table-sm sample-rows-table display table-striped table-bordered dataTable">
</table>
</div>
</div>
</div>
);
}
destroyDt() {
if (this.dt) {
const dt = this.dt;
this.dt = null;
dt.destroy();
}
}
componentWillUnmount() {
this.destroyDt();
this.setSelected_debounced.cancel();
}
} | the_stack |
import { VOLUME_SERVER_VERSION } from './version';
import { LimitsConfig, ServerConfig } from '../config';
export function getSchema() {
function detail(i: number) {
return `${i} (${Math.round(100 * LimitsConfig.maxOutputSizeInVoxelCountByPrecisionLevel[i] / 1000 / 1000) / 100 }M voxels)`;
}
const detailMax = LimitsConfig.maxOutputSizeInVoxelCountByPrecisionLevel.length - 1;
const sources = ServerConfig.idMap.map(m => m[0]);
return {
openapi: '3.0.0',
info: {
version: VOLUME_SERVER_VERSION,
title: 'Volume Server',
description: 'The VolumeServer is a service for accessing subsets of volumetric data. It automatically downsamples the data depending on the volume of the requested region to reduce the bandwidth requirements and provide near-instant access to even the largest data sets.',
},
tags: [
{
name: 'General',
}
],
paths: {
[`${ServerConfig.apiPrefix}/{source}/{id}/`]: {
get: {
tags: ['General'],
summary: 'Returns a JSON response specifying if data is available and the maximum region that can be queried.',
operationId: 'getInfo',
parameters: [
{ $ref: '#/components/parameters/source' },
{ $ref: '#/components/parameters/id' },
],
responses: {
200: {
description: 'Volume availability and info',
content: {
'application/json': {
schema: { $ref: '#/components/schemas/info' }
}
}
},
},
}
},
[`${ServerConfig.apiPrefix}/{source}/{id}/box/{a1,a2,a3}/{b1,b2,b3}/`]: {
get: {
tags: ['General'],
summary: 'Returns density data inside the specified box for the given entry. For X-ray data, returns 2Fo-Fc and Fo-Fc volumes in a single response.',
operationId: 'getBox',
parameters: [
{ $ref: '#/components/parameters/source' },
{ $ref: '#/components/parameters/id' },
{
name: 'bottomLeftCorner',
in: 'path',
description: 'Bottom left corner of the query region in Cartesian or fractional coordinates (determined by the `space` query parameter).',
required: true,
schema: {
type: 'list',
items: {
type: 'float',
}
},
style: 'simple'
},
{
name: 'topRightCorner',
in: 'path',
description: 'Top right corner of the query region in Cartesian or fractional coordinates (determined by the `space` query parameter).',
required: true,
schema: {
type: 'list',
items: {
type: 'float',
}
},
style: 'simple'
},
{ $ref: '#/components/parameters/encoding' },
{ $ref: '#/components/parameters/detail' },
{
name: 'space',
in: 'query',
description: 'Determines the coordinate space the query is in. Can be cartesian or fractional. An optional argument, default values is cartesian.',
schema: {
type: 'string',
enum: ['cartesian', 'fractional']
},
style: 'form'
}
],
responses: {
200: {
description: 'Volume box',
content: {
'text/plain': {},
'application/octet-stream': {},
}
},
},
}
},
[`${ServerConfig.apiPrefix}/{source}/{id}/cell/`]: {
get: {
tags: ['General'],
summary: 'Returns (downsampled) volume data for the entire "data cell". For X-ray data, returns unit cell of 2Fo-Fc and Fo-Fc volumes, for EM data returns everything.',
operationId: 'getCell',
parameters: [
{ $ref: '#/components/parameters/source' },
{ $ref: '#/components/parameters/id' },
{ $ref: '#/components/parameters/encoding' },
{ $ref: '#/components/parameters/detail' },
],
responses: {
200: {
description: 'Volume cell',
content: {
'text/plain': {},
'application/octet-stream': {},
}
},
},
}
}
},
components: {
schemas: {
// TODO how to keep in sync with (or derive from) `api.ts/ExtendedHeader`
info: {
properties: {
formatVersion: {
type: 'string',
description: 'Format version number'
},
axisOrder: {
type: 'array',
items: { type: 'number' },
description: 'Axis order from the slowest to fastest moving, same as in CCP4'
},
origin: {
type: 'array',
items: { type: 'number' },
description: 'Origin in fractional coordinates, in axisOrder'
},
dimensions: {
type: 'array',
items: { type: 'number' },
description: 'Dimensions in fractional coordinates, in axisOrder'
},
spacegroup: {
properties: {
number: { type: 'number' },
size: {
type: 'array',
items: { type: 'number' }
},
angles: {
type: 'array',
items: { type: 'number' }
},
isPeriodic: {
type: 'boolean',
description: 'Determine if the data should be treated as periodic or not. (e.g. X-ray = periodic, EM = not periodic)'
},
}
},
channels: {
type: 'array',
items: { type: 'string' }
},
valueType: {
type: 'string',
enum: ['float32', 'int16', 'int8'],
description: 'Determines the data type of the values'
},
blockSize: {
type: 'number',
description: 'The value are stored in blockSize^3 cubes'
},
sampling: {
type: 'array',
items: {
properties: {
byteOffset: { type: 'number' },
rate: {
type: 'number',
description: 'How many values along each axis were collapsed into 1'
},
valuesInfo: {
properties: {
mean: { type: 'number' },
sigma: { type: 'number' },
min: { type: 'number' },
max: { type: 'number' },
}
},
sampleCount: {
type: 'array',
items: { type: 'number' },
description: 'Number of samples along each axis, in axisOrder'
},
}
}
}
}
}
},
parameters: {
source: {
name: 'source',
in: 'path',
description: `Specifies the data source (determined by the experiment method). Currently supported sources are: ${sources.join(', ')}.`,
required: true,
schema: {
type: 'string',
enum: sources
},
style: 'simple'
},
id: {
name: 'id',
in: 'path',
description: 'Id of the entry. For x-ray, use PDB ID (i.e. 1cbs) and for em use EMDB id (i.e. emd-8116).',
required: true,
schema: {
type: 'string',
},
style: 'simple'
},
encoding: {
name: 'encoding',
in: 'query',
description: 'Determines if text based CIF or binary BinaryCIF encoding is used. An optional argument, default is BinaryCIF encoding.',
schema: {
type: 'string',
enum: ['cif', 'bcif']
},
style: 'form'
},
detail: {
name: 'detail',
in: 'query',
description: `Determines the maximum number of voxels the query can return. Possible values are in the range from ${detail(0)} to ${detail(detailMax)}. Default value is 0. Note: different detail levels might lead to the same result.`,
schema: {
type: 'integer',
},
style: 'form'
}
}
}
};
}
export const shortcutIconLink = `<link rel='shortcut icon' href='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAnUExURQAAAMIrHrspHr0oH7soILonHrwqH7onILsoHrsoH7soH7woILwpIKgVokoAAAAMdFJOUwAQHzNxWmBHS5XO6jdtAmoAAACZSURBVDjLxZNRCsQgDAVNXmwb9f7nXZEaLRgXloXOhwQdjMYYwpOLw55fBT46KhbOKhmRR2zLcFJQj8UR+HxFgArIF5BKJbEncC6NDEdI5SatBRSDJwGAoiFDONrEJXWYhGMIcRJGCrb1TOtDahfUuQXd10jkFYq0ViIrbUpNcVT6redeC1+b9tH2WLR93Sx2VCzkv/7NjfABxjQHksGB7lAAAAAASUVORK5CYII=' />`; | the_stack |
export const getLocalization = (culture: string): any => {
let localization = null;
switch (culture) {
case 'de':
localization =
{
// separator of parts of a date (e.g. '/' in 11/05/1955)
'/': '/',
// separator of parts of a time (e.g. ':' in 05:44 PM)
':': ':',
// the first day of the week (0 = Sunday, 1 = Monday, etc)
firstDay: 1,
days: {
// full day names
names: ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'],
// abbreviated day names
namesAbbr: ['Sonn', 'Mon', 'Dien', 'Mitt', 'Donn', 'Fre', 'Sams'],
// shortest day names
namesShort: ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa']
},
months: {
// full month names (13 months for lunar calendards -- 13th month should be '' if not lunar)
names: ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember', ''],
// abbreviated month names
namesAbbr: ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dez', '']
},
// AM and PM designators in one of these forms:
// The usual view, and the upper and lower case versions
// [standard,lowercase,uppercase]
// The culture does not use AM or PM (likely all standard date formats use 24 hour time)
// null
AM: ['AM', 'am', 'AM'],
PM: ['PM', 'pm', 'PM'],
eras: [
// eras in reverse chronological order.
// name: the name of the era in this culture (e.g. A.D., C.E.)
// start: when the era starts in ticks (gregorian, gmt), null if it is the earliest supported era.
// offset: offset in years from gregorian calendar
{ 'name': 'A.D.', 'start': null, 'offset': 0 }
],
twoDigitYearMax: 2029,
patterns:
{
d: 'dd.MM.yyyy',
D: 'dddd, d. MMMM yyyy',
t: 'HH:mm',
T: 'HH:mm:ss',
f: 'dddd, d. MMMM yyyy HH:mm',
F: 'dddd, d. MMMM yyyy HH:mm:ss',
M: 'dd MMMM',
Y: 'MMMM yyyy'
},
percentsymbol: '%',
currencysymbol: '€',
currencysymbolposition: 'after',
decimalseparator: '.',
thousandsseparator: ',',
pagergotopagestring: 'Gehe zu',
pagershowrowsstring: 'Zeige Zeile:',
pagerrangestring: ' von ',
pagerpreviousbuttonstring: 'nächster',
pagernextbuttonstring: 'voriger',
pagerfirstbuttonstring: 'first',
pagerlastbuttonstring: 'last',
groupsheaderstring: 'Ziehen Sie eine Kolumne und legen Sie es hier zu Gruppe nach dieser Kolumne',
sortascendingstring: 'Sortiere aufsteigend',
sortdescendingstring: 'Sortiere absteigend',
sortremovestring: 'Entferne Sortierung',
groupbystring: 'Group By this column',
groupremovestring: 'Remove from groups',
filterclearstring: 'Löschen',
filterstring: 'Filter',
filtershowrowstring: 'Zeige Zeilen, in denen:',
filterorconditionstring: 'Oder',
filterandconditionstring: 'Und',
filterselectallstring: '(Alle auswählen)',
filterchoosestring: 'Bitte wählen Sie:',
filterstringcomparisonoperators: ['leer', 'nicht leer', 'enthält', 'enthält(gu)',
'nicht enthalten', 'nicht enthalten(gu)', 'beginnt mit', 'beginnt mit(gu)',
'endet mit', 'endet mit(gu)', 'equal', 'gleich(gu)', 'null', 'nicht null'],
filternumericcomparisonoperators: ['gleich', 'nicht gleich', 'weniger als', 'kleiner oder gleich', 'größer als', 'größer oder gleich', 'null', 'nicht null'],
filterdatecomparisonoperators: ['gleich', 'nicht gleich', 'weniger als', 'kleiner oder gleich', 'größer als', 'größer oder gleich', 'null', 'nicht null'],
filterbooleancomparisonoperators: ['gleich', 'nicht gleich'],
validationstring: 'Der eingegebene Wert ist ungültig',
emptydatastring: 'Nokeine Daten angezeigt',
filterselectstring: 'Wählen Sie Filter',
loadtext: 'Loading...',
clearstring: 'Löschen',
todaystring: 'Heute'
}
break;
case 'en':
default:
localization =
{
// separator of parts of a date (e.g. '/' in 11/05/1955)
'/': '/',
// separator of parts of a time (e.g. ':' in 05:44 PM)
':': ':',
// the first day of the week (0 = Sunday, 1 = Monday, etc)
firstDay: 0,
days: {
// full day names
names: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
// abbreviated day names
namesAbbr: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
// shortest day names
namesShort: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
},
months: {
// full month names (13 months for lunar calendards -- 13th month should be '' if not lunar)
names: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ''],
// abbreviated month names
namesAbbr: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', '']
},
// AM and PM designators in one of these forms:
// The usual view, and the upper and lower case versions
// [standard,lowercase,uppercase]
// The culture does not use AM or PM (likely all standard date formats use 24 hour time)
// null
AM: ['AM', 'am', 'AM'],
PM: ['PM', 'pm', 'PM'],
eras: [
// eras in reverse chronological order.
// name: the name of the era in this culture (e.g. A.D., C.E.)
// start: when the era starts in ticks (gregorian, gmt), null if it is the earliest supported era.
// offset: offset in years from gregorian calendar
{ 'name': 'A.D.', 'start': null, 'offset': 0 }
],
twoDigitYearMax: 2029,
patterns: {
// short date pattern
d: 'M/d/yyyy',
// long date pattern
D: 'dddd, MMMM dd, yyyy',
// short time pattern
t: 'h:mm tt',
// long time pattern
T: 'h:mm:ss tt',
// long date, short time pattern
f: 'dddd, MMMM dd, yyyy h:mm tt',
// long date, long time pattern
F: 'dddd, MMMM dd, yyyy h:mm:ss tt',
// month/day pattern
M: 'MMMM dd',
// month/year pattern
Y: 'yyyy MMMM',
// S is a sortable format that does not vary by culture
S: 'yyyy\u0027-\u0027MM\u0027-\u0027dd\u0027T\u0027HH\u0027:\u0027mm\u0027:\u0027ss',
// formatting of dates in MySQL DataBases
ISO: 'yyyy-MM-dd hh:mm:ss',
ISO2: 'yyyy-MM-dd HH:mm:ss',
d1: 'dd.MM.yyyy',
d2: 'dd-MM-yyyy',
d3: 'dd-MMMM-yyyy',
d4: 'dd-MM-yy',
d5: 'H:mm',
d6: 'HH:mm',
d7: 'HH:mm tt',
d8: 'dd/MMMM/yyyy',
d9: 'MMMM-dd',
d10: 'MM-dd',
d11: 'MM-dd-yyyy'
},
percentsymbol: '%',
currencysymbol: '$',
currencysymbolposition: 'before',
decimalseparator: '.',
thousandsseparator: ',',
pagergotopagestring: 'Go to page:',
pagershowrowsstring: 'Show rows:',
pagerrangestring: ' of ',
pagerpreviousbuttonstring: 'previous',
pagernextbuttonstring: 'next',
pagerfirstbuttonstring: 'first',
pagerlastbuttonstring: 'last',
groupsheaderstring: 'Drag a column and drop it here to group by that column',
sortascendingstring: 'Sort Ascending',
sortdescendingstring: 'Sort Descending',
sortremovestring: 'Remove Sort',
groupbystring: 'Group By this column',
groupremovestring: 'Remove from groups',
filterclearstring: 'Clear',
filterstring: 'Filter',
filtershowrowstring: 'Show rows where:',
filterorconditionstring: 'Or',
filterandconditionstring: 'And',
filterselectallstring: '(Select All)',
filterchoosestring: 'Please Choose:',
filterstringcomparisonoperators: ['empty', 'not empty', 'enthalten', 'enthalten(match case)',
'does not contain', 'does not contain(match case)', 'starts with', 'starts with(match case)',
'ends with', 'ends with(match case)', 'equal', 'equal(match case)', 'null', 'not null'],
filternumericcomparisonoperators: ['equal', 'not equal', 'less than', 'less than or equal', 'greater than', 'greater than or equal', 'null', 'not null'],
filterdatecomparisonoperators: ['equal', 'not equal', 'less than', 'less than or equal', 'greater than', 'greater than or equal', 'null', 'not null'],
filterbooleancomparisonoperators: ['equal', 'not equal'],
validationstring: 'Entered value is not valid',
emptydatastring: 'No data to display',
filterselectstring: 'Select Filter',
loadtext: 'Loading...',
clearstring: 'Clear',
todaystring: 'Today'
}
break;
}
return localization;
} | the_stack |
import * as recast from 'recast'
// locals
import '../../../jest.setup'
import { parseFile, ParsedSvelteFile } from './parse'
describe('parser tests', () => {
test('happy path - separate module and instance script', async () => {
const doc = `
<script context="module">
console.log('module')
</script>
<script>
console.log('instance')
</script>
`
// parse the string
const result = await parseFile(doc)
expect(result.instance?.content).toMatchInlineSnapshot(`console.log("instance");`)
expect(result.instance?.start).toMatchInlineSnapshot(`69`)
expect(result.instance?.end).toMatchInlineSnapshot(`115`)
expect(result.module?.content).toMatchInlineSnapshot(`console.log("module");`)
expect(result.module?.start).toMatchInlineSnapshot(`3`)
expect(result.module?.end).toMatchInlineSnapshot(`64`)
checkScriptBounds(doc, result)
})
test('happy path - start on first character', async () => {
const doc = `<script context="module">
console.log('module')
</script>`
// parse the string
const result = await parseFile(doc)
expect(result.instance?.content).toMatchInlineSnapshot(`undefined`)
expect(result.instance?.start).toMatchInlineSnapshot(`undefined`)
expect(result.instance?.end).toMatchInlineSnapshot(`undefined`)
expect(result.module?.content).toMatchInlineSnapshot(`console.log("module");`)
expect(result.module?.start).toMatchInlineSnapshot(`0`)
expect(result.module?.end).toMatchInlineSnapshot(`63`)
checkScriptBounds(doc, result)
})
test('happy path - only module', async () => {
const doc = `
<script context="module">
console.log('module')
</script>
`
// parse the string
const result = await parseFile(doc)
expect(result.instance?.content).toMatchInlineSnapshot(`undefined`)
expect(result.instance?.start).toMatchInlineSnapshot(`undefined`)
expect(result.instance?.end).toMatchInlineSnapshot(`undefined`)
expect(result.module?.content).toMatchInlineSnapshot(`console.log("module");`)
expect(result.module?.start).toMatchInlineSnapshot(`4`)
expect(result.module?.end).toMatchInlineSnapshot(`67`)
checkScriptBounds(doc, result)
})
test('happy path - only instance', async () => {
const doc = `
<script>
console.log('module')
</script>
`
// parse the string
const result = await parseFile(doc)
expect(result.instance?.content).toMatchInlineSnapshot(`console.log("module");`)
expect(result.instance?.start).toMatchInlineSnapshot(`4`)
expect(result.instance?.end).toMatchInlineSnapshot(`50`)
expect(result.module?.content).toMatchInlineSnapshot(`undefined`)
expect(result.module?.start).toMatchInlineSnapshot(`undefined`)
expect(result.module?.end).toMatchInlineSnapshot(`undefined`)
checkScriptBounds(doc, result)
})
test('single quotes', async () => {
const doc = `
<script context='module'>
console.log('module')
</script>
`
// parse the string
const result = await parseFile(doc)
expect(result.instance?.content).toMatchInlineSnapshot(`undefined`)
expect(result.instance?.start).toMatchInlineSnapshot(`undefined`)
expect(result.instance?.end).toMatchInlineSnapshot(`undefined`)
expect(result.module?.content).toMatchInlineSnapshot(`console.log("module");`)
expect(result.module?.start).toMatchInlineSnapshot(`4`)
expect(result.module?.end).toMatchInlineSnapshot(`67`)
checkScriptBounds(doc, result)
})
test('happy path - typescript', async () => {
const doc = `
<script context="module" lang="ts">
type Foo = { hello: string}
</script>
`
// parse the string
const result = await parseFile(doc)
expect(result.instance?.content).toMatchInlineSnapshot(`undefined`)
expect(result.instance?.start).toMatchInlineSnapshot(`undefined`)
expect(result.instance?.end).toMatchInlineSnapshot(`undefined`)
expect(result.module?.content).toMatchInlineSnapshot(`
type Foo = {
hello: string
};
`)
expect(result.module?.start).toMatchInlineSnapshot(`4`)
expect(result.module?.end).toMatchInlineSnapshot(`83`)
checkScriptBounds(doc, result)
})
test('nested script block', async () => {
const doc = `
<div>
<script>
console.log('inner')
</script>
</div>
`
// parse the string
const result = await parseFile(doc)
expect(result.instance?.content).toMatchInlineSnapshot(`undefined`)
expect(result.instance?.start).toMatchInlineSnapshot(`undefined`)
expect(result.instance?.end).toMatchInlineSnapshot(`undefined`)
expect(result.module?.content).toMatchInlineSnapshot(`undefined`)
expect(result.module?.start).toMatchInlineSnapshot(`undefined`)
expect(result.module?.end).toMatchInlineSnapshot(`undefined`)
checkScriptBounds(doc, result)
})
test('script next to html', async () => {
const doc = `
<script>
console.log('script')
</script>
<div>
</div>
`
// parse the string
const result = await parseFile(doc)
expect(result.instance?.content).toMatchInlineSnapshot(`console.log("script");`)
expect(result.instance?.start).toMatchInlineSnapshot(`4`)
expect(result.instance?.end).toMatchInlineSnapshot(`50`)
expect(result.module?.content).toMatchInlineSnapshot(`undefined`)
expect(result.module?.start).toMatchInlineSnapshot(`undefined`)
expect(result.module?.end).toMatchInlineSnapshot(`undefined`)
checkScriptBounds(doc, result)
})
test("logic in script doesn't break things", async () => {
const doc = `
<script context='module'>
if (1<2) {
console.log('hello')
}
</script>
`
// parse the string
const result = await parseFile(doc)
expect(result.instance?.content).toMatchInlineSnapshot(`undefined`)
expect(result.instance?.start).toMatchInlineSnapshot(`undefined`)
expect(result.instance?.end).toMatchInlineSnapshot(`undefined`)
expect(result.module?.content).toMatchInlineSnapshot(`
if (1 < 2) {
console.log("hello");
}
`)
expect(result.module?.start).toMatchInlineSnapshot(`4`)
expect(result.module?.end).toMatchInlineSnapshot(`88`)
checkScriptBounds(doc, result)
})
test("logic in template doesn't break things", async () => {
const doc = `
<script context='module'>
console.log('hello')
</script>
{#if foo < 2}
<div>
hello
</div>
{/if}
`
// parse the string
const result = await parseFile(doc)
expect(result.instance?.content).toMatchInlineSnapshot(`undefined`)
expect(result.instance?.start).toMatchInlineSnapshot(`undefined`)
expect(result.instance?.end).toMatchInlineSnapshot(`undefined`)
expect(result.module?.content).toMatchInlineSnapshot(`console.log("hello");`)
expect(result.module?.start).toMatchInlineSnapshot(`4`)
expect(result.module?.end).toMatchInlineSnapshot(`66`)
checkScriptBounds(doc, result)
})
test('self-closing tags', async () => {
const doc = `
<svelte:head>
<link />
</svelte:head>
<script>
console.log('hello')
</script>
`
// parse the string
const result = await parseFile(doc)
expect(result.instance?.content).toMatchInlineSnapshot(`console.log("hello");`)
expect(result.instance?.start).toMatchInlineSnapshot(`52`)
expect(result.instance?.end).toMatchInlineSnapshot(`97`)
expect(result.module?.content).toMatchInlineSnapshot(`undefined`)
expect(result.module?.start).toMatchInlineSnapshot(`undefined`)
expect(result.module?.end).toMatchInlineSnapshot(`undefined`)
checkScriptBounds(doc, result)
})
test('comments', async () => {
const doc = `
<!-- <script context='module'> -->
<script>
console.log('hello')
</script>
{#if foo < 2}
<div>
hello
</div>
{/if}
`
// parse the string
const result = await parseFile(doc)
expect(result.instance?.content).toMatchInlineSnapshot(`console.log("hello");`)
expect(result.instance?.start).toMatchInlineSnapshot(`42`)
expect(result.instance?.end).toMatchInlineSnapshot(`87`)
expect(result.module?.content).toMatchInlineSnapshot(`undefined`)
expect(result.module?.start).toMatchInlineSnapshot(`undefined`)
expect(result.module?.end).toMatchInlineSnapshot(`undefined`)
checkScriptBounds(doc, result)
})
test("else in template doesn't break things", async () => {
const doc = `
<script context='module'>
console.log('hello')
</script>
{#if foo < 2}
<div>
hello
</div>
{:else if foo < 4}
<div>
hello
</div>
{/if}
`
// parse the string
const result = await parseFile(doc)
expect(result.instance?.content).toMatchInlineSnapshot(`undefined`)
expect(result.instance?.start).toMatchInlineSnapshot(`undefined`)
expect(result.instance?.end).toMatchInlineSnapshot(`undefined`)
expect(result.module?.content).toMatchInlineSnapshot(`console.log("hello");`)
expect(result.module?.start).toMatchInlineSnapshot(`4`)
expect(result.module?.end).toMatchInlineSnapshot(`66`)
checkScriptBounds(doc, result)
})
test('expression in content', async () => {
const doc = `
<script context='module'>
console.log('hello')
</script>
<div>
{hello}
</div>
`
// parse the string
const result = await parseFile(doc)
expect(result.instance?.content).toMatchInlineSnapshot(`undefined`)
expect(result.instance?.start).toMatchInlineSnapshot(`undefined`)
expect(result.instance?.end).toMatchInlineSnapshot(`undefined`)
expect(result.module?.content).toMatchInlineSnapshot(`console.log("hello");`)
expect(result.module?.start).toMatchInlineSnapshot(`4`)
expect(result.module?.end).toMatchInlineSnapshot(`66`)
checkScriptBounds(doc, result)
})
test('expression attribute', async () => {
const doc = `
{#if foo < 2}
<div>
hello
</div>
{:else if foo < 4}
<!--
the crazy <div is to trick the parser into thinking there's
a new tag inside of an expression
-->
<div attribute={foo > 2 && div < 2} foo>
hello
<div>
inner
</div>
</div>
{/if}
<script context='module'>
console.log('hello')
</script>
`
// parse the string
const result = await parseFile(doc)
expect(result.instance?.content).toMatchInlineSnapshot(`undefined`)
expect(result.instance?.start).toMatchInlineSnapshot(`undefined`)
expect(result.instance?.end).toMatchInlineSnapshot(`undefined`)
expect(result.module?.content).toMatchInlineSnapshot(`console.log("hello");`)
expect(result.module?.start).toMatchInlineSnapshot(`307`)
expect(result.module?.end).toMatchInlineSnapshot(`369`)
checkScriptBounds(doc, result)
})
test('tabs to end tags', async () => {
const doc = `<script lang="ts">
console.log('hello')
</script>
<header
class="sticky flex items-center justify-between h-16 top-0 inset-x-0 max-w-7xl px-2 xl:px-0 mx-auto"
>
<svg
class="w-6 h-6"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
><path
/>
hello
</svg>
</header>
`
// parse the string
const result = await parseFile(doc)
expect(result.instance?.content).toMatchInlineSnapshot(`console.log("hello");`)
expect(result.instance?.start).toMatchInlineSnapshot(`0`)
expect(result.instance?.end).toMatchInlineSnapshot(`53`)
expect(result.module?.content).toMatchInlineSnapshot(`undefined`)
expect(result.module?.start).toMatchInlineSnapshot(`undefined`)
expect(result.module?.end).toMatchInlineSnapshot(`undefined`)
checkScriptBounds(doc, result)
})
test("styling tag parse errors don't fail (postcss support)", async () => {
const doc = `<script lang="ts">
const example = object({});
</script>
<style>
.test {
&_title {
width: 500px;
@media (max-width: 500px) {
width: auto;
}
body.is_dark & {
color: white;
}
}
img {
display: block;
}
}
</style>
<div>hello</div>
`
// parse the string
const result = await parseFile(doc)
expect(result.instance?.content).toMatchInlineSnapshot(`const example = object({});`)
expect(result.instance?.start).toMatchInlineSnapshot(`0`)
expect(result.instance?.end).toMatchInlineSnapshot(`58`)
expect(result.module?.content).toMatchInlineSnapshot(`undefined`)
expect(result.module?.start).toMatchInlineSnapshot(`undefined`)
expect(result.module?.end).toMatchInlineSnapshot(`undefined`)
checkScriptBounds(doc, result)
})
test('empty object in script', async () => {
const doc = `<script lang="ts">
const example = object({});
</script>
<div>hello</div>
`
// parse the string
const result = await parseFile(doc)
expect(result.instance?.content).toMatchInlineSnapshot(`const example = object({});`)
expect(result.instance?.start).toMatchInlineSnapshot(`0`)
expect(result.instance?.end).toMatchInlineSnapshot(`58`)
expect(result.module?.content).toMatchInlineSnapshot(`undefined`)
expect(result.module?.start).toMatchInlineSnapshot(`undefined`)
expect(result.module?.end).toMatchInlineSnapshot(`undefined`)
checkScriptBounds(doc, result)
})
})
function checkScriptBounds(doc: string, result?: ParsedSvelteFile | null | undefined) {
if (!result) {
return
}
if (result.module) {
expect(doc[result.module.start]).toEqual('<')
expect(doc[result.module.end]).toEqual('>')
}
if (result.instance) {
expect(doc[result.instance.start]).toEqual('<')
expect(doc[result.instance.end]).toEqual('>')
}
} | the_stack |
import * as Calendar_ColorUtils from "./Utils/Color";
import * as Calendar_Contracts from "./Contracts";
import * as Calendar_Utils_Guid from "./Utils/Guid";
import { timeout } from "./Utils/Promise";
import * as Controls from "VSS/Controls";
import * as Culture from "VSS/Utils/Culture";
import * as Utils_Date from "VSS/Utils/Date";
import * as Utils_String from "VSS/Utils/String";
import * as FullCalendar from "fullCalendar";
export interface CalendarOptions {
fullCalendarOptions: IDictionaryStringTo<any>;
viewRender: any;
}
export interface SourceAndOptions {
source: Calendar_Contracts.IEventSource;
options?: FullCalendar.Options;
callbacks?: { [callbackType: number]: Function };
}
export interface CalendarEventSource extends FullCalendar.EventSource {
(source: Calendar_Contracts.IEventSource, options: FullCalendar.Options): void;
eventSource: Calendar_Contracts.IEventSource;
state?: CalendarEventSourceState;
}
export interface CalendarEventSourceState {
dirty?: boolean;
cachedEvents?: FullCalendar.EventObject[];
}
export enum FullCalendarCallbackType {
// General display events
viewRender,
viewDestroy,
dayRender,
windowResize,
// Clicking, hovering, selecting
dayClick,
eventClick,
eventMouseover,
eventMouseout,
select,
unselect,
// Event rendering events
eventRender,
eventAfterRender,
eventDestroy,
eventAfterAllRender,
// Dragging, dropping
eventDragStart,
eventDragStop,
eventDrop,
eventResizeStart,
eventResizeStop,
eventResize,
drop,
eventReceive,
}
export enum FullCalendarEventRenderingCallbackType {}
export class Calendar extends Controls.Control<CalendarOptions> {
private _callbacks: { [callbackType: number]: Function[] };
private _calendarSources: CalendarEventSource[];
constructor(options: CalendarOptions) {
super($.extend({ cssClass: "vss-calendar" }, options));
this._callbacks = {};
this._calendarSources = [];
}
public initialize() {
super.initialize();
// Determine optimal aspect ratio
const aspectRatio = parseFloat(($(".leftPane").width() / ($(".leftPane").height() - 85)).toFixed(1));
const firstDay = Culture.getDateTimeFormat().FirstDayOfWeek;
this._element.fullCalendar(
$.extend(
{
eventRender: this._getComposedCallback(FullCalendarCallbackType.eventRender),
eventAfterRender: this._getComposedCallback(FullCalendarCallbackType.eventAfterRender),
eventAfterAllRender: this._getComposedCallback(FullCalendarCallbackType.eventAfterAllRender),
eventDestroy: this._getComposedCallback(FullCalendarCallbackType.eventDestroy),
viewRender: (view: FullCalendar.ViewObject, element: JQuery) => this._viewRender(view, element),
viewDestroy: this._getComposedCallback(FullCalendarCallbackType.viewDestroy),
dayRender: this._getComposedCallback(FullCalendarCallbackType.dayRender),
windowResize: this._getComposedCallback(FullCalendarCallbackType.windowResize),
dayClick: this._getComposedCallback(FullCalendarCallbackType.dayClick),
eventClick: this._getComposedCallback(FullCalendarCallbackType.eventClick),
eventMouseover: this._getComposedCallback(FullCalendarCallbackType.eventMouseover),
eventMouseout: this._getComposedCallback(FullCalendarCallbackType.eventMouseout),
select: this._getComposedCallback(FullCalendarCallbackType.select),
unselect: this._getComposedCallback(FullCalendarCallbackType.unselect),
eventDragStart: this._getComposedCallback(FullCalendarCallbackType.eventDragStart),
eventDragStop: this._getComposedCallback(FullCalendarCallbackType.eventDragStop),
eventDrop: this._getComposedCallback(FullCalendarCallbackType.eventDrop),
eventResizeStart: this._getComposedCallback(FullCalendarCallbackType.eventResizeStart),
eventResizeStop: this._getComposedCallback(FullCalendarCallbackType.eventResizeStop),
eventResize: this._getComposedCallback(FullCalendarCallbackType.eventResize),
drop: this._getComposedCallback(FullCalendarCallbackType.drop),
eventReceive: this._getComposedCallback(FullCalendarCallbackType.eventReceive),
header: false,
aspectRatio: aspectRatio,
columnFormat: "dddd",
selectable: true,
firstDay: firstDay,
},
this._options.fullCalendarOptions,
),
);
}
public addEventSource(
source: Calendar_Contracts.IEventSource,
options?: FullCalendar.Options,
callbacks?: { [callbackType: number]: Function },
) {
this.addEventSources([{ source: source, options: options, callbacks: callbacks }]);
}
public addEventSources(sources: SourceAndOptions[]): CalendarEventSource[] {
if (this._disposed) {
return [];
}
sources.forEach(source => {
const calendarSource = this._createEventSource(source.source, source.options || {});
this._calendarSources.push(calendarSource);
this._element.fullCalendar("addEventSource", calendarSource);
if (source.callbacks) {
const callbackTypes = Object.keys(source.callbacks);
for (let i = 0; i < callbackTypes.length; ++i) {
const callbackType: FullCalendarCallbackType = parseInt(callbackTypes[i]);
if (callbackType === FullCalendarCallbackType.eventAfterAllRender) {
// This callback doesn't make sense for individual events.
continue;
}
this.addCallback(
callbackType,
this._createFilteredCallback(
source.callbacks[callbackTypes[i]],
event => event["eventType"] === source.source.id,
),
);
}
}
});
return this._calendarSources;
}
public getViewQuery(): Calendar_Contracts.IEventQuery {
const view = this._element.fullCalendar("getView");
return {
startDate: Utils_Date.shiftToUTC(new Date(view.start.valueOf() as string)),
endDate: Utils_Date.shiftToUTC(new Date(view.end.valueOf() as string)),
};
}
public next(): void {
this._element.fullCalendar("next");
}
public prev(): void {
this._element.fullCalendar("prev");
}
public goTo(date: Date) {
this._element.fullCalendar("gotoDate", date);
}
public showToday(): void {
this._element.fullCalendar("today");
}
public getFormattedDate(format: string): string {
const currentDate: any = this._element.fullCalendar("getDate");
return currentDate.format(format);
}
public renderEvent(event: Calendar_Contracts.CalendarEvent, eventType: string) {
const end = Utils_Date.addDays(new Date(<any>event.endDate), 1).toISOString();
const calEvent: any = {
id: event.id,
title: event.title,
description: event.description,
allDay: true,
start: event.startDate,
end: end,
eventType: eventType,
iterationId: event.iterationId,
category: event.category,
editable: event.movable,
icons: event.icons,
eventData: event.eventData,
};
if (event.__etag) {
calEvent.__etag = event.__etag;
}
if (event.member) {
calEvent.member = event.member;
}
calEvent.color = event.category.color;
calEvent.backgroundColor = calEvent.color;
calEvent.borderColor = calEvent.color;
calEvent.textColor = calEvent.category.textColor || "#FFFFFF";
this._element.fullCalendar("renderEvent", calEvent, false);
}
public updateEvent(event: FullCalendar.EventObject) {
event.color = (<any>event).category.color;
event.backgroundColor = event.color;
event.borderColor = event.color;
this._element.fullCalendar("updateEvent", event);
}
public setOption(key: string, value: any) {
this._element.fullCalendar("option", key, value);
}
public refreshEvents(eventSource?: FullCalendar.EventSource) {
if (!eventSource) {
$(".sprint-label").remove();
this._element.fullCalendar("refetchEvents");
} else {
this._element.fullCalendar("removeEventSource", eventSource);
this._element.fullCalendar("addEventSource", eventSource);
}
}
public removeEvent(id: string) {
if (id) {
this._element.fullCalendar("removeEvents", id);
}
}
private _viewRender(view: FullCalendar.ViewObject, element: JQuery) {
view["renderId"] = Math.random();
}
private _createFilteredCallback(
original: (event: FullCalendar.EventObject, element: JQuery, view: FullCalendar.ViewObject) => any,
filter: (event: FullCalendar.EventObject) => boolean,
): Function {
return (event: FullCalendar.EventObject, element: JQuery, view: FullCalendar.ViewObject) => {
if (filter(event)) {
return original(event, element, view);
}
};
}
private _createEventSource(source: Calendar_Contracts.IEventSource, options: FullCalendar.Options): CalendarEventSource {
const state: CalendarEventSourceState = {};
const getEventsMethod = (
start: Date,
end: Date,
timezone: string | boolean,
callback: (events: FullCalendar.EventObject[]) => void,
) => {
if (!state.dirty && state.cachedEvents) {
callback(state.cachedEvents);
return;
}
const loadSourcePromise = <PromiseLike<Calendar_Contracts.CalendarEvent[]>>source.load();
timeout(loadSourcePromise, 5000, "Could not load event source " + source.name + ". Request timed out.").then(
results => {
const calendarEvents = results.map((value, index) => {
const start = value.startDate;
const end = value.endDate ? Utils_Date.addDays(new Date(value.endDate), 1).toISOString() : start;
const event: any = {
id: value.id || Calendar_Utils_Guid.newGuid(),
title: value.title,
description: value.description,
allDay: true,
start: start,
end: end,
eventType: source.id,
rendering: (<any>options).rendering || "",
category: value.category,
iterationId: value.iterationId,
member: value.member,
editable: value.movable,
icons: value.icons,
eventData: value.eventData,
};
if (value.__etag) {
event.__etag = value.__etag;
}
if ($.isFunction(source.addEvent) && value.category) {
const color =
<any>value.category.color ||
Calendar_ColorUtils.generateColor(
(<string>value.category.title || "uncategorized").toLowerCase(),
);
event.backgroundColor = color;
event.borderColor = color;
event.textColor = value.category.textColor || "#FFFFFF";
}
if ((<any>options).rendering === "background" && value.category) {
const color =
<any>value.category.color ||
Calendar_ColorUtils.generateBackgroundColor(
(<string>event.category.title || "uncategorized").toLowerCase(),
);
event.backgroundColor = color;
event.borderColor = color;
event.textColor = value.category.textColor || "#FFFFFF";
}
return event;
});
state.dirty = false;
state.cachedEvents = calendarEvents;
callback(calendarEvents);
},
reason => {
console.error(
Utils_String.format("Error getting event data.\nEvent source: {0}\nReason: {1}", source.name, reason),
);
callback([]);
},
);
};
const calendarEventSource: CalendarEventSource = <any>getEventsMethod;
calendarEventSource.eventSource = source;
calendarEventSource.state = state;
return calendarEventSource;
}
public addCallback(callbackType: FullCalendarCallbackType, callback: Function) {
if (!this._callbacks[callbackType]) {
this._callbacks[callbackType] = [];
}
this._callbacks[callbackType].push(callback);
}
private _getComposedCallback(callbackType: FullCalendarCallbackType) {
const args = arguments;
return (event: FullCalendar.EventObject, element: JQuery, view: FullCalendar.ViewObject): JQuery | boolean => {
const fns = this._callbacks[callbackType];
if (!fns) {
return undefined;
}
let broken = false;
let updatedElement = element;
for (let i = 0; i < fns.length; ++i) {
const fn = fns[i];
const result = fn(event, updatedElement, view);
if (callbackType === FullCalendarCallbackType.eventRender && result === false) {
broken = true;
break;
}
if (callbackType === FullCalendarCallbackType.eventRender && result instanceof jQuery) {
updatedElement = result;
}
}
if (broken) {
return false;
}
return updatedElement;
};
}
/**
* Adds a one-off event directly to the calendar. Consider adding directly to an event
* source rather than calling this method.
* @param FullCalendar.EventObject[] Array of events to add.
*/
public addEvents(events: FullCalendar.EventObject[]) {
events.forEach(event => {
this._element.fullCalendar("renderEvent", event, true);
});
}
/**
* Remove events from the calendar
* @param Array of event IDs to remove, or a filter function, accepting an event, returing true if it is to be removed, false if it is to be kept. Leave null to remove all events.
* @return EventObject[] - events that were removed.
*/
public removeEvents(filter: any[] | ((event: FullCalendar.EventObject) => boolean)): FullCalendar.EventObject[] {
const clientEvents = this._element.fullCalendar("clientEvents", filter);
this._element.fullCalendar("removeEvents", filter);
return clientEvents;
}
/**
* Gets the current date of the calendar
@ return Date
*/
public getDate(): Date {
return this._element.fullCalendar("getDate");
}
} | the_stack |
* A visitor to visit a Java method. The methods of this class must be called in
* the following order: ( <tt>visitParameter</tt> )* [
* <tt>visitAnnotationDefault</tt> ] ( <tt>visitAnnotation</tt> |
* <tt>visitParameterAnnotation</tt> <tt>visitTypeAnnotation</tt> |
* <tt>visitAttribute</tt> )* [ <tt>visitCode</tt> ( <tt>visitFrame</tt> |
* <tt>visit<i>X</i>Insn</tt> | <tt>visitLabel</tt> |
* <tt>visitInsnAnnotation</tt> | <tt>visitTryCatchBlock</tt> |
* <tt>visitTryCatchAnnotation</tt> | <tt>visitLocalVariable</tt> |
* <tt>visitLocalVariableAnnotation</tt> | <tt>visitLineNumber</tt> )*
* <tt>visitMaxs</tt> ] <tt>visitEnd</tt>. In addition, the
* <tt>visit<i>X</i>Insn</tt> and <tt>visitLabel</tt> methods must be called in
* the sequential order of the bytecode instructions of the visited code,
* <tt>visitInsnAnnotation</tt> must be called <i>after</i> the annotated
* instruction, <tt>visitTryCatchBlock</tt> must be called <i>before</i> the
* labels passed as arguments have been visited,
* <tt>visitTryCatchBlockAnnotation</tt> must be called <i>after</i> the
* corresponding try catch block has been visited, and the
* <tt>visitLocalVariable</tt>, <tt>visitLocalVariableAnnotation</tt> and
* <tt>visitLineNumber</tt> methods must be called <i>after</i> the labels
* passed as arguments have been visited.
*
* @author Eric Bruneton
*/
import { Opcodes } from "./Opcodes"
import { Handle } from "./Handle"
import { Label } from "./Label"
import { AnnotationVisitor } from "./AnnotationVisitor"
import { TypePath } from "./TypePath";
import { Attribute } from "./Attribute";
export abstract class MethodVisitor {
/**
* The ASM API version implemented by this visitor. The value of this field
* must be one of {@link Opcodes#ASM4} or {@link Opcodes#ASM5}.
*/
api: number;
/**
* The method visitor to which this visitor must delegate method calls. May
* be null.
*/
mv: MethodVisitor | null;
/**
* Constructs a new {@link MethodVisitor}.
*
* @param api
* the ASM API version implemented by this visitor. Must be one
* of {@link Opcodes#ASM4} or {@link Opcodes#ASM5}.
* @param mv
* the method visitor to which this visitor must delegate method
* calls. May be null.
*/
public constructor(api: number, mv: MethodVisitor | null = null) {
this.api = 0;
if (api !== Opcodes.ASM4 && api !== Opcodes.ASM5) {
throw new Error();
}
this.api = api;
this.mv = mv;
}
/**
* Visits a parameter of this method.
*
* @param name
* parameter name or null if none is provided.
* @param access
* the parameter's access flags, only <tt>ACC_FINAL</tt>,
* <tt>ACC_SYNTHETIC</tt> or/and <tt>ACC_MANDATED</tt> are
* allowed (see {@link Opcodes}).
*/
public visitParameter(name: string | null, access: number) {
if (this.api < Opcodes.ASM5) {
throw new Error();
}
if (this.mv != null) {
this.mv.visitParameter(name, access);
}
}
/**
* Visits the default value of this annotation interface method.
*
* @return a visitor to the visit the actual default value of this
* annotation interface method, or <tt>null</tt> if this visitor is
* not interested in visiting this default value. The 'name'
* parameters passed to the methods of this annotation visitor are
* ignored. Moreover, exacly one visit method must be called on this
* annotation visitor, followed by visitEnd.
*/
public visitAnnotationDefault(): AnnotationVisitor | null {
if (this.mv != null) {
return this.mv.visitAnnotationDefault();
}
return null;
}
/**
* Visits an annotation of this method.
*
* @param desc
* the class descriptor of the annotation class.
* @param visible
* <tt>true</tt> if the annotation is visible at runtime.
* @return a visitor to visit the annotation values, or <tt>null</tt> if
* this visitor is not interested in visiting this annotation.
*/
public visitAnnotation(desc: string | null, visible: boolean): AnnotationVisitor | null {
if (this.mv != null) {
return this.mv.visitAnnotation(desc, visible);
}
return null;
}
/**
* Visits an annotation on a type in the method signature.
*
* @param typeRef
* a reference to the annotated type. The sort of this type
* reference must be {@link TypeReference#METHOD_TYPE_PARAMETER
* METHOD_TYPE_PARAMETER},
* {@link TypeReference#METHOD_TYPE_PARAMETER_BOUND
* METHOD_TYPE_PARAMETER_BOUND},
* {@link TypeReference#METHOD_RETURN METHOD_RETURN},
* {@link TypeReference#METHOD_RECEIVER METHOD_RECEIVER},
* {@link TypeReference#METHOD_FORMAL_PARAMETER
* METHOD_FORMAL_PARAMETER} or {@link TypeReference#THROWS
* THROWS}. See {@link TypeReference}.
* @param typePath
* the path to the annotated type argument, wildcard bound, array
* element type, or static inner type within 'typeRef'. May be
* <tt>null</tt> if the annotation targets 'typeRef' as a whole.
* @param desc
* the class descriptor of the annotation class.
* @param visible
* <tt>true</tt> if the annotation is visible at runtime.
* @return a visitor to visit the annotation values, or <tt>null</tt> if
* this visitor is not interested in visiting this annotation.
*/
public visitTypeAnnotation(typeRef: number, typePath: TypePath | null, desc: string | null, visible: boolean): AnnotationVisitor | null {
if (this.api < Opcodes.ASM5) {
throw new Error();
}
if (this.mv != null) {
return this.mv.visitTypeAnnotation(typeRef, typePath, desc, visible);
}
return null;
}
/**
* Visits an annotation of a parameter this method.
*
* @param parameter
* the parameter index.
* @param desc
* the class descriptor of the annotation class.
* @param visible
* <tt>true</tt> if the annotation is visible at runtime.
* @return a visitor to visit the annotation values, or <tt>null</tt> if
* this visitor is not interested in visiting this annotation.
*/
public visitParameterAnnotation(parameter: number, desc: string | null, visible: boolean): AnnotationVisitor | null {
if (this.mv != null) {
return this.mv.visitParameterAnnotation(parameter, desc, visible);
}
return null;
}
/**
* Visits a non standard attribute of this method.
*
* @param attr
* an attribute.
*/
public visitAttribute(attr: Attribute) {
if (this.mv != null) {
this.mv.visitAttribute(attr);
}
}
/**
* Starts the visit of the method's code, if any (i.e. non abstract method).
*/
public visitCode() {
if (this.mv != null) {
this.mv.visitCode();
}
}
/**
* Visits the current state of the local variables and operand stack
* elements. This method must(*) be called <i>just before</i> any
* instruction <b>i</b> that follows an unconditional branch instruction
* such as GOTO or THROW, that is the target of a jump instruction, or that
* starts an exception handler block. The visited types must describe the
* values of the local variables and of the operand stack elements <i>just
* before</i> <b>i</b> is executed.<br>
* <br>
* (*) this is mandatory only for classes whose version is greater than or
* equal to {@link Opcodes#V1_6 V1_6}. <br>
* <br>
* The frames of a method must be given either in expanded form, or in
* compressed form (all frames must use the same format, i.e. you must not
* mix expanded and compressed frames within a single method):
* <ul>
* <li>In expanded form, all frames must have the F_NEW type.</li>
* <li>In compressed form, frames are basically "deltas" from the state of
* the previous frame:
* <ul>
* <li>{@link Opcodes#F_SAME} representing frame with exactly the same
* locals as the previous frame and with the empty stack.</li>
* <li>{@link Opcodes#F_SAME1} representing frame with exactly the same
* locals as the previous frame and with single value on the stack (
* <code>nStack</code> is 1 and <code>stack[0]</code> contains value for the
* type of the stack item).</li>
* <li>{@link Opcodes#F_APPEND} representing frame with current locals are
* the same as the locals in the previous frame, except that additional
* locals are defined (<code>nLocal</code> is 1, 2 or 3 and
* <code>local</code> elements contains values representing added types).</li>
* <li>{@link Opcodes#F_CHOP} representing frame with current locals are the
* same as the locals in the previous frame, except that the last 1-3 locals
* are absent and with the empty stack (<code>nLocals</code> is 1, 2 or 3).</li>
* <li>{@link Opcodes#F_FULL} representing complete frame data.</li>
* </ul>
* </li>
* </ul>
* <br>
* In both cases the first frame, corresponding to the method's parameters
* and access flags, is implicit and must not be visited. Also, it is
* illegal to visit two or more frames for the same code location (i.e., at
* least one instruction must be visited between two calls to visitFrame).
*
* @param type
* the type of this stack map frame. Must be
* {@link Opcodes#F_NEW} for expanded frames, or
* {@link Opcodes#F_FULL}, {@link Opcodes#F_APPEND},
* {@link Opcodes#F_CHOP}, {@link Opcodes#F_SAME} or
* {@link Opcodes#F_APPEND}, {@link Opcodes#F_SAME1} for
* compressed frames.
* @param nLocal
* the number of local variables in the visited frame.
* @param local
* the local variable types in this frame. This array must not be
* modified. Primitive types are represented by
* {@link Opcodes#TOP}, {@link Opcodes#INTEGER},
* {@link Opcodes#FLOAT}, {@link Opcodes#LONG},
* {@link Opcodes#DOUBLE},{@link Opcodes#NULL} or
* {@link Opcodes#UNINITIALIZED_THIS} (long and double are
* represented by a single element). Reference types are
* represented by String objects (representing internal names),
* and uninitialized types by Label objects (this label
* designates the NEW instruction that created this uninitialized
* value).
* @param nStack
* the number of operand stack elements in the visited frame.
* @param stack
* the operand stack types in this frame. This array must not be
* modified. Its content has the same format as the "local"
* array.
* @throws IllegalStateException
* if a frame is visited just after another one, without any
* instruction between the two (unless this frame is a
* Opcodes#F_SAME frame, in which case it is silently ignored).
*/
public visitFrame(type?: any, nLocal?: any, local?: any, nStack?: any, stack?: any): any {
if (((typeof type === "number") || type === null) && ((typeof nLocal === "number") || nLocal === null) && ((local != null && local instanceof Array) || local === null) && ((typeof nStack === "number") || nStack === null) && ((stack != null && stack instanceof Array) || stack === null)) {
let __args = Array.prototype.slice.call(arguments);
return <any>(() => {
if (this.mv != null) {
this.mv.visitFrame(type, nLocal, local, nStack, stack);
}
})();
} else { throw new Error("invalid overload"); }
}
/**
* Visits a zero operand instruction.
*
* @param opcode
* the opcode of the instruction to be visited. This opcode is
* either NOP, ACONST_NULL, ICONST_M1, ICONST_0, ICONST_1,
* ICONST_2, ICONST_3, ICONST_4, ICONST_5, LCONST_0, LCONST_1,
* FCONST_0, FCONST_1, FCONST_2, DCONST_0, DCONST_1, IALOAD,
* LALOAD, FALOAD, DALOAD, AALOAD, BALOAD, CALOAD, SALOAD,
* IASTORE, LASTORE, FASTORE, DASTORE, AASTORE, BASTORE, CASTORE,
* SASTORE, POP, POP2, DUP, DUP_X1, DUP_X2, DUP2, DUP2_X1,
* DUP2_X2, SWAP, IADD, LADD, FADD, DADD, ISUB, LSUB, FSUB, DSUB,
* IMUL, LMUL, FMUL, DMUL, IDIV, LDIV, FDIV, DDIV, IREM, LREM,
* FREM, DREM, INEG, LNEG, FNEG, DNEG, ISHL, LSHL, ISHR, LSHR,
* IUSHR, LUSHR, IAND, LAND, IOR, LOR, IXOR, LXOR, I2L, I2F, I2D,
* L2I, L2F, L2D, F2I, F2L, F2D, D2I, D2L, D2F, I2B, I2C, I2S,
* LCMP, FCMPL, FCMPG, DCMPL, DCMPG, IRETURN, LRETURN, FRETURN,
* DRETURN, ARETURN, RETURN, ARRAYLENGTH, ATHROW, MONITORENTER,
* or MONITOREXIT.
*/
public visitInsn(opcode: number) {
if (this.mv != null) {
this.mv.visitInsn(opcode);
}
}
/**
* Visits an instruction with a single int operand.
*
* @param opcode
* the opcode of the instruction to be visited. This opcode is
* either BIPUSH, SIPUSH or NEWARRAY.
* @param operand
* the operand of the instruction to be visited.<br>
* When opcode is BIPUSH, operand value should be between
* Byte.MIN_VALUE and Byte.MAX_VALUE.<br>
* When opcode is SIPUSH, operand value should be between
* Short.MIN_VALUE and Short.MAX_VALUE.<br>
* When opcode is NEWARRAY, operand value should be one of
* {@link Opcodes#T_BOOLEAN}, {@link Opcodes#T_CHAR},
* {@link Opcodes#T_FLOAT}, {@link Opcodes#T_DOUBLE},
* {@link Opcodes#T_BYTE}, {@link Opcodes#T_SHORT},
* {@link Opcodes#T_INT} or {@link Opcodes#T_LONG}.
*/
public visitIntInsn(opcode: number, operand: number) {
if (this.mv != null) {
this.mv.visitIntInsn(opcode, operand);
}
}
/**
* Visits a local variable instruction. A local variable instruction is an
* instruction that loads or stores the value of a local variable.
*
* @param opcode
* the opcode of the local variable instruction to be visited.
* This opcode is either ILOAD, LLOAD, FLOAD, DLOAD, ALOAD,
* ISTORE, LSTORE, FSTORE, DSTORE, ASTORE or RET.
* @param var
* the operand of the instruction to be visited. This operand is
* the index of a local variable.
*/
public visitVarInsn(opcode: number, __var: number) {
if (this.mv != null) {
this.mv.visitVarInsn(opcode, __var);
}
}
/**
* Visits a type instruction. A type instruction is an instruction that
* takes the internal name of a class as parameter.
*
* @param opcode
* the opcode of the type instruction to be visited. This opcode
* is either NEW, ANEWARRAY, CHECKCAST or INSTANCEOF.
* @param type
* the operand of the instruction to be visited. This operand
* must be the internal name of an object or array class (see
* {@link Type#getInternalName() getInternalName}).
*/
public visitTypeInsn(opcode: number, type: string) {
if (this.mv != null) {
this.mv.visitTypeInsn(opcode, type);
}
}
/**
* Visits a field instruction. A field instruction is an instruction that
* loads or stores the value of a field of an object.
*
* @param opcode
* the opcode of the type instruction to be visited. This opcode
* is either GETSTATIC, PUTSTATIC, GETFIELD or PUTFIELD.
* @param owner
* the internal name of the field's owner class (see
* {@link Type#getInternalName() getInternalName}).
* @param name
* the field's name.
* @param desc
* the field's descriptor (see {@link Type Type}).
*/
public visitFieldInsn(opcode: number, owner: string, name: string | null, desc: string | null) {
if (this.mv != null) {
this.mv.visitFieldInsn(opcode, owner, name, desc);
}
}
/**
* Visits a method instruction. A method instruction is an instruction that
* invokes a method.
*
* @param opcode
* the opcode of the type instruction to be visited. This opcode
* is either INVOKEVIRTUAL, INVOKESPECIAL, INVOKESTATIC or
* INVOKEINTERFACE.
* @param owner
* the internal name of the method's owner class (see
* {@link Type#getInternalName() getInternalName}).
* @param name
* the method's name.
* @param desc
* the method's descriptor (see {@link Type Type}).
*/
public visitMethodInsn$int$java_lang_String$java_lang_String$java_lang_String(opcode: number, owner: string, name: string, desc: string) {
if (this.api >= Opcodes.ASM5) {
let itf: boolean = opcode === Opcodes.INVOKEINTERFACE;
this.visitMethodInsn(opcode, owner, name, desc, itf);
return;
}
if (this.mv != null) {
this.mv.visitMethodInsn(opcode, owner, name, desc);
}
}
/**
* Visits a method instruction. A method instruction is an instruction that
* invokes a method.
*
* @param opcode
* the opcode of the type instruction to be visited. This opcode
* is either INVOKEVIRTUAL, INVOKESPECIAL, INVOKESTATIC or
* INVOKEINTERFACE.
* @param owner
* the internal name of the method's owner class (see
* {@link Type#getInternalName() getInternalName}).
* @param name
* the method's name.
* @param desc
* the method's descriptor (see {@link Type Type}).
* @param itf
* if the method's owner class is an interface.
*/
public visitMethodInsn(opcode?: any, owner?: any, name?: any, desc?: any, itf?: any): any {
if (((typeof opcode === "number") || opcode === null) && ((typeof owner === "string") || owner === null) && ((typeof name === "string") || name === null) && ((typeof desc === "string") || desc === null) && ((typeof itf === "boolean") || itf === null)) {
let __args = Array.prototype.slice.call(arguments);
return <any>(() => {
if (this.api < Opcodes.ASM5) {
if (itf !== (opcode === Opcodes.INVOKEINTERFACE)) {
throw new Error("INVOKESPECIAL/STATIC on interfaces require ASM 5");
}
this.visitMethodInsn(opcode, owner, name, desc);
return;
}
if (this.mv != null) {
this.mv.visitMethodInsn(opcode, owner, name, desc, itf);
}
})();
} else if (((typeof opcode === "number") || opcode === null) && ((typeof owner === "string") || owner === null) && ((typeof name === "string") || name === null) && ((typeof desc === "string") || desc === null) && itf === undefined) {
return <any>this.visitMethodInsn$int$java_lang_String$java_lang_String$java_lang_String(opcode, owner, name, desc);
} else { throw new Error("invalid overload"); }
}
/**
* Visits an invokedynamic instruction.
*
* @param name
* the method's name.
* @param desc
* the method's descriptor (see {@link Type Type}).
* @param bsm
* the bootstrap method.
* @param bsmArgs
* the bootstrap method constant arguments. Each argument must be
* an {@link Integer}, {@link Float}, {@link Long},
* {@link Double}, {@link String}, {@link Type} or {@link Handle}
* value. This method is allowed to modify the content of the
* array so a caller should expect that this array may change.
*/
public visitInvokeDynamicInsn(name: string, desc: string, bsm: Handle, ...bsmArgs: any[]) {
if (this.mv != null) {
this.mv.visitInvokeDynamicInsn(name, desc, bsm, ...bsmArgs);
}
}
/**
* Visits a jump instruction. A jump instruction is an instruction that may
* jump to another instruction.
*
* @param opcode
* the opcode of the type instruction to be visited. This opcode
* is either IFEQ, IFNE, IFLT, IFGE, IFGT, IFLE, IF_ICMPEQ,
* IF_ICMPNE, IF_ICMPLT, IF_ICMPGE, IF_ICMPGT, IF_ICMPLE,
* IF_ACMPEQ, IF_ACMPNE, GOTO, JSR, IFNULL or IFNONNULL.
* @param label
* the operand of the instruction to be visited. This operand is
* a label that designates the instruction to which the jump
* instruction may jump.
*/
public visitJumpInsn(opcode: number, label: Label) {
if (this.mv != null) {
this.mv.visitJumpInsn(opcode, label);
}
}
/**
* Visits a label. A label designates the instruction that will be visited
* just after it.
*
* @param label
* a {@link Label Label} object.
*/
public visitLabel(label: Label) {
if (this.mv != null) {
this.mv.visitLabel(label);
}
}
/**
* Visits a LDC instruction. Note that new constant types may be added in
* future versions of the Java Virtual Machine. To easily detect new
* constant types, implementations of this method should check for
* unexpected constant types, like this:
*
* <pre>
* if (cst instanceof Integer) {
* // ...
* } else if (cst instanceof Float) {
* // ...
* } else if (cst instanceof Long) {
* // ...
* } else if (cst instanceof Double) {
* // ...
* } else if (cst instanceof String) {
* // ...
* } else if (cst instanceof Type) {
* int sort = ((Type) cst).getSort();
* if (sort == Type.OBJECT) {
* // ...
* } else if (sort == Type.ARRAY) {
* // ...
* } else if (sort == Type.METHOD) {
* // ...
* } else {
* // throw an exception
* }
* } else if (cst instanceof Handle) {
* // ...
* } else {
* // throw an exception
* }
* </pre>
*
* @param cst
* the constant to be loaded on the stack. This parameter must be
* a non null {@link Integer}, a {@link Float}, a {@link Long}, a
* {@link Double}, a {@link String}, a {@link Type} of OBJECT or
* ARRAY sort for <tt>.class</tt> constants, for classes whose
* version is 49.0, a {@link Type} of METHOD sort or a
* {@link Handle} for MethodType and MethodHandle constants, for
* classes whose version is 51.0.
*/
public visitLdcInsn(cst: any) {
if (this.mv != null) {
this.mv.visitLdcInsn(cst);
}
}
/**
* Visits an IINC instruction.
*
* @param var
* index of the local variable to be incremented.
* @param increment
* amount to increment the local variable by.
*/
public visitIincInsn(__var: number, increment: number) {
if (this.mv != null) {
this.mv.visitIincInsn(__var, increment);
}
}
/**
* Visits a TABLESWITCH instruction.
*
* @param min
* the minimum key value.
* @param max
* the maximum key value.
* @param dflt
* beginning of the default handler block.
* @param labels
* beginnings of the handler blocks. <tt>labels[i]</tt> is the
* beginning of the handler block for the <tt>min + i</tt> key.
*/
public visitTableSwitchInsn(min: number, max: number, dflt: Label, ...labels: Label[]) {
if (this.mv != null) {
this.mv.visitTableSwitchInsn(min, max, dflt, ...labels);
}
}
/**
* Visits a LOOKUPSWITCH instruction.
*
* @param dflt
* beginning of the default handler block.
* @param keys
* the values of the keys.
* @param labels
* beginnings of the handler blocks. <tt>labels[i]</tt> is the
* beginning of the handler block for the <tt>keys[i]</tt> key.
*/
public visitLookupSwitchInsn(dflt: Label, keys: number[], labels: Label[]) {
if (this.mv != null) {
this.mv.visitLookupSwitchInsn(dflt, keys, labels);
}
}
/**
* Visits a MULTIANEWARRAY instruction.
*
* @param desc
* an array type descriptor (see {@link Type Type}).
* @param dims
* number of dimensions of the array to allocate.
*/
public visitMultiANewArrayInsn(desc: string, dims: number) {
if (this.mv != null) {
this.mv.visitMultiANewArrayInsn(desc, dims);
}
}
/**
* Visits an annotation on an instruction. This method must be called just
* <i>after</i> the annotated instruction. It can be called several times
* for the same instruction.
*
* @param typeRef
* a reference to the annotated type. The sort of this type
* reference must be {@link TypeReference#INSTANCEOF INSTANCEOF},
* {@link TypeReference#NEW NEW},
* {@link TypeReference#CONSTRUCTOR_REFERENCE
* CONSTRUCTOR_REFERENCE}, {@link TypeReference#METHOD_REFERENCE
* METHOD_REFERENCE}, {@link TypeReference#CAST CAST},
* {@link TypeReference#CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT
* CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT},
* {@link TypeReference#METHOD_INVOCATION_TYPE_ARGUMENT
* METHOD_INVOCATION_TYPE_ARGUMENT},
* {@link TypeReference#CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT
* CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT}, or
* {@link TypeReference#METHOD_REFERENCE_TYPE_ARGUMENT
* METHOD_REFERENCE_TYPE_ARGUMENT}. See {@link TypeReference}.
* @param typePath
* the path to the annotated type argument, wildcard bound, array
* element type, or static inner type within 'typeRef'. May be
* <tt>null</tt> if the annotation targets 'typeRef' as a whole.
* @param desc
* the class descriptor of the annotation class.
* @param visible
* <tt>true</tt> if the annotation is visible at runtime.
* @return a visitor to visit the annotation values, or <tt>null</tt> if
* this visitor is not interested in visiting this annotation.
*/
public visitInsnAnnotation(typeRef: number, typePath: TypePath | null, desc: string | null, visible: boolean): AnnotationVisitor | null {
if (this.api < Opcodes.ASM5) {
throw new Error();
}
if (this.mv != null) {
return this.mv.visitInsnAnnotation(typeRef, typePath, desc, visible);
}
return null;
}
/**
* Visits a try catch block.
*
* @param start
* beginning of the exception handler's scope (inclusive).
* @param end
* end of the exception handler's scope (exclusive).
* @param handler
* beginning of the exception handler's code.
* @param type
* internal name of the type of exceptions handled by the
* handler, or <tt>null</tt> to catch any exceptions (for
* "finally" blocks).
* @throws IllegalArgumentException
* if one of the labels has already been visited by this visitor
* (by the {@link #visitLabel visitLabel} method).
*/
public visitTryCatchBlock(start: Label, end: Label, handler: Label, type: string | null) {
if (this.mv != null) {
this.mv.visitTryCatchBlock(start, end, handler, type);
}
}
/**
* Visits an annotation on an exception handler type. This method must be
* called <i>after</i> the {@link #visitTryCatchBlock} for the annotated
* exception handler. It can be called several times for the same exception
* handler.
*
* @param typeRef
* a reference to the annotated type. The sort of this type
* reference must be {@link TypeReference#EXCEPTION_PARAMETER
* EXCEPTION_PARAMETER}. See {@link TypeReference}.
* @param typePath
* the path to the annotated type argument, wildcard bound, array
* element type, or static inner type within 'typeRef'. May be
* <tt>null</tt> if the annotation targets 'typeRef' as a whole.
* @param desc
* the class descriptor of the annotation class.
* @param visible
* <tt>true</tt> if the annotation is visible at runtime.
* @return a visitor to visit the annotation values, or <tt>null</tt> if
* this visitor is not interested in visiting this annotation.
*/
public visitTryCatchAnnotation(typeRef: number, typePath: TypePath | null, desc: string | null, visible: boolean): AnnotationVisitor | null {
if (this.api < Opcodes.ASM5) {
throw new Error();
}
if (this.mv != null) {
return this.mv.visitTryCatchAnnotation(typeRef, typePath, desc, visible);
}
return null;
}
/**
* Visits a local variable declaration.
*
* @param name
* the name of a local variable.
* @param desc
* the type descriptor of this local variable.
* @param signature
* the type signature of this local variable. May be
* <tt>null</tt> if the local variable type does not use generic
* types.
* @param start
* the first instruction corresponding to the scope of this local
* variable (inclusive).
* @param end
* the last instruction corresponding to the scope of this local
* variable (exclusive).
* @param index
* the local variable's index.
* @throws IllegalArgumentException
* if one of the labels has not already been visited by this
* visitor (by the {@link #visitLabel visitLabel} method).
*/
public visitLocalVariable(name: string | null, desc: string | null, signature: string | null, start: Label, end: Label, index: number) {
if (this.mv != null) {
this.mv.visitLocalVariable(name, desc, signature, start, end, index);
}
}
/**
* Visits an annotation on a local variable type.
*
* @param typeRef
* a reference to the annotated type. The sort of this type
* reference must be {@link TypeReference#LOCAL_VARIABLE
* LOCAL_VARIABLE} or {@link TypeReference#RESOURCE_VARIABLE
* RESOURCE_VARIABLE}. See {@link TypeReference}.
* @param typePath
* the path to the annotated type argument, wildcard bound, array
* element type, or static inner type within 'typeRef'. May be
* <tt>null</tt> if the annotation targets 'typeRef' as a whole.
* @param start
* the fist instructions corresponding to the continuous ranges
* that make the scope of this local variable (inclusive).
* @param end
* the last instructions corresponding to the continuous ranges
* that make the scope of this local variable (exclusive). This
* array must have the same size as the 'start' array.
* @param index
* the local variable's index in each range. This array must have
* the same size as the 'start' array.
* @param desc
* the class descriptor of the annotation class.
* @param visible
* <tt>true</tt> if the annotation is visible at runtime.
* @return a visitor to visit the annotation values, or <tt>null</tt> if
* this visitor is not interested in visiting this annotation.
*/
public visitLocalVariableAnnotation(typeRef: number, typePath: TypePath | null, start: Label[], end: Label[], index: number[], desc: string | null, visible: boolean): AnnotationVisitor | null {
if (this.api < Opcodes.ASM5) {
throw new Error();
}
if (this.mv != null) {
return this.mv.visitLocalVariableAnnotation(typeRef, typePath, start, end, index, desc, visible);
}
return null;
}
/**
* Visits a line number declaration.
*
* @param line
* a line number. This number refers to the source file from
* which the class was compiled.
* @param start
* the first instruction corresponding to this line number.
* @throws IllegalArgumentException
* if <tt>start</tt> has not already been visited by this
* visitor (by the {@link #visitLabel visitLabel} method).
*/
public visitLineNumber(line: number, start: Label) {
if (this.mv != null) {
this.mv.visitLineNumber(line, start);
}
}
/**
* Visits the maximum stack size and the maximum number of local variables
* of the method.
*
* @param maxStack
* maximum stack size of the method.
* @param maxLocals
* maximum number of local variables for the method.
*/
public visitMaxs(maxStack: number, maxLocals: number) {
if (this.mv != null) {
this.mv.visitMaxs(maxStack, maxLocals);
}
}
/**
* Visits the end of the method. This method, which is the last one to be
* called, is used to inform the visitor that all the annotations and
* attributes of the method have been visited.
*/
public visitEnd() {
if (this.mv != null) {
this.mv.visitEnd();
}
}
} | the_stack |
import { INestApplication } from '@nestjs/common'
import { Test } from '@nestjs/testing'
import { KubernetesManifest } from '../../../../app/v2/core/integrations/interfaces/k8s-manifest.interface'
import * as request from 'supertest'
import { EntityManager } from 'typeorm'
import { AppModule } from '../../../../app/app.module'
import { ComponentEntityV2 as ComponentEntity } from '../../../../app/v2/api/deployments/entity/component.entity'
import { DeploymentEntityV2 as DeploymentEntity } from '../../../../app/v2/api/deployments/entity/deployment.entity'
import { Execution } from '../../../../app/v2/api/deployments/entity/execution.entity'
import { ExecutionTypeEnum } from '../../../../app/v2/api/deployments/enums'
import { FixtureUtilsService } from '../fixture-utils.service'
import { TestSetupUtils } from '../test-setup-utils'
import { simpleManifests } from '../../fixtures/manifests.fixture'
import { UrlConstants } from '../test-constants'
describe('Execution Controller v2', () => {
let fixtureUtilsService: FixtureUtilsService
let app: INestApplication
let manager: EntityManager
let manifests: KubernetesManifest[]
beforeAll(async() => {
const module = Test.createTestingModule({
imports: [
await AppModule.forRootAsync()
],
providers: [
FixtureUtilsService
]
})
app = await TestSetupUtils.createApplication(module)
TestSetupUtils.seApplicationConstants()
fixtureUtilsService = app.get<FixtureUtilsService>(FixtureUtilsService)
manager = fixtureUtilsService.manager
manifests = simpleManifests
})
afterAll(async() => {
await fixtureUtilsService.clearDatabase()
await app.close()
})
beforeEach(async() => {
await fixtureUtilsService.clearDatabase()
})
it('validate query string parameters', async() => {
const errorResponse = {
errors: [{
meta: {
component: 'butler',
timestamp: expect.anything()
},
source: {
pointer: 'size'
},
status: 400,
title: '"size" must be greater than or equal to 1'
},
{
meta: {
component: 'butler',
timestamp: expect.anything()
},
source: {
pointer: 'page'
},
status: 400,
title: '"page" must be greater than or equal to 0'
}]
}
await request(app.getHttpServer())
.get('/v2/executions').query({ current: false, size: 0, page: -1 })
.set('x-circle-id', 'a45fd548-0082-4021-ba80-a50703c44a3b')
.expect(response => {
expect(response.body).toEqual(errorResponse)
})
})
it('returns the right entity values', async() => {
const params = {
defaultCircle: false,
deploymentId: '28a3f957-3702-4c4e-8d92-015939f39cf2',
circle: '333365f8-bb29-49f7-bf2b-3ec956a71583',
components: [
{
helmRepository: UrlConstants.helmRepository,
componentId: '777765f8-bb29-49f7-bf2b-3ec956a71583',
buildImageUrl: 'imageurl.com',
buildImageTag: 'tag1',
componentName: 'component-name',
hostValue: 'host-value',
gatewayName: 'gateway-name'
}
],
authorId: '580a7726-a274-4fc3-9ec1-44e3563d58af',
callbackUrl: UrlConstants.deploymentCallbackUrl,
incomingCircleId: '0d81c2b0-37f2-4ef9-8b96-afb2e3979a30',
}
await createDeploymentAndExecution(params, 'namespace', manifests, manager)
const expectedBody = {
createdAt: expect.any(String),
deployment: {
current: false,
author_id: '580a7726-a274-4fc3-9ec1-44e3563d58af',
callback_url: UrlConstants.deploymentCallbackUrl,
circle_id: '333365f8-bb29-49f7-bf2b-3ec956a71583',
components: [
{
id: expect.any(String),
image_tag: 'tag1',
image_url: 'imageurl.com',
merged: false,
name: 'component-name',
running: false,
hostValue: 'host-value',
gatewayName: 'gateway-name'
}
],
created_at: expect.any(String),
id: '28a3f957-3702-4c4e-8d92-015939f39cf2'
},
finishedAt: null,
id: expect.any(String),
incomingCircleId: '0d81c2b0-37f2-4ef9-8b96-afb2e3979a30',
notificationStatus: 'NOT_SENT',
status: 'CREATED',
type: 'DEPLOYMENT'
}
await request(app.getHttpServer())
.get('/v2/executions').query({ current: false, size: 1, page: 0 })
.set('x-circle-id', 'a45fd548-0082-4021-ba80-a50703c44a3b')
.expect(200)
.expect(response => {
expect(response.body.items[0]).toEqual(expectedBody)
})
})
it('parameters are optional when quering executions', async() => {
const params = {
deploymentId: '28a3f957-3702-4c4e-8d92-015939f39cf2',
circle: '333365f8-bb29-49f7-bf2b-3ec956a71583',
components: [
{
helmRepository: 'https://some-helm.repo',
componentId: '777765f8-bb29-49f7-bf2b-3ec956a71583',
buildImageUrl: 'imageurl.com',
buildImageTag: 'tag1',
componentName: 'component-name',
hostValue: 'host-value',
gatewayName: 'gateway-name'
}
],
authorId: '580a7726-a274-4fc3-9ec1-44e3563d58af',
callbackUrl: 'http://localhost:8883/deploy/notifications/deployment',
incomingCircleId: '0d81c2b0-37f2-4ef9-8b96-afb2e3979a30',
defaultCircle: false
}
await createDeploymentAndExecution(params, 'default', [], manager)
const expectedBody = {
createdAt: expect.any(String),
deployment: {
current: false,
author_id: '580a7726-a274-4fc3-9ec1-44e3563d58af',
callback_url: 'http://localhost:8883/deploy/notifications/deployment',
circle_id: '333365f8-bb29-49f7-bf2b-3ec956a71583',
components: [
{
id: expect.any(String),
image_tag: 'tag1',
image_url: 'imageurl.com',
merged: false,
name: 'component-name',
running: false,
hostValue: 'host-value',
gatewayName: 'gateway-name'
}
],
created_at: expect.any(String),
id: '28a3f957-3702-4c4e-8d92-015939f39cf2'
},
finishedAt: null,
id: expect.any(String),
incomingCircleId: '0d81c2b0-37f2-4ef9-8b96-afb2e3979a30',
notificationStatus: 'NOT_SENT',
status: 'CREATED',
type: 'DEPLOYMENT'
}
await request(app.getHttpServer())
.get('/v2/executions')
.set('x-circle-id', 'a45fd548-0082-4021-ba80-a50703c44a3b')
.expect(200)
.expect(response => {
expect(response.body.items[0]).toEqual(expectedBody)
})
})
it('returns correct page size and last page false', async() => {
const params = {
deploymentId: '28a3f957-3702-4c4e-8d92-015939f39cf2',
circle: '333365f8-bb29-49f7-bf2b-3ec956a71583',
components: [
{
helmRepository: 'https://some-helm.repo',
componentId: '777765f8-bb29-49f7-bf2b-3ec956a71583',
buildImageUrl: 'imageurl.com',
buildImageTag: 'tag1',
componentName: 'component-name',
hostValue: 'host-value',
gatewayName: 'gateway-name'
}
],
authorId: '580a7726-a274-4fc3-9ec1-44e3563d58af',
callbackUrl: 'http://localhost:8883/deploy/notifications/deployment',
incomingCircleId: '0d81c2b0-37f2-4ef9-8b96-afb2e3979a30',
defaultCircle: false
}
await createDeploymentAndExecution(params, 'deafult', [], manager)
await createDeploymentAndExecution({ ...params, deploymentId: 'a33365f8-bb29-49f7-bf2b-3ec956a71583' }, 'default', [], manager)
await createDeploymentAndExecution({ ...params, deploymentId: 'b33365f8-bb29-49f7-bf2b-3ec956a71583' }, 'default', [], manager)
await request(app.getHttpServer())
.get('/v2/executions?size=2&page=0')
.set('x-circle-id', 'a45fd548-0082-4021-ba80-a50703c44a3b')
.expect(200)
.expect(response => {
expect(response.body.size).toEqual(2)
expect(response.body.last).toEqual(false)
})
})
it('returns correct page size and last page true', async() => {
const params = {
deploymentId: '28a3f957-3702-4c4e-8d92-015939f39cf2',
circle: '333365f8-bb29-49f7-bf2b-3ec956a71583',
components: [
{
helmRepository: 'https://some-helm.repo',
componentId: '777765f8-bb29-49f7-bf2b-3ec956a71583',
buildImageUrl: 'imageurl.com',
buildImageTag: 'tag1',
componentName: 'component-name',
hostValue: 'host-value',
gatewayName: 'gateway-name'
}
],
authorId: '580a7726-a274-4fc3-9ec1-44e3563d58af',
callbackUrl: 'http://localhost:8883/deploy/notifications/deployment',
incomingCircleId: '0d81c2b0-37f2-4ef9-8b96-afb2e3979a30',
defaultCircle: false
}
await createDeploymentAndExecution(params, 'default', [], manager)
await createDeploymentAndExecution({ ...params, deploymentId: 'a33365f8-bb29-49f7-bf2b-3ec956a71583' }, 'default', [], manager)
await createDeploymentAndExecution({ ...params, deploymentId: 'b33365f8-bb29-49f7-bf2b-3ec956a71583' }, 'default', [], manager)
await request(app.getHttpServer())
.get('/v2/executions?size=2&page=1')
.set('x-circle-id', 'a45fd548-0082-4021-ba80-a50703c44a3b')
.expect(200)
.expect(response => {
expect(response.body.size).toEqual(1)
expect(response.body.last).toEqual(true)
})
})
})
const createDeploymentAndExecution = async(params: any, namespace: string, manifests: KubernetesManifest[], manager: any) : Promise<Execution> => {
const components = params.components.map((c: any) => {
return new ComponentEntity(
c.helmRepository,
c.buildImageTag,
c.buildImageUrl,
c.componentName,
c.componentId,
c.hostValue,
c.gatewayName,
manifests
)
})
const deployment : DeploymentEntity = await manager.save(new DeploymentEntity(
params.deploymentId,
params.authorId,
params.circle,
params.callbackUrl,
components,
params.defaultCircle,
namespace,
5
))
const execution : Execution = await manager.save(new Execution(
deployment,
ExecutionTypeEnum.DEPLOYMENT,
params.incomingCircleId,
params.deploymentStatus,
))
return execution
} | the_stack |
import { Collection, Db, ObjectID, IndexOptions } from 'mongodb';
import { CreateUserServicePassword, DatabaseInterfaceServicePassword, User } from '@accounts/types';
import { toMongoID } from './utils';
export interface MongoUser {
_id?: string | object;
username?: string;
services: {
password?: {
bcrypt: string;
};
};
emails?: [
{
address: string;
verified: boolean;
}
];
[key: string]: any;
}
export interface MongoServicePasswordOptions {
/**
* Mongo database object.
*/
database: Db;
/**
* The users collection name.
* Default 'users'.
*/
userCollectionName?: string;
/**
* The timestamps for the users collection.
* Default 'createdAt' and 'updatedAt'.
*/
timestamps?: {
createdAt: string;
updatedAt: string;
};
/**
* Should the user collection use _id as string or ObjectId.
* Default 'true'.
*/
convertUserIdToMongoObjectId?: boolean;
/**
* Perform case intensitive query for user name.
* Default 'true'.
*/
caseSensitiveUserName?: boolean;
/**
* Function that generate the id for new objects.
*/
idProvider?: () => string | object;
/**
* Function that generate the date for the timestamps.
* Default to `(date?: Date) => (date ? date.getTime() : Date.now())`.
*/
dateProvider?: (date?: Date) => any;
}
const defaultOptions = {
userCollectionName: 'users',
timestamps: {
createdAt: 'createdAt',
updatedAt: 'updatedAt',
},
convertUserIdToMongoObjectId: true,
caseSensitiveUserName: true,
dateProvider: (date?: Date) => (date ? date.getTime() : Date.now()),
};
export class MongoServicePassword implements DatabaseInterfaceServicePassword {
// Merged options that can be used
private options: MongoServicePasswordOptions & typeof defaultOptions;
// Mongo database object
private database: Db;
// Mongo user collection
private userCollection: Collection;
constructor(options: MongoServicePasswordOptions) {
this.options = {
...defaultOptions,
...options,
timestamps: { ...defaultOptions.timestamps, ...options.timestamps },
};
this.database = this.options.database;
this.userCollection = this.database.collection(this.options.userCollectionName);
}
/**
* Setup the mongo indexes needed for the password service.
* @param options Options passed to the mongo native `createIndex` method.
*/
public async setupIndexes(options: Omit<IndexOptions, 'unique' | 'sparse'> = {}): Promise<void> {
// Username index to allow fast queries made with username
// Username is unique
await this.userCollection.createIndex('username', {
...options,
unique: true,
sparse: true,
});
// Emails index to allow fast queries made with emails, a user can have multiple emails
// Email address is unique
await this.userCollection.createIndex('emails.address', {
...options,
unique: true,
sparse: true,
});
// Token index used to verify the email address of a user
await this.userCollection.createIndex('services.email.verificationTokens.token', {
...options,
sparse: true,
});
// Token index used to verify a password reset request
await this.userCollection.createIndex('services.password.reset.token', {
...options,
sparse: true,
});
}
/**
* Create a new user by providing an email and/or a username and password.
* Emails are saved lowercased.
*/
public async createUser({
password,
username,
email,
...cleanUser
}: CreateUserServicePassword): Promise<string> {
const user: MongoUser = {
...cleanUser,
services: {
password: {
bcrypt: password,
},
},
[this.options.timestamps.createdAt]: this.options.dateProvider(),
[this.options.timestamps.updatedAt]: this.options.dateProvider(),
};
if (username) {
user.username = username;
}
if (email) {
user.emails = [{ address: email.toLowerCase(), verified: false }];
}
if (this.options.idProvider) {
user._id = this.options.idProvider();
}
const ret = await this.userCollection.insertOne(user);
// keep ret.ops for compatibility with MongoDB 3.X, version 4.X uses insertedId
return ((ret.insertedId ?? ret.ops[0]._id) as ObjectID).toString();
}
/**
* Get a user by his id.
* @param userId Id used to query the user.
*/
public async findUserById(userId: string): Promise<User | null> {
const id = this.options.convertUserIdToMongoObjectId ? toMongoID(userId) : userId;
const user = await this.userCollection.findOne({ _id: id });
if (user) {
user.id = user._id.toString();
}
return user;
}
/**
* Get a user by one of his emails.
* Email will be lowercased before running the query.
* @param email Email used to query the user.
*/
public async findUserByEmail(email: string): Promise<User | null> {
const user = await this.userCollection.findOne({
'emails.address': email.toLowerCase(),
});
if (user) {
user.id = user._id.toString();
}
return user;
}
/**
* Get a user by his username.
* Set the `caseSensitiveUserName` option to false if you want the username to be case sensitive.
* @param email Email used to query the user.
*/
public async findUserByUsername(username: string): Promise<User | null> {
const filter = this.options.caseSensitiveUserName
? { username }
: {
$where: `obj.username && (obj.username.toLowerCase() === "${username.toLowerCase()}")`,
};
const user = await this.userCollection.findOne(filter);
if (user) {
user.id = user._id.toString();
}
return user;
}
/**
* Return the user password hash.
* If the user has no password set, will return null.
* @param userId Id used to query the user.
*/
public async findPasswordHash(userId: string): Promise<string | null> {
const user = await this.findUserById(userId);
return user?.services?.password?.bcrypt ?? null;
}
/**
* Get a user by one of the email verification token.
* @param token Verification token used to query the user.
*/
public async findUserByEmailVerificationToken(token: string): Promise<User | null> {
const user = await this.userCollection.findOne({
'services.email.verificationTokens.token': token,
});
if (user) {
user.id = user._id.toString();
}
return user;
}
/**
* Get a user by one of the reset password token.
* @param token Reset password token used to query the user.
*/
public async findUserByResetPasswordToken(token: string): Promise<User | null> {
const user = await this.userCollection.findOne({
'services.password.reset.token': token,
});
if (user) {
user.id = user._id.toString();
}
return user;
}
/**
* Add an email address for a user.
* @param userId Id used to update the user.
* @param newEmail A new email address for the user.
* @param verified Whether the new email address should be marked as verified.
*/
public async addEmail(userId: string, newEmail: string, verified: boolean): Promise<void> {
const id = this.options.convertUserIdToMongoObjectId ? toMongoID(userId) : userId;
const ret = await this.userCollection.updateOne(
{ _id: id },
{
$addToSet: {
emails: {
address: newEmail.toLowerCase(),
verified,
},
},
$set: {
[this.options.timestamps.updatedAt]: this.options.dateProvider(),
},
}
);
if (ret.result.nModified === 0) {
throw new Error('User not found');
}
}
/**
* Remove an email address for a user.
* @param userId Id used to update the user.
* @param email The email address to remove.
*/
public async removeEmail(userId: string, email: string): Promise<void> {
const id = this.options.convertUserIdToMongoObjectId ? toMongoID(userId) : userId;
const ret = await this.userCollection.updateOne(
{ _id: id },
{
$pull: { emails: { address: email.toLowerCase() } },
$set: {
[this.options.timestamps.updatedAt]: this.options.dateProvider(),
},
}
);
if (ret.result.nModified === 0) {
throw new Error('User not found');
}
}
/**
* Marks the user's email address as verified.
* @param userId Id used to update the user.
* @param email The email address to mark as verified.
*/
public async verifyEmail(userId: string, email: string): Promise<void> {
const id = this.options.convertUserIdToMongoObjectId ? toMongoID(userId) : userId;
const ret = await this.userCollection.updateOne(
{ _id: id, 'emails.address': email },
{
$set: {
'emails.$.verified': true,
[this.options.timestamps.updatedAt]: this.options.dateProvider(),
},
$pull: { 'services.email.verificationTokens': { address: email } },
}
);
if (ret.result.nModified === 0) {
throw new Error('User not found');
}
}
/**
* Change the username of the user.
* If the username already exists, the function will fail.
* @param userId Id used to update the user.
* @param newUsername A new username for the user.
*/
public async setUsername(userId: string, newUsername: string): Promise<void> {
const id = this.options.convertUserIdToMongoObjectId ? toMongoID(userId) : userId;
const ret = await this.userCollection.updateOne(
{ _id: id },
{
$set: {
username: newUsername,
[this.options.timestamps.updatedAt]: this.options.dateProvider(),
},
}
);
if (ret.result.nModified === 0) {
throw new Error('User not found');
}
}
/**
* Change the password for a user.
* @param userId Id used to update the user.
* @param newPassword A new password for the user.
*/
public async setPassword(userId: string, newPassword: string): Promise<void> {
const id = this.options.convertUserIdToMongoObjectId ? toMongoID(userId) : userId;
const ret = await this.userCollection.updateOne(
{ _id: id },
{
$set: {
'services.password.bcrypt': newPassword,
[this.options.timestamps.updatedAt]: this.options.dateProvider(),
},
$unset: {
'services.password.reset': '',
},
}
);
if (ret.result.nModified === 0) {
throw new Error('User not found');
}
}
/**
* Add an email verification token to a user.
* @param userId Id used to update the user.
* @param email Which address of the user's to link the token to.
* @param token Random token used to verify the user email.
*/
public async addEmailVerificationToken(
userId: string,
email: string,
token: string
): Promise<void> {
const _id = this.options.convertUserIdToMongoObjectId ? toMongoID(userId) : userId;
await this.userCollection.updateOne(
{ _id },
{
$push: {
'services.email.verificationTokens': {
token,
address: email.toLowerCase(),
when: this.options.dateProvider(),
},
},
}
);
}
/**
* Add a reset password token to a user.
* @param userId Id used to update the user.
* @param email Which address of the user's to link the token to.
* @param token Random token used to verify the user email.
* @param reason Reason to use for the token.
*/
public async addResetPasswordToken(
userId: string,
email: string,
token: string,
reason: string
): Promise<void> {
const _id = this.options.convertUserIdToMongoObjectId ? toMongoID(userId) : userId;
await this.userCollection.updateOne(
{ _id },
{
$push: {
'services.password.reset': {
token,
address: email.toLowerCase(),
when: this.options.dateProvider(),
reason,
},
},
}
);
}
/**
* Remove all the reset password tokens for a user.
* @param userId Id used to update the user.
*/
public async removeAllResetPasswordTokens(userId: string): Promise<void> {
const id = this.options.convertUserIdToMongoObjectId ? toMongoID(userId) : userId;
await this.userCollection.updateOne(
{ _id: id },
{
$unset: {
'services.password.reset': '',
},
}
);
}
} | the_stack |
import { describe } from 'mocha'
import { restore, fake, replace, spy } from 'sinon'
import { ReadModelStore } from '../../src/services/read-model-store'
import { buildLogger } from '../../src/booster-logger'
import {
Level,
Logger,
BoosterConfig,
EventEnvelope,
UUID,
ProviderLibrary,
ReadModelAction,
OptimisticConcurrencyUnexpectedVersionError,
ProjectionResult,
InvalidParameterError,
} from '@boostercloud/framework-types'
import { expect } from '../expect'
import { createInstance } from '@boostercloud/framework-common-helpers'
describe('ReadModelStore', () => {
afterEach(() => {
restore()
})
const logger = buildLogger(Level.error)
class AnImportantEntity {
public constructor(readonly id: UUID, readonly someKey: UUID, readonly count: number) {}
public getPrefixedKey(prefix: string): string {
return `${prefix}-${this.someKey}`
}
}
class AnEntity {
public constructor(readonly id: UUID, readonly someKey: UUID, readonly count: number) {}
}
class SomeReadModel {
public constructor(readonly id: UUID) {}
public static someObserver(entity: AnImportantEntity, obj: any): any {
const count = (obj?.count || 0) + entity.count
return { id: entity.someKey, kind: 'some', count: count }
}
public getId(): UUID {
return this.id
}
public static projectionThatCallsReadModelMethod(
entity: AnEntity,
currentReadModel: SomeReadModel
): ProjectionResult<SomeReadModel> {
currentReadModel.getId()
return ReadModelAction.Nothing
}
public static projectionThatCallsEntityMethod(
entity: AnImportantEntity,
currentReadModel: SomeReadModel
): ProjectionResult<SomeReadModel> {
entity.getPrefixedKey('a prefix')
return ReadModelAction.Nothing
}
}
class AnotherReadModel {
public constructor(readonly id: UUID) {}
public static anotherObserver(entity: AnImportantEntity, obj: any): any {
const count = (obj?.count || 0) + entity.count
return { id: entity.someKey, kind: 'another', count: count }
}
}
const config = new BoosterConfig('test')
config.provider = {
readModels: {
store: () => {},
delete: () => {},
fetch: () => {},
},
} as unknown as ProviderLibrary
config.entities[AnImportantEntity.name] = { class: AnImportantEntity, authorizeReadEvents: [] }
config.entities[AnEntity.name] = { class: AnEntity, authorizeReadEvents: [] }
config.readModels[SomeReadModel.name] = {
class: SomeReadModel,
authorizedRoles: 'all',
properties: [],
before: [],
}
config.readModels[AnotherReadModel.name] = {
class: AnotherReadModel,
authorizedRoles: 'all',
properties: [],
before: [],
}
config.projections[AnImportantEntity.name] = [
{
class: SomeReadModel,
methodName: 'someObserver',
joinKey: 'someKey',
},
{
class: SomeReadModel,
methodName: 'projectionThatCallsEntityMethod',
joinKey: 'someKey',
},
{
class: AnotherReadModel,
methodName: 'anotherObserver',
joinKey: 'someKey',
},
]
config.projections['AnEntity'] = [
{
class: SomeReadModel,
methodName: 'projectionThatCallsReadModelMethod',
joinKey: 'someKey',
},
]
function eventEnvelopeFor(entityName: string): EventEnvelope {
return {
version: 1,
kind: 'snapshot',
entityID: '42',
entityTypeName: entityName,
value: {
id: 'importantEntityID',
someKey: 'joinColumnID',
count: 123,
} as any,
requestID: 'whatever',
typeName: entityName,
createdAt: new Date().toISOString(),
}
}
describe('the `project` method', () => {
context('when the entity class has no projections', () => {
it('returns without errors and without performing any actions', async () => {
const entitySnapshotWithNoProjections: EventEnvelope = {
version: 1,
kind: 'snapshot',
entityID: '42',
entityTypeName: 'AConceptWithoutProjections',
value: { entityID: () => '42' },
requestID: 'whatever',
typeName: AnImportantEntity.name,
createdAt: new Date().toISOString(),
}
replace(config.provider.readModels, 'store', fake())
const readModelStore = new ReadModelStore(config, logger)
replace(readModelStore, 'fetchReadModel', fake.returns(null))
await expect(readModelStore.project(entitySnapshotWithNoProjections)).to.eventually.be.fulfilled
expect(config.provider.readModels.store).not.to.have.been.called
expect(readModelStore.fetchReadModel).not.to.have.been.called
})
})
context('when the new read model returns ReadModelAction.Delete', () => {
it('deletes the associated read model', async () => {
replace(config.provider.readModels, 'store', fake())
replace(config.provider.readModels, 'delete', fake())
replace(
ReadModelStore.prototype,
'projectionFunction',
fake.returns(() => ReadModelAction.Delete)
)
const readModelStore = new ReadModelStore(config, logger)
await readModelStore.project(eventEnvelopeFor(AnImportantEntity.name))
expect(config.provider.readModels.store).not.to.have.been.called
expect(config.provider.readModels.delete).to.have.been.calledThrice
})
})
context('when the new read model returns ReadModelAction.Nothing', () => {
it('ignores the read model', async () => {
replace(config.provider.readModels, 'store', fake())
replace(config.provider.readModels, 'delete', fake())
replace(
ReadModelStore.prototype,
'projectionFunction',
fake.returns(() => ReadModelAction.Nothing)
)
const readModelStore = new ReadModelStore(config, logger)
await readModelStore.project(eventEnvelopeFor(AnImportantEntity.name))
expect(config.provider.readModels.store).not.to.have.been.called
expect(config.provider.readModels.delete).not.to.have.been.called
})
})
context("when the corresponding read models don't exist", () => {
it('creates new instances of the read models', async () => {
replace(config.provider.readModels, 'store', fake())
const readModelStore = new ReadModelStore(config, logger)
replace(readModelStore, 'fetchReadModel', fake.returns(null))
spy(SomeReadModel, 'someObserver')
spy(AnotherReadModel, 'anotherObserver')
const entityValue: any = eventEnvelopeFor(AnImportantEntity.name).value
const anEntityInstance = new AnImportantEntity(entityValue.id, entityValue.someKey, entityValue.count)
await readModelStore.project(eventEnvelopeFor(AnImportantEntity.name))
expect(readModelStore.fetchReadModel).to.have.been.calledThrice
expect(readModelStore.fetchReadModel).to.have.been.calledWith(SomeReadModel.name, 'joinColumnID')
expect(readModelStore.fetchReadModel).to.have.been.calledWith(AnotherReadModel.name, 'joinColumnID')
expect(SomeReadModel.someObserver).to.have.been.calledOnceWith(anEntityInstance, null)
expect(SomeReadModel.someObserver).to.have.returned({
id: 'joinColumnID',
kind: 'some',
count: 123,
boosterMetadata: { version: 1 },
})
expect(AnotherReadModel.anotherObserver).to.have.been.calledOnceWith(anEntityInstance, null)
expect(AnotherReadModel.anotherObserver).to.have.returned({
id: 'joinColumnID',
kind: 'another',
count: 123,
boosterMetadata: { version: 1 },
})
expect(config.provider.readModels.store).to.have.been.calledTwice
expect(config.provider.readModels.store).to.have.been.calledWith(
config,
logger,
SomeReadModel.name,
{
id: 'joinColumnID',
kind: 'some',
count: 123,
boosterMetadata: { version: 1 },
},
0
)
expect(config.provider.readModels.store).to.have.been.calledWith(
config,
logger,
AnotherReadModel.name,
{
id: 'joinColumnID',
kind: 'another',
count: 123,
boosterMetadata: { version: 1 },
},
0
)
})
})
context('when the corresponding read model did exist', () => {
it('updates the read model', async () => {
replace(config.provider.readModels, 'store', fake())
const readModelStore = new ReadModelStore(config, logger)
const someReadModelStoredVersion = 10
const anotherReadModelStoredVersion = 32
replace(
readModelStore,
'fetchReadModel',
fake((className: string, id: UUID) => {
if (className == SomeReadModel.name) {
return { id: id, kind: 'some', count: 77, boosterMetadata: { version: someReadModelStoredVersion } }
} else {
return {
id: id,
kind: 'another',
count: 177,
boosterMetadata: { version: anotherReadModelStoredVersion },
}
}
})
)
spy(SomeReadModel, 'someObserver')
spy(AnotherReadModel, 'anotherObserver')
const anEntitySnapshot = eventEnvelopeFor(AnImportantEntity.name)
const entityValue: any = anEntitySnapshot.value
const anEntityInstance = new AnImportantEntity(entityValue.id, entityValue.someKey, entityValue.count)
await readModelStore.project(anEntitySnapshot)
expect(readModelStore.fetchReadModel).to.have.been.calledThrice
expect(readModelStore.fetchReadModel).to.have.been.calledWith(SomeReadModel.name, 'joinColumnID')
expect(readModelStore.fetchReadModel).to.have.been.calledWith(AnotherReadModel.name, 'joinColumnID')
expect(SomeReadModel.someObserver).to.have.been.calledOnceWith(anEntityInstance, {
id: 'joinColumnID',
kind: 'some',
count: 77,
boosterMetadata: { version: someReadModelStoredVersion },
})
expect(SomeReadModel.someObserver).to.have.returned({
id: 'joinColumnID',
kind: 'some',
count: 200,
boosterMetadata: { version: someReadModelStoredVersion + 1 },
})
expect(AnotherReadModel.anotherObserver).to.have.been.calledOnceWith(anEntityInstance, {
id: 'joinColumnID',
kind: 'another',
count: 177,
boosterMetadata: { version: anotherReadModelStoredVersion },
})
expect(AnotherReadModel.anotherObserver).to.have.returned({
id: 'joinColumnID',
kind: 'another',
count: 300,
boosterMetadata: { version: anotherReadModelStoredVersion + 1 },
})
expect(config.provider.readModels.store).to.have.been.calledTwice
expect(config.provider.readModels.store).to.have.been.calledWith(
config,
logger,
SomeReadModel.name,
{
id: 'joinColumnID',
kind: 'some',
count: 200,
boosterMetadata: { version: someReadModelStoredVersion + 1 },
},
someReadModelStoredVersion
)
expect(config.provider.readModels.store).to.have.been.calledWith(
config,
logger,
AnotherReadModel.name,
{
id: 'joinColumnID',
kind: 'another',
count: 300,
boosterMetadata: { version: anotherReadModelStoredVersion + 1 },
},
anotherReadModelStoredVersion
)
})
})
context('when the projection calls an instance method in the entity', () => {
it('is executed without failing', async () => {
const readModelStore = new ReadModelStore(config, logger)
const getPrefixedKeyFake = fake()
replace(AnImportantEntity.prototype, 'getPrefixedKey', getPrefixedKeyFake)
await readModelStore.project(eventEnvelopeFor(AnImportantEntity.name))
expect(getPrefixedKeyFake).to.have.been.called
})
})
context('when the projection calls an instance method in the read model', () => {
it('is executed without failing', async () => {
const readModelStore = new ReadModelStore(config, logger)
replace(config.provider.readModels, 'fetch', fake.returns([{ id: 'joinColumnID', count: 31415 }]))
const getIdFake = fake()
replace(SomeReadModel.prototype, 'getId', getIdFake)
await readModelStore.project(eventEnvelopeFor(AnEntity.name))
expect(getIdFake).to.have.been.called
})
})
context('when there is high contention and optimistic concurrency is needed', () => {
it('retries 5 times when the error OptimisticConcurrencyUnexpectedVersionError happens 4 times', async () => {
let tryNumber = 1
const expectedTries = 5
const fakeStore = fake((config: BoosterConfig, logger: Logger, readModelName: string): Promise<unknown> => {
if (readModelName === SomeReadModel.name && tryNumber < expectedTries) {
tryNumber++
throw new OptimisticConcurrencyUnexpectedVersionError('test error')
}
return Promise.resolve()
})
replace(config.provider.readModels, 'store', fakeStore)
const readModelStore = new ReadModelStore(config, logger)
await readModelStore.project(eventEnvelopeFor(AnImportantEntity.name))
const someReadModelStoreCalls = fakeStore.getCalls().filter((call) => call.args[2] === SomeReadModel.name)
expect(someReadModelStoreCalls).to.be.have.length(expectedTries)
someReadModelStoreCalls.forEach((call) => {
expect(call.args).to.be.deep.equal([
config,
logger,
SomeReadModel.name,
{
id: 'joinColumnID',
kind: 'some',
count: 123,
boosterMetadata: { version: 1 },
},
0,
])
})
})
})
context('for read models with defined sequenceKeys', () => {
beforeEach(() => {
config.readModelSequenceKeys['AnotherReadModel'] = 'count'
})
afterEach(() => {
delete config.readModelSequenceKeys.AnotherReadModel
})
it('applies the projections with the right sequenceMetadata', async () => {
const anEntitySnapshot = eventEnvelopeFor(AnImportantEntity.name)
const anEntityInstance = createInstance(AnImportantEntity, anEntitySnapshot.value) as any
const readModelStore = new ReadModelStore(config, logger)
const fakeApplyProjectionToReadModel = fake()
replace(readModelStore as any, 'applyProjectionToReadModel', fakeApplyProjectionToReadModel)
await readModelStore.project(anEntitySnapshot)
expect(fakeApplyProjectionToReadModel).to.have.been.calledThrice
for (const projectionMetadata of config.projections[AnImportantEntity.name]) {
const readModelClassName = projectionMetadata.class.name
expect(fakeApplyProjectionToReadModel).to.have.been.calledWith(
anEntityInstance,
projectionMetadata,
readModelClassName,
anEntityInstance[projectionMetadata.joinKey],
readModelClassName === 'AnotherReadModel' ? { name: 'count', value: 123 } : undefined
)
}
})
})
})
describe('the `fetchReadModel` method', () => {
context('with no sequenceMetadata', () => {
it("returns `undefined` when the read model doesn't exist", async () => {
replace(config.provider.readModels, 'fetch', fake.returns(undefined))
const readModelStore = new ReadModelStore(config, logger)
const result = await readModelStore.fetchReadModel(SomeReadModel.name, 'joinColumnID')
expect(config.provider.readModels.fetch).to.have.been.calledOnceWithExactly(
config,
logger,
SomeReadModel.name,
'joinColumnID',
undefined
)
expect(result).to.be.undefined
})
it('returns an instance of the current read model value when it exists', async () => {
replace(config.provider.readModels, 'fetch', fake.returns([{ id: 'joinColumnID' }]))
const readModelStore = new ReadModelStore(config, logger)
const result = await readModelStore.fetchReadModel(SomeReadModel.name, 'joinColumnID')
expect(config.provider.readModels.fetch).to.have.been.calledOnceWithExactly(
config,
logger,
SomeReadModel.name,
'joinColumnID',
undefined
)
expect(result).to.be.deep.equal(new SomeReadModel('joinColumnID'))
})
})
context('with sequenceMetadata', () => {
it("calls the provider's fetch method passing the sequenceMetadata object", async () => {
replace(config.provider.readModels, 'fetch', fake.returns({ id: 'joinColumnID' }))
const readModelStore = new ReadModelStore(config, logger)
await readModelStore.fetchReadModel(SomeReadModel.name, 'joinColumnID', {
name: 'time',
value: 'now!',
})
expect(config.provider.readModels.fetch).to.have.been.calledOnceWithExactly(
config,
logger,
SomeReadModel.name,
'joinColumnID',
{ name: 'time', value: 'now!' }
)
})
})
})
describe('the `joinKeyForProjection` private method', () => {
context('when the joinKey exists', () => {
it('returns the joinKey value', () => {
const anEntitySnapshot = eventEnvelopeFor(AnImportantEntity.name)
const anEntityInstance = createInstance(AnImportantEntity, anEntitySnapshot.value) as any
const readModelStore = new ReadModelStore(config, logger) as any
expect(readModelStore.joinKeyForProjection(anEntityInstance, { joinKey: 'someKey' })).to.be.equal(
'joinColumnID'
)
})
})
context('when the joinkey does not exist', () => {
it('throws an `InvalidParameterError', () => {
const anEntitySnapshot = eventEnvelopeFor(AnImportantEntity.name)
const anEntityInstance = createInstance(AnImportantEntity, anEntitySnapshot.value) as any
const readModelStore = new ReadModelStore(config, logger) as any
expect(() => {
readModelStore.joinKeyForProjection(anEntityInstance, { joinKey: 'whatever' })
}).to.throw(InvalidParameterError)
})
})
})
describe('the `sequenceKeyForProjection` private method', () => {
context('when there is no sequence key for the read model in the config', () => {
it('returns undefined', () => {
const anEntitySnapshot = eventEnvelopeFor(AnImportantEntity.name)
const anEntityInstance = createInstance(AnImportantEntity, anEntitySnapshot.value) as any
const readModelStore = new ReadModelStore(config, logger) as any
expect(readModelStore.sequenceKeyForProjection(anEntityInstance, { class: SomeReadModel })).to.be.undefined
})
})
context('when there is a sequence key for the read model in the config', () => {
beforeEach(() => {
config.readModelSequenceKeys['AnotherReadModel'] = 'count'
})
afterEach(() => {
delete config.readModelSequenceKeys.AnotherReadModel
})
it('returns a `SequenceMetadata`object with the right sequenceKeyName and sequenceValue values', () => {
const anEntitySnapshot = eventEnvelopeFor(AnImportantEntity.name)
const anEntityInstance = createInstance(AnImportantEntity, anEntitySnapshot.value) as any
const readModelStore = new ReadModelStore(config, logger) as any
expect(readModelStore.sequenceKeyForProjection(anEntityInstance, { class: AnotherReadModel })).to.be.deep.equal(
{
name: 'count',
value: 123,
}
)
})
})
})
// TODO: This method is tested indirectly in the `project` method tests, but it would be nice to have dedicated unit tests for it too
describe('the `applyProjectionToReadModel` private method', () => {
context('when `ReadModelAction.Delete` is returned', () => {
it('deletes the read model') // TODO
})
context('when `ReadModelAction.Nothing` is returned', () => {
it('does not update the read model state') // TODO
})
context('with no sequenceMetadata', () => {
it('calls the `fetchReadodel` method with no sequenceMetadata object') // TODO
})
context('with sequenceMetadata', () => {
it('calls the `fetchReadModel` method passing the sequenceMetadata object') // TODO
})
})
}) | the_stack |
import React, { Component } from 'react'
import NodeEditor from './NodeEditor'
import ColorInput from '../inputs/ColorInput'
import InputGroup from '../inputs/InputGroup'
import ImageInput from '../inputs/ImageInput'
import CompoundNumericInput from '../inputs/CompoundNumericInput'
import NumericInputGroup from '../inputs/NumericInputGroup'
import Vector3Input from '../inputs/Vector3Input'
import SelectInput from '../inputs/SelectInput'
import * as EasingFunctions from '@xrengine/engine/src/common/functions/EasingFunctions'
import { SprayCan } from '@styled-icons/fa-solid/SprayCan'
import { camelPad } from '../../functions/utils'
import i18n from 'i18next'
import { withTranslation } from 'react-i18next'
import { CommandManager } from '../../managers/CommandManager'
//creating object containing Curve options for SelectInput
const CurveOptions = Object.keys(EasingFunctions).map((name) => ({
label: camelPad(name),
value: name
}))
//declaring properties for ParticleEmitterNodeEditor
type ParticleEmitterNodeEditorProps = {
node: any
t: Function
}
/**
* ParticleEmitterNodeEditor provides the editor to customize properties.
*
* @author Robert Long
* @type {class component}
*/
export class ParticleEmitterNodeEditor extends Component<ParticleEmitterNodeEditorProps> {
declare props: ParticleEmitterNodeEditorProps
constructor(props: ParticleEmitterNodeEditorProps) {
super(props)
}
//setting iconComponent name
static iconComponent = SprayCan
//setting description and will appears on editor view
static description = i18n.t('editor:properties.partileEmitter.description')
//function used to reflect the change in any property of ParticleEmitterNodeEditor
updateParticles() {
for (const node of CommandManager.instance.selected) {
node.updateParticles()
}
}
//function to handle the changes on colorCurve property
onChangeColorCurve = (colorCurve) => {
CommandManager.instance.setPropertyOnSelection('colorCurve', colorCurve)
}
//function used to handle the changes velocityCurve property
onChangeVelocityCurve = (velocityCurve) => {
CommandManager.instance.setPropertyOnSelection('velocityCurve', velocityCurve)
}
//function used to handle the changes in startColor property
onChangeStartColor = (startColor) => {
CommandManager.instance.setPropertyOnSelection('startColor', startColor)
this.updateParticles()
}
//function used to handle the chnages in middleColor property
onChangeMiddleColor = (middleColor) => {
CommandManager.instance.setPropertyOnSelection('middleColor', middleColor)
}
//function used to handle the changes in endColor property
onChangeEndColor = (endColor) => {
CommandManager.instance.setPropertyOnSelection('endColor', endColor)
}
//function used to handle the changes in startOpacity
onChangeStartOpacity = (startOpacity) => {
CommandManager.instance.setPropertyOnSelection('startOpacity', startOpacity)
}
//function used to handle the change in middleOpacity
onChangeMiddleOpacity = (middleOpacity) => {
CommandManager.instance.setPropertyOnSelection('middleOpacity', middleOpacity)
}
//function used to handle the changes in endOpacity
onChangeEndOpacity = (endOpacity) => {
CommandManager.instance.setPropertyOnSelection('endOpacity', endOpacity)
}
//function to handle the change in src property
onChangeSrc = (src) => {
CommandManager.instance.setPropertyOnSelection('src', src)
}
//function used to handle the changes in sizeCurve
onChangeSizeCurve = (sizeCurve) => {
CommandManager.instance.setPropertyOnSelection('sizeCurve', sizeCurve)
}
//function used to handle changes in startSize property
onChangeStartSize = (startSize) => {
CommandManager.instance.setPropertyOnSelection('startSize', startSize)
this.updateParticles()
}
//function used to handle the changes in endSize property
onChangeEndSize = (endSize) => {
CommandManager.instance.setPropertyOnSelection('endSize', endSize)
}
//function used to handle the changes in sizeRandomness
onChangeSizeRandomness = (sizeRandomness) => {
CommandManager.instance.setPropertyOnSelection('sizeRandomness', sizeRandomness)
this.updateParticles()
}
//function used to handle the changes in startVelocity
onChangeStartVelocity = (startVelocity) => {
CommandManager.instance.setPropertyOnSelection('startVelocity', startVelocity)
}
//function used to handle the changes in endVelocity
onChangeEndVelocity = (endVelocity) => {
CommandManager.instance.setPropertyOnSelection('endVelocity', endVelocity)
}
//function used to handle the changes in angularVelocity
onChangeAngularVelocity = (angularVelocity) => {
CommandManager.instance.setPropertyOnSelection('angularVelocity', angularVelocity)
}
// function used to handle the changes in particleCount
onChangeParticleCount = (particleCount) => {
CommandManager.instance.setPropertyOnSelection('particleCount', particleCount)
this.updateParticles()
}
// function used to handle the changes in lifetime property
onChangeLifetime = (lifetime) => {
CommandManager.instance.setPropertyOnSelection('lifetime', lifetime)
this.updateParticles()
}
//function to handle the changes in ageRandomness property
onChangeAgeRandomness = (ageRandomness) => {
CommandManager.instance.setPropertyOnSelection('ageRandomness', ageRandomness)
this.updateParticles()
}
//function to handle the changes on lifetimeRandomness property
onChangeLifetimeRandomness = (lifetimeRandomness) => {
CommandManager.instance.setPropertyOnSelection('lifetimeRandomness', lifetimeRandomness)
this.updateParticles()
}
//rendering view for ParticleEmitterNodeEditor
render() {
ParticleEmitterNodeEditor.description = this.props.t('editor:properties.partileEmitter.description')
return (
<NodeEditor {...this.props} description={ParticleEmitterNodeEditor.description}>
<NumericInputGroup
name="Particle Count"
label={this.props.t('editor:properties.partileEmitter.lbl-particleCount')}
min={1}
smallStep={1}
mediumStep={1}
largeStep={1}
value={this.props.node.particleCount}
onChange={this.onChangeParticleCount}
/>
<InputGroup name="Image" label={this.props.t('editor:properties.partileEmitter.lbl-image')}>
<ImageInput value={this.props.node.src} onChange={this.onChangeSrc} />
</InputGroup>
<NumericInputGroup
name="Age Randomness"
label={this.props.t('editor:properties.partileEmitter.lbl-ageRandomness')}
info={this.props.t('editor:properties.partileEmitter.info-ageRandomness')}
min={0}
smallStep={0.01}
mediumStep={0.1}
largeStep={1}
value={this.props.node.ageRandomness}
onChange={this.onChangeAgeRandomness}
unit="s"
/>
<NumericInputGroup
name="Lifetime"
label={this.props.t('editor:properties.partileEmitter.lbl-lifetime')}
info={this.props.t('editor:properties.partileEmitter.info-lifetime')}
min={0}
smallStep={0.01}
mediumStep={0.1}
largeStep={1}
value={this.props.node.lifetime}
onChange={this.onChangeLifetime}
unit="s"
/>
<NumericInputGroup
name="Lifetime Randomness"
label={this.props.t('editor:properties.partileEmitter.lbl-lifetimeRandomness')}
info={this.props.t('editor:properties.partileEmitter.info-lifetimeRandomness')}
min={0}
smallStep={0.01}
mediumStep={0.1}
largeStep={1}
value={this.props.node.lifetimeRandomness}
onChange={this.onChangeLifetimeRandomness}
unit="s"
/>
<InputGroup name="Size Curve" label={this.props.t('editor:properties.partileEmitter.lbl-sizeCurve')}>
<SelectInput options={CurveOptions} value={this.props.node.sizeCurve} onChange={this.onChangeSizeCurve} />
</InputGroup>
<NumericInputGroup
name="Start Particle Size"
label={this.props.t('editor:properties.partileEmitter.lbl-startPSize')}
min={0}
smallStep={0.01}
mediumStep={0.1}
largeStep={1}
value={this.props.node.startSize}
onChange={this.onChangeStartSize}
unit="m"
/>
<NumericInputGroup
name="End Particle Size"
label={this.props.t('editor:properties.partileEmitter.lbl-endPSize')}
min={0}
smallStep={0.01}
mediumStep={0.1}
largeStep={1}
value={this.props.node.endSize}
onChange={this.onChangeEndSize}
unit="m"
/>
<NumericInputGroup
name="Size Randomness"
label={this.props.t('editor:properties.partileEmitter.lbl-sizeRandomness')}
info={this.props.t('editor:properties.partileEmitter.info-sizeRandomness')}
min={0}
smallStep={0.01}
mediumStep={0.1}
largeStep={1}
value={this.props.node.sizeRandomness}
onChange={this.onChangeSizeRandomness}
unit="m"
/>
<InputGroup name="Color Curve" label={this.props.t('editor:properties.partileEmitter.lbl-colorCurve')}>
<SelectInput options={CurveOptions} value={this.props.node.colorCurve} onChange={this.onChangeColorCurve} />
</InputGroup>
<InputGroup name="Start Color" label={this.props.t('editor:properties.partileEmitter.lbl-startColor')}>
<ColorInput value={this.props.node.startColor} onChange={this.onChangeStartColor} />
</InputGroup>
<InputGroup name="Start Opacity" label={this.props.t('editor:properties.partileEmitter.lbl-startOpacity')}>
<CompoundNumericInput
min={0}
max={1}
step={0.01}
value={this.props.node.startOpacity}
onChange={this.onChangeStartOpacity}
/>
</InputGroup>
<InputGroup name="Middle Color" label={this.props.t('editor:properties.partileEmitter.lbl-middleColor')}>
<ColorInput value={this.props.node.middleColor} onChange={this.onChangeMiddleColor} />
</InputGroup>
<InputGroup name="Middle Opacity" label={this.props.t('editor:properties.partileEmitter.lbl-middleOpacity')}>
<CompoundNumericInput
min={0}
max={1}
step={0.01}
value={this.props.node.middleOpacity}
onChange={this.onChangeMiddleOpacity}
/>
</InputGroup>
<InputGroup name="End Color" label={this.props.t('editor:properties.partileEmitter.lbl-endColor')}>
<ColorInput value={this.props.node.endColor} onChange={this.onChangeEndColor} />
</InputGroup>
<InputGroup name="End Opacity" label={this.props.t('editor:properties.partileEmitter.lbl-endOpacity')}>
<CompoundNumericInput
min={0}
max={1}
step={0.01}
value={this.props.node.endOpacity}
onChange={this.onChangeEndOpacity}
/>
</InputGroup>
<InputGroup name="Velocity Curve" label={this.props.t('editor:properties.partileEmitter.lbl-velocityCurve')}>
<SelectInput
options={CurveOptions}
value={this.props.node.velocityCurve}
onChange={this.onChangeVelocityCurve}
/>
</InputGroup>
<InputGroup name="Start Velocity" label={this.props.t('editor:properties.partileEmitter.lbl-startVelocity')}>
<Vector3Input
value={this.props.node.startVelocity}
smallStep={0.01}
mediumStep={0.1}
largeStep={1}
onChange={this.onChangeStartVelocity}
/>
</InputGroup>
<InputGroup name="End Velocity" label={this.props.t('editor:properties.partileEmitter.lbl-endVelocity')}>
<Vector3Input
value={this.props.node.endVelocity}
smallStep={0.01}
mediumStep={0.1}
largeStep={1}
onChange={this.onChangeEndVelocity}
/>
</InputGroup>
<NumericInputGroup
name="Angular Velocity"
label={this.props.t('editor:properties.partileEmitter.lbl-angularVelocity')}
min={-100}
smallStep={1}
mediumStep={1}
largeStep={1}
value={this.props.node.angularVelocity}
onChange={this.onChangeAngularVelocity}
unit="°/s"
/>
</NodeEditor>
)
}
}
export default withTranslation()(ParticleEmitterNodeEditor) | the_stack |
import { setSubtreeVisibility } from '../../../mol-plugin/behavior/static/state';
import { PluginCommands } from '../../../mol-plugin/commands';
import { PluginContext } from '../../../mol-plugin/context';
import { StateTransform, StateTree } from '../../../mol-state';
import { SetUtils } from '../../../mol-util/set';
import { TrajectoryHierarchyPresetProvider } from '../../builder/structure/hierarchy-preset';
import { PluginComponent } from '../../component';
import { buildStructureHierarchy, StructureHierarchyRef, ModelRef, StructureComponentRef, StructureHierarchy, StructureRef, TrajectoryRef } from './hierarchy-state';
export class StructureHierarchyManager extends PluginComponent {
private state = {
syncedTree: this.dataState.tree,
notified: false,
hierarchy: StructureHierarchy(),
selection: {
trajectories: [] as ReadonlyArray<TrajectoryRef>,
models: [] as ReadonlyArray<ModelRef>,
structures: [] as ReadonlyArray<StructureRef>
}
}
readonly behaviors = {
selection: this.ev.behavior({
hierarchy: this.current,
trajectories: this.selection.trajectories,
models: this.selection.models,
structures: this.selection.structures
})
}
private get dataState() {
return this.plugin.state.data;
}
private _currentComponentGroups: ReturnType<typeof StructureHierarchyManager['getComponentGroups']> | undefined = void 0;
get currentComponentGroups() {
if (this._currentComponentGroups) return this._currentComponentGroups;
this._currentComponentGroups = StructureHierarchyManager.getComponentGroups(this.selection.structures);
return this._currentComponentGroups;
}
private _currentSelectionSet: Set<StateTransform.Ref> | undefined = void 0;
get seletionSet() {
if (this._currentSelectionSet) return this._currentSelectionSet;
this._currentSelectionSet = new Set();
for (const r of this.selection.trajectories) this._currentSelectionSet.add(r.cell.transform.ref);
for (const r of this.selection.models) this._currentSelectionSet.add(r.cell.transform.ref);
for (const r of this.selection.structures) this._currentSelectionSet.add(r.cell.transform.ref);
return this._currentSelectionSet;
}
get current() {
this.sync(false);
return this.state.hierarchy;
}
get selection() {
this.sync(false);
return this.state.selection;
}
getStructuresWithSelection() {
const xs = this.plugin.managers.structure.hierarchy.current.structures;
const ret: StructureRef[] = [];
for (const s of xs) {
if (this.plugin.managers.structure.selection.structureHasSelection(s)) {
ret.push(s);
}
}
return ret;
}
private syncCurrent<T extends StructureHierarchyRef>(all: ReadonlyArray<T>, added: Set<StateTransform.Ref>): T[] {
const current = this.seletionSet;
const newCurrent: T[] = [];
for (const r of all) {
const ref = r.cell.transform.ref;
if (current.has(ref) || added.has(ref)) newCurrent.push(r);
}
if (newCurrent.length === 0) return all.length > 0 ? [all[0]] : [];
return newCurrent;
}
private sync(notify: boolean) {
if (!notify && this.dataState.inUpdate) return;
if (this.state.syncedTree === this.dataState.tree) {
if (notify && !this.state.notified) {
this.state.notified = true;
this.behaviors.selection.next({ hierarchy: this.state.hierarchy, ...this.state.selection });
}
return;
}
this.state.syncedTree = this.dataState.tree;
const update = buildStructureHierarchy(this.plugin.state.data, this.current);
if (!update.changed) {
return;
}
const { hierarchy } = update;
const trajectories = this.syncCurrent(hierarchy.trajectories, update.added);
const models = this.syncCurrent(hierarchy.models, update.added);
const structures = this.syncCurrent(hierarchy.structures, update.added);
this._currentComponentGroups = void 0;
this._currentSelectionSet = void 0;
this.state.hierarchy = hierarchy;
this.state.selection.trajectories = trajectories;
this.state.selection.models = models;
this.state.selection.structures = structures;
if (notify) {
this.state.notified = true;
this.behaviors.selection.next({ hierarchy, trajectories, models, structures });
} else {
this.state.notified = false;
}
}
updateCurrent(refs: StructureHierarchyRef[], action: 'add' | 'remove') {
const hierarchy = this.current;
const set = action === 'add'
? SetUtils.union(this.seletionSet, new Set(refs.map(r => r.cell.transform.ref)))
: SetUtils.difference(this.seletionSet, new Set(refs.map(r => r.cell.transform.ref)));
const trajectories = [];
const models = [];
const structures = [];
for (const t of hierarchy.trajectories) {
if (set.has(t.cell.transform.ref)) trajectories.push(t);
}
for (const m of hierarchy.models) {
if (set.has(m.cell.transform.ref)) models.push(m);
}
for (const s of hierarchy.structures) {
if (set.has(s.cell.transform.ref)) structures.push(s);
}
this._currentComponentGroups = void 0;
this._currentSelectionSet = void 0;
this.state.selection.trajectories = trajectories;
this.state.selection.models = models;
this.state.selection.structures = structures;
this.behaviors.selection.next({ hierarchy, trajectories, models, structures });
}
remove(refs: (StructureHierarchyRef | string)[], canUndo?: boolean) {
if (refs.length === 0) return;
const deletes = this.plugin.state.data.build();
for (const r of refs) deletes.delete(typeof r === 'string' ? r : r.cell.transform.ref);
return deletes.commit({ canUndo: canUndo ? 'Remove' : false });
}
toggleVisibility(refs: ReadonlyArray<StructureHierarchyRef>, action?: 'show' | 'hide') {
if (refs.length === 0) return;
const isHidden = action !== void 0
? (action === 'show' ? false : true)
: !refs[0].cell.state.isHidden;
for (const c of refs) {
setSubtreeVisibility(this.dataState, c.cell.transform.ref, isHidden);
}
}
applyPreset<P = any, S = {}>(trajectories: ReadonlyArray<TrajectoryRef>, provider: TrajectoryHierarchyPresetProvider<P, S>, params?: P): Promise<any> {
return this.plugin.dataTransaction(async () => {
for (const t of trajectories) {
if (t.models.length > 0) {
await this.clearTrajectory(t);
}
await this.plugin.builders.structure.hierarchy.applyPreset(t.cell, provider, params);
}
});
}
async updateStructure(s: StructureRef, params: any) {
await this.plugin.dataTransaction(async () => {
const root = StateTree.getDecoratorRoot(this.dataState.tree, s.cell.transform.ref);
const children = this.dataState.tree.children.get(root).toArray();
await this.remove(children, false);
await this.plugin.state.updateTransform(this.plugin.state.data, s.cell.transform.ref, params, 'Structure Type');
await this.plugin.builders.structure.representation.applyPreset(s.cell.transform.ref, 'auto');
}, { canUndo: 'Structure Type' });
PluginCommands.Camera.Reset(this.plugin);
}
private clearTrajectory(trajectory: TrajectoryRef) {
const builder = this.dataState.build();
for (const m of trajectory.models) {
builder.delete(m.cell);
}
return builder.commit();
}
constructor(private plugin: PluginContext) {
super();
this.subscribe(plugin.state.data.events.changed, e => {
if (e.inTransaction || plugin.behaviors.state.isAnimating.value) return;
this.sync(true);
});
this.subscribe(plugin.behaviors.state.isAnimating, isAnimating => {
if (!isAnimating && !plugin.behaviors.state.isUpdating.value) this.sync(true);
});
}
}
export namespace StructureHierarchyManager {
export function getComponentGroups(structures: ReadonlyArray<StructureRef>): StructureComponentRef[][] {
if (!structures.length) return [];
if (structures.length === 1) return structures[0].components.map(c => [c]);
const groups: StructureComponentRef[][] = [];
const map = new Map<string, StructureComponentRef[]>();
for (const s of structures) {
for (const c of s.components) {
const key = c.key;
if (!key) continue;
let component = map.get(key);
if (!component) {
component = [];
map.set(key, component);
groups.push(component);
}
component.push(c);
}
}
return groups;
}
export function getSelectedStructuresDescription(plugin: PluginContext) {
const { structures } = plugin.managers.structure.hierarchy.selection;
if (structures.length === 0) return '';
if (structures.length === 1) {
const s = structures[0];
const data = s.cell.obj?.data;
if (!data) return s.cell.obj?.label || 'Structure';
const model = data.models[0] || data.representativeModel || data.masterModel;
if (!model) return s.cell.obj?.label || 'Structure';
const entryId = model.entryId;
if (s.model?.trajectory?.models && s.model.trajectory.models.length === 1) return entryId;
if (s.model) return `${s.model.cell.obj?.label} | ${entryId}`;
return entryId;
}
const p = structures[0];
const t = p?.model?.trajectory;
let sameTraj = true;
for (const s of structures) {
if (s?.model?.trajectory !== t) {
sameTraj = false;
break;
}
}
return sameTraj && t ? `${t.cell.obj?.label} | ${structures.length} structures` : `${structures.length} structures`;
}
} | the_stack |
// IMPORTANT
// This file was generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually.
// In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator
// Generated from: https://androiddeviceprovisioning.googleapis.com/$discovery/rest?version=v1
/// <reference types="gapi.client" />
declare namespace gapi.client {
/** Load Android Device Provisioning Partner API v1 */
function load(name: "androiddeviceprovisioning", version: "v1"): PromiseLike<void>;
function load(name: "androiddeviceprovisioning", version: "v1", callback: () => any): void;
const operations: androiddeviceprovisioning.OperationsResource;
const partners: androiddeviceprovisioning.PartnersResource;
namespace androiddeviceprovisioning {
interface ClaimDeviceRequest {
/** The customer to claim for. */
customerId?: string;
/** The device identifier of the device to claim. */
deviceIdentifier?: DeviceIdentifier;
/** The section to claim. */
sectionType?: string;
}
interface ClaimDeviceResponse {
/** The device ID of the claimed device. */
deviceId?: string;
/**
* The resource name of the device in the format
* `partners/[PARTNER_ID]/devices/[DEVICE_ID]`.
*/
deviceName?: string;
}
interface ClaimDevicesRequest {
/** List of claims. */
claims?: PartnerClaim[];
}
interface Company {
/**
* Input only. Optional. Email address of customer's users in the admin role.
* Each email address must be associated with a Google Account.
*/
adminEmails?: string[];
/** Output only. The ID of the company. Assigned by the server. */
companyId?: string;
/**
* Required. The name of the company. For example _XYZ Corp_. Characters
* allowed are: Latin letters, numerals, hyphens, and spaces. Displayed to the
* customer's employees in the zero-touch enrollment portal.
*/
companyName?: string;
/**
* Output only. The API resource name of the company in the format
* `partners/[PARTNER_ID]/customers/[CUSTOMER_ID]`. Assigned by the server.
*/
name?: string;
/**
* Input only. Email address of customer's users in the owner role. At least
* one `owner_email` is required. Each email address must be associated with a
* Google Account. Owners share the same access as admins but can also add,
* delete, and edit your organization's portal users.
*/
ownerEmails?: string[];
}
interface CreateCustomerRequest {
/**
* Required. The company data to populate the new customer. Must contain a
* value for `companyName` and at least one `owner_email` that's associated
* with a Google Account. The values for `companyId` and `name` must be empty.
*/
customer?: Company;
}
interface Device {
/** Claims. */
claims?: DeviceClaim[];
/**
* The resource name of the configuration.
* Only set for customers.
*/
configuration?: string;
/** Device ID. */
deviceId?: string;
/** Device identifier. */
deviceIdentifier?: DeviceIdentifier;
/** Device metadata. */
deviceMetadata?: DeviceMetadata;
/** Resource name in `partners/[PARTNER_ID]/devices/[DEVICE_ID]`. */
name?: string;
}
interface DeviceClaim {
/** Owner ID. */
ownerCompanyId?: string;
/** Section type of the device claim. */
sectionType?: string;
}
interface DeviceIdentifier {
/** IMEI number. */
imei?: string;
/**
* Manufacturer name to match `android.os.Build.MANUFACTURER` (required).
* Allowed values listed in
* [manufacturer names](/zero-touch/resources/manufacturer-names).
*/
manufacturer?: string;
/** MEID number. */
meid?: string;
/** Serial number (optional). */
serialNumber?: string;
}
interface DeviceMetadata {
/** Metadata entries */
entries?: Record<string, string>;
}
interface DevicesLongRunningOperationMetadata {
/** Number of devices parsed in your requests. */
devicesCount?: number;
/** The overall processing status. */
processingStatus?: string;
/** Processing progress from 0 to 100. */
progress?: number;
}
interface DevicesLongRunningOperationResponse {
/**
* Processing status for each device.
* One `PerDeviceStatus` per device. The order is the same as in your requests.
*/
perDeviceStatus?: OperationPerDevice[];
/** Number of succeesfully processed ones. */
successCount?: number;
}
interface FindDevicesByDeviceIdentifierRequest {
/** The device identifier to search. */
deviceIdentifier?: DeviceIdentifier;
/** Number of devices to show. */
limit?: string;
/** Page token. */
pageToken?: string;
}
interface FindDevicesByDeviceIdentifierResponse {
/** Found devices. */
devices?: Device[];
/** Page token of the next page. */
nextPageToken?: string;
}
interface FindDevicesByOwnerRequest {
/** List of customer IDs to search for. */
customerId?: string[];
/** The number of devices to show in the result. */
limit?: string;
/** Page token. */
pageToken?: string;
/** The section type. */
sectionType?: string;
}
interface FindDevicesByOwnerResponse {
/** Devices found. */
devices?: Device[];
/** Page token of the next page. */
nextPageToken?: string;
}
interface ListCustomersResponse {
/** List of customers related to this partner. */
customers?: Company[];
}
interface Operation {
/**
* If the value is `false`, it means the operation is still in progress.
* If `true`, the operation is completed, and either `error` or `response` is
* available.
*/
done?: boolean;
/**
* This field will always be not set if the operation is created by `claimAsync`, `unclaimAsync`, or `updateMetadataAsync`. In this case, error
* information for each device is set in `response.perDeviceStatus.result.status`.
*/
error?: Status;
/**
* This field will contain a `DevicesLongRunningOperationMetadata` object if the operation is created by `claimAsync`, `unclaimAsync`, or
* `updateMetadataAsync`.
*/
metadata?: Record<string, any>;
/**
* The server-assigned name, which is only unique within the same service that
* originally returns it. If you use the default HTTP mapping, the
* `name` should have the format of `operations/some/unique/name`.
*/
name?: string;
/**
* This field will contain a `DevicesLongRunningOperationResponse` object if the operation is created by `claimAsync`, `unclaimAsync`, or
* `updateMetadataAsync`.
*/
response?: Record<string, any>;
}
interface OperationPerDevice {
/** Request to claim a device. */
claim?: PartnerClaim;
/** Processing result for every device. */
result?: PerDeviceStatusInBatch;
/** Request to unclaim a device. */
unclaim?: PartnerUnclaim;
/** Request to set metadata for a device. */
updateMetadata?: UpdateMetadataArguments;
}
interface PartnerClaim {
/** Customer ID to claim for. */
customerId?: string;
/** Device identifier of the device. */
deviceIdentifier?: DeviceIdentifier;
/** Metadata to set at claim. */
deviceMetadata?: DeviceMetadata;
/** Section type to claim. */
sectionType?: string;
}
interface PartnerUnclaim {
/** Device ID of the device. */
deviceId?: string;
/** Device identifier of the device. */
deviceIdentifier?: DeviceIdentifier;
/** Section type to unclaim. */
sectionType?: string;
}
interface PerDeviceStatusInBatch {
/** Device ID of the device if process succeeds. */
deviceId?: string;
/** Error identifier. */
errorIdentifier?: string;
/** Error message. */
errorMessage?: string;
/** Process result. */
status?: string;
}
interface Status {
/** The status code, which should be an enum value of google.rpc.Code. */
code?: number;
/**
* A list of messages that carry the error details. There is a common set of
* message types for APIs to use.
*/
details?: Array<Record<string, any>>;
/**
* A developer-facing error message, which should be in English. Any
* user-facing error message should be localized and sent in the
* google.rpc.Status.details field, or localized by the client.
*/
message?: string;
}
interface UnclaimDeviceRequest {
/** The device ID returned by `ClaimDevice`. */
deviceId?: string;
/** The device identifier you used when you claimed this device. */
deviceIdentifier?: DeviceIdentifier;
/** The section type to unclaim for. */
sectionType?: string;
}
interface UnclaimDevicesRequest {
/** List of devices to unclaim. */
unclaims?: PartnerUnclaim[];
}
interface UpdateDeviceMetadataInBatchRequest {
/** List of metadata updates. */
updates?: UpdateMetadataArguments[];
}
interface UpdateDeviceMetadataRequest {
/** The metdata to set. */
deviceMetadata?: DeviceMetadata;
}
interface UpdateMetadataArguments {
/** Device ID of the device. */
deviceId?: string;
/** Device identifier. */
deviceIdentifier?: DeviceIdentifier;
/** The metadata to update. */
deviceMetadata?: DeviceMetadata;
}
interface OperationsResource {
/**
* Gets the latest state of a long-running operation. Clients can use this
* method to poll the operation result at intervals as recommended by the API
* service.
*/
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the operation resource. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Operation>;
}
interface CustomersResource {
/**
* Creates a customer for zero-touch enrollment. After the method returns
* successfully, admin and owner roles can manage devices and EMM configs
* by calling API methods or using their zero-touch enrollment portal. The API
* doesn't notify the customer that they have access.
*/
create(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Required. The parent resource ID in format `partners/[PARTNER_ID]` that
* identifies the reseller.
*/
parent: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Company>;
/**
* Lists the customers that are enrolled to the reseller identified by the
* `partnerId` argument. This list includes customers that the reseller
* created and customers that enrolled themselves using the portal.
*/
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** The ID of the partner. */
partnerId: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListCustomersResponse>;
}
interface DevicesResource {
/** Claim the device identified by device identifier. */
claim(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** ID of the partner. */
partnerId: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ClaimDeviceResponse>;
/** Claim devices asynchronously. */
claimAsync(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Partner ID. */
partnerId: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Operation>;
/** Find devices by device identifier. */
findByIdentifier(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** ID of the partner. */
partnerId: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<FindDevicesByDeviceIdentifierResponse>;
/** Find devices by ownership. */
findByOwner(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** ID of the partner. */
partnerId: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<FindDevicesByOwnerResponse>;
/** Get a device. */
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** Resource name in `partners/[PARTNER_ID]/devices/[DEVICE_ID]`. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Device>;
/** Update the metadata. */
metadata(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** ID of the partner. */
deviceId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The owner of the newly set metadata. Set this to the partner ID. */
metadataOwnerId: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<DeviceMetadata>;
/** Unclaim the device identified by the `device_id` or the `deviceIdentifier`. */
unclaim(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** ID of the partner. */
partnerId: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<{}>;
/** Unclaim devices asynchronously. */
unclaimAsync(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Partner ID. */
partnerId: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Operation>;
/** Set metadata in batch asynchronously. */
updateMetadataAsync(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Partner ID. */
partnerId: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Operation>;
}
interface PartnersResource {
customers: CustomersResource;
devices: DevicesResource;
}
}
} | the_stack |
import * as path from "path";
import * as Uuid from "uuid/v4";
import * as vscode from "vscode";
import ArduinoActivator from "../arduinoActivator";
import ArduinoContext from "../arduinoContext";
import * as Constants from "../common/constants";
import * as JSONHelper from "../common/cycle";
import { DeviceContext } from "../deviceContext";
import * as Logger from "../logger/logger";
import LocalWebServer from "./localWebServer";
export class ArduinoContentProvider implements vscode.TextDocumentContentProvider {
private _webserver: LocalWebServer;
private _onDidChange = new vscode.EventEmitter<vscode.Uri>();
constructor(private _extensionPath: string) { }
public async initialize() {
this._webserver = new LocalWebServer(this._extensionPath);
// Arduino Boards Manager
this.addHandlerWithLogger("show-boardmanager", "/boardmanager", (req, res) => this.getHtmlView(req, res));
this.addHandlerWithLogger("show-packagemanager", "/api/boardpackages", async (req, res) => await this.getBoardPackages(req, res));
this.addHandlerWithLogger("install-board", "/api/installboard", async (req, res) => await this.installPackage(req, res), true);
this.addHandlerWithLogger("uninstall-board", "/api/uninstallboard", async (req, res) => await this.uninstallPackage(req, res), true);
this.addHandlerWithLogger("open-link", "/api/openlink", async (req, res) => await this.openLink(req, res), true);
this.addHandlerWithLogger("open-settings", "/api/opensettings", (req, res) => this.openSettings(req, res), true);
// Arduino Libraries Manager
this.addHandlerWithLogger("show-librarymanager", "/librarymanager", (req, res) => this.getHtmlView(req, res));
this.addHandlerWithLogger("load-libraries", "/api/libraries", async (req, res) => await this.getLibraries(req, res));
this.addHandlerWithLogger("install-library", "/api/installlibrary", async (req, res) => await this.installLibrary(req, res), true);
this.addHandlerWithLogger("uninstall-library", "/api/uninstalllibrary", async (req, res) => await this.uninstallLibrary(req, res), true);
this.addHandlerWithLogger("add-libpath", "/api/addlibpath", async (req, res) => await this.addLibPath(req, res), true);
// Arduino Board Config
this.addHandlerWithLogger("show-boardconfig", "/boardconfig", (req, res) => this.getHtmlView(req, res));
this.addHandlerWithLogger("load-installedboards", "/api/installedboards", (req, res) => this.getInstalledBoards(req, res));
this.addHandlerWithLogger("load-configitems", "/api/configitems", async (req, res) => await this.getBoardConfig(req, res));
this.addHandlerWithLogger("update-selectedboard", "/api/updateselectedboard", (req, res) => this.updateSelectedBoard(req, res), true);
this.addHandlerWithLogger("update-config", "/api/updateconfig", async (req, res) => await this.updateConfig(req, res), true);
// Arduino Examples TreeView
this.addHandlerWithLogger("show-examplesview", "/examples", (req, res) => this.getHtmlView(req, res));
this.addHandlerWithLogger("load-examples", "/api/examples", async (req, res) => await this.getExamples(req, res));
this.addHandlerWithLogger("open-example", "/api/openexample", (req, res) => this.openExample(req, res), true);
await this._webserver.start();
}
public async provideTextDocumentContent(uri: vscode.Uri): Promise<string> {
if (!ArduinoContext.initialized) {
await ArduinoActivator.activate();
}
let type = "";
if (uri.toString() === Constants.BOARD_MANAGER_URI.toString()) {
type = "boardmanager";
} else if (uri.toString() === Constants.LIBRARY_MANAGER_URI.toString()) {
type = "librarymanager";
} else if (uri.toString() === Constants.BOARD_CONFIG_URI.toString()) {
type = "boardConfig";
} else if (uri.toString() === Constants.EXAMPLES_URI.toString()) {
type = "examples";
}
const timeNow = new Date().getTime();
return `
<html>
<head>
<script type="text/javascript">
window.onload = function() {
console.log('reloaded results window at time ${timeNow}ms');
var doc = document.documentElement;
var styles = window.getComputedStyle(doc);
var backgroundcolor = styles.getPropertyValue('--background-color') || '#1e1e1e';
var color = styles.getPropertyValue('--color') || '#d4d4d4';
var theme = document.body.className || 'vscode-dark';
var url = "${this._webserver.getEndpointUri(type)}?" +
"theme=" + encodeURIComponent(theme.trim()) +
"&backgroundcolor=" + encodeURIComponent(backgroundcolor.trim()) +
"&color=" + encodeURIComponent(color.trim());
document.getElementById('frame').src = url;
};
</script>
</head>
<body style="margin: 0; padding: 0; height: 100%; overflow: hidden;">
<iframe id="frame" width="100%" height="100%" frameborder="0" style="position:absolute; left: 0; right: 0; bottom: 0; top: 0px;"/>
</body>
</html>`;
}
get onDidChange(): vscode.Event<vscode.Uri> {
return this._onDidChange.event;
}
public update(uri: vscode.Uri) {
this._onDidChange.fire(uri);
}
public getHtmlView(req, res) {
return res.sendFile(path.join(this._extensionPath, "./out/views/index.html"));
}
public async getBoardPackages(req, res) {
await ArduinoContext.boardManager.loadPackages(req.query.update === "true");
return res.json({
platforms: JSONHelper.decycle(ArduinoContext.boardManager.platforms, undefined),
});
}
public async installPackage(req, res) {
if (!req.body.packageName || !req.body.arch) {
return res.status(400).send("BAD Request! Missing { packageName, arch } parameters!");
} else {
try {
await ArduinoContext.arduinoApp.installBoard(req.body.packageName, req.body.arch, req.body.version);
return res.json({
status: "OK",
});
} catch (error) {
return res.status(500).send(`Install board failed with message "code:${error.code}, err:${error.stderr}"`);
}
}
}
public async uninstallPackage(req, res) {
if (!req.body.packagePath) {
return res.status(400).send("BAD Request! Missing { packagePath } parameter!");
} else {
try {
await ArduinoContext.arduinoApp.uninstallBoard(req.body.boardName, req.body.packagePath);
return res.json({
status: "OK",
});
} catch (error) {
return res.status(500).send(`Uninstall board failed with message "${error}"`);
}
}
}
public async openLink(req, res) {
if (!req.body.link) {
return res.status(400).send("BAD Request! Missing { link } parameter!");
} else {
try {
await vscode.commands.executeCommand("vscode.open", vscode.Uri.parse(req.body.link));
return res.json({
status: "OK",
});
} catch (error) {
return res.status(500).send(`Cannot open the link with error message "${error}"`);
}
}
}
public openSettings(req, res) {
vscode.commands.executeCommand("workbench.action.openGlobalSettings");
return res.json({
status: "OK",
});
}
public async getLibraries(req, res) {
await ArduinoContext.arduinoApp.libraryManager.loadLibraries(req.query.update === "true");
return res.json({
libraries: ArduinoContext.arduinoApp.libraryManager.libraries,
});
}
public async installLibrary(req, res) {
if (!req.body.libraryName) {
return res.status(400).send("BAD Request! Missing { libraryName } parameters!");
} else {
try {
await ArduinoContext.arduinoApp.installLibrary(req.body.libraryName, req.body.version);
return res.json({
status: "OK",
});
} catch (error) {
return res.status(500).send(`Install library failed with message "code:${error.code}, err:${error.stderr}"`);
}
}
}
public async uninstallLibrary(req, res) {
if (!req.body.libraryPath) {
return res.status(400).send("BAD Request! Missing { libraryPath } parameters!");
} else {
try {
await ArduinoContext.arduinoApp.uninstallLibrary(req.body.libraryName, req.body.libraryPath);
return res.json({
status: "OK",
});
} catch (error) {
return res.status(500).send(`Uninstall library failed with message "code:${error.code}, err:${error.stderr}"`);
}
}
}
public async addLibPath(req, res) {
if (!req.body.libraryPath) {
return res.status(400).send("BAD Request! Missing { libraryPath } parameters!");
} else {
try {
await ArduinoContext.arduinoApp.includeLibrary(req.body.libraryPath);
return res.json({
status: "OK",
});
} catch (error) {
return res.status(500).send(`Add library path failed with message "code:${error.code}, err:${error.stderr}"`);
}
}
}
public async getInstalledBoards(req, res) {
const installedBoards = [];
ArduinoContext.boardManager.installedBoards.forEach((b) => {
const isSelected = ArduinoContext.boardManager.currentBoard ? b.key === ArduinoContext.boardManager.currentBoard.key : false;
installedBoards.push({
key: b.key,
name: b.name,
platform: b.platform.name,
isSelected,
});
});
return res.json({
installedBoards: JSONHelper.decycle(installedBoards, undefined),
});
}
public async getBoardConfig(req, res) {
return res.json({
configitems: (ArduinoContext.boardManager.currentBoard === null) ? null : ArduinoContext.boardManager.currentBoard.configItems,
});
}
public updateSelectedBoard(req, res) {
if (!req.body.boardId) {
return res.status(400).send("BAD Request! Missing parameters!");
} else {
try {
const bd = ArduinoContext.boardManager.installedBoards.get(req.body.boardId);
ArduinoContext.boardManager.doChangeBoardType(bd);
return res.json({
status: "OK",
});
} catch (error) {
return res.status(500).send(`Update board config failed with message "code:${error.code}, err:${error.stderr}"`);
}
}
}
public async updateConfig(req, res) {
if (!req.body.configId || !req.body.optionId) {
return res.status(400).send("BAD Request! Missing parameters!");
} else {
try {
ArduinoContext.boardManager.currentBoard.updateConfig(req.body.configId, req.body.optionId);
const dc = DeviceContext.getInstance();
dc.configuration = ArduinoContext.boardManager.currentBoard.customConfig;
return res.json({
status: "OK",
});
} catch (error) {
return res.status(500).send(`Update board config failed with message "code:${error.code}, err:${error.stderr}"`);
}
}
}
public async getExamples(req, res) {
const examples = await ArduinoContext.arduinoApp.exampleManager.loadExamples();
return res.json({
examples,
});
}
public openExample(req, res) {
if (!req.body.examplePath) {
return res.status(400).send("BAD Request! Missing { examplePath } parameter!");
} else {
try {
ArduinoContext.arduinoApp.openExample(req.body.examplePath);
return res.json({
status: "OK",
});
} catch (error) {
return res.status(500).send(`Cannot open the example folder with error message "${error}"`);
}
}
}
private addHandlerWithLogger(handlerName: string, url: string, handler: (req, res) => void, post: boolean = false): void {
const wrappedHandler = async (req, res) => {
const guid = Uuid().replace(/-/g, "");
let properties = {};
if (post) {
properties = { ...req.body };
// Removal requirement for GDPR
if ("install-board" === handlerName) {
const packageNameKey = "packageName";
delete properties[packageNameKey];
}
}
Logger.traceUserData(`start-` + handlerName, { correlationId: guid, ...properties });
const timer1 = new Logger.Timer();
try {
await Promise.resolve(handler(req, res));
} catch (error) {
Logger.traceError("expressHandlerError", error, { correlationId: guid, handlerName, ...properties });
}
Logger.traceUserData(`end-` + handlerName, { correlationId: guid, duration: timer1.end() });
};
if (post) {
this._webserver.addPostHandler(url, wrappedHandler);
} else {
this._webserver.addHandler(url, wrappedHandler);
}
}
} | the_stack |
import React from 'react'
import classnames from 'classnames'
import { ViewModelVisualTypes } from 'containers/View/constants'
import DropboxItem from './DropboxItem'
import DropboxContent from './DropboxContent'
import ColorPanel from '../ColorPanel'
import SizePanel from '../SizePanel'
import { IChartInfo, WidgetMode } from '../../Widget'
import { IFieldConfig } from '../../Config/Field'
import { IFieldFormatConfig } from '../../Config/Format'
import { IFieldSortConfig, FieldSortTypes } from '../../Config/Sort'
import { decodeMetricName } from '../../util'
import { Popover, Icon } from 'antd'
import { IFilter } from 'app/components/Control/types'
const styles = require('../Workbench.less')
export type DragType = 'category' | 'value'
export type DropboxType = DragType | 'all'
export type DropboxItemType = DragType | 'add'
export type DropType = 'outside' | 'inside' | 'unmoved'
export type AggregatorType = 'sum' | 'avg' | 'count' | 'COUNTDISTINCT' | 'max' | 'min' | 'median' | 'var' | 'dev'
interface IDataColumn {
name: string
from?: string
sort?: IFieldSortConfig
agg?: AggregatorType
field?: IFieldConfig
format?: IFieldFormatConfig
}
export interface IDataParamSource extends IDataColumn {
type: DragType
visualType: ViewModelVisualTypes
title?: string
chart?: IChartInfo
config?: IDataParamConfig
}
export interface IDragItem extends IDataParamSource {
checked?: boolean
}
export interface IDataParamConfig {
actOn?: string
values?: {
[key: string]: string
},
sql?: string
sqlModel?: IFilter[]
filterSource?: any
field?: {
alias: string,
desc: string
}
}
export interface IDataParamSourceInBox extends IDataColumn {
type: DropboxItemType
visualType?: ViewModelVisualTypes
chart?: IChartInfo
config?: IDataParamConfig
}
interface IDropboxProps {
name: string
title: string
type: DropboxType
value: object
items: IDataParamSource[]
mode: WidgetMode
selectedChartId: number
dragged: IDataParamSource
panelList: IDataParamSource[]
dimetionsCount: number
metricsCount: number
onValueChange: (key: string, value: string) => void
onItemDragStart: (item: IDataParamSource, e: React.DragEvent<HTMLLIElement | HTMLParagraphElement>) => void
onItemDragEnd: (dropType: DropType) => void
onItemRemove: (name: string) => (e) => void
onItemSort: (item: IDataParamSource, sort: FieldSortTypes) => void
onItemChangeAgg: (item: IDataParamSource, agg: AggregatorType) => void
onItemChangeColorConfig: (item: IDataParamSource) => void
onItemChangeFilterConfig: (item: IDataParamSource) => void
onItemChangeFieldConfig: (item: IDataParamSource) => void
onItemChangeFormatConfig: (item: IDataParamSource) => void
onItemChangeChart: (item: IDataParamSource) => (chart: IChartInfo) => void
beforeDrop: (name: string, cachedItem: IDataParamSource, resolve: (next: boolean) => void) => void
onDrop: (name: string, dropIndex: number, dropType: DropType, changedItems: IDataParamSource[], config?: IDataParamConfig) => void
}
interface IDropboxStates {
entering: boolean
items: IDataParamSourceInBox[]
dropIndex: number
dropType: DropType
}
export class Dropbox extends React.PureComponent<IDropboxProps, IDropboxStates> {
constructor (props) {
super(props)
this.state = {
entering: false,
items: [],
dropIndex: -1,
dropType: void 0
}
}
private container: HTMLDivElement = null
private width: number = 0
private x: number = 0
private y: number = 0
private PADDING = 5
private BOX_MIN_HEIGHT = 54
private ITEM_HEIGHT = 28
public componentWillMount () {
this.getItems(this.props)
}
public componentWillReceiveProps (nextProps) {
if (nextProps.items !== this.props.items) {
this.getItems(nextProps)
}
}
private getItems = (props) => {
this.setState({
items: [...props.items]
})
}
private getBoxRect = () => {
const rect = this.container.getBoundingClientRect() as DOMRect
this.width = rect.width
this.x = rect.x
this.y = rect.y
}
private dragEnter = () => {
this.getBoxRect()
this.setState({
dropIndex: 0,
entering: true
})
}
private dragOver = (e) => {
e.preventDefault()
const { items, dragged } = this.props
if (!(dragged.type === 'category'
&& !dragged.from
&& items.find((i) => i.name === dragged.name))) {
// if (this.props.size === 'large') {
const { clientX, clientY } = e
const physicalDropIndex = this.calcPhysicalDropIndex(clientX, clientY)
this.previewDropPosition(physicalDropIndex)
// } else {
// if (this.state.dropIndex === -1) {
// this.setState({
// dropIndex: 0
// })
// }
// }
}
}
private dragLeave = () => {
this.setState({
items: this.state.items.filter((i) => i.type !== 'add'),
entering: false,
dropIndex: -1,
dropType: void 0
})
}
private drop = () => {
const { name, items, dragged, beforeDrop, onDrop } = this.props
const { items: itemsState, dropIndex, dropType } = this.state
if (dropIndex >= 0) {
const alreadyHaveIndex = items.findIndex((i) => i.name === dragged.name)
if (!(dragged.type === 'category' && alreadyHaveIndex >= 0 && dragged.from !== name)) {
beforeDrop(name, dragged, (data: boolean | IDataParamConfig) => {
if (data) {
onDrop(name, dropIndex, dropType, itemsState as IDataParamSource[], data as IDataParamConfig)
} else {
this.dragLeave()
}
})
}
}
this.setState({
entering: false,
dropIndex: -1,
dropType: dropType === 'outside'
? void 0
: dropType === void 0
? 'unmoved'
: dropType
})
}
private itemDragEnd = () => {
this.props.onItemDragEnd(this.state.dropType)
this.setState({
dropType: void 0
})
}
private calcPhysicalDropIndex = (dragX, dragY): number => {
const relX = dragX - this.x
const relY = dragY - this.y
const limitX = this.width - this.PADDING
const limitY = Math.max(this.BOX_MIN_HEIGHT - this.PADDING, this.state.items.length * this.ITEM_HEIGHT + this.PADDING)
if (relX > this.PADDING && relY > this.PADDING && relX < limitX && relY < limitY) {
// const row = Math.floor((relX - this.PADDING) / this.ITEM_WIDTH)
// const col = Math.floor((relY - this.PADDING) / this.ITEM_HEIGHT)
// return col * 2 + row
return Math.floor((relY - this.PADDING) / this.ITEM_HEIGHT)
}
}
private previewDropPosition = (physicalDropIndex) => {
const { items, dragged } = this.props
const { items: itemsState } = this.state
const draggedItemIndex = items.findIndex((i) => i.name === dragged.name)
const draggedItemLocalIndex = itemsState.findIndex((is) => is.name === dragged.name)
let itemLength = items.length
if (draggedItemIndex >= 0) {
itemLength -= 1
}
const realDropIndex = physicalDropIndex !== void 0
? Math.min(itemLength, physicalDropIndex)
: itemLength
if (draggedItemIndex < 0) {
if (draggedItemLocalIndex < 0 || draggedItemLocalIndex !== realDropIndex) {
this.setState({
items: [
...items.slice(0, realDropIndex),
{
name: dragged.type === 'category' ? dragged.name : decodeMetricName(dragged.name),
type: 'add'
},
...items.slice(realDropIndex)
],
dropIndex: realDropIndex,
dropType: 'outside'
})
}
} else {
if (draggedItemLocalIndex !== realDropIndex) {
const temp = itemsState.filter((i, index) => index !== draggedItemLocalIndex)
temp.splice(realDropIndex, 0, dragged)
this.setState({
items: temp,
dropIndex: realDropIndex,
dropType: 'inside'
})
}
}
}
public render () {
const {
name,
title,
type,
value,
panelList,
mode,
selectedChartId,
dragged,
dimetionsCount,
metricsCount,
onValueChange,
onItemDragStart,
onItemSort,
onItemChangeAgg,
onItemChangeColorConfig,
onItemChangeFilterConfig,
onItemChangeFieldConfig,
onItemChangeFormatConfig,
onItemChangeChart,
onItemRemove
} = this.props
const { entering, items } = this.state
let shouldResponse = false
let shouleEnter = false
let dragType = ''
if (dragged) {
dragType = dragged.type
if (type === 'all' || type === dragType) {
shouldResponse = true
shouleEnter = entering
}
}
const containerClass = classnames({
[styles.dropContainer]: true,
[styles.dragOver]: shouldResponse
})
const maskClass = classnames({
[styles.mask]: true,
[styles.onTop]: shouldResponse,
[styles.enter]: shouleEnter,
[styles.category]: dragType === 'category',
[styles.value]: dragType === 'value'
})
let setting
if (['color', 'size'].includes(name)) {
let panel
switch (name) {
case 'color':
panel = (
<ColorPanel
list={panelList}
value={value}
showAll={mode === 'pivot'}
onValueChange={onValueChange}
/>
)
break
case 'size':
panel = (
<SizePanel
list={panelList}
value={value}
hasTabs={mode === 'pivot'}
onValueChange={onValueChange}
/>
)
break
}
setting = (
<Popover
content={panel}
trigger="click"
placement="right"
>
<span className={styles.setting}>
<Icon type="setting" /> 设置
</span>
</Popover>
)
}
const itemContent = items.length
? items.map((item) => (
<DropboxItem
key={item.name}
container={name}
item={item}
dimetionsCount={dimetionsCount}
metricsCount={metricsCount}
onDragStart={onItemDragStart}
onDragEnd={this.itemDragEnd}
onSort={onItemSort}
onChangeAgg={onItemChangeAgg}
onChangeFieldConfig={onItemChangeFieldConfig}
onChangeFormatConfig={onItemChangeFormatConfig}
onChangeColorConfig={onItemChangeColorConfig}
onChangeFilterConfig={onItemChangeFilterConfig}
onChangeChart={onItemChangeChart}
onRemove={onItemRemove(item.name)}
/>
))
: (
<DropboxContent
title={title}
type={type}
/>
)
return (
<div className={styles.dropbox}>
<p className={styles.title}>
{title}
{setting}
</p>
<div
className={containerClass}
ref={(f) => this.container = f}
>
{itemContent}
<div
className={maskClass}
onDragEnter={this.dragEnter}
onDragOver={this.dragOver}
onDragLeave={this.dragLeave}
onDrop={this.drop}
/>
</div>
</div>
)
}
}
export default Dropbox | the_stack |
import { nodeMarker, insertAfter, isBooleanAttribute, objectFromArray, runLifecycle } from './util';
import { MemoryOptions, MosaicComponent } from './options';
import { OTT, _repaint } from './templating';
import MAD from './mad';
/** Represents a piece of dynamic content in the markup. */
export default class Memory {
constructor(public config: MemoryOptions) {}
/** Batches an update together with other component updates so that
* later on they can all perform a single repaint. */
batch(component: MosaicComponent, batchName: string, batchValue: any) {
// Add the (name, value) pair as a batch operation to be carried out
// at the end of the parent component's repaint cycle.
const isData = component.data.hasOwnProperty(batchName);
const batchFunc = isData ? '_batchData' : '_batchAttribute';
component[batchFunc](batchName, batchValue);
// Check if the number of batches matches up to the number of
// attributes present on the HTML element tag. Checking this number
// is fine because you don't split up attributes from data until
// the end of this step.
const bts = component._getBatches();
const totalLength = this.config.trackedAttributeCount || 0;
const attrsLength = bts.attributes.length;
const dataLength = bts.data.length;
if(attrsLength + dataLength >= totalLength) {
// Go through the immediately nested nodes and update them with the
// new data, while also sending over the parsed attributes. Then
// clear the batch when you are done.
const justData = objectFromArray(bts.data);
const justAttrs = objectFromArray(bts.attributes);
// Set the data on the component then repaint it.
if(bts.data.length > 0) {
component.barrier = true;
let keys = Object.keys(justData);
for(let i = 0; i < keys.length; i++) {
const key = keys[i];
const val = justData[key];
component.data[key] = val;
}
component.barrier = false;
}
// Make the component receive the HTML attributes.
if(bts.attributes.length > 0)
runLifecycle('received', component, justAttrs);
// Repaint.
if(bts.data.length > 0)
component.repaint();
// When you are done performing the batcehd updates, clear
// the batch so you can do it again for the next update.
component._resetBatches();
}
}
/** Applies the changes to the appropriate DOM nodes when data changes. */
commit(element: ChildNode|Element|ShadowRoot, pointer: ChildNode|Element, oldValue: any, newValue: any) {
// console.log(element, pointer, oldValue, newValue, this);
switch(this.config.type) {
case 'node':
this.commitNode(element, pointer, oldValue, newValue);
break;
case 'attribute':
if(!this.config.attribute) break;
const { name } = this.config.attribute;
const func = this.config.isEvent ?
this.commitEvent.bind(this) : this.commitAttribute.bind(this);
func(element, pointer, name, oldValue, newValue);
break;
}
}
/** Applies changes to memories of type "node." */
commitNode(element: HTMLElement|ChildNode|ShadowRoot, pointer: HTMLElement|ChildNode, oldValue: any, newValue: any) {
// If you come across a node inside of a Mosaic component, then do not
// actually add it to the DOM. Instead, let it be rendered by the
// constructor and set into the "descendants" property so the component
// itself can decide whether or not to use it as a descendants property.
if(this.config.isComponentType === true && pointer instanceof MosaicComponent)
return;
if(Array.isArray(newValue)) {
let items = newValue;
let frag = document.createDocumentFragment();
for(let i = 0; i < items.length; i++) {
let item = items[i];
let ott = OTT(item);
let node = ott.instance;
_repaint(node, ott.memories, [], ott.values, true);
frag.append(node);
}
let addition = document.createElement('div');
addition.appendChild(frag);
pointer.replaceWith(addition);
}
if(typeof newValue === 'object' && newValue.__isTemplate) {
const ott = OTT(newValue);
const inst = ott.instance;
pointer.replaceWith(inst);
_repaint(inst, ott.memories, [], ott.values, true);
}
if(typeof newValue === 'object' && newValue.__isKeyedArray) {
this.commitArray(element, pointer, oldValue, newValue);
}
else if(typeof newValue === 'function') {
const called = newValue();
const ott = OTT(called);
const inst = ott.instance;
pointer.replaceWith(inst);
_repaint(inst, ott.memories, [], ott.values, true);
}
else {
pointer.replaceWith(newValue);
}
}
/** Applies attributee changes. */
commitAttribute(element: HTMLElement|ChildNode|ShadowRoot, pointer: HTMLElement|ChildNode,
name: string, oldValue: any, newValue: any) {
const attribute = (pointer as Element).attributes.getNamedItem(name);
// If you come across a boolean attribute that should be true, then add
// it as an attribute.
if(!attribute) {
if(isBooleanAttribute(name) && newValue === true)
(pointer as Element).setAttribute(name, 'true');
return;
}
// Replace the first instance of the marker with the new value.
// Then be sure to set the attribute value to this newly replaced
// string so that on the next dynamic attribute it goes to the next
// position to replace (notice how the new value gets converted to a
// string first. This ensures attribute safety).
const newAttributeValue = attribute.value
.replace(nodeMarker, ''+newValue)
.replace(oldValue, ''+newValue);
const setValue = newAttributeValue.length > 0 ? newAttributeValue : newValue;
(pointer as Element).setAttribute(name, setValue);
// Add or remove boolean attributes. Make sure to also the tracked
// attribute count so that you know how many attributes to check
// for at any given time of an update cycle.
if(isBooleanAttribute(name)) {
if(newValue === true) {
(pointer as Element).setAttribute(name, 'true');
if(this.config.trackedAttributeCount)
this.config.trackedAttributeCount += 1;
} else {
(pointer as Element).removeAttribute(name);
if(this.config.trackedAttributeCount)
this.config.trackedAttributeCount -= 1;
}
}
// Remove the function attribute so it's not cluttered. The event
// listener will still exist on the element, though.
if(typeof newValue === 'function') {
(pointer as Element).removeAttribute(name);
// Since you're removing the function as an attribute, be sure
// to update the tracked attribute count so we're not always
// looking for it during a batched update.
if(this.config.trackedAttributeCount)
this.config.trackedAttributeCount -= 1;
}
// Batch the pointer element and the attribute [name, value] pair together so that
// it can be update all at once at the end of the repaint cycle.
if(this.config.isComponentType === true && pointer instanceof MosaicComponent)
this.batch(pointer, name, newValue);
}
/** Applies event changes such as adding/removing listeners. */
commitEvent(element: HTMLElement|ChildNode|ShadowRoot, pointer: HTMLElement|ChildNode,
name: string, oldValue: any, newValue: any) {
const events = (pointer as any).eventHandlers || {};
const shortName = name.substring(2);
// If there's no new value, then try to remove the event listener.
if(!newValue && events[name])
(pointer as Element).removeEventListener(shortName, events[name]);
// While there is a new value, add it to an "eventHandlers" property
// so that you can always keep track of the element's functions.
else if(newValue) {
events[name] = newValue.bind(element);
(pointer as any).eventHandlers = events;
(pointer as Element).addEventListener(
shortName,
(pointer as any).eventHandlers[name]
);
}
// Remove the attribute from the DOM tree to avoid clutter.
if((pointer as Element).hasAttribute(name)) {
(pointer as Element).removeAttribute(name);
if(this.config.trackedAttributeCount)
this.config.trackedAttributeCount -= 1;
}
// Batch the pointer element and the attribute [name, value] pair together so that
// it can be update all at once at the end of the repaint cycle.
if(this.config.isComponentType === true && pointer instanceof MosaicComponent)
this.batch(pointer, name, newValue);
}
/** Helper function for applying changes to arrays. */
commitArray(element: HTMLElement|ChildNode|ShadowRoot, pointer: HTMLElement|ChildNode,
oldValue: any, newValue: any) {
const oldItems = oldValue && typeof oldValue === 'object' && oldValue.__isKeyedArray
? oldValue.items : [];
const newItems = newValue && typeof newValue === 'object' && newValue.__isKeyedArray
? newValue.items : [];
// Heuristics: For repaints that contain only additions or deletions
// don't bother going through the MAD algorithm. Instead, just perform
// the same operation on everything.
// All Additions:
if(oldItems.length === 0 && newItems.length > 0) {
let frag = document.createDocumentFragment();
for(let i = 0; i < newItems.length; i++) {
const item = newItems[i];
const ott = OTT(item, item.key);
const node = ott.instance;
node.arrayOTT = ott;
// Only repaint here if it is NOT a Mosaic component.
if(!(node instanceof MosaicComponent))
_repaint(node, ott.memories, [], ott.values, true);
// Add each item to a document fragment, then set all of it
// at the end for improved DOM performance.
frag.appendChild(node);
}
insertAfter(frag, pointer);
return;
}
// All Deletions:
if(oldItems.length > 0 && newItems.length === 0) {
for(let i = 0; i < oldItems.length; i++) {
// Find the node and remove it from the DOM.
const key = oldItems[i].key;
const found = document.querySelector(`[key='${key}']`);
if(found) found.remove();
}
return;
}
// Use "MAD" to find the differences in the arrays.
const mad = new MAD(oldItems, newItems);
const diffs = mad.diff();
// Keep track of the operation index starting from the beginning of
// the array. Loop through until the end of the list.
let opIndex = 0;
for(let i = 0; i < diffs.length; i++) {
const { added, deleted, count, edit } = diffs[i];
// Modification.
if(deleted && (i + 1) < diffs.length && diffs[i+1].added && count === diffs[i+1].count) {
// There could be more than one modification at a time, so run
// through each one and replace the node at the old index with
// a rendered OTT at the same index.
for(let j = 0; j < edit.length; j++) {
const modItem = edit[j];
const modRef = document.querySelector(`[key="${modItem.key}"]`);
const newItem = diffs[i+1].edit[j];
const ott = OTT(newItem, newItem.key);
const node = ott.instance;
node.arrayOTT = ott;
// Only repaint here if it is NOT a Mosaic component.
if(!(node instanceof MosaicComponent))
_repaint(node, ott.memories, [], ott.values, true);
if(modRef) modRef.replaceWith(node);
}
// You now have to skip over the next operation, which is technically
// an addition. This addition is no longer necessary since we determined
// that it was really a modification.
i += 1;
}
// Handle "add" operations.
else if(added) {
// For each item in the edit, add it starting from the op index.
let ref: HTMLElement|ChildNode|null = pointer;
// First we have to make sure we have the right insertion index.
// Sometimes you are inserting items into the middle of an array,
// and other times you are appending to the end of the array.
if(oldItems.length > 0) ref = document.querySelector(`[key="${oldItems[opIndex - 1].key}"]`);
if(!ref) ref = document.querySelector(`[key="${oldItems[oldItems.length - 1].key}"]`);
let frag = document.createDocumentFragment();
for(let j = 0; j < edit.length; j++) {
const addition = edit[j];
const ott = OTT(addition, addition.key);
const node = ott.instance;
node.arrayOTT = ott;
// Only repaint here if it is NOT a Mosaic component.
if(!(node instanceof MosaicComponent))
_repaint(node, ott.memories, [], ott.values, true);
// Append to a document fragment for faster repainting.
frag.appendChild(node);
}
// Insert the fragment into the reference spot.
ref = insertAfter(frag, ref);
}
// Handle "delete" operations.
else if(deleted) {
// For each item in the edit, add it starting from the op index.
for(let j = 0; j < edit.length; j++) {
const obj = edit[j];
const found = document.querySelector(`[key='${obj.key}']`);
if(found) found.remove();
}
// When we make a deletion, we have to go back one index because
// the length of the array is now shorter.
opIndex -= count;
}
// Update the operation index as we move through the array.
opIndex += count;
}
}
} | the_stack |
import * as React from "react";
import { WebPartContext } from "@microsoft/sp-webpart-base";
import commonServices from "../Common/CommonServices";
import * as stringsConstants from "../constants/strings";
import styles from "../scss/TOTEnableTournament.module.scss";
import * as strings from "../constants/strings";
//React Boot Strap
import Row from "react-bootstrap/Row";
import Col from "react-bootstrap/Col";
//Fluent UI controls
import { IButtonStyles, IChoiceGroupStyles, PrimaryButton } from "@fluentui/react";
import { Label } from "@fluentui/react/lib/Label";
import { ChoiceGroup, IChoiceGroupOption } from "@fluentui/react";
import { Dialog, DialogType, DialogFooter } from "@fluentui/react/lib/Dialog";
import { Icon, IIconProps } from '@fluentui/react/lib/Icon';
import { mergeStyleSets } from '@fluentui/react/lib/Styling';
import { TooltipHost, ITooltipHostStyles } from '@fluentui/react/lib/Tooltip';
import { DirectionalHint } from "@microsoft/office-ui-fabric-react-bundle";
//Global Variables
let commonServiceManager: commonServices;
const backIcon: IIconProps = { iconName: 'NavigateBack' };
const backBtnStyles: Partial<IButtonStyles> = {
root: {
borderColor: "#33344A",
backgroundColor: "white",
height: "auto"
},
rootHovered: {
borderColor: "#33344A",
backgroundColor: "white",
color: "#000003"
},
rootPressed: {
borderColor: "#33344A",
backgroundColor: "white",
color: "#000003"
},
icon: {
fontSize: "17px",
fontWeight: "bolder",
color: "#000003",
opacity: 1
},
label: {
font: "normal normal bold 14px/24px Segoe UI",
letterSpacing: "0px",
color: "#000003",
opacity: 1,
marginTop: "-3px"
}
};
export interface IEnableTournamentProps {
context?: WebPartContext;
siteUrl: string;
onClickCancel: Function;
}
interface IEnableTournamentState {
tournamentsList: any;
selectedTournament: string;
selectedTournamentId: string;
activeTournament: string;
activeTournamentId: string;
activeTournamentFlag: boolean;
showSuccess: boolean;
successMessage: string;
showError: boolean;
errorMessage: string;
tournamentError: boolean;
hideDialog: boolean;
noTournamentsFlag: boolean;
}
const tooltipStyles = {
calloutProps: { gapSpace: 0, style: { paddingLeft: "4%" } }
};
const hostStyles: Partial<ITooltipHostStyles> = { root: { display: 'inline-block' } };
const classes = mergeStyleSets({
icon: {
fontSize: '16px',
color: '#1d0f62',
cursor: 'pointer',
fontWeight: 'bolder',
}
});
const endButtonStyles: Partial<IButtonStyles> = {
root: {
marginBottom: "20px",
height: "38px"
},
textContainer: { fontSize: "16px" },
icon: {
fontSize: "26px",
fontWeight: "bolder",
color: "#FFFFFF",
opacity: 1
}
};
const startButtonStyles: Partial<IButtonStyles> = {
root: {
height: "38px"
},
textContainer: { fontSize: "16px" },
icon: {
fontSize: "18px",
fontWeight: "bolder",
color: "#FFFFFF",
opacity: 1
}
};
const choiceGroupStyles: Partial<IChoiceGroupStyles> = {
flexContainer: [
{
selectors: {
".ms-ChoiceField": {
textAlign: "left",
font: "normal normal 600 18px/20px Segoe UI",
letterSpacing: "0px",
color: "#979593",
opacity: 1
}
}
}
]
};
export default class TOTEnableTournament extends React.Component<
IEnableTournamentProps,
IEnableTournamentState
> {
constructor(props: IEnableTournamentProps, state: IEnableTournamentState) {
super(props);
//Set default values for state
this.state = {
tournamentsList: [],
selectedTournament: "",
activeTournament: "None",
activeTournamentId: "",
activeTournamentFlag: true,
selectedTournamentId: "",
showSuccess: false,
showError: false,
errorMessage: "",
tournamentError: false,
successMessage: "",
hideDialog: true,
noTournamentsFlag: false,
};
commonServiceManager = new commonServices(
this.props.context,
this.props.siteUrl
);
//Bind Methods
this.getTournamentsList = this.getTournamentsList.bind(this);
this.onTournamentSelect = this.onTournamentSelect.bind(this);
this.enableTournament = this.enableTournament.bind(this);
this.getActiveTournament = this.getActiveTournament.bind(this);
this.completeTournament = this.completeTournament.bind(this);
}
//On load of app bind tournaments to choice list and populate the current Active tournament
public async componentDidMount() {
this.getTournamentsList();
this.getActiveTournament();
}
//get active tournament from master list and populate the label
private async getActiveTournament() {
console.log(
stringsConstants.TotLog + "Getting active tournament from master list."
);
try {
let filterActive: string =
"Status eq '" + stringsConstants.TournamentStatusActive + "'";
const activeTournamentsArray: any[] =
await commonServiceManager.getItemsWithOnlyFilter(
stringsConstants.TournamentsMasterList,
filterActive
);
if (activeTournamentsArray.length > 0)
this.setState({
activeTournament: activeTournamentsArray[0]["Title"],
activeTournamentId: activeTournamentsArray[0]["Id"],
});
else this.setState({ activeTournamentFlag: false });
} catch (error) {
console.error("TOT_TOTEnableTournament_getActiveTournament \n", error);
this.setState({
showError: true,
errorMessage:
stringsConstants.TOTErrorMessage +
"while retrieving the active tournament. Below are the details: \n" +
JSON.stringify(error),
});
}
}
// Get a list of all tournaments that are "Not Started" and to bind to Choice List
private async getTournamentsList() {
console.log(
stringsConstants.TotLog + "Getting tournaments from master list."
);
try {
let selectFilter: string =
"Status eq '" + stringsConstants.TournamentStatusNotStarted + "'";
const allTournamentsArray: any[] =
await commonServiceManager.getItemsWithOnlyFilter(
stringsConstants.TournamentsMasterList,
selectFilter
);
var tournamentsChoices = [];
if (allTournamentsArray.length > 0) {
//Loop through all "Not Started" tournaments and create an array with key and text
await allTournamentsArray.forEach((eachTournament) => {
tournamentsChoices.push({
key: eachTournament["Id"],
text: eachTournament["Title"],
});
});
this.setState({ tournamentsList: tournamentsChoices });
}
//If no tournaments are found in the master list set the flag
else this.setState({ noTournamentsFlag: true });
} catch (error) {
console.error("TOT_TOTEnableTournament_getTournamentsList \n", error);
this.setState({
showError: true,
errorMessage:
stringsConstants.TOTErrorMessage +
"while retrieving the tournaments list. Below are the details: \n" +
JSON.stringify(error),
});
}
}
//on select of a tournament set the state
private onTournamentSelect = async (
ev: React.FormEvent<HTMLInputElement>,
option: IChoiceGroupOption
): Promise<void> => {
this.setState({
selectedTournament: option.text,
selectedTournamentId: option.key,
});
}
//On enabling a tournament change the status in master list
private enableTournament() {
try {
//clear previous error messages on the form
this.setState({
showError: false,
tournamentError: false,
hideDialog: true,
});
if (this.state.selectedTournament == "")
this.setState({ tournamentError: true });
else {
console.log(stringsConstants.TotLog + "Enabling selected tournament.");
let submitTournamentObject: any = {
Status: stringsConstants.TournamentStatusActive,
};
commonServiceManager
.updateListItem(
stringsConstants.TournamentsMasterList,
submitTournamentObject,
this.state.selectedTournamentId
)
.then((result) => {
//Set Enabled tournament as Active tournament once enabled
this.setState({
activeTournamentFlag: true,
activeTournament: this.state.selectedTournament,
activeTournamentId: this.state.selectedTournamentId,
});
//clear the state values
this.setState({ selectedTournament: "", selectedTournamentId: "" });
//Show success message
this.setState({
showSuccess: true,
successMessage: "Tournament enabled successfully.",
});
//Refresh the tournaments list after enabling a tournament by deleting it from the array
let newTournamentsRefresh: any[] = this.state.tournamentsList;
for (
var counter = 0;
counter < newTournamentsRefresh.length;
counter++
) {
if (
newTournamentsRefresh[counter]["text"] ==
this.state.activeTournament
) {
newTournamentsRefresh.splice(counter, 1);
this.setState({ tournamentsList: newTournamentsRefresh });
break;
}
}
if (newTournamentsRefresh.length == 0)
this.setState({ noTournamentsFlag: true });
})
.catch((error) => {
console.error("TOT_TOTEnableTournament_enableTournament \n", error);
this.setState({
showError: true,
errorMessage:
stringsConstants.TOTErrorMessage +
"while enabling the tournament. Below are the details: \n" +
JSON.stringify(error),
});
});
}
} catch (error) {
console.error("TOT_TOTEnableTournament_enableTournament \n", error);
this.setState({
showError: true,
errorMessage:
stringsConstants.TOTErrorMessage +
"while enabling the tournament. Below are the details: \n" +
JSON.stringify(error),
});
}
}
//On Completing a tournament change the status in the master list
private completeTournament() {
try {
//clear previous error messages on the form
this.setState({
showError: false,
tournamentError: false,
hideDialog: true,
});
console.log(stringsConstants.TotLog + "Completing active tournament.");
let submitTournamentObject: any = {
Status: stringsConstants.TournamentStatusCompleted,
};
commonServiceManager
.updateListItem(
stringsConstants.TournamentsMasterList,
submitTournamentObject,
this.state.activeTournamentId
)
.then((result) => {
//Reset the state
this.setState({
activeTournamentFlag: false,
activeTournament: "None",
activeTournamentId: "",
selectedTournament: "",
selectedTournamentId: "",
});
//Show success message
this.setState({
showSuccess: true,
successMessage: "Tournament ended successfully.",
});
})
.catch((error) => {
console.error("TOT_TOTEnableTournament_completeTournament \n", error);
this.setState({
showError: true,
errorMessage:
stringsConstants.TOTErrorMessage +
"while completing the tournament. Below are the details: \n" +
JSON.stringify(error),
});
});
} catch (error) {
console.error("TOT_TOTEnableTournament_completeTournament \n", error);
this.setState({
showError: true,
errorMessage:
stringsConstants.TOTErrorMessage +
"while completing the tournament. Below are the details: \n" +
JSON.stringify(error),
});
}
}
//Render Method
public render(): React.ReactElement<IEnableTournamentProps> {
return (
<div className={`container ${styles.mainContainer}`}>
<div className={styles.manageTournamentPath}>
<img src={require("../assets/CMPImages/BackIcon.png")}
className={styles.backImg}
/>
<span
className={styles.backLabel}
onClick={() => this.props.onClickCancel()}
title="Tournament of Teams"
>
Tournament of Teams
</span>
<span className={styles.border}></span>
<span className={styles.manageTournamentLabel}>Manage Tournaments</span>
</div>
<h5 className={styles.pageHeader}>Manage Tournaments</h5>
<div className={styles.textLabels}>
<Label>{strings.ManageTotLabel1}</Label>
<Label>{strings.ManageTotLabel2}</Label>
</div>
<br />
<Dialog
hidden={this.state.hideDialog}
onDismiss={() => this.setState({ hideDialog: true })}
dialogContentProps={{
type: DialogType.close,
title: "Confirm",
subText: this.state.activeTournamentFlag ? "Are you sure want to end the tournament?" : "Are you sure want to start the new tournament?",
}}
containerClassName={'ms-dialogMainOverride ' + styles.textDialog}
modalProps={{ isBlocking: false }}
>
<DialogFooter>
{this.state.activeTournamentFlag && (
<PrimaryButton
onClick={this.completeTournament}
text="Yes"
className={styles.yesBtn}
title="Yes"
/>
)}
{!this.state.activeTournamentFlag && (
<PrimaryButton
onClick={this.enableTournament}
text="Yes"
className={styles.yesBtn}
title="Yes"
/>
)}
<PrimaryButton
onClick={() => this.setState({ hideDialog: true })}
text="No"
className={styles.noBtn}
title="No"
/>
</DialogFooter>
</Dialog>
<div>
{this.state.showSuccess && (
<Label className={styles.successMessage}>
<img src={require('../assets/TOTImages/tickIcon.png')} alt="tickIcon" className={styles.tickImage} />
{this.state.successMessage}
</Label>
)}
{this.state.showError && (
<Label className={styles.errorMessage}>
{this.state.errorMessage}
</Label>
)}
</div>
<div>
<Row>
<Col>
<div className={styles.tournamentStatus}>
<label>Active Tournament: </label>
<label> {this.state.activeTournament} </label>
</div>
</Col>
</Row>
<Row>
<Col>
<PrimaryButton
disabled={!this.state.activeTournamentFlag}
iconProps={{
iconName: "StatusCircleErrorX"
}}
text="End Tournament"
title="End Tournament"
styles={endButtonStyles}
onClick={() => this.setState({ hideDialog: false })}
className={
!this.state.activeTournamentFlag
? styles.disabledBtn
: styles.completeBtn
}
/>
</Col>
</Row>
</div>
<br />
<div className={styles.startTournmentArea}>
<h4 className={styles.subHeaderUnderline}>Start Tournament{" "}</h4>
<div className={styles.infoArea}>
<TooltipHost
content="A new tournament can only be started if there is no active tournament. To start a new tournament end the current tournament."
tooltipProps={tooltipStyles}
styles={hostStyles}
directionalHint={DirectionalHint.bottomCenter}
>
<Icon aria-label="Info" iconName="Info" className={classes.icon} />
</TooltipHost>
</div>
</div>
<div>
<Row>
<Col md={6}>
<ChoiceGroup
disabled={this.state.activeTournamentFlag}
onChange={this.onTournamentSelect.bind(this)}
options={this.state.tournamentsList}
styles={choiceGroupStyles}
/>
{this.state.noTournamentsFlag && (
<Label className={styles.errorMessage}>
No tournaments found.
</Label>
)}
{this.state.tournamentError && (
<Label className={styles.errorMessage}>
Select a tournament to enable.
</Label>
)}
</Col>
</Row>
<Row>
<Col md={6}>
<div className={styles.bottomBtnArea}>
{!this.state.noTournamentsFlag && (
<PrimaryButton
disabled={this.state.activeTournamentFlag}
text="Start Tournament"
title="Start Tournament"
iconProps={{
iconName: "Play"
}}
styles={startButtonStyles}
onClick={() => this.setState({ hideDialog: false })}
className={
this.state.activeTournamentFlag
? styles.disabledBtn
: styles.enableBtn
}
/>
)}
<PrimaryButton
text="Back"
title="Back"
iconProps={backIcon}
styles={backBtnStyles}
onClick={() => this.props.onClickCancel()}
/>
</div>
</Col>
</Row>
</div>
</div> //Final DIV
);
}
} | the_stack |
import type { BaseNode } from 'estree'
import type * as jsxType from 'estree-jsx'
import { name as isIdentifierName } from 'estree-util-is-identifier-name'
import { walk } from 'estree-walker'
import { analyze } from 'periscopic'
import specifiersToObjectPattern from '../estree/specifiers-to-object-pattern'
export interface Options {
providerImportSource?: string
outputFormat: 'program' | 'function-body'
}
function isJSXElement(node: BaseNode): node is jsxType.JSXElement {
return node.type === 'JSXElement'
}
function isFunctionDeclaration(
node: BaseNode
): node is jsxType.FunctionDeclaration {
return node.type === 'FunctionDeclaration'
}
/**
* A plugin that rewrites JSX in functions to accept components as
* `props.components` (when the function is called `OrgaContent`), or from
* a provider (if there is one).
* It also makes sure that any undefined components are defined: either from
* received components or as a function that throws an error.
*/
export function estreeJsxRewrite(options: Options) {
const { providerImportSource, outputFormat } = options
return (tree) => {
// Find everything that’s defined in the top-level scope.
const topScope = analyze(tree).scope.declarations
const stack: {
objects: string[]
components: string[]
tags: string[]
}[] = []
let importProvider = false
walk(tree, {
enter(node) {
if (
node.type === 'FunctionDeclaration' ||
node.type === 'FunctionExpression' ||
node.type === 'ArrowFunctionExpression'
) {
stack.push({ objects: [], components: [], tags: [] })
}
if (isJSXElement(node) && stack.length > 0) {
const element = /** @type {JSXElement} */ node
// Note: inject into the *top-level* function that contains JSX.
// Yes: we collect info about the stack, but we assume top-level functions
// are components.
const scope = stack[0]
let name = node.openingElement.name
// `<x.y>`, `<Foo.Bar>`, `<x.y.z>`.
if (name.type === 'JSXMemberExpression') {
// Find the left-most identifier.
while (name.type === 'JSXMemberExpression') name = name.object
if (
!scope.objects.includes(name.name) &&
!topScope.has(name.name)
) {
scope.objects.push(name.name)
}
}
// `<xml:thing>`.
else if (name.type === 'JSXNamespacedName') {
// Ignore namespaces.
}
// If the name is a valid ES identifier, and it doesn’t start with a
// lowercase letter, it’s a component.
// For example, `$foo`, `_bar`, `Baz` are all component names.
// But `foo` and `b-ar` are tag names.
else if (isIdentifierName(name.name) && !/^[a-z]/.test(name.name)) {
if (
!scope.components.includes(name.name) &&
!topScope.has(name.name)
) {
scope.components.push(name.name)
}
}
// @ts-expect-error Allow fields passed through from mdast through hast to
// esast.
else if (element.data && element.data._xdmExplicitJsx) {
// Do not turn explicit JSX into components from `_components`.
// As in, a given `h1` component is used for `# heading` (next case),
// but not for `<h1>heading</h1>`.
} else {
if (!scope.tags.includes(name.name)) {
scope.tags.push(name.name)
}
element.openingElement.name = {
type: 'JSXMemberExpression',
object: { type: 'JSXIdentifier', name: '_components' },
property: name,
}
if (element.closingElement) {
element.closingElement.name = {
type: 'JSXMemberExpression',
object: { type: 'JSXIdentifier', name: '_components' },
property: { type: 'JSXIdentifier', name: name.name },
}
}
}
}
},
leave(node) {
const defaults: jsxType.Property[] = []
const actual: string[] = []
const parameters: jsxType.Expression[] = []
const declarations: jsxType.VariableDeclarator[] = []
if (
node.type === 'FunctionDeclaration' ||
node.type === 'FunctionExpression' ||
node.type === 'ArrowFunctionExpression'
) {
const fn = node as jsxType.Function
const scope = stack.pop()
let name: string
// Supported for types but our stack is good!
if (!scope) throw new Error('Expected scope on stack')
for (name of scope.tags) {
defaults.push({
type: 'Property',
kind: 'init',
key: { type: 'Identifier', name },
value: { type: 'Literal', value: name },
method: false,
shorthand: false,
computed: false,
})
}
actual.push(...scope.components)
for (name of scope.objects) {
// In some cases, a component is used directly (`<X>`) but it’s also
// used as an object (`<X.Y>`).
if (!actual.includes(name)) {
actual.push(name)
}
}
if (defaults.length > 0 || actual.length > 0) {
parameters.push({ type: 'ObjectExpression', properties: defaults })
if (providerImportSource) {
importProvider = true
parameters.push({
type: 'CallExpression',
callee: { type: 'Identifier', name: '_provideComponents' },
arguments: [],
optional: false,
})
}
// Accept `components` as a prop if this is the `OrgaContent` function.
if (
isFunctionDeclaration(fn) &&
fn.id &&
fn.id.name === 'OrgaContent'
) {
parameters.push({
type: 'MemberExpression',
object: { type: 'Identifier', name: 'props' },
property: { type: 'Identifier', name: 'components' },
computed: false,
optional: false,
})
}
declarations.push({
type: 'VariableDeclarator',
id: { type: 'Identifier', name: '_components' },
init:
parameters.length > 1
? {
type: 'CallExpression',
callee: {
type: 'MemberExpression',
object: { type: 'Identifier', name: 'Object' },
property: { type: 'Identifier', name: 'assign' },
computed: false,
optional: false,
},
arguments: parameters,
optional: false,
}
: parameters[0],
})
// Add components to scope.
// For `['MyComponent', 'OrgaLayout']` this generates:
// ```js
// const {MyComponent, wrapper: OrgaLayout} = _components
// ```
// Note that OrgaLayout is special as it’s taken from
// `_components.wrapper`.
if (actual.length > 0) {
declarations.push({
type: 'VariableDeclarator',
id: {
type: 'ObjectPattern',
properties: actual.map((name) => ({
type: 'Property',
kind: 'init',
key: {
type: 'Identifier',
name: name === 'OrgaLayout' ? 'wrapper' : name,
},
value: { type: 'Identifier', name },
method: false,
shorthand: name !== 'OrgaLayout',
computed: false,
})),
},
init: { type: 'Identifier', name: '_components' },
})
}
// Arrow functions with an implied return:
if (fn.body.type !== 'BlockStatement') {
fn.body = {
type: 'BlockStatement',
body: [{ type: 'ReturnStatement', argument: fn.body }],
}
}
fn.body.body.unshift({
type: 'VariableDeclaration',
kind: 'const',
declarations,
})
}
}
},
})
// If a provider is used (and can be used), import it.
if (importProvider && providerImportSource) {
tree.body.unshift(
createImportProvider(providerImportSource, outputFormat)
)
}
}
}
function createImportProvider(
providerImportSource: string,
outputFormat: Options['outputFormat']
): jsxType.Statement | jsxType.ModuleDeclaration {
const specifiers: Array<jsxType.ImportSpecifier> = [
{
type: 'ImportSpecifier',
imported: { type: 'Identifier', name: 'useOrgaComponents' },
local: { type: 'Identifier', name: '_provideComponents' },
},
]
return outputFormat === 'function-body'
? ({
type: 'VariableDeclaration',
kind: 'const',
declarations: [
{
type: 'VariableDeclarator',
id: specifiersToObjectPattern(specifiers),
init: {
type: 'MemberExpression',
object: { type: 'Identifier', name: 'arguments' },
property: { type: 'Literal', value: 0 },
computed: true,
optional: false,
},
},
],
} as jsxType.Statement)
: ({
type: 'ImportDeclaration',
specifiers,
source: { type: 'Literal', value: providerImportSource },
} as jsxType.ModuleDeclaration)
} | the_stack |
import { ConfigurationTarget, Progress, window, WorkspaceFolder } from "vscode";
import { IdfToolsManager, IEspIdfTool } from "../idfToolsManager";
import * as utils from "../utils";
import { getEspIdfVersions } from "./espIdfVersionList";
import { IEspIdfLink } from "../views/setup/types";
import { getPythonList } from "./installPyReqs";
import { pathExists } from "fs-extra";
import path from "path";
import { getPythonEnvPath } from "../pythonManager";
import { Logger } from "../logger/logger";
import * as idfConf from "../idfConfiguration";
import { getPropertyFromJson, getSelectedIdfInstalled } from "./espIdfJson";
export interface ISetupInitArgs {
espIdfPath: string;
espIdfVersion: string;
espToolsPath: string;
exportedPaths: string;
exportedVars: string;
espIdfVersionsList: IEspIdfLink[];
gitPath: string;
gitVersion: string;
hasPrerequisites: boolean;
pythonVersions: string[];
toolsResults: IEspIdfTool[];
pyBinPath: string;
}
export async function checkPreviousInstall(
pythonVersions: string[]
): Promise<ISetupInitArgs> {
const containerPath =
process.platform === "win32" ? process.env.USERPROFILE : process.env.HOME;
const confEspIdfPath = idfConf.readParameter("idf.espIdfPath") as string;
const confToolsPath = idfConf.readParameter("idf.toolsPath") as string;
const confPyPath = idfConf.readParameter("idf.pythonBinPath") as string;
const toolsPath =
confToolsPath ||
process.env.IDF_TOOLS_PATH ||
path.join(containerPath, ".espressif");
let espIdfPath =
confEspIdfPath ||
process.env.IDF_PATH ||
path.join(containerPath, "esp", "esp-idf");
let pyEnvPath = confPyPath || process.env.PYTHON;
const espIdfJsonPath = path.join(toolsPath, "esp_idf.json");
const espIdfJsonExists = await pathExists(espIdfJsonPath);
let gitPath = idfConf.readParameter("idf.gitPath") || "/usr/bin/git";
if (espIdfJsonExists) {
const idfInstalled = await getSelectedIdfInstalled(toolsPath);
if (idfInstalled && idfInstalled.path && idfInstalled.python) {
espIdfPath = idfInstalled.path;
pyEnvPath = idfInstalled.python;
}
const gitPathFromJson = (await getPropertyFromJson(
toolsPath,
"gitPath"
)) as string;
const gitPathExists = await pathExists(gitPathFromJson);
if (gitPathExists) {
gitPath = gitPathFromJson;
}
}
const gitVersion = await utils.checkGitExists(containerPath, gitPath);
let idfPathVersion = await utils.getEspIdfVersion(espIdfPath, gitPath);
if (idfPathVersion === "x.x" && process.platform === "win32") {
espIdfPath = path.join(process.env.USERPROFILE, "Desktop", "esp-idf");
idfPathVersion = await utils.getEspIdfVersion(espIdfPath, gitPath);
}
if (idfPathVersion === "x.x") {
return {
espToolsPath: toolsPath,
espIdfPath: undefined,
espIdfVersion: undefined,
exportedPaths: undefined,
exportedVars: undefined,
espIdfVersionsList: undefined,
gitPath,
gitVersion,
hasPrerequisites: undefined,
pythonVersions,
toolsResults: undefined,
pyBinPath: undefined,
};
}
const idfToolsManager = await IdfToolsManager.createIdfToolsManager(
espIdfPath,
gitPath
);
const exportedToolsPaths = await idfToolsManager.exportPathsInString(
path.join(toolsPath, "tools")
);
const toolsInfo = await idfToolsManager.getRequiredToolsInfo(
path.join(toolsPath, "tools"),
exportedToolsPaths
);
const failedToolsResult = toolsInfo.filter((tInfo) => !tInfo.doesToolExist);
if (failedToolsResult.length > 0) {
return {
espIdfPath,
espIdfVersion: idfPathVersion,
espToolsPath: toolsPath,
exportedPaths: undefined,
exportedVars: undefined,
espIdfVersionsList: undefined,
gitPath,
gitVersion,
hasPrerequisites: undefined,
pythonVersions,
toolsResults: undefined,
pyBinPath: undefined,
};
}
const exportedVars = await idfToolsManager.exportVars(
path.join(toolsPath, "tools")
);
if (!exportedVars) {
return {
espIdfPath,
espIdfVersion: idfPathVersion,
espToolsPath: toolsPath,
exportedPaths: exportedToolsPaths,
toolsResults: toolsInfo,
exportedVars: undefined,
espIdfVersionsList: undefined,
gitPath,
gitVersion,
hasPrerequisites: undefined,
pythonVersions,
pyBinPath: undefined,
};
}
let isPyEnvValid = await checkPyVenv(pyEnvPath, espIdfPath);
if (!isPyEnvValid) {
pyEnvPath = await checkPyVersion(
pythonVersions,
espIdfPath,
toolsPath,
gitPath
);
}
if (!pyEnvPath) {
return {
espIdfPath,
espIdfVersion: idfPathVersion,
espToolsPath: toolsPath,
exportedPaths: exportedToolsPaths,
exportedVars,
toolsResults: toolsInfo,
espIdfVersionsList: undefined,
gitPath,
gitVersion,
hasPrerequisites: undefined,
pythonVersions,
pyBinPath: undefined,
};
}
return {
espIdfPath,
espIdfVersion: idfPathVersion,
espToolsPath: toolsPath,
exportedPaths: exportedToolsPaths,
exportedVars,
pyBinPath: pyEnvPath,
toolsResults: toolsInfo,
espIdfVersionsList: undefined,
gitPath,
gitVersion,
hasPrerequisites: undefined,
pythonVersions,
};
}
export async function checkPyVersion(
pythonVersions: string[],
espIdfPath: string,
toolsDir: string,
gitPath: string
) {
for (const pyVer of pythonVersions) {
const pyExists = await pathExists(pyVer);
if (!pyExists) {
continue;
}
const venvPyFolder = await getPythonEnvPath(
espIdfPath,
toolsDir,
pyVer,
gitPath
);
const pythonInEnv =
process.platform === "win32"
? path.join(venvPyFolder, "Scripts", "python.exe")
: path.join(venvPyFolder, "bin", "python");
const isVenvValid = await checkPyVenv(pythonInEnv, espIdfPath);
if (isVenvValid) {
return pythonInEnv;
}
}
return;
}
export async function checkPyVenv(pyVenvPath: string, espIdfPath: string) {
const pyExists = await pathExists(pyVenvPath);
if (!pyExists) {
return false;
}
const requirements = path.join(espIdfPath, "requirements.txt");
const reqsResults = await utils.startPythonReqsProcess(
pyVenvPath,
espIdfPath,
requirements
);
if (reqsResults.indexOf("are not satisfied") > -1) {
return false;
}
return true;
}
export async function getSetupInitialValues(
extensionPath: string,
progress: Progress<{ message: string; increment: number }>
) {
progress.report({ increment: 20, message: "Getting ESP-IDF versions..." });
const espIdfVersionsList = await getEspIdfVersions(extensionPath);
progress.report({ increment: 20, message: "Getting Python versions..." });
const pythonVersions = await getPythonList(extensionPath);
const setupInitArgs = {
espIdfVersionsList,
pythonVersions,
} as ISetupInitArgs;
try {
progress.report({
increment: 10,
message: "Checking for previous install...",
});
// Get initial paths
const prevInstall = await checkPreviousInstall(pythonVersions);
if (process.platform !== "win32") {
const canAccessCMake = await utils.isBinInPath(
"cmake",
extensionPath,
process.env
);
const canAccessNinja = await utils.isBinInPath(
"ninja",
extensionPath,
process.env
);
setupInitArgs.hasPrerequisites =
prevInstall.gitVersion !== "Not found" &&
canAccessCMake !== "" &&
canAccessNinja !== "" &&
pythonVersions && pythonVersions.length > 0;
} else {
setupInitArgs.hasPrerequisites = prevInstall.gitVersion !== "Not found";
}
progress.report({ increment: 20, message: "Preparing setup view..." });
if (prevInstall) {
setupInitArgs.espIdfPath = prevInstall.espIdfPath;
setupInitArgs.espIdfVersion = prevInstall.espIdfVersion;
setupInitArgs.espToolsPath = prevInstall.espToolsPath;
setupInitArgs.exportedPaths = prevInstall.exportedPaths;
setupInitArgs.exportedVars = prevInstall.exportedVars;
setupInitArgs.gitPath = prevInstall.gitPath;
setupInitArgs.gitVersion = prevInstall.gitVersion;
setupInitArgs.toolsResults = prevInstall.toolsResults;
setupInitArgs.pyBinPath = prevInstall.pyBinPath;
}
} catch (error) {
Logger.error(error.message, error);
}
return setupInitArgs;
}
export async function isCurrentInstallValid() {
const containerPath =
process.platform === "win32" ? process.env.USERPROFILE : process.env.HOME;
const confToolsPath = idfConf.readParameter("idf.toolsPath") as string;
const toolsPath =
confToolsPath ||
process.env.IDF_TOOLS_PATH ||
path.join(containerPath, ".espressif");
const extraPaths = idfConf.readParameter("idf.customExtraPaths") as string;
let espIdfPath = idfConf.readParameter("idf.espIdfPath");
const gitPath = idfConf.readParameter("idf.gitPath") || "git";
let idfPathVersion = await utils.getEspIdfVersion(espIdfPath, gitPath);
if (idfPathVersion === "x.x" && process.platform === "win32") {
espIdfPath = path.join(process.env.USERPROFILE, "Desktop", "esp-idf");
idfPathVersion = await utils.getEspIdfVersion(espIdfPath, gitPath);
}
if (idfPathVersion === "x.x") {
return false;
}
const idfToolsManager = await IdfToolsManager.createIdfToolsManager(
espIdfPath,
gitPath
);
const toolsInfo = await idfToolsManager.getRequiredToolsInfo(
path.join(toolsPath, "tools"),
extraPaths
);
const failedToolsResult = toolsInfo.filter(
(tInfo) =>
tInfo.actual.indexOf("No match") !== -1 ||
tInfo.actual.indexOf("Error") !== -1
);
return failedToolsResult.length === 0;
}
export async function saveSettings(
espIdfPath: string,
pythonBinPath: string,
exportedPaths: string,
exportedVars: string,
toolsPath: string,
gitPath: string
) {
const confTarget = idfConf.readParameter(
"idf.saveScope"
) as ConfigurationTarget;
let workspaceFolder: WorkspaceFolder;
if (confTarget === ConfigurationTarget.WorkspaceFolder) {
workspaceFolder = await window.showWorkspaceFolderPick({
placeHolder: `Pick Workspace Folder to which settings should be applied`,
});
}
await idfConf.writeParameter(
"idf.espIdfPath",
espIdfPath,
confTarget,
workspaceFolder
);
await idfConf.writeParameter(
"idf.pythonBinPath",
pythonBinPath,
confTarget,
workspaceFolder
);
await idfConf.writeParameter(
"idf.toolsPath",
toolsPath,
confTarget,
workspaceFolder
);
await idfConf.writeParameter(
"idf.customExtraPaths",
exportedPaths,
confTarget,
workspaceFolder
);
await idfConf.writeParameter(
"idf.customExtraVars",
exportedVars,
confTarget,
workspaceFolder
);
await idfConf.writeParameter(
"idf.gitPath",
gitPath,
confTarget,
workspaceFolder
);
window.showInformationMessage("ESP-IDF has been configured");
} | the_stack |
* @packageDocumentation
* @module VerificationUtils
*/
import { u8aConcat, hexToU8a, u8aToHex } from '@polkadot/util'
import { signatureVerify, blake2AsHex } from '@polkadot/util-crypto'
import jsonld from 'jsonld'
import { Attestation, CTypeSchema } from '@kiltprotocol/core'
import { Crypto, JsonSchema } from '@kiltprotocol/utils'
import { DocumentLoader } from 'jsonld-signatures'
import { VerificationKeyTypesMap } from '@kiltprotocol/types'
import {
KILT_SELF_SIGNED_PROOF_TYPE,
KILT_ATTESTED_PROOF_TYPE,
KILT_CREDENTIAL_DIGEST_PROOF_TYPE,
} from './constants'
import type {
VerifiableCredential,
SelfSignedProof,
AttestedProof,
CredentialDigestProof,
IPublicKeyRecord,
} from './types'
import { fromCredentialIRI } from './exportToVerifiableCredential'
export interface VerificationResult {
verified: boolean
errors: Error[]
}
export enum AttestationStatus {
valid = 'valid',
invalid = 'invalid',
revoked = 'revoked',
unknown = 'unknown',
}
export interface AttestationVerificationResult extends VerificationResult {
status: AttestationStatus
}
const CREDENTIAL_MALFORMED_ERROR = (reason: string): Error =>
new Error(`Credential malformed: ${reason}`)
const PROOF_MALFORMED_ERROR = (reason: string): Error =>
new Error(`Proof malformed: ${reason}`)
/**
* Verifies a KILT self signed proof (claimer signature) against a KILT style Verifiable Credential.
* This entails computing the root hash from the hashes contained in the `protected` section of the credentialSubject.
* The resulting hash is then verified against the signature and public key contained in the proof (the latter
* could be a DID URI). It is also expected to by identical to the credential id.
*
* @param credential Verifiable Credential to verify proof against.
* @param proof KILT self signed proof object.
* @param documentLoader Must be able to KILT DID fragments (i.e. The key reference).
* @returns Object indicating whether proof could be verified.
*/
export async function verifySelfSignedProof(
credential: VerifiableCredential,
proof: SelfSignedProof,
documentLoader: DocumentLoader
): Promise<VerificationResult> {
const result: VerificationResult = { verified: true, errors: [] }
try {
// check proof
const type = proof['@type'] || proof.type
if (type !== KILT_SELF_SIGNED_PROOF_TYPE)
throw new Error('Proof type mismatch')
if (!proof.signature) throw PROOF_MALFORMED_ERROR('signature missing')
let { verificationMethod } = proof
// we always fetch the verification method to make sure the key is in fact associated with the did
if (typeof verificationMethod !== 'string') {
verificationMethod = verificationMethod.id
}
if (!verificationMethod) {
throw new Error('verificationMethod not understood')
}
const dereferenced = documentLoader
? await documentLoader(verificationMethod)
: undefined
if (!dereferenced?.document) {
throw new Error(
'verificationMethod could not be dereferenced; did you select an appropriate document loader?'
)
}
verificationMethod = dereferenced.document as IPublicKeyRecord
const credentialOwner =
credential.credentialSubject.id || credential.credentialSubject['@id']
if (!verificationMethod.controller === credentialOwner)
throw new Error('credential subject is not owner of signing key')
const keyType = verificationMethod.type || verificationMethod['@type']
if (!Object.values(VerificationKeyTypesMap).includes(keyType))
throw PROOF_MALFORMED_ERROR(
`signature type unknown; expected one of ${JSON.stringify(
Object.values(VerificationKeyTypesMap)
)}, got "${verificationMethod.type}"`
)
const signerPubKey = verificationMethod.publicKeyHex
if (!signerPubKey)
throw new Error('signer key is missing publicKeyHex property')
const rootHash = fromCredentialIRI(credential.id)
// validate signature over root hash
// signatureVerify can handle all required signature types out of the box
const verification = signatureVerify(
rootHash,
proof.signature,
signerPubKey
)
if (
!(
verification.isValid &&
VerificationKeyTypesMap[verification.crypto] === keyType
)
) {
throw new Error('signature could not be verified')
}
return result
} catch (e) {
result.verified = false
result.errors = [e]
return result
}
}
/**
* Verifies a KILT attestation proof by querying data from the KILT blockchain.
* This includes querying the KILT blockchain with the credential id, which returns an attestation record if attested.
* This record is then compared against attester address and delegation id (the latter of which is taken directly from the credential).
*
* @param credential Verifiable Credential to verify proof against.
* @param proof KILT self signed proof object.
* @returns Object indicating whether proof could be verified.
*/
export async function verifyAttestedProof(
credential: VerifiableCredential,
proof: AttestedProof
): Promise<AttestationVerificationResult> {
let status: AttestationStatus = AttestationStatus.unknown
try {
// check proof
const type = proof['@type'] || proof.type
if (type !== KILT_ATTESTED_PROOF_TYPE)
throw new Error('Proof type mismatch')
const { attester } = proof
if (typeof attester !== 'string' || !attester)
throw PROOF_MALFORMED_ERROR('attester DID not understood')
if (attester !== credential.issuer)
throw PROOF_MALFORMED_ERROR('attester DID not matching credential issuer')
if (typeof credential.id !== 'string' || !credential.id)
throw CREDENTIAL_MALFORMED_ERROR(
'claim id (=claim hash) missing / invalid'
)
const claimHash = fromCredentialIRI(credential.id)
let delegationId: string | null
switch (typeof credential.delegationId) {
case 'string':
delegationId = credential.delegationId
break
case 'undefined':
delegationId = null
break
default:
throw CREDENTIAL_MALFORMED_ERROR('delegationId not understood')
}
// query on-chain data by credential id (= claim root hash)
const onChain = await Attestation.query(claimHash)
// if not found, credential has not been attested, proof is invalid
if (!onChain) {
status = AttestationStatus.invalid
throw new Error(
`attestation for credential with id ${claimHash} not found`
)
}
// if data on proof does not correspond to data on chain, proof is incorrect
if (onChain.owner !== attester || onChain.delegationId !== delegationId) {
status = AttestationStatus.invalid
throw new Error(
`proof not matching on-chain data: proof ${{
attester,
delegation: delegationId,
}}`
)
}
// if proof data is valid but attestation is flagged as revoked, credential is no longer valid
if (onChain.revoked) {
status = AttestationStatus.revoked
throw new Error('attestation revoked')
}
} catch (e) {
return {
verified: false,
errors: [e],
status,
}
}
return { verified: true, errors: [], status: AttestationStatus.valid }
}
/**
* Verifies a proof that reveals the content of selected properties to a verifier. This enables selective disclosure.
* Values and nonces contained within this proof will be hashed, the result of which is expected to equal hashes on the credential.
*
* @param credential Verifiable Credential to verify proof against.
* @param proof KILT self signed proof object.
* @param options Allows passing custom hasher.
* @param options.hasher A custom hasher. Defaults to hex(blake2-256('nonce'+'value')).
* @returns Object indicating whether proof could be verified.
*/
export async function verifyCredentialDigestProof(
credential: VerifiableCredential,
proof: CredentialDigestProof,
options: { hasher?: Crypto.Hasher } = {}
): Promise<VerificationResult> {
const {
hasher = (value, nonce?) => blake2AsHex((nonce || '') + value, 256),
} = options
const result: VerificationResult = { verified: true, errors: [] }
try {
// check proof
const type = proof['@type'] || proof.type
if (type !== KILT_CREDENTIAL_DIGEST_PROOF_TYPE)
throw new Error('Proof type mismatch')
if (typeof proof.nonces !== 'object') {
throw PROOF_MALFORMED_ERROR('proof must contain object "nonces"')
}
if (typeof credential.credentialSubject !== 'object')
throw CREDENTIAL_MALFORMED_ERROR('credential subject missing')
// 1: check credential digest against credential contents & claim property hashes in proof
// collect hashes from hash array, legitimations & delegationId
const hashes: string[] = proof.claimHashes.concat(
credential.legitimationIds,
credential.delegationId || []
)
// convert hex hashes to byte arrays & concatenate
const concatenated = u8aConcat(
...hashes.map((hexHash) => hexToU8a(hexHash))
)
const rootHash = Crypto.hash(concatenated)
// throw if root hash does not match expected (=id)
const expectedRootHash = fromCredentialIRI(credential.id)
if (expectedRootHash !== u8aToHex(rootHash))
throw new Error('computed root hash does not match expected')
// 2: check individual properties against claim hashes in proof
// expand credentialSubject keys by compacting with empty context credential to produce statements
const flattened = await jsonld.compact(credential.credentialSubject, {})
const statements = Object.entries(flattened).map(([key, value]) =>
JSON.stringify({ [key]: value })
)
const expectedUnsalted = Object.keys(proof.nonces)
return statements.reduce<VerificationResult>(
(r, stmt) => {
const unsalted = hasher(stmt)
if (!expectedUnsalted.includes(unsalted))
return {
verified: false,
errors: [
...r.errors,
PROOF_MALFORMED_ERROR(
`Proof contains no digest for statement ${stmt}`
),
],
}
const nonce = proof.nonces[unsalted]
if (!proof.claimHashes.includes(hasher(unsalted, nonce)))
return {
verified: false,
errors: [
...r.errors,
new Error(
`Proof for statement ${stmt} not valid against claimHashes`
),
],
}
return r
},
{ verified: true, errors: [] }
)
} catch (e) {
result.verified = false
result.errors = [e]
return result
}
}
export function validateSchema(
credential: VerifiableCredential
): VerificationResult {
const { schema } = credential.credentialSchema || {}
// if present, perform schema validation
if (schema) {
// there's no rule against additional properties, so we can just validate the ones that are there
const validator = new JsonSchema.Validator(schema)
validator.addSchema(CTypeSchema.CTypeModel)
const result = validator.validate(credential.credentialSubject)
return {
verified: result.valid,
errors: result.errors?.map((e) => new Error(e.error)) || [],
}
}
return { verified: false, errors: [] }
} | the_stack |
import { TextRenderer, CellRenderer, GraphicsContext } from '@lumino/datagrid';
import { ViewBasedJSONModel } from './viewbasedjsonmodel';
import { Theme } from '../utils';
import { TransformStateManager } from './transformStateManager';
import { DataGrid } from '@lumino/datagrid';
/**
* A custom cell renderer for headers that provides a menu icon.
*/
export class HeaderRenderer extends TextRenderer {
constructor(options: HeaderRenderer.IOptions) {
super(options.textOptions);
this._isLightTheme = options.isLightTheme;
this._grid = options.grid;
}
/**
* Model getter.
*/
get model(): ViewBasedJSONModel {
return this._grid.dataModel as ViewBasedJSONModel;
}
/**
* Draw the text for the cell.
*
* @param gc - The graphics context to use for drawing.
*
* @param config - The configuration data for the cell.
*/
drawText(gc: GraphicsContext, config: CellRenderer.CellConfig): void {
// Resolve the font for the cell.
const font = CellRenderer.resolveOption(this.font, config);
// Bail if there is no font to draw.
if (!font) {
return;
}
// Resolve the text color for the cell.
const color = CellRenderer.resolveOption(this.textColor, config);
// Bail if there is no text color to draw.
if (!color) {
return;
}
// Format the cell value to text.
const format = this.format;
let text = format(config);
// Bail if there is no text to draw.
if (!text) {
return;
}
// Resolve the vertical and horizontal alignment.
const vAlign = CellRenderer.resolveOption(this.verticalAlignment, config);
const hAlign = CellRenderer.resolveOption(this.horizontalAlignment, config);
// Resolve the elision direction
const elideDirection = CellRenderer.resolveOption(
this.elideDirection,
config,
);
// Resolve the text wrapping flag
const wrapText = CellRenderer.resolveOption(this.wrapText, config);
// Compute the padded text box height for the specified alignment.
const boxHeight = config.height - (vAlign === 'center' ? 1 : 2);
// Bail if the text box has no effective size.
if (boxHeight <= 0) {
return;
}
// Compute the text height for the gc font.
const textHeight = TextRenderer.measureFontHeight(font);
// Set up the text position variables.
let textX: number;
let textY: number;
let boxWidth: number;
// Compute the Y position for the text.
switch (vAlign) {
case 'top':
textY = config.y + 2 + textHeight;
break;
case 'center':
textY = config.y + config.height / 2 + textHeight / 2;
break;
case 'bottom':
textY = config.y + config.height - 2;
break;
default:
throw 'unreachable';
}
// Compute the X position for the text.
switch (hAlign) {
case 'left':
textX = config.x + 8;
boxWidth = config.width - 14;
break;
case 'center':
textX = config.x + config.width / 2;
boxWidth = config.width;
break;
case 'right':
textX = config.x + config.width - 8;
boxWidth = config.width - 14;
break;
default:
throw 'unreachable';
}
// Clip the cell if the text is taller than the text box height.
if (textHeight > boxHeight) {
gc.beginPath();
gc.rect(config.x, config.y, config.width, config.height - 1);
gc.clip();
}
// Set the gc state.
gc.font = font;
gc.fillStyle = color;
gc.textAlign = hAlign;
gc.textBaseline = 'bottom';
// The current text width in pixels.
let textWidth = gc.measureText(text).width;
// Apply text wrapping if enabled.
if (wrapText && textWidth > boxWidth) {
// Make sure box clipping happens.
gc.beginPath();
gc.rect(config.x, config.y, config.width, config.height - 1);
gc.clip();
// Split column name to words based on
// whitespace preceding a word boundary.
// "Hello world" --> ["Hello ", "world"]
const wordsInColumn = text.split(/\s(?=\b)/);
// Y-coordinate offset for any additional lines
let curY = textY;
let textInCurrentLine = wordsInColumn.shift()!;
// Single word. Applying text wrap on word by splitting
// it into characters and fitting the maximum number of
// characters possible per line (box width).
if (wordsInColumn.length === 0) {
let curLineTextWidth = gc.measureText(textInCurrentLine).width;
while (curLineTextWidth > boxWidth && textInCurrentLine !== '') {
// Iterating from the end of the string until we find a
// substring (0,i) which has a width less than the box width.
for (let i = textInCurrentLine.length; i > 0; i--) {
const curSubString = textInCurrentLine.substring(0, i);
const curSubStringWidth = gc.measureText(curSubString).width;
if (curSubStringWidth < boxWidth || curSubString.length === 1) {
// Found a substring which has a width less than the current
// box width. Rendering that substring on the current line
// and setting the remainder of the parent string as the next
// string to iterate on for the next line.
const nextLineText = textInCurrentLine.substring(
i,
textInCurrentLine.length,
);
textInCurrentLine = nextLineText;
curLineTextWidth = gc.measureText(textInCurrentLine).width;
gc.fillText(curSubString, textX, curY);
curY += textHeight;
// No need to continue iterating after we identified
// an index to break the string on.
break;
}
}
}
}
// Multiple words in column header. Fitting maximum
// number of words possible per line (box width).
else {
while (wordsInColumn.length !== 0) {
// Processing the next word in the queue.
const curWord = wordsInColumn.shift();
// Joining that word with the existing text for
// the current line.
const incrementedText = [textInCurrentLine, curWord].join(' ');
const incrementedTextWidth = gc.measureText(incrementedText).width;
if (incrementedTextWidth > boxWidth) {
// If the newly combined text has a width larger than
// the box width, we render the line before the current
// word was added. We set the current word as the next
// line.
gc.fillText(textInCurrentLine, textX, curY);
curY += textHeight;
textInCurrentLine = curWord!;
} else {
// The combined text hasd a width less than the box width. We
// set the the current line text to be the new combined text.
textInCurrentLine = incrementedText;
}
}
}
gc.fillText(textInCurrentLine!, textX, curY);
// Terminating the call here as we don't want
// to apply text eliding when wrapping is active.
return;
}
// Elide text that is too long
const elide = '\u2026';
// Compute elided text
if (elideDirection === 'right') {
while (textWidth > boxWidth && text.length > 1) {
if (text.length > 4 && textWidth >= 2 * boxWidth) {
// If text width is substantially bigger, take half the string
text = text.substring(0, text.length / 2 + 1) + elide;
} else {
// Otherwise incrementally remove the last character
text = text.substring(0, text.length - 2) + elide;
}
textWidth = gc.measureText(text).width;
}
} else {
while (textWidth > boxWidth && text.length > 1) {
if (text.length > 4 && textWidth >= 2 * boxWidth) {
// If text width is substantially bigger, take half the string
text = elide + text.substring(text.length / 2);
} else {
// Otherwise incrementally remove the last character
text = elide + text.substring(2);
}
textWidth = gc.measureText(text).width;
}
}
// Draw the text for the cell.
gc.fillText(text, textX, textY);
// Check if not bottom row of 'column-header' CellRegion
if (
config.region === 'column-header' &&
config.row !== this._grid.dataModel!.rowCount('column-header') - 1
) {
return;
}
// Fill the area behind the menu icon
// Note: This seems to perform better than adding a clip path
const backgroundSize =
HeaderRenderer.iconWidth +
HeaderRenderer.iconWidth +
HeaderRenderer.iconSpacing +
2 * HeaderRenderer.buttonPadding;
gc.fillStyle = CellRenderer.resolveOption(this.backgroundColor, config);
gc.fillRect(
config.x + config.width - backgroundSize,
config.y + config.height - backgroundSize,
backgroundSize,
backgroundSize,
);
const iconStart =
config.x +
config.width -
HeaderRenderer.iconWidth -
HeaderRenderer.buttonPadding;
// Draw filter icon
this.drawFilterIcon(gc, config);
// Sets filter icon to gray fill
gc.fillStyle = Theme.getBorderColor(1);
gc.fill();
// Check for transform metadata
if (this.model) {
// Get cell metadata
const schemaIndex = this.model.getSchemaIndex(
config.region,
config.column,
);
const colMetaData: TransformStateManager.IColumn | undefined =
this.model.transformMetadata(schemaIndex);
// Fill filter icon if filter applied
if (colMetaData && colMetaData['filter']) {
gc.fillStyle = Theme.getBrandColor(this._isLightTheme ? 8 : 6);
gc.fill();
}
// Fill sort icon if sort applied
if (colMetaData && colMetaData['sort']) {
// Display ascending or descending icon depending on order
if (colMetaData['sort'].desc) {
this.drawSortArrow(gc, config, iconStart, false);
} else {
this.drawSortArrow(gc, config, iconStart, true);
}
gc.fillStyle = Theme.getBrandColor(this._isLightTheme ? 7 : 5);
gc.fill();
}
}
}
/**
* Draw the filter icon for the cell
*
* @param gc - The graphics context to use for drawing.
*
* @param config - The configuration data for the cell.
*/
drawFilterIcon(gc: GraphicsContext, config: CellRenderer.CellConfig): void {
const filterIconStart =
config.x +
config.width -
HeaderRenderer.iconWidth -
HeaderRenderer.buttonPadding;
const filterRightStemWidthX: number = HeaderRenderer.iconWidth / 2 + 1;
const filterLeftStemWidthX: number = HeaderRenderer.iconWidth / 2 - 1;
const filterTop: number =
config.height - HeaderRenderer.iconHeight - 1 + config.y;
gc.beginPath();
// Start drawing in top left of filter icon
gc.moveTo(filterIconStart, filterTop);
gc.lineTo(filterIconStart + HeaderRenderer.iconWidth, filterTop);
// Y is the y value of the top of the stem
gc.lineTo(
filterIconStart + filterRightStemWidthX,
config.y + config.height - HeaderRenderer.iconHeight + 2,
);
// Y is the y value of the bottom of the stem
gc.lineTo(
filterIconStart + filterRightStemWidthX,
config.y + config.height - 1.5 * HeaderRenderer.buttonPadding,
);
gc.lineTo(
filterIconStart + filterLeftStemWidthX,
config.y + config.height - 2 * HeaderRenderer.buttonPadding,
);
gc.lineTo(
filterIconStart + filterLeftStemWidthX,
config.y + config.height - HeaderRenderer.iconHeight + 2,
);
gc.closePath();
}
/**
* Draw the ascending and descending sort icons for the cell
*
* @param gc - The graphics context to use for drawing.
*
* @param config - The configuration data for the cell.
*
* @param filterIconStart - The bottom right corner of drawing area.
*
* @param asc - Indicates whether to draw ascending or descending icon.
*/
drawSortArrow(
gc: GraphicsContext,
config: CellRenderer.CellConfig,
filterIconStart: number,
asc: boolean,
): void {
const arrowWidth = HeaderRenderer.iconWidth - 2;
const sortIconStart = filterIconStart - HeaderRenderer.iconSpacing;
const ascArrowRightStemWidth: number = sortIconStart - arrowWidth / 2 + 0.5;
const descArrowRightStemWidth: number =
sortIconStart - arrowWidth / 2 - 0.5;
const arrowHeadSideY: number =
config.height +
config.y -
HeaderRenderer.buttonPadding -
HeaderRenderer.iconHeight +
4;
const arrowMiddle: number = sortIconStart - arrowWidth / 2;
const ascArrowTipY: number =
config.height + config.y - HeaderRenderer.iconHeight - 1;
const ascArrowBottomY: number =
config.height - 8 + config.y + HeaderRenderer.buttonPadding;
gc.beginPath();
if (asc) {
// Draw starting in middle of arrow
// Y is the tip of the ascending arrow
gc.moveTo(arrowMiddle, ascArrowTipY);
gc.lineTo(sortIconStart, arrowHeadSideY);
gc.lineTo(sortIconStart, arrowHeadSideY + 1);
// Draw to middle of arrow
gc.lineTo(ascArrowRightStemWidth, arrowHeadSideY + 1);
// Y is the bottom of the arrow stem
gc.lineTo(arrowMiddle + 0.5, ascArrowBottomY);
gc.lineTo(arrowMiddle - 0.5, ascArrowBottomY);
gc.lineTo(arrowMiddle - 0.5, arrowHeadSideY + 1);
gc.lineTo(sortIconStart - arrowWidth, arrowHeadSideY + 1);
gc.lineTo(sortIconStart - arrowWidth, arrowHeadSideY);
} else {
// Draw starting in middle of arrow
// Y is the tip of the descending arrow
gc.moveTo(arrowMiddle, ascArrowBottomY);
gc.lineTo(sortIconStart - arrowWidth, arrowHeadSideY + 4.5);
gc.lineTo(sortIconStart - arrowWidth, arrowHeadSideY + 3.5);
// Draw to middle of arrow
gc.lineTo(descArrowRightStemWidth, arrowHeadSideY + 3.5);
// Y is the bottom of the arrow stem
gc.lineTo(descArrowRightStemWidth, ascArrowTipY);
gc.lineTo(arrowMiddle + 0.5, ascArrowTipY);
// Draw left side of descending arrow
gc.lineTo(arrowMiddle + 0.5, arrowHeadSideY + 3.5);
gc.lineTo(sortIconStart, arrowHeadSideY + 3.5);
gc.lineTo(sortIconStart, arrowHeadSideY + 4.5);
}
gc.closePath();
}
/**
* Indicates the size of the menu icon, to support the current implementation
* of hit testing.
*/
static buttonSize = 11;
static iconHeight = 12;
static iconWidth = 7;
static buttonPadding = 3;
static iconSpacing = 1.5;
private _isLightTheme: boolean;
private _grid: DataGrid;
}
/**
* The namespace for the `HeaderRenderer` class statics.
*/
export namespace HeaderRenderer {
/**
* An options object for initializing a renderer.
*/
export interface IOptions {
/**
* The data model this renderer should get metadata from.
*/
textOptions: TextRenderer.IOptions;
isLightTheme: boolean;
grid: DataGrid;
}
} | the_stack |
import * as Configuration from "./Configuration";
import * as DataFormat from "./DataFormat";
import * as IC from "./ICProcess";
import * as Streams from "./Streams";
import * as StringEncoding from "./StringEncoding";
import * as Root from "./AmbrosiaRoot";
import * as Utils from "./Utils/Utils-Index";
import Path = require("path");
import File = require("fs");
const RESERVED_0: Uint8Array = new Uint8Array([0]);
export const EMPTY_BYTE_ARRAY: Uint8Array = new Uint8Array(0);
let _isRecoveryRunning: boolean = false;
let _bytePool: DataFormat.BytePool; // Used to speed-up makeRpcMessage() [for messages that are under 33% of the pool size]
let _completeLiveUpgradeAtNextTakeCheckpoint: boolean = false;
/** Whether recovery (replay) is currently running. */
export function isRecoveryRunning(): boolean
{
return (_isRecoveryRunning);
}
/** Type of a handler for [dispatchable] messages. */
export type MessageDispatcher = (message: DispatchedMessage) => void;
/**
* Type of a handler for the results of all post method calls.\
* Must return true only if the result (or error) was handled.
*
* **WARNING:** To ensure replay integrity, a PostResultDispatcher should only use state that comes from one or more of these sources:
* 1) Checkpointed application state.
* 2) Post method arguments.
* 3) Runtime state that is repeatably deterministic, ie. that will be identical during both real-time and replay.
* This includes program state that is [re]computed from checkpointed application state.
*/
export type PostResultDispatcher = (senderInstanceName: string, methodName: string, methodVersion: number, callID: number, callContextData: any, result: any, errorMsg: string) => boolean;
/** The sub-type of an RPC message. */
export enum RPCType
{
// Note: The JS LB does not support RPCType 0 (Async) like the C# LB does, because it requires C#-specific compiler features.
// Instead, the JS LB supports 'post' (which is built on Fork) to enable receiving method return values.
/**
* A deterministic RPC. Replayed [by the IC] during recovery. Unlike a Impulse message, a Fork message must **only** ever
* be created by a deterministic event during real-time, so that it will always be re-created during recovery.
*/
Fork = 1,
/**
* A non-deterministic RPC (eg. arising from user input). Replayed [by the IC] during recovery, but only if logged.
* Unlike a Fork message, an Impulse message must **only** ever be created by a non-deterministic event during
* real-time; it must never be re-created during recovery, and it is invalid to attempt to do so. An Impulse
* is essentially a non-deterministic trigger for a deterministic chain of messages (Forks).
*/
Impulse = 2
}
/**
* The types of messages that can be sent to and received from the IC.\
* Note: It is unknown (and immaterial) to the LB as to whether it is running in an active/active configuration.
* When running standalone (ie. non-active/active) it will still become the "primary".
*/
export enum MessageType
{
/** A method call. Sent and received. */
RPC = 0,
/** Requests the IC to connect to a remote (non-self) destination instance. Sent only. */
AttachTo = 1,
/** A request to produce/send a checkpoint. Sent and Received. Has no data. */
TakeCheckpoint = 2,
/** A batch of RPC's. Sent and received. */
RPCBatch = 5,
/** A checkpoint of application state. Sent and received. */
Checkpoint = 8,
/** The first message when an application starts for the first time (ie. before there are any logs to recover from). Sent and received. */
InitialMessage = 9,
/**
* A request to perform an code/state upgrade (live), and become the primary. "Live" upgrade is typically only used in an
* active/active configuration, but it can be used for a standalone instance too. Received only. Has no data.
*/
UpgradeTakeCheckpoint = 10,
/** Received when the IC has become the primary [in an active/active configuration] and **should** take a checkpoint. Received only. Has no data. */
TakeBecomingPrimaryCheckpoint = 11,
/** A request to perform a "what-if" code/state upgrade (test). Received only. Has no data. */
UpgradeService = 12,
/** A batch of RPC's that also includes a count of the replayable (ie. Fork) messages in the batch. Received only. */
CountReplayableRPCBatchByte = 13,
/** Received when the IC has become the primary [in an active/active configuration] but **should not** take a checkpoint. Received only. Has no data. */
BecomingPrimary = 15
}
/** The MessageType's (plus AppEvent) that can be passed to the app's MessageDispatcher (AmbrosiaConfig.dispatcher). */
export enum DispatchedMessageType
{
/** A method call. */
RPC = MessageType.RPC,
/** Note: This is an LB-generated message used for notifying the app of an event (see AppEventType). It is NOT an IC-generated message. */
AppEvent = 256 // Deliberately outside the range of a byte to avoid any possibility of conflicting with a real IC MessageType
}
/** Events (conditions and state-changes) that can be signalled to the app via it's MessageDispatcher (AmbrosiaConfig.dispatcher). */
// Note: There is no 'CheckpointSent' or 'CheckpointReceived' event, even though it would seem natural for there to be such events.
// But because the responsibility for providing the CheckpointProducer and CheckpointConsumer methods lies with the developer
// (via the AmbrosiaConfig parameter of IC.start()), these [logical] events are handled via the 'onFinished' callback of the
// OutgoingCheckpoint and IncomingCheckpoint objects (returned by CheckpointProducer/CheckpointConsumer).
export enum AppEventType
{
/**
* Signals that the Immortal Coordinator (IC) is starting up.\
* Note: Only raised when icHostingMode is 'Integrated'.
*/
ICStarting = 1,
/**
* Signals that the Immortal Coordinator (IC) has started (although the LB is not yet connected to it).
* However, "normal" app processing should NOT begin until the 'BecomingPrimary' event is received.\
* Note: Only raised when icHostingMode is 'Integrated'.
*/
ICStarted = 2,
/** Signals that the Language Binding (LB) has not yet successfully connected to the Immortal Coordinator (IC). */
WaitingToConnectToIC = 3,
/** Signals that the Language Binding (LB) has successfully connected to the Immortal Coordinator (IC). */
ICConnected = 4,
/**
* Signals that the Immortal Coordinator (IC) has stopped. The first (and only) parameter of this event is the exit code.\
* If the IC does not stop within 500ms of being requested to stop [using IC.stop()] then the exit code will be 101.\
* Note: Only raised when icHostingMode is 'Integrated'.
*/
ICStopped = 5,
/**
* Signals that the IC is now capable of handling (ie. immediately responding to) self-call RPCs.\
* Note: Only raised when icHostingMode is 'Integrated'.
*/
ICReadyForSelfCallRpc = 6,
/**
* Signals that the replay phase of recovery has completed.\
* This event will **not** be signalled in the "first-start" case.
*/
RecoveryComplete = 7,
/**
* Signals that the app should immediately upgrade its state. The handler for this event must not return until
* the app state has been upgraded. The first (and only) parameter of this event is an AppUpgradeMode enum value.
*
* Upgrading is performed by calling _appState.upgrade(), for example:\
* _appState = _appState.upgrade<AppStateVNext>(AppStateVNext);
*/
UpgradeState = 8,
/**
* Signals that the app should immediately upgrade its code. The handler for this event must not return until
* the app code has been upgraded. The first (and only) parameter of this event is an AppUpgradeMode enum value.
*
* Upgrading is performed by calling IC.upgrade() passing the new handlers from the "upgraded" PublisherFramework.g.ts,
* which must be included in your app (alongside the original PublisherFramework.g.ts).
*/
UpgradeCode = 9,
/** Notification of the size (in bytes) of the checkpoint that is about to start being streamed to AmbrosiaConfig.checkpointConsumer. */
IncomingCheckpointStreamSize = 10,
/** Signals that the 'InitialMessage' has been received. */
FirstStart = 11,
/**
* Signals that this immortal instance is now the Primary so the app's normal processing can begin (mainly receiving/sending RPC messages).\
* Note: Becoming the Primary can happen when the instance is running either standalone or in active/active.
*/
BecomingPrimary = 12,
/**
* Signals that a checkpoint of application state has been successfully loaded (received) from the Immortal Coordinator (IC).
* Raised after the onFinished() callback of the Streams.IncomingCheckpoint object has been called.\
* This event includes a checkpointSizeInBytes parameter.
*/
CheckpointLoaded = 13,
/**
* Signals that a checkpoint of application state has been successfully saved (sent) to the Immortal Coordinator (IC).
* Raised after the onFinished() callback of the Streams.OutgoingCheckpoint object has been called.
*/
CheckpointSaved = 14,
/**
* Signals that a "live" upgrade has completed successfully.\
* This event will **not** be raised when doing a "test" upgrade.
*/
UpgradeComplete = 15
}
/** The kind of app/service upgrade to perform. */
export enum AppUpgradeMode
{
/**
* Perform a "what-if" test. This allows messages to be replayed against a test instance of an upgraded app/service to
* verify if the changes cause bugs. This helps catch regressions in the changes before actually upgrading the live
* app/service.\
* Logs ands checkpoints are only read (never written) in this mode, so it's fully repeatable. Note also that recovery
* will never reach completion in this mode.
*/
Test = 0,
/**
* Performs a upgrade of a "live" (running in production) app/service. Will result in a new checkpoint being taken and
* normal processing (after the upgrade).
*/
Live = 1
}
// These are frequently used, so we don't want to repeatedly create them
const RPC_TYPE_FORK: Uint8Array = new Uint8Array([RPCType.Fork]);
const RPC_TYPE_IMPULSE: Uint8Array = new Uint8Array([RPCType.Impulse]);
const MESSAGE_TYPE_BYTE_RPC = new Uint8Array([MessageType.RPC]);
const MESSAGE_TYPE_BYTE_RPCBATCH = new Uint8Array([MessageType.RPCBatch]);
const MESSAGE_TYPE_BYTE_INITIALMESSAGE = new Uint8Array([MessageType.InitialMessage]);
const MESSAGE_TYPE_BYTE_CHECKPOINT = new Uint8Array([MessageType.Checkpoint]);
const MESSAGE_TYPE_BYTE_ATTACHTO = new Uint8Array([MessageType.AttachTo]);
const MESSAGE_TYPE_BYTE_TAKECHECKPOINT = new Uint8Array([MessageType.TakeCheckpoint]);
/** Class representing the meta-data for a message. */
class MessageMetaData
{
/** The length of the message, excluding the size bytes. */
size: number;
/** The type of the message (eg. RPC). */
messageType: MessageType;
/** The length of the data portion of the message. */
dataLength: number;
/** The start position (byte index) of the message within the receiveBuffer. */
startOfMessageIndex: number;
/** The [non-inclusive] end position (byte index) of the message within the receiveBuffer. This is the same as the start index of the next message [if any] in the receiveBuffer. */
endOfMessageIndex: number;
/** The length of the message, including the size bytes. */
totalLength: number;
/** The start position (byte index) of the data portion of the message within the receiveBuffer. */
startOfDataIndex: number;
constructor(receiveBuffer: Buffer, startIndex: number)
{
let pos: number = startIndex;
let sizeVarInt: DataFormat.varIntResult = DataFormat.readVarInt32(receiveBuffer, pos);
this.startOfMessageIndex = startIndex;
this.size = sizeVarInt.value;
this.totalLength = sizeVarInt.length + this.size;
this.endOfMessageIndex = startIndex + this.totalLength; // This is the non-inclusive end-index (ie. it's the start of the next message [if any])
this.dataLength = this.size - 1; // -1 for MessageType
pos += sizeVarInt.length;
this.messageType = receiveBuffer[pos++];
this.startOfDataIndex = pos;
}
}
/**
* Initializes the message byte pool (used for optimizing message construction). The supplied 'sizeInMB' must be between 2 and 256.\
* Returns true if the byte pool was initialized, or false if it's already been initialized.
*/
export function initializeBytePool(sizeInMB: number = 2): boolean
{
if (!_bytePool)
{
sizeInMB = Math.min(Math.max(sizeInMB, 2), 256);
_bytePool = new DataFormat.BytePool(sizeInMB * 1024 * 1024);
return (true);
}
return (false);
}
/** Class representing a received message which can be passed to the app's MessageDispatcher (AmbrosiaConfig.dispatcher). */
export class DispatchedMessage
{
receivedTime: number;
type: DispatchedMessageType;
constructor(type: DispatchedMessageType)
{
this.receivedTime = Date.now();
this.type = type;
}
}
/** Class representing an Ambrosia application event which can be passed to the app's MessageDispatcher (AmbrosiaConfig.dispatcher). */
export class AppEvent extends DispatchedMessage
{
eventType: AppEventType;
args: any[] = [];
constructor(eventType: AppEventType, ...args: any[])
{
super(DispatchedMessageType.AppEvent);
this.eventType = eventType;
this.args = args;
}
}
/** Class representing a received RPC message. */
export class IncomingRPC extends DispatchedMessage
{
private _methodID: number;
private _rpcType: RPCType;
private _jsonParams: Utils.SimpleObject | null = null; // Will be null when rawParams is set
private _rawParams: Uint8Array | null = null; // Will be null when jsonParams is set; this is used for all serialization formats other than JSON
private _jsonParamNames: string[] = []; // Cached for lookup performance
/** The unique ID of the method [being called by the RPC]. */
get methodID(): number { return (this._methodID); }
/** The type (Fork or Impulse) of the method [being called by the RPC]. */
get rpcType(): RPCType { return (this._rpcType); }
/**
* The names of all the JSON parameters (if any) sent with the RPC.
*
* Note that method parameters (as opposed to internal parameters) begin with Poster.METHOD_PARAMETER_PREFIX.
*/
get jsonParamNames(): string[] { return (this._jsonParamNames); }
constructor(receiveBuffer: Buffer, dataStartIndex: number, dataEndIndex: number)
{
super(DispatchedMessageType.RPC);
let pos: number = dataStartIndex;
pos++; // Skip over reserved byte
let methodIDVarInt: DataFormat.varIntResult = DataFormat.readVarInt32(receiveBuffer, pos);
this._methodID = methodIDVarInt.value
pos += methodIDVarInt.length;
this._rpcType = receiveBuffer[pos++];
// Parse the serialized parameters, which can either be a UTF-8 JSON string, or a raw byte array (for all other serialization formats)
if (pos < dataEndIndex)
{
const isRaw: boolean = (receiveBuffer[pos] !== 123); // 123 = '{'
if (isRaw)
{
// Note: We throw away the first byte, since the "protocol" for raw-format is that the first byte can be any value EXCEPT 123 (0x7B) and will be stripped
let startIndex: number = pos + 1;
this._rawParams = new Uint8Array(dataEndIndex - startIndex);
receiveBuffer.copy(this._rawParams, 0, startIndex, dataEndIndex); // We want to make a copy
}
else
{
const jsonString: string = StringEncoding.fromUTF8Bytes(receiveBuffer, pos, dataEndIndex - pos).trim();
this._jsonParams = Utils.jsonParse(jsonString);
if (this._jsonParams)
{
this._jsonParamNames = Object.keys(this._jsonParams);
}
}
}
}
/** Returns the raw (byte) parameters of the RPC, or throws if there are no raw parameters. */
getRawParams(): Uint8Array
{
if (this._rawParams)
{
return (this._rawParams);
}
else
{
throw new Error(`There are no rawParams for this RPC (methodID ${this._methodID})${this._jsonParams ? `, but there are jsonParams ("${this._jsonParamNames.join(", ")}")` : ""}`);
}
}
/**
* Returns the value of the specified JSON parameter of the RPC, which may be _undefined_ if the requested 'paramName' isn't present.\
* Throws if JSON parameters were not sent with the RPC.
*
* Note that method parameters (as opposed to internal parameters) begin with Poster.METHOD_PARAMETER_PREFIX.
*/
getJsonParam(paramName: string): any
{
if (this._jsonParams)
{
return (this._jsonParams[paramName]);
}
else
{
throw new Error(`There are no jsonParams for this RPC (methodID ${this._methodID})${this._rawParams ? `, but there are rawParams (${this._rawParams.length} bytes)` : ""}`);
}
}
/** Returns true if the RPC has a JSON parameter of the specified name. */
hasJsonParam(paramName: string): boolean
{
return (this._jsonParamNames.indexOf(paramName) !== -1);
}
makeDisplayParams(): string
{
let allowed: boolean = Configuration.loadedConfig().lbOptions.allowDisplayOfRpcParams;
let params: string = "";
if (allowed === true)
{
if (this._jsonParams) { params = Utils.jsonStringify(this._jsonParams); }
if (this._rawParams) { params = `(${this._rawParams.length} bytes) ${Utils.makeDisplayBytes(this._rawParams)}`; }
}
else
{
params = `[Unavailable: The 'lbOptions.allowDisplayOfRpcParams' setting is ${allowed}]`;
}
return (params);
}
}
function makeMessage(type: Uint8Array, ...sections: Uint8Array[]): Uint8Array
{
let dataLength: number = 0;
for (let i = 0; i < sections.length; i++)
{
dataLength += sections[i].length;
}
let messageSize: Uint8Array = DataFormat.writeVarInt32(type.length + dataLength);
let totalLength: number = messageSize.length + type.length + dataLength;
let message: Uint8Array = Buffer.concat([messageSize, type, ...sections], totalLength);
return (message);
}
/** [Internal] Constructs the wire-format (binary) representation of an RPC message. */
export function makeRpcMessage(rpcType: RPCType, destinationInstance: string, methodID: number, jsonOrRawArgs: Utils.SimpleObject | Uint8Array): Uint8Array
{
if ((rpcType === RPCType.Impulse) && (_isRecoveryRunning || !IC.isPrimary()))
{
const methodIdentity: string = (methodID === IC.POST_METHOD_ID) && !(jsonOrRawArgs instanceof Uint8Array) ? `methodName: ${jsonOrRawArgs["methodName"]}` : `methodID: ${methodID}`;
const whenCondition: string = _isRecoveryRunning ? "during recovery" : "before the local IC has become the Primary";
throw new Error(`It is a violation of the recovery protocol to send an Impulse RPC ${whenCondition} (destination: '${destinationInstance}', ${methodIdentity})`);
}
let isSelfCall: boolean = IC.isSelf(destinationInstance);
let destination: Uint8Array = isSelfCall ? EMPTY_BYTE_ARRAY : StringEncoding.toUTF8Bytes(destinationInstance);
let rpcTypeByte: Uint8Array;
let messageSize: number = 0; // Just used to track progress as we add bytes to the message
let maxArgsSize: number = _bytePool.size / 3; // ie. enough room for 2 messages
let canOptimize: boolean = (jsonOrRawArgs instanceof Uint8Array) ? (jsonOrRawArgs.length < maxArgsSize) : true; // For jsonArgs we had to postpone computing the length (for perf. reasons)
let jsonArgs: Uint8Array | null = null;
// If needed, prepare the IC to talk to the destination; when the IC receives this message it adds
// some rows to the CRA connection table (in Azure) which causes the TCP connections to be made.
// Note that 'destinationInstance' MUST have been previously registered; if not, the IC will
// report "Error attaching [localInstance] to [destinationInstance]".
if (!isSelfCall && IC.isNewDestination(destinationInstance))
{
// Note: Even if the caller of makeRpcMessage() decides not to send the returned RPC message,
// the ATTACHTO message below will still have been sent (ie. this is a true side-effect).
// Note: By setting 'immediateFlush' to true when we send we are attempting to limit the [performance] damage caused by "polluting"
// the queue with a non-RPC message [queued messages can only be sent as an RPCBatch if they are all RPC messages].
// If the queue is empty there will be no damage: the ATTACHTO to will simply be sent as a singleton.
// If the queue already has RPC's in it [for a different destination instance] then those messages will not be able to be
// sent as an RPCBatch, but at least all the RPC's added afterwards [for the new ATTACHTO destination] will be able to.
let attachToMessage: Uint8Array = makeMessage(MESSAGE_TYPE_BYTE_ATTACHTO, destination);
IC.sendMessage(attachToMessage, MessageType.AttachTo, destinationInstance, true);
}
if (_isRecoveryRunning)
{
if (rpcType === RPCType.Fork)
{
IC._counters.sentForkMessageCount++;
}
if (!isSelfCall)
{
IC._counters.remoteSentMessageCount++;
}
}
switch (rpcType)
{
case RPCType.Fork:
rpcTypeByte = RPC_TYPE_FORK;
break;
case RPCType.Impulse:
rpcTypeByte = RPC_TYPE_IMPULSE;
break;
default:
throw new Error(`Unsupported rpcType '${rpcType}'`);
}
if (canOptimize)
{
_bytePool.startBlock();
messageSize += _bytePool.addBuffer(MESSAGE_TYPE_BYTE_RPC);
messageSize += isSelfCall ? _bytePool.addBytes([0]) : _bytePool.addVarInt32(destinationInstance.length);
messageSize += isSelfCall ? 0 : _bytePool.addBuffer(destination);
messageSize += _bytePool.addBuffer(RESERVED_0);
messageSize += _bytePool.addVarInt32(methodID);
messageSize += _bytePool.addBuffer(rpcTypeByte);
if (jsonOrRawArgs instanceof Uint8Array)
{
messageSize += _bytePool.addBytes([255]); // The only requirement here is that this byte NOT be 123; it will be stripped when parsing (see IncomingRPC constructor)
messageSize += _bytePool.addBuffer(jsonOrRawArgs);
}
else
{
if (jsonOrRawArgs)
{
// Yes, this is a whacky way to do this, but - on V8 - it's significantly slower to call the next line any place but here
const encodedJsonArgs: Uint8Array = StringEncoding.toUTF8Bytes(Utils.jsonStringify(jsonOrRawArgs));
if (encodedJsonArgs.length < maxArgsSize)
{
messageSize += _bytePool.addBuffer(encodedJsonArgs);
}
else
{
canOptimize = false;
jsonArgs = encodedJsonArgs;
_bytePool.cancelBlock();
}
}
}
if (canOptimize) // See earlier whackiness
{
let messageBody: Uint8Array = _bytePool.endBlock(false); // We only need a [fast] temp-copy because we're going to immediately use it in a [slow] full-copy
_bytePool.startBlock();
_bytePool.addVarInt32(messageBody.length); // Should match messageSize
_bytePool.addBuffer(messageBody);
let message: Uint8Array = _bytePool.endBlock();
return (message);
}
}
if (!canOptimize)
{
// We can't optimize, so fall-back to not using the _bytePool
let rawArgs: Uint8Array | null = (jsonOrRawArgs instanceof Uint8Array) ? jsonOrRawArgs : null;
let destinationLength: Uint8Array = isSelfCall ? RESERVED_0 : DataFormat.writeVarInt32(destinationInstance.length);
let rpcBody: Uint8Array = makeRpcBody(methodID, rpcTypeByte, jsonArgs, rawArgs);
let message: Uint8Array = makeMessage(MESSAGE_TYPE_BYTE_RPC, destinationLength, destination, rpcBody);
return (message);
}
throw new Error("makeRpcMessage() did not return an RPC; this is an internal coding error");
}
function makeRpcBody(methodID: number, rpcType: Uint8Array, jsonArgs: Uint8Array | null, rawArgs: Uint8Array | null): Uint8Array
{
let serializedArgs: Uint8Array = EMPTY_BYTE_ARRAY;
if (rawArgs)
{
let newRaw: Uint8Array = new Uint8Array(rawArgs.length + 1);
newRaw[0] = 255; // The only requirement here is that this byte NOT be 123; it will be stripped when parsing (see IncomingRPC constructor)
newRaw.set(rawArgs, 1);
serializedArgs = newRaw;
}
if (jsonArgs)
{
serializedArgs = jsonArgs;
}
let varIntMethodID: Uint8Array = DataFormat.writeVarInt32(methodID);
let totalLength: number = RESERVED_0.length + varIntMethodID.length + rpcType.length + serializedArgs.length;
let rpcBody: Uint8Array = Buffer.concat([RESERVED_0, varIntMethodID, rpcType, serializedArgs], totalLength);
return (rpcBody);
}
/** [Internal] Creates an RPCBatch message from the supplied RPC messages. */
/*
export function makeRpcBatch(...rpcMessages: Uint8Array[]): Uint8Array
{
// First, check that the batch ONLY contains RPC messages
canUseRPCBatch(rpcMessages, true);
let messageCount: Uint8Array = DataFormat.writeVarInt32(rpcMessages.length);
let message: Uint8Array = makeMessage(MESSAGE_TYPE_BYTE_RPCBATCH, messageCount, ...rpcMessages);
return (message);
}
*/
/**
* [Internal] Returns the "header" portion of an RPCBatch message, assuming that the batch has 'rpcCount' RPC messages that collectively contain 'totalRpcLength' bytes.
* The batch can contain both Fork and Impulse RPC's.\
* **WARNING:** After sending this header you MUST immediately send the matching block of RPC messages.
*/
export function makeRPCBatchMessageHeader(rpcCount: number, totalRpcLength: number): Uint8Array
{
let type: Uint8Array = MESSAGE_TYPE_BYTE_RPCBATCH;
let messageCount: Uint8Array = DataFormat.writeVarInt32(rpcCount);
let messageSize: Uint8Array = DataFormat.writeVarInt32(type.length + messageCount.length + totalRpcLength);
let totalLength: number = messageSize.length + type.length + messageCount.length;
let rpcBatchMessageHeader: Uint8Array = Buffer.concat([messageSize, type, messageCount], totalLength);
return (rpcBatchMessageHeader);
}
/** [Internal] Returns true if all the supplied messages are RPC messages (both Fork and Impulse RPC's are allowed). */
export function canUseRPCBatch(rpcMessages: Uint8Array[], throwOnNonRPC: boolean = false): boolean
{
let canBatch: boolean = true;
for (let i = 0; i < rpcMessages.length; i++)
{
let sizeVarInt: DataFormat.varIntResult = DataFormat.readVarInt32(rpcMessages[i], 0);
let messageType: MessageType = rpcMessages[i][sizeVarInt.length];
if (messageType !== MessageType.RPC)
{
if (throwOnNonRPC)
{
throw new Error(`An RPCBatch can only contain RPC messages; the message at index ${i} of the batch is a '${MessageType[messageType]}'`);
}
canBatch = false;
break;
}
}
return (canBatch);
}
/*
function makeIncomingRpcMessage(methodID: number, rpcType: Uint8Array, jsonOrRawArgs: object | Uint8Array): Uint8Array
{
let message: Uint8Array = makeMessage(MESSAGE_TYPE_BYTE_RPC, makeRpcBody(methodID, rpcType, jsonOrRawArgs));
return (message);
}
*/
/** [Internal] Creates an IncomingRPC from an outgoing RPC message buffer. */
export function makeIncomingRpcFromOutgoingRpc(outgoingRpc: Uint8Array): IncomingRPC
{
let buffer: Buffer = Buffer.from(outgoingRpc);
let metaData: MessageMetaData = new MessageMetaData(buffer, 0);
let destinationLengthVarInt: DataFormat.varIntResult = DataFormat.readVarInt32(buffer, metaData.startOfDataIndex);
let startPos: number = metaData.startOfDataIndex + destinationLengthVarInt.length + destinationLengthVarInt.value;
let incomingRpc: IncomingRPC = new IncomingRPC(buffer, startPos /* Strip off the destination */, metaData.endOfMessageIndex);
return (incomingRpc);
}
/** [Internal] Creates a 'TakeCheckpoint' message. */
export function makeTakeCheckpointMessage(): Uint8Array
{
let message: Uint8Array = makeMessage(MESSAGE_TYPE_BYTE_TAKECHECKPOINT);
return (message);
}
function makeInitialMessage(dataPayload: Uint8Array): Uint8Array
{
let message: Uint8Array = makeMessage(MESSAGE_TYPE_BYTE_INITIALMESSAGE, dataPayload);
return (message);
}
function makeCheckpointMessage(size: number)
{
let sizeBytes: Uint8Array = DataFormat.writeVarInt64(size);
let message: Uint8Array = makeMessage(MESSAGE_TYPE_BYTE_CHECKPOINT, sizeBytes);
return (message);
}
let _lastCompleteLogPageSequenceID: bigint = BigInt(-99); // The last [non-negative] log page sequence ID for a completely read log page
let _lastLogPageSequenceID: bigint = BigInt(-99); // The last log page sequence ID that was read (even if for an incomplete log page); used only for debugging
/** [ReadOnly][Internal] Returns the last [non-negative] log page sequence ID for a completely read log page. Returns -99 if no value is available. */
export function lastCompleteLogPageSequenceID(): bigint { return (_lastCompleteLogPageSequenceID); }
/** [ReadOnly][Internal] Returns the last log page sequence ID that was read (even if for an incomplete log page). Returns -99 if no value is available. */
export function lastLogPageSequenceID(): bigint { return (_lastLogPageSequenceID); }
/**
* [Internal] Returns the length of the first log page in receiveBuffer, but only if the buffer contains [at least] one complete log page.
* Otherwise, returns -1 (indicating that the caller should keep accumulating bytes in receiveBuffer).
*/
export function getCompleteLogPageLength(receiveBuffer: Buffer, bufferLength: number): number
{
if (bufferLength >= 24) // committerID (4 bytes) + pageSize (4 bytes) + checksum (8 bytes) + pageSequenceID (8 bytes)
{
const logPageLength: number = DataFormat.readInt32Fixed(receiveBuffer, 4); // receiveBuffer.readInt32LE(4);
// This is to catch problems with us incorrectly parsing the header (not to check if the IC has a bug), although it adds some performance overhead to the "hot path"
// Note: We ignore negative pageSequenceID's, which have special meaning:
// -1 indicates a log page that only contains a 'TakeBecomingPrimaryCheckpoint', 'UpgradeTakeCheckpoint', 'TakeCheckpoint', or 'UpgradeService' message
// -2 indicates a log page that only contains a 'Checkpoint' message
// Using negative pageSequenceID's allows the IC to easily skip replaying these log pages during TTD.
const logPageSequenceID: bigint = DataFormat.readInt64Fixed(receiveBuffer, 16); // receiveBuffer.readBigInt64LE(16);
const expectedPageSequenceID: bigint = _lastCompleteLogPageSequenceID + BigInt(1);
if ((logPageSequenceID >= 0) && (_lastCompleteLogPageSequenceID >= 0) && (logPageSequenceID !== expectedPageSequenceID))
{
throw new Error(`The log page currently being read has a sequence ID (${logPageSequenceID}) that's not the expected value (${expectedPageSequenceID})`);
}
_lastLogPageSequenceID = logPageSequenceID;
if (logPageLength <= bufferLength)
{
// The receiveBuffer contains [at least] one complete log page
if (logPageSequenceID >= 0)
{
_lastCompleteLogPageSequenceID = logPageSequenceID;
}
return (logPageLength);
}
}
return (-1);
}
/** [Internal] Returns the length of the first log page in receiveBuffer, or -1 if not enough of the first log page's header has been read. */
export function readLogPageLength(receiveBuffer: Buffer, bufferLength: number): number
{
if (bufferLength >= 8) // committerID (4 bytes) + pageSize (4 bytes)
{
const logPageLength: number = DataFormat.readInt32Fixed(receiveBuffer, 4); // receiveBuffer.readInt32LE(4);
return (logPageLength);
}
return (-1);
}
const _interruptedLogPages: { pageBuffer: Buffer, startingMessageNumber: number }[] = []; // Used to defer processing of log pages that generate "too much" pressure on the outgoing message queue
const _emptyPageBuffer: Buffer = Buffer.alloc(0); // A "placeholder" log page buffer
/** Returns the number of log pages that are currently backlogged due to interruption. */
export function interruptedLogPageBacklogCount(): number
{
return (_interruptedLogPages.length);
}
/**
* [Internal] Finishes processing any previous log pages that were temporarily interrupted because they were generating too much outgoing data.\
* Returns the number of interrupted log pages that still need to be processed.
*
* Note: The purpose of interrupting a page is purely to let I/O with the IC interleave, ie. to let the outgoing message stream empty (at least partially).
*/
export function processInterruptedLogPages(config: Configuration.AmbrosiaConfig): number
{
while (_interruptedLogPages.length > 0)
{
// Note: If not enough data was flushed from the outgoing message stream, then the page may get interrupted again (potentially leading to an infinite loop)
const pageResult: number = processLogPage(_interruptedLogPages[0].pageBuffer, config, _interruptedLogPages[0].startingMessageNumber);
if (pageResult === -2)
{
// The page was interrupted again, so check if startingMessageNumber advanced
if (_interruptedLogPages[_interruptedLogPages.length - 1].pageBuffer === _emptyPageBuffer)
{
_interruptedLogPages[0].startingMessageNumber = _interruptedLogPages[_interruptedLogPages.length - 1].startingMessageNumber;
_interruptedLogPages.pop(); // Throw away the enqueued empty page (this entry was just the mechanism used to communicate that the startingMessageNumber has advanced)
}
break; // There's no point trying to finish any more pages [for now]
}
if (pageResult === -1)
{
// The page was fully processed, so we can remove it
_interruptedLogPages.shift();
if (_interruptedLogPages.length === 0)
{
Utils.traceLog(Utils.TraceFlag.LogPageInterruption, `Interrupted log page backlog cleared`);
}
}
}
return (_interruptedLogPages.length);
}
/**
* [Internal] Processes all the messages in a log page.
* Returns the number of checkpoint bytes to read (if any) before the next log page will arrive, or:\
* -1 meaning "The page was fully processed", or\
* -2 meaning "The page was interrupted (to allow I/O to occur)".
*/
export function processLogPage(receiveBuffer: Buffer, config: Configuration.AmbrosiaConfig, startingMessageNumber: number = 0): number
{
// Parse the header
// Note: committerID can be negative
// let committerID: number = DataFormat.readInt32Fixed(receiveBuffer, 0); // receiveBuffer.readInt32LE(0);
let logPageLength: number = DataFormat.readInt32Fixed(receiveBuffer, 4); // receiveBuffer.readInt32LE(4);
// let checkSum: bigint = DataFormat.readInt64Fixed(receiveBuffer, 8); // receiveBuffer.readBigInt64LE(8);
let pageSequenceID: bigint = DataFormat.readInt64Fixed(receiveBuffer, 16); // receiveBuffer.readBigInt64LE(16);
let pos: number = 24;
let outgoingCheckpoint: Streams.OutgoingCheckpoint;
let checkpointMessage: Uint8Array;
let messageNumberInPage: number = 0;
// Parse/process the message(s)
while (pos < logPageLength)
{
messageNumberInPage++;
// Check if this and/or previous log pages have resulted in too much outgoing data (in which case we need to interrupt it to allow I/O with the IC to occur).
// This can happen if the [user provided] incoming RPC message handlers are generating large and/or a high number of outgoing messages (eg. in a tight loop).
// The user can still easily write code that overwhelms the output stream's buffer (which will result in OutgoingMessageStream.checkInternalBuffer() failing),
// but this at least helps mitigate the problem - especially during recovery, when messages previously sent "spaced out" are arriving extremely rapidly in a
// consecutive batch of log pages. See bug #194 for more details.
if (IC.isOutgoingMessageStreamGettingFull(0.75)) // Allow "space" for the current message to add outgoing messages [although whatever space we leave can still end up being insufficient]
{
if (startingMessageNumber === 0)
{
// Initial interruption
const pageBuffer: Buffer = Buffer.alloc(logPageLength);
receiveBuffer.copy(pageBuffer, 0, 0, logPageLength);
_interruptedLogPages.push({ pageBuffer: pageBuffer, startingMessageNumber: messageNumberInPage });
Utils.traceLog(Utils.TraceFlag.LogPageInterruption, `Outgoing message stream is getting full (${IC.outgoingMessageStreamBacklog()} bytes); interrupting log page ${pageSequenceID} (${logPageLength} bytes) at message ${messageNumberInPage}`);
}
else
{
// Re-interruption [ie. we are being called via processInterruptedLogPages()].
// This is a no-op unless we've made additional progress through the page.
if (messageNumberInPage > startingMessageNumber)
{
// Rather than needlessly re-allocate/copy and re-enqueue the same page, we just need to communicate [to processInterruptedLogPages()] that the startingMessageNumber has advanced
_interruptedLogPages.push({ pageBuffer: _emptyPageBuffer, startingMessageNumber: messageNumberInPage });
Utils.traceLog(Utils.TraceFlag.LogPageInterruption, `Outgoing message stream is getting full (${IC.outgoingMessageStreamBacklog()} bytes); re-interrupting log page ${pageSequenceID} at message ${messageNumberInPage}`);
}
}
// Give the outgoing message stream a chance to be flushed to the IC (ie. allow I/O with the IC to interleave)
setImmediate(() => processInterruptedLogPages(config));
return (-2); // The page was interrupted
}
// Parse the message "header"
const msg: MessageMetaData = new MessageMetaData(receiveBuffer, pos);
pos = msg.startOfDataIndex;
// If a startingMessageNumber was specified, then skip messages until we reach it
if (startingMessageNumber > 0)
{
if (messageNumberInPage < startingMessageNumber)
{
pos = msg.endOfMessageIndex;
continue;
}
if (messageNumberInPage === startingMessageNumber)
{
Utils.traceLog(Utils.TraceFlag.LogPageInterruption, `Resuming processing of interrupted log page ${pageSequenceID} at message ${startingMessageNumber}`);
}
}
if (Utils.canLog(Utils.LoggingLevel.Verbose)) // We add this check because this is a high-volume code path, and Utils.log() is expensive
{
let showBytes: boolean = config.lbOptions.debugOutputLogging; // For debugging
Utils.log(`Received '${MessageType[msg.messageType]}' (${msg.totalLength} bytes)` + (showBytes ? `: ${Utils.makeDisplayBytes(receiveBuffer, msg.startOfMessageIndex, msg.totalLength)}` : ""));
}
// A [user-supplied] handler for a received message (typically an RPC) may have called IC.stop(), in which case we can't continue to process messages in the log page
if (Configuration.loadedConfig().isIntegratedIC && !IC.isRunning())
{
break;
}
// Parse the message "data" section
switch (msg.messageType)
{
case MessageType.BecomingPrimary: // No data
IC.isPrimary(true);
IC.emitAppEvent(AppEventType.BecomingPrimary);
IC.checkSelfConnection();
// An active/active secondary (including the checkpointing secondary) remains in constant recovery until
// it becomes the primary (although only a non-checkpointing secondary can ever become the primary)
if (_isRecoveryRunning)
{
_isRecoveryRunning = false;
IC.onRecoveryComplete();
IC.emitAppEvent(AppEventType.RecoveryComplete);
}
else
{
throw new Error(`This [non-checkpointing] active/active secondary (instance '${IC.instanceName()}' replica #${config.replicaNumber}) was not in recovery as expected`);
}
break;
case MessageType.UpgradeTakeCheckpoint: // No data
case MessageType.UpgradeService: // No data
const mode: AppUpgradeMode = (msg.messageType === MessageType.UpgradeTakeCheckpoint) ? AppUpgradeMode.Live : AppUpgradeMode.Test;
if (!_isRecoveryRunning)
{
// A Checkpoint must have preceded this message
throw new Error(`"Unexpected message '${MessageType[msg.messageType]}'; a '${MessageType[MessageType.Checkpoint]}' message should have preceded this message`);
}
else
{
if (mode === AppUpgradeMode.Live)
{
_isRecoveryRunning = false;
IC.onRecoveryComplete();
IC.emitAppEvent(AppEventType.RecoveryComplete);
}
}
// Tell the app to upgrade. Note: The handlers for these events MUST execute synchronously (ie. they must not return until the upgrade is complete).
Utils.log(`Upgrading app (state and code) [in '${AppUpgradeMode[mode]}' mode]...`, null, Utils.LoggingLevel.Minimal);
IC.clearUpgradeFlags();
IC.emitAppEvent(AppEventType.UpgradeState, mode);
IC.emitAppEvent(AppEventType.UpgradeCode, mode);
if (!IC.checkUpgradeFlags())
{
throw new Error(`Upgrade incomplete: Either IC.upgrade() and/or the upgrade() method of your AmbrosiaAppState instance was not called`);
}
else
{
Utils.log("Upgrade of state and code complete", null, Utils.LoggingLevel.Minimal);
}
if (mode === AppUpgradeMode.Test)
{
// When doing a 'test mode' upgrade there will be no 'completion' message from the IC signalling when
// message playback is complete, so we will not end up emitting a 'RecoveryComplete' event to the app
// (and neither will the 'UpgradeComplete' event be emitted)
Utils.log("Running recovery after app upgrade...", null, Utils.LoggingLevel.Minimal);
}
if (mode === AppUpgradeMode.Live)
{
// Take a checkpoint (of the [now upgraded] app state)
outgoingCheckpoint = config.checkpointProducer();
checkpointMessage = makeCheckpointMessage(outgoingCheckpoint.length);
IC.sendMessage(checkpointMessage, MessageType.Checkpoint, IC.instanceName());
IC.sendCheckpoint(outgoingCheckpoint, () =>
// Note: This lambda runs ONLY if sendCheckpoint() succeeds
{
IC.isPrimary(true);
IC.emitAppEvent(AppEventType.BecomingPrimary);
IC.checkSelfConnection();
// The "live" upgrade is not actually complete at this point: it is complete after the next 'TakeCheckpoint' message is
// received (which will usually be the next message received, but there can also be other messages that come before it).
// Note: Another 'tell' that the upgrade has completed is that the <instanceTable>.CurrentVersion will change to the upgradeVersion.
_completeLiveUpgradeAtNextTakeCheckpoint = true;
});
}
break;
case MessageType.TakeBecomingPrimaryCheckpoint: // No data
outgoingCheckpoint = config.checkpointProducer();
checkpointMessage = makeCheckpointMessage(outgoingCheckpoint.length);
if (!_isRecoveryRunning)
{
const initialMessage: Uint8Array = makeInitialMessage(StringEncoding.toUTF8Bytes(Root.languageBindingVersion())); // Note: We could send any arbitrary bytes
IC.sendMessage(initialMessage, MessageType.InitialMessage, IC.instanceName());
}
else
{
_isRecoveryRunning = false;
IC.onRecoveryComplete();
IC.emitAppEvent(AppEventType.RecoveryComplete);
}
IC.sendMessage(checkpointMessage, MessageType.Checkpoint, IC.instanceName());
IC.sendCheckpoint(outgoingCheckpoint, () =>
// Note: This lambda runs ONLY if sendCheckpoint() succeeds
{
IC.isPrimary(true);
IC.emitAppEvent(AppEventType.BecomingPrimary);
IC.checkSelfConnection();
});
break;
case MessageType.InitialMessage:
// The data of an InitialMessage is whatever we set it to be in our 'TakeBecomingPrimaryCheckpoint' response. We simply ignore it.
IC.emitAppEvent(AppEventType.FirstStart);
updateReplayStats(msg.messageType);
break;
case MessageType.RPC:
let rpc: IncomingRPC = new IncomingRPC(receiveBuffer, msg.startOfDataIndex, msg.endOfMessageIndex);
config.dispatcher(rpc);
updateReplayStats(msg.messageType, rpc);
break;
case MessageType.TakeCheckpoint: // No data
// TODO: JonGold needs to address issue #158 ("Clarify Ambrosia protocol") since the C# LB has (obsolete?) code that:
// a) Handles 'TakeCheckpoint' at startup (a case which is not in the protocol spec), and
// b) Sends an 'InitialMessage' in response to a TakeCheckpoint (again, this is not in the protocol spec)
// The protocol spec can be found here: https://github.com/microsoft/AMBROSIA/blob/master/CONTRIBUTING/AMBROSIA_client_network_protocol.md#communication-protocols
outgoingCheckpoint = config.checkpointProducer();
checkpointMessage = makeCheckpointMessage(outgoingCheckpoint.length);
IC.sendMessage(checkpointMessage, MessageType.Checkpoint, IC.instanceName());
IC.sendCheckpoint(outgoingCheckpoint, () =>
// Note: This lambda runs ONLY if sendCheckpoint() succeeds
{
if (_completeLiveUpgradeAtNextTakeCheckpoint)
{
try
{
_completeLiveUpgradeAtNextTakeCheckpoint = false;
// The "live" upgrade is now complete, so update the ambrosiaConfig.json file so that we're prepared for the next restart.
// However, we only do this if the upgrade was requested via the ambrosiaConfig.json. If the upgrade was requested via an
// explicit call to "Ambrosia.exe RegisterInstance" then we assume the user is handling the upgrade process manually (or
// via an 'upgrade orchestration service' they built).
if (Configuration.loadedConfig().isLiveUpgradeRequested)
{
Configuration.loadedConfig().updateSetting("appVersion", Configuration.loadedConfig().upgradeVersion);
Configuration.loadedConfig().updateSetting("activeCode", Configuration.ActiveCodeType[Configuration.ActiveCodeType.VNext]);
// The IC doesn't update the registered currentVersion after the upgrade (it only updates <instanceTable>.CurrentVersion),
// so we have to re-register at the next restart to update it [without this, AmbrosiaConfigFile.initializeAsync() will throw]
Configuration.loadedConfig().updateSetting("autoRegister", true);
}
else
{
// Note: Because the upgrade wasn't requested via ambrosiaConfig.json, we can't report the upgradeVersion that currentVersion must be set to
Utils.log(`Warning: You must re-register the '${IC.instanceName()}' instance (to update --currentVersion) to finish the upgrade`);
}
Utils.log("Upgrade complete", null, Utils.LoggingLevel.Minimal);
// The app may want to do its own post-upgrade work (eg. custom handling of re-registration / code-switching, or signalling
// to any orchestrating infrastructure that may be managing an active/active upgrade).
// Note: Because this event is raised only as a consequence of a non-replayable message (UpgradeTakeCheckpoint), whatever
// actions (if any) the app takes when responding to it are not part of a deterministic chain.
IC.emitAppEvent(AppEventType.UpgradeComplete);
}
catch (error: unknown)
{
Utils.log(Utils.makeError(error));
}
}
});
break;
case MessageType.Checkpoint:
let checkpointLengthVarInt: DataFormat.varIntResult = DataFormat.readVarInt64(receiveBuffer, pos);
let checkpointLength: number = checkpointLengthVarInt.value;
Utils.log(`Starting recovery [load checkpoint (${checkpointLength} bytes) and replay messages]...`);
_isRecoveryRunning = true;
// We keep track of the number of received/resent messages during recovery
IC._counters.remoteSentMessageCount = IC._counters.receivedMessageCount = IC._counters.receivedForkMessageCount = IC._counters.sentForkMessageCount = 0;
// By returning the checkpoint length we tell the caller to read the next checkpointLength bytes as checkpoint data.
// Note: It's safe to return here as a 'Checkpoint' will always be the only message in the log page.
// The caller will skip to the first byte AFTER the current log page [whose length will include
// checkpointLengthVarInt.numBytesRead] so there's no need to also pass back checkpointLengthVarInt.numBytesRead.
return (checkpointLength); // Note: Can be 0
case MessageType.RPCBatch:
case MessageType.CountReplayableRPCBatchByte:
let rpcCountVarInt: DataFormat.varIntResult = DataFormat.readVarInt32(receiveBuffer, pos);
let rpcCount: number = rpcCountVarInt.value;
pos += rpcCountVarInt.length;
if (msg.messageType === MessageType.CountReplayableRPCBatchByte)
{
let forkRpcCountVarInt: DataFormat.varIntResult = DataFormat.readVarInt32(receiveBuffer, pos);
let forkRpcCount: number = forkRpcCountVarInt.value;
pos += forkRpcCountVarInt.length;
Utils.log(`Processing RPC batch (of ${rpcCount} messages, ${forkRpcCount} of which are replayable)...`);
}
else
{
Utils.log(`Processing RPC batch (of ${rpcCount} messages)...`);
}
// Note: We'll let the processing of each contained message update _replayedMessageCount and _receivedForkMessageCount, so we don't
// call updateReplayStats() here (effectively, we ignore the batch "wrapper" for the purpose of tracking replay stats)
continue;
default:
throw new Error(`Log page ${pageSequenceID} contains a message of unknown type (${msg.messageType}); message: ${Utils.makeDisplayBytes(receiveBuffer, msg.startOfMessageIndex, msg.totalLength)}`);
}
pos = msg.endOfMessageIndex;
}
return (-1); // The page was fully processed
}
function updateReplayStats(messageType: MessageType, message?: DispatchedMessage): void
{
if (_isRecoveryRunning)
{
if ((messageType === MessageType.InitialMessage) || (messageType === MessageType.RPC))
{
if ((messageType === MessageType.RPC) && ((message as IncomingRPC).rpcType === RPCType.Fork))
{
IC._counters.receivedForkMessageCount++;
}
IC._counters.receivedMessageCount++;
}
}
} | the_stack |
import { BoxPanel, PanelLayout, Widget } from "@lumino/widgets";
import { Cell, CodeCellModel } from "@jupyterlab/cells";
import { CodeEditorWrapper } from "@jupyterlab/codeeditor";
import { editorServices } from "@jupyterlab/codemirror";
import { INotebookTracker } from "@jupyterlab/notebook";
import {
CELLTEST_RULES,
CELLTEST_TOOL_CONTROLS_CLASS,
CELLTEST_TOOL_EDITOR_CLASS,
CELLTEST_TOOL_RULES_CLASS,
} from "./utils";
const circleSvg = require("../style/circle.svg").default;
/**
* Widget responsible for holding test controls
*
* @class ControlsWidget (name)
*/
class ControlsWidget extends BoxPanel {
public label: HTMLLabelElement;
public svglabel: HTMLElement;
public svg: HTMLElement;
public constructor() {
super({ direction: "top-to-bottom" });
/* Section Header */
this.label = document.createElement("label");
this.label.textContent = "Tests";
this.svglabel = document.createElement("label");
this.svg = document.createElement("svg");
this.svg.innerHTML = circleSvg;
this.svg = this.svg.firstChild as HTMLElement;
const div1 = document.createElement("div");
div1.appendChild(this.label);
const div2 = document.createElement("div");
div1.appendChild(div2);
div2.appendChild(this.svglabel);
div2.appendChild(this.svg);
this.node.appendChild(div1);
this.node.classList.add(CELLTEST_TOOL_CONTROLS_CLASS);
/* Add button */
const div3 = document.createElement("div");
const add = document.createElement("button");
add.textContent = "Add";
add.onclick = () => {
this.add();
};
/* Save button */
const save = document.createElement("button");
save.textContent = "Save";
save.onclick = () => {
this.save();
};
/* Clear button */
const clear = document.createElement("button");
clear.textContent = "Clear";
clear.onclick = () => {
this.clear();
};
/* add to container */
div3.appendChild(add);
div3.appendChild(save);
div3.appendChild(clear);
this.node.appendChild(div3);
}
// eslint-disable-next-line @typescript-eslint/no-empty-function
public add = () => {};
// eslint-disable-next-line @typescript-eslint/no-empty-function
public save = () => {};
// eslint-disable-next-line @typescript-eslint/no-empty-function
public clear = () => {};
}
/**
* Widget responsible for holding test controls
*
* @class ControlsWidget (name)
*/
class RulesWidget extends BoxPanel {
public label: HTMLLabelElement;
public lines_per_cell: HTMLDivElement;
public cells_per_notebook: HTMLDivElement;
public function_definitions: HTMLDivElement;
public class_definitions: HTMLDivElement;
public cell_coverage: HTMLDivElement;
public constructor() {
super({ direction: "top-to-bottom" });
/* Section Header */
this.label = document.createElement("label");
this.label.textContent = "Lint Rules";
this.node.appendChild(this.label);
this.node.classList.add(CELLTEST_TOOL_RULES_CLASS);
/* Add button */
const div = document.createElement("div");
for (const val of [].slice.call(CELLTEST_RULES)) {
const row = document.createElement("div");
const span = document.createElement("span");
span.textContent = val.label;
const chkbx = document.createElement("input");
chkbx.type = "checkbox";
chkbx.name = val.key;
const number = document.createElement("input");
number.type = "number";
number.name = val.key;
chkbx.onchange = () => {
number.disabled = !chkbx.checked;
number.value = number.disabled ? "" : val.value;
this.save();
};
number.onchange = () => {
this.save();
};
if (val.min !== undefined) {
number.min = val.min;
}
if (val.max !== undefined) {
number.max = val.max;
}
if (val.step !== undefined) {
number.step = val.step;
}
row.appendChild(span);
row.appendChild(chkbx);
row.appendChild(number);
this.setByKey(val.key, row);
div.appendChild(row);
}
this.node.appendChild(div);
}
public getByKey(key: string) {
switch (key) {
case "lines_per_cell": {
return this.lines_per_cell;
}
case "cells_per_notebook": {
return this.cells_per_notebook;
}
case "function_definitions": {
return this.function_definitions;
}
case "class_definitions": {
return this.class_definitions;
}
case "cell_coverage": {
return this.cell_coverage;
}
}
}
public setByKey(key: string, elem: HTMLDivElement) {
switch (key) {
case "lines_per_cell": {
this.lines_per_cell = elem;
break;
}
case "cells_per_notebook": {
this.cells_per_notebook = elem;
break;
}
case "function_definitions": {
this.function_definitions = elem;
break;
}
case "class_definitions": {
this.class_definitions = elem;
break;
}
case "cell_coverage": {
this.cell_coverage = elem;
break;
}
}
}
public getValuesByKey(key: string) {
let elem;
switch (key) {
case "lines_per_cell": {
elem = this.lines_per_cell;
break;
}
case "cells_per_notebook": {
elem = this.cells_per_notebook;
break;
}
case "function_definitions": {
elem = this.function_definitions;
break;
}
case "class_definitions": {
elem = this.class_definitions;
break;
}
case "cell_coverage": {
elem = this.cell_coverage;
break;
}
}
const chkbx: HTMLInputElement = elem.querySelector(
'input[type="checkbox"]',
);
const input: HTMLInputElement = elem.querySelector('input[type="number"]');
return { key, enabled: chkbx.checked, value: Number(input.value) };
}
public setValuesByKey(key: string, checked = true, value: number = null) {
let elem;
switch (key) {
case "lines_per_cell": {
elem = this.lines_per_cell;
break;
}
case "cells_per_notebook": {
elem = this.cells_per_notebook;
break;
}
case "function_definitions": {
elem = this.function_definitions;
break;
}
case "class_definitions": {
elem = this.class_definitions;
break;
}
case "cell_coverage": {
elem = this.cell_coverage;
break;
}
}
const chkbx: HTMLInputElement = elem.querySelector(
'input[type="checkbox"]',
);
const input: HTMLInputElement = elem.querySelector('input[type="number"]');
if (input) {
input.value = value === null ? "" : String(value);
input.disabled = !checked;
}
if (chkbx) {
chkbx.checked = checked;
}
}
// eslint-disable-next-line @typescript-eslint/no-empty-function
public save = () => {};
}
/**
* Widget holding the Celltests widget, container for options and editor
*
* @class CelltestsWidget (name)
*/
export class CelltestsWidget extends Widget {
public currentActiveCell: Cell = null;
public notebookTracker: INotebookTracker = null;
private editor: CodeEditorWrapper = null;
private rules: RulesWidget;
private controls: ControlsWidget;
public constructor() {
super();
/* create layout */
const layout = (this.layout = new PanelLayout());
/* create options widget */
const controls = (this.controls = new ControlsWidget());
/* create options widget */
const rules = (this.rules = new RulesWidget());
/* create codemirror editor */
const editorOptions = {
// eslint-disable-next-line @typescript-eslint/unbound-method
factory: editorServices.factoryService.newInlineEditor,
model: new CodeCellModel({}),
};
const editor = (this.editor = new CodeEditorWrapper(editorOptions));
editor.addClass(CELLTEST_TOOL_EDITOR_CLASS);
editor.model.mimeType = "text/x-ipython";
/* add options and editor to widget */
layout.addWidget(controls);
layout.addWidget(editor);
layout.addWidget(rules);
/* set add button functionality */
controls.add = () => {
this.fetchAndSetTests();
return true;
};
/* set save button functionality */
controls.save = () => {
this.saveTestsForActiveCell();
return true;
};
/* set clear button functionality */
controls.clear = () => {
this.deleteTestsForActiveCell();
return true;
};
rules.save = () => {
this.saveRulesForCurrentNotebook();
};
}
public fetchAndSetTests(): void {
const tests = [];
const splits = this.editor.model.value.text.split(/\n/);
// eslint-disable-next-line @typescript-eslint/prefer-for-of
for (let i = 0; i < splits.length; i++) {
tests.push(splits[i] + "\n");
}
if (
this.currentActiveCell !== null &&
this.currentActiveCell.model.type === "code"
) {
this.currentActiveCell.model.metadata.set("celltests", tests);
this.setIndicatorTests();
}
}
public loadTestsForActiveCell(): void {
if (
this.currentActiveCell !== null &&
this.currentActiveCell.model.type === "code"
) {
let tests = this.currentActiveCell.model.metadata.get(
"celltests",
) as string[];
let s = "";
if (tests === undefined || tests.length === 0) {
tests = [
'# Use %cell to mark where the cell should be inserted, or add a line comment "# no %cell" to deliberately skip the cell\n',
"%cell\n",
];
this.setIndicatorNoTests();
} else {
this.setIndicatorTests();
}
// eslint-disable-next-line @typescript-eslint/prefer-for-of
for (let i = 0; i < tests.length; i++) {
s += tests[i];
}
this.editor.model.value.text = s;
this.editor.editor.setOption("readOnly", false);
} else {
this.editor.model.value.text = "# Not a code cell";
this.editor.editor.setOption("readOnly", true);
this.setIndicatorNonCode();
}
}
public saveTestsForActiveCell(): void {
/* if currentActiveCell exists */
if (
this.currentActiveCell !== null &&
this.currentActiveCell.model.type === "code"
) {
const tests = [];
const splits = this.editor.model.value.text.split(/\n/);
// eslint-disable-next-line @typescript-eslint/prefer-for-of
for (let i = 0; i < splits.length; i++) {
tests.push(splits[i] + "\n");
}
this.currentActiveCell.model.metadata.set("celltests", tests);
this.setIndicatorTests();
} else if (this.currentActiveCell !== null) {
// TODO this?
this.currentActiveCell.model.metadata.delete("celltests");
this.setIndicatorNonCode();
}
}
public deleteTestsForActiveCell(): void {
if (this.currentActiveCell !== null) {
this.currentActiveCell.model.metadata.delete("celltests");
this.setIndicatorNoTests();
}
}
public loadRulesForCurrentNotebook(): void {
if (this.notebookTracker !== null) {
const metadata: { [key: string]: number } =
(this.notebookTracker.currentWidget.model.metadata.get("celltests") as {
[key: string]: number;
}) || {};
for (const rule of [].slice.call(CELLTEST_RULES)) {
this.rules.setValuesByKey(
rule.key,
rule.key in metadata,
metadata[rule.key],
);
}
}
}
public saveRulesForCurrentNotebook(): void {
if (this.notebookTracker !== null) {
const metadata = {} as { [key: string]: number };
for (const rule of [].slice.call(CELLTEST_RULES)) {
const settings = this.rules.getValuesByKey(rule.key);
if (settings.enabled) {
metadata[settings.key] = settings.value;
}
}
this.notebookTracker.currentWidget.model.metadata.set(
"celltests",
metadata,
);
}
}
public get editorWidget(): CodeEditorWrapper {
return this.editor;
}
private setIndicatorNoTests(): void {
(this.controls.svg.firstElementChild
.firstElementChild as HTMLElement).style.fill = "#e75c57";
this.controls.svglabel.textContent = "(No Tests)";
}
private setIndicatorTests(): void {
(this.controls.svg.firstElementChild
.firstElementChild as HTMLElement).style.fill = "#008000";
this.controls.svglabel.textContent = "(Tests Exist)";
}
private setIndicatorNonCode(): void {
(this.controls.svg.firstElementChild
.firstElementChild as HTMLElement).style.fill =
"var(--jp-inverse-layout-color3)";
this.controls.svglabel.textContent = "(Non Code Cell)";
}
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import * as utilities from "../utilities";
/**
* Workflow program to be executed by Workflows.
*
* To get more information about Workflow, see:
*
* * [API documentation](https://cloud.google.com/workflows/docs/reference/rest/v1/projects.locations.workflows)
* * How-to Guides
* * [Managing Workflows](https://cloud.google.com/workflows/docs/creating-updating-workflow)
*
* ## Example Usage
* ### Workflow Basic
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const testAccount = new gcp.serviceaccount.Account("testAccount", {
* accountId: "my-account",
* displayName: "Test Service Account",
* });
* const example = new gcp.workflows.Workflow("example", {
* region: "us-central1",
* description: "Magic",
* serviceAccount: testAccount.id,
* sourceContents: `# This is a sample workflow, feel free to replace it with your source code
* #
* # This workflow does the following:
* # - reads current time and date information from an external API and stores
* # the response in CurrentDateTime variable
* # - retrieves a list of Wikipedia articles related to the day of the week
* # from CurrentDateTime
* # - returns the list of articles as an output of the workflow
* # FYI, In terraform you need to escape the $$ or it will cause errors.
*
* - getCurrentTime:
* call: http.get
* args:
* url: https://us-central1-workflowsample.cloudfunctions.net/datetime
* result: CurrentDateTime
* - readWikipedia:
* call: http.get
* args:
* url: https://en.wikipedia.org/w/api.php
* query:
* action: opensearch
* search: ${CurrentDateTime.body.dayOfTheWeek}
* result: WikiResult
* - returnOutput:
* return: ${WikiResult.body[1]}
* `,
* });
* ```
*
* ## Import
*
* This resource does not support import.
*/
export class Workflow extends pulumi.CustomResource {
/**
* Get an existing Workflow resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param state Any extra arguments used during the lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: WorkflowState, opts?: pulumi.CustomResourceOptions): Workflow {
return new Workflow(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'gcp:workflows/workflow:Workflow';
/**
* Returns true if the given object is an instance of Workflow. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is Workflow {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === Workflow.__pulumiType;
}
/**
* The timestamp of when the workflow was created in RFC3339 UTC "Zulu" format, with nanosecond resolution and up to nine
* fractional digits.
*/
public /*out*/ readonly createTime!: pulumi.Output<string>;
/**
* Description of the workflow provided by the user. Must be at most 1000 unicode characters long.
*/
public readonly description!: pulumi.Output<string>;
/**
* A set of key/value label pairs to assign to this Workflow.
*/
public readonly labels!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* Name of the Workflow.
*/
public readonly name!: pulumi.Output<string>;
/**
* Creates a unique name beginning with the
* specified prefix. If this and name are unspecified, a random value is chosen for the name.
*/
public readonly namePrefix!: pulumi.Output<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
public readonly project!: pulumi.Output<string>;
/**
* The region of the workflow.
*/
public readonly region!: pulumi.Output<string | undefined>;
/**
* The revision of the workflow. A new one is generated if the service account or source contents is changed.
*/
public /*out*/ readonly revisionId!: pulumi.Output<string>;
/**
* Name of the service account associated with the latest workflow version. This service
* account represents the identity of the workflow and determines what permissions the workflow has.
* Format: projects/{project}/serviceAccounts/{account}.
*/
public readonly serviceAccount!: pulumi.Output<string>;
/**
* Workflow code to be executed. The size limit is 32KB.
*/
public readonly sourceContents!: pulumi.Output<string | undefined>;
/**
* State of the workflow deployment.
*/
public /*out*/ readonly state!: pulumi.Output<string>;
/**
* The timestamp of when the workflow was last updated in RFC3339 UTC "Zulu" format, with nanosecond resolution and up to
* nine fractional digits.
*/
public /*out*/ readonly updateTime!: pulumi.Output<string>;
/**
* Create a Workflow resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args?: WorkflowArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: WorkflowArgs | WorkflowState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as WorkflowState | undefined;
inputs["createTime"] = state ? state.createTime : undefined;
inputs["description"] = state ? state.description : undefined;
inputs["labels"] = state ? state.labels : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["namePrefix"] = state ? state.namePrefix : undefined;
inputs["project"] = state ? state.project : undefined;
inputs["region"] = state ? state.region : undefined;
inputs["revisionId"] = state ? state.revisionId : undefined;
inputs["serviceAccount"] = state ? state.serviceAccount : undefined;
inputs["sourceContents"] = state ? state.sourceContents : undefined;
inputs["state"] = state ? state.state : undefined;
inputs["updateTime"] = state ? state.updateTime : undefined;
} else {
const args = argsOrState as WorkflowArgs | undefined;
inputs["description"] = args ? args.description : undefined;
inputs["labels"] = args ? args.labels : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["namePrefix"] = args ? args.namePrefix : undefined;
inputs["project"] = args ? args.project : undefined;
inputs["region"] = args ? args.region : undefined;
inputs["serviceAccount"] = args ? args.serviceAccount : undefined;
inputs["sourceContents"] = args ? args.sourceContents : undefined;
inputs["createTime"] = undefined /*out*/;
inputs["revisionId"] = undefined /*out*/;
inputs["state"] = undefined /*out*/;
inputs["updateTime"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(Workflow.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering Workflow resources.
*/
export interface WorkflowState {
/**
* The timestamp of when the workflow was created in RFC3339 UTC "Zulu" format, with nanosecond resolution and up to nine
* fractional digits.
*/
createTime?: pulumi.Input<string>;
/**
* Description of the workflow provided by the user. Must be at most 1000 unicode characters long.
*/
description?: pulumi.Input<string>;
/**
* A set of key/value label pairs to assign to this Workflow.
*/
labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* Name of the Workflow.
*/
name?: pulumi.Input<string>;
/**
* Creates a unique name beginning with the
* specified prefix. If this and name are unspecified, a random value is chosen for the name.
*/
namePrefix?: pulumi.Input<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* The region of the workflow.
*/
region?: pulumi.Input<string>;
/**
* The revision of the workflow. A new one is generated if the service account or source contents is changed.
*/
revisionId?: pulumi.Input<string>;
/**
* Name of the service account associated with the latest workflow version. This service
* account represents the identity of the workflow and determines what permissions the workflow has.
* Format: projects/{project}/serviceAccounts/{account}.
*/
serviceAccount?: pulumi.Input<string>;
/**
* Workflow code to be executed. The size limit is 32KB.
*/
sourceContents?: pulumi.Input<string>;
/**
* State of the workflow deployment.
*/
state?: pulumi.Input<string>;
/**
* The timestamp of when the workflow was last updated in RFC3339 UTC "Zulu" format, with nanosecond resolution and up to
* nine fractional digits.
*/
updateTime?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a Workflow resource.
*/
export interface WorkflowArgs {
/**
* Description of the workflow provided by the user. Must be at most 1000 unicode characters long.
*/
description?: pulumi.Input<string>;
/**
* A set of key/value label pairs to assign to this Workflow.
*/
labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* Name of the Workflow.
*/
name?: pulumi.Input<string>;
/**
* Creates a unique name beginning with the
* specified prefix. If this and name are unspecified, a random value is chosen for the name.
*/
namePrefix?: pulumi.Input<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* The region of the workflow.
*/
region?: pulumi.Input<string>;
/**
* Name of the service account associated with the latest workflow version. This service
* account represents the identity of the workflow and determines what permissions the workflow has.
* Format: projects/{project}/serviceAccounts/{account}.
*/
serviceAccount?: pulumi.Input<string>;
/**
* Workflow code to be executed. The size limit is 32KB.
*/
sourceContents?: pulumi.Input<string>;
} | the_stack |
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { HttpClientModule } from '@angular/common/http';
import {
SchemaFormModule,
SchemaValidatorFactory,
ZSchemaValidatorFactory,
WidgetRegistry,
DefaultWidgetRegistry
} from '../../../projects/schema-form/src/public_api';
import { JsonSchemaExampleComponent } from './json-schema-example.component';
import { By } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
describe('JsonSchemaExampleComponent', () => {
let component: JsonSchemaExampleComponent;
let fixture: ComponentFixture<JsonSchemaExampleComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
SchemaFormModule.forRoot(),
HttpClientModule,
FormsModule,
ReactiveFormsModule
],
declarations: [ JsonSchemaExampleComponent ],
providers: [
{provide: WidgetRegistry, useClass: DefaultWidgetRegistry},
{
provide: SchemaValidatorFactory,
useClass: ZSchemaValidatorFactory
}
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(JsonSchemaExampleComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
describe('JsonSchemaExampleComponent - visibleIf - data-types', () => {
let component: JsonSchemaExampleComponent;
let fixture: ComponentFixture<JsonSchemaExampleComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
SchemaFormModule.forRoot(),
HttpClientModule,
FormsModule,
ReactiveFormsModule
],
declarations: [ JsonSchemaExampleComponent ],
providers: [
{provide: WidgetRegistry, useClass: DefaultWidgetRegistry},
{
provide: SchemaValidatorFactory,
useClass: ZSchemaValidatorFactory
}
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(JsonSchemaExampleComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
/*
it('should create', () => {
expect(component).toBeTruthy();
});
*/
beforeEach(() => {
// select demo sample
const select: HTMLSelectElement = fixture.debugElement.query(By.css('#samples')).nativeElement;
select.value = select.options[4].value; // <-- select a new value
select.dispatchEvent(new Event('change'));
fixture.detectChanges();
});
it(`# 1. Test boolean as boolean`, async(() => {
// Visible component shows up if a boolean value `true` is provided
const app = component
fixture.whenStable().then(() => {
fixture.detectChanges();
// expect selected sample schema to be loaded
expect(app.schema.properties.demo.properties.typeTest.fieldsets[0].description).toEqual('# 1. Test boolean');
// expect page containing a sf-form element
let sf_form = fixture.debugElement.query(By.css('sf-form'))
expect(sf_form).toBeTruthy()
// initial state
let _test_boolean_check = fixture.debugElement.query(By.css('#demo\\.typeTest\\.checkbool'));
expect(_test_boolean_check).toBeTruthy()
let _test_boolean_visible = fixture.debugElement.query(By.css('#demo\\.typeTest\\.testbool'));
expect(_test_boolean_visible).toBeNull()
let _test_boolean_visible_negative = fixture.debugElement.query(By.css('#demo\\.typeTest\\.testboolnegative'));
expect(_test_boolean_visible_negative).toBeTruthy()
// positive state
_test_boolean_check.nativeElement.checked = true
_test_boolean_check.nativeElement.dispatchEvent(new Event('change'));
fixture.detectChanges();
_test_boolean_visible = fixture.debugElement.query(By.css('#demo\\.typeTest\\.testbool'));
expect(_test_boolean_visible).toBeTruthy()
_test_boolean_visible_negative = fixture.debugElement.query(By.css('#demo\\.typeTest\\.testboolnegative'));
expect(_test_boolean_visible_negative).toBeNull()
// negative state
_test_boolean_check.nativeElement.checked = false
_test_boolean_check.nativeElement.dispatchEvent(new Event('change'));
fixture.detectChanges();
_test_boolean_visible = fixture.debugElement.query(By.css('#demo\\.typeTest\\.testbool'));
expect(_test_boolean_visible).toBeNull()
_test_boolean_visible_negative = fixture.debugElement.query(By.css('#demo\\.typeTest\\.testboolnegative'));
expect(_test_boolean_visible_negative).toBeTruthy()
});
}));
it(`# 1. Test boolean as string`, async(() => {
// Visible component shows up if a boolean value `"true"` as string is provided
const app = component
fixture.whenStable().then(() => {
fixture.detectChanges();
// expect selected sample schema to be loaded
expect(app.schema.properties.demo.properties.typeTest.fieldsets[0].description).toEqual('# 1. Test boolean');
// expect page containing a sf-form element
let sf_form = fixture.debugElement.query(By.css('sf-form'))
expect(sf_form).toBeTruthy()
// initial state
let _test_boolean_check_true = fixture.debugElement.query(By.css('#demo\\.typeTest\\.checkboolstring\\.true'));
expect(_test_boolean_check_true).toBeTruthy()
let _test_boolean_check_false = fixture.debugElement.query(By.css('#demo\\.typeTest\\.checkboolstring\\.false'));
expect(_test_boolean_check_false).toBeTruthy()
let _test_boolean_visible = fixture.debugElement.query(By.css('#demo\\.typeTest\\.testboolstring'));
expect(_test_boolean_visible).toBeNull()
// positive state
_test_boolean_check_true.nativeElement.checked = true
_test_boolean_check_true.nativeElement.dispatchEvent(new Event('change'));
fixture.detectChanges();
_test_boolean_visible = fixture.debugElement.query(By.css('#demo\\.typeTest\\.testboolstring'));
expect(_test_boolean_visible).toBeTruthy()
// negative state
_test_boolean_check_false.nativeElement.checked = false
_test_boolean_check_false.nativeElement.dispatchEvent(new Event('change'));
fixture.detectChanges();
_test_boolean_visible = fixture.debugElement.query(By.css('#demo\\.typeTest\\.testboolstring'));
expect(_test_boolean_visible).toBeNull()
});
}));
it(`# 2. Test number`, async(() => {
// Visible component shows up if a number value `1` is provided
const app = component
fixture.whenStable().then(() => {
fixture.detectChanges();
// expect selected sample schema to be loaded
expect(app.schema.properties.demo.properties.typeTest.fieldsets[1].description).toEqual('# 2. Test number');
// expect page containing a sf-form element
let sf_form = fixture.debugElement.query(By.css('sf-form'))
expect(sf_form).toBeTruthy()
// initial state
let _test_number_input = fixture.debugElement.query(By.css('#demo\\.typeTest\\.checknum'));
expect(_test_number_input).toBeTruthy()
let _test_number_visible = fixture.debugElement.query(By.css('#demo\\.typeTest\\.testnum'));
expect(_test_number_visible).toBeNull()
// positive state
_test_number_input.nativeElement.value = '1'
_test_number_input.nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
_test_number_visible = fixture.debugElement.query(By.css('#demo\\.typeTest\\.testnum'));
expect(_test_number_visible).toBeTruthy()
// negative state
_test_number_input.nativeElement.value = '2'
_test_number_input.nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
_test_number_visible = fixture.debugElement.query(By.css('#demo\\.typeTest\\.testnum'));
expect(_test_number_visible).toBeNull()
});
}));
it(`# 2. Test number as string`, async(() => {
// Visible component shows up if a number value `"1"` as string is provided
const app = component
fixture.whenStable().then(() => {
fixture.detectChanges();
// expect selected sample schema to be loaded
expect(app.schema.properties.demo.properties.typeTest.fieldsets[1].description).toEqual('# 2. Test number');
// expect page containing a sf-form element
let sf_form = fixture.debugElement.query(By.css('sf-form'))
expect(sf_form).toBeTruthy()
// initial state
let _test_number_select = fixture.debugElement.query(By.css('#demo\\.typeTest\\.checknumstring'));
expect(_test_number_select).toBeTruthy()
let _test_number_visible = fixture.debugElement.query(By.css('#demo\\.typeTest\\.testnumstring'));
expect(_test_number_visible).toBeNull()
// positive state
_test_number_select.nativeElement.value = _test_number_select.nativeElement.options[1].value; // set to '1'
_test_number_select.nativeElement.dispatchEvent(new Event('change'));
fixture.detectChanges();
_test_number_visible = fixture.debugElement.query(By.css('#demo\\.typeTest\\.testnumstring'));
expect(_test_number_visible).toBeTruthy()
// negative state
_test_number_select.nativeElement.value = _test_number_select.nativeElement.options[2].value; // set to '2'
_test_number_select.nativeElement.dispatchEvent(new Event('change'));
fixture.detectChanges();
_test_number_visible = fixture.debugElement.query(By.css('#demo\\.typeTest\\.testnumstring'));
expect(_test_number_visible).toBeNull()
});
}));
it(`# 3. Test string`, async(() => {
// Visible component shows up if a string value `"a"` is provided
const app = component
fixture.whenStable().then(() => {
fixture.detectChanges();
// expect selected sample schema to be loaded
expect(app.schema.properties.demo.properties.typeTest.fieldsets[2].description).toEqual('# 3. Test string');
// expect page containing a sf-form element
let sf_form = fixture.debugElement.query(By.css('sf-form'))
expect(sf_form).toBeTruthy()
// initial state
let _test_string_input = fixture.debugElement.query(By.css('#demo\\.typeTest\\.checkstring'));
expect(_test_string_input).toBeTruthy()
let _test_number_visible = fixture.debugElement.query(By.css('#demo\\.typeTest\\.teststring'));
expect(_test_number_visible).toBeNull()
// positive state
_test_string_input.nativeElement.value = 'a'
_test_string_input.nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
_test_number_visible = fixture.debugElement.query(By.css('#demo\\.typeTest\\.teststring'));
expect(_test_number_visible).toBeTruthy()
// negative state
_test_string_input.nativeElement.value = 'z'
_test_string_input.nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
_test_number_visible = fixture.debugElement.query(By.css('#demo\\.typeTest\\.teststring'));
expect(_test_number_visible).toBeNull()
});
}));
});
describe('JsonSchemaExampleComponent - visibleIf - condition-types', () => {
let component: JsonSchemaExampleComponent;
let fixture: ComponentFixture<JsonSchemaExampleComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
SchemaFormModule.forRoot(),
HttpClientModule,
FormsModule,
ReactiveFormsModule
],
declarations: [ JsonSchemaExampleComponent ],
providers: [
{provide: WidgetRegistry, useClass: DefaultWidgetRegistry},
{
provide: SchemaValidatorFactory,
useClass: ZSchemaValidatorFactory
}
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(JsonSchemaExampleComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
/*
it('should create', () => {
expect(component).toBeTruthy();
});
*/
beforeEach(() => {
// select demo sample
const select: HTMLSelectElement = fixture.debugElement.query(By.css('#samples')).nativeElement;
select.value = select.options[4].value; // <-- select a new value
select.dispatchEvent(new Event('change'));
fixture.detectChanges();
});
it(`# 4. Test 'VisibleIf' with default 'one-of' with multiple values`, async(() => {
// Visible component shows up if status value is 'Warn' or 'Fail'
fixture.whenStable().then(() => {
fixture.detectChanges();
// expect page containing a sf-form element
let sf_form = fixture.debugElement.query(By.css('sf-form'))
expect(sf_form).toBeTruthy()
// initial state
let _test_boolean_check_pass = fixture.debugElement.query(By.css('#demo\\.visibleIfBinding1a\\.status1a\\.Pass'));
expect(_test_boolean_check_pass).toBeTruthy()
let _test_boolean_check_warn = fixture.debugElement.query(By.css('#demo\\.visibleIfBinding1a\\.status1a\\.Warn'));
expect(_test_boolean_check_warn).toBeTruthy()
let _test_boolean_check_fail = fixture.debugElement.query(By.css('#demo\\.visibleIfBinding1a\\.status1a\\.Fail'));
expect(_test_boolean_check_fail).toBeTruthy()
let _test_boolean_visible = fixture.debugElement.query(By.css('#demo\\.visibleIfBinding1a\\.visibleComponent1a'));
expect(_test_boolean_visible).toBeNull()
// negative state 'Pass'
_test_boolean_check_pass.nativeElement.checked = true
_test_boolean_check_pass.nativeElement.dispatchEvent(new Event('change'));
fixture.detectChanges();
_test_boolean_visible = fixture.debugElement.query(By.css('#demo\\.visibleIfBinding1a\\.visibleComponent1a'));
expect(_test_boolean_visible).toBeNull()
// positive state 'Warn'
_test_boolean_check_warn.nativeElement.checked = true
_test_boolean_check_warn.nativeElement.dispatchEvent(new Event('change'));
fixture.detectChanges();
_test_boolean_visible = fixture.debugElement.query(By.css('#demo\\.visibleIfBinding1a\\.visibleComponent1a'));
expect(_test_boolean_visible).toBeTruthy()
// negative state 'Pass'
_test_boolean_check_pass.nativeElement.checked = true
_test_boolean_check_pass.nativeElement.dispatchEvent(new Event('change'));
fixture.detectChanges();
_test_boolean_visible = fixture.debugElement.query(By.css('#demo\\.visibleIfBinding1a\\.visibleComponent1a'));
expect(_test_boolean_visible).toBeNull()
// positive state 'Fail'
_test_boolean_check_fail.nativeElement.checked = true
_test_boolean_check_fail.nativeElement.dispatchEvent(new Event('change'));
fixture.detectChanges();
_test_boolean_visible = fixture.debugElement.query(By.css('#demo\\.visibleIfBinding1a\\.visibleComponent1a'));
expect(_test_boolean_visible).toBeTruthy()
});
}));
it(`# 5. Test 'VisibleIf' with 'oneOf' condition`, async(() => {
// Visible component shows up if status value is 'Warn' or 'Fail'
fixture.whenStable().then(() => {
fixture.detectChanges();
// expect page containing a sf-form element
let sf_form = fixture.debugElement.query(By.css('sf-form'))
expect(sf_form).toBeTruthy()
// initial state
let _test_boolean_check_pass = fixture.debugElement.query(By.css('#demo\\.visibleIfBinding1b\\.status1b\\.Pass'));
expect(_test_boolean_check_pass).toBeTruthy()
let _test_boolean_check_warn = fixture.debugElement.query(By.css('#demo\\.visibleIfBinding1b\\.status1b\\.Warn'));
expect(_test_boolean_check_warn).toBeTruthy()
let _test_boolean_check_fail = fixture.debugElement.query(By.css('#demo\\.visibleIfBinding1b\\.status1b\\.Fail'));
expect(_test_boolean_check_fail).toBeTruthy()
let _test_boolean_visible = fixture.debugElement.query(By.css('#demo\\.visibleIfBinding1a\\.visibleComponent1b'));
expect(_test_boolean_visible).toBeNull()
// negative state 'Pass'
_test_boolean_check_pass.nativeElement.checked = true
_test_boolean_check_pass.nativeElement.dispatchEvent(new Event('change'));
fixture.detectChanges();
_test_boolean_visible = fixture.debugElement.query(By.css('#demo\\.visibleIfBinding1b\\.visibleComponent1b'));
expect(_test_boolean_visible).toBeNull()
// positive state 'Warn'
_test_boolean_check_warn.nativeElement.checked = true
_test_boolean_check_warn.nativeElement.dispatchEvent(new Event('change'));
fixture.detectChanges();
_test_boolean_visible = fixture.debugElement.query(By.css('#demo\\.visibleIfBinding1b\\.visibleComponent1b'));
expect(_test_boolean_visible).toBeTruthy()
// negative state 'Pass'
_test_boolean_check_pass.nativeElement.checked = true
_test_boolean_check_pass.nativeElement.dispatchEvent(new Event('change'));
fixture.detectChanges();
_test_boolean_visible = fixture.debugElement.query(By.css('#demo\\.visibleIfBinding1b\\.visibleComponent1b'));
expect(_test_boolean_visible).toBeNull()
// positive state 'Fail'
_test_boolean_check_fail.nativeElement.checked = true
_test_boolean_check_fail.nativeElement.dispatchEvent(new Event('change'));
fixture.detectChanges();
_test_boolean_visible = fixture.debugElement.query(By.css('#demo\\.visibleIfBinding1b\\.visibleComponent1b'));
expect(_test_boolean_visible).toBeTruthy()
});
}));
it(`# 6. Test Boolean 'VisibleIf' with 'allOf' condition (check 'Warn' and 'Fail')`, async(() => {
// Visible component shows up if status 'Warn' and 'Fail' are checked
fixture.whenStable().then(() => {
fixture.detectChanges();
// expect page containing a sf-form element
let sf_form = fixture.debugElement.query(By.css('sf-form'))
expect(sf_form).toBeTruthy()
// initial state
let _test_checkbox_pass = fixture.debugElement.query(By.css('#demo\\.visibleIfBinding2a\\.status2a'));
expect(_test_checkbox_pass).toBeTruthy()
let _test_checkbox_warn = fixture.debugElement.query(By.css('#demo\\.visibleIfBinding2a\\.status2b'));
expect(_test_checkbox_warn).toBeTruthy()
let _test_checkbox_fail = fixture.debugElement.query(By.css('#demo\\.visibleIfBinding2a\\.status2c'));
expect(_test_checkbox_fail).toBeTruthy()
let _test_boolean_visible = fixture.debugElement.query(By.css('#demo\\.visibleIfBinding2a\\.visibleComponent2a'));
expect(_test_boolean_visible).toBeNull()
const visibleComponent = '#demo\\.visibleIfBinding2a\\.visibleComponent2a'
const checkboxes = [
_test_checkbox_pass,
_test_checkbox_warn,
_test_checkbox_fail
]
let combinations = [
// 'Pass', 'Warn', 'Fail', 'Should component show up?'
{ values: [false, false, false], visible: false, emit:false }, // the initial state
{ values: [true, false, false], visible: false, emit:false },
{ values: [false, true, false], visible: false, emit:false },
{ values: [false, false, true], visible: false, emit:false },
{ values: [true, true, false], visible: false, emit:false },
{ values: [true, true, true], visible: true, emit:false },
{ values: [false, true, true], visible: true, emit:false }
]
combinations = combinations.concat(
// same as above but this forces emitting the change event
combinations.map(item => { item.emit = true; return item }))
for (const combination of combinations) {
for (let i = 0; i < combination.values.length; i++) {
if (checkboxes[i].nativeElement.checked !== combination.values[i] || combination.emit) {
checkboxes[i].nativeElement.checked = combination.values[i]
checkboxes[i].nativeElement.dispatchEvent(new Event('change'));
}
fixture.detectChanges();
const _test_boolean_visible_el = fixture.debugElement.query(By.css(visibleComponent));
const errorOut=`Expected visibility ${combination.visible} | emits: ${combination.emit||false} | checked: pass:${combination.values[0]}/native:${checkboxes[0].nativeElement.checked}, warn:${combination.values[1]}/native:${checkboxes[1].nativeElement.checked}, fail:${combination.values[2]}/native:${checkboxes[2].nativeElement.checked}`
if(_test_checkbox_warn.nativeElement.checked && _test_checkbox_fail.nativeElement.checked){
expect(_test_boolean_visible_el).toBeTruthy(errorOut)
} else {
expect(_test_boolean_visible_el).toBeNull(errorOut)
}
}
}
});
}));
it(`# 7. Test String 'VisibleIf' with 'allOf' condition (select 'Warn' and 'Fail')`, async(() => {
// Visible component shows up if status 'Warn' and 'Fail' are checked
fixture.whenStable().then(() => {
fixture.detectChanges();
// expect page containing a sf-form element
let sf_form = fixture.debugElement.query(By.css('sf-form'))
expect(sf_form).toBeTruthy()
// initial state
let _test_select_pass = fixture.debugElement.query(By.css('#demo\\.visibleIfBinding2b\\.status2a'));
expect(_test_select_pass).toBeTruthy()
let _test_select_warn = fixture.debugElement.query(By.css('#demo\\.visibleIfBinding2b\\.status2b'));
expect(_test_select_warn).toBeTruthy()
let _test_select_fail = fixture.debugElement.query(By.css('#demo\\.visibleIfBinding2b\\.status2c'));
expect(_test_select_fail).toBeTruthy()
let _test_select_visible = fixture.debugElement.query(By.css('#demo\\.visibleIfBinding2b\\.visibleComponent2b'));
expect(_test_select_visible).toBeNull()
const visibleComponent = '#demo\\.visibleIfBinding2b\\.visibleComponent2b'
const dropdowns = [
_test_select_pass,
_test_select_warn,
_test_select_fail
]
let combinations = [
// 'Pass', 'Warn', 'Fail', 'Should component show up?'
{ values: ['', '', ''], visible: false, emit:false }, // the initial state
{ values: ['Pass', '', ''], visible: false, emit:false },
{ values: ['', 'Warn', ''], visible: false, emit:false },
{ values: ['', '', 'Fail'], visible: false, emit:false },
{ values: ['', 'Pass', 'Fail'], visible: true, emit:false },
{ values: ['Pass', 'Warn', 'Pass'], visible: true, emit:false },
{ values: ['', 'Warn', 'Fail'], visible: true, emit:false },
{ values: ['Pass', 'Warn', 'Fail'], visible: true, emit:false }
]
combinations = combinations.concat(
// same as above but this forces emitting the change event
combinations.map(item => { item.emit = true; return item }))
for (const combination of combinations) {
for (let i = 0; i < combination.values.length; i++) {
if (dropdowns[i].nativeElement.value !== combination.values[i] || combination.emit) {
dropdowns[i].nativeElement.value = combination.values[i]
dropdowns[i].nativeElement.dispatchEvent(new Event('change'));
}
fixture.detectChanges();
const _test_select_visible_el = fixture.debugElement.query(By.css(visibleComponent));
const errorOut=`Expected visibility ${combination.visible} | emits: ${combination.emit||false} | checked: pass:${combination.values[0]}/native:${dropdowns[0].nativeElement.value}, warn:${combination.values[1]}/native:${dropdowns[1].nativeElement.value}, fail:${combination.values[2]}/native:${dropdowns[2].nativeElement.value}`
if (_test_select_warn.nativeElement.value === 'Warn' && _test_select_fail.nativeElement.value === 'Fail') {
expect(_test_select_visible_el).toBeTruthy(errorOut)
} else {
expect(_test_select_visible_el).toBeNull(errorOut)
}
}
}
});
}));
it(`# 8. Test oneOf - Set age to 15, set last name to 'aaa'`, async(() => {
// Visible component shows up if age is set to 15 and last name to 'aaa'
fixture.whenStable().then(() => {
fixture.detectChanges();
// expect page containing a sf-form element
let sf_form = fixture.debugElement.query(By.css('sf-form'))
expect(sf_form).toBeTruthy()
// initial state
let _test_input_age = fixture.debugElement.query(By.css('#demo\\.updateVisibiltyTest\\.age'));
expect(_test_input_age).toBeTruthy()
let _test_select_lastname = fixture.debugElement.query(By.css('#demo\\.updateVisibiltyTest\\.lastName'));
expect(_test_select_lastname).toBeTruthy()
let _test_visible_component = fixture.debugElement.query(By.css('#demo\\.updateVisibiltyTest\\.firstName'));
expect(_test_visible_component).toBeNull()
let visibleComponent = '#demo\\.updateVisibiltyTest\\.firstName'
let elements = [
_test_input_age,
_test_select_lastname
]
let combinations = [
// 'Pass', 'Warn', 'Fail', 'Should component show up?'
{ values: ['', ''], visible: false, emit:false }, // the initial state
{ values: [0, ''], visible: false, emit:false },
{ values: [0, 'bbb'], visible: false, emit:false },
{ values: [0, 'aaa'], visible: false, emit:false },
{ values: [15, 'aaa'], visible: true, emit:false },
{ values: [15, 'bbb'], visible: false, emit:false },
{ values: [155, 'aaa'], visible: false, emit:false },
]
combinations = combinations.concat(
// same as above but this forces emitting the change event
combinations.map(item => { item.emit = true; return item }))
for (const combination of combinations) {
for (let i = 0; i < combination.values.length; i++) {
if (elements[i].nativeElement.value !== combination.values[i] || combination.emit) {
elements[i].nativeElement.value = combination.values[i]
elements[i].nativeElement.dispatchEvent(new Event('change'));
}
fixture.detectChanges();
const _test_select_visible_el = fixture.debugElement.query(By.css(visibleComponent));
const errorOut=`Expected visibility ${combination.visible} | emits: ${combination.emit||false} | checked: age:${combination.values[0]}/native:${elements[0].nativeElement.value}, firstname:${combination.values[1]}/native:${elements[1].nativeElement.value}`
if (_test_input_age.nativeElement.value === 15 && _test_select_lastname.nativeElement.value === 'aaa') {
expect(_test_select_visible_el).toBeTruthy(errorOut)
} else {
expect(_test_select_visible_el).toBeNull(errorOut)
}
}
}
});
}));
}); | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement } from "../shared";
/**
* Statement provider for service [clouddirectory](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonclouddirectory.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Clouddirectory extends PolicyStatement {
public servicePrefix = 'clouddirectory';
/**
* Statement provider for service [clouddirectory](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonclouddirectory.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);
}
/**
* Adds a new Facet to an object.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_AddFacetToObject.html
*/
public toAddFacetToObject() {
return this.to('AddFacetToObject');
}
/**
* Copies input published schema into Directory with same name and version as that of published schema.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_ApplySchema.html
*/
public toApplySchema() {
return this.to('ApplySchema');
}
/**
* Attaches an existing object to another existing object.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_AttachObject.html
*/
public toAttachObject() {
return this.to('AttachObject');
}
/**
* Attaches a policy object to any other object.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_AttachPolicy.html
*/
public toAttachPolicy() {
return this.to('AttachPolicy');
}
/**
* Attaches the specified object to the specified index.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_AttachToIndex.html
*/
public toAttachToIndex() {
return this.to('AttachToIndex');
}
/**
* Attaches a typed link b/w a source & target object reference.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_AttachTypedLink.html
*/
public toAttachTypedLink() {
return this.to('AttachTypedLink');
}
/**
* Performs all the read operations in a batch. Each individual operation inside BatchRead needs to be granted permissions explicitly.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_BatchRead.html
*/
public toBatchRead() {
return this.to('BatchRead');
}
/**
* Performs all the write operations in a batch. Each individual operation inside BatchWrite needs to be granted permissions explicitly.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_BatchWrite.html
*/
public toBatchWrite() {
return this.to('BatchWrite');
}
/**
* Creates a Directory by copying the published schema into the directory.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_CreateDirectory.html
*/
public toCreateDirectory() {
return this.to('CreateDirectory');
}
/**
* Creates a new Facet in a schema.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_CreateFacet.html
*/
public toCreateFacet() {
return this.to('CreateFacet');
}
/**
* Creates an index object.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_CreateIndex.html
*/
public toCreateIndex() {
return this.to('CreateIndex');
}
/**
* Creates an object in a Directory.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_CreateObject.html
*/
public toCreateObject() {
return this.to('CreateObject');
}
/**
* Creates a new schema in a development state.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_CreateSchema.html
*/
public toCreateSchema() {
return this.to('CreateSchema');
}
/**
* Creates a new Typed Link facet in a schema.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_CreateTypedLinkFacet.html
*/
public toCreateTypedLinkFacet() {
return this.to('CreateTypedLinkFacet');
}
/**
* Deletes a directory. Only disabled directories can be deleted.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_DeleteDirectory.html
*/
public toDeleteDirectory() {
return this.to('DeleteDirectory');
}
/**
* Deletes a given Facet. All attributes and Rules associated with the facet will be deleted.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_DeleteFacet.html
*/
public toDeleteFacet() {
return this.to('DeleteFacet');
}
/**
* Deletes an object and its associated attributes.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_DeleteObject.html
*/
public toDeleteObject() {
return this.to('DeleteObject');
}
/**
* Deletes a given schema.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_DeleteSchema.html
*/
public toDeleteSchema() {
return this.to('DeleteSchema');
}
/**
* Deletes a given TypedLink Facet. All attributes and Rules associated with the facet will be deleted.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_DeleteTypedLinkFacet.html
*/
public toDeleteTypedLinkFacet() {
return this.to('DeleteTypedLinkFacet');
}
/**
* Detaches the specified object from the specified index.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_DetachFromIndex.html
*/
public toDetachFromIndex() {
return this.to('DetachFromIndex');
}
/**
* Detaches a given object from the parent object.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_DetachObject.html
*/
public toDetachObject() {
return this.to('DetachObject');
}
/**
* Detaches a policy from an object.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_DetachPolicy.html
*/
public toDetachPolicy() {
return this.to('DetachPolicy');
}
/**
* Detaches a given typed link b/w given source and target object reference.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_DetachTypedLink.html
*/
public toDetachTypedLink() {
return this.to('DetachTypedLink');
}
/**
* Disables the specified directory.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_DisableDirectory.html
*/
public toDisableDirectory() {
return this.to('DisableDirectory');
}
/**
* Enables the specified directory.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_EnableDirectory.html
*/
public toEnableDirectory() {
return this.to('EnableDirectory');
}
/**
* Retrieves metadata about a directory.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_GetDirectory.html
*/
public toGetDirectory() {
return this.to('GetDirectory');
}
/**
* Gets details of the Facet, such as Facet Name, Attributes, Rules, or ObjectType.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_GetFacet.html
*/
public toGetFacet() {
return this.to('GetFacet');
}
/**
* Retrieves attributes that are associated with a typed link.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_GetLinkAttributes.html
*/
public toGetLinkAttributes() {
return this.to('GetLinkAttributes');
}
/**
* Retrieves attributes within a facet that are associated with an object.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_GetObjectAttributes.html
*/
public toGetObjectAttributes() {
return this.to('GetObjectAttributes');
}
/**
* Retrieves metadata about an object.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_GetObjectInformation.html
*/
public toGetObjectInformation() {
return this.to('GetObjectInformation');
}
/**
* Retrieves a JSON representation of the schema.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_GetSchemaAsJson.html
*/
public toGetSchemaAsJson() {
return this.to('GetSchemaAsJson');
}
/**
* Returns identity attributes order information associated with a given typed link facet.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_GetTypedLinkFacetInformation.html
*/
public toGetTypedLinkFacetInformation() {
return this.to('GetTypedLinkFacetInformation');
}
/**
* Lists schemas applied to a directory.
*
* Access Level: List
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_ListAppliedSchemaArns.html
*/
public toListAppliedSchemaArns() {
return this.to('ListAppliedSchemaArns');
}
/**
* Lists indices attached to an object.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_ListAttachedIndices.html
*/
public toListAttachedIndices() {
return this.to('ListAttachedIndices');
}
/**
* Retrieves the ARNs of schemas in the development state.
*
* Access Level: List
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_ListDevelopmentSchemaArns.html
*/
public toListDevelopmentSchemaArns() {
return this.to('ListDevelopmentSchemaArns');
}
/**
* Lists directories created within an account.
*
* Access Level: List
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_ListDirectories.html
*/
public toListDirectories() {
return this.to('ListDirectories');
}
/**
* Retrieves attributes attached to the facet.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_ListFacetAttributes.html
*/
public toListFacetAttributes() {
return this.to('ListFacetAttributes');
}
/**
* Retrieves the names of facets that exist in a schema.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_ListFacetNames.html
*/
public toListFacetNames() {
return this.to('ListFacetNames');
}
/**
* Returns a paginated list of all incoming TypedLinks for a given object.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_ListIncomingTypedLinks.html
*/
public toListIncomingTypedLinks() {
return this.to('ListIncomingTypedLinks');
}
/**
* Lists objects attached to the specified index.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_ListIndex.html
*/
public toListIndex() {
return this.to('ListIndex');
}
/**
* Lists the major version families of each managed schema. If a major version ARN is provided as SchemaArn, the minor version revisions in that family are listed instead.
*
* Access Level: List
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_ListManagedSchemaArns.html
*/
public toListManagedSchemaArns() {
return this.to('ListManagedSchemaArns');
}
/**
* Lists all attributes associated with an object.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_ListObjectAttributes.html
*/
public toListObjectAttributes() {
return this.to('ListObjectAttributes');
}
/**
* Returns a paginated list of child objects associated with a given object.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_ListObjectChildren.html
*/
public toListObjectChildren() {
return this.to('ListObjectChildren');
}
/**
* Retrieves all available parent paths for any object type such as node, leaf node, policy node, and index node objects.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_ListObjectParentPaths.html
*/
public toListObjectParentPaths() {
return this.to('ListObjectParentPaths');
}
/**
* Lists parent objects associated with a given object in pagination fashion.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_ListObjectParents.html
*/
public toListObjectParents() {
return this.to('ListObjectParents');
}
/**
* Returns policies attached to an object in pagination fashion.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_ListObjectPolicies.html
*/
public toListObjectPolicies() {
return this.to('ListObjectPolicies');
}
/**
* Returns a paginated list of all outgoing TypedLinks for a given object.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_ListOutgoingTypedLinks.html
*/
public toListOutgoingTypedLinks() {
return this.to('ListOutgoingTypedLinks');
}
/**
* Returns all of the ObjectIdentifiers to which a given policy is attached.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_ListPolicyAttachments.html
*/
public toListPolicyAttachments() {
return this.to('ListPolicyAttachments');
}
/**
* Retrieves published schema ARNs.
*
* Access Level: List
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_ListPublishedSchemaArns.html
*/
public toListPublishedSchemaArns() {
return this.to('ListPublishedSchemaArns');
}
/**
* Returns tags for a resource.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_ListTagsForResource.html
*/
public toListTagsForResource() {
return this.to('ListTagsForResource');
}
/**
* Returns a paginated list of attributes associated with typed link facet.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_ListTypedLinkFacetAttributes.html
*/
public toListTypedLinkFacetAttributes() {
return this.to('ListTypedLinkFacetAttributes');
}
/**
* Returns a paginated list of typed link facet names that exist in a schema.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_ListTypedLinkFacetNames.html
*/
public toListTypedLinkFacetNames() {
return this.to('ListTypedLinkFacetNames');
}
/**
* Lists all policies from the root of the Directory to the object specified.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_LookupPolicy.html
*/
public toLookupPolicy() {
return this.to('LookupPolicy');
}
/**
* Publishes a development schema with a version.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_PublishSchema.html
*/
public toPublishSchema() {
return this.to('PublishSchema');
}
/**
* Allows a schema to be updated using JSON upload. Only available for development schemas.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_PutSchemaFromJson.html
*/
public toPutSchemaFromJson() {
return this.to('PutSchemaFromJson');
}
/**
* Removes the specified facet from the specified object.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_RemoveFacetFromObject.html
*/
public toRemoveFacetFromObject() {
return this.to('RemoveFacetFromObject');
}
/**
* Adds tags to a resource.
*
* Access Level: Tagging
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_TagResource.html
*/
public toTagResource() {
return this.to('TagResource');
}
/**
* Removes tags from a resource.
*
* Access Level: Tagging
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_UntagResource.html
*/
public toUntagResource() {
return this.to('UntagResource');
}
/**
* Adds/Updates/Deletes existing Attributes, Rules, or ObjectType of a Facet.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_UpdateFacet.html
*/
public toUpdateFacet() {
return this.to('UpdateFacet');
}
/**
* Updates a given typed link’s attributes. Attributes to be updated must not contribute to the typed link’s identity, as defined by its IdentityAttributeOrder.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_UpdateLinkAttributes.html
*/
public toUpdateLinkAttributes() {
return this.to('UpdateLinkAttributes');
}
/**
* Updates a given object's attributes.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_UpdateObjectAttributes.html
*/
public toUpdateObjectAttributes() {
return this.to('UpdateObjectAttributes');
}
/**
* Updates the schema name with a new name.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_UpdateSchema.html
*/
public toUpdateSchema() {
return this.to('UpdateSchema');
}
/**
* Adds/Updates/Deletes existing Attributes, Rules, identity attribute order of a TypedLink Facet.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/directoryservice/latest/APIReference/API_UpdateTypedLinkFacet.html
*/
public toUpdateTypedLinkFacet() {
return this.to('UpdateTypedLinkFacet');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"AddFacetToObject",
"ApplySchema",
"AttachObject",
"AttachPolicy",
"AttachToIndex",
"AttachTypedLink",
"BatchWrite",
"CreateDirectory",
"CreateFacet",
"CreateIndex",
"CreateObject",
"CreateSchema",
"CreateTypedLinkFacet",
"DeleteDirectory",
"DeleteFacet",
"DeleteObject",
"DeleteSchema",
"DeleteTypedLinkFacet",
"DetachFromIndex",
"DetachObject",
"DetachPolicy",
"DetachTypedLink",
"DisableDirectory",
"EnableDirectory",
"PublishSchema",
"PutSchemaFromJson",
"RemoveFacetFromObject",
"UpdateFacet",
"UpdateLinkAttributes",
"UpdateObjectAttributes",
"UpdateSchema",
"UpdateTypedLinkFacet"
],
"Read": [
"BatchRead",
"GetDirectory",
"GetFacet",
"GetLinkAttributes",
"GetObjectAttributes",
"GetObjectInformation",
"GetSchemaAsJson",
"GetTypedLinkFacetInformation",
"ListAttachedIndices",
"ListFacetAttributes",
"ListFacetNames",
"ListIncomingTypedLinks",
"ListIndex",
"ListObjectAttributes",
"ListObjectChildren",
"ListObjectParentPaths",
"ListObjectParents",
"ListObjectPolicies",
"ListOutgoingTypedLinks",
"ListPolicyAttachments",
"ListTagsForResource",
"ListTypedLinkFacetAttributes",
"ListTypedLinkFacetNames",
"LookupPolicy"
],
"List": [
"ListAppliedSchemaArns",
"ListDevelopmentSchemaArns",
"ListDirectories",
"ListManagedSchemaArns",
"ListPublishedSchemaArns"
],
"Tagging": [
"TagResource",
"UntagResource"
]
};
/**
* Adds a resource of type appliedSchema to the statement
*
* https://docs.aws.amazon.com/directoryservice/latest/admin-guide/cd_key_concepts.html#whatisdirectory
*
* @param directoryId - Identifier for the directoryId.
* @param schemaName - Identifier for the schemaName.
* @param version - Identifier for the version.
* @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`.
*/
public onAppliedSchema(directoryId: string, schemaName: string, version: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:clouddirectory:${Region}:${Account}:directory/${DirectoryId}/schema/${SchemaName}/${Version}';
arn = arn.replace('${DirectoryId}', directoryId);
arn = arn.replace('${SchemaName}', schemaName);
arn = arn.replace('${Version}', version);
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 developmentSchema to the statement
*
* https://docs.aws.amazon.com/directoryservice/latest/admin-guide/cd_key_concepts.html#whatisdirectory
*
* @param schemaName - Identifier for the schemaName.
* @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`.
*/
public onDevelopmentSchema(schemaName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:clouddirectory:${Region}:${Account}:schema/development/${SchemaName}';
arn = arn.replace('${SchemaName}', schemaName);
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 directory to the statement
*
* https://docs.aws.amazon.com/directoryservice/latest/admin-guide/cd_key_concepts.html#whatisdirectory
*
* @param directoryId - Identifier for the directoryId.
* @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`.
*/
public onDirectory(directoryId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:clouddirectory:${Region}:${Account}:directory/${DirectoryId}';
arn = arn.replace('${DirectoryId}', directoryId);
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 publishedSchema to the statement
*
* https://docs.aws.amazon.com/directoryservice/latest/admin-guide/cd_key_concepts.html#whatisdirectory
*
* @param schemaName - Identifier for the schemaName.
* @param version - Identifier for the version.
* @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`.
*/
public onPublishedSchema(schemaName: string, version: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:clouddirectory:${Region}:${Account}:schema/published/${SchemaName}/${Version}';
arn = arn.replace('${SchemaName}', schemaName);
arn = arn.replace('${Version}', version);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
} | the_stack |
import {
UnformattedClosureCodeBlock,
TokenType,
UnformattedSyntaxTree,
UnformattedNonGremlinSyntaxTree,
} from '../types';
import { last, neq, pipe } from '../utils';
import { extractGremlinQueries } from './extractGremlinQueries';
const tokenizeOnTopLevelPunctuation = (query: string): string[] => {
let word = '';
let parenthesesCount = 0;
let squareBracketCount = 0;
let curlyBracketCount = 0;
let isInsideSingleQuoteString = false;
query.split('').forEach((char) => {
if (char === '(' && !isInsideSingleQuoteString) {
parenthesesCount++;
word += '(';
return;
}
if (char === '[' && !isInsideSingleQuoteString) {
squareBracketCount++;
word += '[';
return;
}
if (char === '{' && !isInsideSingleQuoteString) {
curlyBracketCount++;
word += '{';
return;
}
if (char === ')' && !isInsideSingleQuoteString) {
parenthesesCount--;
word += ')';
return;
}
if (char === ']' && !isInsideSingleQuoteString) {
squareBracketCount--;
word += ']';
return;
}
if (char === '}' && !isInsideSingleQuoteString) {
curlyBracketCount--;
word += '}';
return;
}
if (char === "'") {
isInsideSingleQuoteString = !isInsideSingleQuoteString;
word += "'";
return;
}
if (char === '.') {
word +=
isInsideSingleQuoteString || parenthesesCount || squareBracketCount || curlyBracketCount
? '.'
: String.fromCharCode(28);
return;
}
word += char;
});
return word
.split(String.fromCharCode(28))
.filter((token) => token !== '')
.map((token) => token.trim());
};
const tokenizeOnTopLevelComma = (query: string): string[] => {
let word = '';
let parenthesesCount = 0;
let squareBracketsCount = 0;
let curlyBracketsCount = 0;
let isInsideSingleQuoteString = false;
query.split('').forEach((char) => {
if (char === '(' && !isInsideSingleQuoteString) {
parenthesesCount++;
word += '(';
return;
}
if (char === '[' && !isInsideSingleQuoteString) {
squareBracketsCount++;
word += '[';
return;
}
if (char === '{' && !isInsideSingleQuoteString) {
curlyBracketsCount++;
word += '{';
return;
}
if (char === ')' && !isInsideSingleQuoteString) {
parenthesesCount--;
word += ')';
return;
}
if (char === ']' && !isInsideSingleQuoteString) {
squareBracketsCount--;
word += ']';
return;
}
if (char === '}' && !isInsideSingleQuoteString) {
curlyBracketsCount--;
word += '}';
return;
}
if (char === "'") {
isInsideSingleQuoteString = !isInsideSingleQuoteString;
word += "'";
return;
}
if (char === ',') {
word +=
isInsideSingleQuoteString || parenthesesCount || squareBracketsCount || curlyBracketsCount
? ','
: String.fromCharCode(28);
return;
}
word += char;
});
return word
.split(String.fromCharCode(28))
.filter((token) => token !== '')
.map((token) => token.trim());
};
const tokenizeOnTopLevelParentheses = (query: string): string[] => {
let word = '';
let parenthesesCount = 0;
let squareBracketsCount = 0;
let curlyBracketsCount = 0;
let isInsideSingleQuoteString = false;
query.split('').forEach((char) => {
if (char === '(' && !isInsideSingleQuoteString) {
if (parenthesesCount === 0) {
word += String.fromCharCode(28);
}
parenthesesCount++;
word += '(';
return;
}
if (char === '[' && !isInsideSingleQuoteString) {
squareBracketsCount++;
word += '[';
return;
}
if (char === '{' && !isInsideSingleQuoteString) {
curlyBracketsCount++;
word += '{';
return;
}
if (char === ')' && !isInsideSingleQuoteString) {
parenthesesCount--;
word += ')';
return;
}
if (char === ']' && !isInsideSingleQuoteString) {
squareBracketsCount--;
word += ']';
return;
}
if (char === '}' && !isInsideSingleQuoteString) {
curlyBracketsCount--;
word += '}';
return;
}
if (char === "'") {
isInsideSingleQuoteString = !isInsideSingleQuoteString;
word += "'";
return;
}
word += char;
});
return word
.split(String.fromCharCode(28))
.filter((token) => token !== '')
.map((token) => token.trim());
};
const tokenizeOnTopLevelCurlyBrackets = (query: string): string[] => {
let word = '';
let parenthesesCount = 0;
let squareBracketsCount = 0;
let curlyBracketsCount = 0;
let isInsideSingleQuoteString = false;
query.split('').forEach((char) => {
if (char === '(' && !isInsideSingleQuoteString) {
parenthesesCount++;
word += '(';
return;
}
if (char === '[' && !isInsideSingleQuoteString) {
squareBracketsCount++;
word += '[';
return;
}
if (char === '{' && !isInsideSingleQuoteString) {
if (curlyBracketsCount === 0) {
word += String.fromCharCode(28);
}
curlyBracketsCount++;
word += '{';
return;
}
if (char === ')' && !isInsideSingleQuoteString) {
parenthesesCount--;
word += ')';
return;
}
if (char === ']' && !isInsideSingleQuoteString) {
squareBracketsCount--;
word += ']';
return;
}
if (char === '}' && !isInsideSingleQuoteString) {
curlyBracketsCount--;
word += '}';
return;
}
if (char === "'") {
isInsideSingleQuoteString = !isInsideSingleQuoteString;
word += "'";
return;
}
word += char;
});
return word
.split(String.fromCharCode(28))
.filter((token) => token !== '')
.map((token) => token.trim());
};
const isWrappedInParentheses = (token: string): boolean => {
if (token.length < 2) return false;
if (token.charAt(0) !== '(') return false;
if (token.slice(-1) !== ')') return false;
return true;
};
const isWrappedInCurlyBrackets = (token: string): boolean => {
if (token.length < 2) return false;
if (token.charAt(0) !== '{') return false;
if (token.slice(-1) !== '}') return false;
return true;
};
const isString = (token: string): boolean => {
if (token.length < 2) return false;
if (token.charAt(0) !== token.substr(-1)) return false;
if (['"', "'"].includes(token.charAt(0))) return true;
return false;
};
const isMethodInvocation = (token: string): boolean => {
return pipe(tokenizeOnTopLevelParentheses, last, isWrappedInParentheses)(token);
};
const isClosureInvocation = (token: string): boolean => {
return pipe(tokenizeOnTopLevelCurlyBrackets, last, isWrappedInCurlyBrackets)(token);
};
const trimParentheses = (expression: string): string => expression.slice(1, -1);
const trimCurlyBrackets = (expression: string): string => expression.slice(1, -1);
const getMethodTokenAndArgumentTokensFromMethodInvocation = (
token: string,
): { methodToken: string; argumentTokens: string[] } => {
// The word before the first parenthesis is the method name
// The token may be a double application of a curried function, so we cannot
// assume that the first opening parenthesis is closed by the last closing
// parenthesis
const tokens = tokenizeOnTopLevelParentheses(token);
return {
methodToken: tokens.slice(0, -1).join(''),
argumentTokens: pipe(trimParentheses, tokenizeOnTopLevelComma)(tokens.slice(-1)[0]),
};
};
const getIndentation = (lineOfCode: string): number => lineOfCode.split('').findIndex(neq(' '));
const getMethodTokenAndClosureCodeBlockFromClosureInvocation = (
token: string,
fullQuery: string,
): { methodToken: string; closureCodeBlock: UnformattedClosureCodeBlock } => {
// The word before the first curly bracket is the method name
// The token may be a double application of a curried function, so we cannot
// assume that the first opening curly bracket is closed by the last closing
// curly bracket
const tokens = tokenizeOnTopLevelCurlyBrackets(token);
const methodToken = tokens.slice(0, -1).join('');
const closureCodeBlockToken = trimCurlyBrackets(tokens.slice(-1)[0]);
const initialClosureCodeBlockIndentation = fullQuery
.substr(0, fullQuery.indexOf(closureCodeBlockToken))
.split('\n')
.slice(-1)[0].length;
return {
methodToken,
closureCodeBlock: trimCurlyBrackets(tokens.slice(-1)[0])
.split('\n')
.map((lineOfCode, i) => ({
lineOfCode: lineOfCode.trimStart(),
relativeIndentation:
i === 0 ? getIndentation(lineOfCode) : getIndentation(lineOfCode) - initialClosureCodeBlockIndentation,
})),
};
};
const parseCodeBlockToSyntaxTree = (fullCode: string, shouldCalculateInitialHorizontalPosition?: boolean) => (
codeBlock: string,
): UnformattedSyntaxTree => {
const tokens = tokenizeOnTopLevelPunctuation(codeBlock);
if (tokens.length === 1) {
const token = tokens[0];
if (isMethodInvocation(token)) {
const { methodToken, argumentTokens } = getMethodTokenAndArgumentTokensFromMethodInvocation(token);
return {
type: TokenType.Method,
method: parseCodeBlockToSyntaxTree(fullCode)(methodToken),
arguments: argumentTokens.map(parseCodeBlockToSyntaxTree(fullCode)),
};
}
if (isClosureInvocation(token)) {
const { methodToken, closureCodeBlock } = getMethodTokenAndClosureCodeBlockFromClosureInvocation(token, fullCode);
return {
type: TokenType.Closure,
method: parseCodeBlockToSyntaxTree(fullCode)(methodToken),
closureCodeBlock,
};
}
if (isString(token)) {
return {
type: TokenType.String,
string: token,
};
}
return {
type: TokenType.Word,
word: token,
};
}
return {
type: TokenType.Traversal,
steps: tokens.map(parseCodeBlockToSyntaxTree(fullCode)),
initialHorizontalPosition: shouldCalculateInitialHorizontalPosition
? fullCode.substr(0, fullCode.indexOf(codeBlock)).split('\n').slice(-1)[0].length
: 0,
};
};
export const parseNonGremlinCodeToSyntaxTree = (code: string): UnformattedNonGremlinSyntaxTree => ({
type: TokenType.NonGremlinCode,
code,
});
export const parseToSyntaxTrees = (code: string): UnformattedSyntaxTree[] => {
const queries = extractGremlinQueries(code);
const { syntaxTrees, remainingCode } = queries.reduce(
(state, query: string): { syntaxTrees: UnformattedSyntaxTree[]; remainingCode: string } => {
const indexOfQuery = state.remainingCode.indexOf(query);
const nonGremlinCode = state.remainingCode.substr(0, indexOfQuery);
return {
syntaxTrees: [
...state.syntaxTrees,
parseNonGremlinCodeToSyntaxTree(nonGremlinCode),
parseCodeBlockToSyntaxTree(code, true)(query),
],
remainingCode: state.remainingCode.substr(indexOfQuery + query.length),
};
},
{ syntaxTrees: [] as UnformattedSyntaxTree[], remainingCode: code },
);
if (!remainingCode) return syntaxTrees;
return [...syntaxTrees, parseNonGremlinCodeToSyntaxTree(remainingCode)];
}; | the_stack |
import React, { useCallback, useMemo } from "react";
import { useDispatch } from "react-redux";
import { Integration } from "state/integration/types";
import { makePrometheusDashboardRequests } from "./dashboards";
import { useSimpleNotification } from "client/services/Notification";
import * as grafana from "client/utils/grafana";
import { updateGrafanaStateForIntegration } from "state/integration/actions";
import DownloadConfigButton from "client/integrations/common/DownloadConfigButton";
import { ViewConfigDialogBtn } from "client/integrations/common/ViewConfigDialogBtn";
import { getConfigFileName } from "client/integrations/configUtils";
import { Box } from "client/components/Box";
import { Button } from "client/components/Button";
import { Card, CardContent, CardHeader } from "client/components/Card";
import { CopyToClipboardIcon } from "client/components/CopyToClipboard";
import { Typography } from "client/components/Typography";
import Timeline from "@material-ui/lab/Timeline";
import TimelineItem from "@material-ui/lab/TimelineItem";
import TimelineSeparator from "@material-ui/lab/TimelineSeparator";
import TimelineConnector from "@material-ui/lab/TimelineConnector";
import TimelineContent from "@material-ui/lab/TimelineContent";
import TimelineDot from "@material-ui/lab/TimelineDot";
import styled from "styled-components";
import { Tenant } from "state/tenant/types";
const TimelineDotWrapper = styled(TimelineDot)`
padding-left: 10px;
padding-right: 10px;
`;
const TimelineWrapper = styled(Timeline)`
.MuiTimelineItem-missingOppositeContent:before {
flex: 0;
padding: 0;
}
`;
type InstallInstructionsProps = {
tenant: Tenant;
integration: Integration;
isDashboardInstalled: boolean;
config: string;
};
export const InstallInstructions = ({
integration,
tenant,
isDashboardInstalled,
config
}: InstallInstructionsProps) => {
const dispatch = useDispatch();
const { registerNotification } = useSimpleNotification();
const notifyError = useCallback(
(title: string, message: string) => {
registerNotification({
state: "error" as const,
title,
information: message
});
},
[registerNotification]
);
const configFilename =
integration.data.mode === "k8s"
? getConfigFileName(tenant, integration)
: getConfigFileName(tenant, integration) + ".tmpl";
const [
step2Instructions,
step3Instructions,
step4Instructions,
dashboardStepIndex
] = useMemo(() => {
if (integration.data.mode === "k8s") {
const deployCommand = `sed "s/__AUTH_TOKEN__/$(cat tenant-api-token-${tenant.name})/g" ${configFilename} | kubectl apply -f -`;
return [
<Box flexGrow={1} pb={2}>
{`Run this command to install the metrics agent to your cluster in the ${integration.data.k8s.deployNamespace} namespace`}
<Box pl={2}>
<code>{deployCommand}</code>
<CopyToClipboardIcon text={deployCommand} />
</Box>
</Box>,
null,
null,
3
];
} else {
const renderedConfigFilename = `opstrace-${tenant.name}-integration-${integration.kind}.yaml`;
const cockroachStatusCommand = integration.data.insecure
? "cockroach node status --format records --insecure"
: "cockroach node status --format records --certs-dir MY_CRDB_CERT_DIR";
const nodesCommand = `NODES=$(${cockroachStatusCommand} | grep sql_address | awk '{print $3}' | sed 's/:.*/:8080/g' | tr '\\n' ','); echo $NODES`;
const renderCommand = `sed "s/__AUTH_TOKEN__/$(cat tenant-api-token-${tenant.name})/g" ${configFilename} | sed "s/__NODE_ADDRESSES__/$NODES/g" > ${renderedConfigFilename}`;
const agentCommand = `./agent-linux-amd64 -log.level=debug -config.file=${renderedConfigFilename}`;
return [
<Box flexGrow={1} pb={2}>
Run this command to determine where your nodes are running, editing
the command as necessary to point to the{" "}
{integration.data.insecure || "certificates directory and"} node HTTP
port (default <code>8080</code>)
<Box pl={2}>
<code>{nodesCommand}</code>
<CopyToClipboardIcon text={nodesCommand} />
</Box>
</Box>,
<Box flexGrow={1} pb={2}>
{`Run this command to populate the downloaded config file with the "${tenant.name}" Tenant api key and the node endpoints`}
<Box pl={2}>
<code>{renderCommand}</code>
<CopyToClipboardIcon text={renderCommand} />
</Box>
</Box>,
<Box flexGrow={1} pb={2}>
<Typography>
<a href="https://github.com/grafana/agent/releases/">Download</a>{" "}
and{" "}
<a href="https://grafana.com/docs/grafana-cloud/agent/agent_as_service/">
run
</a>{" "}
grafana-agent with the populated config on a machine that can reach
Cockroach
</Typography>
<Box pl={2}>
<code>{agentCommand}</code>
<CopyToClipboardIcon text={agentCommand} />
</Box>
</Box>,
5
];
}
}, [tenant.name, integration.data, integration.kind, configFilename]);
const dashboardHandler = async () => {
let folder;
try {
folder = await grafana.createFolder({ integration, tenant });
} catch (error: any) {
notifyError(
`Could not create grafana dashboard folder for integration ${integration.name}`,
error.response.data.message ?? error.message
);
return;
}
for (const d of makePrometheusDashboardRequests({
integrationId: integration.id,
folderId: folder.id
})) {
try {
await grafana.createDashboard(tenant, d);
} catch (error: any) {
/*
Errors are usually communicated as a JSON in a list.
For example:
[
{ "fieldNames": [ "Dashboard" ], "classification": "RequiredError", "message": "Required" }
]
There might be ways to derrive better, human readable error messages, but for now we're
just showing the error JSON.
*/
const errorMessageList = Array.isArray(error.response.data)
? error.response.data.map((errObj: Object) => JSON.stringify(errObj))
: [error.message];
for (const message of errorMessageList) {
notifyError(
`Could not create grafana dashboard ${d.uid} for integration ${integration.name}`,
message
);
}
return;
}
}
dispatch(
updateGrafanaStateForIntegration({
id: integration.id,
grafana: { folder }
})
);
};
return (
<Box width="100%" height="100%" p={1}>
<Card>
<CardHeader
titleTypographyProps={{ variant: "h5" }}
title="Install Instructions"
/>
<CardContent>
<TimelineWrapper>
<TimelineItem>
<TimelineSeparator>
<TimelineDotWrapper variant="outlined" color="primary">
1
</TimelineDotWrapper>
<TimelineConnector />
</TimelineSeparator>
<TimelineContent>
<Box flexGrow={1} pb={2}>
{`Download the generated config YAML and save to the same
location as the api key for Tenant "${tenant.name}", it should be called "tenant-api-token-${tenant.name}".`}
<Box pt={1}>
<DownloadConfigButton
filename={configFilename}
config={config}
>
Download YAML
</DownloadConfigButton>
<ViewConfigDialogBtn
filename={configFilename}
config={config}
/>
</Box>
</Box>
</TimelineContent>
</TimelineItem>
<TimelineItem>
<TimelineSeparator>
<TimelineDotWrapper variant="outlined" color="primary">
2
</TimelineDotWrapper>
<TimelineConnector />
</TimelineSeparator>
<TimelineContent>{step2Instructions}</TimelineContent>
</TimelineItem>
{step3Instructions && (
<TimelineItem>
<TimelineSeparator>
<TimelineDotWrapper variant="outlined" color="primary">
3
</TimelineDotWrapper>
<TimelineConnector />
</TimelineSeparator>
<TimelineContent>
<Box flexGrow={1} pb={2}>
{step3Instructions}
</Box>
</TimelineContent>
</TimelineItem>
)}
{step4Instructions && (
<TimelineItem>
<TimelineSeparator>
<TimelineDotWrapper variant="outlined" color="primary">
4
</TimelineDotWrapper>
<TimelineConnector />
</TimelineSeparator>
<TimelineContent>
<Box flexGrow={1} pb={2}>
{step4Instructions}
</Box>
</TimelineContent>
</TimelineItem>
)}
<TimelineItem>
<TimelineSeparator>
<TimelineDotWrapper variant="outlined" color="primary">
{dashboardStepIndex}
</TimelineDotWrapper>
</TimelineSeparator>
<TimelineContent>
<Box flexGrow={1} pb={2}>
Install Dashboards for this Integration.
<br />
<Button
variant="contained"
size="small"
state="primary"
disabled={isDashboardInstalled}
onClick={dashboardHandler}
>
Install Dashboards
</Button>
</Box>
</TimelineContent>
</TimelineItem>
</TimelineWrapper>
</CardContent>
</Card>
</Box>
);
}; | the_stack |
import { StepRow } from '../../../components/Timeline/VirtualizedTimeline';
import {
createRowDataModel,
createStepRow,
createStepRowData,
createTask,
createTaskListSettings,
createTaskRow,
} from '../../../utils/testhelper';
import {
getTaskFromList,
getTaskPageLink,
makeVisibleRows,
shouldApplySearchFilter,
getRowStartTime,
getRowFinishedTime,
taskDuration,
sortRows,
} from '../Run.utils';
describe('Run utils test set', () => {
it('getTaskPageLink', () => {
// with previous task info and no params
expect(getTaskPageLink('flow', 'run', 'prevStep', 'prevTask', '', {})).to.equal('/flow/run/prevStep/prevTask');
// with previous task info and some params
expect(getTaskPageLink('flow', 'run', 'prevStep', 'prevTask', 'status=completed', {})).to.equal(
'/flow/run/prevStep/prevTask?status=completed',
);
// without previous task info and no task rows
expect(getTaskPageLink('flow', 'run', undefined, undefined, '', {})).to.equal('/flow/run/view/task');
// without previous task info and with task rows
expect(getTaskPageLink('flow', 'run', undefined, undefined, '', createRowDataModel({}))).to.equal(
'/flow/run/start/1',
);
// without previous task info and with task rows and with params
expect(getTaskPageLink('flow', 'run', undefined, undefined, 'status=ok', createRowDataModel({}))).to.equal(
'/flow/run/start/1?status=ok',
);
});
it('getTaskFromList', () => {
expect(getTaskFromList({}, undefined, undefined)).to.equal(null);
expect(getTaskFromList({}, 'undefined', 'undefined')).to.equal(null);
const model = createRowDataModel({});
expect(getTaskFromList(model, 'start', '1')).to.equal(model.start.data['1']);
});
});
describe('Run utils - Row making test set', () => {
it('makeVisibleRows - Most basic settings', () => {
const model = createRowDataModel({});
const graph = createTaskListSettings({});
const visibleSteps = ['start'];
const searchResult = { status: 'NotAsked' as const, result: [] };
const rows = makeVisibleRows(model, graph, visibleSteps, searchResult);
// Expected result is 2 since there is 1 step and 1 task
expect(rows.length).to.equal(2);
});
it('makeVisibleRows - Step filtered by visibleSteps', () => {
const model = createRowDataModel({ end: createStepRowData({}, { step_name: 'end' }, {}) });
const graph = createTaskListSettings({});
const visibleSteps = ['start'];
const searchResult = { status: 'NotAsked' as const, result: [] };
const rows = makeVisibleRows(model, graph, visibleSteps, searchResult);
// Expected result is 2 since end step and its tasks are filtered by visible steps
expect(rows.length).to.equal(2);
});
it('makeVisibleRows - Multiple steps', () => {
const model = createRowDataModel({ end: createStepRowData({}, { step_name: 'end' }, {}) });
const graph = createTaskListSettings({});
const visibleSteps = ['start', 'end'];
const searchResult = { status: 'NotAsked' as const, result: [] };
const rows = makeVisibleRows(model, graph, visibleSteps, searchResult);
// Expected result is 4 since there is 2 steps with 1 tasks each
expect(rows.length).to.equal(4);
});
it('makeVisibleRows - Multiple steps with one step closed', () => {
const model = createRowDataModel({ end: createStepRowData({ isOpen: false }, { step_name: 'end' }, {}) });
const graph = createTaskListSettings({});
const visibleSteps = ['start', 'end'];
const searchResult = { status: 'NotAsked' as const, result: [] };
const rows = makeVisibleRows(model, graph, visibleSteps, searchResult);
// Expected result is 3 since there is 2 steps with 1 tasks each but end step is closed
expect(rows.length).to.equal(3);
});
it('makeVisibleRows - With grouping off', () => {
const model = createRowDataModel({ end: createStepRowData({}, { step_name: 'end' }, {}) });
const graph = createTaskListSettings({ group: false });
const visibleSteps = ['start', 'end'];
const searchResult = { status: 'NotAsked' as const, result: [] };
const rows = makeVisibleRows(model, graph, visibleSteps, searchResult);
// Expected result is 2 since there is 2 steps with 1 tasks each but grouping is off so steps are filtered out
expect(rows.length).to.equal(2);
});
it('makeVisibleRows - With search results loading', () => {
const model = createRowDataModel({});
const graph = createTaskListSettings({ group: false });
const visibleSteps = ['start', 'end'];
const searchResult = { status: 'Loading' as const, result: [] };
const rows = makeVisibleRows(model, graph, visibleSteps, searchResult);
// Expected result is 0 since we are still searching for search results
expect(rows.length).to.equal(0);
});
it('makeVisibleRows - With search results ok', () => {
const model = createRowDataModel({
end: createStepRowData({ data: { 2: [createTask({ task_id: 2 })] } }, { step_name: 'end' }, {}),
});
const graph = createTaskListSettings({});
const visibleSteps = ['start', 'end'];
const searchResult = {
status: 'Ok' as const,
result: [
{
flow_id: 'BasicFlow',
run_number: '1',
searchable: true,
step_name: 'start',
task_id: '1',
},
],
};
const rows = makeVisibleRows(model, graph, visibleSteps, searchResult);
// Expected result is 3 since search result includes item from start tasks -> Return two steps (one having no tasks) and a task
expect(rows.length).to.equal(3);
expect((rows[0] as StepRow).rowObject.tasksTotal).to.equal(1);
expect((rows[0] as StepRow).rowObject.tasksVisible).to.equal(1);
expect(rows[1].type).to.equal('task');
expect((rows[2] as StepRow).rowObject.tasksTotal).to.equal(1);
expect((rows[2] as StepRow).rowObject.tasksVisible).to.equal(0);
});
it('makeVisibleRows - status filter, no results', () => {
const model = createRowDataModel({});
const graph = createTaskListSettings({ statusFilter: 'running' });
const visibleSteps = ['start'];
const searchResult = { status: 'NotAsked' as const, result: [] };
const rows = makeVisibleRows(model, graph, visibleSteps, searchResult);
// Expected result is 1 since there's single step but no visible tasks due to filter. Returning one step with no tasks
expect(rows.length).to.equal(1);
expect((rows[0] as StepRow).rowObject.tasksTotal).to.equal(1);
expect((rows[0] as StepRow).rowObject.tasksVisible).to.equal(0);
});
it('makeVisibleRows - status filter, has results', () => {
const model = createRowDataModel({
end: createStepRowData(
{ data: { 2: [createTask({ task_id: 2, status: 'running' })] } },
{ step_name: 'end' },
{},
),
});
const graph = createTaskListSettings({ statusFilter: 'running' });
const visibleSteps = ['start', 'end'];
const searchResult = { status: 'NotAsked' as const, result: [] };
const rows = makeVisibleRows(model, graph, visibleSteps, searchResult);
// Expected result is 3 since there are two steps but only one of them has visible task. Returning two steps and one task
expect(rows.length).to.equal(3);
expect((rows[0] as StepRow).rowObject.tasksTotal).to.equal(1);
expect((rows[0] as StepRow).rowObject.tasksVisible).to.equal(0);
expect((rows[1] as StepRow).rowObject.tasksTotal).to.equal(1);
expect((rows[1] as StepRow).rowObject.tasksVisible).to.equal(1);
expect(rows[2].type).to.equal('task');
});
it('shouldApplySearchFilter', () => {
expect(shouldApplySearchFilter({ status: 'NotAsked', result: [] })).to.equal(false);
expect(shouldApplySearchFilter({ status: 'Loading', result: [] })).to.equal(true);
expect(shouldApplySearchFilter({ status: 'Error', errorMsg: 'test', result: [] })).to.equal(true);
expect(shouldApplySearchFilter({ status: 'Ok', result: [] })).to.equal(true);
});
it('getRowStartTime', () => {
expect(getRowStartTime(createStepRow({}, {}))).to.equal(0);
expect(getRowStartTime(createTaskRow([createTask({ ts_epoch: 500 })]))).to.equal(500);
expect(getRowStartTime(createTaskRow([createTask({ started_at: 500, ts_epoch: 400 })]))).to.equal(500);
});
it('getRowFinishedTime', () => {
expect(getRowFinishedTime(createStepRow({}, {}))).to.equal(0);
expect(getRowFinishedTime(createTaskRow([createTask({ finished_at: 500 })]))).to.equal(500);
expect(getRowFinishedTime(createTaskRow([createTask({ finished_at: undefined, ts_epoch: 500 })]))).to.equal(500);
expect(
getRowFinishedTime(
createTaskRow([createTask({ finished_at: undefined, ts_epoch: 500 }), createTask({ finished_at: 800 })]),
),
).to.equal(800);
});
it('taskDuration', () => {
expect(taskDuration(createStepRow({}, {}))).to.equal(0);
expect(taskDuration(createTaskRow([createTask({ finished_at: 500, started_at: 100 })]))).to.equal(400);
expect(
taskDuration(
createTaskRow([
createTask({ finished_at: 500, started_at: 100 }),
createTask({ finished_at: 1200, started_at: 600 }),
]),
),
).to.equal(1100);
});
const task_a = createTaskRow([createTask({ ts_epoch: 20, finished_at: 40 })]);
const task_b = createTaskRow([createTask({ ts_epoch: 10, finished_at: 30 })]);
const task_c = createTaskRow([createTask({ ts_epoch: 10, finished_at: 20 })]);
it('sortRows', () => {
expect(sortRows('startTime', 'asc')(task_a, task_b)).to.be.greaterThan(0);
expect(sortRows('startTime', 'desc')(task_a, task_b)).to.be.lessThan(0);
expect(sortRows('endTime', 'asc')(task_a, task_b)).to.be.greaterThan(0);
expect(sortRows('endTime', 'desc')(task_a, task_b)).to.be.lessThan(0);
expect(sortRows('duration', 'asc')(task_a, task_b)).to.equal(0);
expect(sortRows('duration', 'asc')(task_a, task_c)).to.be.greaterThan(0);
expect(sortRows('duration', 'desc')(task_a, task_c)).to.be.lessThan(0);
});
}); | the_stack |
namespace eui.sys {
/**
* @private
* 需要记录的历史速度的最大次数。
*/
let MAX_VELOCITY_COUNT = 4;
/**
* @private
* 记录的历史速度的权重列表。
*/
let VELOCITY_WEIGHTS:number[] = [1, 1.33, 1.66, 2];
/**
* @private
* 当前速度所占的权重。
*/
let CURRENT_VELOCITY_WEIGHT = 2.33;
/**
* @private
* 最小的改变速度,解决浮点数精度问题。
*/
let MINIMUM_VELOCITY = 0.02;
/**
* @private
* 当容器自动滚动时要应用的摩擦系数
*/
let FRICTION = 0.998;
/**
* @private
* 当容器自动滚动时并且滚动位置超出容器范围时要额外应用的摩擦系数
*/
let EXTRA_FRICTION = 0.95;
/**
* @private
* 摩擦系数的自然对数
*/
let FRICTION_LOG = Math.log(FRICTION);
/**
* @private
*
* @param ratio
* @returns
*/
function easeOut(ratio:number):number {
let invRatio:number = ratio - 1.0;
return invRatio * invRatio * invRatio + 1;
}
/**
* @private
* 一个工具类,用于容器的滚屏拖动操作,计算在一段时间持续滚动后释放,应该继续滚动到的值和缓动时间。
* 使用此工具类,您需要创建一个 ScrollThrown 实例,并在滚动发生时调用start()方法,然后在触摸移动过程中调用update()更新当前舞台坐标。
* 内部将会启动一个计时器定时根据当前位置计算出速度值,并缓存下来最后4个值。当停止滚动时,再调用finish()方法,
* 将立即停止记录位移,并将计算出的最终结果存储到 Thrown.scrollTo 和 Thrown.duration 属性上。
*/
export class TouchScroll {
/**
* @private
* 创建一个 TouchScroll 实例
* @param updateFunction 滚动位置更新回调函数
*/
public constructor(updateFunction:(scrollPos:number)=>void, endFunction:()=>void, target:egret.IEventDispatcher) {
if (DEBUG && !updateFunction) {
egret.$error(1003, "updateFunction");
}
this.updateFunction = updateFunction;
this.endFunction = endFunction;
this.target = target;
this.animation = new sys.Animation(this.onScrollingUpdate, this);
this.animation.endFunction = this.finishScrolling;
this.animation.easerFunction = easeOut;
}
/**
* @private
* 当前容器滚动外界可调节的系列
*/
$scrollFactor = 1.0;
/**
* @private
*/
private target:egret.IEventDispatcher;
/**
* @private
*/
private updateFunction:(scrollPos:number)=>void;
/**
* @private
*/
private endFunction:()=>void;
/**
* @private
*/
private previousTime:number = 0;
/**
* @private
*/
private velocity:number = 0;
/**
* @private
*/
private previousVelocity:number[] = [];
/**
* @private
*/
private currentPosition:number = 0;
/**
* @private
*/
private previousPosition:number = 0;
/**
* @private
*/
private currentScrollPos:number = 0;
/**
* @private
*/
private maxScrollPos:number = 0;
/**
* @private
* 触摸按下时的偏移量
*/
private offsetPoint:number = 0;
/**
* @private
* 停止触摸时继续滚动的动画实例
*/
private animation:sys.Animation;
public $bounces:boolean = true;
/**
* @private
* 正在播放缓动动画的标志。
*/
public isPlaying():boolean {
return this.animation.isPlaying;
}
/**
* @private
* 如果正在执行缓动滚屏,停止缓动。
*/
public stop():void {
this.animation.stop();
egret.stopTick(this.onTick, this);
this.started = false;
}
private started:boolean = true;
/**
* @private
* true表示已经调用过start方法。
*/
public isStarted():boolean {
return this.started;
}
/**
* @private
* 开始记录位移变化。注意:当使用完毕后,必须调用 finish() 方法结束记录,否则该对象将无法被回收。
* @param touchPoint 起始触摸位置,以像素为单位,通常是stageX或stageY。
*/
public start(touchPoint:number):void {
this.started = true;
this.velocity = 0;
this.previousVelocity.length = 0;
this.previousTime = egret.getTimer();
this.previousPosition = this.currentPosition = touchPoint;
this.offsetPoint = touchPoint;
egret.startTick(this.onTick, this);
}
/**
* @private
* 更新当前移动到的位置
* @param touchPoint 当前触摸位置,以像素为单位,通常是stageX或stageY。
*/
public update(touchPoint:number, maxScrollValue:number, scrollValue):void {
maxScrollValue = Math.max(maxScrollValue, 0);
this.currentPosition = touchPoint;
this.maxScrollPos = maxScrollValue;
let disMove = this.offsetPoint - touchPoint;
let scrollPos = disMove + scrollValue;
this.offsetPoint = touchPoint;
if (scrollPos < 0) {
if (!this.$bounces) {
scrollPos = 0;
}
else {
scrollPos -= disMove * 0.5;
}
}
if (scrollPos > maxScrollValue) {
if (!this.$bounces) {
scrollPos = maxScrollValue;
}
else {
scrollPos -= disMove * 0.5;
}
}
this.currentScrollPos = scrollPos;
this.updateFunction.call(this.target, scrollPos);
}
/**
* @private
* 停止记录位移变化,并计算出目标值和继续缓动的时间。
* @param currentScrollPos 容器当前的滚动值。
* @param maxScrollPos 容器可以滚动的最大值。当目标值不在 0~maxValue之间时,将会应用更大的摩擦力,从而影响缓动时间的长度。
*/
public finish(currentScrollPos:number, maxScrollPos:number):void {
egret.stopTick(this.onTick, this);
this.started = false;
let sum = this.velocity * CURRENT_VELOCITY_WEIGHT;
let previousVelocityX = this.previousVelocity;
let length = previousVelocityX.length;
let totalWeight = CURRENT_VELOCITY_WEIGHT;
for (let i = 0; i < length; i++) {
let weight = VELOCITY_WEIGHTS[i];
sum += previousVelocityX[0] * weight;
totalWeight += weight;
}
let pixelsPerMS = sum / totalWeight;
let absPixelsPerMS = Math.abs(pixelsPerMS);
let duration = 0;
let posTo = 0;
if (absPixelsPerMS > MINIMUM_VELOCITY) {
posTo = currentScrollPos + (pixelsPerMS - MINIMUM_VELOCITY) / FRICTION_LOG * 2 * this.$scrollFactor;
if (posTo < 0 || posTo > maxScrollPos) {
posTo = currentScrollPos;
while (Math.abs(pixelsPerMS) > MINIMUM_VELOCITY) {
posTo -= pixelsPerMS;
if (posTo < 0 || posTo > maxScrollPos) {
pixelsPerMS *= FRICTION * EXTRA_FRICTION;
}
else {
pixelsPerMS *= FRICTION;
}
duration++;
}
}
else {
duration = Math.log(MINIMUM_VELOCITY / absPixelsPerMS) / FRICTION_LOG;
}
}
else {
posTo = currentScrollPos;
}
if (this.target["$getThrowInfo"]) {
let event:eui.ScrollerThrowEvent = this.target["$getThrowInfo"](currentScrollPos, posTo);
posTo = event.toPos;
}
if (duration > 0) {
//如果取消了回弹,保证动画之后不会超出边界
if (!this.$bounces) {
if (posTo < 0) {
posTo = 0;
}
else if (posTo > maxScrollPos) {
posTo = maxScrollPos;
}
}
this.throwTo(posTo, duration);
}
else {
this.finishScrolling();
}
}
/**
* @private
*
* @param timeStamp
* @returns
*/
private onTick(timeStamp:number):boolean {
let timeOffset = timeStamp - this.previousTime;
if (timeOffset > 10) {
let previousVelocity = this.previousVelocity;
if (previousVelocity.length >= MAX_VELOCITY_COUNT) {
previousVelocity.shift();
}
this.velocity = (this.currentPosition - this.previousPosition) / timeOffset;
previousVelocity.push(this.velocity);
this.previousTime = timeStamp;
this.previousPosition = this.currentPosition;
}
return true;
}
/**
* @private
*
* @param animation
*/
private finishScrolling(animation?:Animation):void {
let hsp = this.currentScrollPos;
let maxHsp = this.maxScrollPos;
let hspTo = hsp;
if (hsp < 0) {
hspTo = 0;
}
if (hsp > maxHsp) {
hspTo = maxHsp;
}
this.throwTo(hspTo, 300);
}
/**
* @private
* 缓动到水平滚动位置
*/
private throwTo(hspTo:number, duration:number = 500):void {
let hsp = this.currentScrollPos;
if (hsp == hspTo) {
this.endFunction.call(this.target);
return;
}
let animation = this.animation;
animation.duration = duration;
animation.from = hsp;
animation.to = hspTo;
animation.play();
}
/**
* @private
* 更新水平滚动位置
*/
private onScrollingUpdate(animation:Animation):void {
this.currentScrollPos = animation.currentValue;
this.updateFunction.call(this.target, animation.currentValue);
}
}
} | the_stack |
import createAnimation from './animation';
import $tool from './tool';
import PhotoRoot from './PhotoRoot';
import {
AnimationInterface,
DoubleToucheEvent,
PhotoBasic,
Point,
Rect,
Rect2,
RectFull,
TouchePoint
} from './interface';
/**
* 主画布
*/
export default class PhotoMain implements PhotoBasic{
className = 'PhotoMain';
readonly canvas: HTMLCanvasElement;
readonly ctx: CanvasRenderingContext2D;
readonly root: PhotoRoot;
// 当前展示的图片的源src
private src: string | undefined;
// 当前展示的图片(原始未处理的)
originalImg: HTMLImageElement | undefined;
// 当前展示的图片(已被处理成宽高小于1500像素)
img: HTMLImageElement | undefined;
// 图片矩形
imgRect: Rect = { x: 0, y: 0, w: 0, h: 0};
// 显示矩形
showRect: RectFull = { x: 0, y: 0, w: 0, h: 0, r: 0, sV: 1, sH: 1 };
private _showRect?: RectFull;
// 图片可移动范围
private moveRect: Rect2 = { minX: null, minY: null, maxX: null, maxY: null };
// 当前触点
private touchList: TouchePoint [] = [];
// 当前状态
private status: string | null = null;
// 单指(或双指中心)初始偏移量
private touchstartPoint: Point = {x: 0, y: 0};
// 初始触点记录
private touchstartEvent: DoubleToucheEvent = $tool.doubleTouche({x: 0, y: 0, id: 0});
private animation: AnimationInterface | undefined = undefined;
private scaleTimer: number | null = null
private loadingEvent?: (loading: boolean) => void;
/**
* 供外部使用,注入的方法会在每次加载图片后执行
*/
loadImgEd = new Map<string, {(...arg: any[]): void}>();
/**
* 构造函数
* @param el
* @param root
*/
constructor(el: HTMLCanvasElement,
root: PhotoRoot){
el.width = root.drawWidth;
el.height = root.drawHeight;
root.addEventList(this);
this.root = root;
this.canvas = el;
this.ctx = el.getContext('2d') as CanvasRenderingContext2D;
this.ctx.translate(this.root.core.x, this.root.core.y);
}
/**
* 载入图片
* @param src
* @param angle
* @param _n
*/
setSrc(src: string, angle = this.showRect.r, _n = 0): void {
this.clear();
this.src = src;
this.loadingEvent && this.loadingEvent(true);
$tool.loadImg(src).then((img: HTMLImageElement) => {
if (!_n) {
this.originalImg = img;
}
const result = $tool.clipByMax(img, 1500);
if (result) {
this.setSrc(result.src, angle, ++_n);
return;
}
this.img = img;
this._initRect();
this.showRect.r = angle;
if (!this.moveRect.minX || !this.moveRect.minY) {
this._initMoveRange();
} else {
this.loadImgEd.forEach(v => {
v && v();
});
const { x, y, w, h, r, sV, sH } = this.showRect;
const range = this._checkRange({x, y, w, h, r, sV, sH});
this.showRect = {
x: x + range[0],
y: y + range[1],
w: w + range[2],
h: h + range[3],
r,
sV,
sH
};
}
this._draw(this.imgRect, this.showRect);
this.showRect.r = angle;
this.loadingEvent && this.loadingEvent(false);
this.root.onPhotoChange && this.root.onPhotoChange({
target: this,
type: 'imageInit'
});
}, () => {
this.loadingEvent && this.loadingEvent(false);
});
}
/**
* 重置状态
*/
reset(): void {
if (this.img) {
this._initRect();
this.showRect.r = 0;
this.showRect.sV = 1;
this.showRect.sH = 1;
if (!this.moveRect.minX || !this.moveRect.minY) {
this._initMoveRange();
} else {
this.loadImgEd.forEach(v => {
v && v();
});
const { x, y, w, h, r, sV, sH } = this.showRect;
const range = this._checkRange();
this.showRect = {
x: x + range[0],
y: y + range[1],
w: w + range[2],
h: h + range[3],
r,
sV,
sH
};
}
this._draw(this.imgRect, this.showRect);
this.root.onPhotoChange && this.root.onPhotoChange({
target: this,
type: 'imageReset'
});
}
}
/**
* 设置图片可移动范围
* @param minX
* @param minY
* @param maxX
* @param maxY
* @param offPoint 中心偏移量
* @param zoom 放大系数
* @return 计算之后的图片坐标偏移量
*/
setMoveRange(minX: number, minY: number,
maxX: number, maxY: number,
offPoint?: Point, zoom?: number):
[number, number, number, number] {
this._initMoveRange(minX, minY, maxX, maxY);
if (!this.img) return [0, 0, 0, 0];
if (offPoint && zoom) {
const { x, y, w, h, r, sV, sH } = this.showRect;
const offX = offPoint.x - x;
const offY = offPoint.y - y;
const offW = w * zoom - w;
const offH = h * zoom - h;
const range = this._checkRange({
...offPoint,
w: w * zoom,
h: h * zoom,
r,
sV,
sH
});
return [
offX + range[0],
offY + range[1],
offW + range[2],
offH + range[3]
];
} else {
const [offX, offY, offW, offH] = this._checkRange();
return [offX, offY, offW, offH];
}
}
/**
* 设置旋转角度
* @param angle // 角度
* @param animation // 是否动画
*/
setAngle (angle: number, animation = false): void {
if (this.img) {
if (animation && this.animation) {
this.animation.abort();
}
this.loadImgEd.forEach(v => {
v && v({
showRect: {
...this.showRect,
r: angle
}
}, animation);
});
this.root.onPhotoChange && this.root.onPhotoChange({
target: this,
type: 'imageAngle'
});
} else {
this.showRect.r = angle;
}
}
/**
* 设置图片翻折
* @param sV 垂直翻折
* @param sH 水平翻折
* @param animation // 是否动画
*/
setFlip (sV: boolean, sH: boolean, animation = false): void {
const sh = this.showRect.sH === -1;
const sv = this.showRect.sV === -1;
if (sh === sH && sv === sV) return;
if (this.img) {
if (!animation) {
this.showRect.sV = sV ? -1 : 1;
this.showRect.sH = sH ? -1 : 1;
this._draw(this.imgRect, this.showRect);
} else {
this.animation?.abort();
this.doAnimation(0, 0, 0, 0, 0, sV, sH);
}
}
this.root.onPhotoChange && this.root.onPhotoChange({
target: this,
type: 'imageFlip'
});
}
/**
* 设置图片垂直翻折
* @param sV 垂直翻折
* @param animation // 是否动画
*/
setFlipV (sV: boolean, animation = false): void {
const sv = this.showRect.sV === -1;
if (sv === sV) return;
if (this.img) {
if (!animation) {
this.showRect.sV = sV ? -1 : 1;
this._draw(this.imgRect, this.showRect);
} else {
this.animation?.abort();
this.doAnimation(0, 0, 0, 0, 0, sV);
}
this.root.onPhotoChange && this.root.onPhotoChange({
target: this,
type: 'imageFlipV'
});
}
}
/**
* 设置图片水平翻折
* @param sH 水平翻折
* @param animation // 是否动画
*/
setFlipH (sH: boolean, animation = false): void {
const sh = this.showRect.sH === -1;
if (sh === sH) return;
if (this.img) {
if (!animation) {
this.showRect.sH = sH ? -1 : 1;
this._draw(this.imgRect, this.showRect);
} else {
this.animation?.abort();
this.doAnimation(0, 0, 0, 0, 0, undefined, sH);
}
this.root.onPhotoChange && this.root.onPhotoChange({
target: this,
type: 'imageFlipH'
});
}
}
/**
* 缩放
* @param zoom 缩放系数,大于1(放大),大于0小于1(缩小)
*/
scale(zoom: number): void{
if (!this.img || zoom < 0 || zoom === 1) return;
this.scaleTimer !== null && clearTimeout(this.scaleTimer);
this.animation?.abort();
this.touchstartPoint = {x: 0, y: 0};
const offPoint = this._changePointByCanvas(this.showRect);
this._scaleByZoom(zoom, offPoint);
this._draw(this.imgRect, this.showRect);
this.scaleTimer = setTimeout(() => {
const [offX, offY, offW, offH] = this._checkRange();
this.doAnimation(offX, offY, offW, offH, 0);
}, 500);
}
/**
* 监听图片加载过程
* @param callback
*/
onLoading(callback: (loading: boolean) => void): void{
this.loadingEvent = callback;
}
/**
* 设置图片矩形
* @param showRect
*/
setShowRect (showRect: RectFull): void {
if (this.img) {
this.showRect = showRect;
this._draw(this.imgRect, this.showRect);
}
}
/**
* 将图片上的坐标映射到画布上
* @param point
*/
private _changePointByCanvas (point: Point): Point{
const { r } = this.showRect;
return $tool.rotatePoint(point.x, point.y, r);
}
/**
* 将画布上的坐标映射到图片上
* @param point
*/
private _changePointByImage (point: Point): Point{
const { r } = this.showRect;
return $tool.rotatePoint(point.x, point.y, -r);
}
/**
* 初始化矩形
* @private
*/
private _initRect(): void {
const img = this.img;
if (!img) return;
const pw = this.root.drawWidth;
const ph = this.root.drawHeight;
const dw = img.width / pw;
const dh = img.height / ph;
const d = (dw < dh) ? dh : dw;
const cw = img.width / d;
const ch = img.height / d;
this.imgRect = {
x: 0,
y: 0,
w: img.width,
h: img.height
};
this.showRect = {
x: 0,
y: 0,
w: cw,
h: ch,
r: this.showRect.r,
sV: this.showRect.sV,
sH: this.showRect.sH
};
}
/**
* 初始化图片可移动范围
* @private
*/
private _initMoveRange(minX: number | null = null, minY: number | null = null, maxX: number | null = null, maxY: number | null = null): void {
if (minX === null || minY === null || maxX === null || maxY === null) {
const {w, h} = this.imgRect;
if (w === 0) return;
const pw = this.root.drawWidth;
const ph = this.root.drawHeight;
const d1 = pw / ph;
const d2 = w / h;
if (d1 > d2) {
const nw = ph * d2;
const nh = ph;
minX = -nw / 2;
minY = -nh / 2;
} else {
const nw = pw;
const nh = pw / d2;
minX = -nw / 2;
minY = -nh / 2;
}
maxX = -minX;
maxY = -minY;
this.moveRect = { minX, minY, maxX, maxY };
} else {
this.moveRect = { minX, minY, maxX, maxY };
}
}
/**
* 绘制画布
* @param imgRect 图片矩形
* @param showRect 将要显示的矩形
* @private
*/
private _draw(imgRect: Rect, showRect: RectFull): void {
this.clear();
if (this.img) {
const { x, y, w, h, r, sV, sH} = showRect;
const ctx = this.ctx;
ctx.save();
ctx.rotate(-r * Math.PI / 180);
ctx.translate(x , y);
ctx.scale(sH, sV);
ctx.drawImage(this.img,
imgRect.x, imgRect.y, imgRect.w, imgRect.h,
-w / 2, -h /2, w, h);
ctx.scale(-sH, -sV);
ctx.translate(-x, -y);
if (this.root.debug) {
ctx.strokeStyle = '#0f0';
ctx.lineWidth = 2;
for (let i = 0; i < this.root.drawHeight / 200; i++) {
ctx.beginPath();
ctx.moveTo(-this.root.core.x,i * 100 + 50);
ctx.lineTo(this.root.core.x,i * 100 + 50);
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.moveTo(-this.root.core.x,-i * 100 - 50);
ctx.lineTo(this.root.core.x,-i * 100 - 50);
ctx.stroke();
ctx.closePath();
}
for (let i = 0; i < this.root.drawWidth / 200; i++) {
ctx.beginPath();
ctx.moveTo(i * 100 + 50, -this.root.core.y);
ctx.lineTo(i * 100 + 50, this.root.core.y);
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.moveTo(-i * 100 - 50, -this.root.core.y);
ctx.lineTo(-i * 100 - 50, this.root.core.y);
ctx.stroke();
ctx.closePath();
}
if (this.moveRect.minX !== null &&
this.moveRect.maxX !== null &&
this.moveRect.minY !== null &&
this.moveRect.maxY !== null) {
ctx.strokeStyle = '#00f';
ctx.fillStyle = 'rgba(0,0,0,0)';
ctx.lineWidth = 2;
ctx.strokeRect(
this.moveRect.minX,
this.moveRect.minY,
this.moveRect.maxX - this.moveRect.minX,
this.moveRect.maxY - this.moveRect.minY);
}
ctx.beginPath();
ctx.fillStyle = '#fff';
ctx.arc(0, 0, 6, 0, 2 * Math.PI);
ctx.fill();
ctx.closePath();
}
ctx.restore();
}
}
/**
* 清除画布
*/
clear (): void {
this.ctx.clearRect(
-this.root.core.x,
-this.root.core.y,
this.root.drawWidth,
this.root.drawHeight);
}
touchEnd(tps: TouchePoint[]): void {
if (!this.img) return;
if (!this.touchList.length) {
return;
}
tps = this.touchList.filter(v => v.id !== tps[0].id);
if (tps.length === 0) {
this.wheelEnd();
} else if (tps.length === 1) {
this._touchStart1(tps[0]);
}
this.touchList = tps;
}
touchMove(tps: TouchePoint[]): void {
if (!this.img) return;
if (tps.length === 1) {
this._touchMove1(tps[0]);
} else if (tps.length === 2) {
this._touchMove2(tps[0], tps[1]);
} else if (tps.length > 2) {
const ids = this.touchList.map(v => v.id);
tps = tps.filter(v => (ids.indexOf(v.id) > -1));
if (tps.length === 2) {
this._touchMove2(tps[0], tps[1]);
}
}
}
touchStart(tps: TouchePoint[]): void {
if (!this.img) return;
this.animation?.abort();
const tp = tps[0];
if (!this.touchList.length) {
this.touchList.push(tp);
this._touchStart1(tp);
} else if (this.touchList.length === 1) {
// 判断触点是否重复
if (this.touchList[0].id !== tp.id) {
this.touchList.push(tp);
this._touchStart2(this.touchList[0], this.touchList[1]);
}
}
}
wheelStart(zoom: number, point: Point): void {
if (!this.img) return;
this.status = 'scale';
this.wheelChange(zoom, point);
}
wheelChange(zoom: number, point: Point): void {
if (!this.img) return;
this.animation?.abort();
this.touchstartEvent = $tool.doubleTouche(point);
const core = this.touchstartEvent.core;
const offPoint = this._changePointByImage(core);
this.touchstartPoint = this._getPointerLocation(offPoint);
this.root.setPriority(this);
zoom = 1 + zoom * 0.0005;
zoom = zoom > 1.08 ? 1.08 : zoom < 0.92593 ? 0.92593 : zoom;
this._scaleByZoom(zoom, point);
this._draw(this.imgRect, this.showRect);
}
wheelEnd(): void {
if (!this.img) return;
this.status = null;
this.touchstartEvent = $tool.doubleTouche({x: 0, y: 0, id: 0});
this.touchstartPoint = {x: 0, y: 0};
const [offX, offY, offW, offH] = this._checkRange();
if (offX || offY || offW || offH) {
this.doAnimation(offX, offY, offW, offH, 0);
}
this.root.deletePriority(this.className);
}
private _touchStart1(tp: TouchePoint) {
this.status = 'move';
this.touchstartEvent = $tool.doubleTouche(tp);
const offPoint = this._changePointByImage(tp);
this.touchstartPoint = this._getPointerLocation(offPoint);
}
private _touchStart2(tp1: TouchePoint, tp2: TouchePoint) {
const { sV, sH } = this.showRect;
this.status = 'scale';
if ((!sV && sH) || (sV && !sH)) {
this.touchstartEvent = $tool.doubleTouche(tp2, tp1);
} else {
this.touchstartEvent = $tool.doubleTouche(tp1, tp2);
}
const core = this.touchstartEvent.core;
const offPoint = this._changePointByImage(core);
this.touchstartPoint = this._getPointerLocation(offPoint);
this.root.setPriority(this);
this.root.onPhotoChange && this.root.onPhotoChange({
target: this,
type: 'imageTouchStart2'
});
}
private _touchMove1(tp: TouchePoint) {
if (this.status === 'move') {
this.root.setPriority(this);
this.touchList[0] = tp;
this._move(tp);
this._draw(this.imgRect, this.showRect);
this.root.onPhotoChange && this.root.onPhotoChange({
target: this,
type: 'imageMove'
});
}
}
private _touchMove2(tp1: TouchePoint, tp2: TouchePoint) {
if (this.status === 'scale') {
this.touchList = [tp1, tp2];
const doubleToucheEvent = $tool.doubleTouche(tp1, tp2);
this._scaleByLocation(doubleToucheEvent)
this._draw(this.imgRect, this.showRect);
}
}
/**
* 获取core相对图片的位置
* @param core
* @private
*/
private _getPointerLocation(core: Point): Point {
return {x: core.x - this.showRect.x, y: core.y - this.showRect.y};
}
/**
* 移动图片
* @private
*/
private _move(core: Point): void {
const pl = this.touchstartPoint;
const offPoint = this._changePointByImage(core);
this.showRect.x = offPoint.x - pl.x;
this.showRect.y = offPoint.y - pl.y;
}
/**
* 缩放图片
* @param e
* @private
*/
private _scaleByLocation(e: DoubleToucheEvent): void{
let zoom = e.length / this.touchstartEvent.length;
zoom = (zoom < 0.9091) ? 0.9091 : zoom;
zoom = (zoom > 1.1) ? 1.1 : zoom;
this._scaleByZoom(zoom, e.core);
this.touchstartEvent = e;
}
/**
* 缩放图片
* @param zoom-
* @param core
* @param angle
* @private
*/
private _scaleByZoom(zoom = 1, core: Point, angle = 0) {
let pl = this.touchstartPoint;
this.touchstartPoint = { x: pl.x * zoom, y: pl.y * zoom};
pl = this.touchstartPoint;
const {w, h, r, sV, sH} = this.showRect;
const offPoint = this._changePointByImage(core);
const showRect = this.showRect = {
x: offPoint.x - pl.x,
y: offPoint.y - pl.y,
w: w * zoom,
h: h * zoom,
r: r + angle,
sV,
sH
};
const [offX, offY, offW, offH] = this._checkRange(showRect);
const isDiff = offX || offY || offW || offH;
if (isDiff) {
this.showRect = this._getShowRect(offX, offY, offW, offH, 0);
}
this.root.onPhotoChange && this.root.onPhotoChange({
target: this,
type: 'imageScale'
});
if (isDiff) {
this.showRect = showRect;
}
}
/**
* 检查图片是否在可移动范围内
* @param showRect
* @private
* @return 坐标偏移量
*/
private _checkRange(showRect = this.showRect): [number, number, number, number] {
let { x: cx, y: cy } = showRect;
const { w: cw, h: ch } = showRect;
cx -= cw / 2;
cy -= ch / 2;
let { minX, minY, maxX, maxY } = this.moveRect;
minX = minX || 0;
minY = minY || 0;
maxX = maxX || 0;
maxY = maxY || 0;
let nx = cx, ny = cy, nw = cw, nh = ch;
let rl = this._getPohtoByRangeLocation([cx, cy, cw, ch]);
const imgOff = cw / ch;
if (rl[4] <= 0) {
nw = maxX - minX;
nh = nw / imgOff;
nx = cx + (cw - nw) / 2;
ny = cy + (ch - nh) / 2;
}
rl = this._getPohtoByRangeLocation([nx, ny, nw, nh]);
if (rl[5] <= 0) {
nh = maxY - minY;
nw = nh * imgOff;
nx = cx + (cw - nw) / 2;
ny = cy + (ch - nh) / 2;
}
rl = this._getPohtoByRangeLocation([nx, ny, nw, nh]);
if (rl[0] > 0) nx -= rl[0];
if (rl[1] > 0) ny -= rl[1];
if (rl[2] < 0) nx -= rl[2];
if (rl[3] < 0) ny -= rl[3];
const offW = nw - cw, offH = nh - ch;
return [
nx - cx + offW / 2,
ny - cy + offH / 2,
offW,
offH
];
}
/**
* 获取图片相对可移动范围的各边坐标的偏移量
* @param newLocation
* @private
*/
private _getPohtoByRangeLocation(newLocation?: [number, number, number, number]):
[number, number, number, number, number, number] {
let { x, y, w, h } = this.showRect;
const { minX, minY, maxX, maxY } = this.moveRect;
if (newLocation) {
[x, y, w, h] = newLocation;
}
return [
x - (minX || 0),
y - (minY || 0),
x + w - (maxX || 0),
y + h - (maxY || 0),
w - (maxX || 0) + (minX || 0),
h - (maxY || 0) + (minY || 0)
];
}
/**
*
* @param offX 偏移量
* @param offY 偏移量
* @param offW 偏移量
* @param offH 偏移量
* @param offR 偏移量
* @param offSV 偏移量
* @param offSH 偏移量
* @private
*/
private _getShowRect(offX: number, offY: number, offW: number, offH: number,
offR: number, offSV?: boolean, offSH?: boolean) {
const { x, y, w, h, r, sV, sH} = this.showRect;
offSV = offSV === void 0 ? sV === -1 : offSV;
offSH = offSH === void 0 ? sH === -1 : offSH;
return {
x: x + offX,
y: y + offY,
w: w + offW,
h: h + offH,
r: r + offR,
sV: offSV ? -1 : 1,
sH: offSH ? -1 : 1,
};
}
/**
* 动画
* @param offX 偏移量
* @param offY 偏移量
* @param offW 偏移量
* @param offH 偏移量
* @param offR 偏移量
* @param offSV 偏移量
* @param offSH 偏移量
* @param endCallback 结束时的回调
* @private
*/
doAnimation(offX: number, offY: number, offW: number, offH: number,
offR: number, offSV?: boolean, offSH?: boolean,
endCallback?: {(...arg: any[]): void}): void {
if (!offX && !offY && !offW && !offH && !offR && offSV === undefined && offSH === undefined) {
return;
}
const { x, y, w, h, r, sV, sH} = this.showRect;
const showRect = this._getShowRect(offX, offY, offW, offH, offR, offSV, offSH);
const _offSV = showRect.sV - sV;
const _offSH = showRect.sH - sH;
if (!offX && !offY && !offW && !offH && !offR && !_offSH && !_offSV) {
return;
}
this._showRect = this.showRect;
this.showRect = showRect;
this.animation = createAnimation({
duration: 300,
timing: 'ease-in-out',
change: (i, j) => {
this._showRect = {
x: x + j * offX,
y: y + j * offY,
w: w + j * offW,
h: h + j * offH,
r: r + j * offR,
sV: sV + j * _offSV,
sH: sH + j * _offSH
}
// 重新绘制画布
this._draw(this.imgRect, this._showRect);
},
end: () => {
if (this._showRect) {
this.showRect = this._showRect;
this._showRect = undefined;
}
endCallback && endCallback();
}
}).start();
}
} | the_stack |
import {
DBCore,
DBCoreCursor,
DBCoreOpenCursorRequest,
DBCoreQueryRequest,
DBCoreIndex,
DBCoreKeyRange,
DBCoreQueryResponse,
DBCoreRangeType,
DBCoreSchema,
DBCoreTableSchema,
DBCoreTable,
DBCoreMutateResponse,
} from "../public/types/dbcore";
import { isArray } from '../functions/utils';
import { eventRejectHandler, preventDefault } from '../functions/event-wrappers';
import { wrap } from '../helpers/promise';
import { getMaxKey } from '../functions/quirks';
import { getKeyExtractor } from './get-key-extractor';
export function arrayify<T>(arrayLike: {length: number, [index: number]: T}): T[] {
return [].slice.call(arrayLike);
}
export function pick<T,Prop extends keyof T>(obj: T, props: Prop[]): Pick<T, Prop> {
const result = {} as Pick<T, Prop>;
props.forEach(prop => result[prop] = obj[prop]);
return result;
}
let _id_counter = 0;
export function getKeyPathAlias(keyPath: null | string | string[]) {
return keyPath == null ?
":id" :
typeof keyPath === 'string' ?
keyPath :
`[${keyPath.join('+')}]`;
}
export function createDBCore (
db: IDBDatabase,
IdbKeyRange: typeof IDBKeyRange,
tmpTrans: IDBTransaction) : DBCore
{
function extractSchema(db: IDBDatabase, trans: IDBTransaction) : {schema: DBCoreSchema, hasGetAll: boolean} {
const tables = arrayify(db.objectStoreNames);
return {
schema: {
name: db.name,
tables: tables.map(table => trans.objectStore(table)).map(store => {
const {keyPath, autoIncrement} = store;
const compound = isArray(keyPath);
const outbound = keyPath == null;
const indexByKeyPath: {[keyPathAlias: string]: DBCoreIndex} = {};
const result = {
name: store.name,
primaryKey: {
name: null,
isPrimaryKey: true,
outbound,
compound,
keyPath,
autoIncrement,
unique: true,
extractKey: getKeyExtractor(keyPath)
} as DBCoreIndex,
indexes: arrayify(store.indexNames).map(indexName => store.index(indexName))
.map(index => {
const {name, unique, multiEntry, keyPath} = index;
const compound = isArray(keyPath);
const result: DBCoreIndex = {
name,
compound,
keyPath,
unique,
multiEntry,
extractKey: getKeyExtractor(keyPath)
};
indexByKeyPath[getKeyPathAlias(keyPath)] = result;
return result;
}),
getIndexByKeyPath: (keyPath: null | string | string[]) => indexByKeyPath[getKeyPathAlias(keyPath)]
};
indexByKeyPath[":id"] = result.primaryKey;
if (keyPath != null) {
indexByKeyPath[getKeyPathAlias(keyPath)] = result.primaryKey;
}
return result;
})
},
hasGetAll: tables.length > 0 && ('getAll' in trans.objectStore(tables[0])) &&
!(typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) &&
!/(Chrome\/|Edge\/)/.test(navigator.userAgent) &&
[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1] < 604) // Bug with getAll() on Safari ver<604. See discussion following PR #579
};
}
function makeIDBKeyRange (range: DBCoreKeyRange) : IDBKeyRange | null {
if (range.type === DBCoreRangeType.Any) return null;
if (range.type === DBCoreRangeType.Never) throw new Error("Cannot convert never type to IDBKeyRange");
const {lower, upper, lowerOpen, upperOpen} = range;
const idbRange = lower === undefined ?
upper === undefined ?
null : //IDBKeyRange.lowerBound(-Infinity, false) : // Any range (TODO: Should we return null instead?)
IdbKeyRange.upperBound(upper, !!upperOpen) : // below
upper === undefined ?
IdbKeyRange.lowerBound(lower, !!lowerOpen) : // above
IdbKeyRange.bound(lower, upper, !!lowerOpen, !!upperOpen);
return idbRange;
}
function createDbCoreTable(tableSchema: DBCoreTableSchema): DBCoreTable {
const tableName = tableSchema.name;
function mutate ({trans, type, keys, values, range}) {
return new Promise<DBCoreMutateResponse>((resolve, reject) => {
resolve = wrap(resolve);
const store = (trans as IDBTransaction).objectStore(tableName);
const outbound = store.keyPath == null;
const isAddOrPut = type === "put" || type === "add";
if (!isAddOrPut && type !== 'delete' && type !== 'deleteRange')
throw new Error ("Invalid operation type: " + type);
const {length} = keys || values || {length: 1}; // keys.length if keys. values.length if values. 1 if range.
if (keys && values && keys.length !== values.length) {
throw new Error("Given keys array must have same length as given values array.");
}
if (length === 0)
// No items to write. Don't even bother!
return resolve({numFailures: 0, failures: {}, results: [], lastResult: undefined});
let req: IDBRequest;
const reqs: IDBRequest[] = [];
const failures: {[operationNumber: number]: Error} = [];
let numFailures = 0;
const errorHandler =
event => {
++numFailures;
preventDefault(event);
};
if (type === 'deleteRange') {
// Here the argument is the range
if (range.type === DBCoreRangeType.Never)
return resolve({numFailures, failures, results: [], lastResult: undefined}); // Deleting the Never range shoulnt do anything.
if (range.type === DBCoreRangeType.Any)
reqs.push(req = store.clear()); // Deleting the Any range is equivalent to store.clear()
else
reqs.push(req = store.delete(makeIDBKeyRange(range)));
} else {
// No matter add, put or delete - find out arrays of first and second arguments to it.
const [args1, args2] = isAddOrPut ?
outbound ?
[values, keys] :
[values, null] :
[keys, null];
if (isAddOrPut) {
for (let i=0; i<length; ++i) {
reqs.push(req = (args2 && args2[i] !== undefined ?
store[type](args1[i], args2[i]) :
store[type](args1[i])) as IDBRequest);
req.onerror = errorHandler;
}
} else {
for (let i=0; i<length; ++i) {
reqs.push(req = store[type](args1[i]) as IDBRequest);
req.onerror = errorHandler;
}
}
}
const done = event => {
const lastResult = event.target.result;
reqs.forEach((req, i) => req.error != null && (failures[i] = req.error));
resolve({
numFailures,
failures,
results: type === "delete" ? keys : reqs.map(req => req.result),
lastResult
});
};
req.onerror = event => { // wrap() not needed. All paths calling outside will wrap!
errorHandler(event);
done(event);
};
req.onsuccess = done;
});
}
function openCursor ({trans, values, query, reverse, unique}: DBCoreOpenCursorRequest): Promise<DBCoreCursor>
{
return new Promise((resolve, reject) => {
resolve = wrap(resolve);
const {index, range} = query;
const store = (trans as IDBTransaction).objectStore(tableName);
// source
const source = index.isPrimaryKey ?
store :
store.index(index.name);
// direction
const direction = reverse ?
unique ?
"prevunique" :
"prev" :
unique ?
"nextunique" :
"next";
// request
const req = values || !('openKeyCursor' in source) ?
source.openCursor(makeIDBKeyRange(range), direction) :
source.openKeyCursor(makeIDBKeyRange(range), direction);
// iteration
req.onerror = eventRejectHandler(reject);
req.onsuccess = wrap(ev => {
const cursor = req.result as unknown as DBCoreCursor;
if (!cursor) {
resolve(null);
return;
}
(cursor as any).___id = ++_id_counter;
(cursor as any).done = false;
const _cursorContinue = cursor.continue.bind(cursor);
let _cursorContinuePrimaryKey = cursor.continuePrimaryKey;
if (_cursorContinuePrimaryKey) _cursorContinuePrimaryKey = _cursorContinuePrimaryKey.bind(cursor);
const _cursorAdvance = cursor.advance.bind(cursor);
const doThrowCursorIsNotStarted = ()=>{throw new Error("Cursor not started");}
const doThrowCursorIsStopped = ()=>{throw new Error("Cursor not stopped");}
(cursor as any).trans = trans;
cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsNotStarted;
cursor.fail = wrap(reject);
cursor.next = function (this: DBCoreCursor) {
// next() must work with "this" pointer in order to function correctly for ProxyCursors (derived objects)
// without having to re-define next() on each child.
let gotOne = 1;
return this.start(() => gotOne-- ? this.continue() : this.stop()).then(() => this);
};
cursor.start = (callback) => {
//console.log("Starting cursor", (cursor as any).___id);
const iterationPromise = new Promise<void>((resolveIteration, rejectIteration) =>{
resolveIteration = wrap(resolveIteration);
req.onerror = eventRejectHandler(rejectIteration);
cursor.fail = rejectIteration;
cursor.stop = value => {
//console.log("Cursor stop", cursor);
cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsStopped;
resolveIteration(value);
};
});
// Now change req.onsuccess to a callback that doesn't call initCursor but just observer.next()
const guardedCallback = () => {
if (req.result) {
//console.log("Next result", cursor);
try {
callback();
} catch (err) {
cursor.fail(err);
}
} else {
(cursor as any).done = true;
cursor.start = ()=>{throw new Error("Cursor behind last entry");}
cursor.stop();
}
}
req.onsuccess = wrap(ev => {
//cursor.continue = _cursorContinue;
//cursor.continuePrimaryKey = _cursorContinuePrimaryKey;
//cursor.advance = _cursorAdvance;
req.onsuccess = guardedCallback;
guardedCallback();
});
cursor.continue = _cursorContinue;
cursor.continuePrimaryKey = _cursorContinuePrimaryKey;
cursor.advance = _cursorAdvance;
guardedCallback();
return iterationPromise;
};
resolve(cursor);
}, reject);
});
}
function query (hasGetAll: boolean) {
return (request: DBCoreQueryRequest) => {
return new Promise<DBCoreQueryResponse>((resolve, reject) => {
resolve = wrap(resolve);
const {trans, values, limit, query} = request;
const nonInfinitLimit = limit === Infinity ? undefined : limit;
const {index, range} = query;
const store = (trans as IDBTransaction).objectStore(tableName);
const source = index.isPrimaryKey ? store : store.index(index.name);
const idbKeyRange = makeIDBKeyRange(range);
if (limit === 0) return resolve({result: []});
if (hasGetAll) {
const req = values ?
(source as any).getAll(idbKeyRange, nonInfinitLimit) :
(source as any).getAllKeys(idbKeyRange, nonInfinitLimit);
req.onsuccess = event => resolve({result: event.target.result});
req.onerror = eventRejectHandler(reject);
} else {
let count = 0;
const req = values || !('openKeyCursor' in source) ?
source.openCursor(idbKeyRange) :
source.openKeyCursor(idbKeyRange)
const result = [];
req.onsuccess = event => {
const cursor = req.result as IDBCursorWithValue;
if (!cursor) return resolve({result});
result.push(values ? cursor.value : cursor.primaryKey);
if (++count === limit) return resolve({result});
cursor.continue();
};
req.onerror = eventRejectHandler(reject);
}
});
};
}
return {
name: tableName,
schema: tableSchema,
mutate,
getMany ({trans, keys}) {
return new Promise<any[]>((resolve, reject) => {
resolve = wrap(resolve);
const store = (trans as IDBTransaction).objectStore(tableName);
const length = keys.length;
const result = new Array(length);
let keyCount = 0;
let callbackCount = 0;
let valueCount = 0;
let req: IDBRequest & {_pos?: number};
const successHandler = event => {
const req = event.target;
if ((result[req._pos] = req.result) != null) ++valueCount;
if (++callbackCount === keyCount) resolve(result);
};
const errorHandler = eventRejectHandler(reject);
for (let i=0; i<length; ++i) {
const key = keys[i];
if (key != null) {
req = store.get(keys[i]);
req._pos = i;
req.onsuccess = successHandler;
req.onerror = errorHandler;
++keyCount;
}
}
if (keyCount === 0) resolve(result);
});
},
get ({trans, key}) {
return new Promise<any>((resolve, reject) => {
resolve = wrap (resolve);
const store = (trans as IDBTransaction).objectStore(tableName);
const req = store.get(key);
req.onsuccess = event => resolve((event.target as any).result);
req.onerror = eventRejectHandler(reject);
});
},
query: query(hasGetAll),
openCursor,
count ({query, trans}) {
const {index, range} = query;
return new Promise<number>((resolve, reject) => {
const store = (trans as IDBTransaction).objectStore(tableName);
const source = index.isPrimaryKey ? store : store.index(index.name);
const idbKeyRange = makeIDBKeyRange(range);
const req = idbKeyRange ? source.count(idbKeyRange) : source.count();
req.onsuccess = wrap(ev => resolve((ev.target as IDBRequest).result));
req.onerror = eventRejectHandler(reject);
});
}
};
}
const {schema, hasGetAll} = extractSchema(db, tmpTrans);
const tables = schema.tables.map(tableSchema => createDbCoreTable(tableSchema));
const tableMap: {[name: string]: DBCoreTable} = {};
tables.forEach(table => tableMap[table.name] = table);
return {
stack: "dbcore",
transaction: db.transaction.bind(db),
table(name: string) {
const result = tableMap[name];
if (!result) throw new Error(`Table '${name}' not found`);
return tableMap[name];
},
MIN_KEY: -Infinity,
MAX_KEY: getMaxKey(IdbKeyRange),
schema
};
} | the_stack |
import { EncodedAssetParams, EncodedLocalStateSchema, EncodedTransaction } from "algosdk";
export const MIN_UINT64 = 0n;
export const MAX_UINT64 = 0xFFFFFFFFFFFFFFFFn;
export const MAX_UINT128 = 340282366920938463463374607431768211455n;
export const MAX_UINT8 = 255;
export const MIN_UINT8 = 0;
export const MAX_UINT6 = 63n;
export const DEFAULT_STACK_ELEM = 0n;
export const MAX_CONCAT_SIZE = 4096;
export const ALGORAND_MIN_TX_FEE = 1000;
// https://github.com/algorand/go-algorand/blob/master/config/consensus.go#L659
export const ALGORAND_ACCOUNT_MIN_BALANCE = 0.1e6; // 0.1 ALGO
export const MaxTEALVersion = 5;
// values taken from: https://developer.algorand.org/docs/features/asc1/stateful/#minimum-balance-requirement-for-a-smart-contract
// minimum balance costs (in microalgos) for ssc schema
export const APPLICATION_BASE_FEE = 0.1e6; // base fee for creating or opt-in to application
export const ASSET_CREATION_FEE = 0.1e6; // creation fee for asset
export const SSC_VALUE_UINT = 28500; // cost for value as uint64
export const SSC_VALUE_BYTES = 50000; // cost for value as bytes
export const MAX_KEY_BYTES = 64; // max length of key
export const MAX_KEY_VAL_BYTES = 128; // max combined length of key-value pair
// values taken from [https://github.com/algorand/go-algorand/blob/master/config/consensus.go#L691]
export const LogicSigMaxCost = 20000;
export const MaxAppProgramCost = 700;
export const LogicSigMaxSize = 1000;
export const MaxAppProgramLen = 1024;
export const ALGORAND_MAX_APP_ARGS_LEN = 16;
export const ALGORAND_MAX_TX_ACCOUNTS_LEN = 4;
// the assets and application arrays combined and totaled with the accounts array can not exceed 8
export const ALGORAND_MAX_TX_ARRAY_LEN = 8;
export const MAX_INNER_TRANSACTIONS = 16;
export const ALGORAND_MAX_LOGS_COUNT = 32;
export const ALGORAND_MAX_LOGS_LENGTH = 1024;
export const MAX_ALGORAND_ACCOUNT_ASSETS = 1000;
export const MAX_ALGORAND_ACCOUNT_CREATED_APPS = 10;
export const MAX_ALGORAND_ACCOUNT_OPTEDIN_APPS = 50;
// for byteslice arithmetic ops, inputs are limited to 64 bytes,
// but ouput can be upto 128 bytes (eg. when using b+ OR b*)
// https://github.com/algorand/go-algorand/blob/bd5a00092c8a63dba8314b97851e46ff247cf7c1/data/transactions/logic/eval.go#L1302
export const MAX_INPUT_BYTE_LEN = 64;
export const MAX_OUTPUT_BYTE_LEN = 128;
export const ZERO_ADDRESS = new Uint8Array(32);
export const ZERO_ADDRESS_STR = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ";
const zeroUint64 = 0n;
const zeroByte = new Uint8Array(0);
// keys with value as null does not represent a txn/global field, these are handled explicitly
// in txn.ts using switch
type keyOfEncTx = keyof EncodedTransaction | keyof EncodedAssetParams | keyof EncodedLocalStateSchema;
// https://developer.algorand.org/docs/reference/teal/opcodes/#txn
// transaction fields supported by teal v1
export const TxnFields: {[key: number]: {[key: string]: keyOfEncTx | null }} = {
1: {
Sender: 'snd',
Fee: 'fee',
FirstValid: 'fv',
FirstValidTime: null,
LastValid: 'lv',
Note: 'note',
Lease: 'lx',
Receiver: 'rcv',
Amount: 'amt',
CloseRemainderTo: 'close',
VotePK: 'votekey',
SelectionPK: 'selkey',
VoteFirst: 'votefst',
VoteLast: 'votelst',
VoteKeyDilution: 'votekd',
Type: 'type',
TypeEnum: null,
XferAsset: 'xaid',
AssetAmount: 'aamt',
AssetSender: 'asnd',
AssetReceiver: 'arcv',
AssetCloseTo: 'aclose',
GroupIndex: null,
TxID: null
}
};
// transaction fields supported by teal v2
TxnFields[2] = {
...TxnFields[1],
ApplicationID: 'apid',
OnCompletion: 'apan',
ApplicationArgs: 'apaa',
NumAppArgs: null,
Accounts: 'apat',
NumAccounts: null,
ApprovalProgram: 'apap',
ClearStateProgram: 'apsu',
RekeyTo: 'rekey',
ConfigAsset: 'caid',
ConfigAssetTotal: 't',
ConfigAssetDecimals: 'dc',
ConfigAssetDefaultFrozen: 'df',
ConfigAssetUnitName: 'un',
ConfigAssetName: 'an',
ConfigAssetURL: 'au',
ConfigAssetMetadataHash: 'am',
ConfigAssetManager: 'm',
ConfigAssetReserve: 'r',
ConfigAssetFreeze: 'f',
ConfigAssetClawback: 'c',
FreezeAsset: 'faid',
FreezeAssetAccount: 'fadd',
FreezeAssetFrozen: 'afrz'
};
TxnFields[3] = {
...TxnFields[2],
Assets: 'apas',
NumAssets: null,
Applications: 'apfa',
NumApplications: null,
GlobalNumUint: 'nui',
GlobalNumByteSlice: 'nbs',
LocalNumUint: 'nui',
LocalNumByteSlice: 'nbs'
};
TxnFields[4] = {
...TxnFields[3],
ExtraProgramPages: 'apep'
};
TxnFields[5] = {
...TxnFields[4],
Nonparticipation: 'nonpart'
};
export const ITxnFields: {[key: number]: {[key: string]: keyOfEncTx | null }} = {
1: {},
2: {},
3: {},
4: {},
5: {
Logs: null,
NumLogs: null,
CreatedAssetID: null,
CreatedApplicationID: null
}
};
// transaction fields of type array
export const TxArrFields: {[key: number]: Set<string>} = {
1: new Set(),
2: new Set(['Accounts', 'ApplicationArgs'])
};
TxArrFields[3] = new Set([...TxArrFields[2], 'Assets', 'Applications']);
TxArrFields[5] = TxArrFields[4] = TxArrFields[3];
// itxn fields of type array
export const ITxArrFields: {[key: number]: Set<string>} = {
1: new Set(),
2: new Set(),
3: new Set(),
4: new Set(),
5: new Set(['Logs'])
};
export const TxFieldDefaults: {[key: string]: any} = {
Sender: ZERO_ADDRESS,
Fee: zeroUint64,
FirstValid: zeroUint64,
LastValid: zeroUint64,
Note: zeroByte,
Lease: zeroByte,
Receiver: ZERO_ADDRESS,
Amount: zeroUint64,
CloseRemainderTo: ZERO_ADDRESS,
VotePK: ZERO_ADDRESS,
SelectionPK: ZERO_ADDRESS,
VoteFirst: zeroUint64,
VoteLast: zeroUint64,
VoteKeyDilution: zeroUint64,
Type: zeroByte,
TypeEnum: zeroUint64,
XferAsset: zeroUint64,
AssetAmount: zeroUint64,
AssetSender: ZERO_ADDRESS,
AssetReceiver: ZERO_ADDRESS,
AssetCloseTo: ZERO_ADDRESS,
GroupIndex: zeroUint64,
ApplicationID: zeroUint64,
OnCompletion: zeroUint64,
ApplicationArgs: zeroByte,
NumAppArgs: zeroUint64,
Accounts: zeroByte,
NumAccounts: zeroUint64,
ApprovalProgram: zeroByte,
ClearStateProgram: zeroByte,
RekeyTo: ZERO_ADDRESS,
ConfigAsset: zeroUint64,
ConfigAssetTotal: zeroUint64,
ConfigAssetDecimals: zeroUint64,
ConfigAssetDefaultFrozen: zeroUint64,
ConfigAssetUnitName: zeroByte,
ConfigAssetName: zeroByte,
ConfigAssetURL: zeroByte,
ConfigAssetMetadataHash: zeroByte,
ConfigAssetManager: ZERO_ADDRESS,
ConfigAssetReserve: ZERO_ADDRESS,
ConfigAssetFreeze: ZERO_ADDRESS,
ConfigAssetClawback: ZERO_ADDRESS,
FreezeAsset: zeroUint64,
FreezeAssetAccount: ZERO_ADDRESS,
FreezeAssetFrozen: zeroUint64,
Assets: zeroByte,
NumAssets: zeroUint64,
Applications: zeroByte,
NumApplications: zeroUint64,
GlobalNumUint: zeroUint64,
GlobalNumByteSlice: zeroUint64,
LocalNumUint: zeroUint64,
LocalNumByteSlice: zeroUint64,
ExtraProgramPages: zeroUint64,
Nonparticipation: zeroUint64
};
export const AssetParamMap: {[key: number]: {[key: string]: string}} = {
1: {
AssetTotal: 'total', // Total number of units of this asset
AssetDecimals: 'decimals', // See AssetDef.Decimals
AssetDefaultFrozen: 'defaultFrozen', // Frozen by default or not
AssetUnitName: 'unitName', // Asset unit name
AssetName: 'name', // Asset name
AssetURL: 'url', // URL with additional info about the asset
AssetMetadataHash: 'metadataHash', // Arbitrary commitment
AssetManager: 'manager', // Manager commitment
AssetReserve: 'reserve', // Reserve address
AssetFreeze: 'freeze', // Freeze address
AssetClawback: 'clawback' // Clawback address
}
};
AssetParamMap[4] = AssetParamMap[3] = AssetParamMap[2] = AssetParamMap[1];
AssetParamMap[5] = {
...AssetParamMap[4],
AssetCreator: 'creator'
};
export const reDigit = /^\d+$/;
/** is Base64 regex
* ^ # Start of input
* ([0-9a-zA-Z+/]{4})* # Groups of 4 valid characters decode
* # to 24 bits of data for each group
* ( # Either ending with:
* ([0-9a-zA-Z+/]{2}==) # two valid characters followed by ==
* | # , or
* ([0-9a-zA-Z+/]{3}=) # three valid characters followed by =
* )? # , or nothing
* $ # End of input
*/
export const reBase64 = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
// A-Z and 2-7 repeated, with optional `=` at the end
export const reBase32 = /^[A-Z2-7]+=*$/;
// reference for values: https://github.com/algorand/go-algorand/blob/master/config/consensus.go#L510
// for fields: https://developer.algorand.org/docs/reference/teal/opcodes/#global
// global field supported by teal v1
export const GlobalFields: {[key: number]: {[key: string]: any}} = { // teal version => global field => value
1: {
MinTxnFee: ALGORAND_MIN_TX_FEE,
MinBalance: 10000,
MaxTxnLife: 1000,
ZeroAddress: ZERO_ADDRESS,
GroupSize: null
}
};
// global field supported by teal v2
// Note: Round, LatestTimestamp are dummy values and these are overrided by runtime class's
// round and timestamp
GlobalFields[2] = {
...GlobalFields[1],
LogicSigVersion: MaxTEALVersion,
Round: 1,
LatestTimestamp: 1,
CurrentApplicationID: null
};
// global fields supported by tealv3
GlobalFields[3] = {
...GlobalFields[2],
CreatorAddress: null
};
// global fields supported by tealv4
GlobalFields[4] = {
...GlobalFields[3]
};
// global fields supported by tealv5
GlobalFields[5] = {
...GlobalFields[4],
GroupID: null,
CurrentApplicationAddress: null
};
// creating map for opcodes whose cost is other than 1
export const OpGasCost: {[key: number]: {[key: string]: number}} = { // version => opcode => cost
// v1 opcodes cost
1: {
sha256: 7,
sha512_256: 9,
keccak256: 26,
ed25519verify: 1900
}
};
// v2 opcodes cost
OpGasCost[2] = {
...OpGasCost[1], // includes all v1 opcodes
sha256: 35,
sha512_256: 45,
keccak256: 130
};
/**
* In tealv3, cost of crypto opcodes are same as v2.
* All other opcodes have cost 1
*/
OpGasCost[3] = { ...OpGasCost[2] };
/*
* tealv4
*/
OpGasCost[4] = {
...OpGasCost[3],
'b+': 10,
'b-': 10,
'b*': 20,
'b/': 20,
'b%': 20,
'b|': 6,
'b&': 6,
'b^': 6,
'b~': 4
};
/**
* teal v5
*/
OpGasCost[5] = {
...OpGasCost[4],
ecdsa_verify: 1700,
ecdsa_pk_decompress: 650,
ecdsa_pk_recover: 2000
};
export const enum MathOp {
// arithmetic
Add,
Sub,
Mul,
Div,
Mod,
// relational
LessThan,
GreaterThan,
LessThanEqualTo,
GreaterThanEqualTo,
// logical & bitwise
EqualTo,
NotEqualTo,
BitwiseOr,
BitwiseAnd,
BitwiseXor,
BitwiseInvert
}
// tealv5 supported types (typeEnum -> type mapping)
// https://developer.algorand.org/docs/get-details/dapps/avm/teal/opcodes/#txn-f
export const TxnTypeMap: {[key: string]: string} = {
1: 'pay',
3: 'acfg', // DeployASA OR RevokeAsset OR ModifyAsset OR DeleteAsset
4: 'axfer', // TransferAsset OR RevokeAsset,
5: 'afrz'
};
/**
* https://developer.algorand.org/docs/get-details/dapps/avm/teal/specification/#typeenum-constants
*/
export enum TransactionTypeEnum {
UNKNOWN = "unknown",
PAYMENT = "pay",
KEY_REGISTRATION = "keyreg",
ASSET_CONFIG = "acfg",
ASSET_TRANSFER = "axfer",
ASSET_FREEZE = "afrz",
APPLICATION_CALL = "appl",
} | the_stack |
import * as THREE from 'three';
import Game from './Game';
import Scene from './Scene';
import { loadSprite } from './scenery/isometric/sprites';
import SampleType from './data/sampleType';
import { BehaviourMode } from './loop/hero';
import { Time } from '../datatypes';
import { compile } from '../utils/shaders';
import Renderer from '../renderer';
import { getParams } from '../params';
import INNER_VERT from './shaders/magicball/inner.vert.glsl';
import INNER_FRAG from './shaders/magicball/inner.frag.glsl';
import GLOW_VERT from './shaders/magicball/glow.vert.glsl';
import GLOW_FRAG from './shaders/magicball/glow.frag.glsl';
import CLOUD_VERT from './shaders/magicball/cloud.vert.glsl';
import CLOUD_FRAG from './shaders/magicball/cloud.frag.glsl';
const isLBA1 = getParams().game === 'lba1';
const LBA1MagicBallMapping = {
8: 1,
9: 2,
10: 43,
11: 13,
};
const MAGIC_BALL_SPRITE = 8;
const INITIAL_SPEED = 6.0;
const COME_BACK_SPEED = 18.0;
const FETCH_KEY_SPEED = 8.0;
const SPEED_LIMIT = 10.0;
const GRAVITY_ACC = 0.002;
const ACTOR_BOX = new THREE.Box3();
const BALL_BOX = new THREE.Box3();
const TMP_VEC = new THREE.Vector3();
const ROTATION_AXIS = new THREE.Vector3(0, 1, 0);
const textureLoader = new THREE.TextureLoader();
const colorsPerLevel = {
0: [
new THREE.Color('#ffffd0'),
new THREE.Color('#fdfd2d'),
new THREE.Color('#f4bc20'),
new THREE.Color('#845810'),
],
1: [
new THREE.Color('#d1e7be'),
new THREE.Color('#80dc31'),
new THREE.Color('#37a92f'),
new THREE.Color('#15591e'),
],
2: [
new THREE.Color('#f9b381'),
new THREE.Color('#fe791a'),
new THREE.Color('#e8210a'),
new THREE.Color('#832e1a'),
],
3: [
new THREE.Color('#000000'),
new THREE.Color('#ffff00'),
new THREE.Color('#ff9400'),
new THREE.Color('#7a0d00'),
]
};
export enum MagicballStatus {
IDLE = 0,
HOLDING_IN_HAND = 1,
THROWING = 2,
COMING_BACK = 3
}
const use3DBall = getParams().ball3d;
/**
* This singleton class manages the magicball
* 3D model (or sprite) as well as its behaviour.
*/
export default class MagicBall {
static get instance() { return this._instance; }
get status(): MagicballStatus { return this._status; }
get threeObject(): THREE.Object3D { return this._threeObject; }
private game: Game;
private position = new THREE.Vector3();
private _threeObject?: THREE.Object3D;
private _status = MagicballStatus.IDLE;
private direction: THREE.Vector3;
private sprite?: any;
private bounces: number;
private maxBounces: number;
private normal = new THREE.Vector3();
private scene: Scene;
private isFetchingKey: boolean;
private static _instance: MagicBall = new MagicBall();
private constructor() {}
/**
* This method inits the magicball to the position
* from which it will be thrown.
* @param position
*/
async init(game: Game, scene: Scene, position: THREE.Vector3 = null) {
this.game = game;
if (this.scene !== scene) {
// Reset when changing scenes
this.scene = scene;
this._status = MagicballStatus.HOLDING_IN_HAND;
await this.loadModel();
}
if (this.status >= MagicballStatus.THROWING) {
return;
}
this.isFetchingKey = (scene.getKeys().length > 0);
this._status = MagicballStatus.HOLDING_IN_HAND;
if (position) {
this.setPosition(position);
}
scene.addMagicBall(this);
}
setPosition(position: THREE.Vector3) {
if (this._status >= MagicballStatus.THROWING) {
return;
}
this.position.copy(position);
if (this.threeObject) {
this.threeObject.position.copy(this.position);
}
}
update(time: Time) {
this.updateModel(time);
if (this._status < MagicballStatus.THROWING) {
return;
}
if (this._status === MagicballStatus.COMING_BACK) {
const hero = this.scene.actors[0];
this.direction.copy(hero.physics.position);
this.direction.y += 1;
this.direction.sub(this.position);
this.direction.normalize();
this.direction.multiplyScalar(time.delta * COME_BACK_SPEED);
this.position.add(this.direction);
if (this.position.distanceTo(hero.physics.position) < 1.5) {
this.stopBall();
}
this._threeObject.position.copy(this.position);
return;
}
TMP_VEC.copy(this.direction);
TMP_VEC.multiplyScalar(time.delta);
this.position.add(TMP_VEC);
this._threeObject.position.copy(this.position);
if (this.isFetchingKey) {
const key = this.scene.getKeys()[0];
if (!key) {
this.reset();
return;
}
if (this.position.distanceTo(key.physics.position) < 0.1) {
key.collectKey(this.game, this.scene);
this.triggerComeBack();
}
return;
}
this.direction.y -= GRAVITY_ACC / time.delta;
this.applySpeedLimit();
const bb = this.sprite
? this.sprite.boundingBox
: MagicBall.sphereGeometry.boundingBox;
BALL_BOX.copy(bb);
BALL_BOX.translate(this.position);
let hitActor = null;
for (let i = 1 /* skip hero */; i < this.scene.actors.length; i += 1) {
const a = this.scene.actors[i];
if ((a.model === null && a.sprite === null)
|| a.state.isDead
|| !(a.props.flags.hasCollisions || a.props.flags.isSprite)) {
continue;
}
const boundingBox = a.model ? a.model.boundingBox : a.sprite.boundingBox;
ACTOR_BOX.copy(boundingBox);
if (a.model) {
ACTOR_BOX.translate(a.physics.position);
} else {
ACTOR_BOX.applyMatrix4(a.threeObject.matrixWorld);
}
if (ACTOR_BOX.intersectsBox(BALL_BOX)) {
hitActor = a;
break;
}
}
if (hitActor) {
hitActor.hit(0 /* hero */, this.game.getState().hero.magicball.strength);
this.triggerComeBack();
return;
}
const ok = this.scene.scenery.physics.getNormal(
this.scene,
this.position,
bb,
this.normal
);
if (ok) {
// const arrowHelper = new THREE.ArrowHelper( normal, this.position, 2, 0xffff00 );
// this.scene.addMesh(arrowHelper);
// Move the ball away from the wall to ensure we don't immediately bounce again.
TMP_VEC.copy(this.normal).multiplyScalar(0.1);
this.position.add(TMP_VEC);
TMP_VEC.copy(this.normal).multiplyScalar(2 * this.normal.dot(this.direction));
this.direction.sub(TMP_VEC);
this.direction.multiplyScalar(0.8);
this.bounces += 1;
if (this.bounces > this.maxBounces) {
this.triggerComeBack(true);
return;
}
this.scene.actors[0].playSample(SampleType.MAGIC_BALL_BOUNCE);
}
if (this.position.y < 0) {
this.triggerComeBack(true);
}
}
private triggerComeBack(playSample = false) {
if (playSample) {
this.scene.actors[0].playSample(SampleType.MAGIC_BALL_STOP);
}
this._status = MagicballStatus.COMING_BACK;
}
private stopBall() {
this.scene.removeMagicBall();
this._status = MagicballStatus.IDLE;
}
reset(playSample = false) {
if (playSample) {
this.scene.actors[0].playSample(SampleType.MAGIC_BALL_STOP);
}
this.scene.removeMagicBall();
this._status = MagicballStatus.IDLE;
}
/**
* Throw the magicball with Twinsen's angle and behaviour
* deciding the trajectory.
* @param angle
* @param behaviour
* @returns Whether the ball was thrown.
*/
throw(angle: number, behaviour: number): boolean {
if (this._status >= MagicballStatus.THROWING) {
// Don't throw again if already throwing
return false;
}
const direction = new THREE.Vector3(0, 0.1, 1.1);
switch (behaviour) {
case BehaviourMode.AGGRESSIVE:
direction.z = 1.2;
break;
case BehaviourMode.DISCRETE:
direction.y = 0.5;
direction.z = 0.3;
break;
}
const euler = new THREE.Euler(0, angle, 0, 'XZY');
direction.applyEuler(euler);
// Offset the ball to line up with Twinsen's hand.
this.position.add(new THREE.Vector3(0, 1.45, 1).applyEuler(euler));
const perpendicularEluer = new THREE.Euler(0, angle - Math.PI / 2, 0, 'XZY');
const perpendicularDirection = new THREE.Vector3(0, 0, 0.25).applyEuler(perpendicularEluer);
this.position.add(perpendicularDirection.clone().multiplyScalar(0.5));
direction.multiplyScalar(INITIAL_SPEED);
return this.throwTowards(direction);
}
/**
* Throws the ball towards given direction
* @param direction
* @returns Whether the ball was thrown
*/
throwTowards(direction: THREE.Vector3): boolean {
if (this._status >= MagicballStatus.THROWING) {
// Don't throw again if already throwing
return false;
}
if (this.game.getState().hero.magicball.level < 4) {
this.scene.actors[0].playSample(SampleType.MAGIC_BALL_THROW);
} else {
this.scene.actors[0].playSample(SampleType.FIRE_BALL_THROW);
}
if (this._threeObject) {
this._threeObject.position.copy(this.position);
}
if (this.isFetchingKey) {
const key = this.scene.getKeys()[0];
if (!key) {
this.reset();
return;
}
const keyPos = key.physics.position;
this.direction = keyPos.clone()
.sub(this.position)
.normalize()
.multiplyScalar(FETCH_KEY_SPEED);
} else {
this.direction = direction.clone();
this.applySpeedLimit();
}
this.bounces = 0;
this.maxBounces = this.game.getState().hero.magicball.maxBounces;
if (this.game.getState().hero.magic <= 0) {
this.maxBounces = 0;
} else {
this.game.getState().hero.magic -= 1;
}
this._status = MagicballStatus.THROWING;
return true;
}
private applySpeedLimit() {
const speed = this.direction.length();
if (speed > SPEED_LIMIT) {
this.direction.normalize().multiplyScalar(SPEED_LIMIT);
}
}
private async loadModel() {
const magicLevel = Math.max(1, this.game.getState().hero.magicball.level) - 1;
let threeObject;
if ((this.game.vr && this.game.controlsState.firstPerson) || use3DBall) {
threeObject = await MagicBall.getBallModel(magicLevel);
} else {
threeObject = new THREE.Object3D();
threeObject.position.copy(this.position);
const type = MAGIC_BALL_SPRITE + magicLevel;
const sprite = await loadSprite(
isLBA1 ? LBA1MagicBallMapping[type] : type,
this.scene.props.ambience,
false, /* hasSpriteAnim3D */
true, /* isBillboard */
this.scene.is3DCam,
);
sprite.threeObject.material.transparent = true;
sprite.threeObject.scale.multiplyScalar(1);
threeObject.add(sprite.threeObject);
this.sprite = sprite;
}
threeObject.name = 'magicball';
threeObject.visible = true;
this._threeObject = threeObject;
}
private updateModel(time: Time) {
if (!this.threeObject) {
return;
}
if (this.sprite) {
const opacity = this._status === MagicballStatus.COMING_BACK ? 0.4 : 1;
this.sprite.threeObject.material.opacity = opacity;
} else {
const opacity = this._status === MagicballStatus.COMING_BACK ? 0.2 : 1;
const innerBall = this.threeObject.children[0] as THREE.Mesh;
(innerBall.material as THREE.RawShaderMaterial).uniforms.opacity.value = opacity;
const glow = this.threeObject.children[1] as THREE.Mesh;
(glow.material as THREE.RawShaderMaterial).uniforms.opacity.value = opacity;
const cloudLayer = this.threeObject.children[2] as THREE.Mesh;
cloudLayer.quaternion.setFromAxisAngle(ROTATION_AXIS, time.elapsed * 0.5);
const material = cloudLayer.material as THREE.RawShaderMaterial;
material.uniforms.opacity.value = opacity;
material.uniforms.uNormalMatrix.value.setFromMatrix4(
cloudLayer.matrixWorld
);
}
}
private static ballModelPromise: Promise<THREE.Object3D>;
private static sphereGeometry: THREE.IcosahedronGeometry = null;
private static glowMaterial: THREE.RawShaderMaterial = null;
private static cloudMaterial: THREE.RawShaderMaterial = null;
private static innerMaterial: THREE.RawShaderMaterial = null;
private static async getBallModel(magicLevel: number): Promise<THREE.Object3D> {
if (!this.ballModelPromise) {
this.ballModelPromise = this.loadBallModel();
}
await this.ballModelPromise;
this.setMagicLevel(magicLevel);
return this.ballModelPromise;
}
private static setMagicLevel(magicLevel) {
const colors = colorsPerLevel[magicLevel];
this.cloudMaterial.uniforms.color.value.copy(colors[0]);
this.glowMaterial.uniforms.color.value.copy(colors[2]);
this.innerMaterial.uniforms.color1.value.copy(colors[1]);
this.innerMaterial.uniforms.color2.value.copy(colors[2]);
this.innerMaterial.uniforms.color3.value.copy(colors[3]);
}
private static async loadBallModel(): Promise<THREE.Object3D> {
const cloudTexture = await textureLoader.loadAsync('images/magicball_clouds.png');
this.sphereGeometry = new THREE.IcosahedronGeometry(0.1, 5);
this.sphereGeometry.computeBoundingBox();
this.glowMaterial = new THREE.RawShaderMaterial({
vertexShader: compile('vert', GLOW_VERT),
fragmentShader: compile('frag', GLOW_FRAG),
transparent: true,
side: THREE.BackSide,
uniforms: {
color: { value: new THREE.Color() },
opacity: { value: 1 },
},
glslVersion: Renderer.getGLSLVersion()
});
this.cloudMaterial = new THREE.RawShaderMaterial({
vertexShader: compile('vert', CLOUD_VERT),
fragmentShader: compile('frag', CLOUD_FRAG),
transparent: true,
uniforms: {
color: { value: new THREE.Color() },
clouds: { value: cloudTexture },
uNormalMatrix: { value: new THREE.Matrix3() },
opacity: { value: 1 },
},
glslVersion: Renderer.getGLSLVersion()
});
this.innerMaterial = new THREE.RawShaderMaterial({
vertexShader: compile('vert', INNER_VERT),
fragmentShader: compile('frag', INNER_FRAG),
transparent: true,
uniforms: {
color1: { value: new THREE.Color() },
color2: { value: new THREE.Color() },
color3: { value: new THREE.Color() },
opacity: { value: 1 },
},
glslVersion: Renderer.getGLSLVersion()
});
const ball = new THREE.Object3D();
const cloudLayer = new THREE.Mesh(this.sphereGeometry, this.cloudMaterial);
const glow = new THREE.Mesh(this.sphereGeometry, this.glowMaterial);
const innerBall = new THREE.Mesh(this.sphereGeometry, this.innerMaterial);
glow.scale.setScalar(1.2);
glow.renderOrder = 1;
innerBall.scale.setScalar(0.92);
innerBall.renderOrder = 2;
cloudLayer.renderOrder = 3;
ball.add(innerBall);
ball.add(glow);
ball.add(cloudLayer);
return ball;
}
} | the_stack |
import tl = require("azure-pipelines-task-lib/task");
import util = require("util");
import { Utility, GitHubAttributes, IRepositoryIssueId, Delimiters, AzureDevOpsVariables, ChangeLogStartCommit, GitHubIssueState, ChangeLogType } from "./Utility";
import { Release } from "./Release";
import { Helper } from "./Helper";
export class ChangeLog {
/**
* Returns the change log.
* @param githubEndpointToken
* @param repositoryName
* @param target
* @param top
* @param compareWithRelease
* @param changeLogType
* @param changeLogCompareToReleaseTag
* @param changeLogLabels
*/
public async getChangeLog(githubEndpointToken: string, repositoryName: string, target: string, top: number, compareWithRelease: ChangeLogStartCommit, changeLogType: string, changeLogCompareToReleaseTag?: string, changeLogLabels?: any[]): Promise<string> {
console.log(tl.loc("ComputingChangeLog"));
let release = new Release();
// We will be fetching changes between startCommitSha...endCommitSha.
// endCommitSha: It is the current commit
// startCommitSha: It is the commit for which previous release was created
// If no previous release found, then it will be the first commit.
// Get the curent commit.
let endCommitSha: string = await new Helper().getCommitShaFromTarget(githubEndpointToken, repositoryName, target);
//Get the start commit.
let startCommitSha: string = await this.getStartCommitSha(githubEndpointToken, repositoryName, endCommitSha, top,compareWithRelease, changeLogCompareToReleaseTag);
// Compare the diff between 2 commits.
tl.debug("start commit: "+ startCommitSha + "; end commit: "+ endCommitSha);
console.log(tl.loc("FetchCommitDiff"));
let commitsListResponse = await release.getCommitsList(githubEndpointToken, repositoryName, startCommitSha, endCommitSha);
tl.debug("Get commits list response: " + JSON.stringify(commitsListResponse));
if (commitsListResponse.statusCode === 200) {
// If end commit is older than start commit i.e. Rollback scenario, we will not show any change log.
if (commitsListResponse.body[GitHubAttributes.status] === GitHubAttributes.behind) {
tl.warning(tl.loc("CommitDiffBehind"));
return "";
}
else {
let commits: any[] = commitsListResponse.body[GitHubAttributes.commits] || [];
// If endCommit and startCommit are same then also we will not show any change log.
if (commits.length === 0) {
console.log(tl.loc("CommitDiffEqual"));
return "";
}
console.log(tl.loc("FetchCommitDiffSuccess"));
// Reversing commits as commits retrieved are in oldest first order
commits = commits.reverse();
// Only show changeLog for top X commits, where X = top
// Form the commitId to issues dictionary
let commitIdToMessageDictionary: { [key: string]: string } = this._getCommitIdToMessageDictionary(commits.length > top ? commits.slice(0, top) : commits);
tl.debug("commitIdToMessageDictionary: " + JSON.stringify(commitIdToMessageDictionary));
let commitIdToRepoIssueIdsDictionary: { [key: string]: Set<string> } = this._getCommitIdToRepoIssueIdsDictionary(commitIdToMessageDictionary, repositoryName);
tl.debug("commitIdToRepoIssueIdsDictionary: " + JSON.stringify(commitIdToRepoIssueIdsDictionary));
if (changeLogType === ChangeLogType.commitBased) {
return this._getCommitBasedChangeLog(commitIdToRepoIssueIdsDictionary, commitIdToMessageDictionary, repositoryName);
}
else {
let issues = new Set([]);
Object.keys(commitIdToRepoIssueIdsDictionary).forEach((commitId: string) => {
if (issues.size >= top) {
return;
}
commitIdToRepoIssueIdsDictionary[commitId].forEach(repoIssueId => {
if (issues.size >= top) {
return;
}
let issueDetails = Utility.extractRepoAndIssueId(repoIssueId);
let issueId = Number(issueDetails.issueId);
if (!!issueId && issueDetails.repository === repositoryName) {
issues.add(issueId);
}
});
});
if (!!changeLogLabels && !!changeLogLabels.length) {
return this._getIssueBasedChangeLog(Array.from(issues), repositoryName, release, githubEndpointToken, changeLogLabels);
}
else {
return this._getAllIssuesChangeLog(Array.from(issues), repositoryName, release, githubEndpointToken);
}
}
}
}
else{
tl.error(tl.loc("FetchCommitDiffError"));
throw new Error(commitsListResponse.body[GitHubAttributes.message]);
}
}
/**
* Generate issue based ChangeLog
* @param issues
* @param repositoryName
* @param release
* @param githubEndpointToken
* @param labels
*/
private async _getIssueBasedChangeLog(issues: number[], repositoryName: string, release: Release, githubEndpointToken: string, labels: any[]) {
if (issues.length === 0) {
console.log(tl.loc("NoIssuesLinkedError"));
return "";
}
let issuesListResponse = await release.getIssuesList(githubEndpointToken, repositoryName, issues, true);
if (issuesListResponse.statusCode === 200) {
if (!!issuesListResponse.body.errors) {
console.log(tl.loc("IssuesFetchError"));
tl.warning(JSON.stringify(issuesListResponse.body.errors));
return "";
}
else {
let changeLog: string = "";
let topXChangeLog: string = ""; // where 'X' is the this._changeLogVisibleLimit.
let seeMoreChangeLog: string = "";
let index = 0;
let issuesList = issuesListResponse.body.data.repository;
tl.debug("issuesListResponse: " + JSON.stringify(issuesList));
let labelsRankDictionary = this._getLabelsRankDictionary(labels);
tl.debug("labelsRankDictionary: " + JSON.stringify(labelsRankDictionary));
let groupedIssuesDictionary = this._getGroupedIssuesDictionary(labelsRankDictionary, issuesList, labels);
tl.debug("Group wise issues : " + JSON.stringify(groupedIssuesDictionary));
Object.keys(groupedIssuesDictionary).forEach((group: string) => {
if (groupedIssuesDictionary[group].length === 0) return;
//If the only category is the default cateogry, don't add the category title.
if (index > 0 || group!= this._defaultGroup){
let changeLogGroupTitle = util.format(this._groupTitleFormat, group);
if (index >= this._changeLogVisibleLimit) {
seeMoreChangeLog = seeMoreChangeLog + changeLogGroupTitle + Delimiters.newLine;
}
else {
topXChangeLog = topXChangeLog + changeLogGroupTitle + Delimiters.newLine;
index++;
}
}
groupedIssuesDictionary[group].forEach(issueDetails => {
let changeLogPerIssue: string = this._getChangeLogPerIssue(issueDetails.id, issueDetails.issue);
if (index >= this._changeLogVisibleLimit) {
seeMoreChangeLog = seeMoreChangeLog + changeLogPerIssue + Delimiters.newLine;
}
else {
topXChangeLog = topXChangeLog + changeLogPerIssue + Delimiters.newLine;
index++;
}
});
});
changeLog = this._generateChangeLog(topXChangeLog, seeMoreChangeLog);
console.log(tl.loc("ComputingChangeLogSuccess"));
return changeLog;
}
}
else {
console.log(tl.loc("IssuesFetchError"));
tl.warning(issuesListResponse.body[GitHubAttributes.message]);
return "";
}
}
/**
* Generate all issue based ChangeLog without labels
* @param issues
* @param repositoryName
* @param release
* @param githubEndpointToken
*/
private async _getAllIssuesChangeLog(issues: number[], repositoryName: string, release: Release, githubEndpointToken: string) {
if (issues.length === 0) {
console.log(tl.loc("NoIssuesLinkedError"));
return "";
}
let issuesListResponse = await release.getIssuesList(githubEndpointToken, repositoryName, issues, false);
if (issuesListResponse.statusCode === 200) {
if (!!issuesListResponse.body.errors) {
console.log(tl.loc("IssuesFetchError"));
tl.warning(JSON.stringify(issuesListResponse.body.errors));
return "";
}
else {
let changeLog: string = "";
let topXChangeLog: string = ""; // where 'X' is the this._changeLogVisibleLimit.
let seeMoreChangeLog: string = "";
let issuesList = issuesListResponse.body.data.repository;
tl.debug("issuesListResponse: " + JSON.stringify(issuesList));
Object.keys(issuesList).forEach((key: string, index: number) => {
let changeLogPerIssue = this._getChangeLogPerIssue(key.substr(1), issuesList[key].title);
// See more functionality
if (index >= this._changeLogVisibleLimit) {
seeMoreChangeLog = seeMoreChangeLog + changeLogPerIssue + Delimiters.newLine;
}
else {
topXChangeLog = topXChangeLog + changeLogPerIssue + Delimiters.newLine;
}
});
changeLog = this._generateChangeLog(topXChangeLog, seeMoreChangeLog);
console.log(tl.loc("ComputingChangeLogSuccess"));
return changeLog;
}
}
else {
console.log(tl.loc("IssuesFetchError"));
tl.warning(issuesListResponse.body[GitHubAttributes.message]);
return "";
}
}
/**
* Generate commit based ChangeLog
* @param commitIdToRepoIssueIdsDictionary
* @param commitIdToMessageDictionary
* @param repositoryName
*/
private async _getCommitBasedChangeLog(commitIdToRepoIssueIdsDictionary: { [key: string]: Set<string> }, commitIdToMessageDictionary: { [key: string]: string }, repositoryName: string){
let changeLog: string = "";
let topXChangeLog: string = ""; // where 'X' is the this._changeLogVisibleLimit.
let seeMoreChangeLog: string = "";
// Evaluate change log
Object.keys(commitIdToRepoIssueIdsDictionary).forEach((commitId: string, index: number) => {
let changeLogPerCommit: string = this._getChangeLogPerCommit(commitId, commitIdToMessageDictionary[commitId], commitIdToRepoIssueIdsDictionary[commitId], repositoryName);
//See more functionality
// If changes are more than 10, then we will show See more button which will be collapsible.
// And under that seeMoreChangeLog will be shown
// topXChangeLog will be visible to user.
if (index >= this._changeLogVisibleLimit) {
seeMoreChangeLog = seeMoreChangeLog + changeLogPerCommit + Delimiters.newLine;
}
else {
topXChangeLog = topXChangeLog + changeLogPerCommit + Delimiters.newLine;
}
});
changeLog = this._generateChangeLog(topXChangeLog, seeMoreChangeLog);
console.log(tl.loc("ComputingChangeLogSuccess"));
return changeLog;
}
/**
* Returns the start commit needed to compute ChangeLog.
* @param githubEndpointToken
* @param repositoryName
* @param endCommitSha
* @param top
* @param compareWithRelease
* @param changeLogCompareToReleaseTag
*/
public async getStartCommitSha(githubEndpointToken: string, repositoryName: string, endCommitSha: string, top: number, compareWithRelease: ChangeLogStartCommit, changeLogCompareToReleaseTag?: string): Promise<string> {
let release = new Release();
let startCommitSha: string;
if (compareWithRelease === ChangeLogStartCommit.lastFullRelease) {
// Get the latest published release to compare the changes with.
console.log(tl.loc("FetchLatestPublishRelease"));
let latestReleaseResponse = await release.getLatestRelease(githubEndpointToken, repositoryName);
tl.debug("Get latest release response: " + JSON.stringify(latestReleaseResponse));
// Get the start commit.
// Release has target_commitsh property but it can be branch name also.
// Hence if a release is present, then get the tag and find its corresponding commit.
// Else get the first commit.
if (latestReleaseResponse.statusCode !== 200 && latestReleaseResponse.statusCode !== 404) {
tl.error(tl.loc("GetLatestReleaseError"));
throw new Error(latestReleaseResponse.body[GitHubAttributes.message]);
}
else if (latestReleaseResponse.statusCode !== 404 && latestReleaseResponse.body && !!latestReleaseResponse.body[GitHubAttributes.tagName]) {
let latestReleaseTag: string = latestReleaseResponse.body[GitHubAttributes.tagName];
tl.debug("latest release tag: " + latestReleaseTag);
let latestReleaseUrl: string = latestReleaseResponse.body[GitHubAttributes.htmlUrl];
console.log(tl.loc("FetchLatestPublishReleaseSuccess", latestReleaseUrl));
startCommitSha = await this._getCommitForTag(githubEndpointToken, repositoryName, latestReleaseTag);
}
else {
console.log(tl.loc("NoLatestPublishRelease"));
console.log(tl.loc("FetchInitialCommit"));
startCommitSha = await this._getInitialCommit(githubEndpointToken, repositoryName, endCommitSha, top);
console.log(tl.loc("FetchInitialCommitSuccess", startCommitSha));
}
return startCommitSha;
}
let comparer;
if (compareWithRelease === ChangeLogStartCommit.lastNonDraftRelease) {
//Latest non-draft Release
console.log(tl.loc("FetchLatestNonDraftRelease"));
comparer = release => !release[GitHubAttributes.draft];
}
else {
//Latest release with the given tag or matching the given regex.
console.log(tl.loc("FetchLastReleaseByTag", changeLogCompareToReleaseTag));
comparer = release => !release[GitHubAttributes.draft] && Utility.isTagMatching(release[GitHubAttributes.tagName], changeLogCompareToReleaseTag);
}
let initialTag = await this.getLastReleaseTag(githubEndpointToken, repositoryName, comparer);
//If no such release exists, get the start commit
//else get the commit for that tag.
if (!initialTag) {
(compareWithRelease === ChangeLogStartCommit.lastNonDraftRelease) && console.log(tl.loc("NoMatchingReleases"));
(compareWithRelease === ChangeLogStartCommit.lastNonDraftReleaseByTag) && console.log(tl.loc("NoTagMatchingReleases", changeLogCompareToReleaseTag));
console.log(tl.loc("FetchInitialCommit"));
startCommitSha = await this._getInitialCommit(githubEndpointToken, repositoryName, endCommitSha, top);
console.log(tl.loc("FetchInitialCommitSuccess", startCommitSha));
}
else {
(compareWithRelease === ChangeLogStartCommit.lastNonDraftRelease) && console.log(tl.loc("FetchMatchingReleaseSuccess"));
(compareWithRelease === ChangeLogStartCommit.lastNonDraftReleaseByTag) && console.log(tl.loc("FetchTagMatchingReleaseSuccess", changeLogCompareToReleaseTag));
startCommitSha = await this._getCommitForTag(githubEndpointToken, repositoryName, initialTag);
}
return startCommitSha;
}
/**
* Returns latest release satisfying the given comparer.
* @param githubEndpointToken
* @param repositoryName
* @param comparer
*/
public async getLastReleaseTag(githubEndpointToken: string, repositoryName: string, comparer:(release: any)=> boolean): Promise<string> {
let release = new Release();
// Fetching all releases in the repository. Sorted in descending order according to 'created_at' attribute.
let releasesResponse = await release.getReleases(githubEndpointToken, repositoryName);
let links: { [key: string]: string } = {};
// Fetching releases api call may end up in paginated results.
// Traversing all the pages and filtering all the releases with given tag.
while (true) {
tl.debug("Get releases response: " + JSON.stringify(releasesResponse));
let startRelease: any;
//404 is returned when there are no releases.
if (releasesResponse.statusCode !== 200 && releasesResponse.statusCode !== 404){
tl.error(tl.loc("GetLatestReleaseError"));
throw new Error(releasesResponse.body[GitHubAttributes.message]);
}
else if (releasesResponse.statusCode === 200) {
// Filter the releases fetched
startRelease = (releasesResponse.body || []).find(comparer);
if (!!startRelease) {
return startRelease[GitHubAttributes.tagName];
}
links = Utility.parseHTTPHeaderLink(releasesResponse.headers[GitHubAttributes.link]);
// Calling the next page if it exists
if (links && links[GitHubAttributes.next]) {
let paginatedResponse = await release.getPaginatedResult(githubEndpointToken, links[GitHubAttributes.next]);
releasesResponse = paginatedResponse;
continue;
}
}
//If status code is 404 or there are no releases satisfying the constraints return null.
return null;
}
}
/**
* Returns the commit for provided tag
* @param githubEndpointToken
* @param repositoryName
* @param tag
*/
private async _getCommitForTag(githubEndpointToken: string, repositoryName: string, tag: string): Promise<string> {
let filteredTag: any = await new Helper().filterTag(githubEndpointToken, repositoryName, tag, this._filterTagsByTagName);
return filteredTag && filteredTag[GitHubAttributes.commit][GitHubAttributes.sha];
}
/**
* Returns a commit which is 'X' (top) commits older than the provided commit sha.
* @param githubEndpointToken
* @param repositoryName
* @param sha
*/
private async _getInitialCommit(githubEndpointToken: string, repositoryName: string, sha: string, top: number): Promise<string> {
let release = new Release();
// No api available to get first commit directly.
// So, fetching all commits before the current commit sha.
// Returning last commit or 250th commit which ever is smaller.
let commitsForGivenShaResponse = await release.getCommitsBeforeGivenSha(githubEndpointToken, repositoryName, sha);
let links: { [key: string]: string } = {};
let commits: any[] = [];
while(true) {
tl.debug("Get initial commit response: " + JSON.stringify(commitsForGivenShaResponse));
if (commitsForGivenShaResponse.statusCode === 200) {
// Returned commits are in latest first order and first commit is the commit queried itself.
(commitsForGivenShaResponse.body || []).forEach(commit => {
commits.push(commit);
});
if (commits.length >= top) {
// Return 250th commit
return commits[top - 1][GitHubAttributes.sha];
}
links = Utility.parseHTTPHeaderLink(commitsForGivenShaResponse.headers[GitHubAttributes.link]);
// Calling the next page if it exists
if (links && links[GitHubAttributes.next]) {
let paginatedResponse = await release.getPaginatedResult(githubEndpointToken, links[GitHubAttributes.next]);
commitsForGivenShaResponse = paginatedResponse;
continue;
}
else {
// Return last commit.
return commits[commits.length - 1][GitHubAttributes.sha];
}
}
else {
tl.error(tl.loc("FetchInitialCommitError"));
throw new Error(commitsForGivenShaResponse.body[GitHubAttributes.message]);
}
}
}
/**
* Returns a dictionary of { commitId to commit message }.
* @param commits
*/
private _getCommitIdToMessageDictionary(commits: any[]): { [key: string]: string } {
let commitIdToMessageDictionary: { [key: string]: string } = {};
for (let commit of (commits || [])) {
commitIdToMessageDictionary[commit[GitHubAttributes.sha]] = commit[GitHubAttributes.commit][GitHubAttributes.message];
}
return commitIdToMessageDictionary;
}
/**
* Returns a dictionary of { commitId to repoIssueIds }.
* @param commitIdToMessageDictionary
* @param repositoryName
*/
private _getCommitIdToRepoIssueIdsDictionary(commitIdToMessageDictionary: { [key: string]: string }, repositoryName: string): { [key: string]: Set<string> } {
let commitIdToRepoIssueIdsDictionary: { [key: string]: Set<string> } = {};
Object.keys(commitIdToMessageDictionary).forEach((commitId: string) => {
commitIdToRepoIssueIdsDictionary[commitId] = this._getRepoIssueIdFromCommitMessage(commitIdToMessageDictionary[commitId], repositoryName);
});
return commitIdToRepoIssueIdsDictionary;
}
/**
* Returns a dictionary of { key to displayname, rank }.
* Key is labelname#issuestate
* This dictionary is used to find the label with highest priority.
* @param labels
*/
private _getLabelsRankDictionary(labels: any[]){
let labelsRankDictionary = {};
for (let index = 0; index < labels.length; index++){
if (!labels[index].label || !labels[index].displayName) continue;
let label = labels[index].label;
let issueState = labels[index].state || this._noStateSpecified;
let key = (label+ Delimiters.hash +issueState).toLowerCase();
if (!labelsRankDictionary[key]){
labelsRankDictionary[key] = {displayName: labels[index].displayName, rank: index};
}
}
return labelsRankDictionary;
}
/**
* Returns a dictionary of { groupname to issues }.
* This dictionary is used to find all the issues under a display name.
* @param labelsRankDictionary
* @param issuesList
*/
private _getGroupedIssuesDictionary(labelsRankDictionary, issuesList, labels){
let labelsIssuesDictionary = {};
labels.forEach(label => {
if (!label.displayName) return;
labelsIssuesDictionary[label.displayName] = [];
});
labelsIssuesDictionary[this._defaultGroup] = [];
Object.keys(issuesList).forEach((issue: string) => {
let group: string = null;
let currentLabelRank: number = Number.MAX_SAFE_INTEGER;
let issueState = issuesList[issue].state;
//For Pull Requests, show only Merged PRs, Ignore Closed PRs
if (!!issuesList[issue].changedFiles){
if(issueState.toLowerCase() === GitHubIssueState.merged.toLowerCase()){
issueState = GitHubIssueState.closed;
}
else if (issueState.toLowerCase() === GitHubIssueState.closed.toLowerCase()){
return;
}
}
issuesList[issue].labels.edges && issuesList[issue].labels.edges.forEach(labelDetails => {
let key = (labelDetails.node.name + Delimiters.hash + issueState).toLowerCase();
if(!labelsRankDictionary[key]) {
key = (labelDetails.node.name + Delimiters.hash + this._noStateSpecified).toLowerCase();
}
if (labelsRankDictionary[key] && labelsRankDictionary[key].rank < currentLabelRank){
group = labelsRankDictionary[key].displayName;
currentLabelRank = labelsRankDictionary[key].rank;
}
});
if (currentLabelRank === Number.MAX_SAFE_INTEGER){
group = this._defaultGroup; //Default category
}
labelsIssuesDictionary[group].push({"issue": issuesList[issue].title, "id": issue.substr(1)});
});
return labelsIssuesDictionary;
}
/**
* Returns the log for a single issue.
* Log format: * #issueId: issueTitle
* @param issueId
* @param issueTitle
*/
private _getChangeLogPerIssue(issueId: number | string, issueTitle: string){
return Delimiters.star + Delimiters.space + Delimiters.hash + issueId + Delimiters.colon + Delimiters.space + issueTitle;
}
/**
* Filter tags by tag name.
* Returns tag object.
*/
private _filterTagsByTagName = (tagsList: any[], tagName: string): any[] => {
let filteredTags: any[] = [];
(tagsList || []).forEach((tag: any) => {
if (tag[GitHubAttributes.nameAttribute] === tagName) {
filteredTags.push(tag);
}
});
return filteredTags;
}
/**
* Returns a unique set of repository#issueId string for each issue mentioned in the commit.
* repository#issueId string is needed as issues can be of cross repository.
* @param message
* @param repositoryName
*/
private _getRepoIssueIdFromCommitMessage(message: string, repositoryName: string): Set<string> {
let match = undefined;
let repoIssueIdSet: Set<string> = new Set();
// regex.exec(message) will return one match at a time.
// Multiple execution will yield all matches.
// Returns undefined if no further match found.
// match is an array, where match[0] is the complete match
// and other match[i] gives the captured strings in order.
// In our regex, we have captured repository name and issueId resp.
while (match = this._issueRegex.exec(message)) {
tl.debug("match: " + match[0]);
tl.debug("match1: " + match[1]);
tl.debug("match2: " + match[2]);
tl.debug("repositoryName: " + repositoryName);
// If no repository name found before an issue, then use user provided repository name to link it to issue
let repo: string = match[1] ? match[1] : repositoryName;
let issueId: string = match[2];
// Using # as separator as neither repoName nor issueId will have #.
let uniqueRepoIssueId: string = repo + Delimiters.hash + issueId;
tl.debug("uniqueRepoIssueId: " + uniqueRepoIssueId);
// Message can contain same issue linked multiple times.
// Do not add an issue if its already added.
if (!repoIssueIdSet.has(uniqueRepoIssueId)) {
repoIssueIdSet.add(uniqueRepoIssueId);
}
}
return repoIssueIdSet;
}
/**
* Returns the log for a single commit.
* Log format: * commitId commitMessageTitle, [ #issueId1, #issueId2 ]
* @param commitId
* @param commitMessage
* @param repoIssueIdSet
* @param repositoryName
*/
private _getChangeLogPerCommit(commitId: string, commitMessage: string, repoIssueIdSet: Set<string>, repositoryName: string): string {
// GitHub commit messages have description as well alongwith title.
// Parsing the commit title and showing to user.
let commitMessageFirstLine: string = Utility.getFirstLine(commitMessage);
// Log format without issues: * commitId commitMessageTitle
let log: string = Delimiters.star + Delimiters.space + commitId + Delimiters.space + commitMessageFirstLine;
let issuesText: string = "";
// Appending each issue mentioned in the commit message.
// Ignoring issue which is present in commit title, to avoid duplicates.
if (!!repoIssueIdSet && repoIssueIdSet.size > 0) {
(repoIssueIdSet).forEach((repoIssueId: string) => {
// Extract repository information for issue as cross repository issues can also be present.
let repoIssueIdInfo: IRepositoryIssueId = Utility.extractRepoAndIssueId(repoIssueId);
let issueIdText: string = "";
// If issue belongs to cross repository, then prefix repository name to issueId so that it can be linked correctly in GitHub.
if (repoIssueIdInfo.repository !== repositoryName) {
issueIdText += repoIssueIdInfo.repository;
}
// # is required before issueId for referencing purpose in GitHub.
issueIdText = issueIdText + Delimiters.hash + repoIssueIdInfo.issueId;
// If this issue is not present in commit title, then append to issues text.
if (!commitMessageFirstLine.includes(issueIdText)) {
if (!!issuesText) {
// Append comma after every issue
issuesText += Delimiters.comma;
}
issuesText = issuesText + Delimiters.space + issueIdText;
}
});
}
// If issues are present, then enclose it in brackets and append to log.
if (!!issuesText) {
log = log + Delimiters.openingBracketWithSpace + issuesText + Delimiters.closingBracketWithSpace;
}
return log;
}
private _getAutoGeneratedText(): string {
let autoGeneratedUrl: string = encodeURI(this._getAutoGeneratedUrl());
if (!!autoGeneratedUrl) {
return util.format(this._autoGeneratedTextFormat, autoGeneratedUrl);
}
return "";
}
private _generateChangeLog(topXChangeLog: string, seeMoreChangeLog: string): string {
let changeLog: string = "";
if (topXChangeLog) {
changeLog = util.format(this._changeLogTitleFormat, this._changeLogTitle) + topXChangeLog;
if(!seeMoreChangeLog) {
changeLog = changeLog + Delimiters.newLine + this._getAutoGeneratedText();
}
else {
changeLog = changeLog + util.format(this._seeMoreChangeLogFormat, this._seeMoreText, seeMoreChangeLog, this._getAutoGeneratedText());
}
}
return changeLog;
}
private _getAutoGeneratedUrl(): string {
let releaseUrl: string = tl.getVariable(AzureDevOpsVariables.releaseWebUrl);
if (!!releaseUrl) {
tl.debug("release web url: " + releaseUrl);
return releaseUrl;
}
else {
let collectionUri: string = tl.getVariable(AzureDevOpsVariables.collectionUri);
// Make sure collection uri does not end with slash
if (collectionUri.endsWith(Delimiters.slash)) {
collectionUri = collectionUri.slice(0, collectionUri.length - 1);
}
let teamProject: string = tl.getVariable(AzureDevOpsVariables.teamProject);
let buildId: string = tl.getVariable(AzureDevOpsVariables.buildId);
tl.debug("Build url: " + util.format(this._buildUrlFormat, collectionUri, teamProject, buildId));
return util.format(this._buildUrlFormat, collectionUri, teamProject, buildId);
}
}
// https://github.com/moby/moby/commit/df23a1e675c7e3cbad617374d85c48103541ee14?short_path=6206c94#diff-6206c94cde21ec0a5563c8369b71e609
// Supported format for GitHub issues: #26 GH-26 repositoryName#26 repositoryNameGH-26, where GH is case in-sensitive.
private readonly _issueRegex = new RegExp("(?:^|[^A-Za-z0-9_]?)([a-z0-9_]+/[a-zA-Z0-9-_.]+)?(?:#|[G|g][H|h]-)([0-9]+)(?:[^A-Za-z_]|$)", "gm");
private readonly _changeLogTitle: string = tl.loc("ChangeLogTitle");
private readonly _seeMoreText: string = tl.loc("SeeMoreText");
private readonly _noStateSpecified: string = "none";
private readonly _defaultGroup: string = tl.loc("DefaultCategory");
private readonly _changeLogVisibleLimit: number = 10;
private readonly _changeLogTitleFormat: string = "\n\n## %s:\n\n";
private readonly _groupTitleFormat: string = "\n### %s:\n\n";
private readonly _buildUrlFormat: string = "%s/%s/_build/results?buildId=%s&view=logs";
private readonly _autoGeneratedTextFormat: string = "This list of changes was [auto generated](%s).";
private readonly _seeMoreChangeLogFormat: string = "<details><summary><b>%s</b></summary>\n\n%s\n%s</details>"; // For showing See more button if more than 10 commits message are to be shown to user.
} | the_stack |
import { BigNumber, Contract as EthersContract } from "ethers"
import { defaultAbiCoder, TransactionDescription } from "@ethersproject/abi"
import { Log } from "@ethersproject/abstract-provider"
import { FunctionFragment, LogDescription } from "ethers/lib/utils"
import pLimit from "p-limit"
import VError from "verror"
import { transactionHash } from "./utils/regEx"
import EtherscanClient from "./clients/EtherscanClient"
import EthereumNodeClient from "./clients/EthereumNodeClient"
const debug = require("debug")("tx2uml")
export enum MessageType {
Unknown,
Call,
Create,
Selfdestruct,
DelegateCall,
StaticCall,
}
export type Param = {
name: string
type: string
value?: string
components?: Param[]
}
export type Trace = {
id: number
type: MessageType
from: string
// For child traces of delegate calls. delegatedFrom = the parent delegate call's to address
delegatedFrom: string
to: string
value: BigNumber
funcSelector?: string
funcName?: string
inputs?: string
inputParams?: Param[]
parsedConstructorParams?: boolean
outputs?: string
outputParams?: Param[]
proxy?: boolean
gasLimit: BigNumber
gasUsed: BigNumber
parentTrace?: Trace
childTraces: Trace[]
depth: number
error?: string
}
export type Event = {
name: string
params: Param[]
}
export type Contract = {
address: string
contractName?: string
appName?: string
balance?: number
tokenName?: string
symbol?: string
decimals?: number
proxyImplementation?: string
ethersContract?: EthersContract
delegatedToContracts?: Contract[]
constructorInputs?: string
events?: Event[]
minDepth?: number
}
export type TokenDetails = {
address: string
name?: string
symbol?: string
decimals?: number
}
export type Contracts = { [address: string]: Contract }
export type Token = {
address: string
name: string
symbol: string
decimals?: number
totalSupply?: BigNumber
}
export type Transfer = {
from: string
to: string
value: BigNumber
ether: boolean
tokenAddress?: string
tokenSymbol?: string
tokenName?: string
decimals?: number
}
export interface TransactionDetails {
hash: string
from: string
to: string
data: string
nonce: number
index: number
value: BigNumber
gasPrice: BigNumber
gasLimit: BigNumber
gasUsed: BigNumber
timestamp: Date
status: boolean
blockNumber: number
logs: Array<Log>
error?: string
}
type ParamTypeInternal = {
name: string
type: string
baseType: string
components?: ParamTypeInternal[]
}
export type Networks = "mainnet" | "ropsten" | "rinkeby" | "kovan"
export class TransactionManager {
constructor(
public readonly ethereumNodeClient: EthereumNodeClient,
public readonly etherscanClient: EtherscanClient,
// 3 works for smaller contracts but Etherscan will rate limit on larger contracts when set to 3
public apiConcurrencyLimit = 2
) {}
async getTransactions(
txHashes: string | string[]
): Promise<TransactionDetails[]> {
const transactions: TransactionDetails[] = []
for (const txHash of txHashes) {
if (!txHash?.match(transactionHash)) {
console.error(
`Array of transaction hashes must be in hexadecimal format with a 0x prefix`
)
process.exit(1)
}
transactions.push(await this.getTransaction(txHash))
}
return transactions
}
async getTransaction(txHash: string): Promise<TransactionDetails> {
return this.ethereumNodeClient.getTransactionDetails(txHash)
}
async getTraces(transactions: TransactionDetails[]): Promise<Trace[][]> {
const transactionsTraces: Trace[][] = []
for (const transaction of transactions) {
transactionsTraces.push(
await this.ethereumNodeClient.getTransactionTrace(
transaction.hash
)
)
}
return transactionsTraces
}
async getContracts(transactionsTraces: Trace[][]): Promise<Contracts> {
const flatTraces = transactionsTraces.flat()
const participantAddresses: string[] = []
// for each contract, maps all the contract addresses it can delegate to.
// eg maps from a proxy contract to an implementation
// or maps a contract calls for many libraries
const delegatesToContracts: { [address: string]: string[] } = {}
for (const trace of Object.values(flatTraces)) {
// duplicates are ok. They will be filtered later
participantAddresses.push(trace.from)
participantAddresses.push(trace.to)
// If trace is a delegate call
if (trace.type === MessageType.DelegateCall) {
// If not already mapped to calling contract
if (!delegatesToContracts[trace.from]) {
// Start a new list of contracts that are delegated to
delegatesToContracts[trace.from] = [trace.to]
} else if (
// if contract has already been mapped and
// contract it delegates to has not already added
!delegatesToContracts[trace.from].includes(trace.to)
) {
// Add the contract being called to the existing list of contracts that are delegated to
delegatesToContracts[trace.from].push(trace.to)
}
}
}
// Convert to a Set to remove duplicates and then back to an array
const uniqueAddresses = Array.from(new Set(participantAddresses))
debug(`${uniqueAddresses.length} contracts in the transactions`)
// get contract ABIs from Etherscan
const contracts = await this.getContractsFromAddresses(uniqueAddresses)
// map the delegatedToContracts on each contract
for (const [address, toAddresses] of Object.entries(
delegatesToContracts
)) {
contracts[address].delegatedToContracts =
// map the to addresses to Contract objects
// with the address of the contract the delegate call is coming from
toAddresses.map(toAddress => ({
...contracts[toAddress],
address,
}))
}
// Get token name and symbol from chain
return await this.setTokenAttributes(contracts)
}
// Get the contract names and ABIs from Etherscan
async getContractsFromAddresses(addresses: string[]): Promise<Contracts> {
const contracts: Contracts = {}
// Get the contract details in parallel with a concurrency limit
const limit = pLimit(this.apiConcurrencyLimit)
const getContractPromises = addresses.map(address => {
return limit(() => this.etherscanClient.getContract(address))
})
const results: Contract[] = await Promise.all(getContractPromises)
results.forEach(result => {
contracts[result.address] = result
})
return contracts
}
async setTokenAttributes(contracts: Contracts): Promise<Contracts> {
// get the token details
const contractAddresses = Object.keys(contracts)
const tokensDetails = await this.ethereumNodeClient.getTokenDetails(
contractAddresses
)
tokensDetails.forEach(tokenDetails => {
contracts[tokenDetails.address].tokenName = tokenDetails.name
contracts[tokenDetails.address].symbol = tokenDetails.symbol
})
return contracts
}
static parseTraceParams(traces: Trace[][], contracts: Contracts) {
const functionSelector2Contract =
mapFunctionSelectors2Contracts(contracts)
for (const trace of traces.flat()) {
if (trace.inputs?.length >= 10) {
if (trace.type === MessageType.Create) {
trace.funcName = "constructor"
addConstructorParamsToTrace(trace, contracts)
return
}
const selectedContracts =
functionSelector2Contract[trace.funcSelector]
if (selectedContracts?.length > 0) {
// get the contract for the function selector that matches the to address
let contract = selectedContracts.find(
contract => contract.address === trace.to
)
// if the function is not on the `to` contract, then its a proxy contract
// so just use any contract if the function is on another contract
if (!contract) {
contract = selectedContracts[0]
trace.proxy = true
}
try {
const txDescription =
contract.interface.parseTransaction({
data: trace.inputs,
})
trace.funcName = txDescription.name
addInputParamsToTrace(trace, txDescription)
addOutputParamsToTrace(trace, txDescription)
} catch (err) {
if (!err.message.match("no matching function")) {
const error = new VError(
err,
`Failed to parse selector ${trace.funcSelector} in trace with id ${trace.id} from ${trace.from} to ${trace.to}`
)
console.warn(error)
}
}
}
}
}
}
static parseTransactionLogs(logs: Array<Log>, contracts: Contracts) {
// for each tx log
for (const log of logs) {
// see if we have the contract source for the log
const contract = contracts[log.address.toLowerCase()]
if (contract?.ethersContract) {
// try and parse the log topic
try {
const event =
contract.ethersContract.interface.parseLog(log)
contract.events.push(parseEvent(contract, event))
} catch (err) {
debug(
`Failed to parse log with topic ${log?.topics[0]} on contract ${log.address}`
)
}
}
// also parse the events on any contracts that are delegated to
contract?.delegatedToContracts?.forEach(delegatedToContract => {
// try and parse the log topic
try {
const event =
delegatedToContract.ethersContract.interface.parseLog(
log
)
contract.events.push(parseEvent(contract, event))
} catch (err) {
debug(
`Failed to parse log with topic ${log?.topics[0]} on contract ${log.address}`
)
}
})
}
}
// Marks each contract the minimum call depth it is used in
static parseTraceDepths(traces: Trace[][], contracts: Contracts) {
const flatTraces = traces.flat()
contracts[flatTraces[0].from].minDepth = 0
for (const trace of flatTraces) {
if (
contracts[trace.to].minDepth == undefined ||
trace.depth < contracts[trace.to].minDepth
) {
contracts[trace.to].minDepth = trace.depth
}
}
}
// Filter out delegated calls from proxies to their implementations
// and remove any excluded contracts
static filterTransactionTraces(
transactionTraces: Trace[][],
contracts: Contracts,
options: { noDelegates?: boolean; excludedContracts?: string[] }
): [Trace[][], Contracts] {
const filteredTransactionTraces = transactionTraces.map(t => [])
let usedAddresses = new Set<string>()
// For each transaction
transactionTraces.forEach((tx, i) => {
// recursively remove any calls to excluded contracts
const filteredExcludedTraces = filterExcludedContracts(
tx[0],
options.excludedContracts
)
// recursively get a tree of traces without delegated calls
const filteredTraces: Trace[] = options.noDelegates
? filterOutDelegatedTraces(filteredExcludedTraces)
: [filteredExcludedTraces]
filteredTransactionTraces[i] = arrayifyTraces(filteredTraces[0])
// Add the tx sender to set of used addresses
usedAddresses.add(filteredTransactionTraces[i][0].from)
// Add all the to addresses of all the trades to the set of used addresses
filteredTransactionTraces[i].forEach(t => usedAddresses.add(t.to))
})
// Filter out contracts that are no longer used from filtered out traces
const usedContracts: Contracts = {}
Array.from(usedAddresses).forEach(
address => (usedContracts[address] = contracts[address])
)
return [filteredTransactionTraces, usedContracts]
}
}
// Recursively filter out delegate calls from proxies or libraries depending on options
const filterOutDelegatedTraces = (
trace: Trace,
lastValidParentTrace?: Trace // there can be multiple traces removed
): Trace[] => {
// If parent trace was a proxy
const removeTrace = trace.type === MessageType.DelegateCall
const parentTrace = removeTrace
? // set to the last parent not removed
lastValidParentTrace
: // parent is not a proxy so is included
{ ...trace.parentTrace, type: MessageType.Call }
// filter the child traces
let filteredChildren: Trace[] = []
trace.childTraces.forEach(child => {
filteredChildren = filteredChildren.concat(
filterOutDelegatedTraces(child, parentTrace)
)
})
// if trace is being removed, return child traces so this trace is removed
if (removeTrace) {
return filteredChildren
}
// else, attach child traces to copied trace and return in array
return [
{
...trace,
proxy: false,
childTraces: filteredChildren,
parentTrace: lastValidParentTrace,
depth: (lastValidParentTrace?.depth || 0) + 1,
delegatedFrom: trace.from,
type: removeTrace ? MessageType.Call : trace.type,
},
]
}
// Recursively filter out any calls to excluded contracts
const filterExcludedContracts = (
trace: Trace,
excludedContracts: string[] = []
): Trace => {
// filter the child traces
let filteredChildren: Trace[] = []
trace.childTraces.forEach(child => {
// If the child trace is a call to an excluded contract, then skip it
if (excludedContracts.includes(child.to)) return
filteredChildren = filteredChildren.concat(
filterExcludedContracts(child, excludedContracts)
)
})
return {
...trace,
childTraces: filteredChildren,
}
}
const arrayifyTraces = (trace: Trace): Trace[] => {
let traces = [trace]
trace.childTraces.forEach(child => {
const arrayifiedChildren = arrayifyTraces(child)
traces = traces.concat(arrayifiedChildren)
})
return traces
}
// map of function selectors to Ethers Contracts
const mapFunctionSelectors2Contracts = (
contracts: Contracts
): {
[functionSelector: string]: EthersContract[]
} => {
// map of function selectors to Ethers Contracts
const functionSelector2Contract: {
[functionSelector: string]: EthersContract[]
} = {}
// For each contract, get function selectors
Object.values(contracts).forEach(contract => {
if (contract.ethersContract) {
Object.values(contract.ethersContract.interface.fragments)
.filter(fragment => fragment.type === "function")
.forEach((fragment: FunctionFragment) => {
const sighash =
contract.ethersContract.interface.getSighash(fragment)
if (!functionSelector2Contract[sighash]) {
functionSelector2Contract[sighash] = []
}
functionSelector2Contract[sighash].push(
contract.ethersContract
)
})
}
})
return functionSelector2Contract
}
const addInputParamsToTrace = (
trace: Trace,
txDescription: TransactionDescription
) => {
// For each function argument, add to the trace input params
txDescription.args.forEach((arg, i) => {
const functionFragment = txDescription.functionFragment.inputs[i]
const components = addValuesToComponents(functionFragment, arg)
trace.inputParams.push({
name: functionFragment.name,
type: functionFragment.type,
value: arg,
components,
})
})
}
const addOutputParamsToTrace = (
trace: Trace,
txDescription: TransactionDescription
): void => {
// Undefined outputs can happen with failed transactions
if (!trace.outputs || trace.outputs === "0x" || trace.error) return
const functionFragments = txDescription.functionFragment.outputs
const outputParams = defaultAbiCoder.decode(
functionFragments,
trace.outputs
)
// For each output, add to the trace output params
outputParams.forEach((param, i) => {
const components = addValuesToComponents(functionFragments[i], param)
trace.outputParams.push({
name: functionFragments[i].name,
type: functionFragments[i].type,
value: param,
components,
})
})
debug(
`Decoded ${trace.outputParams.length} output params for ${trace.funcName} with selector ${trace.funcSelector}`
)
}
const addConstructorParamsToTrace = (trace: Trace, contracts: Contracts) => {
// Do we have the ABI for the deployed contract?
const constructor = contracts[trace.to]?.ethersContract?.interface?.deploy
if (!constructor?.inputs) {
// No ABI so we don't know the constructor params which comes from verified contracts on Etherscan
return
}
// we need this flag to determine if there was no constructor params or they are unknown
trace.parsedConstructorParams = true
// if we don't have the ABI then we won't have the constructorInputs but we'll double check anyway
if (!contracts[trace.to]?.constructorInputs?.length) {
return
}
const constructorParams = defaultAbiCoder.decode(
constructor.inputs,
"0x" + contracts[trace.to]?.constructorInputs
)
// For each constructor param, add to the trace input params
constructorParams.forEach((param, i) => {
const components = addValuesToComponents(constructor.inputs[i], param)
trace.inputParams.push({
name: constructor.inputs[i].name,
type: constructor.inputs[i].type,
value: param,
components,
})
})
debug(`Decoded ${trace.inputParams.length} constructor params.`)
}
const parseEvent = (contract: Contract, log: LogDescription): Event => {
const params: Param[] = []
// For each event param
log.eventFragment.inputs.forEach((param, i) => {
const components = addValuesToComponents(
log.eventFragment.inputs[i],
param
)
params.push({
name: log.eventFragment.inputs[i].name,
type: log.eventFragment.inputs[i].type,
value: log.args[i],
components,
})
})
return {
name: log.name,
params,
}
}
// if function components exists, recursively add arg values to the function components
const addValuesToComponents = (
paramType: ParamTypeInternal,
args: any
): Param[] => {
if (paramType.baseType !== "array") {
if (!paramType?.components) {
return undefined
}
// For each component
return paramType.components.map((component, j) => {
// add the value and recursively add the components
return {
name: component.name,
type: component.type,
value: args[j],
components: addValuesToComponents(component, args[j]),
}
})
} else {
// If an array of components
return args.map((row: any, r: number) => {
// Remove the last two [] characters from the type.
// For example, tuple[] becomes tuple and tuple[][] becomes tuple[]
const childType = paramType.type.slice(0, -2)
// If a multi dimensional array then the baseType is still an array. Otherwise it becomes a tuple
const childBaseType =
childType.slice(-2) === "[]" ? "array" : childType
const components = addValuesToComponents(
{ ...paramType, type: childType, baseType: childBaseType },
row
)
return {
name: r.toString(),
type: childType,
value: row,
components,
}
})
}
} | the_stack |
import { useRef } from 'react';
import { processColor } from 'react-native';
import Animated from 'react-native-reanimated';
// @ts-ignore
import parseSVG from 'parse-svg-path';
// @ts-ignore
import absSVG from 'abs-svg-path';
// @ts-ignore
import normalizeSVG from 'normalize-svg-path';
import { cubicBezierLength } from './cubicBezierLength';
import {
FlingGestureHandlerGestureEvent,
ForceTouchGestureHandlerGestureEvent,
GestureHandlerStateChangeNativeEvent,
LongPressGestureHandlerGestureEvent,
PanGestureHandlerGestureEvent,
PinchGestureHandlerGestureEvent,
RotationGestureHandlerGestureEvent,
TapGestureHandlerGestureEvent,
} from 'react-native-gesture-handler';
import { Easing, interpolate } from './reanimated';
const {
multiply,
event,
floor,
abs,
sub,
block,
Extrapolate,
set,
color,
add,
not,
cond,
neq,
concat,
startClock,
min: min2,
max: max2,
stopClock,
timing,
round,
proc,
Clock,
Value,
} = Animated;
type Color = Animated.Adaptable<string> | Animated.Adaptable<number>;
interface ColorInterpolationConfig {
inputRange: readonly Animated.Adaptable<number>[];
outputRange: Color[];
}
type Adaptable<T> = { [P in keyof T]: Animated.Adaptable<T[P]> };
export interface Vector<
T extends Animated.Adaptable<number> = Animated.Adaptable<number>
> {
x: T;
y: T;
}
type NativeEvent = GestureHandlerStateChangeNativeEvent &
(
| PanGestureHandlerGestureEvent
| TapGestureHandlerGestureEvent
| LongPressGestureHandlerGestureEvent
| RotationGestureHandlerGestureEvent
| FlingGestureHandlerGestureEvent
| PinchGestureHandlerGestureEvent
| ForceTouchGestureHandlerGestureEvent
);
export type TimingConfig = Partial<Omit<Animated.TimingConfig, 'toValue'>>;
type Transform2dName =
| 'translateX'
| 'translateY'
| 'scale'
| 'skewX'
| 'skewY'
| 'scaleX'
| 'scaleY'
| 'rotateZ'
| 'rotate';
type Transformations = {
[Name in Transform2dName]: Animated.Adaptable<number>;
};
export type Transforms2d = (
| Pick<Transformations, 'translateX'>
| Pick<Transformations, 'translateY'>
| Pick<Transformations, 'scale'>
| Pick<Transformations, 'scaleX'>
| Pick<Transformations, 'scaleY'>
| Pick<Transformations, 'skewX'>
| Pick<Transformations, 'skewY'>
| Pick<Transformations, 'rotateZ'>
| Pick<Transformations, 'rotate'>
)[];
export const transformOrigin = (
{ x, y }: Vector,
...transformations: Transforms2d
): Transforms2d => [
{ translateX: x },
{ translateY: y },
...transformations,
{ translateX: multiply(x, -1) },
{ translateY: multiply(y, -1) },
];
type Atomic = string | number | boolean;
export const useValue = <V extends Atomic>(value: V) =>
useConst(() => new Value(value));
export const useConst = <T>(initialValue: T | (() => T)): T => {
const ref = useRef<{ value: T }>();
if (ref.current === undefined) {
// Box the value in an object so we can tell if it's initialized even if the initializer
// returns/is undefined
ref.current = {
value:
typeof initialValue === 'function'
? (initialValue as Function)()
: initialValue,
};
}
return ref.current.value;
};
export const onGestureEvent = (
nativeEvent: Partial<Adaptable<NativeEvent>>
) => {
const gestureEvent = event([{ nativeEvent }]);
return {
onHandlerStateChange: gestureEvent,
onGestureEvent: gestureEvent,
};
};
export const clamp = proc(
(
value: Animated.Adaptable<number>,
lowerBound: Animated.Adaptable<number>,
upperBound: Animated.Adaptable<number>
): Animated.Node<number> => min2(max2(lowerBound, value), upperBound)
);
export const useGestureHandler = (
nativeEvent: Parameters<typeof onGestureEvent>[0]
) => useConst(() => onGestureEvent(nativeEvent));
export const withTransition = (
value: Animated.Node<number>,
timingConfig: TimingConfig = {}
) => {
const init = new Value(0);
const clock = new Clock();
const state = {
finished: new Value(0),
frameTime: new Value(0),
position: new Value(0),
time: new Value(0),
};
const config = {
toValue: new Value(0),
duration: 150,
easing: Easing.linear,
...timingConfig,
};
return block([
cond(not(init), [set(init, 1), set(state.position, value)]),
cond(neq(config.toValue, value), [
set(state.frameTime, 0),
set(state.time, 0),
set(state.finished, 0),
set(config.toValue, value),
startClock(clock),
]),
timing(clock, state, config),
cond(state.finished, stopClock(clock)),
state.position,
]);
};
export const withTimingTransition = withTransition;
export const fract = (x: Animated.Adaptable<number>) => sub(x, floor(x));
export const opacity = (c: number) => ((c >> 24) & 255) / 255;
export const red = (c: number) => (c >> 16) & 255;
export const green = (c: number) => (c >> 8) & 255;
export const blue = (c: number) => c & 255;
export const interpolateColor = (
value: Animated.Adaptable<number>,
config: ColorInterpolationConfig,
colorSpace: 'hsv' | 'rgb' = 'rgb'
): Animated.Node<number> => {
const { inputRange } = config;
const outputRange = config.outputRange.map(c =>
//@ts-ignore
typeof c === 'number' ? c : processColor(c)
);
if (colorSpace === 'hsv') {
//@ts-ignore
return interpolateColorsHSV(value, inputRange, outputRange);
}
//@ts-ignore
return interpolateColorsRGB(value, inputRange, outputRange);
};
export const mix = proc(
(
value: Animated.Adaptable<number>,
x: Animated.Adaptable<number>,
y: Animated.Adaptable<number>
) => add(x, multiply(value, sub(y, x)))
);
const rgbToHsv = (c: number) => {
const r = red(c) / 255;
const g = green(c) / 255;
const b = blue(c) / 255;
const ma = Math.max(r, g, b);
const mi = Math.min(r, g, b);
let h = 0;
const v = ma;
const d = ma - mi;
const s = ma === 0 ? 0 : d / ma;
if (ma === mi) {
h = 0; // achromatic
} else {
switch (ma) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
default: // do nothing
}
h /= 6;
}
return { h, s, v };
};
export const hsv2rgb = (
h: Animated.Adaptable<number>,
s: Animated.Adaptable<number>,
v: Animated.Adaptable<number>
) => {
// vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
const K = {
x: 1,
y: 2 / 3,
z: 1 / 3,
w: 3,
};
// vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
const p = {
x: abs(sub(multiply(fract(add(h, K.x)), 6), K.w)),
y: abs(sub(multiply(fract(add(h, K.y)), 6), K.w)),
z: abs(sub(multiply(fract(add(h, K.z)), 6), K.w)),
};
// return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
const rgb = {
x: multiply(v, mix(s, K.x, clamp(sub(p.x, K.x), 0, 1))),
y: multiply(v, mix(s, K.x, clamp(sub(p.y, K.x), 0, 1))),
z: multiply(v, mix(s, K.x, clamp(sub(p.z, K.x), 0, 1))),
};
return {
r: round(multiply(rgb.x, 255)),
g: round(multiply(rgb.y, 255)),
b: round(multiply(rgb.z, 255)),
};
};
export const hsv2color = proc(
// @ts-ignore
(
h: Animated.Adaptable<number>,
s: Animated.Adaptable<number>,
v: Animated.Adaptable<number>
) => {
const { r, g, b } = hsv2rgb(h, s, v);
return color(r, g, b);
}
);
const interpolateColorsHSV = (
animationValue: Animated.Adaptable<number>,
inputRange: readonly Animated.Adaptable<number>[],
colors: number[]
): Animated.Node<number> => {
const colorsAsHSV = colors.map(c => rgbToHsv(c));
const h = interpolate(animationValue, {
inputRange,
outputRange: colorsAsHSV.map(c => c.h),
extrapolate: Extrapolate.CLAMP,
});
const s = interpolate(animationValue, {
inputRange,
outputRange: colorsAsHSV.map(c => c.s),
extrapolate: Extrapolate.CLAMP,
});
const v = interpolate(animationValue, {
inputRange,
outputRange: colorsAsHSV.map(c => c.v),
extrapolate: Extrapolate.CLAMP,
});
return hsv2color(h, s, v);
};
const interpolateColorsRGB = (
animationValue: Animated.Adaptable<number>,
inputRange: readonly Animated.Adaptable<number>[],
colors: number[]
) => {
const r = round(
interpolate(animationValue, {
inputRange,
outputRange: colors.map(c => red(c)),
extrapolate: Extrapolate.CLAMP,
})
);
const g = round(
interpolate(animationValue, {
inputRange,
outputRange: colors.map(c => green(c)),
extrapolate: Extrapolate.CLAMP,
})
);
const b = round(
interpolate(animationValue, {
inputRange,
outputRange: colors.map(c => blue(c)),
extrapolate: Extrapolate.CLAMP,
})
);
const a = interpolate(animationValue, {
inputRange,
outputRange: colors.map(c => opacity(c)),
extrapolate: Extrapolate.CLAMP,
});
return color(r, g, b, a);
};
export interface ReanimatedPath {
totalLength: number;
segments: { start: number; end: number; p0x: number; p3x: number }[];
length: number[];
start: number[];
end: number[];
p0x: number[];
p0y: number[];
p1x: number[];
p1y: number[];
p2x: number[];
p2y: number[];
p3x: number[];
p3y: number[];
}
type BezierPoint =
| 'p0x'
| 'p0y'
| 'p1x'
| 'p1y'
| 'p2x'
| 'p2y'
| 'p3x'
| 'p3y';
export interface PathInterpolationConfig {
inputRange: readonly Animated.Adaptable<number>[];
outputRange: readonly (ReanimatedPath | string)[];
extrapolate?: Animated.Extrapolate;
extrapolateLeft?: Animated.Extrapolate;
extrapolateRight?: Animated.Extrapolate;
}
export const interpolatePath = (
value: Animated.Adaptable<number>,
{ inputRange, outputRange, ...config }: PathInterpolationConfig
): Animated.Node<string> => {
const paths = outputRange.map(path =>
typeof path === 'string' ? parsePath(path) : path
);
const [path] = paths;
const commands = path.segments.map((_, index) => {
const interpolatePoint = (point: BezierPoint) =>
interpolate(value, {
inputRange,
outputRange: paths.map(p => p[point][index]),
...config,
});
const mx = interpolatePoint('p0x');
const my = interpolatePoint('p0y');
const p1x = interpolatePoint('p1x');
const p1y = interpolatePoint('p1y');
const p2x = interpolatePoint('p2x');
const p2y = interpolatePoint('p2y');
const p3x = interpolatePoint('p3x');
const p3y = interpolatePoint('p3y');
return string`${
index === 0 ? string`M${mx},${my} ` : ''
}C${p1x},${p1y} ${p2x},${p2y} ${p3x},${p3y}`;
});
return concat(...commands);
};
type SVGMoveCommand = ['M', number, number];
type SVGCurveCommand = ['C', number, number, number, number, number, number];
interface Point {
x: number;
y: number;
}
interface BezierCubicCurve {
length: number;
p0: Point;
p1: Point;
p2: Point;
p3: Point;
}
export type Concatable =
| Animated.Adaptable<string>
| Animated.Adaptable<number>;
type SVGNormalizedCommands = [SVGMoveCommand, ...SVGCurveCommand[]];
export const string = (
strings: readonly string[],
...values: readonly Concatable[]
) => {
if (values.length === 0) {
return concat(strings[0]);
}
const result = values.reduce<Concatable[]>(
(acc, v, idx) => [...acc, strings[idx], v],
[]
);
result.push(strings[strings.length - 1]);
return concat(...result);
};
const MX = 1;
const MY = 2;
const CX1 = 1;
const CY1 = 2;
const CX2 = 3;
const CY2 = 4;
const CX = 5;
const CY = 6;
export const parsePath = (d: string): ReanimatedPath => {
const [move, ...curves]: SVGNormalizedCommands = normalizeSVG(
absSVG(parseSVG(d))
);
// @ts-ignore
const parts: BezierCubicCurve[] = curves.map((curve, index) => {
const prevCurve = curves[index - 1];
const p0 =
index === 0
? { x: move[MX], y: move[MY] }
: { x: prevCurve[CX], y: prevCurve[CY] };
const p1 = { x: curve[CX1], y: curve[CY1] };
const p2 = { x: curve[CX2], y: curve[CY2] };
const p3 = { x: curve[CX], y: curve[CY] };
const length = cubicBezierLength(p0, p1, p2, p3);
return {
p0,
p1,
p2,
p3,
length,
};
});
const segments = parts.map((part, index) => {
const start = parts.slice(0, index).reduce((acc, p) => acc + p.length, 0);
const end = start + part.length;
return {
start,
end,
p0x: part.p0.x,
p3x: part.p3.x,
};
});
return {
segments,
totalLength: parts.reduce((acc, part) => acc + part.length, 0),
length: parts.map(part => part.length),
start: segments.map(segment => segment.start),
end: segments.map(segment => segment.end),
p0x: parts.map(part => part.p0.x),
p0y: parts.map(part => part.p0.y),
p1x: parts.map(part => part.p1.x),
p1y: parts.map(part => part.p1.y),
p2x: parts.map(part => part.p2.x),
p2y: parts.map(part => part.p2.y),
p3x: parts.map(part => part.p3.x),
p3y: parts.map(part => part.p3.y),
};
}; | the_stack |
import {
SessionDescriptionHandlerOptions,
SimpleUser,
SimpleUserDelegate,
SimpleUserOptions
} from "../src/platform/web";
import { nameAlice, nameBob, uriAlice, uriBob, webSocketServerAlice, webSocketServerBob } from "./demo-users";
import { getButton, getDiv, getInput } from "./demo-utils";
// A class which extends SimpleUser to handle setup and use of a data channel
class SimpleUserWithDataChannel extends SimpleUser {
private _dataChannel: RTCDataChannel | undefined;
constructor(
private messageInput: HTMLInputElement,
private sendButton: HTMLButtonElement,
private receiveDiv: HTMLDivElement,
server: string,
options: SimpleUserOptions = {}
) {
super(server, options);
}
public get dataChannel(): RTCDataChannel | undefined {
return this._dataChannel;
}
public set dataChannel(dataChannel: RTCDataChannel | undefined) {
this._dataChannel = dataChannel;
if (!dataChannel) {
return;
}
dataChannel.onclose = (event) => {
console.log(`[${this.id}] data channel onClose`);
this.messageInput.disabled = true;
this.receiveDiv.classList.add("disabled");
this.sendButton.disabled = true;
};
dataChannel.onerror = (event) => {
console.error(`[${this.id}] data channel onError`);
console.error(event.error);
alert(`[${this.id}] Data channel error.\n` + event.error);
};
dataChannel.onmessage = (event) => {
console.log(`[${this.id}] data channel onMessage`);
const el = document.createElement("p");
el.classList.add("message");
const node = document.createTextNode(event.data);
el.appendChild(node);
this.receiveDiv.appendChild(el);
this.receiveDiv.scrollTop = this.receiveDiv.scrollHeight;
};
dataChannel.onopen = (event) => {
console.log(`[${this.id}] data channel onOpen`);
this.messageInput.disabled = false;
this.receiveDiv.classList.remove("disabled");
this.sendButton.disabled = false;
};
}
public send(): void {
if (!this.dataChannel) {
const error = "No data channel";
console.error(`[${this.id}] failed to send message`);
console.error(error);
alert(`[${this.id}] Failed to send message.\n` + error);
return;
}
const msg = this.messageInput.value;
if (!msg) {
console.log(`[${this.id}] no data to send`);
return;
}
this.messageInput.value = "";
switch (this.dataChannel.readyState) {
case "connecting":
console.error("Attempted to send message while data channel connecting.");
break;
case "open":
try {
this.dataChannel.send(msg);
} catch (error) {
console.error(`[${this.id}] failed to send message`);
console.error(error);
alert(`[${this.id}] Failed to send message.\n` + error);
}
break;
case "closing":
console.error("Attempted to send message while data channel closing.");
break;
case "closed":
console.error("Attempted to send while data channel connection closed.");
break;
}
}
}
const connectAlice = getButton("connectAlice");
const connectBob = getButton("connectBob");
const disconnectAlice = getButton("disconnectAlice");
const disconnectBob = getButton("disconnectBob");
const registerAlice = getButton("registerAlice");
const registerBob = getButton("registerBob");
const unregisterAlice = getButton("unregisterAlice");
const unregisterBob = getButton("unregisterBob");
const beginAlice = getButton("beginAlice");
const beginBob = getButton("beginBob");
const endAlice = getButton("endAlice");
const endBob = getButton("endBob");
const messageAlice = getInput("messageAlice");
const sendAlice = getButton("sendAlice");
const receiveAlice = getDiv("receiveAlice");
const messageBob = getInput("messageBob");
const sendBob = getButton("sendBob");
const receiveBob = getDiv("receiveBob");
// New SimpleUserWithDataChannel for Alice
const alice = buildUser(
webSocketServerAlice,
uriAlice,
nameAlice,
uriBob,
nameBob,
connectAlice,
disconnectAlice,
registerAlice,
unregisterAlice,
beginAlice,
endAlice,
messageAlice,
sendAlice,
receiveAlice
);
// New SimpleUserWithDataChannel for Bob
const bob = buildUser(
webSocketServerBob,
uriBob,
nameBob,
uriAlice,
nameAlice,
connectBob,
disconnectBob,
registerBob,
unregisterBob,
beginBob,
endBob,
messageBob,
sendBob,
receiveBob
);
if (!alice || !bob) {
console.error("Something went wrong");
}
function buildUser(
webSocketServer: string,
aor: string,
displayName: string,
targetAOR: string,
targetName: string,
connectButton: HTMLButtonElement,
disconnectButton: HTMLButtonElement,
registerButton: HTMLButtonElement,
unregisterButton: HTMLButtonElement,
beginButton: HTMLButtonElement,
endButton: HTMLButtonElement,
messageInput: HTMLInputElement,
sendButton: HTMLButtonElement,
receiveDiv: HTMLDivElement
): SimpleUser {
console.log(`Creating "${name}" <${aor}>...`);
// SimpleUser options
const options: SimpleUserOptions = {
aor,
media: {
constraints: {
// This demo is making "data only" calls
audio: false,
video: false
}
},
userAgentOptions: {
// logLevel: "debug",
displayName
}
};
// Create SimpleUser
const user = new SimpleUserWithDataChannel(messageInput, sendButton, receiveDiv, webSocketServer, options);
// SimpleUser delegate
const delegate: SimpleUserDelegate = {
onCallCreated: makeCallCreatedCallback(user, beginButton, endButton),
onCallReceived: makeCallReceivedCallback(user),
onCallHangup: makeCallHangupCallback(user, beginButton, endButton),
onRegistered: makeRegisteredCallback(user, registerButton, unregisterButton),
onUnregistered: makeUnregisteredCallback(user, registerButton, unregisterButton),
onServerConnect: makeServerConnectCallback(user, connectButton, disconnectButton, registerButton, beginButton),
onServerDisconnect: makeServerDisconnectCallback(user, connectButton, disconnectButton, registerButton, beginButton)
};
user.delegate = delegate;
// Setup connect button click listeners
connectButton.addEventListener(
"click",
makeConnectButtonClickListener(user, connectButton, disconnectButton, registerButton, beginButton)
);
// Setup disconnect button click listeners
disconnectButton.addEventListener(
"click",
makeDisconnectButtonClickListener(user, connectButton, disconnectButton, registerButton, beginButton)
);
// Setup register button click listeners
registerButton.addEventListener("click", makeRegisterButtonClickListener(user, registerButton));
// Setup unregister button click listeners
unregisterButton.addEventListener("click", makeUnregisterButtonClickListener(user, unregisterButton));
// Setup begin button click listeners
beginButton.addEventListener("click", makeBeginButtonClickListener(user, targetAOR, targetName));
// Setup end button click listeners
endButton.addEventListener("click", makeEndButtonClickListener(user));
// Setup send button click listeners
sendButton.addEventListener("click", () => user.send());
// Enable connect button
connectButton.disabled = false;
return user;
}
// Helper function to create call received callback
function makeCallReceivedCallback(user: SimpleUserWithDataChannel): () => void {
return () => {
console.log(`[${user.id}] call received`);
// An example of how to have the session description handler callback when a data channel is created upon answering.
const sessionDescriptionHandlerOptions: SessionDescriptionHandlerOptions = {
onDataChannel: (dataChannel: RTCDataChannel) => {
console.log(`[${user.id}] data channel created`);
user.dataChannel = dataChannel;
}
};
user.answer({ sessionDescriptionHandlerOptions }).catch((error: Error) => {
console.error(`[${user.id}] failed to answer call`);
console.error(error);
alert(`[${user.id}] Failed to answer call.\n` + error);
});
};
}
// Helper function to create call created callback
function makeCallCreatedCallback(
user: SimpleUser,
beginButton: HTMLButtonElement,
endButton: HTMLButtonElement
): () => void {
return () => {
console.log(`[${user.id}] call created`);
beginButton.disabled = true;
endButton.disabled = false;
};
}
// Helper function to create call hangup callback
function makeCallHangupCallback(
user: SimpleUser,
beginButton: HTMLButtonElement,
endButton: HTMLButtonElement
): () => void {
return () => {
console.log(`[${user.id}] call hangup`);
beginButton.disabled = !user.isConnected();
endButton.disabled = true;
};
}
// Helper function to create registered callback
function makeRegisteredCallback(
user: SimpleUser,
registerButton: HTMLButtonElement,
unregisterButton: HTMLButtonElement
): () => void {
return () => {
console.log(`[${user.id}] registered`);
registerButton.disabled = true;
unregisterButton.disabled = false;
};
}
// Helper function to create unregistered callback
function makeUnregisteredCallback(
user: SimpleUser,
registerButton: HTMLButtonElement,
unregisterButton: HTMLButtonElement
): () => void {
return () => {
console.log(`[${user.id}] unregistered`);
registerButton.disabled = !user.isConnected();
unregisterButton.disabled = true;
};
}
// Helper function to create network connect callback
function makeServerConnectCallback(
user: SimpleUser,
connectButton: HTMLButtonElement,
disconnectButton: HTMLButtonElement,
registerButton: HTMLButtonElement,
beginButton: HTMLButtonElement
): () => void {
return () => {
console.log(`[${user.id}] connected`);
connectButton.disabled = true;
disconnectButton.disabled = false;
registerButton.disabled = false;
beginButton.disabled = false;
};
}
// Helper function to create network disconnect callback
function makeServerDisconnectCallback(
user: SimpleUser,
connectButton: HTMLButtonElement,
disconnectButton: HTMLButtonElement,
registerButton: HTMLButtonElement,
beginButton: HTMLButtonElement
): () => void {
return (error?: Error) => {
console.log(`[${user.id}] disconnected`);
connectButton.disabled = false;
disconnectButton.disabled = true;
registerButton.disabled = true;
beginButton.disabled = true;
if (error) {
alert(`[${user.id}] Server disconnected.\n` + error.message);
}
};
}
// Helper function to setup click handler for connect button
function makeConnectButtonClickListener(
user: SimpleUser,
connectButton: HTMLButtonElement,
disconnectButton: HTMLButtonElement,
registerButton: HTMLButtonElement,
beginButton: HTMLButtonElement
): () => void {
return () => {
user
.connect()
.then(() => {
connectButton.disabled = true;
disconnectButton.disabled = false;
registerButton.disabled = false;
beginButton.disabled = false;
})
.catch((error: Error) => {
console.error(`[${user.id}] failed to connect`);
console.error(error);
alert(`[${user.id}] Failed to connect.\n` + error);
});
};
}
// Helper function to setup click handler for disconnect button
function makeDisconnectButtonClickListener(
user: SimpleUser,
connectButton: HTMLButtonElement,
disconnectButton: HTMLButtonElement,
registerButton: HTMLButtonElement,
beginButton: HTMLButtonElement
): () => void {
return () => {
user
.disconnect()
.then(() => {
connectButton.disabled = false;
disconnectButton.disabled = true;
registerButton.disabled = true;
beginButton.disabled = true;
})
.catch((error: Error) => {
console.error(`[${user.id}] failed to disconnect`);
console.error(error);
alert(`[${user.id}] Failed to disconnect.\n` + error);
});
};
}
// Helper function to setup click handler for register button
function makeRegisterButtonClickListener(user: SimpleUser, registerButton: HTMLButtonElement): () => void {
return () => {
user
.register(undefined, {
// An example of how to get access to a SIP response message for custom handling
requestDelegate: {
onReject: (response) => {
console.warn(`[${user.id}] REGISTER rejected`);
let message = `Registration of "${user.id}" rejected.\n`;
message += `Reason: ${response.message.reasonPhrase}\n`;
alert(message);
}
}
})
.then(() => {
registerButton.disabled = true;
})
.catch((error: Error) => {
console.error(`[${user.id}] failed to register`);
console.error(error);
alert(`[${user.id}] Failed to register.\n` + error);
});
};
}
// Helper function to setup click handler for unregister button
function makeUnregisterButtonClickListener(user: SimpleUser, unregisterButton: HTMLButtonElement): () => void {
return () => {
user
.unregister()
.then(() => {
unregisterButton.disabled = true;
})
.catch((error: Error) => {
console.error(`[${user.id}] failed to unregister`);
console.error(error);
alert(`[${user.id}] Failed to unregister.\n` + error);
});
};
}
// Helper function to setup click handler for begin button
function makeBeginButtonClickListener(
user: SimpleUserWithDataChannel,
target: string,
targetDisplay: string
): () => void {
return () => {
// An example of how to have the session description handler create a data channel when generating an
// initial offer and how to have the session description handler callback when a data channel is created.
const sessionDescriptionHandlerOptions: SessionDescriptionHandlerOptions = {
dataChannel: true,
onDataChannel: (dataChannel: RTCDataChannel) => {
console.log(`[${user.id}] data channel created`);
user.dataChannel = dataChannel;
}
};
user
.call(
target,
{ sessionDescriptionHandlerOptions },
{
// An example of how to get access to a SIP response message for custom handling
requestDelegate: {
onReject: (response) => {
console.warn(`[${user.id}] INVITE rejected`);
let message = `Session invitation to "${targetDisplay}" rejected.\n`;
message += `Reason: ${response.message.reasonPhrase}\n`;
message += `Perhaps "${targetDisplay}" is not connected or registered?\n`;
alert(message);
}
}
}
)
.catch((error: Error) => {
console.error(`[${user.id}] failed to begin session`);
console.error(error);
alert(`[${user.id}] Failed to begin session.\n` + error);
});
};
}
// Helper function to setup click handler for begin button
function makeEndButtonClickListener(user: SimpleUser): () => void {
return () => {
user.hangup().catch((error: Error) => {
console.error(`[${user.id}] failed to end session`);
console.error(error);
alert(`[${user.id}] Failed to end session.\n` + error);
});
};
} | the_stack |
import * as React from 'react';
import BootstrapTable, { ColumnDescription, ColumnFormatter, HeaderFormatter } from 'react-bootstrap-table-next';
import filterFactory, {
Comparator,
multiSelectFilter,
numberFilter,
selectFilter,
textFilter,
} from 'react-bootstrap-table2-filter';
import { render } from 'react-dom';
// examples partially taken from https://react-bootstrap-table.github.io/react-bootstrap-table2/docs/table-props.html
interface Product {
id: number;
name: string;
price?: number | undefined;
quality?: number | undefined;
inStockStatus?: number | undefined;
sales?: number | undefined;
}
const products: Product[] = [
{
id: 1,
name: 'Item name 1',
price: 100,
quality: 0,
},
{
id: 2,
name: 'Item name 2',
price: 100,
quality: 1,
},
];
const priceHeaderFormatter: HeaderFormatter<Product> = (column, colIndex, components) => {
return (
<div>
{column.text}
{components.sortElement}
{components.filterElement}
</div>
);
};
const priceFormatter: ColumnFormatter<Product, { indexSquare: number }> = (cell, row, rowIndex) => {
return (
<span>
{rowIndex} - {cell}
</span>
);
};
let priceFilter: any;
const productColumns: Array<ColumnDescription<Product>> = [
{ dataField: 'id', align: 'center', sort: true, text: 'Product ID' },
{ dataField: 'name', align: 'center', sort: true, text: 'Product Name' },
{
isDummyField: true,
dataField: '',
sort: true,
text: 'Product Name',
},
{
dataField: 'price',
sort: true,
formatter: priceFormatter,
text: 'Product Price',
headerFormatter: priceHeaderFormatter,
filter: numberFilter({
options: [2100, 2103, 2105], // if options defined, will render number select instead of number input
delay: 600, // how long will trigger filtering after user typing, default is 500 ms
placeholder: 'custom placeholder', // placeholder for number input
withoutEmptyComparatorOption: true, // dont render empty option for comparator
withoutEmptyNumberOption: true, // dont render empty option for number select if it is defined
comparators: [Comparator.EQ, Comparator.GT, Comparator.LT], // Custom the comparators
style: { display: 'inline-grid' }, // custom the style on number filter
className: 'custom-numberfilter-class', // custom the class on number filter
comparatorStyle: { backgroundColor: 'antiquewhite' }, // custom the style on comparator select
comparatorClassName: 'custom-comparator-class', // custom the class on comparator select
numberStyle: { backgroundColor: 'cadetblue', margin: '0px' }, // custom the style on number input/select
numberClassName: 'custom-number-class', // custom the class on ber input/select
defaultValue: { number: 2103, comparator: Comparator.GT }, // default value
getFilter: filter => {
// priceFilter was assigned once the component has been mounted.
priceFilter = filter;
},
onFilter: filterValue => {},
}),
},
{
isDummyField: true,
dataField: '',
sort: true,
formatter: priceFormatter,
text: 'Product Price',
headerFormatter: priceHeaderFormatter,
},
];
/**
* Number filter test
*/
render(
<BootstrapTable data={products} keyField="id" filter={filterFactory()} columns={productColumns} />,
document.getElementById('app'),
);
/**
* Options as Object
*/
const selectOptionsObject: { [index: number]: string } = {
0: 'good',
1: 'Bad',
2: 'unknown',
};
/**
* Options as Array
*/
const selectOptionsList = [
{ value: 0, label: 'good' },
{ value: 1, label: 'Bad' },
{ value: 2, label: 'unknown' },
];
/**
* Options as Function
*/
const selectOptionsCreator = (column: ColumnDescription<Product>) => [
{ value: 0, label: 'good' },
{ value: 1, label: 'Bad' },
{ value: 2, label: 'unknown' },
];
render(
<BootstrapTable
keyField="id"
data={products}
columns={[
{ dataField: 'id', align: 'center', sort: true, text: 'Product ID' },
{ dataField: 'name', align: 'center', sort: true, text: 'Product Name' },
{
dataField: 'quality',
text: 'Product Quailty',
// formatter: cell => selectOptionsObject[cell],
filter: selectFilter({
options: selectOptionsObject,
className: 'test-classname',
withoutEmptyOption: true,
defaultValue: 2,
comparator: Comparator.LIKE, // default is Comparator.EQ
style: { backgroundColor: 'pink' },
getFilter: filter => {
// qualityFilter was assigned once the component has been mounted.
},
onFilter: filterValue => {},
}),
},
]}
filter={filterFactory()}
/>,
document.getElementById('app'),
);
let qualityFilter: any;
render(
<BootstrapTable
keyField="id"
data={products}
columns={[
{ dataField: 'id', align: 'center', sort: true, text: 'Product ID' },
{
dataField: 'name',
formatter: cell => cell,
align: 'center',
sort: true,
text: 'Product Name',
},
{
dataField: 'quality',
text: 'Product Quailty',
formatter: (cell: number, row, rowIndex, formatExtraData) => selectOptionsObject[cell],
filter: multiSelectFilter({
options: selectOptionsObject,
className: 'test-classname',
withoutEmptyOption: true,
defaultValue: [0, 2],
comparator: Comparator.LIKE, // default is Comparator.EQ
style: { backgroundColor: 'pink' },
getFilter: filter => {
// qualityFilter was assigned once the component has been mounted.
qualityFilter = filter;
},
onFilter: filterValue => {
console.log(filterValue);
},
}),
},
]}
filter={filterFactory()}
/>,
document.getElementById('app'),
);
/**
* Single select column test
*/
const selectColumns = [
{
dataField: 'quality',
text: 'Product Quailty',
formatter: (cell: number) => {
const found = selectOptionsList.find(val => val.value === cell);
return found ? found.value : '';
},
filter: selectFilter({
options: selectOptionsList,
className: 'test-classname',
withoutEmptyOption: true,
defaultValue: 2,
comparator: Comparator.LIKE, // default is Comparator.EQ
style: { backgroundColor: 'pink' },
getFilter: filter => {
// qualityFilter was assigned once the component has been mounted.
qualityFilter = filter;
},
onFilter: filterValue => {},
}),
},
];
render(
<BootstrapTable keyField="id" data={products} columns={selectColumns} filter={filterFactory()} />,
document.getElementById('app'),
);
/**
* Text filter test
*/
const textColumns = [
{
dataField: 'id',
text: 'Product ID',
},
{
dataField: 'name',
text: 'Product Name',
filter: textFilter({
placeholder: 'My Custom PlaceHolder', // custom the input placeholder
className: 'my-custom-text-filter', // custom classname on input
defaultValue: 'test', // default filtering value
comparator: Comparator.EQ, // default is Comparator.LIKE
caseSensitive: true, // default is false, and true will only work when comparator is LIKE
style: { backgroundColor: 'yellow' }, // your custom inline styles on input
delay: 1000, // how long will trigger filtering after user typing, default is 500 ms
onClick: e => console.log(e),
}),
},
{
dataField: 'price',
text: 'Product Price',
filter: textFilter(),
},
];
<BootstrapTable keyField="id" data={products} columns={textColumns} filter={filterFactory()} />;
/**
* After filter test
*/
const afterFilterColumns = [
{
dataField: 'id',
text: 'Product ID',
},
{
dataField: 'name',
text: 'Product Name',
filter: textFilter({
placeholder: 'My Custom PlaceHolder', // custom the input placeholder
className: 'my-custom-text-filter', // custom classname on input
defaultValue: 'test', // default filtering value
comparator: Comparator.EQ, // default is Comparator.LIKE
caseSensitive: true, // default is false, and true will only work when comparator is LIKE
style: { backgroundColor: 'yellow' }, // your custom inline styles on input
delay: 1000, // how long will trigger filtering after user typing, default is 500 ms
onClick: e => console.log(e),
}),
},
{
dataField: 'price',
text: 'Product Price',
filter: textFilter(),
},
];
const afterFilter = (newResult: Product[]): void => {
console.log(newResult);
};
render(
<BootstrapTable keyField="id" data={products} columns={selectColumns} filter={filterFactory({ afterFilter })} />,
document.getElementById('app'),
); | the_stack |
import Stream = require("stream");
import File = require("fs");
import Path = require("path");
import OS = require("os");
import Process = require("process");
// Note: The 'import * as Foo from "./Foo' syntax avoids the "compiler re-write problem" that breaks debugger hover inspection
import * as Configuration from "../Configuration";
import * as StringEncoding from "../StringEncoding";
import * as Utils from "../Utils/Utils-Index";
/** The detail level of a logged message. */
export enum LoggingLevel
{
/** The message will always be logged, regardless of the configured 'outputLoggingLevel'. */
Minimal = 0,
/** The message will only be logged if the configured 'outputLoggingLevel' is 'Verbose' or 'Debug'. */
Verbose = 1,
/** The message will only be logged if the configured 'outputLoggingLevel' is 'Debug'. */
Debug = 2
}
class LoggingOptions
{
/** The level of detail to include in the log. */
loggingLevel: LoggingLevel = LoggingLevel.Minimal;
/** Where log output should be written. */
logDestination: Configuration.OutputLogDestination = Configuration.OutputLogDestination.Console;
/** The folder where the output log file will be written (if logDestination is 'File' or 'ConsoleAndFile'). */
logFolder: string = "./outputLogs";
/** The set of trace flags specified in the lbOptions.traceFlags configuration setting. */
traceFlags: Set<TraceFlag> = new Set<TraceFlag>();
/** Whether to allow the use of color when logging to the console. */
allowColor: boolean = true;
/** Returns true if logging is enabled for the specified destination. */
canLogTo(destination: Configuration.OutputLogDestination): boolean
{
return ((this.logDestination & destination) === destination);
}
}
let _loggingOptions: LoggingOptions;
let _logFileHandle: number = -1;
let _logFileName: string = "";
let _lastMessageLogged: string | null = null;
let _allMessageSuppressionRegExp: RegExp | null = null;
let _consoleMessageSuppressionRegExp: RegExp | null = null;
/** Initializes (from the loaded config file) the options that control output logging. */
function initializeLoggingOptions()
{
let lbOptions: Configuration.LanguageBindingOptions = Configuration.loadedConfig().lbOptions;
_loggingOptions = new LoggingOptions();
_loggingOptions.loggingLevel = lbOptions.outputLoggingLevel;
_loggingOptions.logDestination = lbOptions.outputLogDestination;
_loggingOptions.logFolder = lbOptions.outputLogFolder;
_loggingOptions.allowColor = lbOptions.outputLogAllowColor;
if (lbOptions.traceFlags.length > 0)
{
// Note: The lbOptions.traceFlags value has already been verified and formatted
const traceFlagNames: string[] = lbOptions.traceFlags.split(";");
for (let i = 0; i < traceFlagNames.length; i++)
{
_loggingOptions.traceFlags.add(TraceFlag[traceFlagNames[i] as keyof typeof TraceFlag]);
}
}
openOutputLog();
}
/** Colors that the foreground text can be set to when writing to the console. */
// See https://stackoverflow.com/questions/9781218/how-to-change-node-jss-console-font-color
export enum ConsoleForegroundColors
{
// Note: These are the "bright" values (see https://en.wikipedia.org/wiki/ANSI_escape_code#Colors); the "dim" values are -60 (eg. dim red = "\x1b[31m"),
// but the host console (eg. PowerShell) and "theme" (if applicable) determines which actual RGB color to render.
Red = "\x1b[91m",
Green = "\x1b[92m",
Yellow = "\x1b[93m",
Blue = "\x1b[94m",
Magenta = "\x1b[95m",
Cyan = "\x1b[96m",
White = "\x1b[97m",
/** Used to reset the color back to the prior color. */
Reset = "\x1b[0m"
}
/** Returns the text of the last message logged. Primarily used for testing. */
export function getLastMessageLogged(): string | null
{
return (_lastMessageLogged);
}
/**
* [Internal] Sets a regular expression used to (temporarily) suppress logging of messages that match it.
* If 'regExp' is not supplied, the suppression is cleared.
*
* Errors will not be suppressed, although if 'suppressConsoleOnly' is true then errors _will_ be suppressed
* in the console (but not in the log file) if the definition of 'regExp' includes them. Will throw if 'suppressConsoleOnly'
* is true but the 'outputLogDestination' configuration setting is not 'ConsoleAndFile'.
*
* This method is for **internal use only**.
*/
export function suppressLoggingOf(regExp?: RegExp, suppressConsoleOnly: boolean = false): void
{
if (!regExp)
{
_consoleMessageSuppressionRegExp = _allMessageSuppressionRegExp = null;
}
else
{
if (suppressConsoleOnly)
{
if (_loggingOptions.logDestination !== Configuration.OutputLogDestination.ConsoleAndFile)
{
throw new Error(`Console messages can only be suppressed when 'outputLogDestination' in ${Configuration.loadedConfigFileName()} is 'ConsoleAndFile'`);
}
_consoleMessageSuppressionRegExp = regExp;
}
else
{
_allMessageSuppressionRegExp = regExp;
}
}
}
/** A object with the core properties of an Error object. */
type ErrorLike = Pick<Error, "name" | "message" | "stack">;
/**
* If the supplied 'error' is an Error, simply returns it.\
* If the supplied 'error' is Error-like, creates a new Error instance from it.\
* Otherwise, returns an Error created from whatever 'error' is.
*/
export function makeError(error: Error | unknown): Error
{
/** [Local function] Returns true if the supplied 'error' is an object with the same "shape" as an Error. */
function isErrorLike(error: unknown): error is ErrorLike
{
if (error instanceof Object)
{
if (("name" in error) && ("message" in error) && ("stack" in error))
{
if ((typeof error["name"] === "string") && (typeof error["message"] === "string") && (typeof error["stack"] === "string"))
{
return (true);
}
}
}
return (false);
}
if (error instanceof Error) // This will be true for all derived error types (eg. ReferenceError)
{
return (error);
}
else
{
// Note: This path should only ever happen when we're catching an "error" thrown by user-code, since our code only ever throws Error()
const newError: Error = new Error();
if (isErrorLike(error))
{
newError.name = error.name;
newError.message = error.message;
newError.stack = error.stack;
}
else
{
try
{
newError.message = (typeof error === "string") ? error : ((typeof error === "object") && (error !== null) ? error.toString() : new String(error).valueOf());
const frames: string[] = newError.stack?.split("\n") || [];
if (frames.length > 1)
{
// Remove the "makeError()" frame
if (frames[1].indexOf(".makeError (") !== -1)
{
frames.splice(1, 1);
}
newError.stack = frames.join("\n");
}
else
{
newError.stack = undefined;
}
}
catch (innerError: unknown)
{
newError.message = `[Error could not be produced (reason: ${(innerError as Error).message})]`;
newError.stack = new Error().stack; // We let the stack include the "makeError()" frame" in this case
}
}
return (newError)
}
}
/**
* Returns the current time [or the supplied dateTime] in the format\
* 'YYYY/MM/dd hh:mm:ss.fff' (without the quotes).
*/
export function getTime(dateTime?: number | Date): string
{
let now = new Date(dateTime ? dateTime : Date.now());
let date = now.getFullYear() + "/" + ("0" + (now.getMonth() + 1)).slice(-2) + "/" + ("0" + now.getDate()).slice(-2);
let time = ("0" + now.getHours()).slice(-2) + ":" + ("0" + now.getMinutes()).slice(-2) + ":" + ("0" + now.getSeconds()).slice(-2) + "." + ("00" + now.getMilliseconds()).slice(-3);
return (date + " " + time);
}
function makeLogLine(time: string, message: string, prefix?: string): string
{
prefix = prefix ? (prefix + (prefix.endsWith("]") ? " " : ": ")) : "";
_lastMessageLogged = `${prefix}${message}`;
let line: string = `${time}: ${_lastMessageLogged}`;
return (line);
}
function isLoggable(message: string, msgLevel: LoggingLevel, destination: Configuration.OutputLogDestination): boolean
{
// Suppressed console messages are never loggable
// Note: When suppressing console messages, we also allow suppression of errors
if ((destination === Configuration.OutputLogDestination.Console) && _consoleMessageSuppressionRegExp && _consoleMessageSuppressionRegExp.test(message))
{
return (false);
}
// Errors are always loggable
if (/Error:/i.test(message))
{
return (true);
}
// Suppressed messages are never loggable
if (_allMessageSuppressionRegExp && _allMessageSuppressionRegExp.test(message))
{
return (false);
}
return (_loggingOptions.canLogTo(destination) && (msgLevel <= _loggingOptions.loggingLevel));
}
function logToConsole(time: string, message: string, prefix?: string, color?: ConsoleForegroundColors, msgLevel: LoggingLevel = LoggingLevel.Verbose): void
{
if (!isLoggable(message, msgLevel, Configuration.OutputLogDestination.Console))
{
return;
}
const line: string = makeLogLine(time, message, prefix);
if (_loggingOptions.allowColor)
{
if (!color && /Warning:/i.test(line))
{
color = ConsoleForegroundColors.Yellow;
}
if (!color && /Error:/i.test(line))
{
color = ConsoleForegroundColors.Red;
}
}
else
{
color = undefined;
}
console.log(color ? colorize(line, color) : line);
}
// Note: Logging to a file without also logging to the console is the most performant way to do logging.
function logToFile(time: string, message: string, prefix?: string, msgLevel: LoggingLevel = LoggingLevel.Verbose): void
{
if ((_logFileHandle === -1) || !isLoggable(message, msgLevel, Configuration.OutputLogDestination.File))
{
return;
}
const line: string = makeLogLine(time, message, prefix);
File.writeSync(_logFileHandle, line + Utils.NEW_LINE);
}
/** Opens (creates) the output log file (if needed). */
function openOutputLog(): void
{
if ((_logFileHandle === -1) && _loggingOptions.canLogTo(Configuration.OutputLogDestination.File))
{
if (!File.existsSync(_loggingOptions.logFolder))
{
File.mkdirSync(_loggingOptions.logFolder);
}
const fileName: string = `traceLog_${Utils.getTime().replace(/\//g, "").replace(" ", "_").replace(/:/g, "").slice(0, -4)}.txt`;
_logFileName = Path.resolve(Path.join(_loggingOptions.logFolder, fileName));
// Note: This will overwrite the file if it already exists [see https://nodejs.org/api/fs.html#fs_file_system_flags]
_logFileHandle = File.openSync(_logFileName, "w");
Utils.log(`Logging output to ${_logFileName}`);
}
}
/** [Internal] Closes the output log file. */
export function closeOutputLog(): void
{
try
{
if (_logFileHandle !== -1)
{
File.closeSync(_logFileHandle);
_logFileHandle = -1;
_logFileName = "";
}
}
catch (error: unknown)
{
Utils.log(`Error: Unable to close output log (reason: ${Utils.makeError(error).message})`);
}
}
/** [Internal] Returns the pathed output log file name. */
export function getOutputLog(): string
{
return (_logFileName);
}
/**
* [Internal] Returns true if logging messages of the specified level is allowed.\
* Note: For non-error messages in high-frequency code paths, it is more efficient to call this first to determine if log() should be called.
*/
export function canLog(msgLevel: LoggingLevel): boolean
{
if (!_loggingOptions)
{
initializeLoggingOptions();
}
return (msgLevel <= _loggingOptions.loggingLevel);
}
/** [Internal] Returns true if logging is enabled for the console. */
export function canLogToConsole(): boolean
{
if (!_loggingOptions)
{
initializeLoggingOptions();
}
return (_loggingOptions.canLogTo(Configuration.OutputLogDestination.Console));
}
/**
* Logs the specified message (with the [optional] specified prefix), along with a timestamp, to the console and/or output log file.
* @param {string | Error} message Message (or Error) to log.
* @param {string} [prefix] [Optional] Prefix for the message. Can be specified as null.
* @param {LoggingLevel} [level] [Optional] The level that logging must be set to (in ambrosiaConfig.json) for the message to be logged.
*/
export function log(message: string | Error, prefix: string | null = null, level: LoggingLevel = LoggingLevel.Verbose): void
{
if (!_loggingOptions)
{
initializeLoggingOptions();
}
let errorMessage: string = (message instanceof Error) ? (message.stack || message.toString()) : message;
let time: string = getTime();
logToConsole(time, errorMessage, prefix || undefined, undefined, level);
logToFile(time, errorMessage, prefix || undefined, level);
}
/** Output logging trace flags. See traceLog(). */
export enum TraceFlag
{
/** Logs trace messages related to log page back-pressure (see bug #194). */
LogPageInterruption = 1,
/** Logs trace messages related to memory usage. */
MemoryUsage = 2
}
/**
* Logs the specified message, along with a timestamp, to the console and/or output log file, but **only** if
* the specified traceFlag is included (enabled) in the lbOptions.traceFlags configuration setting.\
* If the requested trace flag is enabled, the message will **always** be logged, regardless of the configured 'outputLoggingLevel'.
*/
export function traceLog(traceFlag: TraceFlag, message: string): void
{
if (!_loggingOptions)
{
initializeLoggingOptions();
}
if (_loggingOptions.traceFlags.has(traceFlag))
{
log(message, `TRACE (${TraceFlag[traceFlag]})`, LoggingLevel.Minimal);
}
}
/** Returns true if the specified trace flag is enabled (configured). */
export function isTraceFlagEnabled(traceFlag: TraceFlag): boolean
{
if (!_loggingOptions)
{
initializeLoggingOptions();
}
return (_loggingOptions.traceFlags.has(traceFlag));
}
/**
* A fail-safe version of log(). Falls back to console.log() if Utils.log() fails.\
* Typically only used before Ambrosia.initialize() / initializeAsync() is called.
*/
export function tryLog(message: string | Error, prefix?: string, level: LoggingLevel = LoggingLevel.Verbose): void
{
try
{
log(message, prefix, level);
}
catch
{
let errorMessage: string = (message instanceof Error) ? (message.stack || message.toString()) : message;
let line: string = makeLogLine(getTime(), errorMessage, prefix);
console.log(line);
}
}
/**
* Logs the specified message (with the [optional] specified prefix) in the specified color, along with a timestamp, to the console and/or output log file.
* @param {ConsoleForegroundColors} color Foreground color for the message. Only applies to the console, not the output log file.
* @param {string} message Message to log.
* @param {string} [prefix] [Optional] Prefix for the message.
* @param {LoggingLevel} [level] [Optional] The level that logging must be set to (in ambrosiaConfig.json) for the message to be logged.
*/
export function logWithColor(color: ConsoleForegroundColors, message: string | Error, prefix?: string, level: LoggingLevel = LoggingLevel.Verbose): void
{
if (!_loggingOptions)
{
initializeLoggingOptions();
}
let errorMessage: string = (message instanceof Error) ? (message.stack || message.toString()) : message;
let time: string = getTime();
logToConsole(time, errorMessage, prefix, color, level);
logToFile(time, errorMessage, prefix, level);
}
/** Logs a "header" to make it easier to find a section of [subsequent] output. */
export function logHeader(title: string, char: string = "-")
{
let separatorLine: string = char.repeat(title.length);
Utils.log(separatorLine);
Utils.log(title);
Utils.log(separatorLine);
}
/** Logs memory usage statistics. Only logs if the 'MemoryUsage' trace flag is set, and will log regardless of the configured 'outputLoggingLevel'. */
export function logMemoryUsage(): void
{
if (!isTraceFlagEnabled(TraceFlag.MemoryUsage))
{
return;
}
const ONE_MB: number = 1024 * 1024;
const memStats: NodeJS.MemoryUsage = Process.memoryUsage();
const computerMemTotal: number = OS.totalmem();
const computerMemUsed: number = computerMemTotal - OS.freemem();
const percentComputerMemUsed: string = ((computerMemUsed / computerMemTotal) * 100).toFixed(1);
const percentHeapUsed: string = ((memStats.heapUsed / memStats.heapTotal) * 100).toFixed(1);
Utils.log(`Memory: RSS = ${toMB(memStats.rss)}, Heap (Total / Used) = ${toMB(memStats.heapTotal)} / ${toMB(memStats.heapUsed)} (${percentHeapUsed}%), Computer (Total / Used) = ${toMB(computerMemTotal)} / ${toMB(computerMemUsed)} (${percentComputerMemUsed}%)`, null, LoggingLevel.Minimal);
function toMB(valueInBytes: number): string
{
return (`${(valueInBytes / ONE_MB).toFixed(2)} MB`);
}
}
/** Formats the message so that, when written to the console, it will have the specified color. */
export function colorize(message: string, color: ConsoleForegroundColors): string
{
return (color ? `${color}${message}${ConsoleForegroundColors.Reset}` : message);
}
/** Returns the file/line/char location (eg. "src\Meta.ts:3142:19") for the top-most (last) stack frame of the specified error. May return null. */
export function getErrorOrigin(error: Error): string | null
{
let origin: string | null = null;
if (error.stack?.indexOf("\n") !== -1)
{
const lines: string[] = error.stack?.split("\n") ?? [];
if (lines.length >= 2)
{
// See: https://v8.dev/docs/stack-trace-api
// lines[1] style #1: ' at emitTypeScriptFileEx (C:\src\Git\AMBROSIA\Clients\AmbrosiaJS\Ambrosia-Node\src\Meta.ts:1583:23)'
// lines[1] style #2: ' at C:\src\Git\AMBROSIA\Clients\AmbrosiaJS\Ambrosia-Node\src\Meta.ts:1583:23'
const topFrame: string = lines[1].trim();
const regExps: RegExp[] = [ RegExp(/^at[ ]{1}.+[ ]{1}\((.+)\)$/), RegExp(/^at[ ]{1}([^ ]+)$/) ];
origin = topFrame; // In case the RegExp's fail
for (let i = 0; i < regExps.length; i++)
{
const execResult: RegExpExecArray | null = regExps[i].exec(topFrame);
if (execResult && (execResult.length > 1))
{
const location: string = execResult[1];
const extension: string = Path.extname(Path.basename(location).split(":")[0]);
if (Utils.equalIgnoringCase(extension, ".ts") || Utils.equalIgnoringCase(extension, ".js"))
{
origin = Path.relative(process.cwd(), location);
break;
}
}
}
}
}
return (origin);
}
/**
* A transform stream used to format StandardOutput (stdout) and/or StandardError (stderr).
* Each line in the [piped-in] output will be transformed to include a timestamp and, optionally, a prefix (source) and color.
* Further, the stream can be watched for certain token values (using tokenWatchList) that - if found - will cause a 'tokenFound'
* event to be emitted [handled with 'tokenFoundHandler(token: string, line: string)'].\
* Note: Tokens are case-sensitive.
*/
export class StandardOutputFormatter extends Stream.Transform
{
private _source: string = ""; // Eg. "[IC]""
private _color: ConsoleForegroundColors; // Initialized in constructor
private _errorColor: ConsoleForegroundColors; // Initialized in constructor
private _tokenWatchList: RegExp[] = [];
// Eg: Parse "ImmortalCoordinator.exe", "Information", "0" and "Ready ..." from "ImmortalCoordinator.exe Information: 0 : Ready ..."
private readonly _lineParser: RegExp = RegExp(/^(\S+)?[\s]*([\S]+)[\s]*[:][\s]*(\d+?)[\s]*[:][\s]*(.*$)/);
constructor(source: string = "", color: ConsoleForegroundColors, errorColor: ConsoleForegroundColors = ConsoleForegroundColors.Red, tokenWatchList: RegExp[] = [], options?: Stream.TransformOptions)
{
super(options);
this._source = source;
this._color = color;
this._errorColor = errorColor;
this._tokenWatchList = tokenWatchList;
}
/** Parses a single line of IC output and returns a more concise version. */
private parseLine(line: string): string
{
let modifiedLine: string = line;
if (line.length > 0)
{
let results: RegExpExecArray | null = this._lineParser.exec(line);
if (results && (results.length === 5))
{
let binaryName: string = results[1]; // Eg. "ImmortalCoordinator.exe"
let messageType: string = results[2]; // "Information", "Warning", or "Error"
let messageID: number = parseInt(results[3]); // Unused by the IC (ie. always 0)
let message: string = results[4]; // Message
modifiedLine = (messageType !== "Information") ? `${messageType}: ${message}` : message;
}
}
return (modifiedLine);
}
/** Returns true if the specified line is an error or an exception. */
private isLineErrorOrException(line: string): boolean
{
line = line.trimLeft();
const result: boolean = /Exception:/.test(line) || /^Error:\s+/.test(line);
// Note: We don't include stack trace lines because - due to chunking - lines (especially for large stack traces) can
// end up being split over 2 chunks, and this "line break" also breaks the regex tests for a stack trace line.
// /^\s+at\s+/.test(line) ||
// /^\s*--- End of/.test(line) ||
return (result);
}
// private _testExceptionCase: boolean = true; // Used for testing the handling of exceptions (with stacks) from the IC
_transform(chunk: Buffer, encoding: string, callback: (error?: Error) => void): void
{
const lineSplitRegEx: RegExp = new RegExp(`${OS.EOL}|\n`); // Sometime CRA messages include just a '\n' character
// Note: A chunk may end in the middle of a line (eg. for large stack traces), which will result in us "breaking" the line across 2 logged lines
let output: string = chunk.toString();
let unprocessedLines: string[] = output.split(lineSplitRegEx);
// We use the same timestamp for ALL lines in a given 'chunk' (which is the most accurate thing to
// do, but it also provides us with visibility into the chunk size and "line breaks" across chunks)
const time: string = getTime();
// if (this._testExceptionCase)
// {
// this._testExceptionCase = false;
// try
// {
// let foo: string[] = [];
// let bar: number = foo.length;
// }
// catch (error: unknown)
// {
// output = Utils.makeError(error).stack || "";
// unprocessedLines = output.split("\n");
// unprocessedLines[0] = unprocessedLines[0].replace("Error:", "Exception:");
// unprocessedLines.push("ImmortalCoordinator.exe Error: 0 : Error doing something!!");
// }
// }
for (let i = 0; i < unprocessedLines.length; i++)
{
const line: string = this.parseLine(unprocessedLines[i]);
if (line.length > 0)
{
// We output the modified line immediately, even if a "tokenFound" handler ends up also writing the line to stdout.
// Since we can't know what the handler does, we output it to maintain the correct sequence of the output (even if
// it may result in the line being outputted twice).
if (_loggingOptions.canLogTo(Configuration.OutputLogDestination.Console))
{
// Note: Stack trace lines will use the standard _color, not _errorColor [see comment in isLineErrorOrException()]
const color: ConsoleForegroundColors = this.isLineErrorOrException(line) ? this._errorColor : this._color;
const modifiedOutput: string = colorize(`${time}: ${this._source}${this._source ? " " : ""}${line}${OS.EOL}`, color);
this.push(StringEncoding.toUTF8Bytes(modifiedOutput)); // If this returns false, it will just buffer
}
// Since the StandardOutputFormatter output doesn't observe [by design] the configured 'outputLoggingLevel',
// we [effectively] do the same if logging to file by specifying the loggingLevel as 'Minimal'
logToFile(time, line, this._source, LoggingLevel.Minimal);
// If needed, fire "tokenFound" handler
if (this.listenerCount("tokenFound") > 0)
{
for (let i = 0; i < this._tokenWatchList.length; i++)
{
if (this._tokenWatchList[i].test(line))
{
// Note: It's not reliable to try to re-combine related lines (eg. the stack trace lines for an exception) because the
// chunk that unprocessedLines came from may not include all the related lines (eg. the entire stack trace).
this.emit("tokenFound", this._tokenWatchList[i].toString(), line); // Note: emit() synchronously calls each of the listeners
break; // Stop on the first token we find
}
}
}
}
}
callback();
}
} | the_stack |
import assert = require("assert");
import { Assembly } from "../ast/assembly";
import { ResolvedType } from "../ast/resolved_type";
import { MIRInvokeKey } from "../compiler/mir_ops";
import { PCode } from "../compiler/mir_emitter";
enum FlowTypeTruthValue {
True = "True",
False = "False",
Unknown = "Unknown"
}
class FlowTypeTruthOps {
static equal(e1: FlowTypeTruthValue, e2: FlowTypeTruthValue): boolean {
return e1 === e2;
}
static subvalue(e1: FlowTypeTruthValue, e2: FlowTypeTruthValue): boolean {
return e2 === FlowTypeTruthOps.join(e1, e2);
}
static join(...values: FlowTypeTruthValue[]): FlowTypeTruthValue {
if (values.length === 0) {
return FlowTypeTruthValue.Unknown;
}
const hasunknown = values.indexOf(FlowTypeTruthValue.Unknown) !== -1;
const hastrue = values.indexOf(FlowTypeTruthValue.True) !== -1;
const hasfalse = values.indexOf(FlowTypeTruthValue.False) !== -1;
if (hasunknown || (hastrue && hasfalse)) {
return FlowTypeTruthValue.Unknown;
}
else {
return hastrue ? FlowTypeTruthValue.True : FlowTypeTruthValue.False;
}
}
static maybeTrueValue(e: FlowTypeTruthValue): boolean {
return (e === FlowTypeTruthValue.True || e === FlowTypeTruthValue.Unknown);
}
static maybeFalseValue(e: FlowTypeTruthValue): boolean {
return (e === FlowTypeTruthValue.False || e === FlowTypeTruthValue.Unknown);
}
}
class ValueType {
readonly layout: ResolvedType;
readonly flowtype: ResolvedType;
constructor(layout: ResolvedType, flowtype: ResolvedType) {
this.layout = layout;
this.flowtype = flowtype;
}
inferFlow(nflow: ResolvedType): ValueType {
return new ValueType(this.layout, nflow);
}
static createUniform(ttype: ResolvedType): ValueType {
return new ValueType(ttype, ttype);
}
static join(assembly: Assembly, ...args: ValueType[]): ValueType {
assert(args.length !== 0);
const jlayout = assembly.typeUpperBound(args.map((ei) => ei.layout));
assert(jlayout.isSameType(args[0].layout)); //we should not let this happen!!!
const jflow = assembly.typeUpperBound(args.map((ei) => ei.flowtype));
return new ValueType(jlayout, jflow);
}
}
class ExpressionReturnResult {
readonly valtype: ValueType;
readonly truthval: FlowTypeTruthValue;
readonly expvar: string | undefined;
constructor(valtype: ValueType, tval: FlowTypeTruthValue, expvar: string | undefined) {
this.valtype = valtype;
this.truthval = tval;
this.expvar = expvar;
}
static join(assembly: Assembly, expvar: string, ...args: ExpressionReturnResult[]): ExpressionReturnResult {
assert(args.length !== 0);
const jtype = ValueType.join(assembly, ...args.map((ei) => ei.valtype));
const jtv = FlowTypeTruthOps.join(...args.map((ei) => ei.truthval));
return new ExpressionReturnResult(jtype, jtv, expvar);
}
}
class VarInfo {
readonly declaredType: ResolvedType;
readonly isConst: boolean;
readonly isCaptured: boolean;
readonly mustDefined: boolean;
readonly flowType: ResolvedType;
constructor(dtype: ResolvedType, isConst: boolean, isCaptured: boolean, mustDefined: boolean, ftype: ResolvedType) {
this.declaredType = dtype;
this.flowType = ftype;
this.isConst = isConst;
this.isCaptured = isCaptured;
this.mustDefined = mustDefined;
}
assign(ftype: ResolvedType): VarInfo {
assert(!this.isConst);
return new VarInfo(this.declaredType, this.isConst, this.isCaptured, true, ftype);
}
infer(ftype: ResolvedType): VarInfo {
return new VarInfo(this.declaredType, this.isConst, this.isCaptured, true, ftype);
}
static join(assembly: Assembly, ...values: VarInfo[]): VarInfo {
assert(values.length !== 0);
const jdef = values.every((vi) => vi.mustDefined);
const jtype = assembly.typeUpperBound(values.map((vi) => vi.flowType));
return new VarInfo(values[0].declaredType, values[0].isConst, values[0].isCaptured, jdef, jtype);
}
}
class TypeEnvironment {
readonly ikey: MIRInvokeKey;
readonly bodyid: string;
readonly terms: Map<string, ResolvedType>;
readonly pcodes: Map<string, PCode>;
readonly args: Map<string, VarInfo> | undefined;
readonly locals: Map<string, VarInfo>[] | undefined;
readonly inferResult: ResolvedType | undefined;
readonly inferYield: (ResolvedType | undefined)[];
readonly expressionResult: ExpressionReturnResult | undefined;
readonly returnResult: ResolvedType | undefined;
readonly yieldResult: ResolvedType | undefined;
readonly frozenVars: Set<string>;
private constructor(ikey: MIRInvokeKey, bodyid: string, terms: Map<string, ResolvedType>, pcodes: Map<string, PCode>,
args: Map<string, VarInfo> | undefined, locals: Map<string, VarInfo>[] | undefined, result: ResolvedType | undefined, inferYield: (ResolvedType | undefined)[],
expressionResult: ExpressionReturnResult | undefined, rflow: ResolvedType | undefined, yflow: ResolvedType | undefined,
frozenVars: Set<string>) {
this.ikey = ikey;
this.bodyid = bodyid;
this.terms = terms;
this.pcodes = pcodes;
this.args = args;
this.locals = locals;
this.inferResult = result;
this.inferYield = inferYield;
this.expressionResult = expressionResult;
this.returnResult = rflow;
this.yieldResult = yflow;
this.frozenVars = frozenVars;
}
private updateVarInfo(name: string, nv: VarInfo): TypeEnvironment {
if (this.getLocalVarInfo(name) !== undefined) {
let localcopy = (this.locals as Map<string, VarInfo>[]).map((frame) => frame.has(name) ? new Map<string, VarInfo>(frame).set(name, nv) : new Map<string, VarInfo>(frame));
return new TypeEnvironment(this.ikey, this.bodyid, this.terms, this.pcodes, this.args, localcopy, this.inferResult, this.inferYield, this.expressionResult, this.returnResult, this.yieldResult, this.frozenVars);
}
else {
const argscopy = new Map<string, VarInfo>(this.args as Map<string, VarInfo>).set(name, nv);
return new TypeEnvironment(this.ikey, this.bodyid, this.terms, this.pcodes, argscopy, this.locals, this.inferResult, this.inferYield, this.expressionResult, this.returnResult, this.yieldResult, this.frozenVars);
}
}
static createInitialEnvForCall(ikey: MIRInvokeKey, bodyid: string, terms: Map<string, ResolvedType>, pcodes: Map<string, PCode>, args: Map<string, VarInfo>, inferResult: ResolvedType | undefined): TypeEnvironment {
return new TypeEnvironment(ikey, bodyid, terms, pcodes, args, [new Map<string, VarInfo>()], inferResult, [], undefined, undefined, undefined, new Set<string>());
}
hasNormalFlow(): boolean {
return this.locals !== undefined;
}
getExpressionResult(): ExpressionReturnResult {
assert(this.hasNormalFlow() && this.expressionResult !== undefined);
return this.expressionResult as ExpressionReturnResult;
}
inferVarsOfType(ftype: ResolvedType, ...vars: (string | undefined)[]): TypeEnvironment {
let cenv = this as TypeEnvironment;
for(let i = 0; i < vars.length; ++i) {
const vv = vars[i];
if (vv !== undefined) {
cenv = cenv.updateVarInfo(vv, (cenv.lookupVar(vv) as VarInfo).infer(ftype));
}
}
return cenv;
}
clearExpressionResult(): TypeEnvironment {
return new TypeEnvironment(this.ikey, this.bodyid, this.terms, this.pcodes, this.args, this.locals, this.inferResult, this.inferYield, undefined, this.returnResult, this.yieldResult, this.frozenVars);
}
setUniformResultExpression(etype: ResolvedType, value?: FlowTypeTruthValue): TypeEnvironment {
assert(this.hasNormalFlow());
const einfo = new ExpressionReturnResult(new ValueType(etype, etype), value || FlowTypeTruthValue.Unknown, undefined);
return new TypeEnvironment(this.ikey, this.bodyid, this.terms, this.pcodes, this.args, this.locals, this.inferResult, this.inferYield, einfo, this.returnResult, this.yieldResult, this.frozenVars);
}
setBoolResultExpression(btype: ResolvedType, value: FlowTypeTruthValue): TypeEnvironment {
assert(this.hasNormalFlow());
const einfo = new ExpressionReturnResult(ValueType.createUniform(btype), value || FlowTypeTruthValue.Unknown, undefined);
return new TypeEnvironment(this.ikey, this.bodyid, this.terms, this.pcodes, this.args, this.locals, this.inferResult, this.inferYield, einfo, this.returnResult, this.yieldResult, this.frozenVars);
}
setVarResultExpression(layouttype: ResolvedType, flowtype: ResolvedType, vname: string): TypeEnvironment {
assert(this.hasNormalFlow());
const einfo = new ExpressionReturnResult(new ValueType(layouttype, flowtype), FlowTypeTruthValue.Unknown, vname);
return new TypeEnvironment(this.ikey, this.bodyid, this.terms, this.pcodes, this.args, this.locals, this.inferResult, this.inferYield, einfo, this.returnResult, this.yieldResult, this.frozenVars);
}
updateResultExpression(layouttype: ResolvedType, flowtype: ResolvedType): TypeEnvironment {
assert(this.hasNormalFlow());
const einfo = new ExpressionReturnResult(new ValueType(layouttype, flowtype), this.getExpressionResult().truthval, this.getExpressionResult().expvar);
return new TypeEnvironment(this.ikey, this.bodyid, this.terms, this.pcodes, this.args, this.locals, this.inferResult, this.inferYield, einfo, this.returnResult, this.yieldResult, this.frozenVars);
}
setResultExpression(layouttype: ResolvedType, flowtype: ResolvedType, value: FlowTypeTruthValue | undefined, vname: string | undefined): TypeEnvironment {
assert(this.hasNormalFlow());
const einfo = new ExpressionReturnResult(new ValueType(layouttype, flowtype), value || this.getExpressionResult().truthval, vname || this.getExpressionResult().expvar);
return new TypeEnvironment(this.ikey, this.bodyid, this.terms, this.pcodes, this.args, this.locals, this.inferResult, this.inferYield, einfo, this.returnResult, this.yieldResult, this.frozenVars);
}
private setResultExpressionWVarOpt(vtype: ValueType, evar: string | undefined, value?: FlowTypeTruthValue): TypeEnvironment {
assert(this.hasNormalFlow());
const rvalue = value || FlowTypeTruthValue.Unknown;
const einfo = new ExpressionReturnResult(vtype, rvalue, evar);
const nte = new TypeEnvironment(this.ikey, this.bodyid, this.terms, this.pcodes, this.args, this.locals, this.inferResult, this.inferYield, einfo, this.returnResult, this.yieldResult, this.frozenVars);
return evar === undefined ? nte : nte.updateVarInfo(evar, (nte.lookupVar(evar) as VarInfo).infer(vtype.flowtype));
}
static convertToBoolFlowsOnResult(assembly: Assembly, options: TypeEnvironment[]): {tenvs: TypeEnvironment[], fenvs: TypeEnvironment[]} {
assert(options.every((opt) => assembly.subtypeOf(opt.getExpressionResult().valtype.flowtype, assembly.getSpecialBoolType())));
const tvals = options.filter((opt) => opt.getExpressionResult().truthval !== FlowTypeTruthValue.False)
.map((opt) => opt.setResultExpressionWVarOpt(ValueType.createUniform(assembly.getSpecialBoolType()), opt.getExpressionResult().expvar, FlowTypeTruthValue.True));
const fvals = options.filter((opt) => opt.getExpressionResult().truthval !== FlowTypeTruthValue.True)
.map((opt) => opt.setResultExpressionWVarOpt(ValueType.createUniform(assembly.getSpecialBoolType()), opt.getExpressionResult().expvar, FlowTypeTruthValue.False));
return {tenvs: tvals, fenvs: fvals};
}
static convertToTypeNotTypeFlowsOnResult(assembly: Assembly, witht: ResolvedType, options: TypeEnvironment[]): {tenvs: TypeEnvironment[], fenvs: TypeEnvironment[]} {
let tp: TypeEnvironment[] = [];
let fp: TypeEnvironment[] = [];
for(let i = 0; i < options.length; ++i) {
const opt = options[i];
const vtype = opt.getExpressionResult().valtype;
const pccs = assembly.splitTypes(vtype.flowtype, witht);
if(!pccs.tp.isEmptyType()) {
tp.push(opt.setResultExpressionWVarOpt(vtype.inferFlow(pccs.tp), opt.getExpressionResult().expvar, opt.getExpressionResult().truthval));
}
if(!pccs.fp.isEmptyType()) {
fp.push(opt.setResultExpressionWVarOpt(vtype.inferFlow(pccs.fp), opt.getExpressionResult().expvar, opt.getExpressionResult().truthval));
}
}
return {tenvs: tp, fenvs: fp};
}
static convertToHasIndexNotHasIndexFlowsOnResult(assembly: Assembly, idx: number, options: TypeEnvironment[]): {tenvs: TypeEnvironment[], fenvs: TypeEnvironment[]} {
let tp: TypeEnvironment[] = [];
let fp: TypeEnvironment[] = [];
for(let i = 0; i < options.length; ++i) {
const opt = options[i];
const vtype = opt.getExpressionResult().valtype;
const pccs = assembly.splitIndex(vtype.flowtype, idx);
if(!pccs.tp.isEmptyType()) {
tp.push(opt.setResultExpressionWVarOpt(vtype.inferFlow(pccs.tp), opt.getExpressionResult().expvar));
}
if(!pccs.fp.isEmptyType()) {
fp.push(opt.setResultExpressionWVarOpt(vtype.inferFlow(pccs.fp), opt.getExpressionResult().expvar));
}
}
return {tenvs: tp, fenvs: fp};
}
static convertToHasIndexNotHasPropertyFlowsOnResult(assembly: Assembly, pname: string, options: TypeEnvironment[]): {tenvs: TypeEnvironment[], fenvs: TypeEnvironment[]} {
let tp: TypeEnvironment[] = [];
let fp: TypeEnvironment[] = [];
for(let i = 0; i < options.length; ++i) {
const opt = options[i];
const vtype = opt.getExpressionResult().valtype;
const pccs = assembly.splitProperty(vtype.flowtype, pname);
if(!pccs.tp.isEmptyType()) {
tp.push(opt.setResultExpressionWVarOpt(vtype.inferFlow(pccs.tp), opt.getExpressionResult().expvar));
}
if(!pccs.fp.isEmptyType()) {
fp.push(opt.setResultExpressionWVarOpt(vtype.inferFlow(pccs.fp), opt.getExpressionResult().expvar));
}
}
return {tenvs: tp, fenvs: fp};
}
setAbort(): TypeEnvironment {
assert(this.hasNormalFlow());
return new TypeEnvironment(this.ikey, this.bodyid, this.terms, this.pcodes, this.args, undefined, this.inferResult, this.inferYield, this.expressionResult, this.returnResult, this.yieldResult, this.frozenVars);
}
setReturn(assembly: Assembly, rtype: ResolvedType): TypeEnvironment {
assert(this.hasNormalFlow());
const rrtype = this.returnResult !== undefined ? assembly.typeUpperBound([this.returnResult, rtype]) : rtype;
return new TypeEnvironment(this.ikey, this.bodyid, this.terms, this.pcodes, this.args, undefined, this.inferResult, this.inferYield, this.expressionResult, rrtype, this.yieldResult, this.frozenVars);
}
setYield(assembly: Assembly, ytype: ResolvedType): TypeEnvironment {
assert(this.hasNormalFlow());
const rytype = this.yieldResult !== undefined ? assembly.typeUpperBound([this.yieldResult, ytype]) : ytype;
return new TypeEnvironment(this.ikey, this.bodyid, this.terms, this.pcodes, this.args, undefined, this.inferResult, this.inferYield, this.expressionResult, this.returnResult, rytype, this.frozenVars);
}
pushLocalScope(): TypeEnvironment {
assert(this.hasNormalFlow());
let localscopy = [...(this.locals as Map<string, VarInfo>[]), new Map<string, VarInfo>()];
return new TypeEnvironment(this.ikey, this.bodyid, this.terms, this.pcodes, this.args, localscopy, this.inferResult, this.inferYield, this.expressionResult, this.returnResult, this.yieldResult, this.frozenVars);
}
popLocalScope(): TypeEnvironment {
let localscopy = this.locals !== undefined ? (this.locals as Map<string, VarInfo>[]).slice(0, -1) : undefined;
return new TypeEnvironment(this.ikey, this.bodyid, this.terms, this.pcodes, this.args, localscopy, this.inferResult, this.inferYield, this.expressionResult, this.returnResult, this.yieldResult, this.frozenVars);
}
isInYieldBlock(): boolean {
return this.inferYield.length !== 0;
}
getLocalVarInfo(name: string): VarInfo | undefined {
const locals = this.locals as Map<string, VarInfo>[];
for (let i = locals.length - 1; i >= 0; --i) {
if (locals[i].has(name)) {
return (locals[i].get(name) as VarInfo);
}
}
return undefined;
}
isVarNameDefined(name: string): boolean {
return this.getLocalVarInfo(name) !== undefined || (this.args as Map<string, VarInfo>).has(name);
}
lookupVar(name: string): VarInfo | null {
return this.getLocalVarInfo(name) || (this.args as Map<string, VarInfo>).get(name) || null;
}
lookupPCode(pc: string): PCode | undefined {
return this.pcodes.get(pc);
}
addVar(name: string, isConst: boolean, dtype: ResolvedType, isDefined: boolean, infertype: ResolvedType): TypeEnvironment {
assert(this.hasNormalFlow());
let localcopy = (this.locals as Map<string, VarInfo>[]).map((frame) => new Map<string, VarInfo>(frame));
localcopy[localcopy.length - 1].set(name, new VarInfo(dtype, isConst, false, isDefined, infertype));
return new TypeEnvironment(this.ikey, this.bodyid, this.terms, this.pcodes, this.args, localcopy, this.inferResult, this.inferYield, this.expressionResult, this.returnResult, this.yieldResult, this.frozenVars);
}
setVar(name: string, flowtype: ResolvedType): TypeEnvironment {
assert(this.hasNormalFlow());
const oldv = this.lookupVar(name) as VarInfo;
const nv = oldv.assign(flowtype);
let localcopy = (this.locals as Map<string, VarInfo>[]).map((frame) => frame.has(name) ? new Map<string, VarInfo>(frame).set(name, nv) : new Map<string, VarInfo>(frame));
return new TypeEnvironment(this.ikey, this.bodyid, this.terms, this.pcodes, this.args, localcopy, this.inferResult, this.inferYield, this.expressionResult, this.returnResult, this.yieldResult, this.frozenVars);
}
setRefVar(name: string): TypeEnvironment {
assert(this.hasNormalFlow());
const oldv = this.lookupVar(name) as VarInfo;
const nv = oldv.assign(oldv.declaredType);
let localcopy = (this.locals as Map<string, VarInfo>[]).map((frame) => frame.has(name) ? new Map<string, VarInfo>(frame).set(name, nv) : new Map<string, VarInfo>(frame));
return new TypeEnvironment(this.ikey, this.bodyid, this.terms, this.pcodes, this.args, localcopy, this.inferResult, this.inferYield, this.expressionResult, this.returnResult, this.yieldResult, this.frozenVars);
}
multiVarUpdate(allDeclared: [boolean, string, ResolvedType, ResolvedType][], allAssigned: [string, ResolvedType][]): TypeEnvironment {
assert(this.hasNormalFlow());
let nenv: TypeEnvironment = this;
for (let i = 0; i < allDeclared.length; ++i) {
const declv = allDeclared[i];
nenv = nenv.addVar(declv[1], declv[0], declv[2], true, declv[3]);
}
for (let i = 0; i < allAssigned.length; ++i) {
const assignv = allAssigned[i];
nenv = nenv.setVar(assignv[0], assignv[1]);
}
return nenv;
}
getCurrentFrameNames(): string[] {
let res: string[] = [];
(this.locals as Map<string, VarInfo>[])[(this.locals as Map<string, VarInfo>[]).length - 1].forEach((v, k) => {
res.push(k);
});
return res;
}
getAllLocalNames(): Set<string> {
let names = new Set<string>();
(this.locals as Map<string, VarInfo>[]).forEach((frame) => {
frame.forEach((v, k) => {
names.add(k);
});
});
return names;
}
freezeVars(inferyield: ResolvedType | undefined): TypeEnvironment {
assert(this.hasNormalFlow());
let svars = new Set<string>();
for (let i = 0; i < (this.locals as Map<string, VarInfo>[]).length; ++i) {
(this.locals as Map<string, VarInfo>[])[i].forEach((v, k) => svars.add(k));
}
const iyeild = [...this.inferYield, inferyield];
return new TypeEnvironment(this.ikey, this.bodyid, this.terms, this.pcodes, this.args, this.locals, this.inferResult, iyeild, this.expressionResult, this.returnResult, this.yieldResult, svars);
}
static join(assembly: Assembly, ...opts: TypeEnvironment[]): TypeEnvironment {
assert(opts.length !== 0);
if (opts.length === 1) {
return opts[0];
}
else {
const fopts = opts.filter((opt) => opt.locals !== undefined);
let argnames: string[] = [];
fopts.forEach((opt) => {
(opt.args as Map<string, VarInfo>).forEach((v, k) => argnames.push(k));
});
let args = fopts.length !== 0 ? new Map<string, VarInfo>() : undefined;
if (args !== undefined) {
argnames.forEach((aname) => {
const vinfo = VarInfo.join(assembly, ...fopts.map((opt) => (opt.args as Map<string, VarInfo>).get(aname) as VarInfo));
(args as Map<string, VarInfo>).set(aname, vinfo);
});
}
let locals = fopts.length !== 0 ? ([] as Map<string, VarInfo>[]) : undefined;
if (locals !== undefined) {
for (let i = 0; i < (fopts[0].locals as Map<string, VarInfo>[]).length; ++i) {
let localsi = new Map<string, VarInfo>();
(fopts[0].locals as Map<string, VarInfo>[])[i].forEach((v, k) => {
localsi.set(k, VarInfo.join(assembly, ...fopts.map((opt) => opt.lookupVar(k) as VarInfo)));
});
locals.push(localsi);
}
}
const expresall = fopts.filter((opt) => opt.expressionResult !== undefined).map((opt) => opt.getExpressionResult());
let expres: ExpressionReturnResult | undefined = undefined;
if (expresall.length !== 0) {
const retype = ValueType.join(assembly, ...expresall.map((opt) => opt.valtype));
const rflow = FlowTypeTruthOps.join(...expresall.map((opt) => opt.truthval));
const evar = expresall.every((ee) => ee.expvar === expresall[0].expvar) ? expresall[0].expvar : undefined;
expres = new ExpressionReturnResult(retype, rflow, evar);
}
const rflow = opts.filter((opt) => opt.returnResult !== undefined).map((opt) => opt.returnResult as ResolvedType);
const yflow = opts.filter((opt) => opt.yieldResult !== undefined).map((opt) => opt.yieldResult as ResolvedType);
return new TypeEnvironment(opts[0].ikey, opts[0].bodyid, opts[0].terms, opts[0].pcodes, args, locals, opts[0].inferResult, opts[0].inferYield, expres, rflow.length !== 0 ? assembly.typeUpperBound(rflow) : undefined, yflow.length !== 0 ? assembly.typeUpperBound(yflow) : undefined, opts[0].frozenVars);
}
}
}
export {
FlowTypeTruthValue, FlowTypeTruthOps, ValueType,
VarInfo, ExpressionReturnResult,
TypeEnvironment
}; | the_stack |
import { Iterate, IterateAction } from 'iteratez';
import { Constants } from './Constants';
import { Day, DayInput, DayProperty } from './Day';
import { durations, Unit } from './DayFunctions';
import { DaySpan } from './DaySpan';
import { FrequencyCheck, FrequencyValue } from './Frequency';
import { Functions as fn } from './Functions';
import { Identifier, IdentifierInput } from './Identifier';
import { LocaleRule, Locales } from './Locale';
import { Op } from './Operation';
import { Parse } from './Parse';
import { ScheduleModifier, ScheduleModifierSpan } from './ScheduleModifier';
import { Time, TimeInput } from './Time';
import { Units } from './Units';
/**
* A tuple which identifies an event on the schedule. The tuple contains the
* total span of the event occurrence, the day of the event (could be the start
* day, end day, or any days in between for multi-day events) as well as the
* identifier for the event.
*/
export type ScheduleEventTuple = [DaySpan, Day, IdentifierInput];
/**
* A shortcut for the most common type of iterators a Schedule returns.
*/
type Iter<M, T = Day> = Iterate<T, number, Schedule<M>>;
/**
* Input given by a user which describes an event schedule.
*
* @typeparam M The type of metadata stored in the schedule.
*/
export interface ScheduleInput<M>
{
/**
* @see [[Schedule.start]]
*/
start?: DayInput;
/**
* @see [[Schedule.end]]
*/
end?: DayInput;
/**
* @see [[Schedule.maxOccurrences]]
*/
maxOccurrences?: number;
/**
* A shortcut to setting the [[Schedule.start]], [[Schedule.end]],
* [[Schedule.year]], [[Schedule.month]], and [[Schedule.dayOfMonth]].
*/
on?: DayInput;
/**
* @see [[Schedule.times]]
*/
times?: TimeInput[];
/**
* @see [[Schedule.duration]]
*/
duration?: number;
/**
* @see [[Schedule.durationUnit]]
*/
durationUnit?: string;
/**
* An array of days or identifiers which should be excluded from the schedule.
*
* @see [[Schedule.exclude]]
*/
exclude?: (Day | IdentifierInput)[];
/**
* An array of days or identifiers which should be included in the schedule.
*
* @see [[Schedule.include]]
*/
include?: (Day | IdentifierInput)[];
/**
* An array of days or identifiers which should be canceled in the schedule.
*
* @see [[Schedule.cancel]]
*/
cancel?: (Day | IdentifierInput)[];
/**
* @see [[Schedule.meta]]
*/
meta?: { [identifier: string]: M };
/**
* @see [[Schedule.month]]
*/
month?: FrequencyValue;
/**
* @see [[Schedule.year]]
*/
year?: FrequencyValue;
/**
* @see [[Schedule.day]]
*/
day?: FrequencyValue;
/**
* @see [[Schedule.quarter]]
*/
quarter?: FrequencyValue;
/**
* @see [[Schedule.dayOfWeek]]
*/
dayOfWeek?: FrequencyValue;
/**
* @see [[Schedule.dayOfMonth]]
*/
dayOfMonth?: FrequencyValue;
/**
* @see [[Schedule.lastDayOfMonth]]
*/
lastDayOfMonth?: FrequencyValue;
/**
* @see [[Schedule.dayOfYear]]
*/
dayOfYear?: FrequencyValue;
/**
* @see [[Schedule.week]]
*/
week?: FrequencyValue;
/**
* @see [[Schedule.weekOfYear]]
*/
weekOfYear?: FrequencyValue;
/**
* @see [[Schedule.weekspanOfYear]]
*/
weekspanOfYear?: FrequencyValue;
/**
* @see [[Schedule.fullWeekOfYear]]
*/
fullWeekOfYear?: FrequencyValue;
/**
* @see [[Schedule.lastWeekspanOfYear]]
*/
lastWeekspanOfYear?: FrequencyValue;
/**
* @see [[Schedule.lastFullWeekOfYear]]
*/
lastFullWeekOfYear?: FrequencyValue;
/**
* @see [[Schedule.weekOfMonth]]
*/
weekOfMonth?: FrequencyValue;
/**
* @see [[Schedule.weekspanOfMonth]]
*/
weekspanOfMonth?: FrequencyValue;
/**
* @see [[Schedule.fullWeekOfMonth]]
*/
fullWeekOfMonth?: FrequencyValue;
/**
* @see [[Schedule.lastWeekspanOfMonth]]
*/
lastWeekspanOfMonth?: FrequencyValue;
/**
* @see [[Schedule.lastFullWeekOfMonth]]
*/
lastFullWeekOfMonth?: FrequencyValue;
/**
* The function to parse metadata with.
*/
parseMeta?(input: any): M;
}
/**
* A class which describes when an event occurs over what time and if it repeats.
*
* @typeparam M The type of metadata stored in the schedule.
*/
export class Schedule<M>
{
/**
* The earliest an event can occur in the schedule, or `null` if there are no
* restrictions when the earliest event can occur. This day is inclusive.
*/
public start: Day;
/**
* The latest an event can occur in the schedule, or `null` if there are no
* restrictions when the latest event can occur. This day is inclusive.
*/
public end: Day;
// Private variable maxOccurrences.
private _maxOccurrences: number;
/**
* The maximum number of occurrences allowed in the Schedule.
* [[Schedule.start]] is required and [[Schedule.end]] is ignored and
* overwritten. This is an expensive check and should be avoided if
* possible. If this value is less than 1 it is ignored.
*/
public get maxOccurrences(): number
{
return this._maxOccurrences;
}
public set maxOccurrences(value: number)
{
this._maxOccurrences = value;
if (this.checks)
{
this.updateEnd();
}
}
/**
* The length of events in this schedule.
*/
public duration: number;
/**
* The unit which describes the duration of the event.
*/
public durationUnit: Unit;
/**
* The times at which the events occur on the days they should. If there are
* no times specified its assumed to be an all day event - potentially over
* multiple days or weeks based on [[Schedule.duration]] and
* [[Schedule.durationUnit]].
*/
public times: Time[];
/**
* The number of days an event in this schedule lasts PAST the starting day.
* If this is a full day event with a duration greater than zero this value
* will be greater than one. If this event occurs at a specific time with a
* given duration that is taken into account and if it passes over into the
* next day this value will be greater than one. This value is used to look
* back in time when trying to figure out what events start or overlap on a
* given day.
*/
public durationInDays: number;
/**
* A set of identifiers which mark what days or times are excluded on the
* schedule. This typically represents the set of event occurrences removed.
*/
public exclude: ScheduleModifier<boolean>;
/**
* A set of identifiers which mark what days or times are included outside
* the normal series of days on the schedule. This typically represents
* an event occurrence which is moved so its added to the exclude and include
* sets.
*/
public include: ScheduleModifier<boolean>;
/**
* A set of identifiers which mark what days, times, weeks, months, etc that
* should have all event occurrences cancelled.
*/
public cancel: ScheduleModifier<boolean>;
/**
* A map of metadata keyed by an identifier. The metadata is placed in
* [[CalendarEvent]].
*/
public meta: ScheduleModifier<M>;
/**
* How frequent the event occurs based on [[Day.day]].
*/
public day: FrequencyCheck;
/**
* How frequent the event occurs based on [[Day.dayOfWeek]].
*/
public dayOfWeek: FrequencyCheck;
/**
* How frequent the event occurs based on [[Day.dayOfMonth]].
*/
public dayOfMonth: FrequencyCheck;
/**
* How frequent the event occurs based on [[Day.lastDayOfMonth]].
*/
public lastDayOfMonth: FrequencyCheck;
/**
* How frequent the event occurs based on [[Day.dayOfYear]].
*/
public dayOfYear: FrequencyCheck;
/**
* How frequent the event occurs based on [[Day.month]].
*/
public month: FrequencyCheck;
/**
* How frequent the event occurs based on [[Day.week]].
*/
public week: FrequencyCheck;
/**
* How frequent the event occurs based on [[Day.weekOfYear]].
*/
public weekOfYear: FrequencyCheck;
/**
* How frequent the event occurs based on [[Day.weekspanOfYear]].
*/
public weekspanOfYear: FrequencyCheck;
/**
* How frequent the event occurs based on [[Day.fullWeekOfYear]].
*/
public fullWeekOfYear: FrequencyCheck;
/**
* How frequent the event occurs based on [[Day.lastWeekspanOfYear]].
*/
public lastWeekspanOfYear: FrequencyCheck;
/**
* How frequent the event occurs based on [[Day.lastFullWeekOfYear]].
*/
public lastFullWeekOfYear: FrequencyCheck;
/**
* How frequent the event occurs based on [[Day.weekOfMonth]].
*/
public weekOfMonth: FrequencyCheck;
/**
* How frequent the event occurs based on [[Day.weekspanOfMonth]].
*/
public weekspanOfMonth: FrequencyCheck;
/**
* How frequent the event occurs based on [[Day.fullWeekOfMonth]].
*/
public fullWeekOfMonth: FrequencyCheck;
/**
* How frequent the event occurs based on [[Day.lastWeekspanOfMonth]].
*/
public lastWeekspanOfMonth: FrequencyCheck;
/**
* How frequent the event occurs based on [[Day.lastFullWeekOfMonth]].
*/
public lastFullWeekOfMonth: FrequencyCheck;
/**
* How frequent the event occurs based on [[Day.year]].
*/
public year: FrequencyCheck;
/**
* How frequent the event occurs based on [[Day.quarter]].
*/
public quarter: FrequencyCheck;
/**
* The array of frequency functions which had valid frequencies.
*
* @see [[FrequencyCheck.given]]
*/
public checks: FrequencyCheck[];
/**
* Creates a schedule based on the given input.
*
* @param input The input which describes the schedule of events.
*/
public constructor(input?: ScheduleInput<M>)
{
this.exclude = new ScheduleModifier<boolean>();
this.include = new ScheduleModifier<boolean>();
this.cancel = new ScheduleModifier<boolean>();
this.meta = new ScheduleModifier<M>();
if (fn.isDefined(input))
{
this.set(input);
}
}
/**
* Sets the schedule with the given input.
*
* @param input The input or schedule which describes the schedule of events.
* @param parseMeta A function to use when parsing meta input into the desired type.
* @see [[Parse.schedule]]
*/
public set(input: ScheduleInput<M> | Schedule<M>,
parseMeta: (input: any) => M = (x => x)): this
{
if (input instanceof Schedule)
{
Parse.schedule<M>( input.toInput(), undefined, this);
}
else
{
Parse.schedule<M>(input, fn.coalesce( input.parseMeta, parseMeta ), this);
}
return this;
}
/**
* Returns the last event time specified or `undefined` if this schedule is
* for an all day event.
*/
public get lastTime(): Time
{
return this.times[ this.times.length - 1 ];
}
/**
* The [[Identifier]] for this schedule. Either [[Identifier.Day]] or
* [[Identifier.Time]].
*/
public get identifierType(): Identifier
{
return this.isFullDay() ? Identifier.Day : Identifier.Time;
}
/**
* Updates the [[Schedule.durationInDays]] variable based on the
* [[Schedule.lastTime]] (if any), the [[Schedule.duration]] and it's
* [[Schedule.durationUnit]].
*/
public updateDurationInDays(): this
{
const start: number = this.lastTime ? this.lastTime.toMilliseconds() : 0;
const duration: number = this.duration * (durations[ this.durationUnit ] || 0);
const exclude: number = Constants.MILLIS_IN_DAY;
const day: number = Constants.MILLIS_IN_DAY;
this.durationInDays = Math.max(0, Math.ceil((start + duration - exclude) / day));
return this;
}
/**
* Updates [[Schedule.checks]] based on the frequencies that were specified
* in the schedule input.
*/
public updateChecks(): this
{
this.checks = Parse.givenFrequency([
this.year,
this.month,
this.day,
this.quarter,
this.week,
this.weekOfYear,
this.fullWeekOfYear,
this.weekspanOfYear,
this.lastFullWeekOfYear,
this.lastWeekspanOfYear,
this.weekOfMonth,
this.weekspanOfMonth,
this.fullWeekOfMonth,
this.lastWeekspanOfMonth,
this.lastFullWeekOfMonth,
this.dayOfWeek,
this.dayOfMonth,
this.lastDayOfMonth,
this.dayOfYear
]);
return this;
}
/**
* Updates the [[Schedule.end]] based on [[Schedule.maxOccurrences]]
*/
public updateEnd(): this
{
if (this.maxOccurrences > 0 && this.start)
{
// Clear so it's not used in calculating maximum years.
this.end = null;
const maximumYears = this.getMaximum('year') - this.start.year + 1;
const lookahead = maximumYears * Constants.DAYS_IN_YEAR;
const previousOccurrences = this.include.spans().where(({ span }) => span.start.isBefore(this.start)).count();
const occurrences = this.maxOccurrences - previousOccurrences;
const last = this.forecast(this.start, false, occurrences, 0, true, lookahead).last();
if (last)
{
this.end = last[0].end;
}
}
return this;
}
/**
* Estimates the maximum number of `prop` from the start date that events
* could be happening. If the start date is not specified -1 will be
* returned representing potentially infinite `prop`s. If specific `prop`s
* are specified the difference between the maximum `prop` and the start `prop`
* will be returned. After that if [[Schedule.maxOccurrences]] is not
* specified -1 will be returned unless the end date is specified. In that
* case the `prop`s between the start and end are returned. Otherwise
* if events occur every X `prop`s then that calculation is used taking into
* account [[Schedule.maxOccurrences]]. Finally no year rule is specified
* so worst case is assumed, [[Schedule.maxOccurrences]].
*
* The returned value is always rounded up, so if the first and last
* occurrence happens the same `prop` 1 will be returned.
*/
public getMaximum (prop: DayProperty): number
{
if (!this.start)
{
return -1;
}
if (this.end)
{
return this.end[prop];
}
const occurs = this.maxOccurrences;
const start = this.start[prop];
const frequency = this[prop];
if (frequency)
{
const input = frequency.input;
if (fn.isFrequencyValueEquals(input))
{
return input;
}
else if (fn.isFrequencyValueOneOf(input))
{
let max: number = input[0];
for (let i = 1; i < input.length; i++)
{
if (input[i] > max) max = input[i];
}
return max;
}
if (occurs > 0 && fn.isFrequencyValueEvery(input))
{
const { every, offset } = input;
return start + (offset || 0) + every * occurs;
}
}
return occurs <= 0 ? -1 : start + occurs - 1;
}
/**
* Gets the start date of the schedule. Even if one is not specified, one
* can be calculated if this is a single event schedule.
*/
public getStart(): Day | null
{
if (this.start)
{
return this.start;
}
const singleEventSpan = this.getSingleEventSpan();
if (singleEventSpan)
{
return singleEventSpan.start;
}
return null;
}
/**
* Gets the end date of the schedule. Even if one is not specified, one
* can be calculated if this is a single event schedule.
*/
public getEnd(): Day | null
{
if (this.end)
{
return this.end;
}
const singleEventSpan = this.getSingleEventSpan();
if (singleEventSpan)
{
return singleEventSpan.end;
}
return null;
}
/**
* Attempts to calculate the entire range of the schedule taking into account
* any start date, end date, the included and excluded dates, and also even
* if the start and end date aren't specified, it checks to see if this is a
* single event schedule. If the start of the result is not defined, that
* means this schedule has occurred since the beginning of time. If the end
* of the result is not defined, that means the schedule will occurr until
* the end of time.
*/
public getRange(useInclude: boolean = true): Partial<DaySpan>
{
const hasTimes = this.times.length > 0;
let start = this.getStart();
let end = this.getEnd();
if (useInclude)
{
this.include.spans().each(({span}) =>
{
if (!this.isExcluded(span.start, hasTimes))
{
if (!start || span.start.isBefore(start))
{
start = span.start;
}
if (!end || span.end.isAfter(end))
{
end = span.end;
}
}
});
}
return { start, end }
}
/**
* Returns an iterator for all occurrences in this schedule. If a finite
* list of occurrences is not possible to generate, an empty iterator will
* be returned. A finite set of occurrences can be determine when a start
* and end date are specified.
*/
public getOccurrences(): Iterate<DaySpan, IdentifierInput, Schedule<M> | ScheduleModifier<M>>
{
const start = this.getStart();
const end = this.getEnd();
if (!start || !end)
{
return Iterate.empty();
}
const daysBetween = start.daysBetween(end, Op.CEIL, true);
const beforeStart = this.include
.spans()
.where(({span}) => span.start.isBefore(start))
.sorted((a, b) => a.span.start.time - b.span.start.time)
.transform(({span}) => span);
const afterStart = this.forecast(start, false, daysBetween)
.transform(([span]) => span);
const afterEnd = this.include
.spans()
.where(({span}) => span.start.isAfter(end))
.sorted((a, b) => a.span.start.time - b.span.start.time)
.transform(({span}) => span);
return Iterate.join(beforeStart, afterStart, afterEnd);
}
/**
* Determines whether the given day lies between the earliest and latest
* valid day in the schedule.
*
* @param day The day to test.
* @returns `true` if the day lies in the schedule, otherwise `false`.
* @see [[Schedule.start]]
* @see [[Schedule.end]]
*/
public matchesSpan(day: Day): boolean
{
return (this.start === null || day.isSameOrAfter(this.start)) &&
(this.end === null || day.isBefore(this.end));
}
/**
* Determines whether the given range overlaps with the earliest and latest
* valid days in this schedule (if any).
*
* @param start The first day in the range.
* @param end The last day in the range.
* @returns `true` if the range intersects with the schedule, otherwise `false`.
* @see [[Schedule.start]]
* @see [[Schedule.end]]
*/
public matchesRange(start: Day, end: Day): boolean
{
if (this.start && end.isBefore(this.start))
{
return false;
}
if (this.end && start.isAfter(this.end))
{
return false;
}
return true;
}
/**
* Determines whether the given day is explicitly excluded in the schedule.
*
* @param day The day to test.
* @param lookAtTime lookAtTime If the specific time of the given day should
* be looked at.
* @returns `true` if the day was excluded, otherwise `false`.
*/
public isExcluded(day: Day, lookAtTime: boolean = true): boolean
{
return this.exclude.get( day, false, lookAtTime );
}
/**
* Determines whether the given day is explicitly included in the schedule.
*
* @param day The day to test.
* @param lookAtTime lookAtTime If the specific time of the given day should
* be looked at.
* @returns `true` if the day is NOT explicitly included, otherwise `false`.
*/
public isIncluded(day: Day, lookAtTime: boolean = true): boolean
{
return this.include.get( day, false, lookAtTime );
}
/**
* Determines whether the given day is cancelled in the schedule.
*
* @param day The day to test.
* @param lookAtTime lookAtTime If the specific time of the given day should
* be looked at.
* @returns `true` if the day was cancelled, otherwise `false`.
*/
public isCancelled(day: Day, lookAtTime: boolean = true): boolean
{
return this.cancel.get( day, false, lookAtTime );
}
/**
* Returns the metadata for the given day or `null` if there is none.
*
* @param day The day to return the metadata for.
* @param otherwise The data to return if none exists for the given day.
* @param lookAtTime lookAtTime If the specific time of the given day should
* be looked at.
* @returns The metadata or `null`.
*/
public getMeta(day: Day, otherwise: M = null, lookAtTime: boolean = true): M
{
return this.meta.get( day, otherwise, lookAtTime );
}
/**
* Returns all metadata for the given day or an empty array if there is none.
*
* @param day The day to return the metadata for.
* @returns The array of metadata ordered by priority or an empty array.
*/
public getMetas(day: Day): M[]
{
return this.meta.getAll( day );
}
/**
* Returns whether the events in the schedule are all day long or start at
* specific times. Full day events start at the start of the day and end at
* the start of the next day (if the duration = `1` and durationUnit = 'days').
* Full day events have no times specified and should have a durationUnit of
* either `days` or `weeks`.
*/
public isFullDay(): boolean
{
return this.times.length === 0;
}
/**
* Sets whether this schedule is a full day event if it is not already. If
* this schedule is a full day event and `false` is passed to this function
* a single timed event will be added based on `defaultTime`. If this schedule
* has timed events and `true` is passed to make the schedule full day, the
* timed events are removed from this schedule. If the durationUnit is not the
* expected unit based on the new full day flag - the duration is reset to 1
* and the duration unit is set to the expected unit.
*
* @param fullDay Whether this schedule should represent a full day event or
* timed events.
* @param defaultTime If `fullDay` is `false` and this schedule is currently
* a full day event - this time will be used as the time of the first event.
*/
public setFullDay(fullDay: boolean = true, defaultTime: TimeInput = '08:00'): this
{
if (fullDay !== this.isFullDay())
{
if (fullDay)
{
this.times = [];
if (this.durationUnit !== 'day')
{
this.duration = 1;
this.durationUnit = 'day';
}
}
else
{
this.times = [Parse.time( defaultTime )];
if (this.durationUnit !== 'hour')
{
this.duration = 1;
this.durationUnit = 'hour';
}
}
}
return this;
}
/**
* Adjusts the [[Schedule.start]] and [[Schedule.end]] dates specified on this
* schedule if this schedule represents a single event and the `start` and
* `end` are already set or `addSpan` is `true`.
*
* @param addSpan If `true`, the `start` and `end` dates will always be
* adjusted if this schedule is a single event.
*/
public adjustDefinedSpan(addSpan: boolean = false): this
{
const single: DaySpan = this.getSingleEventSpan();
if (single && (addSpan || (this.start && this.end)))
{
this.start = single.start.startOf('day');
this.end = single.end.endOf('day');
}
return this;
}
/**
* Returns a span of time for a schedule with full day events starting on the
* start of the given day with the desired duration in days or weeks.
*
* @param day The day the span starts on.
* @returns The span of time starting on the given day.
*/
public getFullSpan(day: Day): DaySpan
{
const start: Day = day.startOf('day');
const end: Day = start.add(this.durationUnit, this.duration);
return new DaySpan( start, end );
}
/**
* Returns a span of time starting on the given day at the given day with the
* duration specified on this schedule.
*
* @param day The day the span starts on.
* @param time The time of day the span starts.
* @returns The span of time calculated.
*/
public getTimeSpan(day: Day, time: Time): DaySpan
{
const start: Day = day.withTime( time );
const end: Day = start.add(this.durationUnit, this.duration);
return new DaySpan( start, end );
}
/**
* Determines whether the given day is a day on the schedule for the start
* of an event. If an event is more than one day and the day given is not the
* start this may return `false`. This does not test for event instances
* that exist through [[Schedule.include]].
*
* @param day The day to test.
* @returns `true` if the day marks the start of an event on the schedule.
* @see [[Schedule.isIncluded]]
* @see [[Schedule.isFullyExcluded]]
* @see [[Schedule.matchesSpan]]
*/
public matchesDay(day: Day): boolean
{
if (this.isIncluded( day, false ))
{
return true;
}
if (!this.matchesSpan( day ) || this.isFullyExcluded( day ))
{
return false;
}
for (const check of this.checks)
{
if (!check( day[ check.property ] ))
{
return false;
}
}
return true;
}
/**
* Determines whether the given day has events added through
* [[Schedule.include]].
*
* @param day The day to look for included times on.
* @returns `true` if there are included event instances on the given day,
* otherwise `false`.
*/
public hasIncludedTime(day: Day): boolean
{
return !this.iterateIncludeTimes( day ).empty();
}
/**
* Determines whether the given day is fully excluded from the schedule. A
* fully excluded day is one that has a day-wide exclusion, or the schedule
* is not an all-day event and all times in the schedule are specifically
* excluded.
*
* @param day The day to test.*
* @returns `true` if he day is fully excluded, otherwise `false`.
*/
public isFullyExcluded(day: Day): boolean
{
// If exclude object is empty, bail early.
if (this.exclude.isEmpty()) {
return false
}
if (this.isExcluded(day, false))
{
return true;
}
if (this.isFullDay())
{
return false;
}
for (const time of this.times)
{
if (!this.isExcluded( day.withTime( time ) ))
{
return false;
}
}
return true;
}
/**
* Finds the next day an event occurs on the schedule given a day to start,
* optionally including it, and a maximum number of days to look ahead.
*
* @param day The day to start to search from.
* @param includeDay If the given day should be included in the search.
* @param lookAhead The maximum number of days to look ahead from the given
* day for event occurrences.
* @returns The next day on the schedule or `null` if none exists.
*/
public nextDay(day: Day, includeDay: boolean = false, lookAhead: number = Constants.DAYS_IN_YEAR): Day
{
return this.iterateDaycast(day, 1, true, includeDay, lookAhead).first();
}
/**
* Finds the next specified number of days that events occur on the schedule
* given a day to start, optionally including it, and a maximum number of days
* to look ahead.
*
* @param day The day to start to search from.
* @param max The maximum number of days to return in the result.
* @param includeDay If the given day should be included in the search.
* @param lookAhead The maximum number of days to look ahead from the given
* day for event occurrences.
* @returns An array containing the next days on the schedule that events
* start or an empty array if there are none.
*/
public nextDays(day: Day, max: number, includeDay: boolean = false, lookAhead: number = Constants.DAYS_IN_YEAR): Iter<M>
{
return this.iterateDaycast(day, max, true, includeDay, lookAhead);
}
/**
* Finds the previous day an event occurs on the schedule given a day to start,
* optionally including it, and a maximum number of days to look behind.
*
* @param day The day to start to search from.
* @param includeDay If the given day should be included in the search.
* @param lookBack The maximum number of days to look behind from the given
* day for event occurrences.
* @returns The previous day on the schedule or `null` if none exists.
*/
public prevDay(day: Day, includeDay: boolean = false, lookBack: number = Constants.DAYS_IN_YEAR): Day
{
return this.iterateDaycast(day, 1, false, includeDay, lookBack).first();
}
/**
* Finds the previous specified number of days that events occur on the
* schedule given a day to start, optionally including it, and a maximum
* number of days to look behind.
*
* @param day The day to start to search from.
* @param max The maximum number of days to return in the result.
* @param includeDay If the given day should be included in the search.
* @param lookAhead The maximum number of days to look behind from the given
* day for event occurrences.
* @returns An array containing the previous days on the schedule that events
* start or an empty array if there are none.
*/
public prevDays(day: Day, max: number, includeDay: boolean = false, lookBack: number = Constants.DAYS_IN_YEAR): Iter<M>
{
return this.iterateDaycast(day, max, false, includeDay, lookBack);
}
/**
* Iterates over days that events start in the schedule given a day to start,
* a maximum number of days to find, and a direction to look.
*
* @param day The day to start to search from.
* @param max The maximum number of days to iterate.
* @param next If `true` this searches forward, otherwise `false` is backwards.
* @param includeDay If the given day should be included in the search.
* @param lookup The maximum number of days to look through from the given
* day for event occurrences.
* @returns A new Iterator for the days found in the cast.
* @see [[Schedule.iterateSpans]]
*/
public iterateDaycast(day: Day, max: number, next: boolean, includeDay: boolean = false, lookup: number = Constants.DAYS_IN_YEAR): Iter<M>
{
return new Iterate<Day, number, Schedule<M>>(iterator =>
{
let iterated: number = 0;
let acted: number = 0;
for (let days = 0; days < lookup; days++)
{
if (!includeDay || days > 0)
{
day = next ? day.next() : day.prev();
}
if (!this.iterateSpans( day, false ).empty())
{
const action: IterateAction = iterator.act( day, acted++ );
if (action === IterateAction.STOP || ++iterated >= max)
{
return;
}
}
}
});
}
/**
* Iterates through the spans (event instances) that start on or covers the
* given day.
*
* @param day The day to look for spans on.
* @param covers If `true` spans which span multiple days will be looked at
* to see if they intersect with the given day, otherwise `false` will
* only look at the given day for the start of events.
* @returns A new Iterator for all the spans found.
*/
public iterateSpans(day: Day, covers: boolean = false): Iter<M, DaySpan>
{
return new Iterate<DaySpan, number, Schedule<M>>(iterator =>
{
let current: Day = day;
let lookBehind: number = covers ? this.durationInDays : 0;
let key: number = 0;
// If the events start at the end of the day and may last multiple days....
if (this.isFullDay())
{
// If the schedule has events which span multiple days we need to look
// backwards for events that overlap with the given day.
while (lookBehind >= 0)
{
// If the current day matches the schedule rules...
if (this.matchesDay( current ))
{
// Build a DaySpan with the given start day and the schedules duration.
const span: DaySpan = this.getFullSpan( current );
// If that dayspan intersects with the given day, it's a winner!
if (span.matchesDay( day ))
{
switch (iterator.act( span, key++ ))
{
case IterateAction.STOP:
return;
}
}
}
current = current.prev();
lookBehind--;
}
}
// This schedule has events which start at certain times
else
{
// If the schedule has events which span multiple days we need to look
// backwards for events that overlap with the given day.
while (lookBehind >= 0)
{
// If the current day matches the schedule rules...
if (this.matchesDay( current ))
{
// Iterate through each daily occurrence in the schedule...
for (const time of this.times)
{
const span: DaySpan = this.getTimeSpan( current, time );
// If the event intersects with the given day and the occurrence
// has not specifically been excluded...
if (span.matchesDay( day ) && !this.isExcluded( span.start, true ))
{
switch (iterator.act( span, key++ ))
{
case IterateAction.STOP:
return;
}
}
}
}
else
{
// The current day does not match the schedule, however the schedule
// might have moved/random event occurrents on the current day.
// We only want the ones that overlap with the given day.
this.iterateIncludeTimes(current, day).each((span, i, timeIterator) =>
{
switch (iterator.act( span, key++ ))
{
case IterateAction.STOP:
timeIterator.stop();
break;
}
})
if (iterator.action === IterateAction.STOP)
{
return;
}
}
lookBehind--;
// Generating current.prev() is costly.
// Avoid generating it if looping condition is no longer satisfied.
if (lookBehind >= 0) {
current = current.prev()
}
}
}
});
}
/**
* Determines if the given day is on the schedule and the time specified on
* the day matches one of the times on the schedule.
*
* @param day The day to test.
* @returns `true` if the day and time match the schedule, otherwise false.
*/
public matchesTime(day: Day): boolean
{
return !!this.iterateSpans( day, true ).where( span => span.start.sameMinute( day ) ).first();
}
/**
* Determines if the given day is covered by this schedule. A schedule can
* specify events that span multiple days - so even though the day does not
* match the starting day of a span - it can be a day that is within the
* schedule.
*
* @param day The day to test.
* @returns `true` if the day is covered by an event on this schedule,
* otherwise `false`.
*/
public coversDay(day: Day): boolean
{
return !this.iterateSpans( day, true ).empty();
}
/**
* Determines if the given timestamp lies in an event occurrence on this
* schedule.
*
* @param day The timestamp to test against the schedule.
* @return `true` if the timestamp lies in an event occurrent start and end
* timestamps, otherwise `false`.
*/
public coversTime(day: Day): boolean
{
return !!this.iterateSpans( day, true ).where( span => span.contains( day ) ).first();
}
/**
* Sets the frequency for the given property. This does not update the
* [[Schedule.checks]] array, the [[Schedule.updateChecks]] function needs
* to be called.
*
* @param property The frequency to update.
* @param frequency The new frequency.
*/
public setFrequency(property: DayProperty, frequency?: FrequencyValue): this
{
this[ property ] = Parse.frequency( frequency, property );
return this;
}
/**
* Changes the exclusion status of the event at the given time. By default
* this excludes this event - but `false` may be passed to undo an exclusion.
*
* @param time The start time of the event occurrence to exclude or include.
* @param excluded Whether the event should be excluded.
*/
public setExcluded(time: Day, excluded: boolean = true): this
{
const type: Identifier = this.identifierType;
this.exclude.set( time, excluded, type );
this.include.set( time, !excluded, type );
return this;
}
/**
* Changes the cancellation status of the event at the given start time. By
* default this cancels the event occurrence - but `false` may be passed to
* undo a cancellation.
*
* @param time The start time of the event occurrence to cancel or uncancel.
* @param cancelled Whether the event should be cancelled.
*/
public setCancelled(time: Day, cancelled: boolean = true): this
{
this.cancel.set( time, cancelled, this.identifierType );
return this;
}
/**
* Removes the time from this schedule and all related included, excluded,
* cancelled instances as well as metadata.
*
* @param time The time to remove from the schedule.
* @param removeInclude If any included instances should be removed as well.
* @returns `true` if the time was removed, otherwise `false`.
*/
public removeTime(time: Time, removeInclude: boolean = true): boolean
{
let found: boolean = false;
for (let i = 0; i < this.times.length && !found; i++)
{
found = time.matches( this.times[ i ] )
if (found)
{
this.times.splice( i, 1 );
}
}
if (found)
{
if (removeInclude)
{
this.include.removeTime( time );
}
this.exclude.removeTime( time );
this.cancel.removeTime( time );
this.meta.removeTime( time );
}
return found;
}
/**
* Moves the event instance starting at `fromTime` to `toTime` optionally
* placing `meta` in the schedules metadata for the new time `toTime`.
* If this schedule has a single event ([[Schedule.isSingleEvent]]) then the
* only value needed is `toTime` and not `fromTime`.
*
* @param toTime The timestamp of the new event.
* @param fromTime The timestamp of the event on the schedule to move if this
* schedule generates multiple events.
* @returns `true` if the schedule had the event moved, otherwise `false`.
*/
public move(toTime: Day, fromTime?: Day, meta?: M): boolean
{
if (!this.moveSingleEvent( toTime ) && fromTime)
{
return this.moveInstance( fromTime, toTime );
}
return false;
}
/**
* Moves a time specified in this schedule to the given time, adjusting
* any cancelled event instances, metadata, and any excluded and included
* event instances.
*
* @param fromTime The time to move.
* @param toTime The new time in the schedule.
* @returns `true` if time was moved, otherwise `false`.
*/
public moveTime(fromTime: Time, toTime: Time): boolean
{
let found: boolean = false;
for (let i = 0; i < this.times.length && !found; i++)
{
found = fromTime.matches( this.times[ i ] )
if (found)
{
this.times.splice( i, 1, toTime );
}
}
if (found)
{
this.include.moveTime( fromTime, toTime );
this.exclude.moveTime( fromTime, toTime );
this.cancel.moveTime( fromTime, toTime );
this.meta.moveTime( fromTime, toTime );
this.adjustDefinedSpan( false );
}
return found;
}
/**
* Moves the event instance starting at `fromTime` to `toTime` optionally
* placing `meta` in the schedules metadata for the new time `toTime`. A move
* is accomplished by excluding the current event and adding an inclusion of
* the new day & time.
*
* @param fromTime The timestamp of the event on the schedule to move.
* @param toTime The timestamp of the new event.
* @returns `true`.
* @see [[Schedule.move]]
*/
public moveInstance(fromTime: Day, toTime: Day): boolean
{
const type: Identifier = this.identifierType;
this.exclude.set( fromTime, true, type );
this.exclude.set( toTime, false, type );
this.include.set( toTime, true, type );
this.include.set( fromTime, false, type );
if (this.cancel.get( fromTime, false ) && !this.cancel.get( toTime, false ))
{
this.cancel.set( toTime, true, type );
if (this.cancel.getIdentifier( fromTime ) === type)
{
this.cancel.unset( fromTime, type );
}
}
const meta: M = this.meta.get( fromTime, null );
if (meta && meta !== this.meta.get( toTime, null ))
{
this.meta.set( toTime, meta, type );
if (this.meta.getIdentifier( fromTime ) === type)
{
this.meta.unset( fromTime, type );
}
}
return true;
}
/**
* Moves the single event in this schedule to the given day/time if applicable.
* If this schedule is not a single event schedule then `false` is returned.
* If this schedule is a timed event the time will take the time of the given
* `toTime` of `takeTime` is `true`.
*
* @param toTime The time to move the single event to.
* @param takeTime If this schedule has a single timed event, should the time
* of the event be changed to the time of the given `toTime`?
* @returns `true` if the schedule was adjusted, otherwise `false`.
* @see [[Schedule.move]]
*/
public moveSingleEvent(toTime: Day, takeTime: boolean = true): boolean
{
if (!this.isSingleEvent())
{
return false;
}
for (const check of this.checks)
{
const prop: DayProperty = check.property;
const value = toTime[ prop ];
const frequency: FrequencyCheck = Parse.frequency( [value], prop );
this[ prop ] = frequency;
}
if (this.times.length === 1 && takeTime)
{
this.times = [toTime.asTime()];
}
this.updateChecks();
const span: DaySpan = this.getSingleEventSpan();
if (this.start)
{
this.start = span.start.startOf('day');
}
if (this.end)
{
this.end = span.end.endOf('day');
}
this.updateEnd();
return true;
}
/**
* Returns the span of the single event in this schedule if it's that type of
* schedule, otherwise `null` is returned.
*
* @returns A span of the single event, otherwise `null`.
* @see [[Schedule.isSingleEvent]]
*/
public getSingleEventSpan(): DaySpan
{
if (!this.isSingleEvent())
{
return null;
}
const startOfYear: Day = Day.build( this.year.input[0], 0, 1 );
const start: Day = this.iterateDaycast( startOfYear, 1, true, true, Constants.DAYS_IN_YEAR ).first();
if (!start)
{
return null;
}
return this.isFullDay() ?
this.getFullSpan( start ) :
this.getTimeSpan( start, this.times[ 0 ] );
}
/**
* Determines whether this schedule produces a single event, and no more.
* If this schedule has any includes, it's assumed to be a multiple event
* schedule. A single event can be detected in the following scenarios where
* each frequency has a single occurrence (see [[Schedule.isSingleFrequency]]).
*
* - year, day of year
* - year, month, day of month
* - year, month, week of month, day of week
* - year, week of year, day of week
*
* @returns `true` if this schedule produces a single event, otherwise `false`.
*/
public isSingleEvent(): boolean
{
// 0 = full day, 1 = once a day, 1+ = multiple events a day
if (this.times.length > 1)
{
return false;
}
// Let's assume if there are includes, this is not a single event.
if (!this.include.isEmpty())
{
return false;
}
// If this can occur on multiple years, not a single event.
if (!this.isSingleYear())
{
return false;
}
// If this is a specific year and day of the year: single!
if (this.isSingleDayOfYear())
{
return true;
}
// If this is a specific year, month, and day of month: single!
if (this.isSingleMonth() && this.isSingleDayOfMonth())
{
return true;
}
// If this is a specific year, month, week of the month, day of the week: single!
if (this.isSingleMonth() && this.isSingleWeekOfMonth() && this.isSingleDayOfWeek())
{
return true;
}
// If this is a specific year, week of the year, day of the week: single!
if (this.isSingleWeekOfYear() && this.isSingleDayOfWeek())
{
return true;
}
// Doesn't look like a single event.
return false;
}
/**
* @returns `true` if this schedule produces events only in a specific year.
* @see [[Schedule.year]]
*/
public isSingleYear(): boolean
{
return this.isSingleFrequency( this.year );
}
/**
* @returns `true` if this schedule produces events only in a specific month.
* @see [[Schedule.month]]
*/
public isSingleMonth(): boolean
{
return this.isSingleFrequency( this.month );
}
/**
* @returns `true` if this schedule produces events only in a specific day of
* the month.
* @see [[Schedule.dayOfMonth]]
* @see [[Schedule.lastDayOfMonth]]
*/
public isSingleDayOfMonth(): boolean
{
return this.isSingleFrequency( this.dayOfMonth ) ||
this.isSingleFrequency( this.lastDayOfMonth );
}
/**
* @returns `true` if this schedule produces events only in a specific day of
* the week.
* @see [[Schedule.day]]
* @see [[Schedule.dayOfWeek]]
*/
public isSingleDayOfWeek(): boolean
{
return this.isSingleFrequency( this.dayOfWeek ) ||
this.isSingleFrequency( this.day );
}
/**
* @returns `true` if this schedule produces events only in a specific day of
* the year.
* @see [[Schedule.dayOfYear]]
*/
public isSingleDayOfYear(): boolean
{
return this.isSingleFrequency( this.dayOfYear );
}
/**
* @returns `true` if this schedule produces events only in a specific week of
* the month.
* @see [[Schedule.weekspanOfMonth]]
* @see [[Schedule.fullWeekOfMonth]]
* @see [[Schedule.weekOfMonth]]
* @see [[Schedule.lastFullWeekOfMonth]]
* @see [[Schedule.lastWeekspanOfMonth]]
*/
public isSingleWeekOfMonth(): boolean
{
return this.isSingleFrequency( this.weekspanOfMonth ) ||
this.isSingleFrequency( this.fullWeekOfMonth ) ||
this.isSingleFrequency( this.weekOfMonth ) ||
this.isSingleFrequency( this.lastFullWeekOfMonth ) ||
this.isSingleFrequency( this.lastWeekspanOfMonth );
}
/**
* @returns `true` if this schedule produces events only in a specific week of
* the year.
* @see [[Schedule.weekspanOfYear]]
* @see [[Schedule.fullWeekOfYear]]
* @see [[Schedule.week]]
* @see [[Schedule.weekOfYear]]
* @see [[Schedule.lastFullWeekOfYear]]
* @see [[Schedule.lastWeekspanOfYear]]
*/
public isSingleWeekOfYear(): boolean
{
return this.isSingleFrequency( this.weekspanOfYear ) ||
this.isSingleFrequency( this.fullWeekOfYear ) ||
this.isSingleFrequency( this.week ) ||
this.isSingleFrequency( this.weekOfYear ) ||
this.isSingleFrequency( this.lastFullWeekOfYear ) ||
this.isSingleFrequency( this.lastWeekspanOfYear );
}
/**
* Determines if the given [[FrequencyCheck]] results in a single occurrence.
*
* @returns `true` if the frequency results in a single event, otherwise `false`.
*/
public isSingleFrequency(frequency: FrequencyCheck): boolean
{
return (fn.isFrequencyValueOneOf(frequency.input) && frequency.input.length === 1) || fn.isFrequencyValueEquals(frequency.input);
}
/**
* Creates a forecast for this schedule which returns a number of event
* occurrences around a given day. A single item could be returned per day, or
* you could get an item for each timed event occurrence.
*
* @param around The day to find a forecast around.
* @param covers If `true` spans which span multiple days will be looked at
* to see if they intersect with the given day, otherwise `false` will
* only look at the given day for the start of events.
* @param daysAfter The number of events to return after the given day.
* @param daysBefore The number of events to return before the given day.
* @param times If timed events should be returned, or only one for each day.
* @param lookAround How many days to look before and after the given day for
* event occurrences.
* @returns A new iterator which provides the event occurence span, the day it
* starts (or is covered if `covers` is `true`), and the identifier for the
* event.
*/
public forecast(around: Day,
covers: boolean = true,
daysAfter: number,
daysBefore: number = daysAfter,
times: boolean = false,
lookAround: number = Constants.DAYS_IN_YEAR): Iter<M, ScheduleEventTuple>
{
const type: Identifier = this.identifierType;
let tupleIndex: number = 0;
const tuplesForDay = (day: Day, tuples: Iter<M, ScheduleEventTuple>): boolean =>
{
const spans: DaySpan[] = this.iterateSpans( day, covers ).array();
const last: number = times ? spans.length : Math.min( 1, spans.length );
const offset: number = times ? 0 : spans.length - 1;
for (let i = 0; i < last; i++)
{
const span: DaySpan = spans[ i + offset ];
const id: IdentifierInput = type.get( span.start );
if (tuples.act( [ span, day, id ], tupleIndex++ ) === IterateAction.STOP)
{
return false;
}
}
return true;
};
const prev = new Iterate<ScheduleEventTuple, number, Schedule<M>>(iterator =>
{
let curr: Day = around;
for (let i = 0; i < lookAround; i++)
{
if (!tuplesForDay( curr, iterator ))
{
break;
}
curr = curr.prev();
}
});
const next = new Iterate<ScheduleEventTuple, number, Schedule<M>>(iterator =>
{
let curr: Day = around;
for (let i = 0; i < lookAround; i++)
{
curr = curr.next();
if (!tuplesForDay( curr, iterator ))
{
break;
}
}
});
return prev.take( daysBefore + 1 ).reverse().append( next.take( daysAfter ) );
}
/**
* Iterates timed events that were explicitly specified on the given day.
* Those events could span multiple days so may be tested against another day.
*
* @param day The day to look for included timed events.
* @param matchAgainst The day to test against the timed event.
* @returns A new Iterator for all the included spans found.
*/
public iterateIncludeTimes(day: Day, matchAgainst: Day = day): Iterate<DaySpan, string, ScheduleModifier<boolean>>
{
const isIncludedTime = (result: [IdentifierInput, boolean]) =>
{
const [id, included] = result;
return included && Identifier.Time.is( id );
};
const getSpan = (result: [IdentifierInput, boolean]) =>
{
const [id] = result;
const time: Day = Identifier.Time.start( id );
const span: DaySpan = this.getTimeSpan( time, time.asTime() );
if (span.matchesDay( matchAgainst ))
{
return span;
}
};
return this.include.query( day.dayIdentifier ).where( isIncludedTime ).transform<DaySpan>( getSpan );
}
/**
* Clones this schedule.
*
* @returns A new schedule which matches this schedule.
*/
public clone(): Schedule<M>
{
return new Schedule<M>( this.toInput() );
}
/**
* Converts the schedule instance back into input.
*
* @param returnDays When `true` the start, end, and array of exclusions will
* have [[Day]] instances, otherwise the UTC timestamp and dayIdentifiers
* will be used when `false`.
* @param returnTimes When `true` the times returned in the input will be
* instances of [[Time]] otherwise the `timeFormat` is used to convert the
* times to strings.
* @param timeFormat The time format to use when returning the times as strings.
* @param alwaysDuration If the duration values (`duration` and
* `durationUnit`) should always be returned in the input.
* @param alwaysReturnEnd If end should be in the input even if
* maxOccurrences is specified on the schedule.
* @returns The input that describes this schedule.
* @see [[Time.format]]
*/
public toInput(returnDays: boolean = false, returnTimes: boolean = false, timeFormat: string = '', alwaysDuration: boolean = false, alwaysReturnEnd: boolean = false): ScheduleInput<M>
{
const defaultUnit: string = Constants.DURATION_DEFAULT_UNIT( this.isFullDay() );
const exclusions: IdentifierInput[] = this.exclude.identifiers(v => v).array();
const inclusions: IdentifierInput[] = this.include.identifiers(v => v).array();
const cancels: IdentifierInput[] = this.cancel.identifiers(v => v).array();
const hasMeta: boolean = !this.meta.isEmpty();
const out: ScheduleInput<M> = {};
const times: TimeInput[] = [];
for (const time of this.times)
{
times.push( returnTimes ? time : (timeFormat ? time.format( timeFormat ) : time.toString()) );
}
if (this.start) out.start = returnDays ? this.start : this.start.time;
if (this.end && (alwaysReturnEnd || this.maxOccurrences < 1)) out.end = returnDays ? this.end : this.end.time;
if (this.maxOccurrences > 0) out.maxOccurrences = this.maxOccurrences;
if (times.length) out.times = times;
if (alwaysDuration || this.duration !== Constants.DURATION_DEFAULT) out.duration = this.duration;
if (alwaysDuration || this.durationUnit !== defaultUnit) out.durationUnit = this.durationUnit;
if (exclusions.length) out.exclude = exclusions;
if (inclusions.length) out.include = inclusions;
if (cancels.length) out.cancel = cancels;
if (hasMeta) out.meta = fn.extend( {}, this.meta.map );
if (this.dayOfWeek.input) out.dayOfWeek = this.dayOfWeek.input;
if (this.dayOfMonth.input) out.dayOfMonth = this.dayOfMonth.input;
if (this.lastDayOfMonth.input) out.lastDayOfMonth = this.lastDayOfMonth.input;
if (this.dayOfYear.input) out.dayOfYear = this.dayOfYear.input;
if (this.year.input) out.year = this.year.input;
if (this.month.input) out.month = this.month.input;
if (this.day.input) out.day = this.day.input;
if (this.week.input) out.week = this.week.input;
if (this.weekOfYear.input) out.weekOfYear = this.weekOfYear.input;
if (this.weekspanOfYear.input) out.weekspanOfYear = this.weekspanOfYear.input;
if (this.fullWeekOfYear.input) out.fullWeekOfYear = this.fullWeekOfYear.input;
if (this.lastWeekspanOfYear.input) out.lastWeekspanOfYear = this.lastWeekspanOfYear.input;
if (this.lastFullWeekOfYear.input) out.lastFullWeekOfYear = this.lastFullWeekOfYear.input;
if (this.weekOfMonth.input) out.weekOfMonth = this.weekOfMonth.input;
if (this.weekspanOfMonth.input) out.weekspanOfMonth = this.weekspanOfMonth.input;
if (this.fullWeekOfMonth.input) out.fullWeekOfMonth = this.fullWeekOfMonth.input;
if (this.lastWeekspanOfMonth.input) out.lastWeekspanOfMonth = this.lastWeekspanOfMonth.input;
if (this.lastFullWeekOfMonth.input) out.lastFullWeekOfMonth = this.lastFullWeekOfMonth.input;
return out;
}
/**
* Describes the schedule in a human friendly string taking into account all
* possible values specified in this schedule.
*
* @param thing A brief description of the things (events) on the schedule.
* @param includeRange When `true` the [[Schedule.start]] and [[Schedule.end]]
* are possibly included in the description if they have values.
* @param includeTimes When `true` the [[Schedule.times]] are possibly included
* in the description.
* @param includeDuration When `true` the [[Schedule.duration]] and
* [[Schedule.durationUnit]] are added to the description if
* [[Schedule.duration]] is not equal to `1`.
* @param includeExcludes When `true` the [[Schedule.exclude]] are added
* to the description if there are any.
* @param includeIncludes When `true` the [[Schedule.include]] are added
* to the description if there are any.
* @param includeCancels When `true` the [[Schedule.cancel]] are added
* to the description if there are any.
* @returns The descroption of the schedule.
*/
public describe(thing: string = 'event',
includeRange: boolean = true,
includeTimes: boolean = true,
includeDuration: boolean = false,
includeExcludes: boolean = false,
includeIncludes: boolean = false,
includeCancels: boolean = false): string
{
const lang = Locales.current;
let out: string = '';
if (includeRange)
{
if (this.start)
{
out += lang.scheduleStartingOn(this.start);
if (this.end)
{
out += lang.scheduleEndingOn(this.end);
}
}
else if (this.end)
{
out += lang.scheduleEndsOn(this.end);
}
}
out += lang.scheduleThing(thing, !out);
out += this.describeRule( this.dayOfWeek.input, lang.ruleDayOfWeek );
out += this.describeRule( this.day.input, lang.ruleDay );
out += this.describeRule( this.lastDayOfMonth.input, lang.ruleLastDayOfMonth );
out += this.describeRule( this.dayOfMonth.input, lang.ruleDayOfMonth );
out += this.describeRule( this.dayOfYear.input, lang.ruleDayOfYear );
out += this.describeRule( this.year.input, lang.ruleYear );
out += this.describeRule( this.month.input, lang.ruleMonth );
out += this.describeRule( this.week.input, lang.ruleWeek );
out += this.describeRule( this.weekOfYear.input, lang.ruleWeekOfYear );
out += this.describeRule( this.weekspanOfYear.input, lang.ruleWeekspanOfYear );
out += this.describeRule( this.fullWeekOfYear.input, lang.ruleFullWeekOfYear );
out += this.describeRule( this.lastWeekspanOfYear.input, lang.ruleLastWeekspanOfYear );
out += this.describeRule( this.lastFullWeekOfYear.input, lang.ruleLastFullWeekOfYear );
out += this.describeRule( this.weekOfMonth.input, lang.ruleWeekOfMonth );
out += this.describeRule( this.fullWeekOfMonth.input, lang.ruleFullWeekOfMonth );
out += this.describeRule( this.weekspanOfMonth.input, lang.ruleWeekspanOfMonth );
out += this.describeRule( this.lastFullWeekOfMonth.input, lang.ruleLastFullWeekOfMonth );
out += this.describeRule( this.lastWeekspanOfMonth.input, lang.ruleLastWeekspanOfMonth );
if (includeTimes && this.times.length)
{
out += lang.scheduleAtTimes;
out += this.describeArray( this.times, x => x.format('hh:mm a') );
}
if (includeDuration && this.duration !== Constants.DURATION_DEFAULT)
{
out += lang.scheduleDuration(this.duration, this.durationUnit);
}
if (includeExcludes)
{
const excludes: ScheduleModifierSpan<boolean>[] = this.exclude.spans().array();
if (excludes.length)
{
out += lang.scheduleExcludes;
out += this.describeArray( excludes, x => x.span.summary(Units.DAY) );
}
}
if (includeIncludes)
{
const includes: ScheduleModifierSpan<boolean>[] = this.include.spans().array();
if (includes.length)
{
out += lang.scheduleIncludes;
out += this.describeArray( includes, x => x.span.summary(Units.DAY) );
}
}
if (includeCancels)
{
const cancels: ScheduleModifierSpan<boolean>[] = this.cancel.spans().array();
if (cancels.length)
{
out += lang.scheduleCancels;
out += this.describeArray( cancels, x => x.span.summary(Units.DAY) );
}
}
return out;
}
/**
* Describes the given frequency.
*
* @param value The frequency to describe.
* @param localeRule The locale rule used to describe the frequency.
* @returns A string description of the frequency.
*/
private describeRule(value: FrequencyValue, localeRule: LocaleRule): string
{
let out = '';
if (fn.isFrequencyValueEvery(value))
{
out += ' ' + localeRule.every(value.every);
if (value.offset)
{
out += ' ' + localeRule.offset(value.offset);
}
}
else if (fn.isFrequencyValueOneOf(value))
{
if (value.length)
{
out += ' ' + localeRule.oneOf(value);
}
}
else if (fn.isFrequencyValueEquals(value))
{
out += ' ' + localeRule.oneOf([value]);
}
return out;
}
/**
* Describes the array by adding commas where appropriate and 'and' before the
* last value of the array (if its more than `1`).
*
* @param array The array of items to describe.
* @param map The function which converts an item to a string.
* @returns The final description of the array items.
*/
private describeArray<T>(array: T[], map: (item: T) => string): string
{
return Locales.current.list(array.map(map));
}
/**
* Generates a schedule for an event which occurs once all day for a given day
* optionally spanning multiple days starting on the given day.
*
* @param input The day the event starts.
* @param days The number of days the event lasts.
* @returns A new schedule that starts on the given day.
*/
public static forDay<M>(input: DayInput, days: number = 1): Schedule<M>
{
const day: Day = Day.parse( input );
if (!day)
{
return null;
}
return new Schedule<M>({
year: [ day.year ],
month: [ day.month ],
dayOfMonth: [ day.dayOfMonth ],
duration: days,
durationUnit: 'day'
});
}
/**
* Generates a schedule for an event which occurs once at a given time on a
* given day optionally spanning any amount of time (default is 1 hour).
*
* @param input The day the event starts.
* @param time The time the event starts.
* @param duration The duration of the event.
* @param durationUnit The unit for the duration of the event.
* @returns A new schedule that starts on the given day and time.
*/
public static forTime<M>(input: DayInput, time: TimeInput, duration: number = 1, durationUnit: Unit = 'hour'): Schedule<M>
{
const day: Day = Day.parse( input );
if (!day)
{
return null;
}
return new Schedule<M>({
year: [ day.year ],
month: [ day.month ],
dayOfMonth: [ day.dayOfMonth ],
times: [ time ],
duration,
durationUnit
});
}
/**
* Generates a schedule for an event which occurs once over a given span.
*
* @param span The span of the event.
* @returns A new schedule that starts and ends at the given timestamps.
*/
public static forSpan<M>(span: DaySpan): Schedule<M>
{
const start = span.start;
const minutes = span.minutes();
const isDay = minutes % Constants.MINUTES_IN_DAY === 0;
const isHour = minutes % Constants.MINUTES_IN_HOUR === 0;
const duration = isDay ? minutes / Constants.MINUTES_IN_DAY : (isHour ? minutes / Constants.MINUTES_IN_HOUR : minutes);
const durationUnit: Unit = isDay ? 'day' : (isHour ? 'hour' : 'minute');
return this.forTime<M>( start, start.asTime(), duration, durationUnit );
}
} | the_stack |
import ByteBuffer from "bytebuffer";
import { EventEmitter } from "events";
import { NetConnectOpts, Socket } from "net";
import { Transform, TransformCallback, Writable } from "stream";
import { unzip } from "zlib";
import { Coder } from "./coders";
import { PacketRegistryEntry, Side, PacketMetadata } from "./packet";
export type State = keyof States;
interface States {
handshake: PacketCoders;
login: PacketCoders;
status: PacketCoders;
play: PacketCoders;
}
/**
* The channel for send and listen the Minecraft packet.
*/
export class Channel extends EventEmitter {
state: State = "handshake";
private readonly states = {
client: {
handshake: new PacketCoders(),
login: new PacketCoders(),
status: new PacketCoders(),
play: new PacketCoders(),
},
server: {
handshake: new PacketCoders(),
login: new PacketCoders(),
status: new PacketCoders(),
play: new PacketCoders(),
},
};
private connection: Socket = new Socket({ allowHalfOpen: false });
private outbound: Writable;
private inbound: Writable;
private enableCompression: boolean = false;
private compressionThreshold: number = -1;
constructor() {
super();
const self = this;
this.outbound = new MinecraftPacketEncoder(this);
this.outbound.pipe(new MinecraftPacketOutbound()).pipe(this.connection);
this.inbound = new MinecraftPacketInBound();
this.inbound
.pipe(new PacketDecompress({
get enableCompression() {
return self.enableCompression;
},
get compressionThreshold() {
return self.compressionThreshold;
},
}))
.pipe(new MinecraftPacketDecoder(this))
.pipe(new PacketEmitter(this));
this.connection.pipe(this.inbound);
}
/**
* Is the connection ready to read and write
*/
get ready() {
return this.connection.readable && this.connection.writable;
}
findCoderById(packetId: number, side: Side): Coder<any> {
const all = this.states[side][this.state];
return all.packetIdCoders[packetId];
}
getPacketId(packetInst: any, side: Side): number {
const packetName = Object.getPrototypeOf(packetInst).constructor.name;
const all = this.states[side][this.state];
return all.packetNameToId[packetName];
}
registerPacketType(clazz: new (...args: any) => any) {
const entry: PacketRegistryEntry = clazz.prototype[PacketMetadata];
const { state, side, id, name, coder } = entry;
const coders = this.states[side][state];
coders.packetIdCoders[id] = coder;
coders.packetNameToId[name] = id;
}
registerPacket(entry: PacketRegistryEntry) {
const { state, side, id, name, coder } = entry;
const coders = this.states[side][state];
coders.packetIdCoders[id] = coder;
coders.packetNameToId[name] = id;
}
/**
* Open the connection and start to listen the port.
*/
async listen(option: NetConnectOpts & { keepalive?: boolean | number }) {
if (this.ready) {
this.connection.destroy();
}
await new Promise<void>((resolve, reject) => {
this.connection.connect(option, () => {
resolve();
});
if (option.timeout) {
this.connection.setTimeout(option.timeout);
}
if (option.keepalive) {
this.connection.setKeepAlive(true, typeof option.keepalive === "boolean" ? 3500 : option.keepalive);
}
this.connection.once("error", (e) => { reject(e); });
this.connection.once("timeout", () => { reject(new Error("Connection timeout.")); });
});
this.connection.on("error", (e) => { this.emit("error", e); });
this.emit("listen");
}
disconnect() {
if (!this.ready) {
return Promise.resolve();
}
return new Promise<void>((resolve, reject) => {
this.connection.once("close", (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
this.connection.end();
});
}
/**
* Sent a packet to server.
*/
send<T>(message: T, skeleton?: Partial<T>) {
if (!this.connection.writable) { throw new Error("Cannot write if the connection isn't writable!"); }
if (skeleton) { Object.assign(message, skeleton); }
this.outbound.write(message);
this.emit("send", message);
}
/**
* Listen for sepcific packet by its class name.
*/
onPacket<T>(packet: new (...args: any[]) => T, listener: (event: T) => void): this {
return this.on(`packet:${packet.name}`, listener);
}
oncePacket<T>(packet: new (...args: any[]) => T, listener: (event: T) => void): this {
return this.once(`packet:${packet.name}`, listener);
}
}
export interface Channel extends EventEmitter {
on<T>(channel: string, listener: (event: T) => void): this;
once<T>(channel: string, listener: (event: T) => void): this;
}
export abstract class PacketInBound extends Transform {
private buffer: ByteBuffer = ByteBuffer.allocate(1024);
protected abstract readPacketLength(bb: ByteBuffer): number
_transform(chunk: Buffer, encoding: string, callback: TransformCallback) {
this.buffer.ensureCapacity(chunk.length + this.buffer.offset);
this.buffer.append(chunk);
this.buffer.flip();
let unresolvedBytes;
do {
const packetLength = this.readPacketLength(this.buffer);
unresolvedBytes = this.buffer.remaining();
if (packetLength <= unresolvedBytes) {
const result = Buffer.alloc(packetLength);
this.buffer.buffer.copy(result, 0, this.buffer.offset, this.buffer.offset + packetLength);
this.push(result);
this.buffer.buffer.copyWithin(0, packetLength); // clear emitted bytes
this.buffer.offset = 0; // reset read offset to the front
this.buffer.limit -= packetLength; // reduce the limit by emitted bytes
unresolvedBytes -= packetLength;
} else {
this.buffer.offset = this.buffer.limit;
this.buffer.limit = this.buffer.capacity();
break;
}
} while (unresolvedBytes > 0);
callback();
}
}
class MinecraftPacketInBound extends PacketInBound {
protected readPacketLength(bb: ByteBuffer): number {
return bb.readVarint32();
}
}
class PacketDecompress extends Transform {
constructor(private option: { readonly enableCompression: boolean, readonly compressionThreshold: number }) {
super();
}
_transform(chunk: Buffer, encoding: string, callback: TransformCallback) {
if (!this.option.enableCompression) {
this.push(chunk);
callback();
return;
}
const message = ByteBuffer.wrap(chunk);
const dataLength = message.readVarint32();
if (dataLength === 0 || dataLength < this.option.compressionThreshold) {
this.push(message.buffer.slice(message.offset));
callback();
} else {
const compressedContent = message.buffer.slice(message.offset);
unzip(compressedContent, (err, result) => {
if (err) {
callback(err);
} else {
this.push(result);
callback();
}
});
}
}
}
export interface PacketRegistry {
findCoderById(packetId: number, side: "client" | "server"): Coder<any>
getPacketId(message: any, side: "client" | "server"): number
}
export abstract class PacketDecoder extends Transform {
constructor(private client: PacketRegistry) {
super({ writableObjectMode: true, readableObjectMode: true });
}
abstract readPacketId(message: ByteBuffer): number
_transform(chunk: Buffer, encoding: string, callback: TransformCallback) {
const message = ByteBuffer.wrap(chunk);
const packetId = this.readPacketId(message);
const packetContent = message.slice();
const coder = this.client.findCoderById(packetId, "server");
if (coder) {
this.push(coder.decode(packetContent));
} else {
console.error(`Unknown packet ${packetId} : ${packetContent.buffer}.`);
}
callback();
}
}
class MinecraftPacketDecoder extends PacketDecoder {
readPacketId(message: ByteBuffer): number {
return message.readVarint32();
}
}
export class PacketEmitter extends Writable {
constructor(private eventBus: EventEmitter) {
super({ objectMode: true });
}
_write(inst: any, encoding: string, callback: (error?: Error | null) => void): void {
this.eventBus.emit(`packet:${Object.getPrototypeOf(inst).constructor.name}`, inst);
callback();
}
}
export abstract class PacketEncoder extends Transform {
constructor(private client: PacketRegistry) {
super({ writableObjectMode: true, readableObjectMode: true });
}
protected abstract writePacketId(bb: ByteBuffer, id: number): void
_transform(message: any, encoding: string, callback: TransformCallback) {
const id = this.client.getPacketId(message, "client");
const coder = this.client.findCoderById(id, "client");
if (coder && coder.encode) {
const buf = new ByteBuffer();
this.writePacketId(buf, id);
coder.encode(buf, message, this.client);
buf.flip();
this.push(buf.buffer.slice(0, buf.limit));
callback();
} else {
callback(new Error(`Cannot find coder for message. ${JSON.stringify(message)}`));
}
}
}
class MinecraftPacketEncoder extends PacketEncoder {
protected writePacketId(bb: ByteBuffer, id: number): void {
bb.writeByte(id);
}
}
export abstract class PacketOutbound extends Transform {
protected abstract writePacketLength(bb: ByteBuffer, len: number): void
_transform(packet: Buffer, encoding: string, callback: TransformCallback) {
const buffer = new ByteBuffer();
this.writePacketLength(buffer, packet.length);
buffer.append(packet);
buffer.flip();
this.push(buffer.buffer.slice(0, buffer.limit));
callback();
}
}
class MinecraftPacketOutbound extends PacketOutbound {
protected writePacketLength(bb: ByteBuffer, len: number): void {
bb.writeVarint32(len);
}
}
class PacketCoders {
packetIdCoders: { [packetId: number]: Coder<any> } = {};
packetNameToId: { [name: string]: number } = {};
} | the_stack |
import Peer from 'simple-peer';
import {v4} from 'uuid';
import {memoize, throttle} from 'lodash';
import {promiseSleep} from './promiseSleep';
import {CommsNode, CommsNodeCallbacks, CommsNodeOptions, SendToOptions} from './commsNode';
import {closeMessage} from './peerMessageHandler';
interface ConnectedPeer {
peerId: string;
peer: Peer.Instance;
connected: number;
initiatedByMe: boolean;
errorCount: number;
linkReadUrl?: string;
linkWriteUrl?: string;
lastSignal: number;
}
export interface SimplePeerOffer {
sdp: string;
type: 'offer' | 'answer';
}
interface SignalMessage {
peerId: string;
userId: string;
offer?: SimplePeerOffer;
recipientId?: string;
}
/**
* A node in a peer-to-peer network. Uses gtove-relay-server to do signalling and webRTC (via simple-peer) for the actual
* communication. Builds a totally connected network topology - each node in the network has a direct peer-to-peer
* connection to each other node.
*/
export class PeerNode extends CommsNode {
static SIGNAL_URL = 'https://radiant-thicket-18054.herokuapp.com/mcast/';
// Relay messages via gtove-relay-server as a fallback for failed p2p (manually emulate TURN).
static RELAY_URL = 'https://radiant-thicket-18054.herokuapp.com/link/';
private requestOffersInterval: number;
private readonly signalChannelId: string;
private onEvents: CommsNodeCallbacks;
private connectedPeers: {[key: string]: ConnectedPeer};
private ignoredPeers: {[key: string]: boolean};
private readonly memoizedThrottle: (key: string, func: (...args: any[]) => any) => (...args: any[]) => any;
private sequenceId: number | null = null;
/**
* @param signalChannelId The unique string used to identify the multi-cast channel on gtove-relay-server. All
* PeerNodes with the same signalChannelId will signal each other and connect.
* @param userId A string uniquely identifying the owner of this node. A single user can own multiple nodes across
* the network.
* @param commsNodeOptions The options this node is initialised with
*/
constructor(signalChannelId: string, userId: string, commsNodeOptions: CommsNodeOptions) {
super();
this.signalChannelId = signalChannelId;
this.options = commsNodeOptions;
this.onEvents = commsNodeOptions.onEvents || {};
this.connectedPeers = {};
this.ignoredPeers = {};
this.peerId = v4();
this.userId = userId;
const throttleWait = commsNodeOptions.throttleWait || 250;
console.log(`Created peer-to-peer node for user ${this.userId} with id ${this.peerId}`);
// Create a memoized throttle function wrapper. Calls with the same (truthy) throttleKey will be throttled so
// the function is called at most once each throttleWait milliseconds. This is used to wrap the send function,
// so things like dragging minis doesn't flood the connection - since each position update supersedes the
// previous one, we don't need to send every intermediate value.
this.memoizedThrottle = memoize((throttleKey, func) => (throttle(func, throttleWait)));
this.sendToRaw = this.sendToRaw.bind(this);
}
async init(): Promise<void> {
// Request offers from anyone already online, then start listening.
await this.requestOffers();
this.startHeartbeat();
await this.listenForSignal();
}
private onSignalError(error: boolean) {
this.onEvents.signalError && this.onEvents.signalError(this, error ? 'Signal error' : '');
}
async getFromSignalServer(): Promise<SignalMessage> {
const response = await fetch(`${PeerNode.SIGNAL_URL}${this.signalChannelId}${this.sequenceId !== null ? `?sequenceId=${this.sequenceId}` : ''}`, {
cache: 'no-store'
});
if (response.ok) {
this.onSignalError(false);
this.sequenceId = Number(response.headers.get('x-relay-sequenceId'));
return response.json();
} else {
this.onSignalError(true);
throw new Error('invalid response from signal server: ' + JSON.stringify(response));
}
}
async postToSignalServer(body: SignalMessage) {
let success = true;
try {
const response = await fetch(`${PeerNode.SIGNAL_URL}${this.signalChannelId}`, {
method: 'POST',
body: JSON.stringify(body)
});
success = response.ok;
} catch (e) {
success = false;
}
this.onSignalError(!success);
if (!success) {
await promiseSleep(5000);
await this.postToSignalServer(body);
}
}
/**
* Handles a single signal from the signalling server.
*
* Signals are of the form {peerId} or {peerId, offer, recipientId}. The first form is a broadcast "I'm
* online, please talk to me" message. The second form is a handshake between peers.
* * "peerId" is the id of the sender of the message.
* * "offer" is a webRTC offer. If omitted, the peer is signalling us that they want to fall back to a relay.
* * "recipientId" is the peerId to whom the offer is being made.
* @param signal
*/
async handleSignal(signal: SignalMessage) {
if (this.shutdown || !signal.peerId) {
// Ignore signals if shut down, or those without a peerId (caused by a timeout).
return;
}
if (signal.peerId !== this.peerId && !this.ignoredPeers[signal.peerId]) {
// Signal from another peer (we need to check because we also see our own signals come back).
if (!this.connectedPeers[signal.peerId]) {
// A node I don't know about is out there. It might be requesting offers (recipientId undefined),
// talking with another peer (recipientId !== my peerId) or making an offer specifically to me
// (recipientId === my peerId).
if (!this.onEvents.shouldConnect || this.onEvents.shouldConnect(this, signal.peerId, signal.userId)) {
// Make an offer to them, initiating the connection unless they've made me an offer.
this.addPeer(signal.peerId, signal.recipientId !== this.peerId);
} else {
// We're going to ignore this peer.
this.ignoredPeers[signal.peerId] = true;
}
}
}
if (this.connectedPeers[signal.peerId]) {
// Update the last signal timestamp for the peer, so they aren't timed out.
this.connectedPeers[signal.peerId].lastSignal = Date.now();
}
if (signal.recipientId === this.peerId) {
// Received a message addressed to our peer
if (this.ignoredPeers[signal.peerId]) {
// This is unexpected - received comms directly from an ignored peer
console.error(`Received a message addressed to me from ignored peer ${signal.userId}/${signal.peerId}`);
} else if (this.connectedPeers[signal.peerId].connected) {
// This is unexpected - we think we're connected, but the peer is still trying to handshake with us.
if (signal.offer && signal.offer.type === 'offer') {
// They're trying to (re-)initiate the connection.
if (this.connectedPeers[signal.peerId].linkReadUrl || Date.now() - this.connectedPeers[signal.peerId].connected < 3000) {
// If we've fallen back on the TURN server, ignore the offer. Also, they might have spammed a
// few offers in a row before we accepted - ignore if connection was only a few seconds ago.
return;
}
// Otherwise, try to accept their offer.
console.warn(`Re-initiating connection with ${signal.peerId}.`);
this.connectedPeers[signal.peerId].peer && this.connectedPeers[signal.peerId].peer.destroy();
this.addPeer(signal.peerId, false);
this.connectedPeers[signal.peerId].peer.signal(signal.offer);
} else if (!signal.offer) {
if (this.connectedPeers[signal.peerId].linkReadUrl) {
// We're already connected via the TURN server.
return;
}
// They're telling us to switch to the relay even though we thought we'd connected P2P.
console.warn(`Changing already-established connection with ${signal.peerId} to relay.`);
this.connectViaRelay(signal.peerId, false);
} else {
if (Date.now() - this.connectedPeers[signal.peerId].connected < 3000) {
// They might have spammed a few answers in a row before we accepted - ignore if connection was
// only a few seconds ago.
return;
}
console.warn(`Received unexpected answer to our offer from ${signal.peerId}`);
}
} else {
// Received an offer from a peer we're not yet connected with.
if (!signal.offer) {
// They've decided to fall back to using the relay server, so switch to that channel.
await this.connectViaRelay(signal.peerId, false);
} else {
if (this.connectedPeers[signal.peerId].initiatedByMe && signal.offer.type === 'offer') {
// Both ends attempted to initiate the connection. Break the tie by treating the
// lexicographically earlier peerId as the initiator.
if (this.peerId > signal.peerId) {
// Start over as the non-initial peer, and reply to the other peer's initial offer.
this.connectedPeers[signal.peerId].peer && this.connectedPeers[signal.peerId].peer.destroy();
this.addPeer(signal.peerId, false);
} else {
// Assume they will start over and reply to our initial offer.
return;
}
}
// Accept the offer.
this.connectedPeers[signal.peerId].peer.signal(signal.offer);
}
}
}
}
/**
* Listens for a message from the signalling server, gtove-relay-server. Signals are used to establish connections
* between webRTC peers.
*/
async listenForSignal(): Promise<void> {
while (!this.shutdown) {
try {
const signal = await this.getFromSignalServer();
await this.handleSignal(signal);
} catch (err) {
console.error(err);
await promiseSleep(5000);
}
}
}
async requestOffers() {
await this.postToSignalServer({peerId: this.peerId, userId: this.userId});
}
startHeartbeat() {
if (!this.requestOffersInterval) {
this.requestOffersInterval =
window.setInterval(this.heartbeat.bind(this), CommsNode.HEARTBEAT_INTERVAL_MS);
}
}
async heartbeat() {
// Periodically invite offers, which also lets connected peers know I'm still active.
await this.requestOffers();
// Check if any peers have failed to signal for a while.
const timeout = Date.now() - 2 * CommsNode.HEARTBEAT_INTERVAL_MS;
for (let peerId of Object.keys(this.connectedPeers)) {
if (this.connectedPeers[peerId].lastSignal < timeout) {
// peer is idle - time it out.
console.warn(`Peer ${peerId} sent last signal ${(Date.now() - this.connectedPeers[peerId].lastSignal)/1000} seconds ago - destroying it.`);
this.destroyPeer(peerId);
}
}
}
async sendOffer(peerId: string, offer: SimplePeerOffer): Promise<void> {
await this.postToSignalServer({peerId: this.peerId, userId: this.userId, offer, recipientId: peerId});
await promiseSleep(5000);
if (this.connectedPeers[peerId] && this.connectedPeers[peerId].connected) {
// We're connected!
return;
}
if (this.connectedPeers[peerId]) {
// Give up on establishing a peer-to-peer connection, fall back on relay.
this.connectViaRelay(peerId, offer.type === 'offer');
}
}
private async connectViaRelay(peerId: string, initiator: boolean): Promise<void> {
console.log(`Failed to connect peer-to-peer with ${peerId}, falling back to relay.`);
this.connectedPeers[peerId] = {
peerId,
peer: this.connectedPeers[peerId] && this.connectedPeers[peerId].peer,
connected: Date.now(),
initiatedByMe: initiator,
lastSignal: Date.now(),
linkReadUrl: PeerNode.RELAY_URL + `${this.peerId}-${peerId}`,
linkWriteUrl: PeerNode.RELAY_URL + `${peerId}-${this.peerId}`,
errorCount: 0
};
// Do not wait for listenForRelayTraffic, it doesn't resolve until this node shuts down.
this.listenForRelayTraffic(peerId);
if (initiator) {
await this.postToSignalServer({peerId: this.peerId, userId: this.userId, recipientId: peerId});
}
this.connectedPeers[peerId].peer.emit('connect');
}
async listenForRelayTraffic(peerId: string) {
while (!this.shutdown && this.connectedPeers[peerId]) {
try {
const response = await fetch(this.connectedPeers[peerId].linkReadUrl!, {cache: 'no-store'});
if (response.ok) {
const message = await response.json();
this.connectedPeers[peerId].peer.emit(message.type, message.message);
} else {
this.connectedPeers[peerId].peer.emit('error', response);
}
} catch (e) {
if (this.connectedPeers[peerId] && this.connectedPeers[peerId].peer) {
this.connectedPeers[peerId].peer.emit('error', e);
}
}
}
}
addPeer(peerId: string, initiator: boolean) {
const peer: Peer.Instance = new Peer({initiator, trickle: false});
peer.on('signal', (offer) => (this.onSignal(peerId, offer)));
peer.on('error', (error) => (this.onError(peerId, error)));
peer.on('close', () => (this.onClose(peerId)));
peer.on('connect', () => (this.onConnect(peerId)));
Object.keys(this.onEvents).forEach((event) => {
peer.on(event, (...args) => this.onEvents[event](this, peerId, ...args));
});
this.connectedPeers[peerId] = {peerId, peer, connected: 0, initiatedByMe: initiator, errorCount: 0, lastSignal: Date.now()};
}
async onSignal(peerId: string, offer: any): Promise<void> {
if (!this.connectedPeers[peerId].linkReadUrl) {
await this.sendOffer(peerId, offer);
}
}
onError(peerId: string, error: Error) {
console.error('Error from', peerId, error);
delete(this.connectedPeers[peerId]);
}
onClose(peerId: string) {
console.log('Lost connection with', peerId);
delete(this.connectedPeers[peerId]);
}
onConnect(peerId: string) {
console.log('Established connection with', peerId);
this.connectedPeers[peerId].connected = Date.now();
}
private async sendDataViaP2POrRelay(peerId: string, message: string) {
try {
if (this.connectedPeers[peerId].linkWriteUrl) {
await fetch(this.connectedPeers[peerId].linkWriteUrl!, {
method: 'POST',
body: JSON.stringify({type: 'data', message})
});
} else {
this.connectedPeers[peerId].peer.send(message);
}
this.connectedPeers[peerId].errorCount = 0;
} catch (e) {
if (this.connectedPeers[peerId]) {
this.connectedPeers[peerId].errorCount++;
const consecutive = this.connectedPeers[peerId].errorCount === 1 ? '' : ` (${this.connectedPeers[peerId].errorCount} consecutive errors)`;
console.error(`Error sending to peer ${peerId}${consecutive}:`, e);
if (this.connectedPeers[peerId].errorCount > 10) {
// Give up on this peer
console.error(`Too many errors, giving up on peer ${peerId}`);
this.destroyPeer(peerId);
}
}
}
}
destroyPeer(peerId: string) {
console.log(`Destroying connection with peer ${peerId}.`);
if (this.connectedPeers[peerId]) {
if (this.connectedPeers[peerId].linkWriteUrl) {
// Don't wait for fetch to resolve.
fetch(this.connectedPeers[peerId].linkWriteUrl!, {
method: 'POST',
body: JSON.stringify({type: 'close'})
});
if (this.connectedPeers[peerId].peer) {
this.connectedPeers[peerId].peer.emit('close');
} else {
this.onEvents.close && this.onEvents.close(this, peerId);
}
} else if (!this.connectedPeers[peerId].connected) {
if (this.connectedPeers[peerId].peer) {
this.connectedPeers[peerId].peer.emit('close');
} else {
this.onEvents.close && this.onEvents.close(this, peerId);
}
} else {
if (this.connectedPeers[peerId].peer) {
this.connectedPeers[peerId].peer.destroy();
} else {
this.onEvents.close && this.onEvents.close(this, peerId);
}
}
delete(this.connectedPeers[peerId]);
}
}
private async sendToRaw(message: string | object, recipients: string[], onSentMessage?: (recipients: string[], message: string | object) => void) {
// JSON has no "undefined" value, so if JSON-stringifying, convert undefined values to null.
const stringMessage: string = (typeof(message) === 'object') ?
JSON.stringify(message, (k, v) => (v === undefined ? null : v)) : message;
for (let peerId of recipients) {
if (this.connectedPeers[peerId] && this.connectedPeers[peerId].connected) {
await this.sendDataViaP2POrRelay(peerId, stringMessage);
} else {
// Keep trying until peerId connects, or the connection is removed.
const intervalId = window.setInterval(async () => {
if (this.connectedPeers[peerId]) {
if (this.connectedPeers[peerId].connected) {
await this.sendDataViaP2POrRelay(peerId, stringMessage);
} else {
return; // Keep trying
}
}
// Either peer has been removed or we've managed to send the message - stop interval loop.
window.clearInterval(intervalId);
}, 250);
}
}
onSentMessage && onSentMessage(recipients, message);
}
/**
* Send a message to peers on the network.
*
* @param message The message to send. If it is an object, it will be JSON.stringified.
* @param only (optional) Array of peerIds to receive the message. If omitted, sends the message to all connected
* peers (except any listed in except)
* @param except (optional) Array of peerIds who should not receive the message.
* @param throttleKey (optional) If specified, messages with the same throttleKey are throttled so only one message
* is actually sent every throttleWait milliseconds - calling sendTo more frequently than that will discard
* messages. The last message is always delivered. Only use this for sending messages which supersede previous
* messages with the same throttleKey value, such as updating an object's position using absolute coordinates.
* @param onSentMessage (optional) Function that will be called after messages have been sent, with the list of
* peerId recipients provided as the parameter.
*/
async sendTo(message: string | object, {only, except, throttleKey, onSentMessage}: SendToOptions = {}) {
const recipients = (only || Object.keys(this.connectedPeers))
.filter((peerId) => (!except || except.indexOf(peerId) < 0));
if (throttleKey) {
await this.memoizedThrottle(throttleKey, this.sendToRaw)(message, recipients, onSentMessage);
} else {
await this.sendToRaw(message, recipients, onSentMessage);
}
}
async disconnectAll() {
Object.keys(this.connectedPeers).forEach((peerId) => (this.destroyPeer(peerId)));
this.connectedPeers = {};
}
async destroy() {
console.log('Shutting down peer-to-peer node', this.peerId);
this.shutdown = true;
window.clearInterval(this.requestOffersInterval);
await this.disconnectAll();
}
async close(peerId: string, reason?: string) {
if (this.connectedPeers[peerId]) {
if (reason) {
await this.sendToRaw(closeMessage(reason), [peerId]);
}
this.destroyPeer(peerId);
}
}
} | the_stack |
import { expect } from "chai";
import { describe } from "razmin";
import { BitstreamReader } from "../bitstream";
import { BitstreamElement } from "./element";
import { Field } from "./field";
describe('BitstreamElement', it => {
it('correctly deserializes a basic element in synchronous mode', async () => {
class ExampleElement extends BitstreamElement {
@Field(2) a;
@Field(3) b;
@Field(4) c;
@Field(5) d;
@Field(6) e;
}
// |-|--|---|----|-----X-----
let value = 0b10010110101011000010000000000000;
let buffer = Buffer.alloc(4);
buffer.writeUInt32BE(value);
let bitstream = new BitstreamReader();
bitstream.addBuffer(buffer);
let element = await ExampleElement.readBlocking(bitstream);
expect(element.a).to.equal(0b10);
expect(element.b).to.equal(0b010);
expect(element.c).to.equal(0b1101);
expect(element.d).to.equal(0b01011);
expect(element.e).to.equal(0b000010);
});
it('correctly deserializes nested elements', async () => {
class PartElement extends BitstreamElement {
@Field(3) c;
@Field(4) d;
}
class WholeElement extends BitstreamElement {
@Field(1) a;
@Field(2) b;
@Field(0) part : PartElement;
@Field(5) e;
@Field(6) f;
}
// ||-|--|---|----|-----X-----
let value = 0b11010110101011000010100000000000;
let buffer = Buffer.alloc(4);
buffer.writeUInt32BE(value);
let bitstream = new BitstreamReader();
bitstream.addBuffer(buffer);
let element = await WholeElement.readBlocking(bitstream);
expect(element.a) .to.equal(0b1);
expect(element.b) .to.equal(0b10);
expect(element.part.c) .to.equal(0b101);
expect(element.part.d) .to.equal(0b1010);
expect(element.e) .to.equal(0b10110);
expect(element.f) .to.equal(0b000101);
});
it('correctly deserializes inherited fields', async () => {
class BaseElement extends BitstreamElement {
@Field(1) a;
@Field(2) b;
}
class ExtendedElement extends BaseElement {
@Field(3) c;
@Field(4) d;
@Field(5) e;
@Field(6) f;
}
// ||-|--|---|----|-----X-----
let value = 0b11010110101011000010100000000000;
let buffer = Buffer.alloc(4);
buffer.writeUInt32BE(value);
let bitstream = new BitstreamReader();
bitstream.addBuffer(buffer);
let element = await ExtendedElement.readBlocking(bitstream);
expect(element.a).to.equal(0b1);
expect(element.b).to.equal(0b10);
expect(element.c).to.equal(0b101);
expect(element.d).to.equal(0b1010);
expect(element.e).to.equal(0b10110);
expect(element.f).to.equal(0b000101);
});
it('understands Buffer when length is a multiple of 8', async () => {
class CustomElement extends BitstreamElement {
@Field(4) a;
@Field(4) b;
@Field(16) c : Buffer;
}
// |---|---|---------------X
let value = 0b11010110101011000010100000000000;
let buffer = Buffer.alloc(4);
buffer.writeUInt32BE(value);
let bitstream = new BitstreamReader();
bitstream.addBuffer(buffer);
let element = await CustomElement.readBlocking(bitstream);
expect(element.a).to.equal(0b1101);
expect(element.b).to.equal(0b0110);
expect(element.c.length).to.equal(2);
expect(element.c[0]).to.equal(0b10101100);
expect(element.c[1]).to.equal(0b00101000);
});
it('fails when Buffer field has non multiple-of-8 length', () => {
let caught : Error;
try {
class CustomElement extends BitstreamElement {
@Field(4) a;
@Field(4) b;
@Field(7) c : Buffer;
}
} catch (e) {
caught = e;
}
expect(caught, 'should have thrown an error').to.exist;
});
it('understands strings', async () => {
class CustomElement extends BitstreamElement {
@Field(4) a;
@Field(4) b;
@Field(5) c : string;
}
let bitstream = new BitstreamReader();
bitstream.addBuffer(Buffer.from([ 0b11010110 ]));
bitstream.addBuffer(Buffer.from('hello', 'utf-8'));
let element = await CustomElement.readBlocking(bitstream);
expect(element.a).to.equal(0b1101);
expect(element.b).to.equal(0b0110);
expect(element.c).to.equal('hello');
});
it('understands discriminants', async () => {
class CustomElement extends BitstreamElement {
@Field(8) charCount;
@Field(i => i.charCount) str : string;
@Field(8) afterwards;
}
let bitstream = new BitstreamReader();
bitstream.addBuffer(Buffer.from([ 5 ]));
bitstream.addBuffer(Buffer.from('hello', 'utf-8'));
bitstream.addBuffer(Buffer.from([ 123 ]));
let element = await CustomElement.readBlocking(bitstream);
expect(element.charCount).to.equal(5);
expect(element.str).to.equal('hello');
expect(element.afterwards).to.equal(123);
});
it('should throw when result of a length discriminant is undefined', async () => {
let caught;
class CustomElement extends BitstreamElement {
@Field(8) charCount;
@Field(i => i.whoopsDoesntExist) str : string;
@Field(8) afterwards;
}
let bitstream = new BitstreamReader();
bitstream.addBuffer(Buffer.from([ 5 ]));
bitstream.addBuffer(Buffer.from('hello', 'utf-8'));
bitstream.addBuffer(Buffer.from([ 123 ]));
try {
await CustomElement.readBlocking(bitstream);
} catch (e) {
caught = e;
}
expect(caught).to.exist;
});
it('should throw when result of a length discriminant is not a number', async () => {
let caught;
class CustomElement extends BitstreamElement {
@Field(8) charCount;
@Field(i => <any>'foo') str : string;
@Field(8) afterwards;
}
let bitstream = new BitstreamReader();
bitstream.addBuffer(Buffer.from([ 5 ]));
bitstream.addBuffer(Buffer.from('hello', 'utf-8'));
bitstream.addBuffer(Buffer.from([ 123 ]));
try {
await CustomElement.readBlocking(bitstream);
} catch (e) {
caught = e;
}
expect(caught).to.exist;
});
it('should understand arrays', async () => {
class ItemElement extends BitstreamElement {
@Field(8) a;
@Field(8) b;
}
class CustomElement extends BitstreamElement {
@Field(8) before;
@Field(0, { array: { type: ItemElement, countFieldLength: 8 } }) items : ItemElement[];
@Field(8) afterwards;
}
let bitstream = new BitstreamReader();
bitstream.addBuffer(Buffer.from([ 123, 3, 1, 2, 11, 12, 21, 22, 123 ]));
let element = await CustomElement.readBlocking(bitstream);
expect(element.before).to.equal(123);
expect(element.items.length).to.equal(3);
expect(element.items[0].a).to.equal(1);
expect(element.items[0].b).to.equal(2);
expect(element.items[1].a).to.equal(11);
expect(element.items[1].b).to.equal(12);
expect(element.items[2].a).to.equal(21);
expect(element.items[2].b).to.equal(22);
expect(element.afterwards).to.equal(123);
});
it('should understand arrays of numbers', async () => {
class CustomElement extends BitstreamElement {
@Field(8) before;
@Field(0, { array: { type: Number, countFieldLength: 8, elementLength: 10 } }) items : number[];
}
let bitstream = new BitstreamReader();
bitstream.addBuffer(Buffer.from([ 123, 3, 0b10011001, 0b10100110, 0b01011011, 0b00111010, 0b10111001 ]));
let element = await CustomElement.readBlocking(bitstream);
expect(element.before).to.equal(123);
expect(element.items.length).to.equal(3);
expect(element.items[0]).to.equal(0b1001100110);
expect(element.items[1]).to.equal(0b1001100101);
expect(element.items[2]).to.equal(0b1011001110);
});
it('should understand a static count determinant', async () => {
class CustomElement extends BitstreamElement {
@Field(8) before;
@Field(0, { array: { type: Number, count: 3, elementLength: 10 } }) items : number[];
}
let bitstream = new BitstreamReader();
bitstream.addBuffer(Buffer.from([ 123, 0b10011001, 0b10100110, 0b01011011, 0b00111010, 0b10111001 ]));
let element = await CustomElement.readBlocking(bitstream);
expect(element.before).to.equal(123);
expect(element.items.length).to.equal(3);
expect(element.items[0]).to.equal(0b1001100110);
expect(element.items[1]).to.equal(0b1001100101);
expect(element.items[2]).to.equal(0b1011001110);
});
it('should understand a dynamic count determinant', async () => {
class CustomElement extends BitstreamElement {
@Field(8) count;
@Field(8) before;
@Field(0, { array: { type: Number, count: i => i.count, elementLength: 10 } }) items : number[];
}
let bitstream = new BitstreamReader();
bitstream.addBuffer(Buffer.from([ 3, 123, 0b10011001, 0b10100110, 0b01011011, 0b00111010, 0b10111001 ]));
let element = await CustomElement.readBlocking(bitstream);
expect(element.before).to.equal(123);
expect(element.items.length).to.equal(3);
expect(element.items[0]).to.equal(0b1001100110);
expect(element.items[1]).to.equal(0b1001100101);
expect(element.items[2]).to.equal(0b1011001110);
});
it('should throw when array is used without specifying type', () => {
let caught;
try {
class CustomElement extends BitstreamElement {
@Field(8) before;
@Field(0, { array: { countFieldLength: 8 } }) items : any[];
@Field(8) afterwards;
}
} catch (e) {
caught = e;
}
expect(caught).to.exist;
});
}) | the_stack |
import { faCalculator, faCheckSquare, faSquare } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { Close } from '@mui/icons-material';
import { Alert, Box, Button, ButtonGroup, CardContent, Divider, Grid, Link, MenuItem, Skeleton, Typography } from '@mui/material';
import React, { lazy, Suspense, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import ReactGA from 'react-ga';
import { Link as RouterLink } from 'react-router-dom';
// eslint-disable-next-line
import Worker from "worker-loader!./BuildWorker";
import Artifact from '../Artifact/Artifact';
import { ArtifactSheet } from '../Artifact/ArtifactSheet';
import Character from '../Character/Character';
import CharacterSheet from '../Character/CharacterSheet';
import CardDark from '../Components/Card/CardDark';
import CardLight from '../Components/Card/CardLight';
import CharacterDropdownButton from '../Components/Character/CharacterDropdownButton';
import CloseButton from '../Components/CloseButton';
import DropdownButton from '../Components/DropdownMenu/DropdownButton';
import InfoComponent from '../Components/InfoComponent';
import ModalWrapper from '../Components/ModalWrapper';
import { DatabaseContext } from '../Database/Database';
import { dbStorage } from '../Database/DBStorage';
import useForceUpdate from '../ReactHooks/useForceUpdate';
import usePromise from '../ReactHooks/usePromise';
import { ArtifactsBySlot, Build, BuildSetting } from '../Types/Build';
import { ICachedCharacter } from '../Types/character';
import { allSlotKeys, CharacterKey } from '../Types/consts';
import { ICalculatedStats } from '../Types/stats';
import { deepClone, objectFromKeyMap } from '../Util/Util';
import WeaponSheet from '../Weapon/WeaponSheet';
import { buildContext, calculateTotalBuildNumber, maxBuildsToShowList } from './Build';
import { initialBuildSettings } from './BuildSetting';
import ArtifactBuildDisplayItem from './Components/ArtifactBuildDisplayItem';
import ArtifactConditionalCard from './Components/ArtifactConditionalCard';
import ArtifactSetPicker from './Components/ArtifactSetPicker';
import BonusStatsCard from './Components/BonusStatsCard';
import BuildAlert, { warningBuildNumber } from './Components/BuildAlert';
import CharacterSelectionCard from './Components/CharacterSelectionCard';
import EnemyEditorCard from './Components/EnemyEditorCard';
import HitModeCard from './Components/HitModeCard';
import MainStatSelectionCard, { artifactsSlotsToSelectMainStats } from './Components/MainStatSelectionCard';
import OptimizationTargetSelector from './Components/OptimizationTargetSelector';
import StatFilterCard from './Components/StatFilterCard';
const InfoDisplay = React.lazy(() => import('./InfoDisplay'));
//lazy load the character display
const CharacterDisplayCard = lazy(() => import('../Character/CharacterDisplayCard'))
function buildSettingsReducer(state: BuildSetting, action): BuildSetting {
switch (action.type) {
case 'mainStatKey': {
const { slotKey, mainStatKey } = action
const mainStatKeys = { ...state.mainStatKeys }//create a new object to update react dependencies
if (state.mainStatKeys[slotKey].includes(mainStatKey))
mainStatKeys[slotKey] = mainStatKeys[slotKey].filter(k => k !== mainStatKey)
else
mainStatKeys[slotKey].push(mainStatKey)
return { ...state, mainStatKeys }
}
case 'mainStatKeyReset': {
const { slotKey } = action
const mainStatKeys = { ...state.mainStatKeys }//create a new object to update react dependencies
mainStatKeys[slotKey] = []
return { ...state, mainStatKeys }
}
case `setFilter`: {
const { index, key, num = 0 } = action
state.setFilters[index] = { key, num }
return { ...state, setFilters: [...state.setFilters] }//do this because this is a dependency, so needs to be a "new" array
}
default:
break;
}
return { ...state, ...action }
}
export default function BuildDisplay({ location: { characterKey: propCharacterKey } }) {
const database = useContext(DatabaseContext)
const [characterKey, setcharacterKey] = useState(() => {
const { characterKey = "" } = dbStorage.get("BuildsDisplay.state") ?? {}
//NOTE that propCharacterKey can override the selected character.
return (propCharacterKey ?? characterKey) as CharacterKey | ""
})
const [modalBuild, setmodalBuild] = useState(-1) // the index of the newBuild that is being displayed in the character modal,
const [showCharacterModal, setshowCharacterModal] = useState(false)
const [generatingBuilds, setgeneratingBuilds] = useState(false)
const [generationProgress, setgenerationProgress] = useState(0)
const [generationDuration, setgenerationDuration] = useState(0)//in ms
const [generationSkipped, setgenerationSkipped] = useState(0)
const [charDirty, setCharDirty] = useForceUpdate()
const artifactSheets = usePromise(ArtifactSheet.getAll(), [])
const [artsDirty, setArtsDirty] = useForceUpdate()
const isMounted = useRef(false)
const worker = useRef(null as Worker | null)
type characterDataType = { character?: ICachedCharacter, characterSheet?: CharacterSheet, weaponSheet?: WeaponSheet, initialStats?: ICalculatedStats, statsDisplayKeys?: { basicKeys: any, [key: string]: any } }
const [{ character, characterSheet, weaponSheet, initialStats, statsDisplayKeys }, setCharacterData] = useState({} as characterDataType)
const buildSettings = useMemo(() => character?.buildSettings ?? initialBuildSettings(), [character])
const { setFilters, statFilters, mainStatKeys, optimizationTarget, mainStatAssumptionLevel, useExcludedArts, useEquippedArts, builds, buildDate, maxBuildsToShow } = buildSettings
if (initialStats)
initialStats.mainStatAssumptionLevel = mainStatAssumptionLevel
const buildStats = useMemo(() => {
if (!initialStats || !artifactSheets) return []
return builds.map(build => {
const arts = Object.fromEntries(build.map(id => database._getArt(id)).map(art => [art?.slotKey, art]))
return Character.calculateBuildwithArtifact(initialStats, arts, artifactSheets)
}).filter(build => build)
}, [builds, database, initialStats, artifactSheets])
const noCharacter = useMemo(() => !database._getCharKeys().length, [database])
const noArtifact = useMemo(() => !database._getArts().length, [database])
const buildSettingsDispatch = useCallback((action) => {
if (!character) return
character.buildSettings = buildSettingsReducer(buildSettings, action)
database.updateChar(character)
}, [character, buildSettings, database])
useEffect(() => ReactGA.pageview('/build'), [])
//select a new character Key
const selectCharacter = useCallback((cKey = "") => {
if (characterKey === cKey) return
setcharacterKey(cKey)
setCharDirty()
setCharacterData({})
}, [setCharDirty, setcharacterKey, characterKey])
//load the character data as a whole
useEffect(() => {
(async () => {
if (!characterKey || !artifactSheets) return
const character = database._getChar(characterKey)
if (!character) return selectCharacter("")// character is prob deleted.
const characterSheet = await CharacterSheet.get(characterKey)
const weapon = database._getWeapon(character.equippedWeapon)
if (!weapon) return
const weaponSheet = await WeaponSheet.get(weapon.key)
if (!characterSheet || !weaponSheet) return
const initialStats = Character.createInitialStats(character, database, characterSheet, weaponSheet)
//NOTE: since initialStats are used, there are no inclusion of artifact formulas here.
const statsDisplayKeys = Character.getDisplayStatKeys(initialStats, { characterSheet, weaponSheet, artifactSheets })
setCharacterData({ character, characterSheet, weaponSheet, initialStats, statsDisplayKeys })
})()
}, [charDirty, characterKey, artifactSheets, database, selectCharacter])
//register changes in artifact database
useEffect(() =>
database.followAnyArt(setArtsDirty),
[setArtsDirty, database])
//register changes in character in db
useEffect(() =>
characterKey ? database.followChar(characterKey, setCharDirty) : undefined,
[characterKey, setCharDirty, database])
//terminate worker when component unmounts
useEffect(() => () => worker.current?.terminate(), [])
//save to BuildsDisplay.state on change
useEffect(() => {
if (isMounted.current) dbStorage.set("BuildsDisplay.state", { characterKey })
else isMounted.current = true
}, [characterKey])
//validate optimizationTarget
useEffect(() => {
if (!statsDisplayKeys) return
if (!Array.isArray(optimizationTarget)) return
for (const sectionKey in statsDisplayKeys) {
const section = statsDisplayKeys[sectionKey]
for (const keys of section)
if (JSON.stringify(keys) === JSON.stringify(optimizationTarget)) return
}
buildSettingsDispatch({ optimizationTarget: initialBuildSettings().optimizationTarget })
}, [optimizationTarget, statsDisplayKeys, buildSettingsDispatch])
const { split, totBuildNumber } = useMemo(() => {
if (!characterKey) // Make sure we have all slotKeys
return { split: objectFromKeyMap(allSlotKeys, () => []) as ArtifactsBySlot, totBuildNumber: 0 }
const artifactDatabase = database._getArts().filter(art => {
//if its equipped on the selected character, bypass the check
if (art.location === characterKey) return true
if (art.exclude && !useExcludedArts) return false
if (art.location && !useEquippedArts) return false
return true
})
const split = Artifact.splitArtifactsBySlot(artifactDatabase);
//filter the split slots on the mainstats selected.
artifactsSlotsToSelectMainStats.forEach(slotKey =>
mainStatKeys[slotKey].length && (split[slotKey] = split[slotKey]?.filter((art) => mainStatKeys[slotKey].includes(art.mainStatKey))))
const totBuildNumber = calculateTotalBuildNumber(split, setFilters)
return artsDirty && { split, totBuildNumber }
}, [characterKey, useExcludedArts, useEquippedArts, mainStatKeys, setFilters, artsDirty, database])
//reset the Alert by setting progress to zero.
useEffect(() => {
setgenerationProgress(0)
}, [totBuildNumber])
const generateBuilds = useCallback(() => {
if (!initialStats || !artifactSheets) return
setgeneratingBuilds(true)
setgenerationDuration(0)
setgenerationProgress(0)
setgenerationSkipped(0)
//get the formula for this target
const artifactSetEffects = Artifact.setEffectsObjs(artifactSheets, initialStats)
const splitArtifacts = deepClone(split) as ArtifactsBySlot
//add mainStatVal to each artifact
Object.values(splitArtifacts).forEach(artArr => {
artArr!.forEach(art => {
art.mainStatVal = Artifact.mainStatValue(art.mainStatKey, art.rarity, Math.max(Math.min(mainStatAssumptionLevel, art.rarity * 4), art.level)) ?? 0;
})
})
//create an obj with app the artifact set effects to pass to buildworker.
const data = {
splitArtifacts, initialStats, artifactSetEffects,
setFilters, minFilters: statFilters, maxBuildsToShow, optimizationTarget
};
worker.current?.terminate()
worker.current = new Worker()
worker.current.onmessage = (e) => {
if (typeof e.data.progress === "number") {
const { progress, timing = 0, skipped = 0 } = e.data
setgenerationProgress(progress)
setgenerationDuration(timing)
setgenerationSkipped(skipped)
return
}
ReactGA.timing({
category: "Build Generation",
variable: "timing",
value: e.data.timing,
label: totBuildNumber.toString()
})
const builds = (e.data.builds as Build[]).map(b => Object.values(b.artifacts).map(a => a.id))
buildSettingsDispatch({ builds, buildDate: Date.now() })
setgeneratingBuilds(false)
worker.current?.terminate()
worker.current = null
};
worker.current.postMessage(data)
}, [artifactSheets, split, totBuildNumber, mainStatAssumptionLevel, initialStats, maxBuildsToShow, optimizationTarget, setFilters, statFilters, buildSettingsDispatch])
const characterName = characterSheet?.name ?? "Character Name"
const closeBuildModal = useCallback(
() => {
setmodalBuild(-1)
setshowCharacterModal(false)
},
[setmodalBuild, setshowCharacterModal],
)
return <buildContext.Provider value={{ equippedBuild: initialStats }}>
<Box display="flex" flexDirection="column" gap={1} sx={{ my: 1 }}>
<InfoComponent
pageKey="buildPage"
modalTitle="Character Management Page Guide"
text={["For self-infused attacks, like Noelle's Sweeping Time, enable the skill in the character talent page.",
"You can compare the difference between equipped artifacts and generated builds.",
"The more complex the formula, the longer the generation time.",]}
><InfoDisplay /></InfoComponent>
<BuildModal {...{ build: buildStats[modalBuild], showCharacterModal, characterKey, selectCharacter, onClose: closeBuildModal }} />
{noCharacter && <Alert severity="error" variant="filled"> Opps! It looks like you haven't added a character to GO yet! You should go to the <Link component={RouterLink} to="/character">Characters</Link> page and add some!</Alert>}
{noArtifact && <Alert severity="warning" variant="filled"> Opps! It looks like you haven't added any artifacts to GO yet! You should go to the <Link component={RouterLink} to="/artifact">Artifacts</Link> page and add some!</Alert>}
{/* Build Generator Editor */}
<CardDark>
<CardContent sx={{ py: 1 }}>
<Typography variant="h6">Build Generator</Typography>
</CardContent>
<Divider />
<CardContent>
<Grid container spacing={1} >
{/* Left half */}
<Grid item xs={12} md={6} lg={5} sx={{
// select all excluding last
"> div:nth-last-of-type(n+2)": { mb: 1 }
}}>
<CardLight>
<CardContent>
<CharacterDropdownButton fullWidth value={characterKey} onChange={selectCharacter} disabled={generatingBuilds} />
</CardContent>
</CardLight>
{/* character selection */}
<CharacterSelectionCard characterKey={characterKey} disabled={generatingBuilds} selectCharacter={selectCharacter} />
{!!character && <BonusStatsCard character={character} />}
{/* Enemy Editor */}
{!!character && <EnemyEditorCard character={character} />}
{/*Minimum Final Stat Filter */}
{!!statsDisplayKeys && <StatFilterCard statFilters={statFilters} statKeys={statsDisplayKeys?.basicKeys as any}
setStatFilters={sFs => buildSettingsDispatch({ statFilters: sFs })} disabled={generatingBuilds} />}
{/* Hit mode options */}
{characterSheet && character && initialStats && <HitModeCard build={initialStats} character={character} disabled={generatingBuilds} />}
</Grid>
{/* Right half */}
<Grid item xs={12} md={6} lg={7} sx={{
// select all excluding last
"> div:nth-last-of-type(n+2)": { mb: 1 }
}}>
{!!initialStats && <ArtifactConditionalCard disabled={generatingBuilds} initialStats={initialStats} />}
{/* Artifact set pickers */}
{!!initialStats && setFilters.map((setFilter, index) => (index <= setFilters.filter(s => s.key).length) && <ArtifactSetPicker key={index} index={index} setFilters={setFilters}
disabled={generatingBuilds} initialStats={initialStats} onChange={(index, key, num) => buildSettingsDispatch({ type: 'setFilter', index, key, num })} />)}
{/* use equipped/excluded */}
{characterKey && <CardLight><CardContent>
<Grid container spacing={1}>
<Grid item flexGrow={1}>
<Button fullWidth onClick={() => buildSettingsDispatch({ useEquippedArts: !useEquippedArts })} disabled={generatingBuilds}>
<span><FontAwesomeIcon icon={useEquippedArts ? faCheckSquare : faSquare} /> Use Equipped Artifacts</span>
</Button>
</Grid>
<Grid item flexGrow={1}>
<Button fullWidth onClick={() => buildSettingsDispatch({ useExcludedArts: !useExcludedArts })} disabled={generatingBuilds}>
<span><FontAwesomeIcon icon={useExcludedArts ? faCheckSquare : faSquare} /> Use Excluded Artifacts</span>
</Button>
</Grid>
</Grid>
</CardContent></CardLight>}
{/* main stat selector */}
{characterKey && <MainStatSelectionCard
mainStatAssumptionLevel={mainStatAssumptionLevel}
mainStatKeys={mainStatKeys}
onChangeMainStatKey={(slotKey, mainStatKey = undefined) => {
if (mainStatKey === undefined)
buildSettingsDispatch({ type: "mainStatKeyReset", slotKey })
else
buildSettingsDispatch({ type: "mainStatKey", slotKey, mainStatKey })
}}
onChangeAssLevel={mainStatAssumptionLevel => buildSettingsDispatch({ mainStatAssumptionLevel })}
disabled={generatingBuilds}
/>}
</Grid>
</Grid>
{/* Footer */}
<Grid container spacing={1} sx={{ mt: 1 }}>
<Grid item flexGrow={1} >
<ButtonGroup>
<Button
disabled={!characterKey || generatingBuilds}
color={(characterKey && totBuildNumber <= warningBuildNumber) ? "success" : "warning"}
onClick={generateBuilds}
startIcon={<FontAwesomeIcon icon={faCalculator} />}
>Generate</Button>
{/* <Tooltip title={<Typography></Typography>} placement="top" arrow> */}
<DropdownButton disabled={generatingBuilds || !characterKey} title={<span><b>{maxBuildsToShow}</b> {maxBuildsToShow === 1 ? "Build" : "Builds"}</span>}>
<MenuItem>
<Typography variant="caption" color="info.main">
Decreasing the number of generated build will decrease build calculation time for large number of builds.
</Typography>
</MenuItem>
<Divider />
{maxBuildsToShowList.map(v => <MenuItem key={v} onClick={() => buildSettingsDispatch({ maxBuildsToShow: v })}>{v} {v === 1 ? "Build" : "Builds"}</MenuItem>)}
</DropdownButton>
{/* </Tooltip> */}
<Button
disabled={!generatingBuilds}
color="error"
onClick={() => {
if (!worker.current) return;
worker.current.terminate();
worker.current = null
setgeneratingBuilds(false)
setgenerationDuration(0)
setgenerationProgress(0)
setgenerationSkipped(0)
}}
startIcon={<Close />}
>Cancel</Button>
</ButtonGroup>
</Grid>
<Grid item>
{statsDisplayKeys && characterSheet && weaponSheet && initialStats && <OptimizationTargetSelector {...{ optimizationTarget, setTarget: target => buildSettingsDispatch({ optimizationTarget: target }), initialStats, characterSheet, weaponSheet, artifactSheets, statsDisplayKeys, disabled: !!generatingBuilds }} />}
</Grid>
</Grid>
{!!characterKey && <Box sx={{ mt: 1 }} >
<BuildAlert {...{ totBuildNumber, generatingBuilds, generationSkipped, generationProgress, generationDuration, characterName, maxBuildsToShow }} />
</Box>}
</CardContent>
</CardDark>
<CardDark>
<CardContent>
<Typography>
{buildStats ? <span>Showing <strong>{buildStats.length}</strong> Builds generated for {characterName}. {!!buildDate && <span>Build generated on: <strong>{(new Date(buildDate)).toLocaleString()}</strong></span>}</span>
: <span>Select a character to generate builds.</span>}
</Typography>
</CardContent>
</CardDark>
<Suspense fallback={<Skeleton variant="rectangular" width="100%" height={600} />}>
{/* Build List */}
{buildStats?.map((build, index) =>
characterSheet && weaponSheet && artifactSheets && <ArtifactBuildDisplayItem sheets={{ characterSheet, weaponSheet, artifactSheets }} build={build} characterKey={characterKey as CharacterKey} index={index} key={Object.values(build.equippedArtifacts ?? {}).join()} statsDisplayKeys={statsDisplayKeys} onClick={() => setmodalBuild(index)} />
)}
</Suspense>
</Box>
</buildContext.Provider>
}
function BuildModal({ build, showCharacterModal, characterKey, selectCharacter, onClose }) {
return <ModalWrapper open={!!(showCharacterModal || build)} onClose={onClose} containerProps={{ maxWidth: "xl" }}>
<CharacterDisplayCard
characterKey={characterKey}
setCharacterKey={selectCharacter}
newBuild={build}
onClose={onClose}
footer={<CloseButton large onClick={onClose} />} />
</ModalWrapper>
} | the_stack |
import {
expect
} from 'chai';
import {
each
} from '@phosphor/algorithm';
import {
StackedPanel, TabBar, TabPanel, Widget
} from '@phosphor/widgets';
import {
LogWidget
} from './widget.spec';
describe('@phosphor/widgets', () => {
describe('TabPanel', () => {
describe('#constructor()', () => {
it('should construct a new tab panel and take no arguments', () => {
let panel = new TabPanel();
expect(panel).to.be.an.instanceof(TabPanel);
});
it('should accept options', () => {
let renderer = Object.create(TabBar.defaultRenderer);
let panel = new TabPanel({
tabPlacement: 'left',
tabsMovable: true,
renderer
});
expect(panel.tabBar.tabsMovable).to.equal(true);
expect(panel.tabBar.renderer).to.equal(renderer);
});
it('should add a `p-TabPanel` class', () => {
let panel = new TabPanel();
expect(panel.hasClass('p-TabPanel')).to.equal(true);
});
});
describe('#dispose()', () => {
it('should dispose of the resources held by the widget', () => {
let panel = new TabPanel();
panel.addWidget(new Widget());
panel.dispose();
expect(panel.isDisposed).to.equal(true);
panel.dispose();
expect(panel.isDisposed).to.equal(true);
});
});
describe('#currentChanged', () => {
it('should be emitted when the current tab is changed', () => {
let panel = new TabPanel();
panel.addWidget(new Widget());
panel.addWidget(new Widget());
let called = false;
let widgets = panel.widgets;
panel.currentChanged.connect((sender, args) => {
expect(sender).to.equal(panel);
expect(args.previousIndex).to.equal(0);
expect(args.previousWidget).to.equal(widgets[0]);
expect(args.currentIndex).to.equal(1);
expect(args.currentWidget).to.equal(widgets[1]);
called = true;
});
panel.currentIndex = 1;
expect(called).to.equal(true);
});
it('should not be emitted when another tab is inserted', () => {
let panel = new TabPanel();
panel.addWidget(new Widget());
panel.addWidget(new Widget());
let called = false;
panel.currentChanged.connect((sender, args) => { called = true; });
panel.insertWidget(0, new Widget());
expect(called).to.equal(false);
});
it('should not be emitted when another tab is removed', () => {
let panel = new TabPanel();
panel.addWidget(new Widget());
panel.addWidget(new Widget());
let called = false;
panel.currentIndex = 1;
panel.currentChanged.connect((sender, args) => { called = true; });
panel.widgets[0].parent = null;
expect(called).to.equal(false);
});
it('should not be emitted when the current tab is moved', () => {
let panel = new TabPanel();
panel.addWidget(new Widget());
panel.addWidget(new Widget());
let called = false;
panel.currentChanged.connect((sender, args) => { called = true; });
panel.insertWidget(2, panel.widgets[0]);
expect(called).to.equal(false);
});
});
describe('#currentIndex', () => {
it('should get the index of the currently selected tab', () => {
let panel = new TabPanel();
panel.addWidget(new Widget());
expect(panel.currentIndex).to.equal(0);
});
it('should be `-1` if no tab is selected', () => {
let panel = new TabPanel();
expect(panel.currentIndex).to.equal(-1);
});
it('should set the index of the currently selected tab', () => {
let panel = new TabPanel();
panel.addWidget(new Widget());
panel.addWidget(new Widget());
panel.currentIndex = 1;
expect(panel.currentIndex).to.equal(1);
});
it('should set the index to `-1` if out of range', () => {
let panel = new TabPanel();
panel.addWidget(new Widget());
panel.addWidget(new Widget());
panel.currentIndex = -2;
expect(panel.currentIndex).to.equal(-1);
panel.currentIndex = 2;
expect(panel.currentIndex).to.equal(-1);
});
});
describe('#currentWidget', () => {
it('should get the currently selected tab', () => {
let panel = new TabPanel();
let widget = new Widget();
panel.addWidget(widget);
expect(panel.currentWidget).to.equal(widget);
});
it('should be `null` if no tab is selected', () => {
let panel = new TabPanel();
expect(panel.currentWidget).to.equal(null);
});
it('should set the currently selected tab', () => {
let panel = new TabPanel();
panel.addWidget(new Widget());
let widget = new Widget();
panel.addWidget(widget);
panel.currentWidget = widget;
expect(panel.currentWidget).to.equal(widget);
});
it('should set `null` if the widget is not in the panel', () => {
let panel = new TabPanel();
panel.addWidget(new Widget());
panel.addWidget(new Widget());
panel.currentWidget = new Widget();
expect(panel.currentWidget).to.equal(null);
});
});
describe('#tabsMovable', () => {
it('should be the tabsMovable property of the tabBar', () => {
let panel = new TabPanel();
expect(panel.tabsMovable).to.equal(false);
panel.tabsMovable = true;
expect(panel.tabBar.tabsMovable).to.equal(true);
});
});
describe('#tabPlacement', () => {
it('should be the tab placement for the tab panel', () => {
let panel = new TabPanel();
expect(panel.tabPlacement).to.equal('top');
expect(panel.tabBar.orientation).to.equal('horizontal');
expect(panel.tabBar.node.getAttribute('data-placement')).to.equal('top');
panel.tabPlacement = 'bottom';
expect(panel.tabBar.orientation).to.equal('horizontal');
expect(panel.tabBar.node.getAttribute('data-placement')).to.equal('bottom');
panel.tabPlacement = 'left';
expect(panel.tabBar.orientation).to.equal('vertical');
expect(panel.tabBar.node.getAttribute('data-placement')).to.equal('left');
panel.tabPlacement = 'right';
expect(panel.tabBar.orientation).to.equal('vertical');
expect(panel.tabBar.node.getAttribute('data-placement')).to.equal('right');
});
});
describe('#tabBar', () => {
it('should get the tab bar associated with the tab panel', () => {
let panel = new TabPanel();
let bar = panel.tabBar;
expect(bar).to.be.an.instanceof(TabBar);
});
it('should have the "p-TabPanel-tabBar" class', () => {
let panel = new TabPanel();
let bar = panel.tabBar;
expect(bar.hasClass('p-TabPanel-tabBar')).to.equal(true);
});
it('should move the widget in the stacked panel when a tab is moved', () => {
let panel = new TabPanel();
let widgets = [new LogWidget(), new LogWidget()];
each(widgets, w => { panel.addWidget(w); });
Widget.attach(panel, document.body);
let bar = panel.tabBar;
let called = false;
bar.tabMoved.connect(() => {
let stack = panel.stackedPanel;
expect(stack.widgets[1]).to.equal(widgets[0]);
called = true;
});
(bar.tabMoved as any).emit({
fromIndex: 0,
toIndex: 1,
title: widgets[0].title
});
expect(called).to.equal(true);
panel.dispose();
});
it('should show the new widget when the current tab changes', () => {
let panel = new TabPanel();
let widgets = [new LogWidget(), new LogWidget(), new LogWidget()];
each(widgets, w => { panel.addWidget(w); });
each(widgets, w => { w.node.tabIndex = -1; });
Widget.attach(panel, document.body);
panel.tabBar.currentChanged.connect((sender, args) => {
expect(widgets[args.previousIndex].isVisible).to.equal(false);
expect(widgets[args.currentIndex].isVisible).to.equal(true);
});
panel.tabBar.currentIndex = 1;
panel.dispose();
});
it('should close the widget when a tab is closed', () => {
let panel = new TabPanel();
let widget = new LogWidget();
panel.addWidget(widget);
Widget.attach(panel, document.body);
let bar = panel.tabBar;
let called = false;
bar.tabCloseRequested.connect(() => {
expect(widget.methods.indexOf('onCloseRequest')).to.not.equal(-1);
called = true;
});
(bar.tabCloseRequested as any).emit({ index: 0, title: widget.title });
expect(called).to.equal(true);
panel.dispose();
});
});
describe('#stackedPanel', () => {
it('should get the stacked panel associated with the tab panel', () => {
let panel = new TabPanel();
let stack = panel.stackedPanel;
expect(stack).to.be.an.instanceof(StackedPanel);
});
it('should have the "p-TabPanel-stackedPanel" class', () => {
let panel = new TabPanel();
let stack = panel.stackedPanel;
expect(stack.hasClass('p-TabPanel-stackedPanel')).to.equal(true);
});
it('remove a tab when a widget is removed from the stacked panel', () => {
let panel = new TabPanel();
let widget = new Widget();
panel.addWidget(widget);
let stack = panel.stackedPanel;
let called = false;
stack.widgetRemoved.connect(() => {
let bar = panel.tabBar;
expect(bar.titles).to.deep.equal([]);
called = true;
});
widget.parent = null;
expect(called).to.equal(true);
});
});
describe('#widgets', () => {
it('should get a read-only array of the widgets in the panel', () => {
let panel = new TabPanel();
let widgets = [new Widget(), new Widget(), new Widget()];
each(widgets, w => { panel.addWidget(w); });
expect(panel.widgets).to.deep.equal(widgets);
});
});
describe('#addWidget()', () => {
it('should add a widget to the end of the tab panel', () => {
let panel = new TabPanel();
let widgets = [new Widget(), new Widget(), new Widget()];
each(widgets, w => { panel.addWidget(w); });
let widget = new Widget();
panel.addWidget(widget);
expect(panel.widgets[3]).to.equal(widget);
expect(panel.tabBar.titles[2]).to.equal(widgets[2].title);
});
it('should move an existing widget', () => {
let panel = new TabPanel();
let widgets = [new Widget(), new Widget(), new Widget()];
each(widgets, w => { panel.addWidget(w); });
panel.addWidget(widgets[0]);
expect(panel.widgets[2]).to.equal(widgets[0]);
});
});
describe('#insertWidget()', () => {
it('should insert a widget into the tab panel at a specified index', () => {
let panel = new TabPanel();
let widgets = [new Widget(), new Widget(), new Widget()];
each(widgets, w => { panel.addWidget(w); });
let widget = new Widget();
panel.insertWidget(1, widget);
expect(panel.widgets[1]).to.equal(widget);
expect(panel.tabBar.titles[1]).to.equal(widget.title);
});
it('should move an existing widget', () => {
let panel = new TabPanel();
let widgets = [new Widget(), new Widget(), new Widget()];
each(widgets, w => { panel.addWidget(w); });
panel.insertWidget(0, widgets[2]);
expect(panel.widgets[0]).to.equal(widgets[2]);
});
});
});
}); | the_stack |
* Typescript definition for ionic framework
* Bosa Daniele
*
* v. 1.0.1
*
* Based on Ionic Framework v. 1.0.0-beta.13 (http://ionicframework.com/)
* Dependencies: angular.d.ts (https://github.com/borisyankov/DefinitelyTyped/blob/master/angularjs/angular.d.ts) for promises
*/
/**
* Define a global ionic object
*/
declare var ionic: Ionic.IBase;
declare module Ionic
{
//#region Base
interface IBase
{
Platform: IPlatform;
DomUtil: IDomUtil;
EventController: IEventController;
//#region EventController Aliases
/**
* @param eventType The event to trigger
* @param data The data for the event. Hint: pass in {target: targetElement}
* @param bubbles Whether the event should bubble up the DOM
* @param cancelable Whether the event should be cancelable
*/
trigger(eventType: string, data: Object, bubbles?: boolean, cancelable?: boolean): void;
/**
* Listen to an event on an element.
*
* @param type The event to listen for
* @param callback The listener to be called
* @param element The element to listen for the event on
*/
on(type: string, callback: () => void, element: Element): void;
/**
* Remove an event listener
*
* @param type The event to listen for
* @param callback The listener to be called
* @param element The element to listen for the event on
*/
off(type: string, callback: () => void, element: Element): void;
/**
* Add an event listener for a gesture on an element.
*
* @param eventType The gesture event to listen for
* @param callback The function to call when the gesture happens
* @param element The angular element to listen for the event on
*/
onGesture(eventType: string, callback: () => void, element: Element): void;
onGesture(eventType: "hold", callback: () => void, element: Element): void;
onGesture(eventType: "tap", callback: () => void, element: Element): void;
onGesture(eventType: "doubletap", callback: () => void, element: Element): void;
onGesture(eventType: "drag", callback: () => void, element: Element): void;
onGesture(eventType: "dragstart", callback: () => void, element: Element): void;
onGesture(eventType: "dragend", callback: () => void, element: Element): void;
onGesture(eventType: "dragup", callback: () => void, element: Element): void;
onGesture(eventType: "dragdown", callback: () => void, element: Element): void;
onGesture(eventType: "dragleft", callback: () => void, element: Element): void;
onGesture(eventType: "dragright", callback: () => void, element: Element): void;
onGesture(eventType: "swipe", callback: () => void, element: Element): void;
onGesture(eventType: "swipeup", callback: () => void, element: Element): void;
onGesture(eventType: "swipedown", callback: () => void, element: Element): void;
onGesture(eventType: "swipeleft", callback: () => void, element: Element): void;
onGesture(eventType: "swiperight", callback: () => void, element: Element): void;
onGesture(eventType: "transform", callback: () => void, element: Element): void;
onGesture(eventType: "transformstart", callback: () => void, element: Element): void;
onGesture(eventType: "transformend", callback: () => void, element: Element): void;
onGesture(eventType: "rotate", callback: () => void, element: Element): void;
onGesture(eventType: "pinch", callback: () => void, element: Element): void;
onGesture(eventType: "pinchin", callback: () => void, element: Element): void;
onGesture(eventType: "pinchout", callback: () => void, element: Element): void;
onGesture(eventType: "touch", callback: () => void, element: Element): void;
onGesture(eventType: "release", callback: () => void, element: Element): void;
/**
* Remove an event listener for a gesture on an element.
*
* @param eventType The gesture event
* @param callback The listener that was added earlier
* @param element The element the listener was added on
*/
offGesture(eventType: string, callback: () => void, element: Element): void;
offGesture(eventType: "hold", callback: () => void, element: Element): void;
offGesture(eventType: "tap", callback: () => void, element: Element): void;
offGesture(eventType: "doubletap", callback: () => void, element: Element): void;
offGesture(eventType: "drag", callback: () => void, element: Element): void;
offGesture(eventType: "dragstart", callback: () => void, element: Element): void;
offGesture(eventType: "dragend", callback: () => void, element: Element): void;
offGesture(eventType: "dragup", callback: () => void, element: Element): void;
offGesture(eventType: "dragdown", callback: () => void, element: Element): void;
offGesture(eventType: "dragleft", callback: () => void, element: Element): void;
offGesture(eventType: "dragright", callback: () => void, element: Element): void;
offGesture(eventType: "swipe", callback: () => void, element: Element): void;
offGesture(eventType: "swipeup", callback: () => void, element: Element): void;
offGesture(eventType: "swipedown", callback: () => void, element: Element): void;
offGesture(eventType: "swipeleft", callback: () => void, element: Element): void;
offGesture(eventType: "swiperight", callback: () => void, element: Element): void;
offGesture(eventType: "transform", callback: () => void, element: Element): void;
offGesture(eventType: "transformstart", callback: () => void, element: Element): void;
offGesture(eventType: "transformend", callback: () => void, element: Element): void;
offGesture(eventType: "rotate", callback: () => void, element: Element): void;
offGesture(eventType: "pinch", callback: () => void, element: Element): void;
offGesture(eventType: "pinchin", callback: () => void, element: Element): void;
offGesture(eventType: "pinchout", callback: () => void, element: Element): void;
offGesture(eventType: "touch", callback: () => void, element: Element): void;
offGesture(eventType: "release", callback: () => void, element: Element): void;
//#endregion
//#region DomUtil Aliases
/**
* Calls requestAnimationFrame, or a polyfill if not available.
*
* @param callback The function to call when the next frame happens
*/
requestAnimationFrame(callback: () => void): void;
/**
* When given a callback, if that callback is called 100 times between animation frames, adding Throttle will make it only run the last of the 100 calls.
*
* @param callback a function which will be throttled to requestAnimationFrame
*/
animationFrameThrottle(callback: () => void): void;
//#endregion
}
//#endregion
//#region Config Provider
/**
* Angular service: $ionicConfigProvider
*
* $ionicConfigProvider can be used during the configuration phase of your app to change how Ionic works.
*/
interface IConfigProvider
{
/**
* Set whether Ionic should prefetch all templateUrls defined in $stateProvider.state. Default true.
* If set to false, the user will have to wait for a template to be fetched the first time he/she is going to a a new page.
*
* @param shouldPrefetch Whether Ionic should prefetch templateUrls defined in $stateProvider.state(). Default true.
*/
prefetchTemplates(shouldPrefetch: boolean): boolean;
}
//#endregion
//#region Platform
interface IDevice
{
/** Get the version of Cordova running on the device. */
cordova: string;
/**
* The device.model returns the name of the device's model or product. The value is set
* by the device manufacturer and may be different across versions of the same product.
*/
model: string;
/** device.name is deprecated as of version 2.3.0. Use device.model instead. */
name: string;
/** Get the device's operating system name. */
platform: string;
/** Get the device's Universally Unique Identifier (UUID). */
uuid: string;
/** Get the operating system version. */
version: string;
}
interface IPlatform
{
//#region Properties
/**
* Whether the device is ready
*/
isReady: boolean;
/**
* Whether the device is full screen.
*/
isFullScreen: boolean;
/**
* An array of all platforms found.
*/
platforms: string[];
/**
* What grade the current platform is.
*/
grade: string;
//#endregion
/**
* Trigger a callback once the device is ready, or immediately if the device is already ready.
* This method can be run from anywhere and does not need to be wrapped by any additional methods.
* When the app is within a WebView (Cordova), it'll fire the callback once the device is ready.
* If the app is within a web browser, it'll fire the callback after window.load.
*/
ready(callback: () => void): void;
/**
* Set the grade of the device: 'a', 'b', or 'c'. 'a' is the best (most css features enabled),
* 'c' is the worst. By default, sets the grade depending on the current device.
*/
setGrade(grade: string): void;
/**
* Set the platform of the device
*/
setPlatform(platform: string): void;
/**
* Return the current device (given by Cordova).
*/
device(): IDevice;
/**
* Check if we are running within a WebView (such as Cordova).
*/
isWebView(): boolean;
/**
* Whether we are running on iPad.
*/
isIPad(): boolean;
/**
* Whether we are running on iOS.
*/
isIOS(): boolean;
/**
* Whether we are running on Android
*/
isAndroid(): boolean;
/**
* Whether we are running on Windows Phone.
*/
isWindowsPhone(): boolean;
/**
* The name of the current platform.
*/
platform(): string;
/**
* The version of the current device platform.
*/
version(): string;
/**
* Exit the application.
*/
exitApp(): void;
/**
* Shows or hides the device status bar (in Cordova).
*
* @param showShould Whether or not to show the status bar.
*/
showStatusBar(shouldShow: boolean): void;
/**
* Sets whether the app is full screen or not (in Cordova).
*
* @param showFullScreen Whether or not to set the app to full screen. Defaults to true.
* @param showStatusBar Whether or not to show the device's status bar. Defaults to false.
*/
fullScreen(showFullScreen: boolean, showStatusBar: boolean): void;
}
//#endregion
// #region Dom Utils
/**
* ionic.DomUtil
*/
interface IDomUtil
{
/**
* alias: ionic.requestAnimationFrame
*
* Calls requestAnimationFrame, or a polyfill if not available.
*
* @param callback The function to call when the next frame happens
*/
requestAnimationFrame(callback: () => void): void;
/**
* alias: ionic.animationFrameThrottle
*
* When given a callback, if that callback is called 100 times between animation frames, adding Throttle will make it only run the last of the 100 calls.
*
* @param callback a function which will be throttled to requestAnimationFrame
*/
animationFrameThrottle(callback: () => void): void;
/**
* Find an element's scroll offset within its container
*
* @param element The element to find the offset of
*/
getPositionInParent(element: Element): void;
/**
* The Window.requestAnimationFrame() method tells the browser that you wish to perform an animation and requests that the browser
* call a specified function to update an animation before the next repaint.
* The method takes as an argument a callback to be invoked before the repaint.
*
* @param callback The function to be called
*/
ready(callback: () => void): void;
/**
* Get a rect representing the bounds of the given textNode.
*/
getTextBounds(textNode: Element): {
left: number;
right: number;
top: number;
bottom: number;
width: number;
height: number;
};
/**
* Get the first index of a child node within the given element of the specified type.
*
* @param element The element to find the index of.
* @param type The nodeName to match children of element against.
*/
getChildIndex(element: Element, type: string): number;
/**
* Returns the closest parent of element matching the className, or null.
*
* @param element
* @param className
*/
getParentWithClass(element: Element, className: string): Element
/**
* Returns the closest parent or self matching the className, or null.
*/
getParentOrSelfWithClass(element: Element, className: string): Element;
/**
* Returns whether {x,y} fits within the rectangle defined by {x1,y1,x2,y2}.
*
* @param x
* @param y
* @param x1
* @param y1
* @param x2
* @param y2
*/
rectContains(x: number, y: number, x1: number, y1: number, x2: number, y2: number): boolean;
}
//#endregion
//#region EventController
/**
* Angular service: $ionicGesture
*/
interface IEventController
{
/**
* alias: ionic.trigger
*
* @param eventType The event to trigger
* @param data The data for the event. Hint: pass in {target: targetElement}
* @param bubbles Whether the event should bubble up the DOM
* @param cancelable Whether the event should be cancelable
*/
trigger(eventType: string, data: Object, bubbles?: boolean, cancelable?: boolean): void;
/**
* alias: ionic.on
*
* Listen to an event on an element
*
* @param type The event to listen for
* @param callback The listener to be called
* @param element The element to listen for the event on
*/
on(type: string, callback: () => void, element: Element): void;
/**
* alias: ionic.off
*
* Remove an event listener
*
* @param type The event to listen for
* @param callback The listener to be called
* @param element The element to listen for the event on
*/
off(type: string, callback: () => void, element: Element): void;
/**
* alias: ionic.onGesture
*
* Add an event listener for a gesture on an element.
*
* @param eventType The gesture event to listen for
* @param callback The function to call when the gesture happens
* @param element The angular element to listen for the event on
*/
onGesture(eventType: string, callback: () => void, element: Element): void;
onGesture(eventType: "hold", callback: () => void, element: Element): void;
onGesture(eventType: "tap", callback: () => void, element: Element): void;
onGesture(eventType: "doubletap", callback: () => void, element: Element): void;
onGesture(eventType: "drag", callback: () => void, element: Element): void;
onGesture(eventType: "dragstart", callback: () => void, element: Element): void;
onGesture(eventType: "dragend", callback: () => void, element: Element): void;
onGesture(eventType: "dragup", callback: () => void, element: Element): void;
onGesture(eventType: "dragdown", callback: () => void, element: Element): void;
onGesture(eventType: "dragleft", callback: () => void, element: Element): void;
onGesture(eventType: "dragright", callback: () => void, element: Element): void;
onGesture(eventType: "swipe", callback: () => void, element: Element): void;
onGesture(eventType: "swipeup", callback: () => void, element: Element): void;
onGesture(eventType: "swipedown", callback: () => void, element: Element): void;
onGesture(eventType: "swipeleft", callback: () => void, element: Element): void;
onGesture(eventType: "swiperight", callback: () => void, element: Element): void;
onGesture(eventType: "transform", callback: () => void, element: Element): void;
onGesture(eventType: "transformstart", callback: () => void, element: Element): void;
onGesture(eventType: "transformend", callback: () => void, element: Element): void;
onGesture(eventType: "rotate", callback: () => void, element: Element): void;
onGesture(eventType: "pinch", callback: () => void, element: Element): void;
onGesture(eventType: "pinchin", callback: () => void, element: Element): void;
onGesture(eventType: "pinchout", callback: () => void, element: Element): void;
onGesture(eventType: "touch", callback: () => void, element: Element): void;
onGesture(eventType: "release", callback: () => void, element: Element): void;
/**
* alias: ionic.offGesture
*
* Remove an event listener for a gesture on an element.
*
* @param eventType The gesture event
* @param callback The listener that was added earlier
* @param element The element the listener was added on
*/
offGesture(eventType: string, callback: () => void, element: Element): void;
offGesture(eventType: "hold", callback: () => void, element: Element): void;
offGesture(eventType: "tap", callback: () => void, element: Element): void;
offGesture(eventType: "doubletap", callback: () => void, element: Element): void;
offGesture(eventType: "drag", callback: () => void, element: Element): void;
offGesture(eventType: "dragstart", callback: () => void, element: Element): void;
offGesture(eventType: "dragend", callback: () => void, element: Element): void;
offGesture(eventType: "dragup", callback: () => void, element: Element): void;
offGesture(eventType: "dragdown", callback: () => void, element: Element): void;
offGesture(eventType: "dragleft", callback: () => void, element: Element): void;
offGesture(eventType: "dragright", callback: () => void, element: Element): void;
offGesture(eventType: "swipe", callback: () => void, element: Element): void;
offGesture(eventType: "swipeup", callback: () => void, element: Element): void;
offGesture(eventType: "swipedown", callback: () => void, element: Element): void;
offGesture(eventType: "swipeleft", callback: () => void, element: Element): void;
offGesture(eventType: "swiperight", callback: () => void, element: Element): void;
offGesture(eventType: "transform", callback: () => void, element: Element): void;
offGesture(eventType: "transformstart", callback: () => void, element: Element): void;
offGesture(eventType: "transformend", callback: () => void, element: Element): void;
offGesture(eventType: "rotate", callback: () => void, element: Element): void;
offGesture(eventType: "pinch", callback: () => void, element: Element): void;
offGesture(eventType: "pinchin", callback: () => void, element: Element): void;
offGesture(eventType: "pinchout", callback: () => void, element: Element): void;
offGesture(eventType: "touch", callback: () => void, element: Element): void;
offGesture(eventType: "release", callback: () => void, element: Element): void;
}
//#endregion
//#region Ionic Position
/**
* Angular service: $ionicPosition
*
* A set of utility methods that can be use to retrieve position of DOM elements.
* It is meant to be used where we need to absolute-position DOM elements in relation to other, existing elements (this is the case for tooltips, popovers, etc.).
*/
interface IPosition
{
/**
* Get the current coordinates of the element, relative to the offset parent. Read-only equivalent of jQuery's position function.
*
* @param element The element to get the position of
*/
position(element: Element): {
top: number;
left: number;
width: number;
height: number;
}
/**
* Get the current coordinates of the element, relative to the document. Read-only equivalent of jQuery's offset function.
*
* @param element The element to get offset of
*/
offset(element: Element): {
top: number;
left: number;
width: number;
height: number;
}
}
//#endregion
//#region Action Sheet
interface IActionSheetOptions
{
/**
* Which buttons to show. Each button is an object with a text field.
*/
buttons?: Array<{ text: string }>;
/**
* The title to show on the action sheet.
*/
titleText?: string;
/**
* The text for a 'cancel' button on the action sheet.
*/
cancelText?: string;
/**
* The text for a 'danger' on the action sheet.
*/
destructiveText?: string;
/**
* Called if the cancel button is pressed, the backdrop is tapped or the hardware back button is pressed.
*/
cancel?: () => void;
/**
* Called when one of the non-destructive buttons is clicked, with the index of the button that was clicked and the button object.
* Return true to close the action sheet, or false to keep it opened.
*/
buttonClicked?: (index?: number) => any;
/**
* Called when the destructive button is clicked. Return true to close the action sheet, or false to keep it opened.
*/
destructiveButtonClicked?: () => boolean;
/**
* Whether to cancel the actionSheet when navigating to a new state. Default true.
*/
cancelOnStateChange?: boolean;
}
/**
* Angular service: $ionicActionSheet
*
* The Action Sheet is a slide-up pane that lets the user choose from a set of options. Dangerous options are highlighted in red and made obvious.
* There are easy ways to cancel out of the action sheet, such as tapping the backdrop or even hitting escape on the keyboard for desktop testing.
*/
interface IActionSheet
{
/**
* Load and return a new action sheet.
* A new isolated scope will be created for the action sheet and the new element will be appended into the body.
*
* Returns hideSheet, a function which, when called, hides & cancels the action sheet.
*/
show(options: IActionSheetOptions): () => void;
}
//#endregion
//#region Backdrop
/**
* Angular service: $ionicBackdrop
*/
interface IBackdrop
{
/**
* Retains the backdrop.
*/
retain(): void;
/**
* Releases the backdrop.
*/
release(): void;
}
//#endregion
//#region Gesture
/**
* Angular service: $ionicGesture
*/
interface IGesture extends IEventController { }
//#endregion
//#region Lists
/**
* Angular service: $ionicListDelegate
*
* Delegate for controlling the ionList directive.
* Methods called directly on the $ionicListDelegate service will control all lists. Use the $getByHandle method to control specific ionList instances.
*/
interface IListDelegate
{
/**
* Set whether or not this list is showing its reorder buttons.
* Returns whether the reorder buttons are shown.
*/
showReorder(showReorder?: boolean): boolean;
/**
* Set whether or not this list is showing its delete buttons.
* Returns whether the delete buttons are shown.
*/
showDelete(showDelete?: boolean): boolean;
/**
* Set whether or not this list is able to swipe to show option buttons.
* Returns whether the list is able to swipe to show option buttons.
*/
canSwipeItems(canSwipeItems?: boolean): boolean;
/**
* Closes any option buttons on the list that are swiped open.
*/
closeOptionButtons(): void;
/**
* Return delegate instance that controls only the ionTabs directives with delegate-handle matching the given handle.
*/
$getByHandle(handle: string): IListDelegate;
}
//#endregion
//#region Loading
interface ILoadingOptions
{
template?: string;
templateUrl?: string;
noBackdrop?: boolean;
delay?: number;
duration?: number;
}
/**
* Angular service: $ionicLoading
*
* An overlay that can be used to indicate activity while blocking user interaction.
*/
interface ILoading
{
show(opts?: ILoadingOptions): void;
hide(): void;
}
//#endregion
//#region Modals
interface IModalOptions
{
/**
* The scope to be a child of. Default: creates a child of $rootScope.
*/
scope?: ng.IScope;
/**
* The animation to show & hide with. Default: 'slide-in-up'
*/
animation?: string;
/**
* Whether to autofocus the first input of the modal when shown. Default: false.
*/
focusFirstInput?: boolean;
/**
* Whether to close the modal on clicking the backdrop. Default: true.
*/
backdropClickToClose?: boolean;
/**
* Whether the modal can be closed using the hardware back button on Android and similar devices. Default: true.
*/
hardwareBackButtonClose?: boolean;
}
/**
* Angular service: $ionicModal
*/
interface IModal
{
/**
* Creates a new modal controller instance.
*
* @param options An IModalOptions object
*/
initialize(options: IModalOptions): void;
/**
* Returns an instance of an ionicModal controller.
*
* @param templateString The template string to use as the modal's content.
* @param options Options to be passed to the initialize method.
*/
fromTemplate(templateString: string, options: IModalOptions): IModal;
/**
* Returns a promise that will be resolved with an instance of an ionicModal controller.
*
* @param templateUrl The url to load the template from.
* @param options Options to be passed to the initialize method.
*/
fromTemplateUrl(templateUrl: string, options: IModalOptions): ng.IPromise<IModal>;
/**
* Show this modal instance
* Returns a promise which is resolved when the modal is finished animating in
*/
show(): ng.IPromise<any>;
/**
* Hide this modal instance
* Returns a promise which is resolved when the modal is finished animating out
*/
hide(): ng.IPromise<any>;
/**
* Remove this modal instance from the DOM and clean up
* Returns a promise which is resolved when the modal is finished animating out
*/
remove(): ng.IPromise<any>;
/**
* Returns whether this modal is currently shown.
*/
isShown(): boolean;
}
//#endregion
//#region Navigation
/**
* Angular service: $ionicNavBarDelegate
*
* Delegate for controlling the ionNavBar directive.
*/
interface INavBarDelegate
{
/**
* Goes back in the view history
*
* @param event The event object (eg from a tap event)
*/
back(event?: Event): void;
/**
* Aligns the title with the buttons in a given direction
*
* @param direction The direction to the align the title text towards. Available: 'left', 'right', 'center'. Default: 'center'.
*/
align(direction?: string): void;
align(direction: "left"): void;
align(direction: "right"): void;
align(direction: "center"): void;
/**
* Set/get whether the ionNavBackButton is shown (if it exists).
* Returns whether the back button is shown
*
* @param show Whether to show the back button
*/
showBackButton(show?: boolean): boolean;
/**
* Set/get whether the ionNavBar is shown
* Returns whether the bar is shown
*
* @param show whether to show the bar
*/
showBar(show?: boolean): boolean;
/**
* Set the title for the ionNavBar
*
* @param title The new title to show
*/
setTitle(title: string): void;
/**
* Change the title, transitioning the new title in and the old one out in a given direction
*
* @param title the new title to show
* @param direction the direction to transition the new title in. Available: 'forward', 'back'.
*/
changeTitle(title: string, direction: string): void;
changeTitle(title: string, direction: "forward"): void;
changeTitle(title: string, direction: "back"): void;
/**
* Returns the current title of the navbar.
*/
getTitle(): string;
/**
* Returns the previous title of the navbar.
*/
getPreviousTitle(): string;
/**
* Return a delegate instance that controls only the navBars with delegate-handle matching the given handl
*/
$getByHandle(handle: string): INavBarDelegate;
}
//#endregion
//#region Popover
interface IPopoverOptions
{
/**
* The scope to be a child of. Default: creates a child of $rootScope
*/
scope?: ng.IScope;
/**
* Whether to autofocus the first input of the popover when shown. Default: false
*/
focusFirstInput?: boolean;
/**
* Whether to close the popover on clicking the backdrop. Default: true
*/
backdropClickToClose?: boolean;
/**
* Whether the popover can be closed using the hardware back button on Android and similar devices. Default: true
*/
hardwareBackButtonClose?: boolean;
}
/**
* Angular service: $ionicPopover
*
* The Popover is a view that floats above an app’s content.
* Popovers provide an easy way to present or gather information from the user and are commonly used in the following situations:
* show more info about the current view, select a commonly used tool or configuration, present a list of actions to perform inside one of your views.
* Put the content of the popover inside of an <ion-popover-view> element
*/
interface IPopover
{
/**
* @param templateString The template string to use as the popovers's content
* @param Options to be passed to the initialize method
*/
fromTemplate(templateString: string, options: IPopoverOptions): IPopover;
/**
* Returns a promise that will be resolved with an instance of an ionicPopover controller ($ionicPopover is built on top of $ionicPopover).
*
* @param templateUrl The url to load the template from
* @param Options to be passed to the initialize method
*/
fromTemplateUrl(templateUrl: string, options: IPopoverOptions): ng.IPromise<IPopover>;
/**
* Creates a new popover controller instance
*
*/
initialize(options: IPopoverOptions): void;
/**
* Show this popover instance.
* Returns a promise which is resolved when the popover is finished animating in.
*
* @param $event The $event or target element which the popover should align itself next to.
*/
show($event: any): ng.IPromise<any>;
/**
* Hide this popover instance.
* Returns a promise which is resolved when the popover is finished animating out.
*/
hide(): ng.IPromise<any>;
/**
* Remove this popover instance from the DOM and clean up.
* Returns a promise which is resolved when the popover is finished animating out.
*/
remove(): ng.IPromise<any>;
/**
* Returns whether this popover is currently shown.
*/
isShown(): boolean;
}
//#endregion
//#region Popup
interface IPopupButton
{
text: string;
type?: string;
onTap?(e: Event): void;
}
interface IPopupOptions
{
/**
* The title of the popup
*/
title: string;
/**
* The sub-title of the popup
*/
subTitle?: string;
/**
* The html template to place in the popup body
*/
template?: string;
/**
* The URL of an html template to place in the popup body
*/
templateUrl?: string;
/**
* A scope to link to the popup content
*/
scope?: ng.IScope;
/**
* Buttons to place in the popup footer
*/
buttons?: Array<IPopupButton>;
}
interface IPopupAlertOptions
{
/**
* The title of the popup
*/
title: string;
/**
* The sub-title of the popup
*/
subTitle?: string;
/**
* The html template to place in the popup body
*/
template?: string;
/**
* The URL of an html template to place in the popup body
*/
templateUrl?: string;
/**
* The text of the OK button
*/
okText?: string;
/**
* The type of the OK button
*/
okType?: string;
}
interface IPopupConfirmOptions
{
/**
* The title of the popup
*/
title: string;
/**
* The sub-title of the popup
*/
subTitle?: string;
/**
* The html template to place in the popup body
*/
template?: string;
/**
* The URL of an html template to place in the popup body
*/
templateUrl?: string;
/**
* The text of the Cancel button
*/
canelText?: string;
/**
* The type of the Cancel button
*/
cancelType?: string;
/**
* The text of the OK button
*/
okText?: string;
/**
* The type of the OK button
*/
okType?: string;
}
interface IPopupPromptOptions
{
/**
* The title of the popup
*/
title: string;
/**
* The sub-title of the popup
*/
subTitle?: string;
/**
* The html template to place in the popup body
*/
template?: string;
/**
* The URL of an html template to place in the popup body
*/
templateUrl?: string;
/**
* The type of input of use
*/
inputType: string;
/**
* A placeholder to use for the input
*/
inputPlaceholder: string;
/**
* The text of the Cancel button
*/
canelText?: string;
/**
* The type of the Cancel button
*/
cancelType?: string;
/**
* The text of the OK button
*/
okText?: string;
/**
* The type of the OK button
*/
okType?: string;
}
/**
* Angular service: $ionicPopup
*
* The Ionic Popup service allows programmatically creating and showing popup windows that require the user to respond in order to continue.
* The popup system has support for more flexible versions of the built in alert(), prompt(), and confirm() functions that users are used to,
* in addition to allowing popups with completely custom content and look.
* An input can be given an autofocus attribute so it automatically receives focus when the popup first shows.
* However, depending on certain use-cases this can cause issues with the tap/click system,
* which is why Ionic prefers using the autofocus attribute as an opt-in feature and not the default.
*/
interface IPopup
{
/**
* Show a complex popup. This is the master show function for all popups.
* A complex popup has a buttons array, with each button having a text and type field, in addition to an onTap function.
* The onTap function, called when the correspondingbutton on the popup is tapped,
* will by default close the popup and resolve the popup promise with its return value.
* If you wish to prevent the default and keep the popup open on button tap, call event.preventDefault() on the passed in tap event.
*
* Returns a promise which is resolved when the popup is closed. Has an additional close function, which can be used to programmatically close the popup.
*
* @param options The options for the new popup
*/
show(options: IPopupOptions): ng.IPromise<any>;
/**
* Show a simple alert popup with a message and one button that the user can tap to close the popup.
*
* Returns a promise which is resolved when the popup is closed. Has one additional function close, which can be called with any value to programmatically close the popup with the given value.
*
* @param options The options for showing the alert
*/
alert(options: IPopupAlertOptions): ng.IPromise<any>;
/**
* Show a simple confirm popup with a Cancel and OK button.
* Resolves the promise with true if the user presses the OK button, and false if the user presses the Cancel button.
*
* Returns a promise which is resolved when the popup is closed. Has one additional function close, which can be called with any value to programmatically close the popup with the given value.
*
* @parma options The options for showing the confirm popup
*/
confirm(options: IPopupConfirmOptions): ng.IPromise<any>;
/**
* Show a simple prompt popup, which has an input, OK button, and Cancel button. Resolves the promise with the value of the input if the user presses OK, and with undefined if the user presses Cancel.
*
* Returns a promise which is resolved when the popup is closed. Has one additional function close, which can be called with any value to programmatically close the popup with the given value.
*
* @param options The options for showing the prompt popup
*/
prompt(options: IPopupPromptOptions): ng.IPromise<any>;
}
//#endregion
//#region Scroll
interface IScrollPosition
{
/**
* The distance the user has scrolled from the left (starts at 0)
*/
left: number;
/**
* The distance the user has scrolled from the top (starts at 0)
*/
top: number;
}
/**
* Angular service: $ionicScrollDelegate
*
* Delegate for controlling scrollViews (created by ionContent and ionScroll directives).
* Methods called directly on the $ionicScrollDelegate service will control all scroll views. Use the $getByHandle method to control specific scrollViews.
*/
interface IScrollDelegate
{
/**
* Tell the scrollView to recalculate the size of its container
*/
resize(): void;
/**
* @param shouldAnimate Whether the scroll should animate
*/
scrollTop(shouldAnimate?: boolean): void;
/**
* @param shouldAnimate Whether the scroll should animate
*/
scrollBottom(shouldAnimate?: boolean): void;
/**
* @param left The x-value to scroll to
* @param top The y-value to scroll to
* @param shouldAnimate Whether the scroll should animate
*/
scrollTo(left: number, top: number, shouldAnimate?: boolean): void;
/**
* @param left The x-offset to scroll by
* @param top The y-offset to scroll by
* @param shouldAnimate Whether the scroll should animate
*/
scrollBy(left: number, top: number, shouldAnimate?: boolean): void;
/**
* @param level Level to zoom to
* @param animate Whether to animate the zoom
* @param originLeft Zoom in at given left coordinate
* @param originTop Zoom in at given top coordinate
*/
zoomTo(level: number, animate?: boolean, originLeft?: number, originTop?: number): void;
/**
* @param factor The factor to zoom by
* @param animate Whether to animate the zoom
* @param originLeft Zoom in at given left coordinate
* @param originTop Zoom in at given top coordinate
*/
zoomBy(factor: number, animate?: boolean, originLeft?: number, originTop?: number): void;
/**
* Returns the scroll position of this view
*/
getScrollPosition(): IScrollPosition;
/**
* Tell the scrollView to scroll to the element with an id matching window.location.hash
* If no matching element is found, it will scroll to top
*
* @param shouldAnimate Whether the scroll should animate
*/
anchorScroll(shouldAnimate?: boolean): void;
/**
* Returns the scrollView associated with this delegate.
*/
// TODO: define ScrollView object
getScrollView(): any;
/**
* Stop remembering the scroll position for this scrollView
*/
forgetScrollPosition(): void;
/**
* If this scrollView has an id associated with its scroll position, (through calling rememberScrollPosition), and that position is remembered, load the position and scroll to it.
*
* @param shouldAnimate Whether the scroll should animate
*/
scrollToRememberedPosition(shouldAnimate?: boolean): void;
/**
* Return a delegate instance that controls only the scrollViews with delegate-handle matching the given handle.
*/
$getByHandle(handle: string): IScrollDelegate;
}
//#endregion
//#region Side Menus
/**
* Angular service: $ionicSideMenuDelegate
*
* Delegate for controlling the ionSideMenus directive.
* Methods called directly on the $ionicSideMenuDelegate service will control all side menus. Use the $getByHandle method to control specific ionSideMenus instances.
*/
interface ISideMenuDelegate
{
/**
* Toggle the left side menu (if it exists).
*
* @param isOpen Whether to open or close the menu. Default: Toggles the menu.
*/
toggleLeft(isOpen?: boolean): void;
/**
* Toggle the right side menu (if it exists).
*
* @param isOpen Whether to open or close the menu. Default: Toggles the menu.
*/
toggleRight(isOpen?: boolean): void;
/**
* Gets the ratio of open amount over menu width. For example, a menu of width 100 that is opened by 50 pixels is 50% opened, and would return a ratio of 0.5.
* Returns 0 if nothing is open, between 0 and 1 if left menu is opened/opening, and between 0 and -1 if right menu is opened/opening.
*/
getOpenRatio(): number;
/**
* Returns whether either the left or right menu is currently opened.
*/
isOpen(): boolean;
/**
* Returns whether the left menu is currently opened.
*/
isOpenLeft(): boolean;
/**
* Returns whether the right menu is currently opened.
*/
isOpenRight(): boolean;
/**
* Returns whether the content can be dragged to open side menus.
*
* @param canDrag Set whether the content can or cannot be dragged to open side menus
*/
canDragContent(canDrag?: boolean): boolean;
/**
* Returns whether the drag can start only from within the edge of screen threshold.
*
* @param value Set whether the content drag can only start if it is below a certain threshold distance from the edge of the screen. If a non-zero number is given, that many pixels is used as the maximum allowed distance from the edge that starts dragging the side menu. If 0 is given, the edge drag threshold is disabled, and dragging from anywhere on the content is allowed.
*/
edgeDragThreshold(value: boolean): boolean;
/**
* Returns whether the drag can start only from within the edge of screen threshold.
*
* @param value Set whether the content drag can only start if it is below a certain threshold distance from the edge of the screen. If true is given, the default number of pixels (25) is used as the maximum allowed distance. If false is given, the edge drag threshold is disabled, and dragging from anywhere on the content is allowed.
*/
edgeDragThreshold(value: number): boolean;
/**
* Return a delegate instance that controls only the ionSideMenus directives with delegate-handle matching the given handle.
*/
$getByHandle(handle: string): ISideMenuDelegate;
}
//#endregion
//#region Slide Box
/**
* Angular service: $ionicSlideBoxDelegate
*
* Delegate that controls the ionSlideBox directive.
* Methods called directly on the $ionicSlideBoxDelegate service will control all slide boxes. Use the $getByHandle method to control specific slide box instances.
*/
interface ISlideBoxDelegate
{
/**
* Update the slidebox (for example if using Angular with ng-repeat, resize it for the elements inside).
*/
update(): void;
/**
* @param to The index to slide to
* @param speed The number of milliseconds for the change to take
*/
slide(to: number, speed?: number): void;
/**
* Returns whether sliding is enabled.
*
* @param shouldEnable Whether to enable sliding the slidebox.
*/
enableSlide(shouldEnable?: boolean): boolean;
/**
* Go to the previous slide. Wraps around if at the beginning.
*/
previous(): void;
/**
* Go to the next slide. Wraps around if at the end.
*/
next(): void;
/**
* Stop sliding. The slideBox will not move again until explicitly told to do so.
*/
stop(): void;
/**
* Start sliding again if the slideBox was stopped.
*/
start(): void;
/**
* Returns the index of the current slide.
*/
currentIndex(): number;
/**
* Returns the number of slides there are currently.
*/
slidesCount(): number;
/**
* Returns a delegate instance that controls only the ionSlideBox directives with delegate-handle matching the given handle.
*/
$getByHandle(handle: string): ISlideBoxDelegate;
}
//#endregion
//#region Tabs
interface ITabsDelegate
{
/**
* Select the tab matching the given index.
*
* @param index Index of the tab to select.
*/
select(index: number): void;
/**
* Returns the index of the selected tab, or -1.
*/
selectedIndex(): number;
/**
* Return delegate instance that controls only the ionTabs directives with delegate-handle matching the given handle.
*/
$getByHandle(handle: string): ITabsDelegate;
}
//#endregion
} | the_stack |
/*
Using the same promise polyfill that is used in qunit@2.14.0 (see https://git.io/JtMxC).
https://github.com/taylorhakes/promise-polyfill/tree/8.2.0
Copyright 2014 Taylor Hakes
Copyright 2014 Forbes Lindesay
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-------
Patches from promise-polyfill@8.2.0 for use in QUnit:
- 2021-01-09: Export as module only, don't change global scope as QUnit must not
affect the host context (e.g. people may test their application intentionally
with different or no polyfills and we must not affect that).
- 2021-01-10: Avoid unconditional reference to setTimeout, which isn't supported
on SpiderMonkey (mozjs 68). Done by re-arranging the code so that we return early
(it has native support for Promise), instead of building an unused polyfill.
- 2021-01-10: Add 'globalThis' to globalNS implementation to support SpiderMonkey.
*/
export default (function () {
'use strict';
/** @suppress {undefinedVars} */
let globalNS = (function () {
// the only reliable means to get the global object is
// `Function('return this')()`
// However, this causes CSP violations in Chrome apps.
if (typeof globalThis !== 'undefined') {
return globalThis;
}
if (typeof self !== 'undefined') {
return self;
}
if (typeof window !== 'undefined') {
return window;
}
if (typeof global !== 'undefined') {
return global;
}
throw new Error('unable to locate global object');
})();
// Expose the polyfill if Promise is undefined or set to a
// non-function value. The latter can be due to a named HTMLElement
// being exposed by browsers for legacy reasons.
// https://github.com/taylorhakes/promise-polyfill/issues/114
if (typeof globalNS['Promise'] === 'function') {
return globalNS['Promise'];
}
/**
* @this {Promise}
*/
function finallyConstructor(callback) {
let constructor = this.constructor;
return this.then(
function (value) {
// @ts-ignore
return constructor.resolve(callback()).then(function () {
return value;
});
},
function (reason) {
// @ts-ignore
return constructor.resolve(callback()).then(function () {
// @ts-ignore
return constructor.reject(reason);
});
}
);
}
function allSettled(arr) {
let P = this;
return new P(function (resolve, reject) {
if (!(arr && typeof arr.length !== 'undefined')) {
return reject(
new TypeError(
typeof arr +
' ' +
arr +
' is not iterable(cannot read property Symbol(Symbol.iterator))'
)
);
}
let args = Array.prototype.slice.call(arr);
if (args.length === 0) return resolve([]);
let remaining = args.length;
function res(i, val) {
if (val && (typeof val === 'object' || typeof val === 'function')) {
let then = val.then;
if (typeof then === 'function') {
then.call(
val,
function (val) {
res(i, val);
},
function (e) {
args[i] = { status: 'rejected', reason: e };
if (--remaining === 0) {
resolve(args);
}
}
);
return;
}
}
args[i] = { status: 'fulfilled', value: val };
if (--remaining === 0) {
resolve(args);
}
}
for (let i = 0; i < args.length; i++) {
res(i, args[i]);
}
});
}
// Store setTimeout reference so promise-polyfill will be unaffected by
// other code modifying setTimeout (like sinon.useFakeTimers())
let setTimeoutFunc = setTimeout;
function isArray(x) {
return Boolean(x && typeof x.length !== 'undefined');
}
function noop() {}
// Polyfill for Function.prototype.bind
function bind(fn, thisArg) {
return function () {
fn.apply(thisArg, arguments);
};
}
/**
* @constructor
* @param {Function} fn
*/
function Promise(fn) {
if (!(this instanceof Promise))
throw new TypeError('Promises must be constructed via new');
if (typeof fn !== 'function') throw new TypeError('not a function');
/** @type {!number} */
this._state = 0;
/** @type {!boolean} */
this._handled = false;
/** @type {Promise|undefined} */
this._value = undefined;
/** @type {!Array<!Function>} */
this._deferreds = [];
doResolve(fn, this);
}
function handle(self, deferred) {
while (self._state === 3) {
self = self._value;
}
if (self._state === 0) {
self._deferreds.push(deferred);
return;
}
self._handled = true;
Promise._immediateFn(function () {
let cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
if (cb === null) {
(self._state === 1 ? resolve : reject)(deferred.promise, self._value);
return;
}
let ret;
try {
ret = cb(self._value);
} catch (e) {
reject(deferred.promise, e);
return;
}
resolve(deferred.promise, ret);
});
}
function resolve(self, newValue) {
try {
// Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
if (newValue === self)
throw new TypeError('A promise cannot be resolved with itself.');
if (
newValue &&
(typeof newValue === 'object' || typeof newValue === 'function')
) {
let then = newValue.then;
if (newValue instanceof Promise) {
self._state = 3;
self._value = newValue;
finale(self);
return;
} else if (typeof then === 'function') {
doResolve(bind(then, newValue), self);
return;
}
}
self._state = 1;
self._value = newValue;
finale(self);
} catch (e) {
reject(self, e);
}
}
function reject(self, newValue) {
self._state = 2;
self._value = newValue;
finale(self);
}
function finale(self) {
if (self._state === 2 && self._deferreds.length === 0) {
Promise._immediateFn(function () {
if (!self._handled) {
Promise._unhandledRejectionFn(self._value);
}
});
}
for (let i = 0, len = self._deferreds.length; i < len; i++) {
handle(self, self._deferreds[i]);
}
self._deferreds = null;
}
/**
* @constructor
*/
function Handler(onFulfilled, onRejected, promise) {
this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
this.onRejected = typeof onRejected === 'function' ? onRejected : null;
this.promise = promise;
}
/**
* Take a potentially misbehaving resolver function and make sure
* onFulfilled and onRejected are only called once.
*
* Makes no guarantees about asynchrony.
*/
function doResolve(fn, self) {
let done = false;
try {
fn(
function (value) {
if (done) return;
done = true;
resolve(self, value);
},
function (reason) {
if (done) return;
done = true;
reject(self, reason);
}
);
} catch (ex) {
if (done) return;
done = true;
reject(self, ex);
}
}
Promise.prototype['catch'] = function (onRejected) {
return this.then(null, onRejected);
};
Promise.prototype.then = function (onFulfilled, onRejected) {
// @ts-ignore
let prom = new this.constructor(noop);
handle(this, new Handler(onFulfilled, onRejected, prom));
return prom;
};
Promise.prototype['finally'] = finallyConstructor;
Promise.all = function (arr) {
return new Promise(function (resolve, reject) {
if (!isArray(arr)) {
return reject(new TypeError('Promise.all accepts an array'));
}
let args = Array.prototype.slice.call(arr);
if (args.length === 0) return resolve([]);
let remaining = args.length;
function res(i, val) {
try {
if (val && (typeof val === 'object' || typeof val === 'function')) {
let then = val.then;
if (typeof then === 'function') {
then.call(
val,
function (val) {
res(i, val);
},
reject
);
return;
}
}
args[i] = val;
if (--remaining === 0) {
resolve(args);
}
} catch (ex) {
reject(ex);
}
}
for (let i = 0; i < args.length; i++) {
res(i, args[i]);
}
});
};
Promise.allSettled = allSettled;
Promise.resolve = function (value) {
if (value && typeof value === 'object' && value.constructor === Promise) {
return value;
}
return new Promise(function (resolve) {
resolve(value);
});
};
Promise.reject = function (value) {
return new Promise(function (_resolve, reject) {
reject(value);
});
};
Promise.race = function (arr) {
return new Promise(function (resolve, reject) {
if (!isArray(arr)) {
return reject(new TypeError('Promise.race accepts an array'));
}
for (let i = 0, len = arr.length; i < len; i++) {
Promise.resolve(arr[i]).then(resolve, reject);
}
});
};
// Use polyfill for setImmediate for performance gains
Promise._immediateFn =
// @ts-ignore
(typeof setImmediate === 'function' &&
function (fn) {
// @ts-ignore
setImmediate(fn);
}) ||
function (fn) {
setTimeoutFunc(fn, 0);
};
Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
if (typeof console !== 'undefined' && console) {
console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console
}
};
return Promise;
})(); | the_stack |
import { Event, EventProcessor } from '@sentry/types';
import { InboundFilters, InboundFiltersOptions } from '../../../src/integrations/inboundfilters';
/**
* Creates an instance of the InboundFilters integration and returns
* the event processor that the InboundFilters integration creates.
*
* To test the InboundFilters integration, call this function and assert on
* how the event processor handles an event. For example, if you set up the
* InboundFilters to filter out an SOME_EXCEPTION_EVENT.
*
* ```
* // some options that cause SOME_EXCEPTION_EVENT to be filtered
* const eventProcessor = createInboundFiltersEventProcessor(options);
*
* expect(eventProcessor(SOME_EXCEPTION_EVENT)).toBe(null);
* ```
*
* @param options options passed into the InboundFilters integration
* @param clientOptions options passed into the mock Sentry client
*/
function createInboundFiltersEventProcessor(
options: Partial<InboundFiltersOptions> = {},
clientOptions: Partial<InboundFiltersOptions> = {},
): EventProcessor {
const eventProcessors: EventProcessor[] = [];
const inboundFiltersInstance = new InboundFilters(options);
function addGlobalEventProcessor(processor: EventProcessor): void {
eventProcessors.push(processor);
expect(eventProcessors).toHaveLength(1);
}
function getCurrentHub(): any {
return {
getIntegration(_integration: any): any {
// pretend integration is enabled
return inboundFiltersInstance;
},
getClient(): any {
return {
getOptions: () => clientOptions,
};
},
};
}
inboundFiltersInstance.setupOnce(addGlobalEventProcessor, getCurrentHub);
return eventProcessors[0];
}
// Fixtures
const MESSAGE_EVENT: Event = {
message: 'captureMessage',
};
const MESSAGE_EVENT_2: Event = {
message: 'captureMessageSomething',
};
const MESSAGE_EVENT_WITH_STACKTRACE: Event = {
message: 'wat',
exception: {
values: [
{
stacktrace: {
// Frames are always in the reverse order, as this is how Sentry expect them to come.
// Frame that crashed is the last one, the one from awesome-analytics
frames: [
{ filename: 'https://our-side.com/js/bundle.js' },
{ filename: 'https://our-side.com/js/bundle.js' },
{ filename: 'https://awesome-analytics.io/some/file.js' },
],
},
},
],
},
};
const MESSAGE_EVENT_WITH_ANON_LAST_FRAME: Event = {
message: 'any',
exception: {
values: [
{
stacktrace: {
frames: [
{ filename: 'https://our-side.com/js/bundle.js' },
{ filename: 'https://awesome-analytics.io/some/file.js' },
{ filename: '<anonymous>' },
],
},
},
],
},
};
const MESSAGE_EVENT_WITH_NATIVE_LAST_FRAME: Event = {
message: 'any',
exception: {
values: [
{
stacktrace: {
frames: [
{ filename: 'https://our-side.com/js/bundle.js' },
{ filename: 'https://awesome-analytics.io/some/file.js' },
{ filename: '[native code]' },
],
},
},
],
},
};
const EXCEPTION_EVENT: Event = {
exception: {
values: [
{
type: 'SyntaxError',
value: 'unidentified ? at line 1337',
},
],
},
};
const EXCEPTION_EVENT_WITH_FRAMES: Event = {
exception: {
values: [
{
stacktrace: {
// Frames are always in the reverse order, as this is how Sentry expect them to come.
// Frame that crashed is the last one, the one from awesome-analytics
frames: [
{ filename: 'https://our-side.com/js/bundle.js' },
{ filename: 'https://our-side.com/js/bundle.js' },
{ filename: 'https://awesome-analytics.io/some/file.js' },
],
},
},
],
},
};
const SENTRY_EVENT: Event = {
exception: {
values: [
{
type: 'SentryError',
value: 'something something server connection',
},
],
},
};
const SCRIPT_ERROR_EVENT: Event = {
exception: {
values: [
{
type: '[undefined]',
value: 'Script error.',
},
],
},
};
const MALFORMED_EVENT: Event = {
exception: {
values: [
{
stacktrace: {
frames: undefined,
},
},
],
},
};
describe('InboundFilters', () => {
describe('_isSentryError', () => {
it('should work as expected', () => {
const eventProcessor = createInboundFiltersEventProcessor();
expect(eventProcessor(MESSAGE_EVENT, {})).toBe(MESSAGE_EVENT);
expect(eventProcessor(EXCEPTION_EVENT, {})).toBe(EXCEPTION_EVENT);
expect(eventProcessor(SENTRY_EVENT, {})).toBe(null);
});
it('should be configurable', () => {
const eventProcessor = createInboundFiltersEventProcessor({ ignoreInternal: false });
expect(eventProcessor(MESSAGE_EVENT, {})).toBe(MESSAGE_EVENT);
expect(eventProcessor(EXCEPTION_EVENT, {})).toBe(EXCEPTION_EVENT);
expect(eventProcessor(SENTRY_EVENT, {})).toBe(SENTRY_EVENT);
});
});
describe('ignoreErrors', () => {
it('string filter with partial match', () => {
const eventProcessor = createInboundFiltersEventProcessor({
ignoreErrors: ['capture'],
});
expect(eventProcessor(MESSAGE_EVENT, {})).toBe(null);
});
it('string filter with exact match', () => {
const eventProcessor = createInboundFiltersEventProcessor({
ignoreErrors: ['captureMessage'],
});
expect(eventProcessor(MESSAGE_EVENT, {})).toBe(null);
});
it('regexp filter with partial match', () => {
const eventProcessor = createInboundFiltersEventProcessor({
ignoreErrors: [/capture/],
});
expect(eventProcessor(MESSAGE_EVENT, {})).toBe(null);
});
it('regexp filter with exact match', () => {
const eventProcessor = createInboundFiltersEventProcessor({
ignoreErrors: [/^captureMessage$/],
});
expect(eventProcessor(MESSAGE_EVENT, {})).toBe(null);
expect(eventProcessor(MESSAGE_EVENT_2, {})).toBe(MESSAGE_EVENT_2);
});
it('prefers message when both message and exception are available', () => {
const eventProcessor = createInboundFiltersEventProcessor({
ignoreErrors: [/captureMessage/],
});
const event = {
...EXCEPTION_EVENT,
...MESSAGE_EVENT,
};
expect(eventProcessor(event, {})).toBe(null);
});
it('can use multiple filters', () => {
const eventProcessor = createInboundFiltersEventProcessor({
ignoreErrors: ['captureMessage', /SyntaxError/],
});
expect(eventProcessor(MESSAGE_EVENT, {})).toBe(null);
expect(eventProcessor(EXCEPTION_EVENT, {})).toBe(null);
});
it('uses default filters', () => {
const eventProcessor = createInboundFiltersEventProcessor();
expect(eventProcessor(SCRIPT_ERROR_EVENT, {})).toBe(null);
});
describe('on exception', () => {
it('uses exception data when message is unavailable', () => {
const eventProcessor = createInboundFiltersEventProcessor({
ignoreErrors: ['SyntaxError: unidentified ? at line 1337'],
});
expect(eventProcessor(EXCEPTION_EVENT, {})).toBe(null);
});
it('can match on exception value', () => {
const eventProcessor = createInboundFiltersEventProcessor({
ignoreErrors: [/unidentified \?/],
});
expect(eventProcessor(EXCEPTION_EVENT, {})).toBe(null);
});
it('can match on exception type', () => {
const eventProcessor = createInboundFiltersEventProcessor({
ignoreErrors: [/^SyntaxError/],
});
expect(eventProcessor(EXCEPTION_EVENT, {})).toBe(null);
});
});
});
describe('denyUrls/allowUrls', () => {
it('should filter captured message based on its stack trace using string filter', () => {
const eventProcessorDeny = createInboundFiltersEventProcessor({
denyUrls: ['https://awesome-analytics.io'],
});
expect(eventProcessorDeny(MESSAGE_EVENT_WITH_STACKTRACE, {})).toBe(null);
});
it('should allow denyUrls to take precedence', () => {
const eventProcessorBoth = createInboundFiltersEventProcessor({
allowUrls: ['https://awesome-analytics.io'],
denyUrls: ['https://awesome-analytics.io'],
});
expect(eventProcessorBoth(MESSAGE_EVENT_WITH_STACKTRACE, {})).toBe(null);
});
it('should filter captured message based on its stack trace using regexp filter', () => {
const eventProcessorDeny = createInboundFiltersEventProcessor({
denyUrls: [/awesome-analytics\.io/],
});
expect(eventProcessorDeny(MESSAGE_EVENT_WITH_STACKTRACE, {})).toBe(null);
});
it('should not filter captured messages with no stacktraces', () => {
const eventProcessor = createInboundFiltersEventProcessor({
denyUrls: ['https://awesome-analytics.io'],
});
expect(eventProcessor(MESSAGE_EVENT, {})).toBe(MESSAGE_EVENT);
});
it('should filter captured exception based on its stack trace using string filter', () => {
const eventProcessor = createInboundFiltersEventProcessor({
denyUrls: ['https://awesome-analytics.io'],
});
expect(eventProcessor(EXCEPTION_EVENT_WITH_FRAMES, {})).toBe(null);
});
it('should filter captured exception based on its stack trace using regexp filter', () => {
const eventProcessor = createInboundFiltersEventProcessor({
denyUrls: [/awesome-analytics\.io/],
});
expect(eventProcessor(EXCEPTION_EVENT_WITH_FRAMES, {})).toBe(null);
});
it("should not filter events that don't match the filtered values", () => {
const eventProcessor = createInboundFiltersEventProcessor({
denyUrls: ['some-other-domain.com'],
});
expect(eventProcessor(EXCEPTION_EVENT_WITH_FRAMES, {})).toBe(EXCEPTION_EVENT_WITH_FRAMES);
});
it('should be able to use multiple filters', () => {
const eventProcessor = createInboundFiltersEventProcessor({
denyUrls: ['some-other-domain.com', /awesome-analytics\.io/],
});
expect(eventProcessor(EXCEPTION_EVENT_WITH_FRAMES, {})).toBe(null);
});
it('should not fail with malformed event event', () => {
const eventProcessor = createInboundFiltersEventProcessor({
denyUrls: ['https://awesome-analytics.io'],
});
expect(eventProcessor(MALFORMED_EVENT, {})).toBe(MALFORMED_EVENT);
});
it('should search for script names when there is an anonymous callback at the last frame', () => {
const eventProcessor = createInboundFiltersEventProcessor({
denyUrls: ['https://awesome-analytics.io/some/file.js'],
});
expect(eventProcessor(MESSAGE_EVENT_WITH_ANON_LAST_FRAME, {})).toBe(null);
});
it('should search for script names when the last frame is from native code', () => {
const eventProcessor = createInboundFiltersEventProcessor({
denyUrls: ['https://awesome-analytics.io/some/file.js'],
});
expect(eventProcessor(MESSAGE_EVENT_WITH_NATIVE_LAST_FRAME, {})).toBe(null);
});
});
}); | the_stack |
import nock from 'nock';
import path from 'path';
import fs from 'fs';
import Assets from '../src/assets';
import { AssetIDResponse, Asset } from '../src/interfaces';
describe('Teraslice Assets', () => {
let assets: Assets;
let scope: nock.Scope;
beforeEach(() => {
assets = new Assets({
baseUrl: 'http://teraslice.example.dev'
});
scope = nock('http://teraslice.example.dev/v1');
});
afterEach(() => {
nock.cleanAll();
});
const date = new Date();
const assetVersion1: Asset = {
id: 'someId',
version: '1.0',
name: 'iAmAnAsset',
_created: date.toISOString()
};
const assetVersion2: Asset = {
id: 'someId',
version: '2.0',
name: 'iAmAnAsset',
_created: new Date(date.getTime() + 500000).toISOString()
};
describe('->upload', () => {
describe('when called with nothing', () => {
it('should reject with asset stream validation error', async () => {
expect.hasAssertions();
try {
// @ts-expect-error
await assets.upload();
} catch (err) {
expect(err.message).toEqual('Asset stream must not be empty');
}
});
});
describe('when called with a string', () => {
const contents = 'example-input';
const idResponse: AssetIDResponse = { _id: 'some-asset-id' };
beforeEach(async () => {
scope.post('/assets', contents)
.reply(200, idResponse);
});
it('should resolve the json result from Teraslice', async () => {
const results = await assets.upload(contents);
expect(results).toEqual(idResponse);
});
});
describe('when called with a stream', () => {
const testFilePath = path.join(__dirname, 'fixtures', 'test.txt');
const contents = fs.readFileSync(testFilePath, 'utf-8');
const idResponse: AssetIDResponse = { _id: 'some-asset-id' };
beforeEach(() => {
scope.post('/assets', (body) => contents === body)
.reply(200, idResponse);
});
it('should resolve the json result from Teraslice', async () => {
const stream = fs.createReadStream(testFilePath);
const results = await assets.upload(stream);
expect(results).toEqual(idResponse);
});
});
});
describe('->list', () => {
const assetList: Asset[] = [
assetVersion1,
assetVersion2
];
describe('when called without any options', () => {
beforeEach(() => {
scope.get('/assets')
.reply(200, assetList);
});
it('should resolve the json result from Teraslice', async () => {
const results = await assets.list();
expect(results).toEqual(assetList);
});
});
describe('when called with search query', () => {
const queryParams = { size: 10, from: 2, sort: '_updated:desc' };
beforeEach(() => {
scope.get('/assets')
.query(queryParams)
.reply(200, assetList);
});
it('should resolve the json result from Teraslice', async () => {
const results = await assets.list(queryParams);
expect(results).toEqual(assetList);
});
});
describe('when called with search query and options', () => {
const queryParams = { size: 10, from: 2, sort: '_updated:desc' };
const searchOptions = { headers: { 'Some-Header': 'yes' } };
beforeEach(() => {
scope.get('/assets')
.matchHeader('Some-Header', 'yes')
.query(queryParams)
.reply(200, assetList);
});
it('should resolve the json result from Teraslice', async () => {
const results = await assets.list(queryParams, searchOptions);
expect(results).toEqual(assetList);
});
});
});
describe('->getAsset', () => {
describe('when called without any arguments', () => {
it('should throw', async () => {
expect.hasAssertions();
try {
// @ts-expect-error
await assets.getAsset();
} catch (err) {
expect(err.message).toEqual('Name is required, and must be of type string');
}
});
});
describe('when called name as anything but string', () => {
it('should throw', async () => {
expect.hasAssertions();
try {
// @ts-expect-error
await assets.getAsset(1234);
} catch (err) {
expect(err.message).toEqual('Name is required, and must be of type string');
}
});
});
describe('when called with asset name', () => {
const { name } = assetVersion1;
beforeEach(() => {
scope.get(`/assets/${name}`)
.reply(200, assetVersion1);
});
it('should resolve the json result from Teraslice', async () => {
const results = await assets.getAsset(name);
expect(results).toEqual(assetVersion1);
});
});
describe('when called with asset name and version', () => {
const { name } = assetVersion1;
const { version } = assetVersion1;
beforeEach(() => {
scope.get(`/assets/${name}/${version}`)
.reply(200, assetVersion1);
});
it('should resolve the json result from Teraslice', async () => {
const results = await assets.getAsset(name, version);
expect(results).toEqual(assetVersion1);
});
});
describe('when called name and version as anything but string', () => {
it('should throw', async () => {
expect.hasAssertions();
try {
// @ts-expect-error
await assets.getAsset('someName', { some: 'thing' });
} catch (err) {
expect(err.message).toEqual('Version if provided must be of type string');
}
});
});
describe('when called with asset name, version and options', () => {
const searchOptions = { headers: { 'Some-Header': 'yes' } };
const { name } = assetVersion1;
const { version } = assetVersion1;
beforeEach(() => {
scope.get(`/assets/${name}/${version}`)
.matchHeader('Some-Header', 'yes')
.reply(200, assetVersion1);
});
it('should resolve the json result from Teraslice', async () => {
const results = await assets.getAsset(name, version, searchOptions);
expect(results).toEqual(assetVersion1);
});
});
});
describe('->txt', () => {
const fakeTxtData = JSON.stringify(assetVersion1);
beforeEach(() => {
scope = nock('http://teraslice.example.dev/');
});
describe('when called without any arguments', () => {
beforeEach(() => {
scope.get('/txt/assets')
.reply(200, fakeTxtData);
});
it('should resolve with txt', async () => {
const results = await assets.txt();
expect(results).toEqual(fakeTxtData);
});
});
describe('when called name as anything but string', () => {
it('should throw', async () => {
expect.hasAssertions();
try {
// @ts-expect-error
await assets.txt(1234);
} catch (err) {
expect(err.message).toEqual('Name must be of type string');
}
});
});
describe('when called with asset name', () => {
const { name } = assetVersion1;
beforeEach(() => {
scope.get(`/txt/assets/${name}`)
.reply(200, fakeTxtData);
});
it('should resolve the json result from Teraslice', async () => {
const results = await assets.txt(name);
expect(results).toEqual(fakeTxtData);
});
});
describe('when called with asset name and version', () => {
const { name } = assetVersion1;
const { version } = assetVersion1;
beforeEach(() => {
scope.get(`/txt/assets/${name}/${version}`)
.reply(200, fakeTxtData);
});
it('should resolve the json result from Teraslice', async () => {
const results = await assets.txt(name, version);
expect(results).toEqual(fakeTxtData);
});
});
describe('when called name and version as anything but string', () => {
it('should throw', async () => {
expect.hasAssertions();
try {
// @ts-expect-error
await assets.txt('someName', { some: 'thing' });
} catch (err) {
expect(err.message).toEqual('Version must be of type string');
}
});
});
describe('when called with asset name, version and options', () => {
const { name } = assetVersion1;
const { version } = assetVersion1;
const queryParams = { size: 10, from: 2, sort: '_updated:desc' };
beforeEach(() => {
scope.get(`/txt/assets/${name}/${version}`)
.query(queryParams)
.reply(200, fakeTxtData);
});
it('should resolve the json result from Teraslice', async () => {
const results = await assets.txt(name, version, queryParams);
expect(results).toEqual(fakeTxtData);
});
});
describe('when called with asset name, version and options and request options', () => {
const searchOptions = { headers: { 'Some-Header': 'yes' } };
const queryParams = { size: 10, from: 2, sort: '_updated:desc' };
const { name } = assetVersion1;
const { version } = assetVersion1;
beforeEach(() => {
scope.get(`/txt/assets/${name}/${version}`)
.query(queryParams)
.matchHeader('Some-Header', 'yes')
.reply(200, fakeTxtData);
});
it('should resolve the json result from Teraslice', async () => {
const results = await assets.txt(name, version, queryParams, searchOptions);
expect(results).toEqual(fakeTxtData);
});
});
});
describe('->remove', () => {
const idResponse: AssetIDResponse = { _id: 'someId' };
beforeEach(() => {
scope.delete('/assets/some-asset-id')
.reply(200, idResponse);
});
describe('when called with nothing', () => {
it('should reject with id validation error', async () => {
expect.hasAssertions();
try {
// @ts-expect-error
await assets.remove();
} catch (err) {
expect(err.message).toEqual('Asset delete requires a ID');
}
});
});
describe('when called an id', () => {
it('should resolve the json result from Teraslice', async () => {
const results = await assets.remove('some-asset-id');
expect(results).toEqual(idResponse);
});
});
describe('when called an id and options', () => {
const searchOptions = { headers: { some: 'header' } };
beforeEach(() => {
scope.delete('/assets/other-asset-id')
.matchHeader('some', 'header')
.reply(200, idResponse);
});
it('should resolve the json result from Teraslice', async () => {
const results = await assets.remove('other-asset-id', searchOptions);
expect(results).toEqual(idResponse);
});
});
});
}); | the_stack |
// This example implements 'dividend', a simple smart contract that will
// automatically disperse iota tokens which are sent to the contract to a group
// of member addresses according to predefined division factors. The intent is
// to showcase basic functionality of WasmLib through a minimal implementation
// and not to come up with a complete robust real-world solution.
// Note that we have drawn sometimes out constructs that could have been done
// in a single line over multiple statements to be able to properly document
// step by step what is happening in the code. We also unnecessarily annotate
// all 'let' statements with their assignment type to improve understanding.
import * as wasmlib from "wasmlib"
import * as sc from "./index";
// 'init' is used as a way to initialize a smart contract. It is an optional
// function that will automatically be called upon contract deployment. In this
// case we use it to initialize the 'owner' state variable so that we can later
// use this information to prevent non-owners from calling certain functions.
// The 'init' function takes a single optional parameter:
// - 'owner', which is the agent id of the entity owning the contract.
// When this parameter is omitted the owner will default to the contract creator.
export function funcInit(ctx: wasmlib.ScFuncContext, f: sc.InitContext): void {
// The schema tool has already created a proper InitContext for this function that
// allows us to access call parameters and state storage in a type-safe manner.
// First we set up a default value for the owner in case the optional
// 'owner' parameter was omitted.
let owner: wasmlib.ScAgentID = ctx.contractCreator();
// Now we check if the optional 'owner' parameter is present in the params map.
if (f.params.owner().exists()) {
// Yes, it was present, so now we overwrite the default owner with
// the one specified by the 'owner' parameter.
owner = f.params.owner().value();
}
// Now that we have sorted out which agent will be the owner of this contract
// we will save this value in the 'owner' variable in state storage on the host.
// Read the documentation on schema.json to understand why this state variable is
// supported at compile-time by code generated from schema.json by the schema tool.
f.state.owner().setValue(owner);
}
// 'member' is a function that can only be used by the entity that owns the
// 'dividend' smart contract. It can be used to define the group of member
// addresses and dispersal factors one by one prior to sending tokens to the
// smart contract's 'divide' function. The 'member' function takes 2 parameters,
// which are both required:
// - 'address', which is an Address to use as member in the group, and
// - 'factor', which is an Int64 relative dispersal factor associated with
// that address
// The 'member' function will save the address/factor combination in state storage
// and also calculate and store a running sum of all factors so that the 'divide'
// function can simply start using these precalculated values when called.
export function funcMember(ctx: wasmlib.ScFuncContext, f: sc.MemberContext): void {
// Note that the schema tool has already dealt with making sure that this function
// can only be called by the owner and that the required parameters are present.
// So once we get to this point in the code we can take that as a given.
// Since we are sure that the 'factor' parameter actually exists we can
// retrieve its actual value into an i64. Note that we use Rust's built-in
// data types when manipulating Int64, String, or Bytes value objects.
let factor: i64 = f.params.factor().value();
// As an extra requirement we check that the 'factor' parameter value is not
// negative. If it is, we panic out with an error message.
// Note how we avoid an if expression like this one here:
// if (factor < 0) {
// ctx.panic("negative factor");
// }
// Using the require() method instead reduces typing and enhances readability.
ctx.require(factor >= 0, "negative factor");
// Since we are sure that the 'address' parameter actually exists we can
// retrieve its actual value into an ScAddress value type.
let address: wasmlib.ScAddress = f.params.address().value();
// We will store the address/factor combinations in a key/value sub-map of the
// state storage named 'members'. The schema tool has generated an appropriately
// type-checked proxy map for us from the schema.json state storage definition.
// If there is no 'members' map present yet in state storage an empty map will
// automatically be created on the host.
let members: sc.MapAddressToMutableInt64 = f.state.members();
// Now we create an ScMutableInt64 proxy for the value stored in the 'members'
// map under the key defined by the 'address' parameter we retrieved earlier.
let currentFactor: wasmlib.ScMutableInt64 = members.getInt64(address);
// We check to see if this key/value combination exists in the 'members' map.
if (!currentFactor.exists()) {
// If it does not exist yet then we have to add this new address to the
// 'memberList' array that keeps track of all address keys used in the
// 'members' map. The schema tool has again created the appropriate type
// for us already. Here too, if the address array was not present yet it
// will automatically be created on the host.
let memberList: sc.ArrayOfMutableAddress = f.state.memberList();
// Now we will append the new address to the memberList array.
// First we determine the current length of the array.
let length: i32 = memberList.length();
// Next we create an ScMutableAddress proxy to the address value that lives
// at that index in the memberList array (no value, since we're appending).
let newAddress: wasmlib.ScMutableAddress = memberList.getAddress(length);
// And finally we append the new address to the array by telling the proxy
// to update the value it refers to with the 'address' parameter.
newAddress.setValue(address);
// Note that we could have achieved the last 3 lines of code in a single line:
// memberList.getAddress(memberList.length()).setValue(address);
}
// Create an ScMutableInt64 proxy named 'totalFactor' for an Int64 value in
// state storage. Note that we don't care whether this value exists or not,
// because WasmLib will treat it as if it has the default value of zero.
let totalFactor: wasmlib.ScMutableInt64 = f.state.totalFactor();
// Now we calculate the new running total sum of factors by first getting the
// current value of 'totalFactor' from the state storage, then subtracting the
// current value of the factor associated with the 'address' parameter, if any
// exists. Again, if the associated value doesn't exist, WasmLib will assume it
// to be zero. Finally we add the factor retrieved from the parameters,
// resulting in the new totalFactor.
let newTotalFactor: i64 = totalFactor.value() - currentFactor.value() + factor;
// Now we store the new totalFactor in the state storage.
totalFactor.setValue(newTotalFactor);
// And we also store the factor from the parameters under the address from the
// parameters in the state storage that the proxy refers to.
currentFactor.setValue(factor);
}
// 'divide' is a function that will take any iotas it receives and properly
// disperse them to the addresses in the member list according to the dispersion
// factors associated with these addresses.
// Anyone can send iota tokens to this function and they will automatically be
// divided over the member list. Note that this function does not deal with
// fractions. It simply truncates the calculated amount to the nearest lower
// integer and keeps any remaining iotas in its own account. They will be added
// to any next round of tokens received prior to calculation of the new
// dividend amounts.
export function funcDivide(ctx: wasmlib.ScFuncContext, f: sc.DivideContext): void {
// Create an ScBalances map proxy to the account balances for this
// smart contract. Note that ScBalances wraps an ScImmutableMap of
// token color/amount combinations in a simpler to use interface.
let balances: wasmlib.ScBalances = ctx.balances();
// Retrieve the amount of plain iota tokens from the account balance.
let amount: i64 = balances.balance(wasmlib.ScColor.IOTA);
// Retrieve the pre-calculated totalFactor value from the state storage.
let totalFactor: i64 = f.state.totalFactor().value();
// Get the proxy to the 'members' map in the state storage.
let members: sc.MapAddressToMutableInt64 = f.state.members();
// Get the proxy to the 'memberList' array in the state storage.
let memberList: sc.ArrayOfMutableAddress = f.state.memberList();
// Determine the current length of the memberList array.
let size: i32 = memberList.length();
// Loop through all indexes of the memberList array.
for (let i = 0; i < size; i++) {
// Retrieve the next indexed address from the memberList array.
let address: wasmlib.ScAddress = memberList.getAddress(i).value();
// Retrieve the factor associated with the address from the members map.
let factor: i64 = members.getInt64(address).value();
// Calculate the fair share of iotas to disperse to this member based on the
// factor we just retrieved. Note that the result will be truncated.
let share: i64 = amount * factor / totalFactor;
// Is there anything to disperse to this member?
if (share > 0) {
// Yes, so let's set up an ScTransfers map proxy that transfers the
// calculated amount of iotas. Note that ScTransfers wraps an
// ScMutableMap of token color/amount combinations in a simpler to use
// interface. The constructor we use here creates and initializes a
// single token color transfer in a single statement. The actual color
// and amount values passed in will be stored in a new map on the host.
let transfers: wasmlib.ScTransfers = wasmlib.ScTransfers.iotas(share);
// Perform the actual transfer of tokens from the smart contract to the
// member address. The transferToAddress() method receives the address
// value and the proxy to the new transfers map on the host, and will
// call the corresponding host sandbox function with these values.
ctx.transferToAddress(address, transfers);
}
}
}
// 'setOwner' is used to change the owner of the smart contract.
// It updates the 'owner' state variable with the provided agent id.
// The 'setOwner' function takes a single mandatory parameter:
// - 'owner', which is the agent id of the entity that will own the contract.
// Only the current owner can change the owner.
export function funcSetOwner(ctx: wasmlib.ScFuncContext, f: sc.SetOwnerContext): void {
// Note that the schema tool has already dealt with making sure that this function
// can only be called by the owner and that the required parameter is present.
// So once we get to this point in the code we can take that as a given.
// Save the new owner parameter value in the 'owner' variable in state storage.
f.state.owner().setValue(f.params.owner().value());
}
// 'getFactor' is a simple View function. It will retrieve the factor
// associated with the (mandatory) address parameter it was provided with.
export function viewGetFactor(ctx: wasmlib.ScViewContext, f: sc.GetFactorContext): void {
// Since we are sure that the 'address' parameter actually exists we can
// retrieve its actual value into an ScAddress value type.
let address: wasmlib.ScAddress = f.params.address().value();
// Create an ScImmutableMap proxy to the 'members' map in the state storage.
// Note that for views this is an *immutable* map as opposed to the *mutable*
// map we can access from the *mutable* state that gets passed to funcs.
let members: sc.MapAddressToImmutableInt64 = f.state.members();
// Retrieve the factor associated with the address parameter.
let factor: i64 = members.getInt64(address).value();
// Set the factor in the results map of the function context.
// The contents of this results map is returned to the caller of the function.
f.results.factor().setValue(factor);
}
// 'getOwner' can be used to retrieve the current owner of the dividend contract
export function viewGetOwner(ctx: wasmlib.ScViewContext, f: sc.GetOwnerContext): void {
f.results.owner().setValue(f.state.owner().value());
} | the_stack |
import {NumericAttribValue, PolyDictionary} from '../../types/GlobalTypes';
import {Vector3} from 'three/src/math/Vector3';
import {Points} from 'three/src/objects/Points';
import {Object3D} from 'three/src/core/Object3D';
import {Mesh} from 'three/src/objects/Mesh';
import {LineSegments} from 'three/src/objects/LineSegments';
import {Group} from 'three/src/objects/Group';
import {BufferGeometry} from 'three/src/core/BufferGeometry';
import {Box3} from 'three/src/math/Box3';
import {CoreObject} from './Object';
import {CoreGeometry} from './Geometry';
import {CoreAttribute} from './Attribute';
import {CoreString} from '../String';
import {CoreConstant, AttribClass, AttribSize, ObjectData, objectTypeFromConstructor} from './Constant';
import {CoreType} from '../Type';
import {ArrayUtils} from '../ArrayUtils';
import {CoreFace} from './Face';
import {Poly} from '../../engine/Poly';
export type GroupString = string;
export interface Object3DWithGeometry extends Object3D {
geometry: BufferGeometry;
}
export class CoreGroup {
// _group: Group
private _timestamp: number | undefined;
// _core_objects:
private _objects: Object3D[] = [];
private _objects_with_geo: Object3DWithGeometry[] = [];
private _core_objects: CoreObject[] | undefined;
// _geometries: BufferGeometry[];
private _core_geometries: CoreGeometry[] | undefined;
private _bounding_box: Box3 | undefined;
// private _bounding_sphere: Sphere | undefined;
constructor() {
//_group: Group){
// this._group = _group;
this.touch();
}
//
//
// TIMESTAMP
//
//
timestamp() {
return this._timestamp;
}
touch() {
const performance = Poly.performance.performanceManager();
this._timestamp = performance.now();
this.reset();
}
reset() {
this._bounding_box = undefined;
// this._bounding_sphere = undefined;
this._core_geometries = undefined;
this._core_objects = undefined;
}
//
//
// CLONE
//
//
clone() {
const core_group = new CoreGroup();
if (this._objects) {
const objects = [];
for (let object of this._objects) {
objects.push(CoreObject.clone(object));
}
core_group.setObjects(objects);
}
return core_group;
}
//
//
// OBJECTS
//
//
setObjects(objects: Object3D[]) {
this._objects = objects;
this._objects_with_geo = objects.filter((obj) => (obj as Mesh).geometry != null) as Object3DWithGeometry[];
this.touch();
}
objects() {
return this._objects;
}
objectsWithGeo() {
return this._objects_with_geo;
}
coreObjects() {
return (this._core_objects = this._core_objects || this._create_core_objects());
}
private _create_core_objects(): CoreObject[] {
// const list: CoreObject[] = [];
// if (this._objects) {
// for (let i = 0; i < this._objects.length; i++) {
// this._objects[i].traverse((object) => {
// const core_object = new CoreObject(object, i);
// list.push(core_object);
// });
// }
// }
if (this._objects) {
return this._objects.map((object, i) => new CoreObject(object, i));
}
return [];
// return list;
}
objectsData(): ObjectData[] {
if (this._objects) {
return this._objects.map((object) => this._objectData(object));
}
return [];
}
private _objectData(object: Object3D): ObjectData {
let points_count = 0;
if ((object as Mesh).geometry) {
points_count = CoreGeometry.pointsCount((object as Mesh).geometry as BufferGeometry);
}
return {
type: objectTypeFromConstructor(object.constructor),
name: object.name,
children_count: object.children.length,
points_count: points_count,
};
}
// group() {
// return this._group;
// }
// uuid() {
// return this._group.uuid;
// }
geometries(): BufferGeometry[] {
// this._geometries = [];
// for (let object of this._objects) {
// object.traverse((object) => this.__geometry_from_object.bind(this)(this._geometries, object));
// // const geometry = this.geometry_from_object(object)
// // if (geometry != null) {
// // return list.push(new CoreGeometry(geometry));
// // }
// // });
// }
// return this._geometries;
const list: BufferGeometry[] = [];
for (let core_object of this.coreObjects()) {
const geometry = (core_object.object() as Mesh).geometry as BufferGeometry;
if (geometry) {
list.push(geometry);
}
}
return list;
}
coreGeometries(): CoreGeometry[] {
return (this._core_geometries = this._core_geometries || this._createCoreGeometries());
}
private _createCoreGeometries() {
const list: CoreGeometry[] = [];
for (let geometry of this.geometries()) {
list.push(new CoreGeometry(geometry));
// object.traverse(object=> this.__core_geometry_from_object.bind(this)(this._core_geometries, object))
// const geometry = this.geometry_from_object(object)
// if (geometry != null) {
// return list.push(new CoreGeometry(geometry));
// }
// });
}
return list;
}
// __geometry_from_object(list: BufferGeometry[], object: Mesh) {
// if (object.geometry) {
// return list.push(object.geometry as BufferGeometry);
// }
// }
// __core_geometry_from_object(list, object){
// const geometry = CoreGroup.geometry_from_object(object)
// if (geometry != null) {
// return list.push(new CoreGeometry(geometry));
// }
// }
static geometryFromObject(object: Object3D): BufferGeometry | null {
if ((object as Mesh).isMesh || (object as LineSegments).isLine || (object as Points).isPoints) {
return (object as Mesh).geometry as BufferGeometry;
}
return null;
}
faces() {
const faces: CoreFace[] = [];
for (let object of this.objectsWithGeo()) {
if (object.geometry) {
const coreGeo = new CoreGeometry(object.geometry);
const geoFaces = coreGeo.faces();
for (let geoFace of geoFaces) {
geoFace.applyMatrix4(object.matrix);
faces.push(geoFace);
}
}
}
return faces;
}
points() {
return this.coreGeometries()
.map((g) => g.points())
.flat();
}
pointsCount() {
return ArrayUtils.sum(this.coreGeometries().map((g) => g.pointsCount()));
}
totalPointsCount() {
if (this._objects) {
let sum = 0;
for (let object of this._objects) {
object.traverse((object) => {
const geometry = (object as Mesh).geometry as BufferGeometry;
if (geometry) {
sum += CoreGeometry.pointsCount(geometry);
}
});
}
return sum;
} else {
return 0;
}
}
pointsFromGroup(group: GroupString) {
if (group) {
const indices = CoreString.indices(group);
const points = this.points();
return ArrayUtils.compact(indices.map((i) => points[i]));
} else {
return this.points();
}
}
static _fromObjects(objects: Object3D[]): CoreGroup {
const core_group = new CoreGroup();
core_group.setObjects(objects);
return core_group;
}
objectsFromGroup(group_name: string): Object3D[] {
return this.coreObjectsFromGroup(group_name).map((co) => co.object());
}
coreObjectsFromGroup(group_name: string): CoreObject[] {
group_name = group_name.trim();
if (group_name !== '') {
const index = parseInt(group_name);
if (!CoreType.isNaN(index)) {
return ArrayUtils.compact([this.coreObjects()[index]]);
} else {
return this.coreObjects().filter((core_object) => {
return CoreString.matchMask(group_name, core_object.name());
});
}
} else {
return this.coreObjects();
}
}
boundingBox(): Box3 {
return (this._bounding_box = this._bounding_box || this._compute_bounding_box());
}
// bounding_sphere(): Sphere {
// return (this._bounding_sphere = this._bounding_sphere || this._compute_bounding_sphere());
// }
center(): Vector3 {
const center = new Vector3();
this.boundingBox().getCenter(center);
return center;
}
size(): Vector3 {
const size = new Vector3();
this.boundingBox().getSize(size);
return size;
}
private _compute_bounding_box() {
let bbox: Box3 | undefined; // = new Box3();
if (this._objects) {
for (let object of this._objects) {
const geometry = (object as Object3DWithGeometry).geometry;
if (geometry) {
geometry.computeBoundingBox();
if (bbox) {
bbox.expandByObject(object);
} else {
if (geometry.boundingBox) {
bbox = geometry.boundingBox.clone();
}
}
}
}
}
bbox = bbox || new Box3(new Vector3(-1, -1, -1), new Vector3(+1, +1, +1));
return bbox;
}
// private _compute_bounding_sphere() {
// let sphere: Sphere | undefined; // = new Box3();
// if (this._objects) {
// for (let object of this._objects) {
// const geometry = (object as Object3DWithGeometry).geometry;
// geometry.computeBoundingSphere();
// if (sphere) {
// sphere.expandByObject(object);
// } else {
// sphere = geometry.boundingBox.clone();
// }
// }
// }
// sphere = sphere || new Sphere(new Vector3(0, 0, 0), 1);
// return sphere;
// }
computeVertexNormals() {
for (let object of this.coreObjects()) {
object.computeVertexNormals();
}
}
hasAttrib(name: string) {
let first_geometry;
if ((first_geometry = this.coreGeometries()[0]) != null) {
return first_geometry.hasAttrib(name);
} else {
return false;
}
}
attribType(name: string) {
const first_core_geometry = this.coreGeometries()[0];
if (first_core_geometry != null) {
return first_core_geometry.attribType(name);
} else {
return null;
}
}
objectAttribType(name: string) {
const first_core_object = this.coreObjects()[0];
if (first_core_object != null) {
return first_core_object.attribType(name);
} else {
return null;
}
}
renameAttrib(old_name: string, new_name: string, attrib_class: AttribClass) {
switch (attrib_class) {
case CoreConstant.ATTRIB_CLASS.VERTEX:
if (this.hasAttrib(old_name)) {
if (this._objects) {
for (let object of this._objects) {
object.traverse((child) => {
const geometry = CoreGroup.geometryFromObject(child);
if (geometry) {
const core_geometry = new CoreGeometry(geometry);
core_geometry.renameAttrib(old_name, new_name);
}
});
}
}
}
break;
case CoreConstant.ATTRIB_CLASS.OBJECT:
if (this.hasAttrib(old_name)) {
if (this._objects) {
for (let object of this._objects) {
object.traverse((child) => {
const core_object = new CoreObject(child, 0);
core_object.renameAttrib(old_name, new_name);
});
}
}
}
break;
}
}
attribNames() {
let first_geometry;
if ((first_geometry = this.coreGeometries()[0]) != null) {
return first_geometry.attribNames();
} else {
return [];
}
}
objectAttribNames() {
let first_object;
if ((first_object = this.coreObjects()[0]) != null) {
return first_object.attribNames();
} else {
return [];
}
}
attribNamesMatchingMask(masks_string: GroupString) {
const masks = CoreString.attribNames(masks_string);
const matching_attrib_names: string[] = [];
for (let attrib_name of this.attribNames()) {
for (let mask of masks) {
if (CoreString.matchMask(attrib_name, mask)) {
matching_attrib_names.push(attrib_name);
} else {
const remapped = CoreAttribute.remapName(mask);
if (attrib_name == remapped) {
matching_attrib_names.push(attrib_name);
}
}
}
}
return ArrayUtils.uniq(matching_attrib_names);
}
attribSizes() {
let first_geometry;
if ((first_geometry = this.coreGeometries()[0]) != null) {
return first_geometry.attribSizes();
} else {
return {};
}
}
objectAttribSizes(): PolyDictionary<AttribSize> {
let first_object;
if ((first_object = this.coreObjects()[0]) != null) {
return first_object.attribSizes();
} else {
return {};
}
}
attribSize(attrib_name: string) {
let first_geometry;
if ((first_geometry = this.coreGeometries()[0]) != null) {
return first_geometry.attribSize(attrib_name);
} else {
return 0;
}
}
addNumericVertexAttrib(name: string, size: number, default_value: NumericAttribValue) {
if (default_value == null) {
default_value = CoreAttribute.default_value(size);
}
for (let core_geometry of this.coreGeometries()) {
core_geometry.addNumericAttrib(name, size, default_value);
}
}
// add_numeric_object_attrib(name: string, size: number, default_value: NumericAttribValue) {
// if (default_value == null) {
// default_value = CoreAttribute.default_value(size);
// }
// for (let core_object of this.coreObjects()) {
// core_object.addNumericAttrib(name, default_value);
// }
// }
static clone(src_group: Group) {
const new_group = new Group();
src_group.children.forEach((src_object) => {
const new_object = CoreObject.clone(src_object);
new_group.add(new_object);
});
return new_group;
}
} | the_stack |
import { PlanStatus, PlanValidation, PlanSecurityType, PlanType } from '@model/plan';
import { ApiImportFakers } from '@fakers/api-imports';
import {
deleteApi,
exportApi,
getApiById,
getApiMembers,
getApiMetadata,
importCreateApi,
importUpdateApi,
} from '@commands/management/api-management-commands';
import { ADMIN_USER } from '@fakers/users/users';
import { ApiMetadataFormat, ApiPageType, ApiPrimaryOwnerType, ApiVisibility } from '@model/apis';
import { getPage, getPages } from '@commands/management/api-pages-management-commands';
import { createUser, deleteUser } from '@commands/management/user-management-commands';
import { createRole, deleteRole } from '@commands/management/organization-configuration-management-commands';
import { getPlans } from '@commands/management/api-plans-management-commands';
import { GroupFakers } from '@fakers/groups';
import { createGroup, deleteGroup, getGroup } from '@commands/management/environment-management-commands';
context('API - Imports - Update', () => {
describe('Update API from import', () => {
describe('Update API which ID in URL does not exist', () => {
const api = ApiImportFakers.api({ id: 'unknown-test-id' });
it('should fail to update API, returning 404', () => {
importUpdateApi(ADMIN_USER, 'unknown-test-id', api)
.notFound()
.should((response) => {
expect(response.body.message).to.eq('Api [unknown-test-id] can not be found.');
});
});
});
describe('Update API which ID in URL exists, without ID in body', () => {
const apiId = '67d8020e-b0b3-47d8-9802-0eb0b357d84c';
const fakeCreateApi = ApiImportFakers.api({ id: apiId });
// update API data. body doesn't contains API id
const fakeUpdateApi = ApiImportFakers.api({
name: 'updatedName',
version: '1.1',
description: 'Updated API description',
visibility: ApiVisibility.PUBLIC,
});
fakeUpdateApi.proxy.virtual_hosts[0].path = '/updated/path';
it('should create API with the specified ID', () => {
importCreateApi(ADMIN_USER, fakeCreateApi)
.ok()
.should((response) => {
expect(response.body.id).to.eq(apiId);
});
});
it('should update the API with the specified ID, even if no ID in body', () => {
importUpdateApi(ADMIN_USER, apiId, fakeUpdateApi)
.ok()
.should((response) => {
expect(response.body.id).to.eq(apiId);
});
});
it('should get updated API with updated data', () => {
getApiById(ADMIN_USER, apiId)
.ok()
.should((response) => {
expect(response.body.id).to.eq(apiId);
expect(response.body.name).to.eq('updatedName');
expect(response.body.version).to.eq('1.1');
expect(response.body.description).to.eq('Updated API description');
expect(response.body.visibility).to.eq('PUBLIC');
expect(response.body.proxy.virtual_hosts[0].path).to.eq('/updated/path');
});
});
it('should delete created API', () => {
deleteApi(ADMIN_USER, apiId).noContent();
});
});
describe('Update API which ID in URL exists, with another API ID in body', () => {
const apiId1 = '67d8020e-b0b3-47d8-9802-0eb0b357d84c';
const fakeCreateApi1 = ApiImportFakers.api({ id: apiId1, name: 'originalName' });
const apiId2 = '67d8020e-b0b3-47d8-9802-0eb0b357d899';
const fakeCreateApi2 = ApiImportFakers.api({ id: apiId2, name: 'originalName' });
// that will update api2, with api1 id in body
const fakeUpdateApi = ApiImportFakers.api({ id: apiId1, name: 'updatedName' });
it('should create API 1', () => {
importCreateApi(ADMIN_USER, fakeCreateApi1).ok();
});
it('should create API 2', () => {
importCreateApi(ADMIN_USER, fakeCreateApi2).ok();
});
it('should update API 2, event if api1 id in body', () => {
importUpdateApi(ADMIN_USER, apiId2, fakeUpdateApi)
.ok()
.should((response) => {
expect(response.body.id).to.eq(apiId2);
});
});
it('should get API1 with unchanged data', () => {
getApiById(ADMIN_USER, apiId1)
.ok()
.should((response) => {
expect(response.body.name).to.eq('originalName');
});
});
it('should get API2 with updated data', () => {
getApiById(ADMIN_USER, apiId2)
.ok()
.should((response) => {
expect(response.body.name).to.eq('updatedName');
});
});
it('should delete created API 1', () => {
deleteApi(ADMIN_USER, apiId1).httpStatus(204);
});
it('should delete created API 2', () => {
deleteApi(ADMIN_USER, apiId2).httpStatus(204);
});
});
describe('Update API with an updated context path matching another API context path', () => {
const apiId1 = '67d8020e-b0b3-47d8-9802-0eb0b357d84c';
const fakeCreateApi1 = ApiImportFakers.api({ id: apiId1 });
fakeCreateApi1.proxy.virtual_hosts[0].path = '/importTest1';
const apiId2 = '67d8020e-b0b3-47d8-9802-0eb0b357d899';
const fakeCreateApi2 = ApiImportFakers.api({ id: apiId2 });
fakeCreateApi2.proxy.virtual_hosts[0].path = '/importTest2';
// that will try to update api2, with the same context path as api1
const fakeUpdateApi = ApiImportFakers.api();
fakeUpdateApi.proxy.virtual_hosts[0].path = '/importTest1';
it('should create API 1', () => {
importCreateApi(ADMIN_USER, fakeCreateApi1).ok();
});
it('should create API 2', () => {
importCreateApi(ADMIN_USER, fakeCreateApi2).ok();
});
it('should fail to update API 2 with same context path as API 1', () => {
importUpdateApi(ADMIN_USER, apiId2, fakeUpdateApi)
.badRequest()
.should((response) => {
expect(response.body.message).to.eq('The path [/importTest1/] is already covered by an other API.');
});
});
it('should delete created API 1', () => {
deleteApi(ADMIN_USER, apiId1).httpStatus(204);
});
it('should delete created API 2', () => {
deleteApi(ADMIN_USER, apiId2).httpStatus(204);
});
});
});
describe('Update API from import with pages', () => {
describe('Update API with existing page matching generated ID', () => {
const apiId = '08a92f8c-e133-42ec-a92f-8ce13382ec73';
const pageId = '7b95cbe6-099d-4b06-95cb-e6099d7b0609';
const generatedPageId = 'c02077fc-7c4d-3c93-8404-6184a6221391';
const fakeApi = ApiImportFakers.api({ id: apiId });
const fakePage = ApiImportFakers.page({ id: pageId });
fakeApi.pages = [fakePage];
let apiUpdate;
it('should create an API with one page of documentation and return specified API ID', () => {
importCreateApi(ADMIN_USER, fakeApi).ok().its('body').should('have.property', 'id').should('eq', apiId);
});
it('should export the API', () => {
exportApi(ADMIN_USER, apiId)
.ok()
.its('body')
.then((apiExport) => {
apiUpdate = apiExport;
});
});
it('should update API page from specified ID', () => {
const pageUpdate = ApiImportFakers.page({
id: pageId,
name: 'Documentation (updated)',
content: '# Documentation\n## Contributing\nTo be done.',
});
apiUpdate.pages = [pageUpdate];
importUpdateApi(ADMIN_USER, apiId, apiUpdate).ok().its('body').should('have.property', 'id').should('eq', apiId);
});
it('should get updated API page from generated page ID', () => {
getPage(ADMIN_USER, apiId, generatedPageId)
.ok()
.its('body')
.should((page) => {
expect(page.name).to.eq('Documentation (updated)');
expect(page.content).to.eq('# Documentation\n## Contributing\nTo be done.');
});
});
it('should delete the API', () => {
deleteApi(ADMIN_USER, apiId).noContent();
});
});
describe('Update API with existing page ID, using previous export', () => {
const apiId = '7061532e-c0e5-4894-818d-f747ad1601dc';
const pageId = '4be08c28-5638-4fec-a90a-51c0cd403b12';
const generatedPageId = '4b07e8b5-d30d-3568-ad3b-7ba0820d2f22';
const fakeApi = ApiImportFakers.api({ id: apiId });
const fakePage = ApiImportFakers.page({ id: pageId });
fakeApi.pages.push(fakePage);
let apiUpdate;
it('should create an API with one page of documentation', () => {
importCreateApi(ADMIN_USER, fakeApi).ok();
});
it('should get API page from generated id', () => {
getPage(ADMIN_USER, apiId, generatedPageId).ok();
});
it('should export the API', () => {
exportApi(ADMIN_USER, apiId)
.ok()
.its('body')
.then((apiExport) => {
apiUpdate = apiExport;
});
});
it('should update the API, using previous export', () => {
importUpdateApi(ADMIN_USER, apiId, apiUpdate).ok();
});
it('should not have created additional API pages', () => {
getPages(ADMIN_USER, apiId).ok().its('body').should('have.length', 2);
});
it('should delete the API', () => {
deleteApi(ADMIN_USER, apiId);
});
});
describe('Update API with page without ID, with name not corresponding to an existing page', () => {
const apiId = 'f5cc6ea7-1ea1-46dd-a48f-34a0386467b4';
const fakeApi = ApiImportFakers.api({ id: apiId });
const pageName = 'documentation';
let apiUpdate;
it('should create an API with no documentation page', () => {
importCreateApi(ADMIN_USER, fakeApi).ok();
});
it('should export the API', () => {
exportApi(ADMIN_USER, apiId)
.ok()
.its('body')
.then((apiExport) => {
apiUpdate = apiExport;
});
});
it('should update the API, adding one documentation page with a name and without an ID', () => {
const fakePage = ApiImportFakers.page({ name: pageName });
cy.wrap(fakePage).should('not.have.a.property', 'id');
apiUpdate.pages = [ApiImportFakers.page(fakePage)];
importUpdateApi(ADMIN_USER, apiId, apiUpdate).ok();
});
it('should have created the page', () => {
getPages(ADMIN_USER, apiId).ok().its('body').should('have.length', 2).its(1).should('have.property', 'name').should('eq', pageName);
});
it('should delete the API', () => {
deleteApi(ADMIN_USER, apiId).noContent();
});
});
describe('Update API with page without ID, with name corresponding to one only existing page', () => {
const apiId = '7f996cc8-27a7-489a-af67-e3b56ec5debb';
const fakeApi = ApiImportFakers.api({ id: apiId });
const pageName = 'documentation';
const fakePage = ApiImportFakers.page({
name: pageName,
content: 'Not much to look at\n',
});
let apiUpdate;
fakeApi.pages.push(fakePage);
it('should create an API with one page of documentation', () => {
importCreateApi(ADMIN_USER, fakeApi).ok();
});
it('should get API documentation page content', () => {
getPages(ADMIN_USER, apiId)
.ok()
.its('body')
.should('have.length', 2)
.its(1)
.should('have.property', 'content')
.should('eq', 'Not much to look at\n');
});
it('should export the API', () => {
exportApi(ADMIN_USER, apiId)
.ok()
.its('body')
.then((apiExport) => {
apiUpdate = apiExport;
});
});
it('should update API documentation page content from name', () => {
const pageUpdate = ApiImportFakers.page(fakePage);
pageUpdate.content = '# API\n';
apiUpdate.pages = [pageUpdate];
cy.wrap(pageUpdate).should('not.have.a.property', 'id');
importUpdateApi(ADMIN_USER, apiId, apiUpdate).ok();
});
it('should have updated API documentation page content from name', () => {
getPages(ADMIN_USER, apiId)
.ok()
.its('body')
.should('have.length', 2)
.its(1)
.should('have.property', 'content')
.should('eq', '# API\n');
});
it('should delete the API', () => {
deleteApi(ADMIN_USER, apiId).noContent();
});
});
describe('Update API with page without ID, with name corresponding to multiple existing page', () => {
const apiId = '283fea9a-563c-494b-b8f3-2883d876765e';
const fakeApi = ApiImportFakers.api({ id: apiId });
const pageName = 'A Conflicting Name';
const fakePages = [ApiImportFakers.page({ name: pageName }), ApiImportFakers.page({ name: pageName })];
fakeApi.pages = fakePages;
let apiUpdate;
it('should create an API with two pages of documentation having the same name', () => {
importCreateApi(ADMIN_USER, fakeApi).ok();
});
it('should get three pages of documentation', () => {
getPages(ADMIN_USER, apiId).ok().its('body').should('have.length', 3);
});
it('should export the API', () => {
exportApi(ADMIN_USER, apiId)
.ok()
.its('body')
.then((apiExport) => {
apiUpdate = apiExport;
});
});
it('should fail when trying to add a page with a conflicting name and without an ID', () => {
const pageUpdate = ApiImportFakers.page({ name: pageName });
apiUpdate.pages = [...fakePages, pageUpdate];
cy.wrap(pageUpdate).should('not.have.a.property', 'id');
importUpdateApi(ADMIN_USER, apiId, apiUpdate)
.httpStatus(500)
.its('body')
.should('have.property', 'message')
.should('eq', 'Not able to identify the page to update: A Conflicting Name. Too much pages with the same name');
});
it('should delete the API', () => {
deleteApi(ADMIN_USER, apiId).noContent();
});
});
describe('Update API, removing pages', () => {
const apiId = '8fc829e8-b713-469f-8db5-06c702b82eb1';
const fakeApi = ApiImportFakers.api({ id: apiId });
fakeApi.pages.push(ApiImportFakers.page(), ApiImportFakers.page());
let apiUpdate;
it('should create an API with two pages of documentation', () => {
importCreateApi(ADMIN_USER, fakeApi).ok();
});
it('should export the API', () => {
exportApi(ADMIN_USER, apiId)
.ok()
.its('body')
.then((apiExport) => {
apiUpdate = apiExport;
});
});
it('should update the API, removing its pages', () => {
apiUpdate.pages = [];
importUpdateApi(ADMIN_USER, apiId, apiUpdate).ok();
});
it('should not have deleted pages', () => {
getPages(ADMIN_USER, apiId).ok().its('body').should('have.length', 3);
});
it('should delete the API', () => {
deleteApi(ADMIN_USER, apiId).noContent();
});
});
describe('Update API, duplicating system folder', () => {
const apiId = 'dfb569b9-a8e1-4ad4-9b84-0dd638ac2f30';
const fakeApi = ApiImportFakers.api({ id: apiId });
fakeApi.pages.push(ApiImportFakers.page());
let apiUpdate;
it('should create an API with one pages of documentation', () => {
importCreateApi(ADMIN_USER, fakeApi).ok();
});
it('should export the API', () => {
exportApi(ADMIN_USER, apiId)
.ok()
.its('body')
.then((apiExport) => {
apiUpdate = apiExport;
});
});
it('should have created a system folder page', () => {
cy.wrap(apiUpdate)
.its('pages')
.should('have.length', 2)
.should('satisfy', (pages) => pages.some(({ type }) => type === ApiPageType.SYSTEM_FOLDER));
});
it('should reject the import if trying to add a new system folder', () => {
apiUpdate.pages = Array.of(ApiImportFakers.page({ type: ApiPageType.SYSTEM_FOLDER }));
importUpdateApi(ADMIN_USER, apiId, apiUpdate).badRequest();
});
it('should delete the API', () => {
deleteApi(ADMIN_USER, apiId).noContent();
});
});
});
describe('Update API form import with members', () => {
describe('Update API that already has members, without specifying any members in data', () => {
const apiId = '533efd8a-22e1-4483-a8af-0c24a2abd590';
let member;
let primaryOwner;
let roleName = 'MY_TEST_ROLE';
let roleId;
let fakeApi;
it('should create user (future member)', () => {
createUser(ADMIN_USER, ApiImportFakers.user())
.ok()
.then((response) => {
member = response.body;
});
});
it('should create user (future primary owner)', () => {
createUser(ADMIN_USER, ApiImportFakers.user())
.ok()
.then((response) => {
primaryOwner = response.body;
});
});
it('should create role', () => {
createRole(ADMIN_USER, ApiImportFakers.role({ name: roleName }))
.ok()
.then((response) => {
roleId = response.body.id;
});
});
it('should create an API, and associate a member with role', () => {
const fakeMember = ApiImportFakers.member({ sourceId: member.email, roles: [roleId] });
fakeApi = ApiImportFakers.api({
id: apiId,
members: [fakeMember],
primaryOwner: { id: primaryOwner.id, type: ApiPrimaryOwnerType.USER, email: primaryOwner.email },
});
importCreateApi(ADMIN_USER, fakeApi).ok();
});
it('should update the API, without any primaryOwner or members in data', () => {
fakeApi.members = [];
fakeApi.primaryOwner = {};
importUpdateApi(ADMIN_USER, fakeApi.id, fakeApi).ok();
});
it('should get API members, which has kept both members that were present before update', () => {
getApiMembers(ADMIN_USER, apiId)
.ok()
.should((response) => {
expect(response.body).have.length(2);
expect(response.body).deep.include({ id: primaryOwner.id, displayName: primaryOwner.displayName, role: 'PRIMARY_OWNER' });
expect(response.body).deep.include({ id: member.id, displayName: member.displayName, role: 'MY_TEST_ROLE' });
});
});
it('should delete the API', () => {
deleteApi(ADMIN_USER, apiId).noContent();
});
it('should delete role', () => {
deleteRole(ADMIN_USER, roleName).noContent();
});
it('should delete member user', () => {
deleteUser(ADMIN_USER, member.id).noContent();
});
it('should delete primary owner user', () => {
deleteUser(ADMIN_USER, primaryOwner.id).noContent();
});
});
describe('Update API that has 2 members, updating the role of 1 member', () => {
const apiId = '533efd8a-22e1-4483-a8af-0c24a2abd590';
let member1;
let member2;
let primaryOwner;
let role1Name = 'MY_TEST_ROLE';
let role1Id;
let role2Name = 'MY_OTHER_ROLE';
let role2Id;
let fakeApi;
it('should create user (member 1)', () => {
createUser(ADMIN_USER, ApiImportFakers.user())
.ok()
.then((response) => {
member1 = response.body;
});
});
it('should create user (member 2)', () => {
createUser(ADMIN_USER, ApiImportFakers.user())
.ok()
.then((response) => {
member2 = response.body;
});
});
it('should create user (primary owner)', () => {
createUser(ADMIN_USER, ApiImportFakers.user())
.ok()
.then((response) => {
primaryOwner = response.body;
});
});
it('should create role1', () => {
createRole(ADMIN_USER, ApiImportFakers.role({ name: role1Name }))
.ok()
.then((response) => {
role1Id = response.body.id;
});
});
it('should create role2', () => {
createRole(ADMIN_USER, ApiImportFakers.role({ name: role2Name }))
.ok()
.then((response) => {
role2Id = response.body.id;
});
});
it('should create an API, with associated members', () => {
// member1 has role1, member2 has role2
const fakeMember1 = ApiImportFakers.member({ sourceId: member1.email, roles: [role1Id] });
const fakeMember2 = ApiImportFakers.member({ sourceId: member2.email, roles: [role2Id] });
fakeApi = ApiImportFakers.api({
id: apiId,
members: [fakeMember1, fakeMember2],
primaryOwner: { id: primaryOwner.id, type: ApiPrimaryOwnerType.USER, email: primaryOwner.email },
});
importCreateApi(ADMIN_USER, fakeApi).ok();
});
it('should update the API, without any primaryOwner or members in data', () => {
// member1 has role2 (changed), member2 has role2 (not changed)
const fakeMember1 = ApiImportFakers.member({ sourceId: member1.email, roles: [role2Id] });
const fakeMember2 = ApiImportFakers.member({ sourceId: member2.email, roles: [role2Id] });
fakeApi.members = [fakeMember1, fakeMember2];
importUpdateApi(ADMIN_USER, fakeApi.id, fakeApi).ok();
});
it('should export the API, resulting with member with updated roles', () => {
exportApi(ADMIN_USER, apiId)
.ok()
.should((response) => {
expect(response.body.members).have.length(3);
const member1Roles = response.body.members.filter((m) => m.sourceId == member1.email)[0].roles;
expect(member1Roles).have.length(2);
expect(member1Roles).include(role1Id);
expect(member1Roles).include(role2Id);
const member2Roles = response.body.members.filter((m) => m.sourceId == member2.email)[0].roles;
expect(member2Roles).have.length(1);
expect(member2Roles).include(role2Id);
});
});
it('should delete the API', () => {
deleteApi(ADMIN_USER, apiId).noContent();
});
it('should delete role 1', () => {
deleteRole(ADMIN_USER, role1Name).noContent();
});
it('should delete role 2', () => {
deleteRole(ADMIN_USER, role2Name).noContent();
});
it('should delete member1 user', () => {
deleteUser(ADMIN_USER, member1.id).noContent();
});
it('should delete member2 user', () => {
deleteUser(ADMIN_USER, member2.id).noContent();
});
it('should delete primary owner user', () => {
deleteUser(ADMIN_USER, primaryOwner.id).noContent();
});
});
});
describe('Update API from import with plans', () => {
describe('Update API with plans without ID', () => {
const apiId = '08a92f8c-e133-42ec-a92f-8ce13382ec73';
const fakePlan1 = ApiImportFakers.plan({ name: 'test plan 1', description: 'this is a test plan' });
const fakePlan2 = ApiImportFakers.plan({ name: 'test plan 2', description: 'this is a test plan' });
const fakeApi = ApiImportFakers.api({ id: apiId });
// this update API, creating 2 plans
const updatedFakeApi = ApiImportFakers.api({ id: apiId, plans: [fakePlan1, fakePlan2] });
it('should create the API', () => {
importCreateApi(ADMIN_USER, fakeApi).ok();
});
it('should update the API', () => {
importUpdateApi(ADMIN_USER, apiId, updatedFakeApi).ok();
});
it('should get 2 plans created on API', () => {
getPlans(ADMIN_USER, apiId, PlanStatus.STAGING)
.ok()
.should((response) => {
expect(response.body).to.have.length(2);
expect(response.body[0].description).to.eq('this is a test plan');
expect(response.body[0].validation).to.eq(PlanValidation.AUTO);
expect(response.body[0].security).to.eq(PlanSecurityType.KEY_LESS);
expect(response.body[0].type).to.eq(PlanType.API);
expect(response.body[0].status).to.eq(PlanStatus.STAGING);
expect(response.body[0].order).to.eq(0);
expect(response.body[1].description).to.eq('this is a test plan');
expect(response.body[1].validation).to.eq(PlanValidation.AUTO);
expect(response.body[1].security).to.eq(PlanSecurityType.KEY_LESS);
expect(response.body[1].type).to.eq(PlanType.API);
expect(response.body[1].status).to.eq(PlanStatus.STAGING);
expect(response.body[1].order).to.eq(0);
});
});
it('should delete the API', () => {
deleteApi(ADMIN_USER, apiId).noContent();
});
});
describe('Update API with plans with ID', () => {
const apiId = '08a92f8c-e133-42ec-a92f-8ce13555ec73';
const fakePlan1 = ApiImportFakers.plan({
id: '08a92f8c-e133-42ec-a92f-8ce139999999',
name: 'test plan 1',
description: 'this is a test plan',
status: PlanStatus.CLOSED,
});
const fakePlan2 = ApiImportFakers.plan({
id: '08a92f8c-e133-42ec-a92f-8ce138888888',
name: 'test plan 2',
description: 'this is a test plan',
status: PlanStatus.CLOSED,
});
const fakeApi = ApiImportFakers.api({ id: apiId });
// this update API, creating 2 plans
const updatedFakeApi = ApiImportFakers.api({ id: apiId, plans: [fakePlan1, fakePlan2] });
it('should create the API', () => {
importCreateApi(ADMIN_USER, fakeApi).ok();
});
it('should update the API', () => {
importUpdateApi(ADMIN_USER, apiId, updatedFakeApi).ok();
});
it('should get 2 plans created on API, with specified status', () => {
getPlans(ADMIN_USER, apiId, PlanStatus.CLOSED)
.ok()
.should((response) => {
expect(response.body).to.have.length(2);
});
});
it('should delete the API', () => {
deleteApi(ADMIN_USER, apiId).noContent();
});
});
describe('Update API with plan without ID matching name of one existing plan', () => {
const apiId = '08a92f8c-e133-42ec-a92f-8ce13382ec73';
const fakePlan1 = ApiImportFakers.plan({ name: 'test plan', description: 'this is a test plan' });
const fakeApi = ApiImportFakers.api({ id: apiId, plans: [fakePlan1] });
// this update will update the plan of the existing API, cause it has the same name
const updateFakePlan = ApiImportFakers.plan({ name: 'test plan', description: 'this is the updated description' });
const updatedFakeApi = ApiImportFakers.api({ id: apiId, plans: [updateFakePlan] });
it('should create the API', () => {
importCreateApi(ADMIN_USER, fakeApi).ok();
});
it('should update the API', () => {
importUpdateApi(ADMIN_USER, apiId, updatedFakeApi).ok();
});
it('should get the API plan, which has been updated', () => {
getPlans(ADMIN_USER, apiId, PlanStatus.STAGING)
.ok()
.should((response) => {
expect(response.body).to.have.length(1);
expect(response.body[0].description).to.eq('this is the updated description');
});
});
it('should delete the API', () => {
deleteApi(ADMIN_USER, apiId).noContent();
});
});
describe('Update API with missing plans from already existing API', () => {
// existing API contains 2 plans
const apiId = '08a92f8c-e133-42ec-a92f-8ce13382ec73';
const fakePlan1 = ApiImportFakers.plan({ name: 'test plan 1' });
const fakePlan2 = ApiImportFakers.plan({ name: 'test plan 2' });
const fakeApi = ApiImportFakers.api({ id: apiId, plans: [fakePlan1, fakePlan2] });
// update API contains 1 other plan
const updateFakePlan = ApiImportFakers.plan({ name: 'test plan 3' });
const updatedFakeApi = ApiImportFakers.api({ id: apiId, plans: [updateFakePlan] });
it('should create the API', () => {
importCreateApi(ADMIN_USER, fakeApi).ok();
});
it('should update the API', () => {
importUpdateApi(ADMIN_USER, apiId, updatedFakeApi).ok();
});
it('should get the API plan, containing only the plan that was in the update', () => {
getPlans(ADMIN_USER, apiId, PlanStatus.STAGING)
.ok()
.should((response) => {
expect(response.body).to.have.length(1);
expect(response.body[0].name).to.eq('test plan 3');
});
});
it('should delete the API', () => {
deleteApi(ADMIN_USER, apiId).noContent();
});
});
});
describe('Update API from import with metadata', () => {
describe('Update API with some metadata having key that already exists', () => {
const apiId = 'aa7f03dc-4ccf-434b-80b2-e5af22b0c76a';
const fakeApi = ApiImportFakers.api({
id: apiId,
metadata: [
{
key: 'team',
name: 'team',
format: ApiMetadataFormat.STRING,
value: 'Ops',
},
],
});
let apiUpdate;
it('should create an API with some metadata having a key with value "team"', () => {
importCreateApi(ADMIN_USER, fakeApi).ok();
});
it('should get the API metadata', () => {
getApiMetadata(ADMIN_USER, apiId).ok().its('body').should('have.length', 2).should('deep.include', {
key: 'team',
name: 'team',
format: ApiMetadataFormat.STRING,
value: 'Ops',
apiId: 'aa7f03dc-4ccf-434b-80b2-e5af22b0c76a',
});
});
it('should export the API', () => {
exportApi(ADMIN_USER, apiId)
.ok()
.its('body')
.then((apiExport) => {
apiUpdate = apiExport;
});
});
it('should update the API metadata having the key "team"', () => {
apiUpdate.metadata = [
{
key: 'team',
name: 'team',
format: ApiMetadataFormat.STRING,
value: 'DevOps',
},
];
importUpdateApi(ADMIN_USER, apiId, apiUpdate).ok();
});
it('should get the updated API metadata', () => {
getApiMetadata(ADMIN_USER, apiId).ok().its('body').should('have.length', 2).should('deep.include', {
key: 'team',
name: 'team',
format: ApiMetadataFormat.STRING,
value: 'DevOps',
apiId: 'aa7f03dc-4ccf-434b-80b2-e5af22b0c76a',
});
});
it('should delete the API', () => {
deleteApi(ADMIN_USER, apiId).noContent();
});
});
describe('Update API with metadata having key that does not yet exist', () => {
const apiId = '4fb4f3d7-e556-421c-b03f-5b2d3da3e774';
const fakeApi = ApiImportFakers.api({ id: apiId });
let apiUpdate;
it('should create an API with no metadata', () => {
importCreateApi(ADMIN_USER, fakeApi).ok();
});
it('should export the API', () => {
exportApi(ADMIN_USER, apiId)
.ok()
.its('body')
.then((apiExport) => {
apiUpdate = apiExport;
});
});
it('should update API with some metadata having a key that does not yet exist', () => {
apiUpdate.metadata = [
{
key: 'team',
name: 'team',
format: ApiMetadataFormat.STRING,
value: 'Info Sec',
},
];
importUpdateApi(ADMIN_USER, apiId, apiUpdate).ok();
});
it('should get the created API metadata', () => {
getApiMetadata(ADMIN_USER, apiId).ok().its('body').should('deep.include', {
key: 'team',
name: 'team',
format: ApiMetadataFormat.STRING,
value: 'Info Sec',
apiId: '4fb4f3d7-e556-421c-b03f-5b2d3da3e774',
});
});
it('should delete the API', () => {
deleteApi(ADMIN_USER, apiId).noContent();
});
});
describe('Update API with metadata having an undefined key', () => {
const apiId = 'a67e7015-224c-4c32-abaa-231f58d4e542';
const fakeApi = ApiImportFakers.api({
id: apiId,
});
let apiUpdate;
it('should create an API with no metadata', () => {
importCreateApi(ADMIN_USER, fakeApi).ok();
});
it('should export the API', () => {
exportApi(ADMIN_USER, apiId)
.ok()
.its('body')
.then((apiExport) => {
apiUpdate = apiExport;
});
});
it('should update the API, adding metadata with an undefined key', () => {
apiUpdate.metadata = [
{
name: 'team',
format: ApiMetadataFormat.STRING,
value: 'Product',
},
];
importUpdateApi(ADMIN_USER, apiId, apiUpdate).ok();
});
it('should get the API metadata', () => {
getApiMetadata(ADMIN_USER, apiId).ok().its('body').its(0).should('deep.equal', {
name: 'team',
format: ApiMetadataFormat.STRING,
value: 'Product',
apiId: 'a67e7015-224c-4c32-abaa-231f58d4e542',
});
});
it('should delete the API', () => {
deleteApi(ADMIN_USER, apiId).noContent();
});
});
});
describe('Update API from import with groups', () => {
describe('Update API with with group name that already exists', () => {
const apiId = '70fbb369-5672-43e6-8a8c-ff7aa81a6055';
const groupName = 'customers';
const fakeGroup = GroupFakers.group({ name: groupName });
const fakeApi = ApiImportFakers.api({ id: apiId });
let groupId;
let apiUpdate;
it('should create a group with name "customers"', () => {
createGroup(ADMIN_USER, fakeGroup)
.created()
.its('body')
.should((body) => {
expect(body.name).to.eq('customers');
})
.should('have.property', 'id')
.then((id) => {
groupId = id;
});
});
it('should create an API associated with no groups', () => {
importCreateApi(ADMIN_USER, fakeApi).ok().its('body').its('groups').should('be.empty');
});
it('should export the API', () => {
exportApi(ADMIN_USER, apiId)
.ok()
.its('body')
.then((apiExport) => {
apiUpdate = apiExport;
});
});
it('should update the API, associating it to the group "customers"', () => {
apiUpdate.groups = ['customers'];
importUpdateApi(ADMIN_USER, apiId, apiUpdate)
.ok()
.its('body')
.should('have.property', 'groups')
.should('have.length', 1)
.its(0)
.should('eq', groupId);
});
it('should delete the group', () => {
deleteGroup(ADMIN_USER, groupId).noContent();
});
it('should delete the API', () => {
deleteApi(ADMIN_USER, apiId).noContent();
});
});
describe('Update API with with group name that does not exists', () => {
const apiId = 'bc071378-7fb5-45df-841a-a2518668ae60';
const groupName = 'sales';
const fakeApi = ApiImportFakers.api({ id: apiId, groups: ['support'] });
let groupId;
let apiUpdate;
it('should create an API associated with no groups', () => {
importCreateApi(ADMIN_USER, fakeApi).ok().its('body').should('have.property', 'groups').should('have.length', 1);
});
it('should export the API', () => {
exportApi(ADMIN_USER, apiId)
.ok()
.its('body')
.then((apiExport) => {
apiUpdate = apiExport;
});
});
it('should update the API, associating it to the group "sales"', () => {
apiUpdate.groups = [groupName];
importUpdateApi(ADMIN_USER, apiId, apiUpdate)
.ok()
.its('body')
.should('have.property', 'groups')
.should('have.length', 1)
.its(0)
.then((id) => {
groupId = id;
});
});
it('should get the created group', () => {
getGroup(ADMIN_USER, groupId).ok().its('body').should('have.property', 'name').should('eq', 'sales');
});
it('should delete the API', () => {
deleteApi(ADMIN_USER, apiId).noContent();
});
it('should delete the group', () => {
deleteGroup(ADMIN_USER, groupId).noContent();
});
});
});
}); | the_stack |
import CodeMirror from 'codemirror'
import 'codemirror/addon/runmode/runmode'
import 'codemirror/mode/markdown/markdown'
import 'codemirror/mode/javascript/javascript'
import 'codemirror/mode/css/css'
import 'codemirror/mode/diff/diff'
import 'codemirror/lib/codemirror.css'
import 'codemirror/addon/edit/continuelist'
import 'codemirror/keymap/vim'
import 'codemirror/addon/hint/show-hint'
import 'codemirror/addon/hint/show-hint.css'
import 'codemirror/keymap/sublime'
import 'codemirror/keymap/emacs'
import 'codemirror/addon/scroll/scrollpastend'
import { loadMode } from '../../../design/lib/codemirror/util'
loadMode(CodeMirror)
export default CodeMirror
export interface EditorPosition {
line: number
ch: number
}
type SuggestionModeType = {
[key: string]: {
autocomplete: string
compareText?: string
displayText: string
}[]
}
const supportedModeSuggestions: SuggestionModeType = {
a: [
{ autocomplete: 'apl', displayText: 'APL' },
{ autocomplete: 'asn', displayText: 'ASN.1' },
{ autocomplete: 'asterisk', displayText: 'Asterisk dialplan' },
],
b: [{ autocomplete: 'brainfuck', displayText: 'Brainfuck' }],
c: [
{ autocomplete: 'c', displayText: 'C' },
{ autocomplete: 'cpp', displayText: 'C++' },
{ autocomplete: 'c#', displayText: 'C#' },
{
autocomplete: 'ceylon',
displayText: 'Ceylon',
},
{ autocomplete: 'clojure', displayText: 'Clojure' },
{
compareText: 'gss',
autocomplete: 'css',
displayText: 'Closure Stylesheets (GSS)',
},
{ autocomplete: 'cmake', displayText: 'CMake' },
{ autocomplete: 'cobol', displayText: 'Cobol' },
{ autocomplete: 'coffeescript', displayText: 'CoffeeScript' },
{ autocomplete: 'commonlisp', displayText: 'Common Lisp' },
{ autocomplete: 'crystal', displayText: 'Crystal' },
{ autocomplete: 'css', displayText: 'CSS' },
{ autocomplete: 'cypher', displayText: 'Cypher' },
{ autocomplete: 'cython', displayText: 'Cython' },
],
d: [
{ autocomplete: 'd', displayText: 'D' },
{ autocomplete: 'dart', displayText: 'Dart' },
{ autocomplete: 'django', displayText: 'Django (templating language)' },
{ autocomplete: 'dockerfile', displayText: 'Dockerfile' },
{ autocomplete: 'diff', displayText: 'Diff' },
{ autocomplete: 'dtd', displayText: 'DTD' },
{ autocomplete: 'dylan', displayText: 'Dylan' },
],
e: [
{ autocomplete: 'ebnf', displayText: 'EBNF' },
{ autocomplete: 'ecl', displayText: 'ECL' },
{ autocomplete: 'eiffel', displayText: 'Eiffel' },
{ autocomplete: 'elm', displayText: 'Elm' },
{ autocomplete: 'erlang', displayText: 'Erlang' },
],
f: [
{ autocomplete: 'factor', displayText: 'Factor' },
{ autocomplete: 'fcl', displayText: 'FCL' },
{ autocomplete: 'forth', displayText: 'Forth' },
{ autocomplete: 'fortran', displayText: 'Fortan' },
{ autocomplete: 'f#', displayText: 'F#' },
],
g: [
{ autocomplete: 'gas', displayText: 'Gas (AT&T-style assembly)' },
{ autocomplete: 'gherkin', displayText: 'Gherkin' },
{ autocomplete: 'go', displayText: 'Go' },
{ autocomplete: 'groovy', displayText: 'Groovy' },
],
h: [
{ autocomplete: 'haml', displayText: 'HAML' },
{ autocomplete: 'handlebars', displayText: 'Handlebars' },
{ autocomplete: 'haskell', displayText: 'Haskell' },
{ autocomplete: 'haskell-literate', displayText: 'Haskell (literate)' },
{ autocomplete: 'haxe', displayText: 'Haxe' },
{
autocomplete: 'htmlembedded',
displayText: 'HTML embedded (JSP, ASP.NET)',
},
{ autocomplete: 'htmlmixed', displayText: 'HTML mixed-mode' },
{ autocomplete: 'html', displayText: 'HTML' },
{ autocomplete: 'http', displayText: 'HTTP' },
],
i: [{ autocomplete: 'idl', displayText: 'IDL' }],
j: [
{
autocomplete: 'js',
displayText: 'Javascript',
compareText: 'javascript',
},
{ autocomplete: 'jinja2', displayText: 'Jinja2' },
{ autocomplete: 'jsx', displayText: 'Javascript (JSX)' },
{ autocomplete: 'julia', displayText: 'Julia' },
{ autocomplete: 'java', displayText: 'Java' },
],
l: [
{ autocomplete: 'livescript', displayText: 'Livescript' },
{ autocomplete: 'lua', displayText: 'Lua' },
{ autocomplete: 'less', displayText: 'LESS' },
],
k: [{ autocomplete: 'kotlin', displayText: 'Kotlin' }],
m: [
{ autocomplete: 'markdown', displayText: 'Markdown (GitHub-flavour)' },
{ autocomplete: 'mathematica', displayText: 'Mathematica' },
{ autocomplete: 'mbox', displayText: 'mbox' },
{ autocomplete: 'mirc', displayText: 'mIRC' },
{ autocomplete: 'modelica', displayText: 'modelica' },
{ autocomplete: 'mscgen', displayText: 'MscGen' },
{ autocomplete: 'mumps', displayText: 'MUMPS' },
],
n: [
{ autocomplete: 'nginx', displayText: 'Nginx' },
{ autocomplete: 'nsis', displayText: 'NSIS' },
{ autocomplete: 'ntriples', displayText: 'N-Triples/N-Quads' },
],
o: [
{ autocomplete: 'octave', displayText: 'Octave (MATLAB)' },
{ autocomplete: 'oz', displayText: 'Oz' },
{ autocomplete: 'ocaml', displayText: 'OCaml' },
{
autocomplete: 'objc',
displayText: 'ObjectiveC',
},
],
p: [
{ autocomplete: 'pascal', displayText: 'Pascal' },
{ autocomplete: 'pegjs', displayText: 'PEG.js' },
{ autocomplete: 'perl', displayText: 'Perl' },
{ autocomplete: 'pgp', displayText: 'PGP (ASCII armor)' },
{ autocomplete: 'php', displayText: 'PHP' },
{ autocomplete: 'pig', displayText: 'Pig Latin' },
{ autocomplete: 'powershell', displayText: 'PowerShell' },
{ autocomplete: 'properties', displayText: 'Properties files' },
{ autocomplete: 'protobuf', displayText: 'ProtoBuf' },
{ autocomplete: 'pug', displayText: 'Pug' },
{ autocomplete: 'puppet', displayText: 'Puppet' },
{ autocomplete: 'python', displayText: 'Python' },
{ autocomplete: 'plantuml', displayText: 'PlantUML' },
],
q: [{ autocomplete: 'q', displayText: 'Q' }],
r: [
{ autocomplete: 'r', displayText: 'R' },
{ autocomplete: 'rpm', displayText: 'rpm' },
{ autocomplete: 'rst', displayText: 'reStructuredText' },
{ autocomplete: 'ruby', displayText: 'Ruby' },
{ autocomplete: 'rust', displayText: 'Rust' },
],
s: [
{ autocomplete: 'sas', displayText: 'SAS' },
{ autocomplete: 'sass', displayText: 'Sass' },
{ autocomplete: 'scheme', displayText: 'Scheme' },
{ autocomplete: 'scala', displayText: 'Scala' },
{ autocomplete: 'shell', displayText: 'Shell' },
{ autocomplete: 'sieve', displayText: 'Sieve' },
{ autocomplete: 'slim', displayText: 'Slim' },
{ autocomplete: 'smalltalk', displayText: 'Smalltalk' },
{ autocomplete: 'spreadsheet', displayText: 'Spreadsheet' },
{ autocomplete: 'smarty', displayText: 'Smarty' },
{ autocomplete: 'solr', displayText: 'Solr' },
{ autocomplete: 'soy', displayText: 'Soy' },
{ autocomplete: 'sparql', displayText: 'SPARQL' },
{ autocomplete: 'sql', displayText: 'SQL' },
{ autocomplete: 'stex', displayText: 'sTeX, LaTeX' },
{ autocomplete: 'stylus', displayText: 'Stylus' },
{ autocomplete: 'swift', displayText: 'Swift' },
],
t: [
{ autocomplete: 'tcl', displayText: 'Tcl' },
{ autocomplete: 'textile', displayText: 'Textile' },
{ autocomplete: 'tiddlywiki', displayText: 'Tiddlywiki' },
{ autocomplete: 'tiki', displayText: 'Tiki wiki' },
{ autocomplete: 'toml', displayText: 'TOML' },
{ autocomplete: 'tornado', displayText: 'Tornado (templating language)' },
{ autocomplete: 'troff', displayText: 'troff (for manpages)' },
{ autocomplete: 'ttcn', displayText: 'TTCN' },
{ autocomplete: 'ttcn-cfg', displayText: 'TTCN Configuration' },
{ autocomplete: 'turtle', displayText: 'Turtle' },
{ autocomplete: 'twig', displayText: 'Twig' },
{
autocomplete: 'ts',
displayText: 'Typescript',
compareText: 'typescript',
},
],
v: [
{ autocomplete: 'vb', displayText: 'VB.NET' },
{ autocomplete: 'vbscript', displayText: 'VBScript' },
{ autocomplete: 'velocity', displayText: 'Velocity' },
{ autocomplete: 'verilog', displayText: 'Verilog/SystemVerilog' },
{ autocomplete: 'vhdl', displayText: 'VHDL' },
{ autocomplete: 'vue', displayText: 'Vue.js app' },
],
w: [
{ autocomplete: 'webidl', displayText: 'Web IDL' },
{ autocomplete: 'wast', displayText: 'WebAssembly Text Format' },
],
x: [
{ autocomplete: 'xml', displayText: 'XML/HTML' },
{ autocomplete: 'xquery', displayText: 'XQuery' },
],
y: [
{ autocomplete: 'yacas', displayText: 'Yacas' },
{ autocomplete: 'yaml', displayText: 'YAML' },
{ autocomplete: 'yaml-frontmatter', displayText: 'YAML frontmatter' },
],
z: [{ autocomplete: 'z80', displayText: 'Z80' }],
}
const improvedModeSuggestions = {}
for (const [key, suggestions] of Object.entries(supportedModeSuggestions)) {
improvedModeSuggestions[key] = suggestions.map((suggestion) => {
return {
compareText: suggestion.compareText,
autocomplete: suggestion.autocomplete,
displayText: `${suggestion.displayText} [${suggestion.autocomplete}]`,
}
})
}
export function getModeSuggestions(
word: string,
suggestionModes: SuggestionModeType = improvedModeSuggestions
): CodeMirror.Hint[] {
for (const [key, suggestions] of Object.entries(suggestionModes)) {
if (!word.startsWith(key)) {
continue
}
const filteredSuggestions = suggestions.filter(
(suggestion) =>
suggestion.autocomplete.startsWith(word) ||
(suggestion.compareText != null &&
suggestion.compareText.startsWith(word))
)
/*
if user accepted suggestion - don't show suggestion which auto-completes to the same string
this handles not only case when we are not calling `showHint` programmatically but also
when it shows automatically (from inside the show hint plugin), and handles this case gracefully
*/
if (
filteredSuggestions.length == 1 &&
(word == filteredSuggestions[0].autocomplete ||
word == filteredSuggestions[0].compareText)
) {
continue
}
return filteredSuggestions
.sort((a, b) => {
const textA = a.compareText != null ? a.compareText : a.autocomplete
const textB = b.compareText != null ? b.compareText : b.autocomplete
return textA.length - textB.length
})
.map((suggestion) => {
return {
text: suggestion.autocomplete,
displayText: suggestion.displayText,
}
})
}
return []
}
export function CodeMirrorEditorModeHints(cm: CodeMirror.Editor) {
return new Promise(function (accept) {
setTimeout(function () {
const cursor = cm.getCursor(),
line = cm.getLine(cursor.line)
let start = cursor.ch
let end = cursor.ch
while (start && /\w/.test(line.charAt(start - 1))) --start
while (end < line.length && /\w/.test(line.charAt(end))) ++end
const word = line.slice(start, end).toLowerCase()
const suggestions = getModeSuggestions(word)
if (suggestions.length == 0) {
return accept(null)
}
return accept({
list: suggestions,
from: CodeMirror.Pos(cursor.line, start),
to: CodeMirror.Pos(cursor.line, end),
})
}, 100)
})
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.