repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
azakordonets/ts-retry
|
lib/esm/retry/utils/untilTruthy/retry.d.ts
|
import { RetryUtilsOptions } from "../options";
export declare function retryUntilTruthy<RETURN_TYPE>(fn: () => RETURN_TYPE, retryOptions?: RetryUtilsOptions): Promise<RETURN_TYPE>;
export declare function retryAsyncUntilTruthy<RETURN_TYPE>(fn: () => Promise<RETURN_TYPE>, retryOptions?: RetryUtilsOptions): Promise<RETURN_TYPE>;
|
azakordonets/ts-retry
|
src/wait/options.ts
|
export let defaultDuration = 60 * 1000;
export function setDefaultDuration(duration: number) {
defaultDuration = duration;
}
export function getDefaultDuration(): number {
return defaultDuration;
}
|
azakordonets/ts-retry
|
src/retry/utils/untilTruthy/index.ts
|
export { retryAsyncUntilTruthy, retryUntilTruthy } from "./retry";
export {
retryAsyncUntilTruthyDecorator,
retryUntilTruthyDecorator,
} from "./decorator";
|
azakordonets/ts-retry
|
lib/esm/retry/options.d.ts
|
<reponame>azakordonets/ts-retry
export declare type UNTIL<RETURN_TYPE> = (result: RETURN_TYPE) => boolean;
export interface RetryOptions<RETURN_TYPE = any> {
maxTry?: number;
delay?: number;
until?: UNTIL<RETURN_TYPE> | null;
onMaxRetryFunc?: (err: Error) => void;
}
export declare let defaultRetryOptions: RetryOptions<any>;
export declare function setDefaultRetryOptions<RETURN_TYPE>(retryOptions: RetryOptions<RETURN_TYPE>): RetryOptions<RETURN_TYPE>;
export declare function getDefaultRetryOptions<RETURN_TYPE = any>(): Readonly<RetryOptions<RETURN_TYPE>>;
|
azakordonets/ts-retry
|
lib/esm/wait/options.d.ts
|
export declare let defaultDuration: number;
export declare function setDefaultDuration(duration: number): void;
export declare function getDefaultDuration(): number;
|
azakordonets/ts-retry
|
lib/esm/wait/decorators.d.ts
|
<gh_stars>10-100
export declare function waitUntilAsyncDecorator<RETURN_TYPE extends (...args: any[]) => Promise<any>>(fn: RETURN_TYPE, duration?: number, error?: Error): (...args: Parameters<RETURN_TYPE>) => ReturnType<RETURN_TYPE>;
/** a waitUntil decorator
* @param fn the function to execute
* @param duration timeout in milliseconds
* @param [error] custom error to throw when fn duration exceeded duration. If not provided a TimeoutError is thrown.
* @returns: a function hat takes same parameters as fn. It calls fn using waitUntil and returns/throws the results/error of this call?
*/
export declare function waitUntilDecorator<RETURN_TYPE extends (...args: any[]) => any>(fn: RETURN_TYPE, duration?: number, error?: Error): (...args: Parameters<RETURN_TYPE>) => ReturnType<RETURN_TYPE>;
|
azakordonets/ts-retry
|
src/retry/utils/untilTruthy/decorators.test.ts
|
import {
retryAsyncUntilTruthyDecorator,
retryUntilTruthyDecorator,
} from "./decorator";
import * as sinon from "sinon";
import * as chai from "chai";
import * as sinonChai from "sinon-chai";
import { isTooManyTries } from "../../tooManyTries";
const should = require("chai").should();
chai.should();
chai.use(sinonChai);
describe("Retry Util", function () {
describe("RetryUntilThruthyDecorator", function () {
it("Success: returns a truthy value immediatly", async function () {
const expectedResult = 1;
const callback = sinon.stub<[], number>();
callback.returns(expectedResult);
const decorated = retryUntilTruthyDecorator(callback);
const actualResult = await decorated();
callback.should.have.been.calledOnce;
actualResult.should.be.equal(expectedResult);
});
it("Success one returns a truthy value", async function () {
const expectedResult = 1;
const callback = sinon.stub<[], number | undefined | null>();
callback.onFirstCall().returns(undefined);
callback.onSecondCall().returns(null);
callback.onThirdCall().returns(expectedResult);
const decorated = retryUntilTruthyDecorator(callback);
const actualResult = await decorated();
callback.should.have.been.callCount(3);
actualResult!.should.be.equal(expectedResult);
});
it("Fails: always return falsy values", async function () {
const result = undefined;
const callback = sinon.stub<[], number | undefined>();
callback.returns(result);
const maxTry = 3;
const decorated = retryUntilTruthyDecorator(
callback,
{ maxTry, delay: 1 },
);
try {
await decorated();
} catch (err) {
callback.should.have.been.callCount(maxTry);
isTooManyTries(err).should.be.true;
}
});
it("Fails: fn always throw an error", async function () {
const errMsg = "BOOM";
const callback = sinon.stub();
callback.throws(new Error(errMsg));
const maxTry = 3;
const decorated = retryUntilTruthyDecorator(
callback,
{ maxTry, delay: 1 },
);
try {
await decorated();
} catch (err) {
callback.should.have.been.callCount(maxTry);
isTooManyTries(err).should.be.false;
(err as Error).message.should.equals(errMsg);
}
});
});
describe("RetryAsyncUntilTruthyDecorator", function () {
it("Success: returns a truthy value immediatly", async function () {
const expectedResult = 1;
const callback = sinon.stub<[], Promise<number>>();
callback.resolves(expectedResult);
const decorated = retryAsyncUntilTruthyDecorator(callback);
const actualResult = await decorated();
callback.should.have.been.calledOnce;
actualResult.should.be.equal(expectedResult);
});
it("Success one returns a truthy value", async function () {
const expectedResult = 1;
const callback = sinon.stub<[], Promise<number | undefined | null>>();
callback.onFirstCall().resolves(undefined);
callback.onSecondCall().resolves(null);
callback.onThirdCall().resolves(expectedResult);
const decorated = retryAsyncUntilTruthyDecorator(callback);
const actualResult = await decorated();
callback.should.have.been.callCount(3);
actualResult!.should.be.equal(expectedResult);
});
it("Fails: always return falsy value", async function () {
const result = undefined;
const callback = sinon.stub<[], Promise<number | undefined>>();
callback.resolves(result);
const maxTry = 3;
const decorated = retryAsyncUntilTruthyDecorator(
callback,
{ maxTry, delay: 1 },
);
try {
await decorated();
} catch (err) {
callback.should.have.been.callCount(maxTry);
isTooManyTries(err).should.be.true;
}
});
it("Fails: fn always throw an error", async function () {
const errMsg = "BOOM";
const callback = sinon.stub();
callback.rejects(new Error(errMsg));
const maxTry = 3;
const decorated = retryAsyncUntilTruthyDecorator(
callback,
{ maxTry, delay: 1 },
);
try {
await decorated();
} catch (err) {
callback.should.have.been.callCount(maxTry);
isTooManyTries(err).should.be.false;
(err as Error).message.should.equals(errMsg);
}
});
});
});
|
azakordonets/ts-retry
|
src/wait/decorators.test.ts
|
<filename>src/wait/decorators.test.ts
import sinon = require("sinon");
import { waitUntilAsyncDecorator, waitUntilDecorator } from "./decorators";
describe("Wait decorators", function () {
it("waitUntilAsyncDecorator should execute the function", async function () {
const timeout = 100;
const param = "Question";
const answer = 42;
const callback = sinon.stub();
callback
.withArgs(param)
.onFirstCall()
.resolves(answer);
const decorated = waitUntilAsyncDecorator(callback, timeout);
(await decorated(param)).should.be.equals(answer);
});
it("waitUntilAsyncDecorator should throw the function error", async function () {
const timeout = 100;
const errorMsg = "BOOM";
const error = new Error(errorMsg);
const callback = sinon.stub().rejects(error);
const decorated = waitUntilAsyncDecorator(callback, timeout);
try {
await decorated();
throw new Error("Expected error not thrown");
} catch (error) {
(error as Error).message.should.be.equals(errorMsg);
}
});
it(
"waitUntilAsyncDecorator should throw an error in case of timeout",
async function () {
const timeout = 50;
const answer = 42;
const callback = () => {
return new Promise<number>((resolve, reject) => {
setTimeout(
() => resolve(answer),
timeout + 50,
);
});
};
const decorated = waitUntilAsyncDecorator(callback, timeout);
try {
await decorated();
throw new Error("Expected error not thrown");
} catch (error) {
(error as any).isTimeout.should.be.equals(true);
}
},
);
it(
"waitUntilAsyncDecorator should throw a custom error in case of timeout",
async function () {
const timeout = 50;
const errorMsg = "BOOM";
const callback = () => {
return new Promise<void>((resolve, reject) => {
setTimeout(
() => resolve(),
timeout + 50,
);
});
};
const decorated = waitUntilAsyncDecorator(
callback,
timeout,
new Error(errorMsg),
);
try {
await decorated();
throw new Error("Expected error not thrown");
} catch (error) {
(error as Error).message.should.be.equals(errorMsg);
}
},
);
it("waitUntilDecorator should execute the function", async function () {
const timeout = 100;
const param = "Question";
const answer = 42;
const callback = sinon.stub();
callback
.withArgs(param)
.onFirstCall()
.returns(answer);
const decorated = waitUntilDecorator(callback, timeout);
(await decorated(param)).should.be.equals(answer);
});
it("waitUntilDecorator should throw the function error", async function () {
const timeout = 100;
const errorMsg = "BOOM";
const error = new Error(errorMsg);
const callback = sinon.stub().throws(error);
const decorated = waitUntilDecorator(callback, timeout);
try {
await decorated();
throw new Error("Expected error not thrown");
} catch (error) {
(error as Error).message.should.be.equals(errorMsg);
}
});
it(
"waitUntilDecorator should throw an error in case of timeout",
async function () {
const timeout = 50;
const answer = 42;
const callback = () => {
return new Promise<number>((resolve, reject) => {
setTimeout(
() => resolve(answer),
timeout + 50,
);
});
};
const decorated = waitUntilDecorator(callback, timeout);
try {
await decorated();
throw new Error("Expected error not thrown");
} catch (error) {
(error as any).isTimeout.should.be.equals(true);
}
},
);
it(
"waitUntilDecorator should throw a custom error in case of timeout",
async function () {
const timeout = 50;
const errorMsg = "BOOM";
const callback = () => {
return new Promise<void>((resolve, reject) => {
setTimeout(
() => resolve(),
timeout + 50,
);
});
};
const decorated = waitUntilDecorator(
callback,
timeout,
new Error(errorMsg),
);
try {
await decorated();
throw new Error("Expected error not thrown");
} catch (error) {
(error as Error).message.should.be.equals(errorMsg);
}
},
);
});
|
azakordonets/ts-retry
|
lib/esm/index.d.ts
|
<filename>lib/esm/index.d.ts<gh_stars>10-100
export type { RetryOptions } from "./retry";
export type { TooManyTries } from "./retry";
export { getDefaultRetryOptions, isTooManyTries, retry, retryAsync, retryAsyncUntilResponse, retryAsyncUntilResponseDecorator, retryAsyncUntilTruthy, retryAsyncUntilTruthyDecorator, retryUntilTruthy, retryUntilTruthyDecorator, setDefaultRetryOptions, } from "./retry";
export type { TimeoutError } from "./wait";
export { getDefaultDuration, isTimeoutError, setDefaultDuration, wait, waitUntil, waitUntilAsync, } from "./wait";
|
azakordonets/ts-retry
|
src/retry/utils/untilDefined/decorators.test.ts
|
import {
retryAsyncUntilDefinedDecorator,
retryUntilDefinedDecorator,
} from "./decorator";
import * as sinon from "sinon";
import * as chai from "chai";
import * as sinonChai from "sinon-chai";
import { isTooManyTries } from "../../tooManyTries";
const should = require("chai").should();
chai.should();
chai.use(sinonChai);
describe("Retry Util", function () {
describe("RetryUntilDefinedDecorator", function () {
it("Success: returns a defined value immediatly", async function () {
const expectedResult = 1;
const callback = sinon.stub<[], number>();
callback.returns(expectedResult);
const decorated = retryUntilDefinedDecorator(callback);
const actualResult = await decorated();
callback.should.have.been.calledOnce;
actualResult.should.be.equal(expectedResult);
});
it("Success one returns a defined value", async function () {
const expectedResult = 1;
const callback = sinon.stub<[], number | undefined | null>();
callback.onFirstCall().returns(undefined);
callback.onSecondCall().returns(null);
callback.onThirdCall().returns(expectedResult);
const decorated = retryUntilDefinedDecorator(callback);
const actualResult = await decorated();
callback.should.have.been.callCount(3);
actualResult.should.be.equal(expectedResult);
});
it("Fails: always return undefined or null", async function () {
const result = undefined;
const callback = sinon.stub<[], number | undefined>();
callback.returns(result);
const maxTry = 3;
const decorated = retryUntilDefinedDecorator(
callback,
{ maxTry, delay: 1 },
);
try {
await decorated();
} catch (err) {
callback.should.have.been.callCount(maxTry);
isTooManyTries(err).should.be.true;
}
});
it("Fails: fn always throw an error", async function () {
const errMsg = "BOOM";
const callback = sinon.stub();
callback.throws(new Error(errMsg));
const maxTry = 3;
const decorated = retryUntilDefinedDecorator(
callback,
{ maxTry, delay: 1 },
);
try {
await decorated();
} catch (err) {
callback.should.have.been.callCount(maxTry);
isTooManyTries(err).should.be.false;
(err as Error).message.should.equals(errMsg);
}
});
});
describe("RetryAsyncUntilDefinedDecorator", function () {
it("Success: returns a defined value immediatly", async function () {
const expectedResult = 1;
const callback = sinon.stub<[], Promise<number>>();
callback.resolves(expectedResult);
const decorated = retryAsyncUntilDefinedDecorator(callback);
const actualResult = await decorated();
callback.should.have.been.calledOnce;
actualResult.should.be.equal(expectedResult);
});
it("Success one returns a defined value", async function () {
const expectedResult = 1;
const callback = sinon.stub<[], Promise<number | undefined | null>>();
callback.onFirstCall().resolves(undefined);
callback.onSecondCall().resolves(null);
callback.onThirdCall().resolves(expectedResult);
const decorated = retryAsyncUntilDefinedDecorator(callback);
const actualResult = await decorated();
callback.should.have.been.callCount(3);
actualResult.should.be.equal(expectedResult);
});
it("Fails: always return undefined or null", async function () {
const result = undefined;
const callback = sinon.stub<[], Promise<number | undefined>>();
callback.resolves(result);
const maxTry = 3;
const decorated = retryAsyncUntilDefinedDecorator(
callback,
{ maxTry, delay: 1 },
);
try {
await decorated();
} catch (err) {
callback.should.have.been.callCount(maxTry);
isTooManyTries(err).should.be.true;
}
});
it("Fails: fn always throw an error", async function () {
const errMsg = "BOOM";
const callback = sinon.stub();
callback.rejects(new Error(errMsg));
const maxTry = 3;
const decorated = retryAsyncUntilDefinedDecorator(
callback,
{ maxTry, delay: 1 },
);
try {
await decorated();
} catch (err) {
callback.should.have.been.callCount(maxTry);
isTooManyTries(err).should.be.false;
(err as Error).message.should.equals(errMsg);
}
});
});
});
|
azakordonets/ts-retry
|
lib/esm/retry/utils/untilResponse/type.d.ts
|
<reponame>azakordonets/ts-retry
export declare type RESPONSE_TYPE = {
ok: boolean;
};
|
azakordonets/ts-retry
|
src/wait/wait.test.ts
|
import { waitUntil } from "..";
import * as chai from "chai";
import * as sinonChai from "sinon-chai";
import { isTimeoutError } from "./wait";
import { getDefaultDuration, setDefaultDuration } from "./options";
import { setDefaultRetryOptions } from "../retry";
const should = require("chai").should();
chai.should();
chai.use(sinonChai);
describe("Wait until", () => {
const defaultDuration = getDefaultDuration();
afterEach(function () {
setDefaultDuration(defaultDuration);
});
it("wait should return function return code", async function () {
const duration = 1000;
const result = Symbol("OK");
const fn = async () => result;
const actualResult = await waitUntil(fn, duration);
actualResult.should.equal(result);
});
it("wait should throw function exception", async function () {
const duration = 1000;
const errorMsg = "BOOM";
const fn = () => {
throw new Error(errorMsg);
};
let actualErr = undefined;
try {
await waitUntil(fn, duration);
} catch (err) {
actualErr = err as any;
}
if (actualErr === undefined) {
throw new Error("Should have thrown an exception");
}
actualErr.message.should.equal(errorMsg);
});
it("wait should throw TimeoutError exception", async function () {
const duration = 1000;
const fn = () => {
return new Promise((resolve) =>
setTimeout(
() => resolve(1),
duration * 2,
)
);
};
let actualErr = undefined;
try {
await waitUntil(fn, duration);
} catch (err) {
actualErr = err as any;
}
if (actualErr === undefined) {
throw new Error("Should have thrown an exception");
}
actualErr.isTimeout.should.equal(true);
isTimeoutError(actualErr).should.equal(true);
});
it("wait should throw TimeoutError exception an default timeout expiration", async function () {
setDefaultDuration(1000);
this.timeout(getDefaultDuration() * 3);
const fn = () => {
return new Promise((resolve) =>
setTimeout(
() => resolve(1),
getDefaultDuration() * 2,
)
);
};
let actualErr = undefined;
try {
await waitUntil(fn);
} catch (err) {
actualErr = err as any;
}
if (actualErr === undefined) {
throw new Error("Should have thrown an exception");
}
actualErr.isTimeout.should.equal(true);
isTimeoutError(actualErr).should.equal(true);
});
it("wait should throw a custom exception", async function () {
const duration = 1000;
const errMsg = "Boom";
const fn = () => {
return new Promise((resolve) =>
setTimeout(
() => resolve(1),
duration * 2,
)
);
};
let actualErr = undefined;
try {
await waitUntil(fn, duration, new Error(errMsg));
} catch (err) {
actualErr = err as any;
}
if (actualErr === undefined) {
throw new Error("Should have thrown an exception");
}
should.not.exist((actualErr as any).isTimeout);
isTimeoutError(actualErr).should.equal(false);
actualErr.message.should.equal(errMsg);
});
});
|
azakordonets/ts-retry
|
src/index.ts
|
<gh_stars>10-100
export type { RetryOptions } from "./retry";
export type { TooManyTries } from "./retry";
export {
getDefaultRetryOptions,
isTooManyTries,
retry,
retryAsync,
retryAsyncUntilResponse,
retryAsyncUntilResponseDecorator,
retryAsyncUntilTruthy,
retryAsyncUntilTruthyDecorator,
retryUntilTruthy,
retryUntilTruthyDecorator,
setDefaultRetryOptions,
} from "./retry";
export type { TimeoutError } from "./wait";
export {
getDefaultDuration,
isTimeoutError,
setDefaultDuration,
wait,
waitUntil,
waitUntilAsync,
} from "./wait";
|
azakordonets/ts-retry
|
src/wait/wait.ts
|
<filename>src/wait/wait.ts
import { asyncDecorator } from "../misc";
import { defaultDuration } from "./options";
export function wait(duration: number = defaultDuration) {
return new Promise((resolve) => setTimeout(resolve, duration));
}
export async function waitUntil<RETURN_TYPE>(
fn: () => RETURN_TYPE,
duration?: number,
error?: Error,
): Promise<RETURN_TYPE> {
const fnAsync = asyncDecorator(fn);
return await waitUntilAsync(fnAsync, duration, error);
}
export async function waitUntilAsync<RETURN_TYPE>(
fn: () => Promise<RETURN_TYPE>,
duration: number = defaultDuration,
error: Error = new TimeoutError(
"function did not complete within allowed time",
),
): Promise<RETURN_TYPE> {
const canary = Symbol("DELAY_EXPIRED");
const result = await Promise.race([
fn(),
timeout(duration, canary),
]);
if (result === canary) {
throw error;
}
return result as RETURN_TYPE;
}
const timeout = async <RETURN_TYPE>(duration: number, result: RETURN_TYPE) => {
await wait(duration);
return result;
};
export class TimeoutError extends Error {
isTimeout = true;
}
export function isTimeoutError(error: Error): error is TimeoutError {
return (error as TimeoutError).isTimeout === true;
}
|
azakordonets/ts-retry
|
src/retry/utils/untilDefined/retry.ts
|
import { retry, retryAsync } from "../../retry";
import {
retryUntilOptionsToRetryOptionsHof,
RetryUtilsOptions,
} from "../options";
const until = <RETURN_TYPE>(
lastResult: RETURN_TYPE | undefined | null,
): boolean => lastResult !== undefined && lastResult !== null;
const getOptions = retryUntilOptionsToRetryOptionsHof(until);
export async function retryUntilDefined<
RETURN_TYPE,
>(
fn: () => RETURN_TYPE | undefined | null,
retryOptions?: RetryUtilsOptions,
): Promise<RETURN_TYPE> {
const options = getOptions<RETURN_TYPE>(retryOptions);
return (await retry(fn, options))!;
}
export async function retryAsyncUntilDefined<
RETURN_TYPE,
>(
fn: () => Promise<RETURN_TYPE | undefined | null>,
retryOptions?: RetryUtilsOptions,
): Promise<RETURN_TYPE> {
const options = getOptions<RETURN_TYPE>(retryOptions);
return (await retryAsync(fn, options))!;
}
|
azakordonets/ts-retry
|
src/wait/options.test.ts
|
import * as chai from "chai";
import * as sinonChai from "sinon-chai";
import { getDefaultDuration, setDefaultDuration } from "../.";
const should = require("chai").should();
chai.should();
chai.use(sinonChai);
describe("wait option", function () {
const defaultDuration = getDefaultDuration();
after(function () {
setDefaultDuration(defaultDuration);
});
it("default duration should be the good one", function () {
getDefaultDuration().should.be.equals(60 * 1000);
});
it("should change default duration", function () {
const duration = 5000;
setDefaultDuration(duration);
getDefaultDuration().should.be.equals(duration);
});
});
|
azakordonets/ts-retry
|
lib/esm/retry/index.d.ts
|
<filename>lib/esm/retry/index.d.ts
export type { RetryOptions } from "./options";
export { getDefaultRetryOptions, setDefaultRetryOptions } from "./options";
export { retry, retryAsync } from "./retry";
export { isTooManyTries } from "./tooManyTries";
export type { TooManyTries } from "./tooManyTries";
export type { RetryUtilsOptions } from "./utils";
export { retryAsyncUntilDefined, retryAsyncUntilDefinedDecorator, retryAsyncUntilTruthy, retryAsyncUntilTruthyDecorator, retryUntilDefined, retryUntilDefinedDecorator, retryUntilTruthy, retryUntilTruthyDecorator, } from "./utils";
export { retryAsyncUntilResponse, retryAsyncUntilResponseDecorator, } from "./utils";
|
azakordonets/ts-retry
|
lib/esm/retry/tooManyTries.d.ts
|
export declare class TooManyTries extends Error {
constructor();
tooManyTries: boolean;
}
export declare function isTooManyTries(error: unknown): error is TooManyTries;
|
azakordonets/ts-retry
|
lib/esm/retry/utils/untilDefined/retry.d.ts
|
import { RetryUtilsOptions } from "../options";
export declare function retryUntilDefined<RETURN_TYPE>(fn: () => RETURN_TYPE | undefined | null, retryOptions?: RetryUtilsOptions): Promise<RETURN_TYPE>;
export declare function retryAsyncUntilDefined<RETURN_TYPE>(fn: () => Promise<RETURN_TYPE | undefined | null>, retryOptions?: RetryUtilsOptions): Promise<RETURN_TYPE>;
|
azakordonets/ts-retry
|
src/retry/retry.test.ts
|
import * as sinon from "sinon";
import * as chai from "chai";
import * as sinonChai from "sinon-chai";
import {
getDefaultRetryOptions,
retry,
RetryOptions,
setDefaultRetryOptions,
} from ".";
import { isTooManyTries } from "./tooManyTries";
const should = require("chai").should();
chai.should();
chai.use(sinonChai);
describe("Retry", function () {
const realDefaultRetryOptions = getDefaultRetryOptions();
after(function () {
setDefaultRetryOptions(realDefaultRetryOptions);
});
beforeEach(function () {
setDefaultRetryOptions({ delay: 10, maxTry: 10 });
});
it("cb works the first time, retry should not re-call it", async function () {
const callback = sinon.stub();
await retry(callback);
callback.should.have.been.calledOnce;
});
it("work after three times, retry should call it while cb throws exception", async function () {
const callback = sinon.stub();
callback.onFirstCall().throws("BOOM");
callback.onSecondCall().throws("BOOM");
await retry(callback);
callback.should.have.been.calledThrice;
});
it('always failed, retry should give up after default "maxTry"', async function () {
const callback = sinon.stub();
callback.throws("BOOM");
try {
await retry(callback);
} catch (err) {}
callback.should.have.been.callCount(getDefaultRetryOptions().maxTry!);
});
it("always failed, retry should give up after given maxTry", async function () {
const callback = sinon.stub();
callback.throws("BOOM");
const options: RetryOptions<void> = { delay: 3, maxTry: 100 };
try {
await retry(callback, options);
} catch (err) {}
callback.should.have.been.callCount(options.maxTry!);
});
describe("Retry with until", function () {
it("Returns immediatly: until is ok", async function () {
const result = 1;
const callback = sinon.stub();
callback.returns(result);
const until = sinon.stub();
until.withArgs(result).returns(true);
await retry(callback, { until });
callback.should.have.been.calledOnce;
until.should.have.been.calledOnce;
});
it("Fails: result is always rejected by until", async function () {
const result = 1;
const callback = sinon.stub();
callback.returns(result);
const until = sinon.stub();
until.withArgs(result).returns(false);
const maxTry = 3;
try {
await retry(callback, { maxTry, until });
} catch (err) {
callback.should.have.been.callCount(maxTry);
until.should.have.been.callCount(maxTry);
isTooManyTries(err).should.be.true;
}
});
it("Call the callback until the result is accepted", async function () {
const result = 1;
const callback = sinon.stub();
callback.returns(result);
const until = sinon.stub();
until.withArgs(result).returns(false).returns(true);
const maxTry = 3;
try {
await retry(callback, { maxTry, until });
} catch (err) {
callback.should.have.been.callCount(2);
until.should.have.been.callCount(2);
}
});
it("Fails: result is always rejected by until", async function () {
const result = 1;
const errMsg = "BOOM";
const callback = sinon.stub();
callback.throws(new Error(errMsg));
const until = sinon.stub();
until.withArgs(result).returns(false);
const maxTry = 3;
try {
await retry(callback, { maxTry, until });
} catch (err) {
callback.should.have.been.callCount(maxTry);
until.should.have.been.callCount(0);
isTooManyTries(err).should.be.false;
(err as Error).message.should.equals(errMsg);
}
});
it("Fails: onMaxRetryFunc should be called on TooManyRetries when defined", async function () {
const result = 1;
const errMsg = "BOOM";
const callback = sinon.stub();
callback.throws(new Error(errMsg));
const until = sinon.stub();
until.withArgs(result).returns(false);
const maxTry = 3;
let shouldBeCalled = false
const beforeTooManyErrorsFn = (err: Error) => {
shouldBeCalled = true
}
try {
await retry(callback, { maxTry, until, onMaxRetryFunc: beforeTooManyErrorsFn });
} catch (err) {
callback.should.have.been.callCount(maxTry);
until.should.have.been.callCount(0);
isTooManyTries(err).should.be.false;
(err as Error).message.should.equals(errMsg);
shouldBeCalled.should.equals(true)
}
});
});
});
|
azakordonets/ts-retry
|
src/wait/index.ts
|
export {
isTimeoutError,
TimeoutError,
wait,
waitUntil,
waitUntilAsync,
} from "./wait";
export { getDefaultDuration, setDefaultDuration } from "./options";
|
azakordonets/ts-retry
|
src/retry/utils/untilResponse/retry.ts
|
<gh_stars>10-100
import { retry, retryAsync } from "../../retry";
import {
retryUntilOptionsToRetryOptionsHof,
RetryUtilsOptions,
} from "../options";
import { RESPONSE_TYPE } from "./type";
const until = <RETURN_TYPE extends RESPONSE_TYPE>(
lastResult: RETURN_TYPE,
): boolean => lastResult.ok;
const getOptions = retryUntilOptionsToRetryOptionsHof(until);
export async function retryAsyncUntilResponse<
RETURN_TYPE extends RESPONSE_TYPE,
>(
fn: () => Promise<RETURN_TYPE>,
retryOptions?: RetryUtilsOptions,
): Promise<RETURN_TYPE> {
const options = getOptions<RETURN_TYPE>(retryOptions);
return await retryAsync(fn, options);
}
|
azakordonets/ts-retry
|
src/retry/options.ts
|
export type UNTIL<RETURN_TYPE> = (result: RETURN_TYPE) => boolean;
export interface RetryOptions<RETURN_TYPE = any> {
maxTry?: number;
delay?: number;
until?: UNTIL<RETURN_TYPE> | null;
onMaxRetryFunc?: (err: Error) => void; // this can be helpful when you want to save some information before throwing TooManyTries error
}
export let defaultRetryOptions: RetryOptions<any> = {
delay: 250,
maxTry: 4 * 60,
until: null,
};
export function setDefaultRetryOptions<RETURN_TYPE>(
retryOptions: RetryOptions<RETURN_TYPE>,
): RetryOptions<RETURN_TYPE> {
defaultRetryOptions = { ...defaultRetryOptions, ...retryOptions };
return getDefaultRetryOptions<RETURN_TYPE>();
}
export function getDefaultRetryOptions<RETURN_TYPE = any>(): Readonly<
RetryOptions<RETURN_TYPE>
> {
return { ...defaultRetryOptions };
}
|
azakordonets/ts-retry
|
src/retry/utils/options.ts
|
<filename>src/retry/utils/options.ts
import { RetryOptions, UNTIL } from "../options";
export type RetryUtilsOptions = Exclude<RetryOptions<void>, "until">;
export const retryUntilOptionsToRetryOptionsHof = <RETURN_TYPE>(
until: UNTIL<RETURN_TYPE>,
) =>
(
retryOptions?: RetryUtilsOptions,
): RetryOptions<RETURN_TYPE> => ({
...retryOptions,
until,
});
|
azakordonets/ts-retry
|
src/retry/option.test.ts
|
<filename>src/retry/option.test.ts
import * as chai from "chai";
import * as sinonChai from "sinon-chai";
import {
getDefaultRetryOptions,
RetryOptions,
setDefaultRetryOptions,
} from ".";
const should = require("chai").should();
chai.should();
chai.use(sinonChai);
describe("RetryDefaultOption", function () {
let realDefaultRetryOptions: RetryOptions;
before(function () {
realDefaultRetryOptions = getDefaultRetryOptions();
});
after(function () {
setDefaultRetryOptions(realDefaultRetryOptions);
});
it("Should have the expected default value", function () {
getDefaultRetryOptions().should.deep.equals(
{ delay: 250, maxTry: 4 * 60, until: null },
);
});
it("defaultOptions can be changed", async function () {
const initialOptions = getDefaultRetryOptions();
const newOptions: RetryOptions<void> = {
maxTry: 10,
delay: 10,
until: () => false,
};
const defaultOptions = setDefaultRetryOptions(newOptions);
defaultOptions.should.deep.equals(newOptions);
getDefaultRetryOptions().should.deep.equals(newOptions);
});
it("default maxTry can be changed", async function () {
const initialOptions = getDefaultRetryOptions();
const newMaxTry = initialOptions.maxTry! * 2;
const expectedOptions: RetryOptions<void> = {
...initialOptions,
maxTry: newMaxTry,
};
setDefaultRetryOptions({ maxTry: newMaxTry }).should.deep.equals(
expectedOptions,
);
getDefaultRetryOptions().should.deep.equals(
expectedOptions,
);
});
it("default delay can be changed", async function () {
const initialOptions = getDefaultRetryOptions();
const newDelay = initialOptions.delay! * 2;
const expectedOptions: RetryOptions<void> = {
...initialOptions,
delay: newDelay,
};
setDefaultRetryOptions({ delay: newDelay }).should.deep.equals(
expectedOptions,
);
getDefaultRetryOptions().should.deep.equals(
expectedOptions,
);
});
it("default until can be changed", async function () {
const initialOptions = getDefaultRetryOptions();
const newUntil = (result: string) => true;
const expectedOptions: RetryOptions<string> = {
...initialOptions,
until: newUntil,
};
setDefaultRetryOptions({ until: newUntil }).should.deep.equals(
expectedOptions,
);
getDefaultRetryOptions().should.deep.equals(
expectedOptions,
);
});
});
|
azakordonets/ts-retry
|
src/retry/decorators.test.ts
|
import { retryAsyncDecorator, retryDecorator } from "./decorators";
import sinon = require("sinon");
import { isTooManyTries } from "./tooManyTries";
const should = require("chai").should();
describe("Retry decorator", function () {
it("async decorator should return the valid result", async function () {
const param = "Question";
const answer = 42;
const callback = sinon.stub();
callback
.withArgs(param)
.onFirstCall()
.resolves(answer);
const decorated = retryAsyncDecorator(callback);
(await decorated(param)).should.be.equals(answer);
callback.should.have.been.callCount(1);
});
it("async decorator should throw an exception", async function () {
const param = "Question";
const errorMsg = "BOOM";
const error = new Error(errorMsg);
const maxTry = 2;
const callback = sinon.stub();
callback.rejects(error);
const decorated = retryAsyncDecorator(callback, { maxTry, delay: 50 });
try {
await decorated(param);
throw new Error("Expected error not thrown");
} catch (error) {
(error as Error).message.should.be.equals(errorMsg);
callback.should.have.been.callCount(maxTry);
}
});
it("decorator should return the valid result", async function () {
const param = "Question";
const answer = 42;
const callback = sinon.stub();
callback
.withArgs(param)
.onFirstCall()
.returns(answer);
const decorated = retryDecorator(callback);
(await decorated(param)).should.be.equals(answer);
callback.should.have.been.callCount(1);
});
it("decorator should throw an exception", async function () {
const param = "Question";
const errorMsg = "BOOM";
const callback = sinon.stub();
const error = new Error(errorMsg);
const maxTry = 2;
callback.throws(error);
const decorated = retryDecorator(callback, { maxTry, delay: 50 });
try {
await decorated(param);
throw new Error("Expected error not thrown");
} catch (error) {
(error as Error).message.should.be.equals(errorMsg);
callback.should.have.been.callCount(maxTry);
}
});
describe("Decorator should use 'until' callback", async function () {
it("should return a valid result", async function () {
const param = "Question";
const answer = 42;
const callback = sinon.stub();
callback
.withArgs(param)
.onFirstCall()
.returns(answer);
const until = sinon.stub();
until.withArgs(answer).returns(true);
const decorated = retryDecorator(callback, { until });
(await decorated(param)).should.be.equals(answer);
callback.should.have.been.callCount(1);
until.should.have.been.callCount(1);
});
it("should return a valid result when until returs true", async function () {
const param = "Question";
const answer = 42;
const callback = sinon.stub();
callback
.withArgs(param)
.returns(answer);
const until = sinon.stub();
until.onCall(0).returns(false);
until.onCall(1).returns(true);
const decorated = retryDecorator(callback, { delay: 5, until });
(await decorated(param)).should.be.equals(answer);
callback.should.have.been.callCount(2);
until.should.have.been.callCount(2);
});
it("should throw an error when callback fails", async function () {
const param = "Question";
const errorMsg = "BOOM";
const callback = sinon.stub();
const error = new Error(errorMsg);
const maxTry = 2;
const until = sinon.stub();
callback.throws(error);
const decorated = retryDecorator(callback, { maxTry, delay: 50, until });
try {
await decorated(param);
throw new Error("Expected error not thrown");
} catch (error) {
(error as Error).message.should.be.equals(errorMsg);
callback.should.have.been.callCount(maxTry);
until.should.have.been.callCount(0);
}
});
it("should throw a TooManyTries when 'until' always return false", async function () {
const maxTry = 3;
const param = "Question";
const answer = 42;
const callback = sinon.stub();
callback
.withArgs(param)
.returns(answer);
const until = sinon.stub();
until.withArgs(answer).returns(false);
const decorated = retryDecorator(
callback,
{ maxTry: 3, delay: 10, until },
);
try {
await decorated(param);
throw new Error("Expected error not thrown");
} catch (error) {
isTooManyTries(error).should.be.true;
callback.should.have.been.callCount(maxTry);
until.should.have.been.callCount(maxTry);
}
});
});
});
|
azakordonets/ts-retry
|
src/retry/utils/untilTruthy/decorator.ts
|
<gh_stars>10-100
import { RetryUtilsOptions } from "../options";
import { retryAsyncUntilTruthy, retryUntilTruthy } from "./retry";
export function retryUntilTruthyDecorator<
PARAMETERS_TYPE extends any[],
RETURN_TYPE,
>(
fn: (...args: PARAMETERS_TYPE) => RETURN_TYPE,
retryOptions?: RetryUtilsOptions,
) {
return async (...args: PARAMETERS_TYPE): Promise<RETURN_TYPE> => {
const wrappedFn = () => fn(...args);
return await retryUntilTruthy(wrappedFn, retryOptions);
};
}
export function retryAsyncUntilTruthyDecorator<
PARAMETERS_TYPE extends any[],
RETURN_TYPE,
>(
fn: (...args: PARAMETERS_TYPE) => Promise<RETURN_TYPE>,
retryOptions?: RetryUtilsOptions,
) {
return async (...args: PARAMETERS_TYPE): Promise<RETURN_TYPE> => {
const wrappedFn = async () => await fn(...args);
return await retryAsyncUntilTruthy(wrappedFn, retryOptions);
};
}
|
azakordonets/ts-retry
|
src/retry/utils/untilResponse/retry.test.ts
|
import { retryAsyncUntilResponse } from "./retry";
import * as sinon from "sinon";
import * as chai from "chai";
import * as sinonChai from "sinon-chai";
import { isTooManyTries } from "../../tooManyTries";
import { RESPONSE_TYPE } from "./type";
const should = require("chai").should();
chai.should();
chai.use(sinonChai);
describe("Retry Util", function () {
describe("RetryAsyncUntilresponse", function () {
it("Success: ok=true, returns value immediatly", async function () {
const expectedResult = {
ok: true,
body: "foo",
};
const callback = sinon.stub<any, Promise<typeof expectedResult>>();
callback.resolves(expectedResult);
const actualResult = await retryAsyncUntilResponse(callback);
callback.should.have.been.calledOnce;
actualResult.should.equals(expectedResult);
});
it("Success one returns ok", async function () {
const expectedResult = {
ok: true,
body: "foo",
};
const callback = sinon.stub<
any,
Promise<typeof expectedResult | RESPONSE_TYPE>
>();
callback.onFirstCall().resolves({ ok: false });
callback.onSecondCall().resolves({ ok: false });
callback.onThirdCall().resolves(expectedResult);
const actualResult = await retryAsyncUntilResponse(callback);
callback.should.have.been.callCount(3);
actualResult!.should.equals(expectedResult);
});
it("Fails: always return a falsy value", async function () {
const result = { ok: false };
const callback = sinon.stub<any, Promise<typeof result>>();
callback.resolves(result);
const maxTry = 3;
try {
await retryAsyncUntilResponse(callback, { maxTry, delay: 2 });
} catch (err) {
callback.should.have.been.callCount(maxTry);
isTooManyTries(err).should.be.true;
}
});
it("Fails: fn always throw an error", async function () {
const errMsg = "BOOM";
const callback = sinon.stub();
callback.rejects(new Error(errMsg));
const maxTry = 3;
try {
await retryAsyncUntilResponse(callback, { maxTry, delay: 2 });
} catch (err) {
callback.should.have.been.callCount(maxTry);
isTooManyTries(err).should.be.false;
(err as Error).message.should.equals(errMsg);
}
});
});
});
|
azakordonets/ts-retry
|
lib/esm/retry/utils/index.d.ts
|
export { RetryUtilsOptions } from "./options";
export { retryAsyncUntilDefined, retryAsyncUntilDefinedDecorator, retryUntilDefined, retryUntilDefinedDecorator, } from "./untilDefined";
export { retryAsyncUntilTruthy, retryAsyncUntilTruthyDecorator, retryUntilTruthy, retryUntilTruthyDecorator, } from "./untilTruthy";
export { retryAsyncUntilResponse, retryAsyncUntilResponseDecorator, } from "./untilResponse";
|
azakordonets/ts-retry
|
src/retry/tooManyTries.ts
|
<reponame>azakordonets/ts-retry
export class TooManyTries extends Error {
constructor() {
super("function did not complete within allowed number of attempts");
}
tooManyTries = true;
}
export function isTooManyTries(error: unknown): error is TooManyTries {
return (error as TooManyTries).tooManyTries === true;
}
|
azakordonets/ts-retry
|
src/retry/utils/untilTruthy/retry.test.ts
|
<gh_stars>10-100
import * as sinon from "sinon";
import * as chai from "chai";
import * as sinonChai from "sinon-chai";
import { isTooManyTries } from "../../tooManyTries";
import { retryAsyncUntilTruthy, retryUntilTruthy } from "./retry";
const should = require("chai").should();
chai.should();
chai.use(sinonChai);
describe("Retry Util", function () {
describe("RetryUntilThruthy", function () {
it("Success: returns a truthy value immediatly", async function () {
const expectedResult = 1;
const callback = sinon.stub<any, number>();
callback.returns(expectedResult);
const actualResult = await retryUntilTruthy(callback);
callback.should.have.been.calledOnce;
actualResult.should.be.equal(expectedResult);
});
it("Success one returns a truthy value", async function () {
const expectedResult = 1;
const callback = sinon.stub<any, number | undefined | null>();
callback.onFirstCall().returns(undefined);
callback.onSecondCall().returns(null);
callback.onThirdCall().returns(expectedResult);
const actualResult = await retryUntilTruthy(callback);
callback.should.have.been.callCount(3);
actualResult!.should.be.equal(expectedResult);
});
it("Fails: always return falsy values", async function () {
const result = -1;
const callback = sinon.stub<any, number>();
callback.returns(result);
const maxTry = 3;
try {
await retryUntilTruthy(callback, { maxTry, delay: 2 });
} catch (err) {
callback.should.have.been.callCount(maxTry);
isTooManyTries(err).should.be.true;
}
});
it("Fails: fn always throw an error", async function () {
const errMsg = "BOOM";
const callback = sinon.stub<any, number>();
callback.throws(new Error(errMsg));
const maxTry = 3;
try {
await retryUntilTruthy(callback, { maxTry, delay: 2 });
} catch (err) {
callback.should.have.been.callCount(maxTry);
isTooManyTries(err).should.be.false;
(err as Error).message.should.equals(errMsg);
}
});
});
describe("RetryAsyncUntilTruthy", function () {
it("Success: returns a truthy value immediatly", async function () {
const expectedResult = 1;
const callback = sinon.stub<any, Promise<number>>();
callback.resolves(expectedResult);
const actualResult = await retryAsyncUntilTruthy(callback);
callback.should.have.been.calledOnce;
actualResult.should.equals(expectedResult);
});
it("Success one returns truthy value", async function () {
const expectedResult = 1;
const callback = sinon.stub<any, Promise<number | undefined | null>>();
callback.onFirstCall().resolves(undefined);
callback.onSecondCall().resolves(null);
callback.onThirdCall().resolves(expectedResult);
const actualResult = await retryAsyncUntilTruthy(callback);
callback.should.have.been.callCount(3);
actualResult!.should.equals(expectedResult);
});
it("Fails: always return a falsy value", async function () {
const result = false;
const callback = sinon.stub<any, Promise<boolean>>();
callback.resolves(result);
const maxTry = 3;
try {
await retryAsyncUntilTruthy(callback, { maxTry, delay: 2 });
} catch (err) {
callback.should.have.been.callCount(maxTry);
isTooManyTries(err).should.be.true;
}
});
it("Fails: fn always throw an error", async function () {
const errMsg = "BOOM";
const callback = sinon.stub();
callback.rejects(new Error(errMsg));
const maxTry = 3;
try {
await retryAsyncUntilTruthy(callback, { maxTry, delay: 2 });
} catch (err) {
callback.should.have.been.callCount(maxTry);
isTooManyTries(err).should.be.false;
(err as Error).message.should.equals(errMsg);
}
});
});
});
|
azakordonets/ts-retry
|
src/retry/utils/untilResponse/decorators.ts
|
import { RetryUtilsOptions } from "../options";
import { retryAsyncUntilResponse } from "./retry";
import { RESPONSE_TYPE } from "./type";
export function retryAsyncUntilResponseDecorator<
PARAMETERS_TYPE extends any[],
RETURN_TYPE extends RESPONSE_TYPE,
>(
fn: (...args: PARAMETERS_TYPE) => Promise<RETURN_TYPE>,
retryOptions?: RetryUtilsOptions,
) {
return async (...args: PARAMETERS_TYPE): Promise<RETURN_TYPE> => {
const wrappedFn = async () => await fn(...args);
return await retryAsyncUntilResponse(wrappedFn, retryOptions);
};
}
|
azakordonets/ts-retry
|
src/retry/tooManyTries.test.ts
|
<reponame>azakordonets/ts-retry
import { isTooManyTries, TooManyTries } from "./tooManyTries";
describe("TooManyTries", function () {
it("Should return false when error is not a ToManyTries", function () {
const error = new Error("BOOM");
isTooManyTries(error).should.false;
});
it("Should return true when error is a ToManyTries", function () {
const error = new TooManyTries();
isTooManyTries(error).should.true;
});
});
|
azakordonets/ts-retry
|
lib/esm/retry/utils/untilResponse/decorators.d.ts
|
import { RetryUtilsOptions } from "../options";
import { RESPONSE_TYPE } from "./type";
export declare function retryAsyncUntilResponseDecorator<PARAMETERS_TYPE extends any[], RETURN_TYPE extends RESPONSE_TYPE>(fn: (...args: PARAMETERS_TYPE) => Promise<RETURN_TYPE>, retryOptions?: RetryUtilsOptions): (...args: PARAMETERS_TYPE) => Promise<RETURN_TYPE>;
|
azakordonets/ts-retry
|
src/retry/index.ts
|
export type { RetryOptions } from "./options";
export { getDefaultRetryOptions, setDefaultRetryOptions } from "./options";
export { retry, retryAsync } from "./retry";
export { isTooManyTries } from "./tooManyTries";
export type { TooManyTries } from "./tooManyTries";
export type { RetryUtilsOptions } from "./utils";
export {
retryAsyncUntilDefined,
retryAsyncUntilDefinedDecorator,
retryAsyncUntilTruthy,
retryAsyncUntilTruthyDecorator,
retryUntilDefined,
retryUntilDefinedDecorator,
retryUntilTruthy,
retryUntilTruthyDecorator,
} from "./utils";
export {
retryAsyncUntilResponse,
retryAsyncUntilResponseDecorator,
} from "./utils";
|
azakordonets/ts-retry
|
lib/esm/misc.d.ts
|
<gh_stars>10-100
export declare const asyncDecorator: <T>(fn: () => T) => () => Promise<T>;
export declare const assertDefined: <T>(value: T | null | undefined, errMsg: string) => value is T;
|
azakordonets/ts-retry
|
src/retry/utils/untilDefined/decorator.ts
|
<gh_stars>10-100
import { RetryUtilsOptions } from "../options";
import { retryAsyncUntilDefined, retryUntilDefined } from "./retry";
export function retryUntilDefinedDecorator<
PARAMETERS_TYPE extends any[],
RETURN_TYPE,
>(
fn: (...args: PARAMETERS_TYPE) => RETURN_TYPE | null | undefined,
retryOptions?: RetryUtilsOptions,
) {
return async (...args: PARAMETERS_TYPE): Promise<RETURN_TYPE> => {
const wrappedFn = () => fn(...args);
return await retryUntilDefined(wrappedFn, retryOptions);
};
}
export function retryAsyncUntilDefinedDecorator<
PARAMETERS_TYPE extends any[],
RETURN_TYPE,
>(
fn: (...args: PARAMETERS_TYPE) => Promise<RETURN_TYPE | null | undefined>,
retryOptions?: RetryUtilsOptions,
) {
return async (...args: PARAMETERS_TYPE): Promise<RETURN_TYPE> => {
const wrappedFn = async () => await fn(...args);
return await retryAsyncUntilDefined(wrappedFn, retryOptions);
};
}
|
azakordonets/ts-retry
|
lib/esm/retry/utils/options.d.ts
|
import { RetryOptions, UNTIL } from "../options";
export declare type RetryUtilsOptions = Exclude<RetryOptions<void>, "until">;
export declare const retryUntilOptionsToRetryOptionsHof: <RETURN_TYPE>(until: UNTIL<RETURN_TYPE>) => (retryOptions?: RetryOptions<void> | undefined) => RetryOptions<RETURN_TYPE>;
|
azakordonets/ts-retry
|
lib/esm/retry/retry.d.ts
|
import { RetryOptions } from "./options";
export declare function retry<RETURN_TYPE>(fn: () => RETURN_TYPE, retryOptions?: RetryOptions<RETURN_TYPE>): Promise<RETURN_TYPE>;
export declare function retryAsync<RETURN_TYPE>(fn: () => Promise<RETURN_TYPE>, retryOptions?: RetryOptions<RETURN_TYPE>): Promise<RETURN_TYPE>;
|
azakordonets/ts-retry
|
src/retry/utils/untilDefined/index.ts
|
<reponame>azakordonets/ts-retry
export { retryAsyncUntilDefined, retryUntilDefined } from "./retry";
export {
retryAsyncUntilDefinedDecorator,
retryUntilDefinedDecorator,
} from "./decorator";
|
urain39/ij2tpl.js
|
gh-page/main.ts
|
import { parse, setFilterMap } from '../ij2tpl';
setFilterMap({
toClass: function(type_) {
let class_ = 'unknown';
if (type_ == 'directory')
class_ = 'dir';
else if (type_ == 'file')
class_ = 'file';
return class_;
}
});
const template = parse(`\
{{?contents.length}}
<ul>
{{?contents}} {{- Is directory? }}
{{-}}<li><a class="icon {{type | toClass}}">{{name}}</a></li>
{{-}}{{@^}}
{{/contents}}
</ul>
{{/contents.length}}
`, '{{', '}}');
const elem: Element = document.getElementById('content') as Element;
/**
* Generated from `tree -J` Mozilla Javascript 1.5 Source.
*/
const data = {'contents':[
{'type':'directory','name':'js','contents':[
{'type':'directory','name':'CVS','contents':[
{'type':'file','name':'Entries'}
,{'type':'file','name':'Entries.Static'}
,{'type':'file','name':'Repository'}
,{'type':'file','name':'Root'}
,{'type':'file','name':'Tag'}
]}
,{'type':'directory','name':'jsd','contents':[
{'type':'directory','name':'CVS','contents':[
{'type':'file','name':'Entries'}
,{'type':'file','name':'Entries.Log'}
,{'type':'file','name':'Repository'}
,{'type':'file','name':'Root'}
,{'type':'file','name':'Tag'}
]}
,{'type':'file','name':'Makefile.in'}
,{'type':'file','name':'README'}
,{'type':'directory','name':'idl','contents':[
{'type':'directory','name':'CVS','contents':[
{'type':'file','name':'Entries'}
,{'type':'file','name':'Repository'}
,{'type':'file','name':'Root'}
,{'type':'file','name':'Tag'}
]}
,{'type':'file','name':'Makefile.in'}
,{'type':'file','name':'jsdIDebuggerService.idl'}
]}
,{'type':'file','name':'jsd.h'}
,{'type':'file','name':'jsd.mak'}
,{'type':'file','name':'jsd.pkg'}
,{'type':'file','name':'jsd1640.def'}
,{'type':'file','name':'jsd1640.rc'}
,{'type':'file','name':'jsd3240.rc'}
,{'type':'file','name':'jsd_atom.c'}
,{'type':'file','name':'jsd_high.c'}
,{'type':'file','name':'jsd_hook.c'}
,{'type':'file','name':'jsd_java.c'}
,{'type':'file','name':'jsd_lock.c'}
,{'type':'file','name':'jsd_lock.h'}
,{'type':'file','name':'jsd_obj.c'}
,{'type':'file','name':'jsd_scpt.c'}
,{'type':'file','name':'jsd_stak.c'}
,{'type':'file','name':'jsd_step.c'}
,{'type':'file','name':'jsd_text.c'}
,{'type':'file','name':'jsd_val.c'}
,{'type':'file','name':'jsd_xpc.cpp'}
,{'type':'file','name':'jsd_xpc.h'}
,{'type':'file','name':'jsdebug.c'}
,{'type':'file','name':'jsdebug.h'}
,{'type':'file','name':'jsdshell.mak'}
,{'type':'file','name':'jsdstubs.c'}
,{'type':'file','name':'mkshell.bat'}
,{'type':'file','name':'resource.h'}
]}
,{'type':'directory','name':'src','contents':[
{'type':'directory','name':'CVS','contents':[
{'type':'file','name':'Entries'}
,{'type':'file','name':'Repository'}
,{'type':'file','name':'Root'}
,{'type':'file','name':'Tag'}
]}
,{'type':'file','name':'Makefile.in'}
,{'type':'file','name':'Makefile.ref'}
,{'type':'file','name':'README.html'}
,{'type':'file','name':'SpiderMonkey.rsp'}
,{'type':'directory','name':'config','contents':[
{'type':'file','name':'AIX4.1.mk'}
,{'type':'file','name':'AIX4.2.mk'}
,{'type':'file','name':'AIX4.3.mk'}
,{'type':'directory','name':'CVS','contents':[
{'type':'file','name':'Entries'}
,{'type':'file','name':'Repository'}
,{'type':'file','name':'Root'}
,{'type':'file','name':'Tag'}
]}
,{'type':'file','name':'Darwin.mk'}
,{'type':'file','name':'Darwin1.3.mk'}
,{'type':'file','name':'Darwin1.4.mk'}
,{'type':'file','name':'Darwin5.2.mk'}
,{'type':'file','name':'Darwin5.3.mk'}
,{'type':'file','name':'HP-UXB.10.10.mk'}
,{'type':'file','name':'HP-UXB.10.20.mk'}
,{'type':'file','name':'HP-UXB.11.00.mk'}
,{'type':'file','name':'IRIX.mk'}
,{'type':'file','name':'IRIX5.3.mk'}
,{'type':'file','name':'IRIX6.1.mk'}
,{'type':'file','name':'IRIX6.2.mk'}
,{'type':'file','name':'IRIX6.3.mk'}
,{'type':'file','name':'IRIX6.5.mk'}
,{'type':'file','name':'Linux_All.mk'}
,{'type':'file','name':'Mac_OS10.0.mk'}
,{'type':'file','name':'OSF1V4.0.mk'}
,{'type':'file','name':'OSF1V5.0.mk'}
,{'type':'file','name':'SunOS4.1.4.mk'}
,{'type':'file','name':'SunOS5.3.mk'}
,{'type':'file','name':'SunOS5.4.mk'}
,{'type':'file','name':'SunOS5.5.1.mk'}
,{'type':'file','name':'SunOS5.5.mk'}
,{'type':'file','name':'SunOS5.6.mk'}
,{'type':'file','name':'SunOS5.7.mk'}
,{'type':'file','name':'SunOS5.8.mk'}
,{'type':'file','name':'SunOS5.9.mk'}
,{'type':'file','name':'WINNT4.0.mk'}
,{'type':'file','name':'WINNT5.0.mk'}
,{'type':'file','name':'WINNT5.1.mk'}
,{'type':'file','name':'WINNT5.2.mk'}
,{'type':'file','name':'dgux.mk'}
]}
,{'type':'file','name':'config.mk'}
,{'type':'directory','name':'editline','contents':[
{'type':'directory','name':'CVS','contents':[
{'type':'file','name':'Entries'}
,{'type':'file','name':'Repository'}
,{'type':'file','name':'Root'}
,{'type':'file','name':'Tag'}
]}
,{'type':'file','name':'Makefile.ref'}
,{'type':'file','name':'README'}
,{'type':'file','name':'editline.3'}
,{'type':'file','name':'editline.c'}
,{'type':'file','name':'editline.h'}
,{'type':'file','name':'sysunix.c'}
,{'type':'file','name':'unix.h'}
]}
,{'type':'directory','name':'fdlibm','contents':[
{'type':'directory','name':'CVS','contents':[
{'type':'file','name':'Entries'}
,{'type':'file','name':'Repository'}
,{'type':'file','name':'Root'}
,{'type':'file','name':'Tag'}
]}
,{'type':'file','name':'Makefile.in'}
,{'type':'file','name':'Makefile.ref'}
,{'type':'file','name':'e_acos.c'}
,{'type':'file','name':'e_acosh.c'}
,{'type':'file','name':'e_asin.c'}
,{'type':'file','name':'e_atan2.c'}
,{'type':'file','name':'e_atanh.c'}
,{'type':'file','name':'e_cosh.c'}
,{'type':'file','name':'e_exp.c'}
,{'type':'file','name':'e_fmod.c'}
,{'type':'file','name':'e_gamma.c'}
,{'type':'file','name':'e_gamma_r.c'}
,{'type':'file','name':'e_hypot.c'}
,{'type':'file','name':'e_j0.c'}
,{'type':'file','name':'e_j1.c'}
,{'type':'file','name':'e_jn.c'}
,{'type':'file','name':'e_lgamma.c'}
,{'type':'file','name':'e_lgamma_r.c'}
,{'type':'file','name':'e_log.c'}
,{'type':'file','name':'e_log10.c'}
,{'type':'file','name':'e_pow.c'}
,{'type':'file','name':'e_rem_pio2.c'}
,{'type':'file','name':'e_remainder.c'}
,{'type':'file','name':'e_scalb.c'}
,{'type':'file','name':'e_sinh.c'}
,{'type':'file','name':'e_sqrt.c'}
,{'type':'file','name':'fdlibm.h'}
,{'type':'file','name':'fdlibm.mak'}
,{'type':'file','name':'fdlibm.mdp'}
,{'type':'file','name':'k_cos.c'}
,{'type':'file','name':'k_rem_pio2.c'}
,{'type':'file','name':'k_sin.c'}
,{'type':'file','name':'k_standard.c'}
,{'type':'file','name':'k_tan.c'}
,{'type':'file','name':'s_asinh.c'}
,{'type':'file','name':'s_atan.c'}
,{'type':'file','name':'s_cbrt.c'}
,{'type':'file','name':'s_ceil.c'}
,{'type':'file','name':'s_copysign.c'}
,{'type':'file','name':'s_cos.c'}
,{'type':'file','name':'s_erf.c'}
,{'type':'file','name':'s_expm1.c'}
,{'type':'file','name':'s_fabs.c'}
,{'type':'file','name':'s_finite.c'}
,{'type':'file','name':'s_floor.c'}
,{'type':'file','name':'s_frexp.c'}
,{'type':'file','name':'s_ilogb.c'}
,{'type':'file','name':'s_isnan.c'}
,{'type':'file','name':'s_ldexp.c'}
,{'type':'file','name':'s_lib_version.c'}
,{'type':'file','name':'s_log1p.c'}
,{'type':'file','name':'s_logb.c'}
,{'type':'file','name':'s_matherr.c'}
,{'type':'file','name':'s_modf.c'}
,{'type':'file','name':'s_nextafter.c'}
,{'type':'file','name':'s_rint.c'}
,{'type':'file','name':'s_scalbn.c'}
,{'type':'file','name':'s_signgam.c'}
,{'type':'file','name':'s_significand.c'}
,{'type':'file','name':'s_sin.c'}
,{'type':'file','name':'s_tan.c'}
,{'type':'file','name':'s_tanh.c'}
,{'type':'file','name':'w_acos.c'}
,{'type':'file','name':'w_acosh.c'}
,{'type':'file','name':'w_asin.c'}
,{'type':'file','name':'w_atan2.c'}
,{'type':'file','name':'w_atanh.c'}
,{'type':'file','name':'w_cosh.c'}
,{'type':'file','name':'w_exp.c'}
,{'type':'file','name':'w_fmod.c'}
,{'type':'file','name':'w_gamma.c'}
,{'type':'file','name':'w_gamma_r.c'}
,{'type':'file','name':'w_hypot.c'}
,{'type':'file','name':'w_j0.c'}
,{'type':'file','name':'w_j1.c'}
,{'type':'file','name':'w_jn.c'}
,{'type':'file','name':'w_lgamma.c'}
,{'type':'file','name':'w_lgamma_r.c'}
,{'type':'file','name':'w_log.c'}
,{'type':'file','name':'w_log10.c'}
,{'type':'file','name':'w_pow.c'}
,{'type':'file','name':'w_remainder.c'}
,{'type':'file','name':'w_scalb.c'}
,{'type':'file','name':'w_sinh.c'}
,{'type':'file','name':'w_sqrt.c'}
]}
,{'type':'file','name':'js.c'}
,{'type':'file','name':'js.mak'}
,{'type':'file','name':'js.mdp'}
,{'type':'file','name':'js.msg'}
,{'type':'file','name':'js.pkg'}
,{'type':'file','name':'js3240.rc'}
,{'type':'file','name':'jsOS240.def'}
,{'type':'file','name':'jsapi.c'}
,{'type':'file','name':'jsapi.h'}
,{'type':'file','name':'jsarena.c'}
,{'type':'file','name':'jsarena.h'}
,{'type':'file','name':'jsarray.c'}
,{'type':'file','name':'jsarray.h'}
,{'type':'file','name':'jsatom.c'}
,{'type':'file','name':'jsatom.h'}
,{'type':'file','name':'jsbit.h'}
,{'type':'file','name':'jsbool.c'}
,{'type':'file','name':'jsbool.h'}
,{'type':'file','name':'jsclist.h'}
,{'type':'file','name':'jscntxt.c'}
,{'type':'file','name':'jscntxt.h'}
,{'type':'file','name':'jscompat.h'}
,{'type':'file','name':'jsconfig.h'}
,{'type':'file','name':'jsconfig.mk'}
,{'type':'file','name':'jscpucfg.c'}
,{'type':'file','name':'jscpucfg.h'}
,{'type':'file','name':'jsdate.c'}
,{'type':'file','name':'jsdate.h'}
,{'type':'file','name':'jsdbgapi.c'}
,{'type':'file','name':'jsdbgapi.h'}
,{'type':'file','name':'jsdhash.c'}
,{'type':'file','name':'jsdhash.h'}
,{'type':'file','name':'jsdtoa.c'}
,{'type':'file','name':'jsdtoa.h'}
,{'type':'file','name':'jsemit.c'}
,{'type':'file','name':'jsemit.h'}
,{'type':'file','name':'jsexn.c'}
,{'type':'file','name':'jsexn.h'}
,{'type':'file','name':'jsfile.c'}
,{'type':'file','name':'jsfile.h'}
,{'type':'file','name':'jsfile.msg'}
,{'type':'file','name':'jsfun.c'}
,{'type':'file','name':'jsfun.h'}
,{'type':'file','name':'jsgc.c'}
,{'type':'file','name':'jsgc.h'}
,{'type':'file','name':'jshash.c'}
,{'type':'file','name':'jshash.h'}
,{'type':'file','name':'jsify.pl'}
,{'type':'file','name':'jsinterp.c'}
,{'type':'file','name':'jsinterp.h'}
,{'type':'file','name':'jslibmath.h'}
,{'type':'file','name':'jslock.c'}
,{'type':'file','name':'jslock.h'}
,{'type':'file','name':'jslocko.asm'}
,{'type':'file','name':'jslog2.c'}
,{'type':'file','name':'jslong.c'}
,{'type':'file','name':'jslong.h'}
,{'type':'file','name':'jsmath.c'}
,{'type':'file','name':'jsmath.h'}
,{'type':'file','name':'jsnum.c'}
,{'type':'file','name':'jsnum.h'}
,{'type':'file','name':'jsobj.c'}
,{'type':'file','name':'jsobj.h'}
,{'type':'file','name':'jsopcode.c'}
,{'type':'file','name':'jsopcode.h'}
,{'type':'file','name':'jsopcode.tbl'}
,{'type':'file','name':'jsosdep.h'}
,{'type':'file','name':'jsotypes.h'}
,{'type':'file','name':'jsparse.c'}
,{'type':'file','name':'jsparse.h'}
,{'type':'file','name':'jsprf.c'}
,{'type':'file','name':'jsprf.h'}
,{'type':'file','name':'jsprvtd.h'}
,{'type':'file','name':'jspubtd.h'}
,{'type':'file','name':'jsregexp.c'}
,{'type':'file','name':'jsregexp.h'}
,{'type':'file','name':'jsscan.c'}
,{'type':'file','name':'jsscan.h'}
,{'type':'file','name':'jsscope.c'}
,{'type':'file','name':'jsscope.h'}
,{'type':'file','name':'jsscript.c'}
,{'type':'file','name':'jsscript.h'}
,{'type':'file','name':'jsshell.msg'}
,{'type':'file','name':'jsstddef.h'}
,{'type':'file','name':'jsstr.c'}
,{'type':'file','name':'jsstr.h'}
,{'type':'file','name':'jstypes.h'}
,{'type':'file','name':'jsutil.c'}
,{'type':'file','name':'jsutil.h'}
,{'type':'file','name':'jsxdrapi.c'}
,{'type':'file','name':'jsxdrapi.h'}
,{'type':'directory','name':'liveconnect','contents':[
{'type':'directory','name':'CVS','contents':[
{'type':'file','name':'Entries'}
,{'type':'file','name':'Entries.Log'}
,{'type':'file','name':'Repository'}
,{'type':'file','name':'Root'}
,{'type':'file','name':'Tag'}
]}
,{'type':'file','name':'LiveConnect.dsp'}
,{'type':'file','name':'LiveConnectShell.dsp'}
,{'type':'file','name':'LiveConnectShell.dsw'}
,{'type':'file','name':'Makefile.in'}
,{'type':'file','name':'Makefile.ref'}
,{'type':'file','name':'README.html'}
,{'type':'directory','name':'_jni','contents':[
{'type':'directory','name':'CVS','contents':[
{'type':'file','name':'Entries'}
,{'type':'file','name':'Repository'}
,{'type':'file','name':'Root'}
,{'type':'file','name':'Tag'}
]}
,{'type':'file','name':'netscape_javascript_JSException.h'}
,{'type':'file','name':'netscape_javascript_JSObject.h'}
]}
,{'type':'directory','name':'classes','contents':[
{'type':'directory','name':'CVS','contents':[
{'type':'file','name':'Entries'}
,{'type':'file','name':'Entries.Log'}
,{'type':'file','name':'Repository'}
,{'type':'file','name':'Root'}
,{'type':'file','name':'Tag'}
]}
,{'type':'file','name':'Makefile.in'}
,{'type':'file','name':'Makefile.ref'}
,{'type':'directory','name':'netscape','contents':[
{'type':'directory','name':'CVS','contents':[
{'type':'file','name':'Entries'}
,{'type':'file','name':'Repository'}
,{'type':'file','name':'Root'}
,{'type':'file','name':'Tag'}
]}
,{'type':'file','name':'Makefile.ref'}
,{'type':'directory','name':'javascript','contents':[
{'type':'directory','name':'CVS','contents':[
{'type':'file','name':'Entries'}
,{'type':'file','name':'Repository'}
,{'type':'file','name':'Root'}
,{'type':'file','name':'Tag'}
]}
,{'type':'file','name':'JSException.java'}
,{'type':'file','name':'JSObject.java'}
,{'type':'file','name':'JSProxy.java'}
,{'type':'file','name':'JSRunnable.java'}
,{'type':'file','name':'JSUtil.java'}
,{'type':'file','name':'Makefile.ref'}
]}
]}
]}
,{'type':'directory','name':'config','contents':[
{'type':'file','name':'AIX4.1.mk'}
,{'type':'file','name':'AIX4.2.mk'}
,{'type':'file','name':'AIX4.3.mk'}
,{'type':'directory','name':'CVS','contents':[
{'type':'file','name':'Entries'}
,{'type':'file','name':'Repository'}
,{'type':'file','name':'Root'}
,{'type':'file','name':'Tag'}
]}
,{'type':'file','name':'HP-UXB.10.10.mk'}
,{'type':'file','name':'HP-UXB.10.20.mk'}
,{'type':'file','name':'HP-UXB.11.00.mk'}
,{'type':'file','name':'IRIX6.2.mk'}
,{'type':'file','name':'IRIX6.3.mk'}
,{'type':'file','name':'IRIX6.5.mk'}
,{'type':'file','name':'Linux_All.mk'}
,{'type':'file','name':'OSF1V4.0.mk'}
,{'type':'file','name':'OSF1V5.0.mk'}
,{'type':'file','name':'SunOS5.5.1.mk'}
,{'type':'file','name':'SunOS5.6.mk'}
,{'type':'file','name':'SunOS5.7.mk'}
,{'type':'file','name':'SunOS5.8.mk'}
,{'type':'file','name':'WINNT4.0.mk'}
]}
,{'type':'file','name':'jsj.c'}
,{'type':'file','name':'jsj.msg'}
,{'type':'file','name':'jsj_JSObject.c'}
,{'type':'file','name':'jsj_JavaArray.c'}
,{'type':'file','name':'jsj_JavaClass.c'}
,{'type':'file','name':'jsj_JavaMember.c'}
,{'type':'file','name':'jsj_JavaObject.c'}
,{'type':'file','name':'jsj_JavaPackage.c'}
,{'type':'file','name':'jsj_array.c'}
,{'type':'file','name':'jsj_class.c'}
,{'type':'file','name':'jsj_convert.c'}
,{'type':'file','name':'jsj_field.c'}
,{'type':'file','name':'jsj_hash.c'}
,{'type':'file','name':'jsj_hash.h'}
,{'type':'file','name':'jsj_method.c'}
,{'type':'file','name':'jsj_nodl.c'}
,{'type':'file','name':'jsj_private.h'}
,{'type':'file','name':'jsj_simpleapi.c'}
,{'type':'file','name':'jsj_utils.c'}
,{'type':'file','name':'jsjava.h'}
,{'type':'file','name':'liveconnect.pkg'}
,{'type':'file','name':'netscape_javascript_JSObject.h'}
,{'type':'file','name':'nsCLiveconnect.cpp'}
,{'type':'file','name':'nsCLiveconnect.h'}
,{'type':'file','name':'nsCLiveconnectFactory.cpp'}
,{'type':'file','name':'nsCLiveconnectFactory.h'}
,{'type':'file','name':'nsILiveconnect.h'}
,{'type':'file','name':'nsISecureLiveconnect.h'}
,{'type':'file','name':'nsISecurityContext.h'}
,{'type':'file','name':'win32.order'}
]}
,{'type':'file','name':'lock_SunOS.s'}
,{'type':'file','name':'perfect.js'}
,{'type':'directory','name':'perlconnect','contents':[
{'type':'directory','name':'CVS','contents':[
{'type':'file','name':'Entries'}
,{'type':'file','name':'Repository'}
,{'type':'file','name':'Root'}
,{'type':'file','name':'Tag'}
]}
,{'type':'file','name':'JS.def'}
,{'type':'file','name':'JS.dsp'}
,{'type':'file','name':'JS.pm'}
,{'type':'file','name':'JS.xs'}
,{'type':'file','name':'Makefile.PL'}
,{'type':'file','name':'Makefile.ref'}
,{'type':'file','name':'PerlConnect.dsp'}
,{'type':'file','name':'PerlConnect.dsw'}
,{'type':'file','name':'PerlConnect.pm'}
,{'type':'file','name':'PerlConnectShell.dsp'}
,{'type':'file','name':'README.html'}
,{'type':'file','name':'bg.jpg'}
,{'type':'file','name':'jsperl.c'}
,{'type':'file','name':'jsperl.h'}
,{'type':'file','name':'jsperlbuild.pl'}
,{'type':'file','name':'jsperlpvt.h'}
,{'type':'file','name':'test.js'}
,{'type':'file','name':'test.pl'}
,{'type':'file','name':'typemap'}
]}
,{'type':'file','name':'plify_jsdhash.sed'}
,{'type':'file','name':'prmjtime.c'}
,{'type':'file','name':'prmjtime.h'}
,{'type':'file','name':'resource.h'}
,{'type':'file','name':'rules.mk'}
,{'type':'file','name':'win32.order'}
]}
]}
]};
elem.innerHTML = template.render(data);
|
urain39/ij2tpl.js
|
ij2tpl.ts
|
<reponame>urain39/ij2tpl.js
/**
* @file IJ2TPL.js - A Lightweight Template Engine.
* @version v0.1.3
* @author urain39 <<EMAIL>>
* @copyright (c) 2018-2020 IJ2TPL.js / IJ2TPL.ts Authors.
*/
/* eslint-disable prefer-const */
export const version: string = '0.1.3';
/* eslint-disable no-unused-vars */
// FIXME: ^^^ It seems that is a bug of ESLint
const enum TokenString {
IF = '?'
, NOT = '!'
, ELSE = '*'
, END = '/'
, RAW = '#'
, COMMENT = '-'
, PARTIAL = '@'
}
const enum TokenType {
IF = 0
, NOT
, ELSE
, END
, TEXT
, RAW
, FORMAT
, COMMENT // Used for initialization only
, PARTIAL
}
const enum TokenMember {
TYPE = 0
, VALUE
, BLOCK
, INDENTATION = 2
, ELSE_BLOCK
}
const enum NameMember {
NAME = 0
, NAMES
, FILTERS
, IS_ACTION
}
/* eslint-enable no-unused-vars */
// Compatible tokenized tokens
type _Token = [TokenType, string, string?];
// ^^^ INDENTATION
// NAME NAMES FILTERS IS_ACTION
export type Name = [string, string[] | null, string[] | null, boolean];
// See https://github.com/microsoft/TypeScript/pull/33050
// https://stackoverflow.com/questions/47842266/recursive-types-in-typescript
type SectionTuple<T> = [TokenType, Name, T[], T[] | null];
// ^^^ BLOCK, ELSE_BLOCK
export interface Section extends SectionTuple<Section> {}
export type Text = _Token; // Text token same as tokenized token
export type Formatter = [TokenType, Name];
export type Partial = [TokenType, string, string];
// Token literally compatible all tokens
export type Token = _Token | Section | Text | Formatter | Partial;
// See TS1023, an index type must be `string` or `number`
interface IMap< /* K, */ V> { [key: string]: V; [index: number]: V; }
// FIXME: It's also a bug of ESLint
// eslint-disable-next-line no-unused-vars
export type Filter = (value: any, context?: Context | null) => any;
let filterMap: IMap<Filter> = {};
export function setFilterMap(filterMap_: IMap<Filter>): void {
filterMap = filterMap_;
}
// See https://github.com/microsoft/TypeScript/issues/14682
const TokenTypeMap: IMap<TokenType> = {
[TokenString.IF]: TokenType.IF
, [TokenString.NOT]: TokenType.NOT
, [TokenString.ELSE]: TokenType.ELSE
, [TokenString.END]: TokenType.END
, [TokenString.RAW]: TokenType.RAW
, [TokenString.PARTIAL]: TokenType.PARTIAL
};
// NOTE: If we use `IndentedTestRe` with capture-group directly, the `<string>.replace` method
// will always generate a new string. So we need test it before replace it ;)
const IndentedTestRe = /(^|[\n\r])([\t \xA0\uFEFF]+)$/
// ^^^ To support IE6, we cannot use non-capturing groups
, IndentedWhiteSpaceRe = /[\t \xA0\uFEFF]+$/
, stripIndentation = (token: _Token, tokens: _Token[]): string => {
let value: string
, result: ReturnType<typeof String.prototype.match>
, indentation: string = '';
// Remove token's indentation if exists
if (token[TokenMember.TYPE] === TokenType.TEXT) {
token = token as Text;
value = token[TokenMember.VALUE];
// eslint-disable-next-line no-cond-assign
if (result = value.match(IndentedTestRe))
indentation = result[2],
value = value.replace(IndentedWhiteSpaceRe, '');
if(value)
token[TokenMember.VALUE] = value;
else
tokens.pop(); // Don't save text that has become empty
}
return indentation;
}
// We strip all white spaces to make check section easy(for `buildTree`)
, WhiteSpaceRe = /[\s\xA0\uFEFF]+/g
, stripWhiteSpace = (string_: string): string => string_.replace(WhiteSpaceRe, '');
export function tokenize(source: string, prefix: string, suffix: string): _Token[] {
let type_: string
, value: string
, indentation: string
, token: Token = [TokenType.COMMENT, ''] // Initialized for first backward check
, tokens: _Token[] = [];
for (let i = 0, j = 0
, l = source.length
, pl = prefix.length
, sl = suffix.length; i < l;
) {
// Match '{'
j = source.indexOf(prefix, i);
// Not found the '{'
if (j === -1) {
// Eat the rest of the source
value = source.slice(i);
// Don't save the empty text ''
if (value)
token = [TokenType.TEXT, value], tokens.push(token);
break; // Done
}
// Eat the left side of a token
value = source.slice(i, j);
j += pl; // Skip the '{'
if (value)
token = [TokenType.TEXT, value], tokens.push(token);
// Match the '}'
i = source.indexOf(suffix, j);
// Not found the '}'
if (i === -1)
throw new Error(`No matching prefix '${prefix}'`);
// We don't want to call `source.slice` for comments
if (source.charAt(j) === TokenString.COMMENT) {
stripIndentation(token, tokens);
i += sl; // Skip the '}' for comments
token = [TokenType.COMMENT, '']; // Don't forget to update `token`
continue; // Tokenize next one
}
// Eat the text between the '{' and '}'
value = source.slice(j, i);
i += sl; // Skip the '}' for tokens
value = stripWhiteSpace(value);
if (!value)
continue; // Skip the empty token, such as '{}'
type_ = value.charAt(0);
switch (type_) {
case TokenString.IF:
case TokenString.NOT:
case TokenString.ELSE:
case TokenString.END:
case TokenString.PARTIAL:
indentation = stripIndentation(token, tokens);
// Skip section's newline if exists
if (i < l) {
switch (source.charAt(i)) {
case '\n':
i += 1; // LF
break;
case '\r':
// Have next character?
i += (j = i + 1) < l ?
// Yes, next character is LF?
source.charAt(j) === '\n' ?
2 // Yes, then newline is CRLF
:
1 // No, then newline is CR
:
1 // No, then newline is CR
;
break;
}
}
token = [TokenTypeMap[type_], value.slice(1), indentation],
tokens.push(token);
break;
case TokenString.RAW:
token = [TokenTypeMap[type_], value.slice(1)],
tokens.push(token);
break;
default:
token = [TokenType.FORMAT, value],
tokens.push(token);
break;
}
}
return tokens;
}
const hasOwnProperty = {}.hasOwnProperty
// See https://github.com/janl/mustache.js/pull/530
, htmlSpecialRe = /["&'\/<=>`]/g // eslint-disable-line no-useless-escape
, htmlSpecialEntityMap: IMap<string> = {
'"': '"'
, '&': '&'
, "'": ''' // eslint-disable-line quotes
, '/': '/'
, '<': '<'
, '=': '='
, '>': '>'
, '`': '`'
}
, escapeHTML = (value: any): string => String(value).replace(
htmlSpecialRe, (special: string): string => htmlSpecialEntityMap[special]
);
let escapeFunction = escapeHTML; // Escape for HTML by default
export function escape(value: any): string {
return escapeFunction(value);
}
export function setEscapeFunction(escapeFunction_: (value: any) => string): void {
escapeFunction = escapeFunction_;
}
export class Context {
public data: IMap<any>;
public cache: IMap<any>;
public parent: Context | null;
public constructor(data: IMap<any>, parent: Context | null) {
this.data = data;
this.cache = { '.': this.data };
this.parent = parent;
}
public resolve(name: Name): any {
let data: IMap<any>
, cache: IMap<any>
, name_: string
, name__: string
, names: string[]
, filters: string[]
, value: any = null
, context: Context | null = this
, hasProperties: boolean = false;
if (!name[NameMember.IS_ACTION]) {
cache = context.cache;
name_ = name[NameMember.NAME];
// Cached in context?
if (hasOwnProperty.call(cache, name_)) {
value = cache[name_];
} else { // No cached records found
// eslint-disable-next-line no-cond-assign
if (names = name[NameMember.NAMES] as string[]) {
name__ = names[0];
hasProperties = true;
} else {
name__ = name_;
}
// Try to look up the name in data
do {
data = context.data;
// Find out which context contains name
if (data && hasOwnProperty.call(data, name__)) {
value = data[name__];
// Resolve properties if exists
if (hasProperties) {
for (let i = 1, l = names.length; i < l; i++) {
name__ = names[i];
if (value && hasOwnProperty.call(value, name__)) {
value = value[name__];
} else {
value = null; // Reset
break;
}
}
}
break;
}
context = context.parent;
} while (context);
// Support for function
if (typeof value === 'function')
value = value(context);
// Cache the name
cache[name_] = value;
}
}
// eslint-disable-next-line no-cond-assign
if (filters = name[NameMember.FILTERS] as string[]) {
for (let i = 0, l = filters.length, filterName; i < l;) {
filterName = filters[i++];
if (hasOwnProperty.call(filterMap, filterName))
value = filterMap[filterName](value, context);
else
throw new Error(`Cannot resolve filter '${filterName}'`);
}
}
return value;
}
}
let isArray = Array.isArray;
if (!isArray) {
const toString = {}.toString;
// XXX: Fix a possible issue
isArray = <typeof Array.isArray>function<T>(value: T[]): value is T[] {
return toString.call(value) === '[object Array]';
};
}
export class Renderer {
public treeRoot: Token[];
public constructor(treeRoot: Token[]) {
this.treeRoot = treeRoot;
}
/**
* Do NOT invoke it directly, you should just call `render`
*/
private renderTree(treeRoot: Token[], context: Context, partialMap?: IMap<Renderer>): string {
const BEGINNING_RE = /^(.+)$/gm; // We don't want to indent empty lines
let value: any
, valueLength!: number
, section: Section
, indentation: string
, buffer: string = ''
, isArray_: boolean = false;
for (let i = 0, l = treeRoot.length, token; i < l;) {
token = treeRoot[i++];
switch (token[TokenMember.TYPE]) {
case TokenType.IF:
section = token as Section;
value = context.resolve(section[TokenMember.VALUE]);
isArray_ = isArray(value);
// We can only know true or false after we sure it is array or not
if (isArray_ ? valueLength = value.length : value) {
if (isArray_)
for (let i = 0, l = valueLength, value_; i < l;) {
value_ = value[i++];
buffer += this.renderTree(
section[TokenMember.BLOCK]
, new Context(value_, context)
, partialMap
);
}
else
buffer += this.renderTree(
section[TokenMember.BLOCK]
, new Context(value, context)
, partialMap
);
}
break;
case TokenType.NOT:
section = token as Section;
value = context.resolve(section[TokenMember.VALUE]);
isArray_ = isArray(value);
if (!(isArray_ ? value.length : value))
buffer += this.renderTree(
section[TokenMember.BLOCK]
, context
, partialMap
);
break;
// FIXME: It may be slower than If-Section + Not-Section(about 1 ops/sec)
case TokenType.ELSE:
section = token as Section;
value = context.resolve(section[TokenMember.VALUE]);
isArray_ = isArray(value);
if (isArray_ ? valueLength = value.length : value) {
if (isArray_)
for (let i = 0, l = valueLength, value_; i < l;) {
value_ = value[i++];
buffer += this.renderTree(
section[TokenMember.BLOCK]
, new Context(value_, context)
, partialMap
);
}
else
buffer += this.renderTree(
section[TokenMember.BLOCK]
, new Context(value, context)
, partialMap
);
} else {
buffer += this.renderTree(
section[TokenMember.ELSE_BLOCK] as Token[]
, context
, partialMap
);
}
break;
case TokenType.TEXT:
token = token as Text;
value = token[TokenMember.VALUE];
// Empty text has been skipped when tokenizing
buffer += value;
break;
case TokenType.RAW:
token = token as Formatter;
value = context.resolve(token[TokenMember.VALUE]);
// Check if it is non-values(null and undefined)
if (value != null)
buffer += value;
break;
case TokenType.FORMAT:
token = token as Formatter;
value = context.resolve(token[TokenMember.VALUE]);
if (value != null)
buffer += escapeFunction === escapeHTML && typeof value === 'number' ?
value // Numbers are absolutely safe for HTML
:
escapeFunction(value)
;
break;
case TokenType.PARTIAL:
token = token as Partial;
value = token[TokenMember.VALUE];
indentation = token[TokenMember.INDENTATION];
if (value === '&') { // Recursive render with parents
buffer += this.renderTree(this.treeRoot, context, partialMap)
.replace(BEGINNING_RE, `${indentation}$&`);
} else if (value === '^') { // Recursive render without parents
buffer += this.renderTree(this.treeRoot, new Context(context.data, null), partialMap)
.replace(BEGINNING_RE, `${indentation}$&`);
} else if (partialMap && hasOwnProperty.call(partialMap, value))
buffer += this.renderTree(partialMap[value].treeRoot, context, partialMap)
.replace(BEGINNING_RE, `${indentation}$&`);
else
throw new Error(`Cannot resolve partial '${value}'`);
break;
}
}
return buffer;
}
public render(data: IMap<any>, partialMap?: IMap<Renderer>): string {
return this.renderTree(
this.treeRoot, new Context(data, null), partialMap
);
}
}
const TokenTypeReverseMap: IMap<TokenString> = {
[TokenType.IF]: TokenString.IF
, [TokenType.NOT]: TokenString.NOT
, [TokenType.ELSE]: TokenString.ELSE
, [TokenType.END]: TokenString.END
};
const processToken = (token_: _Token): Section | Formatter => {
let name: string
, names: string[] | null
, filters: string[] | null
, isAction: boolean
, token: Token;
names = null;
filters = null;
isAction = false;
name = token_[TokenMember.VALUE];
// NOTE: Name can be empty
if (name.indexOf('|') !== -1) {
filters = name.split('|');
name = filters[0];
filters = filters.slice(1);
if (!name)
isAction = true;
}
// One '.' means current data
if (name.indexOf('.') > 0)
names = name.split('.');
// NOTE: Filters are just additional part of Token
token = [token_[TokenMember.TYPE], [name, names, filters, isAction]];
return token;
};
function buildTree(tokens: _Token[]): Token[] {
let type_: TokenType
, value: string
, token: Token
, collector: Token[]
, elseBlock: Token[]
, section: Section | undefined
, sections: Section[] = []
, sectionsLength: number
, treeRoot: Token[] = [];
collector = treeRoot;
for (let i = 0, l = tokens.length, token_; i < l;) {
token_ = tokens[i++];
type_ = token_[TokenMember.TYPE];
switch (type_) {
// Enter a section
case TokenType.IF:
case TokenType.NOT:
token = processToken(token_); // Make `_Token` -> `Token`
collector.push(token); // Current block saves token
section = token as Section;
sections.push(section); // Stack saves section
// Initialize and switch to section's block
collector = section[TokenMember.BLOCK] = [];
section[TokenMember.ELSE_BLOCK] = null; // Padding?
break;
// Switch to section's else-block
case TokenType.ELSE:
// Get entered section
// eslint-disable-next-line no-cond-assign
section = (sectionsLength = sections.length) ?
sections[sectionsLength - 1]
:
void 0x95E2 // Reset
;
value = token_[TokenMember.VALUE];
if (!section ||
// `ELSE` are valid for `IF`, invalid for `NOT`
section[TokenMember.TYPE] !== TokenType.IF ||
value !== section[TokenMember.VALUE][NameMember.NAME]
)
throw new Error(`Unexpected token '<type=${TokenTypeReverseMap[type_]}, value=${value}>'`);
// Initialize and switch to section's else-block
collector = section[TokenMember.ELSE_BLOCK] = [];
break;
// Leave a section
case TokenType.END:
section = sections.pop();
value = token_[TokenMember.VALUE];
if (!section ||
value !== section[TokenMember.VALUE][NameMember.NAME]
)
throw new Error(`Unexpected token '<type=${TokenTypeReverseMap[type_]}, value=${value}>'`);
// Change type for which section contains initialized else-block
if (section[TokenMember.ELSE_BLOCK])
section[TokenMember.TYPE] = TokenType.ELSE;
// Re-bind block to parent block
// eslint-disable-next-line no-cond-assign
collector = (sectionsLength = sections.length) ?
// Is parent section has initialized else-block?
(section = sections[sectionsLength - 1]
, elseBlock = section[TokenMember.ELSE_BLOCK] as Token[]
) ?
// Yes, then parent block is else-block
elseBlock
:
// No, then parent block is (if-)block
section[TokenMember.BLOCK]
:
treeRoot;
break;
// Formatter
case TokenType.RAW:
case TokenType.FORMAT:
token = processToken(token_);
collector.push(token);
break;
// Text or Partial
default:
collector.push(token_);
break;
}
}
if (sections.length) {
section = sections.pop() as Section;
throw new Error(`No matching section '<type=${
TokenTypeReverseMap[section[TokenMember.TYPE]]}, value=${section[TokenMember.VALUE][NameMember.NAME]}>'`);
}
return treeRoot;
}
export function parse(source: string, prefix: string = '{', suffix: string = '}'): Renderer {
const treeRoot = buildTree(tokenize(
source, prefix, suffix
));
return new Renderer(treeRoot);
}
|
alexandresantosm/clean-cache-control
|
src/data/usecases/index.ts
|
export * from "./load-purchases/local-load-purchases";
|
alexandresantosm/clean-cache-control
|
src/data/protocols/cache/cache-store.ts
|
<filename>src/data/protocols/cache/cache-store.ts
export interface CacheStore {
fetch: (key: string) => any;
delete: (key: string) => void;
insert: (key: string, value: any) => void;
replace: (key: string, value: any) => void;
}
|
alexandresantosm/clean-cache-control
|
src/domain/usecases/index.ts
|
<reponame>alexandresantosm/clean-cache-control
export * from "./save-purchases";
export * from "./load-purchases";
|
alexandresantosm/clean-cache-control
|
src/data/usecases/load-purchases/local-load-purchases.ts
|
<gh_stars>0
import { CachePolicy, CacheStore } from "@/data/protocols/cache";
import { SavePurchases, LoadPurchases } from "@/domain/usecases";
export class LocalLoadPurchases implements SavePurchases, LoadPurchases {
private readonly key = "purchases";
constructor(
private readonly cacheStore: CacheStore,
private readonly currentDate: Date
) {}
async save(purchases: Array<SavePurchases.Params>): Promise<void> {
this.cacheStore.replace(this.key, {
timestamp: this.currentDate,
value: purchases,
});
}
async loadAll(): Promise<Array<LoadPurchases.Result>> {
try {
const cache = this.cacheStore.fetch(this.key);
const isValidDate = CachePolicy.validate(
cache.timestamp,
this.currentDate
);
return isValidDate ? cache.value : [];
} catch (error) {
return [];
}
}
validate(): void {
try {
const cache = this.cacheStore.fetch(this.key);
const isValidDate = CachePolicy.validate(
cache.timestamp,
this.currentDate
);
if (!isValidDate) {
throw new Error();
}
} catch (error) {
this.cacheStore.delete(this.key);
}
}
}
|
alexandresantosm/clean-cache-control
|
src/data/protocols/cache/index.ts
|
<gh_stars>0
export * from "./cache-store";
export * from "./cache-policy";
|
alexandresantosm/clean-cache-control
|
src/data/usecases/load-purchases/local-load-purchases.spec.ts
|
import { LocalLoadPurchases } from "@/data/usecases";
import {
CacheStoreSpy,
mockPurchases,
getCacheExpirationDate,
} from "@/data/test";
type SutTypes = {
sut: LocalLoadPurchases;
cacheStore: CacheStoreSpy;
};
const makeSut = (timestamp = new Date()): SutTypes => {
const cacheStore = new CacheStoreSpy();
const sut = new LocalLoadPurchases(cacheStore, timestamp);
return { cacheStore, sut };
};
describe("LocalLoadPurchases", () => {
test("Should not delete or insert cache on sut.init", () => {
const { cacheStore } = makeSut();
expect(cacheStore.actions).toEqual([]);
});
test("Should call correct key on load", async () => {
const { cacheStore, sut } = makeSut();
await sut.loadAll();
expect(cacheStore.fetchKey).toBe("purchases");
});
test("Should return empty list if load fails", async () => {
const { cacheStore, sut } = makeSut();
cacheStore.simulateFetchError();
const purchases = await sut.loadAll();
expect(cacheStore.actions).toEqual([CacheStoreSpy.Action.fetch]);
expect(purchases).toEqual([]);
});
test("Should return a list of purchases if cache is valid", async () => {
const currentDate = new Date();
const timestamp = getCacheExpirationDate(currentDate);
timestamp.setSeconds(timestamp.getSeconds() + 1);
const { cacheStore, sut } = makeSut(currentDate);
cacheStore.fetchResult = {
timestamp,
value: mockPurchases(),
};
const purchases = await sut.loadAll();
expect(cacheStore.actions).toEqual([CacheStoreSpy.Action.fetch]);
expect(cacheStore.fetchKey).toBe("purchases");
expect(purchases).toEqual(cacheStore.fetchResult.value);
});
test("Should return an empty list if cache is expired", async () => {
const currentDate = new Date();
const timestamp = getCacheExpirationDate(currentDate);
timestamp.setSeconds(timestamp.getSeconds() - 1);
const { cacheStore, sut } = makeSut(currentDate);
cacheStore.fetchResult = {
timestamp,
value: mockPurchases(),
};
const purchases = await sut.loadAll();
expect(cacheStore.actions).toEqual([CacheStoreSpy.Action.fetch]);
expect(cacheStore.fetchKey).toBe("purchases");
expect(purchases).toEqual([]);
});
test("Should return an empty list if cache is on expiration date", async () => {
const currentDate = new Date();
const timestamp = getCacheExpirationDate(currentDate);
const { cacheStore, sut } = makeSut(currentDate);
cacheStore.fetchResult = {
timestamp,
value: mockPurchases(),
};
const purchases = await sut.loadAll();
expect(cacheStore.actions).toEqual([CacheStoreSpy.Action.fetch]);
expect(cacheStore.fetchKey).toBe("purchases");
expect(purchases).toEqual([]);
});
test("Should return an empty list if cache is empty", async () => {
const currentDate = new Date();
const timestamp = getCacheExpirationDate(currentDate);
timestamp.setSeconds(timestamp.getSeconds() + 1);
const { cacheStore, sut } = makeSut(currentDate);
cacheStore.fetchResult = {
timestamp,
value: [],
};
const purchases = await sut.loadAll();
expect(cacheStore.actions).toEqual([CacheStoreSpy.Action.fetch]);
expect(cacheStore.fetchKey).toBe("purchases");
expect(purchases).toEqual([]);
});
});
|
alexandresantosm/clean-cache-control
|
src/data/test/index.ts
|
<filename>src/data/test/index.ts
export * from "./mock-purchases";
export * from "./mock-cache";
|
alexandresantosm/clean-cache-control
|
src/domain/usecases/save-purchases.ts
|
import { PurchaseModel } from "@/domain/models";
export interface SavePurchases {
save: (purchases: Array<SavePurchases.Params>) => Promise<void>;
}
export namespace SavePurchases {
export type Params = PurchaseModel;
}
|
alexandresantosm/clean-cache-control
|
src/domain/models/index.ts
|
export * from "./purchasesModel";
|
sofiyaca/NATURL
|
src/components/cart/Cart.tsx
|
<gh_stars>1-10
import React from "react";
import CartItem from "../cartItem/CartItem";
import "./Cart.scss";
import { Link } from "@reach/router";
export default function Cart({
handleClearCartClick,
handleRemoveItemFromCartClick,
onCheckoutClick,
itemsInCart,
totalCost,
}) {
return (
<div className="Cart">
<h2 className="Cart-title">Your shopping cart</h2>
{itemsInCart.length > 0 ? (
<div>
{itemsInCart.map((item) => (
<CartItem
key={item.id}
itemId={item.id}
thumbnail={item.image_link}
name={item.name}
cost={item.price * item.quantity}
selectedColors={item.selectedColors}
quantity={item.quantity}
onRemoveItemFromCartClick={() =>
handleRemoveItemFromCartClick(item.id)
}
/>
))}
<div className="Cart-total-cost">
Total cost: ${totalCost.toFixed(2)}
<button
className="checkout-clearcart-button"
onClick={handleClearCartClick}
>
Clear Cart
</button>
</div>
<div className="Cart-navigation">
<button className="Cart-button-purchase" onClick={onCheckoutClick}>
Proceed To Checkout
</button>
<Link to="/products">
<button className="checkout-continueshopping-button">
Continue Shopping
</button>
</Link>
</div>
</div>
) : (
<div className="Cart-message-empty">Cart is empty</div>
)}
</div>
);
}
|
sofiyaca/NATURL
|
src/components/cartItem/CartItem.tsx
|
<gh_stars>1-10
import React from "react";
import { CloseCircleOutlined } from "@ant-design/icons";
import "./CartItem.scss";
import { Link } from "@reach/router";
export default function CartItem({
itemId,
thumbnail,
name,
cost,
quantity,
selectedColors,
onRemoveItemFromCartClick,
}) {
const productPath = `/product/${itemId}`;
return (
<div className="CartItem">
<div className="CartItem-description">
<div className="CartItem-thumbnail">
<img
className="CartItem-thumbnail-img"
alt="product-thumbnail"
src={thumbnail}
/>
</div>
<Link to={productPath} className="CartItem-product-link">
{name}
</Link>
</div>
<div className="CartItem-details">
<div className="CartItem-selected-color-container">
{selectedColors.map((color) => (
<>
<span
key={color}
className="CartItem-selected-color"
style={{ backgroundColor: color }}
></span>
<span> </span>
</>
))}
</div>
<div className="CartItem-quantity">Qty: {quantity}</div>
<div>${cost.toFixed(2)}</div>
<button
className="CartItem-button-remove"
onClick={onRemoveItemFromCartClick}
>
<CloseCircleOutlined />
</button>
</div>
</div>
);
}
|
davidtimovski/soccer-streamlined
|
lib/parser.ts
|
<filename>lib/parser.ts
/// <reference path="match.ts" />
/// <reference path="stream.ts" />
class Parser {
private static readonly kickOffTimeRegex: RegExp = /\[.+\]/;
getMatchesFromPosts(posts: any[]): Match[] {
let matches = new Array<Match>();
for (let post of posts) {
let kickOffTime = this.getKickOffTimeFromTitle(post.data.title);
// Skip non-match posts
if (post.data.locked || post.data.stickied || !kickOffTime) {
continue;
}
let match = new Match();
match.id = post.data.id;
match.title = this.getTitleWithoutTime(post.data.title);
match.url = 'https://www.reddit.com' + post.data.permalink;
match.kickOffTime = kickOffTime;
match.kickOffTimeFormatted = this.formatKickOffTime(kickOffTime);
match.leagueIcon = post.data.link_flair_css_class;
matches.push(match);
}
let kickOffTimeAscending = (a: Match, b: Match): number => {
if (a.kickOffTime < b.kickOffTime) {
return -1;
}
if (a.kickOffTime > b.kickOffTime) {
return 1;
}
return 0;
};
return matches.sort(kickOffTimeAscending);
}
getStreamsFromComments(comments: any[], postUrl: string): Stream[] {
let streams = new Array<Stream>();
for (let comment of comments) {
let linksInBody: Link[] = [];
let aceStreamsInBody: AceStream[] = [];
let sopCastStreamsInBody: SopCast[] = [];
Link.greedyRegexMatch(comment.data.body, linksInBody);
AceStream.greedyRegexMatch(comment.data.body, aceStreamsInBody);
SopCast.greedyRegexMatch(comment.data.body, sopCastStreamsInBody);
if ((linksInBody.length + aceStreamsInBody.length + sopCastStreamsInBody.length) > 0) {
let stream = new Stream();
stream.author = comment.data.author;
stream.commentUrl = postUrl + comment.data.id;
stream.links = linksInBody;
stream.aceStreams = aceStreamsInBody;
stream.sopCastStreams = sopCastStreamsInBody;
streams.push(stream);
}
}
return streams;
}
private greedyRegexMatch(search: string, regex: RegExp, matchingGroup: number, result: any[]): void {
let matches = regex.exec(search);
if (matches !== null) {
result.push(matches[matchingGroup]);
this.greedyRegexMatch(search, regex, matchingGroup, result);
}
}
private getKickOffTimeFromTitle(title: string): Date {
let requestPart = title.match(/\[request\]/i);
let kickOffTimePart = title.match(Parser.kickOffTimeRegex);
// Skip match requests and match posts where the title is malformed
if (requestPart || !kickOffTimePart) {
return null;
}
let hoursAndMinutesText: string = kickOffTimePart[0].trim().substring(1, kickOffTimePart[0].length - 1);
let hoursAndMinutesArray: string[] = hoursAndMinutesText.trim().split(/\D+/);
let now = new Date();
let utc: number = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate(),
parseInt(hoursAndMinutesArray[0], 10), parseInt(hoursAndMinutesArray[1], 10), 0, 0);
if (isNaN(utc)) {
return null;
}
return new Date(utc);
}
private getTitleWithoutTime(title: string): string {
let kickOffTimePart = title.match(Parser.kickOffTimeRegex);
return title.replace(kickOffTimePart[0], '');
}
private formatKickOffTime(date: Date): string {
let hours: string = '0' + date.getHours();
hours = hours.substr(hours.length - 2);
let minutes: string = '0' + date.getMinutes();
minutes = minutes.substr(minutes.length - 2);
return `${hours}:${minutes}`;
}
}
|
davidtimovski/soccer-streamlined
|
lib/httpClient.ts
|
class HttpClient {
get(url: string, successCallback: (result: any) => void, errorCallback: (statusCode: number) => void): void {
let request = new XMLHttpRequest();
request.onreadystatechange = () =>
{
if (request.readyState == 4)
{
if (request.status == 200) {
successCallback(JSON.parse(request.responseText));
} else {
errorCallback(request.status);
}
}
};
request.open('GET', url);
request.send();
}
}
|
davidtimovski/soccer-streamlined
|
popup.ts
|
/// <reference path="./lib/app.ts" />
let httpClient = new HttpClient();
let httpError = () => {
DomHelper.hideElement(DomHelper.loadingGif);
DomHelper.showElement(DomHelper.soccerStreamsNote);
};
function getData() {
httpClient.get(
'https://soccerorigin.davidtimovski.com',
(streamsOrigin) => {
httpClient.get(
streamsOrigin.origin + '.json',
(result) => {
let posts = result.data.children;
let app = new App();
let parser = new Parser();
let matches = parser.getMatchesFromPosts(posts);
if (matches.length > 0) {
app.populateMatchesTable(matches);
} else {
DomHelper.showInfoMessage(
'There are currently no available matches'
);
}
DomHelper.hideElement(DomHelper.loadingGif);
DomHelper.showElement(DomHelper.matchesTable);
DomHelper.soccerStreamsLink.innerText = streamsOrigin.origin;
DomHelper.soccerStreamsLink.addEventListener(
'click',
() => {
chrome.tabs.create({ url: streamsOrigin.origin, active: true });
},
false
);
DomHelper.showElement(DomHelper.soccerStreamsLinkWrap);
let searchInput = <HTMLInputElement>document.getElementById('search');
searchInput.addEventListener('keyup', () => {
app.filterMatches(searchInput.value);
});
searchInput.addEventListener('keyup', (event) => {
if (event.key === 'Enter') {
app.openFirstMatch();
}
});
let body = document.getElementsByTagName('body')[0];
body.addEventListener('keyup', (event) => {
// If a letter was typed
let typingRegex: RegExp = /^[a-zA-Z]$/;
if (
typingRegex.exec(event.key) !== null &&
DomHelper.matchesTable.style.display === 'block'
) {
if (searchInput.dataset.visible === 'false') {
searchInput.dataset.visible = 'true';
DomHelper.showElement(searchInput);
searchInput.focus();
searchInput.value = event.key;
app.filterMatches(searchInput.value);
}
} else if (event.key === 'Backspace') {
app.backToMatches();
}
});
},
httpError
);
},
httpError
);
}
// Show error because extension is obsolete
httpError();
|
radoslaw-medryk/react-template
|
src/components/ReactApp.tsx
|
<reponame>radoslaw-medryk/react-template<filename>src/components/ReactApp.tsx<gh_stars>0
import * as React from "react";
import { Hello } from "./Hello";
import { useConfig } from "@/src/config/useConfig";
export type ReactAppProps = {
//
};
export const ReactApp: React.SFC<ReactAppProps> = () => {
const config = useConfig();
const name = config ? config.hello : "~loading~";
return <Hello name={name} />;
};
|
radoslaw-medryk/react-template
|
src/components/Hello.tsx
|
<reponame>radoslaw-medryk/react-template<filename>src/components/Hello.tsx
import * as React from "react";
import { styled } from "linaria/react";
import { Rotor } from "./Rotor";
const HelloRotor = styled(Rotor)`
background: papayawhip;
height: 100vh;
`;
const HelloText = styled.h1`
color: tomato;
`;
export type HelloProps = {
name: string;
};
export const Hello: React.SFC<HelloProps> = ({ name }) => {
return (
<HelloRotor cycleTimeSec={2}>
<HelloText>Hello {name}!</HelloText>
</HelloRotor>
);
};
|
radoslaw-medryk/react-template
|
src/config/config.tsx
|
<gh_stars>0
import axios from "axios";
export type Config = {
hello: string;
};
const defaultConfig: Config = require("@/configs/dev-config.json");
export const configPromise = axios
.get("/config.json")
.then(response => {
return response.data as Config;
})
.catch(e => {
console.warn("Get /config.json failed, fallback to defaults.", e);
return defaultConfig;
});
|
radoslaw-medryk/react-template
|
src/config/useConfig.tsx
|
import * as React from "react";
import { configPromise, Config } from "./config";
export function useConfig(): Config | undefined {
const [config, setConfig] = React.useState<Config | undefined>(undefined);
React.useEffect(() => {
async function getConfigAsync() {
const configResult = await configPromise;
setConfig(configResult);
}
getConfigAsync();
});
return config;
}
|
radoslaw-medryk/react-template
|
src/components/Rotor.tsx
|
import { styled } from "linaria/react";
export type RotorProps = {
cycleTimeSec: number;
};
// TODO [RM]: linaria passes all props down to div which gives React warning.
export const Rotor = styled.div<RotorProps>`
display: flex;
flex-flow: row-nowrap;
justify-content: center;
align-items: center;
& > * {
animation: rotate ${props => props.cycleTimeSec}s linear infinite;
}
@keyframes rotate {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
`;
|
martin-luo/MyUtils
|
util/debounceAndThrottle.ts
|
<filename>util/debounceAndThrottle.ts
/**
* This file contains the typescript version debouncing and throttling function.
*
* Acknowledgement: This code is borrowed from the util.js, which is in the same folder as this
* file, and [Juejin.im](https://juejin.im/post/5c00f7fe51882516be2ee2fc)
*/
/**
* @export
*
* @description Debounce function.
* @description 函数防抖
*
* @param {Function} fn Function to be debounced.
* @param {number} delay Time to wait before calling the function.
* @param {*} scope Scope.
* @param {boolean} [immediate=false] Flag indicating if we should call the function immediately.
* @returns {Function}
*/
export function debounce(
fn: Function,
delay: number,
scope: any,
immediate: boolean = false
): Function {
let timer: number = null;
return function() {
let context: any = scope || this;
let args: IArguments = arguments;
if (timer) {
clearTimeout(timer);
}
if (immediate) {
let callNow: boolean = !timer;
timer = setTimeout(() => (timer = null), delay);
if (callNow) {
fn.apply(context, args);
}
} else {
timer = setTimeout(() => fn.apply(context, args), delay);
}
};
}
/**
* Mode of the throttling function.
*
* @enum {number}
*/
enum ThrottleMode {
TimeStamp,
Timer
}
/**
* @export
*
* @description Throttling function.
* @description 函数节流.
*
* @param {Function} fn Function to be throttled.
* @param {number} threshold Time to wait before the function is called.
* @param {*} scope Scope.
* @param {ThrottleMode} [mode=ThrottleMode.TimeStamp] Mode of the throttle funciton.
* @returns {Function}
*/
export function throttle(
fn: Function,
threshold: number,
scope: any,
mode: ThrottleMode = ThrottleMode.TimeStamp
): Function {
return mode === ThrottleMode.TimeStamp
? throttleByTimestamp(fn, threshold, scope)
: throttleByTimer(fn, threshold, scope);
}
/**
* @export
*
* @description Timestamp version throttling function.
* @description 节流函数 (时间戳版)
*
* @param {Function} fn Function to be throttled.
* @param {number} threshold Time to wait before the function is called.
* @param {*} scope Scope.
* @returns {Function}
*/
export function throttleByTimestamp(
fn: Function,
threshold: number,
scope: any
): Function {
let prev: number = Date.now();
return function() {
let context: any = scope || this;
let args: IArguments = arguments;
let now: number = Date.now();
if (now - prev > threshold) {
prev = now;
fn.apply(context, args);
}
};
}
/**
* @export
*
* @description Timer version throttling function.
* @description 节流函数 (定时器版)
*
* @param {Function} fn Function to be throttled.
* @param {number} threshold Time to wait before the function is called.
* @param {*} scope Scope.
* @returns {Function}
*/
export function throttleByTimer(
fn: Function,
threshold: number,
scope: any
): Function {
let timer: number;
return function() {
let context: any = scope || this;
let args: IArguments = arguments;
if (!timer) {
timer = setTimeout(() => {
fn.apply(context, args);
timer = null;
}, threshold);
}
};
}
|
martin-luo/MyUtils
|
util/ajax.ts
|
/**
* The status of the XMLHttpRequest.
*
* @enum {number}
*/
enum XMLHttpRequestReadyState {
NotInitialized,
ServerConnectionEstablished,
RequestReceived,
ProcessingRequest,
ResponseIsReady
}
const HTTP_STATUS_CODE_OK: number = 200;
/**
* @description This is an AJAX-like function, which is implemented using the XMLHttpRequest.
* @description Acknowledgement: This implementation borrows idea from the [W3Schools](https://www.w3schools.com/xml/ajax_intro.asp).
* @description Please be aware that this is not a robust function, I am just writing it to show it is possible to implement the ajax call using XMLHTTPRequest.
*
* @author <NAME>
*
* @export
* @param {string} url The API endpoints.
* @param {(response: XMLHttpRequestResponseType) => any} onResponseIsReady Callback function when the response is received.
* @param {BodyInit} [body=null] Body to be sent with the request. When no value is passed in, the request will be sent using GET method, otherwise POST mthod, together with the body.
* @param {boolean} [async=true] Flag indicating if the call is asynchronous or not.
*/
export function ajaxInXMLHttpRequest(
url: string,
onResponseIsReady: (response: XMLHttpRequestResponseType) => any,
body: BodyInit = null,
async: boolean = true
): void {
let xhr: XMLHttpRequest;
if (window.XMLHttpRequest) {
// code for modern browsers
xhr = new XMLHttpRequest();
} else {
// code for old IE browsers
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
// Event handler when the XMLHttpResponse is received.
xhr.onreadystatechange = function(this: XMLHttpRequest, event: Event) {
if (
this.readyState === XMLHttpRequestReadyState.ResponseIsReady &&
this.status === HTTP_STATUS_CODE_OK
) {
onResponseIsReady(this.response);
}
};
// Check if body is null, if it's null, treat this request as a POST request.
const xhrMethod: string = body ? "POST" : "GET";
xhr.open(xhrMethod, url, async);
xhr.send(body);
}
/**
* @description This is an AJAX-like function, which is implemented using the XMLHttpRequest, and is returned as a Promise.
* @description Acknowledgement: This implementation borrows idea from the [W3Schools](https://www.w3schools.com/xml/ajax_intro.asp) and [CSDN](https://blog.csdn.net/qq_29849641/article/details/69233788).
* @description Please be aware that this is not a robust function, I am just writing it to show it is possible to implement the ajax call using XMLHTTPRequest.
*
* @author <NAME>
*
* @export
* @param {string} url The API endpoints.
* @param {BodyInit} [body=null] Body to be sent with the request. When no value is passed in, the request will be sent using GET method, otherwise POST mthod, together with the body.
* @param {boolean} [async=true] Flag indicating if the call is asynchronous or not.
* @returns {Promise<any>}
*/
export function ajaxPromiseInXMLHttpRequest(
url: string,
body: BodyInit = null,
async: boolean = true
): Promise<any> {
return new Promise((resolveFunction: Function, rejectFunction: Function) => {
let xhr: XMLHttpRequest;
if (window.XMLHttpRequest) {
// code for modern browsers
xhr = new XMLHttpRequest();
} else {
// code for old IE browsers
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
// Event handler when the XMLHttpResponse is received.
xhr.onreadystatechange = function(this: XMLHttpRequest, event: Event) {
if (
this.readyState === XMLHttpRequestReadyState.ResponseIsReady &&
this.status === HTTP_STATUS_CODE_OK
) {
try {
resolveFunction(JSON.parse(this.response));
} catch {
console.error(
"Exception thrown when trying to parse the response. Now trying to resolve the response directly..."
);
resolveFunction(this.response);
}
} else {
rejectFunction(this.responseText);
}
};
// Check if body is null, if it's null, treat this request as a POST request.
const xhrMethod: string = body ? "POST" : "GET";
xhr.open(xhrMethod, url, async);
xhr.send(xhrMethod);
});
}
|
donpark/ebml-stream
|
src/models/tags/Block.ts
|
import { EbmlDataTag } from "./EbmlDataTag";
import { BlockLacing } from "../enums/BlockLacing";
import { Tools } from "../../Tools";
import { EbmlTagId } from "../enums/EbmlTagId";
import { EbmlElementType } from "../enums/EbmlElementType";
export class Block extends EbmlDataTag {
payload: Buffer;
track: number;
value: number;
invisible: boolean;
lacing: BlockLacing;
constructor(subTypeId?: number) {
super(subTypeId || EbmlTagId.Block, EbmlElementType.Binary);
}
protected writeTrackBuffer(): Buffer {
return Tools.writeVint(this.track);
}
protected writeValueBuffer(): Buffer {
let value = Buffer.alloc(2);
value.writeInt16BE(this.value, 0);
return value;
}
protected writeFlagsBuffer(): Buffer {
let flags = 0x00;
if(this.invisible) {
flags |= 0x10;
}
switch(this.lacing) {
case BlockLacing.None:
break;
case BlockLacing.Xiph:
flags |= 0x04;
break;
case BlockLacing.EBML:
flags |= 0x08;
break;
case BlockLacing.FixedSize:
flags |= 0x0c;
break;
}
return Buffer.of(flags);
}
encodeContent(): Buffer {
return Buffer.concat([
this.writeTrackBuffer(),
this.writeValueBuffer(),
this.writeFlagsBuffer(),
this.payload
]);
}
parseContent(data: Buffer): void {
const track = Tools.readVint(data);
this.track = track.value;
this.value = Tools.readSigned(data.subarray(track.length, track.length+2));
let flags: number = data[track.length+2];
this.invisible = Boolean(flags & 0x10);
switch(flags & 0x0c) {
case 0x00:
this.lacing = BlockLacing.None;
break;
case 0x04:
this.lacing = BlockLacing.Xiph;
break;
case 0x08:
this.lacing = BlockLacing.EBML;
break;
case 0x0c:
this.lacing = BlockLacing.FixedSize;
break;
}
this.payload = data.slice(track.length + 3);
}
}
|
donpark/ebml-stream
|
test/tools.spec.ts
|
<filename>test/tools.spec.ts
import assert from 'assert';
import { Tools as tools } from '../src/Tools';
import "jasmine";
describe('EBML', () => {
describe('tools', () => {
describe('#readVint()', () => {
function readVint(buffer: Buffer, expected: number): void {
const vint = tools.readVint(buffer, 0);
assert.strictEqual(vint.value, expected);
assert.strictEqual(vint.length, buffer.length);
}
it('should read the correct value for all 1 byte ints', () => {
for (let i = 0; i < 0x80 - 1; i += 1) {
readVint(Buffer.from([i | 0x80]), i);
}
readVint(Buffer.from([0xff]), -1);
});
it('should read the correct value for 1 byte int with non-zero start', () => {
const b = Buffer.from([0x00, 0x81]);
const vint = tools.readVint(b, 1);
assert.strictEqual(1, vint.value);
assert.strictEqual(1, vint.length);
});
it('should read the correct value for all 2 byte ints', () => {
for (let i = 0; i < 0x40; i += 1)
for (let j = 0; j < 0xff; j += 1) {
readVint(Buffer.from([i | 0x40, j]), (i << 8) + j);
}
});
it('should read the correct value for all 3 byte ints', () => {
for (let i = 0; i < 0x20; i += 1) {
for (let j = 0; j < 0xff; j += 2) {
for (let k = 0; k < 0xff; k += 3) {
readVint(Buffer.from([i | 0x20, j, k]), (i << 16) + (j << 8) + k);
}
}
}
});
// not brute forcing any more bytes, takes sooo long
it('should read the correct value for 4 byte int min/max values', () => {
readVint(Buffer.from([0x10, 0x20, 0x00, 0x00]), 2 ** 21);
readVint(Buffer.from([0x1f, 0xff, 0xff, 0xfe]), 2 ** 28 - 2);
});
it('should read the correct value for 5 byte int min/max values', () => {
readVint(Buffer.from([0x08, 0x10, 0x00, 0x00, 0x00]), 2 ** 28);
readVint(Buffer.from([0x0f, 0xff, 0xff, 0xff, 0xfe]), 2 ** 35 - 2);
});
it('should read the correct value for 6 byte int min/max values', () => {
readVint(Buffer.from([0x04, 0x08, 0x00, 0x00, 0x00, 0x00]), 2 ** 35);
readVint(
Buffer.from([0x07, 0xff, 0xff, 0xff, 0xff, 0xfe]),
2 ** 42 - 2,
);
});
it('should read the correct value for 7 byte int min/max values', () => {
readVint(
Buffer.from([0x02, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00]),
2 ** 42,
);
readVint(
Buffer.from([0x03, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe]),
2 ** 49 - 2,
);
});
it('should read the correct value for 8 byte int min value', () => {
readVint(
Buffer.from([0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]),
2 ** 49,
);
});
it('should read the correct value for the max representable JS number (2^53)', () => {
readVint(
Buffer.from([0x01, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]),
2 ** 53,
);
});
// an unknown value is represented by -1
it('should return value -1 for more than max representable JS number (2^53 + 1)', () => {
readVint(
Buffer.from([0x01, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01]),
-1,
);
});
it('should return value -1 for more than max representable JS number (8 byte int max value)', () => {
readVint(
Buffer.from([0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]),
-1,
);
});
it('should throw for 9+ byte int values', () => {
assert.throws(() => {
tools.readVint(
Buffer.from([0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff]),
);
}, /Unrepresentable length/);
});
});
describe('#writeVint()', () => {
function writeVint(value: number, expected: Buffer): void {
const actual = tools.writeVint(value);
assert.strictEqual(expected.toString('hex'), actual.toString('hex'));
}
it('should throw when writing -1', () => {
assert.throws(() => {
tools.writeVint(-1);
}, /Unrepresentable value/);
});
it('should write all 1 byte ints', () => {
for (let i = 0; i < 0x80 - 1; i += 1) {
writeVint(i, Buffer.from([i | 0x80]));
}
});
it('should write 2 byte int min/max values', () => {
writeVint(2 ** 7 - 1, Buffer.from([0x40, 0x7f]));
writeVint(2 ** 14 - 2, Buffer.from([0x7f, 0xfe]));
});
it('should write 3 byte int min/max values', () => {
writeVint(2 ** 14 - 1, Buffer.from([0x20, 0x3f, 0xff]));
writeVint(2 ** 21 - 2, Buffer.from([0x3f, 0xff, 0xfe]));
});
it('should write 4 byte int min/max values', () => {
writeVint(2 ** 21 - 1, Buffer.from([0x10, 0x1f, 0xff, 0xff]));
writeVint(2 ** 28 - 2, Buffer.from([0x1f, 0xff, 0xff, 0xfe]));
});
it('should write 5 byte int min/max value', () => {
writeVint(2 ** 28 - 1, Buffer.from([0x08, 0x0f, 0xff, 0xff, 0xff]));
writeVint(2 ** 35 - 2, Buffer.from([0x0f, 0xff, 0xff, 0xff, 0xfe]));
});
it('should write 6 byte int min/max value', () => {
writeVint(
2 ** 35 - 1,
Buffer.from([0x04, 0x07, 0xff, 0xff, 0xff, 0xff]),
);
writeVint(
2 ** 42 - 2,
Buffer.from([0x07, 0xff, 0xff, 0xff, 0xff, 0xfe]),
);
});
it('should write 7 byte int min/max value', () => {
writeVint(
2 ** 42 - 1,
Buffer.from([0x02, 0x03, 0xff, 0xff, 0xff, 0xff, 0xff]),
);
writeVint(
2 ** 49 - 2,
Buffer.from([0x03, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe]),
);
});
it('should write the correct value for 8 byte int min value', () => {
writeVint(
2 ** 49 - 1,
Buffer.from([0x01, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]),
);
});
it('should write the correct value for the max representable JS number (2^53)', () => {
writeVint(
2 ** 53,
Buffer.from([0x01, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]),
);
});
/*
* can't prevent this, 2^53 + 1 === 2^53
* it('should throw for more than max representable JS number (2^53 + 1)', function() {
* assert.throws(function() {
* tools.writeVint((2 ** 53) + 1));
* }, /Unrepresentable value/)
* })
*/
it('should throw for more than max representable JS number (8 byte int max value)', () => {
assert.throws(() => {
tools.writeVint(2 ** 56 + 1);
}, /Unrepresentable value/);
});
it('should throw for 9+ byte int values', () => {
assert.throws(() => {
tools.writeVint(2 ** 56 + 1);
}, /Unrepresentable value/);
});
});
describe('#readFloat', () => {
it('can read 32-bit floats', () => {
assert.strictEqual(
tools.readFloat(Buffer.from([0x40, 0x20, 0x00, 0x00])),
2.5,
);
});
it('can read 64-bit floats', () => {
assert.strictEqual(
tools.readFloat(
Buffer.from([0x40, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]),
),
2.5,
);
});
it('returns NaN with invalid sized arrays', () => {
assert.ok(
Number.isNaN(tools.readFloat(Buffer.from([0x40, 0x20, 0x00]))),
);
});
});
describe('#readUnsigned', () => {
it('handles 8-bit ints', () => {
assert.strictEqual(tools.readUnsigned(Buffer.from([0x07])), 7);
});
it('handles 16-bit ints', () => {
assert.strictEqual(tools.readUnsigned(Buffer.from([0x07, 0x07])), 1799);
});
it('handles 32-bit ints', () => {
assert.strictEqual(
tools.readUnsigned(Buffer.from([0x07, 0x07, 0x07, 0x07])),
117901063,
);
});
it('handles ints smaller than 49 bits as numbers', () => {
assert.strictEqual(
tools.readUnsigned(Buffer.from([0x07, 0x07, 0x07, 0x07, 0x07])),
30182672135,
);
assert.strictEqual(
tools.readUnsigned(Buffer.from([0x07, 0x07, 0x07, 0x07, 0x07, 0x07])),
7726764066567,
);
});
it('returns ints 49 bits or larger as strings', () => {
assert.strictEqual(
tools.readUnsigned(
Buffer.from([0x1, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07]),
),
'01070707070707',
);
assert.strictEqual(
typeof tools.readUnsigned(
Buffer.from([0x1, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07]),
),
'string',
);
});
});
describe('#readUtf8', () => {});
describe('#readSigned', () => {
it('handles 8-bit ints', () => {
assert.strictEqual(tools.readSigned(Buffer.from([0x07])), 7);
});
it('handles 16-bit ints', () => {
assert.strictEqual(tools.readSigned(Buffer.from([0x07, 0x07])), 1799);
});
it('handles 32-bit ints', () => {
assert.strictEqual(
tools.readSigned(Buffer.from([0x07, 0x07, 0x07, 0x07])),
117901063,
);
});
it('returns NaN with invalid sized arrays', () => {
assert.ok(
Number.isNaN(tools.readSigned(Buffer.from([0x40, 0x20, 0x00]))),
);
});
});
describe('#readDataFromTag', () => {});
});
});
|
donpark/ebml-stream
|
src/EbmlStreamDecoder.ts
|
import { Transform, TransformOptions, TransformCallback } from 'stream';
import { Tools as tools } from './Tools';
import { EbmlTag } from './models/EbmlTag';
import { EbmlElementType } from './models/enums/EbmlElementType';
import { EbmlTagPosition } from './models/enums/EbmlTagPosition';
import { EbmlTagFactory } from './models/EbmlTagFactory';
import { EbmlTagId } from './models/enums/EbmlTagId';
export class EbmlStreamDecoderOptions {
bufferTagIds?: EbmlTagId[] = [];
}
export class EbmlStreamDecoder extends Transform {
private _currentBufferOffset: number = 0;
private _tagStack: ProcessingTag[] = [];
private _buffer: Buffer = Buffer.alloc(0);
private _bufferTagIds: EbmlTagId[] = [];
/* Expose property for testing */
get buffer(): Buffer {
return this._buffer;
}
constructor(options: TransformOptions & EbmlStreamDecoderOptions = {}) {
super(<TransformOptions>{ ...options, readableObjectMode: true });
this._bufferTagIds = options.bufferTagIds || [];
}
// @ts-ignore
_transform(chunk: any, enc: string, done: TransformCallback): void {
this._buffer = Buffer.concat([this._buffer, Buffer.from(chunk)]);
while(this.parseTags());
done();
}
private parseTags(): boolean {
const currentTag = this.readTagHeader(this._buffer);
if(!currentTag) {
return false;
}
if(currentTag.type === EbmlElementType.Master && !this._bufferTagIds.some(i => i ===currentTag.id)) {
this._tagStack.push(currentTag);
this.emitTag(currentTag, EbmlTagPosition.Start);
this.advanceBuffer(currentTag.tagHeaderLength);
return true;
} else {
if(this._buffer.length < currentTag.tagHeaderLength + currentTag.size) {
return false;
}
const data = this._buffer.slice(currentTag.tagHeaderLength, currentTag.tagHeaderLength+ currentTag.size);
this.emitTag(currentTag, EbmlTagPosition.Content, data);
this.advanceBuffer(currentTag.tagHeaderLength + currentTag.size);
while (this._tagStack.length > 0) {
const nextTag = this._tagStack[this._tagStack.length - 1];
if (this._currentBufferOffset < (nextTag.absoluteStart + nextTag.tagHeaderLength + nextTag.size)) {
break;
}
this.emitTag(nextTag, EbmlTagPosition.End);
this._tagStack.pop();
}
}
return true;
}
private advanceBuffer(length: number): void {
this._currentBufferOffset += length;
this._buffer = this._buffer.slice(length);
}
private readTagHeader(buffer: Buffer, offset: number = 0): ProcessingTag {
if (buffer.length == 0) {
return null;
}
const tag = tools.readVint(buffer, offset);
if (tag == null) {
return null;
}
const size = tools.readVint(buffer, offset + tag.length);
if(size == null) {
return null;
}
const tagIdHex = tools.readHexString(buffer, offset, offset + tag.length)
const tagId = Number.parseInt(tagIdHex, 16);
let tagObject = EbmlTagFactory.create(tagId);
tagObject.size = size.value;
return Object.assign(tagObject, {
absoluteStart: this._currentBufferOffset + offset,
tagHeaderLength: tag.length + size.length
});
}
private emitTag(tag: ProcessingTag, position: EbmlTagPosition, data?: Buffer): void {
let emittedTag = EbmlTagFactory.create(tag.id);
emittedTag.size = tag.size;
emittedTag.position = position;
if(position === EbmlTagPosition.Content) {
emittedTag.parseContent(data);
}
this.push(emittedTag);
}
}
type ProcessingTag = EbmlTag & {
absoluteStart: number;
tagHeaderLength: number;
};
|
DanxiongLei/Vimdroid
|
lib/device/android.ts
|
<reponame>DanxiongLei/Vimdroid
/**
* Created by ldx on 2017/4/7.
*/
import {DeviceBase, ProtocolBase, Resp} from "./base";
import {BaseError, SubcoreError} from "../util/error";
import logger from "../util/logger";
import {UIDevice, UserInterface} from "../user-interface";
import constants from "../constants";
import * as path from "path";
import {Config} from "../index";
const adb = require('adbkit');
export class AndroidDevice extends DeviceBase {
private static adbClient: any;
private device: AndroidDeviceModel;
private uiCallback: AndroidCallback;
private userInterface: UserInterface;
private initialized: boolean = false;
constructor(ui) {
super();
this.userInterface = ui;
}
get protocol() {
return new AndroidProtocol(this);
}
registerCallback(callback: AndroidCallback) {
this.uiCallback = callback;
}
/**
* 1. 初始化
* 2. 搜索设备
* 3. 安装子程序
* 4. 建立并测试连接
* 5. 成功/失败
*/
async onCreate() {
logger.log(`onCreate`);
// 搜索设备
let device = await this.chooseDevice();
if (!device) {
// 用户取消
return false;
}
this.device = device;
// 安装子程序并建立连接
await this.prepareSubcore();
await this.establishConnect();
await this.ensurePrepared();
return true;
}
private async ensurePrepared() {
let prepared = await this.protocol.ensurePrepared();
logger.log("ensurePrepared ", prepared);
switch (prepared.status) {
case constants.RESP_STATUS.FAILURE:
if (this.uiCallback) {
this.uiCallback.failure(prepared.data);
}
break;
case constants.RESP_STATUS.FAILURE_NOT_FATAL:
if (this.uiCallback) {
this.uiCallback.message(prepared.data);
}
break;
case constants.RESP_STATUS.OK:
this.initialized = true;
if (this.uiCallback) {
this.uiCallback.allPreparedSuccessfully();
}
break;
default:
}
}
private async establishConnect() {
if (this.uiCallback) {
this.uiCallback.tryingToEstablishConnect();
}
const client = AndroidDevice.getAdbClient();
// 启动Instrument
client.shell(this.device.id, "am instrument -w" +
" -e class \"com.damonlei.vimdroid.Initializer#startup\"" +
" com.damonlei.vimdroid.test/" +
"android.support.test.runner.AndroidJUnitRunner"
).then(adb.util.readAll
).then((output) => {
logger.log("run instrument finished", output.toString().trim());
}).catch(err => {
logger.error(err);
throw err;
});
// 尝试进行连接
let resp = await this.tryToPingRetry(3, 1000);
logger.log("Ping received", resp);
if (resp.status !== constants.RESP_STATUS.OK) {
throw new SubcoreError(resp.data);
}
}
private tryToPingRetry(retry: number, timeout: number) {
let _resolve, _reject;
let self = this;
async function handler() {
let resp = await self.tryToPing();
if (resp) {
_resolve(resp);
return;
}
if (retry > 0) {
retry--;
setTimeout(handler, timeout);
} else {
_reject(new SubcoreError("Could not connect with mobile."));
}
}
return new Promise((resolve: (x: Resp<string>) => {}, reject) => {
_resolve = resolve;
_reject = reject;
try {
setTimeout(handler, timeout);
} catch (err) {
logger.error(err);
_reject(err);
}
});
}
private async tryToPing() {
logger.log("ping...");
let resp;
try {
resp = await this.protocol.ping();
} catch (e) {
logger.error(e, "Trying to ping failed.");
return null;
}
if (resp.status !== constants.RESP_STATUS.OK) {
logger.log("Trying to ping failed.", resp.data);
return resp;
}
return resp;
}
private async prepareSubcore() {
if (this.uiCallback) {
this.uiCallback.tryingToPrepareSubcore();
}
const client = AndroidDevice.getAdbClient();
if (Config.FORCE_INSTALL_SUBCORE || !(await client.isInstalled(this.device.id, constants.PACKAGE_NAME))) {
if (this.uiCallback) {
this.uiCallback.tryingToInstallSubcore();
}
await this.installSubcore();
}
}
private async installSubcore() {
await AndroidDevice.getAdbClient().install(this.device.id, path.join(__dirname, "../res/apk/app.apk"));
await AndroidDevice.getAdbClient().install(this.device.id, path.join(__dirname, "../res/apk/app-server.apk"));
}
private async chooseDevice() {
if (this.uiCallback) {
this.uiCallback.tryingToSearchDevice();
}
const client = AndroidDevice.getAdbClient();
let devices: AndroidDeviceModel[];
try {
devices = await AndroidDevice.getAdbDevices(client);
} catch (e) {
logger.error(e, AndroidConnectError.name);
throw new AndroidConnectError();
}
await AndroidDevice.insertDeviceName(client, devices);
return await this.chooseOneDeviceFromArray(devices);
}
private async chooseOneDeviceFromArray(devices) {
let hitDevice;
if (devices.length > 1) {
let deviceId = await this.userInterface.makeUserChoose(AndroidDevice.adaptUIDevice(devices));
for (let device of devices) {
if (device.id === deviceId) {
hitDevice = device;
break;
}
}
} else if (devices.length === 1) {
hitDevice = devices[0];
} else {
throw new Error("Devices length === 0");
}
return hitDevice;
}
private static async insertDeviceName(client, devices: AndroidDeviceModel[]) {
for (let item of devices) {
let properties = await client.getProperties(item.id);
item.name = properties['ro.product.name'];
}
return devices;
}
private static adaptUIDevice(devices: AndroidDeviceModel[]) {
let result: UIDevice[] = [];
for (let item of devices) {
result.push({id: item.id, name: `${item.name} [${item.type}]`});
}
return result;
}
private static async getAdbDevices(client) {
const devices = await client.listDevices();
if (!devices) {
throw new Error("Devices got from adb is empty");
}
let hit = false;
for (let item of devices) {
if (item.type != "offline") {
hit = true;
break;
}
}
if (!hit) {
throw new Error("All devices adb got is offline");
}
return devices;
}
private static getAdbClient() {
if (AndroidDevice.adbClient == null) {
logger.log(`create adbClient`);
AndroidDevice.adbClient = adb.createClient();
}
return AndroidDevice.adbClient;
}
protected async communicate<T>(id: number, entity?: string): Promise<Resp<T>> {
const socket = await AndroidDevice.getAdbClient().openTcp(this.device.id, constants.DEVICE_PORT);
return DeviceBase.__communicate__<T>(socket, id, entity);
}
onDestroy() {
}
}
interface AndroidDeviceModel {
id: string, type: string, name?: string, path?: string
}
export class AndroidConnectError extends BaseError {
}
class AndroidProtocol extends ProtocolBase {
public ensurePrepared(): Promise<Resp<string>> {
return this._send_(constants.CMD_ID.ensurePrepared);
}
}
export interface AndroidCallback {
tryingToSearchDevice();
tryingToPrepareSubcore();
tryingToInstallSubcore();
tryingToEstablishConnect();
allPreparedSuccessfully();
failure(msg);
message(msg);
}
|
DanxiongLei/Vimdroid
|
lib/util/error.ts
|
/**
* Created by ldx on 2017/4/8.
*/
import logger from "./logger";
import {strings} from "../res/string";
export class BaseError extends Error {
constructor(msg?: string) {
super(msg);
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
}
public cause() {
return strings.error[this.name].cause;
}
public solution() {
return strings.error[this.name].solution;
}
public toString(): string {
return logger.errorStr(this);
}
}
export class SubcoreError extends BaseError {
}
|
DanxiongLei/Vimdroid
|
lib/ui-cli.ts
|
<filename>lib/ui-cli.ts
/**
* Created by ldx on 2017/4/9.
*/
import {strings} from "./res/string";
import logger from "./util/logger";
import {UserInterface, UIDevice} from "./user-interface";
import {AndroidCallback} from "./device/android";
import * as CLI from "./index";
import {Config} from "./index";
import {BaseError} from "./util/error";
const argv = require("yargs")
.usage(`${strings.uiUsage}`)
.boolean("d").alias("d", "debug").describe("d", strings.uiOptionDebug)
.boolean("v").alias("v", "version").describe("v", strings.uiOptionVersion)
.boolean("s").alias("s", "setting").describe("s", "Coming soon...")
.boolean("f").alias("f", "force").describe("f", "[DEBUG]Force install the new app version.")
.help("h").alias("h", "help").describe("h", strings.uiOptionHelp)
.detectLocale(false)
.argv;
if (argv.v) {
const pkg = require("../package.json");
console.log(`${pkg.name} ${pkg.version}`);
process.exit(0);
}
if (argv.debug) {
Config.DEBUG = true;
}
if (argv.force) {
Config.FORCE_INSTALL_SUBCORE = true;
}
class TerminalUI extends UserInterface implements AndroidCallback {
failure(msg) {
console.log(msg);
terminate().then();
}
message(msg) {
console.log(msg);
}
tryingToSearchDevice() {
console.log("正在搜索设备...")
}
tryingToPrepareSubcore() {
console.log("正在准备android端子程序...")
}
tryingToInstallSubcore() {
console.log("正在安装android端子程序...")
}
tryingToEstablishConnect() {
console.log("正在与子程序建立连接...")
}
allPreparedSuccessfully() {
console.log("初始化完成...")
}
makeUserChoose(devices: UIDevice[]): Promise<string> {
return undefined;
}
}
const ui = new TerminalUI();
async function start() {
let isErr = false;
try {
await CLI.start(ui, ui);
} catch (err) {
outputErr(err);
isErr = true;
}
if (isErr) {
await terminate();
}
}
async function terminate() {
console.log(strings.uiTerminate);
logger.log("terminate...");
try {
await CLI.terminate();
} catch (err) {
logger.error(err);
} finally {
process.exit(0);
}
}
start().then(() =>{
// do nothing;
});
process.stdin.on("keypress", (str, key) => {
if (key.ctrl && key.name === 'c') {
terminate().then();
}
});
function outputErr(err) {
if (err instanceof BaseError) {
console.log(`${err.cause()} ${err.message} ${err.solution()}`);
logger.error(err);
} else {
let unknownError = strings.error[BaseError.name];
console.log(`${unknownError.cause} ${unknownError.solution}`);
console.log(logger.errorStr(err));
}
}
|
DanxiongLei/Vimdroid
|
lib/index.ts
|
<filename>lib/index.ts<gh_stars>1-10
/**
* Created by ldx on 2017/4/9.
*/
import {AndroidDevice, AndroidCallback} from "./device/android";
import * as keypress from "./io/keypress";
import {UserInterface} from "./user-interface";
import logger from "./util/logger";
import {Resp} from "./device/base";
export let androidDevice;
export const Config = {
DEBUG: false,
FORCE_INSTALL_SUBCORE: false
};
export async function start(ui: UserInterface, callback: AndroidCallback) {
keypress.emitKeypressEvents(keyObserve);
androidDevice = new AndroidDevice(ui);
androidDevice.registerCallback(callback);
let result = await androidDevice.create();
logger.log(result);
return result;
}
interface KeyEvent {
name: string;
ctrl: boolean;
shift: boolean;
sequence?: string
meta: string
}
async function keyObserve(key: KeyEvent) {
logger.log("receive keyEvent : ", key);
if (key.ctrl && key.name === 'c') {
return;
}
try {
let resp: Resp<string> = await androidDevice.protocol.sendKeypress(key);
logger.log(`receive resp(${JSON.stringify(resp)}) for keyEvent(${key.name})`);
} catch (err) {
logger.error(err, "keyObserve protocol.sendKeyPress Error");
}
}
export async function terminate() {
process.stdin.removeAllListeners("keypress");
logger.log("CLI.terminate");
try {
await androidDevice.protocol.shutdown();
} catch (err) {
}
androidDevice = null;
}
export async function settings() {
}
|
DanxiongLei/Vimdroid
|
lib/res/string.ts
|
/**
* Created by ldx on 2017/4/8.
*/
import {AndroidConnectError} from "../device/android";
import {BaseError, SubcoreError} from "../util/error";
export const strings = {
error: {
[SubcoreError.name]: {
cause: "子程序错误.",
solution: ""
},
[AndroidConnectError.name]: {
cause: "连接手机失败.",
solution: "请确认:\n" +
" 1. 是否正确连接usb连接线.\n" +
" 2. 是否已在手机上开启开发者模式.\n" +
" 3. 部分手机需设置连接方式."
},
[BaseError.name]: {
cause: "未知错误.",
solution: "请联系作者."
},
},
uiUsage: "Usage : " +
" vimdroid [options] 开启程序; Ctrl-C退出\n" +
" 使您能够用电脑键盘控制您的Android手机。\n" +
" 请将Android设备和电脑使用usb连接,在命令行中运行程序,并根据引导在手机上授权。\n" +
" 授权后,支持键位:\n\n" +
" f : 选中某区域,对其进行点击\n" +
" hjkl : 向左下上右滚动\n" +
" i : 进入输入模式",
uiOptionDebug: "以调试模式启动程序。",
uiOptionHelp: "显示帮助信息",
uiOptionVersion: "显示版本号",
uiTerminate: "程序已终止."
};
|
DanxiongLei/Vimdroid
|
lib/user-interface.ts
|
<filename>lib/user-interface.ts<gh_stars>1-10
/**
* Created by ldx on 2017/4/8.
*/
export abstract class UserInterface {
async abstract makeUserChoose(devices: UIDevice[]): Promise<string> ;
}
export interface UIDevice {
id: string, name: string
}
|
DanxiongLei/Vimdroid
|
lib/util/utils.ts
|
/**
* Created by ldx on 2017/4/9.
*/
|
DanxiongLei/Vimdroid
|
lib/util/logger.ts
|
<reponame>DanxiongLei/Vimdroid
/**
* Created by ldx on 2017/4/7.
*/
import * as path from "path";
import {Config} from "../index";
export default class logger {
public static log(...args) {
if (!Config.DEBUG) {
return;
}
args.forEach((item, index, array) => {
if (typeof item === 'object') {
try {
array[index] = JSON.stringify(item);
} catch (e) {
array[index] = item.toString();
}
}
});
console.log(`[!!!DEBUG!!!][${logger.getInvokeMessage()}] - ${args}`);
}
public static errorStr(e: Error, message?: string) {
return `[!!!ERROR!!!][${logger.parseRawStack(e.stack).toString()}]`
+ `- ${message}: ${e.name} with msg [${e.message}]\n${e.stack}`;
}
public static error(e: Error, message?: string) {
if (!Config.DEBUG) {
return;
}
console.log(logger.errorStr(e, message));
}
public static getInvokeMessage(): string {
const stack = logger.getRawStack();
let parsed;
try {
parsed = logger.parseRawStack(stack);
} catch (err) {
console.log(stack);
throw err;
}
return parsed.toString();
}
public static parseRawStack(stack: string): Stack {
let cantParsedStack = new Stack({fileName: `Stack can not parsed.[${stack}]`, method: null, lineNumber: 0});
let lines = stack.split("\n");
if (lines.length < 2) {
return cantParsedStack;
}
let line = lines[1];
const reg_with_method = /^\s*at (\S+) \((.+\.js):(\d+):\d+\)\s*$/;
if (reg_with_method.test(line)) {
let split = reg_with_method.exec(line);
return new Stack({
fileName: path.basename(split[2]),
method: split[1],
lineNumber: parseInt(split[3]),
});
}
const reg_without_method = /^\s*at (.+\.js):(\d+):\d+\s*$/;
if (reg_without_method.test(line)) {
let split = reg_without_method.exec(line);
return new Stack({
fileName: path.basename(split[1]),
method: null,
lineNumber: parseInt(split[2]),
});
}
return cantParsedStack;
}
private static getRawStack(limit = 1, opt = logger.log): string {
const rawLimit = Error.stackTraceLimit;
Error.stackTraceLimit = limit;
const result: any = {};
Error.captureStackTrace(result, opt);
Error.stackTraceLimit = rawLimit;
return result.stack;
}
};
class Stack {
fileName: string;
method: string;
lineNumber: number;
constructor(source) {
Object.assign(this, source);
}
public toString(): string {
return `${this.method}():(${this.fileName}:${this.lineNumber})`
}
}
|
DanxiongLei/Vimdroid
|
lib/constants.ts
|
/**
* Created by ldx on 2017/4/7.
*/
const ANDROID_PACKAGE_NAME = "com.damonlei.vimdroid";
const constants = {
CMD_ID: {
ping: 236,
keyboard: 237,
ensurePrepared: 238,
shutdown: 239
},
RESP_STATUS: {
OK: 0,
FAILURE: -1,
FAILURE_NOT_FATAL: -2
},
DEVICE_PORT: 10086,
PACKAGE_NAME: ANDROID_PACKAGE_NAME,
SERVICE_CMP: `${ANDROID_PACKAGE_NAME}/.AppService`,
ERROR_CODE: {
ADB_ERROR: 403,
DEVICE_NOT_FOUND: 404,
APP_NOT_INSTALLED: 405,
TCP_ERROR: 406,
MOBILE_END_ERROR: 407
},
};
export default constants;
|
DanxiongLei/Vimdroid
|
lib/device/base.ts
|
/**
* Created by ldx on 2017/4/7.
*/
import constants from "../constants";
import {Socket} from "net";
import logger from "../util/logger";
/**
* UIDevice
* - onCreate 初始化
* - isInitialized 判断是否初始化
* - communicate(id, string) : string
* - isConnected 判断是否仍在连接状态
*
* 无连接状态 --> 无准备状态 --> 准备完成状态
*/
export abstract class DeviceBase {
public async create() {
return await this.onCreate();
}
protected async onCreate() {
return true;
}
abstract get protocol() : ProtocolBase;
abstract onDestroy();
protected finish() {
}
protected abstract communicate<T>(id: number, entity?: string): Promise<Resp<T>>;
protected static __communicate__<T>(socket: Socket, id: number, entity: string = ""): Promise<Resp<T>> {
socket.setEncoding("utf8");
socket.setNoDelay(true);
socket.write(`${id}\n${entity}\n`);
return new Promise((resolve: (resp: Resp<T>) => {}, reject) => {
let response = "";
socket.on("data", function (data) {
response += data;
if (response.endsWith("\n")) {
socket.end();
}
});
socket.on("error", function (err) {
reject(err);
});
socket.on("end", function () {
let json;
try {
json = JSON.parse(response);
} catch (err) {
logger.log("JSON.parse error", response);
throw err;
}
resolve(json);
});
});
}
}
export abstract class ProtocolBase {
protected mDevice;
constructor(device: DeviceBase) {
this.mDevice = device;
}
protected _send_<T>(id, entity?: string | Object): Promise<Resp<T>> {
logger.log("__send__ id:", id);
if (typeof entity === 'object') {
entity = JSON.stringify(entity);
}
return this.mDevice.communicate(id, entity);
}
public ping(): Promise<Resp<string>> {
return this._send_<string>(constants.CMD_ID.ping);
}
public sendKeypress(key: Object): Promise<Resp<string>> {
return this._send_(constants.CMD_ID.keyboard, key);
}
public shutdown(): Promise<Resp<string>> {
return this._send_(constants.CMD_ID.shutdown);
}
}
export interface Resp<T> {
status: number;
data?: T;
}
|
hieutran3010/EnglishOnline
|
src/app/components/collection/List/DatasourceInfiniteLoadingList.tsx
|
import React, { memo, useCallback, useEffect, useMemo, useState } from 'react';
import * as Sentry from '@sentry/react';
import InfiniteLoadingList, {
IInfiniteLoadingListProps,
} from './InfiniteLoadingList';
import {
IDataSource,
OrderOption,
QueryCriteria,
QueryOperator,
} from '../types';
import { concat, trim, join } from 'lodash/fp';
import isEmpty from 'lodash/fp/isEmpty';
import { Input, Space, Tag, Tooltip, Typography } from 'antd';
const { Search } = Input;
const { Text } = Typography;
interface Props extends IInfiniteLoadingListProps {
datasource: IDataSource;
pageSize?: number;
orders?: OrderOption;
canSearch?: boolean;
searchPlaceholder?: string;
searchFields?: string[];
}
const DatasourceInfiniteLoadingList = ({
datasource,
onRenderItem,
pageSize,
orders,
canSearch,
searchPlaceholder,
searchFields,
}: Props) => {
const [data, setData] = useState<any[]>([]);
const [totalCount, setTotalCount] = useState(0);
const [page, setPage] = useState(0);
const [loading, setLoading] = useState(false);
const [filters, setFilters] = useState<QueryCriteria[]>([]);
const [currentSearchKey, setCurrentSearchKey] = useState<
string | undefined
>();
const totalPage = useMemo(() => {
return Math.ceil(totalCount / (pageSize ?? 20));
}, [pageSize, totalCount]);
const _getTotal = useCallback(
async (queryCriteria: QueryCriteria[] = []) => {
const total = await datasource.countAsync(queryCriteria).catch(error => {
Sentry.captureException(
`[DatasourceInfiniteLoadingList][_getTotal]. Error: ${JSON.stringify(
error,
)}`,
);
return 0;
});
return total;
},
[datasource],
);
const _getItems = useCallback(
async (newPage: number, queryCriteria: QueryCriteria[] = []) => {
const items = await datasource
.queryManyAsync(
{
criteria: queryCriteria,
page: newPage,
pageSize: pageSize ?? 20,
order: orders,
},
true,
)
.catch(error => {
Sentry.captureException(
`[DatasourceInfiniteLoadingList][_getItems] page = ${newPage}. Error: ${JSON.stringify(
error,
)}`,
);
return [];
});
return items;
},
[datasource, orders, pageSize],
);
const _onLoadData = useCallback(async () => {
if (page === totalPage) {
return;
}
setLoading(true);
const newPage = page + 1;
const items = await _getItems(newPage, filters);
setData(page === 0 ? items : concat(data, items));
setPage(newPage);
setLoading(false);
}, [_getItems, data, filters, page, totalPage]);
useEffect(() => {
let didCancel = false;
async function getInitialDataAsync() {
const firstPage = 0;
const total = await _getTotal();
if (!didCancel) {
setTotalCount(total);
setData([]);
setPage(firstPage);
}
}
const reloadedSubscription = datasource.onReloaded.subscribe(() => {
getInitialDataAsync();
});
return function cleanUp() {
didCancel = true;
if (reloadedSubscription) {
reloadedSubscription.unsubscribe();
}
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [datasource]);
const onSearchChanged = useCallback(
async (searchKey: string | undefined) => {
const formattedSearchKey = trim(searchKey || '');
if (isEmpty(formattedSearchKey) && isEmpty(currentSearchKey)) {
return;
}
if (formattedSearchKey === currentSearchKey) {
return;
}
let criteria: QueryCriteria[] = [];
if (!isEmpty(formattedSearchKey)) {
criteria.push({
field: join('@')(searchFields),
operator: QueryOperator.C,
value: formattedSearchKey,
});
}
setPage(0);
setFilters(criteria);
setCurrentSearchKey(formattedSearchKey);
const newTotal = await _getTotal(criteria);
setTotalCount(newTotal);
setData([]);
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[currentSearchKey, searchFields],
);
return (
<>
{canSearch && (
<Tooltip title={searchPlaceholder}>
<Search
enterButton
onSearch={onSearchChanged}
loading={loading}
allowClear
style={{ marginBottom: 10 }}
/>
</Tooltip>
)}
<Space size="small" style={{ width: '100%', justifyContent: 'flex-end' }}>
<Tag color="green" style={{ margin: 0 }}>
{totalCount}
</Tag>
<Text>bills</Text>
</Space>
<InfiniteLoadingList
onRenderItem={onRenderItem}
data={data}
onLoadData={_onLoadData}
loading={loading}
totalItems={totalCount}
/>
</>
);
};
export default memo(DatasourceInfiniteLoadingList);
|
hieutran3010/EnglishOnline
|
src/app/components/AppNavigation/LeftNavigation.tsx
|
<gh_stars>0
import React, { memo } from 'react';
import { Layout } from 'antd';
import Menu from './Menu';
import { IMenuItem } from './types';
const { Sider } = Layout;
interface LeftNavigation {
isCollapsed: boolean;
menus: IMenuItem[];
appName?: string;
onSelectedMenuChanged?: (key: string) => void;
selectedMenuKeys?: string[];
}
const LeftNavigation = ({
isCollapsed,
menus,
onSelectedMenuChanged,
selectedMenuKeys,
}: LeftNavigation) => {
return (
<Sider
trigger={null}
collapsible
collapsed={isCollapsed}
style={{
overflow: 'auto',
height: '100%',
boxShadow:
'0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)',
position: 'fixed',
minWidth: 200,
maxWidth: 400,
width: 'auto',
}}
>
<Menu
items={menus}
onSelectedMenuChanged={onSelectedMenuChanged}
selectedMenuKeys={selectedMenuKeys}
/>
</Sider>
);
};
export default memo(LeftNavigation);
|
hieutran3010/EnglishOnline
|
src/app/containers/Post/types.ts
|
import Post from 'app/models/post';
/* --- STATE --- */
export interface PostState {
isFetchingPosts: boolean;
posts: Post[];
}
export type ContainerState = PostState;
|
hieutran3010/EnglishOnline
|
src/app/components/collection/AutoComplete/AutoComplete.tsx
|
import React, { useState, useCallback, useMemo } from 'react';
import { AutoComplete } from 'antd';
import { AutoCompleteProps } from 'antd/lib/auto-complete';
import isEmpty from 'lodash/fp/isEmpty';
import find from 'lodash/fp/find';
import get from 'lodash/fp/get';
import set from 'lodash/fp/set';
import map from 'lodash/fp/map';
import filter from 'lodash/fp/filter';
import size from 'lodash/fp/size';
import head from 'lodash/fp/head';
import {
IDataSource,
QueryOperator,
QueryParams,
QueryCriteria,
} from '../types';
const { Option } = AutoComplete;
const getQueryParams = (
searchKey: string,
searchPropNames: string[],
pageSize?: number,
): QueryParams => {
if (!searchKey || isEmpty(searchKey)) {
// get first page
return {
pageSize,
page: 1,
};
}
let criteria: QueryCriteria[] = [];
searchPropNames.forEach((propName: string) => {
criteria.push({
field: propName,
operator: QueryOperator.C,
value: searchKey,
});
});
return { criteria };
};
interface Props {
fetchDataSource: IDataSource;
minSearchLength: number;
searchPropNames: string[];
valuePath: string;
onSelected?: (item: any) => void;
displayPath: string;
itemRender?: (item: any) => React.Component;
pageSize?: number;
excludeValue?: any;
onNormalizeSearchKey?: (searchKey: string) => string;
}
const DefaultAutoComplete = React.forwardRef(
(
{
fetchDataSource,
minSearchLength,
searchPropNames,
onSelected,
displayPath,
valuePath,
itemRender,
pageSize,
excludeValue,
onNormalizeSearchKey,
...restProps
}: Props & AutoCompleteProps,
ref: any,
) => {
const [items, setItems] = useState<any[]>();
const [isFetchedFirstTime, setIsFetchedFirstTime] = useState(false);
const fetchData = useCallback(
async (searchKey: string) => {
const queryParams = getQueryParams(
searchKey,
searchPropNames,
pageSize,
);
const data = await fetchDataSource.queryManyAsync(queryParams, true);
if (!isEmpty(data)) {
setItems(data);
if (size(data) === 1) {
const uniqueData = head(data);
const val = get(displayPath)(uniqueData) || uniqueData;
if (val === searchKey) {
onSelected && onSelected(head(data));
}
}
} else {
setItems([]);
}
},
[fetchDataSource, onSelected, pageSize, searchPropNames, displayPath],
);
const onSearchChange = useCallback(
(value: string) => {
if (isEmpty(value)) {
fetchData('');
return;
}
let searchKey = value;
if (onNormalizeSearchKey) {
searchKey = onNormalizeSearchKey(searchKey);
}
if (searchKey.length < minSearchLength) {
return;
}
fetchData(searchKey);
},
[fetchData, minSearchLength, onNormalizeSearchKey],
);
const onInternalSelected = useCallback(
(_value, option) => {
if (onSelected) {
const { key } = option;
const item = find(set(valuePath, key)({}))(items);
onSelected(item);
}
},
[items, onSelected, valuePath],
);
const onDropdownVisibleChanged = useCallback(
(open: boolean) => {
if (open === true && isEmpty(items) && !isFetchedFirstTime) {
fetchData('');
setIsFetchedFirstTime(true);
}
},
[fetchData, isFetchedFirstTime, items],
);
const source = useMemo(() => {
let filteredItems = items;
if (excludeValue && !isEmpty(excludeValue)) {
filteredItems = filter(
(item: any) => get(valuePath)(item) !== excludeValue,
)(items);
}
return map((item: any) => (
<Option
key={get(valuePath)(item) || item}
value={get(valuePath)(item) || item}
text={get(displayPath)(item) || item}
>
{(itemRender && itemRender(item)) || get(displayPath)(item) || item}
</Option>
))(filteredItems);
}, [displayPath, excludeValue, itemRender, items, valuePath]);
return (
<AutoComplete
ref={ref}
onSearch={onSearchChange}
onSelect={onInternalSelected}
onDropdownVisibleChange={onDropdownVisibleChanged}
{...restProps}
>
{source}
</AutoComplete>
);
},
);
DefaultAutoComplete.defaultProps = {
minSearchLength: 2,
valuePath: 'id',
pageSize: 20,
};
export default DefaultAutoComplete;
|
hieutran3010/EnglishOnline
|
src/app/fetchers/base/GraphQLFetcherBase.ts
|
<filename>src/app/fetchers/base/GraphQLFetcherBase.ts
import { GraphQLDoorClient, GraphQLEntityFetcher } from 'graphql-door-client';
import { authService } from 'app/services/auth';
export default class GraphQLFetcherBase<TModel> extends GraphQLEntityFetcher<
TModel
> {
graphqlDoorClient: GraphQLDoorClient;
constructor(entityName: string, onGetDefaultSelectFields: () => string[]) {
const endpoint = `${process.env.REACT_APP_API_ENDPOINT}/graphql`;
const client = new GraphQLDoorClient(endpoint, {
getToken: authService.getIdTokenAsync,
});
super(entityName, onGetDefaultSelectFields, client);
this.graphqlDoorClient = client;
}
}
|
hieutran3010/EnglishOnline
|
src/app/containers/Post/selectors.ts
|
import { createSelector } from '@reduxjs/toolkit';
import { RootState } from 'types';
import { initialState } from './slice';
const selectDomain = (state: RootState) => state.post || initialState;
export const selectPosts = createSelector(
[selectDomain],
postState => postState.posts,
);
export const selectIsFetchingPosts = createSelector(
[selectDomain],
postState => postState.isFetchingPosts,
);
|
hieutran3010/EnglishOnline
|
src/app/containers/Courses/index.tsx
|
/**
*
* Courses
*
*/
import React, { memo } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { useInjectReducer, useInjectSaga } from 'utils/redux-injectors';
import { reducer, sliceKey } from './slice';
import { selectCourses } from './selectors';
import { coursesSaga } from './saga';
interface Props {}
export const Courses = memo((props: Props) => {
useInjectReducer({ key: sliceKey, reducer: reducer });
useInjectSaga({ key: sliceKey, saga: coursesSaga });
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const courses = useSelector(selectCourses);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const dispatch = useDispatch();
return (
<>
<div>
</div>
</>
);
});
|
hieutran3010/EnglishOnline
|
src/app/containers/Auth/EmailVerification/index.tsx
|
/**
*
* EmailVerification
*
*/
import React, { memo, useCallback, useState } from 'react';
import { toast } from 'react-toastify';
import { Result, Button, Space } from 'antd';
import { useHistory } from 'react-router-dom';
import { authService, authStorage } from 'app/services/auth';
export const EmailVerification = memo(() => {
const history = useHistory();
const [isSending, setIsSending] = useState(false);
const onSendEmailVerification = useCallback(async () => {
setIsSending(true);
await authService.sendEmailVerification();
setIsSending(false);
toast.success(
'Một email đã được gởi tới bạn cho việc xác minh, vui lòng kiểm tra mail!',
);
authService.logout();
history.push('/');
}, [history]);
const onConfirmed = useCallback(async () => {
await authService.logout();
history.push('/');
}, [history]);
const user = authStorage.getUser();
return (
<Result
status="403"
title="403"
subTitle={`Bạn chưa xác thực cho email ${user.email}. Vui lòng kiểm tra mail và xác thực!`}
extra={
<Space>
<Button
type="primary"
onClick={onSendEmailVerification}
loading={isSending}
>
Gởi email xác thực
</Button>
<Button onClick={onConfirmed} disabled={isSending}>
Tôi đã xác thực
</Button>
</Space>
}
/>
);
});
|
hieutran3010/EnglishOnline
|
src/app/components/Layout/RootContainer.tsx
|
<gh_stars>0
import React, { ReactElement, useCallback, useMemo } from 'react';
import { PageHeader } from 'antd';
import { StyledContainer } from './styles/StyledRootContainer';
import { PageHeaderProps } from 'antd/lib/page-header';
interface Props {
title: string | ReactElement;
subTitle?: string;
children: any;
rightComponents?: ReactElement[];
canBack: boolean;
onBack?: () => void;
}
const RootContainer = ({
title,
subTitle,
children,
rightComponents,
canBack,
onBack,
...restProps
}: Props & PageHeaderProps) => {
const _onBack = useCallback(() => window.history.back(), []);
const getOnBackFunc = useMemo(() => {
if (onBack) {
return onBack;
}
if (canBack === true) {
return _onBack;
}
return undefined;
}, [_onBack, canBack, onBack]);
return (
<StyledContainer>
<PageHeader
title={title}
subTitle={subTitle}
style={{ margin: 10, marginBottom: 0 }}
extra={rightComponents}
onBack={getOnBackFunc}
{...restProps}
/>
<div>{children}</div>
</StyledContainer>
);
};
RootContainer.defaultProps = {
canBack: false,
};
export default RootContainer;
|
hieutran3010/EnglishOnline
|
src/app/fetchers/base/RestfulFetcherBase.ts
|
<reponame>hieutran3010/EnglishOnline
import WrappedAxiosFetcher from './WrappedAxiosFetcher';
import { authService } from 'app/services/auth';
export default class RestfulFetcherBase<TModel> extends WrappedAxiosFetcher<
TModel
> {
constructor(controller: string) {
const endpoint = `${process.env.REACT_APP_API_ENDPOINT}/${controller}`;
super(endpoint, authService.getIdTokenAsync);
}
}
|
hieutran3010/EnglishOnline
|
src/app/fetchers/postCommentFetcher.ts
|
import PostComment from 'app/models/postComment';
import { GraphQLFetcherBase } from './base';
export default class PostCommentFetcher extends GraphQLFetcherBase<
PostComment
> {
selectFields: string[] = ['id', 'owner', 'content', 'postId'];
constructor() {
super('PostComment', () => this.selectFields);
}
}
|
hieutran3010/EnglishOnline
|
src/app/models/user.ts
|
<reponame>hieutran3010/EnglishOnline<filename>src/app/models/user.ts
import ModelBase from './modelBase';
export default class User extends ModelBase {
email!: string;
emailVerified!: boolean;
phoneNumber?: string;
password?: string;
displayName!: string;
avatarUrl?: string;
role?: string;
disabled?: boolean;
roles: string[];
/**
*
*/
constructor() {
super();
this.roles = [];
}
}
|
hieutran3010/EnglishOnline
|
src/app/components/Layout/styles/StyledRootContainer.ts
|
<reponame>hieutran3010/EnglishOnline<filename>src/app/components/Layout/styles/StyledRootContainer.ts<gh_stars>0
import styled from 'styled-components/macro';
export const StyledContainer = styled.div`
background-color: white;
border-radius: 10px;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1),
0 2px 4px -1px rgba(0, 0, 0, 0.06);
`;
|
hieutran3010/EnglishOnline
|
src/app/containers/HomePage/index.tsx
|
/*
* HomePage
*
* This is the first thing users see of our App, at the '/' route
*
*/
import React, { useEffect, useCallback, useState } from 'react';
import { Route, Switch, useHistory, Redirect } from 'react-router-dom';
import { Spin, Menu, Layout, Tooltip } from 'antd';
import {
HomeOutlined,
FileProtectOutlined,
LogoutOutlined,
} from '@ant-design/icons';
import { authService, authStorage } from 'app/services/auth';
import { getScreenMode } from 'app/components/AppNavigation';
import { useInjectReducer } from 'utils/redux-injectors';
import { useSelector, useDispatch } from 'react-redux';
import { isMobile } from 'react-device-detect';
import { Login } from '../Auth/Login/Loadable';
import { EmailVerification } from '../Auth/EmailVerification/Loadable';
import { reducer, actions, sliceKey } from './slice';
import { Post } from '../Post/Loadable';
import Logo from 'app/components/Logo';
const logo = require('assets/logo.png');
const logoSmall = require('assets/logo-compact.png');
const { Header, Content } = Layout;
export function HomePage() {
const history = useHistory();
const dispatch = useDispatch();
useInjectReducer({ key: sliceKey, reducer });
const [isVerifiedAuth, setIsVerifiedAuth] = useState(false);
const [selectedMenu, setSelectedMenu] = useState(['home']);
const onSizeChanged = useCallback(() => {
dispatch(actions.setScreenMode(getScreenMode()));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
window.addEventListener('resize', onSizeChanged);
return function cleanUp() {
window.removeEventListener('resize', onSizeChanged);
};
}, [onSizeChanged]);
useEffect(() => {
const loginSubscriber = authService.onLoginSuccess.subscribe(
(user: any) => {
setIsVerifiedAuth(true);
if (!user.emailVerified) {
history.push('/emailVerification');
}
},
);
const logoutSubscriber = authService.onLogoutSuccess.subscribe(() => {
setIsVerifiedAuth(false);
history.push('/');
});
return function cleanUp() {
loginSubscriber.unsubscribe();
logoutSubscriber.unsubscribe();
};
}, [history]);
const onMenuChanged = useCallback(e => {
setSelectedMenu([e.key]);
}, []);
const onLogOut = useCallback(() => {
authService.logout();
}, []);
const isAuthenticated = authService.isAuthenticated();
if (!isAuthenticated) {
return (
<Switch>
<Route breadcrumbName="Đăng Nhập" exact path="/" component={Login} />
<Route
breadcrumbName="Xác Thực Email"
exact
path="/emailVerification"
component={EmailVerification}
/>
</Switch>
);
}
if (!isVerifiedAuth) {
return (
<div
style={{
width: '100%',
height: '100vh',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
}}
>
<Spin size="large" />
</div>
);
}
return (
<Layout style={{ height: '100%' }}>
<Header style={{ padding: 0 }}>
<Menu
onClick={onMenuChanged}
mode="horizontal"
selectedKeys={selectedMenu}
style={{ textAlign: 'center' }}
>
<Menu.Item key="home" icon={<HomeOutlined />}>
Home
</Menu.Item>
<Menu.Item key="courses" icon={<FileProtectOutlined />}>
Courses
</Menu.Item>
</Menu>
<div style={{ position: 'fixed', top: 0 }}>
<Logo isSmall={isMobile} logoSrc={logo} logoSmallSrc={logoSmall} />
</div>
<div style={{ position: 'fixed', top: -5, right: 15, fontSize: 25 }}>
<Tooltip title="Thoát">
<LogoutOutlined onClick={onLogOut} />
</Tooltip>
</div>
</Header>
<Content style={{ padding: 20, overflow: 'auto', marginTop: 2 }}>
<Switch>
<Route breadcrumbName="Posts" exact path="/" component={Post} />
</Switch>
</Content>
</Layout>
);
}
|
hieutran3010/EnglishOnline
|
src/app/models/post.ts
|
import ModelBase from './modelBase';
import PostComment from './postComment';
export default class Post extends ModelBase {
owner!: string;
content!: string;
ownerAvatar!: string;
postComments?: PostComment[];
}
|
hieutran3010/EnglishOnline
|
src/app/containers/HomePage/Loadable.tsx
|
<filename>src/app/containers/HomePage/Loadable.tsx<gh_stars>0
/**
* Asynchronously loads the component for HomePage
*/
import React from 'react';
import { lazyLoad } from 'utils/loadable';
import { LazyLoadingSkeleton } from 'app/components/Skeleton';
export const HomePage = lazyLoad(
() => import('./index'),
module => module.HomePage,
{ fallback: <LazyLoadingSkeleton /> },
);
|
hieutran3010/EnglishOnline
|
src/app/fetchers/base/WrappedAxiosFetcher.ts
|
import axios, { AxiosResponse, AxiosRequestConfig } from 'axios';
import qs from 'qs';
export default class WrappedAxiosFetcher<T> {
baseUrl: string;
onGetIdTokenAsync?: () => Promise<string>;
constructor(endpoint: string, onGetIdTokenAsync?: () => Promise<string>) {
this.baseUrl = endpoint;
this.onGetIdTokenAsync = onGetIdTokenAsync;
}
post = async (model: T, route?: string) => {
const defaultConfig = await this._getDefaultConfig();
return axios.post(route || '', model, defaultConfig);
};
patch = async (patch: any, route?: string) => {
const defaultConfig = await this._getDefaultConfig();
return axios
.patch(route || '', patch, defaultConfig)
.then((response: AxiosResponse) => response.data);
};
getMany = async (route?: string, queryParams?: any): Promise<T[]> => {
const defaultConfig = await this._getDefaultConfig();
defaultConfig.params = queryParams;
return axios
.get(route || '', defaultConfig)
.then((response: AxiosResponse) => response.data);
};
get = async (
route?: string,
queryParams?: any,
otherConfig?: AxiosRequestConfig,
): Promise<T> => {
const defaultConfig = await this._getDefaultConfig(otherConfig);
defaultConfig.params = queryParams;
return axios
.get(route || '', defaultConfig)
.then((response: AxiosResponse) => response.data);
};
private _getDefaultConfig = async (
otherConfig?: AxiosRequestConfig,
): Promise<AxiosRequestConfig> => {
const result: AxiosRequestConfig = {
baseURL: this.baseUrl,
paramsSerializer: params => {
return qs.stringify(params);
},
...(otherConfig || {}),
};
if (this.onGetIdTokenAsync) {
const token = await this.onGetIdTokenAsync();
result.headers = { Authorization: `Bearer ${token}` };
}
return result;
};
}
|
hieutran3010/EnglishOnline
|
src/app/containers/Courses/types.ts
|
<reponame>hieutran3010/EnglishOnline
/* --- STATE --- */
export interface CoursesState {}
export type ContainerState = CoursesState;
|
hieutran3010/EnglishOnline
|
src/app/collection-datasource/graphql/constants.ts
|
<reponame>hieutran3010/EnglishOnline<gh_stars>0
export const GRAPHQL_QUERY_OPERATOR = {
CONTAINS: 'Contains',
EQUALS: '==',
NOT_EQUAL: '!=',
GT: '>',
GTE: '>=',
LT: '<',
LTE: '<=',
ANY_FALSE: 'Any',
ANY_TRUE: 'Any',
};
|
hieutran3010/EnglishOnline
|
src/app/index.tsx
|
/**
*
* App
*
* This component is the skeleton around the actual pages, and should only
* contain code that should be seen on all pages. (e.g. navigation bar)
*/
import * as React from 'react';
import { Helmet } from 'react-helmet-async';
import { Switch, Route, BrowserRouter } from 'react-router-dom';
import { GlobalStyle } from '../styles/global-styles';
import { HomePage } from './containers/HomePage/Loadable';
import { NotFoundPage } from './containers/NotFoundPage/Loadable';
import { initializeFirebase } from './services/firebase';
initializeFirebase();
export function App() {
return (
<BrowserRouter>
<Helmet titleTemplate="English Zone" defaultTitle="English Zone">
<meta name="description" content="English Zone" />
</Helmet>
<Switch>
<Route path={process.env.PUBLIC_URL + '/'} component={HomePage} />
<Route exact component={NotFoundPage} />
</Switch>
<GlobalStyle />
</BrowserRouter>
);
}
|
hieutran3010/EnglishOnline
|
src/app/components/Layout/ContentContainer.tsx
|
import React from 'react';
import { Card } from 'antd';
import { CardProps } from 'antd/lib/card';
import omit from 'lodash/fp/omit';
const ContentContainer = (props: CardProps) => {
const { children, style } = props;
return (
<Card
className="content-container"
size="small"
style={{
height: '100%',
overflowY: 'auto',
overflowX: 'hidden',
...style,
}}
bordered={false}
{...omit(['style'])(props)}
>
{children}
</Card>
);
};
export default ContentContainer;
|
hieutran3010/EnglishOnline
|
src/app/fetchers/postFetcher.ts
|
import Post from 'app/models/post';
import { GraphQLFetcherBase } from './base';
export default class PostFetcher extends GraphQLFetcherBase<Post> {
selectFields: string[] = ['id', 'owner', 'content'];
constructor() {
super('Post', () => this.selectFields);
}
}
|
hieutran3010/EnglishOnline
|
src/app/containers/Auth/Login/index.tsx
|
<reponame>hieutran3010/EnglishOnline
/**
*
* Login
*
*/
import React, { memo, useCallback, useMemo, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { Form, Input, Button, Alert, Space } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import isEmpty from 'lodash/fp/isEmpty';
import { toast } from 'react-toastify';
import { useInjectReducer, useInjectSaga } from 'utils/redux-injectors';
import { getLoginValidator } from 'app/models/validators/userValidator';
import { PasswordInput } from 'app/components/Input';
import { actions, reducer, sliceKey } from './slice';
import {
selectIsBeingLogin,
selectError,
selectRecoveryError,
} from './selectors';
import { loginSaga } from './saga';
import {
StyledLogInContainer,
StyledLoginFormContainer,
} from './styles/StyledIndex';
const logo = require('assets/logo.png');
enum AuthenticationMode {
Login = 0,
RecoverPass,
}
export const Login = memo(() => {
useInjectReducer({ key: sliceKey, reducer: reducer });
useInjectSaga({ key: sliceKey, saga: loginSaga });
const isBeingLogin = useSelector(selectIsBeingLogin);
const error = useSelector(selectError);
const recoveryError = useSelector(selectRecoveryError);
const [authMode, setAuthMode] = useState<AuthenticationMode>(
AuthenticationMode.Login,
);
const dispatch = useDispatch();
const onFinish = useCallback(
form => {
dispatch(actions.login(form));
},
[dispatch],
);
const onRecoverPass = useCallback(() => {
setAuthMode(AuthenticationMode.RecoverPass);
}, []);
const onBackToLogin = useCallback(() => {
setAuthMode(AuthenticationMode.Login);
}, []);
const onSendRecoveryEmail = useCallback(
form => {
const { email } = form;
dispatch(
actions.recoveryPassword({
email,
onSent: () => {
toast.success(
'Đã gởi email! Vui lòng check mail để tiếp tục khôi phục mật khẩu!',
);
setAuthMode(AuthenticationMode.Login);
},
}),
);
},
[dispatch],
);
const loginValidator = useMemo(() => getLoginValidator(), []);
return (
<StyledLogInContainer>
<StyledLoginFormContainer>
<img src={logo} height="40px" alt="" style={{ marginBottom: 24 }} />
{authMode === AuthenticationMode.Login && (
<Form name="normal_login" className="login-form" onFinish={onFinish}>
<Form.Item name="email" rules={loginValidator.email}>
<Input
prefix={<UserOutlined className="site-form-item-icon" />}
placeholder="Email"
ref={ref => ref?.select()}
disabled={isBeingLogin}
/>
</Form.Item>
<Form.Item name="password" rules={loginValidator.password}>
<PasswordInput
placeholder="<PASSWORD>"
prefix={<LockOutlined className="site-form-item-icon" />}
disabled={isBeingLogin}
/>
</Form.Item>
<Form.Item>
<Button
className="login-form-forgot"
type="link"
disabled={isBeingLogin}
onClick={onRecoverPass}
>
Quên mật khẩu?
</Button>
</Form.Item>
<Form.Item>
{error && !isEmpty(error) && (
<Alert
type="error"
message={error}
showIcon
style={{ marginBottom: 10 }}
/>
)}
<Button
type="primary"
htmlType="submit"
className="login-form-button"
loading={isBeingLogin}
>
Đăng Nhập
</Button>
</Form.Item>
</Form>
)}
{authMode === AuthenticationMode.RecoverPass && (
<Form onFinish={onSendRecoveryEmail}>
<Form.Item name="email" rules={loginValidator.email}>
<Input
prefix={<UserOutlined className="site-form-item-icon" />}
placeholder="Nhập email của bạn"
ref={ref => ref?.select()}
disabled={isBeingLogin}
/>
</Form.Item>
{recoveryError && !isEmpty(recoveryError) && (
<Form.Item>
<Alert type="error" message={recoveryError} showIcon />
</Form.Item>
)}
<Form.Item>
<Space>
<Button
type="primary"
htmlType="submit"
className="login-form-button"
>
Gởi email phục hồi mật khẩu
</Button>
<Button htmlType="button" onClick={onBackToLogin}>
Đăng Nhập
</Button>
</Space>
</Form.Item>
</Form>
)}
</StyledLoginFormContainer>
</StyledLogInContainer>
);
});
|
hieutran3010/EnglishOnline
|
src/app/components/Select/index.ts
|
<filename>src/app/components/Select/index.ts
import CountrySelect from './CountrySelect';
export { CountrySelect };
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.