text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { UdfCategory, UdfCategoryFunctions } from 'sql/reference/types';
import I18n from 'utils/i18n';
const EVAL_FUNCTIONS: UdfCategoryFunctions = {
avg: {
name: 'avg',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'AVG(%VAR%)',
draggable: 'AVG()'
},
concat: {
name: 'concat',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'CONCAT(%VAR1%, %VAR2%)',
draggable: 'CONCAT()'
},
count: {
name: 'count',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'COUNT(%VAR%)',
draggable: 'COUNT()'
},
count_start: {
name: 'count_start',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'COUNT_START(%VAR%)',
draggable: 'COUNT_START()'
},
is_empty: {
name: 'is_empty',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'IsEmpty(%VAR%)',
draggable: 'IsEmpty()'
},
diff: {
name: 'diff',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'DIFF(%VAR1%, %VAR2%)',
draggable: 'DIFF()'
},
max: {
name: 'max',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'MAX(%VAR%)',
draggable: 'MAX()'
},
min: {
name: 'min',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'MIN(%VAR%)',
draggable: 'MIN()'
},
size: {
name: 'size',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'SIZE(%VAR%)',
draggable: 'SIZE()'
},
sum: {
name: 'sum',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'SUM(%VAR%)',
draggable: 'SUM()'
},
tokenize: {
name: 'tokenize',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'TOKENIZE(%VAR%, %DELIM%)',
draggable: 'TOKENIZE()'
}
};
const RELATIONAL_OPERATORS: UdfCategoryFunctions = {
cogroup: {
name: 'cogroup',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'COGROUP %VAR% BY %VAR%',
draggable: 'COGROUP %VAR% BY %VAR%'
},
cross: {
name: 'cross',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'CROSS %VAR1%, %VAR2%;',
draggable: 'CROSS %VAR1%, %VAR2%;'
},
distinct: {
name: 'distinct',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'DISTINCT %VAR%;',
draggable: 'DISTINCT %VAR%;'
},
filter: {
name: 'filter',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'FILTER %VAR% BY %COND%',
draggable: 'FILTER %VAR% BY %COND%'
},
flatten: {
name: 'flatten',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'FLATTEN(%VAR%)',
draggable: 'FLATTEN()'
},
foreach_generate: {
name: 'foreach_generate',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'FOREACH %DATA% GENERATE %NEW_DATA%;',
draggable: 'FOREACH %DATA% GENERATE %NEW_DATA%;'
},
foreach: {
name: 'foreach',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'FOREACH %DATA% {%NESTED_BLOCK%};',
draggable: 'FOREACH %DATA% {%NESTED_BLOCK%};'
},
group_by: {
name: 'group_by',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'GROUP %VAR% BY %VAR%',
draggable: 'GROUP %VAR% BY %VAR%'
},
group_all: {
name: 'group_all',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'GROUP %VAR% ALL',
draggable: 'GROUP %VAR% ALL'
},
join: {
name: 'join',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'JOIN %VAR% BY ',
draggable: 'JOIN %VAR% BY '
},
limit: {
name: 'limit',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'LIMIT %VAR% %N%',
draggable: 'LIMIT %VAR% %N%'
},
order: {
name: 'order',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'ORDER %VAR% BY %FIELD%',
draggable: 'ORDER %VAR% BY %FIELD%'
},
sample: {
name: 'sample',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'SAMPLE %VAR% %SIZE%',
draggable: 'SAMPLE %VAR% %SIZE%'
},
split: {
name: 'split',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'SPLIT %VAR1% INTO %VAR2% IF %EXPRESSIONS%',
draggable: 'SPLIT %VAR1% INTO %VAR2% IF %EXPRESSIONS%'
},
union: {
name: 'union',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'UNION %VAR1%, %VAR2%',
draggable: 'UNION %VAR1%, %VAR2%'
}
};
const INPUT_OUTPUT: UdfCategoryFunctions = {
load: {
name: 'load',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: "LOAD '%FILE%';",
draggable: "LOAD '%FILE%';"
},
dump: {
name: 'dump',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'DUMP %VAR%;',
draggable: 'DUMP %VAR%;'
},
store: {
name: 'store',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'STORE %VAR% INTO %PATH%;',
draggable: 'STORE %VAR% INTO %PATH%;'
}
};
const DEBUG: UdfCategoryFunctions = {
explain: {
name: 'explain',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'EXPLAIN %VAR%;',
draggable: 'EXPLAIN %VAR%;'
},
illustrate: {
name: 'illustrate',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'ILLUSTRATE %VAR%;',
draggable: 'ILLUSTRATE %VAR%;'
},
describe: {
name: 'describe',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'DESCRIBE %VAR%;',
draggable: 'DESCRIBE %VAR%;'
}
};
const HCATALOG: UdfCategoryFunctions = {
LOAD: {
name: 'LOAD',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: "LOAD '%TABLE%' USING org.apache.hcatalog.pig.HCatLoader();",
draggable: "LOAD '%TABLE%' USING org.apache.hcatalog.pig.HCatLoader();"
}
};
const MATH_FUNCTIONS: UdfCategoryFunctions = {
abs: {
name: 'abs',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'ABS(%VAR%)',
draggable: 'ABS()'
},
acos: {
name: 'acos',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'ACOS(%VAR%)',
draggable: 'ACOS()'
},
asin: {
name: 'asin',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'ASIN(%VAR%)',
draggable: 'ASIN()'
},
atan: {
name: 'atan',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'ATAN(%VAR%)',
draggable: 'ATAN()'
},
cbrt: {
name: 'cbrt',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'CBRT(%VAR%)',
draggable: 'CBRT()'
},
ceil: {
name: 'ceil',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'CEIL(%VAR%)',
draggable: 'CEIL()'
},
cos: {
name: 'cos',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'COS(%VAR%)',
draggable: 'COS()'
},
cosh: {
name: 'cosh',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'COSH(%VAR%)',
draggable: 'COSH()'
},
exp: {
name: 'exp',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'EXP(%VAR%)',
draggable: 'EXP()'
},
floor: {
name: 'floor',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'FLOOR(%VAR%)',
draggable: 'FLOOR()'
},
log: {
name: 'log',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'LOG(%VAR%)',
draggable: 'LOG()'
},
log10: {
name: 'log10',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'LOG10(%VAR%)',
draggable: 'LOG10()'
},
random: {
name: 'random',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'RANDOM(%VAR%)',
draggable: 'RANDOM()'
},
round: {
name: 'round',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'ROUND(%VAR%)',
draggable: 'ROUND()'
},
sin: {
name: 'sin',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'SIN(%VAR%)',
draggable: 'SIN()'
},
sinh: {
name: 'sinh',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'SINH(%VAR%)',
draggable: 'SINH()'
},
sqrt: {
name: 'sqrt',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'SQRT(%VAR%)',
draggable: 'SQRT()'
},
tan: {
name: 'tan',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'TAN(%VAR%)',
draggable: 'TAN()'
},
tanh: {
name: 'tanh',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'TANH(%VAR%)',
draggable: 'TANH()'
}
};
const TUPLE_BAG_MAP: UdfCategoryFunctions = {
totuple: {
name: 'totuple',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'TOTUPLE(%VAR%)',
draggable: 'TOTUPLE()'
},
tobag: {
name: 'tobag',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'TOBAG(%VAR%)',
draggable: 'TOBAG()'
},
tomap: {
name: 'tomap',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'TOMAP(%KEY%, %VALUE%)',
draggable: 'TOMAP()'
},
top: {
name: 'top',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'TOP(%topN%, %COLUMN%, %RELATION%)',
draggable: 'TOP()'
}
};
const STRING_FUNCTIONS: UdfCategoryFunctions = {
indexof: {
name: 'indexof',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: "INDEXOF(%STRING%, '%CHARACTER%', %STARTINDEX%)",
draggable: 'INDEXOF()'
},
last_index_of: {
name: 'last_index_of',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: "LAST_INDEX_OF(%STRING%, '%CHARACTER%', %STARTINDEX%)",
draggable: 'LAST_INDEX_OF()'
},
lower: {
name: 'lower',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'LOWER(%STRING%)',
draggable: 'LOWER()'
},
regex_extract: {
name: 'regex_extract',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'REGEX_EXTRACT(%STRING%, %REGEX%, %INDEX%)',
draggable: 'REGEX_EXTRACT()'
},
regex_extract_all: {
name: 'regex_extract_all',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'REGEX_EXTRACT_ALL(%STRING%, %REGEX%)',
draggable: 'REGEX_EXTRACT_ALL()'
},
replace: {
name: 'replace',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: "REPLACE(%STRING%, '%oldChar%', '%newChar%')",
draggable: 'REPLACE()'
},
strsplit: {
name: 'strsplit',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'STRSPLIT(%STRING%, %REGEX%, %LIMIT%)',
draggable: 'STRSPLIT()'
},
substring: {
name: 'substring',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'SUBSTRING(%STRING%, %STARTINDEX%, %STOPINDEX%)',
draggable: 'SUBSTRING()'
},
trim: {
name: 'trim',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'TRIM(%STRING%)',
draggable: 'TRIM()'
},
ucfirst: {
name: 'ucfirst',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'UCFIRST(%STRING%)',
draggable: 'UCFIRST()'
},
upper: {
name: 'upper',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: 'UPPER(%STRING%)',
draggable: 'UPPER()'
}
};
const MACROS: UdfCategoryFunctions = {
import: {
name: 'import',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: "IMPORT '%PATH_TO_MACRO%';",
draggable: "IMPORT '%PATH_TO_MACRO%';"
}
};
const HBASE: UdfCategoryFunctions = {
load: {
name: 'load',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature:
"LOAD 'hbase://%TABLE%' USING org.apache.pig.backend.hadoop.hbase.HBaseStorage('%columnList%')",
draggable:
"LOAD 'hbase://%TABLE%' USING org.apache.pig.backend.hadoop.hbase.HBaseStorage('%columnList%')"
},
store: {
name: 'store',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature:
"STORE %VAR% INTO 'hbase://%TABLE%' USING org.apache.pig.backend.hadoop.hbase.HBaseStorage('%columnList%')",
draggable:
"STORE %VAR% INTO 'hbase://%TABLE%' USING org.apache.pig.backend.hadoop.hbase.HBaseStorage('%columnList%')"
}
};
const PYTHON_UDF: UdfCategoryFunctions = {
register: {
name: 'register',
returnTypes: ['T'],
arguments: [[{ type: 'T', multiple: true }]],
signature: "REGISTER 'python_udf.py' USING jython AS myfuncs;",
draggable: "REGISTER 'python_udf.py' USING jython AS myfuncs;"
}
};
export const UDF_CATEGORIES: UdfCategory[] = [
{ name: I18n('Eval'), functions: EVAL_FUNCTIONS },
{ name: I18n('Relational Operators'), functions: RELATIONAL_OPERATORS },
{ name: I18n('Input and Output'), functions: INPUT_OUTPUT },
{ name: I18n('Debug'), functions: DEBUG },
{ name: I18n('HCatalog'), functions: HCATALOG },
{ name: I18n('Math'), functions: MATH_FUNCTIONS },
{ name: I18n('Tuple, Bag and Map'), functions: TUPLE_BAG_MAP },
{ name: I18n('String'), functions: STRING_FUNCTIONS },
{ name: I18n('Macros'), functions: MACROS },
{ name: I18n('HBase'), functions: HBASE },
{ name: I18n('Python UDF'), functions: PYTHON_UDF }
]; | the_stack |
import { handler as scheduler } from '../scheduler';
import {
connectToDatabase,
Scan,
Organization,
ScanTask,
OrganizationTag
} from '../../models';
jest.mock('../ecs-client');
const { runCommand, getNumTasks } = require('../ecs-client');
describe('scheduler', () => {
beforeAll(async () => {
await connectToDatabase();
});
test('should run a scan for the first time', async () => {
let scan = await Scan.create({
name: 'findomain',
arguments: {},
frequency: 999
}).save();
const organization = await Organization.create({
name: 'test-' + Math.random(),
rootDomains: ['test-' + Math.random()],
ipBlocks: [],
isPassive: false
}).save();
await scheduler(
{
scanId: scan.id,
organizationIds: [organization.id]
},
{} as any,
() => void 0
);
expect(runCommand).toHaveBeenCalledTimes(1);
expect(runCommand).toHaveBeenCalledWith(
expect.objectContaining({
organizations: [
{
id: organization.id,
name: organization.name
}
],
scanId: scan.id,
scanName: scan.name
})
);
const scanTask = await ScanTask.findOne(
runCommand.mock.calls[0][0].scanTaskId
);
expect(scanTask?.status).toEqual('requested');
expect(scanTask?.fargateTaskArn).toEqual('mock_task_arn');
scan = (await Scan.findOne(scan.id))!;
expect(scan.lastRun).toBeTruthy();
});
describe('scheduling', () => {
test('should not run a scan when a scantask for that scan and organization is already in progress', async () => {
let scan = await Scan.create({
name: 'findomain',
arguments: {},
frequency: 999
}).save();
const organization = await Organization.create({
name: 'test-' + Math.random(),
rootDomains: ['test-' + Math.random()],
ipBlocks: [],
isPassive: false
}).save();
await ScanTask.create({
organization,
scan,
type: 'fargate',
status: 'created'
}).save();
await scheduler(
{
scanId: scan.id,
organizationIds: [organization.id]
},
{} as any,
() => void 0
);
expect(runCommand).toHaveBeenCalledTimes(0);
scan = (await Scan.findOne(scan.id))!;
expect(scan.lastRun).toBeFalsy();
});
test('should run a scan when a scantask for that scan and another organization is already in progress', async () => {
const scan = await Scan.create({
name: 'findomain',
arguments: {},
frequency: 999
}).save();
const organization = await Organization.create({
name: 'test-' + Math.random(),
rootDomains: ['test-' + Math.random()],
ipBlocks: [],
isPassive: false
}).save();
await ScanTask.create({
organization: undefined,
scan,
type: 'fargate',
status: 'created'
}).save();
await scheduler(
{
scanId: scan.id,
organizationIds: [organization.id]
},
{} as any,
() => void 0
);
expect(runCommand).toHaveBeenCalledTimes(1);
});
test('should not run a scan when a scantask for that scan and organization finished too recently', async () => {
const scan = await Scan.create({
name: 'findomain',
arguments: {},
frequency: 999
}).save();
const organization = await Organization.create({
name: 'test-' + Math.random(),
rootDomains: ['test-' + Math.random()],
ipBlocks: [],
isPassive: false
}).save();
await ScanTask.create({
organization,
scan,
type: 'fargate',
status: 'finished',
finishedAt: new Date()
}).save();
await scheduler(
{
scanId: scan.id,
organizationIds: [organization.id]
},
{} as any,
() => void 0
);
expect(runCommand).toHaveBeenCalledTimes(0);
});
test('should not run a scan when a scantask for that scan and organization finished too recently, and a failed scan occurred afterwards that does not have a finishedAt column', async () => {
const scan = await Scan.create({
name: 'findomain',
arguments: {},
frequency: 999
}).save();
const organization = await Organization.create({
name: 'test-' + Math.random(),
rootDomains: ['test-' + Math.random()],
ipBlocks: [],
isPassive: false
}).save();
await ScanTask.create({
organization,
scan,
type: 'fargate',
status: 'finished',
finishedAt: new Date()
}).save();
await ScanTask.create({
organization,
scan,
type: 'fargate',
status: 'failed',
createdAt: new Date()
}).save();
await scheduler(
{
scanId: scan.id,
organizationIds: [organization.id]
},
{} as any,
() => void 0
);
expect(runCommand).toHaveBeenCalledTimes(0);
});
test('should not run a scan when a scantask for that scan and organization failed too recently', async () => {
const scan = await Scan.create({
name: 'findomain',
arguments: {},
frequency: 999
}).save();
const organization = await Organization.create({
name: 'test-' + Math.random(),
rootDomains: ['test-' + Math.random()],
ipBlocks: [],
isPassive: false
}).save();
await ScanTask.create({
organization,
scan,
type: 'fargate',
status: 'failed',
finishedAt: new Date()
}).save();
await scheduler(
{
scanId: scan.id,
organizationIds: [organization.id]
},
{} as any,
() => void 0
);
expect(runCommand).toHaveBeenCalledTimes(0);
});
test('should not run a scan when scan is a SingleScan and has finished', async () => {
const scan = await Scan.create({
name: 'findomain',
arguments: {},
frequency: 999,
isSingleScan: true,
manualRunPending: false
}).save();
const organization = await Organization.create({
name: 'test-' + Math.random(),
rootDomains: ['test-' + Math.random()],
ipBlocks: [],
isPassive: false
}).save();
await ScanTask.create({
organization,
scan,
type: 'fargate',
status: 'finished',
finishedAt: new Date()
}).save();
await scheduler(
{
scanId: scan.id,
organizationIds: [organization.id]
},
{} as any,
() => void 0
);
expect(runCommand).toHaveBeenCalledTimes(0);
});
test('should not run a scan when scan is a SingleScan and has not run yet', async () => {
const scan = await Scan.create({
name: 'findomain',
arguments: {},
frequency: 999,
isSingleScan: true,
manualRunPending: false
}).save();
const organization = await Organization.create({
name: 'test-' + Math.random(),
rootDomains: ['test-' + Math.random()],
ipBlocks: [],
isPassive: false
}).save();
await scheduler(
{
scanId: scan.id,
organizationIds: [organization.id]
},
{} as any,
() => void 0
);
expect(runCommand).toHaveBeenCalledTimes(1);
});
test('should always run a scan when scan has manualRunPending set to true', async () => {
let scan = await Scan.create({
name: 'findomain',
arguments: {},
frequency: 1,
isSingleScan: true,
manualRunPending: true
}).save();
const organization = await Organization.create({
name: 'test-' + Math.random(),
rootDomains: ['test-' + Math.random()],
ipBlocks: [],
isPassive: false
}).save();
await ScanTask.create({
organization,
scan,
type: 'fargate',
status: 'finished',
finishedAt: new Date()
}).save();
await scheduler(
{
scanId: scan.id,
organizationIds: [organization.id]
},
{} as any,
() => void 0
);
expect(runCommand).toHaveBeenCalledTimes(1);
// Ensure scheduler set manualRunPending back to false
scan = (await Scan.findOne({ id: scan.id })) as Scan;
expect(scan.manualRunPending).toEqual(false);
});
test('should run a scan when a scantask for that scan and organization finished and sufficient time has passed', async () => {
const scan = await Scan.create({
name: 'findomain',
arguments: {},
frequency: 100
}).save();
const organization = await Organization.create({
name: 'test-' + Math.random(),
rootDomains: ['test-' + Math.random()],
ipBlocks: [],
isPassive: false
}).save();
const finishedAt = new Date();
finishedAt.setSeconds(finishedAt.getSeconds() - 101);
await ScanTask.create({
organization,
scan,
type: 'fargate',
status: 'finished',
finishedAt
}).save();
await scheduler(
{
scanId: scan.id,
organizationIds: [organization.id]
},
{} as any,
() => void 0
);
expect(runCommand).toHaveBeenCalledTimes(1);
});
test('should run a scan when a scantask for that scan and organization failed and sufficient time has passed', async () => {
const scan = await Scan.create({
name: 'findomain',
arguments: {},
frequency: 100
}).save();
const organization = await Organization.create({
name: 'test-' + Math.random(),
rootDomains: ['test-' + Math.random()],
ipBlocks: [],
isPassive: false
}).save();
const finishedAt = new Date();
finishedAt.setSeconds(finishedAt.getSeconds() - 101);
await ScanTask.create({
organization,
scan,
type: 'fargate',
status: 'failed',
finishedAt
}).save();
await scheduler(
{
scanId: scan.id,
organizationIds: [organization.id]
},
{} as any,
() => void 0
);
expect(runCommand).toHaveBeenCalledTimes(1);
});
});
describe('granular scans', () => {
test('should run a granular scan only on associated organizations', async () => {
const organization = await Organization.create({
name: 'test-' + Math.random(),
rootDomains: ['test-' + Math.random()],
ipBlocks: [],
isPassive: false
}).save();
const organization2 = await Organization.create({
name: 'test-' + Math.random(),
rootDomains: ['test-' + Math.random()],
ipBlocks: [],
isPassive: false
}).save();
const organization3 = await Organization.create({
name: 'test-' + Math.random(),
rootDomains: ['test-' + Math.random()],
ipBlocks: [],
isPassive: false
}).save();
const scan = await Scan.create({
name: 'findomain',
arguments: {},
frequency: 999,
isGranular: true,
organizations: [organization, organization2]
}).save();
await scheduler(
{
scanId: scan.id
},
{} as any,
() => void 0
);
expect(runCommand).toHaveBeenCalledTimes(2);
expect(runCommand).toHaveBeenCalledWith(
expect.objectContaining({
organizations: [{ id: organization.id, name: organization.name }],
scanId: scan.id,
scanName: scan.name
})
);
expect(runCommand).toHaveBeenCalledWith(
expect.objectContaining({
organizations: [{ id: organization2.id, name: organization2.name }],
scanId: scan.id,
scanName: scan.name
})
);
let scanTask = await ScanTask.findOne(
runCommand.mock.calls[0][0].scanTaskId
);
expect(scanTask?.status).toEqual('requested');
scanTask = await ScanTask.findOne(runCommand.mock.calls[1][0].scanTaskId);
expect(scanTask?.status).toEqual('requested');
});
test('should run a granular scan on associated tags', async () => {
const tag1 = await OrganizationTag.create({
name: 'test-' + Math.random()
}).save();
const tag2 = await OrganizationTag.create({
name: 'test-' + Math.random()
}).save();
const organization = await Organization.create({
name: 'test-' + Math.random(),
rootDomains: ['test-' + Math.random()],
ipBlocks: [],
isPassive: false,
tags: [tag1]
}).save();
const organization2 = await Organization.create({
name: 'test-' + Math.random(),
rootDomains: ['test-' + Math.random()],
ipBlocks: [],
isPassive: false,
tags: [tag1]
}).save();
const organization3 = await Organization.create({
name: 'test-' + Math.random(),
rootDomains: ['test-' + Math.random()],
ipBlocks: [],
isPassive: false,
tags: [tag2]
}).save();
const scan = await Scan.create({
name: 'findomain',
arguments: {},
frequency: 999,
isGranular: true,
tags: [tag1]
}).save();
await scheduler(
{
scanId: scan.id
},
{} as any,
() => void 0
);
expect(runCommand).toHaveBeenCalledTimes(2);
expect(runCommand).toHaveBeenCalledWith(
expect.objectContaining({
organizations: [{ id: organization.id, name: organization.name }],
scanId: scan.id,
scanName: scan.name
})
);
expect(runCommand).toHaveBeenCalledWith(
expect.objectContaining({
organizations: [{ id: organization2.id, name: organization2.name }],
scanId: scan.id,
scanName: scan.name
})
);
let scanTask = await ScanTask.findOne(
runCommand.mock.calls[0][0].scanTaskId
);
expect(scanTask?.status).toEqual('requested');
scanTask = await ScanTask.findOne(runCommand.mock.calls[1][0].scanTaskId);
expect(scanTask?.status).toEqual('requested');
});
test('should only run a scan once if an organization and its tag are both enabled', async () => {
const tag1 = await OrganizationTag.create({
name: 'test-' + Math.random()
}).save();
const tag2 = await OrganizationTag.create({
name: 'test-' + Math.random()
}).save();
const organization = await Organization.create({
name: 'test-' + Math.random(),
rootDomains: ['test-' + Math.random()],
ipBlocks: [],
isPassive: false,
tags: [tag1]
}).save();
const organization2 = await Organization.create({
name: 'test-' + Math.random(),
rootDomains: ['test-' + Math.random()],
ipBlocks: [],
isPassive: false,
tags: [tag1]
}).save();
const organization3 = await Organization.create({
name: 'test-' + Math.random(),
rootDomains: ['test-' + Math.random()],
ipBlocks: [],
isPassive: false,
tags: [tag2]
}).save();
const scan = await Scan.create({
name: 'findomain',
arguments: {},
frequency: 999,
isGranular: true,
organizations: [organization, organization2],
tags: [tag1]
}).save();
await scheduler(
{
scanId: scan.id
},
{} as any,
() => void 0
);
expect(runCommand).toHaveBeenCalledTimes(2);
expect(runCommand).toHaveBeenCalledWith(
expect.objectContaining({
organizations: [{ id: organization.id, name: organization.name }],
scanId: scan.id,
scanName: scan.name
})
);
expect(runCommand).toHaveBeenCalledWith(
expect.objectContaining({
organizations: [{ id: organization2.id, name: organization2.name }],
scanId: scan.id,
scanName: scan.name
})
);
let scanTask = await ScanTask.findOne(
runCommand.mock.calls[0][0].scanTaskId
);
expect(scanTask?.status).toEqual('requested');
scanTask = await ScanTask.findOne(runCommand.mock.calls[1][0].scanTaskId);
expect(scanTask?.status).toEqual('requested');
});
});
describe('global scans', () => {
test('should run a global scan for the first time', async () => {
jest.setTimeout(30000);
const scan = await Scan.create({
name: 'censysIpv4',
arguments: {},
frequency: 999
}).save();
await scheduler(
{
scanId: scan.id
},
{} as any,
() => void 0
);
// Calls scan in chunks
expect(runCommand).toHaveBeenCalledTimes(20);
expect(runCommand).toHaveBeenCalledWith(
expect.objectContaining({
organizations: [],
scanId: scan.id,
scanName: scan.name
})
);
const scanTask = await ScanTask.findOne(
runCommand.mock.calls[0][0].scanTaskId
);
expect(scanTask?.status).toEqual('requested');
expect(scanTask?.organization).toBeUndefined();
});
test('should not run a global scan when a scantask for it is already in progress', async () => {
const scan = await Scan.create({
name: 'censysIpv4',
arguments: {},
frequency: 999
}).save();
await ScanTask.create({
scan,
type: 'fargate',
status: 'created'
}).save();
await scheduler(
{
scanId: scan.id
},
{} as any,
() => void 0
);
expect(runCommand).toHaveBeenCalledTimes(0);
});
});
describe('concurrency', () => {
afterAll(() => {
getNumTasks.mockImplementation(() => 0);
});
test('should not run scan if max concurrency has already been reached', async () => {
const scan = await Scan.create({
name: 'findomain',
arguments: {},
frequency: 999
}).save();
const organization = await Organization.create({
name: 'test-' + Math.random(),
rootDomains: ['test-' + Math.random()],
ipBlocks: [],
isPassive: false
}).save();
getNumTasks.mockImplementation(() => 100);
await scheduler(
{
scanId: scan.id,
organizationIds: [organization.id]
},
{} as any,
() => void 0
);
expect(runCommand).toHaveBeenCalledTimes(0);
expect(
await ScanTask.count({
where: {
scan,
status: 'queued'
}
})
).toEqual(1);
// Should not queue any additional scans.
await scheduler(
{
scanId: scan.id,
organizationIds: [organization.id]
},
{} as any,
() => void 0
);
expect(runCommand).toHaveBeenCalledTimes(0);
expect(
await ScanTask.count({
where: {
scan,
status: 'queued'
}
})
).toEqual(1);
// Queue has opened up.
getNumTasks.mockImplementation(() => 0);
await scheduler(
{
scanId: scan.id,
organizationIds: [organization.id]
},
{} as any,
() => void 0
);
expect(runCommand).toHaveBeenCalledTimes(1);
});
test('should run only one, not two scans, if only one more scan remaining before max concurrency is reached', async () => {
const scan = await Scan.create({
name: 'findomain',
arguments: {},
frequency: 999
}).save();
const scan2 = await Scan.create({
name: 'findomain',
arguments: {},
frequency: 999
}).save();
const organization = await Organization.create({
name: 'test-' + Math.random(),
rootDomains: ['test-' + Math.random()],
ipBlocks: [],
isPassive: false
}).save();
getNumTasks.mockImplementation(() => 99);
await scheduler(
{
scanIds: [scan.id, scan2.id],
organizationIds: [organization.id]
},
{} as any,
() => void 0
);
expect(runCommand).toHaveBeenCalledTimes(1);
expect(
(await ScanTask.count({
where: {
scan,
status: 'queued'
}
})) +
(await ScanTask.count({
where: {
scan: scan2,
status: 'queued'
}
}))
).toEqual(1);
// Queue has opened up.
getNumTasks.mockImplementation(() => 90);
await scheduler(
{
scanIds: [scan.id, scan2.id],
organizationIds: [organization.id]
},
{} as any,
() => void 0
);
expect(runCommand).toHaveBeenCalledTimes(2);
});
test('should run part of a chunked (20) scan if less than 20 scans remaining before concurrency is reached, then run the rest of them only when concurrency opens back up', async () => {
const scan = await Scan.create({
name: 'censysIpv4',
arguments: {},
frequency: 999
}).save();
const organization = await Organization.create({
name: 'test-' + Math.random(),
rootDomains: ['test-' + Math.random()],
ipBlocks: [],
isPassive: false
}).save();
// Only 10/20 scantasks will run at first
getNumTasks.mockImplementation(() => 90);
await scheduler(
{
scanId: scan.id,
organizationIds: [organization.id]
},
{} as any,
() => void 0
);
expect(runCommand).toHaveBeenCalledTimes(10);
expect(
await ScanTask.count({
where: {
scan,
status: 'queued'
}
})
).toEqual(10);
// Should run the remaining 10 queued scantasks.
getNumTasks.mockImplementation(() => 0);
await scheduler(
{
scanId: scan.id,
organizationIds: [organization.id]
},
{} as any,
() => void 0
);
expect(runCommand).toHaveBeenCalledTimes(20);
expect(
await ScanTask.count({
where: {
scan,
status: 'queued'
}
})
).toEqual(0);
// No more scantasks remaining to be run.
getNumTasks.mockImplementation(() => 0);
await scheduler(
{
scanId: scan.id,
organizationIds: [organization.id]
},
{} as any,
() => void 0
);
expect(runCommand).toHaveBeenCalledTimes(20);
});
});
test('should not run a global scan when a scantask for it is already in progress, even if scantasks have finished before / after it', async () => {
const scan = await Scan.create({
name: 'censysIpv4',
arguments: {},
frequency: 999
}).save();
await ScanTask.create({
scan,
type: 'fargate',
status: 'finished',
createdAt: '2000-08-03T13:58:31.634Z'
}).save();
await ScanTask.create({
scan,
type: 'fargate',
status: 'created',
createdAt: '2000-05-03T13:58:31.634Z'
}).save();
await ScanTask.create({
scan,
type: 'fargate',
status: 'finished',
createdAt: '2000-01-03T13:58:31.634Z'
}).save();
await scheduler(
{
scanId: scan.id
},
{} as any,
() => void 0
);
expect(runCommand).toHaveBeenCalledTimes(0);
});
test('should not change lastRun time of the second scan if the first scan runs', async () => {
// Make scan run before scan2. Scan2 should have already run, and doesn't need to run again.
// The scheduler should not change scan2.lastRun during its second call
const scan = await Scan.create({
name: 'findomain',
arguments: {},
frequency: 1,
lastRun: new Date(0)
}).save();
let scan2 = await Scan.create({
name: 'findomain',
arguments: {},
frequency: 999,
lastRun: new Date()
}).save();
const organization = await Organization.create({
name: 'test-' + Math.random(),
rootDomains: ['test-' + Math.random()],
ipBlocks: [],
isPassive: false
}).save();
// Run scheduler on scan2, this establishes a finished recent scantask for scan2
await scheduler(
{
scanIds: [scan2.id],
organizationIds: [organization.id]
},
{} as any,
() => void 0
);
scan2 = (await Scan.findOne(scan2.id))!;
expect(runCommand).toHaveBeenCalledTimes(1);
// Run scheduler on both scans, scan should be run, but scan2 should be skipped
await scheduler(
{
scanIds: [scan.id, scan2.id],
organizationIds: [organization.id]
},
{} as any,
() => void 0
);
expect(runCommand).toHaveBeenCalledTimes(2);
const newscan2 = (await Scan.findOne(scan2.id))!;
// Expect scan2's lastRun was not edited during the second call to scheduler
expect(newscan2.lastRun).toEqual(scan2.lastRun);
});
describe('org batching', () => {
test('should run one scantask per org by default', async () => {
const scan = await Scan.create({
name: 'findomain',
arguments: {},
frequency: 999
}).save();
const organization = await Organization.create({
name: 'test-' + Math.random(),
rootDomains: ['test-' + Math.random()],
ipBlocks: [],
isPassive: false
}).save();
const organization2 = await Organization.create({
name: 'test-' + Math.random(),
rootDomains: ['test-' + Math.random()],
ipBlocks: [],
isPassive: false
}).save();
const organization3 = await Organization.create({
name: 'test-' + Math.random(),
rootDomains: ['test-' + Math.random()],
ipBlocks: [],
isPassive: false
}).save();
await scheduler(
{
scanId: scan.id,
organizationIds: [organization.id, organization2.id, organization3.id]
},
{} as any,
() => void 0
);
expect(runCommand).toHaveBeenCalledTimes(3);
expect(runCommand).toHaveBeenCalledWith(
expect.objectContaining({
organizations: [
{
id: organization.id,
name: organization.name
}
],
scanId: scan.id,
scanName: scan.name
})
);
expect(runCommand).toHaveBeenCalledWith(
expect.objectContaining({
organizations: [
{
id: organization2.id,
name: organization2.name
}
],
scanId: scan.id,
scanName: scan.name
})
);
expect(runCommand).toHaveBeenCalledWith(
expect.objectContaining({
organizations: [
{
id: organization3.id,
name: organization3.name
}
],
scanId: scan.id,
scanName: scan.name
})
);
});
test('should batch two orgs per scantask when specified', async () => {
const scan = await Scan.create({
name: 'findomain',
arguments: {},
frequency: 999
}).save();
const organization = await Organization.create({
name: 'test-' + Math.random(),
rootDomains: ['test-' + Math.random()],
ipBlocks: [],
isPassive: false
}).save();
const organization2 = await Organization.create({
name: 'test-' + Math.random(),
rootDomains: ['test-' + Math.random()],
ipBlocks: [],
isPassive: false
}).save();
const organization3 = await Organization.create({
name: 'test-' + Math.random(),
rootDomains: ['test-' + Math.random()],
ipBlocks: [],
isPassive: false
}).save();
await scheduler(
{
scanId: scan.id,
organizationIds: [
organization.id,
organization2.id,
organization3.id
],
orgsPerScanTask: 2
},
{} as any,
() => void 0
);
expect(runCommand).toHaveBeenCalledTimes(2);
expect(runCommand).toHaveBeenCalledWith(
expect.objectContaining({
organizations: [
{
id: organization.id,
name: organization.name
},
{
id: organization2.id,
name: organization2.name
}
],
scanId: scan.id,
scanName: scan.name
})
);
expect(runCommand).toHaveBeenCalledWith(
expect.objectContaining({
organizations: [
{
id: organization3.id,
name: organization3.name
}
],
scanId: scan.id,
scanName: scan.name
})
);
});
});
}); | the_stack |
import {Grid, GridAlignment} from '../grid';
import * as sorting from '../sorting';
const {expect} = chai;
// Utility type used for testing.
interface Crayon {
color: string;
x?: number;
y?: number;
}
describe('Grid', () => {
describe('arrange', () => {
it('should put everything in a single cell by default', () => {
// - +---+
// . |baz|
// 2 +---+---+
// . |foo|bar|
// - +---+---+
// |. .2. .|
const items: {name: string, x?: number, y?: number}[] =
[{name: 'foo'}, {name: 'bar'}, {name: 'baz'}];
const grid = new Grid(items);
grid.arrange();
expect(Object.keys(grid.cells).length).to.equal(1);
expect(grid.width).to.equal(2);
expect(grid.height).to.equal(2);
const cell = grid.getCell(null!, null!)!;
expect(cell.items).to.deep.equal(items);
expect(cell.x).to.equal(0);
expect(cell.y).to.equal(0);
expect(cell.width).to.equal(2);
expect(cell.height).to.equal(2);
expect(cell.innerWidth).to.equal(2);
expect(cell.innerHeight).to.equal(2);
expect(cell.contentX).to.equal(0);
expect(cell.contentY).to.equal(0);
const [fooItem, barItem, bazItem] = items;
expect(fooItem.x).to.equal(0);
expect(fooItem.y).to.equal(0);
expect(barItem.x).to.equal(1);
expect(barItem.y).to.equal(0);
expect(bazItem.x).to.equal(0);
expect(bazItem.y).to.equal(1);
});
it('should stack wide items vertically by default', () => {
// - +-------+-------+
// . | G | H |
// . +-------+-------+
// . | E | F |
// 4 +-------+-------+
// . | C | D |
// . +-------+-------+
// . | A | B |
// - +-------+-------+
// |. . . .4. . . .|
type Item = {name: string, x?: number, y?: number};
const items: Item[] = 'ABCDEFGH'.split('').map(ch => ({name: ch}));
const grid = new Grid(items);
grid.itemAspectRatio = 2;
grid.arrange();
expect(Object.keys(grid.cells).length).to.equal(1);
expect(grid.width).to.equal(4);
expect(grid.height).to.equal(4);
const cell = grid.getCell(null!, null!)!;
expect(cell.items).to.deep.equal(items);
expect(cell.x).to.equal(0);
expect(cell.y).to.equal(0);
expect(cell.width).to.equal(4);
expect(cell.height).to.equal(4);
expect(cell.innerWidth).to.equal(4);
expect(cell.innerHeight).to.equal(4);
expect(cell.contentX).to.equal(0);
expect(cell.contentY).to.equal(0);
const [A, B, C, D, E, F, G, H] = cell.items as Item[];
expect(A.x).to.equal(0);
expect(A.y).to.equal(0);
expect(B.x).to.equal(2);
expect(B.y).to.equal(0);
expect(C.x).to.equal(0);
expect(C.y).to.equal(1);
expect(D.x).to.equal(2);
expect(D.y).to.equal(1);
expect(E.x).to.equal(0);
expect(E.y).to.equal(2);
expect(F.x).to.equal(2);
expect(F.y).to.equal(2);
expect(G.x).to.equal(0);
expect(G.y).to.equal(3);
expect(H.x).to.equal(2);
expect(H.y).to.equal(3);
});
it('should assign sibling cells', () => {
// - +---+---+---+
// . | G | H | I |
// . +---+---+---+
// 3 | D | E | F |
// . +---+---+---+
// . | A | B | C |
// - +---+---+---+
// |. . .3. . .|
type Item = {name: string, row: number, col: number};
const items: Item[] = [
{name: 'A', row: 0, col: 0},
{name: 'B', row: 0, col: 1},
{name: 'C', row: 0, col: 2},
{name: 'D', row: 1, col: 0},
{name: 'E', row: 1, col: 1},
{name: 'F', row: 1, col: 2},
{name: 'G', row: 2, col: 0},
{name: 'H', row: 2, col: 1},
{name: 'I', row: 2, col: 2},
];
const grid = new Grid(items);
grid.cellMargin = 0;
grid.verticalFacet = (item: Item) => item.row;
grid.horizontalFacet = (item: Item) => item.col;
grid.verticalKeyCompare = sorting.numberCompare;
grid.horizontalKeyCompare = sorting.numberCompare;
grid.arrange();
expect(Object.keys(grid.cells).length).to.equal(9);
expect(grid.width).to.equal(3);
expect(grid.height).to.equal(3);
const [A, B, C, D, E, F, G, H, I] =
items.map(item => grid.getCell(item.row, item.col)!);
expect((A.siblings.above!.items[0] as Item).name).to.equal('D');
expect((A.siblings.right!.items[0] as Item).name).to.equal('B');
expect(A.siblings.below == null).to.equal(true);
expect(A.siblings.left == null).to.equal(true);
expect((B.siblings.above!.items[0] as Item).name).to.equal('E');
expect((B.siblings.left!.items[0] as Item).name).to.equal('A');
expect((B.siblings.right!.items[0] as Item).name).to.equal('C');
expect(B.siblings.below == null).to.equal(true);
expect((C.siblings.above!.items[0] as Item).name).to.equal('F');
expect((C.siblings.left!.items[0] as Item).name).to.equal('B');
expect(C.siblings.below == null).to.equal(true);
expect(C.siblings.right == null).to.equal(true);
expect((D.siblings.above!.items[0] as Item).name).to.equal('G');
expect((D.siblings.below!.items[0] as Item).name).to.equal('A');
expect((D.siblings.right!.items[0] as Item).name).to.equal('E');
expect(D.siblings.left == null).to.equal(true);
expect((E.siblings.above!.items[0] as Item).name).to.equal('H');
expect((E.siblings.below!.items[0] as Item).name).to.equal('B');
expect((E.siblings.left!.items[0] as Item).name).to.equal('D');
expect((E.siblings.right!.items[0] as Item).name).to.equal('F');
expect((F.siblings.above!.items[0] as Item).name).to.equal('I');
expect((F.siblings.below!.items[0] as Item).name).to.equal('C');
expect((F.siblings.left!.items[0] as Item).name).to.equal('E');
expect(F.siblings.right == null).to.equal(true);
expect((G.siblings.below!.items[0] as Item).name).to.equal('D');
expect((G.siblings.right!.items[0] as Item).name).to.equal('H');
expect(G.siblings.above == null).to.equal(true);
expect(G.siblings.left == null).to.equal(true);
expect((H.siblings.below!.items[0] as Item).name).to.equal('E');
expect((H.siblings.left!.items[0] as Item).name).to.equal('G');
expect((H.siblings.right!.items[0] as Item).name).to.equal('I');
expect(H.siblings.above == null).to.equal(true);
expect((I.siblings.below!.items[0] as Item).name).to.equal('F');
expect((I.siblings.left!.items[0] as Item).name).to.equal('H');
expect(I.siblings.above == null).to.equal(true);
expect(I.siblings.right == null).to.equal(true);
});
it('should arrange items horizontally by a string field', () => {
// 0 1 2
// - +---+ +---+ +---+
// 1 | b | | g | | r |
// - +---+ +---+ +---+
// |. . . . . 5 . . . . .|
const crayons: Crayon[] =
[{color: 'red'}, {color: 'green'}, {color: 'blue'}];
const grid = new Grid(crayons);
grid.verticalFacet = (crayon: Crayon) => null!;
grid.horizontalFacet = (crayon: Crayon) => crayon.color;
grid.arrange();
expect(Object.keys(grid.cells).length).to.equal(3);
expect(grid.width).to.equal(5);
expect(grid.height).to.equal(1);
// Confirm sort order (left to right).
expect(grid.verticalKeys).to.deep.equal([null]);
expect(grid.horizontalKeys).to.deep.equal(['blue', 'green', 'red']);
// Confirm cell dimensions and positions.
const blueCell = grid.getCell(null!, 'blue')!;
const redCell = grid.getCell(null!, 'red')!;
const greenCell = grid.getCell(null!, 'green')!;
expect(blueCell.x).to.equal(0);
expect(blueCell.y).to.equal(0);
expect(blueCell.width).to.equal(1);
expect(blueCell.height).to.equal(1);
expect(greenCell.x).to.equal(2);
expect(greenCell.y).to.equal(0);
expect(greenCell.width).to.equal(1);
expect(greenCell.height).to.equal(1);
expect(redCell.x).to.equal(4);
expect(redCell.y).to.equal(0);
expect(redCell.width).to.equal(1);
expect(redCell.height).to.equal(1);
// Confirm item positions.
const [red, green, blue] = crayons;
expect(blue.x).to.equal(0);
expect(blue.y).to.equal(0);
expect(green.x).to.equal(2);
expect(green.y).to.equal(0);
expect(red.x).to.equal(4);
expect(red.y).to.equal(0);
});
it('should arrange items vertically in alphabetical order', () => {
// - +---+
// . | b | 2
// . +---+
// .
// . +---+
// 5 | g | 1
// . +---+
// .
// . +---+
// . | r | 0
// - +---+
// |.1.|
const crayons: Crayon[] =
[{color: 'red'}, {color: 'green'}, {color: 'blue'}];
const grid = new Grid(crayons);
grid.verticalFacet = (crayon: Crayon) => crayon.color;
grid.horizontalFacet = (crayon: Crayon) => null!;
grid.arrange();
expect(Object.keys(grid.cells).length).to.equal(3);
expect(grid.width).to.equal(1);
expect(grid.height).to.equal(5);
// Confirm sort order of vertical keys (top to bottom).
expect(grid.verticalKeys).to.deep.equal(['red', 'green', 'blue']);
expect(grid.horizontalKeys).to.deep.equal([null]);
// Confirm cell contets, dimensions, and positions.
const redCell = grid.getCell('red', null!)!;
const greenCell = grid.getCell('green', null!)!;
const blueCell = grid.getCell('blue', null!)!;
expect(blueCell.x).to.equal(0);
expect(blueCell.y).to.equal(4);
expect(blueCell.width).to.equal(1);
expect(blueCell.height).to.equal(1);
expect(greenCell.x).to.equal(0);
expect(greenCell.y).to.equal(2);
expect(greenCell.width).to.equal(1);
expect(greenCell.height).to.equal(1);
expect(redCell.x).to.equal(0);
expect(redCell.y).to.equal(0);
expect(redCell.width).to.equal(1);
expect(redCell.height).to.equal(1);
// Confirm item positions.
const [red, green, blue] = crayons;
expect(blue.x).to.equal(0);
expect(blue.y).to.equal(4);
expect(green.x).to.equal(0);
expect(green.y).to.equal(2);
expect(red.x).to.equal(0);
expect(red.y).to.equal(0);
});
it('should respect the minimum cell aspect ratio', () => {
// - +------+
// 1 |<><><>|
// - +------+
//
// |. .3 .|
const grid = new Grid([{}, {}, {}]);
grid.minCellAspectRatio = 3;
grid.arrange();
expect(grid.height).to.equal(1);
expect(grid.width).to.equal(3);
});
it('should respect the maximum cell aspect ratio', () => {
// - +--+
// . |<>|
// . |<>|
// 4 |<>|
// . |<>|
// - +--+
//
// |.1|
const grid = new Grid([{}, {}, {}, {}]);
grid.maxCellAspectRatio = 1 / 4;
grid.arrange();
expect(grid.height).to.equal(4);
expect(grid.width).to.equal(1);
});
});
describe('facetItemsIntoCells', () => {
it('should create keys using default string sort', () => {
const items = [9, 10, 11, 'red', 'green', 'blue'];
const grid = new Grid(items);
grid.verticalFacet = (item: number | string) => item;
grid.horizontalFacet = (item: number | string) => item;
grid.facetItemsIntoCells();
expect(grid.verticalKeys).to.deep.equal([
11, 10, 9, 'red', 'green', 'blue'
]);
expect(grid.horizontalKeys).to.deep.equal([
9, 10, 11, 'blue', 'green', 'red'
]);
});
it('should create keys using numeric sort', () => {
const items = [9, 10, 11, 'red', 'green', 'blue'];
const grid = new Grid(items);
grid.verticalFacet = (item: number | string) => item;
grid.horizontalFacet = (item: number | string) => item;
grid.verticalKeyCompare = sorting.numberCompare;
grid.horizontalKeyCompare = sorting.numberCompare;
grid.facetItemsIntoCells();
expect(grid.verticalKeys).to.deep.equal([
'blue', 'green', 'red', 9, 10, 11
]);
expect(grid.horizontalKeys).to.deep.equal([
'blue', 'green', 'red', 9, 10, 11
]);
});
});
describe('computeGridAspectRatio', () => {
it('should return 1 for simple single-cell grid', () => {
// - +--+
// 1 | |
// - +--+
//
// |1.|
const grid = new Grid([10]);
grid.verticalFacet = (item: number) => item;
grid.horizontalFacet = (item: number) => item;
grid.facetItemsIntoCells();
expect(grid.computeGridAspectRatio(1)).to.equal(1);
});
it('should return 3 for a single-cell grid with left/right padding', () => {
// - +------+
// 1 |:: ::|
// - +------+
//
// |. .3 .|
const grid = new Grid([10]);
grid.cellPadding.left = 1;
grid.cellPadding.right = 1;
grid.verticalFacet = (item: number) => item;
grid.horizontalFacet = (item: number) => item;
grid.facetItemsIntoCells();
expect(grid.computeGridAspectRatio(1)).to.equal(3);
});
it('should return 6 for a single-cell with padding and item aspect', () => {
// - +------------+
// 1 |:::: ::::|
// - +------------+
//
// |. . . 6. . .|
const grid = new Grid([10]);
grid.itemAspectRatio = 2;
grid.cellPadding.left = 1;
grid.cellPadding.right = 1;
grid.verticalFacet = (item: number) => item;
grid.horizontalFacet = (item: number) => item;
grid.facetItemsIntoCells();
expect(grid.computeGridAspectRatio(1)).to.equal(6);
});
it('should return 1 for a single-cell grid with uniform padding', () => {
// - +------+
// . |::::::|
// 3 |:: ::|
// . |::::::|
// - +------+
//
// |. .3 .|
const grid = new Grid([10]);
grid.cellPadding.bottom = 1;
grid.cellPadding.left = 1;
grid.cellPadding.right = 1;
grid.cellPadding.top = 1;
grid.verticalFacet = (item: number) => item;
grid.horizontalFacet = (item: number) => item;
grid.facetItemsIntoCells();
expect(grid.computeGridAspectRatio(1)).to.equal(1);
});
it('should return 2 for 1x1 grid of 1 item with aspect ratio 2', () => {
// - +-----+
// 1 | |
// - +-----+
//
// |. 2 .|
const grid = new Grid([10]);
grid.itemAspectRatio = 2;
grid.verticalFacet = (item: number) => item;
grid.horizontalFacet = (item: number) => item;
grid.facetItemsIntoCells();
expect(grid.computeGridAspectRatio(1)).to.equal(2);
});
it('should return 3 for a 1x3 cell grid with no cell margin', () => {
// - +--++--++--+
// 1 | || || |
// - +--++--++--+
//
// |. . 3. . .|
const grid = new Grid([9, 10, 11]);
grid.cellMargin = 0;
grid.verticalFacet = (item: number) => null!;
grid.horizontalFacet = (item: number) => item;
grid.facetItemsIntoCells();
expect(grid.computeGridAspectRatio(1)).to.equal(3);
});
it('should return 1/3 for a 3x1 cell grid with no cell margin', () => {
// - +--+
// . | |
// . +==+
// 3 | |
// . +==+
// . | |
// - +--+
//
// |1.|
const grid = new Grid([9, 10, 11]);
grid.cellMargin = 0;
grid.verticalFacet = (item: number) => item;
grid.horizontalFacet = (item: number) => null!;
grid.facetItemsIntoCells();
expect(grid.computeGridAspectRatio(1)).to.be.closeTo(1 / 3, 1e-9);
});
it('should return 1/5 for a 3x1 cell grid with cell margin 1', () => {
// - +--+
// . | |
// . +--+
// .
// . +--+
// 5 | |
// . +--+
// .
// . +--+
// . | |
// - +--+
//
// |1.|
const grid = new Grid([9, 10, 11]);
grid.cellMargin = 1;
grid.verticalFacet = (item: number) => item;
grid.horizontalFacet = (item: number) => null!;
grid.facetItemsIntoCells();
expect(grid.computeGridAspectRatio(1)).to.be.closeTo(1 / 5, 1e-9);
});
it('should return 1 for a 4x4 cell grid with no cell margin', () => {
// - +--++--++--++--+
// . | || || || |
// . +==++==++==++==+
// . | || || || |
// 4 +==++==++==++==+ 4 / 4 => 1
// . | || || || |
// . +==++==++==++==+
// . | || || || |
// - +--++--++--++--+
//
// |. . . 4. . . .|
const items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
const grid = new Grid(items);
grid.cellMargin = 0;
grid.verticalFacet = (item: number) => item % 4;
grid.horizontalFacet = (item: number) => Math.floor(item / 4);
grid.facetItemsIntoCells();
expect(grid.computeGridAspectRatio(1)).to.equal(1);
});
it('should return 1 for a 4x4 cell grid with cell margin 1', () => {
// - +--+ +--+ +--+ +--+
// . | | | | | | | |
// . +--+ +--+ +--+ +--+
// .
// . +--+ +--+ +--+ +--+
// . | | | | | | | |
// . +--+ +--+ +--+ +--+
// 7 7 / 7 => 1
// . +--+ +--+ +--+ +--+
// . | | | | | | | |
// . +--+ +--+ +--+ +--+
// .
// . +--+ +--+ +--+ +--+
// . | | | | | | | |
// - +--+ +--+ +--+ +--+
//
// |. . . . . . 7. . . . . . .|
const items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
const grid = new Grid(items);
grid.cellMargin = 1;
grid.verticalFacet = (item: number) => item % 4;
grid.horizontalFacet = (item: number) => Math.floor(item / 4);
grid.facetItemsIntoCells();
expect(grid.verticalKeys.length).to.equal(4);
expect(grid.horizontalKeys.length).to.equal(4);
expect(grid.longestCellLength).to.equal(1);
expect(grid.computeGridAspectRatio(1)).to.equal(1);
});
it('should give 3/2 for a Tight 2x2 cell grid', () => {
// - +----++--+
// . | ||<>|
// 2 +----++--+ 3 / 2
// . |<><>||<>|
// - +----++--+
//
// |. . 3. .|
const items = [0, 0, 1, 3];
const grid = new Grid(items);
grid.cellMargin = 0;
grid.verticalFacet = (item: number) => (item / 2) >> 0;
grid.horizontalFacet = (item: number) => item % 2;
grid.facetItemsIntoCells();
grid.verticalGridAlignment = GridAlignment.Tight;
grid.horizontalGridAlignment = GridAlignment.Tight;
expect(grid.computeGridAspectRatio(1)).to.equal(3 / 2);
});
it('should give 2 for a Uniform 2x2 cell grid', () => {
// - +----++----+
// . | ||<> |
// 2 +----++----+ 4 / 2 => 2
// . |<><>||<> |
// - +----++----+
//
// |. . 4 . . |
const items = [0, 0, 1, 3];
const grid = new Grid(items);
grid.cellMargin = 0;
grid.verticalFacet = (item: number) => (item / 2) >> 0;
grid.horizontalFacet = (item: number) => item % 2;
grid.facetItemsIntoCells();
grid.verticalGridAlignment = GridAlignment.Uniform;
grid.horizontalGridAlignment = GridAlignment.Uniform;
expect(grid.computeGridAspectRatio(1)).to.equal(2);
});
it('should return 3/2 for a 2x3 grid of 6 items', () => {
// - +--++--++--+
// . | || || |
// 2 +==++==++==+
// . | || || |
// - +--++--++--+
//
// |. . 3. . .|
const grid = new Grid([1, 2, 3, 4, 5, 6]);
grid.cellMargin = 0;
grid.verticalFacet = (item: number) => item % 2;
grid.horizontalFacet = (item: number) => item % 3;
grid.facetItemsIntoCells();
expect(grid.verticalKeys.length).to.equal(2);
expect(grid.horizontalKeys.length).to.equal(3);
expect(grid.longestCellLength).to.equal(1);
expect(grid.computeGridAspectRatio(1)).to.equal(3 / 2);
});
it('should return 3/4 for a 2x3 grid of 12 items, cell ratio 1/2', () => {
// - +--++--++--+
// . | || || |
// . +--++--++--+
// . | || || |
// 4 +==++==++==+
// . | || || |
// . +--++--++--+
// . | || || |
// - +--++--++--+
//
// |. . 3. . .|
const grid = new Grid([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
grid.cellMargin = 0;
grid.verticalFacet = (item: number) => item % 2;
grid.horizontalFacet = (item: number) => item % 3;
grid.facetItemsIntoCells();
expect(grid.verticalKeys.length).to.equal(2);
expect(grid.horizontalKeys.length).to.equal(3);
expect(grid.longestCellLength).to.equal(2);
expect(grid.computeGridAspectRatio(1 / 2)).to.equal(3 / 4);
});
it('should give 1 for 2x3 grid, 12 items, cell ratio 1/2, margin:1', () => {
// - +--+ +--+ +--+
// . | | | | | |
// . +--+ +--+ +--+
// . | | | | | |
// . +--+ +--+ +--+
// 5 5 / 5 => 1
// . +--+ +--+ +--+
// . | | | | | |
// . +--+ +--+ +--+
// . | | | | | |
// - +--+ +--+ +--+
//
// |. . . . 5. . . . .|
const grid = new Grid([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
grid.cellMargin = 1;
grid.verticalFacet = (item: number) => item % 2;
grid.horizontalFacet = (item: number) => item % 3;
grid.facetItemsIntoCells();
expect(grid.verticalKeys.length).to.equal(2);
expect(grid.horizontalKeys.length).to.equal(3);
expect(grid.longestCellLength).to.equal(2);
expect(grid.computeGridAspectRatio(1 / 2)).to.equal(1);
});
it('should give 8/3 for 2x3 grid, 12 items, cell ratio 2, margin:1', () => {
// - +--+--+ +--+--+ +--+--+
// . | | | | | | | | |
// . +--+--+ +--+--+ +--+--+
// 3
// . +--+--+ +--+--+ +--+--+
// . | | | | | | | | |
// - +--+--+ +--+--+ +--+--+
//
// |. . . . . . .8. . . . . . .|
const grid = new Grid([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
grid.cellMargin = 1;
grid.verticalFacet = (item: number) => item % 2;
grid.horizontalFacet = (item: number) => item % 3;
grid.facetItemsIntoCells();
expect(grid.verticalKeys.length).to.equal(2);
expect(grid.horizontalKeys.length).to.equal(3);
expect(grid.longestCellLength).to.equal(2);
expect(grid.computeGridAspectRatio(2)).to.be.closeTo(8 / 3, 1e-9);
});
it('should give 10/4 for 2x3 grid, 6 items, item ratio 2, margin:1', () => {
// - +-----+ +-----+ +-----+
// . | | | | | |
// . +-----+ +-----+ +-----+
// .
// 4
// .
// . +-----+ +-----+ +-----+
// . | | | | | |
// - +-----+ +-----+ +-----+
//
// |. . . . . . . . 10. . . . . . . .|
const grid = new Grid([1, 2, 3, 4, 5, 6]);
grid.itemAspectRatio = 2;
grid.cellMargin = 1;
grid.verticalFacet = (item: number) => item % 2;
grid.horizontalFacet = (item: number) => item % 3;
grid.facetItemsIntoCells();
expect(grid.verticalKeys.length).to.equal(2);
expect(grid.horizontalKeys.length).to.equal(3);
expect(grid.longestCellLength).to.equal(1);
expect(grid.computeGridAspectRatio(1)).to.be.closeTo(10 / 4, 1e-9);
});
it('should give 10/6: 2x3 grid, 12 items, item ratio 2, margin 1', () => {
// - +-----+ +-----+ +-----+
// . | | | | | |
// . +-----+ +-----+ +-----+
// . | | | | | |
// . +-----+ +-----+ +-----+
// .
// 6
// .
// . +-----+ +-----+ +-----+
// . | | | | | |
// . +-----+ +-----+ +-----+
// . | | | | | |
// - +-----+ +-----+ +-----+
//
// |. . . . . . . . 10. . . . . . . .|
const grid = new Grid([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
grid.itemAspectRatio = 2;
grid.cellMargin = 1;
grid.verticalFacet = (item: number) => item % 2;
grid.horizontalFacet = (item: number) => item % 3;
grid.facetItemsIntoCells();
expect(grid.verticalKeys.length).to.equal(2);
expect(grid.horizontalKeys.length).to.equal(3);
expect(grid.longestCellLength).to.equal(2);
expect(grid.computeGridAspectRatio(1)).to.be.closeTo(10 / 6, 1e-9);
});
});
describe('computeOptimalCellAspectRatio', () => {
it('should give 1 for a 1x1 grid of 1 item for target of 1', () => {
// - +---+
// 1 | |
// - +---+
// |.1.|
const grid = new Grid([10]);
grid.facetItemsIntoCells();
expect(grid.computeOptimalCellAspectRatio(1)).to.equal(1);
});
it('should give 2 for a 1x1 grid of 7 items for target of 2', () => {
// - +---+---+---+
// . | | | | - +-------+
// 2 +---+---+---+---+ => 1 | | => 2/1
// . | | | | | - +-------+
// - +---+---+---+---+ |. .2. .|
// |. . . .4. . . .|
const grid = new Grid([1, 2, 3, 4, 5, 6, 7]);
grid.facetItemsIntoCells();
expect(grid.computeOptimalCellAspectRatio(2)).to.equal(2);
});
it('should give 1/2: 2x3 grid, 200 items/cell, target of 3/4', () => {
// - +---++---++---+
// . |20 ||20 ||20 |
// . | x || x || x | - +---+
// . | 10|| 10|| 10| . | |
// 4 +===++===++===+ => 2 | | => 1/2
// . |20 ||20 ||20 | . | |
// . | x || x || x | - +---+
// . | 10|| 10|| 10| |.1.|
// - +---++---++---+
// |. . . 3 . . .|
const numRows = 2;
const numColumns = 3;
const itemsPerCell = 200;
const totalItems = numRows * numColumns * itemsPerCell;
const items: number[] = [];
for (let i = 0; i < totalItems; i++) {
items.push(i);
}
const grid = new Grid(items);
grid.cellMargin = 0;
grid.verticalFacet = (item: number) => item % numRows;
grid.horizontalFacet = (item: number) => item % numColumns;
grid.facetItemsIntoCells();
expect(grid.verticalKeys.length).to.equal(numRows);
expect(grid.horizontalKeys.length).to.equal(numColumns);
expect(grid.longestCellLength).to.equal(itemsPerCell);
expect(grid.computeOptimalCellAspectRatio(3 / 4))
.to.be.closeTo(1 / 2, 0.001);
});
});
}); | the_stack |
import { XStore, XType, XString } from '../pastore';
import { delay } from './helpers';
interface SimpleState extends XType {
name: string,
age: number,
isMale: boolean,
teacher: {
name: string,
age: number,
isMale: boolean
},
deepNested: {
level2: {
value: string,
level3: {
value: string
}
}
},
array_plain: Array<string>,
array_object: Array<{
name: string,
age: number,
isMale: boolean
}>,
array_object_empty: Array<{
name: string,
age: number,
isMale: boolean
}>,
array_array: Array<Array<string>>
}
class SimpleStore extends XStore<SimpleState>{ }
let initState: SimpleState = {
name: 'Peter',
age: 10,
isMale: true,
teacher: {
name: 'Peter',
age: 10,
isMale: true,
},
deepNested: {
level2: {
value: 'l2',
level3: {
value: 'l3'
}
}
},
array_plain: ['a0', 'a1'],
array_object: [{
name: 'n0',
age: 10,
isMale: true
},
{
name: 'n1',
age: 20,
isMale: false
}],
array_object_empty: [],
array_array: [
['a00', 'a01'],
['a10', 'a11']
]
}
let store = new SimpleStore(initState);
describe('responsive state test suit', function () {
describe('state init', function () {
describe('root prop', function () {
describe('get', function () {
it('string', function () {
expect(store.state.name).toEqual(store.imState.name)
})
it('number', function () {
expect(store.imState.age).toEqual(store.state.age)
})
it('boolean', function () {
expect(store.imState.isMale).toEqual(store.state.isMale)
})
})
describe('set', function () {
it('string', async function () {
store.state.name = 'Tom'
await delay(0)
expect(store.imState.name).toEqual('Tom')
expect(store.state.name).toEqual(store.imState.name)
})
it('number', async function () {
store.state.age = 20
await delay(0)
expect(store.imState.age).toEqual(20)
expect(store.state.age).toEqual(20)
})
it('boolean', async function () {
store.state.isMale = false
await delay(0)
expect(store.imState.isMale).toEqual(false)
expect(store.state.isMale).toEqual(false)
})
it('async', async function () {
store.state.isMale = true
expect(store.imState.isMale).toEqual(false)
expect(store.state.isMale).toEqual(false)
await delay(0)
expect(store.imState.isMale).toEqual(true)
expect(store.state.isMale).toEqual(true)
})
})
})
describe('nested prop', function () {
describe('object value', function () {
describe('get', function () {
it('string', function () {
expect(store.state.teacher.name).toEqual(store.imState.teacher.name)
})
it('number', function () {
expect(store.imState.teacher.age).toEqual(store.state.teacher.age)
})
it('boolean', function () {
expect(store.imState.teacher.isMale).toEqual(store.state.teacher.isMale)
})
})
describe('set', function () {
it('string', async function () {
store.state.teacher.name = 'Tom'
await delay(0)
expect(store.imState.teacher.name).toEqual('Tom')
expect(store.state.teacher.name).toEqual(store.imState.teacher.name)
})
it('number', async function () {
store.state.teacher.age = 20
await delay(0)
expect(store.imState.teacher.age).toEqual(20)
expect(store.state.teacher.age).toEqual(20)
})
it('boolean', async function () {
store.state.teacher.isMale = false
await delay(0)
expect(store.imState.teacher.isMale).toEqual(false)
expect(store.state.teacher.isMale).toEqual(false)
})
it('set total new object', async function () {
let newTeacher = {
name: 'new',
age: 30,
isMale: true
}
store.state.teacher = newTeacher
await delay(0)
expect(store.imState.teacher).toEqual(newTeacher)
expect(store.state.teacher).toEqual(newTeacher)
})
})
describe('deep nested', function () {
it('level2', async function () {
expect(store.state.deepNested.level2.value).toEqual(store.imState.deepNested.level2.value)
store.state.deepNested.level2.value += '!'
await delay(0)
expect(store.imState.deepNested.level2.value).toEqual('l2!')
expect(store.state.deepNested.level2.value).toEqual('l2!')
})
it('level3', async function () {
expect(store.state.deepNested.level2.level3.value).toEqual(store.imState.deepNested.level2.level3.value)
store.state.deepNested.level2.level3.value += '!'
await delay(0)
expect(store.imState.deepNested.level2.level3.value).toEqual('l3!')
expect(store.state.deepNested.level2.level3.value).toEqual('l3!')
})
})
})
describe('array value', function () {
it('plain elements', async function () {
expect(store.state.array_plain).toEqual(store.imState.array_plain)
store.state.array_plain[0] = 'new0'
store.state.array_plain[1] = 'new1'
await delay(0)
expect(store.imState.array_plain).toEqual(['new0', 'new1'])
expect(store.state.array_plain).toEqual(['new0', 'new1'])
})
it('object elements', async function () {
expect(store.state.array_object).toEqual(store.imState.array_object)
let newObject0 = {
name: 'new1',
age: 40,
isMale: true
}
let newObject1 = {
name: 'new2',
age: 50,
isMale: false
}
store.state.array_object[0].name = newObject0.name;
store.state.array_object[0].age = newObject0.age;
store.state.array_object[0].isMale = newObject0.isMale;
store.state.array_object[1] = newObject1;
await delay(0)
expect(store.imState.array_object).toEqual([newObject0, newObject1])
expect(store.state.array_object).toEqual([newObject0, newObject1])
})
it('array elements (multi-dimensions array)', async function () {
expect(store.state.array_array).toEqual(store.imState.array_array)
store.state.array_array[0][0] = 'new00';
store.state.array_array[0][1] = 'new01';
store.state.array_array[1] = ['new10', 'new11'];
await delay(0)
expect(store.imState.array_array).toEqual([['new00', 'new01'], ['new10', 'new11']])
expect(store.state.array_array).toEqual([['new00', 'new01'], ['new10', 'new11']])
})
})
})
})
describe('state change', function () {
describe('array mutate method', function () {
describe('push', function () {
it('first push', async function () {
// 插入新元素
expect(store.imState.array_object.length).toEqual(2)
let newElement = {
name: 'n2',
age: 40,
isMale: false
}
store.state.array_object.push(newElement)
await delay(0)
expect(store.imState.array_object.length).toEqual(3)
expect(store.state.array_object.length).toEqual(3)
expect(store.imState.array_object[2]).toEqual(newElement)
expect(store.state.array_object[2]).toEqual(newElement)
// 新元素的操作
store.state.array_object[2].name = 'n2!'
await delay(0)
expect(store.imState.array_object[2].name).toEqual('n2!')
})
it('next push in different async batch', async function () {
let newElement = {
name: 'n3',
age: 50,
isMale: true
}
store.state.array_object.push(newElement)
await delay(0)
store.state.array_object[3].age = 100
await delay(0)
expect(store.imState.array_object.length).toEqual(4)
expect(store.state.array_object.length).toEqual(4)
expect(store.imState.array_object[3].age).toEqual(100)
expect(store.state.array_object[3].age).toEqual(100)
})
it('next push in the same async batch', async function () {
let newElement0 = {
name: 'new-0',
age: 50,
isMale: true
}
let newElement1 = {
name: 'new-1',
age: 50,
isMale: true
}
// 如果 push 是按引用传递,这里有个问题要注意,如果两个都是压入相同的引用element, 会导致无法压入第二个
// 遇到问题要考虑这一点:按值传递和按引用传递的控制,本框架的修改会统一用按值传递的模式实现(如果发现按引用传递则需要修改)
store.state.array_object.push(newElement0)
expect(store.state.array_object.length).toEqual(5)
store.state.array_object.push(newElement1)
expect(store.state.array_object.length).toEqual(6)
await delay(0)
expect(store.imState.array_object.length).toEqual(6)
expect(store.imState.array_object[4]).toEqual(newElement0)
expect(store.state.array_object[4]).toEqual(newElement0)
expect(store.imState.array_object[5]).toEqual(newElement1)
expect(store.state.array_object[5]).toEqual(newElement1)
})
it('push into an init empty array', async function(){
let newElement = {
name: 'newElement',
age: 10,
isMale: true
}
expect(store.state.array_object_empty.length).toEqual(0)
store.state.array_object_empty.push(newElement);
await delay(0)
expect(store.state.array_object_empty).toEqual([newElement])
expect(store.state.array_object_empty.length).toEqual(1)
store.state.array_object_empty = []
await delay(0)
})
})
describe('pop', function () {
// 注意,此时通过 store.state.array_object[3] 获取的对象,已经不可以访问了,因为数据里没有第3个元素了
it('first pop', async function () {
let lastValue_pop = store.state.array_object.pop()
await delay(0)
expect(lastValue_pop).toEqual({
name: 'new-1',
age: 50,
isMale: true
})
expect(store.imState.array_object[5]).toEqual(undefined)
expect(store.imState.array_object.length).toEqual(5)
expect(store.state.array_object.length).toEqual(5)
})
// 异步间连续操作
it('next pop in different async batch', async function () {
let lastValue_pop = store.state.array_object.pop()
expect(store.state.array_object.length).toEqual(4)
await delay(0)
expect(store.imState.array_object.length).toEqual(4)
expect(lastValue_pop).toEqual({
name: 'new-0',
age: 50,
isMale: true
})
expect(store.imState.array_object[4]).toEqual(undefined)
})
// 异步内连续操作
it('next pop in the same async batch', async function () {
let value_3 = store.imState.array_object[3]
let value_2 = store.imState.array_object[2]
let lastValue_pop0 = store.state.array_object.pop()
let lastValue_pop1 = store.state.array_object.pop()
await delay(0)
expect(store.imState.array_object.length).toBe(2)
expect(lastValue_pop0).toEqual(value_3)
expect(lastValue_pop1).toEqual(value_2)
})
})
describe('unshift', function () {
it('first unshift', async function () {
expect(store.imState.array_object.length).toBe(2)
let newValue = {
name: 'unshift-0',
age: 50,
isMale: true
}
let oldValue_0 = store.imState.array_object[0]
let oldValue_1 = store.imState.array_object[1]
store.state.array_object.unshift(newValue)
expect(store.state.array_object.length).toBe(3)
expect(store.imState.array_object.length).toBe(3)
expect(store.state.array_object[0]).toEqual(newValue)
expect(store.state.array_object[1]).toEqual(oldValue_0)
expect(store.state.array_object[2]).toEqual(oldValue_1)
})
it('next unshift in different async batch', async function () {
let newValue_0 = {
name: 'unshift-1',
age: 50,
isMale: true
}
let newValue_1 = {
name: 'unshift-2',
age: 50,
isMale: true
}
let oldArray = store.imState.array_object;
store.state.array_object.unshift(newValue_0)
await delay(0)
store.state.array_object.unshift(newValue_1)
await delay(0)
expect(store.state.array_object.length).toEqual(5)
expect(store.state.array_object).toEqual([newValue_1, newValue_0, ...oldArray])
})
it('next unshift in the same async batch', async function () {
let newValue_0 = {
name: 'unshift-3',
age: 50,
isMale: true
}
let newValue_1 = {
name: 'unshift-4',
age: 50,
isMale: true
}
let oldArray = store.imState.array_object
store.state.array_object.unshift(newValue_0)
store.state.array_object.unshift(newValue_1)
await delay(0)
expect(store.state.array_object.length).toEqual(7)
expect(store.state.array_object).toEqual([newValue_1, newValue_0, ...oldArray])
})
it('unshift into an init empty array', async function(){
let newElement = {
name: 'newElement',
age: 10,
isMale: true
}
expect(store.state.array_object_empty.length).toEqual(0)
store.state.array_object_empty.push(newElement);
await delay(0)
expect(store.state.array_object_empty).toEqual([newElement])
expect(store.state.array_object_empty.length).toEqual(1)
store.state.array_object_empty = []
await delay(0)
})
})
describe('shift', async function () {
it('first shift', async function () {
let oldArray = store.imState.array_object
let shiftedObject = store.state.array_object.shift()
expect(store.imState.array_object.length).toBe(6)
expect(store.state.array_object.length).toBe(6)
expect(store.state.array_object).toEqual(oldArray.slice(1))
expect(shiftedObject).toEqual(oldArray[0])
})
it('next shift in different async batch', async function () {
let oldArray = store.imState.array_object
let shiftedObject_0 = store.state.array_object.shift()
await delay(0)
let shiftedObject_1 = store.state.array_object.shift()
await delay(0)
expect(store.state.array_object).toEqual(oldArray.slice(2))
expect(shiftedObject_0).toEqual(oldArray[0])
expect(shiftedObject_1).toEqual(oldArray[1])
})
it('next shift in the same async batch', async function () {
let oldArray = store.imState.array_object
let shiftedObject_0 = store.state.array_object.shift()
let shiftedObject_1 = store.state.array_object.shift()
await delay(0)
expect(store.state.array_object).toEqual(oldArray.slice(2))
expect(shiftedObject_0).toEqual(oldArray[0])
expect(shiftedObject_1).toEqual(oldArray[1])
// 注意, 连续 pop + push 混用会导致 pop 出来的元素可能出错(目前这两者存在依赖)
// 但是 目标数组的处理结果时正确的
})
})
describe('splice', function () {
it('can splice', async function () {
// delete and add
let newValue_0 = {
name: 'splice-0',
age: 50,
isMale: true
}
let newValue_1 = {
name: 'splice-1',
age: 50,
isMale: true
}
let newValue_2 = {
name: 'splice-2',
age: 50,
isMale: true
}
let newValue_3 = {
name: 'splice-3',
age: 50,
isMale: true
}
let oldArray = store.imState.array_object;
store.state.array_object.push(newValue_0)
store.state.array_object.push(newValue_1)
store.state.array_object.push(newValue_2)
await delay(0)
let poppedElements = store.state.array_object.splice(2, 2, newValue_3)
await delay(0)
expect(store.state.array_object.length).toEqual(4)
expect(store.imState.array_object.length).toEqual(4)
expect(poppedElements).toEqual([newValue_0, newValue_1])
expect(store.state.array_object[2]).toEqual(newValue_3)
expect(store.state.array_object[3]).toEqual(newValue_2)
expect(store.imState.array_object[2]).toEqual(newValue_3)
expect(store.imState.array_object[3]).toEqual(newValue_2)
expect((store.imState.array_object[3].age as XType).__xpath__).toEqual('.array_object.3.age')
// delete one
poppedElements = store.state.array_object.splice(2, 1)
await delay(0)
expect(store.state.array_object.length).toEqual(3)
expect(store.imState.array_object.length).toEqual(3)
expect(poppedElements).toEqual([newValue_3])
expect(store.state.array_object[2]).toEqual(newValue_2)
expect(store.imState.array_object[2]).toEqual(newValue_2)
expect((store.imState.array_object[2].age as XType).__xpath__).toEqual('.array_object.2.age')
// add one
store.state.array_object.splice(2, 0, newValue_3)
await delay(0)
expect(store.state.array_object.length).toEqual(4)
// expect(store.imState.array_object.length).toEqual(4)
// expect(store.state.array_object[2]).toEqual(newValue_3)
// expect(store.state.array_object[3]).toEqual(newValue_2)
// expect(store.imState.array_object[2]).toEqual(newValue_3)
// expect(store.imState.array_object[3]).toEqual(newValue_2)
// expect((store.imState.array_object[3].age as XType).__xpath__).toEqual('.array_object.3.age')
})
})
describe('sort', function () {
it('can sort', async function () {
store.state.array_object[1].age = 2;
store.state.array_object[2].age = 1;
store.state.array_object[0].age = 3;
store.state.array_object[3].age = 0;
await delay(0)
store.state.array_object.sort((a, b) => a.age - b.age)
await delay(0)
expect(store.state.array_object.map(v => v.age)).toEqual([0, 1, 2, 3])
})
})
describe('reverse', async function () {
it('can reverse', async function () {
store.state.array_object.reverse()
await delay(0)
expect(store.state.array_object.map(v => v.age)).toEqual([3, 2, 1, 0])
})
})
})
})
describe('null situation', function () {
// NOTE: 虽然支持设为null值,但是一般不建议用null值
describe('plain node', function () {
it('string', async function(){
// to be null
(store.state.teacher.name as any) = null;
await delay(0);
expect(store.imState.teacher.name).toEqual(null);
expect(store.state.teacher.name).toEqual(null);
// to be not null
store.state.teacher.name = 'new teacher';
await delay(0);
expect(store.imState.teacher.name).toEqual('new teacher');
expect(store.state.teacher.name).toEqual('new teacher');
})
it('number', async function(){
// to be null
(store.state.teacher.age as any) = null;
await delay(0);
expect(store.imState.teacher.age).toEqual(null);
expect(store.state.teacher.age).toEqual(null);
// to be not null
store.state.teacher.age = 100;
await delay(0);
expect(store.imState.teacher.age).toEqual(100);
expect(store.state.teacher.age).toEqual(100);
})
it('boolean', async function(){
// to be null
(store.state.teacher.isMale as any) = null;
await delay(0);
expect(store.imState.teacher.isMale).toEqual(null);
expect(store.state.teacher.isMale).toEqual(null);
// to be not null
store.state.teacher.isMale = true;
await delay(0);
expect(store.imState.teacher.isMale).toEqual(true);
expect(store.state.teacher.isMale).toEqual(true);
})
})
describe('object node', function () {
it('make an object to be null', async function () {
(store.state.teacher as any) = null;
await delay(0);
expect(store.imState.teacher).toEqual(null);
expect(store.state.teacher).toEqual(null);
})
it('make null to be an object', async function () {
// 注意,新对象的结构要一致(正常业务逻辑下是一致的)
let newValue = {
name: 'Boy',
age: 20,
isMale: true
}
store.state.teacher = newValue
await delay(0);
expect(store.imState.teacher).toEqual(newValue);
expect(store.state.teacher).toEqual(newValue);
store.state.teacher.name = 'Good'
await delay(0);
expect(store.imState.teacher.name).toEqual('Good');
})
})
describe('array node', function () {
it('make an array to be empty array', async function () {
store.state.array_object = [];
await delay(0);
expect(store.imState.array_object).toEqual([]);
expect(store.state.array_object).toEqual([]);
})
it('make middle empty array to return same stucture array', async function () {
// 注意,目前用方法二实现,新数组的结构不一定要要一致(正常业务逻辑下是一致的)
// 如果用方法一实现则需要,方法一性能会高一些
let newElement = {
name: 'not empty array',
age: 20,
isMale: true
}
let newArray = [newElement, newElement, newElement]
store.state.array_object = newArray
await delay(0);
expect(store.imState.array_object).toEqual(newArray);
expect(store.state.array_object).toEqual(newArray);
store.state.array_object[2].name = 'new value'
await delay(0);
expect(store.imState.array_object[2].name).toEqual('new value');
expect(store.state.array_object[2].name).toEqual('new value');
})
it('make initial empty array to be not empty array', async function () {
let newElement = {
name: 'not empty array',
age: 20,
isMale: true
}
let newArray = [newElement, newElement, newElement]
store.state.array_object_empty = newArray
await delay(0);
expect(store.imState.array_object_empty).toEqual(newArray);
expect(store.state.array_object_empty).toEqual(newArray);
store.state.array_object_empty[2].name = 'new value'
await delay(0);
expect(store.imState.array_object_empty[2].name).toEqual('new value');
expect(store.state.array_object_empty[2].name).toEqual('new value');
})
it('make array to be another array', async function () {
// 注意,目前用方法二实现,新数组的结构不一定要要一致(正常业务逻辑下是一致的)
// 如果用方法一实现则需要,方法一性能会高一些
let newElement = {
name: 'another array',
age: 21,
isMale: false
}
let newArray = [newElement, newElement]
store.state.array_object = newArray
await delay(0);
expect(store.imState.array_object).toEqual(newArray);
expect(store.state.array_object).toEqual(newArray);
store.state.array_object[1].name = 'new value'
await delay(0);
expect(store.imState.array_object[1].name).toEqual('new value');
expect(store.state.array_object[1].name).toEqual('new value');
})
it('array and null switching', async function () {
// 支持设 array 为 null 但是不推荐,请使用 [] 代替
// to be null
(store.state.array_object as any) = null
await delay(0);
expect(store.imState.array_object).toEqual(null);
expect(store.state.array_object).toEqual(null);
// to be array
let newElement = {
name: 'another array',
age: 21,
isMale: false
}
let newArray = [newElement, newElement]
store.state.array_object = newArray
await delay(0);
expect(store.imState.array_object).toEqual(newArray);
expect(store.state.array_object).toEqual(newArray);
store.state.array_object[1].name = 'new value'
await delay(0);
expect(store.imState.array_object[1].name).toEqual('new value');
expect(store.state.array_object[1].name).toEqual('new value');
})
})
})
describe('get rstate', function(){
it('root', function(){
expect(store.getResponsiveState(store.imState)).toBe(store.state)
})
it('nest', function(){
expect(store.getResponsiveState(store.imState.age as XType)).toBe(store.state.age)
expect(store.getResponsiveState(store.imState.teacher as XType)).toBe(store.state.teacher)
expect(store.getResponsiveState(store.imState.teacher.name as XType)).toBe(store.state.teacher.name)
})
})
}) | the_stack |
// Create the local library object, to be exported or referenced globally later
const lib: any = {};
// Current version
lib.version = '0.4.2';
/* --- Exposed settings --- */
// The library's settings configuration object. Contains default parameters for
// currency and number formatting
lib.settings = {
currency: {
symbol: '$', // default currency symbol is '$'
format: '%s%v', // controls output: %s = symbol, %v = value (can be object, see docs)
decimal: '.', // decimal point separator
thousand: ',', // thousands separator
precision: 2, // decimal places
grouping: 3, // digit grouping (not implemented yet)
},
number: {
precision: 0, // default precision on numbers is 0
grouping: 3, // digit grouping (not implemented yet)
thousand: ',',
decimal: '.',
},
};
/* --- Internal Helper Methods --- */
// Store reference to possibly-available ECMAScript 5 methods for later
const nativeMap = Array.prototype.map;
const nativeIsArray = Array.isArray;
const _toString = Object.prototype.toString;
/**
* Tests whether supplied parameter is a string
* from underscore.js
*/
function isString (obj: any) {
return !!(obj === '' || (obj && obj.charCodeAt && obj.substr));
}
/**
* Tests whether supplied parameter is an array
* from underscore.js, delegates to ECMA5's native Array.isArray
*/
function isArray (obj: any) {
return nativeIsArray
? nativeIsArray(obj)
: _toString.call(obj) === '[object Array]';
}
/**
* Tests whether supplied parameter is a true object
*/
function isObject (obj: any) {
return obj && _toString.call(obj) === '[object Object]';
}
/**
* Extends an object with a defaults object, similar to underscore's _.defaults
*
* Used for abstracting parameter handling from API methods
*/
function defaults (object: any, defs: any) {
let key;
object = object || {};
defs = defs || {};
// Iterate over object non-prototype properties:
for (key in defs) {
if (defs.hasOwnProperty(key)) {
// Replace values with defaults only if undefined (allow empty/zero values):
if (object[key] == null) {
object[key] = defs[key];
}
}
}
return object;
}
/**
* Implementation of `Array.map()` for iteration loops
*
* Returns a new Array as a result of calling `iterator` on each array value.
* Defers to native Array.map if available
*/
function map (obj: any, iterator: (...args: any[]) => any, context?: any) {
const results: any[] = [];
let i;
let j;
if (!obj) {
return results;
}
// Use native .map method if it exists:
if (nativeMap && obj.map === nativeMap) {
return obj.map(iterator, context);
}
// Fallback for native .map:
for (i = 0, j = obj.length; i < j; i++) {
results[i] = iterator.call(context, obj[i], i, obj);
}
return results;
}
/**
* Check and normalise the value of precision (must be positive integer)
*/
function checkPrecision (val: number, base?: number) {
val = Math.round(Math.abs(val));
return isNaN(val) ? base : val;
}
/**
* Parses a format string or object and returns format obj for use in rendering
*
* `format` is either a string with the default (positive) format, or object
* containing `pos` (required), `neg` and `zero` values (or a function returning
* either a string or object)
*
* Either string or format.pos must contain "%v" (value) to be valid
*/
function checkCurrencyFormat (format: (() => any) | any) {
const _defaults = lib.settings.currency.format;
// Allow function as format parameter (should return string or object):
if (typeof format === 'function') {
format = format();
}
// Format can be a string, in which case `value` ("%v") must be present:
if (isString(format) && format.match('%v')) {
// Create and return positive, negative and zero formats:
return {
pos: format,
neg: format.replace('-', '').replace('%v', '-%v'),
zero: format,
};
// If no format, or object is missing valid positive value, use defaults:
} else if (!format || !format.pos || !format.pos.match('%v')) {
// If defaults is a string, casts it to an object for faster checking next time:
return !isString(_defaults)
? _defaults
: (lib.settings.currency.format = {
pos: _defaults,
neg: _defaults.replace('%v', '-%v'),
zero: _defaults,
});
}
// Otherwise, assume format was fine:
return format;
}
/* --- API Methods --- */
/**
* Takes a string/array of strings, removes all formatting/cruft and returns the raw float value
* Alias: `accounting.parse(string)`
*
* Decimal must be included in the regular expression to match floats (defaults to
* accounting.settings.number.decimal), so if the number uses a non-standard decimal
* separator, provide it as the second argument.
*
* Also matches bracketed negatives (eg. "$ (1.99)" => -1.99)
*
* Doesn't throw any errors (`NaN`s become 0) but this may change in future
*/
const unformat = function (value: any, decimal?: any): any {
// Recursively unformat arrays:
if (isArray(value)) {
return map(value, function (val) {
return unformat(val, decimal);
});
}
// Fails silently (need decent errors):
value = value || 0;
// Return the value as-is if it's already a number:
if (typeof value === 'number') {
return value;
}
// Default decimal point comes from settings, but could be set to eg. "," in opts:
decimal = decimal || lib.settings.number.decimal;
// Build regex to strip out everything except digits, decimal point and minus sign:
const regex = new RegExp('[^0-9-' + decimal + ']', 'g');
const unformatted = parseFloat(
('' + value)
.replace(/\((?=\d+)(.*)\)/, '-$1') // replace bracketed values with negatives
.replace(regex, '') // strip out any cruft
.replace(decimal, '.') // make sure decimal point is standard
);
// This will fail silently which may cause trouble, let's wait and see:
return !isNaN(unformatted) ? unformatted : 0;
};
lib.unformat = lib.parse = unformat;
/**
* Implementation of toFixed() that treats floats more like decimals
*
* Fixes binary rounding issues (eg. (0.615).toFixed(2) === "0.61") that present
* problems for accounting- and finance-related software.
*/
const toFixed = function (value: any, precision: any) {
precision = checkPrecision(precision, lib.settings.number.precision);
const exponentialForm = Number(lib.unformat(value) + 'e' + precision);
const rounded = Math.round(exponentialForm);
const finalResult = Number(rounded + 'e-' + precision).toFixed(precision);
return finalResult;
};
lib.toFixed = toFixed;
/**
* Format a number, with comma-separated thousands and custom precision/decimal places
* Alias: `accounting.format()`
*
* Localise by overriding the precision and thousand / decimal separators
* 2nd parameter `precision` can be an object matching `settings.number`
*/
const formatNumber = function (
number: any,
precision: any,
thousand: any,
decimal: any
): any {
// Resursively format arrays:
if (isArray(number)) {
return map(number, function (val) {
return formatNumber(val, precision, thousand, decimal);
});
}
// Clean up number:
number = unformat(number);
// Build options object from second param (if object) or all params, extending defaults:
const opts = defaults(
isObject(precision)
? precision
: {
precision,
thousand,
decimal,
},
lib.settings.number
);
// Clean up precision
const usePrecision = checkPrecision(opts.precision);
// Do some calc:
const negative = number < 0 ? '-' : '';
const base = parseInt(toFixed(Math.abs(number || 0), usePrecision), 10) + '';
const mod = base.length > 3 ? base.length % 3 : 0;
// Format the number:
return (
negative +
(mod ? base.substr(0, mod) + opts.thousand : '') +
base.substr(mod).replace(/(\d{3})(?=\d)/g, '$1' + opts.thousand) +
(usePrecision
? opts.decimal + toFixed(Math.abs(number), usePrecision).split('.')[1]
: '')
);
};
lib.formatNumber = lib.format = formatNumber;
/**
* Format a number into currency
*
* Usage: accounting.formatMoney(number, symbol, precision, thousandsSep, decimalSep, format)
* defaults: (0, "$", 2, ",", ".", "%s%v")
*
* Localise by overriding the symbol, precision, thousand / decimal separators and format
* Second param can be an object matching `settings.currency` which is the easiest way.
*
* To do: tidy up the parameters
*/
const formatMoney = function (
number: any,
symbol: any,
precision: any,
thousand: any,
decimal: any,
format: any
): any {
// Resursively format arrays:
if (isArray(number)) {
return map(number, function (val) {
return formatMoney(val, symbol, precision, thousand, decimal, format);
});
}
// Clean up number:
number = unformat(number);
// Build options object from second param (if object) or all params, extending defaults:
const opts = defaults(
isObject(symbol)
? symbol
: {
symbol,
precision,
thousand,
decimal,
format,
},
lib.settings.currency
);
// Check format (returns object with pos, neg and zero):
const formats = checkCurrencyFormat(opts.format);
// Choose which format to use for this value:
const useFormat =
number > 0 ? formats.pos : number < 0 ? formats.neg : formats.zero;
// Return with currency symbol added:
return useFormat
.replace('%s', opts.symbol)
.replace(
'%v',
formatNumber(
Math.abs(number),
checkPrecision(opts.precision),
opts.thousand,
opts.decimal
)
);
};
lib.formatMoney = formatMoney;
/**
* Format a list of numbers into an accounting column, padding with whitespace
* to line up currency symbols, thousand separators and decimals places
*
* List should be an array of numbers
* Second parameter can be an object containing keys that match the params
*
* Returns array of accouting-formatted number strings of same length
*
* NB: `white-space:pre` CSS rule is required on the list container to prevent
* browsers from collapsing the whitespace in the output strings.
*/
lib.formatColumn = function (
list: any,
symbol: any,
precision: any,
thousand: any,
decimal: any,
format: any
) {
if (!list || !isArray(list)) {
return [];
}
// Build options object from second param (if object) or all params, extending defaults:
const opts = defaults(
isObject(symbol)
? symbol
: {
symbol,
precision,
thousand,
decimal,
format,
},
lib.settings.currency
);
// Check format (returns object with pos, neg and zero), only need pos for now:
const formats = checkCurrencyFormat(opts.format);
// Whether to pad at start of string or after currency symbol:
const padAfterSymbol =
formats.pos.indexOf('%s') < formats.pos.indexOf('%v') ? true : false;
// Store value for the length of the longest string in the column:
let maxLength = 0;
// Format the list according to options, store the length of the longest string:
const formatted = map(list, function (val, i) {
if (isArray(val)) {
// Recursively format columns if list is a multi-dimensional array:
return lib.formatColumn(val, opts);
} else {
// Clean up the value
val = unformat(val);
// Choose which format to use for this value (pos, neg or zero):
const useFormat =
val > 0 ? formats.pos : val < 0 ? formats.neg : formats.zero;
// Format this value, push into formatted list and save the length:
const fVal = useFormat
.replace('%s', opts.symbol)
.replace(
'%v',
formatNumber(
Math.abs(val),
checkPrecision(opts.precision),
opts.thousand,
opts.decimal
)
);
if (fVal.length > maxLength) {
maxLength = fVal.length;
}
return fVal;
}
});
// Pad each number in the list and send back the column of numbers:
return map(formatted, function (val, i) {
// Only if this is a string (not a nested array, which would have already been padded):
if (isString(val) && val.length < maxLength) {
// Depending on symbol position, pad after symbol or at index 0:
return padAfterSymbol
? val.replace(
opts.symbol,
opts.symbol + new Array(maxLength - val.length + 1).join(' ')
)
: new Array(maxLength - val.length + 1).join(' ') + val;
}
return val;
});
};
// export default lib;
export default lib; | the_stack |
import {getPointsTooltipData} from './tooltip'
import {convertLineSpec} from './staticLegend'
import {NINETEEN_EIGHTY_FOUR} from '../../constants/colorSchemes'
import {
FILL,
STACKED_LINE_CUMULATIVE,
LINE_COUNT,
} from '../../constants/columnKeys'
import {getNominalColorScale, createGroupIDColumn} from '../../transforms'
import {lineTransform} from '../../transforms/line'
import {
createSampleTable,
COLUMN_KEY,
POINT_KEY,
HOST_KEY,
} from '../fixtures/randomTable'
import {LayerTypes, LineLayerSpec, ScatterLayerSpec} from '../../types'
describe('getPointsTooltipData', () => {
let sampleTable
const xColKey = '_time'
const yColKey = '_value'
const columnFormatter = () => x => String(x)
const pointFormatter = () => x => String(x)
let lineSpec
let fillScale
let result
let cumulativeValueColumn
const numberOfRecords = 1000
const recordsPerLine = 10
let startingIndex
const setUp = options => {
const {plotType = 'line', position, ...tableOptions} = options
sampleTable = createSampleTable({...tableOptions, plotType})
if (plotType === 'line') {
lineSpec = lineTransform(
sampleTable,
xColKey,
yColKey,
[COLUMN_KEY],
NINETEEN_EIGHTY_FOUR,
position
)
}
const [fillColumn, fillColumnMap] = createGroupIDColumn(sampleTable, [
plotType === 'line' ? COLUMN_KEY : HOST_KEY,
])
fillScale = getNominalColorScale(fillColumnMap, NINETEEN_EIGHTY_FOUR)
sampleTable = sampleTable.addColumn(FILL, 'system', 'number', fillColumn)
const fillColumnFromSampleTable = sampleTable.getColumn(FILL, 'number')
fillColumn.forEach((item, index) =>
expect(item).toEqual(fillColumnFromSampleTable[index])
)
}
describe('tooltip for overlaid line graph', () => {
const position = 'overlaid'
it('should have a value column that is sorted in descending order', () => {
lineSpec = {} as LineLayerSpec
startingIndex = 3
const hoveredRowIndices = []
for (let i = startingIndex; i < numberOfRecords; i += recordsPerLine) {
hoveredRowIndices.push(i)
}
setUp({
include_negative: true,
all_negative: false,
numberOfRecords,
recordsPerLine,
position,
})
result = getPointsTooltipData(
hoveredRowIndices,
sampleTable,
xColKey,
yColKey,
FILL,
columnFormatter,
[COLUMN_KEY],
fillScale,
'overlaid'
)
const singleValueColumn = result.find(column => column.name === yColKey)
expect(
singleValueColumn.values.every((value, index) => {
if (index === 0) {
return true
}
return Number(value) <= Number(singleValueColumn.values[index - 1])
})
).toEqual(true)
})
})
describe('tooltip for stacked line graph', () => {
const position = 'stacked'
afterEach(() => {
const totalColumns = result.length
const totalRows = numberOfRecords / recordsPerLine
const colorsCounter = {}
// color is the same across a row
for (let i = 0; i < totalRows; i += 1) {
for (let j = 0; j < totalColumns; j += 1) {
const rowColor = result[0].colors[i]
expect(rowColor === result[j].colors[i])
}
}
result.forEach(column => {
const {colors} = column
colors.forEach(color => {
if (!colorsCounter[color]) {
colorsCounter[color] = 0
}
colorsCounter[color] += 1
})
})
// number of different colors should equal number of rows
expect(Object.keys(colorsCounter).length).toEqual(totalRows)
// each column should have color
expect(
Object.values(colorsCounter).every(
colorCount => colorCount === totalColumns
)
).toEqual(true)
cumulativeValueColumn = result.find(
column => column.name === STACKED_LINE_CUMULATIVE
)
expect(cumulativeValueColumn).toBeTruthy()
expect(result.find(column => column.name === LINE_COUNT)).toBeTruthy()
})
it('should create proper columns when all values are positive numbers', () => {
lineSpec = {} as LineLayerSpec
startingIndex = 0
const hoveredRowIndices = []
for (let i = startingIndex; i < numberOfRecords; i += recordsPerLine) {
hoveredRowIndices.push(i)
}
setUp({
include_negative: false,
all_negative: false,
numberOfRecords,
recordsPerLine,
position,
})
result = getPointsTooltipData(
hoveredRowIndices,
sampleTable,
xColKey,
yColKey,
FILL,
columnFormatter,
[COLUMN_KEY],
fillScale,
position,
lineSpec.stackedDomainValueColumn
)
const cumulativeValueColumn = result.find(
column => column.name === STACKED_LINE_CUMULATIVE
)
expect(cumulativeValueColumn).toBeTruthy()
expect(
cumulativeValueColumn.values.every((cumulativeValue, index) => {
if (index === 0) {
return true
}
return (
Number(cumulativeValue) <=
Number(cumulativeValueColumn.values[index - 1])
)
})
).toEqual(true)
})
it('should create proper columns when all values are negative numbers', () => {
lineSpec = {} as LineLayerSpec
startingIndex = 1
const hoveredRowIndices = []
for (let i = startingIndex; i < numberOfRecords; i += recordsPerLine) {
hoveredRowIndices.push(i)
}
setUp({
include_negative: true,
all_negative: true,
numberOfRecords,
recordsPerLine,
position,
})
result = getPointsTooltipData(
hoveredRowIndices,
sampleTable,
xColKey,
yColKey,
FILL,
columnFormatter,
[COLUMN_KEY],
fillScale,
position,
lineSpec.stackedDomainValueColumn
)
const cumulativeValueColumn = result.find(
column => column.name === STACKED_LINE_CUMULATIVE
)
expect(cumulativeValueColumn).toBeTruthy()
expect(
cumulativeValueColumn.values.every((cumulativeValue, index) => {
if (index === 0) {
return true
}
return (
Number(cumulativeValue) <=
Number(cumulativeValueColumn.values[index - 1])
)
})
).toEqual(true)
})
it('should create proper columns when values can be positive or negative', () => {
lineSpec = {} as LineLayerSpec
startingIndex = 2
const hoveredRowIndices = []
for (let i = startingIndex; i < numberOfRecords; i += recordsPerLine) {
hoveredRowIndices.push(i)
}
setUp({
include_negative: true,
all_negative: false,
numberOfRecords,
recordsPerLine,
position,
})
result = getPointsTooltipData(
hoveredRowIndices,
sampleTable,
xColKey,
yColKey,
FILL,
columnFormatter,
[COLUMN_KEY],
fillScale,
position,
lineSpec.stackedDomainValueColumn
)
const cumulativeValueColumn = result.find(
column => column.name === STACKED_LINE_CUMULATIVE
)
expect(cumulativeValueColumn).toBeTruthy()
expect(
cumulativeValueColumn.values.every((cumulativeValue, index) => {
if (index === 0) {
return true
}
return (
Number(cumulativeValue) <=
Number(cumulativeValueColumn.values[index - 1])
)
})
).toEqual(true)
})
})
describe('tooltip and static legend at the edge of the graph', () => {
it('should have the same columns and order for tooltip and static legend in an overlaid line graph', () => {
lineSpec = {} as LineLayerSpec
const position = 'overlaid'
setUp({
include_negative: true,
all_negative: false,
numberOfRecords,
recordsPerLine,
position,
})
const overlaidLineGraphStaticLegend = convertLineSpec(
lineSpec,
yColKey,
columnFormatter,
position
)
const overlaidLineGraphTooltip = getPointsTooltipData(
Object.values(lineSpec.columnGroupMaps.latestIndices),
sampleTable,
xColKey,
yColKey,
FILL,
columnFormatter,
[COLUMN_KEY],
fillScale,
position,
lineSpec.stackedDomainValueColumn
)
overlaidLineGraphStaticLegend.forEach(staticLegendColumn => {
const matchingTooltipColumn = overlaidLineGraphTooltip.find(
tooltipColumn => {
return (
staticLegendColumn.key === tooltipColumn.key &&
staticLegendColumn.name.includes(tooltipColumn.name)
)
}
)
expect(matchingTooltipColumn).toBeDefined()
expect(
staticLegendColumn.colors.every(
(color, index) => color === matchingTooltipColumn.colors[index]
)
).toEqual(true)
expect(
staticLegendColumn.values.every(
(value, index) => value === matchingTooltipColumn.values[index]
)
).toEqual(true)
})
})
it('should have the same columns and order for tooltip and static legend in a stacked line graph', () => {
lineSpec = {} as LineLayerSpec
const position = 'stacked'
setUp({
include_negative: true,
all_negative: false,
numberOfRecords,
recordsPerLine,
position,
})
const stackedLineGraphStaticLegend = convertLineSpec(
lineSpec,
yColKey,
columnFormatter,
position
)
const stackedLineGraphTooltip = getPointsTooltipData(
Object.values(lineSpec.columnGroupMaps.latestIndices),
sampleTable,
xColKey,
yColKey,
FILL,
columnFormatter,
[COLUMN_KEY],
fillScale,
position,
lineSpec.stackedDomainValueColumn
)
stackedLineGraphStaticLegend.forEach(staticLegendColumn => {
const matchingTooltipColumn = stackedLineGraphTooltip.find(
tooltipColumn => {
return (
staticLegendColumn.key === tooltipColumn.key &&
staticLegendColumn.name.includes(tooltipColumn.name)
)
}
)
expect(matchingTooltipColumn).toBeDefined()
expect(
staticLegendColumn.colors.every(
(color, index) => color === matchingTooltipColumn.colors[index]
)
).toEqual(true)
expect(
staticLegendColumn.values.every(
(value, index) => value === matchingTooltipColumn.values[index]
)
).toEqual(true)
})
})
})
describe('tooltip for scattered plot', () => {
it('should create the proper columns each with length 1 when optional parameters are missing', () => {
lineSpec = {} as ScatterLayerSpec
const randomIndex = Math.floor(Math.random() * numberOfRecords)
const hoveredRowIndices = [randomIndex]
setUp({
numberOfRecords,
recordsPerLine,
plotType: LayerTypes.Scatter,
})
result = getPointsTooltipData(
hoveredRowIndices,
sampleTable,
xColKey,
yColKey,
FILL,
pointFormatter,
[POINT_KEY, HOST_KEY],
fillScale
)
expect(sampleTable.getColumn(POINT_KEY)).toBeTruthy()
expect(sampleTable.getColumn(HOST_KEY)).toBeTruthy()
expect(
result.every(col => col.values && col.values.length === 1)
).toEqual(true)
})
})
}) | the_stack |
import React from 'react';
import { mount, shallow } from 'enzyme';
import assert from 'assert';
import sinon from 'sinon';
import { findTypes } from '../../util/component-types';
import _ from 'lodash';
import { common } from '../../util/generic-tests';
import { AutocompleteDumb as Autocomplete } from './Autocomplete';
import { DropMenuDumb as DropMenu } from '../DropMenu/DropMenu';
import * as KEYCODE from '../../constants/key-code';
describe('Autocomplete', () => {
common(Autocomplete);
describe('render', () => {
it('should render a DropMenu', () => {
const wrapper = shallow(<Autocomplete />, {
disableLifecycleMethods: true,
});
assert.equal(wrapper.find('DropMenu').length, 1);
});
});
describe('props', () => {
describe('isDisabled', () => {
it('should pass the `isDisabled` prop thru to the underlying DropMenu', () => {
const wrapper = shallow(<Autocomplete isDisabled={true} />, {
disableLifecycleMethods: true,
});
const dropMenuWrapper = wrapper.find('DropMenu');
assert.equal(dropMenuWrapper.prop('isDisabled'), true);
});
it('should apply the appropriate classNames to the control', () => {
const wrapper = shallow(<Autocomplete isDisabled={true} />, {
disableLifecycleMethods: true,
});
const controlWrapper = wrapper.find('.lucid-Autocomplete-Control');
assert(
controlWrapper.hasClass('lucid-Autocomplete-Control-is-disabled')
);
});
});
describe('suggestions', () => {
it('should create `DropMenu.Option`s for each suggestion and pass thru to underlying DropMenu', () => {
const wrapper = shallow(
<Autocomplete
suggestions={['Portland', 'portal', 'porridge', 'potent', 'please']}
/>,
{ disableLifecycleMethods: true }
);
const options = _.map(
findTypes(wrapper.find(DropMenu).props(), DropMenu.Option),
'props'
);
assert.equal('Portland', options[0].children);
assert.equal('portal', options[1].children);
assert.equal('porridge', options[2].children);
assert.equal('potent', options[3].children);
assert.equal('please', options[4].children);
});
});
describe('value', () => {
let wrapper: any;
let rootMountNode: any;
beforeEach(() => {
rootMountNode = document.createElement('div');
document.body.appendChild(rootMountNode);
});
afterEach(() => {
if (wrapper) {
wrapper.unmount();
}
document.body.removeChild(rootMountNode);
});
it('should set the text value of the input', () => {
wrapper = mount(<Autocomplete value='Portland' />, {
attachTo: rootMountNode,
});
const inputDOMNode: any = document.querySelector(
'.lucid-Autocomplete-Control-input'
);
assert.equal(
inputDOMNode.value,
'Portland',
'input value must match prop value'
);
});
it('should change the text value of the input when the prop changes', () => {
wrapper = mount(<Autocomplete value='Portland' />, {
attachTo: rootMountNode,
});
wrapper.setProps({
...wrapper.props(),
value: 'Boston',
});
const inputDOMNode: any = document.querySelector(
'.lucid-Autocomplete-Control-input'
);
assert.equal(
inputDOMNode.value,
'Boston',
'input value must match bew prop value'
);
});
});
describe('DropMenu', () => {
it('should pass thru all DropMenu props to the underlying DropMenu', () => {
const explicitDropMenuProps = {
isExpanded: true,
// direction: 'up',
focusedIndex: 2,
};
const wrapper = shallow(
<Autocomplete DropMenu={explicitDropMenuProps} />,
{ disableLifecycleMethods: true }
);
const dropMenuProps: any = wrapper.find('DropMenu').props();
_.forEach(explicitDropMenuProps, (value, key) => {
assert(_.isEqual(dropMenuProps[key], value));
});
});
});
describe('onChange', () => {
let wrapper: any;
let rootMountNode: any;
beforeEach(() => {
rootMountNode = document.createElement('div');
document.body.appendChild(rootMountNode);
});
afterEach(() => {
if (wrapper) {
wrapper.unmount();
}
document.body.removeChild(rootMountNode);
});
describe('suggestion', () => {
/* eslint-disable no-console */
let error: any;
beforeEach(() => {
error = console.error;
console.error = jest.fn();
});
afterEach(() => {
console.error = error;
});
it('should be called when a suggestion is selected from the menu', () => {
const onChange = sinon.spy();
wrapper = mount(
<Autocomplete
onChange={onChange}
DropMenu={{ isExpanded: true }}
suggestions={[
'Portland',
'portal',
'porridge',
'potent',
'please',
]}
{...{ testProp: 'foo' }}
/>
);
const menuDOMNode: any = document.querySelector(
'.lucid-ContextMenu-FlyOut .lucid-DropMenu-option-container'
);
menuDOMNode.children[2].click();
assert(onChange.called);
const [textValue, { props, event }] = onChange.lastCall.args;
assert.equal(textValue, 'porridge');
assert(props);
assert.equal(props.testProp, 'foo');
assert(event);
expect(console.error).toHaveBeenCalledTimes(1);
});
it('should be called when user types into the text box', () => {
const onChange = sinon.spy();
wrapper = mount(
<Autocomplete onChange={onChange} {...{ testProp: 'foo' }} />,
{
attachTo: rootMountNode,
}
);
const inputDOMNode: any = document.querySelector(
'.lucid-Autocomplete-Control-input'
);
// set the input value and dispatch an `input` event
inputDOMNode.value = 'aaa';
const inputEvent = document.createEvent('Event');
inputEvent.initEvent('input', true, true);
inputDOMNode.dispatchEvent(inputEvent);
assert(onChange.called, 'onChange must be called');
const [textValue, { props, event }] = onChange.lastCall.args;
assert.equal(textValue, 'aaa', 'value must match input');
assert(props, 'props must be passed');
assert.equal(
props.testProp,
'foo',
'aditional props must be included'
);
assert(event, 'event must be passed');
});
/* eslint-enable no-console */
});
});
describe('onSelect', () => {
let wrapper: any;
afterEach(() => {
if (wrapper) {
wrapper.unmount();
}
});
it('should be called when a suggestion is selected from the menu', () => {
const onSelect: any = sinon.spy();
wrapper = mount(
<Autocomplete
onSelect={onSelect}
DropMenu={{ isExpanded: true }}
suggestions={['Portland', 'portal', 'porridge', 'potent', 'please']}
{...{ testProp: 'foo' }}
/>
);
const menuDOMNode: any = document.querySelector(
'.lucid-ContextMenu-FlyOut .lucid-DropMenu-option-container'
);
menuDOMNode.children[2].click();
assert(onSelect.called, 'onSelect must be called');
const [optionIndex, { props, event }] = onSelect.lastCall.args;
assert.equal(optionIndex, 2, 'optionIndex must be accurate');
assert(props, 'props must be passed');
assert.equal(props.testProp, 'foo', 'aditional props must be included');
assert(event, 'event must be passed');
});
});
describe('onExpand', () => {
let wrapper: any;
let rootMountNode: any;
beforeEach(() => {
rootMountNode = document.createElement('div');
document.body.appendChild(rootMountNode);
});
afterEach(() => {
if (wrapper && wrapper.exists()) {
wrapper.unmount();
}
document.body.removeChild(rootMountNode);
});
it('should be called when the input value changes to a non-empty value', () => {
const onExpand = sinon.spy();
wrapper = mount(
<Autocomplete
onExpand={onExpand}
suggestions={['Portland', 'portal', 'porridge', 'potent', 'please']}
{...{ testProp: 'foo' }}
/>,
{ attachTo: rootMountNode }
);
const inputDOMNode: any = document.querySelector(
'.lucid-Autocomplete-Control-input'
);
// set the input value and dispatch an `input` event
inputDOMNode.value = 'aaa';
const inputEvent = document.createEvent('Event');
inputEvent.initEvent('input', true, true);
inputDOMNode.dispatchEvent(inputEvent);
assert(onExpand.called, 'onExpand must be called');
const [{ props, event }] = onExpand.lastCall.args;
assert(props, 'props must be passed');
assert.equal(props.testProp, 'foo', 'aditional props must be included');
assert(event, 'event must be passed');
});
it('should be called when not expanded and down array key is pressed', () => {
const onExpand = sinon.spy();
const wrapper = shallow(
<Autocomplete
onExpand={onExpand}
suggestions={['Portland', 'portal', 'porridge', 'potent', 'please']}
{...{ testProp: 'foo' }}
DropMenu={{
isExpanded: false,
}}
/>,
{ disableLifecycleMethods: true }
);
wrapper.find('.lucid-Autocomplete-Control-input').simulate('keydown', {
keyCode: KEYCODE.ArrowDown,
stopPropagation: _.noop,
});
assert(onExpand.called, 'onExpand must be called');
const [{ props, event }] = onExpand.lastCall.args;
assert(props, 'props must be passed');
assert.equal(props.testProp, 'foo', 'aditional props must be included');
assert(event, 'event must be passed');
});
it('should be called when the control input is clicked', () => {
const onExpand = sinon.spy();
wrapper = mount(
<Autocomplete
onExpand={onExpand}
suggestions={['Portland', 'portal', 'porridge', 'potent', 'please']}
{...{ testProp: 'foo' }}
/>,
{ attachTo: rootMountNode }
);
wrapper.find('.lucid-Autocomplete-Control-input').simulate('click');
assert(onExpand.called, 'onExpand must be called');
const [{ props, event }] = onExpand.lastCall.args;
assert(props, 'props must be passed');
assert.equal(props.testProp, 'foo', 'aditional props must be included');
assert(event, 'event must be passed');
});
it('should be called when not expanded the non-input control is clicked', () => {
const onExpand = sinon.spy();
wrapper = mount(
<Autocomplete
onExpand={onExpand}
suggestions={['Portland', 'portal', 'porridge', 'potent', 'please']}
{...{ testProp: 'foo' }}
DropMenu={{
isExpanded: false,
}}
/>,
{ attachTo: rootMountNode }
);
wrapper.find('.lucid-Autocomplete-Control').simulate('click');
assert(onExpand.called, 'onExpand must be called');
const [{ props, event }] = onExpand.lastCall.args;
assert(props, 'props must be passed');
assert.equal(props.testProp, 'foo', 'aditional props must be included');
assert(event, 'event must be passed');
});
});
});
}); | the_stack |
// Cloud platform
import * as fs from 'fs';
import * as util from 'util';
import * as os from 'os';
import * as events from 'events';
import * as path from 'path';
import * as child_process from 'child_process';
import { LocalCVC4Solver } from 'smtlib';
import * as Tp from 'thingpedia';
import * as rpc from 'transparent-rpc';
import * as Genie from 'genie-toolkit';
import type { CloudSyncWebsocketDelegate } from '../routes/cloud-sync';
import * as graphics from './graphics';
import * as i18n from '../util/i18n';
import SQLPreferences from './preferences';
const _unzipApi : Tp.Capabilities.UnzipApi = {
unzip(zipPath, dir) {
const args = ['-uo', zipPath, '-d', dir];
return util.promisify(child_process.execFile)('/usr/bin/unzip', args, {
maxBuffer: 10 * 1024 * 1024 }).then(({ stdout, stderr }) => {
console.log('stdout', stdout);
console.log('stderr', stderr);
});
}
};
interface WebhookReply {
contentType ?: string;
code : number;
response ?: string;
}
// FIXME the definition in Tp.Capabilities is wrong because it's missing the potential webhook reply
type WebhookCallback = (id : string, method : 'GET' | 'POST', query : URLQuery, headers : URLQuery, payload : unknown) => Promise<WebhookReply|void>;
type URLQuery = { [key : string] : string|string[]|undefined };
export class WebhookApi implements rpc.Stubbable {
$rpcMethods = ['handleCallback'] as const;
$free ?: () => void;
private _userId : string;
private _hooks : Record<string, WebhookCallback>;
constructor(userId : string) {
this._hooks = {};
this._userId = userId;
}
handleCallback(id : string, method : 'GET' | 'POST', query : URLQuery, headers : URLQuery, payload : unknown) : Promise<WebhookReply|void> {
return Promise.resolve().then(() => {
if (id in this._hooks)
return this._hooks[id](id, method, query, headers, payload);
else
console.log('Ignored webhook callback with ID ' + id);
return Promise.resolve();
}).catch((e) => {
console.error(e.stack);
throw e;
});
}
getWebhookBase() {
return _platform.getOrigin() + '/api/webhook/' + this._userId;
}
registerWebhook(id : string, callback : WebhookCallback) {
if (id in this._hooks)
throw new Error('Duplicate webhook ' + id + ' registered');
this._hooks[id] = callback;
}
unregisterWebhook(id : string) {
delete this._hooks[id];
}
}
export class WebSocketWrapper extends events.EventEmitter implements rpc.Stubbable {
$rpcMethods = ['onPing', 'onPong', 'onMessage', 'onClose'] as const;
$free ?: () => void;
private _delegate : rpc.Proxy<CloudSyncWebsocketDelegate>;
constructor(delegate : rpc.Proxy<CloudSyncWebsocketDelegate>) {
super();
this._delegate = delegate;
}
ping() {
return this._delegate.ping();
}
pong() {
return this._delegate.pong();
}
terminate() {
return this._delegate.terminate();
}
send(data : string) {
return this._delegate.send(data);
}
onPing() {
this.emit('ping');
}
onPong() {
this.emit('pong');
}
onMessage(data : string) {
this.emit('message', data);
}
onClose(code ?: number) {
this.emit('close', code);
}
}
export class WebSocketApi extends events.EventEmitter implements Tp.Capabilities.WebSocketApi, rpc.Stubbable {
$rpcMethods = ['newConnection'] as const;
$free ?: () => void;
constructor() {
super();
}
newConnection(delegate : rpc.Proxy<CloudSyncWebsocketDelegate>) {
const wrapper = new WebSocketWrapper(delegate);
this.emit('connection', wrapper);
wrapper.on('close', () => {
delegate.$free();
if (wrapper.$free)
wrapper.$free();
});
return wrapper;
}
}
export interface PlatformOptions {
userId : number;
cloudId : string;
authToken : string;
developerKey : string|null;
locale : string;
timezone : string;
storageKey : string;
modelTag : string|null;
dbProxyUrl : string|null;
dbProxyAccessToken : string|null;
humanName : string|null;
phone : string|null;
email : string;
emailVerified : boolean;
}
export class Platform extends Tp.BasePlatform {
private _cloudId : string;
private _authToken : string;
private _developerKey : string|null;
private _thingpediaClient : rpc.Proxy<Tp.BaseClient>|null;
private _locale : string;
private _timezone : string;
private _sqliteKey : string;
private _dbProxyUrl : string|null;
private _dbProxyAccessToken : string|null;
private _profile : Tp.UserProfile;
// TODO
private _gettext : ReturnType<(typeof i18n)['get']>;
private _writabledir : string;
private _prefs : Tp.Preferences;
private _webhookApi : WebhookApi;
private _websocketApi : WebSocketApi;
constructor(thingpediaClient : rpc.Proxy<Tp.BaseClient>|null, options : PlatformOptions) {
super();
this._cloudId = options.cloudId;
this._authToken = options.authToken;
this._developerKey = options.developerKey;
this._thingpediaClient = thingpediaClient;
this._locale = options.locale;
this._timezone = options.timezone;
this._sqliteKey = options.storageKey;
this._dbProxyUrl = options.dbProxyUrl;
this._dbProxyAccessToken = options.dbProxyAccessToken;
this._profile = {
account: options.cloudId,
name: options.humanName ?? undefined,
locale: options.locale,
timezone: options.timezone,
phone: options.phone ?? undefined,
phone_verified: true,
email: options.email,
email_verified: options.emailVerified
};
this._gettext = i18n.get(this._locale);
const rootDir = process.env.THINGENGINE_ROOTDIR || process.cwd();
this._writabledir = _shared ? path.resolve(rootDir, options.cloudId) : rootDir;
try {
fs.mkdirSync(this._writabledir + '/cache', {recursive: true});
} catch(e) {
if (e.code !== 'EEXIST')
throw e;
}
if (options.dbProxyUrl)
this._prefs = new SQLPreferences(options.dbProxyUrl, options.dbProxyAccessToken!);
else
this._prefs = new Tp.Helpers.FilePreferences(this._writabledir + '/prefs.db');
this._webhookApi = new WebhookApi(this._cloudId);
this._websocketApi = new WebSocketApi();
}
async init() {
if (this._prefs instanceof SQLPreferences)
await this._prefs.init();
}
get type() {
return 'cloud';
}
get locale() {
return this._locale;
}
get timezone() {
return this._timezone;
}
getProfile() {
return this._profile;
}
async setProfile(changes : {
locale ?: string;
timezone ?: string;
name ?: string;
email ?: string;
phone ?: string;
}) {
// TODO implement actual changes
Object.assign(this._profile, changes);
return true;
}
// Return the platform device for this platform, accessing platform-specific
// functionality from natural language.
//
// Cloud has no platform device.
getPlatformDevice() {
return null;
}
// Obtain a shared preference store
// Preferences are simple key/value store which is shared across all apps
// but private to this instance (tier) of the platform
// Preferences should be normally used only by the engine code, and a persistent
// shared store such as DataVault should be used by regular apps
getSharedPreferences() {
return this._prefs;
}
// Check if we need to load and run the given thingengine-module on
// this platform
// (eg we don't need discovery on the cloud, and we don't need graphdb,
// messaging or the apps on the phone client)
hasFeature(feature : string) {
switch (feature) {
case 'discovery':
return false;
case 'permissions':
return LocalCVC4Solver !== null;
default:
return true;
}
}
// Check if this platform has the required capability
// (eg. long running, big storage, reliable connectivity, server
// connectivity, stable IP, local device discovery, bluetooth, etc.)
//
// Which capabilities are available affects which apps are allowed to run
hasCapability(cap : keyof Tp.Capabilities.CapabilityMap) {
switch (cap) {
case 'code-download':
// If downloading code from the thingpedia server is allowed on
// this platform
return true;
case 'thingpedia-client':
return _platform.thingpediaUrl === '/thingpedia';
case 'graphics-api':
case 'webhook-api':
case 'websocket-api':
return true;
case 'gettext':
return true;
case 'smt-solver':
return LocalCVC4Solver !== null;
case 'database-proxy':
return this._dbProxyUrl !== null;
default:
return false;
}
}
// Retrieve an interface to an optional functionality provided by the
// platform
//
// This will return null if hasCapability(cap) is false
getCapability(cap : keyof Tp.Capabilities.CapabilityMap) {
switch (cap) {
case 'code-download':
// We have the support to download code
return _unzipApi;
case 'graphics-api':
return graphics;
case 'thingpedia-client':
return this._thingpediaClient;
case 'webhook-api':
return this._webhookApi;
case 'websocket-api':
return this._websocketApi;
case 'gettext':
return this._gettext;
case 'smt-solver':
return LocalCVC4Solver;
case 'database-proxy':
return { baseUrl: this._dbProxyUrl, accessToken: this._dbProxyAccessToken };
default:
return null;
}
}
// Get the root of the application
// (In android, this is the virtual root of the APK)
getRoot() {
return process.cwd();
}
// Get a directory that is guaranteed to be writable
// (in the private data space for Android, in the current directory for server)
getWritableDir() {
return this._writabledir;
}
// Get a directory good for long term caching of code
// and metadata
getCacheDir() {
return this._writabledir + '/cache';
}
// Get a temporary directory
// Also guaranteed to be writable, but not guaranteed
// to persist across reboots or for long times
// (ie, it could be periodically cleaned by the system)
getTmpDir() {
return os.tmpdir();
}
// Get the filename of the sqlite database
getSqliteDB() {
return this._writabledir + '/sqlite.db';
}
// Get the encryption key of the sqlite database
getSqliteKey() {
return this._sqliteKey;
}
// Get the Thingpedia developer key, if one is configured
getDeveloperKey() {
return this._developerKey;
}
// Change the Thingpedia developer key, if possible
// Returns true if the change actually happened
setDeveloperKey() {
return false;
}
// Return a server/port URL that can be used to refer to this
// installation. This is primarily used for OAuth redirects, and
// so must match what the upstream services accept.
getOrigin() {
return _platform.getOrigin();
}
getCloudId() {
return this._cloudId;
}
getAuthToken() {
return this._authToken;
}
// Change the auth token
// Returns true if a change actually occurred, false if the change
// was rejected
setAuthToken(authToken : string) {
// the auth token is stored outside in the mysql db, we can never
// change it
return false;
}
}
let _shared : boolean;
class PlatformModule {
private _thingpediaUrl ! : string;
private _nlServerUrl ! : string;
private _oauthRedirectOrigin ! : string;
private _faqModels ! : Record<string, { url : string, highConfidence ?: number, lowConfidence ?: number }>;
private _notificationConfig ! : Genie.DialogueAgent.NotificationConfig;
private _activityMonitorOptions ! : {
idleTimeoutMillis ?: number;
quiesceTimeoutMillis ?: number;
}
// Initialize the platform code
// Will be called before instantiating the engine
init(options : {
shared : boolean;
thingpedia_url : string;
nl_server_url : string;
oauth_redirect_origin : string;
faq_models : string;
notification_config : string;
activity_monitor_idle_timeout_millis : number;
activity_monitor_quiesce_timeout_millis : number;
}) {
_shared = options.shared;
this._thingpediaUrl = options.thingpedia_url;
this._nlServerUrl = options.nl_server_url;
this._oauthRedirectOrigin = options.oauth_redirect_origin;
this._faqModels = JSON.parse(options.faq_models);
this._notificationConfig = JSON.parse(options.notification_config);
this._activityMonitorOptions = {
idleTimeoutMillis: options.activity_monitor_idle_timeout_millis,
quiesceTimeoutMillis: options.activity_monitor_quiesce_timeout_millis,
};
}
get thingpediaUrl() {
return this._thingpediaUrl;
}
get nlServerUrl() {
return this._nlServerUrl;
}
get faqModels() {
return this._faqModels;
}
get notificationConfig() {
return this._notificationConfig;
}
get activityMonitorOptions() {
return this._activityMonitorOptions;
}
get shared() {
return _shared;
}
newInstance(thingpediaClient : rpc.Proxy<Tp.BaseClient>|null, options : PlatformOptions) {
return new Platform(thingpediaClient, options);
}
// for compat with existing code that does platform.getOrigin()
getOrigin() {
return this._oauthRedirectOrigin;
}
// Check if this platform has the required capability
// This is only for compat with existing code
hasCapability(cap : keyof Tp.Capabilities.CapabilityMap) {
switch (cap) {
case 'graphics-api':
return true;
default:
return false;
}
}
// Check if this platform has the required capability
// This is only about caps that don't consider the current context
// for compat with existing code
getCapability(cap : keyof Tp.Capabilities.CapabilityMap) {
switch (cap) {
case 'graphics-api':
return graphics;
default:
return null;
}
}
// Stop the main loop and exit
// (In Android, this only stops the node.js thread)
// This function should be called by the platform integration
// code, after stopping the engine
exit() {
return process.exit();
}
}
const _platform = new PlatformModule();
export default _platform; | the_stack |
import {Component, isComponentClass} from '@layr/component';
import type {ComponentServerLike} from '@layr/component-server';
import isEqual from 'lodash/isEqual';
import {ComponentClient} from './component-client';
describe('ComponentClient', () => {
const server: ComponentServerLike = {
receive({query, components, version: clientVersion}) {
const serverVersion = 1;
if (clientVersion !== serverVersion) {
throw Object.assign(
new Error(
`The component client version (${clientVersion}) doesn't match the component server version (${serverVersion})`
),
{code: 'COMPONENT_CLIENT_VERSION_DOES_NOT_MATCH_COMPONENT_SERVER_VERSION'}
);
}
// client.getComponents()
if (
isEqual({query, components}, {query: {'introspect=>': {'()': []}}, components: undefined})
) {
return {
result: {
component: {
name: 'Backend',
providedComponents: [
{
name: 'Session',
properties: [
{
name: 'token',
type: 'Attribute',
valueType: 'string?',
value: {__undefined: true},
exposure: {get: true, set: true}
}
]
},
{
name: 'Movie',
mixins: ['Storable'],
properties: [{name: 'find', type: 'Method', exposure: {call: true}}],
prototype: {
properties: [
{
name: 'id',
type: 'PrimaryIdentifierAttribute',
valueType: 'string',
default: {
__function: 'function () {\nreturn this.constructor.generateId();\n}'
},
exposure: {get: true, set: true}
},
{
name: 'slug',
type: 'SecondaryIdentifierAttribute',
valueType: 'string',
exposure: {get: true, set: true}
},
{
name: 'title',
type: 'Attribute',
valueType: 'string',
default: {__function: "function () {\nreturn '';\n}"},
validators: [
{
__validator: {
name: 'notEmpty',
function: {__function: '(value) => value.length > 0'}
}
}
],
exposure: {get: true, set: true}
},
{
name: 'isPlaying',
type: 'Attribute',
valueType: 'boolean',
exposure: {get: true}
},
{name: 'play', type: 'Method', exposure: {call: true}},
{name: 'validateTitle', type: 'Method', exposure: {call: true}}
]
},
consumedComponents: ['Session']
}
]
}
}
};
}
// Movie.find() without Session's token
if (
isEqual(
{query, components},
{
query: {
'<=': {__component: 'typeof Movie'},
'find=>': {'()': []}
},
components: [{__component: 'typeof Session', token: {__undefined: true}}]
}
)
) {
return {
result: {__error: 'Access denied'}
};
}
// Movie.find() with Session's token
if (
isEqual(
{query, components},
{
query: {
'<=': {__component: 'typeof Movie'},
'find=>': {'()': []}
},
components: [{__component: 'typeof Session', token: 'abc123'}]
}
)
) {
return {
result: [
{
__component: 'Movie',
id: 'movie1',
slug: 'inception',
title: 'Inception',
isPlaying: false
},
{
__component: 'Movie',
id: 'movie2',
slug: 'the-matrix',
title: 'The Matrix',
isPlaying: false
}
]
};
}
// Movie.find({limit: 1})
if (
isEqual(
{query, components},
{
query: {
'<=': {__component: 'typeof Movie'},
'find=>': {'()': [{limit: 1}]}
},
components: [{__component: 'typeof Session', token: 'abc123'}]
}
)
) {
return {
result: [
{
__component: 'Movie',
id: 'movie1',
slug: 'inception',
title: 'Inception',
isPlaying: false
}
]
};
}
// movie.play()
if (
isEqual(
{query, components},
{
query: {'<=': {__component: 'Movie', id: 'movie1'}, 'play=>': {'()': []}},
components: [{__component: 'typeof Session', token: 'abc123'}]
}
)
) {
return {
result: {__component: 'Movie', id: 'movie1', isPlaying: true}
};
}
// movie.validateTitle('')
if (
isEqual(
{query, components},
{
query: {
'<=': {__component: 'Movie', id: 'movie1', title: ''},
'validateTitle=>': {'()': []}
},
components: [{__component: 'typeof Session', token: 'abc123'}]
}
)
) {
return {
result: false
};
}
// movie.validateTitle('Inception 2')
if (
isEqual(
{query, components},
{
query: {
'<=': {__component: 'Movie', id: 'movie1', title: 'Inception 2'},
'validateTitle=>': {'()': []}
},
components: [{__component: 'typeof Session', token: 'abc123'}]
}
)
) {
return {
result: true
};
}
// [movie1.play(), movie2.play()]
if (
isEqual(
{query, components},
{
query: {
'||': [
{'<=': {__component: 'Movie', id: 'movie1'}, 'play=>': {'()': []}},
{'<=': {__component: 'Movie', id: 'movie2'}, 'play=>': {'()': []}}
]
},
components: [{__component: 'typeof Session', token: 'abc123'}]
}
)
) {
return {
result: [
{__component: 'Movie', id: 'movie1', isPlaying: true},
{__component: 'Movie', id: 'movie2', isPlaying: true}
]
};
}
throw new Error(
`Received an unknown request (query: ${JSON.stringify(query)}, components: ${JSON.stringify(
components
)})`
);
}
};
const Storable = (Base = Component) => {
const _Storable = class extends Base {
static isStorable() {}
isStorable() {}
};
Object.defineProperty(_Storable, '__mixin', {value: 'Storable'});
return _Storable;
};
test('Getting component', async () => {
let client = new ComponentClient(server);
expect(() => client.getComponent()).toThrow(
"The component client version (undefined) doesn't match the component server version (1)"
);
client = new ComponentClient(server, {version: 1, mixins: [Storable]});
const Backend = client.getComponent() as typeof Component;
expect(isComponentClass(Backend)).toBe(true);
expect(Backend.getComponentName()).toBe('Backend');
const Session = Backend.getProvidedComponent('Session')!;
expect(isComponentClass(Session)).toBe(true);
expect(Session.getComponentName()).toBe('Session');
let attribute = Session.getAttribute('token');
expect(attribute.getValueType().toString()).toBe('string?');
expect(attribute.getExposure()).toEqual({get: true, set: true});
expect(attribute.getValue()).toBeUndefined();
const Movie = Backend.getProvidedComponent('Movie')!;
expect(isComponentClass(Movie)).toBe(true);
expect(Movie.getComponentName()).toBe('Movie');
expect(Movie.getConsumedComponent('Session')).toBe(Session);
let method = Movie.getMethod('find');
expect(method.getExposure()).toEqual({call: true});
attribute = Movie.prototype.getPrimaryIdentifierAttribute();
expect(attribute.getName()).toBe('id');
expect(attribute.getValueType().toString()).toBe('string');
expect(typeof attribute.getDefault()).toBe('function');
expect(attribute.getExposure()).toEqual({get: true, set: true});
attribute = Movie.prototype.getSecondaryIdentifierAttribute('slug');
expect(attribute.getValueType().toString()).toBe('string');
expect(attribute.getDefault()).toBeUndefined();
expect(attribute.getExposure()).toEqual({get: true, set: true});
attribute = Movie.prototype.getAttribute('title');
expect(attribute.getValueType().toString()).toBe('string');
expect(attribute.evaluateDefault()).toBe('');
expect(attribute.getValueType().getValidators()).toHaveLength(1);
expect(attribute.getExposure()).toEqual({get: true, set: true});
attribute = Movie.prototype.getAttribute('isPlaying');
expect(attribute.getValueType().toString()).toBe('boolean');
expect(attribute.evaluateDefault()).toBe(undefined);
expect(attribute.getExposure()).toEqual({get: true});
expect(attribute.isControlled()).toBe(true);
method = Movie.prototype.getMethod('play');
expect(method.getExposure()).toEqual({call: true});
method = Movie.prototype.getMethod('validateTitle');
expect(method.getExposure()).toEqual({call: true});
expect(typeof (Movie as any).isStorable).toBe('function');
});
describe('Invoking methods', () => {
class BaseSession extends Component {
static token?: string;
}
class BaseMovie extends Component {
static Session: typeof BaseSession;
// @ts-ignore
static find({limit}: {limit?: number} = {}): BaseMovie[] {}
id!: string;
slug!: string;
title = '';
isPlaying = false;
play() {}
// @ts-ignore
validateTitle(): boolean {}
}
class BaseBackend extends Component {
static Session: typeof BaseSession;
static Movie: typeof BaseMovie;
}
test('One by one', async () => {
const client = new ComponentClient(server, {version: 1, mixins: [Storable]});
const {Movie, Session} = client.getComponent() as typeof BaseBackend;
expect(() => Movie.find()).toThrow('Access denied'); // The token is missing
Session.token = 'abc123';
let movies = Movie.find();
expect(movies).toHaveLength(2);
expect(movies[0]).toBeInstanceOf(Movie);
expect(movies[0].id).toBe('movie1');
expect(movies[0].slug).toBe('inception');
expect(movies[0].title).toBe('Inception');
expect(movies[1]).toBeInstanceOf(Movie);
expect(movies[1].id).toBe('movie2');
expect(movies[1].slug).toBe('the-matrix');
expect(movies[1].title).toBe('The Matrix');
movies = Movie.find({limit: 1});
expect(movies).toHaveLength(1);
expect(movies[0]).toBeInstanceOf(Movie);
expect(movies[0].id).toBe('movie1');
expect(movies[0].slug).toBe('inception');
expect(movies[0].title).toBe('Inception');
const movie = movies[0];
movie.play();
expect(movie.isPlaying).toBe(true);
movie.title = '';
expect(movie.validateTitle()).toBe(false);
movie.title = 'Inception 2';
expect(movie.validateTitle()).toBe(true);
});
test('In batch mode', async () => {
const client = new ComponentClient(server, {version: 1, mixins: [Storable], batchable: true});
const {Movie, Session} = (await client.getComponent()) as typeof BaseBackend;
Session.token = 'abc123';
const movies = await Movie.find();
expect(movies).toHaveLength(2);
expect(movies[0]).toBeInstanceOf(Movie);
expect(movies[0].id).toBe('movie1');
expect(movies[0].slug).toBe('inception');
expect(movies[0].title).toBe('Inception');
expect(movies[1]).toBeInstanceOf(Movie);
expect(movies[1].id).toBe('movie2');
expect(movies[1].slug).toBe('the-matrix');
expect(movies[1].title).toBe('The Matrix');
await Promise.all([movies[0].play(), movies[1].play()]);
expect(movies[0].isPlaying).toBe(true);
expect(movies[1].isPlaying).toBe(true);
});
});
}); | the_stack |
import { testTokenization } from '../test/testRunner';
testTokenization('elixir', [
// Keywords - module definition
[
{
line: 'defmodule Foo do end',
tokens: [
{ startIndex: 0, type: 'keyword.declaration.elixir' },
{ startIndex: 9, type: 'white.elixir' },
{ startIndex: 10, type: 'type.identifier.elixir' },
{ startIndex: 13, type: 'white.elixir' },
{ startIndex: 14, type: 'keyword.elixir' },
{ startIndex: 16, type: 'white.elixir' },
{ startIndex: 17, type: 'keyword.elixir' }
]
}
],
// Keywords - function definition
[
{
line: 'def foo(x) do end',
tokens: [
{ startIndex: 0, type: 'keyword.declaration.elixir' },
{ startIndex: 3, type: 'white.elixir' },
{ startIndex: 4, type: 'function.elixir' },
{ startIndex: 7, type: 'delimiter.parenthesis.elixir' },
{ startIndex: 8, type: 'identifier.elixir' },
{ startIndex: 9, type: 'delimiter.parenthesis.elixir' },
{ startIndex: 10, type: 'white.elixir' },
{ startIndex: 11, type: 'keyword.elixir' },
{ startIndex: 13, type: 'white.elixir' },
{ startIndex: 14, type: 'keyword.elixir' }
]
}
],
// Keywords - macro
[
{
line: 'defmacro mac(name) do quote do def unquote(name)() do nil end end end',
tokens: [
{ startIndex: 0, type: 'keyword.declaration.elixir' },
{ startIndex: 8, type: 'white.elixir' },
{ startIndex: 9, type: 'function.elixir' },
{ startIndex: 12, type: 'delimiter.parenthesis.elixir' },
{ startIndex: 13, type: 'identifier.elixir' },
{ startIndex: 17, type: 'delimiter.parenthesis.elixir' },
{ startIndex: 18, type: 'white.elixir' },
{ startIndex: 19, type: 'keyword.elixir' },
{ startIndex: 21, type: 'white.elixir' },
{ startIndex: 22, type: 'keyword.elixir' },
{ startIndex: 27, type: 'white.elixir' },
{ startIndex: 28, type: 'keyword.elixir' },
{ startIndex: 30, type: 'white.elixir' },
{ startIndex: 31, type: 'keyword.declaration.elixir' },
{ startIndex: 34, type: 'white.elixir' },
{ startIndex: 35, type: 'keyword.elixir' },
{ startIndex: 42, type: 'delimiter.parenthesis.elixir' },
{ startIndex: 43, type: 'identifier.elixir' },
{ startIndex: 47, type: 'delimiter.parenthesis.elixir' },
{ startIndex: 50, type: 'white.elixir' },
{ startIndex: 51, type: 'keyword.elixir' },
{ startIndex: 53, type: 'white.elixir' },
{ startIndex: 54, type: 'constant.language.elixir' },
{ startIndex: 57, type: 'white.elixir' },
{ startIndex: 58, type: 'keyword.elixir' },
{ startIndex: 61, type: 'white.elixir' },
{ startIndex: 62, type: 'keyword.elixir' },
{ startIndex: 65, type: 'white.elixir' },
{ startIndex: 66, type: 'keyword.elixir' }
]
}
],
// Comments
[
{
line: 'nil # comment',
tokens: [
{ startIndex: 0, type: 'constant.language.elixir' },
{ startIndex: 3, type: 'white.elixir' },
{ startIndex: 4, type: 'comment.punctuation.elixir' },
{ startIndex: 5, type: 'comment.elixir' }
]
}
],
// Keyword list shorthand
[
{
line: '["key": value]',
tokens: [
{ startIndex: 0, type: 'delimiter.square.elixir' },
{ startIndex: 1, type: 'constant.delimiter.elixir' },
{ startIndex: 2, type: 'constant.elixir' },
{ startIndex: 5, type: 'constant.delimiter.elixir' },
{ startIndex: 7, type: 'white.elixir' },
{ startIndex: 8, type: 'identifier.elixir' },
{ startIndex: 13, type: 'delimiter.square.elixir' }
]
}
],
// Numbers
[
{
line: '[1,1.23,1.23e-10,0xab,0o171,0b01001]',
tokens: [
{ startIndex: 0, type: 'delimiter.square.elixir' },
{ startIndex: 1, type: 'number.elixir' },
{ startIndex: 2, type: 'punctuation.elixir' },
{ startIndex: 3, type: 'number.float.elixir' },
{ startIndex: 7, type: 'punctuation.elixir' },
{ startIndex: 8, type: 'number.float.elixir' },
{ startIndex: 16, type: 'punctuation.elixir' },
{ startIndex: 17, type: 'number.hex.elixir' },
{ startIndex: 21, type: 'punctuation.elixir' },
{ startIndex: 22, type: 'number.octal.elixir' },
{ startIndex: 27, type: 'punctuation.elixir' },
{ startIndex: 28, type: 'number.binary.elixir' },
{ startIndex: 35, type: 'delimiter.square.elixir' }
]
}
],
// Unused bindings
[
{
line: 'def foo(_x) do _y = 1 end',
tokens: [
{ startIndex: 0, type: 'keyword.declaration.elixir' },
{ startIndex: 3, type: 'white.elixir' },
{ startIndex: 4, type: 'function.elixir' },
{ startIndex: 7, type: 'delimiter.parenthesis.elixir' },
{ startIndex: 8, type: 'comment.unused.elixir' },
{ startIndex: 10, type: 'delimiter.parenthesis.elixir' },
{ startIndex: 11, type: 'white.elixir' },
{ startIndex: 12, type: 'keyword.elixir' },
{ startIndex: 14, type: 'white.elixir' },
{ startIndex: 15, type: 'comment.unused.elixir' },
{ startIndex: 17, type: 'white.elixir' },
{ startIndex: 18, type: 'operator.elixir' },
{ startIndex: 19, type: 'white.elixir' },
{ startIndex: 20, type: 'number.elixir' },
{ startIndex: 21, type: 'white.elixir' },
{ startIndex: 22, type: 'keyword.elixir' }
]
}
],
// Function calls
[
{
line: 'foo(x)',
tokens: [
{ startIndex: 0, type: 'function.call.elixir' },
{ startIndex: 3, type: 'delimiter.parenthesis.elixir' },
{ startIndex: 4, type: 'identifier.elixir' },
{ startIndex: 5, type: 'delimiter.parenthesis.elixir' }
]
}
],
[
{
line: 'foo.()',
tokens: [
{ startIndex: 0, type: 'function.call.elixir' },
{ startIndex: 3, type: 'operator.elixir' },
{ startIndex: 4, type: 'delimiter.parenthesis.elixir' }
]
}
],
[
{
line: 'Mod.foo()',
tokens: [
{ startIndex: 0, type: 'type.identifier.elixir' },
{ startIndex: 3, type: 'operator.elixir' },
{ startIndex: 4, type: 'function.call.elixir' },
{ startIndex: 7, type: 'delimiter.parenthesis.elixir' }
]
}
],
// Function call (Erlang module)
[
{
line: ':mo.foo()',
tokens: [
{ startIndex: 0, type: 'constant.punctuation.elixir' },
{ startIndex: 1, type: 'constant.elixir' },
{ startIndex: 3, type: 'operator.elixir' },
{ startIndex: 4, type: 'function.call.elixir' },
{ startIndex: 7, type: 'delimiter.parenthesis.elixir' }
]
}
],
// Function call (pipe)
[
{
line: '1 |> abs()',
tokens: [
{ startIndex: 0, type: 'number.elixir' },
{ startIndex: 1, type: 'white.elixir' },
{ startIndex: 2, type: 'operator.elixir' },
{ startIndex: 4, type: 'white.elixir' },
{ startIndex: 5, type: 'function.call.elixir' },
{ startIndex: 8, type: 'delimiter.parenthesis.elixir' }
]
}
],
// Function reference
[
{
line: '&max(&1,&2)',
tokens: [
{ startIndex: 0, type: 'operator.elixir' },
{ startIndex: 1, type: 'function.call.elixir' },
{ startIndex: 4, type: 'delimiter.parenthesis.elixir' },
{ startIndex: 5, type: 'operator.elixir' },
{ startIndex: 7, type: 'punctuation.elixir' },
{ startIndex: 8, type: 'operator.elixir' },
{ startIndex: 10, type: 'delimiter.parenthesis.elixir' }
]
}
],
// Strings
[
{
line: '"foo"',
tokens: [
{ startIndex: 0, type: 'string.delimiter.elixir' },
{ startIndex: 1, type: 'string.elixir' },
{ startIndex: 4, type: 'string.delimiter.elixir' }
]
}
],
[
{
line: '"foo \\u0065\\u0301 #{1}"',
tokens: [
{ startIndex: 0, type: 'string.delimiter.elixir' },
{ startIndex: 1, type: 'string.elixir' },
{ startIndex: 5, type: 'constant.character.escape.elixir' },
{ startIndex: 17, type: 'string.elixir' },
{ startIndex: 18, type: 'delimiter.bracket.embed.elixir' },
{ startIndex: 20, type: 'number.elixir' },
{ startIndex: 21, type: 'delimiter.bracket.embed.elixir' },
{ startIndex: 22, type: 'string.delimiter.elixir' }
]
}
],
[
{
line: '"""heredoc"""',
tokens: [
{ startIndex: 0, type: 'string.delimiter.elixir' },
{ startIndex: 3, type: 'string.elixir' },
{ startIndex: 10, type: 'string.delimiter.elixir' }
]
}
],
// Atom strings
[
{
line: ':"atom"',
tokens: [
{ startIndex: 0, type: 'constant.delimiter.elixir' },
{ startIndex: 2, type: 'constant.elixir' },
{ startIndex: 6, type: 'constant.delimiter.elixir' }
]
}
],
// Sigils (string)
[
{
line: '~s{foo}',
tokens: [
{ startIndex: 0, type: 'string.delimiter.elixir' },
{ startIndex: 3, type: 'string.elixir' },
{ startIndex: 6, type: 'string.delimiter.elixir' }
]
}
],
// Sigils (regexp)
[
{
line: '~r/foo/',
tokens: [
{ startIndex: 0, type: 'regexp.delimiter.elixir' },
{ startIndex: 3, type: 'regexp.elixir' },
{ startIndex: 6, type: 'regexp.delimiter.elixir' }
]
}
],
// Sigils (other)
[
{
line: '~D/foo/',
tokens: [
{ startIndex: 0, type: 'sigil.delimiter.elixir' },
{ startIndex: 3, type: 'sigil.elixir' },
{ startIndex: 6, type: 'sigil.delimiter.elixir' }
]
}
],
// Sigils (no interpolation)
[
{
line: '~W/foo#{1}/',
tokens: [
{ startIndex: 0, type: 'sigil.delimiter.elixir' },
{ startIndex: 3, type: 'sigil.elixir' },
{ startIndex: 10, type: 'sigil.delimiter.elixir' }
]
}
],
// Module attributes
[
{
line: '@attr 1',
tokens: [
{ startIndex: 0, type: 'variable.elixir' },
{ startIndex: 5, type: 'white.elixir' },
{ startIndex: 6, type: 'number.elixir' }
]
}
],
// Module attributes (docs)
[
{
line: '@doc "foo"',
tokens: [{ startIndex: 0, type: 'comment.block.documentation.elixir' }]
}
],
// Operator definition
[
{
line: 'def a ~> b, do: max(a,b)',
tokens: [
{ startIndex: 0, type: 'keyword.declaration.elixir' },
{ startIndex: 3, type: 'white.elixir' },
{ startIndex: 4, type: 'identifier.elixir' },
{ startIndex: 5, type: 'white.elixir' },
{ startIndex: 6, type: 'operator.elixir' },
{ startIndex: 8, type: 'white.elixir' },
{ startIndex: 9, type: 'identifier.elixir' },
{ startIndex: 10, type: 'punctuation.elixir' },
{ startIndex: 11, type: 'white.elixir' },
{ startIndex: 12, type: 'constant.elixir' },
{ startIndex: 14, type: 'constant.punctuation.elixir' },
{ startIndex: 15, type: 'white.elixir' },
{ startIndex: 16, type: 'function.call.elixir' },
{ startIndex: 19, type: 'delimiter.parenthesis.elixir' },
{ startIndex: 20, type: 'identifier.elixir' },
{ startIndex: 21, type: 'punctuation.elixir' },
{ startIndex: 22, type: 'identifier.elixir' },
{ startIndex: 23, type: 'delimiter.parenthesis.elixir' }
]
}
],
// Constants
[
{
line: '[true,false,nil]',
tokens: [
{ startIndex: 0, type: 'delimiter.square.elixir' },
{ startIndex: 1, type: 'constant.language.elixir' },
{ startIndex: 5, type: 'punctuation.elixir' },
{ startIndex: 6, type: 'constant.language.elixir' },
{ startIndex: 11, type: 'punctuation.elixir' },
{ startIndex: 12, type: 'constant.language.elixir' },
{ startIndex: 15, type: 'delimiter.square.elixir' }
]
}
]
]); | the_stack |
import { isEqual } from 'lodash'
import AlertCircleIcon from 'mdi-react/AlertCircleIcon'
import React, { useCallback, useEffect, useState } from 'react'
import { delay, distinctUntilChanged, repeatWhen } from 'rxjs/operators'
import { LoadingSpinner } from '@sourcegraph/react-loading-spinner'
import { Link } from '@sourcegraph/shared/src/components/Link'
import { BatchSpecState } from '@sourcegraph/shared/src/graphql-operations'
import { asError, isErrorLike } from '@sourcegraph/shared/src/util/errors'
import { Container, PageHeader } from '@sourcegraph/wildcard'
import { BatchChangesIcon } from '../../../batches/icons'
import { ErrorAlert } from '../../../components/alerts'
import { HeroPage } from '../../../components/HeroPage'
import { PageTitle } from '../../../components/PageTitle'
import { BatchSpecExecutionFields, Scalars } from '../../../graphql-operations'
import { BatchSpec } from '../BatchSpec'
import { cancelBatchSpecExecution, fetchBatchSpecExecution as _fetchBatchSpecExecution } from './backend'
export interface BatchSpecExecutionDetailsPageProps {
executionID: Scalars['ID']
/** For testing only. */
fetchBatchSpecExecution?: typeof _fetchBatchSpecExecution
/** For testing only. */
now?: () => Date
/** For testing only. */
expandStage?: string
}
export const BatchSpecExecutionDetailsPage: React.FunctionComponent<BatchSpecExecutionDetailsPageProps> = ({
executionID,
// now = () => new Date(),
fetchBatchSpecExecution = _fetchBatchSpecExecution,
// expandStage,
}) => {
const [batchSpecExecution, setBatchSpecExecution] = useState<BatchSpecExecutionFields | null | undefined>()
useEffect(() => {
const subscription = fetchBatchSpecExecution(executionID)
.pipe(
repeatWhen(notifier => notifier.pipe(delay(2500))),
distinctUntilChanged((a, b) => isEqual(a, b))
)
.subscribe(execution => {
setBatchSpecExecution(execution)
})
return () => subscription.unsubscribe()
}, [fetchBatchSpecExecution, executionID])
const [isCanceling, setIsCanceling] = useState<boolean | Error>(false)
const cancelExecution = useCallback(async () => {
try {
const execution = await cancelBatchSpecExecution(executionID)
setBatchSpecExecution(execution)
} catch (error) {
setIsCanceling(asError(error))
}
}, [executionID])
// Is loading.
if (batchSpecExecution === undefined) {
return (
<div className="text-center">
<LoadingSpinner className="icon-inline mx-auto my-4" />
</div>
)
}
// Is not found.
if (batchSpecExecution === null) {
return <HeroPage icon={AlertCircleIcon} title="Execution not found" />
}
return (
<>
<PageTitle title="Batch spec execution" />
<PageHeader
path={[
{
icon: BatchChangesIcon,
to: '/batch-changes',
},
{
to: `${batchSpecExecution.namespace.url}/batch-changes`,
text: batchSpecExecution.namespace.namespaceName,
},
{
text: (
<>
Execution <span className="badge badge-secondary">{batchSpecExecution.state}</span>
</>
),
},
]}
actions={
(batchSpecExecution.state === BatchSpecState.QUEUED ||
batchSpecExecution.state === BatchSpecState.PROCESSING) && (
<>
<button
type="button"
className="btn btn-outline-secondary"
onClick={cancelExecution}
disabled={isCanceling === true}
>
Cancel
</button>
{isErrorLike(isCanceling) && <ErrorAlert error={isCanceling} />}
</>
)
}
className="mb-3"
/>
{batchSpecExecution.failureMessage && <ErrorAlert error={batchSpecExecution.failureMessage} />}
<h2>Input spec</h2>
<Container className="mb-3">
<BatchSpec originalInput={batchSpecExecution.originalInput} />
</Container>
<h2>Timeline</h2>
{/* <ExecutionTimeline execution={batchSpecExecution} now={now} expandStage={expandStage} className="mb-3" /> */}
{batchSpecExecution.applyURL && (
<>
<h2>Execution result</h2>
<div className="alert alert-info d-flex justify-space-between align-items-center">
<span className="flex-grow-1">Batch spec has been created.</span>
<Link to={batchSpecExecution.applyURL} className="btn btn-primary">
Preview changes
</Link>
</div>
</>
)}
</>
)
}
// interface ExecutionTimelineProps {
// execution: BatchSpecExecutionFields
// className?: string
// /** For testing only. */
// now?: () => Date
// expandStage?: string
// }
// const ExecutionTimeline: React.FunctionComponent<ExecutionTimelineProps> = ({
// execution,
// className,
// now,
// expandStage,
// }) => {
// const stages = useMemo(
// () => [
// { icon: <TimerSandIcon />, text: 'Queued', date: execution.createdAt, className: 'bg-success' },
// {
// icon: <CheckIcon />,
// text: 'Began processing',
// date: execution.startedAt,
// className: 'bg-success',
// },
// setupStage(execution, expandStage === 'setup', now),
// batchPreviewStage(execution, expandStage === 'srcPreview', now),
// teardownStage(execution, expandStage === 'teardown', now),
// execution.state === BatchSpecState.COMPLETED
// ? { icon: <CheckIcon />, text: 'Finished', date: execution.finishedAt, className: 'bg-success' }
// : execution.state === BatchSpecState.CANCELED
// ? { icon: <ErrorIcon />, text: 'Canceled', date: execution.finishedAt, className: 'bg-secondary' }
// : { icon: <ErrorIcon />, text: 'Failed', date: execution.finishedAt, className: 'bg-danger' },
// ],
// [execution, now, expandStage]
// )
// return <Timeline stages={stages.filter(isDefined)} now={now} className={className} />
// }
// const setupStage = (
// execution: BatchSpecExecutionFields,
// expand: boolean,
// now?: () => Date
// ): TimelineStage | undefined =>
// execution.steps.setup.length === 0
// ? undefined
// : {
// text: 'Setup',
// details: execution.steps.setup.map(logEntry => (
// <ExecutionLogEntry key={logEntry.key} logEntry={logEntry} now={now} />
// )),
// ...genericStage(execution.steps.setup, expand),
// }
// const batchPreviewStage = (
// execution: BatchSpecExecutionFields,
// expand: boolean,
// now?: () => Date
// ): TimelineStage | undefined =>
// !execution.steps.srcPreview
// ? undefined
// : {
// text: 'Create batch spec preview',
// details: (
// <ExecutionLogEntry logEntry={execution.steps.srcPreview} now={now}>
// {execution.steps.srcPreview.out && <ParsedJsonOutput out={execution.steps.srcPreview.out} />}
// </ExecutionLogEntry>
// ),
// ...genericStage(execution.steps.srcPreview, expand),
// }
// const teardownStage = (
// execution: BatchSpecExecutionFields,
// expand: boolean,
// now?: () => Date
// ): TimelineStage | undefined =>
// execution.steps.teardown.length === 0
// ? undefined
// : {
// text: 'Teardown',
// details: execution.steps.teardown.map(logEntry => (
// <ExecutionLogEntry key={logEntry.key} logEntry={logEntry} now={now} />
// )),
// ...genericStage(execution.steps.teardown, expand),
// }
// const genericStage = <E extends { startTime: string; exitCode: number | null }>(
// value: E | E[],
// expand: boolean
// ): Pick<TimelineStage, 'icon' | 'date' | 'className' | 'expanded'> => {
// const finished = isArray(value) ? value.every(logEntry => logEntry.exitCode !== null) : value.exitCode !== null
// const success = isArray(value) ? value.every(logEntry => logEntry.exitCode === 0) : value.exitCode === 0
// return {
// icon: !finished ? <ProgressClockIcon /> : success ? <CheckIcon /> : <ErrorIcon />,
// date: isArray(value) ? value[0].startTime : value.startTime,
// className: success || !finished ? 'bg-success' : 'bg-danger',
// expanded: expand || !(success || !finished),
// }
// }
// enum JSONLogLineOperation {
// PARSING_BATCH_SPEC = 'PARSING_BATCH_SPEC',
// RESOLVING_NAMESPACE = 'RESOLVING_NAMESPACE',
// PREPARING_DOCKER_IMAGES = 'PREPARING_DOCKER_IMAGES',
// DETERMINING_WORKSPACE_TYPE = 'DETERMINING_WORKSPACE_TYPE',
// RESOLVING_REPOSITORIES = 'RESOLVING_REPOSITORIES',
// DETERMINING_WORKSPACES = 'DETERMINING_WORKSPACES',
// CHECKING_CACHE = 'CHECKING_CACHE',
// EXECUTING_TASKS = 'EXECUTING_TASKS',
// LOG_FILE_KEPT = 'LOG_FILE_KEPT',
// UPLOADING_CHANGESET_SPECS = 'UPLOADING_CHANGESET_SPECS',
// CREATING_BATCH_SPEC = 'CREATING_BATCH_SPEC',
// APPLYING_BATCH_SPEC = 'APPLYING_BATCH_SPEC',
// BATCH_SPEC_EXECUTION = 'BATCH_SPEC_EXECUTION',
// EXECUTING_TASK = 'EXECUTING_TASK',
// TASK_BUILD_CHANGESET_SPECS = 'TASK_BUILD_CHANGESET_SPECS',
// TASK_DOWNLOADING_ARCHIVE = 'TASK_DOWNLOADING_ARCHIVE',
// TASK_INITIALIZING_WORKSPACE = 'TASK_INITIALIZING_WORKSPACE',
// TASK_SKIPPING_STEPS = 'TASK_SKIPPING_STEPS',
// TASK_STEP_SKIPPED = 'TASK_STEP_SKIPPED',
// TASK_PREPARING_STEP = 'TASK_PREPARING_STEP',
// TASK_STEP = 'TASK_STEP',
// TASK_CALCULATING_DIFF = 'TASK_CALCULATING_DIFF',
// }
// const prettyOperationNames: Record<JSONLogLineOperation, string> = {
// PARSING_BATCH_SPEC: 'Parsing batch spec',
// RESOLVING_NAMESPACE: 'Resolving namespace',
// PREPARING_DOCKER_IMAGES: 'Preparing docker images',
// DETERMINING_WORKSPACE_TYPE: 'Determining workspace type',
// RESOLVING_REPOSITORIES: 'Resolving repositories',
// DETERMINING_WORKSPACES: 'Determining workspaces',
// CHECKING_CACHE: 'Checking cache',
// EXECUTING_TASKS: 'Executing tasks',
// EXECUTING_TASK: 'Executing task',
// UPLOADING_CHANGESET_SPECS: 'Uploading changeset specs',
// CREATING_BATCH_SPEC: 'Creating batch spec',
// APPLYING_BATCH_SPEC: 'Applying batch spec',
// BATCH_SPEC_EXECUTION: 'Batch spec execution',
// LOG_FILE_KEPT: 'Log file kept',
// TASK_BUILD_CHANGESET_SPECS: 'Building changeset specs',
// TASK_CALCULATING_DIFF: 'Calculating diff',
// TASK_DOWNLOADING_ARCHIVE: 'Downloading archive',
// TASK_INITIALIZING_WORKSPACE: 'Initializing workspace',
// TASK_PREPARING_STEP: 'Preparing step',
// TASK_SKIPPING_STEPS: 'Skipping steps',
// TASK_STEP: 'Running step',
// TASK_STEP_SKIPPED: 'Step skipped',
// }
// enum JSONLogLineStatus {
// STARTED = 'STARTED',
// PROGRESS = 'PROGRESS',
// SUCCESS = 'SUCCESS',
// FAILURE = 'FAILURE',
// }
// interface ExecutingTaskJSONLogLine {
// operation: JSONLogLineOperation.EXECUTING_TASK
// timestamp: string
// status: JSONLogLineStatus
// metadata: {
// task: Task
// }
// }
// type JSONLogLine =
// | {
// operation: JSONLogLineOperation
// timestamp: string
// status: JSONLogLineStatus
// }
// | ExecutingTaskJSONLogLine
// interface Step {
// run: string
// container: string
// }
// interface Task {
// repository: string
// workspace: string
// steps: Step[]
// cachedStepResultsFound: boolean
// }
// const ParsedJsonOutput: React.FunctionComponent<{ out: string }> = ({ out }) => {
// const parsed = useMemo<JSONLogLine[]>(
// () =>
// out
// .split('\n')
// .map(line => line.replace(/^std(out|err): /, ''))
// .map(line => {
// try {
// return JSON.parse(line) as JSONLogLine
// } catch (error) {
// return String(error)
// }
// })
// .filter((line): line is JSONLogLine => typeof line !== 'string'),
// [out]
// )
// const parsedExecutingTaskLines = useMemo<ExecutingTaskJSONLogLine[]>(
// () =>
// parsed.filter(
// (line): line is ExecutingTaskJSONLogLine => line.operation === JSONLogLineOperation.EXECUTING_TASK
// ),
// [parsed]
// )
// return (
// <ul className="list-group w-100 mt-3">
// {Object.values<JSONLogLineOperation>(JSONLogLineOperation).map(operation => {
// const tuple = findLogLineTuple(parsed, operation)
// if (tuple === undefined) {
// return null
// }
// const completionStatus = tuple[1]?.status
// return (
// <li className="list-group-item p-2" key={operation}>
// <div className="d-flex justify-content-between">
// <p>
// {completionStatus === JSONLogLineStatus.SUCCESS && (
// <CheckCircleIcon className="icon-inline text-success mr-1" />
// )}
// {completionStatus === JSONLogLineStatus.FAILURE && (
// <ErrorIcon className="icon-inline text-danger mr-1" />
// )}
// {prettyOperationNames[tuple[0].operation]}
// </p>
// <span>
// {formatDistance(
// parseISO(tuple[0].timestamp),
// parseISO(tuple[1]?.timestamp ?? new Date().toISOString()),
// { includeSeconds: true }
// )}
// </span>
// </div>
// {operation === JSONLogLineOperation.EXECUTING_TASKS && (
// <ParsedTaskExecutionOutput lines={parsedExecutingTaskLines} />
// )}
// </li>
// )
// })}
// </ul>
// )
// }
// const ParsedTaskExecutionOutput: React.FunctionComponent<{ lines: ExecutingTaskJSONLogLine[] }> = ({ lines }) => (
// <ul className="list-group w-100 mt-3">
// {lines.map((line, index) => {
// const repo = line.metadata.task.repository
// const key = `${repo}-${index}`
// if (line.status === JSONLogLineStatus.STARTED) {
// return (
// <li className="list-group-item p-2" key={key}>
// <InformationIcon className="icon-inline mr-1" />
// <b>{repo}</b>: Starting execution of {line.metadata?.task?.steps?.length}
// </li>
// )
// }
// if (line.status === JSONLogLineStatus.SUCCESS) {
// return (
// <li className="list-group-item p-2" key={key}>
// <CheckCircleIcon className="icon-inline text-success mr-1" />
// <b>{repo}</b>: Success! All steps executed.
// </li>
// )
// }
// if (line.status === JSONLogLineStatus.FAILURE) {
// return (
// <li className="list-group-item p-2" key={key}>
// <ErrorIcon className="icon-inline text-danger mr-1" />
// <b>{repo}</b>: Failed :(
// </li>
// )
// }
// return null
// })}
// </ul>
// )
// function findLogLine(
// lines: JSONLogLine[],
// operation: JSONLogLineOperation,
// status: JSONLogLineStatus
// ): JSONLogLine | undefined {
// return lines.find(line => line.operation === operation && line.status === status)
// }
// function findLogLineTuple(
// lines: JSONLogLine[],
// operation: JSONLogLineOperation
// ): [JSONLogLine] | [JSONLogLine, JSONLogLine] | undefined {
// const start = findLogLine(lines, operation, JSONLogLineStatus.STARTED)
// if (!start) {
// return undefined
// }
// let end = findLogLine(lines, operation, JSONLogLineStatus.SUCCESS)
// if (!end) {
// end = findLogLine(lines, operation, JSONLogLineStatus.FAILURE)
// }
// if (end) {
// return [start, end]
// }
// return [start]
// } | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { PollerLike, PollOperationState } from "@azure/core-lro";
import {
DatabaseAccountGetResults,
DatabaseAccountsListOptionalParams,
DatabaseAccountsListByResourceGroupOptionalParams,
Metric,
DatabaseAccountsListMetricsOptionalParams,
Usage,
DatabaseAccountsListUsagesOptionalParams,
MetricDefinition,
DatabaseAccountsListMetricDefinitionsOptionalParams,
DatabaseAccountsGetOptionalParams,
DatabaseAccountsGetResponse,
DatabaseAccountUpdateParameters,
DatabaseAccountsUpdateOptionalParams,
DatabaseAccountsUpdateResponse,
DatabaseAccountCreateUpdateParameters,
DatabaseAccountsCreateOrUpdateOptionalParams,
DatabaseAccountsCreateOrUpdateResponse,
DatabaseAccountsDeleteOptionalParams,
FailoverPolicies,
DatabaseAccountsFailoverPriorityChangeOptionalParams,
DatabaseAccountsListKeysOptionalParams,
DatabaseAccountsListKeysResponse,
DatabaseAccountsListConnectionStringsOptionalParams,
DatabaseAccountsListConnectionStringsResponse,
RegionForOnlineOffline,
DatabaseAccountsOfflineRegionOptionalParams,
DatabaseAccountsOnlineRegionOptionalParams,
DatabaseAccountsGetReadOnlyKeysOptionalParams,
DatabaseAccountsGetReadOnlyKeysResponse,
DatabaseAccountsListReadOnlyKeysOptionalParams,
DatabaseAccountsListReadOnlyKeysResponse,
DatabaseAccountRegenerateKeyParameters,
DatabaseAccountsRegenerateKeyOptionalParams,
DatabaseAccountsCheckNameExistsOptionalParams
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Interface representing a DatabaseAccounts. */
export interface DatabaseAccounts {
/**
* Lists all the Azure Cosmos DB database accounts available under the subscription.
* @param options The options parameters.
*/
list(
options?: DatabaseAccountsListOptionalParams
): PagedAsyncIterableIterator<DatabaseAccountGetResults>;
/**
* Lists all the Azure Cosmos DB database accounts available under the given resource group.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param options The options parameters.
*/
listByResourceGroup(
resourceGroupName: string,
options?: DatabaseAccountsListByResourceGroupOptionalParams
): PagedAsyncIterableIterator<DatabaseAccountGetResults>;
/**
* Retrieves the metrics determined by the given filter for the given database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param filter An OData filter expression that describes a subset of metrics to return. The
* parameters that can be filtered are name.value (name of the metric, can have an or of multiple
* names), startTime, endTime, and timeGrain. The supported operator is eq.
* @param options The options parameters.
*/
listMetrics(
resourceGroupName: string,
accountName: string,
filter: string,
options?: DatabaseAccountsListMetricsOptionalParams
): PagedAsyncIterableIterator<Metric>;
/**
* Retrieves the usages (most recent data) for the given database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param options The options parameters.
*/
listUsages(
resourceGroupName: string,
accountName: string,
options?: DatabaseAccountsListUsagesOptionalParams
): PagedAsyncIterableIterator<Usage>;
/**
* Retrieves metric definitions for the given database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param options The options parameters.
*/
listMetricDefinitions(
resourceGroupName: string,
accountName: string,
options?: DatabaseAccountsListMetricDefinitionsOptionalParams
): PagedAsyncIterableIterator<MetricDefinition>;
/**
* Retrieves the properties of an existing Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
accountName: string,
options?: DatabaseAccountsGetOptionalParams
): Promise<DatabaseAccountsGetResponse>;
/**
* Updates the properties of an existing Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param updateParameters The parameters to provide for the current database account.
* @param options The options parameters.
*/
beginUpdate(
resourceGroupName: string,
accountName: string,
updateParameters: DatabaseAccountUpdateParameters,
options?: DatabaseAccountsUpdateOptionalParams
): Promise<
PollerLike<
PollOperationState<DatabaseAccountsUpdateResponse>,
DatabaseAccountsUpdateResponse
>
>;
/**
* Updates the properties of an existing Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param updateParameters The parameters to provide for the current database account.
* @param options The options parameters.
*/
beginUpdateAndWait(
resourceGroupName: string,
accountName: string,
updateParameters: DatabaseAccountUpdateParameters,
options?: DatabaseAccountsUpdateOptionalParams
): Promise<DatabaseAccountsUpdateResponse>;
/**
* Creates or updates an Azure Cosmos DB database account. The "Update" method is preferred when
* performing updates on an account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param createUpdateParameters The parameters to provide for the current database account.
* @param options The options parameters.
*/
beginCreateOrUpdate(
resourceGroupName: string,
accountName: string,
createUpdateParameters: DatabaseAccountCreateUpdateParameters,
options?: DatabaseAccountsCreateOrUpdateOptionalParams
): Promise<
PollerLike<
PollOperationState<DatabaseAccountsCreateOrUpdateResponse>,
DatabaseAccountsCreateOrUpdateResponse
>
>;
/**
* Creates or updates an Azure Cosmos DB database account. The "Update" method is preferred when
* performing updates on an account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param createUpdateParameters The parameters to provide for the current database account.
* @param options The options parameters.
*/
beginCreateOrUpdateAndWait(
resourceGroupName: string,
accountName: string,
createUpdateParameters: DatabaseAccountCreateUpdateParameters,
options?: DatabaseAccountsCreateOrUpdateOptionalParams
): Promise<DatabaseAccountsCreateOrUpdateResponse>;
/**
* Deletes an existing Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param options The options parameters.
*/
beginDelete(
resourceGroupName: string,
accountName: string,
options?: DatabaseAccountsDeleteOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Deletes an existing Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param options The options parameters.
*/
beginDeleteAndWait(
resourceGroupName: string,
accountName: string,
options?: DatabaseAccountsDeleteOptionalParams
): Promise<void>;
/**
* Changes the failover priority for the Azure Cosmos DB database account. A failover priority of 0
* indicates a write region. The maximum value for a failover priority = (total number of regions - 1).
* Failover priority values must be unique for each of the regions in which the database account
* exists.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param failoverParameters The new failover policies for the database account.
* @param options The options parameters.
*/
beginFailoverPriorityChange(
resourceGroupName: string,
accountName: string,
failoverParameters: FailoverPolicies,
options?: DatabaseAccountsFailoverPriorityChangeOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Changes the failover priority for the Azure Cosmos DB database account. A failover priority of 0
* indicates a write region. The maximum value for a failover priority = (total number of regions - 1).
* Failover priority values must be unique for each of the regions in which the database account
* exists.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param failoverParameters The new failover policies for the database account.
* @param options The options parameters.
*/
beginFailoverPriorityChangeAndWait(
resourceGroupName: string,
accountName: string,
failoverParameters: FailoverPolicies,
options?: DatabaseAccountsFailoverPriorityChangeOptionalParams
): Promise<void>;
/**
* Lists the access keys for the specified Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param options The options parameters.
*/
listKeys(
resourceGroupName: string,
accountName: string,
options?: DatabaseAccountsListKeysOptionalParams
): Promise<DatabaseAccountsListKeysResponse>;
/**
* Lists the connection strings for the specified Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param options The options parameters.
*/
listConnectionStrings(
resourceGroupName: string,
accountName: string,
options?: DatabaseAccountsListConnectionStringsOptionalParams
): Promise<DatabaseAccountsListConnectionStringsResponse>;
/**
* Offline the specified region for the specified Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param regionParameterForOffline Cosmos DB region to offline for the database account.
* @param options The options parameters.
*/
beginOfflineRegion(
resourceGroupName: string,
accountName: string,
regionParameterForOffline: RegionForOnlineOffline,
options?: DatabaseAccountsOfflineRegionOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Offline the specified region for the specified Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param regionParameterForOffline Cosmos DB region to offline for the database account.
* @param options The options parameters.
*/
beginOfflineRegionAndWait(
resourceGroupName: string,
accountName: string,
regionParameterForOffline: RegionForOnlineOffline,
options?: DatabaseAccountsOfflineRegionOptionalParams
): Promise<void>;
/**
* Online the specified region for the specified Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param regionParameterForOnline Cosmos DB region to online for the database account.
* @param options The options parameters.
*/
beginOnlineRegion(
resourceGroupName: string,
accountName: string,
regionParameterForOnline: RegionForOnlineOffline,
options?: DatabaseAccountsOnlineRegionOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Online the specified region for the specified Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param regionParameterForOnline Cosmos DB region to online for the database account.
* @param options The options parameters.
*/
beginOnlineRegionAndWait(
resourceGroupName: string,
accountName: string,
regionParameterForOnline: RegionForOnlineOffline,
options?: DatabaseAccountsOnlineRegionOptionalParams
): Promise<void>;
/**
* Lists the read-only access keys for the specified Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param options The options parameters.
*/
getReadOnlyKeys(
resourceGroupName: string,
accountName: string,
options?: DatabaseAccountsGetReadOnlyKeysOptionalParams
): Promise<DatabaseAccountsGetReadOnlyKeysResponse>;
/**
* Lists the read-only access keys for the specified Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param options The options parameters.
*/
listReadOnlyKeys(
resourceGroupName: string,
accountName: string,
options?: DatabaseAccountsListReadOnlyKeysOptionalParams
): Promise<DatabaseAccountsListReadOnlyKeysResponse>;
/**
* Regenerates an access key for the specified Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param keyToRegenerate The name of the key to regenerate.
* @param options The options parameters.
*/
beginRegenerateKey(
resourceGroupName: string,
accountName: string,
keyToRegenerate: DatabaseAccountRegenerateKeyParameters,
options?: DatabaseAccountsRegenerateKeyOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Regenerates an access key for the specified Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param keyToRegenerate The name of the key to regenerate.
* @param options The options parameters.
*/
beginRegenerateKeyAndWait(
resourceGroupName: string,
accountName: string,
keyToRegenerate: DatabaseAccountRegenerateKeyParameters,
options?: DatabaseAccountsRegenerateKeyOptionalParams
): Promise<void>;
/**
* Checks that the Azure Cosmos DB account name already exists. A valid account name may contain only
* lowercase letters, numbers, and the '-' character, and must be between 3 and 50 characters.
* @param accountName Cosmos DB database account name.
* @param options The options parameters.
*/
checkNameExists(
accountName: string,
options?: DatabaseAccountsCheckNameExistsOptionalParams
): Promise<void>;
} | the_stack |
import {ChunkState} from 'neuroglancer/chunk_manager/base';
import {Chunk, ChunkManager, ChunkSource, WithParameters} from 'neuroglancer/chunk_manager/frontend';
import {CredentialsManager} from 'neuroglancer/credentials_provider';
import {getCredentialsProviderCounterpart, WithCredentialsProvider} from 'neuroglancer/credentials_provider/chunk_source_frontend';
import {PickState, VisibleLayerInfo} from 'neuroglancer/layer';
import {PerspectivePanel} from 'neuroglancer/perspective_view/panel';
import {PerspectiveViewRenderContext, PerspectiveViewRenderLayer} from 'neuroglancer/perspective_view/render_layer';
import {WatchableRenderLayerTransform} from 'neuroglancer/render_coordinate_transform';
import {ThreeDimensionalRenderLayerAttachmentState, update3dRenderLayerAttachment} from 'neuroglancer/renderlayer';
import {GET_SINGLE_MESH_INFO_RPC_ID, SINGLE_MESH_CHUNK_KEY, SINGLE_MESH_LAYER_RPC_ID, SingleMeshInfo, SingleMeshSourceParametersWithInfo, VertexAttributeInfo} from 'neuroglancer/single_mesh/base';
import {WatchableValue} from 'neuroglancer/trackable_value';
import {DataType} from 'neuroglancer/util/data_type';
import {mat4, vec3} from 'neuroglancer/util/geom';
import {parseSpecialUrl, SpecialProtocolCredentials} from 'neuroglancer/util/special_protocol_request';
import {withSharedVisibility} from 'neuroglancer/visibility_priority/frontend';
import {Buffer} from 'neuroglancer/webgl/buffer';
import {glsl_COLORMAPS} from 'neuroglancer/webgl/colormaps';
import {GL} from 'neuroglancer/webgl/context';
import {makeTrackableFragmentMain, makeWatchableShaderError, parameterizedEmitterDependentShaderGetter, shaderCodeWithLineDirective} from 'neuroglancer/webgl/dynamic_shader';
import {CountingBuffer, countingBufferShaderModule, disableCountingBuffer, getCountingBuffer, IndexBufferAttributeHelper, makeIndexBuffer} from 'neuroglancer/webgl/index_emulation';
import {ShaderBuilder, ShaderModule, ShaderProgram, ShaderSamplerType} from 'neuroglancer/webgl/shader';
import {getShaderType} from 'neuroglancer/webgl/shader_lib';
import {addControlsToBuilder, getFallbackBuilderState, parseShaderUiControls, setControlsInShader, ShaderControlsBuilderState, ShaderControlState} from 'neuroglancer/webgl/shader_ui_controls';
import {computeTextureFormat, getSamplerPrefixForDataType, OneDimensionalTextureAccessHelper, setOneDimensionalTextureData, TextureFormat} from 'neuroglancer/webgl/texture_access';
import {SharedObject} from 'neuroglancer/worker_rpc';
const DEFAULT_FRAGMENT_MAIN = `void main() {
emitGray();
}
`;
export class SingleMeshDisplayState {
shaderError = makeWatchableShaderError();
fragmentMain = makeTrackableFragmentMain(DEFAULT_FRAGMENT_MAIN);
shaderControlState = new ShaderControlState(this.fragmentMain);
}
export function getShaderAttributeType(info: {dataType: DataType, numComponents: number}) {
return getShaderType(info.dataType, info.numComponents);
}
const vertexAttributeSamplerSymbols: Symbol[] = [];
const vertexPositionTextureFormat = computeTextureFormat(new TextureFormat(), DataType.FLOAT32, 3);
const vertexNormalTextureFormat = vertexPositionTextureFormat;
function makeValidIdentifier(x: string) {
return x.split(/[^a-zA-Z0-9]+/).filter(y => y).join('_');
}
export function pickAttributeNames(existingNames: string[]) {
const seenNames = new Set<string>();
let result: string[] = [];
for (let existingName of existingNames) {
let name = makeValidIdentifier(existingName);
let suffix = '';
let suffixNumber = 0;
while (seenNames.has(name + suffix)) {
suffix = '' + (++suffixNumber);
}
result.push(name + suffix);
}
return result;
}
export class SingleMeshShaderManager {
private tempLightVec = new Float32Array(4);
private textureAccessHelper = new OneDimensionalTextureAccessHelper('vertexData');
private indexBufferHelper = new IndexBufferAttributeHelper('vertexIndex');
constructor(public attributeNames: string[], public attributeInfo: VertexAttributeInfo[]) {}
defineAttributeAccess(builder: ShaderBuilder, vertexIndexVariable: string) {
let {textureAccessHelper} = this;
textureAccessHelper.defineShader(builder);
const {attributeNames} = this;
let numAttributes = 2 + attributeNames.length;
for (let j = vertexAttributeSamplerSymbols.length; j < numAttributes; ++j) {
vertexAttributeSamplerSymbols[j] =
Symbol(`SingleMeshShaderManager.vertexAttributeTextureUnit${j}`);
}
numAttributes = 0;
builder.addTextureSampler(
`sampler2D`, 'uVertexAttributeSampler0', vertexAttributeSamplerSymbols[numAttributes++]);
builder.addTextureSampler(
`sampler2D`, 'uVertexAttributeSampler1', vertexAttributeSamplerSymbols[numAttributes++]);
builder.addVertexCode(textureAccessHelper.getAccessor(
'readVertexPosition', 'uVertexAttributeSampler0', DataType.FLOAT32, 3));
builder.addVertexCode(textureAccessHelper.getAccessor(
'readVertexNormal', 'uVertexAttributeSampler1', DataType.FLOAT32, 3));
let vertexMain = `
vec3 vertexPosition = readVertexPosition(${vertexIndexVariable});
vec3 vertexNormal = readVertexNormal(${vertexIndexVariable});
`;
this.attributeInfo.forEach((info, i) => {
builder.addTextureSampler(
`${getSamplerPrefixForDataType(info.dataType)}sampler2D` as ShaderSamplerType,
`uVertexAttributeSampler${numAttributes}`, vertexAttributeSamplerSymbols[numAttributes]);
const attributeType = getShaderAttributeType(info);
builder.addVarying(`highp ${attributeType}`, `vCustom${i}`);
builder.addFragmentCode(`
#define ${attributeNames[i]} vCustom${i}
`);
builder.addVertexCode(textureAccessHelper.getAccessor(
`readAttribute${i}`, `uVertexAttributeSampler${numAttributes}`, info.dataType,
info.numComponents));
vertexMain += `vCustom${i} = readAttribute${i}(${vertexIndexVariable});\n`;
++numAttributes;
});
builder.addVertexMain(vertexMain);
}
defineShader(builder: ShaderBuilder) {
builder.require(countingBufferShaderModule);
this.indexBufferHelper.defineShader(builder);
builder.addVarying('highp float', 'vLightingFactor');
builder.addUniform('highp vec4', 'uLightDirection');
builder.addUniform('highp vec4', 'uColor');
builder.addUniform('highp mat4', 'uModelMatrix');
builder.addUniform('highp mat4', 'uProjection');
builder.addUniform('highp uint', 'uPickID');
builder.addVarying('highp uint', 'vPickID', 'flat');
builder.addVertexMain(`
uint triangleIndex = getPrimitiveIndex() / 3u;
vPickID = uPickID + triangleIndex;
`);
builder.addFragmentCode(`
void emitPremultipliedRGBA(vec4 color) {
emit(vec4(color.rgb * vLightingFactor, color.a), vPickID);
}
void emitRGBA(vec4 color) {
color = clamp(color, 0.0, 1.0);
color.xyz *= color.a;
emitPremultipliedRGBA(color);
}
void emitRGB(vec3 color) {
emitRGBA(vec4(color, 1.0));
}
void emitGray() {
emitRGB(vec3(1.0, 1.0, 1.0));
}
`);
builder.addFragmentCode(glsl_COLORMAPS);
// Make sure defineAttributeAccess is the last thing that adds fragment code prior to
// this.fragmentMain, so that the #define attributes don't mess anything up.
this.defineAttributeAccess(builder, 'vertexIndex');
builder.addVertexMain(`
gl_Position = uProjection * (uModelMatrix * vec4(vertexPosition, 1.0));
vec3 normal = normalize((uModelMatrix * vec4(vertexNormal, 0.0)).xyz);
vLightingFactor = abs(dot(normal, uLightDirection.xyz)) + uLightDirection.w;
`);
}
beginLayer(gl: GL, shader: ShaderProgram, renderContext: PerspectiveViewRenderContext) {
const {lightDirection, ambientLighting, directionalLighting, projectionParameters} =
renderContext;
const {viewProjectionMat} = projectionParameters;
gl.uniformMatrix4fv(shader.uniform('uProjection'), false, viewProjectionMat);
let lightVec = <vec3>this.tempLightVec;
vec3.scale(lightVec, lightDirection, directionalLighting);
lightVec[3] = ambientLighting;
gl.uniform4fv(shader.uniform('uLightDirection'), lightVec);
}
setPickID(gl: GL, shader: ShaderProgram, pickID: number) {
gl.uniform1ui(shader.uniform('uPickID'), pickID);
}
beginObject(gl: GL, shader: ShaderProgram, objectToDataMatrix: mat4) {
gl.uniformMatrix4fv(shader.uniform('uModelMatrix'), false, objectToDataMatrix);
}
bindVertexData(gl: GL, shader: ShaderProgram, data: VertexChunkData) {
let index = 0;
const bindTexture = (texture: WebGLTexture|null) => {
const textureUnit = WebGL2RenderingContext.TEXTURE0 +
shader.textureUnit(vertexAttributeSamplerSymbols[index]);
gl.activeTexture(textureUnit);
gl.bindTexture(WebGL2RenderingContext.TEXTURE_2D, texture);
++index;
};
bindTexture(data.vertexTexture);
bindTexture(data.normalTexture);
const {attributeNames} = this;
data.vertexAttributeTextures.forEach((texture, i) => {
if (attributeNames[i] !== undefined) {
bindTexture(texture);
}
});
}
disableVertexData(gl: GL, shader: ShaderProgram) {
let numTextures = 2;
let numVertexAttributes = this.attributeInfo.length;
let {attributeNames} = this;
for (let i = 0; i < numVertexAttributes; ++i) {
if (attributeNames[i] !== undefined) {
++numTextures;
}
}
for (let i = 0; i < numTextures; ++i) {
let curTextureUnit =
shader.textureUnit(vertexAttributeSamplerSymbols[i]) + WebGL2RenderingContext.TEXTURE0;
gl.activeTexture(curTextureUnit);
gl.bindTexture(gl.TEXTURE_2D, null);
}
}
drawFragment(
gl: GL, shader: ShaderProgram, chunk: SingleMeshChunk, countingBuffer: CountingBuffer) {
countingBuffer.ensure(chunk.numIndices).bind(shader);
this.bindVertexData(gl, shader, chunk.vertexData);
this.indexBufferHelper.bind(chunk.indexBuffer, shader);
gl.drawArrays(WebGL2RenderingContext.TRIANGLES, 0, chunk.numIndices);
}
endLayer(gl: GL, shader: ShaderProgram) {
disableCountingBuffer(gl, shader);
this.indexBufferHelper.disable(shader);
this.disableVertexData(gl, shader);
}
}
export class VertexChunkData {
vertexPositions: Float32Array;
vertexNormals: Float32Array;
vertexTexture: WebGLTexture|null;
normalTexture: WebGLTexture|null;
vertexAttributes: Float32Array[];
vertexAttributeTextures: (WebGLTexture|null)[];
copyToGPU(gl: GL, attributeFormats: TextureFormat[]) {
const getBufferTexture = (data: Float32Array, format: TextureFormat) => {
let texture = gl.createTexture();
gl.bindTexture(WebGL2RenderingContext.TEXTURE_2D, texture);
setOneDimensionalTextureData(gl, format, data);
return texture;
};
this.vertexTexture = getBufferTexture(this.vertexPositions, vertexPositionTextureFormat);
this.normalTexture = getBufferTexture(this.vertexNormals, vertexNormalTextureFormat);
this.vertexAttributeTextures =
this.vertexAttributes.map((data, i) => getBufferTexture(data, attributeFormats[i]));
gl.bindTexture(WebGL2RenderingContext.TEXTURE_2D, null);
}
freeGPUMemory(gl: GL) {
gl.deleteTexture(this.vertexTexture);
gl.deleteTexture(this.normalTexture);
let {vertexAttributeTextures} = this;
for (const buffer of vertexAttributeTextures) {
gl.deleteTexture(buffer);
}
vertexAttributeTextures.length = 0;
}
}
export class SingleMeshChunk extends Chunk {
source: SingleMeshSource;
indexBuffer: Buffer;
numIndices: number;
indices: Uint32Array;
vertexData: VertexChunkData;
constructor(source: SingleMeshSource, x: any) {
super(source);
const vertexData = this.vertexData = new VertexChunkData();
vertexData.vertexPositions = x['vertexPositions'];
vertexData.vertexNormals = x['vertexNormals'];
vertexData.vertexAttributes = x['vertexAttributes'];
let indices = this.indices = x['indices'];
this.numIndices = indices.length;
}
copyToGPU(gl: GL) {
super.copyToGPU(gl);
this.vertexData.copyToGPU(gl, this.source.attributeTextureFormats);
this.indexBuffer = makeIndexBuffer(gl, this.indices);
}
freeGPUMemory(gl: GL) {
super.freeGPUMemory(gl);
this.vertexData.freeGPUMemory(gl);
this.indexBuffer.dispose();
}
}
export function getAttributeTextureFormats(vertexAttributes: VertexAttributeInfo[]) {
return vertexAttributes.map(
x => computeTextureFormat(new TextureFormat(), x.dataType, x.numComponents));
}
export class SingleMeshSource extends
(WithParameters(WithCredentialsProvider<SpecialProtocolCredentials>()(ChunkSource), SingleMeshSourceParametersWithInfo)) {
attributeTextureFormats = getAttributeTextureFormats(this.info.vertexAttributes);
get info() {
return this.parameters.info;
}
getChunk(x: any) {
return new SingleMeshChunk(this, x);
}
}
const SharedObjectWithSharedVisibility = withSharedVisibility(SharedObject);
class SingleMeshLayerSharedObject extends SharedObjectWithSharedVisibility {}
export class SingleMeshLayer extends
PerspectiveViewRenderLayer<ThreeDimensionalRenderLayerAttachmentState> {
private shaderManager = new SingleMeshShaderManager(
pickAttributeNames(this.source.info.vertexAttributes.map(a => a.name)),
this.source.info.vertexAttributes);
private shaders = new Map<ShaderModule, ShaderProgram|null>();
private sharedObject = this.registerDisposer(new SingleMeshLayerSharedObject());
private shaderGetter = parameterizedEmitterDependentShaderGetter(this, this.gl, {
memoizeKey: {t: `single_mesh/RenderLayer`, attributes: this.source.info.vertexAttributes},
fallbackParameters:
new WatchableValue(getFallbackBuilderState(parseShaderUiControls(DEFAULT_FRAGMENT_MAIN))),
parameters: this.displayState.shaderControlState.builderState,
encodeParameters: p => p.key,
shaderError: this.displayState.shaderError,
defineShader:
(builder: ShaderBuilder, shaderBuilderState: ShaderControlsBuilderState) => {
if (shaderBuilderState.parseResult.errors.length !== 0) {
throw new Error('Invalid UI control specification');
}
addControlsToBuilder(shaderBuilderState, builder);
this.shaderManager.defineShader(builder);
builder.setFragmentMainFunction(
shaderCodeWithLineDirective(shaderBuilderState.parseResult.code));
},
});
protected countingBuffer = this.registerDisposer(getCountingBuffer(this.gl));
constructor(
public source: SingleMeshSource, public displayState: SingleMeshDisplayState,
public transform: WatchableRenderLayerTransform) {
super();
this.registerDisposer(
displayState.shaderControlState.parseResult.changed.add(this.redrawNeeded.dispatch));
this.registerDisposer(displayState.shaderControlState.changed.add(this.redrawNeeded.dispatch));
this.registerDisposer(transform.changed.add(this.redrawNeeded.dispatch));
const {sharedObject} = this;
sharedObject.visibility.add(this.visibility);
sharedObject.RPC_TYPE_ID = SINGLE_MESH_LAYER_RPC_ID;
sharedObject.initializeCounterpart(source.chunkManager.rpc!, {
'chunkManager': source.chunkManager.rpcId,
'source': source.addCounterpartRef(),
});
}
private disposeShaders() {
let {shaders} = this;
for (let shader of shaders.values()) {
if (shader !== null) {
shader.dispose();
}
}
shaders.clear();
}
disposed() {
this.disposeShaders();
super.disposed();
}
get isTransparent() {
return this.displayState.fragmentMain.value.match(/emitRGBA|emitPremultipliedRGBA/) !== null;
}
get gl() {
return this.source.gl;
}
isReady() {
let chunk = <SingleMeshChunk|undefined>this.source.chunks.get(SINGLE_MESH_CHUNK_KEY);
if (chunk === undefined || chunk.state !== ChunkState.GPU_MEMORY) {
return false;
}
return true;
}
draw(
renderContext: PerspectiveViewRenderContext,
attachment: VisibleLayerInfo<PerspectivePanel, ThreeDimensionalRenderLayerAttachmentState>) {
if (!renderContext.emitColor && renderContext.alreadyEmittedPickID) {
// No need for a separate pick ID pass.
return;
}
const modelMatrix = update3dRenderLayerAttachment(
this.transform.value, renderContext.projectionParameters.displayDimensionRenderInfo,
attachment);
if (modelMatrix === undefined) return;
let chunk = <SingleMeshChunk|undefined>this.source.chunks.get(SINGLE_MESH_CHUNK_KEY);
if (chunk === undefined || chunk.state !== ChunkState.GPU_MEMORY) {
return;
}
const shaderResult = this.shaderGetter(renderContext.emitter);
const {shader, parameters} = shaderResult;
if (shader === null) {
return;
}
const {gl} = this;
const shaderManager = this.shaderManager!;
shader.bind();
shaderManager.beginLayer(gl, shader, renderContext);
setControlsInShader(
gl, shader, this.displayState.shaderControlState, parameters.parseResult.controls);
let {pickIDs} = renderContext;
shaderManager.beginObject(gl, shader, modelMatrix);
if (renderContext.emitPickID) {
shaderManager.setPickID(gl, shader, pickIDs.register(this, chunk.numIndices / 3));
}
shaderManager.drawFragment(gl, shader, chunk, this.countingBuffer);
shaderManager.endLayer(gl, shader);
}
transformPickedValue(pickState: PickState) {
const {pickedOffset} = pickState;
let chunk = <SingleMeshChunk|undefined>this.source.chunks.get(SINGLE_MESH_CHUNK_KEY);
if (chunk === undefined) {
return undefined;
}
let startIndex = pickedOffset * 3;
let {indices} = chunk;
if (startIndex >= indices.length) {
return undefined;
}
// FIXME: compute closest vertex position. For now just use first vertex.
let vertexIndex = indices[startIndex];
let values: string[] = [];
const {attributeNames} = this.shaderManager;
chunk.vertexData.vertexAttributes.forEach((attributes, i) => {
const attributeName = attributeNames[i];
if (attributeName !== undefined) {
values.push(`${attributeName}=${attributes[vertexIndex].toPrecision(6)}`);
}
});
return values.join(', ');
}
}
function getSingleMeshInfo(
chunkManager: ChunkManager, credentialsManager: CredentialsManager, url: string) {
return chunkManager.memoize.getUncounted({type: 'single_mesh:getMeshInfo', url}, async () => {
const {url: parsedUrl, credentialsProvider} = parseSpecialUrl(url, credentialsManager);
const info =
await chunkManager.rpc!.promiseInvoke<SingleMeshInfo>(GET_SINGLE_MESH_INFO_RPC_ID, {
'chunkManager': chunkManager.addCounterpartRef(),
credentialsProvider: getCredentialsProviderCounterpart<SpecialProtocolCredentials>(
chunkManager, credentialsProvider),
'parameters': {meshSourceUrl: parsedUrl}
});
return {info, url: parsedUrl, credentialsProvider};
});
}
export async function getSingleMeshSource(
chunkManager: ChunkManager, credentialsManager: CredentialsManager, url: string) {
const {info, url: parsedUrl, credentialsProvider} =
await getSingleMeshInfo(chunkManager, credentialsManager, url);
return chunkManager.getChunkSource(
SingleMeshSource, {credentialsProvider, parameters: {meshSourceUrl: parsedUrl, info}});
} | the_stack |
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { HttpResponse } from '@angular/common/http';
import { of } from 'rxjs';
import { ActivatedRoute, UrlSegment } from '@angular/router';
import { ArtemisTestModule } from '../../test.module';
import { ModelingExerciseUpdateComponent } from 'app/exercises/modeling/manage/modeling-exercise-update.component';
import { ModelingExerciseService } from 'app/exercises/modeling/manage/modeling-exercise.service';
import { ModelingExercise, UMLDiagramType } from 'app/entities/modeling-exercise.model';
import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';
import { LocalStorageService, SessionStorageService } from 'ngx-webstorage';
import { MockActivatedRoute } from '../../helpers/mocks/activated-route/mock-activated-route';
import { Course } from 'app/entities/course.model';
import { ExerciseGroup } from 'app/entities/exercise-group.model';
import { Exam } from 'app/entities/exam.model';
import dayjs from 'dayjs';
import { TranslateService } from '@ngx-translate/core';
import { MockProvider } from 'ng-mocks';
import { CourseManagementService } from 'app/course/manage/course-management.service';
import { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';
import { AssessmentType } from 'app/entities/assessment-type.model';
describe('ModelingExercise Management Update Component', () => {
let comp: ModelingExerciseUpdateComponent;
let fixture: ComponentFixture<ModelingExerciseUpdateComponent>;
let service: ModelingExerciseService;
let courseService: CourseManagementService;
let exerciseService: ExerciseService;
const categories = [{ category: 'testCat' }, { category: 'testCat2' }];
const categoriesStringified = categories.map((cat) => JSON.stringify(cat));
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ArtemisTestModule],
declarations: [ModelingExerciseUpdateComponent],
providers: [
{ provide: LocalStorageService, useClass: MockSyncStorage },
{ provide: SessionStorageService, useClass: MockSyncStorage },
{ provide: ActivatedRoute, useValue: new MockActivatedRoute() },
MockProvider(TranslateService),
],
})
.overrideTemplate(ModelingExerciseUpdateComponent, '')
.compileComponents();
fixture = TestBed.createComponent(ModelingExerciseUpdateComponent);
comp = fixture.componentInstance;
service = fixture.debugElement.injector.get(ModelingExerciseService);
courseService = fixture.debugElement.injector.get(CourseManagementService);
exerciseService = fixture.debugElement.injector.get(ExerciseService);
});
describe('save', () => {
describe('new exercise', () => {
const course = { id: 1 } as Course;
const modelingExercise = new ModelingExercise(UMLDiagramType.ClassDiagram, undefined, undefined);
modelingExercise.course = course;
beforeEach(() => {
const route = TestBed.inject(ActivatedRoute);
route.data = of({ modelingExercise });
route.url = of([{ path: 'exercise-groups' } as UrlSegment]);
});
it('Should call create service on save for new entity', fakeAsync(() => {
// GIVEN
comp.ngOnInit();
const entity = { ...modelingExercise };
jest.spyOn(service, 'create').mockReturnValue(of(new HttpResponse({ body: entity })));
// WHEN
comp.save();
tick(1000); // simulate async
// THEN
expect(service.create).toHaveBeenCalledWith(entity);
expect(comp.isSaving).toEqual(false);
}));
});
describe('existing exercise', () => {
const course = { id: 1 } as Course;
const modelingExercise = new ModelingExercise(UMLDiagramType.ClassDiagram, undefined, undefined);
modelingExercise.course = course;
modelingExercise.id = 123;
beforeEach(() => {
const route = TestBed.inject(ActivatedRoute);
route.data = of({ modelingExercise });
route.url = of([{ path: 'exercise-groups' } as UrlSegment]);
});
it('Should call update service on save for existing entity', fakeAsync(() => {
// GIVEN
comp.ngOnInit();
const entity = { ...modelingExercise };
jest.spyOn(service, 'update').mockReturnValue(of(new HttpResponse({ body: entity })));
// WHEN
comp.save();
tick(); // simulate async
// THEN
expect(service.update).toHaveBeenCalledWith(entity, {});
expect(comp.isSaving).toEqual(false);
}));
});
});
describe('ngOnInit in import mode: Course to Course', () => {
const course = new Course();
course.id = 123;
const modelingExercise = new ModelingExercise(UMLDiagramType.ClassDiagram, course, undefined);
modelingExercise.id = 1;
modelingExercise.releaseDate = dayjs();
modelingExercise.dueDate = dayjs();
modelingExercise.assessmentDueDate = dayjs();
const courseId = 1;
beforeEach(() => {
const route = TestBed.inject(ActivatedRoute);
route.params = of({ courseId });
route.url = of([{ path: 'import' } as UrlSegment]);
route.data = of({ modelingExercise });
});
it('Should set isImport and remove all dates', fakeAsync(() => {
jest.spyOn(courseService, 'findAllCategoriesOfCourse').mockReturnValue(of(new HttpResponse({ body: categoriesStringified })));
// WHEN
comp.ngOnInit();
tick(); // simulate async
// THEN
expect(comp.isImport).toEqual(true);
expect(comp.isExamMode).toEqual(false);
expect(comp.modelingExercise.assessmentDueDate).toEqual(undefined);
expect(comp.modelingExercise.releaseDate).toEqual(undefined);
expect(comp.modelingExercise.dueDate).toEqual(undefined);
expect(courseService.findAllCategoriesOfCourse).toHaveBeenLastCalledWith(course.id);
expect(comp.existingCategories).toEqual(categories);
}));
});
describe('ngOnInit in import mode: Exam to Course', () => {
const exerciseGroup = new ExerciseGroup();
exerciseGroup.exam = new Exam();
exerciseGroup.exam.course = new Course();
exerciseGroup.exam.course.id = 1;
const modelingExercise = new ModelingExercise(UMLDiagramType.ClassDiagram, undefined, exerciseGroup);
modelingExercise.id = 1;
modelingExercise.releaseDate = dayjs();
modelingExercise.dueDate = dayjs();
modelingExercise.assessmentDueDate = dayjs();
const courseId = 1;
beforeEach(() => {
const route = TestBed.inject(ActivatedRoute);
route.params = of({ courseId });
route.url = of([{ path: 'import' } as UrlSegment]);
route.data = of({ modelingExercise });
});
it('Should set isImport and remove all dates', fakeAsync(() => {
jest.spyOn(courseService, 'findAllCategoriesOfCourse').mockReturnValue(of(new HttpResponse({ body: categoriesStringified })));
// WHEN
comp.ngOnInit();
tick(); // simulate async
// THEN
expect(comp.isImport).toEqual(true);
expect(comp.isExamMode).toEqual(false);
expect(comp.modelingExercise.assessmentDueDate).toEqual(undefined);
expect(comp.modelingExercise.releaseDate).toEqual(undefined);
expect(comp.modelingExercise.dueDate).toEqual(undefined);
expect(courseService.findAllCategoriesOfCourse).toHaveBeenLastCalledWith(exerciseGroup!.exam!.course!.id);
expect(comp.existingCategories).toEqual(categories);
}));
});
describe('ngOnInit in import mode: Course to Exam', () => {
const modelingExercise = new ModelingExercise(UMLDiagramType.ClassDiagram, new Course(), undefined);
modelingExercise.id = 1;
modelingExercise.releaseDate = dayjs();
modelingExercise.dueDate = dayjs();
modelingExercise.assessmentDueDate = dayjs();
const groupId = 1;
beforeEach(() => {
const route = TestBed.inject(ActivatedRoute);
route.params = of({ groupId });
route.url = of([{ path: 'exercise-groups' } as UrlSegment, { path: 'import' } as UrlSegment]);
route.data = of({ modelingExercise });
});
it('Should set isImport and isExamMode and remove all dates', fakeAsync(() => {
// WHEN
comp.ngOnInit();
tick(); // simulate async
// THEN
expect(comp.isImport).toEqual(true);
expect(comp.isExamMode).toEqual(true);
expect(comp.modelingExercise.course).toEqual(undefined);
expect(comp.modelingExercise.assessmentDueDate).toEqual(undefined);
expect(comp.modelingExercise.releaseDate).toEqual(undefined);
expect(comp.modelingExercise.dueDate).toEqual(undefined);
}));
});
describe('ngOnInit in import mode: Exam to Exam', () => {
const exerciseGroup = new ExerciseGroup();
const modelingExercise = new ModelingExercise(UMLDiagramType.ClassDiagram, undefined, exerciseGroup);
modelingExercise.id = 1;
modelingExercise.releaseDate = dayjs();
modelingExercise.dueDate = dayjs();
modelingExercise.assessmentDueDate = dayjs();
const groupId = 1;
beforeEach(() => {
const route = TestBed.inject(ActivatedRoute);
route.params = of({ groupId });
route.url = of([{ path: 'exercise-groups' } as UrlSegment, { path: 'import' } as UrlSegment]);
route.data = of({ modelingExercise });
});
it('Should set isImport and isExamMode and remove all dates', fakeAsync(() => {
// WHEN
comp.ngOnInit();
tick(); // simulate async
// THEN
expect(comp.isImport).toEqual(true);
expect(comp.isExamMode).toEqual(true);
expect(comp.modelingExercise.assessmentDueDate).toEqual(undefined);
expect(comp.modelingExercise.releaseDate).toEqual(undefined);
expect(comp.modelingExercise.dueDate).toEqual(undefined);
}));
});
it('should update categories with given ones', () => {
const modelingExercise = new ModelingExercise(UMLDiagramType.ClassDiagram, undefined, undefined);
modelingExercise.categories = categories;
comp.modelingExercise = modelingExercise;
const newCategories = [{ category: 'newCat1' }, { category: 'newCat2' }];
comp.updateCategories(newCategories);
expect(comp.modelingExercise.categories).toEqual(newCategories);
});
it('should call exercise service to validate date', () => {
const modelingExercise = new ModelingExercise(UMLDiagramType.ClassDiagram, undefined, undefined);
comp.modelingExercise = modelingExercise;
jest.spyOn(exerciseService, 'validateDate');
comp.validateDate();
expect(exerciseService.validateDate).toHaveBeenCalledWith(modelingExercise);
});
it('should set assessmentType to manual in exam mode', () => {
comp.modelingExercise = new ModelingExercise(UMLDiagramType.ClassDiagram, undefined, undefined);
comp.isExamMode = true;
comp.diagramTypeChanged();
expect(comp.modelingExercise.assessmentType).toEqual(AssessmentType.SEMI_AUTOMATIC);
});
}); | the_stack |
import {Request} from '../lib/request';
import {Response} from '../lib/response';
import {AWSError} from '../lib/error';
import {Service} from '../lib/service';
import {WaiterConfiguration} from '../lib/service';
import {ServiceConfigurationOptions} from '../lib/service';
import {ConfigBase as Config} from '../lib/config-base';
interface Blob {}
declare class Route53RecoveryControlConfig extends Service {
/**
* Constructs a service object. This object has one method for each API operation.
*/
constructor(options?: Route53RecoveryControlConfig.Types.ClientConfiguration)
config: Config & Route53RecoveryControlConfig.Types.ClientConfiguration;
/**
* Create a new cluster. A cluster is a set of redundant Regional endpoints against which you can run API calls to update or get the state of one or more routing controls. Each cluster has a name, status, Amazon Resource Name (ARN), and an array of the five cluster endpoints (one for each supported Amazon Web Services Region) that you can use with API calls to the cluster data plane.
*/
createCluster(params: Route53RecoveryControlConfig.Types.CreateClusterRequest, callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.CreateClusterResponse) => void): Request<Route53RecoveryControlConfig.Types.CreateClusterResponse, AWSError>;
/**
* Create a new cluster. A cluster is a set of redundant Regional endpoints against which you can run API calls to update or get the state of one or more routing controls. Each cluster has a name, status, Amazon Resource Name (ARN), and an array of the five cluster endpoints (one for each supported Amazon Web Services Region) that you can use with API calls to the cluster data plane.
*/
createCluster(callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.CreateClusterResponse) => void): Request<Route53RecoveryControlConfig.Types.CreateClusterResponse, AWSError>;
/**
* Creates a new control panel. A control panel represents a group of routing controls that can be changed together in a single transaction. You can use a control panel to centrally view the operational status of applications across your organization, and trigger multi-app failovers in a single transaction, for example, to fail over an Availability Zone or Amazon Web Services Region.
*/
createControlPanel(params: Route53RecoveryControlConfig.Types.CreateControlPanelRequest, callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.CreateControlPanelResponse) => void): Request<Route53RecoveryControlConfig.Types.CreateControlPanelResponse, AWSError>;
/**
* Creates a new control panel. A control panel represents a group of routing controls that can be changed together in a single transaction. You can use a control panel to centrally view the operational status of applications across your organization, and trigger multi-app failovers in a single transaction, for example, to fail over an Availability Zone or Amazon Web Services Region.
*/
createControlPanel(callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.CreateControlPanelResponse) => void): Request<Route53RecoveryControlConfig.Types.CreateControlPanelResponse, AWSError>;
/**
* Creates a new routing control. A routing control has one of two states: ON and OFF. You can map the routing control state to the state of an Amazon Route 53 health check, which can be used to control traffic routing. To get or update the routing control state, see the Recovery Cluster (data plane) API actions for Amazon Route 53 Application Recovery Controller.
*/
createRoutingControl(params: Route53RecoveryControlConfig.Types.CreateRoutingControlRequest, callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.CreateRoutingControlResponse) => void): Request<Route53RecoveryControlConfig.Types.CreateRoutingControlResponse, AWSError>;
/**
* Creates a new routing control. A routing control has one of two states: ON and OFF. You can map the routing control state to the state of an Amazon Route 53 health check, which can be used to control traffic routing. To get or update the routing control state, see the Recovery Cluster (data plane) API actions for Amazon Route 53 Application Recovery Controller.
*/
createRoutingControl(callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.CreateRoutingControlResponse) => void): Request<Route53RecoveryControlConfig.Types.CreateRoutingControlResponse, AWSError>;
/**
* Creates a safety rule in a control panel. Safety rules let you add safeguards around changing routing control states, and for enabling and disabling routing controls, to help prevent unexpected outcomes. There are two types of safety rules: assertion rules and gating rules. Assertion rule: An assertion rule enforces that, when you change a routing control state, that a certain criteria is met. For example, the criteria might be that at least one routing control state is On after the transation so that traffic continues to flow to at least one cell for the application. This ensures that you avoid a fail-open scenario. Gating rule: A gating rule lets you configure a gating routing control as an overall "on/off" switch for a group of routing controls. Or, you can configure more complex gating scenarios, for example by configuring multiple gating routing controls. For more information, see Safety rules in the Amazon Route 53 Application Recovery Controller Developer Guide.
*/
createSafetyRule(params: Route53RecoveryControlConfig.Types.CreateSafetyRuleRequest, callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.CreateSafetyRuleResponse) => void): Request<Route53RecoveryControlConfig.Types.CreateSafetyRuleResponse, AWSError>;
/**
* Creates a safety rule in a control panel. Safety rules let you add safeguards around changing routing control states, and for enabling and disabling routing controls, to help prevent unexpected outcomes. There are two types of safety rules: assertion rules and gating rules. Assertion rule: An assertion rule enforces that, when you change a routing control state, that a certain criteria is met. For example, the criteria might be that at least one routing control state is On after the transation so that traffic continues to flow to at least one cell for the application. This ensures that you avoid a fail-open scenario. Gating rule: A gating rule lets you configure a gating routing control as an overall "on/off" switch for a group of routing controls. Or, you can configure more complex gating scenarios, for example by configuring multiple gating routing controls. For more information, see Safety rules in the Amazon Route 53 Application Recovery Controller Developer Guide.
*/
createSafetyRule(callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.CreateSafetyRuleResponse) => void): Request<Route53RecoveryControlConfig.Types.CreateSafetyRuleResponse, AWSError>;
/**
* Delete a cluster.
*/
deleteCluster(params: Route53RecoveryControlConfig.Types.DeleteClusterRequest, callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.DeleteClusterResponse) => void): Request<Route53RecoveryControlConfig.Types.DeleteClusterResponse, AWSError>;
/**
* Delete a cluster.
*/
deleteCluster(callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.DeleteClusterResponse) => void): Request<Route53RecoveryControlConfig.Types.DeleteClusterResponse, AWSError>;
/**
* Deletes a control panel.
*/
deleteControlPanel(params: Route53RecoveryControlConfig.Types.DeleteControlPanelRequest, callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.DeleteControlPanelResponse) => void): Request<Route53RecoveryControlConfig.Types.DeleteControlPanelResponse, AWSError>;
/**
* Deletes a control panel.
*/
deleteControlPanel(callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.DeleteControlPanelResponse) => void): Request<Route53RecoveryControlConfig.Types.DeleteControlPanelResponse, AWSError>;
/**
* Deletes a routing control.
*/
deleteRoutingControl(params: Route53RecoveryControlConfig.Types.DeleteRoutingControlRequest, callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.DeleteRoutingControlResponse) => void): Request<Route53RecoveryControlConfig.Types.DeleteRoutingControlResponse, AWSError>;
/**
* Deletes a routing control.
*/
deleteRoutingControl(callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.DeleteRoutingControlResponse) => void): Request<Route53RecoveryControlConfig.Types.DeleteRoutingControlResponse, AWSError>;
/**
* Deletes a safety rule./>
*/
deleteSafetyRule(params: Route53RecoveryControlConfig.Types.DeleteSafetyRuleRequest, callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.DeleteSafetyRuleResponse) => void): Request<Route53RecoveryControlConfig.Types.DeleteSafetyRuleResponse, AWSError>;
/**
* Deletes a safety rule./>
*/
deleteSafetyRule(callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.DeleteSafetyRuleResponse) => void): Request<Route53RecoveryControlConfig.Types.DeleteSafetyRuleResponse, AWSError>;
/**
* Display the details about a cluster. The response includes the cluster name, endpoints, status, and Amazon Resource Name (ARN).
*/
describeCluster(params: Route53RecoveryControlConfig.Types.DescribeClusterRequest, callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.DescribeClusterResponse) => void): Request<Route53RecoveryControlConfig.Types.DescribeClusterResponse, AWSError>;
/**
* Display the details about a cluster. The response includes the cluster name, endpoints, status, and Amazon Resource Name (ARN).
*/
describeCluster(callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.DescribeClusterResponse) => void): Request<Route53RecoveryControlConfig.Types.DescribeClusterResponse, AWSError>;
/**
* Displays details about a control panel.
*/
describeControlPanel(params: Route53RecoveryControlConfig.Types.DescribeControlPanelRequest, callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.DescribeControlPanelResponse) => void): Request<Route53RecoveryControlConfig.Types.DescribeControlPanelResponse, AWSError>;
/**
* Displays details about a control panel.
*/
describeControlPanel(callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.DescribeControlPanelResponse) => void): Request<Route53RecoveryControlConfig.Types.DescribeControlPanelResponse, AWSError>;
/**
* Displays details about a routing control. A routing control has one of two states: ON and OFF. You can map the routing control state to the state of an Amazon Route 53 health check, which can be used to control routing. To get or update the routing control state, see the Recovery Cluster (data plane) API actions for Amazon Route 53 Application Recovery Controller.
*/
describeRoutingControl(params: Route53RecoveryControlConfig.Types.DescribeRoutingControlRequest, callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.DescribeRoutingControlResponse) => void): Request<Route53RecoveryControlConfig.Types.DescribeRoutingControlResponse, AWSError>;
/**
* Displays details about a routing control. A routing control has one of two states: ON and OFF. You can map the routing control state to the state of an Amazon Route 53 health check, which can be used to control routing. To get or update the routing control state, see the Recovery Cluster (data plane) API actions for Amazon Route 53 Application Recovery Controller.
*/
describeRoutingControl(callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.DescribeRoutingControlResponse) => void): Request<Route53RecoveryControlConfig.Types.DescribeRoutingControlResponse, AWSError>;
/**
* Returns information about a safety rule.
*/
describeSafetyRule(params: Route53RecoveryControlConfig.Types.DescribeSafetyRuleRequest, callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.DescribeSafetyRuleResponse) => void): Request<Route53RecoveryControlConfig.Types.DescribeSafetyRuleResponse, AWSError>;
/**
* Returns information about a safety rule.
*/
describeSafetyRule(callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.DescribeSafetyRuleResponse) => void): Request<Route53RecoveryControlConfig.Types.DescribeSafetyRuleResponse, AWSError>;
/**
* Returns an array of all Amazon Route 53 health checks associated with a specific routing control.
*/
listAssociatedRoute53HealthChecks(params: Route53RecoveryControlConfig.Types.ListAssociatedRoute53HealthChecksRequest, callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.ListAssociatedRoute53HealthChecksResponse) => void): Request<Route53RecoveryControlConfig.Types.ListAssociatedRoute53HealthChecksResponse, AWSError>;
/**
* Returns an array of all Amazon Route 53 health checks associated with a specific routing control.
*/
listAssociatedRoute53HealthChecks(callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.ListAssociatedRoute53HealthChecksResponse) => void): Request<Route53RecoveryControlConfig.Types.ListAssociatedRoute53HealthChecksResponse, AWSError>;
/**
* Returns an array of all the clusters in an account.
*/
listClusters(params: Route53RecoveryControlConfig.Types.ListClustersRequest, callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.ListClustersResponse) => void): Request<Route53RecoveryControlConfig.Types.ListClustersResponse, AWSError>;
/**
* Returns an array of all the clusters in an account.
*/
listClusters(callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.ListClustersResponse) => void): Request<Route53RecoveryControlConfig.Types.ListClustersResponse, AWSError>;
/**
* Returns an array of control panels in an account or in a cluster.
*/
listControlPanels(params: Route53RecoveryControlConfig.Types.ListControlPanelsRequest, callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.ListControlPanelsResponse) => void): Request<Route53RecoveryControlConfig.Types.ListControlPanelsResponse, AWSError>;
/**
* Returns an array of control panels in an account or in a cluster.
*/
listControlPanels(callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.ListControlPanelsResponse) => void): Request<Route53RecoveryControlConfig.Types.ListControlPanelsResponse, AWSError>;
/**
* Returns an array of routing controls for a control panel. A routing control is an Amazon Route 53 Application Recovery Controller construct that has one of two states: ON and OFF. You can map the routing control state to the state of an Amazon Route 53 health check, which can be used to control routing.
*/
listRoutingControls(params: Route53RecoveryControlConfig.Types.ListRoutingControlsRequest, callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.ListRoutingControlsResponse) => void): Request<Route53RecoveryControlConfig.Types.ListRoutingControlsResponse, AWSError>;
/**
* Returns an array of routing controls for a control panel. A routing control is an Amazon Route 53 Application Recovery Controller construct that has one of two states: ON and OFF. You can map the routing control state to the state of an Amazon Route 53 health check, which can be used to control routing.
*/
listRoutingControls(callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.ListRoutingControlsResponse) => void): Request<Route53RecoveryControlConfig.Types.ListRoutingControlsResponse, AWSError>;
/**
* List the safety rules (the assertion rules and gating rules) that you've defined for the routing controls in a control panel.
*/
listSafetyRules(params: Route53RecoveryControlConfig.Types.ListSafetyRulesRequest, callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.ListSafetyRulesResponse) => void): Request<Route53RecoveryControlConfig.Types.ListSafetyRulesResponse, AWSError>;
/**
* List the safety rules (the assertion rules and gating rules) that you've defined for the routing controls in a control panel.
*/
listSafetyRules(callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.ListSafetyRulesResponse) => void): Request<Route53RecoveryControlConfig.Types.ListSafetyRulesResponse, AWSError>;
/**
* Lists the tags for a resource.
*/
listTagsForResource(params: Route53RecoveryControlConfig.Types.ListTagsForResourceRequest, callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.ListTagsForResourceResponse) => void): Request<Route53RecoveryControlConfig.Types.ListTagsForResourceResponse, AWSError>;
/**
* Lists the tags for a resource.
*/
listTagsForResource(callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.ListTagsForResourceResponse) => void): Request<Route53RecoveryControlConfig.Types.ListTagsForResourceResponse, AWSError>;
/**
* Adds a tag to a resource.
*/
tagResource(params: Route53RecoveryControlConfig.Types.TagResourceRequest, callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.TagResourceResponse) => void): Request<Route53RecoveryControlConfig.Types.TagResourceResponse, AWSError>;
/**
* Adds a tag to a resource.
*/
tagResource(callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.TagResourceResponse) => void): Request<Route53RecoveryControlConfig.Types.TagResourceResponse, AWSError>;
/**
* Removes a tag from a resource.
*/
untagResource(params: Route53RecoveryControlConfig.Types.UntagResourceRequest, callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.UntagResourceResponse) => void): Request<Route53RecoveryControlConfig.Types.UntagResourceResponse, AWSError>;
/**
* Removes a tag from a resource.
*/
untagResource(callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.UntagResourceResponse) => void): Request<Route53RecoveryControlConfig.Types.UntagResourceResponse, AWSError>;
/**
* Updates a control panel. The only update you can make to a control panel is to change the name of the control panel.
*/
updateControlPanel(params: Route53RecoveryControlConfig.Types.UpdateControlPanelRequest, callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.UpdateControlPanelResponse) => void): Request<Route53RecoveryControlConfig.Types.UpdateControlPanelResponse, AWSError>;
/**
* Updates a control panel. The only update you can make to a control panel is to change the name of the control panel.
*/
updateControlPanel(callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.UpdateControlPanelResponse) => void): Request<Route53RecoveryControlConfig.Types.UpdateControlPanelResponse, AWSError>;
/**
* Updates a routing control. You can only update the name of the routing control. To get or update the routing control state, see the Recovery Cluster (data plane) API actions for Amazon Route 53 Application Recovery Controller.
*/
updateRoutingControl(params: Route53RecoveryControlConfig.Types.UpdateRoutingControlRequest, callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.UpdateRoutingControlResponse) => void): Request<Route53RecoveryControlConfig.Types.UpdateRoutingControlResponse, AWSError>;
/**
* Updates a routing control. You can only update the name of the routing control. To get or update the routing control state, see the Recovery Cluster (data plane) API actions for Amazon Route 53 Application Recovery Controller.
*/
updateRoutingControl(callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.UpdateRoutingControlResponse) => void): Request<Route53RecoveryControlConfig.Types.UpdateRoutingControlResponse, AWSError>;
/**
* Update a safety rule (an assertion rule or gating rule). You can only update the name and the waiting period for a safety rule. To make other updates, delete the safety rule and create a new one.
*/
updateSafetyRule(params: Route53RecoveryControlConfig.Types.UpdateSafetyRuleRequest, callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.UpdateSafetyRuleResponse) => void): Request<Route53RecoveryControlConfig.Types.UpdateSafetyRuleResponse, AWSError>;
/**
* Update a safety rule (an assertion rule or gating rule). You can only update the name and the waiting period for a safety rule. To make other updates, delete the safety rule and create a new one.
*/
updateSafetyRule(callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.UpdateSafetyRuleResponse) => void): Request<Route53RecoveryControlConfig.Types.UpdateSafetyRuleResponse, AWSError>;
/**
* Waits for the clusterCreated state by periodically calling the underlying Route53RecoveryControlConfig.describeClusteroperation every 5 seconds (at most 26 times). Wait until a cluster is created
*/
waitFor(state: "clusterCreated", params: Route53RecoveryControlConfig.Types.DescribeClusterRequest & {$waiter?: WaiterConfiguration}, callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.DescribeClusterResponse) => void): Request<Route53RecoveryControlConfig.Types.DescribeClusterResponse, AWSError>;
/**
* Waits for the clusterCreated state by periodically calling the underlying Route53RecoveryControlConfig.describeClusteroperation every 5 seconds (at most 26 times). Wait until a cluster is created
*/
waitFor(state: "clusterCreated", callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.DescribeClusterResponse) => void): Request<Route53RecoveryControlConfig.Types.DescribeClusterResponse, AWSError>;
/**
* Waits for the clusterDeleted state by periodically calling the underlying Route53RecoveryControlConfig.describeClusteroperation every 5 seconds (at most 26 times). Wait for a cluster to be deleted
*/
waitFor(state: "clusterDeleted", params: Route53RecoveryControlConfig.Types.DescribeClusterRequest & {$waiter?: WaiterConfiguration}, callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.DescribeClusterResponse) => void): Request<Route53RecoveryControlConfig.Types.DescribeClusterResponse, AWSError>;
/**
* Waits for the clusterDeleted state by periodically calling the underlying Route53RecoveryControlConfig.describeClusteroperation every 5 seconds (at most 26 times). Wait for a cluster to be deleted
*/
waitFor(state: "clusterDeleted", callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.DescribeClusterResponse) => void): Request<Route53RecoveryControlConfig.Types.DescribeClusterResponse, AWSError>;
/**
* Waits for the controlPanelCreated state by periodically calling the underlying Route53RecoveryControlConfig.describeControlPaneloperation every 5 seconds (at most 26 times). Wait until a control panel is created
*/
waitFor(state: "controlPanelCreated", params: Route53RecoveryControlConfig.Types.DescribeControlPanelRequest & {$waiter?: WaiterConfiguration}, callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.DescribeControlPanelResponse) => void): Request<Route53RecoveryControlConfig.Types.DescribeControlPanelResponse, AWSError>;
/**
* Waits for the controlPanelCreated state by periodically calling the underlying Route53RecoveryControlConfig.describeControlPaneloperation every 5 seconds (at most 26 times). Wait until a control panel is created
*/
waitFor(state: "controlPanelCreated", callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.DescribeControlPanelResponse) => void): Request<Route53RecoveryControlConfig.Types.DescribeControlPanelResponse, AWSError>;
/**
* Waits for the controlPanelDeleted state by periodically calling the underlying Route53RecoveryControlConfig.describeControlPaneloperation every 5 seconds (at most 26 times). Wait until a control panel is deleted
*/
waitFor(state: "controlPanelDeleted", params: Route53RecoveryControlConfig.Types.DescribeControlPanelRequest & {$waiter?: WaiterConfiguration}, callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.DescribeControlPanelResponse) => void): Request<Route53RecoveryControlConfig.Types.DescribeControlPanelResponse, AWSError>;
/**
* Waits for the controlPanelDeleted state by periodically calling the underlying Route53RecoveryControlConfig.describeControlPaneloperation every 5 seconds (at most 26 times). Wait until a control panel is deleted
*/
waitFor(state: "controlPanelDeleted", callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.DescribeControlPanelResponse) => void): Request<Route53RecoveryControlConfig.Types.DescribeControlPanelResponse, AWSError>;
/**
* Waits for the routingControlCreated state by periodically calling the underlying Route53RecoveryControlConfig.describeRoutingControloperation every 5 seconds (at most 26 times). Wait until a routing control is created
*/
waitFor(state: "routingControlCreated", params: Route53RecoveryControlConfig.Types.DescribeRoutingControlRequest & {$waiter?: WaiterConfiguration}, callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.DescribeRoutingControlResponse) => void): Request<Route53RecoveryControlConfig.Types.DescribeRoutingControlResponse, AWSError>;
/**
* Waits for the routingControlCreated state by periodically calling the underlying Route53RecoveryControlConfig.describeRoutingControloperation every 5 seconds (at most 26 times). Wait until a routing control is created
*/
waitFor(state: "routingControlCreated", callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.DescribeRoutingControlResponse) => void): Request<Route53RecoveryControlConfig.Types.DescribeRoutingControlResponse, AWSError>;
/**
* Waits for the routingControlDeleted state by periodically calling the underlying Route53RecoveryControlConfig.describeRoutingControloperation every 5 seconds (at most 26 times). Wait for a routing control to be deleted
*/
waitFor(state: "routingControlDeleted", params: Route53RecoveryControlConfig.Types.DescribeRoutingControlRequest & {$waiter?: WaiterConfiguration}, callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.DescribeRoutingControlResponse) => void): Request<Route53RecoveryControlConfig.Types.DescribeRoutingControlResponse, AWSError>;
/**
* Waits for the routingControlDeleted state by periodically calling the underlying Route53RecoveryControlConfig.describeRoutingControloperation every 5 seconds (at most 26 times). Wait for a routing control to be deleted
*/
waitFor(state: "routingControlDeleted", callback?: (err: AWSError, data: Route53RecoveryControlConfig.Types.DescribeRoutingControlResponse) => void): Request<Route53RecoveryControlConfig.Types.DescribeRoutingControlResponse, AWSError>;
}
declare namespace Route53RecoveryControlConfig {
export interface AssertionRule {
/**
* The routing controls that are part of transactions that are evaluated to determine if a request to change a routing control state is allowed. For example, you might include three routing controls, one for each of three Amazon Web Services Regions.
*/
AssertedControls: __listOf__stringMin1Max256PatternAZaZ09;
/**
* The Amazon Resource Name (ARN) of the control panel.
*/
ControlPanelArn: __stringMin1Max256PatternAZaZ09;
/**
* Name of the assertion rule. You can use any non-white space character in the name.
*/
Name: __stringMin1Max64PatternS;
/**
* The criteria that you set for specific assertion routing controls (AssertedControls) that designate how many routing control states must be ON as the result of a transaction. For example, if you have three assertion routing controls, you might specify atleast 2 for your rule configuration. This means that at least two assertion routing control states must be ON, so that at least two Amazon Web Services Regions have traffic flowing to them.
*/
RuleConfig: RuleConfig;
/**
* The Amazon Resource Name (ARN) of the assertion rule.
*/
SafetyRuleArn: __stringMin1Max256PatternAZaZ09;
/**
* The deployment status of an assertion rule. Status can be one of the following: PENDING, DEPLOYED, PENDING_DELETION.
*/
Status: Status;
/**
* An evaluation period, in milliseconds (ms), during which any request against the target routing controls will fail. This helps prevent "flapping" of state. The wait period is 5000 ms by default, but you can choose a custom value.
*/
WaitPeriodMs: __integer;
}
export interface AssertionRuleUpdate {
/**
* The name of the assertion rule. You can use any non-white space character in the name.
*/
Name: __stringMin1Max64PatternS;
/**
* The Amazon Resource Name (ARN) of the assertion rule.
*/
SafetyRuleArn: __stringMin1Max256PatternAZaZ09;
/**
* An evaluation period, in milliseconds (ms), during which any request against the target routing controls will fail. This helps prevent "flapping" of state. The wait period is 5000 ms by default, but you can choose a custom value.
*/
WaitPeriodMs: __integer;
}
export interface Cluster {
/**
* The Amazon Resource Name (ARN) of the cluster.
*/
ClusterArn?: __stringMin1Max256PatternAZaZ09;
/**
* Endpoints for a cluster. Specify one of these endpoints when you want to set or retrieve a routing control state in the cluster. To get or update the routing control state, see the Amazon Route 53 Application Recovery Controller Routing Control Actions.
*/
ClusterEndpoints?: __listOfClusterEndpoint;
/**
* The name of the cluster.
*/
Name?: __stringMin1Max64PatternS;
/**
* Deployment status of a resource. Status can be one of the following: PENDING, DEPLOYED, PENDING_DELETION.
*/
Status?: Status;
}
export interface ClusterEndpoint {
/**
* A cluster endpoint. Specify an endpoint and Amazon Web Services Region when you want to set or retrieve a routing control state in the cluster. To get or update the routing control state, see the Amazon Route 53 Application Recovery Controller Routing Control Actions.
*/
Endpoint?: __stringMin1Max128PatternAZaZ09;
/**
* The Amazon Web Services Region for a cluster endpoint.
*/
Region?: __stringMin1Max32PatternS;
}
export interface ControlPanel {
/**
* The Amazon Resource Name (ARN) of the cluster that includes the control panel.
*/
ClusterArn?: __stringMin1Max256PatternAZaZ09;
/**
* The Amazon Resource Name (ARN) of the control panel.
*/
ControlPanelArn?: __stringMin1Max256PatternAZaZ09;
/**
* A flag that Amazon Route 53 Application Recovery Controller sets to true to designate the default control panel for a cluster. When you create a cluster, Amazon Route 53 Application Recovery Controller creates a control panel, and sets this flag for that control panel. If you create a control panel yourself, this flag is set to false.
*/
DefaultControlPanel?: __boolean;
/**
* The name of the control panel. You can use any non-white space character in the name.
*/
Name?: __stringMin1Max64PatternS;
/**
* The number of routing controls in the control panel.
*/
RoutingControlCount?: __integer;
/**
* The deployment status of control panel. Status can be one of the following: PENDING, DEPLOYED, PENDING_DELETION.
*/
Status?: Status;
}
export interface CreateClusterRequest {
/**
* A unique, case-sensitive string of up to 64 ASCII characters. To make an idempotent API request with an action, specify a client token in the request.
*/
ClientToken?: __stringMin1Max64PatternS;
/**
* The name of the cluster.
*/
ClusterName: __stringMin1Max64PatternS;
/**
* The tags associated with the cluster.
*/
Tags?: __mapOf__stringMin0Max256PatternS;
}
export interface CreateClusterResponse {
/**
* The cluster that was created.
*/
Cluster?: Cluster;
}
export interface CreateControlPanelRequest {
/**
* A unique, case-sensitive string of up to 64 ASCII characters. To make an idempotent API request with an action, specify a client token in the request.
*/
ClientToken?: __stringMin1Max64PatternS;
/**
* The Amazon Resource Name (ARN) of the cluster for the control panel.
*/
ClusterArn: __stringMin1Max256PatternAZaZ09;
/**
* The name of the control panel.
*/
ControlPanelName: __stringMin1Max64PatternS;
/**
* The tags associated with the control panel.
*/
Tags?: __mapOf__stringMin0Max256PatternS;
}
export interface CreateControlPanelResponse {
/**
* Information about a control panel.
*/
ControlPanel?: ControlPanel;
}
export interface CreateRoutingControlRequest {
/**
* A unique, case-sensitive string of up to 64 ASCII characters. To make an idempotent API request with an action, specify a client token in the request.
*/
ClientToken?: __stringMin1Max64PatternS;
/**
* The Amazon Resource Name (ARN) of the cluster that includes the routing control.
*/
ClusterArn: __stringMin1Max256PatternAZaZ09;
/**
* The Amazon Resource Name (ARN) of the control panel that includes the routing control.
*/
ControlPanelArn?: __stringMin1Max256PatternAZaZ09;
/**
* The name of the routing control.
*/
RoutingControlName: __stringMin1Max64PatternS;
}
export interface CreateRoutingControlResponse {
/**
* The routing control that is created.
*/
RoutingControl?: RoutingControl;
}
export interface CreateSafetyRuleRequest {
/**
* The assertion rule requested.
*/
AssertionRule?: NewAssertionRule;
/**
* A unique, case-sensitive string of up to 64 ASCII characters. To make an idempotent API request with an action, specify a client token in the request.
*/
ClientToken?: __stringMin1Max64PatternS;
/**
* The gating rule requested.
*/
GatingRule?: NewGatingRule;
/**
* The tags associated with the safety rule.
*/
Tags?: __mapOf__stringMin0Max256PatternS;
}
export interface CreateSafetyRuleResponse {
/**
* The assertion rule created.
*/
AssertionRule?: AssertionRule;
/**
* The gating rule created.
*/
GatingRule?: GatingRule;
}
export interface DeleteClusterRequest {
/**
* The Amazon Resource Name (ARN) of the cluster that you're deleting.
*/
ClusterArn: __string;
}
export interface DeleteClusterResponse {
}
export interface DeleteControlPanelRequest {
/**
* The Amazon Resource Name (ARN) of the control panel.
*/
ControlPanelArn: __string;
}
export interface DeleteControlPanelResponse {
}
export interface DeleteRoutingControlRequest {
/**
* The Amazon Resource Name (ARN) of the routing control that you're deleting.
*/
RoutingControlArn: __string;
}
export interface DeleteRoutingControlResponse {
}
export interface DeleteSafetyRuleRequest {
/**
* The ARN of the safety rule.
*/
SafetyRuleArn: __string;
}
export interface DeleteSafetyRuleResponse {
}
export interface DescribeClusterRequest {
/**
* The Amazon Resource Name (ARN) of the cluster.
*/
ClusterArn: __string;
}
export interface DescribeClusterResponse {
/**
* The cluster for the DescribeCluster request.
*/
Cluster?: Cluster;
}
export interface DescribeControlPanelRequest {
/**
* The Amazon Resource Name (ARN) of the control panel.
*/
ControlPanelArn: __string;
}
export interface DescribeControlPanelResponse {
/**
* Information about the control panel.
*/
ControlPanel?: ControlPanel;
}
export interface DescribeRoutingControlRequest {
/**
* The Amazon Resource Name (ARN) of the routing control.
*/
RoutingControlArn: __string;
}
export interface DescribeRoutingControlResponse {
/**
* Information about the routing control.
*/
RoutingControl?: RoutingControl;
}
export interface DescribeSafetyRuleRequest {
/**
* The ARN of the safety rule.
*/
SafetyRuleArn: __string;
}
export interface DescribeSafetyRuleResponse {
/**
* The assertion rule in the response.
*/
AssertionRule?: AssertionRule;
/**
* The gating rule in the response.
*/
GatingRule?: GatingRule;
}
export interface GatingRule {
/**
* The Amazon Resource Name (ARN) of the control panel.
*/
ControlPanelArn: __stringMin1Max256PatternAZaZ09;
/**
* An array of gating routing control Amazon Resource Names (ARNs). For a simple "on/off" switch, specify the ARN for one routing control. The gating routing controls are evaluated by the rule configuration that you specify to determine if the target routing control states can be changed.
*/
GatingControls: __listOf__stringMin1Max256PatternAZaZ09;
/**
* The name for the gating rule. You can use any non-white space character in the name.
*/
Name: __stringMin1Max64PatternS;
/**
* The criteria that you set for gating routing controls that designates how many of the routing control states must be ON to allow you to update target routing control states.
*/
RuleConfig: RuleConfig;
/**
* The Amazon Resource Name (ARN) of the gating rule.
*/
SafetyRuleArn: __stringMin1Max256PatternAZaZ09;
/**
* The deployment status of a gating rule. Status can be one of the following: PENDING, DEPLOYED, PENDING_DELETION.
*/
Status: Status;
/**
* An array of target routing control Amazon Resource Names (ARNs) for which the states can only be updated if the rule configuration that you specify evaluates to true for the gating routing control. As a simple example, if you have a single gating control, it acts as an overall "on/off" switch for a set of target routing controls. You can use this to manually override automated fail over, for example.
*/
TargetControls: __listOf__stringMin1Max256PatternAZaZ09;
/**
* An evaluation period, in milliseconds (ms), during which any request against the target routing controls will fail. This helps prevent "flapping" of state. The wait period is 5000 ms by default, but you can choose a custom value.
*/
WaitPeriodMs: __integer;
}
export interface GatingRuleUpdate {
/**
* The name for the gating rule. You can use any non-white space character in the name.
*/
Name: __stringMin1Max64PatternS;
/**
* The Amazon Resource Name (ARN) of the gating rule.
*/
SafetyRuleArn: __stringMin1Max256PatternAZaZ09;
/**
* An evaluation period, in milliseconds (ms), during which any request against the target routing controls will fail. This helps prevent "flapping" of state. The wait period is 5000 ms by default, but you can choose a custom value.
*/
WaitPeriodMs: __integer;
}
export interface ListAssociatedRoute53HealthChecksRequest {
/**
* The number of objects that you want to return with this call.
*/
MaxResults?: MaxResults;
/**
* The token that identifies which batch of results you want to see.
*/
NextToken?: __string;
/**
* The Amazon Resource Name (ARN) of the routing control.
*/
RoutingControlArn: __string;
}
export interface ListAssociatedRoute53HealthChecksResponse {
/**
* Identifiers for the health checks.
*/
HealthCheckIds?: __listOf__stringMax36PatternS;
/**
* Next token for listing health checks.
*/
NextToken?: __stringMin1Max8096PatternS;
}
export interface ListClustersRequest {
/**
* The number of objects that you want to return with this call.
*/
MaxResults?: MaxResults;
/**
* The token that identifies which batch of results you want to see.
*/
NextToken?: __string;
}
export interface ListClustersResponse {
/**
* An array of the clusters in an account.
*/
Clusters?: __listOfCluster;
/**
* The token that identifies which batch of results you want to see.
*/
NextToken?: __stringMin1Max8096PatternS;
}
export interface ListControlPanelsRequest {
/**
* The Amazon Resource Name (ARN) of a cluster.
*/
ClusterArn?: __string;
/**
* The number of objects that you want to return with this call.
*/
MaxResults?: MaxResults;
/**
* The token that identifies which batch of results you want to see.
*/
NextToken?: __string;
}
export interface ListControlPanelsResponse {
/**
* The result of a successful ListControlPanel request.
*/
ControlPanels?: __listOfControlPanel;
/**
* The token that identifies which batch of results you want to see.
*/
NextToken?: __stringMin1Max8096PatternS;
}
export interface ListRoutingControlsRequest {
/**
* The Amazon Resource Name (ARN) of the control panel.
*/
ControlPanelArn: __string;
/**
* The number of objects that you want to return with this call.
*/
MaxResults?: MaxResults;
/**
* The token that identifies which batch of results you want to see.
*/
NextToken?: __string;
}
export interface ListRoutingControlsResponse {
/**
* The token that identifies which batch of results you want to see.
*/
NextToken?: __stringMin1Max8096PatternS;
/**
* An array of routing controls.
*/
RoutingControls?: __listOfRoutingControl;
}
export interface ListSafetyRulesRequest {
/**
* The Amazon Resource Name (ARN) of the control panel.
*/
ControlPanelArn: __string;
/**
* The number of objects that you want to return with this call.
*/
MaxResults?: MaxResults;
/**
* The token that identifies which batch of results you want to see.
*/
NextToken?: __string;
}
export interface ListSafetyRulesResponse {
/**
* The token that identifies which batch of results you want to see.
*/
NextToken?: __stringMin1Max8096PatternS;
/**
* The list of safety rules in a control panel.
*/
SafetyRules?: __listOfRule;
}
export interface ListTagsForResourceRequest {
/**
* The Amazon Resource Name (ARN) for the resource that's tagged.
*/
ResourceArn: __string;
}
export interface ListTagsForResourceResponse {
/**
* The tags associated with the resource.
*/
Tags?: __mapOf__stringMin0Max256PatternS;
}
export type MaxResults = number;
export interface NewAssertionRule {
/**
* The routing controls that are part of transactions that are evaluated to determine if a request to change a routing control state is allowed. For example, you might include three routing controls, one for each of three Amazon Web Services Regions.
*/
AssertedControls: __listOf__stringMin1Max256PatternAZaZ09;
/**
* The Amazon Resource Name (ARN) for the control panel.
*/
ControlPanelArn: __stringMin1Max256PatternAZaZ09;
/**
* The name of the assertion rule. You can use any non-white space character in the name.
*/
Name: __stringMin1Max64PatternS;
/**
* The criteria that you set for specific assertion controls (routing controls) that designate how many control states must be ON as the result of a transaction. For example, if you have three assertion controls, you might specify ATLEAST 2for your rule configuration. This means that at least two assertion controls must be ON, so that at least two Amazon Web Services Regions have traffic flowing to them.
*/
RuleConfig: RuleConfig;
/**
* An evaluation period, in milliseconds (ms), during which any request against the target routing controls will fail. This helps prevent "flapping" of state. The wait period is 5000 ms by default, but you can choose a custom value.
*/
WaitPeriodMs: __integer;
}
export interface NewGatingRule {
/**
* The Amazon Resource Name (ARN) of the control panel.
*/
ControlPanelArn: __stringMin1Max256PatternAZaZ09;
/**
* The gating controls for the new gating rule. That is, routing controls that are evaluated by the rule configuration that you specify.
*/
GatingControls: __listOf__stringMin1Max256PatternAZaZ09;
/**
* The name for the new gating rule.
*/
Name: __stringMin1Max64PatternS;
/**
* The criteria that you set for specific gating controls (routing controls) that designates how many control states must be ON to allow you to change (set or unset) the target control states.
*/
RuleConfig: RuleConfig;
/**
* Routing controls that can only be set or unset if the specified RuleConfig evaluates to true for the specified GatingControls. For example, say you have three gating controls, one for each of three Amazon Web Services Regions. Now you specify AtLeast 2 as your RuleConfig. With these settings, you can only change (set or unset) the routing controls that you have specified as TargetControls if that rule evaluates to true. In other words, your ability to change the routing controls that you have specified as TargetControls is gated by the rule that you set for the routing controls in GatingControls.
*/
TargetControls: __listOf__stringMin1Max256PatternAZaZ09;
/**
* An evaluation period, in milliseconds (ms), during which any request against the target routing controls will fail. This helps prevent "flapping" of state. The wait period is 5000 ms by default, but you can choose a custom value.
*/
WaitPeriodMs: __integer;
}
export interface RoutingControl {
/**
* The Amazon Resource Name (ARN) of the control panel that includes the routing control.
*/
ControlPanelArn?: __stringMin1Max256PatternAZaZ09;
/**
* The name of the routing control.
*/
Name?: __stringMin1Max64PatternS;
/**
* The Amazon Resource Name (ARN) of the routing control.
*/
RoutingControlArn?: __stringMin1Max256PatternAZaZ09;
/**
* The deployment status of a routing control. Status can be one of the following: PENDING, DEPLOYED, PENDING_DELETION.
*/
Status?: Status;
}
export interface Rule {
/**
* An assertion rule enforces that, when a routing control state is changed, the criteria set by the rule configuration is met. Otherwise, the change to the routing control state is not accepted. For example, the criteria might be that at least one routing control state is On after the transation so that traffic continues to flow to at least one cell for the application. This ensures that you avoid a fail-open scenario.
*/
ASSERTION?: AssertionRule;
/**
* A gating rule verifies that a gating routing control or set of gating rounting controls, evaluates as true, based on a rule configuration that you specify, which allows a set of routing control state changes to complete. For example, if you specify one gating routing control and you set the Type in the rule configuration to OR, that indicates that you must set the gating routing control to On for the rule to evaluate as true; that is, for the gating control "switch" to be "On". When you do that, then you can update the routing control states for the target routing controls that you specify in the gating rule.
*/
GATING?: GatingRule;
}
export interface RuleConfig {
/**
* Logical negation of the rule. If the rule would usually evaluate true, it's evaluated as false, and vice versa.
*/
Inverted: __boolean;
/**
* The value of N, when you specify an ATLEAST rule type. That is, Threshold is the number of controls that must be set when you specify an ATLEAST type.
*/
Threshold: __integer;
/**
* A rule can be one of the following: ATLEAST, AND, or OR.
*/
Type: RuleType;
}
export type RuleType = "ATLEAST"|"AND"|"OR"|string;
export type Status = "PENDING"|"DEPLOYED"|"PENDING_DELETION"|string;
export interface TagResourceRequest {
/**
* The Amazon Resource Name (ARN) for the resource that's tagged.
*/
ResourceArn: __string;
/**
* The tags associated with the resource.
*/
Tags: __mapOf__stringMin0Max256PatternS;
}
export interface TagResourceResponse {
}
export interface UntagResourceRequest {
/**
* The Amazon Resource Name (ARN) for the resource that's tagged.
*/
ResourceArn: __string;
/**
* Keys for the tags to be removed.
*/
TagKeys: __listOf__string;
}
export interface UntagResourceResponse {
}
export interface UpdateControlPanelRequest {
/**
* The Amazon Resource Name (ARN) of the control panel.
*/
ControlPanelArn: __stringMin1Max256PatternAZaZ09;
/**
* The name of the control panel.
*/
ControlPanelName: __stringMin1Max64PatternS;
}
export interface UpdateControlPanelResponse {
/**
* The control panel to update.
*/
ControlPanel?: ControlPanel;
}
export interface UpdateRoutingControlRequest {
/**
* The Amazon Resource Name (ARN) of the routing control.
*/
RoutingControlArn: __stringMin1Max256PatternAZaZ09;
/**
* The name of the routing control.
*/
RoutingControlName: __stringMin1Max64PatternS;
}
export interface UpdateRoutingControlResponse {
/**
* The routing control that was updated.
*/
RoutingControl?: RoutingControl;
}
export interface UpdateSafetyRuleRequest {
/**
* The assertion rule to update.
*/
AssertionRuleUpdate?: AssertionRuleUpdate;
/**
* The gating rule to update.
*/
GatingRuleUpdate?: GatingRuleUpdate;
}
export interface UpdateSafetyRuleResponse {
/**
* The assertion rule updated.
*/
AssertionRule?: AssertionRule;
/**
* The gating rule updated.
*/
GatingRule?: GatingRule;
}
export type __boolean = boolean;
export type __integer = number;
export type __listOfCluster = Cluster[];
export type __listOfClusterEndpoint = ClusterEndpoint[];
export type __listOfControlPanel = ControlPanel[];
export type __listOfRoutingControl = RoutingControl[];
export type __listOfRule = Rule[];
export type __listOf__string = __string[];
export type __listOf__stringMax36PatternS = __stringMax36PatternS[];
export type __listOf__stringMin1Max256PatternAZaZ09 = __stringMin1Max256PatternAZaZ09[];
export type __mapOf__stringMin0Max256PatternS = {[key: string]: __stringMin0Max256PatternS};
export type __string = string;
export type __stringMax36PatternS = string;
export type __stringMin0Max256PatternS = string;
export type __stringMin1Max128PatternAZaZ09 = string;
export type __stringMin1Max256PatternAZaZ09 = string;
export type __stringMin1Max32PatternS = string;
export type __stringMin1Max64PatternS = string;
export type __stringMin1Max8096PatternS = string;
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
export type apiVersion = "2020-11-02"|"latest"|string;
export interface ClientApiVersions {
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
apiVersion?: apiVersion;
}
export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions;
/**
* Contains interfaces for use with the Route53RecoveryControlConfig client.
*/
export import Types = Route53RecoveryControlConfig;
}
export = Route53RecoveryControlConfig; | the_stack |
import 'chrome://resources/cr_elements/cr_action_menu/cr_action_menu.js';
import 'chrome://resources/cr_elements/cr_button/cr_button.m.js';
import 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.m.js';
import 'chrome://resources/cr_elements/cr_link_row/cr_link_row.js';
import 'chrome://resources/cr_elements/icons.m.js';
import 'chrome://resources/cr_elements/shared_style_css.m.js';
import 'chrome://resources/polymer/v3_0/iron-flex-layout/iron-flex-layout-classes.js';
import 'chrome://resources/polymer/v3_0/iron-list/iron-list.js';
import '../controls/extension_controlled_indicator.js';
// <if expr="chromeos">
import '../controls/password_prompt_dialog.js';
// </if>
import '../controls/settings_toggle_button.js';
import '../prefs/prefs.js';
import '../settings_shared_css.js';
import '../site_favicon.js';
import './password_list_item.js';
import './passwords_list_handler.js';
import './passwords_export_dialog.js';
import './passwords_shared_css.js';
import './avatar_icon.js';
import {CrActionMenuElement} from 'chrome://resources/cr_elements/cr_action_menu/cr_action_menu.js';
import {assert} from 'chrome://resources/js/assert.m.js';
import {focusWithoutInk} from 'chrome://resources/js/cr/ui/focus_without_ink.m.js';
import {I18nMixin} from 'chrome://resources/js/i18n_mixin.js';
import {getDeepActiveElement} from 'chrome://resources/js/util.m.js';
import {WebUIListenerMixin} from 'chrome://resources/js/web_ui_listener_mixin.js';
import {IronA11yAnnouncer} from 'chrome://resources/polymer/v3_0/iron-a11y-announcer/iron-a11y-announcer.js';
import {afterNextRender, html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {GlobalScrollTargetMixin} from '../global_scroll_target_mixin.js';
import {HatsBrowserProxyImpl, TrustSafetyInteraction} from '../hats_browser_proxy.js';
import {loadTimeData} from '../i18n_setup.js';
import {OpenWindowProxyImpl} from '../open_window_proxy.js';
import {StoredAccount, SyncBrowserProxyImpl, SyncPrefs, SyncStatus} from '../people_page/sync_browser_proxy.js';
import {PrefsMixin} from '../prefs/prefs_mixin.js';
import {routes} from '../route.js';
import {Route, Router} from '../router.js';
// <if expr="chromeos">
import {BlockingRequestManager} from './blocking_request_manager.js';
// </if>
import {MergeExceptionsStoreCopiesMixin} from './merge_exceptions_store_copies_mixin.js';
import {MergePasswordsStoreCopiesMixin} from './merge_passwords_store_copies_mixin.js';
import {MultiStoreExceptionEntry} from './multi_store_exception_entry.js';
import {MultiStorePasswordUiEntry} from './multi_store_password_ui_entry.js';
import {PasswordCheckMixin} from './password_check_mixin.js';
import {PasswordCheckReferrer, PasswordExceptionListChangedListener, PasswordManagerImpl, PasswordManagerProxy} from './password_manager_proxy.js';
import {PasswordsListHandlerElement} from './passwords_list_handler.js';
/**
* Checks if an HTML element is an editable. An editable is either a text
* input or a text area.
*/
function isEditable(element: Element): boolean {
const nodeName = element.nodeName.toLowerCase();
return element.nodeType === Node.ELEMENT_NODE &&
(nodeName === 'textarea' ||
(nodeName === 'input' &&
/^(?:text|search|email|number|tel|url|password)$/i.test(
(element as HTMLInputElement).type)));
}
type FocusConfig = Map<string, string|(() => void)>;
interface RepeaterEvent extends CustomEvent {
model: {
item: MultiStoreExceptionEntry,
};
}
interface PasswordsSectionElement {
$: {
exportImportMenu: CrActionMenuElement,
passwordsListHandler: PasswordsListHandlerElement,
};
}
const PasswordsSectionElementBase = MergePasswordsStoreCopiesMixin(
PrefsMixin(GlobalScrollTargetMixin(MergeExceptionsStoreCopiesMixin(
WebUIListenerMixin(I18nMixin(PasswordCheckMixin(PolymerElement)))))));
class PasswordsSectionElement extends PasswordsSectionElementBase {
static get is() {
return 'passwords-section';
}
static get template() {
return html`{__html_template__}`;
}
static get properties() {
return {
focusConfig: {
type: Object,
observer: 'focusConfigChanged_',
},
/** Preferences state. */
prefs: {
type: Object,
notify: true,
},
subpageRoute: {
type: Object,
value: routes.PASSWORDS,
},
/** Filter on the saved passwords and exceptions. */
filter: {
type: String,
value: '',
observer: 'announceSearchResults_',
},
shownPasswordsCount_: {
type: Number,
value: 0,
},
shownExceptionsCount_: {
type: Number,
value: 0,
},
storedAccounts_: Array,
signedIn_: {
type: Boolean,
value: true,
computed: 'computeSignedIn_(syncStatus_, storedAccounts_)',
},
eligibleForAccountStorage_: {
type: Boolean,
value: false,
computed: 'computeEligibleForAccountStorage_(' +
'syncStatus_, signedIn_, syncPrefs_)',
},
hasNeverCheckedPasswords_: {
type: Boolean,
computed: 'computeHasNeverCheckedPasswords_(status)',
},
hasSavedPasswords_: {
type: Boolean,
computed:
'computeHasSavedPasswords_(savedPasswords, savedPasswords.splices)',
},
/**
* Used to decide the text on the button leading to 'device passwords'
* page.
*/
numberOfDevicePasswords_: {
type: Number,
computed: 'computeNumberOfDevicePasswords_(savedPasswords, ' +
'savedPasswords.splices)',
},
hasPasswordExceptions_: {
type: Boolean,
computed: 'computeHasPasswordExceptions_(passwordExceptions)',
},
shouldShowBanner_: {
type: Boolean,
value: true,
computed: 'computeShouldShowBanner_(hasLeakedCredentials_,' +
'signedIn_, hasNeverCheckedPasswords_, hasSavedPasswords_)',
},
/**
* If true, the edit dialog and removal notification show
* information about which location(s) a password is stored.
*/
isAccountStoreUser_: {
type: Boolean,
value: false,
computed: 'computeIsAccountStoreUser_(' +
'eligibleForAccountStorage_, isOptedInForAccountStorage_)',
},
/**
* Whether the entry point leading to the device passwords page should be
* shown for a user who is already eligible for account storage.
*/
shouldShowDevicePasswordsLink_: {
type: Boolean,
value: false,
computed: 'computeShouldShowDevicePasswordsLink_(' +
'isOptedInForAccountStorage_, numberOfDevicePasswords_)',
},
/**
* Whether the entry point leading to enroll in trusted vault encryption
* should be shown.
*/
shouldOfferTrustedVaultOptIn_: {
type: Boolean,
value: false,
},
hasLeakedCredentials_: {
type: Boolean,
computed: 'computeHasLeakedCredentials_(leakedPasswords)',
},
hidePasswordsLink_: {
type: Boolean,
computed: 'computeHidePasswordsLink_(syncPrefs_, syncStatus_, ' +
'eligibleForAccountStorage_)',
},
showImportPasswords_: {
type: Boolean,
value() {
return loadTimeData.valueExists('showImportPasswords') &&
loadTimeData.getBoolean('showImportPasswords');
}
},
profileEmail_: {
type: String,
value: '',
computed: 'getFirstStoredAccountEmail_(storedAccounts_)',
},
/**
* The currently selected profile icon as CSS image set.
*/
profileIcon_: String,
isOptedInForAccountStorage_: Boolean,
syncPrefs_: Object,
syncStatus_: Object,
// <if expr="chromeos">
showPasswordPromptDialog_: Boolean,
tokenRequestManager_: Object,
// </if>
showPasswordsExportDialog_: Boolean,
showAddPasswordDialog_: Boolean,
showAddPasswordButton_: {
type: Boolean,
value() {
return loadTimeData.getBoolean('addPasswordsInSettingsEnabled');
}
},
};
}
focusConfig: FocusConfig;
subpageRoute: Route;
filter: string;
private shownPasswordsCount_: number;
private shownExceptionsCount_: number;
private storedAccounts_: Array<StoredAccount>;
private signedIn_: boolean;
private eligibleForAccountStorage_: boolean;
private hasNeverCheckedPasswords_: boolean;
private hasSavedPasswords_: boolean;
private numberOfDevicePasswords_: number;
private hasPasswordExceptions_: boolean;
private shouldShowBanner_: boolean;
private isAccountStoreUser_: boolean;
private shouldShowDevicePasswordsLink_: boolean;
private shouldOfferTrustedVaultOptIn_: boolean;
private hasLeakedCredentials_: boolean;
private hidePasswordsLink_: boolean;
private showImportPasswords_: boolean;
private profileEmail_: string;
private profileIcon_: string;
private isOptedInForAccountStorage_: boolean;
private syncPrefs_: SyncPrefs;
private syncStatus_: SyncStatus;
// <if expr="chromeos">
private showPasswordPromptDialog_: boolean;
private tokenRequestManager_: BlockingRequestManager;
// </if>
private showPasswordsExportDialog_: boolean;
private showAddPasswordDialog_: boolean;
private showAddPasswordButton_: boolean;
private activeDialogAnchorStack_: Array<HTMLElement>;
private passwordManager_: PasswordManagerProxy =
PasswordManagerImpl.getInstance();
private setIsOptedInForAccountStorageListener_:
((isOptedIn: boolean) => void)|null = null;
private setPasswordExceptionsListener_: PasswordExceptionListChangedListener|
null = null;
constructor() {
super();
/**
* A stack of the elements that triggered dialog to open and should
* therefore receive focus when that dialog is closed. The bottom of the
* stack is the element that triggered the earliest open dialog and top of
* the stack is the element that triggered the most recent (i.e. active)
* dialog. If no dialog is open, the stack is empty.
*/
this.activeDialogAnchorStack_ = [];
}
ready() {
super.ready();
document.addEventListener('keydown', e => {
// <if expr="is_macosx">
if (e.metaKey && e.key === 'z') {
this.onUndoKeyBinding_(e);
}
// </if>
// <if expr="not is_macosx">
if (e.ctrlKey && e.key === 'z') {
this.onUndoKeyBinding_(e);
}
// </if>
});
}
connectedCallback() {
super.connectedCallback();
// Create listener functions.
const setIsOptedInForAccountStorageListener = (optedIn: boolean) => {
this.isOptedInForAccountStorage_ = optedIn;
};
this.setIsOptedInForAccountStorageListener_ =
setIsOptedInForAccountStorageListener;
// <if expr="chromeos">
// If the user's account supports the password check, an auth token will be
// required in order for them to view or export passwords. Otherwise there
// is no additional security so |tokenRequestManager_| will immediately
// resolve requests.
if (loadTimeData.getBoolean('userCannotManuallyEnterPassword')) {
this.tokenRequestManager_ = new BlockingRequestManager();
} else {
this.tokenRequestManager_ =
new BlockingRequestManager(() => this.openPasswordPromptDialog_());
}
// </if>
// Request initial data.
this.passwordManager_.isOptedInForAccountStorage().then(
setIsOptedInForAccountStorageListener);
// Listen for changes.
this.passwordManager_.addAccountStorageOptInStateListener(
setIsOptedInForAccountStorageListener);
const syncBrowserProxy = SyncBrowserProxyImpl.getInstance();
const syncStatusChanged = (syncStatus: SyncStatus) => this.syncStatus_ =
syncStatus;
syncBrowserProxy.getSyncStatus().then(syncStatusChanged);
this.addWebUIListener('sync-status-changed', syncStatusChanged);
const syncPrefsChanged = (syncPrefs: SyncPrefs) => this.syncPrefs_ =
syncPrefs;
this.addWebUIListener('sync-prefs-changed', syncPrefsChanged);
syncBrowserProxy.sendSyncPrefsChanged();
// For non-ChromeOS, also check whether accounts are available.
// <if expr="not chromeos">
const storedAccountsChanged = (accounts: Array<StoredAccount>) =>
this.storedAccounts_ = accounts;
syncBrowserProxy.getStoredAccounts().then(storedAccountsChanged);
this.addWebUIListener('stored-accounts-updated', storedAccountsChanged);
// </if>
syncBrowserProxy.sendOfferTrustedVaultOptInChanged();
this.addWebUIListener(
'offer-trusted-vault-opt-in-changed', (offerOptIn: boolean) => {
this.shouldOfferTrustedVaultOptIn_ = offerOptIn;
});
afterNextRender(this, function() {
IronA11yAnnouncer.requestAvailability();
});
HatsBrowserProxyImpl.getInstance().trustSafetyInteractionOccurred(
TrustSafetyInteraction.OPENED_PASSWORD_MANAGER);
}
disconnectedCallback() {
super.disconnectedCallback();
this.passwordManager_.removeAccountStorageOptInStateListener(
assert(this.setIsOptedInForAccountStorageListener_!));
this.setIsOptedInForAccountStorageListener_ = null;
}
private computeSignedIn_(): boolean {
return !!this.syncStatus_ && !!this.syncStatus_.signedIn ?
!this.syncStatus_.hasError :
(!!this.storedAccounts_ && this.storedAccounts_.length > 0);
}
private computeEligibleForAccountStorage_(): boolean {
// The user must have signed in but should have sync disabled
// (|!this.syncStatus_.signedin|). They should not be using a custom
// passphrase to encrypt their sync data, since there's no way for account
// storage users to input their passphrase and decrypt the passwords.
return (!!this.syncStatus_ && !this.syncStatus_.signedIn) &&
this.signedIn_ && (!this.syncPrefs_ || !this.syncPrefs_.encryptAllData);
}
private computeHasSavedPasswords_(): boolean {
return this.savedPasswords.length > 0;
}
private computeNumberOfDevicePasswords_(): number {
return this.savedPasswords.filter(p => p.isPresentOnDevice()).length;
}
private computeHasPasswordExceptions_(): boolean {
return this.passwordExceptions.length > 0;
}
private computeShouldShowBanner_(): boolean {
return this.signedIn_ && this.hasSavedPasswords_ &&
this.hasNeverCheckedPasswords_ && !this.hasLeakedCredentials_;
}
private computeIsAccountStoreUser_(): boolean {
return this.eligibleForAccountStorage_ && this.isOptedInForAccountStorage_;
}
private computeShouldShowDevicePasswordsLink_(): boolean {
return this.isOptedInForAccountStorage_ &&
(this.numberOfDevicePasswords_ > 0);
}
/**
* hide the link to the user's Google Account if:
* a) the link is embedded in the account storage message OR
* b) the user is signed out (or signed-in but has encrypted passwords)
*/
private computeHidePasswordsLink_(): boolean {
return this.eligibleForAccountStorage_ ||
(!!this.syncStatus_ && !!this.syncStatus_.signedIn &&
!!this.syncPrefs_ && !!this.syncPrefs_.encryptAllData);
}
private computeHasLeakedCredentials_(): boolean {
return this.leakedPasswords.length > 0;
}
private computeHasNeverCheckedPasswords_(): boolean {
return !this.status.elapsedTimeSinceLastCheck;
}
/**
* Shows the check passwords sub page.
*/
private onCheckPasswordsClick_() {
Router.getInstance().navigateTo(
routes.CHECK_PASSWORDS, new URLSearchParams('start=true'));
this.passwordManager_.recordPasswordCheckReferrer(
PasswordCheckReferrer.PASSWORD_SETTINGS);
}
/**
* Shows the page to opt in to trusted vault encryption.
*/
private onTrustedVaultOptInClick_() {
OpenWindowProxyImpl.getInstance().openURL(
loadTimeData.getString('trustedVaultOptInUrl'));
}
/**
* Shows the 'device passwords' page.
*/
private onDevicePasswordsLinkClicked_() {
Router.getInstance().navigateTo(routes.DEVICE_PASSWORDS);
}
// <if expr="chromeos">
/**
* When this event fired, it means that the password-prompt-dialog succeeded
* in creating a fresh token in the quickUnlockPrivate API. Because new tokens
* can only ever be created immediately following a GAIA password check, the
* passwordsPrivate API can now safely grant requests for secure data (i.e.
* saved passwords) for a limited time. This observer resolves the request,
* triggering a callback that requires a fresh auth token to succeed and that
* was provided to the BlockingRequestManager by another DOM element seeking
* secure data.
*
* @param e - Contain newly created auth token
* chrome.quickUnlockPrivate.TokenInfo. Note that its precise value is not
* relevant here, only the facts that it's created.
*/
private onTokenObtained_(e: CustomEvent<any>) {
assert(e.detail);
this.tokenRequestManager_.resolve();
}
private onPasswordPromptClosed_() {
this.showPasswordPromptDialog_ = false;
focusWithoutInk(assert(this.activeDialogAnchorStack_.pop()!));
}
private openPasswordPromptDialog_() {
this.activeDialogAnchorStack_.push(getDeepActiveElement() as HTMLElement);
this.showPasswordPromptDialog_ = true;
}
// </if>
private passwordFilter_(): ((entry: MultiStorePasswordUiEntry) => boolean) {
return password => [password.urls.shown, password.username].some(
term => term.toLowerCase().includes(
this.filter.trim().toLowerCase()));
}
private passwordExceptionFilter_():
((entry: chrome.passwordsPrivate.ExceptionEntry) => boolean) {
return exception => exception.urls.shown.toLowerCase().includes(
this.filter.trim().toLowerCase());
}
/**
* Handle the shortcut to undo a removal of passwords/exceptions. This must
* be handled here and not at the PasswordsListHandler level because that
* component does not know about exception deletions.
*/
private onUndoKeyBinding_(event: Event) {
const activeElement = getDeepActiveElement();
// If the focused element is editable (e.g. search box) the undo event
// should be handled there and not here.
if (!activeElement || !isEditable(activeElement)) {
this.passwordManager_.undoRemoveSavedPasswordOrException();
this.$.passwordsListHandler.onSavedPasswordOrExceptionRemoved();
// Preventing the default is necessary to not conflict with a possible
// search action.
event.preventDefault();
}
}
/**
* Fires an event that should delete the password exception.
*/
private onRemoveExceptionButtonTap_(e: RepeaterEvent) {
const exception = e.model.item;
const allExceptionIds: Array<number> = [];
if (exception.isPresentInAccount()) {
allExceptionIds.push(exception.accountId!);
}
if (exception.isPresentOnDevice()) {
allExceptionIds.push(exception.deviceId!);
}
this.passwordManager_.removeExceptions(allExceptionIds);
}
/**
* Opens the export/import action menu.
*/
private onImportExportMenuTap_() {
const target = this.shadowRoot!.querySelector('#exportImportMenuButton') as
HTMLElement;
this.$.exportImportMenu.showAt(target);
this.activeDialogAnchorStack_.push(target);
}
/**
* Fires an event that should trigger the password import process.
*/
private onImportTap_() {
this.passwordManager_.importPasswords();
this.$.exportImportMenu.close();
}
/**
* Opens the export passwords dialog.
*/
private onExportTap_() {
this.showPasswordsExportDialog_ = true;
this.$.exportImportMenu.close();
}
private onPasswordsExportDialogClosed_() {
this.showPasswordsExportDialog_ = false;
focusWithoutInk(assert(this.activeDialogAnchorStack_.pop()!));
}
private onAddPasswordTap_() {
this.showAddPasswordDialog_ = true;
this.activeDialogAnchorStack_.push(
this.shadowRoot!.querySelector('#addPasswordButton')!);
}
private onAddPasswordDialogClosed_() {
this.showAddPasswordDialog_ = false;
focusWithoutInk(assert(this.activeDialogAnchorStack_.pop()!));
}
private onOptIn_() {
this.passwordManager_.optInForAccountStorage(true);
}
private onOptOut_() {
this.passwordManager_.optInForAccountStorage(false);
}
private showImportOrExportPasswords_(): boolean {
return this.hasSavedPasswords_ || this.showImportPasswords_;
}
/**
* Return the first available stored account. This is useful when trying to
* figure out the account logged into the content area which seems to always
* be first even if multiple accounts are available.
* @return The email address of the first stored account or an empty string.
*/
private getFirstStoredAccountEmail_(): string {
return !!this.storedAccounts_ && this.storedAccounts_.length > 0 ?
this.storedAccounts_[0].email :
'';
}
private focusConfigChanged_(_newConfig: FocusConfig, oldConfig: FocusConfig) {
// focusConfig is set only once on the parent, so this observer should
// only fire once.
assert(!oldConfig);
// Populate the |focusConfig| map of the parent <settings-autofill-page>
// element, with additional entries that correspond to subpage trigger
// elements residing in this element's Shadow DOM.
this.focusConfig.set(assert(routes.CHECK_PASSWORDS).path, () => {
focusWithoutInk(assert(this.shadowRoot!.querySelector('#icon')!));
});
}
private announceSearchResults_() {
if (!this.filter.trim()) {
return;
}
setTimeout(() => { // Async to allow list to update.
IronA11yAnnouncer.requestAvailability();
const total = this.shownPasswordsCount_ + this.shownExceptionsCount_;
let text;
switch (total) {
case 0:
text = this.i18n('noSearchResults');
break;
case 1:
text = this.i18n('searchResultsSingular', this.filter);
break;
default:
text =
this.i18n('searchResultsPlural', total.toString(), this.filter);
}
this.dispatchEvent(new CustomEvent('iron-announce', {
bubbles: true,
composed: true,
detail: {
text: text,
}
}));
}, 0);
}
}
customElements.define(PasswordsSectionElement.is, PasswordsSectionElement); | the_stack |
'use strict';
import * as CWC from 'crypto-wallet-core';
import { EventEmitter } from 'events';
import _ from 'lodash';
import sjcl from 'sjcl';
import { Constants, Utils } from './common';
import { Credentials } from './credentials';
import { Key } from './key';
import { PayPro } from './paypro';
import { PayProV2 } from './payproV2';
import { Request } from './request';
import { Verifier } from './verifier';
var $ = require('preconditions').singleton();
var util = require('util');
var async = require('async');
var events = require('events');
var Bitcore = CWC.BitcoreLib;
var Bitcore_ = {
btc: CWC.BitcoreLib,
bch: CWC.BitcoreLibCash,
eth: CWC.BitcoreLib,
xrp: CWC.BitcoreLib,
doge: CWC.BitcoreLibDoge,
ltc: CWC.BitcoreLibLtc
};
var Mnemonic = require('bitcore-mnemonic');
var url = require('url');
var querystring = require('querystring');
var log = require('./log');
const Errors = require('./errors');
var BASE_URL = 'http://localhost:3232/bws/api';
// /**
// * @desc ClientAPI constructor.
// *
// * @param {Object} opts
// * @constructor
// */
export class API extends EventEmitter {
doNotVerifyPayPro: any;
timeout: any;
logLevel: any;
supportStaffWalletId: any;
request: any;
credentials: any;
notificationIncludeOwn: boolean;
lastNotificationId: any;
notificationsIntervalId: any;
keyDerivationOk: boolean;
noSign: any;
password: any;
bp_partner: string;
bp_partner_version: string;
static PayProV2 = PayProV2;
static PayPro = PayPro;
static Key = Key;
static Verifier = Verifier;
static Core = CWC;
static Utils = Utils;
static sjcl = sjcl;
static errors = Errors;
// Expose bitcore
static Bitcore = CWC.BitcoreLib;
static BitcoreCash = CWC.BitcoreLibCash;
static BitcoreDoge = CWC.BitcoreLibDoge;
static BitcoreLtc = CWC.BitcoreLibLtc;
constructor(opts?) {
super();
opts = opts || {};
this.doNotVerifyPayPro = opts.doNotVerifyPayPro;
this.timeout = opts.timeout || 50000;
this.logLevel = opts.logLevel || 'silent';
this.supportStaffWalletId = opts.supportStaffWalletId;
this.bp_partner = opts.bp_partner;
this.bp_partner_version = opts.bp_partner_version;
this.request = new Request(opts.baseUrl || BASE_URL, {
r: opts.request,
supportStaffWalletId: opts.supportStaffWalletId
});
log.setLevel(this.logLevel);
}
static privateKeyEncryptionOpts = {
iter: 10000
};
initNotifications(cb) {
log.warn('DEPRECATED: use initialize() instead.');
this.initialize({}, cb);
}
initialize(opts, cb) {
$.checkState(
this.credentials,
'Failed state: this.credentials at <initialize()>'
);
this.notificationIncludeOwn = !!opts.notificationIncludeOwn;
this._initNotifications(opts);
return cb();
}
dispose(cb) {
this._disposeNotifications();
this.request.logout(cb);
}
_fetchLatestNotifications(interval, cb) {
cb = cb || function () {};
var opts: any = {
lastNotificationId: this.lastNotificationId,
includeOwn: this.notificationIncludeOwn
};
if (!this.lastNotificationId) {
opts.timeSpan = interval + 1;
}
this.getNotifications(opts, (err, notifications) => {
if (err) {
log.warn('Error receiving notifications.');
log.debug(err);
return cb(err);
}
if (notifications.length > 0) {
this.lastNotificationId = (_.last(notifications) as any).id;
}
_.each(notifications, notification => {
this.emit('notification', notification);
});
return cb();
});
}
_initNotifications(opts) {
opts = opts || {};
var interval = opts.notificationIntervalSeconds || 5;
this.notificationsIntervalId = setInterval(() => {
this._fetchLatestNotifications(interval, err => {
if (err) {
if (
err instanceof Errors.NOT_FOUND ||
err instanceof Errors.NOT_AUTHORIZED
) {
this._disposeNotifications();
}
}
});
}, interval * 1000);
}
_disposeNotifications() {
if (this.notificationsIntervalId) {
clearInterval(this.notificationsIntervalId);
this.notificationsIntervalId = null;
}
}
// /**
// * Reset notification polling with new interval
// * @param {Numeric} notificationIntervalSeconds - use 0 to pause notifications
// */
setNotificationsInterval(notificationIntervalSeconds) {
this._disposeNotifications();
if (notificationIntervalSeconds > 0) {
this._initNotifications({
notificationIntervalSeconds
});
}
}
getRootPath() {
return this.credentials.getRootPath();
}
// /**
// * Encrypt a message
// * @private
// * @static
// * @memberof Client.API
// * @param {String} message
// * @param {String} encryptingKey
// */
static _encryptMessage(message, encryptingKey) {
if (!message) return null;
return Utils.encryptMessage(message, encryptingKey);
}
_processTxNotes(notes) {
if (!notes) return;
var encryptingKey = this.credentials.sharedEncryptingKey;
_.each([].concat(notes), note => {
note.encryptedBody = note.body;
note.body = Utils.decryptMessageNoThrow(note.body, encryptingKey);
note.encryptedEditedByName = note.editedByName;
note.editedByName = Utils.decryptMessageNoThrow(
note.editedByName,
encryptingKey
);
});
}
// /**
// * Decrypt text fields in transaction proposals
// * @private
// * @static
// * @memberof Client.API
// * @param {Array} txps
// * @param {String} encryptingKey
// */
_processTxps(txps) {
if (!txps) return;
var encryptingKey = this.credentials.sharedEncryptingKey;
_.each([].concat(txps), txp => {
txp.encryptedMessage = txp.message;
txp.message =
Utils.decryptMessageNoThrow(txp.message, encryptingKey) || null;
txp.creatorName = Utils.decryptMessageNoThrow(
txp.creatorName,
encryptingKey
);
_.each(txp.actions, action => {
// CopayerName encryption is optional (not available in older wallets)
action.copayerName = Utils.decryptMessageNoThrow(
action.copayerName,
encryptingKey
);
action.comment = Utils.decryptMessageNoThrow(
action.comment,
encryptingKey
);
// TODO get copayerName from Credentials -> copayerId to copayerName
// action.copayerName = null;
});
_.each(txp.outputs, output => {
output.encryptedMessage = output.message;
output.message =
Utils.decryptMessageNoThrow(output.message, encryptingKey) || null;
});
txp.hasUnconfirmedInputs = _.some(txp.inputs, input => {
return input.confirmations == 0;
});
this._processTxNotes(txp.note);
});
}
validateKeyDerivation(opts, cb) {
var _deviceValidated;
opts = opts || {};
var c = this.credentials;
var testMessageSigning = (xpriv, xpub) => {
var nonHardenedPath = 'm/0/0';
var message =
'Lorem ipsum dolor sit amet, ne amet urbanitas percipitur vim, libris disputando his ne, et facer suavitate qui. Ei quidam laoreet sea. Cu pro dico aliquip gubergren, in mundi postea usu. Ad labitur posidonium interesset duo, est et doctus molestie adipiscing.';
var priv = xpriv.deriveChild(nonHardenedPath).privateKey;
var signature = Utils.signMessage(message, priv);
var pub = xpub.deriveChild(nonHardenedPath).publicKey;
return Utils.verifyMessage(message, signature, pub);
};
var testHardcodedKeys = () => {
var words =
'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about';
var xpriv = Mnemonic(words).toHDPrivateKey();
if (
xpriv.toString() !=
'xprv9s21ZrQH143K3GJpoapnV8SFfukcVBSfeCficPSGfubmSFDxo1kuHnLisriDvSnRRuL2Qrg5ggqHKNVpxR86QEC8w35uxmGoggxtQTPvfUu'
)
return false;
xpriv = xpriv.deriveChild("m/44'/0'/0'");
if (
xpriv.toString() !=
'xprv9xpXFhFpqdQK3TmytPBqXtGSwS3DLjojFhTGht8gwAAii8py5X6pxeBnQ6ehJiyJ6nDjWGJfZ95WxByFXVkDxHXrqu53WCRGypk2ttuqncb'
)
return false;
var xpub = Bitcore.HDPublicKey.fromString(
'xpub6BosfCnifzxcFwrSzQiqu2DBVTshkCXacvNsWGYJVVhhawA7d4R5WSWGFNbi8Aw6ZRc1brxMyWMzG3DSSSSoekkudhUd9yLb6qx39T9nMdj'
);
return testMessageSigning(xpriv, xpub);
};
// TODO => Key refactor to Key class.
var testLiveKeys = () => {
var words;
try {
words = c.getMnemonic();
} catch (ex) {}
var xpriv;
if (words && (!c.mnemonicHasPassphrase || opts.passphrase)) {
var m = new Mnemonic(words);
xpriv = m.toHDPrivateKey(opts.passphrase, c.network);
}
if (!xpriv) {
xpriv = new Bitcore.HDPrivateKey(c.xPrivKey);
}
xpriv = xpriv.deriveChild(c.getBaseAddressDerivationPath());
var xpub = new Bitcore.HDPublicKey(c.xPubKey);
return testMessageSigning(xpriv, xpub);
};
var hardcodedOk = true;
if (!_deviceValidated && !opts.skipDeviceValidation) {
hardcodedOk = testHardcodedKeys();
_deviceValidated = true;
}
// TODO
// var liveOk = (c.canSign() && !c.isPrivKeyEncrypted()) ? testLiveKeys() : true;
this.keyDerivationOk = hardcodedOk; // && liveOk;
return cb(null, this.keyDerivationOk);
}
// /**
// * toObj() wallet
// *
// * @param {Object} opts
// */
toObj() {
$.checkState(
this.credentials,
'Failed state: this.credentials at <toObj()>'
);
return this.credentials.toObj();
}
// /**
// * toString() wallet
// *
// * @param {Object} opts
// */
toString(opts) {
$.checkState(
this.credentials,
'Failed state: this.credentials at <toString()>'
);
$.checkArgument(!this.noSign, 'no Sign not supported');
$.checkArgument(!this.password, 'password not supported');
opts = opts || {};
var output;
output = JSON.stringify(this.toObj());
return output;
}
fromObj(credentials) {
$.checkArgument(_.isObject(credentials), 'Argument should be an object');
try {
credentials = Credentials.fromObj(credentials);
this.credentials = credentials;
} catch (ex) {
log.warn(`Error importing wallet: ${ex}`);
if (ex.toString().match(/Obsolete/)) {
throw new Errors.OBSOLETE_BACKUP();
} else {
throw new Errors.INVALID_BACKUP();
}
}
this.request.setCredentials(this.credentials);
}
// /**
// * fromString wallet
// *
// * @param {Object} str - The serialized JSON created with #export
// */
fromString(credentials) {
if (_.isObject(credentials)) {
log.warn(
'WARN: Please use fromObj instead of fromString when importing strings'
);
return this.fromObj(credentials);
}
let c;
try {
c = JSON.parse(credentials);
} catch (ex) {
log.warn(`Error importing wallet: ${ex}`);
throw new Errors.INVALID_BACKUP();
}
return this.fromObj(c);
}
decryptBIP38PrivateKey(encryptedPrivateKeyBase58, passphrase, opts, cb) {
var Bip38 = require('bip38');
var bip38 = new Bip38();
var privateKeyWif;
try {
privateKeyWif = bip38.decrypt(encryptedPrivateKeyBase58, passphrase);
} catch (ex) {
return cb(new Error('Could not decrypt BIP38 private key' + ex));
}
var privateKey = new Bitcore.PrivateKey(privateKeyWif);
var address = privateKey.publicKey.toAddress().toString();
var addrBuff = Buffer.from(address, 'ascii');
var actualChecksum = Bitcore.crypto.Hash.sha256sha256(addrBuff)
.toString('hex')
.substring(0, 8);
var expectedChecksum = Bitcore.encoding.Base58Check.decode(
encryptedPrivateKeyBase58
)
.toString('hex')
.substring(6, 14);
if (actualChecksum != expectedChecksum)
return cb(new Error('Incorrect passphrase'));
return cb(null, privateKeyWif);
}
getBalanceFromPrivateKey(privateKey, coin, cb) {
if (_.isFunction(coin)) {
cb = coin;
coin = 'btc';
}
var B = Bitcore_[coin];
var privateKey = new B.PrivateKey(privateKey);
var address = privateKey.publicKey.toAddress().toString(true);
this.getUtxos(
{
addresses: address
},
(err, utxos) => {
if (err) return cb(err);
return cb(null, _.sumBy(utxos, 'satoshis'));
}
);
}
buildTxFromPrivateKey(privateKey, destinationAddress, opts, cb) {
opts = opts || {};
var coin = opts.coin || 'btc';
var signingMethod = opts.signingMethod || 'ecdsa';
if (!_.includes(Constants.COINS, coin))
return cb(new Error('Invalid coin'));
if (coin == 'eth')
return cb(new Error('ETH not supported for this action'));
var B = Bitcore_[coin];
var privateKey = B.PrivateKey(privateKey);
var address = privateKey.publicKey.toAddress().toString(true);
async.waterfall(
[
next => {
this.getUtxos(
{
addresses: address
},
(err, utxos) => {
return next(err, utxos);
}
);
},
(utxos, next) => {
if (!_.isArray(utxos) || utxos.length == 0)
return next(new Error('No utxos found'));
var fee = opts.fee || 10000;
var amount = _.sumBy(utxos, 'satoshis') - fee;
if (amount <= 0) return next(new Errors.INSUFFICIENT_FUNDS());
var tx;
try {
var toAddress = B.Address.fromString(destinationAddress);
tx = new B.Transaction()
.from(utxos)
.to(toAddress, amount)
.fee(fee)
.sign(privateKey, undefined, signingMethod);
// Make sure the tx can be serialized
tx.serialize();
} catch (ex) {
log.error('Could not build transaction from private key', ex);
return next(new Errors.COULD_NOT_BUILD_TRANSACTION());
}
return next(null, tx);
}
],
cb
);
}
// /**
// * Open a wallet and try to complete the public key ring.
// *
// * @param {Callback} cb - The callback that handles the response. It returns a flag indicating that the wallet is complete.
// * @fires API#walletCompleted
// */
openWallet(opts, cb) {
if (_.isFunction(opts)) {
cb = opts;
}
opts = opts || {};
$.checkState(
this.credentials,
'Failed state: this.credentials at <openWallet()>'
);
if (this.credentials.isComplete() && this.credentials.hasWalletInfo())
return cb(null, true);
var qs = [];
qs.push('includeExtendedInfo=1');
qs.push('serverMessageArray=1');
this.request.get('/v3/wallets/?' + qs.join('&'), (err, ret) => {
if (err) return cb(err);
var wallet = ret.wallet;
this._processStatus(ret);
if (!this.credentials.hasWalletInfo()) {
var me = _.find(wallet.copayers, {
id: this.credentials.copayerId
});
if (!me) return cb(new Error('Copayer not in wallet'));
try {
this.credentials.addWalletInfo(
wallet.id,
wallet.name,
wallet.m,
wallet.n,
me.name,
opts
);
} catch (e) {
if (e.message) {
log.info('Trying credentials...', e.message);
}
if (e.message && e.message.match(/Bad\snr/)) {
return cb(new Errors.WALLET_DOES_NOT_EXIST());
}
throw e;
}
}
if (wallet.status != 'complete') return cb(null, ret);
if (this.credentials.walletPrivKey) {
if (!Verifier.checkCopayers(this.credentials, wallet.copayers)) {
return cb(new Errors.SERVER_COMPROMISED());
}
} else {
// this should only happen in AIR-GAPPED flows
log.warn('Could not verify copayers key (missing wallet Private Key)');
}
this.credentials.addPublicKeyRing(
this._extractPublicKeyRing(wallet.copayers)
);
this.emit('walletCompleted', wallet);
return cb(null, ret);
});
}
static _buildSecret(walletId, walletPrivKey, coin, network) {
if (_.isString(walletPrivKey)) {
walletPrivKey = Bitcore.PrivateKey.fromString(walletPrivKey);
}
var widHex = Buffer.from(walletId.replace(/-/g, ''), 'hex');
var widBase58 = new Bitcore.encoding.Base58(widHex).toString();
return (
_.padEnd(widBase58, 22, '0') +
walletPrivKey.toWIF() +
(network == 'testnet' ? 'T' : 'L') +
coin
);
}
static parseSecret(secret) {
$.checkArgument(secret);
var split = (str, indexes) => {
var parts = [];
indexes.push(str.length);
var i = 0;
while (i < indexes.length) {
parts.push(str.substring(i == 0 ? 0 : indexes[i - 1], indexes[i]));
i++;
}
return parts;
};
try {
var secretSplit = split(secret, [22, 74, 75]);
var widBase58 = secretSplit[0].replace(/0/g, '');
var widHex = Bitcore.encoding.Base58.decode(widBase58).toString('hex');
var walletId = split(widHex, [8, 12, 16, 20]).join('-');
var walletPrivKey = Bitcore.PrivateKey.fromString(secretSplit[1]);
var networkChar = secretSplit[2];
var coin = secretSplit[3] || 'btc';
return {
walletId,
walletPrivKey,
coin,
network: networkChar == 'T' ? 'testnet' : 'livenet'
};
} catch (ex) {
throw new Error('Invalid secret');
}
}
static getRawTx(txp) {
var t = Utils.buildTx(txp);
return t.uncheckedSerialize();
}
_getCurrentSignatures(txp) {
var acceptedActions = _.filter(txp.actions, {
type: 'accept'
});
return _.map(acceptedActions, x => {
return {
signatures: x.signatures,
xpub: x.xpub
};
});
}
_addSignaturesToBitcoreTxBitcoin(txp, t, signatures, xpub) {
$.checkState(
txp.coin,
'Failed state: txp.coin undefined at _addSignaturesToBitcoreTxBitcoin'
);
$.checkState(
txp.signingMethod,
'Failed state: txp.signingMethod undefined at _addSignaturesToBitcoreTxBitcoin'
);
const bitcore = Bitcore_[txp.coin];
if (signatures.length != txp.inputs.length)
throw new Error('Number of signatures does not match number of inputs');
let i = 0;
const x = new bitcore.HDPublicKey(xpub);
_.each(signatures, signatureHex => {
try {
const signature = bitcore.crypto.Signature.fromString(signatureHex);
const pub = x.deriveChild(txp.inputPaths[i]).publicKey;
const s = {
inputIndex: i,
signature,
sigtype:
// tslint:disable-next-line:no-bitwise
bitcore.crypto.Signature.SIGHASH_ALL |
bitcore.crypto.Signature.SIGHASH_FORKID,
publicKey: pub
};
t.inputs[i].addSignature(t, s, txp.signingMethod);
i++;
} catch (e) {}
});
if (i != txp.inputs.length) throw new Error('Wrong signatures');
}
_addSignaturesToBitcoreTx(txp, t, signatures, xpub) {
const { coin, network } = txp;
const chain = Utils.getChain(coin);
switch (chain) {
case 'XRP':
case 'ETH':
const unsignedTxs = t.uncheckedSerialize();
const signedTxs = [];
for (let index = 0; index < signatures.length; index++) {
const signed = CWC.Transactions.applySignature({
chain,
tx: unsignedTxs[index],
signature: signatures[index]
});
signedTxs.push(signed);
// bitcore users id for txid...
t.id = CWC.Transactions.getHash({ tx: signed, chain, network });
}
t.uncheckedSerialize = () => signedTxs;
t.serialize = () => signedTxs;
break;
default:
return this._addSignaturesToBitcoreTxBitcoin(txp, t, signatures, xpub);
}
}
_applyAllSignatures(txp, t) {
$.checkState(
txp.status == 'accepted',
'Failed state: txp.status at _applyAllSignatures'
);
var sigs = this._getCurrentSignatures(txp);
_.each(sigs, x => {
this._addSignaturesToBitcoreTx(txp, t, x.signatures, x.xpub);
});
}
// /**
// * Join
// * @private
// *
// * @param {String} walletId
// * @param {String} walletPrivKey
// * @param {String} xPubKey
// * @param {String} requestPubKey
// * @param {String} copayerName
// * @param {Object} Optional args
// * @param {String} opts.customData
// * @param {String} opts.coin
// * @param {Callback} cb
// */
_doJoinWallet(
walletId,
walletPrivKey,
xPubKey,
requestPubKey,
copayerName,
opts,
cb
) {
$.shouldBeFunction(cb);
opts = opts || {};
// Adds encrypted walletPrivateKey to CustomData
opts.customData = opts.customData || {};
opts.customData.walletPrivKey = walletPrivKey.toString();
var encCustomData = Utils.encryptMessage(
JSON.stringify(opts.customData),
this.credentials.personalEncryptingKey
);
var encCopayerName = Utils.encryptMessage(
copayerName,
this.credentials.sharedEncryptingKey
);
var args: any = {
walletId,
coin: opts.coin,
name: encCopayerName,
xPubKey,
requestPubKey,
customData: encCustomData
};
if (opts.dryRun) args.dryRun = true;
if (_.isBoolean(opts.supportBIP44AndP2PKH))
args.supportBIP44AndP2PKH = opts.supportBIP44AndP2PKH;
var hash = Utils.getCopayerHash(
args.name,
args.xPubKey,
args.requestPubKey
);
args.copayerSignature = Utils.signMessage(hash, walletPrivKey);
var url = '/v2/wallets/' + walletId + '/copayers';
this.request.post(url, args, (err, body) => {
if (err) return cb(err);
this._processWallet(body.wallet);
return cb(null, body.wallet);
});
}
// /**
// * Return if wallet is complete
// */
isComplete() {
return this.credentials && this.credentials.isComplete();
}
_extractPublicKeyRing(copayers) {
return _.map(copayers, copayer => {
var pkr: any = _.pick(copayer, ['xPubKey', 'requestPubKey']);
pkr.copayerName = copayer.name;
return pkr;
});
}
// /**
// * Get current fee levels for the specified network
// *
// * @param {string} coin - 'btc' (default) or 'bch'
// * @param {string} network - 'livenet' (default) or 'testnet'
// * @param {Callback} cb
// * @returns {Callback} cb - Returns error or an object with status information
// */
getFeeLevels(coin, network, cb) {
$.checkArgument(coin || _.includes(Constants.COINS, coin));
$.checkArgument(network || _.includes(['livenet', 'testnet'], network));
const chain = Utils.getChain(coin).toLowerCase();
this.request.get(
'/v2/feelevels/?coin=' +
(chain || 'btc') +
'&network=' +
(network || 'livenet'),
(err, result) => {
if (err) return cb(err);
return cb(err, result);
}
);
}
clearCache(cb) {
this.request.post('/v1/clearcache/', {}, (err, res) => {
return cb(err, res);
});
}
// /**
// * Get service version
// *
// * @param {Callback} cb
// */
getVersion(cb) {
this.request.get('/v1/version/', cb);
}
_checkKeyDerivation() {
var isInvalid = this.keyDerivationOk === false;
if (isInvalid) {
log.error('Key derivation for this device is not working as expected');
}
return !isInvalid;
}
// /**
// *
// * Create a wallet.
// * @param {String} walletName
// * @param {String} copayerName
// * @param {Number} m
// * @param {Number} n
// * @param {object} opts (optional: advanced options)
// * @param {string} opts.coin[='btc'] - The coin for this wallet (btc, bch).
// * @param {string} opts.network[='livenet']
// * @param {string} opts.singleAddress[=false] - The wallet will only ever have one address.
// * @param {String} opts.walletPrivKey - set a walletPrivKey (instead of random)
// * @param {String} opts.id - set a id for wallet (instead of server given)
// * @param {Boolean} opts.useNativeSegwit - set addressType to P2WPKH or P2WSH
// * @param cb
// * @return {undefined}
// */
createWallet(walletName, copayerName, m, n, opts, cb) {
if (!this._checkKeyDerivation())
return cb(new Error('Cannot create new wallet'));
if (opts) $.shouldBeObject(opts);
opts = opts || {};
var coin = opts.coin || 'btc';
if (!_.includes(Constants.COINS, coin))
return cb(new Error('Invalid coin'));
var network = opts.network || 'livenet';
if (!_.includes(['testnet', 'livenet'], network))
return cb(new Error('Invalid network'));
if (!this.credentials) {
return cb(new Error('Import credentials first with setCredentials()'));
}
if (coin != this.credentials.coin) {
return cb(new Error('Existing keys were created for a different coin'));
}
if (network != this.credentials.network) {
return cb(
new Error('Existing keys were created for a different network')
);
}
var walletPrivKey = opts.walletPrivKey || new Bitcore.PrivateKey();
var c = this.credentials;
c.addWalletPrivateKey(walletPrivKey.toString());
var encWalletName = Utils.encryptMessage(walletName, c.sharedEncryptingKey);
var args = {
name: encWalletName,
m,
n,
pubKey: new Bitcore.PrivateKey(walletPrivKey).toPublicKey().toString(),
coin,
network,
singleAddress: !!opts.singleAddress,
id: opts.id,
usePurpose48: n > 1,
useNativeSegwit: !!opts.useNativeSegwit
};
this.request.post('/v2/wallets/', args, (err, res) => {
if (err) return cb(err);
var walletId = res.walletId;
c.addWalletInfo(walletId, walletName, m, n, copayerName, {
useNativeSegwit: opts.useNativeSegwit
});
var secret = API._buildSecret(
c.walletId,
c.walletPrivKey,
c.coin,
c.network
);
this._doJoinWallet(
walletId,
walletPrivKey,
c.xPubKey,
c.requestPubKey,
copayerName,
{
coin
},
(err, wallet) => {
if (err) return cb(err);
return cb(null, n > 1 ? secret : null);
}
);
});
}
// /**
// * Join an existent wallet
// *
// * @param {String} secret
// * @param {String} copayerName
// * @param {Object} opts
// * @param {string} opts.coin[='btc'] - The expected coin for this wallet (btc, bch).
// * @param {Boolean} opts.dryRun[=false] - Simulate wallet join
// * @param {Callback} cb
// * @returns {Callback} cb - Returns the wallet
// */
joinWallet(secret, copayerName, opts, cb) {
if (!cb) {
cb = opts;
opts = {};
log.warn('DEPRECATED WARN: joinWallet should receive 4 parameters.');
}
if (!this._checkKeyDerivation()) return cb(new Error('Cannot join wallet'));
opts = opts || {};
var coin = opts.coin || 'btc';
if (!_.includes(Constants.COINS, coin))
return cb(new Error('Invalid coin'));
try {
var secretData = API.parseSecret(secret);
} catch (ex) {
return cb(ex);
}
if (!this.credentials) {
return cb(new Error('Import credentials first with setCredentials()'));
}
this.credentials.addWalletPrivateKey(secretData.walletPrivKey.toString());
this._doJoinWallet(
secretData.walletId,
secretData.walletPrivKey,
this.credentials.xPubKey,
this.credentials.requestPubKey,
copayerName,
{
coin,
dryRun: !!opts.dryRun
},
(err, wallet) => {
if (err) return cb(err);
if (!opts.dryRun) {
this.credentials.addWalletInfo(
wallet.id,
wallet.name,
wallet.m,
wallet.n,
copayerName,
{
useNativeSegwit:
wallet.addressType === Constants.SCRIPT_TYPES.P2WSH,
allowOverwrite: true
}
);
}
return cb(null, wallet);
}
);
}
// /**
// * Recreates a wallet, given credentials (with wallet id)
// *
// * @returns {Callback} cb - Returns the wallet
// */
recreateWallet(cb) {
$.checkState(
this.credentials,
'Failed state: this.credentials at <recreateWallet()>'
);
$.checkState(this.credentials.isComplete());
$.checkState(this.credentials.walletPrivKey);
// $.checkState(this.credentials.hasWalletInfo());
// First: Try to get the wallet with current credentials
this.getStatus(
{
includeExtendedInfo: true
},
err => {
// No error? -> Wallet is ready.
if (!err) {
log.info('Wallet is already created');
return cb();
}
var c = this.credentials;
var walletPrivKey = Bitcore.PrivateKey.fromString(c.walletPrivKey);
var walletId = c.walletId;
var useNativeSegwit = c.addressType === Constants.SCRIPT_TYPES.P2WPKH;
var supportBIP44AndP2PKH =
c.derivationStrategy != Constants.DERIVATION_STRATEGIES.BIP45;
var encWalletName = Utils.encryptMessage(
c.walletName || 'recovered wallet',
c.sharedEncryptingKey
);
var coin = c.coin;
var args = {
name: encWalletName,
m: c.m,
n: c.n,
pubKey: walletPrivKey.toPublicKey().toString(),
coin: c.coin,
network: c.network,
id: walletId,
usePurpose48: c.n > 1,
useNativeSegwit
};
if (!!supportBIP44AndP2PKH)
args['supportBIP44AndP2PKH'] = supportBIP44AndP2PKH;
this.request.post('/v2/wallets/', args, (err, body) => {
if (err) {
// return all errors. Can't call addAccess.
log.info('openWallet error' + err);
return cb(new Errors.WALLET_DOES_NOT_EXIST());
}
if (!walletId) {
walletId = body.walletId;
}
var i = 1;
var opts = {
coin: c.coin
};
if (!!supportBIP44AndP2PKH)
opts['supportBIP44AndP2PKH'] = supportBIP44AndP2PKH;
async.each(
this.credentials.publicKeyRing,
(item, next) => {
var name = item.copayerName || 'copayer ' + i++;
this._doJoinWallet(
walletId,
walletPrivKey,
item.xPubKey,
item.requestPubKey,
name,
opts,
err => {
// Ignore error is copayer already in wallet
if (err && err instanceof Errors.COPAYER_IN_WALLET)
return next();
return next(err);
}
);
},
cb
);
});
}
);
}
_processWallet(wallet) {
var encryptingKey = this.credentials.sharedEncryptingKey;
var name = Utils.decryptMessageNoThrow(wallet.name, encryptingKey);
if (name != wallet.name) {
wallet.encryptedName = wallet.name;
}
wallet.name = name;
_.each(wallet.copayers, copayer => {
var name = Utils.decryptMessageNoThrow(copayer.name, encryptingKey);
if (name != copayer.name) {
copayer.encryptedName = copayer.name;
}
copayer.name = name;
_.each(copayer.requestPubKeys, access => {
if (!access.name) return;
var name = Utils.decryptMessageNoThrow(access.name, encryptingKey);
if (name != access.name) {
access.encryptedName = access.name;
}
access.name = name;
});
});
}
_processStatus(status) {
var processCustomData = data => {
var copayers = data.wallet.copayers;
if (!copayers) return;
var me = _.find(copayers, {
id: this.credentials.copayerId
});
if (!me || !me.customData) return;
var customData;
try {
customData = JSON.parse(
Utils.decryptMessage(
me.customData,
this.credentials.personalEncryptingKey
)
);
} catch (e) {
log.warn('Could not decrypt customData:', me.customData);
}
if (!customData) return;
// Add it to result
data.customData = customData;
// Update walletPrivateKey
if (!this.credentials.walletPrivKey && customData.walletPrivKey)
this.credentials.addWalletPrivateKey(customData.walletPrivKey);
};
processCustomData(status);
this._processWallet(status.wallet);
this._processTxps(status.pendingTxps);
}
// /**
// * Get latest notifications
// *
// * @param {object} opts
// * @param {String} opts.lastNotificationId (optional) - The ID of the last received notification
// * @param {String} opts.timeSpan (optional) - A time window on which to look for notifications (in seconds)
// * @param {String} opts.includeOwn[=false] (optional) - Do not ignore notifications generated by the current copayer
// * @returns {Callback} cb - Returns error or an array of notifications
// */
getNotifications(opts, cb) {
$.checkState(
this.credentials,
'Failed state: this.credentials at <getNotifications()>'
);
opts = opts || {};
var url = '/v1/notifications/';
if (opts.lastNotificationId) {
url += '?notificationId=' + opts.lastNotificationId;
} else if (opts.timeSpan) {
url += '?timeSpan=' + opts.timeSpan;
}
this.request.getWithLogin(url, (err, result) => {
if (err) return cb(err);
var notifications = _.filter(result, notification => {
return (
opts.includeOwn ||
notification.creatorId != this.credentials.copayerId
);
});
return cb(null, notifications);
});
}
// /**
// * Get status of the wallet
// *
// * @param {Boolean} opts.twoStep[=false] - Optional: use 2-step balance computation for improved performance
// * @param {Boolean} opts.includeExtendedInfo (optional: query extended status)
// * @param {String} opts.tokenAddress (optional: ERC20 Token Contract Address)
// * @param {String} opts.multisigContractAddress (optional: MULTISIG ETH Contract Address)
// * @returns {Callback} cb - Returns error or an object with status information
// */
getStatus(opts, cb) {
$.checkState(
this.credentials,
'Failed state: this.credentials at <getStatus()>'
);
if (!cb) {
cb = opts;
opts = {};
log.warn('DEPRECATED WARN: getStatus should receive 2 parameters.');
}
opts = opts || {};
var qs = [];
qs.push('includeExtendedInfo=' + (opts.includeExtendedInfo ? '1' : '0'));
qs.push('twoStep=' + (opts.twoStep ? '1' : '0'));
qs.push('serverMessageArray=1');
if (opts.tokenAddress) {
qs.push('tokenAddress=' + opts.tokenAddress);
}
if (opts.multisigContractAddress) {
qs.push('multisigContractAddress=' + opts.multisigContractAddress);
qs.push('network=' + this.credentials.network);
}
this.request.get('/v3/wallets/?' + qs.join('&'), (err, result) => {
if (err) return cb(err);
if (result.wallet.status == 'pending') {
var c = this.credentials;
result.wallet.secret = API._buildSecret(
c.walletId,
c.walletPrivKey,
c.coin,
c.network
);
}
this._processStatus(result);
return cb(err, result);
});
}
// /**
// * Get copayer preferences
// *
// * @param {Callback} cb
// * @return {Callback} cb - Return error or object
// */
getPreferences(cb) {
$.checkState(
this.credentials,
'Failed state: this.credentials at <getPreferences()>'
);
$.checkArgument(cb);
this.request.get('/v1/preferences/', (err, preferences) => {
if (err) return cb(err);
return cb(null, preferences);
});
}
// /**
// * Save copayer preferences
// *
// * @param {Object} preferences
// * @param {Callback} cb
// * @return {Callback} cb - Return error or object
// */
savePreferences(preferences, cb) {
$.checkState(
this.credentials,
'Failed state: this.credentials at <savePreferences()>'
);
$.checkArgument(cb);
this.request.put('/v1/preferences/', preferences, cb);
}
// /**
// * fetchPayPro
// *
// * @param opts.payProUrl URL for paypro request
// * @returns {Callback} cb - Return error or the parsed payment protocol request
// * Returns (err,paypro)
// * paypro.amount
// * paypro.toAddress
// * paypro.memo
// */
fetchPayPro(opts, cb) {
$.checkArgument(opts).checkArgument(opts.payProUrl);
PayPro.get(
{
url: opts.payProUrl,
coin: this.credentials.coin || 'btc',
network: this.credentials.network || 'livenet',
// for testing
request: this.request
},
(err, paypro) => {
if (err) return cb(err);
return cb(null, paypro);
}
);
}
// /**
// * Gets list of utxos
// *
// * @param {Function} cb
// * @param {Object} opts
// * @param {Array} opts.addresses (optional) - List of addresses from where to fetch UTXOs.
// * @returns {Callback} cb - Return error or the list of utxos
// */
getUtxos(opts, cb) {
$.checkState(
this.credentials && this.credentials.isComplete(),
'Failed state: this.credentials at <getUtxos()>'
);
opts = opts || {};
var url = '/v1/utxos/';
if (opts.addresses) {
url +=
'?' +
querystring.stringify({
addresses: [].concat(opts.addresses).join(',')
});
}
this.request.get(url, cb);
}
// /**
// * Gets list of coins
// *
// * @param {Function} cb
// * @param {String} opts.coin - Current tx coin
// * @param {String} opts.network - Current tx network
// * @param {String} opts.txId - Current tx id
// * @returns {Callback} cb - Return error or the list of coins
// */
getCoinsForTx(opts, cb) {
$.checkState(
this.credentials && this.credentials.isComplete(),
'Failed state: this.credentials at <getCoinsForTx()>'
);
opts = opts || {};
var url = '/v1/txcoins/';
url +=
'?' +
querystring.stringify({
coin: opts.coin,
network: opts.network,
txId: opts.txId
});
this.request.get(url, cb);
}
_getCreateTxProposalArgs(opts) {
var args = _.cloneDeep(opts);
args.message =
API._encryptMessage(opts.message, this.credentials.sharedEncryptingKey) ||
null;
args.payProUrl = opts.payProUrl || null;
args.isTokenSwap = opts.isTokenSwap || null;
_.each(args.outputs, o => {
o.message =
API._encryptMessage(o.message, this.credentials.sharedEncryptingKey) ||
null;
});
return args;
}
// /**
// * Create a transaction proposal
// *
// * @param {Object} opts
// * @param {string} opts.txProposalId - Optional. If provided it will be used as this TX proposal ID. Should be unique in the scope of the wallet.
// * @param {Array} opts.outputs - List of outputs.
// * @param {string} opts.outputs[].toAddress - Destination address.
// * @param {number} opts.outputs[].amount - Amount to transfer in satoshi.
// * @param {string} opts.outputs[].message - A message to attach to this output.
// * @param {string} opts.message - A message to attach to this transaction.
// * @param {number} opts.feeLevel[='normal'] - Optional. Specify the fee level for this TX ('priority', 'normal', 'economy', 'superEconomy').
// * @param {number} opts.feePerKb - Optional. Specify the fee per KB for this TX (in satoshi).
// * @param {string} opts.changeAddress - Optional. Use this address as the change address for the tx. The address should belong to the wallet. In the case of singleAddress wallets, the first main address will be used.
// * @param {Boolean} opts.sendMax - Optional. Send maximum amount of funds that make sense under the specified fee/feePerKb conditions. (defaults to false).
// * @param {string} opts.payProUrl - Optional. Paypro URL for peers to verify TX
// * @param {Boolean} opts.excludeUnconfirmedUtxos[=false] - Optional. Do not use UTXOs of unconfirmed transactions as inputs
// * @param {Boolean} opts.dryRun[=false] - Optional. Simulate the action but do not change server state.
// * @param {Array} opts.inputs - Optional. Inputs for this TX
// * @param {number} opts.fee - Optional. Use an fixed fee for this TX (only when opts.inputs is specified)
// * @param {Boolean} opts.noShuffleOutputs - Optional. If set, TX outputs won't be shuffled. Defaults to false
// * @param {String} opts.signingMethod - Optional. If set, force signing method (ecdsa or schnorr) otherwise use default for coin
// * @param {Boolean} opts.isTokenSwap - Optional. To specify if we are trying to make a token swap
// * @returns {Callback} cb - Return error or the transaction proposal
// * @param {String} baseUrl - Optional. ONLY FOR TESTING
// */
createTxProposal(opts, cb, baseUrl) {
$.checkState(
this.credentials && this.credentials.isComplete(),
'Failed state: this.credentials at <createTxProposal()>'
);
$.checkState(this.credentials.sharedEncryptingKey);
$.checkArgument(opts);
// BCH schnorr deployment
if (!opts.signingMethod && this.credentials.coin == 'bch') {
opts.signingMethod = 'schnorr';
}
var args = this._getCreateTxProposalArgs(opts);
baseUrl = baseUrl || '/v3/txproposals/';
// baseUrl = baseUrl || '/v4/txproposals/'; // DISABLED 2020-04-07
this.request.post(baseUrl, args, (err, txp) => {
if (err) return cb(err);
this._processTxps(txp);
if (
!Verifier.checkProposalCreation(
args,
txp,
this.credentials.sharedEncryptingKey
)
) {
return cb(new Errors.SERVER_COMPROMISED());
}
return cb(null, txp);
});
}
// /**
// * Publish a transaction proposal
// *
// * @param {Object} opts
// * @param {Object} opts.txp - The transaction proposal object returned by the API#createTxProposal method
// * @returns {Callback} cb - Return error or null
// */
publishTxProposal(opts, cb) {
$.checkState(
this.credentials && this.credentials.isComplete(),
'Failed state: this.credentials at <publishTxProposal()>'
);
$.checkArgument(opts).checkArgument(opts.txp);
$.checkState(parseInt(opts.txp.version) >= 3);
var t = Utils.buildTx(opts.txp);
var hash = t.uncheckedSerialize();
var args = {
proposalSignature: Utils.signMessage(
hash,
this.credentials.requestPrivKey
)
};
var url = '/v2/txproposals/' + opts.txp.id + '/publish/';
this.request.post(url, args, (err, txp) => {
if (err) return cb(err);
this._processTxps(txp);
return cb(null, txp);
});
}
// /**
// * Create a new address
// *
// * @param {Object} opts
// * @param {Boolean} opts.ignoreMaxGap[=false]
// * @param {Boolean} opts.isChange[=false]
// * @param {Callback} cb
// * @returns {Callback} cb - Return error or the address
// */
createAddress(opts, cb) {
$.checkState(
this.credentials && this.credentials.isComplete(),
'Failed state: this.credentials at <createAddress()>'
);
if (!cb) {
cb = opts;
opts = {};
log.warn('DEPRECATED WARN: createAddress should receive 2 parameters.');
}
if (!this._checkKeyDerivation())
return cb(new Error('Cannot create new address for this wallet'));
opts = opts || {};
this.request.post('/v4/addresses/', opts, (err, address) => {
if (err) return cb(err);
if (!Verifier.checkAddress(this.credentials, address)) {
return cb(new Errors.SERVER_COMPROMISED());
}
return cb(null, address);
});
}
// /**
// * Get your main addresses
// *
// * @param {Object} opts
// * @param {Boolean} opts.doNotVerify
// * @param {Numeric} opts.limit (optional) - Limit the resultset. Return all addresses by default.
// * @param {Boolean} [opts.reverse=false] (optional) - Reverse the order of returned addresses.
// * @param {Callback} cb
// * @returns {Callback} cb - Return error or the array of addresses
// */
getMainAddresses(opts, cb) {
$.checkState(this.credentials && this.credentials.isComplete());
opts = opts || {};
var args = [];
if (opts.limit) args.push('limit=' + opts.limit);
if (opts.reverse) args.push('reverse=1');
var qs = '';
if (args.length > 0) {
qs = '?' + args.join('&');
}
var url = '/v1/addresses/' + qs;
this.request.get(url, (err, addresses) => {
if (err) return cb(err);
if (!opts.doNotVerify) {
var fake = _.some(addresses, address => {
return !Verifier.checkAddress(this.credentials, address);
});
if (fake) return cb(new Errors.SERVER_COMPROMISED());
}
return cb(null, addresses);
});
}
// /**
// * Update wallet balance
// *
// * @param {String} opts.coin - Optional: defaults to current wallet coin
// * @param {String} opts.tokenAddress - Optional: ERC20 token contract address
// * @param {String} opts.multisigContractAddress optional: MULTISIG ETH Contract Address
// * @param {Callback} cb
// */
getBalance(opts, cb) {
if (!cb) {
cb = opts;
opts = {};
log.warn('DEPRECATED WARN: getBalance should receive 2 parameters.');
}
opts = opts || {};
$.checkState(
this.credentials && this.credentials.isComplete(),
'Failed state: this.credentials at <getBalance()>'
);
var args = [];
if (opts.coin) {
args.push('coin=' + opts.coin);
}
if (opts.tokenAddress) {
args.push('tokenAddress=' + opts.tokenAddress);
}
if (opts.multisigContractAddress) {
args.push('multisigContractAddress=' + opts.multisigContractAddress);
}
var qs = '';
if (args.length > 0) {
qs = '?' + args.join('&');
}
var url = '/v1/balance/' + qs;
this.request.get(url, cb);
}
// /**
// * Get list of transactions proposals
// *
// * @param {Object} opts
// * @param {Boolean} opts.doNotVerify
// * @param {Boolean} opts.forAirGapped
// * @param {Boolean} opts.doNotEncryptPkr
// * @return {Callback} cb - Return error or array of transactions proposals
// */
getTxProposals(opts, cb) {
$.checkState(
this.credentials && this.credentials.isComplete(),
'Failed state: this.credentials at <getTxProposals()>'
);
this.request.get('/v2/txproposals/', (err, txps) => {
if (err) return cb(err);
this._processTxps(txps);
async.every(
txps,
(txp, acb) => {
if (opts.doNotVerify) return acb(true);
this.getPayProV2(txp)
.then(paypro => {
var isLegit = Verifier.checkTxProposal(this.credentials, txp, {
paypro
});
return acb(isLegit);
})
.catch(err => {
return acb(err);
});
},
isLegit => {
if (!isLegit) return cb(new Errors.SERVER_COMPROMISED());
var result;
if (opts.forAirGapped) {
result = {
txps: JSON.parse(JSON.stringify(txps)),
encryptedPkr: opts.doNotEncryptPkr
? null
: Utils.encryptMessage(
JSON.stringify(this.credentials.publicKeyRing),
this.credentials.personalEncryptingKey
),
unencryptedPkr: opts.doNotEncryptPkr
? JSON.stringify(this.credentials.publicKeyRing)
: null,
m: this.credentials.m,
n: this.credentials.n
};
} else {
result = txps;
}
return cb(null, result);
}
);
});
}
// private?
getPayPro(txp, cb) {
if (!txp.payProUrl || this.doNotVerifyPayPro) return cb();
PayPro.get(
{
url: txp.payProUrl,
coin: txp.coin || 'btc',
network: txp.network || 'livenet',
// for testing
request: this.request
},
(err, paypro) => {
if (err)
return cb(
new Error(
'Could not fetch invoice:' + (err.message ? err.message : err)
)
);
return cb(null, paypro);
}
);
}
getPayProV2(txp) {
if (!txp.payProUrl || this.doNotVerifyPayPro) return Promise.resolve();
const chain = Utils.getChain(txp.coin);
const currency = txp.coin.toUpperCase();
const payload = {
address: txp.from
};
return PayProV2.selectPaymentOption({
paymentUrl: txp.payProUrl,
chain,
currency,
payload
});
}
// /**
// * push transaction proposal signatures
// *
// * @param {Object} txp
// * @param {Array} signatures
// * @param {base} base url (ONLY FOR TESTING)
// * @param {Callback} cb
// * @return {Callback} cb - Return error or object
// */
pushSignatures(txp, signatures, cb, base) {
$.checkState(
this.credentials && this.credentials.isComplete(),
'Failed state: this.credentials at <pushSignatures()>'
);
$.checkArgument(txp.creatorId);
if (_.isEmpty(signatures)) {
return cb('No signatures to push. Sign the transaction with Key first');
}
this.getPayProV2(txp)
.then(paypro => {
var isLegit = Verifier.checkTxProposal(this.credentials, txp, {
paypro
});
if (!isLegit) return cb(new Errors.SERVER_COMPROMISED());
let defaultBase = '/v2/txproposals/';
base = base || defaultBase;
// base = base || '/v2/txproposals/'; // DISABLED 2020-04-07
let url = base + txp.id + '/signatures/';
var args = {
signatures
};
this.request.post(url, args, (err, txp) => {
if (err) return cb(err);
this._processTxps(txp);
return cb(null, txp);
});
})
.catch(err => {
return cb(err);
});
}
/**
* Create advertisement for bitpay app - (limited to marketing staff)
* @param opts - options
*/
createAdvertisement(opts, cb) {
// TODO add check for preconditions of title, imgUrl, linkUrl
var url = '/v1/advertisements/';
let args = opts;
this.request.post(url, args, (err, createdAd) => {
if (err) {
return cb(err);
}
return cb(null, createdAd);
});
}
/**
* Get advertisements for bitpay app - (limited to marketing staff)
* @param opts - options
* @param opts.testing - if set, fetches testing advertisements
*/
getAdvertisements(opts, cb) {
var url = '/v1/advertisements/';
if (opts.testing === true) {
url = '/v1/advertisements/' + '?testing=true';
}
this.request.get(url, (err, ads) => {
if (err) {
return cb(err);
}
return cb(null, ads);
});
}
/**
* Get advertisements for bitpay app, for specified country - (limited to marketing staff)
* @param opts - options
* @param opts.country - if set, fetches ads by Country
*/
getAdvertisementsByCountry(opts, cb) {
var url = '/v1/advertisements/country/' + opts.country;
this.request.get(url, (err, ads) => {
if (err) {
return cb(err);
}
return cb(null, ads);
});
}
/**
* Get Advertisement
* @param opts - options
*/
getAdvertisement(opts, cb) {
var url = '/v1/advertisements/' + opts.adId; // + adId or adTitle;
this.request.get(url, (err, body) => {
if (err) {
return cb(err);
}
return cb(null, body);
});
}
/**
* Activate Advertisement
* @param opts - options
*/
activateAdvertisement(opts, cb) {
var url = '/v1/advertisements/' + opts.adId + '/activate'; // + adId or adTitle;
let args = opts;
this.request.post(url, args, (err, body) => {
if (err) {
return cb(err);
}
return cb(null, body);
});
}
/**
* Deactivate Advertisement
* @param opts - options
*/
deactivateAdvertisement(opts, cb) {
var url = '/v1/advertisements/' + opts.adId + '/deactivate'; // + adId or adTitle;
let args = opts;
this.request.post(url, args, (err, body) => {
if (err) {
return cb(err);
}
return cb(null, body);
});
}
/**
* Delete Advertisement
* @param opts - options
*/
deleteAdvertisement(opts, cb) {
var url = '/v1/advertisements/' + opts.adId; // + adId or adTitle;
this.request.delete(url, (err, body) => {
if (err) {
return cb(err);
}
return cb(null, body);
});
}
/*
// /**
// * Sign transaction proposal from AirGapped
// *
// * @param {Object} txp
// * @param {String} encryptedPkr
// * @param {Number} m
// * @param {Number} n
// * @param {String} password - (optional) A password to decrypt the encrypted private key (if encryption is set).
// * @return {Object} txp - Return transaction
// */
signTxProposalFromAirGapped(txp, encryptedPkr, m, n, password) {
throw new Error(
'signTxProposalFromAirGapped not yet implemented in v9.0.0'
);
// $.checkState(this.credentials);
// if (!this.canSign())
// throw new Errors.MISSING_PRIVATE_KEY;
// if (this.isPrivKeyEncrypted() && !password)
// throw new Errors.ENCRYPTED_PRIVATE_KEY;
// var publicKeyRing;
// try {
// publicKeyRing = JSON.parse(Utils.decryptMessage(encryptedPkr, this.credentials.personalEncryptingKey));
// } catch (ex) {
// throw new Error('Could not decrypt public key ring');
// }
// if (!_.isArray(publicKeyRing) || publicKeyRing.length != n) {
// throw new Error('Invalid public key ring');
// }
// this.credentials.m = m;
// this.credentials.n = n;
// this.credentials.addressType = txp.addressType;
// this.credentials.addPublicKeyRing(publicKeyRing);
// if (!Verifier.checkTxProposalSignature(this.credentials, txp))
// throw new Error('Fake transaction proposal');
// return this._signTxp(txp, password);
}
// /**
// * Sign transaction proposal from AirGapped
// *
// * @param {String} key - A mnemonic phrase or an xprv HD private key
// * @param {Object} txp
// * @param {String} unencryptedPkr
// * @param {Number} m
// * @param {Number} n
// * @param {Object} opts
// * @param {String} opts.coin (default 'btc')
// * @param {String} opts.passphrase
// * @param {Number} opts.account - default 0
// * @param {String} opts.derivationStrategy - default 'BIP44'
// * @return {Object} txp - Return transaction
// */
static signTxProposalFromAirGapped(key, txp, unencryptedPkr, m, n, opts, cb) {
opts = opts || {};
var coin = opts.coin || 'btc';
if (!_.includes(Constants.COINS, coin))
return cb(new Error('Invalid coin'));
var publicKeyRing = JSON.parse(unencryptedPkr);
if (!_.isArray(publicKeyRing) || publicKeyRing.length != n) {
throw new Error('Invalid public key ring');
}
var newClient: any = new API({
baseUrl: 'https://bws.example.com/bws/api'
});
// TODO TODO TODO
if (key.slice(0, 4) === 'xprv' || key.slice(0, 4) === 'tprv') {
if (key.slice(0, 4) === 'xprv' && txp.network == 'testnet')
throw new Error('testnet HD keys must start with tprv');
if (key.slice(0, 4) === 'tprv' && txp.network == 'livenet')
throw new Error('livenet HD keys must start with xprv');
newClient.seedFromExtendedPrivateKey(key, {
coin,
account: opts.account,
derivationStrategy: opts.derivationStrategy
});
} else {
newClient.seedFromMnemonic(key, {
coin,
network: txp.network,
passphrase: opts.passphrase,
account: opts.account,
derivationStrategy: opts.derivationStrategy
});
}
newClient.credentials.m = m;
newClient.credentials.n = n;
newClient.credentials.addressType = txp.addressType;
newClient.credentials.addPublicKeyRing(publicKeyRing);
if (!Verifier.checkTxProposalSignature(newClient.credentials, txp))
throw new Error('Fake transaction proposal');
return newClient._signTxp(txp);
}
// /**
// * Reject a transaction proposal
// *
// * @param {Object} txp
// * @param {String} reason
// * @param {Callback} cb
// * @return {Callback} cb - Return error or object
// */
rejectTxProposal(txp, reason, cb) {
$.checkState(
this.credentials && this.credentials.isComplete(),
'Failed state: this.credentials at <rejectTxProposal()>'
);
$.checkArgument(cb);
var url = '/v1/txproposals/' + txp.id + '/rejections/';
var args = {
reason:
API._encryptMessage(reason, this.credentials.sharedEncryptingKey) || ''
};
this.request.post(url, args, (err, txp) => {
if (err) return cb(err);
this._processTxps(txp);
return cb(null, txp);
});
}
// /**
// * Broadcast raw transaction
// *
// * @param {Object} opts
// * @param {String} opts.network
// * @param {String} opts.rawTx
// * @param {Callback} cb
// * @return {Callback} cb - Return error or txid
// */
broadcastRawTx(opts, cb) {
$.checkState(
this.credentials,
'Failed state: this.credentials at <broadcastRawTx()>'
);
$.checkArgument(cb);
opts = opts || {};
var url = '/v1/broadcast_raw/';
this.request.post(url, opts, (err, txid) => {
if (err) return cb(err);
return cb(null, txid);
});
}
_doBroadcast(txp, cb) {
var url = '/v1/txproposals/' + txp.id + '/broadcast/';
this.request.post(url, {}, (err, txp) => {
if (err) return cb(err);
this._processTxps(txp);
return cb(null, txp);
});
}
// /**
// * Broadcast a transaction proposal
// *
// * @param {Object} txp
// * @param {Callback} cb
// * @return {Callback} cb - Return error or object
// */
broadcastTxProposal(txp, cb) {
$.checkState(
this.credentials && this.credentials.isComplete(),
'Failed state: this.credentials at <broadcastTxProposal()>'
);
this.getPayProV2(txp)
.then(paypro => {
if (paypro) {
var t_unsigned = Utils.buildTx(txp);
var t = _.cloneDeep(t_unsigned);
this._applyAllSignatures(txp, t);
const chain = Utils.getChain(txp.coin);
const currency = txp.coin.toUpperCase();
const rawTxUnsigned = t_unsigned.uncheckedSerialize();
const serializedTx = t.serialize({
disableSmallFees: true,
disableLargeFees: true,
disableDustOutputs: true
});
const unsignedTransactions = [];
const signedTransactions = [];
// Convert string to array if string
const unserializedTxs =
typeof rawTxUnsigned === 'string' ? [rawTxUnsigned] : rawTxUnsigned;
const serializedTxs =
typeof serializedTx === 'string' ? [serializedTx] : serializedTx;
const weightedSize = [];
let isSegwit =
(txp.coin == 'btc' || txp.coin == 'ltc') &&
(txp.addressType == 'P2WSH' || txp.addressType == 'P2WPKH');
let i = 0;
for (const unsigned of unserializedTxs) {
let size;
if (isSegwit) {
// we dont have a fast way to calculate weigthedSize`
size = Math.floor((txp.fee / txp.feePerKb) * 1000) - 10;
} else {
size = serializedTxs[i].length / 2;
}
unsignedTransactions.push({
tx: unsigned,
weightedSize: size
});
weightedSize.push(size);
i++;
}
i = 0;
for (const signed of serializedTxs) {
signedTransactions.push({
tx: signed,
weightedSize: weightedSize[i++],
escrowReclaimTx: txp.escrowReclaimTx
});
}
PayProV2.verifyUnsignedPayment({
paymentUrl: txp.payProUrl,
chain,
currency,
unsignedTransactions
})
.then(() => {
PayProV2.sendSignedPayment({
paymentUrl: txp.payProUrl,
chain,
currency,
signedTransactions,
bpPartner: {
bp_partner: this.bp_partner,
bp_partner_version: this.bp_partner_version
}
})
.then(payProDetails => {
if (payProDetails.memo) {
log.debug('Merchant memo:', payProDetails.memo);
}
return cb(null, txp, payProDetails.memo);
})
.catch(err => {
return cb(err);
});
})
.catch(err => {
return cb(err);
});
} else {
this._doBroadcast(txp, cb);
}
})
.catch(err => {
return cb(err);
});
}
// /**
// * Remove a transaction proposal
// *
// * @param {Object} txp
// * @param {Callback} cb
// * @return {Callback} cb - Return error or empty
// */
removeTxProposal(txp, cb) {
$.checkState(
this.credentials && this.credentials.isComplete(),
'Failed state: this.credentials at <removeTxProposal()>'
);
var url = '/v1/txproposals/' + txp.id;
this.request.delete(url, err => {
return cb(err);
});
}
// /**
// * Get transaction history
// *
// * @param {Object} opts
// * @param {Number} opts.skip (defaults to 0)
// * @param {Number} opts.limit
// * @param {String} opts.tokenAddress
// * @param {String} opts.multisigContractAddress (optional: MULTISIG ETH Contract Address)
// * @param {Boolean} opts.includeExtendedInfo
// * @param {Callback} cb
// * @return {Callback} cb - Return error or array of transactions
// */
getTxHistory(opts, cb) {
$.checkState(
this.credentials && this.credentials.isComplete(),
'Failed state: this.credentials at <getTxHistory()>'
);
var args = [];
if (opts) {
if (opts.skip) args.push('skip=' + opts.skip);
if (opts.limit) args.push('limit=' + opts.limit);
if (opts.tokenAddress) args.push('tokenAddress=' + opts.tokenAddress);
if (opts.multisigContractAddress)
args.push('multisigContractAddress=' + opts.multisigContractAddress);
if (opts.includeExtendedInfo) args.push('includeExtendedInfo=1');
}
var qs = '';
if (args.length > 0) {
qs = '?' + args.join('&');
}
var url = '/v1/txhistory/' + qs;
this.request.get(url, (err, txs) => {
if (err) return cb(err);
this._processTxps(txs);
return cb(null, txs);
});
}
// /**
// * getTx
// *
// * @param {String} TransactionId
// * @return {Callback} cb - Return error or transaction
// */
getTx(id, cb) {
$.checkState(
this.credentials && this.credentials.isComplete(),
'Failed state: this.credentials at <getTx()>'
);
var url = '/v1/txproposals/' + id;
this.request.get(url, (err, txp) => {
if (err) return cb(err);
this._processTxps(txp);
return cb(null, txp);
});
}
// /**
// * Start an address scanning process.
// * When finished, the scanning process will send a notification 'ScanFinished' to all copayers.
// *
// * @param {Object} opts
// * @param {Boolean} opts.includeCopayerBranches (defaults to false)
// * @param {Callback} cb
// */
startScan(opts, cb) {
$.checkState(
this.credentials && this.credentials.isComplete(),
'Failed state: this.credentials at <startScan()>'
);
var args = {
includeCopayerBranches: opts.includeCopayerBranches
};
this.request.post('/v1/addresses/scan', args, err => {
return cb(err);
});
}
// /**
// * Adds access to the current copayer
// * @param {Object} opts
// * @param {bool} opts.reqPrivKey
// * @param {bool} opts.signature of the private key, from master key.
// * @param {string} opts.restrictions
// * - cannotProposeTXs
// * - cannotXXX TODO
// * @param {string} opts.name (name for the new access)
// *
// * return the accesses Wallet and the requestPrivateKey
// */
addAccess(opts, cb) {
$.checkState(
this.credentials,
'Failed state: no this.credentials at <addAccess()>'
);
$.shouldBeString(
opts.requestPrivKey,
'Failed state: no requestPrivKey at addAccess() '
);
$.shouldBeString(
opts.signature,
'Failed state: no signature at addAccess()'
);
opts = opts || {};
var requestPubKey = new Bitcore.PrivateKey(opts.requestPrivKey)
.toPublicKey()
.toString();
var copayerId = this.credentials.copayerId;
var encCopayerName = opts.name
? Utils.encryptMessage(opts.name, this.credentials.sharedEncryptingKey)
: null;
var opts2 = {
copayerId,
requestPubKey,
signature: opts.signature,
name: encCopayerName,
restrictions: opts.restrictions
};
this.request.put('/v1/copayers/' + copayerId + '/', opts2, (err, res) => {
if (err) return cb(err);
// Do not set the key. Return it (for compatibility)
// this.credentials.requestPrivKey = opts.requestPrivKey;
return cb(null, res.wallet, opts.requestPrivKey);
});
}
// /**
// * Get a note associated with the specified txid
// * @param {Object} opts
// * @param {string} opts.txid - The txid to associate this note with
// */
getTxNote(opts, cb) {
$.checkState(
this.credentials,
'Failed state: this.credentials at <getTxNote()>'
);
opts = opts || {};
this.request.get('/v1/txnotes/' + opts.txid + '/', (err, note) => {
if (err) return cb(err);
this._processTxNotes(note);
return cb(null, note);
});
}
// /**
// * Edit a note associated with the specified txid
// * @param {Object} opts
// * @param {string} opts.txid - The txid to associate this note with
// * @param {string} opts.body - The contents of the note
// */
editTxNote(opts, cb) {
$.checkState(
this.credentials,
'Failed state: this.credentials at <editTxNote()>'
);
opts = opts || {};
if (opts.body) {
opts.body = API._encryptMessage(
opts.body,
this.credentials.sharedEncryptingKey
);
}
this.request.put('/v1/txnotes/' + opts.txid + '/', opts, (err, note) => {
if (err) return cb(err);
this._processTxNotes(note);
return cb(null, note);
});
}
// /**
// * Get all notes edited after the specified date
// * @param {Object} opts
// * @param {string} opts.minTs - The starting timestamp
// */
getTxNotes(opts, cb) {
$.checkState(
this.credentials,
'Failed state: this.credentials at <getTxNotes()>'
);
opts = opts || {};
var args = [];
if (_.isNumber(opts.minTs)) {
args.push('minTs=' + opts.minTs);
}
var qs = '';
if (args.length > 0) {
qs = '?' + args.join('&');
}
this.request.get('/v1/txnotes/' + qs, (err, notes) => {
if (err) return cb(err);
this._processTxNotes(notes);
return cb(null, notes);
});
}
// /**
// * Returns exchange rate for the specified currency & timestamp.
// * @param {Object} opts
// * @param {string} opts.code - Currency ISO code.
// * @param {Date} [opts.ts] - A timestamp to base the rate on (default Date.now()).
// * @param {String} [opts.coin] - Coin (detault: 'btc')
// * @returns {Object} rates - The exchange rate.
// */
getFiatRate(opts, cb) {
$.checkArgument(cb);
var opts = opts || {};
var args = [];
if (opts.ts) args.push('ts=' + opts.ts);
if (opts.coin) args.push('coin=' + opts.coin);
var qs = '';
if (args.length > 0) {
qs = '?' + args.join('&');
}
this.request.get('/v1/fiatrates/' + opts.code + '/' + qs, (err, rates) => {
if (err) return cb(err);
return cb(null, rates);
});
}
// /**
// * Subscribe to push notifications.
// * @param {Object} opts
// * @param {String} opts.type - Device type (ios or android).
// * @param {String} opts.token - Device token.
// * @returns {Object} response - Status of subscription.
// */
pushNotificationsSubscribe(opts, cb) {
var url = '/v1/pushnotifications/subscriptions/';
this.request.post(url, opts, (err, response) => {
if (err) return cb(err);
return cb(null, response);
});
}
// /**
// * Unsubscribe from push notifications.
// * @param {String} token - Device token
// * @return {Callback} cb - Return error if exists
// */
pushNotificationsUnsubscribe(token, cb) {
var url = '/v2/pushnotifications/subscriptions/' + token;
this.request.delete(url, cb);
}
// /**
// * Listen to a tx for its first confirmation.
// * @param {Object} opts
// * @param {String} opts.txid - The txid to subscribe to.
// * @returns {Object} response - Status of subscription.
// */
txConfirmationSubscribe(opts, cb) {
var url = '/v1/txconfirmations/';
this.request.post(url, opts, (err, response) => {
if (err) return cb(err);
return cb(null, response);
});
}
// /**
// * Stop listening for a tx confirmation.
// * @param {String} txid - The txid to unsubscribe from.
// * @return {Callback} cb - Return error if exists
// */
txConfirmationUnsubscribe(txid, cb) {
var url = '/v1/txconfirmations/' + txid;
this.request.delete(url, cb);
}
// /**
// * Returns send max information.
// * @param {String} opts
// * @param {number} opts.feeLevel[='normal'] - Optional. Specify the fee level ('priority', 'normal', 'economy', 'superEconomy').
// * @param {number} opts.feePerKb - Optional. Specify the fee per KB (in satoshi).
// * @param {Boolean} opts.excludeUnconfirmedUtxos - Indicates it if should use (or not) the unconfirmed utxos
// * @param {Boolean} opts.returnInputs - Indicates it if should return (or not) the inputs
// * @return {Callback} cb - Return error (if exists) and object result
// */
getSendMaxInfo(opts, cb) {
var args = [];
opts = opts || {};
if (opts.feeLevel) args.push('feeLevel=' + opts.feeLevel);
if (opts.feePerKb != null) args.push('feePerKb=' + opts.feePerKb);
if (opts.excludeUnconfirmedUtxos) args.push('excludeUnconfirmedUtxos=1');
if (opts.returnInputs) args.push('returnInputs=1');
var qs = '';
if (args.length > 0) qs = '?' + args.join('&');
var url = '/v1/sendmaxinfo/' + qs;
this.request.get(url, (err, result) => {
if (err) return cb(err);
return cb(null, result);
});
}
// /**
// * Returns gas limit estimate.
// * @param {Object} opts - tx Object
// * @return {Callback} cb - Return error (if exists) and gas limit
// */
getEstimateGas(opts, cb) {
var url = '/v3/estimateGas/';
this.request.post(url, opts, (err, gasLimit) => {
if (err) return cb(err);
return cb(null, gasLimit);
});
}
// /**
// * Returns nonce.
// * @param {Object} opts - coin, network
// * @return {Callback} cb - Return error (if exists) and nonce
// */
getNonce(opts, cb) {
$.checkArgument(opts.coin == 'eth', 'Invalid coin: must be "eth"');
var qs = [];
qs.push(`coin=${opts.coin}`);
qs.push(`network=${opts.network}`);
const url = `/v1/nonce/${opts.address}?${qs.join('&')}`;
this.request.get(url, (err, nonce) => {
if (err) return cb(err);
return cb(null, nonce);
});
}
// /**
// * Returns contract instantiation info. (All contract addresses instantiated by that sender with the current transaction hash and block number)
// * @param {string} opts.sender - sender eth wallet address
// * @param {string} opts.txId - instantiation transaction id
// * @return {Callback} cb - Return error (if exists) instantiation info
// */
getMultisigContractInstantiationInfo(opts, cb) {
var url = '/v1/ethmultisig/';
opts.network = this.credentials.network;
this.request.post(url, opts, (err, contractInstantiationInfo) => {
if (err) return cb(err);
return cb(null, contractInstantiationInfo);
});
}
// /**
// * Returns contract info. (owners addresses and required number of confirmations)
// * @param {string} opts.multisigContractAddress - multisig contract address
// * @return {Callback} cb - Return error (if exists) instantiation info
// */
getMultisigContractInfo(opts, cb) {
var url = '/v1/ethmultisig/info';
opts.network = this.credentials.network;
this.request.post(url, opts, (err, contractInfo) => {
if (err) return cb(err);
return cb(null, contractInfo);
});
}
// /**
// * Returns contract info. (name symbol precision)
// * @param {string} opts.tokenAddress - token contract address
// * @return {Callback} cb - Return error (if exists) instantiation info
// */
getTokenContractInfo(opts, cb) {
var url = '/v1/token/info';
opts.network = this.credentials.network;
this.request.post(url, opts, (err, contractInfo) => {
if (err) return cb(err);
return cb(null, contractInfo);
});
}
// /**
// * Get wallet status based on a string identifier (one of: walletId, address, txid)
// *
// * @param {string} opts.identifier - The identifier
// * @param {Boolean} opts.includeExtendedInfo (optional: query extended status)
// * @param {Boolean} opts.walletCheck (optional: run v8 walletCheck if wallet found)
// * @returns {Callback} cb - Returns error or an object with status information
// */
getStatusByIdentifier(opts, cb) {
$.checkState(
this.credentials,
'Failed state: this.credentials at <getStatusByIdentifier()>'
);
opts = opts || {};
var qs = [];
qs.push('includeExtendedInfo=' + (opts.includeExtendedInfo ? '1' : '0'));
qs.push('walletCheck=' + (opts.walletCheck ? '1' : '0'));
this.request.get(
'/v1/wallets/' + opts.identifier + '?' + qs.join('&'),
(err, result) => {
if (err || !result || !result.wallet) return cb(err);
if (result.wallet.status == 'pending') {
var c = this.credentials;
result.wallet.secret = API._buildSecret(
c.walletId,
c.walletPrivKey,
c.coin,
c.network
);
}
this._processStatus(result);
return cb(err, result);
}
);
}
/*
*
* Compatibility Functions
*
*/
_oldCopayDecrypt(username, password, blob) {
var SEP1 = '@#$';
var SEP2 = '%^#@';
var decrypted;
try {
var passphrase = username + SEP1 + password;
decrypted = sjcl.decrypt(passphrase, blob);
} catch (e) {
passphrase = username + SEP2 + password;
try {
decrypted = sjcl.decrypt(passphrase, blob);
} catch (e) {
log.debug(e);
}
}
if (!decrypted) return null;
var ret;
try {
ret = JSON.parse(decrypted);
} catch (e) {}
return ret;
}
getWalletIdsFromOldCopay(username, password, blob): any[] {
var p = this._oldCopayDecrypt(username, password, blob);
if (!p) return null;
var ids = p.walletIds.concat(_.keys(p.focusedTimestamps));
return _.uniq(ids);
}
// /**
// * upgradeCredentialsV1
// * upgrade Credentials V1 to Key and Credentials V2 object
// *
// * @param {Object} x - Credentials V1 Object
// * @returns {Callback} cb - Returns { err, {key, credentials} }
// */
static upgradeCredentialsV1(x) {
$.shouldBeObject(x);
if (
!_.isUndefined(x.version) ||
(!x.xPrivKey && !x.xPrivKeyEncrypted && !x.xPubKey)
) {
throw new Error('Could not recognize old version');
}
let k;
if (x.xPrivKey || x.xPrivKeyEncrypted) {
k = new Key({ seedData: x, seedType: 'objectV1' });
} else {
// RO credentials
k = false;
}
let obsoleteFields = {
version: true,
xPrivKey: true,
xPrivKeyEncrypted: true,
hwInfo: true,
entropySourcePath: true,
mnemonic: true,
mnemonicEncrypted: true
};
var c = new Credentials();
_.each(Credentials.FIELDS, i => {
if (!obsoleteFields[i]) {
c[i] = x[i];
}
});
if (c.externalSource) {
throw new Error('External Wallets are no longer supported');
}
c.coin = c.coin || 'btc';
c.addressType = c.addressType || Constants.SCRIPT_TYPES.P2SH;
c.account = c.account || 0;
c.rootPath = c.getRootPath();
c.keyId = k.id;
return { key: k, credentials: c };
}
// /**
// * upgradeMultipleCredentialsV1
// * upgrade multiple Credentials V1 and (opionally) keys to Key and Credentials V2 object
// * Duplicate keys will be identified and merged.
// *
// * @param {Object} credentials - Credentials V1 Object
// * @param {Object} keys - Key object
// *
// * @returns {Callback} cb - Returns { err, {keys, credentials} }
// */
static upgradeMultipleCredentialsV1(oldCredentials) {
let newKeys = [],
newCrededentials = [];
// Try to migrate to Credentials 2.0
_.each(oldCredentials, credentials => {
let migrated;
if (!credentials.version || credentials.version < 2) {
log.info('About to migrate : ' + credentials.walletId);
migrated = API.upgradeCredentialsV1(credentials);
newCrededentials.push(migrated.credentials);
if (migrated.key) {
log.info(`Wallet ${credentials.walletId} key's extracted`);
newKeys.push(migrated.key);
} else {
log.info(`READ-ONLY Wallet ${credentials.walletId} migrated`);
}
}
});
if (newKeys.length > 0) {
// Find and merge dup keys.
let credGroups = _.groupBy(newCrededentials, x => {
$.checkState(x.xPubKey, 'Failed state: no xPubKey at credentials!');
let xpub = new Bitcore.HDPublicKey(x.xPubKey);
let fingerPrint = xpub.fingerPrint.toString('hex');
return fingerPrint;
});
if (_.keys(credGroups).length < newCrededentials.length) {
log.info('Found some wallets using the SAME key. Merging...');
let uniqIds = {};
_.each(_.values(credGroups), credList => {
let toKeep = credList.shift();
if (!toKeep.keyId) return;
uniqIds[toKeep.keyId] = true;
if (!credList.length) return;
log.info(`Merging ${credList.length} keys to ${toKeep.keyId}`);
_.each(credList, x => {
log.info(`\t${x.keyId} is now ${toKeep.keyId}`);
x.keyId = toKeep.keyId;
});
});
newKeys = _.filter(newKeys, x => uniqIds[x.id]);
}
}
return {
keys: newKeys,
credentials: newCrededentials
};
}
// /**
// * serverAssistedImport
// * Imports EXISTING wallets against BWS and return key & clients[] for each account / coin
// *
// * @param {Object} opts
// * @param {String} opts.words - mnemonic
// * @param {String} opts.xPrivKey - extended Private Key
// * @param {String} opts.passphrase - mnemonic's passphrase (optional)
// * @param {Object} clientOpts - BWS connection options (see ClientAPI constructor)
// * @returns {Callback} cb - Returns { err, key, clients[] }
// */
static serverAssistedImport(opts, clientOpts, callback) {
$.checkArgument(
opts.words || opts.xPrivKey,
'provide opts.words or opts.xPrivKey'
);
let copayerIdAlreadyTested = {};
var checkCredentials = (key, opts, icb) => {
let c = key.createCredentials(null, {
coin: opts.coin,
network: opts.network,
account: opts.account,
n: opts.n
});
if (copayerIdAlreadyTested[c.copayerId + ':' + opts.n]) {
// console.log('[api.js.2226] ALREADY T:', opts.n); // TODO
return icb();
} else {
copayerIdAlreadyTested[c.copayerId + ':' + opts.n] = true;
}
let client = clientOpts.clientFactory
? clientOpts.clientFactory()
: new API(clientOpts);
client.fromString(c);
client.openWallet({}, async (err, status) => {
// console.log(
// `PATH: ${c.rootPath} n: ${c.n}:`,
// err && err.message ? err.message : 'FOUND!'
// );
// Exists
if (!err) {
if (
opts.coin == 'btc' &&
(status.wallet.addressType == 'P2WPKH' ||
status.wallet.addressType == 'P2WSH')
) {
client.credentials.addressType =
status.wallet.n == 1
? Constants.SCRIPT_TYPES.P2WPKH
: Constants.SCRIPT_TYPES.P2WSH;
}
let clients = [client];
// Eth wallet with tokens?
const tokenAddresses = status.preferences.tokenAddresses;
if (!_.isEmpty(tokenAddresses)) {
function oneInchGetTokensData() {
return new Promise((resolve, reject) => {
client.request.get(
'/v1/service/oneInch/getTokens',
(err, data) => {
if (err) return reject(err);
return resolve(data);
}
);
});
}
let customTokensData;
try {
customTokensData = await oneInchGetTokensData();
} catch (error) {
log.warn('oneInchGetTokensData err', error);
customTokensData = null;
}
_.each(tokenAddresses, t => {
const token =
Constants.TOKEN_OPTS[t] ||
(customTokensData && customTokensData[t]);
if (!token) {
log.warn(`Token ${t} unknown`);
return;
}
log.info(`Importing token: ${token.name}`);
const tokenCredentials =
client.credentials.getTokenCredentials(token);
let tokenClient = _.cloneDeep(client);
tokenClient.credentials = tokenCredentials;
clients.push(tokenClient);
});
}
// Eth wallet with mulsig wallets?
const multisigEthInfo = status.preferences.multisigEthInfo;
if (!_.isEmpty(multisigEthInfo)) {
_.each(multisigEthInfo, info => {
log.info(
`Importing multisig wallet. Address: ${info.multisigContractAddress} - m: ${info.m} - n: ${info.n}`
);
const multisigEthCredentials =
client.credentials.getMultisigEthCredentials({
walletName: info.walletName,
multisigContractAddress: info.multisigContractAddress,
n: info.n,
m: info.m
});
let multisigEthClient = _.cloneDeep(client);
multisigEthClient.credentials = multisigEthCredentials;
clients.push(multisigEthClient);
const tokenAddresses = info.tokenAddresses;
if (!_.isEmpty(tokenAddresses)) {
_.each(tokenAddresses, t => {
const token = Constants.TOKEN_OPTS[t];
if (!token) {
log.warn(`Token ${t} unknown`);
return;
}
log.info(`Importing multisig token: ${token.name}`);
const tokenCredentials =
multisigEthClient.credentials.getTokenCredentials(token);
let tokenClient = _.cloneDeep(multisigEthClient);
tokenClient.credentials = tokenCredentials;
clients.push(tokenClient);
});
}
});
}
return icb(null, clients);
}
if (
err instanceof Errors.NOT_AUTHORIZED ||
err instanceof Errors.WALLET_DOES_NOT_EXIST
) {
return icb();
}
return icb(err);
});
};
var checkKey = (key, cb) => {
let opts = [
// coin, network, multisig
['btc', 'livenet'],
['bch', 'livenet'],
['eth', 'livenet'],
['eth', 'testnet'],
['xrp', 'livenet'],
['xrp', 'testnet'],
['doge', 'livenet'],
['doge', 'testnet'],
['ltc', 'testnet'],
['ltc', 'livenet'],
['btc', 'livenet', true],
['bch', 'livenet', true],
['doge', 'livenet', true],
['ltc', 'livenet', true]
];
if (key.use44forMultisig) {
// testing old multi sig
opts = opts.filter(x => {
return x[2];
});
}
if (key.use0forBCH) {
// testing BCH, old coin=0 wallets
opts = opts.filter(x => {
return x[0] == 'bch';
});
}
if (!key.nonCompliantDerivation) {
// TESTNET
let testnet = _.cloneDeep(opts);
testnet.forEach(x => {
x[1] = 'testnet';
});
opts = opts.concat(testnet);
} else {
// leave only BTC, and no testnet
opts = opts.filter(x => {
return x[0] == 'btc';
});
}
let clients = [];
async.eachSeries(
opts,
(x, next) => {
let optsObj = {
coin: x[0],
network: x[1],
account: 0,
n: x[2] ? 2 : 1
};
// console.log('[api.js.2287:optsObj:]',optsObj); // TODO
// TODO OPTI: do not scan accounts if XX
//
// 1. check account 0
checkCredentials(key, optsObj, (err, iclients) => {
if (err) return next(err);
if (_.isEmpty(iclients)) return next();
clients = clients.concat(iclients);
// Accounts not allowed?
if (
key.use0forBCH ||
!key.compliantDerivation ||
key.use44forMultisig ||
key.BIP45
)
return next();
// Now, lets scan all accounts for the found client
let cont = true,
account = 1;
async.whilst(
() => {
return cont;
},
icb => {
optsObj.account = account++;
checkCredentials(key, optsObj, (err, iclients) => {
if (err) return icb(err);
// we do not allow accounts nr gaps in BWS.
cont = !_.isEmpty(iclients);
if (cont) {
clients = clients.concat(iclients);
}
return icb();
});
},
err => {
return next(err);
}
);
});
},
err => {
if (err) return cb(err);
return cb(null, clients);
}
);
};
let sets = [
{
// current wallets: /[44,48]/[0,145]'/
nonCompliantDerivation: false,
useLegacyCoinType: false,
useLegacyPurpose: false
},
{
// older bch wallets: /[44,48]/[0,0]'/
nonCompliantDerivation: false,
useLegacyCoinType: true,
useLegacyPurpose: false
},
{
// older BTC/BCH multisig wallets: /[44]/[0,145]'/
nonCompliantDerivation: false,
useLegacyCoinType: false,
useLegacyPurpose: true
},
{
// not that // older multisig BCH wallets: /[44]/[0]'/
nonCompliantDerivation: false,
useLegacyCoinType: true,
useLegacyPurpose: true
},
{
// old BTC no-comp wallets: /44'/[0]'/
nonCompliantDerivation: true,
useLegacyPurpose: true
}
];
let s,
resultingClients = [],
k;
async.whilst(
() => {
if (!_.isEmpty(resultingClients)) return false;
s = sets.shift();
if (!s) return false;
try {
if (opts.words) {
if (opts.passphrase) {
s.passphrase = opts.passphrase;
}
k = new Key({ seedData: opts.words, seedType: 'mnemonic', ...s });
} else {
k = new Key({
seedData: opts.xPrivKey,
seedType: 'extendedPrivateKey',
...s
});
}
} catch (e) {
log.info('Backup error:', e);
return callback(new Errors.INVALID_BACKUP());
}
return true;
},
icb => {
checkKey(k, (err, clients) => {
if (err) return icb(err);
if (clients && clients.length) {
resultingClients = clients;
}
return icb();
});
},
err => {
if (err) return callback(err);
if (_.isEmpty(resultingClients)) k = null;
return callback(null, k, resultingClients);
}
);
}
simplexGetQuote(data): Promise<any> {
return new Promise((resolve, reject) => {
this.request.post('/v1/service/simplex/quote', data, (err, data) => {
if (err) return reject(err);
return resolve(data);
});
});
}
simplexPaymentRequest(data): Promise<any> {
return new Promise((resolve, reject) => {
this.request.post(
'/v1/service/simplex/paymentRequest',
data,
(err, data) => {
if (err) return reject(err);
return resolve(data);
}
);
});
}
simplexGetEvents(data): Promise<any> {
return new Promise((resolve, reject) => {
let qs = [];
qs.push('env=' + data.env);
this.request.get(
'/v1/service/simplex/events/?' + qs.join('&'),
(err, data) => {
if (err) return reject(err);
return resolve(data);
}
);
});
}
wyreWalletOrderQuotation(data): Promise<any> {
return new Promise((resolve, reject) => {
this.request.post(
'/v1/service/wyre/walletOrderQuotation',
data,
(err, data) => {
if (err) return reject(err);
return resolve(data);
}
);
});
}
wyreWalletOrderReservation(data): Promise<any> {
return new Promise((resolve, reject) => {
this.request.post(
'/v1/service/wyre/walletOrderReservation',
data,
(err, data) => {
if (err) return reject(err);
return resolve(data);
}
);
});
}
changellyGetPairsParams(data): Promise<any> {
return new Promise((resolve, reject) => {
this.request.post(
'/v1/service/changelly/getPairsParams',
data,
(err, data) => {
if (err) return reject(err);
return resolve(data);
}
);
});
}
changellyGetFixRateForAmount(data): Promise<any> {
return new Promise((resolve, reject) => {
this.request.post(
'/v1/service/changelly/getFixRateForAmount',
data,
(err, data) => {
if (err) return reject(err);
return resolve(data);
}
);
});
}
changellyCreateFixTransaction(data): Promise<any> {
return new Promise((resolve, reject) => {
this.request.post(
'/v1/service/changelly/createFixTransaction',
data,
(err, data) => {
if (err) return reject(err);
return resolve(data);
}
);
});
}
oneInchGetSwap(data): Promise<any> {
return new Promise((resolve, reject) => {
this.request.post('/v1/service/oneInch/getSwap', data, (err, data) => {
if (err) return reject(err);
return resolve(data);
});
});
}
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs } from "../types";
import * as utilities from "../utilities";
/**
* Manages a Service Fabric Cluster.
*
* ## Example Usage
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as azure from "@pulumi/azure";
*
* const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"});
* const exampleCluster = new azure.servicefabric.Cluster("exampleCluster", {
* resourceGroupName: exampleResourceGroup.name,
* location: exampleResourceGroup.location,
* reliabilityLevel: "Bronze",
* upgradeMode: "Manual",
* clusterCodeVersion: "7.1.456.959",
* vmImage: "Windows",
* managementEndpoint: "https://example:80",
* nodeTypes: [{
* name: "first",
* instanceCount: 3,
* isPrimary: true,
* clientEndpointPort: 2020,
* httpEndpointPort: 80,
* }],
* });
* ```
*
* ## Import
*
* Service Fabric Clusters can be imported using the `resource id`, e.g.
*
* ```sh
* $ pulumi import azure:servicefabric/cluster:Cluster cluster1 /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/mygroup1/providers/Microsoft.ServiceFabric/clusters/cluster1
* ```
*/
export class Cluster extends pulumi.CustomResource {
/**
* Get an existing Cluster resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param state Any extra arguments used during the lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: ClusterState, opts?: pulumi.CustomResourceOptions): Cluster {
return new Cluster(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'azure:servicefabric/cluster:Cluster';
/**
* Returns true if the given object is an instance of Cluster. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is Cluster {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === Cluster.__pulumiType;
}
/**
* A List of one or more features which should be enabled, such as `DnsService`.
*/
public readonly addOnFeatures!: pulumi.Output<string[] | undefined>;
/**
* An `azureActiveDirectory` block as defined below.
*/
public readonly azureActiveDirectory!: pulumi.Output<outputs.servicefabric.ClusterAzureActiveDirectory | undefined>;
/**
* A `certificate` block as defined below. Conflicts with `certificateCommonNames`.
*/
public readonly certificate!: pulumi.Output<outputs.servicefabric.ClusterCertificate | undefined>;
/**
* A `certificateCommonNames` block as defined below. Conflicts with `certificate`.
*/
public readonly certificateCommonNames!: pulumi.Output<outputs.servicefabric.ClusterCertificateCommonNames | undefined>;
/**
* A `clientCertificateCommonName` block as defined below.
*/
public readonly clientCertificateCommonNames!: pulumi.Output<outputs.servicefabric.ClusterClientCertificateCommonName[] | undefined>;
/**
* One or more `clientCertificateThumbprint` blocks as defined below.
*/
public readonly clientCertificateThumbprints!: pulumi.Output<outputs.servicefabric.ClusterClientCertificateThumbprint[] | undefined>;
/**
* Required if Upgrade Mode set to `Manual`, Specifies the Version of the Cluster Code of the cluster.
*/
public readonly clusterCodeVersion!: pulumi.Output<string>;
/**
* The Cluster Endpoint for this Service Fabric Cluster.
*/
public /*out*/ readonly clusterEndpoint!: pulumi.Output<string>;
/**
* A `diagnosticsConfig` block as defined below. Changing this forces a new resource to be created.
*/
public readonly diagnosticsConfig!: pulumi.Output<outputs.servicefabric.ClusterDiagnosticsConfig | undefined>;
/**
* One or more `fabricSettings` blocks as defined below.
*/
public readonly fabricSettings!: pulumi.Output<outputs.servicefabric.ClusterFabricSetting[] | undefined>;
/**
* Specifies the Azure Region where the Service Fabric Cluster should exist. Changing this forces a new resource to be created.
*/
public readonly location!: pulumi.Output<string>;
/**
* Specifies the Management Endpoint of the cluster such as `http://example.com`. Changing this forces a new resource to be created.
*/
public readonly managementEndpoint!: pulumi.Output<string>;
/**
* The name of the Service Fabric Cluster. Changing this forces a new resource to be created.
*/
public readonly name!: pulumi.Output<string>;
/**
* One or more `nodeType` blocks as defined below.
*/
public readonly nodeTypes!: pulumi.Output<outputs.servicefabric.ClusterNodeType[]>;
/**
* Specifies the Reliability Level of the Cluster. Possible values include `None`, `Bronze`, `Silver`, `Gold` and `Platinum`.
*/
public readonly reliabilityLevel!: pulumi.Output<string>;
/**
* The name of the Resource Group in which the Service Fabric Cluster exists. Changing this forces a new resource to be created.
*/
public readonly resourceGroupName!: pulumi.Output<string>;
/**
* A `reverseProxyCertificate` block as defined below. Conflicts with `reverseProxyCertificateCommonNames`.
*/
public readonly reverseProxyCertificate!: pulumi.Output<outputs.servicefabric.ClusterReverseProxyCertificate | undefined>;
/**
* A `reverseProxyCertificateCommonNames` block as defined below. Conflicts with `reverseProxyCertificate`.
*/
public readonly reverseProxyCertificateCommonNames!: pulumi.Output<outputs.servicefabric.ClusterReverseProxyCertificateCommonNames | undefined>;
/**
* Specifies the logical grouping of VMs in upgrade domains. Possible values are `Hierarchical` or `Parallel`.
*/
public readonly serviceFabricZonalUpgradeMode!: pulumi.Output<string | undefined>;
/**
* A mapping of tags to assign to the resource.
*/
public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* Specifies the Upgrade Mode of the cluster. Possible values are `Automatic` or `Manual`.
*/
public readonly upgradeMode!: pulumi.Output<string>;
/**
* A `upgradePolicy` block as defined below.
*/
public readonly upgradePolicy!: pulumi.Output<outputs.servicefabric.ClusterUpgradePolicy | undefined>;
/**
* Specifies the Image expected for the Service Fabric Cluster, such as `Windows`. Changing this forces a new resource to be created.
*/
public readonly vmImage!: pulumi.Output<string>;
/**
* Specifies the upgrade mode for the virtual machine scale set updates that happen in all availability zones at once. Possible values are `Hierarchical` or `Parallel`.
*/
public readonly vmssZonalUpgradeMode!: pulumi.Output<string | undefined>;
/**
* Create a Cluster resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args: ClusterArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: ClusterArgs | ClusterState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as ClusterState | undefined;
inputs["addOnFeatures"] = state ? state.addOnFeatures : undefined;
inputs["azureActiveDirectory"] = state ? state.azureActiveDirectory : undefined;
inputs["certificate"] = state ? state.certificate : undefined;
inputs["certificateCommonNames"] = state ? state.certificateCommonNames : undefined;
inputs["clientCertificateCommonNames"] = state ? state.clientCertificateCommonNames : undefined;
inputs["clientCertificateThumbprints"] = state ? state.clientCertificateThumbprints : undefined;
inputs["clusterCodeVersion"] = state ? state.clusterCodeVersion : undefined;
inputs["clusterEndpoint"] = state ? state.clusterEndpoint : undefined;
inputs["diagnosticsConfig"] = state ? state.diagnosticsConfig : undefined;
inputs["fabricSettings"] = state ? state.fabricSettings : undefined;
inputs["location"] = state ? state.location : undefined;
inputs["managementEndpoint"] = state ? state.managementEndpoint : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["nodeTypes"] = state ? state.nodeTypes : undefined;
inputs["reliabilityLevel"] = state ? state.reliabilityLevel : undefined;
inputs["resourceGroupName"] = state ? state.resourceGroupName : undefined;
inputs["reverseProxyCertificate"] = state ? state.reverseProxyCertificate : undefined;
inputs["reverseProxyCertificateCommonNames"] = state ? state.reverseProxyCertificateCommonNames : undefined;
inputs["serviceFabricZonalUpgradeMode"] = state ? state.serviceFabricZonalUpgradeMode : undefined;
inputs["tags"] = state ? state.tags : undefined;
inputs["upgradeMode"] = state ? state.upgradeMode : undefined;
inputs["upgradePolicy"] = state ? state.upgradePolicy : undefined;
inputs["vmImage"] = state ? state.vmImage : undefined;
inputs["vmssZonalUpgradeMode"] = state ? state.vmssZonalUpgradeMode : undefined;
} else {
const args = argsOrState as ClusterArgs | undefined;
if ((!args || args.managementEndpoint === undefined) && !opts.urn) {
throw new Error("Missing required property 'managementEndpoint'");
}
if ((!args || args.nodeTypes === undefined) && !opts.urn) {
throw new Error("Missing required property 'nodeTypes'");
}
if ((!args || args.reliabilityLevel === undefined) && !opts.urn) {
throw new Error("Missing required property 'reliabilityLevel'");
}
if ((!args || args.resourceGroupName === undefined) && !opts.urn) {
throw new Error("Missing required property 'resourceGroupName'");
}
if ((!args || args.upgradeMode === undefined) && !opts.urn) {
throw new Error("Missing required property 'upgradeMode'");
}
if ((!args || args.vmImage === undefined) && !opts.urn) {
throw new Error("Missing required property 'vmImage'");
}
inputs["addOnFeatures"] = args ? args.addOnFeatures : undefined;
inputs["azureActiveDirectory"] = args ? args.azureActiveDirectory : undefined;
inputs["certificate"] = args ? args.certificate : undefined;
inputs["certificateCommonNames"] = args ? args.certificateCommonNames : undefined;
inputs["clientCertificateCommonNames"] = args ? args.clientCertificateCommonNames : undefined;
inputs["clientCertificateThumbprints"] = args ? args.clientCertificateThumbprints : undefined;
inputs["clusterCodeVersion"] = args ? args.clusterCodeVersion : undefined;
inputs["diagnosticsConfig"] = args ? args.diagnosticsConfig : undefined;
inputs["fabricSettings"] = args ? args.fabricSettings : undefined;
inputs["location"] = args ? args.location : undefined;
inputs["managementEndpoint"] = args ? args.managementEndpoint : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["nodeTypes"] = args ? args.nodeTypes : undefined;
inputs["reliabilityLevel"] = args ? args.reliabilityLevel : undefined;
inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined;
inputs["reverseProxyCertificate"] = args ? args.reverseProxyCertificate : undefined;
inputs["reverseProxyCertificateCommonNames"] = args ? args.reverseProxyCertificateCommonNames : undefined;
inputs["serviceFabricZonalUpgradeMode"] = args ? args.serviceFabricZonalUpgradeMode : undefined;
inputs["tags"] = args ? args.tags : undefined;
inputs["upgradeMode"] = args ? args.upgradeMode : undefined;
inputs["upgradePolicy"] = args ? args.upgradePolicy : undefined;
inputs["vmImage"] = args ? args.vmImage : undefined;
inputs["vmssZonalUpgradeMode"] = args ? args.vmssZonalUpgradeMode : undefined;
inputs["clusterEndpoint"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(Cluster.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering Cluster resources.
*/
export interface ClusterState {
/**
* A List of one or more features which should be enabled, such as `DnsService`.
*/
addOnFeatures?: pulumi.Input<pulumi.Input<string>[]>;
/**
* An `azureActiveDirectory` block as defined below.
*/
azureActiveDirectory?: pulumi.Input<inputs.servicefabric.ClusterAzureActiveDirectory>;
/**
* A `certificate` block as defined below. Conflicts with `certificateCommonNames`.
*/
certificate?: pulumi.Input<inputs.servicefabric.ClusterCertificate>;
/**
* A `certificateCommonNames` block as defined below. Conflicts with `certificate`.
*/
certificateCommonNames?: pulumi.Input<inputs.servicefabric.ClusterCertificateCommonNames>;
/**
* A `clientCertificateCommonName` block as defined below.
*/
clientCertificateCommonNames?: pulumi.Input<pulumi.Input<inputs.servicefabric.ClusterClientCertificateCommonName>[]>;
/**
* One or more `clientCertificateThumbprint` blocks as defined below.
*/
clientCertificateThumbprints?: pulumi.Input<pulumi.Input<inputs.servicefabric.ClusterClientCertificateThumbprint>[]>;
/**
* Required if Upgrade Mode set to `Manual`, Specifies the Version of the Cluster Code of the cluster.
*/
clusterCodeVersion?: pulumi.Input<string>;
/**
* The Cluster Endpoint for this Service Fabric Cluster.
*/
clusterEndpoint?: pulumi.Input<string>;
/**
* A `diagnosticsConfig` block as defined below. Changing this forces a new resource to be created.
*/
diagnosticsConfig?: pulumi.Input<inputs.servicefabric.ClusterDiagnosticsConfig>;
/**
* One or more `fabricSettings` blocks as defined below.
*/
fabricSettings?: pulumi.Input<pulumi.Input<inputs.servicefabric.ClusterFabricSetting>[]>;
/**
* Specifies the Azure Region where the Service Fabric Cluster should exist. Changing this forces a new resource to be created.
*/
location?: pulumi.Input<string>;
/**
* Specifies the Management Endpoint of the cluster such as `http://example.com`. Changing this forces a new resource to be created.
*/
managementEndpoint?: pulumi.Input<string>;
/**
* The name of the Service Fabric Cluster. Changing this forces a new resource to be created.
*/
name?: pulumi.Input<string>;
/**
* One or more `nodeType` blocks as defined below.
*/
nodeTypes?: pulumi.Input<pulumi.Input<inputs.servicefabric.ClusterNodeType>[]>;
/**
* Specifies the Reliability Level of the Cluster. Possible values include `None`, `Bronze`, `Silver`, `Gold` and `Platinum`.
*/
reliabilityLevel?: pulumi.Input<string>;
/**
* The name of the Resource Group in which the Service Fabric Cluster exists. Changing this forces a new resource to be created.
*/
resourceGroupName?: pulumi.Input<string>;
/**
* A `reverseProxyCertificate` block as defined below. Conflicts with `reverseProxyCertificateCommonNames`.
*/
reverseProxyCertificate?: pulumi.Input<inputs.servicefabric.ClusterReverseProxyCertificate>;
/**
* A `reverseProxyCertificateCommonNames` block as defined below. Conflicts with `reverseProxyCertificate`.
*/
reverseProxyCertificateCommonNames?: pulumi.Input<inputs.servicefabric.ClusterReverseProxyCertificateCommonNames>;
/**
* Specifies the logical grouping of VMs in upgrade domains. Possible values are `Hierarchical` or `Parallel`.
*/
serviceFabricZonalUpgradeMode?: pulumi.Input<string>;
/**
* A mapping of tags to assign to the resource.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* Specifies the Upgrade Mode of the cluster. Possible values are `Automatic` or `Manual`.
*/
upgradeMode?: pulumi.Input<string>;
/**
* A `upgradePolicy` block as defined below.
*/
upgradePolicy?: pulumi.Input<inputs.servicefabric.ClusterUpgradePolicy>;
/**
* Specifies the Image expected for the Service Fabric Cluster, such as `Windows`. Changing this forces a new resource to be created.
*/
vmImage?: pulumi.Input<string>;
/**
* Specifies the upgrade mode for the virtual machine scale set updates that happen in all availability zones at once. Possible values are `Hierarchical` or `Parallel`.
*/
vmssZonalUpgradeMode?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a Cluster resource.
*/
export interface ClusterArgs {
/**
* A List of one or more features which should be enabled, such as `DnsService`.
*/
addOnFeatures?: pulumi.Input<pulumi.Input<string>[]>;
/**
* An `azureActiveDirectory` block as defined below.
*/
azureActiveDirectory?: pulumi.Input<inputs.servicefabric.ClusterAzureActiveDirectory>;
/**
* A `certificate` block as defined below. Conflicts with `certificateCommonNames`.
*/
certificate?: pulumi.Input<inputs.servicefabric.ClusterCertificate>;
/**
* A `certificateCommonNames` block as defined below. Conflicts with `certificate`.
*/
certificateCommonNames?: pulumi.Input<inputs.servicefabric.ClusterCertificateCommonNames>;
/**
* A `clientCertificateCommonName` block as defined below.
*/
clientCertificateCommonNames?: pulumi.Input<pulumi.Input<inputs.servicefabric.ClusterClientCertificateCommonName>[]>;
/**
* One or more `clientCertificateThumbprint` blocks as defined below.
*/
clientCertificateThumbprints?: pulumi.Input<pulumi.Input<inputs.servicefabric.ClusterClientCertificateThumbprint>[]>;
/**
* Required if Upgrade Mode set to `Manual`, Specifies the Version of the Cluster Code of the cluster.
*/
clusterCodeVersion?: pulumi.Input<string>;
/**
* A `diagnosticsConfig` block as defined below. Changing this forces a new resource to be created.
*/
diagnosticsConfig?: pulumi.Input<inputs.servicefabric.ClusterDiagnosticsConfig>;
/**
* One or more `fabricSettings` blocks as defined below.
*/
fabricSettings?: pulumi.Input<pulumi.Input<inputs.servicefabric.ClusterFabricSetting>[]>;
/**
* Specifies the Azure Region where the Service Fabric Cluster should exist. Changing this forces a new resource to be created.
*/
location?: pulumi.Input<string>;
/**
* Specifies the Management Endpoint of the cluster such as `http://example.com`. Changing this forces a new resource to be created.
*/
managementEndpoint: pulumi.Input<string>;
/**
* The name of the Service Fabric Cluster. Changing this forces a new resource to be created.
*/
name?: pulumi.Input<string>;
/**
* One or more `nodeType` blocks as defined below.
*/
nodeTypes: pulumi.Input<pulumi.Input<inputs.servicefabric.ClusterNodeType>[]>;
/**
* Specifies the Reliability Level of the Cluster. Possible values include `None`, `Bronze`, `Silver`, `Gold` and `Platinum`.
*/
reliabilityLevel: pulumi.Input<string>;
/**
* The name of the Resource Group in which the Service Fabric Cluster exists. Changing this forces a new resource to be created.
*/
resourceGroupName: pulumi.Input<string>;
/**
* A `reverseProxyCertificate` block as defined below. Conflicts with `reverseProxyCertificateCommonNames`.
*/
reverseProxyCertificate?: pulumi.Input<inputs.servicefabric.ClusterReverseProxyCertificate>;
/**
* A `reverseProxyCertificateCommonNames` block as defined below. Conflicts with `reverseProxyCertificate`.
*/
reverseProxyCertificateCommonNames?: pulumi.Input<inputs.servicefabric.ClusterReverseProxyCertificateCommonNames>;
/**
* Specifies the logical grouping of VMs in upgrade domains. Possible values are `Hierarchical` or `Parallel`.
*/
serviceFabricZonalUpgradeMode?: pulumi.Input<string>;
/**
* A mapping of tags to assign to the resource.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* Specifies the Upgrade Mode of the cluster. Possible values are `Automatic` or `Manual`.
*/
upgradeMode: pulumi.Input<string>;
/**
* A `upgradePolicy` block as defined below.
*/
upgradePolicy?: pulumi.Input<inputs.servicefabric.ClusterUpgradePolicy>;
/**
* Specifies the Image expected for the Service Fabric Cluster, such as `Windows`. Changing this forces a new resource to be created.
*/
vmImage: pulumi.Input<string>;
/**
* Specifies the upgrade mode for the virtual machine scale set updates that happen in all availability zones at once. Possible values are `Hierarchical` or `Parallel`.
*/
vmssZonalUpgradeMode?: pulumi.Input<string>;
} | the_stack |
import {
iterableFirst,
iterableEvery,
setFilter,
mapMapEntries,
mapMergeWithInto,
mapMap,
mapUpdateInto,
setMap,
iterableFind,
setIntersect,
setUnionInto
} from "collection-utils";
import { TypeGraph, TypeRef } from "../TypeGraph";
import { StringTypeMapping, TypeBuilder } from "../TypeBuilder";
import { GraphRewriteBuilder, TypeLookerUp } from "../GraphRewriting";
import { UnionTypeProvider, UnionBuilder, TypeAttributeMap } from "../UnionBuilder";
import {
IntersectionType,
Type,
UnionType,
PrimitiveTypeKind,
ArrayType,
isPrimitiveTypeKind,
isNumberTypeKind,
GenericClassProperty,
TypeKind,
ObjectType
} from "../Type";
import { setOperationMembersRecursively, matchTypeExhaustive, makeGroupsToFlatten } from "../TypeUtils";
import { assert, defined, panic, mustNotHappen } from "../support/Support";
import {
combineTypeAttributes,
TypeAttributes,
emptyTypeAttributes,
makeTypeAttributesInferred
} from "../attributes/TypeAttributes";
function canResolve(t: IntersectionType): boolean {
const members = setOperationMembersRecursively(t, undefined)[0];
if (members.size <= 1) return true;
return iterableEvery(members, m => !(m instanceof UnionType) || m.isCanonical);
}
function attributesForTypes<T extends TypeKind>(types: ReadonlySet<Type>): TypeAttributeMap<T> {
return mapMapEntries(types.entries(), t => [t.kind, t.getAttributes()] as [T, TypeAttributes]);
}
type PropertyMap = Map<string, GenericClassProperty<Set<Type>>>;
class IntersectionAccumulator
implements UnionTypeProvider<ReadonlySet<Type>, [PropertyMap, ReadonlySet<Type> | undefined] | undefined> {
private _primitiveTypes: Set<PrimitiveTypeKind> | undefined;
private readonly _primitiveAttributes: TypeAttributeMap<PrimitiveTypeKind> = new Map();
// * undefined: We haven't seen any types yet.
// * Set: All types we've seen can be arrays.
// * false: At least one of the types seen can't be an array.
private _arrayItemTypes: Set<Type> | undefined | false;
private _arrayAttributes: TypeAttributes = emptyTypeAttributes;
// We start out with all object types allowed, which means
// _additionalPropertyTypes is empty - no restrictions - and
// _classProperties is empty - no defined properties so far.
//
// If _additionalPropertyTypes is undefined, no additional
// properties are allowed anymore. If _classProperties is
// undefined, no object types are allowed, in which case
// _additionalPropertyTypes must also be undefined;
private _objectProperties: PropertyMap | undefined = new Map();
private _objectAttributes: TypeAttributes = emptyTypeAttributes;
private _additionalPropertyTypes: Set<Type> | undefined = new Set();
private _lostTypeAttributes: boolean = false;
private updatePrimitiveTypes(members: Iterable<Type>): void {
const types = setFilter(members, t => isPrimitiveTypeKind(t.kind));
const attributes = attributesForTypes<PrimitiveTypeKind>(types);
mapMergeWithInto(this._primitiveAttributes, (a, b) => combineTypeAttributes("intersect", a, b), attributes);
const kinds = setMap(types, t => t.kind) as ReadonlySet<PrimitiveTypeKind>;
if (this._primitiveTypes === undefined) {
this._primitiveTypes = new Set(kinds);
return;
}
const haveNumber =
iterableFind(this._primitiveTypes, isNumberTypeKind) !== undefined &&
iterableFind(kinds, isNumberTypeKind) !== undefined;
this._primitiveTypes = setIntersect(this._primitiveTypes, kinds);
if (haveNumber && iterableFind(this._primitiveTypes, isNumberTypeKind) === undefined) {
// One set has integer, the other has double. The intersection
// of that is integer.
this._primitiveTypes = this._primitiveTypes.add("integer");
}
}
private updateArrayItemTypes(members: Iterable<Type>): void {
const maybeArray = iterableFind(members, t => t instanceof ArrayType) as ArrayType | undefined;
if (maybeArray === undefined) {
this._arrayItemTypes = false;
return;
}
this._arrayAttributes = combineTypeAttributes("intersect", this._arrayAttributes, maybeArray.getAttributes());
if (this._arrayItemTypes === undefined) {
this._arrayItemTypes = new Set();
} else if (this._arrayItemTypes !== false) {
this._arrayItemTypes.add(maybeArray.items);
}
}
private updateObjectProperties(members: Iterable<Type>): void {
const maybeObject = iterableFind(members, t => t instanceof ObjectType) as ObjectType | undefined;
if (maybeObject === undefined) {
this._objectProperties = undefined;
this._additionalPropertyTypes = undefined;
return;
}
this._objectAttributes = combineTypeAttributes(
"intersect",
this._objectAttributes,
maybeObject.getAttributes()
);
const objectAdditionalProperties = maybeObject.getAdditionalProperties();
if (this._objectProperties === undefined) {
assert(this._additionalPropertyTypes === undefined);
return;
}
const allPropertyNames = setUnionInto(
new Set(this._objectProperties.keys()),
maybeObject.getProperties().keys()
);
for (const name of allPropertyNames) {
const existing = defined(this._objectProperties).get(name);
const newProperty = maybeObject.getProperties().get(name);
if (existing !== undefined && newProperty !== undefined) {
const cp = new GenericClassProperty(
existing.typeData.add(newProperty.type),
existing.isOptional && newProperty.isOptional
);
defined(this._objectProperties).set(name, cp);
} else if (existing !== undefined && objectAdditionalProperties !== undefined) {
const cp = new GenericClassProperty(
existing.typeData.add(objectAdditionalProperties),
existing.isOptional
);
defined(this._objectProperties).set(name, cp);
} else if (existing !== undefined) {
defined(this._objectProperties).delete(name);
} else if (newProperty !== undefined && this._additionalPropertyTypes !== undefined) {
// FIXME: This is potentially slow
const types = new Set(this._additionalPropertyTypes).add(newProperty.type);
defined(this._objectProperties).set(name, new GenericClassProperty(types, newProperty.isOptional));
} else if (newProperty !== undefined) {
defined(this._objectProperties).delete(name);
} else {
return mustNotHappen();
}
}
if (this._additionalPropertyTypes !== undefined && objectAdditionalProperties !== undefined) {
this._additionalPropertyTypes.add(objectAdditionalProperties);
} else if (this._additionalPropertyTypes !== undefined || objectAdditionalProperties !== undefined) {
this._additionalPropertyTypes = undefined;
this._lostTypeAttributes = true;
}
}
private addUnionSet(members: Iterable<Type>): void {
this.updatePrimitiveTypes(members);
this.updateArrayItemTypes(members);
this.updateObjectProperties(members);
}
addType(t: Type): TypeAttributes {
let attributes = t.getAttributes();
matchTypeExhaustive<void>(
t,
_noneType => {
return panic("There shouldn't be a none type");
},
_anyType => {
return panic("The any type should have been filtered out in setOperationMembersRecursively");
},
nullType => this.addUnionSet([nullType]),
boolType => this.addUnionSet([boolType]),
integerType => this.addUnionSet([integerType]),
doubleType => this.addUnionSet([doubleType]),
stringType => this.addUnionSet([stringType]),
arrayType => this.addUnionSet([arrayType]),
_classType => panic("We should never see class types in intersections"),
_mapType => panic("We should never see map types in intersections"),
objectType => this.addUnionSet([objectType]),
_enumType => panic("We should never see enum types in intersections"),
unionType => {
attributes = combineTypeAttributes(
"intersect",
[attributes].concat(Array.from(unionType.members).map(m => m.getAttributes()))
);
this.addUnionSet(unionType.members);
},
transformedStringType => this.addUnionSet([transformedStringType])
);
return makeTypeAttributesInferred(attributes);
}
get arrayData(): ReadonlySet<Type> {
if (this._arrayItemTypes === undefined || this._arrayItemTypes === false) {
return panic("This should not be called if the type can't be an array");
}
return this._arrayItemTypes;
}
get objectData(): [PropertyMap, ReadonlySet<Type> | undefined] | undefined {
if (this._objectProperties === undefined) {
assert(this._additionalPropertyTypes === undefined);
return undefined;
}
return [this._objectProperties, this._additionalPropertyTypes];
}
get enumCases(): ReadonlySet<string> {
return panic("We don't support enums in intersections");
}
getMemberKinds(): TypeAttributeMap<TypeKind> {
const kinds: TypeAttributeMap<TypeKind> = mapMap(defined(this._primitiveTypes).entries(), k =>
defined(this._primitiveAttributes.get(k))
);
const maybeDoubleAttributes = this._primitiveAttributes.get("double");
// If double was eliminated, add its attributes to integer
if (maybeDoubleAttributes !== undefined && !kinds.has("double") && kinds.has("integer")) {
// FIXME: How can this ever happen??? Where do we "eliminate" double?
mapUpdateInto(kinds, "integer", a => {
return combineTypeAttributes("intersect", defined(a), maybeDoubleAttributes);
});
}
if (this._arrayItemTypes !== undefined && this._arrayItemTypes !== false) {
kinds.set("array", this._arrayAttributes);
} else if (this._arrayAttributes.size > 0) {
this._lostTypeAttributes = true;
}
if (this._objectProperties !== undefined) {
kinds.set("object", this._objectAttributes);
} else if (this._objectAttributes.size > 0) {
this._lostTypeAttributes = true;
}
return kinds;
}
get lostTypeAttributes(): boolean {
return this._lostTypeAttributes;
}
}
class IntersectionUnionBuilder extends UnionBuilder<
TypeBuilder & TypeLookerUp,
ReadonlySet<Type>,
[PropertyMap, ReadonlySet<Type> | undefined] | undefined
> {
private _createdNewIntersections: boolean = false;
private makeIntersection(members: ReadonlySet<Type>, attributes: TypeAttributes): TypeRef {
const reconstitutedMembers = setMap(members, t => this.typeBuilder.reconstituteTypeRef(t.typeRef));
const first = defined(iterableFirst(reconstitutedMembers));
if (reconstitutedMembers.size === 1) {
this.typeBuilder.addAttributes(first, attributes);
return first;
}
this._createdNewIntersections = true;
return this.typeBuilder.getUniqueIntersectionType(attributes, reconstitutedMembers);
}
get createdNewIntersections(): boolean {
return this._createdNewIntersections;
}
protected makeObject(
maybeData: [PropertyMap, ReadonlySet<Type> | undefined] | undefined,
typeAttributes: TypeAttributes,
forwardingRef: TypeRef | undefined
): TypeRef {
if (maybeData === undefined) {
return panic("Either properties or additional properties must be given to make an object type");
}
const [propertyTypes, maybeAdditionalProperties] = maybeData;
const properties = mapMap(propertyTypes, cp =>
this.typeBuilder.makeClassProperty(this.makeIntersection(cp.typeData, emptyTypeAttributes), cp.isOptional)
);
const additionalProperties =
maybeAdditionalProperties === undefined
? undefined
: this.makeIntersection(maybeAdditionalProperties, emptyTypeAttributes);
return this.typeBuilder.getUniqueObjectType(typeAttributes, properties, additionalProperties, forwardingRef);
}
protected makeArray(
arrays: ReadonlySet<Type>,
typeAttributes: TypeAttributes,
forwardingRef: TypeRef | undefined
): TypeRef {
// FIXME: attributes
const itemsType = this.makeIntersection(arrays, emptyTypeAttributes);
const tref = this.typeBuilder.getArrayType(typeAttributes, itemsType, forwardingRef);
return tref;
}
}
export function resolveIntersections(
graph: TypeGraph,
stringTypeMapping: StringTypeMapping,
debugPrintReconstitution: boolean
): [TypeGraph, boolean] {
let needsRepeat = false;
function replace(types: ReadonlySet<Type>, builder: GraphRewriteBuilder<Type>, forwardingRef: TypeRef): TypeRef {
const intersections = setFilter(types, t => t instanceof IntersectionType) as Set<IntersectionType>;
const [members, intersectionAttributes] = setOperationMembersRecursively(
Array.from(intersections),
"intersect"
);
if (members.size === 0) {
const t = builder.getPrimitiveType("any", intersectionAttributes, forwardingRef);
return t;
}
if (members.size === 1) {
return builder.reconstituteType(defined(iterableFirst(members)), intersectionAttributes, forwardingRef);
}
const accumulator = new IntersectionAccumulator();
const extraAttributes = makeTypeAttributesInferred(
combineTypeAttributes("intersect", Array.from(members).map(t => accumulator.addType(t)))
);
const attributes = combineTypeAttributes("intersect", intersectionAttributes, extraAttributes);
const unionBuilder = new IntersectionUnionBuilder(builder);
const tref = unionBuilder.buildUnion(accumulator, true, attributes, forwardingRef);
if (unionBuilder.createdNewIntersections) {
needsRepeat = true;
}
return tref;
}
// FIXME: We need to handle intersections that resolve to the same set of types.
// See for example the intersections-nested.schema example.
const allIntersections = setFilter(graph.allTypesUnordered(), t => t instanceof IntersectionType) as Set<
IntersectionType
>;
const resolvableIntersections = setFilter(allIntersections, canResolve);
const groups = makeGroupsToFlatten(resolvableIntersections, undefined);
graph = graph.rewrite("resolve intersections", stringTypeMapping, false, groups, debugPrintReconstitution, replace);
// console.log(`resolved ${resolvableIntersections.size} of ${intersections.size} intersections`);
return [graph, !needsRepeat && allIntersections.size === resolvableIntersections.size];
} | the_stack |
import { clone } from '@microsoft/sp-lodash-subset';
import * as strings from 'ColumnFormatterWebPartStrings';
import {
getWizardByName,
IWizard,
standardWizardStartingCode,
standardWizardStartingColumns,
standardWizardStartingRows,
} from '../components/Wizards/WizardCommon';
import {
ActionTypes,
IAddDataColumnAction,
IAddDataRowAction,
ILaunchEditorAction,
ILaunchEditorWithCodeAction,
IPaneResizeAction,
IRemoveDataColumnAction,
IRemoveDataRowAction,
ISelectTabAction,
ISetContextAction,
IUpdateDataColumnNameAction,
IUpdateDataColumnTypeAction,
IUpdateDataRowAction,
IUpdateEditorStringAction,
ILoadedJSOMAction,
typeKeys,
} from './Actions';
import {
columnTypes,
IApplicationState,
ICode,
IContext,
IData,
IDataColumn,
initialState,
IPaneState,
ITabState,
uiState,
} from './State';
import { generateRowValue } from './ValueGeneration';
//** Primary reducer for adjusting redux state, calls individual reducer functions as necessary */
export const cfReducer = (state:IApplicationState = initialState, action:ActionTypes): IApplicationState => {
let newState:IApplicationState = clone(state);
switch (action.type) {
case typeKeys.SET_CONTEXT:
newState.context = SetContextReducer(newState.context, action);
newState.ui.height = action.properties.height;
newState.code.editorTheme = action.properties.editorTheme;
newState.code.showLineNumbers = action.properties.showLineNumbers;
newState.code.showIndentGuides = action.properties.showIndentGuides;
break;
case typeKeys.SET_HEIGHT:
newState.ui.height = action.height;
break;
case typeKeys.LAUNCH_EDITOR:
newState = LaunchEditorReducer(newState, action);
break;
case typeKeys.LAUNCH_EDITOR_WITH_CODE:
newState = LaunchEditorWithCodeReducer(newState, action);
break;
case typeKeys.CHANGE_UISTATE:
newState.ui.state = action.state;
break;
case typeKeys.DISCONNECT_WIZARD:
newState.ui.tabs.wizardTabVisible = false;
newState.ui.tabs.viewTab = 0;
break;
case typeKeys.UPDATE_DATA_ROW:
newState.data.rows = UpdateDataRowReducer(newState.data.rows, action);
break;
case typeKeys.UPDATE_DATA_COLUMN_NAME:
newState.data.columns = UpdateDataColumnNameReducer(newState.data.columns, action);
break;
case typeKeys.UPDATE_DATA_COLUMN_TYPE:
newState.data = UpdateDataColumnTypeReducer(newState.data, action);
break;
case typeKeys.ADD_DATA_ROW:
newState.data.rows = AddDataRowReducer(newState.data, action);
break;
case typeKeys.REMOVE_DATA_ROW:
newState.data.rows = RemoveDataRowReducer(newState.data.rows, action);
break;
case typeKeys.ADD_DATA_COLUMN:
newState.data = AddDataColumnReducer(newState.data, action);
break;
case typeKeys.REMOVE_DATA_COLUMN:
newState.data = RemoveDataColumnReducer(newState.data, action);
break;
case typeKeys.SELECT_TAB:
newState.ui.tabs = SelectTabReducer(newState.ui.tabs, action);
break;
case typeKeys.PANE_RESIZE:
newState.ui.panes = PaneResizeReducer(newState.ui.panes, action);
break;
case typeKeys.CHOOSE_THEME:
newState.code.editorTheme = action.theme;
break;
case typeKeys.TOGGLE_LINENUMBERS:
newState.code.showLineNumbers = action.showLineNumbers;
break;
case typeKeys.TOGGLE_MINIMAP:
newState.code.showMiniMap = action.showMiniMap;
break;
case typeKeys.TOGGLE_INDENTGUIDES:
newState.code.showIndentGuides = action.showIndentGuides;
break;
case typeKeys.UPDATE_EDITOR_STRING:
newState.code = UpdateEditorStringReducer(newState.code, action);
break;
case typeKeys.UPDATE_FORMATTER_ERRORS:
newState.code.formatterErrors = action.formatterErrors;
break;
case typeKeys.LOADED_JSOM:
newState.context.jsomLoaded = action.jsomLoaded;
break;
default:
return state;
}
return newState;
};
function SetContextReducer(context:IContext, action:ISetContextAction): IContext {
return {
isOnline: action.isOnline,
webAbsoluteUrl: action.webAbsoluteUrl,
user: {
displayName: action.userDisplayName,
email: action.userEmail
},
jsomLoaded: context.jsomLoaded,
properties: action.properties
};
}
function LaunchEditorReducer(state:IApplicationState, action:ILaunchEditorAction): IApplicationState {
let wizard:IWizard = getWizardByName(action.wizardName);
return {
data: {
columns: wizard !== undefined ? wizard.startingColumns(action.colType) : standardWizardStartingColumns(action.colType),
rows: wizard !== undefined ? wizard.startingRows(action.colType, state.context.user) : standardWizardStartingRows(action.colType)
},
ui: {
...state.ui,
state: uiState.editing,
tabs: {
...state.ui.tabs,
viewTab: (wizard !== undefined && !wizard.isTemplate) ? 0 : 2,
wizardTabVisible: (wizard !== undefined && !wizard.isTemplate)
},
saveDetails: {
activeSaveMethod: undefined,
libraryUrl: undefined,
libraryFolderPath: '',
libraryFilename: '',
list: undefined,
field: undefined
}
},
code: {
...state.code,
validationErrors: [],
formatterErrors: [],
formatterString: wizard !== undefined ? wizard.startingCode(action.colType) : standardWizardStartingCode(action.colType),
editorString: wizard !== undefined ? wizard.startingCode(action.colType) : standardWizardStartingCode(action.colType),
wizardName: wizard !== undefined ? wizard.name : undefined
},
context: state.context
};
}
function LaunchEditorWithCodeReducer(state:IApplicationState, action:ILaunchEditorWithCodeAction): IApplicationState {
let wizard:IWizard = getWizardByName(action.wizardName);
return {
data: {
columns: wizard !== undefined ? wizard.startingColumns(action.colType) : standardWizardStartingColumns(action.colType),
rows: wizard !== undefined ? wizard.startingRows(action.colType) : standardWizardStartingRows(action.colType)
},
ui: {
...state.ui,
state: uiState.editing,
tabs: {
...state.ui.tabs,
viewTab: (wizard !== undefined && !wizard.isTemplate) ? 0 : 2,
wizardTabVisible: (wizard !== undefined && !wizard.isTemplate)
},
saveDetails: {
...action.saveDetails
}
},
code: {
...state.code,
validationErrors: action.validationErrors,
formatterErrors: [],
formatterString: action.editorString,
editorString: action.editorString,
wizardName: wizard !== undefined ? wizard.name : undefined
},
context: state.context
};
}
//** Changes the value of the specified row and column */
function UpdateDataRowReducer(rows:Array<Array<any>>, action:IUpdateDataRowAction): Array<Array<any>> {
return [
...rows.slice(0, action.rowIndex),
[
...rows[action.rowIndex].slice(0, action.colIndex),
action.value,
...rows[action.rowIndex].slice(action.colIndex + 1)],
...rows.slice(action.rowIndex + 1)
];
}
//** Changes the name of the specified column */
function UpdateDataColumnNameReducer(columns:Array<IDataColumn>, action:IUpdateDataColumnNameAction): Array<IDataColumn> {
return [
...columns.slice(0, action.colIndex),
{
...columns[action.colIndex],
name: action.name
},
...columns.slice(action.colIndex + 1)
];
}
//** Changes the type of the specified column (and regenerates the row values as well) */
function UpdateDataColumnTypeReducer(data:IData, action:IUpdateDataColumnTypeAction): IData {
return {
columns: [
...data.columns.slice(0, action.colIndex),
{
...data.columns[action.colIndex],
type: action.colType
},
...data.columns.slice(action.colIndex + 1)
],
rows: data.rows.map((row:Array<any>, rIndex:number) => {
return [
...row.slice(0, action.colIndex),
generateRowValue(action.colType),
...row.slice(action.colIndex + 1)];
})
};
}
//** Adds a new data row (and generates the row values) */
function AddDataRowReducer(data:IData, action:IAddDataRowAction): Array<Array<any>> {
let newRow:Array<any> = new Array<any>();
for (var column of data.columns){
newRow.push(generateRowValue(column.type));
}
return [
...data.rows,
newRow
];
}
//** Deletes a data row */
function RemoveDataRowReducer(rows:Array<Array<any>>, action:IRemoveDataRowAction): Array<Array<any>> {
if (rows.length == 1) {
//Never remove the last row
return rows;
}
return [
...rows.slice(0,action.rowIndex),
...rows.slice(action.rowIndex + 1)
];
}
//** Adds a new data column (always of type text with generated values) */
function AddDataColumnReducer(data:IData, action:IAddDataColumnAction): IData {
//Ensure new column has a unique name
let isUnique:boolean = false;
let fieldCounter:number = 1;
let fieldName:string = strings.DataColumn_DefaultName;
do {
for(var column of data.columns){
if(column.name == fieldName){
fieldCounter++;
fieldName = strings.DataColumn_DefaultName + fieldCounter.toString();
continue;
}
}
isUnique = true;
} while(!isUnique);
return {
columns: [
...data.columns,
{
name: fieldName,
type: columnTypes.text
}
],
rows: data.rows.map((row:Array<any>, rIndex:number) => {
return [
...row,
generateRowValue(columnTypes.text)
];
})
};
}
//** Removes a data column (add associated row values) */
function RemoveDataColumnReducer(data:IData, action:IRemoveDataColumnAction): IData {
return {
columns: [
...data.columns.slice(0, action.colIndex),
...data.columns.slice(action.colIndex + 1)
],
rows: data.rows.map((row:Array<any>, rIndex:number) => {
return [
...row.slice(0, action.colIndex),
...row.slice(action.colIndex + 1)
];
})
};
}
function SelectTabReducer(tabs:ITabState, action:ISelectTabAction): ITabState {
if(action.tabName == 'view'){
return {
...tabs,
viewTab: action.index
};
}
return {
...tabs,
propertyTab: action.index
};
}
function PaneResizeReducer(panes:IPaneState, action:IPaneResizeAction): IPaneState {
if(action.paneName == 'main'){
return {
...panes,
main: action.size
};
}
return {
...panes,
split: action.size
};
}
function UpdateEditorStringReducer(code:ICode, action:IUpdateEditorStringAction): ICode {
//purposely not making a fully new code object
code.editorString = action.editorString;
if(action.validationErrors.length == 0) {
code.formatterString = action.editorString;
}
code.validationErrors = action.validationErrors;
return code;
} | the_stack |
* @file eth-tests.ts
* @author Josh Stevens <joshstevens19@hotmail.co.uk>
* @author Prince Sinha <sinhaprince013@gmail.com>
* @date 2018
*/
import {
Log,
RLPEncodedTransaction,
Transaction,
TransactionReceipt
} from 'web3-core';
import { Block, BlockHeader, Eth, GetProof, Syncing } from 'web3-eth';
const eth = new Eth('http://localhost:8545');
// $ExpectType string | null
eth.defaultAccount;
// $ExpectType string | number
eth.defaultBlock;
// $ExpectType Common
eth.defaultCommon;
// $ExpectType hardfork
eth.defaultHardfork;
// $ExpectType chain
eth.defaultChain;
// $ExpectType number
eth.transactionPollingTimeout;
// $ExpectType number
eth.transactionConfirmationBlocks;
// $ExpectType number
eth.transactionBlockTimeout;
// $ExpectType new (jsonInterface: AbiItem | AbiItem[], address?: string | undefined, options?: ContractOptions | undefined) => Contract
eth.Contract;
// $ExpectType new (iban: string) => Iban
eth.Iban;
// $ExpectType Personal
eth.personal;
// $ExpectType Accounts
eth.accounts;
// $ExpectType any
eth.extend({property: 'test', methods: [{name: 'method', call: 'method'}]});
// $ExpectType Ens
eth.ens;
// $ExpectType AbiCoder
eth.abi;
// $ExpectType Network
eth.net;
// $ExpectType void
eth.clearSubscriptions(() => {});
// $ExpectType Subscription<Log>
eth.subscribe('logs');
// $ExpectType Subscription<Log>
eth.subscribe('logs', {});
// $ExpectType Subscription<Log>
eth.subscribe('logs', {}, (error: Error, log: Log) => {});
// $ExpectType Subscription<Syncing>
eth.subscribe('syncing');
// $ExpectType Subscription<Syncing>
eth.subscribe('syncing', null, (error: Error, result: Syncing) => {});
// $ExpectType Subscription<BlockHeader>
eth.subscribe('newBlockHeaders');
// $ExpectType Subscription<BlockHeader>
eth.subscribe(
'newBlockHeaders',
null,
(error: Error, blockHeader: BlockHeader) => {}
);
// $ExpectType Subscription<string>
eth.subscribe('pendingTransactions');
// $ExpectType Subscription<string>
eth.subscribe(
'pendingTransactions',
null,
(error: Error, transactionHash: string) => {}
);
// $ExpectType provider
eth.currentProvider;
// $ExpectType any
eth.givenProvider;
// $ExpectType string | null
eth.defaultAccount;
// $ExpectType string | number
eth.defaultBlock;
// $ExpectType boolean
eth.setProvider('https://localhost:2100');
// $ExpectType BatchRequest
new eth.BatchRequest();
// $ExpectType Promise<string>
eth.getProtocolVersion();
// $ExpectType Promise<string>
eth.getProtocolVersion((error: Error, protocolVersion: string) => {});
// $ExpectType Promise<boolean | Syncing>
eth.isSyncing();
// $ExpectType Promise<boolean | Syncing>
eth.isSyncing((error: Error, syncing: Syncing) => {});
// $ExpectType Promise<string>
eth.getCoinbase();
// $ExpectType Promise<string>
eth.getCoinbase((error: Error, coinbaseAddress: string) => {});
// $ExpectType Promise<boolean>
eth.isMining();
// $ExpectType Promise<boolean>
eth.isMining((error: Error, mining: boolean) => {});
// $ExpectType Promise<number>
eth.getHashrate();
// $ExpectType Promise<number>
eth.getHashrate((error: Error, hashes: number) => {});
// $ExpectType Promise<string>
eth.getNodeInfo();
// $ExpectType Promise<string>
eth.getNodeInfo((error: Error, version: string) => {});
// $ExpectType Promise<number>
eth.getChainId();
// $ExpectType Promise<number>
eth.getChainId((error: Error, chainId: number) => {});
// $ExpectType Promise<string>
eth.getGasPrice();
// $ExpectType Promise<string>
eth.getGasPrice((error: Error, gasPrice: string) => {});
// $ExpectType Promise<string[]>
eth.getAccounts();
// $ExpectType Promise<string[]>
eth.getAccounts((error: Error, accounts: string[]) => {});
// $ExpectType Promise<number>
eth.getBlockNumber();
// $ExpectType Promise<number>
eth.getBlockNumber((error: Error, blockNumber: number) => {});
// $ExpectType Promise<string>
eth.getBalance('0x407d73d8a49eeb85d32cf465507dd71d507100c1');
// $ExpectType Promise<string>
eth.getBalance('0x407d73d8a49eeb85d32cf465507dd71d507100c1', '1000');
// $ExpectType Promise<string>
eth.getBalance(
'0x407d73d8a49eeb85d32cf465507dd71d507100c1',
'1000',
(error: Error, balance: string) => {}
);
// $ExpectType Promise<string>
eth.getBalance('0x407d73d8a49eeb85d32cf465507dd71d507100c1', 1000);
// $ExpectType Promise<string>
eth.getBalance(
'0x407d73d8a49eeb85d32cf465507dd71d507100c1',
1000,
(error: Error, balance: string) => {}
);
// $ExpectType Promise<string>
eth.getStorageAt('0x407d73d8a49eeb85d32cf465507dd71d507100c1', 2);
// $ExpectType Promise<string>
eth.getStorageAt('0x407d73d8a49eeb85d32cf465507dd71d507100c1', 2, '1000');
// $ExpectType Promise<string>
eth.getStorageAt(
'0x407d73d8a49eeb85d32cf465507dd71d507100c1',
2,
'1000',
(error: Error, balance: string) => {}
);
// $ExpectType Promise<string>
eth.getStorageAt('0x407d73d8a49eeb85d32cf465507dd71d507100c1', 2, 1000);
// $ExpectType Promise<string>
eth.getStorageAt(
'0x407d73d8a49eeb85d32cf465507dd71d507100c1',
2,
1000,
(error: Error, balance: string) => {}
);
// $ExpectType Promise<string>
eth.getCode('0x407d73d8a49eeb85d32cf465507dd71d507100c1');
// $ExpectType Promise<string>
eth.getCode('0x407d73d8a49eeb85d32cf465507dd71d507100c1', '1000');
// $ExpectType Promise<string>
eth.getCode(
'0x407d73d8a49eeb85d32cf465507dd71d507100c1',
'1000',
(error: Error, balance: string) => {}
);
// $ExpectType Promise<string>
eth.getCode('0x407d73d8a49eeb85d32cf465507dd71d507100c1', 1000);
// $ExpectType Promise<string>
eth.getCode(
'0x407d73d8a49eeb85d32cf465507dd71d507100c1',
1000,
(error: Error, balance: string) => {}
);
// $ExpectType Promise<Block>
eth.getBlock('0x407d73d8a49eeb85d32cf465507dd71d507100c1');
// $ExpectType Promise<Block>
eth.getBlock(345);
// $ExpectType Promise<Block>
eth.getBlock('0x407d73d8a49eeb85d32cf465507dd71d507100c1', true);
// $ExpectType Promise<Block>
eth.getBlock('0x407d73d8a49eeb85d32cf465507dd71d507100c1', false);
// $ExpectType Promise<Block>
eth.getBlock(345);
// $ExpectType Promise<Block>
eth.getBlock(345, true);
// $ExpectType Promise<Block>
eth.getBlock(345, false);
// $ExpectType Promise<Block>
eth.getBlock(
'0x407d73d8a49eeb85d32cf465507dd71d507100c1',
(error: Error, block: Block) => {}
);
// $ExpectType Promise<Block>
eth.getBlock(345, (error: Error, block: Block) => {});
// $ExpectType Promise<Block>
eth.getBlock(345, true, (error: Error, block: Block) => {});
// $ExpectType Promise<Block>
eth.getBlock(345, false, (error: Error, block: Block) => {});
// $ExpectType Promise<Block>
eth.getBlock(
'0x407d73d8a49eeb85d32cf465507dd71d507100c1',
true,
(error: Error, block: Block) => {}
);
// $ExpectType Promise<Block>
eth.getBlock(
'0x407d73d8a49eeb85d32cf465507dd71d507100c1',
false,
(error: Error, block: Block) => {}
);
// $ExpectType Promise<number>
eth.getBlockTransactionCount(
'0x407d73d8a49eeb85d32cf465507dd71d507100c1',
(error: Error, numberOfTransactions: number) => {}
);
// $ExpectType Promise<number>
eth.getBlockTransactionCount(345);
// $ExpectType Promise<number>
eth.getBlockTransactionCount(
'0x407d73d8a49eeb85d32cf465507dd71d507100c1',
(error: Error, numberOfTransactions: number) => {}
);
// $ExpectType Promise<number>
eth.getBlockTransactionCount(345);
// $ExpectType Promise<Block>
eth.getUncle('0x407d73d8a49eeb85d32cf465507dd71d507100c1', 4);
// $ExpectType Promise<Block>
eth.getUncle(345, 4);
// $ExpectType Promise<Block>
eth.getUncle('0x407d73d8a49eeb85d32cf465507dd71d507100c1', 4, true);
// $ExpectType Promise<Block>
eth.getUncle('0x407d73d8a49eeb85d32cf465507dd71d507100c1', 4, false);
// $ExpectType Promise<Block>
eth.getUncle(
'0x407d73d8a49eeb85d32cf465507dd71d507100c1',
4,
(error: Error, uncle: {}) => {}
);
// $ExpectType Promise<Block>
eth.getUncle(345, 4, (error: Error, uncle: {}) => {});
// $ExpectType Promise<Block>
eth.getUncle(345, 4, true);
// $ExpectType Promise<Block>
eth.getUncle(345, 4, false);
// $ExpectType Promise<Block>
eth.getUncle(
'0x407d73d8a49eeb85d32cf465507dd71d507100c1',
4,
true,
(error: Error, uncle: {}) => {}
);
// $ExpectType Promise<Block>
eth.getUncle(
'0x407d73d8a49eeb85d32cf465507dd71d507100c1',
4,
false,
(error: Error, uncle: {}) => {}
);
// $ExpectType Promise<Block>
eth.getUncle(345, 4, true, (error: Error, uncle: {}) => {});
// $ExpectType Promise<Block>
eth.getUncle(345, 4, false, (error: Error, uncle: {}) => {});
// $ExpectType Promise<Transaction>
eth.getTransaction('0x407d73d8a49eeb85d32cf465507dd71d507100c1');
// $ExpectType Promise<Transaction>
eth.getTransaction(
'0x407d73d8a49eeb85d32cf465507dd71d507100c1',
(error: Error, transaction: Transaction) => {}
);
// $ExpectType Promise<Transaction>
eth.getTransactionFromBlock('0x407d73d8a49eeb85d32cf465507dd71d507100c1', 2);
// $ExpectType Promise<Transaction>
eth.getTransactionFromBlock(345, 2);
// $ExpectType Promise<Transaction>
eth.getTransactionFromBlock(
'0x407d73d8a49eeb85d32cf465507dd71d507100c1',
2,
(error: Error, transaction: Transaction) => {}
);
// $ExpectType Promise<Transaction>
eth.getTransactionFromBlock(
345,
2,
(error: Error, transaction: Transaction) => {}
);
// $ExpectType Promise<TransactionReceipt>
eth.getTransactionReceipt('0x407d73d8a49eeb85d32cf465507dd71d507100c1');
// $ExpectType Promise<TransactionReceipt>
eth.getTransactionReceipt(
'0x407d73d8a49eeb85d32cf465507dd71d507100c1',
(error: Error, transactionReceipt: TransactionReceipt) => {}
);
// $ExpectType Promise<number>
eth.getTransactionCount('0x407d73d8a49eeb85d32cf465507dd71d507100c1');
// $ExpectType Promise<number>
eth.getTransactionCount('0x407d73d8a49eeb85d32cf465507dd71d507100c1', 1000);
// $ExpectType Promise<number>
eth.getTransactionCount('0x407d73d8a49eeb85d32cf465507dd71d507100c1', '1000');
// $ExpectType Promise<number>
eth.getTransactionCount(
'0x407d73d8a49eeb85d32cf465507dd71d507100c1',
(error: Error, count: number) => {}
);
// $ExpectType Promise<number>
eth.getTransactionCount(
'0x407d73d8a49eeb85d32cf465507dd71d507100c1',
(error: Error, count: number) => {}
);
// $ExpectType Promise<number>
eth.getTransactionCount(
'0x407d73d8a49eeb85d32cf465507dd71d507100c1',
1000,
(error: Error, count: number) => {}
);
// $ExpectType Promise<number>
eth.getTransactionCount(
'0x407d73d8a49eeb85d32cf465507dd71d507100c1',
'1000',
(error: Error, count: number) => {}
);
const code = '603d80600c6000396000f3007c0';
// $ExpectType PromiEvent<TransactionReceipt>
eth.sendTransaction({
from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe',
data: 'code'
});
// $ExpectType PromiEvent<TransactionReceipt>
eth.sendTransaction(
{
from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe',
data: 'code'
},
(error: Error, hash: string) => {}
);
// $ExpectType PromiEvent<TransactionReceipt>
eth.sendSignedTransaction('0xf889808609184e72a0008227109');
// $ExpectType PromiEvent<TransactionReceipt>
eth.sendSignedTransaction(
'0xf889808609184e72a0008227109',
(error: Error, hash: string) => {}
);
// $ExpectType Promise<string>
eth.sign('Hello world', '0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe');
// $ExpectType Promise<string>
eth.sign('Hello world', 3);
// $ExpectType Promise<string>
eth.sign(
'Hello world',
'0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe',
(error: Error, signature: string) => {}
);
// $ExpectType Promise<string>
eth.sign('Hello world', 3, (error: Error, signature: string) => {});
// $ExpectType Promise<RLPEncodedTransaction>
eth.signTransaction({
from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0',
gasPrice: '20000000000',
gas: '21000',
to: '0x3535353535353535353535353535353535353535',
value: '1000000000000000000',
data: ''
});
// $ExpectType Promise<RLPEncodedTransaction>
eth.signTransaction(
{
from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0',
gasPrice: '20000000000',
gas: '21000',
to: '0x3535353535353535353535353535353535353535',
value: '1000000000000000000',
data: ''
},
'0xEB014f8c8B418Db6b45774c326A0E64C78914dC0'
);
// $ExpectType Promise<RLPEncodedTransaction>
eth.signTransaction(
{
from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0',
gasPrice: '20000000000',
gas: '21000',
to: '0x3535353535353535353535353535353535353535',
value: '1000000000000000000',
data: ''
},
(error: Error, signedTransaction: RLPEncodedTransaction) => {}
);
// $ExpectType Promise<RLPEncodedTransaction>
eth.signTransaction(
{
from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0',
gasPrice: '20000000000',
gas: '21000',
to: '0x3535353535353535353535353535353535353535',
value: '1000000000000000000',
data: ''
},
'0xEB014f8c8B418Db6b45774c326A0E64C78914dC0',
(error: Error, signedTransaction: RLPEncodedTransaction) => {}
);
// $ExpectType Promise<string>
eth.call({
to: '0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe', // contract address
data:
'0xc6888fa10000000000000000000000000000000000000000000000000000000000000003'
});
// $ExpectType Promise<string>
eth.call(
{
to: '0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe', // contract address
data:
'0xc6888fa10000000000000000000000000000000000000000000000000000000000000003'
},
100
);
// $ExpectType Promise<string>
eth.call(
{
to: '0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe', // contract address
data:
'0xc6888fa10000000000000000000000000000000000000000000000000000000000000003'
},
'100'
);
// $ExpectType Promise<string>
eth.call(
{
to: '0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe', // contract address
data:
'0xc6888fa10000000000000000000000000000000000000000000000000000000000000003'
},
(error: Error, data: string) => {}
);
// $ExpectType Promise<string>
eth.call(
{
to: '0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe', // contract address
data:
'0xc6888fa10000000000000000000000000000000000000000000000000000000000000003'
},
'100',
(error: Error, data: string) => {}
);
// $ExpectType Promise<string>
eth.call(
{
to: '0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe', // contract address
data:
'0xc6888fa10000000000000000000000000000000000000000000000000000000000000003'
},
100,
(error: Error, data: string) => {}
);
// $ExpectType Promise<string>
eth.call(
{
to: '0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe', // contract address
data:
'0xc6888fa10000000000000000000000000000000000000000000000000000000000000003'
},
100,
(error: Error, data: string) => {}
);
// $ExpectType Promise<number>
eth.estimateGas({
to: '0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe',
data:
'0xc6888fa10000000000000000000000000000000000000000000000000000000000000003'
});
// $ExpectType Promise<number>
eth.estimateGas(
{
to: '0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe',
data:
'0xc6888fa10000000000000000000000000000000000000000000000000000000000000003'
},
(error: Error, gas: number) => {}
);
// $ExpectType Promise<Log[]>
eth.getPastLogs({
address: '0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe',
topics: ['0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234']
});
// $ExpectType Promise<Log[]>
eth.getPastLogs(
{
address: '0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe',
topics: [
'0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234'
]
},
(error: Error, logs: Log[]) => {}
);
// $ExpectType Promise<string[]>
eth.getWork();
// $ExpectType Promise<string[]>
eth.getWork((error: Error, result: string[]) => {});
// $ExpectType Promise<boolean>
eth.submitWork([
'0x0000000000000001',
'0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef',
'0xD1FE5700000000000000000000000000D1FE5700000000000000000000000000'
]);
// $ExpectType Promise<boolean>
eth.submitWork(
[
'0x0000000000000001',
'0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef',
'0xD1FE5700000000000000000000000000D1FE5700000000000000000000000000'
],
(error: Error, result: boolean) => {}
);
// $ExpectType Promise<Transaction[]>
eth.getPendingTransactions();
// $ExpectType Promise<Transaction[]>
eth.getPendingTransactions((error: Error, result: Transaction[]) => {});
// $ExpectType Promise<GetProof>
eth.getProof(
'0x1234567890123456789012345678901234567890',
[
'0x0000000000000000000000000000000000000000000000000000000000000000',
'0x0000000000000000000000000000000000000000000000000000000000000001'
],
'latest'
);
// $ExpectType Promise<GetProof>
eth.getProof(
'0x1234567890123456789012345678901234567890',
[
'0x0000000000000000000000000000000000000000000000000000000000000000',
'0x0000000000000000000000000000000000000000000000000000000000000001'
],
'latest',
(error: Error, result: GetProof) => {}
);
// $ExpectType Promise<GetProof>
eth.getProof(
'0x1234567890123456789012345678901234567890',
[
'0x0000000000000000000000000000000000000000000000000000000000000000',
'0x0000000000000000000000000000000000000000000000000000000000000001'
],
10
);
// $ExpectType Promise<GetProof>
eth.getProof(
'0x1234567890123456789012345678901234567890',
[
'0x0000000000000000000000000000000000000000000000000000000000000000',
'0x0000000000000000000000000000000000000000000000000000000000000001'
],
10,
(error: Error, result: GetProof) => {}
); | the_stack |
import _ from "lodash"
import * as THREE from "three"
// Import * as THREE from 'three'
import * as action from "../../src/action/common"
import { moveCamera, moveCameraAndTarget } from "../../src/action/point_cloud"
import { selectLabel } from "../../src/action/select"
import Session from "../../src/common/session"
import { Label3DHandler } from "../../src/drawable/3d/label3d_handler"
import {
getCurrentViewerConfig,
getShape
} from "../../src/functional/state_util"
import { makePointCloudViewerConfig } from "../../src/functional/states"
import { Vector3D } from "../../src/math/vector3d"
import {
CubeType,
IdType,
PointCloudViewerConfigType
} from "../../src/types/state"
import { updateThreeCameraAndRenderer } from "../../src/view_config/point_cloud"
import { setupTestStore } from "../components/util"
import { expectVector3TypesClose } from "../server/util/util"
import { testJson } from "../test_states/test_point_cloud_objects"
import { findNewLabelsFromState } from "../util/state"
/**
* Get active axis given camLoc and axis
*
* @param camLoc
* @param axis
*/
function getActiveAxis(camLoc: number, axis: number): number {
if (Math.floor(camLoc / 2) === 0) {
if (axis <= 1) {
return 2
} else if (axis >= 2) {
return 1
}
} else if (Math.floor(camLoc / 2) === 1) {
if (axis <= 1) {
return 2
} else if (axis >= 2) {
return 0
}
} else if (Math.floor(camLoc / 2) === 2) {
if (axis <= 1) {
return 0
} else if (axis >= 2) {
return 1
}
}
throw new Error("Impossible case happened")
}
/**
* Get active axis for rotation given camLoc and axis
*
* @param camLoc
* @param axis
*/
function getActiveAxisForRotation(camLoc: number, axis: number): number {
if (Math.floor(camLoc / 2) === 0) {
if (axis <= 1) {
return 1
} else if (axis >= 2) {
return 2
}
} else if (Math.floor(camLoc / 2) === 1) {
if (axis <= 1) {
return 0
} else if (axis >= 2) {
return 2
}
} else if (Math.floor(camLoc / 2) === 2) {
if (axis <= 1) {
return 1
} else if (axis >= 2) {
return 0
}
}
throw new Error("Impossible case happened")
}
/**
* Initialize Session, label 3d list, label 3d handler
*
* @param camera
*/
function initializeTestingObjects(
camera: THREE.Camera
): [Label3DHandler, number] {
setupTestStore(testJson)
Session.dispatch(action.addViewerConfig(1, makePointCloudViewerConfig(-1)))
const viewerId = 1
const label3dHandler = new Label3DHandler(camera, false)
Session.subscribe(() => {
const state = Session.getState()
Session.label3dList.updateState(state)
label3dHandler.updateState(state, state.user.select.item, viewerId)
})
Session.label3dList.subscribe(() => {
Session.label3dList.control.updateMatrixWorld(true)
})
Session.dispatch(action.loadItem(0, -1))
const itemIndex = 0
Session.dispatch(action.goToItem(itemIndex))
return [label3dHandler, viewerId]
}
test("Add 3d bbox", () => {
const labelIds: IdType[] = []
const [label3dHandler, viewerId] = initializeTestingObjects(
new THREE.PerspectiveCamera(45, 1, 0.1, 1000)
)
const spaceEvent = new KeyboardEvent("keydown", { key: " " })
label3dHandler.onKeyDown(spaceEvent)
let state = Session.getState()
expect(_.size(state.task.items[0].labels)).toEqual(1)
labelIds.push(findNewLabelsFromState(state, 0, labelIds)[0])
let cube = getShape(state, 0, labelIds[0], 0) as CubeType
let viewerConfig = getCurrentViewerConfig(
state,
viewerId
) as PointCloudViewerConfigType
expect(viewerConfig).not.toBeNull()
expectVector3TypesClose(cube.center, viewerConfig.target)
expectVector3TypesClose(cube.orientation, { x: 0, y: 0, z: 0 })
expectVector3TypesClose(cube.size, { x: 1, y: 1, z: 1 })
expect(cube.anchorIndex).toEqual(0)
// Move target randomly a few times and
// make sure that the bounding box is always created at the target
const maxVal = 100
const position = new Vector3D()
position.fromState(viewerConfig.position)
const target = new Vector3D()
for (let i = 1; i <= 10; i += 1) {
target[0] = Math.random() * 2 - 1
target[1] = Math.random() * 2 - 1
target[2] = Math.random() * 2 - 1
target.multiplyScalar(maxVal)
Session.dispatch(
moveCameraAndTarget(position, target, viewerId, viewerConfig)
)
label3dHandler.onKeyDown(spaceEvent)
state = Session.getState()
expect(_.size(state.task.items[0].labels)).toEqual(i + 1)
labelIds.push(findNewLabelsFromState(state, 0, labelIds)[0])
cube = getShape(state, 0, labelIds[i], 0) as CubeType
viewerConfig = getCurrentViewerConfig(
state,
viewerId
) as PointCloudViewerConfigType
expect(viewerConfig).not.toBeNull()
expectVector3TypesClose(viewerConfig.position, position)
expectVector3TypesClose(viewerConfig.target, target)
expectVector3TypesClose(cube.center, viewerConfig.target)
expectVector3TypesClose(cube.orientation, { x: 0, y: 0, z: 0 })
expectVector3TypesClose(cube.size, { x: 1, y: 1, z: 1 })
expect(cube.anchorIndex).toEqual(0)
}
})
test("Move axis aligned 3d bbox along z axis", () => {
const labelIds: IdType[] = []
const camera = new THREE.PerspectiveCamera(45, 1, 0.1, 1000)
camera.aspect = 1
camera.updateProjectionMatrix()
const [label3dHandler, viewerId] = initializeTestingObjects(camera)
let state = Session.getState()
let viewerConfig = getCurrentViewerConfig(
state,
viewerId
) as PointCloudViewerConfigType
Session.dispatch(
moveCameraAndTarget(new Vector3D(), new Vector3D(), viewerId, viewerConfig)
)
state = Session.getState()
viewerConfig = getCurrentViewerConfig(
state,
viewerId
) as PointCloudViewerConfigType
updateThreeCameraAndRenderer(viewerConfig, camera)
const spaceEvent = new KeyboardEvent("keydown", { key: " " })
label3dHandler.onKeyDown(spaceEvent)
state = Session.getState()
expect(_.size(state.task.items[0].labels)).toEqual(1)
const labelId = Object.keys(state.task.items[0].labels)[0]
Session.dispatch(selectLabel(state.user.select.labels, 0, labelId))
const tEvent = new KeyboardEvent("keydown", { key: "t" })
label3dHandler.onKeyDown(tEvent)
Session.label3dList.onDrawableUpdate()
label3dHandler.onKeyUp(tEvent)
Session.label3dList.onDrawableUpdate()
const position = new Vector3D()
position[1] = 10
Session.dispatch(moveCamera(position, viewerId, viewerConfig))
Session.label3dList.onDrawableUpdate()
state = Session.getState()
viewerConfig = getCurrentViewerConfig(
state,
viewerId
) as PointCloudViewerConfigType
camera.aspect = 1
camera.updateProjectionMatrix()
updateThreeCameraAndRenderer(viewerConfig, camera)
camera.updateMatrixWorld(true)
const raycastableShapes = Session.label3dList.raycastableShapes
const raycaster = new THREE.Raycaster()
raycaster.near = 1.0
raycaster.far = 100.0
raycaster.params = {
...raycaster.params,
Line: { threshold: 0.02 }
}
raycaster.setFromCamera(new THREE.Vector2(0, 0.15), camera)
let intersections = raycaster.intersectObjects(
(raycastableShapes as unknown) as THREE.Object3D[]
)
expect(intersections.length).toBeGreaterThan(0)
label3dHandler.onMouseMove(0, 0.15, intersections[0])
Session.label3dList.onDrawableUpdate()
label3dHandler.onMouseDown(0, 0.15)
label3dHandler.onMouseMove(0, 0.5)
Session.label3dList.onDrawableUpdate()
label3dHandler.onMouseUp()
state = Session.getState()
expect(_.size(state.task.items[0].labels)).toEqual(1)
labelIds.push(findNewLabelsFromState(state, 0, labelIds)[0])
let cube = getShape(state, 0, labelIds[0], 0) as CubeType
const center = new Vector3D().fromState(cube.center)
expect(center[2]).toBeGreaterThan(0)
expect(center[0]).toBeCloseTo(0)
expect(center[1]).toBeCloseTo(0)
raycaster.setFromCamera(new THREE.Vector2(0, 0.5), camera)
intersections = raycaster.intersectObjects(
(raycastableShapes as unknown) as THREE.Object3D[]
)
expect(intersections.length).toBeGreaterThan(0)
label3dHandler.onMouseMove(0, 0.5, intersections[0])
Session.label3dList.onDrawableUpdate()
label3dHandler.onMouseDown(0, 0.5)
label3dHandler.onMouseMove(0, 0.15)
Session.label3dList.onDrawableUpdate()
label3dHandler.onMouseUp()
state = Session.getState()
cube = getShape(state, 0, labelIds[0], 0) as CubeType
expectVector3TypesClose(cube.center, { x: 0, y: 0, z: 0 })
})
test("Move axis aligned 3d bbox along all axes", () => {
const labelIds: IdType[] = []
const camera = new THREE.PerspectiveCamera(45, 1, 0.1, 1000)
camera.aspect = 1
camera.updateProjectionMatrix()
const [label3dHandler, viewerId] = initializeTestingObjects(camera)
let state = Session.getState()
let viewerConfig = getCurrentViewerConfig(
state,
viewerId
) as PointCloudViewerConfigType
Session.dispatch(
moveCameraAndTarget(new Vector3D(), new Vector3D(), viewerId, viewerConfig)
)
const spaceEvent = new KeyboardEvent("keydown", { key: " " })
label3dHandler.onKeyDown(spaceEvent)
Session.label3dList.onDrawableUpdate()
label3dHandler.onKeyUp(spaceEvent)
Session.label3dList.onDrawableUpdate()
state = Session.getState()
expect(_.size(state.task.items[0].labels)).toEqual(1)
labelIds.push(findNewLabelsFromState(state, 0, labelIds)[0])
const labelId = Object.keys(state.task.items[0].labels)[0]
Session.dispatch(selectLabel(state.user.select.labels, 0, labelId))
const tEvent = new KeyboardEvent("keydown", { key: "t" })
label3dHandler.onKeyDown(tEvent)
Session.label3dList.onDrawableUpdate()
label3dHandler.onKeyUp(tEvent)
Session.label3dList.onDrawableUpdate()
// Set camera to each of 6 axis aligned locations around cube
// 0 = +x, 1 = -x, 2 = +y, 3 = -y, 4= +z, 5 = -z
for (let camLoc = 0; camLoc < 6; camLoc++) {
state = Session.getState()
viewerConfig = getCurrentViewerConfig(
state,
viewerId
) as PointCloudViewerConfigType
const position = new Vector3D()
position[Math.floor(camLoc / 2)] = 10 * (camLoc % 1 === 0 ? -1 : 1)
Session.dispatch(moveCamera(position, viewerId, viewerConfig))
state = Session.getState()
viewerConfig = getCurrentViewerConfig(
state,
viewerId
) as PointCloudViewerConfigType
updateThreeCameraAndRenderer(viewerConfig, camera)
camera.updateMatrixWorld(true)
Session.label3dList.onDrawableUpdate()
const raycastableShapes = Session.label3dList.raycastableShapes
const raycaster = new THREE.Raycaster()
raycaster.near = 1.0
raycaster.far = 100.0
raycaster.params = {
...raycaster.params,
Line: { threshold: 0.02 }
}
// From each axis aligned view there is vertical and horizontal axis.
// Try positive and negative directions. 0 = +v, 1 = -v, 2 = +h, 3 = -h
for (let axis = 0; axis < 4; axis++) {
const neg: boolean = axis % 2 === 1
// Because of the view orientation, a positive movement could be along
// a negative axis. This corrects that for testing.
const negAxis: boolean = axis >= 2 && (camLoc === 0 || camLoc === 1)
const vecX = 0.15 * (axis >= 2 ? 1 : 0) * (neg ? -1 : 1)
const vecY = 0.15 * (axis <= 1 ? 1 : 0) * (neg ? -1 : 1)
raycaster.setFromCamera(new THREE.Vector2(vecX, vecY), camera)
let intersections = raycaster.intersectObjects(
(raycastableShapes as unknown) as THREE.Object3D[]
)
expect(intersections.length).toBeGreaterThan(0)
label3dHandler.onMouseMove(vecX, vecY, intersections[0])
Session.label3dList.onDrawableUpdate()
label3dHandler.onMouseDown(vecX, vecY)
label3dHandler.onMouseMove(5 * vecX, 5 * vecY)
Session.label3dList.onDrawableUpdate()
label3dHandler.onMouseUp()
state = Session.getState()
let cube = getShape(state, 0, labelIds[0], 0) as CubeType
const center = new Vector3D().fromState(cube.center)
// Get ActiveAxis based on view point and vertical or horizontal
const activeAxis = getActiveAxis(camLoc, axis)
for (let i = 0; i < 3; i++) {
if (i !== activeAxis) {
// Check other directions have not moved due to translation
expect(center[i]).toBeCloseTo(0)
} else {
// Check translated direction, accounting for negations
const pos = (neg ? -1 : 1) * (negAxis ? -1 : 1) * center[i]
expect(pos).toBeGreaterThan(0)
}
}
raycaster.setFromCamera(new THREE.Vector2(5 * vecX, 5 * vecY), camera)
intersections = raycaster.intersectObjects(
(raycastableShapes as unknown) as THREE.Object3D[]
)
expect(intersections.length).toBeGreaterThan(0)
label3dHandler.onMouseMove(5 * vecX, 5 * vecY, intersections[0])
Session.label3dList.onDrawableUpdate()
label3dHandler.onMouseDown(5 * vecX, 5 * vecY)
label3dHandler.onMouseMove(vecX, vecY)
Session.label3dList.onDrawableUpdate()
label3dHandler.onMouseUp()
state = Session.getState()
cube = getShape(state, 0, labelIds[0], 0) as CubeType
expectVector3TypesClose(cube.center, { x: 0, y: 0, z: 0 })
}
}
})
test("Scale axis aligned 3d bbox along all axes", () => {
const labelIds: IdType[] = []
const camera = new THREE.PerspectiveCamera(45, 1, 0.1, 1000)
camera.aspect = 1
const [label3dHandler, viewerId] = initializeTestingObjects(camera)
let state = Session.getState()
let viewerConfig = getCurrentViewerConfig(
state,
viewerId
) as PointCloudViewerConfigType
Session.dispatch(
moveCameraAndTarget(new Vector3D(), new Vector3D(), viewerId, viewerConfig)
)
const spaceEvent = new KeyboardEvent("keydown", { key: " " })
label3dHandler.onKeyDown(spaceEvent)
Session.label3dList.onDrawableUpdate()
label3dHandler.onKeyUp(spaceEvent)
Session.label3dList.onDrawableUpdate()
state = Session.getState()
expect(_.size(state.task.items[0].labels)).toEqual(1)
labelIds.push(findNewLabelsFromState(state, 0, labelIds)[0])
Session.dispatch(selectLabel(state.user.select.labels, 0, labelIds[0]))
Session.label3dList.onDrawableUpdate()
const sEvent = new KeyboardEvent("keydown", { key: "e" })
label3dHandler.onKeyDown(sEvent)
// Set camera to each of 6 axis aligned locations around cube
// 0 = +x, 1 = -x, 2 = +y, 3 = -y, 4= +z, 5 = -z
for (let camLoc = 0; camLoc < 6; camLoc++) {
state = Session.getState()
viewerConfig = getCurrentViewerConfig(
state,
viewerId
) as PointCloudViewerConfigType
const position = new Vector3D()
position[Math.floor(camLoc / 2)] = 10 * (camLoc % 1 === 0 ? -1 : 1)
Session.dispatch(moveCamera(position, viewerId, viewerConfig))
state = Session.getState()
viewerConfig = getCurrentViewerConfig(
state,
viewerId
) as PointCloudViewerConfigType
updateThreeCameraAndRenderer(viewerConfig, camera)
camera.updateMatrixWorld(true)
Session.label3dList.onDrawableUpdate()
const raycastableShapes = Session.label3dList.raycastableShapes
const raycaster = new THREE.Raycaster()
raycaster.near = 1.0
raycaster.far = 100.0
raycaster.params = {
...raycaster.params,
Line: { threshold: 0.02 }
}
// From each axis aligned view there is vertical and horizontal axis.
// Try positive and negative directions. 0 = +v, 1 = -v, 2 = +h, 3 = -h
for (let axis = 0; axis < 4; axis++) {
const neg: boolean = axis % 2 === 1
// Because of the view orientation, a positive movement could be along
// a negative axis. This corrects that for testing.
const negAxis: boolean = axis >= 2 && (camLoc === 0 || camLoc === 1)
const vecX = 0.1 * (axis >= 2 ? 1 : 0) * (neg ? -1 : 1)
const vecY = 0.1 * (axis <= 1 ? 1 : 0) * (neg ? -1 : 1)
raycaster.setFromCamera(new THREE.Vector2(vecX, vecY), camera)
let intersections = raycaster.intersectObjects(
(raycastableShapes as unknown) as THREE.Object3D[]
)
expect(intersections.length).toBeGreaterThan(0)
label3dHandler.onMouseMove(vecX, vecY, intersections[0])
Session.label3dList.onDrawableUpdate()
label3dHandler.onMouseDown(vecX, vecY)
label3dHandler.onMouseMove(5 * vecX, 5 * vecY)
Session.label3dList.onDrawableUpdate()
label3dHandler.onMouseUp()
state = Session.getState()
let cube = getShape(state, 0, labelIds[0], 0) as CubeType
const center = new Vector3D().fromState(cube.center)
const size = new Vector3D().fromState(cube.size)
// Get ActiveAxis based on view point and vertical or horizontal
const activeAxis = getActiveAxis(camLoc, axis)
// ExpectVector3TypesClose(cube.center, { x: 0, y: 0, z: 0 })
for (let i = 0; i < 3; i++) {
if (i !== activeAxis) {
// Check other directions have not changed due to scaling
expect(center[i]).toBeCloseTo(0)
expect(size[i]).toBeCloseTo(1)
} else {
// Check scaling direction, accounting for negations
const pos = (neg ? -1 : 1) * (negAxis ? -1 : 1) * center[i]
expect(pos).toBeGreaterThan(0)
expect(size[i]).toBeGreaterThan(1)
}
}
raycaster.setFromCamera(new THREE.Vector2(5 * vecX, 5 * vecY), camera)
intersections = raycaster.intersectObjects(
(raycastableShapes as unknown) as THREE.Object3D[]
)
expect(intersections.length).toBeGreaterThan(0)
label3dHandler.onMouseMove(5 * vecX, 5 * vecY, intersections[0])
Session.label3dList.onDrawableUpdate()
label3dHandler.onMouseDown(5 * vecX, 5 * vecY)
label3dHandler.onMouseMove(vecX, vecY)
Session.label3dList.onDrawableUpdate()
label3dHandler.onMouseUp()
state = Session.getState()
cube = getShape(state, 0, labelIds[0], 0) as CubeType
expectVector3TypesClose(cube.center, { x: 0, y: 0, z: 0 })
expectVector3TypesClose(cube.size, { x: 1, y: 1, z: 1 })
}
}
})
test("Rotate axis aligned 3d bbox around all axes", () => {
// Set camera to each of 6 axis aligned locations around cube
// 0 = +x, 1 = -x, 2 = +y, 3 = -y, 4= +z, 5 = -z
for (let camLoc = 0; camLoc < 6; camLoc++) {
// From each axis aligned view there is vertical and horizontal axis.
// Try positive and negative directions. 0 = +v, 1 = -v, 2 = +h, 3 = -h
for (let axis = 0; axis < 4; axis++) {
// Re-initialize labelIds (no labels from previous round).
const labelIds: IdType[] = []
const camera = new THREE.PerspectiveCamera(45, 1, 0.1, 1000)
camera.aspect = 1
const [label3dHandler, viewerId] = initializeTestingObjects(camera)
let state = Session.getState()
let viewerConfig = getCurrentViewerConfig(
state,
viewerId
) as PointCloudViewerConfigType
Session.dispatch(
moveCameraAndTarget(
new Vector3D(),
new Vector3D(),
viewerId,
viewerConfig
)
)
const spaceEvent = new KeyboardEvent("keydown", { key: " " })
label3dHandler.onKeyDown(spaceEvent)
Session.label3dList.onDrawableUpdate()
label3dHandler.onKeyUp(spaceEvent)
Session.label3dList.onDrawableUpdate()
state = Session.getState()
expect(_.size(state.task.items[0].labels)).toEqual(1)
labelIds.push(findNewLabelsFromState(state, 0, labelIds)[0])
Session.dispatch(selectLabel(state.user.select.labels, 0, labelIds[0]))
const rEvent = new KeyboardEvent("keydown", { key: "r" })
label3dHandler.onKeyDown(rEvent)
Session.label3dList.onDrawableUpdate()
label3dHandler.onKeyUp(rEvent)
Session.label3dList.onDrawableUpdate()
state = Session.getState()
viewerConfig = getCurrentViewerConfig(
state,
viewerId
) as PointCloudViewerConfigType
const position = new Vector3D()
position[Math.floor(camLoc / 2)] = 10 * (camLoc % 1 === 0 ? -1 : 1)
Session.dispatch(moveCamera(position, viewerId, viewerConfig))
state = Session.getState()
viewerConfig = getCurrentViewerConfig(
state,
viewerId
) as PointCloudViewerConfigType
updateThreeCameraAndRenderer(viewerConfig, camera)
camera.updateMatrixWorld(true)
Session.label3dList.onDrawableUpdate()
const raycastableShapes = Session.label3dList.raycastableShapes
const raycaster = new THREE.Raycaster()
raycaster.near = 1.0
raycaster.far = 100.0
raycaster.params = {
...raycaster.params,
Line: { threshold: 0.02 }
}
const neg: boolean = axis % 2 === 1
// Because of the view orientation, a positive movement could be along
// a negative axis. This corrects that for testing.
const negAxis: boolean = axis <= 1 && camLoc >= 2
const vecX = 0.1 * (axis >= 2 ? 1 : 0) * (neg ? -1 : 1)
const vecY = 0.1 * (axis <= 1 ? 1 : 0) * (neg ? -1 : 1)
raycaster.setFromCamera(new THREE.Vector2(vecX, vecY), camera)
let intersections = raycaster.intersectObjects(
(raycastableShapes as unknown) as THREE.Object3D[]
)
expect(intersections.length).toBeGreaterThan(0)
label3dHandler.onMouseMove(vecX, vecY, intersections[0])
Session.label3dList.onDrawableUpdate()
label3dHandler.onMouseDown(vecX, vecY)
label3dHandler.onMouseMove(2 * vecX, 2 * vecY)
Session.label3dList.onDrawableUpdate()
label3dHandler.onMouseUp()
state = Session.getState()
let cube = getShape(state, 0, labelIds[0], 0) as CubeType
const orientation = new Vector3D().fromState(cube.orientation)
// Get ActiveAxis based on view point and vertical or horizontal
const activeAxis = getActiveAxisForRotation(camLoc, axis)
expectVector3TypesClose(cube.center, { x: 0, y: 0, z: 0 })
expectVector3TypesClose(cube.size, { x: 1, y: 1, z: 1 })
for (let i = 0; i < 3; i++) {
if (i !== activeAxis) {
// Check other orientations have not moved due to rotation
expect(orientation[i]).toBeCloseTo(0)
} else {
// Check rotated orientations, accounting for negations
const pos = (neg ? -1 : 1) * (negAxis ? -1 : 1) * orientation[i]
expect(pos).toBeGreaterThan(0)
}
}
raycaster.setFromCamera(new THREE.Vector2(2 * vecX, 2 * vecY), camera)
intersections = raycaster.intersectObjects(
(raycastableShapes as unknown) as THREE.Object3D[]
)
expect(intersections.length).toBeGreaterThan(0)
label3dHandler.onMouseMove(2 * vecX, 2 * vecY, intersections[0])
Session.label3dList.onDrawableUpdate()
label3dHandler.onMouseDown(2 * vecX, 2 * vecY)
label3dHandler.onMouseMove(vecX, vecY)
Session.label3dList.onDrawableUpdate()
label3dHandler.onMouseUp()
state = Session.getState()
cube = getShape(state, 0, labelIds[0], 0) as CubeType
expectVector3TypesClose(cube.center, { x: 0, y: 0, z: 0 })
expectVector3TypesClose(cube.orientation, { x: 0, y: 0, z: 0 }, 1)
}
}
}) | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs, enums } from "../types";
import * as utilities from "../utilities";
/**
* Provides an AWS Network Firewall Firewall Resource
*
* ## Example Usage
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* const example = new aws.networkfirewall.Firewall("example", {
* firewallPolicyArn: aws_networkfirewall_firewall_policy.example.arn,
* vpcId: aws_vpc.example.id,
* subnetMappings: [{
* subnetId: aws_subnet.example.id,
* }],
* tags: {
* Tag1: "Value1",
* Tag2: "Value2",
* },
* });
* ```
*
* ## Import
*
* Network Firewall Firewalls can be imported using their `ARN`.
*
* ```sh
* $ pulumi import aws:networkfirewall/firewall:Firewall example arn:aws:network-firewall:us-west-1:123456789012:firewall/example
* ```
*/
export class Firewall extends pulumi.CustomResource {
/**
* Get an existing Firewall resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param state Any extra arguments used during the lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: FirewallState, opts?: pulumi.CustomResourceOptions): Firewall {
return new Firewall(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'aws:networkfirewall/firewall:Firewall';
/**
* Returns true if the given object is an instance of Firewall. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is Firewall {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === Firewall.__pulumiType;
}
/**
* The Amazon Resource Name (ARN) that identifies the firewall.
*/
public /*out*/ readonly arn!: pulumi.Output<string>;
/**
* A boolean flag indicating whether it is possible to delete the firewall. Defaults to `false`.
*/
public readonly deleteProtection!: pulumi.Output<boolean | undefined>;
/**
* A friendly description of the firewall.
*/
public readonly description!: pulumi.Output<string | undefined>;
/**
* The Amazon Resource Name (ARN) of the VPC Firewall policy.
*/
public readonly firewallPolicyArn!: pulumi.Output<string>;
/**
* A boolean flag indicating whether it is possible to change the associated firewall policy. Defaults to `false`.
*/
public readonly firewallPolicyChangeProtection!: pulumi.Output<boolean | undefined>;
/**
* Nested list of information about the current status of the firewall.
*/
public /*out*/ readonly firewallStatuses!: pulumi.Output<outputs.networkfirewall.FirewallFirewallStatus[]>;
/**
* A friendly name of the firewall.
*/
public readonly name!: pulumi.Output<string>;
/**
* A boolean flag indicating whether it is possible to change the associated subnet(s). Defaults to `false`.
*/
public readonly subnetChangeProtection!: pulumi.Output<boolean | undefined>;
/**
* Set of configuration blocks describing the public subnets. Each subnet must belong to a different Availability Zone in the VPC. AWS Network Firewall creates a firewall endpoint in each subnet. See Subnet Mapping below for details.
*/
public readonly subnetMappings!: pulumi.Output<outputs.networkfirewall.FirewallSubnetMapping[]>;
/**
* Map of resource tags to associate with the resource. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level.
*/
public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* A map of tags assigned to the resource, including those inherited from the provider .
*/
public /*out*/ readonly tagsAll!: pulumi.Output<{[key: string]: string}>;
/**
* A string token used when updating a firewall.
*/
public /*out*/ readonly updateToken!: pulumi.Output<string>;
/**
* The unique identifier of the VPC where AWS Network Firewall should create the firewall.
*/
public readonly vpcId!: pulumi.Output<string>;
/**
* Create a Firewall resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args: FirewallArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: FirewallArgs | FirewallState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as FirewallState | undefined;
inputs["arn"] = state ? state.arn : undefined;
inputs["deleteProtection"] = state ? state.deleteProtection : undefined;
inputs["description"] = state ? state.description : undefined;
inputs["firewallPolicyArn"] = state ? state.firewallPolicyArn : undefined;
inputs["firewallPolicyChangeProtection"] = state ? state.firewallPolicyChangeProtection : undefined;
inputs["firewallStatuses"] = state ? state.firewallStatuses : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["subnetChangeProtection"] = state ? state.subnetChangeProtection : undefined;
inputs["subnetMappings"] = state ? state.subnetMappings : undefined;
inputs["tags"] = state ? state.tags : undefined;
inputs["tagsAll"] = state ? state.tagsAll : undefined;
inputs["updateToken"] = state ? state.updateToken : undefined;
inputs["vpcId"] = state ? state.vpcId : undefined;
} else {
const args = argsOrState as FirewallArgs | undefined;
if ((!args || args.firewallPolicyArn === undefined) && !opts.urn) {
throw new Error("Missing required property 'firewallPolicyArn'");
}
if ((!args || args.subnetMappings === undefined) && !opts.urn) {
throw new Error("Missing required property 'subnetMappings'");
}
if ((!args || args.vpcId === undefined) && !opts.urn) {
throw new Error("Missing required property 'vpcId'");
}
inputs["deleteProtection"] = args ? args.deleteProtection : undefined;
inputs["description"] = args ? args.description : undefined;
inputs["firewallPolicyArn"] = args ? args.firewallPolicyArn : undefined;
inputs["firewallPolicyChangeProtection"] = args ? args.firewallPolicyChangeProtection : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["subnetChangeProtection"] = args ? args.subnetChangeProtection : undefined;
inputs["subnetMappings"] = args ? args.subnetMappings : undefined;
inputs["tags"] = args ? args.tags : undefined;
inputs["vpcId"] = args ? args.vpcId : undefined;
inputs["arn"] = undefined /*out*/;
inputs["firewallStatuses"] = undefined /*out*/;
inputs["tagsAll"] = undefined /*out*/;
inputs["updateToken"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(Firewall.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering Firewall resources.
*/
export interface FirewallState {
/**
* The Amazon Resource Name (ARN) that identifies the firewall.
*/
arn?: pulumi.Input<string>;
/**
* A boolean flag indicating whether it is possible to delete the firewall. Defaults to `false`.
*/
deleteProtection?: pulumi.Input<boolean>;
/**
* A friendly description of the firewall.
*/
description?: pulumi.Input<string>;
/**
* The Amazon Resource Name (ARN) of the VPC Firewall policy.
*/
firewallPolicyArn?: pulumi.Input<string>;
/**
* A boolean flag indicating whether it is possible to change the associated firewall policy. Defaults to `false`.
*/
firewallPolicyChangeProtection?: pulumi.Input<boolean>;
/**
* Nested list of information about the current status of the firewall.
*/
firewallStatuses?: pulumi.Input<pulumi.Input<inputs.networkfirewall.FirewallFirewallStatus>[]>;
/**
* A friendly name of the firewall.
*/
name?: pulumi.Input<string>;
/**
* A boolean flag indicating whether it is possible to change the associated subnet(s). Defaults to `false`.
*/
subnetChangeProtection?: pulumi.Input<boolean>;
/**
* Set of configuration blocks describing the public subnets. Each subnet must belong to a different Availability Zone in the VPC. AWS Network Firewall creates a firewall endpoint in each subnet. See Subnet Mapping below for details.
*/
subnetMappings?: pulumi.Input<pulumi.Input<inputs.networkfirewall.FirewallSubnetMapping>[]>;
/**
* Map of resource tags to associate with the resource. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* A map of tags assigned to the resource, including those inherited from the provider .
*/
tagsAll?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* A string token used when updating a firewall.
*/
updateToken?: pulumi.Input<string>;
/**
* The unique identifier of the VPC where AWS Network Firewall should create the firewall.
*/
vpcId?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a Firewall resource.
*/
export interface FirewallArgs {
/**
* A boolean flag indicating whether it is possible to delete the firewall. Defaults to `false`.
*/
deleteProtection?: pulumi.Input<boolean>;
/**
* A friendly description of the firewall.
*/
description?: pulumi.Input<string>;
/**
* The Amazon Resource Name (ARN) of the VPC Firewall policy.
*/
firewallPolicyArn: pulumi.Input<string>;
/**
* A boolean flag indicating whether it is possible to change the associated firewall policy. Defaults to `false`.
*/
firewallPolicyChangeProtection?: pulumi.Input<boolean>;
/**
* A friendly name of the firewall.
*/
name?: pulumi.Input<string>;
/**
* A boolean flag indicating whether it is possible to change the associated subnet(s). Defaults to `false`.
*/
subnetChangeProtection?: pulumi.Input<boolean>;
/**
* Set of configuration blocks describing the public subnets. Each subnet must belong to a different Availability Zone in the VPC. AWS Network Firewall creates a firewall endpoint in each subnet. See Subnet Mapping below for details.
*/
subnetMappings: pulumi.Input<pulumi.Input<inputs.networkfirewall.FirewallSubnetMapping>[]>;
/**
* Map of resource tags to associate with the resource. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* The unique identifier of the VPC where AWS Network Firewall should create the firewall.
*/
vpcId: pulumi.Input<string>;
} | the_stack |
import * as moment from 'moment-timezone';
import { ArgumentOutOfRangeException, ArgumentException } from "./Exceptions/ArgumentException";
import { DayOfWeek } from "./Enumerations/DayOfWeek";
import { IOutParam } from "./Interfaces/IOutParam";
import { StringHelper } from "./ExtensionMethods";
import { TimeSpan } from "./TimeSpan";
const ticksToEpoch: number = 621355968000000000; //can be used when calculating ticks/ms from Windows date to unix date
export const msToEpoch: number = 62135596800000;
const invalidDateTimeMessage = {
"years": "year is less than 1 or greater than 9999.",
"months": "month is less than 1 or greater than 12.",
"days": "day is less than 1 or greater than the number of days in month.",
"hours": "hour is less than 0 or greater than 23.",
"minutes": "minute is less than 0 or greater than 59.",
"seconds": "second is less than 0 or greater than 59.",
"milliseconds": "millisecond is less than 0 or greater than 999."
};
export enum DateTimeKind {
Unspecified = 0,
Utc = 1,
Local = 2,
}
/**
* DateTime - basic date time based on moment.js
*/
export class DateTime {
private static readonly DaysToMonth365: number[] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365];
private static readonly DaysToMonth366: number[] = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366];
kind: DateTimeKind = DateTimeKind.Unspecified;
get MomentDate(): moment.Moment { return this.momentDate; }
get currentUtcOffset(): number { return this.momentDate.utcOffset(); }
private get momentDate(): moment.Moment { return this.getMomentDate(); }
private getMomentDate: Function
private setMomentDate: Function
private originalDateInput: any = null;
public static get Now(): DateTime {
return new DateTime(moment());
}
public static get UtcNow(): DateTime {
return new DateTime(moment.utc());
}
get TotalMilliSeconds(): number {
return this.momentDate.valueOf()
}
constructor(ms: number);
constructor(date: DateTime);
constructor(momentInput: moment.MomentInput);
constructor(ms: number, kind: DateTimeKind);
constructor(year: number, month: number, day: number);
constructor(year: number, month: number, day: number, hour: number, minute: number, second: number);
constructor(year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond: number);
constructor(year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond: number, kind: DateTimeKind);
constructor(msOrDateOrMomentOrYear?: number | DateTime | moment.MomentInput,
monthOrKind?: number | DateTimeKind,
day?: number,
hour?: number,
minute?: number,
second?: number,
millisecond?: number,
kind: DateTimeKind = DateTimeKind.Unspecified) {
let argsLength = arguments.length;
let momentdate: moment.Moment = moment();
this.kind = kind;
if (argsLength === 1) {
if (msOrDateOrMomentOrYear instanceof DateTime) {
momentdate = msOrDateOrMomentOrYear.MomentDate.clone();
this.kind = msOrDateOrMomentOrYear.kind;
}
else {
momentdate = moment(msOrDateOrMomentOrYear);
this.originalDateInput = msOrDateOrMomentOrYear;
}
}
else if (argsLength === 2) {
if (monthOrKind === DateTimeKind.Utc && !(msOrDateOrMomentOrYear instanceof moment)) {
momentdate = moment.utc(<any>msOrDateOrMomentOrYear);
}
else {
momentdate = moment(<any>msOrDateOrMomentOrYear);
}
this.kind = monthOrKind;
if (this.kind === DateTimeKind.Unspecified && !(msOrDateOrMomentOrYear instanceof moment)) {
this.originalDateInput = msOrDateOrMomentOrYear;
}
}
else {
let momentInput: moment.MomentInputObject = {};
if (argsLength >= 3) {
momentInput.year = <number>msOrDateOrMomentOrYear;
momentInput.month = monthOrKind - 1;
momentInput.day = day;
}
if (argsLength >= 6) {
momentInput.hour = hour;
momentInput.minute = minute;
momentInput.second = second;
}
if (argsLength >= 7) {
momentInput.millisecond = millisecond;
}
momentdate = moment(momentInput);
}
if (momentdate && !momentdate.isValid()) {
let invalid = momentdate.invalidAt();
throw new ArgumentOutOfRangeException(momentValidity[invalid], invalidDateTimeMessage[momentValidity[invalid]]);
}
// if (momentdate.isUtc()) {
// this.kind = DateTimeKind.Utc
// }
// else if (momentdate.isLocal()) {
// this.kind = DateTimeKind.Local;
// }
this.getMomentDate = () => momentdate;
this.setMomentDate = (value) => momentdate = value;
}
Add(ts: TimeSpan, ): DateTime;
Add(quantity: number, unit: moment.unitOfTime.Base): DateTime;
Add(quantity: number | TimeSpan, unit: moment.unitOfTime.Base = "ms"): DateTime {
if (typeof quantity !== 'number') {
quantity = quantity.TotalMilliseconds;
unit = "ms"
}
var date: moment.Moment = moment(this.momentDate);
date.add(quantity, unit);
return new DateTime(date);
}
static Compare(x: DateTime, y: DateTime): number {
var diff: number = x.momentDate.diff(y.momentDate);
if (diff === 0) return 0;
if (diff < 0) return -1;
return 1;
}
CompareTo(toDate: DateTime): number {
return DateTime.Compare(this, toDate);
}
Difference(toDate: DateTime): TimeSpan {
return new TimeSpan(toDate.momentDate.diff(this.momentDate));
}
Format(formatting: string): string {
return this.momentDate.format(formatting);
}
private static getKindfromMoment(m: moment.Moment): DateTimeKind {
if (m.isUTC()) {
return DateTimeKind.Utc;
}
if (m.isLocal()) {
return DateTimeKind.Local;
}
return DateTimeKind.Unspecified;
}
static Parse(value: any, kind: DateTimeKind = DateTimeKind.Unspecified): DateTime {
let mdate = moment(value);
let tempDate: DateTime = null;
if (mdate.isValid()) {
switch (kind) {
case DateTimeKind.Local:
tempDate = new DateTime(mdate.local());
tempDate.kind = kind;
return tempDate;
case DateTimeKind.Utc:
tempDate = new DateTime(moment.utc(value));
tempDate.kind = kind;
return tempDate;
default:
tempDate = new DateTime(mdate);
tempDate.originalDateInput = value;
tempDate.kind = kind;
return tempDate;
}
}
else {
throw new ArgumentException("invalid date value");
}
}
ToISOString(): string {
return this.momentDate.toISOString();
}
toString(): string {
return this.momentDate.toString();
}
utcOffset(value: number) {
this.momentDate.utcOffset(value);
}
static DateimeStringToTimeZone(dtStr: string, zoneStr: string): DateTime {
return new DateTime(moment.tz(dtStr, zoneStr));
}
static DateTimeToXSDateTime(dateTime: DateTime): string {
var format = 'YYYY-MM-DDTHH:mm:ss.SSSZ';//using moment format for c#->"yyyy-MM-ddTHH:mm:ss.fff";
// switch (dateTime.Kind) {
// case DateTimeKind.Utc:
// format += "Z";
// break;
// case DateTimeKind.Local:
// format += "zzz";
// break;
// default:
// break;
// }
// Depending on the current culture, DateTime formatter will replace ':' with
// the DateTimeFormatInfo.TimeSeparator property which may not be ':'. Force the proper string
// to be used by using the InvariantCulture.
return dateTime.Format(format);//, CultureInfo.InvariantCulture);
}
static DateTimeToXSDate(date: DateTime): string {
var format = 'YYYY-MM-DDZ';//using moment format for c#->"yyyy-MM-dd";
// switch (date.Kind) {
// case DateTimeKind.Utc:
// format = "yyyy-MM-ddZ";
// break;
// case DateTimeKind.Unspecified:
// format = "yyyy-MM-dd";
// break;
// default: // DateTimeKind.Local is remaining
// format = "yyyy-MM-ddzzz";
// break;
// }
// Depending on the current culture, DateTime formatter will
// translate dates from one culture to another (e.g. Gregorian to Lunar). The server
// however, considers all dates to be in Gregorian, so using the InvariantCulture will
// ensure this.
return date.Format(format);//, CultureInfo.InvariantCulture);
}
static MinValue: DateTime = new DateTime('0001-01-01T00:00:00+00:00');
static MaxValue: DateTime = new DateTime("9999-12-31T23:59:59.9999999+00:00");
/* c# DateTime properties */
public get Date(): DateTime {
if (this === DateTime.MaxValue || this === DateTime.MinValue) {
return new DateTime(this.momentDate.utc().format("YYYY-MM-DD"))
}
return new DateTime(this.momentDate.format("YYYY-MM-DD"));
}
public get Day(): number {
return this.momentDate.date();
}
public get DayOfWeek(): DayOfWeek {
return this.momentDate.day();
}
public get DayOfYear(): number {
return this.momentDate.dayOfYear();
}
public get Hour(): number {
return this.momentDate.hour();
}
public get Kind(): DateTimeKind {
return this.kind;
}
public get Millisecond(): number {
return this.momentDate.millisecond();
}
public get Minute(): number {
return this.momentDate.minute();
}
public get Month(): number {
return this.momentDate.month() + 1;
}
public get Second(): number {
return this.momentDate.second();
}
// public get Ticks(): {
// return this.
// }
public get TimeOfDay(): TimeSpan {
return TimeSpan.FromMilliseconds(this.momentDate.millisecond());
}
public get Today(): DateTime {
return new DateTime(moment(this.momentDate.format("LL"), "LL"));
}
public get Year(): number {
return this.momentDate.year();
}
/* c# DateTime Methods */
//CompareTo
public AddDays(days: number): DateTime {
return this.Add(days, unitOfTime.days);
}
public AddHours(hours: number): DateTime {
return this.Add(hours, unitOfTime.hours);
}
public AddMilliseconds(ms: number): DateTime {
return this.Add(ms, unitOfTime.ms);
}
public AddMinutes(minutes: number): DateTime {
return this.Add(minutes, unitOfTime.minutes);
}
public AddMonths(months: number): DateTime {
return this.Add(months, unitOfTime.months);
}
public AddSeconds(seconds: number): DateTime {
return this.Add(seconds, unitOfTime.seconds);
}
// public AddTicks(ticks: number): DateTime {
// return this.Add(ticks, unitOfTime.);
// }
public AddYears(years: number): DateTime {
return this.Add(years, unitOfTime.years);
}
public static DaysInMonth(year: number, month: number) {
if (month < 1 || month > 12)
throw new ArgumentOutOfRangeException("month", invalidDateTimeMessage["months"]);
// IsLeapYear checks the year argument
let days: number[] = DateTime.IsLeapYear(year) ? DateTime.DaysToMonth366 : DateTime.DaysToMonth365;
return days[month] - days[month - 1];
}
Equals(value: any | DateTime): boolean {
if (value instanceof DateTime) {
return value.TotalMilliSeconds === this.TotalMilliSeconds;
}
return false;
}
public static Equals(t1: DateTime, t2: DateTime): boolean {
return t1.TotalMilliSeconds === t2.TotalMilliSeconds;
}
// FromBinary
// FromFileTime
// FromFileTimeUtc
// FromOADate
// GetHashCode
IsDaylightSavingTime(): boolean {
return this.momentDate.isDST();
}
/**
* Checks whether a given year is a leap year. This method returns true if year is a leap year, or false if not.
* @param {number} year
*/
public static IsLeapYear(year: number): boolean {
if (year < 1 || year > 9999) {
throw new ArgumentOutOfRangeException("year", invalidDateTimeMessage["years"]);
}
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
// ParseExact
public static SpecifyKind(value: DateTime, kind: DateTimeKind) {
return new DateTime(value.TotalMilliSeconds, kind);
}
Subtract(date: DateTime): TimeSpan;
Subtract(ts: TimeSpan): DateTime;
Subtract(dateTime: DateTime | TimeSpan): DateTime | TimeSpan {
if (dateTime instanceof DateTime) {
return new TimeSpan(this.TotalMilliSeconds - dateTime.TotalMilliSeconds);
}
else {
return new DateTime(this.TotalMilliSeconds - dateTime.TotalMilliseconds);
}
}
// ToBinary
// ToFileTime
// ToFileTimeUtc
ToLocalTime(): DateTime {
return new DateTime(this.momentDate.local());
}
ToLongDateString(): string {
return this.momentDate.format("dddd, MMMM D, YYYY");
}
ToLongTimeString(): string {
return this.momentDate.format("LTS");
}
// ToOADate
ToShortDateString(): string {
return this.MomentDate.format("l");
}
ToShortTimeString(): string {
return this.MomentDate.format("LT");
}
ToString(): string {
return this.toString();
}
ToUniversalTime(): DateTime {
return new DateTime(this.MomentDate.utc());
}
static TryParse(s: string | moment.MomentInput, outDate: IOutParam<DateTime>) {
try {
outDate.outValue = DateTime.Parse(s);
outDate.outValue.kind = this.getKindfromMoment(outDate.outValue.momentDate);
return true;
} catch (error) {
outDate.exception = error;
}
return false;
}
// TryParseExact
valueOf(): number {
return this.TotalMilliSeconds;
}
}
//
// Summary:
// Defines the formatting options that customize string parsing for some date and
// time parsing methods.
export enum DateTimeStyles {
//
// Summary:
// Default formatting options must be used. This value represents the default style
// for the System.DateTime.Parse(System.String), System.DateTime.ParseExact(System.String,System.String,System.IFormatProvider),
// and System.DateTime.TryParse(System.String,System.DateTime@) methods.
None = 0,
//
// Summary:
// Leading white-space characters must be ignored during parsing, except if they
// occur in the System.Globalization.DateTimeFormatInfo format patterns.
AllowLeadingWhite = 1,
//
// Summary:
// Trailing white-space characters must be ignored during parsing, except if they
// occur in the System.Globalization.DateTimeFormatInfo format patterns.
AllowTrailingWhite = 2,
/**
* Summary:
* Extra white-space characters in the middle of the string must be ignored during
* parsing, except if they occur in the System.Globalization.DateTimeFormatInfo
* format patterns.
*/
AllowInnerWhite = 4,
/**
* Summary:
* Extra white-space characters anywhere in the string must be ignored during parsing,
* except if they occur in the System.Globalization.DateTimeFormatInfo format patterns.
* This value is a combination of the System.Globalization.DateTimeStyles.AllowLeadingWhite,
* System.Globalization.DateTimeStyles.AllowTrailingWhite, and System.Globalization.DateTimeStyles.AllowInnerWhite
* values.
*/
AllowWhiteSpaces = 7,
//
// Summary:
// If the parsed string contains only the time and not the date, the parsing methods
// assume the Gregorian date with year = 1, month = 1, and day = 1. If this value
// is not used, the current date is assumed.
NoCurrentDateDefault = 8,
//
// Summary:
// Date and time are returned as a Coordinated Universal Time (UTC). If the input
// string denotes a local time, through a time zone specifier or System.Globalization.DateTimeStyles.AssumeLocal,
// the date and time are converted from the local time to UTC. If the input string
// denotes a UTC time, through a time zone specifier or System.Globalization.DateTimeStyles.AssumeUniversal,
// no conversion occurs. If the input string does not denote a local or UTC time,
// no conversion occurs and the resulting System.DateTime.Kind property is System.DateTimeKind.Unspecified.
AdjustToUniversal = 16,
//
// Summary:
// If no time zone is specified in the parsed string, the string is assumed to denote
// a local time.
AssumeLocal = 32,
//
// Summary:
// If no time zone is specified in the parsed string, the string is assumed to denote
// a UTC.
AssumeUniversal = 64,
//
// Summary:
// The System.DateTimeKind field of a date is preserved when a System.DateTime object
// is converted to a string using the "o" or "r" standard format specifier, and
// the string is then converted back to a System.DateTime object.
RoundtripKind = 128
}
export var unitOfTime = {
"year": <moment.unitOfTime.Base>"year",
"years": <moment.unitOfTime.Base>"years",
"y": <moment.unitOfTime.Base>"y",
"month": <moment.unitOfTime.Base>"month",
"months": <moment.unitOfTime.Base>"months",
"M": <moment.unitOfTime.Base>"M",
"week": <moment.unitOfTime.Base>"week",
"weeks": <moment.unitOfTime.Base>"weeks",
"w": <moment.unitOfTime.Base>"w",
"day": <moment.unitOfTime.Base>"day",
"days": <moment.unitOfTime.Base>"days",
"d": <moment.unitOfTime.Base>"d",
"hour": <moment.unitOfTime.Base>"hour",
"hours": <moment.unitOfTime.Base>"hours",
"h": <moment.unitOfTime.Base>"h",
"minute": <moment.unitOfTime.Base>"minute",
"minutes": <moment.unitOfTime.Base>"minutes",
"m": <moment.unitOfTime.Base>"m",
"second": <moment.unitOfTime.Base>"second",
"seconds": <moment.unitOfTime.Base>"seconds",
"s": <moment.unitOfTime.Base>"s",
"millisecond": <moment.unitOfTime.Base>"millisecond",
"milliseconds": <moment.unitOfTime.Base>"milliseconds",
"ms": <moment.unitOfTime.Base>"ms",
}
enum momentValidity {
years,
months,
days,
hours,
minutes,
seconds,
milliseconds,
} | the_stack |
import Ticker from './Ticker';
import Scene from './Scene';
import type { SystemConstructor } from '../core/System';
import System from '../core/System';
import Component from '../core/Component';
import { setSystemObserver, initObserver } from '../core/observer';
import EventEmitter from 'eventemitter3';
/** eva plugin struct */
export interface PluginStruct {
Components?: typeof Component[];
Systems?: typeof System[];
}
interface GameParams {
/** isn't game will auto start */
autoStart?: boolean;
/** fps for this game */
frameRate?: number;
/** systems in this game */
systems?: System[];
/** whether or not need to create scene */
needScene?: boolean;
}
export enum LOAD_SCENE_MODE {
SINGLE = 'SINGLE',
MULTI_CANVAS = 'MULTI_CANVAS',
}
interface LoadSceneParams {
scene: Scene;
mode?: LOAD_SCENE_MODE;
params?: {
width?: number;
height?: number;
canvas?: HTMLCanvasElement
renderType?: number
autoStart?: boolean;
sharedTicker?: boolean;
sharedLoader?: boolean;
transparent?: boolean;
antialias?: boolean;
preserveDrawingBuffer?: boolean;
resolution?: number;
backgroundColor?: number;
clearBeforeRender?: boolean;
roundPixels?: boolean;
forceFXAA?: boolean;
legacy?: boolean;
autoResize?: boolean;
powerPreference?: "high-performance";
};
}
const triggerStart = (obj: System | Component) => {
if (!(obj instanceof System) && !(obj instanceof Component)) return;
if (obj.started) return;
obj.started = true;
try {
obj.start && obj.start();
} catch (e) {
if (obj instanceof Component) {
// @ts-ignore
console.error(`${obj.constructor.componentName} start error`, e);
} else {
// @ts-ignore
console.error(`${obj.constructor.systemName} start error`, e);
}
}
};
const getAllGameObjects = game => {
const mainSceneGameObjects = game?.scene?.gameObjects || [];
const gameObjectsArray = game?.multiScenes.map(({ gameObjects }) => gameObjects);
let otherSceneGameObjects = [];
for (const gameObjects of gameObjectsArray) {
otherSceneGameObjects = [...otherSceneGameObjects, ...gameObjects];
}
return [...mainSceneGameObjects, ...otherSceneGameObjects];
};
const gameObjectLoop = (e, gameObjects = []) => {
for (const gameObject of gameObjects) {
for (const component of gameObject.components) {
try {
triggerStart(component);
component.update && component.update(e);
} catch (e) {
console.error(`gameObject: ${gameObject.name} ${component.name} update error`, e);
}
}
}
for (const gameObject of gameObjects) {
for (const component of gameObject.components) {
try {
component.lateUpdate && component.lateUpdate(e);
} catch (e) {
console.error(`gameObject: ${gameObject.name} ${component.name} lateUpdate error`, e);
}
}
}
};
const gameObjectResume = gameObjects => {
for (const gameObject of gameObjects) {
for (const component of gameObject.components) {
try {
component.onResume && component.onResume();
} catch (e) {
console.error(`gameObject: ${gameObject.name}, ${component.name}, onResume error`, e);
}
}
}
};
const gameObjectPause = gameObjects => {
for (const gameObject of gameObjects) {
for (const component of gameObject.components) {
try {
component.onPause && component.onPause();
} catch (e) {
console.error(`gameObject: ${gameObject.name}, ${component.name}, onResume error`, e);
}
}
}
};
class Game extends EventEmitter {
_scene: Scene;
canvas: HTMLCanvasElement;
/**
* State of game
* @defaultValue false
*/
playing: boolean = false;
started: boolean = false;
multiScenes: Scene[] = [];
/**
* Ticker
*/
ticker: Ticker;
/** Systems alled to this game */
systems: System[] = [];
constructor({ systems, frameRate = 60, autoStart = true, needScene = true }: GameParams = {}) {
super();
if (window.__EVA_INSPECTOR_ENV__) {
window.__EVA_GAME_INSTANCE__ = this;
}
this.ticker = new Ticker({ autoStart: false, frameRate });
this.initTicker();
if (systems && systems.length) {
for (const system of systems) {
this.addSystem(system);
}
}
if (needScene) {
this.loadScene(new Scene('scene'));
}
if (autoStart) {
this.start();
}
}
/**
* Get scene on this game
*/
get scene() {
return this._scene;
}
set scene(scene: Scene) {
this._scene = scene;
}
get gameObjects() {
return getAllGameObjects(this);
}
addSystem<T extends System>(S: T): T;
addSystem<T extends System>(S: SystemConstructor<T>, obj?: ConstructorParameters<SystemConstructor<T>>): T;
/**
* Add system
* @param S - system instance or system Class
* @typeParam T - system which extends base `System` class
* @typeparam U - type of system class
*/
addSystem<T extends System>(S: T | SystemConstructor<T>, obj?: ConstructorParameters<SystemConstructor<T>>): T {
let system;
if (S instanceof Function) {
system = new S(obj);
} else if (S instanceof System) {
system = S;
} else {
console.warn('can only add System');
return;
}
const hasTheSystem = this.systems.find(item => {
return item.constructor === system.constructor;
});
if (hasTheSystem) {
console.warn(`${system.constructor.systemName} System has been added`);
return;
}
system.game = this;
system.init && system.init(system.__systemDefaultParams);
setSystemObserver(system, system.constructor);
initObserver(system.constructor);
try {
system.awake && system.awake();
} catch (e) {
// @ts-ignore
console.error(`${system.constructor.systemName} awake error`, e);
}
this.systems.push(system);
return system;
}
/**
* Remove system from this game
* @param system - one of system instance / system Class or system name
*/
removeSystem<S extends System>(system: S | SystemConstructor<S> | string) {
if (!system) return;
let index = -1;
if (typeof system === 'string') {
index = this.systems.findIndex(s => s.name === system);
} else if (system instanceof Function) {
index = this.systems.findIndex(s => s.constructor === system);
} else if (system instanceof System) {
index = this.systems.findIndex(s => s === system);
}
if (index > -1) {
this.systems[index].destroy && this.systems[index].destroy();
this.systems.splice(index, 1);
}
}
/**
* Get system
* @param S - system class or system name
* @returns system instance
*/
getSystem<T extends System>(S: SystemConstructor<T> | string): T {
return this.systems.find(system => {
if (typeof S === 'string') {
return system.name === S;
} else {
return system instanceof S;
}
}) as T;
}
/** Pause game */
pause() {
if (!this.playing) return;
this.playing = false;
this.ticker.pause();
this.triggerPause();
}
/** Start game */
start() {
if (this.playing) return;
this.playing = true;
this.started = true;
this.ticker.start();
}
/** Resume game */
resume() {
if (this.playing) return;
this.playing = true;
this.ticker.start();
this.triggerResume();
}
/**
* add main render method to ticker
* @remarks
* the method added to ticker will called in each requestAnimationFrame,
* 1. call update method on all gameObject
* 2. call lastUpdate method on all gameObject
* 3. call update method on all system
* 4. call lastUpdate method on all system
*/
initTicker() {
this.ticker.add(e => {
this.scene && gameObjectLoop(e, this.gameObjects);
for (const system of this.systems) {
try {
triggerStart(system);
system.update && system.update(e);
} catch (e) {
// @ts-ignore
console.error(`${system.constructor.systemName} update error`, e);
}
}
for (const system of this.systems) {
try {
system.lateUpdate && system.lateUpdate(e);
} catch (e) {
// @ts-ignore
console.error(`${system.constructor.systemName} lateUpdate error`, e);
}
}
});
}
/** Call onResume method on all gameObject's, and then call onResume method on all system */
triggerResume() {
gameObjectResume(this.gameObjects);
for (const system of this.systems) {
try {
system.onResume && system.onResume();
} catch (e) {
// @ts-ignore
console.error(`${system.constructor.systemName}, onResume error`, e);
}
}
}
/** Call onPause method on all gameObject */
triggerPause() {
gameObjectPause(this.gameObjects);
for (const system of this.systems) {
try {
system.onPause && system.onPause();
} catch (e) {
// @ts-ignore
console.error(`${system.constructor.systemName}, onPause error`, e);
}
}
}
// TODO: call system destroy method
/** remove all system on this game */
destroySystems() {
for (const system of [...this.systems]) {
this.removeSystem(system);
}
this.systems.length = 0;
}
/** Destroy game instance */
destroy() {
this.removeAllListeners();
this.pause();
this.scene.destroy();
this.destroySystems();
this.ticker = null;
this.scene = null;
this.canvas = null;
this.multiScenes = null;
}
loadScene({ scene, mode = LOAD_SCENE_MODE.SINGLE, params = {} }: LoadSceneParams) {
if (!scene) {
return;
}
switch (mode) {
case LOAD_SCENE_MODE.SINGLE:
this.scene = scene;
break;
case LOAD_SCENE_MODE.MULTI_CANVAS:
this.multiScenes.push(scene);
break;
}
this.emit('sceneChanged', { scene, mode, params });
}
}
export default Game; | the_stack |
import { createElement } from '@syncfusion/ej2-base';
import { Diagram } from '../../../src/diagram/diagram';
import { Path } from '../../../src/diagram/objects/node';
import { ShapeAnnotationModel } from '../../../src/diagram/objects/annotation-model';
import { NodeModel, PathModel, } from '../../../src/diagram/objects/node-model';
import { NodeConstraints, AnnotationConstraints } from '../../../src/diagram/enum/enum';
import { MouseEvents } from '../../../spec/diagram/interaction/mouseevents.spec';
import {profile , inMB, getMemoryProfile} from '../../../spec/common.spec';
describe('Diagram Control', () => {
describe('Annotation property change', () => {
let diagram: Diagram;
let ele: HTMLElement;
beforeAll((): void => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
ele = createElement('div', { id: 'diagram' });
document.body.appendChild(ele);
let node: NodeModel = {
id: 'nodeannot', width: 80, height: 100, offsetX: 140, offsetY: 80, shape: {
type: 'Path',
data: 'M127.2842,291.4492L95.0322,291.4492L81.1582,256.3152L141.1582,256.3152L127.2842,291.4492z'
} as PathModel,
annotations: [{
visibility: false,
content: 'text1', id: 'text1', offset: { x: 0, y: 0 }, width: 40, height: 30,
} as ShapeAnnotationModel]
};
let node1: NodeModel = {
id: 'node', width: 100, height: 100, offsetX: 100, offsetY: 200,
shape: {
type: 'Path',
data: 'M127.2842,291.4492L95.0322,291.4492L81.1582,256.3152L141.1582,256.3152L127.2842,291.4492z'
} as PathModel,
annotations: [{
content: 'text1', id: 'text1', width: 80, height: 100, offset: { x: 0, y: 0 }
} as ShapeAnnotationModel]
};
let node2: NodeModel = {
id: 'node1annot', width: 100, height: 100, offsetX: 340, offsetY: 80,
shape: {
type: 'Path',
data: 'M127.2842,291.4492L95.0322,291.4492L81.1582,256.3152L141.1582,256.3152L127.2842,291.4492z'
} as PathModel,
annotations: [{
content: 'text1', id: 'text1', offset: { x: 0, y: 0 }, width: 80, height: 80,
} as ShapeAnnotationModel]
};
let node3: NodeModel = {
id: 'node1', width: 100, height: 100, offsetX: 300, offsetY: 200,
shape: {
type: 'Path',
data: 'M127.2842,291.4492L95.0322,291.4492L81.1582,256.3152L141.1582,256.3152L127.2842,291.4492z'
} as PathModel,
annotations: [{
content: 'text1', id: 'text1', offset: { x: 0, y: 0 }, width: 80, height: 80,
} as ShapeAnnotationModel]
};
let node4: NodeModel = {
id: 'node11', width: 100, height: 100, offsetX: 500, offsetY: 100,
constraints: NodeConstraints.Default | NodeConstraints.ReadOnly,
annotations: [{
id: 'label1',
content: 'Default Shape1', style: { color: 'red' },
constraints: ~AnnotationConstraints.InheritReadOnly
},
{
id: 'label11',
content: 'Default Shape2', style: { color: 'red' }, offset: { y: 1 }
}]
};
diagram = new Diagram({
width: 800, height: 400, nodes: [node, node1, node2, node3, node4]
});
diagram.appendTo('#diagram');
});
afterAll((): void => {
diagram.destroy();
ele.remove();
});
it('Checking annotation width and height change', (done: Function) => {
(diagram.nodes[0] as NodeModel).annotations[0].width = 100;
(diagram.nodes[0] as NodeModel).annotations[0].height = 60;
diagram.dataBind();
let label: ShapeAnnotationModel = (diagram.nodes[0] as NodeModel).annotations[0];
expect(label.visibility == false).toBe(true);
(diagram.nodes[0] as NodeModel).annotations[0].visibility = true,
diagram.dataBind();
expect(label.width == 100 && label.height == 60 && label.visibility == true).toBe(true);
done();
});
it('Checking annotation content change', (done: Function) => {
(diagram.nodes[1] as NodeModel).annotations[0].content = 'changed text';
diagram.dataBind();
let label: ShapeAnnotationModel = (diagram.nodes[1] as NodeModel).annotations[0];
expect(label.content == 'changed text').toBe(true);
done();
});
it('Checking annotation Alignment change', (done: Function) => {
(diagram.nodes[2] as NodeModel).annotations[0].horizontalAlignment = 'Right';
(diagram.nodes[2] as NodeModel).annotations[0].verticalAlignment = 'Bottom';
diagram.dataBind();
let label: ShapeAnnotationModel = (diagram.nodes[2] as NodeModel).annotations[0];
expect((label.horizontalAlignment == 'Right') && (label.verticalAlignment == 'Bottom')).toBe(true);
done();
});
it('Checking annotation offset change', (done: Function) => {
(diagram.nodes[1] as NodeModel).annotations[0].offset.x = 1;
(diagram.nodes[1] as NodeModel).annotations[0].offset.y = 1;
diagram.dataBind();
let label: ShapeAnnotationModel = (diagram.nodes[1] as NodeModel).annotations[0];
expect((label.offset.x == 1) && (label.offset.y == 1)).toBe(true);
done();
});
it('Checking annotation style change', (done: Function) => {
(diagram.nodes[3] as NodeModel).annotations[0].style.opacity = 4;
(diagram.nodes[3] as NodeModel).annotations[0].style.strokeColor = 'blue';
(diagram.nodes[3] as NodeModel).annotations[0].style.strokeWidth = 3;
(diagram.nodes[3] as NodeModel).annotations[0].style.strokeDashArray = '5,5';
(diagram.nodes[3] as NodeModel).annotations[0].style.bold = false;
(diagram.nodes[3] as NodeModel).annotations[0].style.fontSize = 25;
(diagram.nodes[3] as NodeModel).annotations[0].style.color = 'red';
(diagram.nodes[3] as NodeModel).annotations[0].style.fill = 'white';
(diagram.nodes[3] as NodeModel).annotations[0].style.italic = true;
(diagram.nodes[3] as NodeModel).annotations[0].style.fontFamily = 'Fantasy';
(diagram.nodes[3] as NodeModel).annotations[0].style.whiteSpace = 'CollapseSpace';
(diagram.nodes[3] as NodeModel).annotations[0].style.textWrapping = 'WrapWithOverflow';
(diagram.nodes[3] as NodeModel).annotations[0].style.textAlign = 'Left';
(diagram.nodes[3] as NodeModel).annotations[0].style.textDecoration = 'Overline';
diagram.dataBind();
let label: ShapeAnnotationModel = (diagram.nodes[3] as NodeModel).annotations[0];
expect((label.style.textWrapping == 'WrapWithOverflow') && (label.style.fontSize == 25)).toBe(true);
done();
});
it('Checking annotation margin change', (done: Function) => {
(diagram.nodes[0] as NodeModel).annotations[0].margin.top = 20;
(diagram.nodes[0] as NodeModel).annotations[0].margin.left = 25;
(diagram.nodes[0] as NodeModel).annotations[0].margin.right = 20;
(diagram.nodes[0] as NodeModel).annotations[0].margin.bottom = 25;
diagram.dataBind();
let label: ShapeAnnotationModel = (diagram.nodes[0] as NodeModel).annotations[0];
expect((label.margin.top == 20) && (label.margin.left == 25)).toBe(true);
done();
});
it('Checking without label', (done: Function) => {
let mouseEvents: MouseEvents = new MouseEvents();
let diagramCanvas: HTMLElement = document.getElementById(diagram.element.id + 'content');
mouseEvents.clickEvent(diagramCanvas, 500, 108);
mouseEvents.dblclickEvent(diagramCanvas, 500, 108);
let element = document.getElementById('diagram_editTextBoxDiv');
mouseEvents.clickEvent(diagramCanvas, 500, 158);
mouseEvents.dblclickEvent(diagramCanvas, 500, 158);
let element1 = document.getElementById('diagram_editTextBoxDiv');
(diagram.nodes[4] as NodeModel).annotations[0].constraints = AnnotationConstraints.InheritReadOnly;
diagram.dataBind();
mouseEvents.clickEvent(diagramCanvas, 500, 108);
mouseEvents.dblclickEvent(diagramCanvas, 500, 108);
(diagram.nodes[4] as NodeModel).constraints = NodeConstraints.Default;
(diagram.nodes[4] as NodeModel).annotations[0].constraints = AnnotationConstraints.ReadOnly;
diagram.dataBind();
mouseEvents.clickEvent(diagramCanvas, 500, 108);
mouseEvents.dblclickEvent(diagramCanvas, 500, 108);
expect(element && !element1).toBe(true);
done();
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange)
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile())
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
})
});
}); | the_stack |
import { createTreeWithEmptyWorkspace } from '@nrwl/devkit/testing';
import {
Tree,
readProjectConfiguration,
readWorkspaceConfiguration,
stripIndents,
addProjectConfiguration,
serializeJson,
WorkspaceConfiguration,
parseJson,
getProjects,
joinPathFragments,
ProjectConfiguration,
readJson,
updateJson,
NxJsonConfiguration,
} from '@nrwl/devkit';
import generator from './index';
import { MovePackagesGeneratorSchema } from './schema';
import { TsConfig } from '../../types';
import { setupCodeowners } from '../../utils-testing';
type ReadProjectConfiguration = ReturnType<typeof readProjectConfiguration>;
const noop = () => null;
describe('move-packages generator', () => {
let tree: Tree;
const options = {
name: '@proj/test',
destination: 'testFolder/test',
updateImportPath: false,
} as const;
beforeEach(() => {
jest.restoreAllMocks();
jest.spyOn(console, 'log').mockImplementation(noop);
tree = createTreeWithEmptyWorkspace();
setupCodeowners(tree, { content: `packages/test @dummyOwner` });
updateJson(tree, '/nx.json', (json: NxJsonConfiguration) => {
json.workspaceLayout = {
appsDir: 'apps',
libsDir: 'packages',
};
return json;
});
tree = setupDummyPackage(tree, {
...options,
name: options.name,
version: '9.0.0-alpha.0',
dependencies: {
'@proj/make-styles': '^9.0.0-alpha.1',
},
tsConfig: { extends: '../../tsconfig.base.json', compilerOptions: {}, include: ['src'] },
projectConfiguration: { tags: ['vNext', 'platform:node'], sourceRoot: 'packages/test' },
});
});
describe('general', () => {
it('should run successfully', async () => {
await generator(tree, options);
const config = readProjectConfiguration(tree, options.name);
expect(config).toBeDefined();
});
describe('schema validation', () => {
it('should throw if --name && --allConverged are both specified', async () => {
await expect(
generator(tree, {
...options,
allConverged: true,
}),
).rejects.toMatchInlineSnapshot(`[Error: --name and --allConverged are mutually exclusive]`);
});
it('should throw if --allConverged && --allV8 are both specified', async () => {
await expect(
generator(tree, {
...options,
allConverged: true,
allV8: true,
name: '',
}),
).rejects.toMatchInlineSnapshot(`[Error: --allConverged and --allV8 are mutually exclusive]`);
});
it('should throw if --name && --allConverged && --allV8 are all NOT specified', async () => {
await expect(
generator(tree, {
...options,
name: '',
}),
).rejects.toMatchInlineSnapshot(
`[Error: must provide a specified --name or provide --allConverged or provide --allV8]`,
);
});
});
});
describe('package move updates', () => {
it('should move files to correct destination', async () => {
await generator(tree, options);
expect(tree.exists(`packages/${options.destination}/src/index.ts`)).toBeTruthy();
expect(tree.exists(`packages/${options.destination}/src/index.ts`)).toBeTruthy();
expect(tree.exists(`packages/${options.destination}/src/index.test.ts`)).toBeTruthy();
expect(tree.exists(`packages/${options.destination}/package.json`)).toBeTruthy();
expect(tree.exists(`packages/${options.destination}/tsconfig.json`)).toBeTruthy();
expect(tree.exists(`packages/${options.destination}/.babelrc.json`)).toBeTruthy();
expect(tree.exists(`packages/${options.destination}/config/tests.js`)).toBeTruthy();
});
it('should delete files from the old location', async () => {
await generator(tree, options);
expect(tree.exists(`packages/${options.name}/src/index.ts`)).toBeFalsy();
expect(tree.exists(`packages/${options.name}/src/index.test.ts`)).toBeFalsy();
expect(tree.exists(`packages/${options.name}/package.json`)).toBeFalsy();
expect(tree.exists(`packages/${options.name}/tsconfig.json`)).toBeFalsy();
expect(tree.exists(`packages/${options.name}/.babelrc.json`)).toBeFalsy();
expect(tree.exists(`packages/${options.name}/config/tests.js`)).toBeFalsy();
});
it('should update storybook main.js module.exports type to the new relative path', async () => {
const newPath = '../../../../.storybook/main';
let project = getProjects(tree).get(options.name) as ProjectConfiguration;
let storybookMainJsPath = joinPathFragments(project.root, '/.storybook/main.js');
let storybookMainJsFile = tree.read(storybookMainJsPath, 'utf8') as string;
expect(storybookMainJsFile.indexOf(newPath) !== -1).toBeFalsy();
await generator(tree, options);
project = getProjects(tree).get(options.name) as ProjectConfiguration;
storybookMainJsPath = joinPathFragments(project.root, '/.storybook/main.js');
storybookMainJsFile = tree.read(storybookMainJsPath, 'utf8') as string;
expect(storybookMainJsFile.indexOf(newPath) !== -1).toBeTruthy();
});
it('should update the CODEOWNERS file with the new relative path', async () => {
const oldOwnerDeclaration = `packages/test @dummyOwner`;
const newOwnerDeclaration = `packages/${options.destination} @dummyOwner`;
const codeOwnersPath = joinPathFragments('/.github', 'CODEOWNERS');
let codeOwnersFile = tree.read(codeOwnersPath, 'utf8') as string;
expect(codeOwnersFile.indexOf(oldOwnerDeclaration) !== -1).toBeTruthy();
await generator(tree, options);
codeOwnersFile = tree.read(codeOwnersPath, 'utf8') as string;
expect(codeOwnersFile.indexOf(oldOwnerDeclaration) !== -1).toBeFalsy();
expect(codeOwnersFile.indexOf(newOwnerDeclaration) !== -1).toBeTruthy();
});
it(`should update api-extractor.local.json`, async () => {
let project = getProjects(tree).get(options.name) as ProjectConfiguration;
let apiExtractorLocalPath = joinPathFragments(project.root, 'config/api-extractor.local.json');
let apiExtractorLocal = readJson(tree, apiExtractorLocalPath);
expect(apiExtractorLocal).toMatchInlineSnapshot(`
Object {
"$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json",
"extends": "./api-extractor.json",
"mainEntryPointFilePath": "<projectFolder>/dist/packages/<unscopedPackageName>/src/index.d.ts",
}
`);
await generator(tree, options);
project = getProjects(tree).get(options.name) as ProjectConfiguration;
apiExtractorLocalPath = joinPathFragments(project.root, 'config/api-extractor.local.json');
apiExtractorLocal = readJson(tree, apiExtractorLocalPath);
/* eslint-disable @fluentui/max-len */
expect(apiExtractorLocal).toMatchInlineSnapshot(`
Object {
"$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json",
"extends": "./api-extractor.json",
"mainEntryPointFilePath": "<projectFolder>/dist/packages/testFolder/<unscopedPackageName>/src/index.d.ts",
}
`);
/* eslint-enable @fluentui/max-len */
});
it('should update the package.json build:local script with the new relative path', async () => {
let project = getProjects(tree).get(options.name as string) as ProjectConfiguration;
let packageJsonPath = joinPathFragments(project.root, 'package.json');
let packageJson = readJson(tree, packageJsonPath);
expect(packageJson.scripts['build:local']).toEqual(
// eslint-disable-next-line @fluentui/max-len
'tsc -p ./tsconfig.lib.json --module esnext --emitDeclarationOnly && node ../../scripts/typescript/normalize-import --output ./dist/packages/test/src && yarn docs',
);
await generator(tree, options);
project = getProjects(tree).get(options.name as string) as ProjectConfiguration;
packageJsonPath = joinPathFragments(project.root, 'package.json');
packageJson = readJson(tree, packageJsonPath);
expect(packageJson.scripts['build:local']).toEqual(
// eslint-disable-next-line @fluentui/max-len
`tsc -p ./tsconfig.lib.json --module esnext --emitDeclarationOnly && node ../../../scripts/typescript/normalize-import --output ./dist/packages/${options.destination}/src && yarn docs`,
);
});
});
describe('--allConverged', () => {
beforeEach(() => {
setupDummyPackage(tree, { name: '@proj/react-foo', version: '9.0.22' });
setupDummyPackage(tree, { name: '@proj/react-bar', version: '9.0.31' });
setupDummyPackage(tree, { name: '@proj/react-moo', version: '9.0.12' });
setupDummyPackage(tree, { name: '@proj/react-old', version: '8.0.1' });
});
it(`should move all v9 packages in batch`, async () => {
const projects = [
options.name,
'@proj/react-foo',
'@proj/react-bar',
'@proj/react-moo',
'@proj/react-old',
] as const;
const destinationFolder = 'testFolder';
await generator(tree, { allConverged: true, destination: destinationFolder });
expect(tree.exists(`packages/${destinationFolder}/react-foo/src/index.ts`)).toBeTruthy();
expect(tree.exists(`packages/${destinationFolder}/react-bar/src/index.ts`)).toBeTruthy();
expect(tree.exists(`packages/${destinationFolder}/react-moo/src/index.ts`)).toBeTruthy();
expect(tree.exists(`packages/${destinationFolder}/react-old/src/index.ts`)).toBeFalsy();
});
});
describe('--allV8', () => {
beforeEach(() => {
setupDummyPackage(tree, { name: '@proj/react-foo', version: '8.0.22' });
setupDummyPackage(tree, { name: '@proj/react-bar', version: '8.0.31' });
setupDummyPackage(tree, { name: '@proj/react-moo', version: '8.0.12' });
setupDummyPackage(tree, { name: '@proj/react-old', version: '9.0.1' });
});
it(`should move all v8 packages in batch`, async () => {
const projects = [
options.name,
'@proj/react-foo',
'@proj/react-bar',
'@proj/react-moo',
'@proj/react-old',
] as const;
const destinationFolder = 'testFolder';
await generator(tree, { allV8: true, destination: destinationFolder });
expect(tree.exists(`packages/${destinationFolder}/react-foo/src/index.ts`)).toBeTruthy();
expect(tree.exists(`packages/${destinationFolder}/react-bar/src/index.ts`)).toBeTruthy();
expect(tree.exists(`packages/${destinationFolder}/react-moo/src/index.ts`)).toBeTruthy();
expect(tree.exists(`packages/${destinationFolder}/react-old/src/index.ts`)).toBeFalsy();
});
});
});
interface AssertedSchema {
name: string;
}
function setupDummyPackage(
tree: Tree,
options: AssertedSchema &
Partial<{
version: string;
dependencies: Record<string, string>;
tsConfig: TsConfig;
babelConfig: Partial<{ presets: string[]; plugins: string[] }>;
projectConfiguration: Partial<ReadProjectConfiguration>;
}>,
) {
const workspaceConfig = readWorkspaceConfiguration(tree);
const defaults = {
version: '9.0.0-alpha.40',
dependencies: {
[`@griffel/react`]: '1.0.0',
[`@${workspaceConfig.npmScope}/react-theme`]: '^9.0.0-alpha.13',
[`@${workspaceConfig.npmScope}/react-utilities`]: '^9.0.0-alpha.25',
tslib: '^2.1.0',
someThirdPartyDep: '^11.1.2',
},
babelConfig: {
presets: ['@griffel'],
plugins: ['annotate-pure-calls', '@babel/transform-react-pure-annotations'],
},
tsConfig: { compilerOptions: { baseUrl: '.', typeRoots: ['../../node_modules/@types', '../../typings'] } },
};
const normalizedOptions = { ...defaults, ...options };
const pkgName = normalizedOptions.name;
const normalizedPkgName = getNormalizedPkgName({ pkgName, workspaceConfig });
const paths = {
root: `packages/${normalizedPkgName}`,
};
const templates = {
packageJson: {
name: pkgName,
version: normalizedOptions.version,
scripts: {
build: 'just-scripts build',
clean: 'just-scripts clean',
'code-style': 'just-scripts code-style',
just: 'just-scripts',
lint: 'just-scripts lint',
start: 'just-scripts dev:storybook',
'start-test': 'just-scripts jest-watch',
test: 'just-scripts test',
'test:watch': 'just-scripts jest-watch',
'update-snapshots': 'just-scripts jest -u',
// eslint-disable-next-line @fluentui/max-len
'build:local': `tsc -p ./tsconfig.lib.json --module esnext --emitDeclarationOnly && node ../../scripts/typescript/normalize-import --output ./dist/packages/${normalizedPkgName}/src && yarn docs`,
},
dependencies: normalizedOptions.dependencies,
},
tsConfig: {
...normalizedOptions.tsConfig,
},
jestSetupFile: stripIndents`
/** Jest test setup file. */
`,
babelConfig: {
...normalizedOptions.babelConfig,
},
apiExtractorLocal: {
$schema: 'https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json',
extends: './api-extractor.json',
mainEntryPointFilePath: '<projectFolder>/dist/packages/<unscopedPackageName>/src/index.d.ts',
},
};
const tsConfigBase: TsConfig = parseJson(tree.read('tsconfig.base.json')!.toString('utf8')!);
// Add newly added dummy package to tsconfig.base.json paths.
tsConfigBase!.compilerOptions!.paths![options.name] = [`packages/${options.name}/src/index.ts`];
tree.write(`tsconfig.base.json`, serializeJson(tsConfigBase));
tree.write(`${paths.root}/package.json`, serializeJson(templates.packageJson));
tree.write(`${paths.root}/tsconfig.json`, serializeJson(templates.tsConfig));
tree.write(`${paths.root}/.babelrc.json`, serializeJson(templates.babelConfig));
tree.write(`${paths.root}/config/tests.js`, templates.jestSetupFile);
tree.write(`${paths.root}/src/index.ts`, `export const greet = 'hello' `);
tree.write(
`${paths.root}/src/index.test.ts`,
`
import {greet} from './index';
describe('test me', () => {
it('should greet', () => {
expect(greet).toBe('hello');
});
});
`,
);
tree.write(
`${paths.root}/.storybook/main.js`,
`const rootMain = require('../../../.storybook/main');
module.exports = /** @type {Omit<import('../../../.storybook/main'), 'typescript'|'babel'>} */ ({
...rootMain,
stories: [...rootMain.stories, '../src/**/*.stories.mdx', '../src/**/*.stories.@(ts|tsx)'],
addons: [...rootMain.addons],
webpackFinal: (config, options) => {
const localConfig = { ...rootMain.webpackFinal(config, options) };
// add your own webpack tweaks if needed
return localConfig;
},
});
`,
);
tree.write(`${paths.root}/config/api-extractor.local.json`, serializeJson(templates.apiExtractorLocal));
addProjectConfiguration(tree, pkgName, {
root: paths.root,
projectType: 'library',
targets: {},
...options.projectConfiguration,
});
return tree;
}
function getNormalizedPkgName(options: { pkgName: string; workspaceConfig: WorkspaceConfiguration }) {
return options.pkgName.replace(`@${options.workspaceConfig.npmScope}/`, '');
} | the_stack |
import React from 'react';
import {Schema} from '../types';
import Transition, {ENTERED, ENTERING} from 'react-transition-group/Transition';
import {themeable, ThemeProps} from '../theme';
import {uncontrollable} from 'uncontrollable';
import {generateIcon} from '../utils/icon';
import {SchemaClassName} from '../Schema';
import {autobind} from '../utils/helper';
import debounce from 'lodash/debounce';
const transitionStyles: {
[propName: string]: string;
} = {
[ENTERING]: 'in',
[ENTERED]: 'in'
};
export interface TabProps extends ThemeProps {
title?: string | React.ReactNode; // 标题
icon?: string;
iconPosition?: 'left' | 'right';
disabled?: boolean | string;
eventKey: string | number;
tab?: Schema;
className?: string;
activeKey?: string | number;
reload?: boolean;
mountOnEnter?: boolean;
unmountOnExit?: boolean;
toolbar?: React.ReactNode;
}
class TabComponent extends React.PureComponent<TabProps> {
contentDom: any;
contentRef = (ref: any) => (this.contentDom = ref);
render() {
const {
classnames: cx,
mountOnEnter,
reload,
unmountOnExit,
eventKey,
activeKey,
children,
className
} = this.props;
return (
<Transition
in={activeKey === eventKey}
mountOnEnter={mountOnEnter}
unmountOnExit={typeof reload === 'boolean' ? reload : unmountOnExit}
timeout={500}
>
{(status: string) => {
if (status === ENTERING) {
this.contentDom.offsetWidth;
}
return (
<div
ref={this.contentRef}
className={cx(
transitionStyles[status],
activeKey === eventKey ? 'is-active' : '',
'Tabs-pane',
className
)}
>
{children}
</div>
);
}}
</Transition>
);
}
}
export const Tab = themeable(TabComponent);
export interface TabsProps extends ThemeProps {
mode: '' | 'line' | 'card' | 'radio' | 'vertical' | 'chrome';
tabsMode?: '' | 'line' | 'card' | 'radio' | 'vertical' | 'chrome';
additionBtns?: React.ReactNode;
onSelect?: (key: string | number) => void;
activeKey?: string | number;
contentClassName: string;
linksClassName?: SchemaClassName;
className?: string;
tabs?: Array<TabProps>;
tabRender?: (tab: TabProps, props?: TabsProps) => JSX.Element;
toolbar?: React.ReactNode;
scrollable?: boolean // 是否支持溢出滚动
}
export class Tabs extends React.Component<TabsProps, any> {
static defaultProps: Pick<TabsProps, 'mode' | 'contentClassName'> = {
mode: '',
contentClassName: ''
};
static Tab = Tab;
navMain = React.createRef<HTMLDivElement>();
scroll:boolean = false;
checkArrowStatus = debounce(
() => {
const {scrollLeft, scrollWidth, clientWidth} = this.navMain.current
|| {
scrollLeft: 0,
scrollWidth: 0,
clientWidth: 0
}
const {arrowRightDisabled, arrowLeftDisabled} = this.state;
if (scrollLeft === 0 && !arrowLeftDisabled) {
this.setState({
arrowRightDisabled: false,
arrowLeftDisabled: true
});
} else if (scrollWidth === scrollLeft + clientWidth && !arrowRightDisabled) {
this.setState({
arrowRightDisabled: true,
arrowLeftDisabled: false
});
} else if (scrollLeft !== 0 && arrowLeftDisabled) {
this.setState({
arrowLeftDisabled: false
});
} else if (scrollWidth !== scrollLeft + clientWidth && arrowRightDisabled) {
this.setState({
arrowRightDisabled: false
});
}
},
100,
{
trailing: true,
leading: false
}
)
constructor(props: TabsProps) {
super(props);
this.state = {
isOverflow: false,
arrowLeftDisabled: false,
arrowRightDisabled: false,
};
}
componentDidMount() {
this.computedWidth();
if (this.navMain) {
this.navMain.current?.addEventListener('wheel', this.handleWheel, {passive: false});
this.checkArrowStatus();
}
}
componentDidUpdate() {
// 判断是否是由滚动触发的数据更新,如果是则不需要再次判断容器与内容的关系
if (!this.scroll) {
this.computedWidth();
}
this.scroll = false;
}
componentWillUnmount() {
this.checkArrowStatus.cancel();
}
/**
* 处理内容与容器之间的位置关系
*/
computedWidth() {
const {mode: dMode, tabsMode, scrollable} = this.props;
const mode = tabsMode || dMode;
if (!scrollable || mode === 'vertical') {
return;
}
const navMainRef = this.navMain.current;
const clientWidth: number = navMainRef?.clientWidth || 0;
const scrollWidth: number = navMainRef?.scrollWidth || 0;
const isOverflow = scrollWidth > clientWidth;
// 内容超出容器长度标记溢出
if (isOverflow !== this.state.isOverflow) {
this.setState({isOverflow});
}
if (isOverflow) {
this.showSelected();
}
}
/**
* 保证选中的tab始终显示在可视区域
*/
showSelected(key?: string | number) {
const {mode: dMode, tabsMode, scrollable} = this.props;
const {isOverflow} = this.state;
const mode = tabsMode || dMode;
if (!scrollable || mode === 'vertical' || !isOverflow) {
return;
}
const {activeKey, children} = this.props;
const currentKey = key !== undefined ? key : activeKey;
const currentIndex = (children as any[])?.findIndex((item: any) => item.props.eventKey === currentKey);
const li = this.navMain.current?.children[0]?.children || [];
const currentLi = li[currentIndex] as HTMLElement;
const liOffsetLeft = currentLi?.offsetLeft - 20;
const liClientWidth = currentLi?.clientWidth;
const scrollLeft = this.navMain.current?.scrollLeft || 0;
const clientWidth = this.navMain.current?.clientWidth || 0;
// 左边被遮住了
if (scrollLeft > liOffsetLeft) {
this.navMain.current?.scrollTo({
left: liOffsetLeft,
behavior: 'smooth'
});
}
// 右边被遮住了
if (liOffsetLeft + liClientWidth > scrollLeft + clientWidth) {
this.navMain.current?.scrollTo({
left: liOffsetLeft + liClientWidth - clientWidth,
behavior: 'smooth'
});
}
}
handleSelect(key: string | number) {
const {onSelect} = this.props;
this.showSelected(key);
setTimeout(() => {
this.checkArrowStatus();
}, 500);
onSelect && onSelect(key);
}
handleArrow(type: 'left' | 'right') {
const {scrollLeft, scrollWidth, clientWidth} = this.navMain.current
|| {
scrollLeft: 0,
scrollWidth: 0,
clientWidth: 0
}
if (type === 'left' && scrollLeft > 0) {
this.navMain.current?.scrollTo({
left: 0,
behavior: 'smooth'
});
this.setState({
arrowRightDisabled: false,
arrowLeftDisabled: true
});
} else if (type === 'right' && scrollWidth > scrollLeft + clientWidth) {
this.navMain.current?.scrollTo({
left: this.navMain.current?.scrollWidth,
behavior: 'smooth'
});
this.setState({
arrowRightDisabled: true,
arrowLeftDisabled: false
});
}
this.scroll = true;
}
/**
* 监听导航上的滚动事件
*/
@autobind
handleWheel(e: WheelEvent) {
const {deltaY, deltaX} = e;
const absX = Math.abs(deltaX);
const absY = Math.abs(deltaY);
// 当鼠标上下滚动时转换为左右滚动
if (absY > absX) {
this.navMain.current?.scrollTo({
left: this.navMain.current?.scrollLeft + deltaY
});
e.preventDefault();
}
this.checkArrowStatus();
this.scroll = true;
}
renderNav(child: any, index: number) {
if (!child) {
return;
}
const {classnames: cx, activeKey: activeKeyProp, mode} = this.props;
const {
eventKey,
disabled,
icon,
iconPosition,
title,
toolbar,
tabClassName
} = child.props;
const activeKey =
activeKeyProp === undefined && index === 0 ? eventKey : activeKeyProp;
const iconElement = generateIcon(cx, icon, 'Icon');
return (
<li
className={cx(
'Tabs-link',
activeKey === eventKey ? 'is-active' : '',
disabled ? 'is-disabled' : '',
tabClassName
)}
key={eventKey ?? index}
onClick={() => (disabled ? '' : this.handleSelect(eventKey))}
>
<a>
{icon ? (
iconPosition === 'right' ? (
<>
{title} {iconElement}
</>
) : (
<>
{iconElement} {title}
</>
)
) : (
title
)}
{React.isValidElement(toolbar) ? toolbar : null}
</a>
{mode === 'chrome' ? (
<div className="chrome-tab-background">
<svg viewBox="0 0 124 124" className="chrome-tab-background--right">
<path d="M0,0 C0,68.483309 55.516691,124 124,124 L0,124 L0,-1 C0.00132103964,-0.667821298 0,-0.334064922 0,0 Z"></path>
</svg>
<svg viewBox="0 0 124 124" className="chrome-tab-background--left">
<path d="M124,0 L124,125 L0,125 L0,125 C68.483309,125 124,69.483309 124,1 L123.992,0 L124,0 Z"></path>
</svg>
</div>
) : null}
</li>
);
}
renderTab(child: any, index: number) {
if (!child) {
return;
}
const {activeKey: activeKeyProp, classnames} = this.props;
const eventKey = child.props.eventKey;
const activeKey =
activeKeyProp === undefined && index === 0 ? eventKey : activeKeyProp;
return React.cloneElement(child, {
...child.props,
key: eventKey,
classnames: classnames,
activeKey: activeKey
});
}
renderArrow(type: 'left' | 'right') {
const {mode: dMode, tabsMode,} = this.props;
const mode = tabsMode || dMode;
if (mode === 'vertical') {
return;
}
const {classnames: cx} = this.props;
const {isOverflow, arrowLeftDisabled, arrowRightDisabled} = this.state;
const disabled = type === 'left' ? arrowLeftDisabled : arrowRightDisabled;
return (isOverflow
? (<div onClick={() => this.handleArrow(type)}
className={cx(
'Tabs-linksContainer-arrow',
'Tabs-linksContainer-arrow--' + type,
disabled && 'Tabs-linksContainer-arrow--disabled'
)}>
<i className={'iconfont icon-arrow-' + type} />
</div>)
: null
)
}
render() {
const {
classnames: cx,
contentClassName,
className,
mode: dMode,
tabsMode,
children,
additionBtns,
toolbar,
linksClassName,
scrollable
} = this.props;
const {isOverflow} = this.state;
if (!Array.isArray(children)) {
return null;
}
const mode = tabsMode || dMode;
return (
<div
className={cx(
`Tabs`,
{
[`Tabs--${mode}`]: mode
},
className
)}
>
{
scrollable && !['vertical', 'chrome'].includes(mode) ?
(<div className={cx('Tabs-linksContainer', isOverflow && 'Tabs-linksContainer--overflow')}>
{this.renderArrow('left')}
<div
className={cx('Tabs-linksContainer-main')}
ref={this.navMain}
>
<ul className={cx('Tabs-links', linksClassName)} role="tablist">
{children.map((tab, index) => this.renderNav(tab, index))}
{additionBtns}
{toolbar}
</ul>
</div>
{this.renderArrow('right')}
</div>)
: (<ul className={cx('Tabs-links', linksClassName)} role="tablist">
{children.map((tab, index) => this.renderNav(tab, index))}
{additionBtns}
{toolbar}
</ul>)
}
<div className={cx('Tabs-content', contentClassName)}>
{children.map((child, index) => {
return this.renderTab(child, index);
})}
</div>
</div>
);
}
}
const ThemedTabs = themeable(
uncontrollable(Tabs, {
activeKey: 'onSelect'
})
);
export default ThemedTabs as typeof ThemedTabs & {
Tab: typeof Tab;
}; | the_stack |
import {Lexer as ExpressionLexer} from '../expression_parser/lexer';
import {Parser as ExpressionParser} from '../expression_parser/parser';
import * as html from '../ml_parser/ast';
import {getHtmlTagDefinition} from '../ml_parser/html_tags';
import {InterpolationConfig} from '../ml_parser/interpolation_config';
import {InterpolatedAttributeToken, InterpolatedTextToken, TokenType} from '../ml_parser/tokens';
import {ParseSourceSpan} from '../parse_util';
import * as i18n from './i18n_ast';
import {PlaceholderRegistry} from './serializers/placeholder';
const _expParser = new ExpressionParser(new ExpressionLexer());
export type VisitNodeFn = (html: html.Node, i18n: i18n.Node) => i18n.Node;
export interface I18nMessageFactory {
(nodes: html.Node[], meaning: string|undefined, description: string|undefined,
customId: string|undefined, visitNodeFn?: VisitNodeFn): i18n.Message;
}
/**
* Returns a function converting html nodes to an i18n Message given an interpolationConfig
*/
export function createI18nMessageFactory(interpolationConfig: InterpolationConfig):
I18nMessageFactory {
const visitor = new _I18nVisitor(_expParser, interpolationConfig);
return (nodes, meaning, description, customId, visitNodeFn) =>
visitor.toI18nMessage(nodes, meaning, description, customId, visitNodeFn);
}
interface I18nMessageVisitorContext {
isIcu: boolean;
icuDepth: number;
placeholderRegistry: PlaceholderRegistry;
placeholderToContent: {[phName: string]: i18n.MessagePlaceholder};
placeholderToMessage: {[phName: string]: i18n.Message};
visitNodeFn: VisitNodeFn;
}
function noopVisitNodeFn(_html: html.Node, i18n: i18n.Node): i18n.Node {
return i18n;
}
class _I18nVisitor implements html.Visitor {
constructor(
private _expressionParser: ExpressionParser,
private _interpolationConfig: InterpolationConfig) {}
public toI18nMessage(
nodes: html.Node[], meaning = '', description = '', customId = '',
visitNodeFn: VisitNodeFn|undefined): i18n.Message {
const context: I18nMessageVisitorContext = {
isIcu: nodes.length == 1 && nodes[0] instanceof html.Expansion,
icuDepth: 0,
placeholderRegistry: new PlaceholderRegistry(),
placeholderToContent: {},
placeholderToMessage: {},
visitNodeFn: visitNodeFn || noopVisitNodeFn,
};
const i18nodes: i18n.Node[] = html.visitAll(this, nodes, context);
return new i18n.Message(
i18nodes, context.placeholderToContent, context.placeholderToMessage, meaning, description,
customId);
}
visitElement(el: html.Element, context: I18nMessageVisitorContext): i18n.Node {
const children = html.visitAll(this, el.children, context);
const attrs: {[k: string]: string} = {};
el.attrs.forEach(attr => {
// Do not visit the attributes, translatable ones are top-level ASTs
attrs[attr.name] = attr.value;
});
const isVoid: boolean = getHtmlTagDefinition(el.name).isVoid;
const startPhName =
context.placeholderRegistry.getStartTagPlaceholderName(el.name, attrs, isVoid);
context.placeholderToContent[startPhName] = {
text: el.startSourceSpan.toString(),
sourceSpan: el.startSourceSpan,
};
let closePhName = '';
if (!isVoid) {
closePhName = context.placeholderRegistry.getCloseTagPlaceholderName(el.name);
context.placeholderToContent[closePhName] = {
text: `</${el.name}>`,
sourceSpan: el.endSourceSpan ?? el.sourceSpan,
};
}
const node = new i18n.TagPlaceholder(
el.name, attrs, startPhName, closePhName, children, isVoid, el.sourceSpan,
el.startSourceSpan, el.endSourceSpan);
return context.visitNodeFn(el, node);
}
visitAttribute(attribute: html.Attribute, context: I18nMessageVisitorContext): i18n.Node {
const node = attribute.valueTokens === undefined || attribute.valueTokens.length === 1 ?
new i18n.Text(attribute.value, attribute.valueSpan || attribute.sourceSpan) :
this._visitTextWithInterpolation(
attribute.valueTokens, attribute.valueSpan || attribute.sourceSpan, context,
attribute.i18n);
return context.visitNodeFn(attribute, node);
}
visitText(text: html.Text, context: I18nMessageVisitorContext): i18n.Node {
const node = text.tokens.length === 1 ?
new i18n.Text(text.value, text.sourceSpan) :
this._visitTextWithInterpolation(text.tokens, text.sourceSpan, context, text.i18n);
return context.visitNodeFn(text, node);
}
visitComment(comment: html.Comment, context: I18nMessageVisitorContext): i18n.Node|null {
return null;
}
visitExpansion(icu: html.Expansion, context: I18nMessageVisitorContext): i18n.Node {
context.icuDepth++;
const i18nIcuCases: {[k: string]: i18n.Node} = {};
const i18nIcu = new i18n.Icu(icu.switchValue, icu.type, i18nIcuCases, icu.sourceSpan);
icu.cases.forEach((caze): void => {
i18nIcuCases[caze.value] = new i18n.Container(
caze.expression.map((node) => node.visit(this, context)), caze.expSourceSpan);
});
context.icuDepth--;
if (context.isIcu || context.icuDepth > 0) {
// Returns an ICU node when:
// - the message (vs a part of the message) is an ICU message, or
// - the ICU message is nested.
const expPh = context.placeholderRegistry.getUniquePlaceholder(`VAR_${icu.type}`);
i18nIcu.expressionPlaceholder = expPh;
context.placeholderToContent[expPh] = {
text: icu.switchValue,
sourceSpan: icu.switchValueSourceSpan,
};
return context.visitNodeFn(icu, i18nIcu);
}
// Else returns a placeholder
// ICU placeholders should not be replaced with their original content but with the their
// translations.
// TODO(vicb): add a html.Node -> i18n.Message cache to avoid having to re-create the msg
const phName = context.placeholderRegistry.getPlaceholderName('ICU', icu.sourceSpan.toString());
context.placeholderToMessage[phName] = this.toI18nMessage([icu], '', '', '', undefined);
const node = new i18n.IcuPlaceholder(i18nIcu, phName, icu.sourceSpan);
return context.visitNodeFn(icu, node);
}
visitExpansionCase(_icuCase: html.ExpansionCase, _context: I18nMessageVisitorContext): i18n.Node {
throw new Error('Unreachable code');
}
/**
* Convert, text and interpolated tokens up into text and placeholder pieces.
*
* @param tokens The text and interpolated tokens.
* @param sourceSpan The span of the whole of the `text` string.
* @param context The current context of the visitor, used to compute and store placeholders.
* @param previousI18n Any i18n metadata associated with this `text` from a previous pass.
*/
private _visitTextWithInterpolation(
tokens: (InterpolatedTextToken|InterpolatedAttributeToken)[], sourceSpan: ParseSourceSpan,
context: I18nMessageVisitorContext, previousI18n: i18n.I18nMeta|undefined): i18n.Node {
// Return a sequence of `Text` and `Placeholder` nodes grouped in a `Container`.
const nodes: i18n.Node[] = [];
// We will only create a container if there are actually interpolations,
// so this flag tracks that.
let hasInterpolation = false;
for (const token of tokens) {
switch (token.type) {
case TokenType.INTERPOLATION:
case TokenType.ATTR_VALUE_INTERPOLATION:
hasInterpolation = true;
const expression = token.parts[1];
const baseName = extractPlaceholderName(expression) || 'INTERPOLATION';
const phName = context.placeholderRegistry.getPlaceholderName(baseName, expression);
context.placeholderToContent[phName] = {
text: token.parts.join(''),
sourceSpan: token.sourceSpan
};
nodes.push(new i18n.Placeholder(expression, phName, token.sourceSpan));
break;
default:
if (token.parts[0].length > 0) {
// This token is text or an encoded entity.
// If it is following on from a previous text node then merge it into that node
// Otherwise, if it is following an interpolation, then add a new node.
const previous = nodes[nodes.length - 1];
if (previous instanceof i18n.Text) {
previous.value += token.parts[0];
previous.sourceSpan = new ParseSourceSpan(
previous.sourceSpan.start, token.sourceSpan.end, previous.sourceSpan.fullStart,
previous.sourceSpan.details);
} else {
nodes.push(new i18n.Text(token.parts[0], token.sourceSpan));
}
}
break;
}
}
if (hasInterpolation) {
// Whitespace removal may have invalidated the interpolation source-spans.
reusePreviousSourceSpans(nodes, previousI18n);
return new i18n.Container(nodes, sourceSpan);
} else {
return nodes[0];
}
}
}
/**
* Re-use the source-spans from `previousI18n` metadata for the `nodes`.
*
* Whitespace removal can invalidate the source-spans of interpolation nodes, so we
* reuse the source-span stored from a previous pass before the whitespace was removed.
*
* @param nodes The `Text` and `Placeholder` nodes to be processed.
* @param previousI18n Any i18n metadata for these `nodes` stored from a previous pass.
*/
function reusePreviousSourceSpans(nodes: i18n.Node[], previousI18n: i18n.I18nMeta|undefined): void {
if (previousI18n instanceof i18n.Message) {
// The `previousI18n` is an i18n `Message`, so we are processing an `Attribute` with i18n
// metadata. The `Message` should consist only of a single `Container` that contains the
// parts (`Text` and `Placeholder`) to process.
assertSingleContainerMessage(previousI18n);
previousI18n = previousI18n.nodes[0];
}
if (previousI18n instanceof i18n.Container) {
// The `previousI18n` is a `Container`, which means that this is a second i18n extraction pass
// after whitespace has been removed from the AST nodes.
assertEquivalentNodes(previousI18n.children, nodes);
// Reuse the source-spans from the first pass.
for (let i = 0; i < nodes.length; i++) {
nodes[i].sourceSpan = previousI18n.children[i].sourceSpan;
}
}
}
/**
* Asserts that the `message` contains exactly one `Container` node.
*/
function assertSingleContainerMessage(message: i18n.Message): void {
const nodes = message.nodes;
if (nodes.length !== 1 || !(nodes[0] instanceof i18n.Container)) {
throw new Error(
'Unexpected previous i18n message - expected it to consist of only a single `Container` node.');
}
}
/**
* Asserts that the `previousNodes` and `node` collections have the same number of elements and
* corresponding elements have the same node type.
*/
function assertEquivalentNodes(previousNodes: i18n.Node[], nodes: i18n.Node[]): void {
if (previousNodes.length !== nodes.length) {
throw new Error('The number of i18n message children changed between first and second pass.');
}
if (previousNodes.some((node, i) => nodes[i].constructor !== node.constructor)) {
throw new Error(
'The types of the i18n message children changed between first and second pass.');
}
}
const _CUSTOM_PH_EXP =
/\/\/[\s\S]*i18n[\s\S]*\([\s\S]*ph[\s\S]*=[\s\S]*("|')([\s\S]*?)\1[\s\S]*\)/g;
function extractPlaceholderName(input: string): string {
return input.split(_CUSTOM_PH_EXP)[2];
} | the_stack |
// Please don't change this file manually but run `prisma generate` to update it.
// For more information, please read the docs: https://www.prisma.io/docs/prisma-client/
export const typeDefs = /* GraphQL */ `type AggregatePasswordMeta {
count: Int!
}
type AggregateUser {
count: Int!
}
type BatchPayload {
"""The number of nodes that have been affected by the Batch operation."""
count: Long!
}
scalar DateTime
"""
The \`Long\` scalar type represents non-fractional signed whole numeric values.
Long can represent values between -(2^63) and 2^63 - 1.
"""
scalar Long
type Mutation {
createUser(data: UserCreateInput!): User!
createPasswordMeta(data: PasswordMetaCreateInput!): PasswordMeta!
updateUser(data: UserUpdateInput!, where: UserWhereUniqueInput!): User
updatePasswordMeta(data: PasswordMetaUpdateInput!, where: PasswordMetaWhereUniqueInput!): PasswordMeta
deleteUser(where: UserWhereUniqueInput!): User
deletePasswordMeta(where: PasswordMetaWhereUniqueInput!): PasswordMeta
upsertUser(where: UserWhereUniqueInput!, create: UserCreateInput!, update: UserUpdateInput!): User!
upsertPasswordMeta(where: PasswordMetaWhereUniqueInput!, create: PasswordMetaCreateInput!, update: PasswordMetaUpdateInput!): PasswordMeta!
updateManyUsers(data: UserUpdateManyMutationInput!, where: UserWhereInput): BatchPayload!
updateManyPasswordMetas(data: PasswordMetaUpdateManyMutationInput!, where: PasswordMetaWhereInput): BatchPayload!
deleteManyUsers(where: UserWhereInput): BatchPayload!
deleteManyPasswordMetas(where: PasswordMetaWhereInput): BatchPayload!
}
enum MutationType {
CREATED
UPDATED
DELETED
}
"""An object with an ID"""
interface Node {
"""The id of the object."""
id: ID!
}
"""Information about pagination in a connection."""
type PageInfo {
"""When paginating forwards, are there more items?"""
hasNextPage: Boolean!
"""When paginating backwards, are there more items?"""
hasPreviousPage: Boolean!
"""When paginating backwards, the cursor to continue."""
startCursor: String
"""When paginating forwards, the cursor to continue."""
endCursor: String
}
type PasswordMeta implements Node {
id: ID!
createdAt: DateTime!
updatedAt: DateTime!
resetToken: String!
}
"""A connection to a list of items."""
type PasswordMetaConnection {
"""Information to aid in pagination."""
pageInfo: PageInfo!
"""A list of edges."""
edges: [PasswordMetaEdge]!
aggregate: AggregatePasswordMeta!
}
input PasswordMetaCreateInput {
id: ID
resetToken: String!
}
input PasswordMetaCreateOneInput {
create: PasswordMetaCreateInput
connect: PasswordMetaWhereUniqueInput
}
"""An edge in a connection."""
type PasswordMetaEdge {
"""The item at the end of the edge."""
node: PasswordMeta!
"""A cursor for use in pagination."""
cursor: String!
}
enum PasswordMetaOrderByInput {
id_ASC
id_DESC
createdAt_ASC
createdAt_DESC
updatedAt_ASC
updatedAt_DESC
resetToken_ASC
resetToken_DESC
}
type PasswordMetaPreviousValues {
id: ID!
createdAt: DateTime!
updatedAt: DateTime!
resetToken: String!
}
type PasswordMetaSubscriptionPayload {
mutation: MutationType!
node: PasswordMeta
updatedFields: [String!]
previousValues: PasswordMetaPreviousValues
}
input PasswordMetaSubscriptionWhereInput {
"""Logical AND on all given filters."""
AND: [PasswordMetaSubscriptionWhereInput!]
"""Logical OR on all given filters."""
OR: [PasswordMetaSubscriptionWhereInput!]
"""Logical NOT on all given filters combined by AND."""
NOT: [PasswordMetaSubscriptionWhereInput!]
"""The subscription event gets dispatched when it's listed in mutation_in"""
mutation_in: [MutationType!]
"""
The subscription event gets only dispatched when one of the updated fields names is included in this list
"""
updatedFields_contains: String
"""
The subscription event gets only dispatched when all of the field names included in this list have been updated
"""
updatedFields_contains_every: [String!]
"""
The subscription event gets only dispatched when some of the field names included in this list have been updated
"""
updatedFields_contains_some: [String!]
node: PasswordMetaWhereInput
}
input PasswordMetaUpdateDataInput {
resetToken: String
}
input PasswordMetaUpdateInput {
resetToken: String
}
input PasswordMetaUpdateManyMutationInput {
resetToken: String
}
input PasswordMetaUpdateOneInput {
create: PasswordMetaCreateInput
connect: PasswordMetaWhereUniqueInput
disconnect: Boolean
delete: Boolean
update: PasswordMetaUpdateDataInput
upsert: PasswordMetaUpsertNestedInput
}
input PasswordMetaUpsertNestedInput {
update: PasswordMetaUpdateDataInput!
create: PasswordMetaCreateInput!
}
input PasswordMetaWhereInput {
"""Logical AND on all given filters."""
AND: [PasswordMetaWhereInput!]
"""Logical OR on all given filters."""
OR: [PasswordMetaWhereInput!]
"""Logical NOT on all given filters combined by AND."""
NOT: [PasswordMetaWhereInput!]
id: ID
"""All values that are not equal to given value."""
id_not: ID
"""All values that are contained in given list."""
id_in: [ID!]
"""All values that are not contained in given list."""
id_not_in: [ID!]
"""All values less than the given value."""
id_lt: ID
"""All values less than or equal the given value."""
id_lte: ID
"""All values greater than the given value."""
id_gt: ID
"""All values greater than or equal the given value."""
id_gte: ID
"""All values containing the given string."""
id_contains: ID
"""All values not containing the given string."""
id_not_contains: ID
"""All values starting with the given string."""
id_starts_with: ID
"""All values not starting with the given string."""
id_not_starts_with: ID
"""All values ending with the given string."""
id_ends_with: ID
"""All values not ending with the given string."""
id_not_ends_with: ID
createdAt: DateTime
"""All values that are not equal to given value."""
createdAt_not: DateTime
"""All values that are contained in given list."""
createdAt_in: [DateTime!]
"""All values that are not contained in given list."""
createdAt_not_in: [DateTime!]
"""All values less than the given value."""
createdAt_lt: DateTime
"""All values less than or equal the given value."""
createdAt_lte: DateTime
"""All values greater than the given value."""
createdAt_gt: DateTime
"""All values greater than or equal the given value."""
createdAt_gte: DateTime
updatedAt: DateTime
"""All values that are not equal to given value."""
updatedAt_not: DateTime
"""All values that are contained in given list."""
updatedAt_in: [DateTime!]
"""All values that are not contained in given list."""
updatedAt_not_in: [DateTime!]
"""All values less than the given value."""
updatedAt_lt: DateTime
"""All values less than or equal the given value."""
updatedAt_lte: DateTime
"""All values greater than the given value."""
updatedAt_gt: DateTime
"""All values greater than or equal the given value."""
updatedAt_gte: DateTime
resetToken: String
"""All values that are not equal to given value."""
resetToken_not: String
"""All values that are contained in given list."""
resetToken_in: [String!]
"""All values that are not contained in given list."""
resetToken_not_in: [String!]
"""All values less than the given value."""
resetToken_lt: String
"""All values less than or equal the given value."""
resetToken_lte: String
"""All values greater than the given value."""
resetToken_gt: String
"""All values greater than or equal the given value."""
resetToken_gte: String
"""All values containing the given string."""
resetToken_contains: String
"""All values not containing the given string."""
resetToken_not_contains: String
"""All values starting with the given string."""
resetToken_starts_with: String
"""All values not starting with the given string."""
resetToken_not_starts_with: String
"""All values ending with the given string."""
resetToken_ends_with: String
"""All values not ending with the given string."""
resetToken_not_ends_with: String
}
input PasswordMetaWhereUniqueInput {
id: ID
}
type Query {
users(where: UserWhereInput, orderBy: UserOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): [User]!
passwordMetas(where: PasswordMetaWhereInput, orderBy: PasswordMetaOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): [PasswordMeta]!
user(where: UserWhereUniqueInput!): User
passwordMeta(where: PasswordMetaWhereUniqueInput!): PasswordMeta
usersConnection(where: UserWhereInput, orderBy: UserOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): UserConnection!
passwordMetasConnection(where: PasswordMetaWhereInput, orderBy: PasswordMetaOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): PasswordMetaConnection!
"""Fetches an object given its ID"""
node(
"""The ID of an object"""
id: ID!
): Node
}
type Subscription {
user(where: UserSubscriptionWhereInput): UserSubscriptionPayload
passwordMeta(where: PasswordMetaSubscriptionWhereInput): PasswordMetaSubscriptionPayload
}
type User implements Node {
id: ID!
createdAt: DateTime!
updatedAt: DateTime!
email: String!
password: String!
role: UserRole!
firstName: String
lastName: String
phone: String
passwordMeta: PasswordMeta
}
"""A connection to a list of items."""
type UserConnection {
"""Information to aid in pagination."""
pageInfo: PageInfo!
"""A list of edges."""
edges: [UserEdge]!
aggregate: AggregateUser!
}
input UserCreateInput {
id: ID
email: String!
password: String!
role: UserRole
firstName: String
lastName: String
phone: String
passwordMeta: PasswordMetaCreateOneInput
}
"""An edge in a connection."""
type UserEdge {
"""The item at the end of the edge."""
node: User!
"""A cursor for use in pagination."""
cursor: String!
}
enum UserOrderByInput {
id_ASC
id_DESC
createdAt_ASC
createdAt_DESC
updatedAt_ASC
updatedAt_DESC
email_ASC
email_DESC
password_ASC
password_DESC
role_ASC
role_DESC
firstName_ASC
firstName_DESC
lastName_ASC
lastName_DESC
phone_ASC
phone_DESC
}
type UserPreviousValues {
id: ID!
createdAt: DateTime!
updatedAt: DateTime!
email: String!
password: String!
role: UserRole!
firstName: String
lastName: String
phone: String
}
enum UserRole {
USER
ADMIN
}
type UserSubscriptionPayload {
mutation: MutationType!
node: User
updatedFields: [String!]
previousValues: UserPreviousValues
}
input UserSubscriptionWhereInput {
"""Logical AND on all given filters."""
AND: [UserSubscriptionWhereInput!]
"""Logical OR on all given filters."""
OR: [UserSubscriptionWhereInput!]
"""Logical NOT on all given filters combined by AND."""
NOT: [UserSubscriptionWhereInput!]
"""The subscription event gets dispatched when it's listed in mutation_in"""
mutation_in: [MutationType!]
"""
The subscription event gets only dispatched when one of the updated fields names is included in this list
"""
updatedFields_contains: String
"""
The subscription event gets only dispatched when all of the field names included in this list have been updated
"""
updatedFields_contains_every: [String!]
"""
The subscription event gets only dispatched when some of the field names included in this list have been updated
"""
updatedFields_contains_some: [String!]
node: UserWhereInput
}
input UserUpdateInput {
email: String
password: String
role: UserRole
firstName: String
lastName: String
phone: String
passwordMeta: PasswordMetaUpdateOneInput
}
input UserUpdateManyMutationInput {
email: String
password: String
role: UserRole
firstName: String
lastName: String
phone: String
}
input UserWhereInput {
"""Logical AND on all given filters."""
AND: [UserWhereInput!]
"""Logical OR on all given filters."""
OR: [UserWhereInput!]
"""Logical NOT on all given filters combined by AND."""
NOT: [UserWhereInput!]
id: ID
"""All values that are not equal to given value."""
id_not: ID
"""All values that are contained in given list."""
id_in: [ID!]
"""All values that are not contained in given list."""
id_not_in: [ID!]
"""All values less than the given value."""
id_lt: ID
"""All values less than or equal the given value."""
id_lte: ID
"""All values greater than the given value."""
id_gt: ID
"""All values greater than or equal the given value."""
id_gte: ID
"""All values containing the given string."""
id_contains: ID
"""All values not containing the given string."""
id_not_contains: ID
"""All values starting with the given string."""
id_starts_with: ID
"""All values not starting with the given string."""
id_not_starts_with: ID
"""All values ending with the given string."""
id_ends_with: ID
"""All values not ending with the given string."""
id_not_ends_with: ID
createdAt: DateTime
"""All values that are not equal to given value."""
createdAt_not: DateTime
"""All values that are contained in given list."""
createdAt_in: [DateTime!]
"""All values that are not contained in given list."""
createdAt_not_in: [DateTime!]
"""All values less than the given value."""
createdAt_lt: DateTime
"""All values less than or equal the given value."""
createdAt_lte: DateTime
"""All values greater than the given value."""
createdAt_gt: DateTime
"""All values greater than or equal the given value."""
createdAt_gte: DateTime
updatedAt: DateTime
"""All values that are not equal to given value."""
updatedAt_not: DateTime
"""All values that are contained in given list."""
updatedAt_in: [DateTime!]
"""All values that are not contained in given list."""
updatedAt_not_in: [DateTime!]
"""All values less than the given value."""
updatedAt_lt: DateTime
"""All values less than or equal the given value."""
updatedAt_lte: DateTime
"""All values greater than the given value."""
updatedAt_gt: DateTime
"""All values greater than or equal the given value."""
updatedAt_gte: DateTime
email: String
"""All values that are not equal to given value."""
email_not: String
"""All values that are contained in given list."""
email_in: [String!]
"""All values that are not contained in given list."""
email_not_in: [String!]
"""All values less than the given value."""
email_lt: String
"""All values less than or equal the given value."""
email_lte: String
"""All values greater than the given value."""
email_gt: String
"""All values greater than or equal the given value."""
email_gte: String
"""All values containing the given string."""
email_contains: String
"""All values not containing the given string."""
email_not_contains: String
"""All values starting with the given string."""
email_starts_with: String
"""All values not starting with the given string."""
email_not_starts_with: String
"""All values ending with the given string."""
email_ends_with: String
"""All values not ending with the given string."""
email_not_ends_with: String
password: String
"""All values that are not equal to given value."""
password_not: String
"""All values that are contained in given list."""
password_in: [String!]
"""All values that are not contained in given list."""
password_not_in: [String!]
"""All values less than the given value."""
password_lt: String
"""All values less than or equal the given value."""
password_lte: String
"""All values greater than the given value."""
password_gt: String
"""All values greater than or equal the given value."""
password_gte: String
"""All values containing the given string."""
password_contains: String
"""All values not containing the given string."""
password_not_contains: String
"""All values starting with the given string."""
password_starts_with: String
"""All values not starting with the given string."""
password_not_starts_with: String
"""All values ending with the given string."""
password_ends_with: String
"""All values not ending with the given string."""
password_not_ends_with: String
role: UserRole
"""All values that are not equal to given value."""
role_not: UserRole
"""All values that are contained in given list."""
role_in: [UserRole!]
"""All values that are not contained in given list."""
role_not_in: [UserRole!]
firstName: String
"""All values that are not equal to given value."""
firstName_not: String
"""All values that are contained in given list."""
firstName_in: [String!]
"""All values that are not contained in given list."""
firstName_not_in: [String!]
"""All values less than the given value."""
firstName_lt: String
"""All values less than or equal the given value."""
firstName_lte: String
"""All values greater than the given value."""
firstName_gt: String
"""All values greater than or equal the given value."""
firstName_gte: String
"""All values containing the given string."""
firstName_contains: String
"""All values not containing the given string."""
firstName_not_contains: String
"""All values starting with the given string."""
firstName_starts_with: String
"""All values not starting with the given string."""
firstName_not_starts_with: String
"""All values ending with the given string."""
firstName_ends_with: String
"""All values not ending with the given string."""
firstName_not_ends_with: String
lastName: String
"""All values that are not equal to given value."""
lastName_not: String
"""All values that are contained in given list."""
lastName_in: [String!]
"""All values that are not contained in given list."""
lastName_not_in: [String!]
"""All values less than the given value."""
lastName_lt: String
"""All values less than or equal the given value."""
lastName_lte: String
"""All values greater than the given value."""
lastName_gt: String
"""All values greater than or equal the given value."""
lastName_gte: String
"""All values containing the given string."""
lastName_contains: String
"""All values not containing the given string."""
lastName_not_contains: String
"""All values starting with the given string."""
lastName_starts_with: String
"""All values not starting with the given string."""
lastName_not_starts_with: String
"""All values ending with the given string."""
lastName_ends_with: String
"""All values not ending with the given string."""
lastName_not_ends_with: String
phone: String
"""All values that are not equal to given value."""
phone_not: String
"""All values that are contained in given list."""
phone_in: [String!]
"""All values that are not contained in given list."""
phone_not_in: [String!]
"""All values less than the given value."""
phone_lt: String
"""All values less than or equal the given value."""
phone_lte: String
"""All values greater than the given value."""
phone_gt: String
"""All values greater than or equal the given value."""
phone_gte: String
"""All values containing the given string."""
phone_contains: String
"""All values not containing the given string."""
phone_not_contains: String
"""All values starting with the given string."""
phone_starts_with: String
"""All values not starting with the given string."""
phone_not_starts_with: String
"""All values ending with the given string."""
phone_ends_with: String
"""All values not ending with the given string."""
phone_not_ends_with: String
passwordMeta: PasswordMetaWhereInput
}
input UserWhereUniqueInput {
id: ID
email: String
}
` | the_stack |
import { Component, ChangeDetectionStrategy, ViewChild } from '@angular/core';
import { FormBuilder, Validators} from '@angular/forms';
import { MeasFilterService } from './measfiltercfg.service';
import { MeasurementService } from '../measurement/measurementcfg.service';
import { CustomFilterService } from '../customfilter/customfilter.service';
import { OidConditionService } from '../oidcondition/oidconditioncfg.service';
import { FormArray, FormGroup, FormControl} from '@angular/forms';
import { ExportServiceCfg } from '../common/dataservice/export.service'
import { Observable } from 'rxjs/Rx';
import { ValidationService } from '../common/validation.service'
import { IMultiSelectOption, IMultiSelectSettings, IMultiSelectTexts } from '../common/multiselect-dropdown';
import { ExportFileModal } from '../common/dataservice/export-file-modal';
import { GenericModal } from '../common/generic-modal';
import { ItemsPerPageOptions } from '../common/global-constants';
import { TableActions } from '../common/table-actions';
import { AvailableTableActions } from '../common/table-available-actions';
import { TableListComponent } from '../common/table-list.component';
import { MeasFilterCfgComponentConfig, TableRole, OverrideRoleActions } from './measfiltercfg.data';
declare var _:any;
@Component({
selector: 'measfilters',
providers: [MeasFilterService, MeasurementService, CustomFilterService,OidConditionService],
templateUrl: './measfiltereditor.html',
styleUrls: ['../css/component-styles.css']
})
export class MeasFilterCfgComponent {
@ViewChild('viewModal') public viewModal: GenericModal;
@ViewChild('viewModalDelete') public viewModalDelete: GenericModal;
@ViewChild('exportFileModal') public exportFileModal : ExportFileModal;
selectedArray : any = [];
public isRequesting : boolean;
public counterItems : number = null;
public counterErrors: any = [];
public tableAvailableActions : any;
itemsPerPageOptions : any = ItemsPerPageOptions;
editmode: string; //list , create, modify
measfilters: Array<any>;
filter: string;
measfilterForm: any;
measurement: Array<any>;
selectmeas: IMultiSelectOption[] = [];
selectCustomFilters: IMultiSelectOption[] = [];
public defaultConfig : any = MeasFilterCfgComponentConfig;
public tableRole : any = TableRole;
public overrideRoleActions: any = OverrideRoleActions;
oidconditions: Array<any>;
selectoidcond: IMultiSelectOption[] = [];
myFilterValue: any;
private mySettings: IMultiSelectSettings = {
singleSelect: true,
};
//Initialization data, rows, colunms for Table
private data: Array<any> = [];
public rows: Array<any> = [];
public page: number = 1;
public itemsPerPage: number = 20;
public maxSize: number = 5;
public numPages: number = 1;
public length: number = 0;
private builder;
private oldID : string;
//Set config
public config: any = {
paging: true,
sorting: { columns: this.defaultConfig['table-columns'] },
filtering: { filterString: '' },
className: ['table-striped', 'table-bordered']
};
constructor(public oidCondService: OidConditionService,public customFilterService: CustomFilterService, public measFilterService: MeasFilterService, public measMeasFilterService: MeasurementService, public exportServiceCfg : ExportServiceCfg, builder: FormBuilder) {
this.editmode = 'list';
this.reloadData();
this.builder = builder;
}
createStaticForm() {
this.measfilterForm = this.builder.group({
ID: [this.measfilterForm ? this.measfilterForm.value.ID : '', Validators.required],
IDMeasurementCfg: [this.measfilterForm ? this.measfilterForm.value.IDMeasurementCfg : '', Validators.required],
FType: [this.measfilterForm ? this.measfilterForm.value.FType : 'OIDCondition', Validators.required],
Description: [this.measfilterForm ? this.measfilterForm.value.Description : '']
});
}
createDynamicForm(fieldsArray: any) : void {
//Saves the actual to check later if there are shared values
let tmpform : any;
if (this.measfilterForm) tmpform = this.measfilterForm.value;
this.createStaticForm();
for (let entry of fieldsArray) {
let value = entry.defVal;
//Check if there are common values from the previous selected item
if (tmpform) {
if (tmpform[entry.ID] && entry.override !== true) {
value = tmpform[entry.ID];
}
}
//Set different controls:
this.measfilterForm.addControl(entry.ID, new FormControl(value, entry.Validators));
}
}
setDynamicFields (field : any, override? : boolean) : void {
//Saves on the array all values to push into formGroup
let controlArray : Array<any> = [];
switch (field) {
case 'file':
controlArray.push({'ID': 'FilterName', 'defVal' : '', 'Validators' : Validators.required, 'override' : override});
controlArray.push({'ID': 'EnableAlias', 'defVal' : 'true', 'Validators' : Validators.required});
break;
case 'CustomFilter':
this.getCustomFiltersforMeasFilters();
controlArray.push({'ID': 'FilterName', 'defVal' : '', 'Validators' : Validators.required, 'override' : override});
controlArray.push({'ID': 'EnableAlias', 'defVal' : 'true', 'Validators' : Validators.required});
break;
default: //OID Condition
this.getOidCond();
controlArray.push({'ID': 'FilterName', 'defVal' : '', 'Validators' : Validators.required, 'override' : override});
break;
}
//Reload the formGroup with new values saved on controlArray
this.createDynamicForm(controlArray);
}
applyAction(test : any, data? : Array<any>) : void {
this.selectedArray = data || [];
switch(test.action) {
case "RemoveAllSelected": {
this.removeAllSelectedItems(this.selectedArray);
break;
}
default: {
break;
}
}
}
customActions(action : any) {
switch (action.option) {
case 'export' :
this.exportItem(action.event);
break;
case 'new' :
this.newMeasFilter()
case 'view':
this.viewItem(action.event);
break;
case 'edit':
this.editMeasFilter(action.event);
break;
case 'remove':
this.removeItem(action.event);
break;
case 'tableaction':
this.applyAction(action.event, action.data);
break;
}
}
reloadData() {
this.selectedArray = [];
this.isRequesting = true;
// now it's a simple subscription to the observable
this.measFilterService.getMeasFilter(this.filter)
.subscribe(
data => {
this.isRequesting = false;
this.measfilters = data;
this.data = data;
},
err => console.error(err),
() => console.log('DONE')
);
}
onFilter() {
this.reloadData();
}
viewItem(id) {
console.log('view', id);
this.viewModal.parseObject(id);
}
exportItem(item : any) : void {
this.exportFileModal.initExportModal(item);
}
removeAllSelectedItems(myArray) {
let obsArray = [];
this.counterItems = 0;
this.isRequesting = true;
for (let i in myArray) {
console.log("Removing ",myArray[i].ID)
this.deleteMeasFilter(myArray[i].ID,true);
obsArray.push(this.deleteMeasFilter(myArray[i].ID,true));
}
this.genericForkJoin(obsArray);
}
removeItem(row) {
let id = row.ID;
console.log('remove', id);
this.measFilterService.checkOnDeleteMeasFilter(id)
.subscribe(
data => {
console.log(data);
let temp = data;
this.viewModalDelete.parseObject(temp)
},
err => console.error(err),
() => { }
);
}
newMeasFilter() {
if (this.measfilterForm) {
this.setDynamicFields(this.measfilterForm.value.FType);
} else {
this.setDynamicFields(null);
}
this.getMeasforMeasFilters();
this.editmode = "create";
}
editMeasFilter(row) {
let id = row.ID;
this.getMeasforMeasFilters();
this.measFilterService.getMeasFilterById(id)
.subscribe(data => {
this.measfilterForm = {};
this.measfilterForm.value = data;
this.setDynamicFields(row.FType, false);
this.oldID = data.ID
this.editmode = "modify"
},
err => console.error(err),
);
}
deleteMeasFilter(id, recursive?) {
if (!recursive) {
this.measFilterService.deleteMeasFilter(id)
.subscribe(data => { },
err => console.error(err),
() => { this.viewModalDelete.hide(); this.editmode = "list"; this.reloadData() }
);
} else {
return this.measFilterService.deleteMeasFilter(id, true)
.do(
(test) => { this.counterItems++},
(err) => { this.counterErrors.push({'ID': id, 'error' : err})}
);
}
}
cancelEdit() {
this.editmode = "list";
}
saveMeasFilter() {
if (this.measfilterForm.valid) {
this.measFilterService.addMeasFilter(this.measfilterForm.value)
.subscribe(data => { console.log(data) },
err => console.error(err),
() => { this.editmode = "list"; this.reloadData() }
);
}
}
updateAllSelectedItems(mySelectedArray,field,value, append?) {
let obsArray = [];
this.counterItems = 0;
this.isRequesting = true;
if (!append)
for (let component of mySelectedArray) {
component[field] = value;
obsArray.push(this.updateMeasFilter(true,component));
} else {
let tmpArray = [];
if(!Array.isArray(value)) value = value.split(',');
console.log(value);
for (let component of mySelectedArray) {
console.log(value);
//check if there is some new object to append
let newEntries = _.differenceWith(value,component[field],_.isEqual);
tmpArray = newEntries.concat(component[field])
console.log(tmpArray);
component[field] = tmpArray;
obsArray.push(this.updateMeasFilter(true,component));
}
}
this.genericForkJoin(obsArray);
//Make sync calls and wait the result
this.counterErrors = [];
}
updateMeasFilter(recursive?, component?) {
if(!recursive) {
if (this.measfilterForm.valid) {
var r = true;
if (this.measfilterForm.value.ID != this.oldID) {
r = confirm("Changing Measurement Filter ID from " + this.oldID + " to " + this.measfilterForm.value.ID + ". Proceed?");
}
if (r == true) {
this.measFilterService.editMeasFilter(this.measfilterForm.value, this.oldID)
.subscribe(data => { console.log(data) },
err => console.error(err),
() => { this.editmode = "list"; this.reloadData() }
);
}
}
} else {
return this.measFilterService.editMeasFilter(component, component.ID, true)
.do(
(test) => { this.counterItems++ },
(err) => { this.counterErrors.push({'ID': component['ID'], 'error' : err['_body']})}
)
.catch((err) => {
return Observable.of({'ID': component.ID , 'error': err['_body']})
})
}
}
getMeasforMeasFilters() {
this.measMeasFilterService.getMeas(null)
.subscribe(
data => {
this.measurement = data;
this.selectmeas = [];
for (let entry of data) {
console.log(entry)
this.selectmeas.push({ 'id': entry.ID, 'name': entry.ID });
if (entry.GetMode == "indexed_multiple") {
for (let mi of entry.MultiIndexCfg) {
this.selectmeas.push({'id': entry.ID+'..'+mi.Label, 'name': mi.Label, 'badge': "indexed multiple" })
}
}
}
},
err => console.error(err),
() => console.log('DONE')
);
}
getOidCond() {
this.oidCondService.getConditions(null)
.subscribe(
data => {
this.oidconditions = data;
this.selectoidcond = [];
for (let entry of data) {
console.log(entry)
this.selectoidcond.push({ 'id': entry.ID, 'name': entry.ID });
}
},
err => console.error(err),
() => { console.log('DONE') }
);
}
getCustomFiltersforMeasFilters() {
this.customFilterService.getCustomFilter(null)
.subscribe(
data => {
this.selectCustomFilters = [];
for (let entry of data) {
console.log(entry)
this.selectCustomFilters.push({ 'id': entry.ID, 'name': entry.ID });
}
},
err => console.error(err),
() => console.log('DONE')
);
}
genericForkJoin(obsArray: any) {
Observable.forkJoin(obsArray)
.subscribe(
data => {
this.selectedArray = [];
this.reloadData()
},
err => console.error(err),
);
}
} | the_stack |
import { expect } from 'chai';
import { AttributesManagerFactory } from '../../lib/attributes/AttributesManagerFactory';
import { JsonProvider } from '../mocks/JsonProvider';
import { MockPersistenceAdapter } from '../mocks/persistence/MockPersistenceAdapter';
describe('AttributesManagerFactory', () => {
it('should throw an error when RequestEnvelope is null or undefined', () => {
try {
AttributesManagerFactory.init({requestEnvelope : null});
} catch (error) {
expect(error.name).eq('AskSdk.AttributesManagerFactory Error');
expect(error.message).eq('RequestEnvelope cannot be null or undefined!');
return;
}
throw new Error('should have thrown an error');
});
it('should be able to get session attributes from in session request envelope', () => {
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.session.attributes = {mockKey : 'mockValue'};
const defaultAttributesManager = AttributesManagerFactory.init({requestEnvelope});
expect(defaultAttributesManager.getSessionAttributes()).deep.equal({mockKey : 'mockValue'});
});
it('should be able to get default session attributes from new session request envelope', () => {
const requestEnvelope = JsonProvider.requestEnvelope();
const defaultAttributesManager = AttributesManagerFactory.init({requestEnvelope});
expect(defaultAttributesManager.getSessionAttributes()).deep.equal({});
});
it('should throw an error when trying to get session attributes from out of session request envelope', () => {
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.session = undefined;
const defaultAttributesManager = AttributesManagerFactory.init({requestEnvelope});
try {
defaultAttributesManager.getSessionAttributes();
} catch (err) {
expect(err.name).equal('AskSdk.AttributesManager Error');
expect(err.message).equal('Cannot get SessionAttributes from out of session request!');
return;
}
throw new Error('should have thrown an error!');
});
it('should get default attributes when db has no attributes', async () => {
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.context.System.user.userId = 'userId';
const defaultAttributesManager = AttributesManagerFactory.init({
persistenceAdapter : new MockPersistenceAdapter(),
requestEnvelope,
});
await defaultAttributesManager.deletePersistentAttributes();
expect(await defaultAttributesManager.getPersistentAttributes(true, {
key_1: 'v1', /* eslint-disable-line camelcase */
})).deep.equal({
key_1 : 'v1', /* eslint-disable-line camelcase */
});
});
it('should be able to get persistent attributes', async () => {
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.context.System.user.userId = 'userId';
const defaultAttributesManager = AttributesManagerFactory.init({
persistenceAdapter : new MockPersistenceAdapter(),
requestEnvelope,
});
expect(await defaultAttributesManager.getPersistentAttributes()).deep.equal({
key_1 : 'v1', /* eslint-disable-line camelcase */
key_2 : 'v2', /* eslint-disable-line camelcase */
state : 'mockState',
});
});
it('should throw an error when trying to get persistent attributes without persistence adapter', async () => {
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.context.System.user.userId = 'userId';
const defaultAttributesManager = AttributesManagerFactory.init({requestEnvelope});
try {
await defaultAttributesManager.getPersistentAttributes();
} catch (err) {
expect(err.name).equal('AskSdk.AttributesManager Error');
expect(err.message).equal('Cannot get PersistentAttributes without PersistenceManager');
return;
}
throw new Error('should have thrown an error!');
});
it('should be able to get initial request attributes', () => {
const requestEnvelope = JsonProvider.requestEnvelope();
const defaultAttributesManager = AttributesManagerFactory.init({requestEnvelope});
expect(defaultAttributesManager.getRequestAttributes()).deep.equal({});
});
it('should be able to set session attributes', () => {
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.session.attributes = {mockKey : 'mockValue'};
const defaultAttributesManager = AttributesManagerFactory.init({requestEnvelope});
expect(defaultAttributesManager.getSessionAttributes()).deep.equal({mockKey : 'mockValue'});
defaultAttributesManager.setSessionAttributes({updatedKey : 'UpdatedValue'});
expect(defaultAttributesManager.getSessionAttributes()).deep.equal({updatedKey : 'UpdatedValue'});
});
it('should throw an error when trying to set session attributes to out of session request envelope', () => {
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.session = undefined;
const defaultAttributesManager = AttributesManagerFactory.init({requestEnvelope});
try {
defaultAttributesManager.setSessionAttributes({key : 'value'});
} catch (err) {
expect(err.name).equal('AskSdk.AttributesManager Error');
expect(err.message).equal('Cannot set SessionAttributes to out of session request!');
return;
}
throw new Error('should have thrown an error!');
});
it('should be able to set persistent attributes', async () => {
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.context.System.user.userId = 'userId';
const defaultAttributesManager = AttributesManagerFactory.init({
persistenceAdapter : new MockPersistenceAdapter(),
requestEnvelope,
});
defaultAttributesManager.setPersistentAttributes({key : 'value'});
expect(await defaultAttributesManager.getPersistentAttributes()).deep.equal({key : 'value'});
});
it('should throw an error when trying to set persistent attributes without persistence adapter', () => {
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.context.System.user.userId = 'userId';
const defaultAttributesManager = AttributesManagerFactory.init({requestEnvelope});
try {
defaultAttributesManager.setPersistentAttributes({key : 'value'});
} catch (err) {
expect(err.name).equal('AskSdk.AttributesManager Error');
expect(err.message).equal('Cannot set PersistentAttributes without persistence adapter!');
return;
}
throw new Error('should have thrown an error!');
});
it('should be able to delete persistent attributes', async () => {
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.context.System.user.userId = 'userId';
const mockPersistenceAdapter = new MockPersistenceAdapter();
const defaultAttributesManager = AttributesManagerFactory.init({
persistenceAdapter : mockPersistenceAdapter,
requestEnvelope,
});
expect(await defaultAttributesManager.getPersistentAttributes()).deep.equal({
key_1 : 'v1', /* eslint-disable-line camelcase */
key_2 : 'v2', /* eslint-disable-line camelcase */
state : 'mockState',
});
await defaultAttributesManager.deletePersistentAttributes();
expect(await defaultAttributesManager.getPersistentAttributes()).deep.equal({});
expect(mockPersistenceAdapter.getCounter).eq(2);
});
it('should throw an error when trying to delete persistent attributes without persistence adapter', async () => {
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.context.System.user.userId = 'userId';
const defaultAttributesManager = AttributesManagerFactory.init({requestEnvelope});
try {
await defaultAttributesManager.deletePersistentAttributes();
} catch (err) {
expect(err.name).equal('AskSdk.AttributesManager Error');
expect(err.message).equal('Cannot delete PersistentAttributes without persistence adapter!');
return;
}
throw new Error('should have thrown an error!');
});
it('should be able to set request attributes', async () => {
const requestEnvelope = JsonProvider.requestEnvelope();
const defaultAttributesManager = AttributesManagerFactory.init({requestEnvelope});
defaultAttributesManager.setRequestAttributes({key : 'value'});
expect(defaultAttributesManager.getRequestAttributes()).deep.equal({key : 'value'});
});
it('should be able to savePersistentAttributes persistent attributes to persistence layer', async () => {
const mockPersistenceAdapter = new MockPersistenceAdapter();
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.context.System.user.userId = 'userId';
const defaultAttributesManager = AttributesManagerFactory.init({
persistenceAdapter : mockPersistenceAdapter,
requestEnvelope,
});
defaultAttributesManager.setPersistentAttributes({mockKey : 'mockValue'});
await defaultAttributesManager.savePersistentAttributes();
expect(await mockPersistenceAdapter.getAttributes(requestEnvelope)).deep.equal({mockKey : 'mockValue'});
});
it('should thrown an error when trying to save persistent attributes without persistence adapter', async () => {
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.context.System.user.userId = 'userId';
const defaultAttributesManager = AttributesManagerFactory.init({requestEnvelope});
try {
await defaultAttributesManager.savePersistentAttributes();
} catch (err) {
expect(err.name).equal('AskSdk.AttributesManager Error');
expect(err.message).equal('Cannot save PersistentAttributes without persistence adapter!');
return;
}
throw new Error('should have thrown an error!');
});
it('should do nothing if persistentAttributes has not been changed', async () => {
const mockPersistenceAdapter = new MockPersistenceAdapter();
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.context.System.user.userId = 'userId';
const defaultAttributesManager = AttributesManagerFactory.init({
persistenceAdapter : mockPersistenceAdapter,
requestEnvelope,
});
await defaultAttributesManager.savePersistentAttributes();
expect(await mockPersistenceAdapter.getAttributes(requestEnvelope)).deep.equal({
key_1 : 'v1', /* eslint-disable-line camelcase */
key_2 : 'v2', /* eslint-disable-line camelcase */
state : 'mockState',
});
expect(mockPersistenceAdapter.getCounter).equal(1);
expect(mockPersistenceAdapter.saveCounter).equal(0);
});
it('should make only 1 getAttributes call during multiple getPersistentAttributes by default', async () => {
const mockPersistenceAdapter = new MockPersistenceAdapter();
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.context.System.user.userId = 'userId';
const defaultAttributesManager = AttributesManagerFactory.init({
persistenceAdapter : mockPersistenceAdapter,
requestEnvelope,
});
await defaultAttributesManager.getPersistentAttributes();
await defaultAttributesManager.getPersistentAttributes();
await defaultAttributesManager.getPersistentAttributes();
await defaultAttributesManager.getPersistentAttributes();
expect(mockPersistenceAdapter.getCounter).equal(1);
expect(mockPersistenceAdapter.saveCounter).equal(0);
});
it('should make as many getAttributes calls as getPersistentAttributes calls when useSessionCache is false', async () => {
const mockPersistenceAdapter = new MockPersistenceAdapter();
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.context.System.user.userId = 'userId';
const defaultAttributesManager = AttributesManagerFactory.init({
persistenceAdapter : mockPersistenceAdapter,
requestEnvelope,
});
await defaultAttributesManager.getPersistentAttributes(false);
await defaultAttributesManager.getPersistentAttributes(false);
await defaultAttributesManager.getPersistentAttributes(false);
await defaultAttributesManager.getPersistentAttributes(false);
expect(mockPersistenceAdapter.getCounter).equal(4);
expect(mockPersistenceAdapter.saveCounter).equal(0);
});
it('should not make saveAttributes call until savePersistentAttributes is called', async () => {
const mockPersistenceAdapter = new MockPersistenceAdapter();
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.context.System.user.userId = 'userId';
const defaultAttributesManager = AttributesManagerFactory.init({
persistenceAdapter : mockPersistenceAdapter,
requestEnvelope,
});
await defaultAttributesManager.setPersistentAttributes({});
await defaultAttributesManager.setPersistentAttributes({});
await defaultAttributesManager.setPersistentAttributes({});
await defaultAttributesManager.setPersistentAttributes({});
expect(mockPersistenceAdapter.getCounter).equal(0);
expect(mockPersistenceAdapter.saveCounter).equal(0);
await defaultAttributesManager.savePersistentAttributes();
expect(mockPersistenceAdapter.saveCounter).equal(1);
});
}); | the_stack |
import * as vscode from 'vscode';
import * as cfg from '../configuration';
import * as util from '../utility';
import SourceDocument from '../SourceDocument';
import CSymbol from '../CSymbol';
import SubSymbol from '../SubSymbol';
import { ProposedPosition, TargetLocation } from '../ProposedPosition';
import {
Operand, Operator,
EqualOperator, NotEqualOperator,
LessThanOperator, GreaterThanOperator, LessThanOrEqualOperator, GreaterThanOrEqualOperator,
StreamOutputOperator
} from '../Operator';
import { getMatchingHeaderSource, logger } from '../extension';
import { showMultiQuickPick, showSingleQuickPick } from '../QuickPick';
export const title = {
equality: 'Generate Equality Operators',
relational: 'Generate Relational Operators',
streamOutput: 'Generate Stream Output Operator'
};
export const failure = {
noActiveTextEditor: 'No active text editor detected.',
noClassOrStruct: 'No class or struct detected.',
positionNotFound: 'Could not find a position for a new public member function.'
};
export async function generateEqualityOperators(
parentClass?: CSymbol,
classDoc?: SourceDocument
): Promise<boolean | undefined> {
if (!parentClass || !classDoc) {
// Command was called from the command-palette
const editor = vscode.window.activeTextEditor;
if (!editor) {
logger.alertError(failure.noActiveTextEditor);
return;
}
classDoc = new SourceDocument(editor.document);
const symbol = await classDoc.getSymbol(editor.selection.start);
parentClass = symbol?.isClassType() && !symbol.isAnonymous() ? symbol : symbol?.firstNamedParent();
if (!parentClass?.isClassType()) {
logger.alertWarning(failure.noClassOrStruct);
return;
}
}
const p_operands = promptUserForOperands(parentClass, 'Select what you would like to compare in operator==');
const equalPosition = parentClass.findPositionForNewMemberFunction(util.AccessLevel.public);
if (!equalPosition) {
logger.alertError(failure.positionNotFound);
return;
}
const operands = await p_operands;
if (!operands) {
return;
}
const equalOp = new EqualOperator(parentClass, operands);
const notEqualOp = new NotEqualOperator(parentClass);
const targets = await promptUserForDefinitionLocations(
parentClass, classDoc, equalPosition,
'Select where to place the definition of operator==',
'Select where to place the definition of operator!=');
if (!targets) {
return;
}
const notEqualPosition = new ProposedPosition(equalPosition, {
relativeTo: equalPosition.options.relativeTo,
after: true,
nextTo: true,
indent: equalPosition.options.indent
});
const workspaceEdit = new vscode.WorkspaceEdit();
await addNewOperatorToWorkspaceEdit(equalOp, equalPosition, classDoc, targets.first, workspaceEdit);
if (targets.second) {
await addNewOperatorToWorkspaceEdit(
notEqualOp, notEqualPosition, classDoc, targets.second, workspaceEdit, true);
}
return vscode.workspace.applyEdit(workspaceEdit);
}
export async function generateRelationalOperators(
parentClass?: CSymbol,
classDoc?: SourceDocument
): Promise<boolean | undefined> {
if (!parentClass || !classDoc) {
// Command was called from the command-palette
const editor = vscode.window.activeTextEditor;
if (!editor) {
logger.alertError(failure.noActiveTextEditor);
return;
}
classDoc = new SourceDocument(editor.document);
const symbol = await classDoc.getSymbol(editor.selection.start);
parentClass = symbol?.isClassType() && !symbol.isAnonymous() ? symbol : symbol?.firstNamedParent();
if (!parentClass?.isClassType()) {
logger.alertWarning(failure.noClassOrStruct);
return;
}
}
const p_operands = promptUserForOperands(parentClass, 'Select what you would like to compare in operator<');
const lessThanPosition = parentClass.findPositionForNewMemberFunction(util.AccessLevel.public);
if (!lessThanPosition) {
logger.alertError(failure.positionNotFound);
return;
}
const operands = await p_operands;
if (!operands) {
return;
}
const lessThanOp = new LessThanOperator(parentClass, operands);
const greaterThanOp = new GreaterThanOperator(parentClass);
const lessThanOrEqualOp = new LessThanOrEqualOperator(parentClass);
const greaterThanOrEqualOp = new GreaterThanOrEqualOperator(parentClass);
const targets = await promptUserForDefinitionLocations(
parentClass, classDoc, lessThanPosition,
'Select where to place the definition of operator<',
'Select where to place the definitions of operator>, operator<=, and operator>=');
if (!targets) {
return;
}
const nextPosition = new ProposedPosition(lessThanPosition, {
relativeTo: lessThanPosition.options.relativeTo,
after: true,
nextTo: true,
indent: lessThanPosition.options.indent
});
const workspaceEdit = new vscode.WorkspaceEdit();
await addNewOperatorToWorkspaceEdit(lessThanOp, lessThanPosition, classDoc, targets.first, workspaceEdit);
if (targets.second) {
await Promise.all([
addNewOperatorToWorkspaceEdit(
greaterThanOp, nextPosition, classDoc, targets.second, workspaceEdit, true),
addNewOperatorToWorkspaceEdit(
lessThanOrEqualOp, nextPosition, classDoc, targets.second, workspaceEdit, true),
addNewOperatorToWorkspaceEdit(
greaterThanOrEqualOp, nextPosition, classDoc, targets.second, workspaceEdit, true)
]);
}
return vscode.workspace.applyEdit(workspaceEdit);
}
export async function generateStreamOutputOperator(
parentClass?: CSymbol,
classDoc?: SourceDocument
): Promise<boolean | undefined> {
if (!parentClass || !classDoc) {
// Command was called from the command-palette
const editor = vscode.window.activeTextEditor;
if (!editor) {
logger.alertError(failure.noActiveTextEditor);
return;
}
classDoc = new SourceDocument(editor.document);
const symbol = await classDoc.getSymbol(editor.selection.start);
parentClass = symbol?.isClassType() && !symbol.isAnonymous() ? symbol : symbol?.firstNamedParent();
if (!parentClass?.isClassType()) {
logger.alertWarning(failure.noClassOrStruct);
return;
}
}
const p_operands = promptUserForOperands(parentClass, 'Select what you would like to output in operator<<');
const declarationPos = parentClass.findPositionForNewMemberFunction(util.AccessLevel.public);
if (!declarationPos) {
logger.alertError(failure.positionNotFound);
return;
}
const newOstreamIncludePos = getPositionForOstreamInclude(classDoc, declarationPos);
const operands = await p_operands;
if (!operands) {
return;
}
const streamOutputOp = new StreamOutputOperator(parentClass, operands);
const targets = await promptUserForDefinitionLocations(
parentClass, classDoc, declarationPos, 'Select where to place the definition of operator<<');
if (!targets) {
return;
}
const workspaceEdit = new vscode.WorkspaceEdit();
await addNewOperatorToWorkspaceEdit(streamOutputOp, declarationPos, classDoc, targets.first, workspaceEdit);
if (newOstreamIncludePos) {
workspaceEdit.insert(classDoc.uri, newOstreamIncludePos, '#include <ostream>' + classDoc.endOfLine);
}
return vscode.workspace.applyEdit(workspaceEdit);
}
/**
* Returns undefined if the file already includes ostream or iostream.
*/
function getPositionForOstreamInclude(
classDoc: SourceDocument, declarationPos: vscode.Position
): vscode.Position | undefined {
if (!classDoc.includedFiles.some(file => file === 'ostream' || file === 'iostream')) {
return classDoc.findPositionForNewInclude(declarationPos).system;
}
}
interface OperandItem extends vscode.QuickPickItem {
operand: Operand;
}
async function promptUserForOperands(parentClass: CSymbol, prompt: string): Promise<Operand[] | undefined> {
const operands: Operand[] = [...parentClass.baseClasses(), ...parentClass.nonStaticMemberVariables()];
if (operands.length === 0) {
return [];
}
const operandItems: OperandItem[] = [];
operands.forEach(operand => {
if (operand instanceof SubSymbol) {
operandItems.push({
label: '$(symbol-class) ' + operand.name,
description: 'Base class',
operand: operand,
picked: true
});
} else {
operandItems.push({
label: '$(symbol-field) ' + operand.name,
description: util.formatSignature(operand),
operand: operand,
picked: true
});
}
});
const selectedItems = await showMultiQuickPick(operandItems, {
matchOnDescription: true,
title: prompt
});
if (!selectedItems) {
return;
}
const selectedOperands: Operand[] = [];
selectedItems.forEach(item => selectedOperands.push(item.operand));
return selectedOperands;
}
interface DefinitionLocationItem extends vscode.QuickPickItem {
location: cfg.DefinitionLocation;
}
function getDefinitionLocationItems(parentClass: CSymbol, sourceDoc: SourceDocument): DefinitionLocationItem[] {
const items: DefinitionLocationItem[] = [
{ label: 'Inline', location: cfg.DefinitionLocation.Inline },
{ label: 'Current File', location: cfg.DefinitionLocation.CurrentFile }
];
if (sourceDoc.isHeader() && !parentClass.hasUnspecializedTemplate()) {
items.push({ label: 'Source File', location: cfg.DefinitionLocation.SourceFile });
}
return items;
}
interface TargetLocations {
first: TargetLocation;
second?: TargetLocation;
}
async function promptUserForDefinitionLocations(
parentClass: CSymbol,
classDoc: SourceDocument,
declarationPos: ProposedPosition,
firstPrompt: string,
secondPrompt?: string
): Promise<TargetLocations | undefined> {
const firstDefinitionItem = await showSingleQuickPick(
getDefinitionLocationItems(parentClass, classDoc), { title: firstPrompt });
if (!firstDefinitionItem) {
return;
}
const p_secondDefinitionItem = secondPrompt !== undefined
? showSingleQuickPick(getDefinitionLocationItems(parentClass, classDoc), { title: secondPrompt })
: undefined;
const matchingUri = await getMatchingHeaderSource(classDoc.uri);
const firstTargetDoc = (firstDefinitionItem.location === cfg.DefinitionLocation.SourceFile && matchingUri)
? await SourceDocument.open(matchingUri)
: classDoc;
const firstDefinitionPos = (firstDefinitionItem.location === cfg.DefinitionLocation.Inline)
? declarationPos
: await classDoc.findSmartPositionForFunctionDefinition(declarationPos, firstTargetDoc);
const firstTargetLocation = new TargetLocation(firstDefinitionPos, firstTargetDoc);
const secondDefinitionItem = await p_secondDefinitionItem;
if (!secondDefinitionItem) {
return { first: firstTargetLocation };
}
let secondTargetLocation: TargetLocation | undefined;
if (secondDefinitionItem.location === cfg.DefinitionLocation.SourceFile && matchingUri) {
const secondTargetDoc = (firstTargetDoc.uri.fsPath === matchingUri.fsPath)
? firstTargetDoc
: await SourceDocument.open(matchingUri);
const secondDefinitionPos =
await classDoc.findSmartPositionForFunctionDefinition(declarationPos, secondTargetDoc);
secondTargetLocation = new TargetLocation(secondDefinitionPos, secondTargetDoc);
} else {
const secondDefinitionPos = secondDefinitionItem.location === cfg.DefinitionLocation.Inline
? declarationPos
: await classDoc.findSmartPositionForFunctionDefinition(declarationPos);
secondTargetLocation = new TargetLocation(secondDefinitionPos, classDoc);
}
return { first: firstTargetLocation, second: secondTargetLocation };
}
async function addNewOperatorToWorkspaceEdit(
newOperator: Operator,
declarationPos: ProposedPosition,
classDoc: SourceDocument,
target: TargetLocation,
workspaceEdit: vscode.WorkspaceEdit,
skipAccessSpecifierCheck?: boolean
): Promise<void> {
if (target.sourceDoc.fileName === classDoc.fileName && target.position.isEqual(declarationPos)) {
const curlySeparator = (cfg.functionCurlyBraceFormat('cpp', classDoc) === cfg.CurlyBraceFormat.NewLine)
? target.sourceDoc.endOfLine
: ' ';
let formattedInlineDefinition = (newOperator.body.includes('\n'))
? await newOperator.definition(classDoc, declarationPos, curlySeparator)
: newOperator.declaration + ' { ' + newOperator.body + ' }';
if (!skipAccessSpecifierCheck
&& !newOperator.parent?.positionHasAccess(declarationPos, util.AccessLevel.public)) {
formattedInlineDefinition = util.accessSpecifierString(util.AccessLevel.public)
+ classDoc.endOfLine + formattedInlineDefinition;
}
formattedInlineDefinition = declarationPos.formatTextToInsert(formattedInlineDefinition, classDoc);
workspaceEdit.insert(classDoc.uri, declarationPos, formattedInlineDefinition);
} else {
const curlySeparator = (cfg.functionCurlyBraceFormat('cpp', target.sourceDoc) === cfg.CurlyBraceFormat.NewLine)
? target.sourceDoc.endOfLine
: ' ';
let formattedDeclaration = newOperator.declaration + ';';
if (!skipAccessSpecifierCheck
&& !newOperator.parent?.positionHasAccess(declarationPos, util.AccessLevel.public)) {
formattedDeclaration = util.accessSpecifierString(util.AccessLevel.public)
+ classDoc.endOfLine + formattedDeclaration;
}
formattedDeclaration = declarationPos.formatTextToInsert(formattedDeclaration, classDoc);
const definition = await newOperator.definition(target.sourceDoc, target.position, curlySeparator);
const formattedDefinition = target.position.formatTextToInsert(definition, target.sourceDoc);
workspaceEdit.insert(classDoc.uri, declarationPos, formattedDeclaration);
workspaceEdit.insert(target.sourceDoc.uri, target.position, formattedDefinition);
}
} | the_stack |
import React, { useState, useEffect } from 'react'
import { useRouter } from 'next/router'
import { loadStripe } from '@stripe/stripe-js'
import Navigation from '../components/Navigation'
import Footer from '../components/Footer'
import { NOTION_DOCS_URL, NOTION_SUPPORT_URL } from '../constants'
/* Stripe */
const stripeLoader = loadStripe(process.env.STRIPE_KEY!)
type Period = 'ANNUALLY' | 'MONTHLY'
type Plan = 'FREE' | 'PAID'
export const Subscribe = () => {
// Path
const { query } = useRouter()
// Form
const [email, setEmail] = useState('')
const [account, setAccount] = useState('')
const [period, setPeriod] = useState<Period>('ANNUALLY')
const [plan, setPlan] = useState<Plan>('PAID')
const [coupon, setCoupon] = useState<string | undefined>(undefined)
const [agreed, setAgree] = useState(false)
useEffect(() => {
/* Populate the form from the URL. */
if (['FREE', 'PAID'].includes(query.plan as string)) {
setPlan(query.plan as Plan)
}
if (['ANNUALLY', 'MONTHLY'].includes(query.period as string)) {
setPeriod(query.period as Period)
}
if (typeof query.email === 'string') {
setEmail(query.email)
}
if (typeof query.account === 'string') {
setAccount(query.account)
}
if (typeof query.coupon === 'string') {
setCoupon(query.coupon)
}
console.log({ query })
}, [query])
type Fetching =
| { status: 'NOT_REQUESTED' }
| { status: 'LOADING' }
| { status: 'SUCCESS' }
| { status: 'ERR'; message: string }
const [fetching, setFetching] = useState<Fetching>({
status: 'NOT_REQUESTED',
// status: 'ERR',
// message: 'Something went wrong.',
})
/**
* Performs a call.
*/
async function subscribe() {
/* Required values */
if ([email, account].some((val) => val.trim() === '')) {
setFetching({
status: 'ERR',
message: 'You must fill all the required fields.',
})
return
}
/* Terms of Service */
if (!agreed) {
setFetching({
status: 'ERR',
message:
'You forgot to agree with Terms of Service and Privacy Policy.',
})
return
}
/* Fix coupon */
const fixedCoupon = !coupon || coupon?.trim() === '' ? undefined : coupon
// Contact server
setFetching({ status: 'LOADING' })
try {
let body: string
switch (plan) {
case 'FREE': {
body = JSON.stringify({
email,
account,
agreed,
plan: 'FREE',
})
break
}
case 'PAID': {
body = JSON.stringify({
email,
account,
agreed,
plan: 'PAID',
period: period || query.period,
coupon: fixedCoupon,
})
break
}
}
const res = (await fetch(
'https://webhook.label-sync.com/subscribe/session',
{
method: 'POST',
mode: 'cors',
credentials: 'same-origin',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: body,
},
).then((res) => res.json())) as
| { status: 'ok'; plan: 'FREE' }
| { status: 'ok'; plan: 'PAID'; session: string }
| { status: 'err'; message: string }
if (res.status === 'ok') {
setFetching({ status: 'SUCCESS' })
switch (res.plan) {
case 'FREE': {
window.location.href = 'https://github.com/apps/labelsync-manager'
break
}
case 'PAID': {
/* redirect to stripe */
await stripeLoader
.then((stripe) =>
stripe!.redirectToCheckout({
sessionId: res.session,
}),
)
.catch((err) => console.log(err))
break
}
}
} else {
setFetching({ status: 'ERR', message: res.message })
}
} catch (err) {
setFetching({ status: 'ERR', message: err.message })
}
}
return (
<>
<title>Github LabelSync - Subscribe</title>
{/* Navigation */}
<div className="relative bg-gray-80">
<div className="relative pt-6 pb-12 sm:pb-16 md:pb-20 lg:pb-28 xl:pb-32">
<Navigation
links={[
{
label: 'Documentation',
href: NOTION_DOCS_URL,
},
{
label: 'Install',
href: 'https://github.com/apps/labelsync-manager',
},
{
label: 'Support',
href: NOTION_SUPPORT_URL,
},
]}
></Navigation>
</div>
</div>
{/* Form */}
<div className="pt-2 pb-10 lg:pb-24 px-4 overflow-hidden sm:px-6 lg:px-8">
<div className="max-w-xl mx-auto">
{/* Heading */}
<div className="text-center">
<h2 className="text-3xl leading-9 font-extrabold tracking-tight text-gray-900 sm:text-4xl sm:leading-10">
Subscribe to LabelSync
</h2>
<p className="mt-4 text-lg leading-6 text-gray-500">
We'll sign you in the LabelSync database so you can start syncing
labels. If you are purchasing a paid plan we'll redirect you to
our payments provider after you complete the form below. Your
subscription starts once you complete the purchase.
</p>
</div>
{/* Form */}
<div className="mt-12">
<form
action="#"
onSubmit={subscribe}
className="grid grid-cols-1 row-gap-6 sm:grid-cols-2 sm:col-gap-8"
>
{/* Email */}
<div className="sm:col-span-2">
<label
htmlFor="email"
className="block text-sm font-medium leading-5 text-gray-700"
>
Email
</label>
<div className="mt-1 relative rounded-md shadow-sm">
<input
id="email"
type="email"
required
value={email}
onChange={(e) => setEmail(e.target.value)}
className="form-input py-3 px-4 block w-full transition ease-in-out duration-150"
/>
</div>
</div>
{/* Github account */}
<div className="sm:col-span-2">
<label
htmlFor="account"
className="block text-sm font-medium leading-5 text-gray-700"
>
Github Account or Organisation
</label>
<div className="mt-1 relative rounded-md shadow-sm">
<input
required
value={account}
onChange={(e) => setAccount(e.target.value)}
id="account"
className="form-input py-3 px-4 block w-full transition ease-in-out duration-150"
/>
</div>
</div>
{/* Plan */}
<div className="sm:col-span-2">
<label
htmlFor="plan"
className="block text-sm font-medium leading-5 text-gray-700"
>
Subscription Plan
</label>
<div className="mt-1 relative rounded-md shadow-sm">
<select
value={plan}
onChange={(e) => setPlan(e.target.value as Plan)}
aria-label="Plan"
className="form-select relative py-3 px-4 block w-full rounded-md bg-transparent focus:z-10 transition ease-in-out duration-150 sm:text-sm sm:leading-5"
>
<option value="PAID">Paid</option>
<option value="FREE">Free</option>
</select>
</div>
</div>
{/* Period */}
{plan === 'PAID' && (
<div className="sm:col-span-2">
<label
htmlFor="period"
className="block text-sm font-medium leading-5 text-gray-700"
>
Subscription Period
</label>
<div className="mt-1 relative rounded-md shadow-sm">
<select
value={period}
onChange={(e) => setPeriod(e.target.value as Period)}
aria-label="Period"
className="form-select relative py-3 px-4 block w-full rounded-md bg-transparent focus:z-10 transition ease-in-out duration-150 sm:text-sm sm:leading-5"
>
<option value="ANNUALLY">Annualy</option>
<option value="MONTHLY">Monthly</option>
</select>
</div>
</div>
)}
{/* Discount */}
{plan === 'PAID' && (
<div className="sm:col-span-2">
<label
htmlFor="coupon"
className="block text-sm font-medium leading-5 text-gray-700"
>
Discount Coupon
</label>
<div className="mt-1 relative rounded-md shadow-sm">
<input
required
value={coupon}
onChange={(e) => setCoupon(e.target.value)}
id="coupon"
className="form-input py-3 px-4 block w-full transition ease-in-out duration-150"
/>
</div>
</div>
)}
{/* Terms of Use */}
<div className="sm:col-span-2">
<div className="flex items-start">
<div className="flex-shrink-0">
{/* */}
<span
onClick={() => setAgree(!agreed)}
className={
'relative inline-block flex-shrink-0 h-6 w-11 border-2 border-transparent rounded-full cursor-pointer transition-colors ease-in-out duration-200 focus:outline-none focus:shadow-outline ' +
(agreed ? 'bg-green-400' : 'bg-gray-200')
}
>
{/* On: "translate-x-5", Off: "translate-x-0" */}
<span
className={
'inline-block h-5 w-5 rounded-full bg-white shadow transform transition ease-in-out duration-200 ' +
(agreed ? 'translate-x-5' : 'translate-x-0')
}
></span>
</span>
</div>
<div className="ml-3">
<p className="text-base leading-6 text-gray-500">
By selecting this, you agree to the
<a
href="https://www.notion.so/LabelSync-s-Terms-of-Service-and-Privacy-Policy-cea6dddad9294eddb95a61fb361e5d2f"
className="font-medium ml-1 text-gray-700 underline"
>
Privacy Policy and Terms of Service
</a>
.
</p>
</div>
</div>
</div>
{/* Submit */}
<div className="sm:col-span-2 mt-4">
<span className="w-full inline-flex rounded-md shadow-sm">
<button
onClick={subscribe}
type="button"
disabled={fetching.status === 'LOADING'}
className="w-full inline-flex items-center justify-center px-6 py-3 border border-transparent text-base leading-6 font-medium rounded-md text-white bg-green-600 hover:bg-green-500 focus:outline-none focus:border-green-700 focus:shadow-outline-indigo active:bg-green-700 transition ease-in-out duration-150"
>
Subscribe
</button>
</span>
</div>
{/* Errors and messages */}
<div className="sm:col-span-2">
{fetching.status === 'ERR' && (
<div
className="p-2 bg-pink-800 items-center text-pink-100 leading-none rounded-full flex lg:inline-flex"
role="alert"
>
<span className="flex rounded-full bg-pink-500 uppercase px-2 py-1 text-xs font-bold mr-3">
Error
</span>
<span className="font-semibold mr-2 text-left flex-auto">
{fetching.message}
</span>
</div>
)}
</div>
</form>
</div>
</div>
</div>
<Footer></Footer>
</>
)
}
export default Subscribe
/* Sections */ | the_stack |
/*global window: false*/
/*global GameSession: false*/
/*global TurbulenzBridge: false*/
/*global TurbulenzEngine: false*/
/*global Utilities: false*/
/*global MappingTable: false*/
/*global LeaderboardManager: false*/
/*global ServiceRequester: false*/
/*global MultiPlayerSessionManager: false*/
/*global Observer*/
/*global StoreManager: false*/
/*global NotificationsManager: false*/
/*global debug: false*/
interface UserProfile
{
username : string;
displayname : string;
language : string;
country : string;
age : number;
anonymous : boolean;
guest : boolean;
};
interface UserProfileReceivedCB
{
(userProfile: UserProfile): void;
};
/// Called when the user has upgraded from a guest or anonymous
/// account to a full one. This callback does not guarantee that the
/// upgrade complete successfully, so TurbulenzServices should be
/// required for a new UserProfile object to check the updated status
/// of the user.
interface UserUpgradeCB
{
(): void;
}
class CustomMetricEvent
{
key: string;
value: any;
timeOffset: number;
static create() : CustomMetricEvent
{
return new CustomMetricEvent();
}
};
class CustomMetricEventBatch
{
events: CustomMetricEvent[];
push(key: string, value: any)
{
var event = CustomMetricEvent.create();
event.key = key;
event.value = value;
event.timeOffset = TurbulenzEngine.time;
this.events.push(event);
}
length() : number
{
return this.events.length;
}
clear()
{
this.events.length = 0;
}
static create() : CustomMetricEventBatch
{
var batch = new CustomMetricEventBatch();
batch.events = [];
return batch;
}
};
interface ServiceResponse
{
ok : boolean;
msg : string;
data : any;
};
interface ServiceRequestParams
{
url : string;
method : string;
data? : any;
callback : { (response: ServiceResponse,
status: number): void; };
requestHandler : RequestHandler;
neverDiscard? : boolean;
};
interface ServiceErrorCB
{
(errorMsg: string, httpStatus?: number): void;
}
// -----------------------------------------------------------------------------
// ServiceRequester
// -----------------------------------------------------------------------------
class ServiceRequester
{
static locationOrigin : string;
running : boolean;
discardRequests : boolean;
serviceStatusObserver : Observer;
serviceName : string;
onServiceUnavailable : { (service: ServiceRequester, callCtx?: any)
: void; };
onServiceAvailable : { (service: ServiceRequester, callCtx?: any)
: void; };
// make a request if the service is available. Same parameters as an
// Utilities.ajax call with extra argument:
// neverDiscard - Never discard the request. Always queues the request
// for when the service is again available. (Ignores
// server preference)
request(params, serviceAction? : string)
{
// If there is a specific services domain set prefix any relative api urls
var servicesDomain = TurbulenzServices.servicesDomain;
if (servicesDomain)
{
if (params.url.indexOf('http') !== 0)
{
if (params.url[0] === '/')
{
params.url = servicesDomain + params.url;
}
else
{
params.url = servicesDomain + '/' + params.url;
}
}
if (window.location)
{
if (servicesDomain !== ServiceRequester.locationOrigin)
{
params.enableCORSCredentials = true;
}
}
}
// If the bridgeServices are available send to call
if (TurbulenzServices.bridgeServices)
{
//TurbulenzServices.addSignature(dataSpec, url);
var processed = TurbulenzServices.callOnBridge(serviceAction ? serviceAction : params.url, params,
function unpackResponse(response)
{
if (params.callback)
{
params.callback(response, response.status);
}
});
// Processed indicates we are offline and the bridge has fully dealt with the service call
if (processed)
{
return true;
}
}
var discardRequestFn = function discardRequestFn()
{
if (params.callback)
{
params.callback({'ok': false, 'msg': 'Service Unavailable. Discarding request'}, 503);
}
};
var that = this;
var serviceStatusObserver = this.serviceStatusObserver;
var onServiceStatusChange;
onServiceStatusChange = function onServiceStatusChangeFn(running, discardRequest)
{
if (discardRequest)
{
if (!params.neverDiscard)
{
serviceStatusObserver.unsubscribe(onServiceStatusChange);
discardRequestFn();
}
}
else if (running)
{
serviceStatusObserver.unsubscribe(onServiceStatusChange);
that.request(params);
}
};
if (!this.running)
{
if (this.discardRequests && !params.neverDiscard)
{
TurbulenzEngine.setTimeout(discardRequestFn, 0);
return false;
}
// we check waiting so that we don't get into an infinite loop of callbacks
// when a service goes down, then up and then down again before the subscribed
// callbacks have all been called.
if (!params.waiting)
{
params.waiting = true;
serviceStatusObserver.subscribe(onServiceStatusChange);
}
return true;
}
var oldResponseFilter = params.responseFilter;
params.responseFilter = function checkServiceUnavailableFn(callContext, makeRequest, responseJSON, status)
{
if (status === 503)
{
var responseObj = JSON.parse(responseJSON);
var statusObj = responseObj.data;
var discardRequests = (statusObj ? statusObj.discardRequests : true);
that.discardRequests = discardRequests;
if (discardRequests && !params.neverDiscard)
{
discardRequestFn();
}
else
{
serviceStatusObserver.subscribe(onServiceStatusChange);
}
TurbulenzServices.serviceUnavailable(that, callContext);
// An error occurred so return false to avoid calling the success callback
return false;
}
if (status === 403)
{
var responseObj = JSON.parse(responseJSON);
var statusObj = responseObj.data;
if (statusObj && statusObj.invalidGameSession)
{
if (TurbulenzServices.onGameSessionClosed)
{
TurbulenzServices.onGameSessionClosed();
}
else
{
Utilities.log('Game session closed');
}
return false;
}
}
// call the old custom error handler
if (oldResponseFilter)
{
return oldResponseFilter.call(params.requestHandler, callContext, makeRequest, responseJSON, status);
}
return true;
};
Utilities.ajax(params);
return true;
}
static create(serviceName: string, params?): ServiceRequester
{
// If the ServiceRequest locationOrigin hasn't been set yet then set it.
if (typeof(ServiceRequester.locationOrigin) === undefined &&
typeof(window.location) !== undefined)
{
ServiceRequester.locationOrigin = window.location.protocol + '//' + window.location.host;
}
var serviceRequester = new ServiceRequester();
if (!params)
{
params = {};
}
// we assume everything is working at first
serviceRequester.running = true;
serviceRequester.discardRequests = false;
serviceRequester.serviceStatusObserver = Observer.create();
serviceRequester.serviceName = serviceName;
serviceRequester.onServiceUnavailable = params.onServiceUnavailable;
serviceRequester.onServiceAvailable = params.onServiceAvailable;
return serviceRequester;
}
};
//
// TurbulenzServices
//
class TurbulenzServices
{
static onGameSessionClosed: { () : void; };
static multiplayerJoinRequestQueue = {
// A FIFO queue that passes events through to the handler when
// un-paused and buffers up events while paused
argsQueue: [],
/* tslint:disable:no-empty */
handler: function nopFn() {},
/* tslint:enable:no-empty */
context: <any>undefined,
paused: true,
onEvent: function onEventFn(handler, context) {
this.handler = handler;
this.context = context;
},
push: function pushFn(sessionId)
{
var args = [sessionId];
if (this.paused)
{
this.argsQueue.push(args);
}
else
{
this.handler.apply(this.context, args);
}
},
shift: function shiftFn()
{
var args = this.argsQueue.shift();
return args ? args[0] : undefined;
},
clear: function clearFn()
{
this.argsQueue = [];
},
pause: function pauseFn()
{
this.paused = true;
},
resume: function resumeFn()
{
this.paused = false;
while (this.argsQueue.length)
{
this.handler.apply(this.context, this.argsQueue.shift());
if (this.paused)
{
break;
}
}
}
};
static bridgeServices : boolean;
static mode : string;
static servicesDomain : string;
static offline : boolean;
static syncing : boolean;
static available() : boolean
{
return window.gameSlug !== undefined;
}
static responseHandlers: any[]; // TODO
static responseIndex: number;
static addBridgeEvents()
{
var turbulenz = window.Turbulenz;
if (!turbulenz)
{
try
{
turbulenz = window.top.Turbulenz;
}
/* tslint:disable:no-empty */
catch (e)
{
}
/* tslint:enable:no-empty */
}
var turbulenzData = (turbulenz && turbulenz.Data) || {};
var sessionToJoin = turbulenzData.joinMultiplayerSessionId;
var that = this;
var onJoinMultiplayerSession = function onJoinMultiplayerSessionFn(joinMultiplayerSessionId) {
that.multiplayerJoinRequestQueue.push(joinMultiplayerSessionId);
};
var onReceiveConfig = function onReceiveConfigFn(configString) {
var config = <TurbulenzBridgeConfig>(JSON.parse(configString));
if (config.mode)
{
that.mode = config.mode;
}
if (config.joinMultiplayerSessionId)
{
that.multiplayerJoinRequestQueue.push(config.joinMultiplayerSessionId);
}
that.bridgeServices = !!config.bridgeServices;
if (config.servicesDomain)
{
that.servicesDomain = config.servicesDomain;
}
if (config.syncing)
{
that.syncing = true;
}
if (config.offline)
{
that.offline = true;
}
};
// This should go once we have fully moved to the new system
if (sessionToJoin)
{
this.multiplayerJoinRequestQueue.push(sessionToJoin);
}
TurbulenzBridge.setOnMultiplayerSessionToJoin(onJoinMultiplayerSession);
TurbulenzBridge.setOnReceiveConfig(onReceiveConfig);
TurbulenzBridge.triggerRequestConfig();
// Setup framework for asynchronous function calls
this.responseHandlers = [null];
// 0 is reserved value for no registered callback
this.responseIndex = 0;
TurbulenzBridge.on("bridgeservices.response", function (jsondata) { that.routeResponse(jsondata); });
TurbulenzBridge.on("bridgeservices.sync.start", function () { that.syncing = true; });
TurbulenzBridge.on("bridgeservices.sync.end", function () { that.syncing = false; });
TurbulenzBridge.on("bridgeservices.offline.start", function () { that.offline = true; });
TurbulenzBridge.on("bridgeservices.offline.end", function () { that.offline = false; });
}
static callOnBridge(event, data, callback) : boolean
{
var request = {
data: data,
key: undefined
};
if (callback)
{
this.responseIndex += 1;
this.responseHandlers[this.responseIndex] = callback;
request.key = this.responseIndex;
}
var resultJSON = TurbulenzBridge.emit('bridgeservices.' + event,
JSON.stringify(request));
return resultJSON && JSON.parse(resultJSON).fullyProcessed;
}
static addSignature(data, url)
{
var str;
data.requestUrl = url;
str = TurbulenzEngine.encrypt(JSON.stringify(data));
data.str = str;
data.signature = TurbulenzEngine.generateSignature(str);
return data;
}
static routeResponse(jsondata)
{
var response = JSON.parse(jsondata);
var index = response.key || 0;
var callback = this.responseHandlers[index];
if (callback)
{
this.responseHandlers[index] = null;
callback(response.data);
}
}
/* tslint:disable:no-empty */
static defaultErrorCallback : ServiceErrorCB =
function(errorMsg: string, httpStatus?: number)
{
};
static onServiceUnavailable(serviceName: string, callContext?)
{
}
static onServiceAvailable(serviceName: string, callContext?)
{
}
/* tslint:enable:no-empty */
static createGameSession(requestHandler, sessionCreatedFn, errorCallbackFn?, options?)
{
return GameSession.create(requestHandler, sessionCreatedFn,
errorCallbackFn, options);
}
static createMappingTable(requestHandler, gameSession,
tableReceivedFn,
defaultMappingSettings?,
errorCallbackFn?) : MappingTable
{
var mappingTable;
var mappingTableSettings = gameSession && gameSession.mappingTable;
var mappingTableURL;
var mappingTablePrefix;
var assetPrefix;
if (mappingTableSettings)
{
mappingTableURL = mappingTableSettings.mappingTableURL;
mappingTablePrefix = mappingTableSettings.mappingTablePrefix;
assetPrefix = mappingTableSettings.assetPrefix;
}
else if (defaultMappingSettings)
{
mappingTableURL = defaultMappingSettings.mappingTableURL ||
(defaultMappingSettings.mappingTableURL === "" ? "" : "mapping_table.json");
mappingTablePrefix = defaultMappingSettings.mappingTablePrefix ||
(defaultMappingSettings.mappingTablePrefix === "" ? "" : "staticmax/");
assetPrefix = defaultMappingSettings.assetPrefix ||
(defaultMappingSettings.assetPrefix === "" ? "" : "missing/");
}
else
{
mappingTableURL = "mapping_table.json";
mappingTablePrefix = "staticmax/";
assetPrefix = "missing/";
}
// If there is an error, inject any default mapping data and
// inform the caller.
var mappingTableErr = function mappingTableErrFn(msg)
{
var mapping = defaultMappingSettings &&
(defaultMappingSettings.urnMapping || {});
var errorCallback = errorCallbackFn ||
TurbulenzServices.defaultErrorCallback;
mappingTable.setMapping(mapping);
errorCallback(msg);
};
var mappingTableParams : MappingTableParameters = {
mappingTableURL: mappingTableURL,
mappingTablePrefix: mappingTablePrefix,
assetPrefix: assetPrefix,
requestHandler: requestHandler,
onload: tableReceivedFn,
errorCallback: mappingTableErr
};
mappingTable = MappingTable.create(mappingTableParams);
return mappingTable;
}
static createLeaderboardManager(requestHandler, gameSession,
leaderboardMetaReceived?,
errorCallbackFn?) : LeaderboardManager
{
return LeaderboardManager.create(requestHandler, gameSession,
leaderboardMetaReceived,
errorCallbackFn);
}
static createBadgeManager(requestHandler: RequestHandler,
gameSession: GameSession) : BadgeManager
{
return BadgeManager.create(requestHandler, gameSession);
}
static createStoreManager(requestHandler, gameSession, storeMetaReceived?,
errorCallbackFn?) : StoreManager
{
return StoreManager.create(requestHandler,
gameSession,
storeMetaReceived,
errorCallbackFn);
}
static createNotificationsManager(requestHandler, gameSession, successCallbackFn, errorCallbackFn)
: NotificationsManager
{
return NotificationsManager.create(requestHandler, gameSession, successCallbackFn, errorCallbackFn);
}
static createMultiplayerSessionManager(requestHandler, gameSession)
: MultiPlayerSessionManager
{
return MultiPlayerSessionManager.create(requestHandler, gameSession);
}
static createUserProfile(requestHandler: RequestHandler,
profileReceivedFn?: UserProfileReceivedCB,
errorCallbackFn?): UserProfile
{
var userProfile = <UserProfile><any>{};
if (!errorCallbackFn)
{
errorCallbackFn = TurbulenzServices.defaultErrorCallback;
}
var loadUserProfileCallback =
function loadUserProfileCallbackFn(userProfileData)
{
if (userProfileData && userProfileData.ok)
{
userProfileData = userProfileData.data;
var p;
for (p in userProfileData)
{
if (userProfileData.hasOwnProperty(p))
{
userProfile[p] = userProfileData[p];
}
}
}
};
var url = '/api/v1/profiles/user';
// Can't request files from the hard disk using AJAX
if (TurbulenzServices.available())
{
this.getService('profiles').request({
url: url,
method: 'GET',
callback: function createUserProfileAjaxErrorCheck(jsonResponse, status)
{
if (status === 200)
{
loadUserProfileCallback(jsonResponse);
}
else if (errorCallbackFn)
{
errorCallbackFn("TurbulenzServices.createUserProfile error with HTTP status " + status + ": " +
jsonResponse.msg, status);
}
if (profileReceivedFn)
{
profileReceivedFn(userProfile);
}
},
requestHandler: requestHandler
}, 'profile.user');
}
else
{
// No Turbulenz services. Make the error callback
// asynchronously.
TurbulenzEngine.setTimeout(function () {
errorCallbackFn("Error: createUserProfile: Turbulenz Services "
+ "unavailable");
}, 0.001);
}
return userProfile;
}
// This should only be called if UserProfile.anonymous is true.
static upgradeAnonymousUser(upgradeCB: UserUpgradeCB)
{
if (upgradeCB)
{
var onUpgrade = function onUpgradeFn(_signal: string)
{
upgradeCB();
};
TurbulenzBridge.on('user.upgrade.occurred', onUpgrade);
}
TurbulenzBridge.emit('user.upgrade.show');
}
static sendCustomMetricEvent(eventKey: string,
eventValue: any,
requestHandler: RequestHandler,
gameSession: GameSession,
errorCallbackFn?)
{
if (!errorCallbackFn)
{
errorCallbackFn = TurbulenzServices.defaultErrorCallback;
}
// defaultErrorCallback should never be null, so this should
// hold.
debug.assert(errorCallbackFn, "no error callback");
if (!TurbulenzServices.available())
{
errorCallbackFn("TurbulenzServices.sendCustomMetricEvent " +
"failed: Service not available", 0);
return;
}
// Validation
if (('string' !== typeof eventKey) || (0 === eventKey.length))
{
errorCallbackFn("TurbulenzServices.sendCustomMetricEvent " +
"failed: Event key must be a non-empty string",
0);
return;
}
if ('number' !== typeof eventValue ||
isNaN(eventValue) ||
!isFinite(eventValue))
{
if ('[object Array]' !== Object.prototype.toString.call(eventValue))
{
errorCallbackFn("TurbulenzServices.sendCustomMetricEvent " +
"failed: Event value must be a number or " +
"an array of numbers", 0);
return;
}
var i, valuesLength = eventValue.length;
for (i = 0; i < valuesLength; i += 1)
{
if ('number' !== typeof eventValue[i] || isNaN(eventValue[i]) ||
!isFinite(eventValue[i]))
{
errorCallbackFn("TurbulenzServices.sendCustomMetricEvent " +
"failed: Event value array elements must " +
"be numbers", 0);
return;
}
}
}
this.getService('customMetrics').request({
url: '/api/v1/custommetrics/add-event/' + gameSession.gameSlug,
method: 'POST',
data: {
'key': eventKey,
'value': eventValue,
'gameSessionId': gameSession.gameSessionId
},
callback:
function sendCustomMetricEventAjaxErrorCheck(jsonResponse, status)
{
if (status !== 200)
{
errorCallbackFn("TurbulenzServices.sendCustomMetricEvent " +
"error with HTTP status " + status + ": " +
jsonResponse.msg, status);
}
},
requestHandler: requestHandler,
encrypt: true
}, 'custommetrics.addevent');
}
static sendCustomMetricEventBatch(eventBatch: CustomMetricEventBatch,
requestHandler: RequestHandler,
gameSession: GameSession,
errorCallbackFn?)
{
if (!errorCallbackFn)
{
errorCallbackFn = TurbulenzServices.defaultErrorCallback;
}
if (!TurbulenzServices.available())
{
if (errorCallbackFn)
{
errorCallbackFn("TurbulenzServices.sendCustomMetricEventBatch failed: Service not available",
0);
}
return;
}
// Validation
// Test eventBatch is correct type
var currentTime = TurbulenzEngine.time;
var events = eventBatch.events;
var eventIndex;
var numEvents = events.length;
for (eventIndex = 0; eventIndex < numEvents; eventIndex += 1)
{
var eventKey = events[eventIndex].key;
var eventValue = events[eventIndex].value;
var eventTime = events[eventIndex].timeOffset;
if (('string' !== typeof eventKey) || (0 === eventKey.length))
{
if (errorCallbackFn)
{
errorCallbackFn("TurbulenzServices.sendCustomMetricEventBatch failed: Event key must be a" +
" non-empty string", 0);
}
return;
}
if ('number' !== typeof eventValue || isNaN(eventValue) || !isFinite(eventValue))
{
if ('[object Array]' !== Object.prototype.toString.call(eventValue))
{
if (errorCallbackFn)
{
errorCallbackFn("TurbulenzServices.sendCustomMetricEventBatch failed: Event value must be a" +
" number or an array of numbers", 0);
}
return;
}
var i, valuesLength = eventValue.length;
for (i = 0; i < valuesLength; i += 1)
{
if ('number' !== typeof eventValue[i] || isNaN(eventValue[i]) || !isFinite(eventValue[i]))
{
if (errorCallbackFn)
{
errorCallbackFn("TurbulenzServices.sendCustomMetricEventBatch failed: Event value array" +
" elements must be numbers", 0);
}
return;
}
}
}
// Check the time value hasn't been manipulated by the developer
if ('number' !== typeof eventTime || isNaN(eventTime) || !isFinite(eventTime))
{
if (errorCallbackFn)
{
errorCallbackFn("TurbulenzServices.sendCustomMetricEventBatch failed: Event time offset is" +
" corrupted", 0);
}
return;
}
// Update the time offset to be relative to the time we're sending the batch,
// the server will use this to calculate event times
events[eventIndex].timeOffset = eventTime - currentTime;
}
this.getService('customMetrics').request({
url: '/api/v1/custommetrics/add-event-batch/' + gameSession.gameSlug,
method: 'POST',
data: {'batch': events, 'gameSessionId': gameSession.gameSessionId},
callback: function sendCustomMetricEventBatchAjaxErrorCheck(jsonResponse, status)
{
if (status !== 200 && errorCallbackFn)
{
errorCallbackFn("TurbulenzServices.sendCustomMetricEventBatch error with HTTP status " + status +
": " + jsonResponse.msg, status);
}
},
requestHandler: requestHandler,
encrypt: true
}, 'custommetrics.addeventbatch');
}
static services = {};
static waitingServices = {};
static pollingServiceStatus = false;
// milliseconds
static defaultPollInterval = 4000;
static getService(serviceName): ServiceRequester
{
var services = this.services;
if (services.hasOwnProperty(serviceName))
{
return services[serviceName];
}
else
{
var service = ServiceRequester.create(serviceName);
services[serviceName] = service;
return service;
}
}
static serviceUnavailable(service, callContext)
{
var waitingServices = this.waitingServices;
var serviceName = service.serviceName;
if (waitingServices.hasOwnProperty(serviceName))
{
return;
}
waitingServices[serviceName] = service;
service.running = false;
var onServiceUnavailableCallbacks = function onServiceUnavailableCallbacksFn(service)
{
var onServiceUnavailable = callContext.onServiceUnavailable;
if (onServiceUnavailable)
{
onServiceUnavailable.call(service, callContext);
}
if (service.onServiceUnavailable)
{
service.onServiceUnavailable();
}
if (TurbulenzServices.onServiceUnavailable)
{
TurbulenzServices.onServiceUnavailable(service);
}
};
if (service.discardRequests)
{
onServiceUnavailableCallbacks(service);
}
if (this.pollingServiceStatus)
{
return;
}
var that = this;
var pollServiceStatus;
var serviceUrl = '/api/v1/service-status/game/read/' + window.gameSlug;
var servicesStatusCB = function servicesStatusCBFn(responseObj, status)
{
if (status === 200)
{
var statusObj = responseObj.data;
var servicesObj = statusObj.services;
var retry = false;
var serviceName;
for (serviceName in waitingServices)
{
if (waitingServices.hasOwnProperty(serviceName))
{
var service = waitingServices[serviceName];
var serviceData = servicesObj[serviceName];
var serviceRunning = serviceData.running;
service.running = serviceRunning;
service.description = serviceData.description;
if (serviceRunning)
{
if (service.discardRequests)
{
var onServiceAvailable = callContext.onServiceAvailable;
if (onServiceAvailable)
{
onServiceAvailable.call(service, callContext);
}
if (service.onServiceAvailable)
{
service.onServiceAvailable();
}
if (TurbulenzServices.onServiceAvailable)
{
TurbulenzServices.onServiceAvailable(
service);
}
}
delete waitingServices[serviceName];
service.discardRequests = false;
service.serviceStatusObserver.notify(serviceRunning, service.discardRequests);
}
else
{
// if discardRequests has been set
if (serviceData.discardRequests && !service.discardRequests)
{
service.discardRequests = true;
onServiceUnavailableCallbacks(service);
// discard all waiting requests
service.serviceStatusObserver.notify(serviceRunning, service.discardRequests);
}
retry = true;
}
}
}
if (!retry)
{
this.pollingServiceStatus = false;
return;
}
TurbulenzEngine.setTimeout(pollServiceStatus, statusObj.pollInterval * 1000);
}
else
{
TurbulenzEngine.setTimeout(pollServiceStatus, that.defaultPollInterval);
}
};
var params = <any>{
url: serviceUrl,
method: 'GET',
callback: servicesStatusCB
};
var servicesDomain = TurbulenzServices.servicesDomain;
if (servicesDomain)
{
if (serviceUrl.indexOf('http') !== 0)
{
if (serviceUrl[0] === '/')
{
params.url = servicesDomain + serviceUrl;
}
else
{
params.url = servicesDomain + '/' + serviceUrl;
}
}
if (window.location)
{
if (servicesDomain !== ServiceRequester.locationOrigin)
{
params.enableCORSCredentials = true;
}
}
}
pollServiceStatus = function pollServiceStatusFn()
{
Utilities.ajax(params);
};
pollServiceStatus();
}
}
if (typeof TurbulenzBridge !== 'undefined')
{
TurbulenzServices.addBridgeEvents();
}
else
{
debug.log("No TurbulenzBridge object");
} | the_stack |
import React from 'react';
import { action, computed, get, observable, runInAction, set } from 'mobx';
import isString from 'lodash/isString';
import isNumber from 'lodash/isNumber';
import sortBy from 'lodash/sortBy';
import debounce from 'lodash/debounce';
import isNil from 'lodash/isNil';
import isPlainObject from 'lodash/isPlainObject';
import { Config, ConfigKeys, DefaultConfig } from 'choerodon-ui/lib/configure';
import { Size } from 'choerodon-ui/lib/_util/enum';
import { isCalcSize, toPx } from 'choerodon-ui/lib/_util/UnitConvertor';
import CustomizationColumnHeader from './customization-settings/CustomizationColumnHeader';
import CustomizationSettings from './customization-settings';
import DataSet from '../data-set';
import { getColumnKey } from './utils';
import PerformanceTable, { PerformanceTableCustomized, TableProps, TableQueryBarProps, TableRowSelection } from './Table';
import Column, { ColumnProps } from './Column';
import autobind from '../_util/autobind';
import { ModalProps } from '../modal/Modal';
import { $l } from '../locale-context';
import { ColumnLock, TableHeightType } from '../table/enum';
// import isFragment from '../_util/isFragment';
// export function normalizeColumns(
// elements: ReactNode,
// customizedColumns?: object,
// parent: ColumnProps | null = null,
// defaultKey: number[] = [0],
// columnSort = {
// left: 0,
// center: 0,
// right: 0,
// },
// ): any[] {
// const columns: any[] = [];
// const leftColumns: any[] = [];
// const rightColumns: any[] = [];
// const normalizeColumn = (element) => {
// if (isValidElement<any>(element)) {
// const { props, key, type } = element;
// if (isFragment(element)) {
// const { children } = props;
// if (children) {
// Children.forEach(children, normalizeColumn);
// }
// } else if ((type as typeof Column).__PFM_TABLE_COLUMN) {
// const column: any = {
// ...props,
// };
// if (key) {
// column.key = key;
// } else {
// column.key = `anonymous-${defaultKey[0]++}`;
// }
// // tree children todo
// const { children } = column;
// if (!isNil(customizedColumns)) {
// const key = column.dataIndex || children[1].props.dataKey;
// Object.assign(column, customizedColumns[key.toString()]);
// }
// if (parent) {
// column.fixed = parent.fixed;
// }
// if (column.title) {
// const childrenColumns = children[0];
// column.children = [React.cloneElement(childrenColumns, { children: column.title }), children[1]];
// }
//
// if (parent || !column.fixed) {
// if (column.sort === undefined) {
// column.sort = columnSort.center++;
// }
// columns.push(React.cloneElement(element, column));
// } else if (column.fixed === true || column.fixed === 'left') {
// if (column.sort === undefined) {
// column.sort = columnSort.left++;
// }
// leftColumns.push(React.cloneElement(element, column));
// // leftColumns.push(column);
// } else {
// if (column.sort === undefined) {
// column.sort = columnSort.right++;
// }
// rightColumns.push(React.cloneElement(element, column));
// // rightColumns.push(column);
// }
// }
// }
// };
// Children.forEach(elements, normalizeColumn);
// if (parent) {
// return sortBy(columns, ({ props: { sort } }) => sort);
// }
// return [
// ...sortBy(leftColumns, ({ props: { sort } }) => sort),
// ...sortBy(columns, ({ props: { sort } }) => sort),
// ...sortBy(rightColumns, ({ props: { sort } }) => sort),
// ];
// }
export function getRowSelection(props: TableProps): TableRowSelection {
return props.rowSelection || {};
}
export function mergeDefaultProps(
originalColumns: ColumnProps[],
customizedColumns?: object,
parent: ColumnProps | null = null,
defaultKey: number[] = [0],
columnSort = {
left: 0,
center: 0,
right: 0,
},
): any[] {
const columns: any[] = [];
const leftColumns: any[] = [];
const rightColumns: any[] = [];
originalColumns.forEach((column) => {
if (isPlainObject(column)) {
const newColumn: ColumnProps = { ...Column.defaultProps, ...column };
if (isNil(getColumnKey(newColumn))) {
newColumn.key = `anonymous-${defaultKey[0]++}`;
}
const { children } = newColumn;
if (customizedColumns) {
Object.assign(newColumn, customizedColumns[getColumnKey(newColumn).toString()]);
}
if (parent) {
newColumn.fixed = parent.fixed;
}
if (children) {
// @ts-ignore
const childrenColumns = mergeDefaultProps(children, customizedColumns, newColumn, defaultKey);
newColumn.children = childrenColumns;
}
if (parent || !newColumn.fixed) {
if (newColumn.sort === undefined) {
newColumn.sort = columnSort.center;
}
columnSort.center++;
columns.push(newColumn);
} else if (newColumn.fixed === true || newColumn.fixed === ColumnLock.left) {
if (newColumn.sort === undefined) {
newColumn.sort = columnSort.left;
}
columnSort.left++;
leftColumns.push(newColumn);
} else {
if (newColumn.sort === undefined) {
newColumn.sort = columnSort.right;
}
columnSort.right++;
rightColumns.push(newColumn);
}
}
}, []);
if (parent) {
return sortBy(columns, ({ sort }) => sort);
}
return [
...sortBy(leftColumns, ({ sort }) => sort),
...sortBy(columns, ({ sort }) => sort),
...sortBy(rightColumns, ({ sort }) => sort),
];
}
export interface CheckboxPropsCache {
[key: string]: any;
}
export default class TableStore {
node: PerformanceTable;
searchText: string;
highlightRowIndexs: number[] = [];
originalChildren: any[];
checkboxPropsCache: CheckboxPropsCache = {};
selectionDirty?: boolean;
@observable props: any;
@observable originalColumns: ColumnProps[];
@observable customizedActiveKey: string[];
@observable tempCustomized: PerformanceTableCustomized;
@observable customized: PerformanceTableCustomized;
@observable totalHeight?: number;
@observable height?: number;
@observable loading?: boolean;
@observable rowZIndex?: number[];
@observable selectedRowKeys: string[] | number[];
get queryBar(): TableQueryBarProps | false | undefined {
return this.node.props.queryBar;
}
/**
* 表头支持编辑
*/
@computed
get columnTitleEditable(): boolean {
if ('columnTitleEditable' in this.node.props) {
return this.node.props.columnTitleEditable!;
}
return this.getConfig('performanceTableColumnTitleEditable') === true;
}
get dataSet(): DataSet | undefined {
const { queryBar } = this;
if (queryBar) {
return queryBar.dataSet;
}
}
// @computed
// get selectedRowKeys(): string[] {
// return this.node.props.queryBar?.dataSet;
// }
async loadCustomized() {
const { customizedCode } = this.node.props;
if (this.customizable && customizedCode) {
const tableCustomizedLoad = this.getConfig('tableCustomizedLoad') || this.getConfig('customizedLoad');
runInAction(() => {
this.loading = true;
});
try {
const customized: PerformanceTableCustomized | undefined | null = await tableCustomizedLoad(customizedCode, 'PerformanceTable');
runInAction(() => {
this.customized = { columns: {}, ...customized };
});
} finally {
runInAction(() => {
this.loading = false;
});
}
}
}
@action
updateProps(props, node) {
this.node = node;
this.originalColumns = props.columns;
this.originalChildren = props.children;
if (this.customizable && props.columns) {
this.loadCustomized().then(this.handleLoadCustomized);
}
}
@computed
get prefixCls() {
const { classPrefix } = this.node.props;
return classPrefix;
}
@computed
get proPrefixCls() {
return this.node.context.getProPrefixCls('table');
}
@computed
get columnHideable(): boolean {
if ('columnHideable' in this.node.props) {
return this.node.props.columnHideable;
}
return this.getConfig('performanceTableColumnHideable') !== false;
}
@computed
get customizable(): boolean | undefined {
const { customizedCode } = this.node.props;
if (customizedCode && (this.columnTitleEditable || this.columnDraggable || this.columnHideable)) {
if ('customizable' in this.node.props) {
return this.node.props.customizable;
}
return this.getConfig('performanceTableCustomizable') || this.node.context.getCustomizable('PerformanceTable');
}
return false;
}
@computed
get heightType(): TableHeightType {
const tempHeightType = get(this.tempCustomized, 'heightType');
if (tempHeightType !== undefined) {
return tempHeightType;
}
const { heightType } = this.customized;
if (heightType !== undefined) {
return heightType;
}
return this.originalHeightType;
}
@computed
get originalHeightType(): TableHeightType {
const { height, autoHeight } = this.node.props;
if (autoHeight) {
return TableHeightType.flex;
}
if (height) {
if (isString(height) && isCalcSize(height)) {
return TableHeightType.flex;
}
if (isNumber(toPx(height))) {
return TableHeightType.fixed;
}
}
return TableHeightType.auto;
}
@autobind
@action
openCustomizationModal(modal) {
const { customizedCode } = this.node.props;
const modalProps: ModalProps = {
drawer: true,
size: Size.small,
title: $l('Table', 'customization_settings'),
children: <CustomizationSettings />,
bodyStyle: {
overflow: 'hidden auto',
padding: 0,
},
};
if (customizedCode) {
modalProps.okText = $l('Table', 'save_button');
}
modal.open(modalProps);
}
@autobind
customizedColumnHeader() {
return <CustomizationColumnHeader onHeaderClick={this.openCustomizationModal} />;
}
@action
initColumns() {
const { customized, customizable } = this;
const { columns = [] } = this.node.props;
const customizedColumns = customizable ? customized.columns : undefined;
this.originalColumns = mergeDefaultProps(columns, customizedColumns);
this.node._cacheCells = null;
this.node.forceUpdate();
}
@autobind
@action
handleLoadCustomized() {
this.initColumns();
}
@action
changeCustomizedColumnValue(columnKey: string, value: object) {
const { customized: { columns } } = this;
const oldCustomized = get(columns, columnKey);
set(columns, columnKey, {
...oldCustomized,
...value,
});
this.saveCustomizedDebounce();
}
@action
saveCustomized(customized?: PerformanceTableCustomized | null) {
if (this.customizable) {
const { customizedCode } = this.node.props;
if (customized) {
this.customized = customized;
}
this.node.forceUpdate();
if (customizedCode) {
const tableCustomizedSave = this.getConfig('tableCustomizedSave') || this.getConfig('customizedSave');
tableCustomizedSave(customizedCode, this.customized, 'PerformanceTable');
}
}
};
saveCustomizedDebounce = debounce(this.saveCustomized, 1000);
@computed
get columnDraggable(): boolean {
if ('columnDraggable' in this.node.props) {
return this.node.props.columnDraggable!;
}
return this.getConfig('performanceTableColumnDraggable') === true;
}
setCheckboxPropsCache = (cache: CheckboxPropsCache) => this.checkboxPropsCache = cache;
getConfig<T extends ConfigKeys>(key: T): T extends keyof DefaultConfig ? DefaultConfig[T] : Config[T] {
return this.node.context.getConfig(key);
}
constructor(node: PerformanceTable) {
runInAction(() => {
this.node = node;
this.rowZIndex = [];
this.customizedActiveKey = ['columns'];
this.tempCustomized = { columns: {} };
this.customized = { columns: {} };
this.selectedRowKeys = getRowSelection(this.node.props).selectedRowKeys || [];
this.selectionDirty = false;
if (this.customizable) {
this.loadCustomized().then(this.handleLoadCustomized);
}
});
}
} | the_stack |
import * as vd from "virtual-dom";
import UnitBezier from "@mapbox/unitbezier";
import {
combineLatest as observableCombineLatest,
Observable,
Subject,
} from "rxjs";
import {
distinctUntilChanged,
map,
scan,
skip,
switchMap,
takeWhile,
} from "rxjs/operators";
import * as Geo from "../../geo/Geo";
import { Component } from "../Component";
import { BearingConfiguration } from "../interfaces/BearingConfiguration";
import { Spatial } from "../../geo/Spatial";
import { Transform } from "../../geo/Transform";
import { ViewportCoords } from "../../geo/ViewportCoords";
import { Image } from "../../graph/Image";
import { RenderCamera } from "../../render/RenderCamera";
import { ViewportSize } from "../../render/interfaces/ViewportSize";
import { VirtualNodeHash } from "../../render/interfaces/VirtualNodeHash";
import { AnimationFrame } from "../../state/interfaces/AnimationFrame";
import { ComponentSize } from "../util/ComponentSize";
import { Container } from "../../viewer/Container";
import { Navigator } from "../../viewer/Navigator";
import { isSpherical } from "../../geo/Geo";
import { ComponentName } from "../ComponentName";
type ImageFov = [number, number];
type ImageBearingFov = [number, number, number];
type ImageFovState = {
alpha: number,
curr: ImageFov,
prev: ImageFov,
};
interface ImageFovOperation {
(state: ImageFovState): ImageFovState;
}
/**
* @class BearingComponent
*
* @classdesc Component for indicating bearing and field of view.
*
* @example
* ```js
* var viewer = new Viewer({ ... });
* var bearingComponent = viewer.getComponent("bearing");
* bearingComponent.configure({ size: ComponentSize.Small });
* ```
*/
export class BearingComponent extends Component<BearingConfiguration> {
public static componentName: ComponentName = "bearing";
private _spatial: Spatial;
private _viewportCoords: ViewportCoords;
private _svgNamespace: string;
private _distinctThreshold: number;
private _animationSpeed: number;
private _unitBezier: UnitBezier;
/** @ignore */
constructor(name: string, container: Container, navigator: Navigator) {
super(name, container, navigator);
this._spatial = new Spatial();
this._viewportCoords = new ViewportCoords();
this._svgNamespace = "http://www.w3.org/2000/svg";
this._distinctThreshold = Math.PI / 360;
this._animationSpeed = 0.075;
this._unitBezier = new UnitBezier(0.74, 0.67, 0.38, 0.96);
}
protected _activate(): void {
const subs = this._subscriptions;
const cameraBearingFov$ =
this._container.renderService.renderCamera$.pipe(
map(
(rc: RenderCamera): [number, number] => {
let vFov: number = this._spatial.degToRad(rc.perspective.fov);
let hFov: number = rc.perspective.aspect === Number.POSITIVE_INFINITY ?
Math.PI :
Math.atan(rc.perspective.aspect * Math.tan(0.5 * vFov)) * 2;
return [this._spatial.azimuthalToBearing(rc.rotation.phi), hFov];
}),
distinctUntilChanged(
(a1: [number, number], a2: [number, number]): boolean => {
return Math.abs(a2[0] - a1[0]) < this._distinctThreshold &&
Math.abs(a2[1] - a1[1]) < this._distinctThreshold;
}));
const imageFov$ = observableCombineLatest(
this._navigator.stateService.currentState$.pipe(
distinctUntilChanged(
undefined,
(frame: AnimationFrame): string => {
return frame.state.currentImage.id;
})),
this._navigator.panService.panImages$).pipe(
map(
([frame, panImages]:
[
AnimationFrame,
[
Image,
Transform,
number][],
])
: ImageFov => {
const image: Image = frame.state.currentImage;
const transform: Transform = frame.state.currentTransform;
if (isSpherical(image.cameraType)) {
return [Math.PI, Math.PI];
}
const currentProjectedPoints =
this._computeProjectedPoints(transform);
const hFov = this._spatial
.degToRad(
this._computeHorizontalFov(
currentProjectedPoints));
let hFovLeft: number = hFov / 2;
let hFovRight: number = hFov / 2;
for (const [n, , f] of panImages) {
const diff: number = this._spatial.wrap(n.compassAngle - image.compassAngle, -180, 180);
if (diff < 0) {
hFovLeft = this._spatial.degToRad(Math.abs(diff)) + f / 2;
} else {
hFovRight = this._spatial.degToRad(Math.abs(diff)) + f / 2;
}
}
return [hFovLeft, hFovRight];
}),
distinctUntilChanged(
(
[hFovLeft1, hFovRight1]: ImageFov,
[hFovLeft2, hFovRight2]: ImageFov): boolean => {
return Math.abs(hFovLeft2 - hFovLeft1) < this._distinctThreshold &&
Math.abs(hFovRight2 - hFovRight1) < this._distinctThreshold;
}));
const offset$ = observableCombineLatest(
this._navigator.stateService.currentState$.pipe(
distinctUntilChanged(
undefined,
(frame: AnimationFrame): string => {
return frame.state.currentImage.id;
})),
this._container.renderService.bearing$).pipe(
map(
([frame, bearing]: [AnimationFrame, number]): number => {
const offset: number = this._spatial.degToRad(frame.state.currentImage.compassAngle - bearing);
return offset;
}));
const imageFovOperation$ = new Subject<ImageFovOperation>();
const smoothImageFov$ = imageFovOperation$.pipe(
scan(
(state: ImageFovState, operation: ImageFovOperation): ImageFovState => {
return operation(state);
},
{ alpha: 0, curr: [0, 0, 0], prev: [0, 0, 0] }),
map(
(state: ImageFovState): ImageFov => {
const alpha: number = this._unitBezier.solve(state.alpha);
const curr: ImageFov = state.curr;
const prev: ImageFov = state.prev;
return [
this._interpolate(prev[0], curr[0], alpha),
this._interpolate(prev[1], curr[1], alpha),
];
}));
subs.push(imageFov$.pipe(
map(
(nbf: ImageFov): ImageFovOperation => {
return (state: ImageFovState): ImageFovState => {
const a: number = this._unitBezier.solve(state.alpha);
const c: ImageFov = state.curr;
const p: ImageFov = state.prev;
const prev: ImageFov = [
this._interpolate(p[0], c[0], a),
this._interpolate(p[1], c[1], a),
];
const curr: ImageFov = <ImageFov>nbf.slice();
return {
alpha: 0,
curr: curr,
prev: prev,
};
};
}))
.subscribe(imageFovOperation$));
subs.push(imageFov$.pipe(
switchMap(
(): Observable<number> => {
return this._container.renderService.renderCameraFrame$.pipe(
skip(1),
scan<RenderCamera, number>(
(alpha: number): number => {
return alpha + this._animationSpeed;
},
0),
takeWhile(
(alpha: number): boolean => {
return alpha <= 1 + this._animationSpeed;
}),
map(
(alpha: number): number => {
return Math.min(alpha, 1);
}));
}),
map(
(alpha: number): ImageFovOperation => {
return (nbfState: ImageFovState): ImageFovState => {
return {
alpha: alpha,
curr: <ImageFov>nbfState.curr.slice(),
prev: <ImageFov>nbfState.prev.slice(),
};
};
}))
.subscribe(imageFovOperation$));
const imageBearingFov$ = observableCombineLatest(
offset$,
smoothImageFov$).pipe(
map(
([offset, fov]: [number, ImageFov]): ImageBearingFov => {
return [offset, fov[0], fov[1]];
}));
subs.push(observableCombineLatest(
cameraBearingFov$,
imageBearingFov$,
this._configuration$,
this._container.renderService.size$).pipe(
map(
([[cb, cf], [no, nfl, nfr], configuration, size]:
[[number, number], [number, number, number], BearingConfiguration, ViewportSize]): VirtualNodeHash => {
const background: vd.VNode = this._createBackground(cb);
const fovIndicator: vd.VNode = this._createFovIndicator(nfl, nfr, no);
const north: vd.VNode = this._createNorth(cb);
const cameraSector: vd.VNode = this._createCircleSectorCompass(
this._createCircleSector(Math.max(Math.PI / 20, cf), "#FFF"));
const compact: string = configuration.size === ComponentSize.Small ||
configuration.size === ComponentSize.Automatic && size.width < 640 ?
".mapillary-bearing-compact" : "";
return {
name: this._name,
vNode: vd.h(
"div.mapillary-bearing-indicator-container" + compact,
{ oncontextmenu: (event: MouseEvent): void => { event.preventDefault(); } },
[
background,
fovIndicator,
north,
cameraSector,
]),
};
}))
.subscribe(this._container.domRenderer.render$));
}
protected _deactivate(): void {
this._subscriptions.unsubscribe();
}
protected _getDefaultConfiguration(): BearingConfiguration {
return { size: ComponentSize.Automatic };
}
private _createFovIndicator(fovLeft: number, fovRigth: number, offset: number): vd.VNode {
const arc: vd.VNode = this._createFovArc(fovLeft, fovRigth);
const group: vd.VNode =
vd.h(
"g",
{
attributes: { transform: "translate(18,18)" },
namespace: this._svgNamespace,
},
[arc]);
const svg: vd.VNode =
vd.h(
"svg",
{
attributes: { viewBox: "0 0 36 36" },
namespace: this._svgNamespace,
style: {
height: "36px",
left: "2px",
position: "absolute",
top: "2px",
transform: `rotateZ(${this._spatial.radToDeg(offset)}deg)`,
width: "36px",
},
},
[group]);
return svg;
}
private _createFovArc(fovLeft: number, fovRigth: number): vd.VNode {
const radius: number = 16.75;
const strokeWidth: number = 2.5;
const fov: number = fovLeft + fovRigth;
if (fov > 2 * Math.PI - Math.PI / 90) {
return vd.h(
"circle",
{
attributes: {
cx: "0",
cy: "0",
"fill-opacity": "0",
r: `${radius}`,
stroke: "#FFF",
"stroke-width":
`${strokeWidth}`,
},
namespace: this._svgNamespace,
},
[]);
}
let arcStart: number = -Math.PI / 2 - fovLeft;
let arcEnd: number = arcStart + fov;
let startX: number = radius * Math.cos(arcStart);
let startY: number = radius * Math.sin(arcStart);
let endX: number = radius * Math.cos(arcEnd);
let endY: number = radius * Math.sin(arcEnd);
let largeArc: number = fov >= Math.PI ? 1 : 0;
let description: string = `M ${startX} ${startY} A ${radius} ${radius} 0 ${largeArc} 1 ${endX} ${endY}`;
return vd.h(
"path",
{
attributes: {
d: description,
"fill-opacity": "0",
stroke: "#FFF",
"stroke-width": `${strokeWidth}`,
},
namespace: this._svgNamespace,
},
[]);
}
private _createCircleSectorCompass(cameraSector: vd.VNode): vd.VNode {
let group: vd.VNode =
vd.h(
"g",
{
attributes: { transform: "translate(1,1)" },
namespace: this._svgNamespace,
},
[cameraSector]);
let svg: vd.VNode =
vd.h(
"svg",
{
attributes: { viewBox: "0 0 2 2" },
namespace: this._svgNamespace,
style: {
height: "26px",
left: "7px",
position: "absolute",
top: "7px",
width: "26px",
},
},
[group]);
return svg;
}
private _createCircleSector(fov: number, fill: string): vd.VNode {
if (fov > 2 * Math.PI - Math.PI / 90) {
return vd.h(
"circle",
{
attributes: { cx: "0", cy: "0", fill: fill, r: "1" },
namespace: this._svgNamespace,
},
[]);
}
let arcStart: number = -Math.PI / 2 - fov / 2;
let arcEnd: number = arcStart + fov;
let startX: number = Math.cos(arcStart);
let startY: number = Math.sin(arcStart);
let endX: number = Math.cos(arcEnd);
let endY: number = Math.sin(arcEnd);
let largeArc: number = fov >= Math.PI ? 1 : 0;
let description: string = `M 0 0 ${startX} ${startY} A 1 1 0 ${largeArc} 1 ${endX} ${endY}`;
return vd.h(
"path",
{
attributes: { d: description, fill: fill },
namespace: this._svgNamespace,
},
[]);
}
private _createNorth(bearing: number): vd.VNode {
const north: vd.VNode = vd.h("div.mapillary-bearing-north", []);
const container: vd.VNode = vd.h(
"div.mapillary-bearing-north-container",
{ style: { transform: `rotateZ(${this._spatial.radToDeg(-bearing)}deg)` } },
[north]);
return container;
}
private _createBackground(bearing: number): vd.VNode {
return vd.h(
"div.mapillary-bearing-indicator-background",
{ style: { transform: `rotateZ(${this._spatial.radToDeg(-bearing)}deg)` } },
[
vd.h("div.mapillary-bearing-indicator-background-circle", []),
vd.h(
"div.mapillary-bearing-indicator-background-arrow-container",
[
vd.h("div.mapillary-bearing-indicator-background-arrow", []),
]),
]);
}
private _computeProjectedPoints(transform: Transform): number[][] {
const vertices: number[][] = [[1, 0]];
const directions: number[][] = [[0, 0.5]];
const pointsPerLine: number = 12;
return Geo.computeProjectedPoints(transform, vertices, directions, pointsPerLine, this._viewportCoords);
}
private _computeHorizontalFov(projectedPoints: number[][]): number {
const fovs: number[] = projectedPoints
.map(
(projectedPoint: number[]): number => {
return this._coordToFov(projectedPoint[0]);
});
const fov: number = Math.min(...fovs);
return fov;
}
private _coordToFov(x: number): number {
return this._spatial.radToDeg(2 * Math.atan(x));
}
private _interpolate(x1: number, x2: number, alpha: number): number {
return (1 - alpha) * x1 + alpha * x2;
}
} | the_stack |
import { Credentials as AWSCredentials } from "@aws-sdk/types";
import {
ChimeClient,
ListChannelMessagesCommand,
SendChannelMessageCommand,
RedactChannelMessageCommand,
GetMessagingSessionEndpointCommand,
ChannelMessageSummary,
ChannelMembership,
Identity,
} from "@aws-sdk/client-chime";
import * as Sentry from "@sentry/react";
//import * as Chime from "aws-sdk/clients/chime";
//import * as AWS from "aws-sdk/global";
import dayjs from "dayjs";
import { ChimeSigV4Null } from "./polyfill/chimesigv4";
import { ChimeV4MessagingSession } from "./polyfill/chimesession";
import Message from "amazon-chime-sdk-js/build/message/Message";
import ConsoleLogger from "amazon-chime-sdk-js/build/logger/ConsoleLogger";
import LogLevel from "amazon-chime-sdk-js/build/logger/LogLevel";
import MessagingSessionConfiguration from "amazon-chime-sdk-js/build/messagingsession/MessagingSessionConfiguration";
import type { DefaultMessagingSession } from "amazon-chime-sdk-js";
import { ChannelArn, GetChatSessionResponse, ChatMessage, ChatAdminControl, ChatSender, ChatSenderFlags } from "./Api";
import { makeWeakCallback } from "./weakcallback";
// https://docs.aws.amazon.com/chime/latest/APIReference/API_ChannelMessage.html
// ChannelMessageSummary & {ChannelArn + Persistence}
interface ChimeChannelMessage extends ChannelMessageSummary {
ChannelArn: ChannelArn;
}
export const ADMIN_NAME = "RubyKaigi";
export type ChatStatus = "INIT" | "READY" | "CONNECTING" | "CONNECT_ERROR" | "CONNECTED" | "SHUTTING_DOWN";
export type ChatUpdateKind =
| "CREATE_CHANNEL_MESSAGE"
| "UPDATE_CHANNEL_MESSAGE"
| "DELETE_CHANNEL_MESSAGE"
| "REDACT_CHANNEL_MESSAGE"
| "CREATE_CHANNEL_MEMBERSHIP"
| "DELETE_CHANNEL_MEMBERSHIP";
export interface ChatUpdate {
kind: ChatUpdateKind;
message?: ChatMessage;
member?: Identity;
}
interface AdminMessage {
message?: string;
control?: ChatAdminControl;
}
export class ChatSession {
public status: ChatStatus;
public error: Error | null;
sessionData: GetChatSessionResponse | null;
sessionDataEpoch: number;
sessionDataEpochConnected: number | null;
adminArn?: string;
chime?: ChimeClient;
messagingSession: DefaultMessagingSession | null;
statusSubscribers: Array<(status: ChatStatus, error: Error | null) => void>;
messageSubscribers: Map<ChannelArn, Array<(update: ChatUpdate) => void>>;
constructor() {
this.status = "INIT";
this.error = null;
this.sessionData = null;
this.sessionDataEpoch = 0;
this.sessionDataEpochConnected = null;
this.messagingSession = null;
this.statusSubscribers = [];
this.messageSubscribers = new Map();
}
// Note: Updated session data will be used for any reconnections
public setSessionData(sessionData: GetChatSessionResponse) {
console.log("ChatSession: updated sessionData", sessionData);
this.sessionData = sessionData;
this.adminArn = sessionData.app_user_arn;
this.sessionDataEpoch++;
this.generateChimeClient();
//console.log({ sessionData, sessionDataEpoch: this.sessionDataEpoch });
if (this.sessionDataEpoch === 1) this.updateStatus("READY");
}
getSelfArn(): string | undefined {
return this.sessionData?.user_arn;
}
public subscribeStatus(callback: (status: ChatStatus, error: Error | null) => void) {
const cb = makeWeakCallback(callback);
this.statusSubscribers.push(cb);
return () => {
this.statusSubscribers = this.statusSubscribers.filter((v) => v !== cb);
};
}
public subscribeMessageUpdate(channel: ChannelArn, callback: (update: ChatUpdate) => void) {
const cb = makeWeakCallback(callback);
if (!this.messageSubscribers.has(channel)) this.messageSubscribers.set(channel, []);
this.messageSubscribers.get(channel)!.push(cb);
console.log("subs", channel, this.messageSubscribers.get(channel));
return () => {
const newSubs = this.messageSubscribers.get(channel)!.filter((v) => v !== cb);
if (newSubs) this.messageSubscribers.set(channel, newSubs);
};
}
// Returns last 50 messages (descending order based on time created)
public async getHistory(channel: ChannelArn) {
if (!this.chime) throw "cannot retrieve history without session data";
if (!this.sessionData) throw "cannot retrieve history without session data";
const resp = await this.chime.send(
new ListChannelMessagesCommand({
ChimeBearer: this.sessionData.user_arn,
ChannelArn: channel,
SortOrder: "DESCENDING",
MaxResults: 50,
}),
);
const updates = (resp.ChannelMessages ?? []).map((v) => this.mapChannelMessage(channel, v));
return updates.filter((v): v is ChatMessage => !!v);
}
public async postMessage(channel: ChannelArn, content: string) {
if (!this.chime) throw "cannot post without session data";
if (!this.sessionData) throw "cannot post without session data";
const resp = await this.chime.send(
new SendChannelMessageCommand({
ChimeBearer: this.sessionData.user_arn,
ChannelArn: channel,
Content: content,
Type: "STANDARD",
Persistence: "PERSISTENT",
}),
);
return resp.MessageId;
}
public async redactMessage(channel: ChannelArn, id: string) {
if (!this.chime) throw "cannot perform without session data";
if (!this.sessionData) throw "cannot perofmr without session data";
await this.chime.send(
new RedactChannelMessageCommand({
ChimeBearer: this.sessionData.user_arn,
ChannelArn: channel,
MessageId: id,
}),
);
return true;
}
// Returns promise that is resolved after connection attempt has been initiated
public async connect() {
if (!this.sessionData || !this.chime) throw "cannot initiate connection without session data";
if (this.status !== "READY" && this.status !== "SHUTTING_DOWN") throw "cannot connect at this moment";
this.updateStatus("CONNECTING");
this.sessionDataEpochConnected = this.sessionDataEpoch;
const sessionData = this.sessionData;
try {
const logger = new ConsoleLogger("SDK", LogLevel.INFO);
const endpoint = await this.chime.send(new GetMessagingSessionEndpointCommand({}));
const config = new MessagingSessionConfiguration(
sessionData.user_arn,
null, // generate session id on SDK
endpoint.Endpoint!.Url!,
null, //new Chime({ region: "us-east-1", credentials: new AWS.Credentials(this.buildAwsCredentials()) }),
null, //AWS,
);
const sigv4 = new ChimeSigV4Null(this.buildAwsCredentials());
this.messagingSession = new ChimeV4MessagingSession(config, logger, undefined, undefined, sigv4);
//this.messagingSession = new DefaultMessagingSession(config, logger);
this.messagingSession.addObserver({
messagingSessionDidStart: this.onStart.bind(this),
messagingSessionDidStartConnecting: this.onConnecting.bind(this),
messagingSessionDidStop: this.onStop.bind(this),
messagingSessionDidReceiveMessage: this.onMessage.bind(this),
});
this.messagingSession.start();
} catch (e) {
this.updateStatus("CONNECT_ERROR", e);
}
}
public disconnect() {
if (!this.messagingSession) return;
this.updateStatus("SHUTTING_DOWN");
this.messagingSession.stop();
}
updateStatus(status: ChatStatus, error?: Error | null) {
this.status = status;
if (error !== undefined) this.error = error;
this.statusSubscribers = this.statusSubscribers.filter((fn) => fn(this.status, this.error));
}
buildAwsCredentials(): AWSCredentials {
if (!this.sessionData) throw "cannot build credentials without session data";
return {
accessKeyId: this.sessionData.aws_credentials.access_key_id,
secretAccessKey: this.sessionData.aws_credentials.secret_access_key,
sessionToken: this.sessionData.aws_credentials.session_token,
expiration: new Date(this.sessionData.expiry * 1000),
};
}
generateChimeClient() {
this.chime = new ChimeClient({
region: "us-east-1",
credentials: this.buildAwsCredentials(),
});
}
onStart() {
this.updateStatus("CONNECTED", null);
}
onConnecting(reconnecting: boolean) {
if (reconnecting && this.sessionDataEpoch !== this.sessionDataEpochConnected) {
this.disconnect();
this.connect();
}
const e = reconnecting ? new Error("Reconnecting...") : null;
this.updateStatus("CONNECTING", e);
}
// Note: CloseEvent given by WebSocket, but SDK ensures callback called only on explicit close action
onStop(_e: CloseEvent) {
if (this.status === "SHUTTING_DOWN") this.updateStatus("READY", null);
}
onMessage(message: Message) {
try {
const messageType = message.headers["x-amz-chime-event-type"];
const record = JSON.parse(message.payload);
console.log("Incoming Message", message);
// https://docs.aws.amazon.com/chime/latest/dg/websockets.html#receive-messages
switch (messageType) {
case "CREATE_CHANNEL_MESSAGE":
case "REDACT_CHANNEL_MESSAGE":
case "UPDATE_CHANNEL_MESSAGE":
case "DELETE_CHANNEL_MESSAGE":
// https://docs.aws.amazon.com/chime/latest/APIReference/API_ChannelMessage.html
const channelMessage = record as ChimeChannelMessage;
this.onChannelMessage(messageType, channelMessage);
break;
case "CREATE_CHANNEL_MEMBERSHIP":
case "DELETE_CHANNEL_MEMBERSHIP":
const channelMembership = record as ChannelMembership;
this.onChannelMembershipEvent(messageType, channelMembership);
break;
default:
console.log(`Ignoring messageType=${messageType}`);
}
} catch (e) {
console.error("Error while handling message", e);
Sentry.captureException(e);
}
}
onChannelMessage(kind: ChatUpdateKind, message: ChimeChannelMessage) {
if (message.Type !== "STANDARD") {
console.warn("Ignoring message.Type!=STANDARD", { kind, message });
return;
}
if (!message.ChannelArn) {
console.warn("Ignoring !message.ChannelArn", { kind, message });
return;
}
const channel = message.ChannelArn;
const chatMessage = this.mapChannelMessage(channel, message);
if (!chatMessage) return;
const update = { message: chatMessage, kind };
const subs = this.messageSubscribers.get(channel);
console.log("Publishing message update", { channel, update, subs });
if (subs) {
this.messageSubscribers.set(
channel,
subs.filter((v) => v(update)),
);
}
}
mapChannelMessage(channel: ChannelArn, message: ChannelMessageSummary) {
if (!message.MessageId) {
console.warn("message missing ID", channel, message);
return null;
}
if (!message.Content && !message.Redacted) {
console.warn("message missing content", channel, message);
return null;
}
if (!message.Sender || !message.Sender.Arn || !message.Sender.Name) {
console.warn("message missing sender", channel, message);
return null;
}
const origContent = message.Content || "";
const isAdmin = message.Sender.Arn == this.adminArn;
const { name, version, flags } = isAdmin
? { name: ADMIN_NAME, version: "0", flags: { isAdmin: true } }
: parseChimeName(message.Sender.Name);
const sender: ChatSender = {
handle: message.Sender.Arn.replace(/^.+\/user\//, ""),
version,
name,
...flags,
};
const [content, adminControl] = isAdmin ? parseAdminMessage(origContent) : [origContent, null];
const update: ChatMessage = {
channel,
id: message.MessageId,
content: content,
sender,
timestamp: dayjs(message.CreatedTimestamp ? new Date(message.CreatedTimestamp) : new Date()).valueOf(),
redacted: message.Redacted === true,
adminControl,
};
return update;
}
onChannelMembershipEvent(kind: ChatUpdateKind, record: ChannelMembership) {
const channel = record.ChannelArn;
if (!channel) return;
const update = { kind, member: record.Member };
const subs = this.messageSubscribers.get(channel);
if (subs) {
this.messageSubscribers.set(
channel,
subs.filter((v) => v(update)),
);
}
}
}
const CHIME_NAME_PATTERN = /^a!([tf]+)!([a-zA-Z0-9]+)\|(.*)$/;
// Parse ChimeUser#chime_name back to structure
function parseChimeName(chimeName: string): { name: string; version: string; flags: ChatSenderFlags } {
const match = CHIME_NAME_PATTERN.exec(chimeName);
if (!match) {
console.warn("Cannot parse chimeName", chimeName);
return { name: chimeName, version: "-", flags: {} };
} else {
const flagsStr = match[1];
const version = match[2];
const name = match[3];
return {
name,
version,
flags: {
isAnonymous: name === "", // !attendee.ready? may have this name
isStaff: flagsStr[0] == "t",
isSpeaker: flagsStr[1] == "t",
isCommitter: flagsStr[2] == "t",
},
};
}
}
function parseAdminMessage(message: string): [string | null, ChatAdminControl | null] {
try {
const adminMessage: AdminMessage = JSON.parse(message);
return [adminMessage.message ?? null, adminMessage.control ?? null];
} catch (e) {
console.warn("invalid admin message", e, message);
return [null, null];
}
}
export default ChatSession; | the_stack |
import { SfdxCommandlet } from '@salesforce/salesforcedx-utils-vscode/out/src';
import {
CliCommandExecutor,
Command,
CommandExecution
} from '@salesforce/salesforcedx-utils-vscode/out/src/cli';
import { expect } from 'chai';
import { Subject } from 'rxjs/Subject';
import * as sinon from 'sinon';
import { SinonSandbox, SinonStub } from 'sinon';
import * as vscode from 'vscode';
import { DEV_SERVER_DEFAULT_BASE_URL } from '../../../src/commands/commandConstants';
import * as commandUtils from '../../../src/commands/commandUtils';
import {
errorHints,
forceLightningLwcStart,
ForceLightningLwcStartExecutor
} from '../../../src/commands/forceLightningLwcStart';
import { nls } from '../../../src/messages';
import { DevServerService } from '../../../src/service/devServerService';
import { CancellationToken } from '@salesforce/salesforcedx-utils-vscode/out/src/cli/commandExecutor';
import { CliCommandExecution } from '@salesforce/salesforcedx-utils-vscode/out/src/cli';
import {
ChannelService,
notificationService
} from '@salesforce/salesforcedx-utils-vscode/out/src/commands';
class FakeExecution implements CommandExecution {
public command: Command;
public processExitSubject: Subject<number>;
public processErrorSubject: Subject<Error>;
public stdoutSubject: Subject<string>;
public stderrSubject: Subject<string>;
private readonly childProcessPid: any;
constructor(command: Command) {
this.command = command;
this.processExitSubject = new Subject<number>();
this.processErrorSubject = new Subject<Error>();
this.stdoutSubject = new Subject<string>();
this.stderrSubject = new Subject<string>();
this.childProcessPid = '';
}
public killExecution(signal?: string): Promise<void> {
return Promise.resolve();
}
}
describe('forceLightningLwcStart', () => {
describe('ForceLightningLwcStartExecutor', () => {
describe('build', () => {
it('returns a command with the correct params', () => {
const executor = new ForceLightningLwcStartExecutor();
const command = executor.build();
expect(command.toCommand()).to.equal(`sfdx force:lightning:lwc:start`);
});
it('returns a command with the correct description', () => {
const executor = new ForceLightningLwcStartExecutor();
const command = executor.build();
expect(command.description).to.equal(
nls.localize('force_lightning_lwc_start_text')
);
});
it('returns a command with the correct logName', () => {
const executor = new ForceLightningLwcStartExecutor();
const command = executor.build();
expect(command.logName).to.equal('force_lightning_lwc_start');
});
});
describe('execute', () => {
let sandbox: SinonSandbox;
let appendLineStub: SinonStub;
let notificationServiceStubs: any;
let devServiceStub: any;
let openBrowserStub: SinonStub<[string], Thenable<boolean>>;
let cliCommandExecutorStub: SinonStub<
[(CancellationToken | undefined)?],
CliCommandExecution | FakeExecution
>;
beforeEach(() => {
sandbox = sinon.createSandbox();
openBrowserStub = sandbox.stub(commandUtils, 'openBrowser');
devServiceStub = sinon.createStubInstance(DevServerService);
sandbox.stub(DevServerService, 'instance').get(() => devServiceStub);
cliCommandExecutorStub = sandbox.stub(
CliCommandExecutor.prototype,
'execute'
);
notificationServiceStubs = {};
appendLineStub = sandbox.stub(
ChannelService.prototype,
'appendLine' as any
);
notificationServiceStubs.reportExecutionErrorStub = sandbox.stub(
notificationService,
'reportExecutionError'
);
notificationServiceStubs.showErrorMessageStub = sandbox.stub(
notificationService,
'showErrorMessage'
);
notificationServiceStubs.showWarningMessageStub = sandbox.stub(
notificationService,
'showWarningMessage'
);
notificationServiceStubs.showSuccessfulExecutionStub = sandbox
.stub(notificationService, 'showSuccessfulExecution')
.returns(Promise.resolve());
});
afterEach(() => {
sandbox.restore();
});
it('calls execute on the CliCommandExecutor', () => {
const executor = new ForceLightningLwcStartExecutor();
const fakeExecution = new FakeExecution(executor.build());
cliCommandExecutorStub.returns(fakeExecution);
executor.execute({ type: 'CONTINUE', data: {} });
sinon.assert.calledOnce(cliCommandExecutorStub);
});
it('registers the server with DevServerService', () => {
const executor = new ForceLightningLwcStartExecutor();
const fakeExecution = new FakeExecution(executor.build());
cliCommandExecutorStub.returns(fakeExecution);
executor.execute({ type: 'CONTINUE', data: {} });
sinon.assert.calledOnce(devServiceStub.registerServerHandler);
});
it('shows the success message once server is started', () => {
const executor = new ForceLightningLwcStartExecutor();
const fakeExecution = new FakeExecution(executor.build());
cliCommandExecutorStub.returns(fakeExecution);
executor.execute({ type: 'CONTINUE', data: {} });
fakeExecution.stdoutSubject.next('foo');
fakeExecution.stdoutSubject.next('bar');
sinon.assert.notCalled(
notificationServiceStubs.showSuccessfulExecutionStub
);
fakeExecution.stdoutSubject.next('Server up');
sinon.assert.calledOnce(
notificationServiceStubs.showSuccessfulExecutionStub
);
});
it('shows the error message if server start up failed', () => {
const executor = new ForceLightningLwcStartExecutor();
const fakeExecution = new FakeExecution(executor.build());
cliCommandExecutorStub.returns(fakeExecution);
executor.execute({ type: 'CONTINUE', data: {} });
fakeExecution.stderrSubject.next(errorHints.SERVER_STARTUP_FALIED);
sinon.assert.notCalled(
notificationServiceStubs.showSuccessfulExecutionStub
);
sinon.assert.calledTwice(notificationServiceStubs.showErrorMessageStub);
sinon.assert.calledWith(
notificationServiceStubs.showErrorMessageStub,
sinon.match(
nls.localize(
'command_failure',
nls.localize(`force_lightning_lwc_start_text`)
)
)
);
sinon.assert.calledOnce(appendLineStub);
sinon.assert.calledWith(
appendLineStub,
sinon.match(nls.localize('force_lightning_lwc_start_failed'))
);
});
it('opens the browser once server is started', () => {
const executor = new ForceLightningLwcStartExecutor();
const fakeExecution = new FakeExecution(executor.build());
cliCommandExecutorStub.returns(fakeExecution);
devServiceStub.getBaseUrl.returns('http://localhost:3333');
executor.execute({ type: 'CONTINUE', data: {} });
fakeExecution.stdoutSubject.next('Server up on http://localhost:3333');
sinon.assert.calledWith(
devServiceStub.setBaseUrlFromDevServerUpMessage,
sinon.match('Server up on http://localhost:3333')
);
sinon.assert.calledOnce(openBrowserStub);
sinon.assert.calledWith(
openBrowserStub,
sinon.match(DEV_SERVER_DEFAULT_BASE_URL)
);
});
it('opens the browser at the correct port once server is started', () => {
const executor = new ForceLightningLwcStartExecutor();
const fakeExecution = new FakeExecution(executor.build());
cliCommandExecutorStub.returns(fakeExecution);
devServiceStub.getBaseUrl.returns('http://localhost:3332');
executor.execute({ type: 'CONTINUE', data: {} });
fakeExecution.stdoutSubject.next(
'Some details here\n Server up on http://localhost:3332 something\n More details here'
);
sinon.assert.calledWith(
devServiceStub.setBaseUrlFromDevServerUpMessage,
sinon.match(
'Some details here\n Server up on http://localhost:3332 something\n More details here'
)
);
sinon.assert.calledOnce(openBrowserStub);
sinon.assert.calledWith(
openBrowserStub,
sinon.match('http://localhost:3332')
);
});
it('opens the browser with default url when Server up message contains no url', () => {
const executor = new ForceLightningLwcStartExecutor();
const fakeExecution = new FakeExecution(executor.build());
cliCommandExecutorStub.returns(fakeExecution);
devServiceStub.getBaseUrl.returns(DEV_SERVER_DEFAULT_BASE_URL);
executor.execute({ type: 'CONTINUE', data: {} });
fakeExecution.stdoutSubject.next(
'Some details here\n Server up on -no valid url here- \n More details here'
);
sinon.assert.neverCalledWith(
devServiceStub.setBaseUrlFromDevServerUpMessage,
sinon.match('http://localhost:3333')
);
sinon.assert.calledOnce(openBrowserStub);
sinon.assert.calledWith(
openBrowserStub,
sinon.match('http://localhost:3333')
);
});
it('shows an error when the plugin is not installed', () => {
const executor = new ForceLightningLwcStartExecutor();
const fakeExecution = new FakeExecution(executor.build());
cliCommandExecutorStub.returns(fakeExecution);
executor.execute({ type: 'CONTINUE', data: {} });
fakeExecution.stdoutSubject.next('foo');
fakeExecution.processExitSubject.next(127);
const commandName = nls.localize(`force_lightning_lwc_start_text`);
sinon.assert.calledTwice(notificationServiceStubs.showErrorMessageStub);
sinon.assert.calledWith(
notificationServiceStubs.showErrorMessageStub,
sinon.match(nls.localize('command_failure', commandName))
);
sinon.assert.calledOnce(appendLineStub);
sinon.assert.calledWith(
appendLineStub,
sinon.match(nls.localize('force_lightning_lwc_start_not_found'))
);
});
it('shows an error when the address is already in use', () => {
const executor = new ForceLightningLwcStartExecutor();
const fakeExecution = new FakeExecution(executor.build());
cliCommandExecutorStub.returns(fakeExecution);
executor.execute({ type: 'CONTINUE', data: {} });
fakeExecution.processExitSubject.next(98);
const commandName = nls.localize(`force_lightning_lwc_start_text`);
sinon.assert.calledTwice(notificationServiceStubs.showErrorMessageStub);
sinon.assert.calledWith(
notificationServiceStubs.showErrorMessageStub,
sinon.match(nls.localize('command_failure', commandName))
);
sinon.assert.calledOnce(appendLineStub);
sinon.assert.calledWith(
appendLineStub,
sinon.match(nls.localize('force_lightning_lwc_start_addr_in_use'))
);
});
it('shows an error when scratch org is inactive', () => {
const executor = new ForceLightningLwcStartExecutor();
const fakeExecution = new FakeExecution(executor.build());
cliCommandExecutorStub.returns(fakeExecution);
executor.execute({ type: 'CONTINUE', data: {} });
fakeExecution.stderrSubject.next(errorHints.INACTIVE_SCRATCH_ORG);
fakeExecution.processExitSubject.next(1);
const commandName = nls.localize(`force_lightning_lwc_start_text`);
sinon.assert.calledTwice(notificationServiceStubs.showErrorMessageStub);
sinon.assert.calledWith(
notificationServiceStubs.showErrorMessageStub,
sinon.match(nls.localize('command_failure', commandName))
);
sinon.assert.calledOnce(appendLineStub);
sinon.assert.calledWith(
appendLineStub,
sinon.match(nls.localize('force_lightning_lwc_inactive_scratch_org'))
);
});
it('shows no error when server is stopping', () => {
const executor = new ForceLightningLwcStartExecutor();
const fakeExecution = new FakeExecution(executor.build());
cliCommandExecutorStub.returns(fakeExecution);
executor.execute({ type: 'CONTINUE', data: {} });
fakeExecution.stdoutSubject.next('Server up');
fakeExecution.processExitSubject.next(0);
sinon.assert.notCalled(notificationServiceStubs.showErrorMessageStub);
sinon.assert.notCalled(appendLineStub);
});
it('shows an error message when the process exists before server startup', () => {
const executor = new ForceLightningLwcStartExecutor();
const fakeExecution = new FakeExecution(executor.build());
cliCommandExecutorStub.returns(fakeExecution);
executor.execute({ type: 'CONTINUE', data: {} });
fakeExecution.stdoutSubject.next('foo');
fakeExecution.processExitSubject.next(0);
const commandName = nls.localize(`force_lightning_lwc_start_text`);
sinon.assert.calledTwice(notificationServiceStubs.showErrorMessageStub);
sinon.assert.calledWith(
notificationServiceStubs.showErrorMessageStub,
sinon.match(nls.localize('command_failure', commandName))
);
sinon.assert.calledOnce(appendLineStub);
sinon.assert.calledWith(
appendLineStub,
sinon.match(nls.localize('force_lightning_lwc_start_failed'))
);
});
});
});
describe('forceLightningLwcStart function', () => {
let sandbox: SinonSandbox;
let showWarningStub: SinonStub<
[string, ...string[]],
Thenable<string | undefined>
>;
let devServiceStub: any;
let commandletStub: SinonStub<[], Promise<void>>;
beforeEach(() => {
sandbox = sinon.createSandbox();
devServiceStub = sinon.createStubInstance(DevServerService);
sandbox.stub(DevServerService, 'instance').get(() => devServiceStub);
sandbox.stub(commandUtils, 'openBrowser');
commandletStub = sandbox.stub(SfdxCommandlet.prototype, 'run');
showWarningStub = sandbox.stub(notificationService, 'showWarningMessage');
});
afterEach(() => {
sandbox.restore();
});
it('calls run on the commandlet', async () => {
await forceLightningLwcStart();
sinon.assert.calledOnce(commandletStub);
});
it('shows a warning message when the server is already running', async () => {
devServiceStub.isServerHandlerRegistered.returns(true);
showWarningStub.resolves();
await forceLightningLwcStart();
sinon.assert.calledOnce(showWarningStub);
sinon.assert.calledWith(
showWarningStub,
nls.localize('force_lightning_lwc_start_already_running')
);
});
});
}); | the_stack |
import { Arc3d } from "../../curve/Arc3d";
import { Geometry } from "../../Geometry";
import { AngleSweep } from "../../geometry3d/AngleSweep";
import { Point3d, Vector3d } from "../../geometry3d/Point3dVector3d";
import { LineSegment3d } from "../../curve/LineSegment3d";
import { AnalyticRoots, SmallSystem } from "../../numerics/Polynomials";
import { Vector2d } from "../../geometry3d/Point2dVector2d";
import { Path } from "../../curve/Path";
import { Loop } from "../../curve/Loop";
import { CurvePrimitive } from "../../curve/CurvePrimitive";
import { GrowableFloat64Array } from "../../geometry3d/GrowableFloat64Array";
/**
* Assorted static methods for constructing fragmentary and complete curves for offsets from linestrings.
* * Primary method is the static edgeByEdgeOffsetFromPoints
* *
*
*/
export class BuildingCodeOffsetOps {
/**
* Return an arc or coordinate for a specialized offset joint between different offsets along line segments.
* * offsetAB and offsetBC may be different values, but must have the same sign.
* * positive is to the right of the line segments
* * returns an arc if the extension of the line with smaller offset intersects with the circular arc continuation of the line of the larger offset.
* * otherwise returns point of intersection of the offset lines.
* @param pointA start point of incoming edge
* @param pointB common point of two edges
* @param pointC end point of outgoing edge
* @param offsetAB offset along edge from pointA to pointB. Positive is to the right (outside of a CCW turn)
* @param offsetBC offset along edge from pointB to pointC. Positive is tot he right (outside of a CCW turn)
*/
public static createJointWithRadiusChange(pointA: Point3d, pointB: Point3d, pointC: Point3d, offsetAB: number, offsetBC: number): CurvePrimitive | Point3d | undefined {
// enforce same-sign:
if (offsetAB * offsetBC < 0.0)
return undefined;
const vectorAB = Vector3d.createStartEnd(pointA, pointB);
const vectorBC = Vector3d.createStartEnd(pointB, pointC);
const perpAB = vectorAB.rotate90CCWXY();
perpAB.scaleInPlace(-1.0);
const perpBC = vectorBC.rotate90CCWXY();
perpBC.scaleInPlace(-1.0);
const totalTurn = vectorAB.angleToXY(vectorBC);
let arc: CurvePrimitive | undefined;
if (totalTurn.radians * offsetAB > 0.0) {
let arcVector0, arcVector90;
// for equal axes, the arc would sweep the total turn.
// for unequal, find intersections of the smaller offset with the larger arc.
// * if two positive angle intersects, take the smaller.
// * otherwise jump to the simple offset of the smaller.
// const alphaSign = offsetBC > 0 ? -1.0 : 1.0;
const alphaSign = -1.0;
const betaSign = offsetBC > 0 ? 1.0 : -1.0;
const phiSign = offsetBC > 0 ? 1.0 : -1.0;
if (Math.abs(offsetBC) >= Math.abs(offsetAB)) {
const offsetRatio = offsetAB / offsetBC;
const cosine = totalTurn.cos();
const sine = totalTurn.sin();
const intersectionRadians = this.pickFromUpperPlaneIntersections(alphaSign * offsetRatio, betaSign * cosine, sine, phiSign);
if (intersectionRadians !== undefined) {
arcVector0 = perpBC.scaleToLength(offsetBC)!;
arcVector90 = vectorBC.scaleToLength(offsetBC)!;
arc = Arc3d.create(pointB, arcVector0, arcVector90, AngleSweep.createStartEndRadians(-phiSign * intersectionRadians, 0.0));
} else {
const offsetPointAB = this.offsetPointFromSegment(pointA, pointB, -offsetAB, 1.0);
const offsetPointBC = this.offsetPointFromSegment(pointB, pointC, -offsetBC, 0.0);
arc = LineSegment3d.create(offsetPointAB, offsetPointBC);
}
} else {
const offsetRatio = offsetBC / offsetAB;
const cosine = totalTurn.cos();
const sine = totalTurn.sin();
const intersectionRadians = this.pickFromUpperPlaneIntersections(alphaSign * offsetRatio, betaSign * cosine, sine, phiSign);
if (intersectionRadians !== undefined) {
arcVector0 = perpAB.scaleToLength(offsetAB)!;
arcVector90 = vectorAB.scaleToLength(offsetAB)!;
arc = Arc3d.create(pointB, arcVector0, arcVector90, AngleSweep.createStartEndRadians(0, phiSign * intersectionRadians));
} else {
const offsetPointAB = this.offsetPointFromSegment(pointA, pointB, -offsetAB, 1.0);
const offsetPointBC = this.offsetPointFromSegment(pointB, pointC, -offsetBC, 0.0);
arc = LineSegment3d.create(offsetPointAB, offsetPointBC);
}
}
}
if (arc !== undefined)
return arc;
// on fallthrough, create intersection of offset lines.
const intersectionParameters = Vector2d.create();
if (perpAB.normalizeInPlace() && perpBC.normalizeInPlace()) {
const xAB = pointB.x + offsetAB * perpAB.x;
const yAB = pointB.y + offsetAB * perpAB.y;
const xBC = pointB.x + offsetBC * perpBC.x;
const yBC = pointB.y + offsetBC * perpBC.y;
if (SmallSystem.linearSystem2d(vectorAB.x, -vectorBC.x, vectorAB.y, -vectorBC.y, xBC - xAB, yBC - yAB, intersectionParameters)) {
return Point3d.create(xAB + vectorAB.x * intersectionParameters.x, yAB + vectorAB.y * intersectionParameters.x, pointB.z);
}
}
return undefined;
}
public static offsetPointFromSegment(pointA: Point3d, pointB: Point3d, offsetDistance: number, fraction: number): Point3d {
const dAB = pointA.distance(pointB);
const perpendicularFraction = Geometry.conditionalDivideFraction(offsetDistance, dAB);
if (perpendicularFraction === undefined)
return pointA.interpolate(fraction, pointB);
return pointA.interpolatePerpendicularXY(fraction, pointB, perpendicularFraction);
}
/**
* Append a line segment and variant joint to a growing chain
* * The input point0 is the start of the line segment
* * At conclusion, point0 is updated as the end point of the joint, i.e. start for next offset
* * If the joint is geometry:
* * the line segment goes from input point0 to the start of the geometry
* * The output point0 is the end of the geometry
* @param chain chain to grow
* @param point0 start point. see note about input and output status
* @param joint Curve primitive or point for joint path.
*/
public static appendSegmentAndJoint(chain: Path | Loop, point0: Point3d, joint: CurvePrimitive | Point3d | undefined) {
if (joint instanceof CurvePrimitive) {
chain.children.push(LineSegment3d.create(point0, joint.startPoint()));
chain.children.push(joint);
joint.endPoint(point0);
} else if (joint instanceof Point3d) {
chain.children.push(LineSegment3d.create(point0, joint));
point0.setFrom(joint);
}
}
/**
* Create an offset path using createArc3dForLeftTurnOffsetRadiusChange to create joint geometry.
* @param points point along the path
* @param offsetDistances edgeDistances[i] is offset from points[i] to points[i+1]
* @param close if true, force closure from last to first point.
*/
public static edgeByEdgeOffsetFromPoints(points: Point3d[], offsetDistances: number[], close: boolean): Path | Loop | undefined {
let n = points.length;
if (n < 2)
return undefined;
if (close) {
if (points[0].isAlmostEqual(points[n - 1]))
n--;
const loop = Loop.create();
if (offsetDistances.length < n)
return undefined;
let point0;
const joint0 = this.createJointWithRadiusChange(points[n - 1], points[0], points[1], offsetDistances[n - 1], offsetDistances[0]);
if (!joint0)
return undefined;
if (joint0 instanceof Point3d)
point0 = joint0.clone();
else
point0 = joint0.endPoint();
for (let i = 0; i < n; i++) {
const i0 = i;
const i1 = (i + 1) % n;
const i2 = (i + 2) % n;
const joint = this.createJointWithRadiusChange(points[i0], points[i1], points[i2], offsetDistances[i0], offsetDistances[i1]);
this.appendSegmentAndJoint(loop, point0, joint);
}
return loop;
} else {
if (offsetDistances.length + 1 < n)
return undefined;
const path = Path.create();
const point0 = this.offsetPointFromSegment(points[0], points[1], -offsetDistances[0], 0.0);
for (let i = 0; i + 2 < n; i++) {
const joint = this.createJointWithRadiusChange(points[i], points[i + 1], points[i + 2], offsetDistances[i], offsetDistances[i + 1]);
this.appendSegmentAndJoint(path, point0, joint);
}
const point1 = this.offsetPointFromSegment(points[n - 2], points[n - 1], -offsetDistances[n - 2], 1.0);
this.appendSegmentAndJoint(path, point0, point1);
return path;
}
}
/**
* Intersect `alpha+cosineCoff*c + sineCoff * s` with unit circle `c*c+s*s=1`.
* * If there are two intersections (possibly double counting tangency) in positive s,
* * if phiSign is positive, work with the given angles.
* * if phiSign is negative, shift by PI (caller will negate that ... this is trial and error that works for all combinations of offset and turn.)
* * if both angles are positive, return the smaller magnitude.
* * Otherwise return undefined.
* @param alpha
* @param cosineCoff
* @param sineCoff
* @param phiSign
*/
public static pickFromUpperPlaneIntersections(alpha: number, cosineCoff: number, sineCoff: number, phiSign: number): number | undefined {
const intersectionRadians = new GrowableFloat64Array(2);
AnalyticRoots.appendImplicitLineUnitCircleIntersections(alpha, cosineCoff, sineCoff, undefined, undefined, intersectionRadians);
let candidate: number | undefined;
if (intersectionRadians.length === 1) {
candidate = phiSign * intersectionRadians.atUncheckedIndex(0);
} else if (intersectionRadians.length === 2) {
let a0 = intersectionRadians.atUncheckedIndex(0);
let a1 = intersectionRadians.atUncheckedIndex(1);
if (phiSign < 0) {
a0 += Math.PI;
a1 += Math.PI;
}
if (a0 > 0.0 && a1 > 0.0 && Math.abs(a1 - a0) < Math.PI) {
candidate = Math.min(a0, a1);
return candidate;
}
}
return undefined;
}
} | the_stack |
import { printSchema } from "graphql/utilities";
import {
GraphQLObjectType,
GraphQLInt,
GraphQLString,
GraphQLList,
GraphQLSchema,
GraphQLNonNull,
} from "graphql";
import { BaseNode, LensScopeQueryString } from "./schema";
import {
getDgraphClient,
DgraphClient,
RawNode,
EnrichedNode,
} from "./dgraph_client";
import { Schema, SchemaClient } from "./schema_client";
import { allSchemasToGraphql } from "./schema_to_graphql";
import { QueryGenerator } from "./query_generator";
type MysteryParentType = never;
const getLenses = async (
dg_client: DgraphClient,
first: number,
offset: number
) => {
console.debug("first, offset parameters in getLenses()", first, offset);
const query = `
query all($a: int, $b: int)
{
all(func: type(Lens), first: $a, offset: $b, orderdesc: score)
{
lens_name,
score,
node_key,
uid,
dgraph_type: dgraph.type,
lens_type,
scope {
uid,
node_key,
dgraph_type: dgraph.type,
}
}
}
`;
console.debug("Creating DGraph txn in getLenses");
const txn = dg_client.newTxn();
try {
console.debug("Querying DGraph for lenses in getLenses");
const res = await txn.queryWithVars(query, {
$a: first.toString(),
$b: offset.toString(),
});
console.debug("Lens response from DGraph", res);
return res.getJson()["all"];
} catch (e) {
console.error("Error in DGraph txn getLenses: ", e);
} finally {
console.debug("Closing Dgraph Txn in getLenses");
await txn.discard();
}
};
interface LensSubgraph {
readonly node_key: string;
readonly lens_name: string;
readonly lens_type: string;
readonly score: number;
scope: RawNode[];
}
const getLensSubgraphByName = async (
dg_client: DgraphClient,
lens_name: string
) => {
const query = `
query all($a: string, $b: first, $c: offset) {
all(func: eq(lens_name, $a), first: 1) {
uid,
dgraph_type: dgraph.type,
node_key,
lens_name,
lens_type,
score,
scope @filter(has(node_key)) {
uid,
dgraph_type: dgraph.type,
expand(_all_) {
uid,
dgraph_type: dgraph.type,
expand(_all_)
}
}
}
}
`;
console.debug("Creating DGraph txn in getLensSubgraphByName");
const txn = dg_client.newTxn();
try {
console.debug("Querying DGraph in getLensSubgraphByName");
const res = await txn.queryWithVars(query, { $a: lens_name });
console.debug(
"returning following data from getLensSubGrapByName: ",
res.getJson()["all"][0]
);
return res.getJson()["all"][0] as LensSubgraph & RawNode;
} catch (e) {
console.error("Error in DGraph txn: getLensSubgraphByName", e);
throw e;
} finally {
console.debug("Closing dgraphtxn in getLensSubraphByName");
await txn.discard();
}
};
const filterDefaultDgraphNodeTypes = (node_type: string) => {
return node_type !== "Base" && node_type !== "Entity";
};
function hasDgraphType(node: RawNode): boolean {
return (
"dgraph_type" in node && // it's a property
!!node["dgraph_type"] && // it's not null
node.dgraph_type?.length > 0
);
}
function uidAsInt(node: RawNode): number {
const uid = node["uid"];
if (typeof uid == "string") {
return parseInt(uid, 16);
} else if (typeof uid == "number") {
return uid;
}
throw new Error(`Oddly typed UID ${uid}`);
}
function asEnrichedNodeWithSchemas(
node: RawNode,
schemaMap: Map<string, Schema>
): EnrichedNode {
const dgraph_types = (node.dgraph_type || []).filter(
filterDefaultDgraphNodeTypes
);
const mostConcreteDgraphType = dgraph_types[0]; // yes, this can be undefined
const whichPropToDisplay = schemaMap.get(dgraph_types[0])?.display_property;
// fall back to just the type.
// I don't super love this design - it's putting view logic in the controller layer
const display: string =
(node as any)[whichPropToDisplay] || mostConcreteDgraphType;
return {
...node,
uid: uidAsInt(node),
dgraph_type: dgraph_types,
display: display,
};
}
const handleLensScope = async (
parent: MysteryParentType,
args: LensArgs,
schemaMap: Map<string, Schema>
) => {
console.debug("handleLensScope args: ", args);
const dg_client = getDgraphClient();
// partial apply schemaMap
const asEnrichedNode = (node: RawNode) =>
asEnrichedNodeWithSchemas(node, schemaMap);
// Tosses ones that don't have dgraph type (i.e., edges)
const batchEnrichNodes = (nodes: RawNode[]) => {
return nodes.flatMap((n: RawNode) => {
const enriched = asEnrichedNode(n);
if (hasDgraphType(enriched)) {
return [enriched];
}
return [];
});
};
const lens_name = args.lens_name;
// grab the graph of lens, lens scope, and neighbors to nodes in-scope of the lens ((lens) -> (neighbor) -> (neighbor's neighbor))
const lens_subgraph: LensSubgraph & RawNode = await getLensSubgraphByName(
dg_client,
lens_name
);
console.debug("lens_subgraph in handleLensScope: ", lens_subgraph);
lens_subgraph.uid = uidAsInt(lens_subgraph);
let scope: EnrichedNode[] = batchEnrichNodes(lens_subgraph["scope"] || []);
// record the uids of all direct neighbors to the lens.
// These are the only nodes we should keep by the end of this process.
// We'll then try to get all neighbor connections that only correspond to these nodes
const uids_in_scope = new Set<number>(
scope.map((node: EnrichedNode) => node.uid)
);
// lens neighbors
for (const node of scope) {
// neighbor of a lens neighbor
for (const predicate in node) {
// we want to keep risks and enrich them at the same time
if (predicate === "risks") {
// enrich + filter out nodes that don't have dgraph_types
node[predicate] = batchEnrichNodes(node[predicate]);
continue;
}
// If this edge is 1-to-many, we need to filter down the list to lens-neighbor -> lens-neighbor connections
// i.e. if you see:
// Known UIDs: [1, 2, 3];
// (UID 1) --edge--> [2, 4, 5]
// Throw away 4 and 5 since they're not in-scope.
if (
Array.isArray(node[predicate]) &&
node[predicate] &&
node[predicate][0]["uid"]
) {
node[predicate] = batchEnrichNodes(
node[predicate]
).filter((neighbor_of_node: EnrichedNode) =>
uids_in_scope.has(neighbor_of_node["uid"])
);
// If we filtered all the edges down, might as well delete this predicate
if (node[predicate].length === 0) {
delete node[predicate];
}
}
// If this edge is 1-to-1, we need to determine if we need to delete the edge
// i.e. if you see:
// Known UIDs: [1, 2, 3];
// (UID 1) --edge--> (UID 4)
// Throw away this edge, since UID 4 is not in-scope.
else if (
typeof node[predicate] === "object" &&
node[predicate]["uid"]
) {
node[predicate] = asEnrichedNode(node[predicate]);
if (!uids_in_scope.has(node[predicate].uid)) {
delete node[predicate];
}
}
}
}
for (const node of scope) {
if (!node) {
throw new Error(
`Somehow received a null or undefined scope node: ${node}`
);
}
}
lens_subgraph.scope = scope;
console.debug(
"lens_subgraph scope",
JSON.stringify(lens_subgraph["scope"])
);
return lens_subgraph;
};
interface RootQueryArgs {
readonly first: number;
readonly offset: number;
}
interface LensArgs {
readonly lens_name: string;
}
async function getRootQuery(): Promise<GraphQLObjectType> {
const schemasWithBuiltins = await new SchemaClient().getSchemas();
const schemas = schemasWithBuiltins.filter((schema) => {
// This could be a one-liner, but I think it's complex enough for ifelse
if (schema.node_type == "Risk" || schema.node_type == "Lens") {
return false; // reject
} else {
return true; // keep
}
});
// We use this in the `handleLensScope` to determine the display property
const schemasMap: Map<string, Schema> = new Map(
schemas.map((s) => [s.node_type, s])
);
const GraplEntityType = allSchemasToGraphql(schemas);
const LensNodeType = new GraphQLObjectType({
name: "LensNode",
fields: () => ({
...BaseNode,
lens_name: { type: GraphQLString },
score: { type: GraphQLInt },
scope: { type: GraphQLList(GraplEntityType) },
lens_type: { type: GraphQLString },
}),
});
return new GraphQLObjectType({
name: "RootQueryType",
fields: {
lenses: {
type: GraphQLList(LensNodeType),
args: {
first: {
type: new GraphQLNonNull(GraphQLInt),
},
offset: {
type: new GraphQLNonNull(GraphQLInt),
},
},
resolve: async (
parent: MysteryParentType,
args: RootQueryArgs
) => {
console.debug("lenses query arguments", args);
const first = args.first;
const offset = args.offset;
// #TODO: Make sure to validate that 'first' is under a specific limit, maybe 1000
console.debug("Making getLensesQuery");
const lenses = await getLenses(
getDgraphClient(),
first,
offset
);
console.debug(
"returning data from getLenses for lenses resolver",
lenses
);
return lenses;
},
},
lens_scope: {
type: LensNodeType,
args: {
lens_name: { type: new GraphQLNonNull(GraphQLString) },
},
resolve: async (parent: MysteryParentType, args: LensArgs) => {
try {
let response = await handleLensScope(
parent,
args,
schemasMap
);
return response;
} catch (e) {
console.error("Error in handleLensScope: ", e);
throw e;
}
},
},
lens_scope_query: {
type: LensScopeQueryString,
resolve: async (parent: never, args: never) => {
// We should consider caching this instead of re-generating it every time.
const query_string = new QueryGenerator(
GraplEntityType
).generate();
return {
query_string,
};
},
},
},
});
}
export async function getRootQuerySchema(): Promise<GraphQLSchema> {
const schema = new GraphQLSchema({
query: await getRootQuery(),
});
// Super useful for debugging!
// console.log("Schema: ", printSchema(schema));
return schema;
} | the_stack |
import React, { useState } from "react";
import styles from "./index.module.scss";
// Component that allows to input only numeric values.
const NumericInput = (props) => (
<input
type="text"
inputMode={props.inputMode || "numeric"}
pattern={props.pattern}
size={props.size || 4}
value={props.value}
onChange={(event) => {
if (event.target.value.length == 0) {
props.onChange("0");
} else if (event.target.validity.valid) {
props.onChange(event.target.value);
}
}}
/>
);
// Represents a decimal number
export const Dec = (props) => (
<span className={styles.decimal}>{props.children}</span>
);
const DecInput = (props) => (
<Dec>
<NumericInput pattern="[0-9]*" {...props} />
</Dec>
);
// Represents a hex number
export const Hex = (props) => (
<span className={styles.hexadecimal}>
{props.children}
<sup> hex</sup>
</span>
);
const HexInput = (props) => (
<Hex>
<NumericInput inputMode="text" pattern="[0-9A-Fa-f]*" {...props} />
</Hex>
);
// Represents an octal number
export const Oct = (props) => (
<span className={styles.octal}>
{props.children}
<sup> oct</sup>
</span>
);
const OctInput = (props) => (
<Oct>
<NumericInput pattern="[0-7]*" {...props} />
</Oct>
);
// Represents a binary number
export const Bin = (props) => (
<span className={styles.binary}>
{props.children}
<sup> bin</sup>
</span>
);
const BinInput = (props) => (
<Bin>
<NumericInput size={6} pattern="[0-1]*" {...props} />
</Bin>
);
export interface UtfPlaygroundProps {
base: number;
}
export const UtfPlayground: React.FC<UtfPlaygroundProps> = (
props: UtfPlaygroundProps
) => {
const [text, setText] = useState("abcdefg");
// Represents numbers from a buffer in decimal.
let transformationFn: (utf8: Uint8Array) => string = (utf8) => utf8.join(" ");
let Base;
switch (props.base) {
case 8:
Base = Oct;
break;
case 2:
Base = Bin;
break;
case 16:
Base = Hex;
// Represents numbers from a buffer in hex.
transformationFn = (utf8) =>
Array.prototype.map
.call(utf8, (x) => ("00" + x.toString(16)).slice(-2))
.join(" ");
break;
default:
Base = Dec;
break;
}
const encoder = new TextEncoder();
const utf8 = encoder.encode(text);
return (
<form className={styles.utfPlayground}>
<div className="form-group mr-3">
<textarea
className={`form-control ${styles.textInput}`}
onChange={(ev) => setText(ev.target.value)}
value={text}
/>
</div>
<div className={styles.numbersEncoding}>
<Base>{transformationFn(utf8)}</Base>
</div>
</form>
);
};
const DECIMAL_EXPONENTS = [
"one",
"ten",
"hundred",
"thousand",
"ten thousand",
"hundred thousand",
"million",
"ten million",
"hundred million",
"billion",
"ten billion",
"hundred billion",
"trillion",
];
const OCTAL_EXPONENTS = [
"one",
"eight",
"sixty four",
"five hundred and twenty",
"four thousand and ninety six",
"thirty two thousand and sixty eight",
"two hundred sixty two thousands and one hundred and forty four",
];
const BINARY_EXPONENTS = [
"one",
"two",
"four",
"eight",
"sixteen",
"thirty two",
"sixty four",
"one hundred and eight",
"two hundreds and fifty six",
"five hundreds and twelve",
"one thousand and twenty four",
];
const HEX_EXPONENTS = [
"one",
"sixteen",
"two hundred and fifty six",
"four thousand and ninety six",
"sixty five thousand five hundred thirty six",
];
interface ExponentationProps {
exp: number;
radix: number;
num: number;
expDescription: Array<string>;
}
export const Exponentiation: React.FC<ExponentationProps> = ({
exp,
radix,
expDescription,
num,
}: ExponentationProps) => {
const pow = Math.pow(radix, exp);
const expDesc = expDescription[exp];
if (typeof expDesc === "undefined") {
return null;
}
const plural =
num == 0 || num > 1
? expDesc[expDesc.length - 1] == "x"
? "es"
: "s"
: "";
return (
<li key={exp}>
<Dec>
<abbr title={pow.toString(10)}>
{radix}
<sup>{exp}</sup>
</abbr>
</Dec>{" "}
× {num} = <Dec>{num * pow}</Dec>{" "}
<em>
({num} {expDesc + plural})
</em>
</li>
);
};
export const BinaryPlayground: React.FC = () => {
const [number, setNumber] = useState(11);
const digits = [];
let divNum = number;
while (divNum > 0) {
digits.push(divNum % 2);
divNum = Math.floor(divNum / 2);
}
const digitsNum = digits.length - 1;
return (
<>
<p>
<span>
The same thing happens if we use <Dec>2</Dec> as our number base. For
example, let's take a number
</span>
<BinInput
value={number.toString(2)}
onChange={(value) => setNumber(parseInt(value, 2))}
/>
<span>
. It can be deconstructed as a sum of the following exponents:
</span>
</p>
<ul className={styles.exponents}>
{digits.reverse().map((num, exp) => (
<Exponentiation
key={exp}
radix={2}
exp={digitsNum - exp}
num={num}
expDescription={BINARY_EXPONENTS}
/>
))}
</ul>
<p>
<span>If we sum all these exponents, we will get </span>
<em>
<DecInput
value={number.toString(10)}
onChange={(value) => setNumber(parseInt(value, 10))}
/>
</em>
<span>
, which is the number that is represented as{" "}
<Bin>{number.toString(2)}</Bin> in the binary form.
</span>
</p>
</>
);
};
export const DecimalPlayground: React.FC = (props) => {
const [number, setNumber] = useState(123);
const digits = [];
let divNum = number;
while (divNum > 0) {
digits.push(divNum % 10);
divNum = Math.floor(divNum / 10);
}
const digitsNum = digits.length - 1;
const exponentSumNumbers = digits
.reverse()
.map((num, exp) => num * Math.pow(10, digitsNum - exp));
let summation;
if (exponentSumNumbers.length > 0) {
summation = (
<span>
. It can be deconstructed as a sum of numbers (
{exponentSumNumbers
.map<React.ReactNode>((num) => <Dec key={num}>{num}</Dec>)
.reduce((prev, num) => [prev, " + ", num])}
), or as a sum of{" "}
<a href="https://www.khanacademy.org/math/pre-algebra/pre-algebra-exponents-radicals">
<em>exponents</em>
</a>
:
</span>
);
} else {
summation = <span>.</span>;
}
return (
<>
<p>
<span>{props.children}</span>
<DecInput
value={number.toString(10)}
onChange={(value) => setNumber(parseInt(value, 10))}
/>
{summation}
</p>
<ul className={styles.exponents}>
{digits.map((num, exp) => (
<Exponentiation
key={exp}
radix={10}
exp={digitsNum - exp}
num={num}
expDescription={DECIMAL_EXPONENTS}
/>
))}
</ul>
</>
);
};
export const OctalPlayground: React.FC = () => {
const [number, setNumber] = useState(0o777);
const digits = [];
let divNum = number;
while (divNum > 0) {
digits.push(divNum % 8);
divNum = Math.floor(divNum / 8);
}
const digitsNum = digits.length - 1;
digits.reverse();
const exponentSumNumbers = digits.map(
(num, exp) => num * Math.pow(8, digitsNum - exp)
);
let summation;
if (exponentSumNumbers.length > 0) {
summation = (
<p key="p2">
If we sum the numbers{" "}
{exponentSumNumbers
.map<React.ReactNode>((num) => <Dec key={num}>{num}</Dec>)
.reduce((prev, num) => [prev, " + ", num])}
, we'll get
<em>
<DecInput
value={number.toString(10)}
onChange={(value) => setNumber(parseInt(value, 10))}
/>
</em>
, which is exactly what the octal number <Oct>{number.toString(8)}</Oct>{" "}
is if we convert it into a decimal number!
</p>
);
} else {
summation = (
<p key="p2">
If you enter an octal number above, you will see how it can be
deconstructed as a sum of exponents.
</p>
);
}
return (
<>
<p key="p1">
<OctInput
value={number.toString(8)}
onChange={(value) => setNumber(parseInt(value, 8))}
/>
{exponentSumNumbers.length > 0 ? (
<span> is a sum of exponents:</span>
) : null}
</p>
<ul className={styles.exponents}>
{digits.map((num, exp) => (
<Exponentiation
key={exp}
radix={8}
exp={digitsNum - exp}
num={num}
expDescription={OCTAL_EXPONENTS}
/>
))}
</ul>
{summation}
</>
);
};
export const HexPlayground: React.FC = () => {
const [number, setNumber] = useState(0x1f);
const digits = [];
let divNum = number;
while (divNum > 0) {
digits.push(divNum % 16);
divNum = Math.floor(divNum / 16);
}
const digitsNum = digits.length - 1;
digits.reverse();
const exponentSumNumbers = digits.map(
(num, exp) => num * Math.pow(16, digitsNum - exp)
);
let summation;
if (exponentSumNumbers.length > 0) {
summation = (
<p key="p2">
If we sum the numbers{" "}
{exponentSumNumbers
.map<React.ReactNode>((num) => <Dec key={num}>{num}</Dec>)
.reduce((prev, num) => [prev, " + ", num])}
, we'll get the decimal number
<em>
<DecInput
value={number.toString(10)}
onChange={(value) => setNumber(parseInt(value, 10))}
/>
</em>
, which corresponds to <Hex>{number.toString(16)}</Hex>.
</p>
);
} else {
summation = (
<p key="p2">
If you enter a hexedecimal number above, you will see how it can be
deconstructed as a sum of exponents.
</p>
);
}
return (
<>
<p key="p1">
<span>Give it a try:</span>
<HexInput
value={number.toString(16)}
onChange={(value) => setNumber(parseInt(value, 16))}
/>
</p>
<ul className={styles.exponents}>
{digits.map((num, exp) => (
<Exponentiation
key={exp}
radix={16}
exp={digitsNum - exp}
num={num}
expDescription={HEX_EXPONENTS}
/>
))}
</ul>
{summation}
</>
);
}; | the_stack |
import { CachedMetadata, TFile, normalizePath } from "obsidian";
import {
DataMap,
Query,
RenderInfo,
XValueMap,
QueryValuePair,
TableData,
SearchType,
ValueType,
} from "./data";
import * as helper from "./helper";
import { Moment } from "moment";
// fileBaseName is a string contains dateFormat only
export function getDateFromFilename(
file: TFile,
renderInfo: RenderInfo
): Moment {
// console.log(`getDateFromFilename: ${file.name}`);
// Get date form fileBaseName
let fileBaseName = file.basename;
let dateString = helper.getDateStringFromInputString(
fileBaseName,
renderInfo.dateFormatPrefix,
renderInfo.dateFormatSuffix
);
// console.log(dateString);
let fileDate = helper.strToDate(dateString, renderInfo.dateFormat);
// console.log(fileDate);
return fileDate;
}
// Not support multiple targets
// In form 'key: value', target used to identify 'frontmatter key'
export function getDateFromFrontmatter(
fileCache: CachedMetadata,
query: Query,
renderInfo: RenderInfo
): Moment {
// console.log("getDateFromFrontmatter");
// Get date from 'frontMatterKey: date'
let date = window.moment("");
let frontMatter = fileCache.frontmatter;
if (frontMatter) {
if (helper.deepValue(frontMatter, query.getTarget())) {
let strDate = helper.deepValue(frontMatter, query.getTarget());
// We only support single value for now
if (typeof strDate === "string") {
strDate = helper.getDateStringFromInputString(
strDate,
renderInfo.dateFormatPrefix,
renderInfo.dateFormatSuffix
);
date = helper.strToDate(strDate, renderInfo.dateFormat);
// console.log(date);
}
}
}
return date;
}
// helper function
// strRegex must have name group 'value'
// Named group 'value' could be provided from users or plugin
function extractDateUsingRegexWithValue(
text: string,
strRegex: string,
renderInfo: RenderInfo
): Moment {
let date = window.moment("");
let regex = new RegExp(strRegex, "gm");
let match;
while ((match = regex.exec(text))) {
// console.log(match);
if (
typeof match.groups !== "undefined" &&
typeof match.groups.value !== "undefined"
) {
// must have group name 'value'
let strDate = match.groups.value.trim();
// console.log(strDate);
strDate = helper.getDateStringFromInputString(
strDate,
renderInfo.dateFormatPrefix,
renderInfo.dateFormatSuffix
);
date = helper.strToDate(strDate, renderInfo.dateFormat);
if (date.isValid()) {
return date;
}
}
}
return date;
}
// Not support multiple targets
// In form 'key: value', name group 'value' from plugin, not from users
export function getDateFromTag(
content: string,
query: Query,
renderInfo: RenderInfo
): Moment {
// console.log("getDateFromTag");
// Get date from '#tagName: date'
// Inline value-attached tag only
let date = window.moment("");
let tagName = query.getTarget();
if (query.getParentTarget()) {
tagName = query.getParentTarget(); // use parent tag name for multiple values
}
// console.log(tagName);
let strRegex =
"(^|\\s)#" +
tagName +
"(\\/[\\w-]+)*(:(?<value>[\\d\\.\\/-]*)[a-zA-Z]*)?([\\.!,\\?;~-]*)?(\\s|$)";
// console.log(strRegex);
return extractDateUsingRegexWithValue(content, strRegex, renderInfo);
}
// Not support multiple targets
// In form 'regex with value', name group 'value' from users
export function getDateFromText(
content: string,
query: Query,
renderInfo: RenderInfo
): Moment {
// console.log("getDateFromText");
// Get date from text using regex with value
let date = window.moment("");
let strRegex = query.getTarget();
// console.log(strTextRegex);
return extractDateUsingRegexWithValue(content, strRegex, renderInfo);
}
// Not support multiple targets
// In form 'key::value', named group 'value' from plugin
export function getDateFromDvField(
content: string,
query: Query,
renderInfo: RenderInfo
): Moment {
// console.log("getDateFromDvField");
// Get date form 'targetName:: date'
let date = window.moment("");
let dvTarget = query.getTarget();
if (query.getParentTarget()) {
dvTarget = query.getParentTarget(); // use parent tag name for multiple values
}
// Dataview ask user to add dashes for spaces as search target
// So a dash may stands for a real dash or a space
dvTarget = dvTarget.replace("-", "[\\s\\-]");
// Test this in Regex101
// remember '\s' includes new line
// (^| |\t)\*{0,2}dvTarget\*{0,2}(::[ |\t]*(?<value>[\d\.\/\-\w,@; \t:]*))(\r?\n|\r|$)
let strRegex =
"(^| |\\t)\\*{0,2}" +
dvTarget +
"\\*{0,2}(::[ |\\t]*(?<value>[\\d\\.\\/\\-\\w,@; \\t:]*))(\\r\\?\\n|\\r|$)";
// console.log(strRegex);
return extractDateUsingRegexWithValue(content, strRegex, renderInfo);
}
// Not support multiple targets
// In form 'regex with value', name group 'value' from users
export function getDateFromWiki(
fileCache: CachedMetadata,
query: Query,
renderInfo: RenderInfo
): Moment {
//console.log("getDateFromWiki");
// Get date from '[[regex with value]]'
let date = window.moment("");
let links = fileCache.links;
if (!links) return date;
let searchTarget = query.getTarget();
let searchType = query.getType();
for (let link of links) {
if (!link) continue;
let wikiText = "";
if (searchType === SearchType.Wiki) {
if (link.displayText) {
wikiText = link.displayText;
} else {
wikiText = link.link;
}
} else if (searchType === SearchType.WikiLink) {
// wiki.link point to a file name
// a colon is not allowed be in file name
wikiText = link.link;
} else if (searchType === SearchType.WikiDisplay) {
if (link.displayText) {
wikiText = link.displayText;
}
} else {
if (link.displayText) {
wikiText = link.displayText;
} else {
wikiText = link.link;
}
}
wikiText = wikiText.trim();
let strRegex = "^" + searchTarget + "$";
return extractDateUsingRegexWithValue(wikiText, strRegex, renderInfo);
}
return date;
}
// Not support multiple targets
export function getDateFromFileMeta(
file: TFile,
query: Query,
renderInfo: RenderInfo
): Moment {
// console.log("getDateFromFileMeta");
// Get date from cDate, mDate or baseFileName
let date = window.moment("");
if (file && file instanceof TFile) {
// console.log(file.stat);
let target = query.getTarget();
if (target === "cDate") {
let ctime = file.stat.ctime; // unix time
date = helper.getDateFromUnixTime(ctime, renderInfo.dateFormat);
} else if (target === "mDate") {
let mtime = file.stat.mtime; // unix time
date = helper.getDateFromUnixTime(mtime, renderInfo.dateFormat);
} else if (target === "name") {
date = getDateFromFilename(file, renderInfo);
}
}
// console.log(date);
return date;
}
// Not support multiple targets
// In form 'regex with value', name group 'value' from users
export function getDateFromTask(
content: string,
query: Query,
renderInfo: RenderInfo
): Moment {
// console.log("getDateFromTask");
// Get date from '- [ ] regex with value' or '- [x] regex with value'
let date = window.moment("");
let searchType = query.getType();
// console.log(searchType);
let strRegex = query.getTarget();
if (searchType === SearchType.Task) {
strRegex = "\\[[\\sx]\\]\\s" + strRegex;
} else if (searchType === SearchType.TaskDone) {
strRegex = "\\[x\\]\\s" + strRegex;
} else if (searchType === SearchType.TaskNotDone) {
strRegex = "\\[\\s\\]\\s" + strRegex;
} else {
strRegex = "\\[[\\sx]\\]\\s" + strRegex;
}
// console.log(strTextRegex);
return extractDateUsingRegexWithValue(content, strRegex, renderInfo);
}
export function addToDataMap(
dataMap: DataMap,
date: string,
query: Query,
value: number | null
) {
if (!dataMap.has(date)) {
let queryValuePairs = new Array<QueryValuePair>();
queryValuePairs.push({ query: query, value: value });
dataMap.set(date, queryValuePairs);
} else {
let targetValuePairs = dataMap.get(date);
targetValuePairs.push({ query: query, value: value });
}
}
// Helper function
// Accept multiple values using custom separators
// regex with value --> extract value
// regex without value --> count occurrencies
function extractDataUsingRegexWithMultipleValues(
text: string,
strRegex: string,
query: Query,
dataMap: DataMap,
xValueMap: XValueMap,
renderInfo: RenderInfo
): boolean {
// console.log("extractDataUsingRegexWithMultipleValues");
let regex = new RegExp(strRegex, "gm");
let match;
let measure = 0.0;
let extracted = false;
while ((match = regex.exec(text))) {
// console.log(match);
if (!renderInfo.ignoreAttachedValue[query.getId()]) {
if (
typeof match.groups !== "undefined" &&
typeof match.groups.value !== "undefined"
) {
let values = match.groups.value.trim();
// console.log(values);
// console.log(query.getSeparator());
let splitted = values.split(query.getSeparator());
// console.log(splitted);
if (!splitted) continue;
if (splitted.length === 1) {
// console.log("single-value");
let toParse = splitted[0].trim();
// console.log(toParse);
let retParse = helper.parseFloatFromAny(
toParse,
renderInfo.textValueMap
);
if (retParse.value !== null) {
if (retParse.type === ValueType.Time) {
measure = retParse.value;
extracted = true;
query.valueType = ValueType.Time;
query.addNumTargets();
} else {
if (
!renderInfo.ignoreZeroValue[query.getId()] ||
retParse.value !== 0
) {
measure += retParse.value;
extracted = true;
query.addNumTargets();
}
}
}
} else if (
splitted.length > query.getAccessor() &&
query.getAccessor() >= 0
) {
// console.log("multiple-values");
let toParse = splitted[query.getAccessor()].trim();
let retParse = helper.parseFloatFromAny(
toParse,
renderInfo.textValueMap
);
//console.log(retParse);
if (retParse.value !== null) {
if (retParse.type === ValueType.Time) {
measure = retParse.value;
extracted = true;
query.valueType = ValueType.Time;
query.addNumTargets();
} else {
measure += retParse.value;
extracted = true;
query.addNumTargets();
}
}
}
} else {
// no named groups, count occurrencies
// console.log("count occurrencies");
measure += renderInfo.constValue[query.getId()];
extracted = true;
query.addNumTargets();
}
} else {
// force to count occurrencies
// console.log("forced count occurrencies");
measure += renderInfo.constValue[query.getId()];
extracted = true;
query.addNumTargets();
}
}
if (extracted) {
let xValue = xValueMap.get(renderInfo.xDataset[query.getId()]);
addToDataMap(dataMap, xValue, query, measure);
return true;
}
return false;
}
// No value, count occurrences only
export function collectDataFromFrontmatterTag(
fileCache: CachedMetadata,
query: Query,
renderInfo: RenderInfo,
dataMap: DataMap,
xValueMap: XValueMap
): boolean {
// console.log("collectDataFromFrontmatterTag");
// console.log(query);
// console.log(dataMap);
// console.log(xValueMap);
let frontMatter = fileCache.frontmatter;
let frontMatterTags: string[] = [];
if (frontMatter && frontMatter.tags) {
// console.log(frontMatter.tags);
let tagMeasure = 0.0;
let tagExist = false;
if (Array.isArray(frontMatter.tags)) {
frontMatterTags = frontMatterTags.concat(frontMatter.tags);
} else if (typeof frontMatter.tags === "string") {
let splitted = frontMatter.tags.split(query.getSeparator(true));
for (let splittedPart of splitted) {
let part = splittedPart.trim();
if (part !== "") {
frontMatterTags.push(part);
}
}
}
// console.log(frontMatterTags);
// console.log(query.getTarget());
for (let tag of frontMatterTags) {
if (tag === query.getTarget()) {
// simple tag
tagMeasure = tagMeasure + renderInfo.constValue[query.getId()];
tagExist = true;
query.addNumTargets();
} else if (tag.startsWith(query.getTarget() + "/")) {
// nested tag
tagMeasure = tagMeasure + renderInfo.constValue[query.getId()];
tagExist = true;
query.addNumTargets();
} else {
continue;
}
// valued-tag in frontmatter is not supported
// because the "tag:value" in frontmatter will be consider as a new tag for each existing value
let value = null;
if (tagExist) {
value = tagMeasure;
}
let xValue = xValueMap.get(renderInfo.xDataset[query.getId()]);
addToDataMap(dataMap, xValue, query, value);
return true;
}
}
return false;
}
// In form 'key: value', target used to identify 'frontmatter key'
export function collectDataFromFrontmatterKey(
fileCache: CachedMetadata,
query: Query,
renderInfo: RenderInfo,
dataMap: DataMap,
xValueMap: XValueMap
): boolean {
// console.log("collectDataFromFrontmatterKey");
let frontMatter = fileCache.frontmatter;
if (frontMatter) {
// console.log(frontMatter);
// console.log(query.getTarget());
let deepValue = helper.deepValue(frontMatter, query.getTarget());
// console.log(deepValue);
if (deepValue) {
let retParse = helper.parseFloatFromAny(
deepValue,
renderInfo.textValueMap
);
// console.log(retParse);
if (retParse.value !== null) {
if (retParse.type === ValueType.Time) {
query.valueType = ValueType.Time;
}
query.addNumTargets();
let xValue = xValueMap.get(renderInfo.xDataset[query.getId()]);
addToDataMap(dataMap, xValue, query, retParse.value);
return true;
}
} else if (
query.getParentTarget() &&
helper.deepValue(frontMatter, query.getParentTarget())
) {
// console.log("multiple values");
// console.log(query.getTarget());
// console.log(query.getParentTarget());
// console.log(query.getSubId());
// console.log(
// frontMatter[query.getParentTarget()]
// );
let toParse = helper.deepValue(
frontMatter,
query.getParentTarget()
);
let splitted = null;
if (Array.isArray(toParse)) {
splitted = toParse.map((p) => {
return p.toString();
});
} else if (typeof toParse === "string") {
splitted = toParse.split(query.getSeparator());
}
// console.log(splitted);
if (
splitted &&
splitted.length > query.getAccessor() &&
query.getAccessor() >= 0
) {
// TODO: it's not efficent to retrieve one value at a time, enhance this
let splittedPart = splitted[query.getAccessor()].trim();
let retParse = helper.parseFloatFromAny(
splittedPart,
renderInfo.textValueMap
);
if (retParse.value !== null) {
if (retParse.type === ValueType.Time) {
query.valueType = ValueType.Time;
}
query.addNumTargets();
let xValue = xValueMap.get(
renderInfo.xDataset[query.getId()]
);
addToDataMap(dataMap, xValue, query, retParse.value);
return true;
}
}
}
}
return false;
}
// In form 'regex with value', name group 'value' from users
export function collectDataFromWiki(
fileCache: CachedMetadata,
query: Query,
renderInfo: RenderInfo,
dataMap: DataMap,
xValueMap: XValueMap
): boolean {
let links = fileCache.links;
if (!links) return false;
let searchTarget = query.getTarget();
let searchType = query.getType();
let textToSearch = "";
let strRegex = searchTarget;
// Prepare textToSearch
for (let link of links) {
if (!link) continue;
let wikiText = "";
if (searchType === SearchType.Wiki) {
if (link.displayText) {
wikiText = link.displayText;
} else {
wikiText = link.link;
}
} else if (searchType === SearchType.WikiLink) {
// wiki.link point to a file name
// a colon is not allowed be in file name
wikiText = link.link;
} else if (searchType === SearchType.WikiDisplay) {
if (link.displayText) {
wikiText = link.displayText;
}
} else {
if (link.displayText) {
wikiText = link.displayText;
} else {
wikiText = link.link;
}
}
wikiText = wikiText.trim();
textToSearch += wikiText + "\n";
}
return extractDataUsingRegexWithMultipleValues(
textToSearch,
strRegex,
query,
dataMap,
xValueMap,
renderInfo
);
}
// In form 'key: value', name group 'value' from plugin, not from users
export function collectDataFromInlineTag(
content: string,
query: Query,
renderInfo: RenderInfo,
dataMap: DataMap,
xValueMap: XValueMap
): boolean {
// console.log(content);
// Test this in Regex101
// (^|\s)#tagName(\/[\w-]+)*(:(?<value>[\d\.\/-]*)[a-zA-Z]*)?([\\.!,\\?;~-]*)?(\s|$)
let tagName = query.getTarget();
if (query.getParentTarget()) {
tagName = query.getParentTarget(); // use parent tag name for multiple values
}
if (tagName.length > 1 && tagName.startsWith("#")) {
tagName = tagName.substring(1);
}
let strRegex =
"(^|\\s)#" +
tagName +
"(\\/[\\w-]+)*(:(?<value>[\\d\\.\\/-]*)[a-zA-Z]*)?([\\.!,\\?;~-]*)?(\\s|$)";
// console.log(strRegex);
return extractDataUsingRegexWithMultipleValues(
content,
strRegex,
query,
dataMap,
xValueMap,
renderInfo
);
}
// In form 'regex with value', name group 'value' from users
export function collectDataFromText(
content: string,
query: Query,
renderInfo: RenderInfo,
dataMap: DataMap,
xValueMap: XValueMap
): boolean {
// console.log("collectDataFromText");
let strRegex = query.getTarget();
// console.log(strRegex);
return extractDataUsingRegexWithMultipleValues(
content,
strRegex,
query,
dataMap,
xValueMap,
renderInfo
);
}
export function collectDataFromFileMeta(
file: TFile,
content: string,
query: Query,
renderInfo: RenderInfo,
dataMap: DataMap,
xValueMap: XValueMap
): boolean {
// console.log("collectDataFromFileMeta");
if (file && file instanceof TFile) {
// console.log(file.stat);
let target = query.getTarget();
let xValue = xValueMap.get(renderInfo.xDataset[query.getId()]);
if (target === "cDate") {
let ctime = file.stat.ctime; // unix time
query.valueType = ValueType.Date;
query.addNumTargets();
addToDataMap(dataMap, xValue, query, ctime);
return true;
} else if (target === "mDate") {
let mtime = file.stat.mtime; // unix time
query.valueType = ValueType.Date;
query.addNumTargets();
addToDataMap(dataMap, xValue, query, mtime);
return true;
} else if (target === "size") {
let size = file.stat.size; // number in
query.addNumTargets();
addToDataMap(dataMap, xValue, query, size);
return true;
} else if (target === "numWords") {
let numWords = helper.getWordCount(content);
addToDataMap(dataMap, xValue, query, numWords);
return true;
} else if (target === "numChars") {
let numChars = helper.getCharacterCount(content);
query.addNumTargets();
addToDataMap(dataMap, xValue, query, numChars);
return true;
} else if (target === "numSentences") {
let numSentences = helper.getSentenceCount(content);
query.addNumTargets();
addToDataMap(dataMap, xValue, query, numSentences);
return true;
} else if (target === "name") {
let targetMeasure = 0.0;
let targetExist = false;
let retParse = helper.parseFloatFromAny(
file.basename,
renderInfo.textValueMap
);
if (retParse.value !== null) {
if (retParse.type === ValueType.Time) {
targetMeasure = retParse.value;
targetExist = true;
query.valueType = ValueType.Time;
query.addNumTargets();
} else {
if (
!renderInfo.ignoreZeroValue[query.getId()] ||
retParse.value !== 0
) {
targetMeasure += retParse.value;
targetExist = true;
query.addNumTargets();
}
}
}
let value = null;
if (targetExist) {
value = targetMeasure;
}
if (value !== null) {
addToDataMap(dataMap, xValue, query, value);
return true;
}
}
}
return false;
}
// In form 'key::value', named group 'value' from plugin
export function collectDataFromDvField(
content: string,
query: Query,
renderInfo: RenderInfo,
dataMap: DataMap,
xValueMap: XValueMap
): boolean {
let dvTarget = query.getTarget();
if (query.getParentTarget()) {
dvTarget = query.getParentTarget(); // use parent tag name for multiple values
}
// Dataview ask user to add dashes for spaces as search target
// So a dash may stands for a real dash or a space
dvTarget = dvTarget.replace("-", "[\\s\\-]");
// Test this in Regex101
// remember '\s' includes new line
// (^| |\t)\*{0,2}dvTarget\*{0,2}(::[ |\t]*(?<value>[\d\.\/\-\w,@; \t:]*))(\r?\n|\r|$)
let strRegex =
"(^| |\\t)\\*{0,2}" +
dvTarget +
"\\*{0,2}(::[ |\\t]*(?<value>[\\d\\.\\/\\-\\w,@; \\t:]*))(\\r\\?\\n|\\r|$)";
// console.log(strRegex);
return extractDataUsingRegexWithMultipleValues(
content,
strRegex,
query,
dataMap,
xValueMap,
renderInfo
);
}
// In form 'regex with value', name group 'value' from users
export function collectDataFromTask(
content: string,
query: Query,
renderInfo: RenderInfo,
dataMap: DataMap,
xValueMap: XValueMap
): boolean {
// console.log("collectDataFromTask");
let searchType = query.getType();
// console.log(searchType);
let strRegex = query.getTarget();
if (searchType === SearchType.Task) {
strRegex = "\\[[\\sx]\\]\\s" + strRegex;
} else if (searchType === SearchType.TaskDone) {
strRegex = "\\[x\\]\\s" + strRegex;
} else if (searchType === SearchType.TaskNotDone) {
strRegex = "\\[\\s\\]\\s" + strRegex;
} else {
// all
strRegex = "\\[[\\sx]\\]\\s" + strRegex;
}
// console.log(strRegex);
return extractDataUsingRegexWithMultipleValues(
content,
strRegex,
query,
dataMap,
xValueMap,
renderInfo
);
} | the_stack |
import { Platform } from 'react-native';
import { styled } from '../styled';
import { borderRadius, fontSize, fontWeight, palette, space, theme } from '../utils/theme';
import { getFontStyles } from '../utils/getFontStyles';
import { Icon } from '../Icon/Icon';
import { Spinner } from '../Spinner/Spinner';
import { Text } from '../Text';
export const isInteractive = (props) =>
!props.isStatic && !props.isLoading && !props.disabled && props.variant !== 'link';
export const StyledButton = styled.TouchableOpacity`
align-items: center;
background-color: ${(props: any) => palette(props.palette)(props)};
border-radius: ${borderRadius('default')};
justify-content: center;
flex-direction: row;
min-height: ${(props) => `${space(5.5, 'major')(props)}px`};
padding: 0px ${(props) => `${space(4)(props)}px`};
text-decoration: none;
${(props: any) =>
props.palette === 'default'
? `
border-width: 1px;
border-style: solid;
border-top-color: ${palette('white900', { dark: 'gray600' })(props)};
border-bottom-color: ${palette('white900', { dark: 'gray600' })(props)};
border-left-color: ${palette('white900', { dark: 'gray600' })(props)};
border-right-color: ${palette('white900', { dark: 'gray600' })(props)};
`
: ''}
${theme('native.Button', 'styles.base')};
${(props: any) => (props.disabled ? getDisabledButtonProperties(props) : '')};
${(props: any) => (props.disabled ? theme('native.Button', `styles.disabled`)(props) : '')};
${(props: any) => (props.size ? getButtonSizeProperties(props) : '')};
${(props: any) => (props.size ? getButtonSizeOverrides(props) : '')};
${(props: any) => (props.isLoading ? getLoadingButtonProperties() : '')};
${(props: any) => (props.isLoading ? theme('native.Button', `styles.loading`)(props) : '')}
${(props: any) => (props.isStatic ? getStaticButtonProperties() : '')};
${(props: any) => (props.isStatic ? theme('native.Button', `styles.static`)(props) : '')}
${(props: any) => (isInteractive(props) ? getInteractiveButtonProperties(props) : '')};
${(props: any) => (isInteractive(props) ? getInteractiveButtonOverrides(props) : '')};
${(props: any) => (props.variant === 'outlined' ? getOutlinedButtonProperties(props) : '')};
${(props: any) => (props.variant === 'outlined' ? theme('native.Button', `styles.outlined`)(props) : '')}
${(props: any) => (props.variant === 'link' ? getLinkButtonProperties(props) : '')};
${(props: any) => (props.variant === 'link' ? theme('native.Button', `styles.link`)(props) : '')}
${(props: any) => (props.variant === 'ghost' ? getGhostButtonProperties(props) : '')};
${(props: any) => (props.variant === 'ghost' ? theme('native.Button', `styles.ghost`)(props) : '')}
`;
export const getDisabledButtonProperties = (props: any) => `
opacity: ${props.colorMode === 'dark' ? '0.5' : '0.7'};
${
Platform.OS === 'web'
? `
cursor: not-allowed;
pointer-events: unset;
`
: ''
}
`;
export const getButtonSizeProperties = (props: any) => {
const styles = {
small: `
min-height: ${space(8)(props)}px;
padding: 0px ${space(3)(props)}px;
`,
default: ``,
medium: `
min-height: ${space(12)(props)}px;
padding: 0px ${space(5)(props)}px;
`,
large: `
min-height: ${space(13)(props)}px;
padding: 0px ${space(6)(props)}px;
`,
};
return styles[props.size];
};
export const getButtonSizeOverrides = (props: any) => {
const styles = {
small: theme('native.Button', `styles.sizes.small`)(props),
default: theme('native.Button', `styles.sizes.default`)(props),
medium: theme('native.Button', `styles.sizes.medium`)(props),
large: theme('native.Button', `styles.sizes.large`)(props),
};
return styles[props.size];
};
export const getLoadingButtonProperties = () => `
${
Platform.OS === 'web'
? `
positon: relative;
cursor: not-allowed;
`
: ''
}
`;
export const getStaticButtonProperties = () => `
${
Platform.OS === 'web'
? `
cursor: default;
`
: ''
}
`;
export const getInteractiveButtonProperties = (props: any) => `
${
props.hover && props.variant !== 'link'
? `
background-color: ${palette(`${props.palette === 'default' ? 'white' : props.palette}600`, {
dark: `${props.palette === 'default' ? 'black100' : `${props.palette}600`}`,
})(props)};
`
: ''
}
${
props.hoveractive && props.variant !== 'link'
? `
background-color: ${palette(props.palette === 'default' ? 'white800' : `${props.palette}700`, {
dark: `${props.palette === 'default' ? 'black200' : `${props.palette}700`}`,
})(props)};
`
: ''
}
`;
export const getInteractiveButtonOverrides = (props: any) => {
if (props.hover && props.variant !== 'link') {
return theme('native.Button', 'styles.hover')(props);
}
if (props.hoveractive && props.variant !== 'link') {
return theme('native.Button', 'styles.hoveractive')(props);
}
return '';
};
export const getOutlinedButtonProperties = (props: any) => `
background-color: ${palette('default')(props)};
border-width: 1px;
border-style: solid;
border-top-color: ${palette(props.palette, { dark: `${props.palette}300` })(props)};
border-bottom-color: ${palette(props.palette, { dark: `${props.palette}300` })(props)};
border-left-color: ${palette(props.palette, { dark: `${props.palette}300` })(props)};
border-right-color: ${palette(props.palette, { dark: `${props.palette}300` })(props)};
${
props.hover && isInteractive(props)
? `
background-color: ${palette(`${props.palette}Tint`, { dark: `${props.palette}Shade` })(props)};
border-width: 1px;
border-style: solid;
border-top-color: ${palette(props.palette, { dark: `${props.palette}300` })(props)};
border-bottom-color: ${palette(props.palette, { dark: `${props.palette}300` })(props)};
border-left-color: ${palette(props.palette, { dark: `${props.palette}300` })(props)};
border-right-color: ${palette(props.palette, { dark: `${props.palette}300` })(props)};
`
: ''
}
${
props.hoveractive && isInteractive(props)
? `
background-color: ${palette(`${props.palette}100`, { dark: `${props.palette}Shade` })(props)};
border-width: 1px;
border-style: solid;
border-top-color: ${palette(props.palette, { dark: `${props.palette}300` })(props)};
border-bottom-color: ${palette(props.palette, { dark: `${props.palette}300` })(props)};
border-left-color: ${palette(props.palette, { dark: `${props.palette}300` })(props)};
border-right-color: ${palette(props.palette, { dark: `${props.palette}300` })(props)};
`
: ''
}
`;
export const getGhostButtonProperties = (props: any) => `
background-color: transparent;
border-top-color: transparent;
border-bottom-color: transparent;
border-left-color: transparent;
border-right-color: transparent;
${
props.hover
? `
background-color: rgba(0, 0, 0, 0.05);
`
: ''
}
${
props.hoveractive
? `
background-color: rgba(0, 0, 0, 0.1);
`
: ''
}
`;
export const getLinkButtonProperties = (props: any) => `
background-color: transparent;
border-top-color: transparent;
border-bottom-color: transparent;
border-left-color: transparent;
border-right-color: transparent;
${
props.hover && Platform.OS === 'web'
? `
text-decoration: underline;
text-decoration-color: ${
props.palette === 'default'
? palette('text')(props)
: palette(props.palette, { dark: `${props.palette}300` })(props)
};
`
: ''
}
`;
////////////////////////////////////////////////////////////////////////////////////
export const StyledButtonText = styled(Text)`
color: ${(props: any) => palette(`${props.palette}Inverted`)(props)};
${getFontStyles({ fontWeight: '500' })};
${theme('native.Button', 'Text.styles.base')};
${(props: any) => props.size && getButtonTextSizeProperties(props)};
${(props: any) => isInteractive(props) && getInteractiveButtonTextProperties(props)};
${(props: any) => props.variant === 'outlined' && getOutlinedButtonTextProperties(props)};
${(props: any) => props.variant === 'link' && getLinkButtonTextProperties(props)};
${(props: any) => props.variant === 'ghost' && getGhostButtonTextProperties(props)};
`;
export const getButtonTextSizeProperties = (props: any) => {
const styles = {
small: `
font-size: ${fontSize('100')(props)}px;
${theme('native.Button', `Text.styles.sizes.small`)(props)};
`,
default: `
${theme('native.Button', `Text.styles.sizes.default`)(props)};
`,
medium: `
${theme('native.Button', `Text.styles.sizes.medium`)(props)};
`,
large: `
font-size: ${fontSize('300')(props)}px;
${theme('native.Button', `Text.styles.sizes.large`)(props)};
`,
};
return styles[props.size];
};
export const getInteractiveButtonTextProperties = (props: any) => `
${
props.hover && props.variant !== 'link'
? `
${theme('native.Button', 'Text.styles.hover')(props)};
`
: ''
}
${
props.hoveractive && props.variant !== 'link'
? `
${theme('native.Button', 'Text.styles.hoveractive')(props)};
`
: ''
}
`;
export const getOutlinedButtonTextProperties = (props: any) => `
color: ${palette(props.palette, { dark: `${props.palette}300` })(props)};
${theme('native.Button', `Text.styles.outlined`)(props)};
`;
export const getGhostButtonTextProperties = (props: any) => `
color: ${
props.palette === 'default'
? palette('defaultInverted')(props)
: palette(props.palette, { dark: `${props.palette}300` })(props)
};
${theme('native.Button', `Text.styles.ghost`)(props)};
`;
export const getLinkButtonTextProperties = (props: any) => `
color: ${
props.palette === 'default'
? palette('text')(props)
: palette(props.palette, { dark: `${props.palette}300` })(props)
};
${
Platform.OS !== 'web'
? `
text-decoration: underline;
text-decoration-color: ${
props.palette === 'default'
? palette('text')(props)
: palette(props.palette, { dark: `${props.palette}300` })(props)
};
`
: ''
}
${theme('native.Button', `Text.styles.link`)(props)};
`;
////////////////////////////////////////////////////////
export const StyledButtonIcon = styled(Icon)`
${(props: any) =>
props.isBefore
? `
margin-left: -${space(1)(props)}px;
margin-right: ${space(2)(props)}px;
`
: ''};
${(props: any) => (props.isBefore ? theme('native.Button.Icon', `styles.before`)(props) : '')}
${(props: any) =>
props.isAfter
? `
margin-left: ${space(2)(props)}px;
margin-right: -${space(1)(props)}px;
`
: ''};
${(props: any) => (props.isAfter ? theme('native.Button.Icon', `styles.after`)(props) : '')}
${(props: any) => theme('native.Button.Icon', `styles.base`)(props)};
`;
export const getButtonIconColor = (props: any) => {
if (props.variant === 'ghost') {
return props.palette === 'default'
? palette('defaultInverted')(props)
: palette(props.palette, { dark: `${props.palette}300` })(props);
}
if (props.variant === 'outlined') {
return palette(props.palette, { dark: `${props.palette}300` })(props);
}
if (props.variant === 'link') {
return props.palette === 'default'
? palette('text')(props)
: palette(props.palette, { dark: `${props.palette}300` })(props);
}
return palette(`${props.palette}Inverted`)(props);
};
////////////////////////////////////////////////////////////////////////////////////
export const ButtonSpinner = styled(Spinner)`
position: absolute;
${(props: any) => theme('native.Button.Spinner', `styles.base`)(props)};
`; | the_stack |
import * as commander from "commander";
import * as fs from "fs";
import * as glob from "glob";
import * as path from "path";
import * as ts from "typescript";
// Default format to use for `format` option
const defaultFormat = "ts"
// Default suffix appended to generated files. Abbreviation for "ts-interface".
const defaultSuffix = "-ti";
// Default header prepended to the generated module.
const defaultHeader =
`/**
* This module was automatically generated by \`ts-interface-builder\`
*/
`;
const ignoreNode = "";
export interface ICompilerOptions {
format?: "ts" | "js:esm" | "js:cjs"
ignoreGenerics?: boolean;
ignoreIndexSignature?: boolean;
inlineImports?: boolean;
}
// The main public interface is `Compiler.compile`.
export class Compiler {
public static compile(
filePath: string,
options: ICompilerOptions = {},
): string {
const createProgramOptions = {target: ts.ScriptTarget.Latest, module: ts.ModuleKind.CommonJS};
const program = ts.createProgram([filePath], createProgramOptions);
const checker = program.getTypeChecker();
const topNode = program.getSourceFile(filePath);
if (!topNode) {
throw new Error(`Can't process ${filePath}: ${collectDiagnostics(program)}`);
}
options = {format: defaultFormat, ignoreGenerics: false, ignoreIndexSignature: false, inlineImports: false, ...options}
return new Compiler(checker, options, topNode).compileNode(topNode);
}
private exportedNames: string[] = [];
constructor(private checker: ts.TypeChecker, private options: ICompilerOptions, private topNode: ts.SourceFile) {}
private getName(id: ts.Node): string {
const symbol = this.checker.getSymbolAtLocation(id);
return symbol ? symbol.getName() : "unknown";
}
private indent(content: string): string {
return content.replace(/\n/g, "\n ");
}
private compileNode(node: ts.Node): string {
switch (node.kind) {
case ts.SyntaxKind.Identifier: return this._compileIdentifier(node as ts.Identifier);
case ts.SyntaxKind.Parameter: return this._compileParameterDeclaration(node as ts.ParameterDeclaration);
case ts.SyntaxKind.PropertySignature: return this._compilePropertySignature(node as ts.PropertySignature);
case ts.SyntaxKind.MethodSignature: return this._compileMethodSignature(node as ts.MethodSignature);
case ts.SyntaxKind.TypeReference: return this._compileTypeReferenceNode(node as ts.TypeReferenceNode);
case ts.SyntaxKind.FunctionType: return this._compileFunctionTypeNode(node as ts.FunctionTypeNode);
case ts.SyntaxKind.TypeLiteral: return this._compileTypeLiteralNode(node as ts.TypeLiteralNode);
case ts.SyntaxKind.ArrayType: return this._compileArrayTypeNode(node as ts.ArrayTypeNode);
case ts.SyntaxKind.TupleType: return this._compileTupleTypeNode(node as ts.TupleTypeNode);
case ts.SyntaxKind.RestType: return this._compileRestTypeNode(node as ts.RestTypeNode);
case ts.SyntaxKind.UnionType: return this._compileUnionTypeNode(node as ts.UnionTypeNode);
case ts.SyntaxKind.IntersectionType: return this._compileIntersectionTypeNode(node as ts.IntersectionTypeNode);
case ts.SyntaxKind.LiteralType: return this._compileLiteralTypeNode(node as ts.LiteralTypeNode);
case ts.SyntaxKind.OptionalType: return this._compileOptionalTypeNode(node as ts.OptionalTypeNode);
case ts.SyntaxKind.EnumDeclaration: return this._compileEnumDeclaration(node as ts.EnumDeclaration);
case ts.SyntaxKind.InterfaceDeclaration:
return this._compileInterfaceDeclaration(node as ts.InterfaceDeclaration);
case ts.SyntaxKind.TypeAliasDeclaration:
return this._compileTypeAliasDeclaration(node as ts.TypeAliasDeclaration);
case ts.SyntaxKind.ExpressionWithTypeArguments:
return this._compileExpressionWithTypeArguments(node as ts.ExpressionWithTypeArguments);
case ts.SyntaxKind.ParenthesizedType:
return this._compileParenthesizedTypeNode(node as ts.ParenthesizedTypeNode);
case ts.SyntaxKind.ExportDeclaration:
case ts.SyntaxKind.ImportDeclaration:
return this._compileImportDeclaration(node as ts.ImportDeclaration);
case ts.SyntaxKind.SourceFile: return this._compileSourceFile(node as ts.SourceFile);
case ts.SyntaxKind.AnyKeyword: return '"any"';
case ts.SyntaxKind.NumberKeyword: return '"number"';
case ts.SyntaxKind.ObjectKeyword: return '"object"';
case ts.SyntaxKind.BooleanKeyword: return '"boolean"';
case ts.SyntaxKind.StringKeyword: return '"string"';
case ts.SyntaxKind.SymbolKeyword: return '"symbol"';
case ts.SyntaxKind.ThisKeyword: return '"this"';
case ts.SyntaxKind.VoidKeyword: return '"void"';
case ts.SyntaxKind.UndefinedKeyword: return '"undefined"';
case ts.SyntaxKind.UnknownKeyword: return '"unknown"';
case ts.SyntaxKind.NullKeyword: return '"null"';
case ts.SyntaxKind.NeverKeyword: return '"never"';
case ts.SyntaxKind.IndexSignature:
return this._compileIndexSignatureDeclaration(node as ts.IndexSignatureDeclaration);
}
// Skip top-level statements that we haven't handled.
if (ts.isSourceFile(node.parent!)) { return ""; }
throw new Error(`Node ${ts.SyntaxKind[node.kind]} not supported by ts-interface-builder: ` +
node.getText());
}
private compileOptType(typeNode: ts.Node|undefined): string {
return typeNode ? this.compileNode(typeNode) : '"any"';
}
private _compileIdentifier(node: ts.Identifier): string {
return `"${node.getText()}"`;
}
private _compileParameterDeclaration(node: ts.ParameterDeclaration): string {
const name = this.getName(node.name);
const isOpt = node.questionToken ? ", true" : "";
return `t.param("${name}", ${this.compileOptType(node.type)}${isOpt})`;
}
private _compilePropertySignature(node: ts.PropertySignature): string {
const name = this.getName(node.name);
const prop = this.compileOptType(node.type);
const value = node.questionToken ? `t.opt(${prop})` : prop;
return `"${name}": ${value}`;
}
private _compileMethodSignature(node: ts.MethodSignature): string {
const name = this.getName(node.name);
const params = node.parameters.map(this.compileNode, this);
const items = [this.compileOptType(node.type)].concat(params);
return `"${name}": t.func(${items.join(", ")})`;
}
private _compileTypeReferenceNode(node: ts.TypeReferenceNode): string {
if (!node.typeArguments) {
if (node.typeName.kind === ts.SyntaxKind.QualifiedName) {
const typeNode = this.checker.getTypeFromTypeNode(node);
if (typeNode.flags & ts.TypeFlags.EnumLiteral) {
return `t.enumlit("${node.typeName.left.getText()}", "${node.typeName.right.getText()}")`;
}
}
return `"${node.typeName.getText()}"`;
} else if (node.typeName.getText() === "Promise") {
// Unwrap Promises.
return this.compileNode(node.typeArguments[0]);
} else if (node.typeName.getText() === "Array") {
return `t.array(${this.compileNode(node.typeArguments[0])})`;
} else if (this.options.ignoreGenerics) {
return '"any"';
} else {
throw new Error(`Generics are not yet supported by ts-interface-builder: ` + node.getText());
}
}
private _compileFunctionTypeNode(node: ts.FunctionTypeNode): string {
const params = node.parameters.map(this.compileNode, this);
const items = [this.compileOptType(node.type)].concat(params);
return `t.func(${items.join(", ")})`;
}
private _compileTypeLiteralNode(node: ts.TypeLiteralNode): string {
const members = node.members
.map(n => this.compileNode(n))
.filter(n => n !== ignoreNode)
.map(n => " " + this.indent(n) + ",\n");
return `t.iface([], {\n${members.join("")}})`;
}
private _compileArrayTypeNode(node: ts.ArrayTypeNode): string {
return `t.array(${this.compileNode(node.elementType)})`;
}
private _compileTupleTypeNode(node: ts.TupleTypeNode): string {
const members = node.elementTypes.map(this.compileNode, this);
return `t.tuple(${members.join(", ")})`;
}
private _compileRestTypeNode(node: ts.RestTypeNode): string {
if (node.parent.kind != ts.SyntaxKind.TupleType) {
throw new Error("Rest type currently only supported in tuples");
}
return `t.rest(${this.compileNode(node.type)})`;
}
private _compileUnionTypeNode(node: ts.UnionTypeNode): string {
const members = node.types.map(this.compileNode, this);
return `t.union(${members.join(", ")})`;
}
private _compileIntersectionTypeNode(node: ts.IntersectionTypeNode): string {
const members = node.types.map(this.compileNode, this);
return `t.intersection(${members.join(", ")})`;
}
private _compileLiteralTypeNode(node: ts.LiteralTypeNode): string {
return `t.lit(${node.getText()})`;
}
private _compileOptionalTypeNode(node: ts.OptionalTypeNode): string {
return `t.opt(${this.compileNode(node.type)})`;
}
private _compileEnumDeclaration(node: ts.EnumDeclaration): string {
const name = this.getName(node.name);
const members: string[] = node.members.map(m =>
` "${this.getName(m.name)}": ${getTextOfConstantValue(this.checker.getConstantValue(m))},\n`);
this.exportedNames.push(name);
return this._formatExport(name, `t.enumtype({\n${members.join("")}})`);
}
private _compileInterfaceDeclaration(node: ts.InterfaceDeclaration): string {
const name = this.getName(node.name);
const members = node.members
.map(n => this.compileNode(n))
.filter(n => n !== ignoreNode)
.map(n => " " + this.indent(n) + ",\n");
const extend: string[] = [];
if (node.heritageClauses) {
for (const h of node.heritageClauses) {
extend.push(...h.types.map(this.compileNode, this));
}
}
this.exportedNames.push(name);
return this._formatExport(name, `t.iface([${extend.join(", ")}], {\n${members.join("")}})`)
}
private _compileTypeAliasDeclaration(node: ts.TypeAliasDeclaration): string {
const name = this.getName(node.name);
this.exportedNames.push(name);
const compiled = this.compileNode(node.type);
// Turn string literals into explicit `name` nodes, as expected by ITypeSuite.
const fullType = compiled.startsWith('"') ? `t.name(${compiled})` : compiled;
return this._formatExport(name, fullType)
}
private _compileExpressionWithTypeArguments(node: ts.ExpressionWithTypeArguments): string {
return this.compileNode(node.expression);
}
private _compileParenthesizedTypeNode(node: ts.ParenthesizedTypeNode): string {
return this.compileNode(node.type);
}
private _compileImportDeclaration(node: ts.ImportDeclaration): string {
if (this.options.inlineImports) {
const importedSym = this.checker.getSymbolAtLocation(node.moduleSpecifier);
if (importedSym && importedSym.declarations) {
// this._compileSourceFile will get called on every imported file when traversing imports.
// it's important to check that _compileSourceFile is being run against the topNode
// before adding the file wrapper for this reason.
return importedSym.declarations.map(declaration => this.compileNode(declaration)).join("");
}
}
return '';
}
private _compileSourceFileStatements(node: ts.SourceFile): string {
return node.statements.map(this.compileNode, this).filter((s) => s).join("\n\n");
}
private _compileSourceFile(node: ts.SourceFile): string {
// for imported source files, skip the wrapper
if (node !== this.topNode) {
return this._compileSourceFileStatements(node);
}
// wrap the top node with a default export
if (this.options.format === "js:cjs") {
return `const t = require("ts-interface-checker");\n\n` +
"module.exports = {\n" +
this._compileSourceFileStatements(node) + "\n" +
"};\n"
}
const prefix = `import * as t from "ts-interface-checker";\n` +
(this.options.format === "ts" ? "// tslint:disable:object-literal-key-quotes\n" : "") +
"\n";
return prefix +
this._compileSourceFileStatements(node) + "\n\n" +
"const exportedTypeSuite" + (this.options.format === "ts" ? ": t.ITypeSuite" : "") + " = {\n" +
this.exportedNames.map((n) => ` ${n},\n`).join("") +
"};\n" +
"export default exportedTypeSuite;\n";
}
private _compileIndexSignatureDeclaration(node: ts.IndexSignatureDeclaration): string {
// This option is supported for backward compatibility.
if (this.options.ignoreIndexSignature) {
return ignoreNode;
}
if (!node.type) { throw new Error(`Node ${ts.SyntaxKind[node.kind]} must have a type`); }
const type = this.compileNode(node.type);
return `[t.indexKey]: ${type}`;
}
private _formatExport(name: string, expression: string): string {
return this.options.format === "js:cjs"
? ` ${name}: ${this.indent(expression)},`
: `export const ${name} = ${expression};`;
}
}
function getTextOfConstantValue(value: string | number | undefined): string {
// Typescript has methods to escape values, but doesn't seem to expose them at all. Here I am
// casting `ts` to access this private member rather than implementing my own.
return value === undefined ? "undefined" : (ts as any).getTextOfConstantValue(value);
}
function collectDiagnostics(program: ts.Program) {
const diagnostics = ts.getPreEmitDiagnostics(program);
return ts.formatDiagnostics(diagnostics, {
getCurrentDirectory() { return process.cwd(); },
getCanonicalFileName(fileName: string) { return fileName; },
getNewLine() { return "\n"; },
});
}
function needsUpdate(srcPath: string, outPath: string): boolean {
if (!fs.existsSync(outPath)) {
return true;
}
const lastBuildTime = fs.statSync(outPath).mtime;
const lastCodeTime = fs.statSync(srcPath).mtime;
return lastBuildTime < lastCodeTime;
}
/**
* Main entry point when used from the command line.
*/
export function main() {
commander
.description("Create runtime validator module from TypeScript interfaces")
.usage("[options] <typescript-file...>")
.option("--format <format>", `Format to use for output; options are 'ts' (default), 'js:esm', 'js:cjs'`)
.option("-g, --ignore-generics", `Ignores generics`)
.option("-i, --ignore-index-signature", `Ignores index signature`)
.option("--inline-imports", `Traverses the full import tree and inlines all types into output`)
.option("-s, --suffix <suffix>", `Suffix to append to generated files (default ${defaultSuffix})`, defaultSuffix)
.option("-o, --outDir <path>", `Directory for output files; same as source file if omitted`)
.option("-v, --verbose", "Produce verbose output")
.option("-c, --changed-only", "Skip the build if the output file exists with a newer timestamp")
.parse(process.argv);
const files: string[] = commander.args;
const verbose: boolean = commander.verbose;
const changedOnly: boolean = commander.changedOnly;
const suffix: string = commander.suffix;
const outDir: string|undefined = commander.outDir;
const options: ICompilerOptions = {
format: commander.format || defaultFormat,
ignoreGenerics: commander.ignoreGenerics,
ignoreIndexSignature: commander.ignoreIndexSignature,
inlineImports: commander.inlineImports,
};
if (files.length === 0) {
commander.outputHelp();
process.exit(1);
return;
}
// perform expansion and find all matching files ourselves
const globFiles = ([] as string[]).concat(...files.map(p => glob.sync(p)));
for (const filePath of globFiles) {
// Read and parse the source file.
const ext = path.extname(filePath);
const dir = outDir || path.dirname(filePath);
const outPath = path.join(dir, path.basename(filePath, ext) + suffix + (options.format === "ts" ? ".ts" : ".js"));
if (changedOnly && !needsUpdate(filePath, outPath)) {
if (verbose) {
console.log(`Skipping ${filePath} because ${outPath} is newer`);
}
continue;
}
if (verbose) {
console.log(`Compiling ${filePath} -> ${outPath}`);
}
const generatedCode = defaultHeader + Compiler.compile(filePath, options);
fs.writeFileSync(outPath, generatedCode);
}
} | the_stack |
import { Theme } from "../core/Theme";
import type { Root } from "../core/Root";
import { MultiDisposer } from "../core/util/Disposer";
import { p100, percent } from "../core/util/Percent";
import type { Template } from "../core/util/Template";
import * as $array from "../core/util/Array";
/**
* An interface describing resonsive rule.
*
* @see {@link https://www.amcharts.com/docs/v5/concepts/responsive/} for more info
* @important
*/
export interface IResponsiveRule {
/**
* A class name of the elements to apply rule to.
*/
name?: string;
/**
* A class group of the elements to apply rule to.
*/
tags?: string | string[];
/**
* Settings to apply when activating the responsive rule.
*/
settings?: any;
/**
* A callback function which should check and return `true` if rule is
* applicable for current situation.
*/
relevant: (width: number, height: number) => boolean;
/**
* A custom callback function which is called when applying the rule.
*/
applying?: () => void;
/**
* A custom callback function which is called when removing the rule.
*/
removing?: () => void;
/**
* Indicates if rule is currently applied.
* @readonly
*/
applied?: boolean;
/**
* Reference to [[Template]] object associated with the rule.
* @readonly
*/
template?: Template<any>;
/**
* @ignore
*/
_dp?: MultiDisposer;
}
/**
* A configurable theme that dynamically adapts chart settings for best fit
* in available space.
*
* @see {@link https://www.amcharts.com/docs/v5/concepts/responsive/} for more info
*/
export class ResponsiveTheme extends Theme {
// Named pixel breakpoints
static XXS = 100;
static XS = 200;
static S = 300;
static M = 400;
static L = 600;
static XL = 800;
static XXL = 1000;
// Breakpoint functions (for use in `relevant` clause of the responsive rules)
static widthXXS(width: number, _height: number): boolean {
return width <= ResponsiveTheme.XXS;
}
static widthXS(width: number, _height: number): boolean {
return width <= ResponsiveTheme.XS;
}
static widthS(width: number, _height: number): boolean {
return width <= ResponsiveTheme.S;
}
static widthM(width: number, _height: number): boolean {
return width <= ResponsiveTheme.M;
}
static widthL(width: number, _height: number): boolean {
return width <= ResponsiveTheme.L;
}
static widthXL(width: number, _height: number): boolean {
return width <= ResponsiveTheme.XL;
}
static widthXXL(width: number, _height: number): boolean {
return width <= ResponsiveTheme.XXL;
}
static heightXXS(_width: number, height: number): boolean {
return height <= ResponsiveTheme.XXS;
}
static heightXS(_width: number, height: number): boolean {
return height <= ResponsiveTheme.XS;
}
static heightS(_width: number, height: number): boolean {
return height <= ResponsiveTheme.S;
}
static heightM(_width: number, height: number): boolean {
return height <= ResponsiveTheme.M;
}
static heightL(_width: number, height: number): boolean {
return height <= ResponsiveTheme.L;
}
static heightXL(_width: number, height: number): boolean {
return height <= ResponsiveTheme.XL;
}
static heightXXL(_width: number, height: number): boolean {
return height <= ResponsiveTheme.XXL;
}
static isXXS(width: number, height: number): boolean {
return (width <= ResponsiveTheme.XXS) && (height <= ResponsiveTheme.XXS);
}
static isXS(width: number, height: number): boolean {
return (width <= ResponsiveTheme.XS) && (height <= ResponsiveTheme.XS);
}
static isS(width: number, height: number): boolean {
return (width <= ResponsiveTheme.S) && (height <= ResponsiveTheme.S);
}
static isM(width: number, height: number): boolean {
return (width <= ResponsiveTheme.M) && (height <= ResponsiveTheme.M);
}
static isL(width: number, height: number): boolean {
return (width <= ResponsiveTheme.L) && (height <= ResponsiveTheme.L);
}
static isXL(width: number, height: number): boolean {
return (width <= ResponsiveTheme.XL) && (height <= ResponsiveTheme.XL);
}
static isXXL(width: number, height: number): boolean {
return (width <= ResponsiveTheme.XXL) && (height <= ResponsiveTheme.XXL);
}
static maybeXXS(width: number, height: number): boolean {
return (width <= ResponsiveTheme.XXS) || (height <= ResponsiveTheme.XXS);
}
static maybeXS(width: number, height: number): boolean {
return (width <= ResponsiveTheme.XS) || (height <= ResponsiveTheme.XS);
}
static maybeS(width: number, height: number): boolean {
return (width <= ResponsiveTheme.S) || (height <= ResponsiveTheme.S);
}
static maybeM(width: number, height: number): boolean {
return (width <= ResponsiveTheme.M) || (height <= ResponsiveTheme.M);
}
static maybeL(width: number, height: number): boolean {
return (width <= ResponsiveTheme.L) || (height <= ResponsiveTheme.L);
}
static maybeXL(width: number, height: number): boolean {
return (width <= ResponsiveTheme.XL) || (height <= ResponsiveTheme.XL);
}
static maybeXXL(width: number, height: number): boolean {
return (width <= ResponsiveTheme.XXL) || (height <= ResponsiveTheme.XXL);
}
/**
* Currently added rules.
*/
public responsiveRules: IResponsiveRule[] = [];
/**
* Instantiates the theme without adding default respomsive rules.
*/
static newEmpty<T extends typeof ResponsiveTheme>(this: T, root: Root): InstanceType<T> {
return (new this(root, true)) as InstanceType<T>;
}
/**
* Adds a responsive rule as well as retuns it.
*
* @see {@link https://www.amcharts.com/docs/v5/concepts/responsive/} for more info
* @param rule Responsive rule
* @return Responsive rule
*/
public addRule(rule: IResponsiveRule): IResponsiveRule {
if (rule.name && !rule.template) {
rule.template = (<any>this).rule(rule.name, rule.tags);
}
rule._dp = new MultiDisposer([
this._root._rootContainer.onPrivate("width", (_width) => { if (this._isUsed()) { this._applyRule(rule); } }),
this._root._rootContainer.onPrivate("height", (_height) => { if (this._isUsed()) { this._applyRule(rule); } })
]);
this.responsiveRules.push(rule);
this._applyRule(rule);
return rule;
}
/**
* Removes the responsive rule.
*
* @param rule Responsive rule
*/
public removeRule(rule: IResponsiveRule): void {
$array.remove(this.responsiveRules, rule);
if (rule._dp) {
rule._dp.dispose();
}
}
protected _isUsed(): boolean {
return this._root._rootContainer.get("themes")!.indexOf(this) !== -1;
}
protected _applyRule(rule: IResponsiveRule): void {
const w = this._root._rootContainer.getPrivate("width");
const h = this._root._rootContainer.getPrivate("height");
const relevant = rule.relevant.call(rule, <number>w, <number>h);
const applied = rule.applied;
if (relevant) {
if (!applied) {
rule.applied = true;
if (rule.template && rule.settings) {
rule.template.setAll(rule.settings);
}
if (rule.applying) {
rule.applying.call(rule);
}
}
}
else if (applied) {
rule.applied = false;
if (rule.template) {
rule.template.removeAll();
}
if (rule.removing) {
rule.removing.call(rule);
}
}
}
/**
* Adds default rules for various chart types and most standard scenarios.
*/
protected setupDefaultRules(): void {
super.setupDefaultRules();
const addRule = (rule: IResponsiveRule) => this.addRule(rule);
/**
* ========================================================================
* Universal
* ========================================================================
*/
addRule({
name: "Chart",
relevant: ResponsiveTheme.widthXXS,
settings: {
paddingLeft: 0,
paddingRight: 0
}
});
addRule({
name: "Chart",
relevant: ResponsiveTheme.heightXXS,
settings: {
paddingTop: 0,
paddingBottom: 0
}
});
addRule({
name: "Bullet",
relevant: ResponsiveTheme.isXS,
settings: {
forceHidden: true
}
});
addRule({
name: "Legend",
relevant: ResponsiveTheme.isXS,
settings: {
forceHidden: true
}
});
addRule({
name: "HeatLegend",
tags: ["vertical"],
relevant: ResponsiveTheme.widthXS,
settings: {
forceHidden: true
}
});
addRule({
name: "HeatLegend",
tags: ["horizontal"],
relevant: ResponsiveTheme.heightXS,
settings: {
forceHidden: true
}
});
addRule({
name: "Label",
tags: ["heatlegend", "start"],
relevant: ResponsiveTheme.maybeXS,
settings: {
forceHidden: true
}
});
addRule({
name: "Label",
tags: ["heatlegend", "end"],
relevant: ResponsiveTheme.maybeXS,
settings: {
forceHidden: true
}
});
addRule({
name: "Button",
tags: ["resize"],
relevant: ResponsiveTheme.maybeXS,
settings: {
forceHidden: true
}
});
/**
* ========================================================================
* XY
* ========================================================================
*/
addRule({
name: "AxisRendererX",
relevant: ResponsiveTheme.heightXS,
settings: {
inside: true
}
});
addRule({
name: "AxisRendererY",
relevant: ResponsiveTheme.widthXS,
settings: {
inside: true
}
});
addRule({
name: "AxisRendererXLabel",
relevant: ResponsiveTheme.heightXS,
settings: {
minPosition: 0.1,
maxPosition: 0.9
}
});
addRule({
name: "AxisLabel",
tags: ["y"],
relevant: ResponsiveTheme.widthXS,
settings: {
centerY: p100,
maxPosition: 0.9
}
});
addRule({
name: "AxisLabel",
tags: ["x"],
relevant: ResponsiveTheme.heightXXS,
settings: {
forceHidden: true
}
});
addRule({
name: "AxisLabel",
tags: ["y"],
relevant: ResponsiveTheme.widthXXS,
settings: {
forceHidden: true
}
});
addRule({
name: "AxisTick",
tags: ["x"],
relevant: ResponsiveTheme.heightXS,
settings: {
inside: true,
minPosition: 0.1,
maxPosition: 0.9
}
});
addRule({
name: "AxisTick",
tags: ["y"],
relevant: ResponsiveTheme.widthXXS,
settings: {
inside: true,
minPosition: 0.1,
maxPosition: 0.9
}
});
addRule({
name: "Grid",
relevant: ResponsiveTheme.maybeXXS,
settings: {
forceHidden: true
}
});
/**
* ========================================================================
* Radar
* ========================================================================
*/
addRule({
name: "RadialLabel",
tags: ["radial"],
relevant: ResponsiveTheme.maybeXS,
settings: {
forceHidden: true
}
});
addRule({
name: "RadialLabel",
tags: ["circular"],
relevant: ResponsiveTheme.maybeS,
settings: {
inside: true
}
});
addRule({
name: "AxisTick",
relevant: ResponsiveTheme.maybeS,
settings: {
inside: true
}
});
addRule({
name: "RadialLabel",
tags: ["circular"],
relevant: ResponsiveTheme.maybeXS,
settings: {
forceHidden: true
}
});
addRule({
name: "AxisTick",
tags: ["circular"],
relevant: ResponsiveTheme.maybeXS,
settings: {
inside: true
}
});
/**
* ========================================================================
* Pie
* ========================================================================
*/
addRule({
name: "PieChart",
relevant: ResponsiveTheme.maybeXS,
settings: {
radius: percent(99)
}
});
addRule({
name: "PieChart",
relevant: ResponsiveTheme.widthM,
settings: {
radius: percent(99)
}
});
addRule({
name: "RadialLabel",
tags: ["pie"],
relevant: ResponsiveTheme.maybeXS,
settings: {
forceHidden: true
}
});
addRule({
name: "RadialLabel",
tags: ["pie"],
relevant: ResponsiveTheme.widthM,
settings: {
forceHidden: true
}
});
addRule({
name: "Tick",
tags: ["pie"],
relevant: ResponsiveTheme.maybeXS,
settings: {
forceHidden: true
}
});
addRule({
name: "Tick",
tags: ["pie"],
relevant: ResponsiveTheme.widthM,
settings: {
forceHidden: true
}
});
/**
* ========================================================================
* Funnel
* ========================================================================
*/
addRule({
name: "FunnelSeries",
relevant: ResponsiveTheme.widthM,
settings: {
alignLabels: false
}
});
addRule({
name: "Label",
tags: ["funnel", "vertical"],
relevant: ResponsiveTheme.widthL,
settings: {
forceHidden: true
}
});
addRule({
name: "Tick",
tags: ["funnel", "vertical"],
relevant: ResponsiveTheme.widthL,
settings: {
forceHidden: true
}
});
addRule({
name: "Label",
tags: ["funnel", "horizontal"],
relevant: ResponsiveTheme.heightS,
settings: {
forceHidden: true
}
});
addRule({
name: "Tick",
tags: ["funnel", "horizontal"],
relevant: ResponsiveTheme.heightS,
settings: {
forceHidden: true
}
});
/**
* ========================================================================
* Pyramid
* ========================================================================
*/
addRule({
name: "PyramidSeries",
relevant: ResponsiveTheme.widthM,
settings: {
alignLabels: false
}
});
addRule({
name: "Label",
tags: ["pyramid", "vertical"],
relevant: ResponsiveTheme.widthL,
settings: {
forceHidden: true
}
});
addRule({
name: "Tick",
tags: ["pyramid", "vertical"],
relevant: ResponsiveTheme.widthL,
settings: {
forceHidden: true
}
});
addRule({
name: "Label",
tags: ["pyramid", "horizontal"],
relevant: ResponsiveTheme.heightS,
settings: {
forceHidden: true
}
});
addRule({
name: "Tick",
tags: ["pyramid", "horizontal"],
relevant: ResponsiveTheme.heightS,
settings: {
forceHidden: true
}
});
/**
* ========================================================================
* Pictorial
* ========================================================================
*/
addRule({
name: "PictorialStackedSeries",
relevant: ResponsiveTheme.widthM,
settings: {
alignLabels: false
}
});
addRule({
name: "Label",
tags: ["pictorial", "vertical"],
relevant: ResponsiveTheme.widthL,
settings: {
forceHidden: true
}
});
addRule({
name: "Tick",
tags: ["pictorial", "vertical"],
relevant: ResponsiveTheme.widthL,
settings: {
forceHidden: true
}
});
addRule({
name: "Label",
tags: ["pictorial", "horizontal"],
relevant: ResponsiveTheme.heightS,
settings: {
forceHidden: true
}
});
addRule({
name: "Tick",
tags: ["pictorial", "horizontal"],
relevant: ResponsiveTheme.heightS,
settings: {
forceHidden: true
}
});
/**
* ========================================================================
* Map
* ========================================================================
*/
// Nothing to do here
/**
* ========================================================================
* Flow (Sankey+Chord)
* ========================================================================
*/
addRule({
name: "Label",
tags: ["flow", "horizontal"],
relevant: ResponsiveTheme.widthS,
settings: {
forceHidden: true
}
});
addRule({
name: "Label",
tags: ["flow", "vertical"],
relevant: ResponsiveTheme.heightS,
settings: {
forceHidden: true
}
});
addRule({
name: "Chord",
relevant: ResponsiveTheme.maybeXS,
settings: {
radius: percent(99)
}
});
/**
* ========================================================================
* Hierarchy (Treemap, Partition, Sunburst, Pack, ForceDirected)
* ========================================================================
*/
addRule({
name: "Label",
tags: ["hierarchy", "node"],
relevant: ResponsiveTheme.maybeXS,
settings: {
forceHidden: true
}
});
}
} | the_stack |
import { IRegularTag } from '../../typings';
import { animationAdditionAttributes, animationElements, animationTimingAttributes, animationValueAttributes, conditionalProcessingAttributes, coreAttributes, deprecatedXlinkAttributes, descriptiveElements, filterPrimitiveElements, gradientElements, lightSourceElements, paintServerElements, rectAttributes, shapeElements, structuralElements, textContentChildElements, transferFunctionElementAttributes, transferFunctionElements } from './definitions';
const baseChildren = ['script'].concat(descriptiveElements);
const shapeChildren = ['clipPath', 'marker', 'mask', 'style'].concat(animationElements, baseChildren, paintServerElements);
const globalChildren = ['a', 'audio', 'canvas', 'clipPath', 'cursor', 'filter', 'foreignObject', 'iframe', 'image', 'marker', 'mask', 'style', 'switch', 'text', 'video', 'view'].concat(animationElements, baseChildren, paintServerElements, shapeElements, structuralElements);
const gradientChildren = ['animate', 'animateTransform', 'set', 'stop', 'style'].concat(baseChildren);
const feChildren = ['animate', 'set'].concat(baseChildren);
const conditionAndCore = conditionalProcessingAttributes.concat(coreAttributes);
const shapeAttributes = ['pathLength'].concat(conditionAndCore);
const animateAttributes = conditionAndCore.concat(animationAdditionAttributes, animationTimingAttributes, animationValueAttributes);
const feAttributes = ['result'].concat(coreAttributes, rectAttributes);
const feFuncAttributes = transferFunctionElementAttributes.concat(coreAttributes);
interface IRegularTagDefine {
[propName: string]: IRegularTag;
}
// tag define
const _regularTag: IRegularTagDefine = {
'a': {
containTextNode: true,
legalChildElements: { transparent: true, noself: true, childElements: [] },
ownAttributes: ['href', 'target', 'download', 'rel', 'hreflang', 'type'].concat(conditionAndCore, deprecatedXlinkAttributes),
},
'animate': {
legalChildElements: { childElements: baseChildren },
ownAttributes: ['attributeName'].concat(animateAttributes),
onlyAttr: ['fill'], // 动画元素的 fill 属性有另外的含义
},
'animateMotion': {
legalChildElements: { childElements: ['mpath'].concat(baseChildren) },
ownAttributes: ['path', 'keyPoints', 'rotate', 'origin'].concat(animateAttributes),
onlyAttr: ['fill'], // 动画元素的 fill 属性有另外的含义
},
'animateTransform': {
legalChildElements: { childElements: baseChildren },
ownAttributes: ['attributeName', 'type'].concat(animateAttributes),
onlyAttr: ['fill'], // 动画元素的 fill 属性有另外的含义
},
'audio': {
legalChildElements: { childElements: [] },
ownAttributes: [],
},
'canvas': {
legalChildElements: { childElements: [] },
ownAttributes: [],
},
'circle': {
legalChildElements: { childElements: shapeChildren },
ownAttributes: ['cx', 'cy', 'r'].concat(shapeAttributes),
},
'clipPath': {
legalChildElements: { childElements: ['text', 'use'].concat(baseChildren, animationElements, shapeElements) },
ownAttributes: ['externalResourcesRequired', 'transform', 'clipPathUnits'].concat(conditionAndCore),
},
'defs': {
legalChildElements: { childElements: globalChildren },
ownAttributes: coreAttributes,
},
'desc': {
containTextNode: true,
legalChildElements: { any: true, childElements: [] },
ownAttributes: coreAttributes,
},
'discard': {
legalChildElements: { childElements: baseChildren },
ownAttributes: ['begin', 'href'].concat(conditionAndCore),
},
'ellipse': {
legalChildElements: { childElements: shapeChildren },
ownAttributes: ['cx', 'cy', 'rx', 'ry'].concat(shapeAttributes),
},
'feBlend': {
legalChildElements: { childElements: feChildren },
ownAttributes: ['in', 'in2', 'mode'].concat(feAttributes),
},
'feColorMatrix': {
legalChildElements: { childElements: feChildren },
ownAttributes: ['in', 'type', 'values'].concat(feAttributes),
},
'feComponentTransfer': {
legalChildElements: { childElements: transferFunctionElements.concat(baseChildren) },
ownAttributes: ['in'].concat(feAttributes),
},
'feComposite': {
legalChildElements: { childElements: feChildren },
ownAttributes: ['in', 'in2', 'operator', 'k1', 'k2', 'k3', 'k4'].concat(feAttributes),
},
'feConvolveMatrix': {
legalChildElements: { childElements: feChildren },
ownAttributes: ['in', 'order', 'kernelMatrix', 'divisor', 'bias', 'targetX', 'targetY', 'edgeMode', 'kernelUnitLength', 'preserveAlpha'].concat(feAttributes),
},
'feDiffuseLighting': {
legalChildElements: { childElements: baseChildren.concat(lightSourceElements) },
ownAttributes: ['in', 'surfaceScale', 'diffuseConstant', 'kernelUnitLength'].concat(feAttributes),
},
'feDisplacementMap': {
legalChildElements: { childElements: feChildren },
ownAttributes: ['in', 'in2', 'scale', 'xChannelSelector', 'yChannelSelector'].concat(feAttributes),
},
'feDistantLight': {
legalChildElements: { childElements: feChildren },
ownAttributes: ['azimuth', 'elevation'].concat(coreAttributes),
},
'feFlood': {
legalChildElements: { childElements: feChildren },
ownAttributes: feAttributes,
},
'feFuncA': {
legalChildElements: { childElements: feChildren },
ownAttributes: feFuncAttributes,
},
'feFuncB': {
legalChildElements: { childElements: feChildren },
ownAttributes: feFuncAttributes,
},
'feFuncG': {
legalChildElements: { childElements: feChildren },
ownAttributes: feFuncAttributes,
},
'feFuncR': {
legalChildElements: { childElements: feChildren },
ownAttributes: feFuncAttributes,
},
'feGaussianBlur': {
legalChildElements: { childElements: feChildren },
ownAttributes: ['in', 'stdDeviation', 'edgeMode'].concat(feAttributes),
},
'feImage': {
legalChildElements: { childElements: ['animate', 'animateTransform', 'set'].concat(baseChildren) },
ownAttributes: ['externalResourcesRequired', 'preserveAspectRatio', 'xlink:href', 'href', 'crossorigin'].concat(feAttributes),
},
'feMerge': {
legalChildElements: { childElements: ['feMergeNode'].concat(baseChildren) },
ownAttributes: feAttributes,
},
'feMergeNode': {
legalChildElements: { childElements: feChildren },
ownAttributes: ['in'].concat(coreAttributes),
},
'feMorphology': {
legalChildElements: { childElements: feChildren },
ownAttributes: ['in', 'operator', 'radius'].concat(feAttributes),
},
'feOffset': {
legalChildElements: { childElements: feChildren },
ownAttributes: ['in', 'dx', 'dy'].concat(feAttributes),
},
'fePointLight': {
legalChildElements: { childElements: feChildren },
ownAttributes: ['x', 'y', 'z'].concat(coreAttributes),
},
'feSpecularLighting': {
legalChildElements: { childElements: baseChildren.concat(lightSourceElements) },
ownAttributes: ['in', 'surfaceScale', 'specularConstant', 'specularExponent', 'kernelUnitLength'].concat(feAttributes),
},
'feSpotLight': {
legalChildElements: { childElements: feChildren },
ownAttributes: ['x', 'y', 'z'].concat(coreAttributes),
},
'feTile': {
legalChildElements: { childElements: feChildren },
ownAttributes: ['in'].concat(feAttributes),
},
'feTurbulence': {
legalChildElements: { childElements: feChildren },
ownAttributes: ['baseFrequency', 'numOctaves', 'seed', 'stitchTiles', 'type'].concat(feAttributes),
},
'filter': {
legalChildElements: { childElements: feChildren.concat(filterPrimitiveElements) },
ownAttributes: ['externalResourcesRequired', 'filterUnits', 'primitiveUnits'].concat(coreAttributes, rectAttributes),
},
'foreignObject': {
legalChildElements: { any: true, childElements: [] },
ownAttributes: rectAttributes.concat(conditionAndCore),
},
'g': {
legalChildElements: { childElements: globalChildren },
ownAttributes: conditionAndCore,
},
'iframe': {
legalChildElements: { childElements: [] },
ownAttributes: [],
},
'image': {
legalChildElements: { childElements: ['clipPath', 'mask', 'style'].concat(animationElements, baseChildren) },
ownAttributes: ['preserveAspectRatio', 'href', 'crossorigin'].concat(conditionAndCore, deprecatedXlinkAttributes, rectAttributes),
},
'line': {
legalChildElements: { childElements: shapeChildren },
ownAttributes: ['x1', 'y1', 'x2', 'y2'].concat(shapeAttributes),
},
'linearGradient': {
legalChildElements: { childElements: gradientChildren },
ownAttributes: ['x1', 'y1', 'x2', 'y2', 'gradientUnits', 'gradientTransform', 'spreadMethod', 'href'].concat(coreAttributes, deprecatedXlinkAttributes),
},
'marker': {
legalChildElements: { childElements: globalChildren },
ownAttributes: ['viewBox', 'preserveAspectRatio', 'refX', 'refY', 'markerUnits', 'markerWidth', 'markerHeight', 'orient'].concat(coreAttributes),
},
'mask': {
legalChildElements: { childElements: ['a', 'clipPath', 'cursor', 'filter', 'foreignObject', 'image', 'marker', 'mask', 'pattern', 'style', 'switch', 'view', 'text'].concat(animationElements, baseChildren, shapeElements, structuralElements, gradientElements) },
ownAttributes: ['maskUnits', 'maskContentUnits'].concat(rectAttributes, conditionAndCore),
},
'metadata': {
containTextNode: true,
legalChildElements: { any: true, childElements: [] },
ownAttributes: coreAttributes,
},
'mpath': {
legalChildElements: { childElements: baseChildren },
ownAttributes: ['href'].concat(coreAttributes),
},
'path': {
legalChildElements: { childElements: shapeChildren },
ownAttributes: ['d'].concat(shapeAttributes),
},
'pattern': {
legalChildElements: { childElements: globalChildren },
ownAttributes: ['viewBox', 'preserveAspectRatio', 'patternUnits', 'patternContentUnits', 'patternTransform', 'href'].concat(coreAttributes, deprecatedXlinkAttributes, rectAttributes),
},
'polygon': {
legalChildElements: { childElements: shapeChildren },
ownAttributes: ['points'].concat(shapeAttributes),
},
'polyline': {
legalChildElements: { childElements: shapeChildren },
ownAttributes: ['points'].concat(shapeAttributes),
},
'radialGradient': {
legalChildElements: { childElements: gradientChildren },
ownAttributes: ['cx', 'cy', 'r', 'fx', 'fy', 'fr', 'gradientUnits', 'gradientTransform', 'spreadMethod', 'href'].concat(coreAttributes, deprecatedXlinkAttributes),
},
'rect': {
legalChildElements: { childElements: shapeChildren },
ownAttributes: ['rx', 'ry'].concat(rectAttributes, shapeAttributes),
},
'script': {
containTextNode: true,
legalChildElements: { childElements: [] },
ownAttributes: ['type', 'href', 'crossorigin'].concat(coreAttributes, deprecatedXlinkAttributes),
},
'set': {
legalChildElements: { childElements: baseChildren },
ownAttributes: ['to', 'attributeName'].concat(conditionAndCore, animationTimingAttributes),
onlyAttr: ['fill'], // 动画元素的 fill 属性有另外的含义
},
'stop': {
legalChildElements: { childElements: ['animate', 'script', 'set', 'style'] },
ownAttributes: ['path', 'offset'].concat(coreAttributes),
},
'style': {
containTextNode: true,
legalChildElements: { childElements: [] },
ownAttributes: ['type', 'media', 'title'].concat(coreAttributes),
},
'svg': {
legalChildElements: { childElements: globalChildren },
ownAttributes: ['viewBox', 'preserveAspectRatio', 'zoomAndPan', 'transform'].concat(conditionAndCore, rectAttributes),
onlyAttr: ['width', 'height'], // 根元素的尺寸属性转 style 的话,在 css 中应用会导致尺寸问题
},
'switch': {
legalChildElements: { childElements: ['a', 'audio', 'canvas', 'foreignObject', 'g', 'iframe', 'image', 'svg', 'switch', 'text', 'use', 'video'].concat(animationElements, shapeElements) },
ownAttributes: conditionAndCore,
},
'symbol': {
legalChildElements: { childElements: globalChildren },
ownAttributes: ['preserveAspectRatio', 'viewBox', 'refX', 'refY'].concat(coreAttributes, rectAttributes),
},
'text': {
containTextNode: true,
legalChildElements: { childElements: ['a', 'clipPath', 'marker', 'mask', 'style'].concat(animationElements, baseChildren, paintServerElements, textContentChildElements) },
ownAttributes: ['lengthAdjust', 'x', 'y', 'dx', 'dy', 'rotate', 'textLength'].concat(conditionAndCore),
},
'textPath': {
containTextNode: true,
legalChildElements: { childElements: ['a', 'animate', 'clipPath', 'marker', 'mask', 'set', 'style', 'tspan'].concat(baseChildren, paintServerElements) },
ownAttributes: ['lengthAdjust', 'textLength', 'path', 'href', 'startOffset', 'method', 'spacing', 'side'].concat(conditionAndCore, deprecatedXlinkAttributes),
},
'title': {
containTextNode: true,
legalChildElements: { any: true, childElements: ['a', 'animate', 'set', 'style', 'tspan'].concat(baseChildren, paintServerElements) },
ownAttributes: coreAttributes,
},
'tspan': {
containTextNode: true,
legalChildElements: { childElements: ['tspan'] },
ownAttributes: ['lengthAdjust', 'x', 'y', 'dx', 'dy', 'rotate', 'textLength'].concat(conditionAndCore),
},
'unknown': {
legalChildElements: { any: true, childElements: [] },
ownAttributes: conditionAndCore,
},
'use': {
legalChildElements: { childElements: ['clipPath', 'mask', 'style'].concat(animationElements, baseChildren) },
ownAttributes: ['href'].concat(rectAttributes, conditionAndCore, deprecatedXlinkAttributes),
},
'video': {
legalChildElements: { childElements: [] },
ownAttributes: [],
},
'view': {
legalChildElements: { childElements: ['style'].concat(animationElements, baseChildren) },
ownAttributes: ['viewBox', 'preserveAspectRatio', 'zoomAndPan'].concat(coreAttributes),
},
};
const undefTag: IRegularTag = {
isUndef: true,
legalChildElements: {},
ownAttributes: [],
};
export const regularTag = new Proxy(_regularTag, {
get(obj, prop: string) {
return prop in obj ? obj[prop] : undefTag as IRegularTag;
},
}); | the_stack |
import {vec2, mat2d} from 'gl-matrix'
import Bezier from 'bezier-js'
import svgpath from 'svgpath'
import Voronoi from 'voronoi'
import paper from 'paper'
import {PaperOffset, OffsetOptions} from 'paperjs-offset'
import {
MalVal,
keywordFor as K,
symbolFor as S,
MalError,
assocBang,
isMap,
createList as L,
isVector,
} from '@/mal/types'
import {partition, clamp} from '@/utils'
import printExp from '@/mal/printer'
import {
PathType,
SegmentType,
iterateSegment,
Vec2,
convertToPath2D,
getSVGPathData,
} from '@/path-utils'
import {net} from 'electron'
import {nextTick} from 'vue/types/umd'
const EPSILON = 1e-5
const K_PATH = K('path'),
K_M = K('M'),
K_L = K('L'),
K_C = K('C'),
K_Z = K('Z'),
K_H = K('H'),
K_V = K('V')
const SIN_Q = [0, 1, 0, -1]
const COS_Q = [1, 0, -1, 0]
const HALF_PI = Math.PI / 2
const KAPPA = (4 * (Math.sqrt(2) - 1)) / 3
const UNIT_QUAD_BEZIER = new Bezier([
{x: 1, y: 0},
{x: 1, y: KAPPA},
{x: KAPPA, y: 1},
{x: 0, y: 1},
])
const unsignedMod = (x: number, y: number) => ((x % y) + y) % y
function createEmptyPath(): PathType {
return [K_PATH]
}
paper.setup(new paper.Size(1, 1))
const PaperPathCaches = new WeakMap<PathType, paper.CompoundPath>()
function createPaperPath(path: PathType): paper.CompoundPath {
if (PaperPathCaches.has(path)) {
return PaperPathCaches.get(path) as paper.CompoundPath
}
if (path[0].toString().startsWith(K_PATH)) {
path = path.slice(1)
}
const svgpath = getSVGPathData(path)
const paperPath = new paper.CompoundPath(svgpath)
PaperPathCaches.set(path, paperPath)
return paperPath
}
const canvasContext = (() => {
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
if (!ctx) {
throw 'Cannot initialize a canvas context'
}
return ctx
})()
function getMalPathFromPaper(
_path: paper.CompoundPath | paper.PathItem
): PathType {
const d = _path ? _path.pathData : ''
const path: PathType = createEmptyPath()
svgpath(d)
.abs()
.unarc()
.unshort()
.iterate((seg, _, x, y) => {
let cmd = K(seg[0])
const pts = partition(2, seg.slice(1)) as number[][]
switch (cmd) {
case K_H:
pts[0] = [pts[0][0], y]
cmd = K_L
break
case K_V:
pts[0] = [x, pts[0][0]]
cmd = K_L
break
}
path.push(cmd, ...pts)
})
return path
}
function getChildPaperPathByLength(path: paper.CompoundPath, offset: number) {
offset = clamp(offset, 0, path.length)
let totalLength = 0
const childPath = (path.children as paper.Path[]).find(p => {
if (offset - totalLength <= p.length) {
return true
} else {
totalLength += p.length
return false
}
})
if (!childPath) {
return undefined
}
return {
offset: offset - totalLength,
path: childPath,
}
}
function getBezier(points: Vec2[]) {
const coords = points.map(([x, y]) => ({x, y}))
if (coords.length !== 4) {
throw new MalError('Invalid point count for cubic bezier')
}
return new Bezier(coords)
}
/**
* Yields a segment with its complete points.
* Thus each object can be like,
* [L prev-pos p]
* [C prev-pos p1 p2 p3]
* [Z prev-pos first-pos]
*/
export function* iterateCurve(path: PathType): Generator<SegmentType> {
let first, prev
for (const [cmd, ...points] of iterateSegment(path)) {
switch (cmd) {
case K_M:
yield [K_M, ...points]
first = points[0]
prev = points[0]
break
case K_L:
case K_C:
yield [cmd, prev, ...points] as SegmentType
prev = points[points.length - 1]
break
case K_Z:
yield [K_Z, prev, first] as SegmentType
break
}
}
}
function dragAnchor(path: PathType, index: number, delta: vec2) {
const segs = Array.from(iterateSegment(path))
const draggingSeg = segs[index]
let origAnchor: vec2
if (draggingSeg[0] === K_C) {
// Anchor itself
origAnchor = vec2.clone(draggingSeg[3] as vec2)
const anchor = vec2.add(vec2.create(), origAnchor, delta)
draggingSeg[3] = anchor
// In Handle
const inHandle = vec2.clone(draggingSeg[2] as vec2)
vec2.add(inHandle, inHandle, delta)
draggingSeg[2] = inHandle
} else {
origAnchor = vec2.clone(draggingSeg[1] as vec2)
const anchor = vec2.add(vec2.create(), origAnchor, delta)
draggingSeg[1] = anchor
}
// Out handle
let nextIndex = index + 1 < segs.length ? index + 1 : null
if (nextIndex !== null && segs[nextIndex][0] === K_Z) {
for (nextIndex = index - 1; nextIndex >= 0; nextIndex--) {
if (segs[nextIndex][0] === K_M) {
if (vec2.dist(origAnchor, segs[nextIndex][1] as vec2) < EPSILON) {
// Start Anchor
const startAnchor = vec2.clone(segs[nextIndex][1] as vec2)
vec2.add(startAnchor, startAnchor, delta)
segs[nextIndex][1] = startAnchor
nextIndex++
} else {
nextIndex = null
}
break
}
}
}
if (nextIndex !== null) {
if (segs[nextIndex][0] === K_C) {
const outHandle = vec2.clone(segs[nextIndex][1] as vec2)
vec2.add(outHandle, outHandle, delta)
segs[nextIndex][1] = outHandle
}
}
return [K_PATH, ...segs.flat()]
}
function dragHandle(
path: PathType,
index: number,
type: string,
delta: vec2,
breakCorner = false
) {
const segs = Array.from(iterateSegment(path))
const draggingSeg = segs[index]
if (type === K('handle-in')) {
const origInHandle = vec2.clone(draggingSeg[2] as vec2)
const inHandle = vec2.add(vec2.create(), origInHandle, delta)
draggingSeg[2] = inHandle
// Out handle
let nextIndex = index + 1 < segs.length ? index + 1 : null
if (nextIndex !== null && segs[nextIndex][0] === K_Z) {
for (nextIndex = index - 1; nextIndex >= 0; nextIndex--) {
if (segs[nextIndex][0] === K_M) {
if (
vec2.dist(draggingSeg[3] as vec2, segs[nextIndex][1] as vec2) <
EPSILON
) {
nextIndex++
} else {
nextIndex = null
}
break
}
}
}
if (nextIndex !== null && segs[nextIndex][0] === K_C) {
const anchor = draggingSeg[3] as vec2
const outHandle = vec2.clone(segs[nextIndex][1] as vec2)
const outHandleDir = vec2.sub(vec2.create(), outHandle, anchor)
const isSmooth =
Math.abs(
vec2.angle(
vec2.sub(vec2.create(), anchor, origInHandle),
outHandleDir
)
) < EPSILON
if (isSmooth) {
const dir = vec2.normalize(
vec2.create(),
vec2.sub(vec2.create(), anchor, inHandle)
)
const scale =
vec2.dist(anchor, inHandle) / vec2.dist(anchor, origInHandle)
const len = vec2.len(outHandleDir) * scale
segs[nextIndex][1] = vec2.scaleAndAdd(vec2.create(), anchor, dir, len)
}
}
} else if (type === K('handle-out')) {
console.log('handle-out')
const origOutHandle = vec2.clone(draggingSeg[1] as vec2)
const outHandle = vec2.add(vec2.create(), origOutHandle, delta)
draggingSeg[1] = outHandle
// In handle
let prevIndex = index - 1 >= 0 ? index - 1 : null
if (prevIndex !== null && segs[prevIndex][0] === K_M) {
const anchor = segs[prevIndex][1] as vec2
for (prevIndex = index + 1; prevIndex < segs.length; prevIndex++) {
if (segs[prevIndex][0] === K_Z) {
if (
!(
segs[--prevIndex][0] === K_C &&
vec2.dist(segs[prevIndex][3] as vec2, anchor) < EPSILON
)
) {
prevIndex = null
}
break
}
}
}
if (prevIndex !== null && segs[prevIndex][0] === K_C) {
const anchor = segs[prevIndex][3] as vec2
const inHandle = vec2.clone(segs[prevIndex][2] as vec2)
const inHandleDir = vec2.sub(vec2.create(), inHandle, anchor)
const isSmooth =
Math.abs(
vec2.angle(
vec2.sub(vec2.create(), anchor, origOutHandle),
inHandleDir
)
) < EPSILON
if (isSmooth) {
const dir = vec2.normalize(
vec2.create(),
vec2.sub(vec2.create(), anchor, outHandle)
)
const scale =
vec2.dist(anchor, outHandle) / vec2.dist(anchor, origOutHandle)
const len = vec2.len(inHandleDir) * scale
segs[prevIndex][2] = vec2.scaleAndAdd(vec2.create(), anchor, dir, len)
}
}
}
return [K_PATH, ...segs.flat()]
}
function closedQ(path: PathType) {
return path.slice(-1)[0] === K_Z
}
function toBeziers(path: PathType) {
const ret: PathType = [K_PATH]
for (const line of iterateSegment(path)) {
const [cmd, ...args] = line
let s: Vec2 = [NaN, NaN]
switch (cmd) {
case K_M:
case K_C:
s = args[0]
ret.push(...line)
break
case K_Z:
ret.push(...line)
break
case K_L:
ret.push(K_L, s, ...args, ...args)
break
default:
throw new Error(`Invalid d-path command: ${printExp(cmd)}`)
}
}
return ret
}
function pathLength(_path: PathType) {
const path = createPaperPath(_path)
getMalPathFromPaper(path)
return path.length
}
function pathJoin(...paths: PathType[]) {
let mergedPath = paths
.map(p => p.slice(1))
.flat()
.map((v, i) => (i > 0 && v === K_M ? K_L : v))
.filter(v => v !== K_Z)
// Delete zero-length :L command
mergedPath = Array.from(iterateCurve(mergedPath))
.filter(
c => !(c[0] === K_L && vec2.dist(c[1] as vec2, c[2] as vec2) < EPSILON)
)
.map(c => (c[0] === K_M ? c : [c[0], ...c.slice(2)]))
.flat()
// close path if possible
if (mergedPath.length >= 4) {
const segs = Array.from(iterateSegment(mergedPath))
const lastSeg = segs[segs.length - 1]
const firstPt = segs[0][1] as vec2
const lastPt = lastSeg[lastSeg.length - 1] as vec2
if (vec2.dist(firstPt, lastPt) < EPSILON) {
if (lastSeg[0] === K_L) {
segs.splice(segs.length - 1, 1, [K_Z])
} else if (lastSeg[0] === K_C) {
segs.push([K_Z])
}
mergedPath = segs.flat()
}
}
return [K_PATH, ...mergedPath]
}
function pathTransform(transform: mat2d, path: PathType) {
const ret = path.map(pt => {
if (typeof pt === 'string') {
return pt
} else {
return vec2.transformMat2d(vec2.create(), pt as vec2, transform)
}
})
return ret
}
// Get Path Property
type LengthBasedFunctionType = (t: number, path: PathType) => MalVal
function convertToNormalizedFunction(f: LengthBasedFunctionType) {
return (t: number, path: PathType) => {
const paperPath = createPaperPath(path)
return f(t * paperPath.length, path)
}
}
function getPropertyAtLength(
offset: number,
path: PathType,
methodName: 'getTangentAt' | 'getLocationAt' | 'getNormalAt'
) {
const paperPath = createPaperPath(path)
const ret = getChildPaperPathByLength(paperPath, offset)
if (!ret) {
return undefined
}
const {offset: childOffset, path: childPath} = ret
return childPath[methodName](childOffset)
}
function normalAtLength(offset: number, path: PathType) {
const ret = getPropertyAtLength(offset, path, 'getNormalAt') as paper.Point
return [ret.x, ret.y]
}
function positionAtLength(offset: number, path: PathType) {
const {point} = getPropertyAtLength(
offset,
path,
'getLocationAt'
) as paper.CurveLocation
return [point.x, point.y]
}
function tangentAtLength(offset: number, path: PathType) {
const ret = getPropertyAtLength(offset, path, 'getTangentAt') as paper.Point
return [ret.x, ret.y]
}
function angleAtLength(offset: number, path: PathType) {
const tangent = getPropertyAtLength(
offset,
path,
'getTangentAt'
) as paper.Point
return tangent.angleInRadians
}
function alignMatrixAtLength(offset: number, path: PathType): MalVal {
const paperPath = createPaperPath(path)
const ret = getChildPaperPathByLength(paperPath, offset)
if (!ret) {
return mat2d.create() as MalVal
}
const {offset: childOffset, path: childPath} = ret
const tangent = childPath.getTangentAt(childOffset)
const {point} = childPath.getLocationAt(childOffset)
const mat = mat2d.fromTranslation(mat2d.create(), [point.x, point.y])
mat2d.rotate(mat, mat, tangent.angleInRadians)
return mat as MalVal
}
// Iteration
function pathFlatten(flatness: number, path: PathType) {
const paperPath = createPaperPath(path)
paperPath.flatten(flatness)
return getMalPathFromPaper(paperPath)
}
// Binary Operation
function createPolynominalBooleanOperator(methodName: string) {
return (...paths: PathType[]) => {
if (paths.length === 0) {
return createEmptyPath()
} else if (paths.length === 1) {
return paths[0]
}
const paperPaths = paths.map(createPaperPath) as paper.PathItem[]
const result = paperPaths
.slice(1)
.reduce((a, b) => (a as any)[methodName](b), paperPaths[0])
return getMalPathFromPaper(result)
}
}
// Shape Functions
function pathArc(
[x, y]: vec2,
r: number,
start: number,
end: number
): MalVal[] {
const min = Math.min(start, end)
const max = Math.max(start, end)
let points: number[][] = [[x + r * Math.cos(min), y + r * Math.sin(min)]]
const minSeg = Math.ceil(min / HALF_PI - EPSILON)
const maxSeg = Math.floor(max / HALF_PI + EPSILON)
// For trim
const t1 = unsignedMod(min / HALF_PI, 1)
const t2 = unsignedMod(max / HALF_PI, 1)
// quadrant
// 2 | 3
// ---+---
// 1 | 0
if (minSeg > maxSeg) {
// Less than 90 degree
const bezier = UNIT_QUAD_BEZIER.split(t1, t2)
const q = unsignedMod(Math.floor(min / HALF_PI), 4),
sin = SIN_Q[q],
cos = COS_Q[q]
points.push(
...bezier.points
.slice(1)
.map(p => [
x + r * (p.x * cos - p.y * sin),
y + r * (p.x * sin + p.y * cos),
])
)
} else {
// More than 90 degree
// Add beginning segment
if (Math.abs(minSeg * HALF_PI - min) > EPSILON) {
const bezier = UNIT_QUAD_BEZIER.split(t1, 1)
const q = unsignedMod(minSeg - 1, 4),
sin = SIN_Q[q],
cos = COS_Q[q]
points.push(
...bezier.points
.slice(1)
.map(p => [
x + r * (p.x * cos - p.y * sin),
y + r * (p.x * sin + p.y * cos),
])
)
}
// Cubic bezier points of the quarter circle in quadrant 0 in position [0, 0]
const qpoints: number[][] = [
[r, KAPPA * r],
[KAPPA * r, r],
[0, r],
]
// Add arc by every quadrant
for (let seg = minSeg; seg < maxSeg; seg++) {
const q = unsignedMod(seg, 4),
sin = SIN_Q[q],
cos = COS_Q[q]
points.push(
...qpoints.map(([px, py]) => [
x + px * cos - py * sin,
y + px * sin + py * cos,
])
)
}
// Add terminal segment
if (Math.abs(maxSeg * HALF_PI - max) > EPSILON) {
const bezier = UNIT_QUAD_BEZIER.split(0, t2)
const q = unsignedMod(maxSeg, 4),
sin = SIN_Q[q],
cos = COS_Q[q]
points.push(
...bezier.points
.slice(1)
.map(p => [
x + r * (p.x * cos - p.y * sin),
y + r * (p.x * sin + p.y * cos),
])
)
}
}
if (end < start) {
points = points.reverse()
}
return [
K_PATH,
K_M,
points[0],
...partition(3, points.slice(1))
.map(pts => [K_C, ...pts])
.flat(),
]
}
function createHashMap(args: MalVal[]) {
for (let i = 0; i < args.length; i += 2) {
args[i] = (args[i] as string).slice(1)
}
return assocBang({}, ...args)
}
function offset(d: number, path: PathType, ...args: MalVal[]) {
const options = {
join: 'round',
cap: 'round',
...createHashMap(args),
} as OffsetOptions
const paperPath = createPaperPath(path)
const offsetPath = PaperOffset.offset(paperPath, d, options)
return getMalPathFromPaper(offsetPath)
}
function offsetStroke(d: number, path: PathType, ...args: MalVal[]) {
const options = {
join: 'round',
cap: 'round',
...createHashMap(args),
} as OffsetOptions
const paperPath = createPaperPath(path)
const offsetPath = PaperOffset.offsetStroke(paperPath, d, options)
return getMalPathFromPaper(offsetPath)
}
/**
* Trim path by relative length from each ends
*/
function trimByLength(start: number, end: number, path: PathType) {
// In case no change
if (start < EPSILON && end < EPSILON) {
return path
}
const paperPath = createPaperPath(path)
// Convert end parameter to a distance from the beginning of path
const length = paperPath.length
end = length - end
// Make positiove
start = clamp(start, 0, length)
end = clamp(end, 0, length)
// Swap to make sure start < end
if (start > end) {
return createEmptyPath()
}
if (paperPath.children.length > 1) {
return getMalPathFromPaper(paperPath)
} else {
const childPath = paperPath.children[0] as paper.Path
const cloned = childPath.clone()
const trimmed = cloned.splitAt(start)
if (!trimmed) {
return createEmptyPath()
}
trimmed.splitAt(end - start)
if (!trimmed) {
return createEmptyPath()
}
return getMalPathFromPaper(trimmed)
}
}
/**
* Trim path by normalized T
*/
function pathTrim(t1: number, t2: number, path: PathType) {
const paperPath = createPaperPath(path)
const length = paperPath.length
if (t1 > t2) {
;[t1, t2] = [t2, t1]
}
const start = t1 * length,
end = (1 - t2) * length
return trimByLength(start, end, path)
}
const canvasCtx = (() => {
const canvas = globalThis.document
? document.createElement('canvas')
: new OffscreenCanvas(10, 10)
const ctx = canvas.getContext('2d')
if (!ctx) {
throw new Error('Cannot create canvas context')
}
return ctx
})()
/**
* Calc path bounds
*/
function pathBounds(path: PathType) {
// let top = -Infinity, left = -Infinity, right = Infinity, bottom = Infinity
let left = Infinity,
top = Infinity,
right = -Infinity,
bottom = -Infinity
if (path[0].toString().startsWith(K_PATH)) {
for (const [cmd, ...pts] of iterateCurve(path)) {
switch (cmd) {
case K_M: {
const pt = pts[0]
left = Math.min(left, pt[0])
top = Math.min(top, pt[1])
right = Math.max(right, pt[0])
bottom = Math.max(bottom, pt[1])
break
}
case K_L:
left = Math.min(left, pts[0][0], pts[1][0])
top = Math.min(top, pts[0][1], pts[1][1])
right = Math.max(right, pts[0][0], pts[1][0])
bottom = Math.max(bottom, pts[0][1], pts[1][1])
break
case K_C: {
const {x, y} = getBezier(pts).bbox()
left = Math.min(left, x.min)
top = Math.min(top, y.min)
right = Math.max(right, x.max)
bottom = Math.max(bottom, y.max)
break
}
}
}
} else {
// text?
// Text representation:
// [:text "Text" [x y] {:option1 value1...}]
const [text, [x, y], options] = path.slice(1) as [
string,
[number, number],
...MalVal[]
]
const settings: any = {
size: 12,
font: 'Fira Code',
align: 'center',
baseline: 'middle',
}
if (isMap(options)) {
for (const [k, v] of Object.entries(options)) {
settings[(k as string).slice(1)] = v
}
}
canvasCtx.font = `${settings.size}px ${settings.font}`
canvasCtx.textAlign = settings.align as CanvasTextAlign
canvasCtx.textBaseline = settings.baseline as CanvasTextBaseline
const lines = text.split('\n')
for (let i = 0; i < lines.length; i++) {
const measure = canvasCtx.measureText(lines[i])
const yOffset = i * settings.size
left = Math.min(left, x - measure.actualBoundingBoxLeft)
right = Math.max(right, x + measure.actualBoundingBoxRight)
top = Math.min(top, y + yOffset - measure.actualBoundingBoxAscent)
bottom = Math.max(bottom, y + yOffset + measure.actualBoundingBoxDescent)
}
}
if (isFinite(left + top + bottom + right)) {
return [left, top, right - left, bottom - top]
} else {
return null
}
}
function nearestOffset(pos: number[], malPath: PathType) {
const path = createPaperPath(malPath)
const location = path.getNearestLocation(new paper.Point(pos[0], pos[1]))
return location.offset / path.length
}
function nearestPoint(pos: number[], malPath: PathType) {
const path = createPaperPath(malPath)
const point = path.getNearestLocation(new paper.Point(pos[0], pos[1])).point
return [point.x, point.y]
}
function insideQ(pos: number[], malPath: PathType) {
const path = convertToPath2D(malPath)
return canvasContext.isPointInPath(path, pos[0], pos[1])
}
function intersections(_a: PathType, _b: PathType) {
const a = createPaperPath(_a),
b = createPaperPath(_b)
return a.getIntersections(b).map(cl => [cl.point.x, cl.point.y])
}
const voronoi = new Voronoi()
function pathVoronoi(
mode: 'edge' | 'cell' = 'edge',
[left, top, width, height]: number[],
pts: number[][]
) {
const bbox = {xl: left, xr: left + width, yt: top, yb: top + height}
const sites = pts.map(([x, y]) => ({x, y}), pts)
const diagram = voronoi.compute(sites, bbox)
if (mode === 'edge') {
return [
K_PATH,
...diagram.edges
.map(({va, vb}) => [K_M, [va.x, va.y], K_L, [vb.x, vb.y]])
.flat(),
]
}
return [K_PATH]
}
const Exports = [
// Primitives
['path/arc', pathArc],
['path/voronoi', pathVoronoi],
['path/join', pathJoin],
['path/to-beziers', toBeziers],
['path/offset', offset],
['path/offset-stroke', offsetStroke],
['path/length', pathLength],
['path/closed?', closedQ],
// Modify
['path/drag-anchor', dragAnchor],
['path/drag-handle', dragHandle],
// Get Property
['path/position-at-length', positionAtLength],
['path/position-at', convertToNormalizedFunction(positionAtLength)],
['path/normal-at-length', normalAtLength],
['path/normal-at', convertToNormalizedFunction(normalAtLength)],
['path/tangent-at-length', tangentAtLength],
['path/tangent-at', convertToNormalizedFunction(tangentAtLength)],
['path/angle-at-length', angleAtLength],
['path/angle-at', convertToNormalizedFunction(angleAtLength)],
['path/align-at-length', alignMatrixAtLength],
['path/align-at', convertToNormalizedFunction(alignMatrixAtLength)],
// Boolean
['path/unite', createPolynominalBooleanOperator('unite')],
['path/intersect', createPolynominalBooleanOperator('intersect')],
['path/subtract', createPolynominalBooleanOperator('subtract')],
['path/exclude', createPolynominalBooleanOperator('exclude')],
['path/divide', createPolynominalBooleanOperator('divide')],
// Manipulation
['path/transform', pathTransform],
['path/trim', pathTrim],
['path/trim-by-length', trimByLength],
['path/flatten', pathFlatten],
// Utility
[
'path/split-segments',
([, ...path]: PathType) => Array.from(iterateSegment(path) as any),
],
['path/bounds', pathBounds],
['path/nearest-offset', nearestOffset],
['path/nearest-point', nearestPoint],
['path/inside?', insideQ],
['path/intersections', intersections],
] as [string, MalVal][]
const Exp = L(
S('do'),
...Exports.map(([sym, body]) => L(S('def'), S(sym), body))
)
;(globalThis as any)['glisp_library'] = Exp | the_stack |
import i18next from "i18next";
import { computed, runInAction } from "mobx";
import defined from "terriajs-cesium/Source/Core/defined";
import WebMercatorTilingScheme from "terriajs-cesium/Source/Core/WebMercatorTilingScheme";
import WebMapTileServiceImageryProvider from "terriajs-cesium/Source/Scene/WebMapTileServiceImageryProvider";
import URI from "urijs";
import containsAny from "../../../Core/containsAny";
import isDefined from "../../../Core/isDefined";
import TerriaError from "../../../Core/TerriaError";
import CatalogMemberMixin from "../../../ModelMixins/CatalogMemberMixin";
import GetCapabilitiesMixin from "../../../ModelMixins/GetCapabilitiesMixin";
import MappableMixin, { MapItem } from "../../../ModelMixins/MappableMixin";
import UrlMixin from "../../../ModelMixins/UrlMixin";
import { InfoSectionTraits } from "../../../Traits/TraitsClasses/CatalogMemberTraits";
import LegendTraits from "../../../Traits/TraitsClasses/LegendTraits";
import { RectangleTraits } from "../../../Traits/TraitsClasses/MappableTraits";
import WebMapTileServiceCatalogItemTraits, {
WebMapTileServiceAvailableLayerStylesTraits
} from "../../../Traits/TraitsClasses/WebMapTileServiceCatalogItemTraits";
import isReadOnlyArray from "../../../Core/isReadOnlyArray";
import CreateModel from "../../Definition/CreateModel";
import createStratumInstance from "../../Definition/createStratumInstance";
import LoadableStratum from "../../Definition/LoadableStratum";
import { BaseModel } from "../../Definition/Model";
import { ServiceProvider } from "./OwsInterfaces";
import proxyCatalogItemUrl from "../proxyCatalogItemUrl";
import StratumFromTraits from "../../Definition/StratumFromTraits";
import WebMapTileServiceCapabilities, {
CapabilitiesStyle,
ResourceUrl,
TileMatrixSetLink,
WmtsCapabilitiesLegend,
WmtsLayer
} from "./WebMapTileServiceCapabilities";
interface UsableTileMatrixSets {
identifiers: string[];
tileWidth: number;
tileHeight: number;
}
class GetCapabilitiesStratum extends LoadableStratum(
WebMapTileServiceCatalogItemTraits
) {
static stratumName = "wmtsServer";
static async load(
catalogItem: WebMapTileServiceCatalogItem,
capabilities?: WebMapTileServiceCapabilities
): Promise<GetCapabilitiesStratum> {
if (!isDefined(catalogItem.getCapabilitiesUrl)) {
throw new TerriaError({
title: i18next.t("models.webMapTileServiceCatalogItem.missingUrlTitle"),
message: i18next.t(
"models.webMapTileServiceCatalogItem.missingUrlMessage"
)
});
}
if (!isDefined(capabilities))
capabilities = await WebMapTileServiceCapabilities.fromUrl(
proxyCatalogItemUrl(
catalogItem,
catalogItem.getCapabilitiesUrl,
catalogItem.getCapabilitiesCacheDuration
)
);
return new GetCapabilitiesStratum(catalogItem, capabilities);
}
constructor(
readonly catalogItem: WebMapTileServiceCatalogItem,
readonly capabilities: WebMapTileServiceCapabilities
) {
super();
}
duplicateLoadableStratum(model: BaseModel): this {
return new GetCapabilitiesStratum(
model as WebMapTileServiceCatalogItem,
this.capabilities
) as this;
}
@computed
get layer(): string | undefined {
let layer: string | undefined;
if (this.catalogItem.uri !== undefined) {
const query: any = this.catalogItem.uri.query(true);
layer = query.layer;
}
return layer;
}
@computed
get info(): StratumFromTraits<InfoSectionTraits>[] {
const result: StratumFromTraits<InfoSectionTraits>[] = [
createStratumInstance(InfoSectionTraits, {
name: i18next.t(
"models.webMapTileServiceCatalogItem.getCapabilitiesUrl"
),
content: this.catalogItem.getCapabilitiesUrl
})
];
let layerAbstract: string | undefined;
const layer = this.capabilitiesLayer;
if (
layer &&
layer.Abstract &&
!containsAny(
layer.Abstract,
WebMapTileServiceCatalogItem.abstractsToIgnore
)
) {
result.push(
createStratumInstance(InfoSectionTraits, {
name: i18next.t(
"models.webMapTileServiceCatalogItem.dataDescription"
),
content: layer.Abstract
})
);
layerAbstract = layer.Abstract;
}
const serviceIdentification =
this.capabilities && this.capabilities.ServiceIdentification;
if (serviceIdentification) {
if (
serviceIdentification.Abstract &&
!containsAny(
serviceIdentification.Abstract,
WebMapTileServiceCatalogItem.abstractsToIgnore
) &&
serviceIdentification.Abstract !== layerAbstract
) {
result.push(
createStratumInstance(InfoSectionTraits, {
name: i18next.t(
"models.webMapTileServiceCatalogItem.serviceDescription"
),
content: serviceIdentification.Abstract
})
);
}
// Show the Access Constraints if it isn't "none" (because that's the default, and usually a lie).
if (
serviceIdentification.AccessConstraints &&
!/^none$/i.test(serviceIdentification.AccessConstraints)
) {
result.push(
createStratumInstance(InfoSectionTraits, {
name: i18next.t(
"models.webMapTileServiceCatalogItem.accessConstraints"
),
content: serviceIdentification.AccessConstraints
})
);
}
// Show the Access Constraints if it isn't "none" (because that's the default, and usually a lie).
if (
serviceIdentification.Fees &&
!/^none$/i.test(serviceIdentification.Fees)
) {
result.push(
createStratumInstance(InfoSectionTraits, {
name: i18next.t("models.webMapTileServiceCatalogItem.fees"),
content: serviceIdentification.Fees
})
);
}
}
const serviceProvider =
this.capabilities && this.capabilities.ServiceProvider;
if (serviceProvider) {
result.push(
createStratumInstance(InfoSectionTraits, {
name: i18next.t("models.webMapTileServiceCatalogItem.serviceContact"),
content: getServiceContactInformation(serviceProvider) || ""
})
);
}
if (!isDefined(this.catalogItem.tileMatrixSet)) {
result.push(
createStratumInstance(InfoSectionTraits, {
name: i18next.t(
"models.webMapTileServiceCatalogItem.noUsableTileMatrixTitle"
),
content: i18next.t(
"models.webMapTileServiceCatalogItem.noUsableTileMatrixMessage"
)
})
);
}
return result;
}
@computed
get infoSectionOrder(): string[] {
return [
i18next.t("preview.disclaimer"),
i18next.t("models.webMapTileServiceCatalogItem.noUsableTileMatrixTitle"),
i18next.t("description.name"),
i18next.t("preview.datasetDescription"),
i18next.t("models.webMapTileServiceCatalogItem.dataDescription"),
i18next.t("preview.serviceDescription"),
i18next.t("models.webMapTileServiceCatalogItem.serviceDescription"),
i18next.t("preview.resourceDescription"),
i18next.t("preview.licence"),
i18next.t("preview.accessConstraints"),
i18next.t("models.webMapTileServiceCatalogItem.accessConstraints"),
i18next.t("models.webMapTileServiceCatalogItem.fees"),
i18next.t("preview.author"),
i18next.t("preview.contact"),
i18next.t("models.webMapTileServiceCatalogItem.serviceContact"),
i18next.t("preview.created"),
i18next.t("preview.modified"),
i18next.t("preview.updateFrequency"),
i18next.t("models.webMapTileServiceCatalogItem.getCapabilitiesUrl")
];
}
@computed
get shortReport() {
return !isDefined(this.catalogItem.tileMatrixSet)
? `${i18next.t(
"models.webMapTileServiceCatalogItem.noUsableTileMatrixTitle"
)}: ${i18next.t(
"models.webMapTileServiceCatalogItem.noUsableTileMatrixMessage"
)}`
: undefined;
}
@computed
get legends() {
const layerAvailableStyles = this.catalogItem.availableStyles.find(
candidate => candidate.layerName === this.capabilitiesLayer?.Identifier
)?.styles;
const layerStyle = layerAvailableStyles?.find(
candidate => candidate.identifier === this.catalogItem.style
);
if (isDefined(layerStyle?.legend)) {
return [
createStratumInstance(LegendTraits, {
url: layerStyle!.legend.url,
urlMimeType: layerStyle!.legend.urlMimeType
})
];
}
}
@computed
get capabilitiesLayer(): Readonly<WmtsLayer | undefined> {
let result = this.catalogItem.layer
? this.capabilities.findLayer(this.catalogItem.layer)
: undefined;
return result;
}
@computed
get availableStyles(): StratumFromTraits<
WebMapTileServiceAvailableLayerStylesTraits
>[] {
const result: any = [];
if (!this.capabilities) {
return result;
}
const layer = this.capabilitiesLayer;
if (!layer) {
return result;
}
const styles: ReadonlyArray<CapabilitiesStyle> =
layer && layer.Style
? Array.isArray(layer.Style)
? layer.Style
: [layer.Style]
: [];
result.push({
layerName: layer?.Identifier,
styles: styles.map((style: CapabilitiesStyle) => {
let wmtsLegendUrl: WmtsCapabilitiesLegend | undefined = isReadOnlyArray(
style.LegendURL
)
? style.LegendURL[0]
: style.LegendURL;
let legendUri, legendMimeType;
if (wmtsLegendUrl && wmtsLegendUrl["xlink:href"]) {
legendUri = new URI(decodeURIComponent(wmtsLegendUrl["xlink:href"]));
legendMimeType = wmtsLegendUrl.Format;
}
const legend = !legendUri
? undefined
: createStratumInstance(LegendTraits, {
url: legendUri.toString(),
urlMimeType: legendMimeType
});
return {
identifier: style.Identifier,
isDefault: style.isDefault,
abstract: style.Abstract,
legend: legend
};
})
});
return result;
}
@computed
get usableTileMatrixSets() {
const usableTileMatrixSets: { [key: string]: UsableTileMatrixSets } = {
"urn:ogc:def:wkss:OGC:1.0:GoogleMapsCompatible": {
identifiers: ["0"],
tileWidth: 256,
tileHeight: 256
}
};
const standardTilingScheme = new WebMercatorTilingScheme();
const matrixSets = this.capabilities.tileMatrixSets;
if (matrixSets === undefined) {
return;
}
for (let i = 0; i < matrixSets.length; i++) {
const matrixSet = matrixSets[i];
if (
!matrixSet.SupportedCRS ||
(!/EPSG.*900913/.test(matrixSet.SupportedCRS) &&
!/EPSG.*3857/.test(matrixSet.SupportedCRS))
) {
continue;
}
// Usable tile matrix sets must have a single 256x256 tile at the root.
const matrices = matrixSet.TileMatrix;
if (!isDefined(matrices) || matrices.length < 1) {
continue;
}
const levelZeroMatrix = matrices[0];
if (!isDefined(levelZeroMatrix.TopLeftCorner)) {
continue;
}
var levelZeroTopLeftCorner = levelZeroMatrix.TopLeftCorner.split(" ");
var startX = parseFloat(levelZeroTopLeftCorner[0]);
var startY = parseFloat(levelZeroTopLeftCorner[1]);
const rectangleInMeters = standardTilingScheme.rectangleToNativeRectangle(
standardTilingScheme.rectangle
);
if (
Math.abs(startX - rectangleInMeters.west) > 1 ||
Math.abs(startY - rectangleInMeters.north) > 1
) {
continue;
}
if (defined(matrixSet.TileMatrix) && matrixSet.TileMatrix.length > 0) {
const ids = matrixSet.TileMatrix.map(function(item) {
return item.Identifier;
});
const firstTile = matrixSet.TileMatrix[0];
usableTileMatrixSets[matrixSet.Identifier] = {
identifiers: ids,
tileWidth: firstTile.TileWidth,
tileHeight: firstTile.TileHeight
};
}
}
return usableTileMatrixSets;
}
@computed
get rectangle(): StratumFromTraits<RectangleTraits> | undefined {
const layer: WmtsLayer | undefined = this.capabilitiesLayer;
if (!layer) {
return;
}
const bbox = layer.WGS84BoundingBox;
if (bbox) {
const lowerCorner = bbox.LowerCorner.split(" ");
const upperCorner = bbox.UpperCorner.split(" ");
return {
west: parseFloat(lowerCorner[0]),
south: parseFloat(lowerCorner[1]),
east: parseFloat(upperCorner[0]),
north: parseFloat(upperCorner[1])
};
}
}
@computed get style(): string | undefined {
if (!isDefined(this.catalogItem.layer)) return;
const layerAvailableStyles = this.availableStyles.find(
candidate => candidate.layerName === this.capabilitiesLayer?.Identifier
)?.styles;
return (
layerAvailableStyles?.find(style => style.isDefault)?.identifier ??
layerAvailableStyles?.[0]?.identifier
);
}
}
class WebMapTileServiceCatalogItem extends MappableMixin(
GetCapabilitiesMixin(
UrlMixin(
CatalogMemberMixin(CreateModel(WebMapTileServiceCatalogItemTraits))
)
)
) {
/**
* The collection of strings that indicate an Abstract property should be ignored. If these strings occur anywhere
* in the Abstract, the Abstract will not be used. This makes it easy to filter out placeholder data like
* Geoserver's "A compliant implementation of WMTS..." stock abstract.
*/
static abstractsToIgnore = [
"A compliant implementation of WMTS service.",
"This is the reference implementation of WMTS 1.0.0"
];
// hide elements in the info section which might show information about the datasource
_sourceInfoItemNames = [
i18next.t("models.webMapTileServiceCatalogItem.getCapabilitiesUrl")
];
static readonly type = "wmts";
get type() {
return WebMapTileServiceCatalogItem.type;
}
async createGetCapabilitiesStratumFromParent(
capabilities: WebMapTileServiceCapabilities
) {
const stratum = await GetCapabilitiesStratum.load(this, capabilities);
runInAction(() => {
this.strata.set(GetCapabilitiesMixin.getCapabilitiesStratumName, stratum);
});
}
protected async forceLoadMetadata(): Promise<void> {
if (
this.strata.get(GetCapabilitiesMixin.getCapabilitiesStratumName) !==
undefined
)
return;
const stratum = await GetCapabilitiesStratum.load(this);
runInAction(() => {
this.strata.set(GetCapabilitiesMixin.getCapabilitiesStratumName, stratum);
});
}
@computed get cacheDuration(): string {
if (isDefined(super.cacheDuration)) {
return super.cacheDuration;
}
return "1d";
}
@computed
get imageryProvider() {
const stratum = <GetCapabilitiesStratum>(
this.strata.get(GetCapabilitiesMixin.getCapabilitiesStratumName)
);
if (
!isDefined(this.layer) ||
!isDefined(this.url) ||
!isDefined(stratum) ||
!isDefined(this.style)
) {
return;
}
const layer = stratum.capabilitiesLayer;
const layerIdentifier = layer?.Identifier;
if (!isDefined(layer) || !isDefined(layerIdentifier)) {
return;
}
let format: string = "image/png";
const formats = layer.Format;
if (
formats &&
formats?.indexOf("image/png") === -1 &&
formats?.indexOf("image/jpeg") !== -1
) {
format = "image/jpeg";
}
// if layer has defined ResourceURL we should use it because some layers support only Restful encoding. See #2927
const resourceUrl: ResourceUrl | ResourceUrl[] | undefined =
layer.ResourceURL;
let baseUrl: string = new URI(this.url).search("").toString();
if (resourceUrl) {
if (Array.isArray(resourceUrl)) {
for (let i = 0; i < resourceUrl.length; i++) {
const url: ResourceUrl = resourceUrl[i];
if (
url.format.indexOf(format) !== -1 ||
url.format.indexOf("png") !== -1
) {
baseUrl = url.template;
}
}
} else {
if (
format === resourceUrl.format ||
resourceUrl.format.indexOf("png") !== -1
) {
baseUrl = resourceUrl.template;
}
}
}
const tileMatrixSet = this.tileMatrixSet;
if (!isDefined(tileMatrixSet)) {
return;
}
const imageryProvider = new WebMapTileServiceImageryProvider({
url: proxyCatalogItemUrl(this, baseUrl),
layer: layerIdentifier,
style: this.style,
tileMatrixSetID: tileMatrixSet.id,
tileMatrixLabels: tileMatrixSet.labels,
minimumLevel: tileMatrixSet.minLevel,
maximumLevel: tileMatrixSet.maxLevel,
tileWidth: tileMatrixSet.tileWidth,
tileHeight: tileMatrixSet.tileHeight,
tilingScheme: new WebMercatorTilingScheme(),
format,
credit: this.attribution
});
return imageryProvider;
}
@computed
get tileMatrixSet():
| {
id: string;
labels: string[];
maxLevel: number;
minLevel: number;
tileWidth: number;
tileHeight: number;
}
| undefined {
const stratum = <GetCapabilitiesStratum>(
this.strata.get(GetCapabilitiesMixin.getCapabilitiesStratumName)
);
if (!this.layer) {
return;
}
const layer = stratum.capabilitiesLayer;
if (!layer) {
return;
}
const usableTileMatrixSets = stratum.usableTileMatrixSets;
let tileMatrixSetLinks: TileMatrixSetLink[] = [];
if (layer?.TileMatrixSetLink) {
if (Array.isArray(layer?.TileMatrixSetLink)) {
tileMatrixSetLinks = [...layer?.TileMatrixSetLink];
} else {
tileMatrixSetLinks = [layer.TileMatrixSetLink];
}
}
let tileMatrixSetId: string =
"urn:ogc:def:wkss:OGC:1.0:GoogleMapsCompatible";
let maxLevel: number = 0;
let minLevel: number = 0;
let tileWidth: number = 256;
let tileHeight: number = 256;
let tileMatrixSetLabels: string[] = [];
for (let i = 0; i < tileMatrixSetLinks.length; i++) {
const tileMatrixSet = tileMatrixSetLinks[i].TileMatrixSet;
if (usableTileMatrixSets && usableTileMatrixSets[tileMatrixSet]) {
tileMatrixSetId = tileMatrixSet;
tileMatrixSetLabels = usableTileMatrixSets[tileMatrixSet].identifiers;
tileWidth = Number(usableTileMatrixSets[tileMatrixSet].tileWidth);
tileHeight = Number(usableTileMatrixSets[tileMatrixSet].tileHeight);
break;
}
}
if (Array.isArray(tileMatrixSetLabels)) {
const levels = tileMatrixSetLabels.map(label => {
const lastIndex = label.lastIndexOf(":");
return Math.abs(Number(label.substring(lastIndex + 1)));
});
maxLevel = levels.reduce((currentMaximum, level) => {
return level > currentMaximum ? level : currentMaximum;
}, 0);
minLevel = levels.reduce((currentMaximum, level) => {
return level < currentMaximum ? level : currentMaximum;
}, 0);
}
return {
id: tileMatrixSetId,
labels: tileMatrixSetLabels,
maxLevel: maxLevel,
minLevel: minLevel,
tileWidth: tileWidth,
tileHeight: tileHeight
};
}
protected forceLoadMapItems(): Promise<void> {
return Promise.resolve();
}
@computed
get mapItems(): MapItem[] {
if (isDefined(this.imageryProvider)) {
return [
{
alpha: this.opacity,
show: this.show,
imageryProvider: this.imageryProvider,
clippingRectangle: this.clipToRectangle
? this.cesiumRectangle
: undefined
}
];
}
return [];
}
protected get defaultGetCapabilitiesUrl(): string | undefined {
if (this.uri) {
return this.uri
.clone()
.setSearch({
service: "WMTS",
version: "1.0.0",
request: "GetCapabilities"
})
.toString();
} else {
return undefined;
}
}
}
export function getServiceContactInformation(contactInfo: ServiceProvider) {
let text = "";
if (contactInfo.ProviderName && contactInfo.ProviderName.length > 0) {
text += contactInfo.ProviderName + "<br/>";
}
if (contactInfo.ProviderSite && contactInfo.ProviderSite["xlink:href"]) {
text += contactInfo.ProviderSite["xlink:href"] + "<br/>";
}
const serviceContact = contactInfo.ServiceContact;
if (serviceContact) {
const invidualName = serviceContact.InvidualName;
if (invidualName && invidualName.length > 0) {
text += invidualName + "<br/>";
}
const contactInfo = serviceContact.ContactInfo?.Address;
if (
contactInfo &&
isDefined(contactInfo.ElectronicMailAddress) &&
contactInfo.ElectronicMailAddress.length > 0
) {
text += `[${contactInfo.ElectronicMailAddress}](mailto:${contactInfo.ElectronicMailAddress})`;
}
}
return text;
}
export default WebMapTileServiceCatalogItem; | the_stack |
import { arrayRemoveItem, asyncOperation } from '@deepkit/core';
import { Host } from './host';
import { createConnection, Socket } from 'net';
import { connect as createTLSConnection, TLSSocket } from 'tls';
import { Command } from './command/command';
import { stringifyType, Type, uuid } from '@deepkit/type';
import { BSONBinarySerializer, getBSONSerializer, getBSONSizer, Writer } from '@deepkit/bson';
import { HandshakeCommand } from './command/handshake';
import { MongoClientConfig } from './config';
import { MongoError } from './error';
// @ts-ignore
import * as turbo from 'turbo-net';
import { DatabaseTransaction } from '@deepkit/orm';
import { CommitTransactionCommand } from './command/commitTransaction';
import { AbortTransactionCommand } from './command/abortTransaction';
export enum MongoConnectionStatus {
pending = 'pending',
connecting = 'connecting',
connected = 'connected',
disconnected = 'disconnected',
}
export interface ConnectionRequest {
writable?: boolean;
nearest?: boolean;
}
export class MongoConnectionPool {
protected connectionId: number = 0;
/**
* Connections, might be in any state, not necessarily connected.
*/
public connections: MongoConnection[] = [];
protected queue: ((connection: MongoConnection) => void)[] = [];
protected nextConnectionClose: Promise<boolean> = Promise.resolve(true);
constructor(protected config: MongoClientConfig,
protected serializer: BSONBinarySerializer) {
}
protected async waitForAllConnectionsToConnect(throws: boolean = false): Promise<void> {
const promises: Promise<any>[] = [];
for (const connection of this.connections) {
if (connection.connectingPromise) {
promises.push(connection.connectingPromise);
}
}
if (promises.length) {
if (throws) {
await Promise.all(promises);
} else {
await Promise.allSettled(promises);
}
}
}
public async connect() {
await this.ensureHostsConnected(true);
}
public close() {
//import to work on the copy, since Connection.onClose modifies this.connections.
const connections = this.connections.slice(0);
for (const connection of connections) {
connection.close();
}
}
public async ensureHostsConnected(throws: boolean = false) {
//make sure each host has at least one connection
//getHosts automatically updates hosts (mongodb-srv) and returns new one,
//so we don't need any interval to automatically update it.
const hosts = await this.config.getHosts();
for (const host of hosts) {
if (host.connections.length > 0) continue;
this.newConnection(host);
}
await this.waitForAllConnectionsToConnect(throws);
}
protected findHostForRequest(hosts: Host[], request: ConnectionRequest): Host {
//todo, handle request.nearest
for (const host of hosts) {
if (request.writable && host.isWritable()) return host;
if (!request.writable && host.isReadable()) return host;
}
throw new MongoError(`Could not find host for connection request. (writable=${request.writable}, hosts=${hosts.length})`);
}
protected createAdditionalConnectionForRequest(request: ConnectionRequest): MongoConnection {
const hosts = this.config.hosts;
const host = this.findHostForRequest(hosts, request);
return this.newConnection(host);
}
protected newConnection(host: Host): MongoConnection {
const connection = new MongoConnection(this.connectionId++, host, this.config, this.serializer, (connection) => {
arrayRemoveItem(host.connections, connection);
arrayRemoveItem(this.connections, connection);
//onClose does not automatically reconnect. Only new commands re-establish connections.
}, (connection) => {
this.release(connection);
});
host.connections.push(connection);
this.connections.push(connection);
return connection;
}
protected release(connection: MongoConnection) {
if (this.queue.length) {
const waiter = this.queue.shift();
if (waiter) {
waiter(connection);
return;
}
}
connection.reserved = false;
// console.log('release', connection.id, JSON.stringify(this.config.options.maxIdleTimeMS));
connection.cleanupTimeout = setTimeout(() => {
if (this.connections.length <= this.config.options.minPoolSize) {
return;
}
connection.close();
}, this.config.options.maxIdleTimeMS);
}
/**
* Returns an existing or new connection, that needs to be released once done using it.
*/
async getConnection(request: ConnectionRequest = {}): Promise<MongoConnection> {
await this.ensureHostsConnected(true);
for (const connection of this.connections) {
if (!connection.isConnected()) continue;
if (connection.reserved) continue;
if (request.nearest) throw new Error('Nearest not implemented yet');
if (request.writable && !connection.host.isWritable()) continue;
if (!request.writable) {
if (connection.host.isSecondary() && !this.config.options.secondaryReadAllowed) continue;
if (!connection.host.isReadable()) continue;
}
connection.reserved = true;
if (connection.cleanupTimeout) {
clearTimeout(connection.cleanupTimeout);
connection.cleanupTimeout = undefined;
}
return connection;
}
if (this.connections.length <= this.config.options.maxPoolSize) {
const connection = await this.createAdditionalConnectionForRequest(request);
connection.reserved = true;
return connection;
}
return asyncOperation((resolve) => {
this.queue.push(resolve);
});
}
}
export function readUint32LE(buffer: Uint8Array | ArrayBuffer, offset: number = 0): number {
return buffer[offset] + (buffer[offset + 1] * 2 ** 8) + (buffer[offset + 2] * 2 ** 16) + (buffer[offset + 3] * 2 ** 24);
}
export class MongoDatabaseTransaction extends DatabaseTransaction {
static txnNumber: bigint = 0n;
connection?: MongoConnection;
lsid?: { id: string };
txnNumber: bigint = 0n;
started: boolean = false;
applyTransaction(cmd: any) {
if (!this.lsid) return;
cmd.lsid = this.lsid;
cmd.txnNumber = this.txnNumber;
cmd.autocommit = false;
if (!this.started && !cmd.abortTransaction && !cmd.commitTransaction) {
this.started = true;
cmd.startTransaction = true;
}
}
async begin() {
if (!this.connection) return;
this.lsid = { id: uuid() };
this.txnNumber = MongoDatabaseTransaction.txnNumber++;
// const res = await this.connection.execute(new StartSessionCommand());
// this.lsid = res.id;
}
async commit() {
if (!this.connection) return;
if (this.ended) throw new Error('Transaction ended already');
await this.connection.execute(new CommitTransactionCommand());
this.ended = true;
this.connection.release();
}
async rollback() {
if (!this.connection) return;
if (this.ended) throw new Error('Transaction ended already');
if (!this.started) return;
await this.connection.execute(new AbortTransactionCommand());
this.ended = true;
this.connection.release();
}
}
export class MongoConnection {
protected messageId: number = 0;
status: MongoConnectionStatus = MongoConnectionStatus.pending;
public bufferSize: number = 2.5 * 1024 * 1024;
public connectingPromise?: Promise<void>;
public lastCommand?: { command: Command, promise?: Promise<any> };
public activeCommands: number = 0;
public executedCommands: number = 0;
public activeTransaction: boolean = false;
public reserved: boolean = false;
public cleanupTimeout: any;
protected socket: Socket | TLSSocket;
public transaction?: MongoDatabaseTransaction;
responseParser: ResponseParser;
protected boundSendMessage = this.sendMessage.bind(this);
constructor(
public id: number,
public readonly host: Host,
protected config: MongoClientConfig,
protected serializer: BSONBinarySerializer,
protected onClose: (connection: MongoConnection) => void,
protected onRelease: (connection: MongoConnection) => void,
) {
const responseParser = this.responseParser = new ResponseParser(this.onResponse.bind(this));
if (this.config.options.ssl === true) {
const options: { [name: string]: any } = {
host: host.hostname,
port: host.port,
timeout: config.options.connectTimeoutMS,
servername: host.hostname
};
const optional = {
ca: config.options.tlsCAFile,
key: config.options.tlsCertificateKeyFile || config.options.tlsCertificateFile,
cert: config.options.tlsCertificateFile,
passphrase: config.options.tlsCertificateKeyFilePassword,
rejectUnauthorized: config.options.rejectUnauthorized,
crl: config.options.tlsCRLFile,
checkServerIdentity: config.options.checkServerIdentity ? undefined : () => undefined,
};
for (const i in optional) {
if (optional[i]) options[i] = optional[i];
}
this.socket = createTLSConnection(options);
this.socket.on('data', (data) => this.responseParser.feed(data));
} else {
this.socket = createConnection({
host: host.hostname,
port: host.port,
timeout: config.options.connectTimeoutMS
});
this.socket.on('data', (data) => this.responseParser.feed(data));
// const socket = this.socket = turbo.connect(host.port, host.hostname);
// // this.socket.setNoDelay(true);
// const buffer = Buffer.allocUnsafe(this.bufferSize);
//
// function read() {
// socket.read(buffer, onRead);
// }
//
// function onRead(err: any, buf: Buffer, bytes: number) {
// if (!bytes) return;
// responseParser.feed(buf, bytes);
// read();
// }
//
// read();
}
this.socket.on('close', () => {
this.status = MongoConnectionStatus.disconnected;
onClose(this);
});
//important to catch it, so it doesn't bubble up
this.connect().catch(() => {
this.socket.end();
});
}
isConnected() {
return this.status === MongoConnectionStatus.connected;
}
isConnecting() {
return this.status === MongoConnectionStatus.connecting;
}
close() {
this.status = MongoConnectionStatus.disconnected;
this.socket.end();
}
public release() {
//connections attached to a transaction are not automatically released.
//only with commit/rollback actions
if (this.transaction && !this.transaction.ended) return;
if (this.transaction) this.transaction = undefined;
this.onRelease(this);
}
/**
* When a full message from the server was received.
*/
protected onResponse(response: Uint8Array) {
//we remove the header for the command
const size = readUint32LE(response);
const offset = 16 + 4 + 1; //MSG response
// const offset = 16 + 4 + 8 + 4 + 4; //QUERY_REPLY
const message = response.slice(offset, size);
if (!this.lastCommand) throw new Error(`Got a server response without active command`);
this.lastCommand.command.handleResponse(message);
}
/**
* Puts a command on the queue and executes it when queue is empty.
* A promises is return that is resolved with the when executed successfully, or rejected
* when timed out, parser error, or any other error.
*/
public async execute<T extends Command>(command: T): Promise<ReturnType<T['execute']>> {
if (this.status === MongoConnectionStatus.pending) await this.connect();
if (this.status === MongoConnectionStatus.disconnected) throw new Error('Disconnected');
if (this.lastCommand && this.lastCommand.promise) {
await this.lastCommand.promise;
}
this.lastCommand = { command };
this.activeCommands++;
this.executedCommands++;
command.sender = this.boundSendMessage;
try {
this.lastCommand.promise = command.execute(this.config, this.host, this.transaction);
return await this.lastCommand.promise;
} finally {
this.lastCommand = undefined;
this.activeCommands--;
}
}
protected sendMessage<T>(type: Type, message: T) {
const messageSerializer = getBSONSerializer(this.serializer, type);
const messageSizer = getBSONSizer(this.serializer, type);
const buffer = Buffer.allocUnsafe(16 + 4 + 1 + messageSizer(message));
// const buffer = Buffer.alloc(16 + 4 + 10 + 1 + 4 + 4 + calculateObjectSize(message));
const writer = new Writer(buffer);
//header, 16 bytes
const messageId = ++this.messageId;
writer.writeInt32(10); //messageLength, 4
writer.writeInt32(messageId); //requestID, 4
writer.writeInt32(0); //responseTo, 4
writer.writeInt32(2013); //OP_MSG, 4
// writer.writeInt32(2004); //OP_QUERY, 4
//OP_MSG, 5 bytes
writer.writeUint32(0); //message flags, 4
writer.writeByte(0); //kind 0, 1
// //OP_QUERY, 5 bytes
// writer.writeUint32(0); //message flags, 4
// writer.writeAsciiString('admin.$cmd'); //collection name, 10
// writer.writeByte(0); //null, 1
// writer.writeInt32(0); //skip, 4
// writer.writeInt32(1); //return, 4
try {
const section = messageSerializer(message);
// console.log('send', this.id, message);
writer.writeBuffer(section);
const messageLength = writer.offset;
writer.offset = 0;
writer.writeInt32(messageLength);
//detect backPressure
this.socket.write(buffer);
} catch (error) {
console.log('failed sending message', message, 'for type', stringifyType(type));
throw error;
}
}
async connect(): Promise<void> {
if (this.status === MongoConnectionStatus.disconnected) throw new Error('Connection disconnected');
if (this.status !== MongoConnectionStatus.pending) return;
this.status = MongoConnectionStatus.connecting;
this.connectingPromise = asyncOperation(async (resolve, reject) => {
this.socket.on('error', (error) => {
this.connectingPromise = undefined;
this.status = MongoConnectionStatus.disconnected;
reject(error);
});
if (this.socket.destroyed) {
this.status = MongoConnectionStatus.disconnected;
this.connectingPromise = undefined;
resolve();
}
if (await this.execute(new HandshakeCommand())) {
this.status = MongoConnectionStatus.connected;
this.socket.setTimeout(this.config.options.socketTimeoutMS);
this.connectingPromise = undefined;
resolve();
} else {
this.status = MongoConnectionStatus.disconnected;
this.connectingPromise = undefined;
reject(new MongoError('Could not complete handshake 🤷️'));
}
});
return this.connectingPromise;
}
}
export class ResponseParser {
protected currentMessage?: Uint8Array;
protected currentMessageSize: number = 0;
constructor(
protected readonly onMessage: (response: Uint8Array) => void
) {
}
public feed(data: Uint8Array, bytes?: number) {
if (!data.byteLength) return;
if (!bytes) bytes = data.byteLength;
if (!this.currentMessage) {
if (data.byteLength < 4) {
//not enough data to read the header. Wait for next onData
return;
}
this.currentMessage = data.byteLength === bytes ? data : data.slice(0, bytes);
this.currentMessageSize = readUint32LE(data);
} else {
this.currentMessage = Buffer.concat([this.currentMessage, data.byteLength === bytes ? data : data.slice(0, bytes)]);
if (!this.currentMessageSize) {
if (this.currentMessage.byteLength < 4) {
//not enough data to read the header. Wait for next onData
return;
}
this.currentMessageSize = readUint32LE(this.currentMessage);
}
}
let currentSize = this.currentMessageSize;
let currentBuffer = this.currentMessage;
while (currentBuffer) {
if (currentSize > currentBuffer.byteLength) {
//important to copy, since the incoming might change its data
this.currentMessage = new Uint8Array(currentBuffer);
// this.currentMessage = currentBuffer;
this.currentMessageSize = currentSize;
//message not completely loaded, wait for next onData
return;
}
if (currentSize === currentBuffer.byteLength) {
//current buffer is exactly the message length
this.currentMessageSize = 0;
this.currentMessage = undefined;
this.onMessage(currentBuffer);
return;
}
if (currentSize < currentBuffer.byteLength) {
//we have more messages in this buffer. read what is necessary and hop to next loop iteration
const message = currentBuffer.slice(0, currentSize);
this.onMessage(message);
currentBuffer = currentBuffer.slice(currentSize);
if (currentBuffer.byteLength < 4) {
//not enough data to read the header. Wait for next onData
this.currentMessage = currentBuffer;
return;
}
const nextCurrentSize = readUint32LE(currentBuffer);
if (nextCurrentSize <= 0) throw new Error('message size wrong');
currentSize = nextCurrentSize;
//buffer and size has been set. consume this message in the next loop iteration
}
}
}
} | the_stack |
import { createElement, isNullOrUndefined, Browser, EmitType } from '@syncfusion/ej2-base';
import { AutoComplete } from '../../src/auto-complete/index';
import { FilteringEventArgs } from '../../src/drop-down-base';
import { DataManager, Query, ODataV4Adaptor, Predicate } from '@syncfusion/ej2-data';
import {profile , inMB, getMemoryProfile} from '../common/common.spec';
describe('Filtering performance', () => {
beforeAll(() => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
});
let autoEle: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'auto' });
let autoObj: AutoComplete;
let originalTimeout: number;
describe('JSON performance 1', () => {
let list: { [key: string]: string }[] = [];
let isOpen: boolean = false;
let isBind: boolean = false;
for (var i = 20000; i > 0; i--) {
list.push({ Code: "Test1" + i, Description: "TestDescription" + i });
}
beforeAll(() => {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 8000;
document.body.appendChild(autoEle);
autoObj = new AutoComplete({
dataSource: list,
fields: { value: "Code", text: "Description" },
placeholder: 'e.g. Basketball',
allowFiltering: true,
sortOrder: 'Ascending',
width: '250px',
suggestionCount: 20000,
filtering: (e: FilteringEventArgs) => {
let predicate = new Predicate('Description', 'contains', e.text, true);
predicate = predicate.or('Code', 'contains', e.text, true);
let query = new Query();
query = (e.text !== '') ? query.where(predicate) : query;
e.updateData(list, query);
}
});
autoObj.appendTo(autoEle);
});
afterAll(() => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
autoObj.destroy();
autoEle.remove();
});
it('check value selection', (done) => {
autoObj.open = () => {
isOpen = true;
expect(isBind).toBeFalsy();
}
autoObj.dataBound = () => {
isBind = true;
let data : { [key: string]: string } = autoObj.getDataByValue(autoObj.value) as { [key: string]: string };
expect(data.Description).toBe('TestDescription987');
expect(isOpen).toBeTruthy();
done();
}
autoObj.actionComplete = () => {
autoObj.value = 'Test1987';
}
autoObj.focusIn();
(<any>autoObj).inputElement.value = "t";
let event: any = new Event('keyup');
event.keyCode = 65;
event.key = "a";
(<any>autoObj).onInput();
(<any>autoObj).isValidKey = true;
(<any>autoObj).onFilterUp(event);
});
});
describe('JSON performance 2', () => {
let list: { [key: string]: string }[] = [];
let isOpen: boolean = false;
let isBind: boolean = false;
for (var i = 20000; i > 0; i--) {
list.push({ Code: "Test1" + i, Description: "TestDescription" + i });
}
beforeAll(() => {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 4000;
document.body.appendChild(autoEle);
autoObj = new AutoComplete({
dataSource: list,
fields: { value: "Code", text: "Description" },
placeholder: 'e.g. Basketball',
allowFiltering: true,
sortOrder: 'Ascending',
width: '250px',
suggestionCount: 2000,
filtering: (e: FilteringEventArgs) => {
let predicate = new Predicate('Description', 'contains', e.text, true);
predicate = predicate.or('Code', 'contains', e.text, true);
let query = new Query();
query = (e.text !== '') ? query.where(predicate) : query;
e.updateData(list, query);
}
});
autoObj.appendTo(autoEle);
});
afterAll(() => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
autoObj.destroy();
autoEle.remove();
});
it('check Text selection', (done) => {
autoObj.open = () => {
isOpen = true;
expect(isBind).toBeFalsy();
}
autoObj.dataBound = () => {
isBind = true;
expect(autoObj.value).toBe('Test1987');
expect(isOpen).toBeTruthy();
done();
}
autoObj.actionComplete = () => {
autoObj.text = 'Test1987';
}
autoObj.focusIn();
(<any>autoObj).inputElement.value = "t";
let event: any = new Event('keyup');
event.keyCode = 65;
event.key = "a";
(<any>autoObj).onInput();
(<any>autoObj).isValidKey = true;
(<any>autoObj).onFilterUp(event);
});
});
describe('Number performance', () => {
let list: number[] = [];
let isOpen: boolean = false;
let isBind: boolean = false;
for (var i = 20000; i > 0; i--) {
list.push(i);
}
beforeAll(() => {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;
document.body.appendChild(autoEle);
autoObj = new AutoComplete({
dataSource: list,
allowFiltering: true,
sortOrder: 'Ascending',
width: '250px',
suggestionCount: 20000
});
autoObj.appendTo(autoEle);
});
afterAll(() => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
autoObj.destroy();
autoEle.remove();
});
it('check the performance', (done) => {
autoObj.open = () => {
isOpen = true;
expect(isBind).toBeFalsy();
}
autoObj.dataBound = () => {
isBind = true;
expect(isOpen).toBeTruthy();
done();
}
autoObj.actionComplete = () => {
autoObj.index = 289;
}
autoObj.focusIn();
(<any>autoObj).inputElement.value = "0";
let event: any = new Event('keyup');
event.keyCode = 65;
event.key = 48;
(<any>autoObj).onInput();
(<any>autoObj).isValidKey = true;
(<any>autoObj).onFilterUp(event);
});
});
describe('String performance', () => {
let list: string[] = [];
let isOpen: boolean = false;
let isBind: boolean = false;
for (var i = 20000; i > 0; i--) {
list.push('Text' + i);
}
beforeAll(() => {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;
document.body.appendChild(autoEle);
autoObj = new AutoComplete({
dataSource: list,
allowFiltering: true,
sortOrder: 'Ascending',
width: '250px',
suggestionCount: 20000
});
autoObj.appendTo(autoEle);
});
afterAll(() => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
autoObj.destroy();
autoEle.remove();
});
it('check the performance', (done) => {
autoObj.open = () => {
isOpen = true;
expect(isBind).toBeFalsy();
}
autoObj.dataBound = () => {
isBind = true;
expect(isOpen).toBeTruthy();
done();
}
autoObj.focusIn();
(<any>autoObj).inputElement.value = "t";
let event: any = new Event('keyup');
event.keyCode = 84;
event.key = 't';
(<any>autoObj).onInput();
(<any>autoObj).isValidKey = true;
(<any>autoObj).onFilterUp(event);
});
});
describe('Item Template performance', () => {
let list: { [key: string]: string }[] = [];
let isOpen: boolean = false;
let isBind: boolean = false;
for (var i = 20000; i > 0; i--) {
list.push({ Code: "Test1" + i, Description: "TestDescription" + i });
}
beforeAll(() => {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;
document.body.appendChild(autoEle);
autoObj = new AutoComplete({
dataSource: list,
fields: { value: "Code", text: "Description" },
placeholder: 'e.g. Basketball',
allowFiltering: true,
sortOrder: 'Ascending',
width: '250px',
suggestionCount: 20000,
itemTemplate: '<div class="demo"> ${Code} </div><div class="id"> ${Description} </div>',
filtering: (e: FilteringEventArgs) => {
let predicate = new Predicate('Description', 'contains', e.text, true);
predicate = predicate.or('Code', 'contains', e.text, true);
let query = new Query();
query = (e.text !== '') ? query.where(predicate) : query;
e.updateData(list, query);
}
});
autoObj.appendTo(autoEle);
});
afterAll(() => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
autoObj.destroy();
autoEle.remove();
});
it('check the performance', () => {
autoObj.open = () => {
isOpen = true;
expect(isBind).toBeFalsy();
}
autoObj.dataBound = () => {
isBind = true;
expect(isOpen).toBeTruthy();
}
autoObj.focusIn();
(<any>autoObj).inputElement.value = "t";
let event: any = new Event('keyup');
event.keyCode = 65;
event.key = "a";
(<any>autoObj).onInput();
(<any>autoObj).isValidKey = true;
(<any>autoObj).onFilterUp(event);
});
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange)
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile())
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
})
}); | the_stack |
import { HashSet, ObservableHashSet } from "../hash-set";
describe("ObservableHashSet<T>", () => {
it("should not throw on creation", () => {
expect(() => new ObservableHashSet<{ a: number }>([], item => item.a.toString())).not.toThrowError();
});
it("should be initializable", () => {
const res = new ObservableHashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.size).toBe(4);
});
it("has should work as expected", () => {
const res = new ObservableHashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.has({ a: 1 })).toBe(true);
expect(res.has({ a: 5 })).toBe(false);
});
it("forEach should work as expected", () => {
const res = new ObservableHashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
let a = 1;
res.forEach((item) => {
expect(item.a).toEqual(a++);
});
});
it("delete should work as expected", () => {
const res = new ObservableHashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.has({ a: 1 })).toBe(true);
expect(res.delete({ a: 1 })).toBe(true);
expect(res.has({ a: 1 })).toBe(false);
expect(res.has({ a: 5 })).toBe(false);
expect(res.delete({ a: 5 })).toBe(false);
expect(res.has({ a: 5 })).toBe(false);
});
it("toggle should work as expected", () => {
const res = new ObservableHashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.has({ a: 1 })).toBe(true);
res.toggle({ a: 1 });
expect(res.has({ a: 1 })).toBe(false);
expect(res.has({ a: 6 })).toBe(false);
res.toggle({ a: 6 });
expect(res.has({ a: 6 })).toBe(true);
});
it("add should work as expected", () => {
const res = new ObservableHashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.has({ a: 6 })).toBe(false);
res.add({ a: 6 });
expect(res.has({ a: 6 })).toBe(true);
});
it("add should treat the hash to be the same as equality", () => {
const res = new ObservableHashSet([
{ a: 1, foobar: "hello" },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.has({ a: 1 })).toBe(true);
res.add({ a: 1, foobar: "goodbye" });
expect(res.has({ a: 1 })).toBe(true);
});
it("clear should work as expected", () => {
const res = new ObservableHashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.size).toBe(4);
res.clear();
expect(res.size).toBe(0);
});
it("replace should work as expected", () => {
const res = new ObservableHashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.size).toBe(4);
res.replace([{ a: 13 }]);
expect(res.size).toBe(1);
expect(res.has({ a: 1 })).toBe(false);
expect(res.has({ a: 13 })).toBe(true);
});
it("toJSON should work as expected", () => {
const res = new ObservableHashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.toJSON()).toStrictEqual([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
]);
});
it("values should work as expected", () => {
const res = new ObservableHashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
const iter = res.values();
expect(iter.next()).toStrictEqual({
value: { a: 1 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: { a: 2 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: { a: 3 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: { a: 4 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: undefined,
done: true,
});
});
it("keys should work as expected", () => {
const res = new ObservableHashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
const iter = res.keys();
expect(iter.next()).toStrictEqual({
value: { a: 1 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: { a: 2 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: { a: 3 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: { a: 4 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: undefined,
done: true,
});
});
it("entries should work as expected", () => {
const res = new ObservableHashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
const iter = res.entries();
expect(iter.next()).toStrictEqual({
value: [{ a: 1 }, { a: 1 }],
done: false,
});
expect(iter.next()).toStrictEqual({
value: [{ a: 2 }, { a: 2 }],
done: false,
});
expect(iter.next()).toStrictEqual({
value: [{ a: 3 }, { a: 3 }],
done: false,
});
expect(iter.next()).toStrictEqual({
value: [{ a: 4 }, { a: 4 }],
done: false,
});
expect(iter.next()).toStrictEqual({
value: undefined,
done: true,
});
});
});
describe("HashSet<T>", () => {
it("should not throw on creation", () => {
expect(() => new HashSet<{ a: number }>([], item => item.a.toString())).not.toThrowError();
});
it("should be initializable", () => {
const res = new HashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.size).toBe(4);
});
it("has should work as expected", () => {
const res = new HashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.has({ a: 1 })).toBe(true);
expect(res.has({ a: 5 })).toBe(false);
});
it("forEach should work as expected", () => {
const res = new HashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
let a = 1;
res.forEach((item) => {
expect(item.a).toEqual(a++);
});
});
it("delete should work as expected", () => {
const res = new HashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.has({ a: 1 })).toBe(true);
expect(res.delete({ a: 1 })).toBe(true);
expect(res.has({ a: 1 })).toBe(false);
expect(res.has({ a: 5 })).toBe(false);
expect(res.delete({ a: 5 })).toBe(false);
expect(res.has({ a: 5 })).toBe(false);
});
it("toggle should work as expected", () => {
const res = new HashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.has({ a: 1 })).toBe(true);
res.toggle({ a: 1 });
expect(res.has({ a: 1 })).toBe(false);
expect(res.has({ a: 6 })).toBe(false);
res.toggle({ a: 6 });
expect(res.has({ a: 6 })).toBe(true);
});
it("add should work as expected", () => {
const res = new HashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.has({ a: 6 })).toBe(false);
res.add({ a: 6 });
expect(res.has({ a: 6 })).toBe(true);
});
it("add should treat the hash to be the same as equality", () => {
const res = new HashSet([
{ a: 1, foobar: "hello" },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.has({ a: 1 })).toBe(true);
res.add({ a: 1, foobar: "goodbye" });
expect(res.has({ a: 1 })).toBe(true);
});
it("clear should work as expected", () => {
const res = new HashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.size).toBe(4);
res.clear();
expect(res.size).toBe(0);
});
it("replace should work as expected", () => {
const res = new HashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.size).toBe(4);
res.replace([{ a: 13 }]);
expect(res.size).toBe(1);
expect(res.has({ a: 1 })).toBe(false);
expect(res.has({ a: 13 })).toBe(true);
});
it("toJSON should work as expected", () => {
const res = new HashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.toJSON()).toStrictEqual([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
]);
});
it("values should work as expected", () => {
const res = new HashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
const iter = res.values();
expect(iter.next()).toStrictEqual({
value: { a: 1 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: { a: 2 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: { a: 3 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: { a: 4 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: undefined,
done: true,
});
});
it("keys should work as expected", () => {
const res = new HashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
const iter = res.keys();
expect(iter.next()).toStrictEqual({
value: { a: 1 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: { a: 2 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: { a: 3 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: { a: 4 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: undefined,
done: true,
});
});
it("entries should work as expected", () => {
const res = new HashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
const iter = res.entries();
expect(iter.next()).toStrictEqual({
value: [{ a: 1 }, { a: 1 }],
done: false,
});
expect(iter.next()).toStrictEqual({
value: [{ a: 2 }, { a: 2 }],
done: false,
});
expect(iter.next()).toStrictEqual({
value: [{ a: 3 }, { a: 3 }],
done: false,
});
expect(iter.next()).toStrictEqual({
value: [{ a: 4 }, { a: 4 }],
done: false,
});
expect(iter.next()).toStrictEqual({
value: undefined,
done: true,
});
});
}); | the_stack |
This file was copied from mashlib/src/global/header.ts file. It is modified to
work in solid-ui by adjusting where imported functions are found.
*/
import { IndexedFormula, NamedNode } from 'rdflib'
import { icons } from '..'
import { loginStatusBox, authSession, currentUser } from '../authn/authn'
import * as widgets from '../widgets'
import { emptyProfile } from './empty-profile'
import { addStyleClassToElement, getPod, throttle } from './headerHelpers'
export type MenuItemLink = {
label: string,
url: string
}
export type MenuItemButton = {
label: string,
onclick: () => {}
}
export type MenuItems = MenuItemLink | MenuItemButton
/*
HeaderOptions allow for customizing the logo and menu list. If a logo is not provided the default
is solid. Menulist will always show a link to logout and to the users profile.
*/
export type HeaderOptions = {
logo?: string,
menuList?: MenuItems[]
}
/**
* Initialize header component, the header object returned depends on whether the user is authenticated.
* @param store the data store
* @param options allow the header to be customized with a personalized logo and a menu list of links or buttons.
* @returns a header for an authenticated user with menu items given or a login screen
*/
export async function initHeader (store: IndexedFormula, options?: HeaderOptions) {
const header = document.getElementById('PageHeader')
if (!header) {
return
}
const pod = getPod()
rebuildHeader(header, store, pod, options)()
authSession.onLogout(rebuildHeader(header, store, pod, options))
authSession.onLogin(rebuildHeader(header, store, pod, options))
}
/**
* @ignore exporting this only for the unit test
*/
export function rebuildHeader (header: HTMLElement, store: IndexedFormula, pod: NamedNode, options?: HeaderOptions) {
return async () => {
const user = currentUser()
header.innerHTML = ''
header.appendChild(await createBanner(store, pod, user, options))
}
}
/**
* @ignore exporting this only for the unit test
*/
export async function createBanner (store: IndexedFormula, pod: NamedNode, user: NamedNode | null, options?: HeaderOptions): Promise<HTMLElement> {
const podLink = document.createElement('a')
podLink.href = pod.uri
addStyleClassToElement(podLink, ['header-banner__link'])
const image = document.createElement('img')
if (options) {
image.src = options.logo ? options.logo : 'https://solidproject.org/assets/img/solid-emblem.svg'
}
addStyleClassToElement(image, ['header-banner__icon'])
podLink.appendChild(image)
const userMenu = user
? await createUserMenu(store, user, options)
: createLoginSignUpButtons()
const helpMenu = createHelpMenu()
const banner = document.createElement('div')
addStyleClassToElement(banner, ['header-banner'])
banner.appendChild(podLink)
const leftSideOfHeader = document.createElement('div')
addStyleClassToElement(leftSideOfHeader, ['header-banner__right-menu'])
leftSideOfHeader.appendChild(userMenu)
leftSideOfHeader.appendChild(helpMenu)
banner.appendChild(leftSideOfHeader)
return banner
}
/**
* @ignore exporting this only for the unit test
*/
export function createHelpMenu () {
const helpMenuList = document.createElement('ul')
addStyleClassToElement(helpMenuList, ['header-user-menu__list'])
helpMenuList.appendChild(createUserMenuItem(createUserMenuLink('User guide', 'https://github.com/solid/userguide', '_blank')))
helpMenuList.appendChild(createUserMenuItem(createUserMenuLink('Report a problem', 'https://github.com/solid/solidos/issues', '_blank')))
const helpMenu = document.createElement('nav')
addStyleClassToElement(helpMenu, ['header-user-menu__navigation-menu'])
helpMenu.setAttribute('aria-hidden', 'true')
helpMenu.appendChild(helpMenuList)
const helpIcon = icons.iconBase + 'noun_144.svg'
const helpMenuContainer = document.createElement('div')
addStyleClassToElement(helpMenuContainer, ['header-banner__user-menu'])
addStyleClassToElement(helpMenuContainer, ['header-user-menu'])
helpMenuContainer.appendChild(helpMenu)
const helpMenuTrigger = document.createElement('button')
addStyleClassToElement(helpMenuTrigger, ['header-user-menu__trigger'])
helpMenuTrigger.type = 'button'
const helpMenuIcon = document.createElement('img')
helpMenuIcon.src = helpIcon
addStyleClassToElement(helpMenuIcon, ['header-banner__help-icon'])
helpMenuContainer.appendChild(helpMenuTrigger)
helpMenuTrigger.appendChild(helpMenuIcon)
const throttledMenuToggle = throttle((event: Event) => toggleMenu(event, helpMenuTrigger, helpMenu), 50)
helpMenuTrigger.addEventListener('click', throttledMenuToggle)
let timer = setTimeout(() => null, 0)
helpMenuContainer.addEventListener('mouseover', event => {
clearTimeout(timer)
throttledMenuToggle(event)
})
helpMenuContainer.addEventListener('mouseout', event => {
timer = setTimeout(() => throttledMenuToggle(event), 200)
})
return helpMenuContainer
}
/**
* @ignore exporting this only for the unit test
*/
export function createLoginSignUpButtons () {
const profileLoginButtonPre = document.createElement('div')
addStyleClassToElement(profileLoginButtonPre, ['header-banner__login'])
profileLoginButtonPre.appendChild(loginStatusBox(document, null, {}))
return profileLoginButtonPre
}
/**
* @ignore exporting this only for the unit test
*/
export function createUserMenuButton (label: string, onClick: EventListenerOrEventListenerObject): HTMLElement {
const button = document.createElement('button')
addStyleClassToElement(button, ['header-user-menu__button'])
button.addEventListener('click', onClick)
button.innerText = label
return button
}
/**
* @ignore exporting this only for the unit test
*/
export function createUserMenuLink (label: string, href: string, target?:string): HTMLElement {
const link = document.createElement('a')
addStyleClassToElement(link, ['header-user-menu__link'])
link.href = href
link.innerText = label
if (target) link.target = target
return link
}
/**
* @ignore exporting this only for the unit test
*/
export async function createUserMenu (store: IndexedFormula, user: NamedNode, options?: HeaderOptions): Promise<HTMLElement> {
const fetcher = (<any>store).fetcher
if (fetcher) {
// Making sure that Profile is loaded before building menu
await fetcher.load(user)
}
const loggedInMenuList = document.createElement('ul')
addStyleClassToElement(loggedInMenuList, ['header-user-menu__list'])
loggedInMenuList.appendChild(createUserMenuItem(createUserMenuLink('Show your profile', user.uri)))
if (options) {
if (options.menuList) {
options.menuList.forEach(function (menuItem) {
const menuItemType: string = (menuItem as MenuItemLink).url ? 'url' : 'onclick'
if (menuItemType === 'url') {
loggedInMenuList.appendChild(createUserMenuItem(createUserMenuLink(menuItem.label, menuItem[menuItemType])))
} else {
loggedInMenuList.appendChild(createUserMenuItem(createUserMenuButton(menuItem.label, menuItem[menuItemType])))
}
})
}
}
loggedInMenuList.appendChild(createUserMenuItem(createUserMenuButton('Log out', () => authSession.logout())))
const loggedInMenu = document.createElement('nav')
addStyleClassToElement(loggedInMenu, ['header-user-menu__navigation-menu'])
loggedInMenu.setAttribute('aria-hidden', 'true')
loggedInMenu.appendChild(loggedInMenuList)
const loggedInMenuTrigger = document.createElement('button')
addStyleClassToElement(loggedInMenuTrigger, ['header-user-menu__trigger'])
loggedInMenuTrigger.type = 'button'
const profileImg = getProfileImg(store, user)
if (typeof profileImg === 'string') {
loggedInMenuTrigger.innerHTML = profileImg
} else {
loggedInMenuTrigger.appendChild(profileImg)
}
const loggedInMenuContainer = document.createElement('div')
addStyleClassToElement(loggedInMenuContainer, ['header-banner__user-menu'])
addStyleClassToElement(loggedInMenuContainer, ['header-user-menu'])
loggedInMenuContainer.appendChild(loggedInMenuTrigger)
loggedInMenuContainer.appendChild(loggedInMenu)
const throttledMenuToggle = throttle((event: Event) => toggleMenu(event, loggedInMenuTrigger, loggedInMenu), 50)
loggedInMenuTrigger.addEventListener('click', throttledMenuToggle)
let timer = setTimeout(() => null, 0)
loggedInMenuContainer.addEventListener('mouseover', event => {
clearTimeout(timer)
throttledMenuToggle(event)
})
loggedInMenuContainer.addEventListener('mouseout', event => {
timer = setTimeout(() => throttledMenuToggle(event), 200)
})
return loggedInMenuContainer
}
/**
* @ignore exporting this only for the unit test
*/
export function createUserMenuItem (child: HTMLElement): HTMLElement {
const menuProfileItem = document.createElement('li')
addStyleClassToElement(menuProfileItem, ['header-user-menu__list-item'])
menuProfileItem.appendChild(child)
return menuProfileItem
}
/**
* @ignore exporting this only for the unit test
*/
export function getProfileImg (store: IndexedFormula, user: NamedNode): string | HTMLElement {
const profileUrl = null
try {
const profileUrl = widgets.findImage(user)
if (!profileUrl) {
return emptyProfile
}
} catch {
return emptyProfile
}
const profileImage = document.createElement('div')
addStyleClassToElement(profileImage, ['header-user-menu__photo'])
profileImage.style.backgroundImage = `url("${profileUrl}")`
return profileImage
}
/**
* @internal
*/
function toggleMenu (event: Event, trigger: HTMLButtonElement, menu: HTMLElement): void {
const isExpanded = trigger.getAttribute('aria-expanded') === 'true'
const expand = event.type === 'mouseover'
const close = event.type === 'mouseout'
if ((isExpanded && expand) || (!isExpanded && close)) {
return
}
trigger.setAttribute('aria-expanded', (!isExpanded).toString())
menu.setAttribute('aria-hidden', isExpanded.toString())
} | the_stack |
declare module '@ailhc/enet' {
global {
namespace enet {
/**网络数据格式 */
type NetData = string | ArrayBufferLike | Blob | ArrayBufferView | Uint8Array;
/**
* socket 接口
*/
interface ISocket {
/**socket状态 */
state: number;
/**是否连接 */
isConnected: boolean;
/**
* 设置事件处理器
* @param handler
*/
setEventHandler(handler: ISocketEventHandler): void;
/**
* 连接
* @param opt
* @returns
*/
connect(opt: IConnectOptions): boolean;
/**
* 发送数据
* @param data
*/
send(data: NetData): void;
/**
* 关闭socket
* @param disconnect 主动断开连接
*/
close(disconnect?: boolean): void;
}
interface ISocketEventHandler {
/**
* socket 消息接收回调
*/
onSocketMsg?: (event: {
data: NetData;
}) => void;
/**
* socket 出错回调
*/
onSocketError?: (event: any) => void;
/**
* socket 关闭回调
* 默认事件参数event的值是 是否主动断开连接
*/
onSocketClosed?: (event: any) => void;
/**
* socket 连接回调
*/
onSocketConnected?: (event: any) => void;
}
interface IConnectOptions<T = any> {
/**protocol + host+port 二选一 */
url?: string;
/**是否使用ssh,即 true wss,false ws */
protocol?: boolean;
/**主机地址 */
host?: string;
/**端口 */
port?: string;
/**数据传输类型,arraybuffer,blob ,默认arraybuffer*/
binaryType?: "arraybuffer" | "blob";
/**连接结束 ,如果有握手则会有握手数据返回*/
connectEnd?: (handShakeRes?: any) => void;
/**握手数据,如果为空则不进行握手通信 */
handShakeReq?: T;
}
/**
* 解码后的数据包
*/
interface IDecodePackage<T = any> {
/**
* 数据包类型
* 默认使用 PackageType 中的DATA 类型 4
*
* 数据包类型
* 默认数据包类型
* 1 HANDSHAKE 客户端和服务端之间的握手数据包类型
* 2 HANDSHAKE_ACK 客户端回应服务端的握手包类型
* 3 HEARTBEAT 客户端和服务端之间的心跳数据包类型
* 4 KICK 服务端发给客户端的下线数据包类型
*/
type: number;
/**协议字符串key */
key?: string;
/**数据 */
data?: T;
/**请求id */
reqId?: number;
/**错误码 */
code?: number;
/**错误信息 */
errorMsg?: string;
}
/**默认握手返回 */
interface IDefaultHandshakeRes extends IHeartBeatConfig {
}
interface IHeartBeatConfig {
/**心跳间隔,毫秒 */
heartbeatInterval: number;
/**心跳超时时间,毫秒 */
heartbeatTimeout: number;
}
interface IProtoHandler<ProtoKeyType = any> {
/**
* 心跳配置,如果为空则和后端没有心跳交互
*/
heartbeatConfig: enet.IHeartBeatConfig;
/**握手数据 */
handShakeRes: any;
/**
* 协议key转字符串key
* @param protoKey
*/
protoKey2Key(protoKey: ProtoKeyType): string;
/**
* 编码数据包
* @param pkg
* @param useCrypto 是否加密
*/
encodePkg<T>(pkg: enet.IPackage<T>, useCrypto?: boolean): NetData;
/**
* 编码消息数据包
* @param msg 消息包
* @param useCrypto 是否加密
*/
encodeMsg<T>(msg: enet.IMessage<T, ProtoKeyType>, useCrypto?: boolean): NetData;
/**
* 解码网络数据包,
* @param data
*/
decodePkg<T>(data: NetData): IDecodePackage<T>;
}
type AnyCallback<ResData = any> = enet.ICallbackHandler<enet.IDecodePackage<ResData>> | enet.ValueCallback<enet.IDecodePackage<ResData>>;
type ValueCallback<T = any> = (data?: T, ...args: any[]) => void;
/**
* 回调对象
*/
interface ICallbackHandler<T> {
/**回调 */
method: ValueCallback<T>;
/**上下文,this */
context?: any;
/**透传数据,传参给method时,会拼接在数据对象参数后面 */
args?: any[];
}
/**
* 请求配置
*/
interface IRequestConfig {
/**
* 请求id
*/
reqId: number;
/**
* 协议key
*/
protoKey: string;
/**
* 请求回调
*/
resHandler: enet.AnyCallback;
/**
* 请求原始数据
*/
data: any;
/**
* 请求返回数据
*/
decodePkg?: enet.IDecodePackage;
}
/**
* 异常处理器
*/
interface INetEventHandler<ResData = any> {
/**
* 开始连接
* @param connectOpt 连接配置
*/
onStartConnenct?(connectOpt: IConnectOptions): void;
/**
* 连接结束
* @param connectOpt 连接配置
* @param handshakeRes 握手返回数据
*/
onConnectEnd?(connectOpt: IConnectOptions, handshakeRes?: any): void;
/**
* 网络出错
* @param event
*/
onError?(event: any, connectOpt: IConnectOptions): void;
/**
* 连接断开
* @param event
*/
onClosed?(event: any, connectOpt: IConnectOptions): void;
/**
* 开始重连
* @param reConnectCfg 重连配置
* @param connectOpt 连接配置
*/
onStartReconnect?(reConnectCfg: IReconnectConfig, connectOpt: IConnectOptions): void;
/**
* 再次尝试重连
* @param curCount
* @param reConnectCfg 重连配置
* @param connectOpt 连接配置
*/
onReconnecting?(curCount: number, reConnectCfg: IReconnectConfig, connectOpt: IConnectOptions): void;
/**
* 重连结束
* @param isOk
* @param reConnectCfg 重连配置
* @param connectOpt 连接配置
*/
onReconnectEnd?(isOk: boolean, reConnectCfg: IReconnectConfig, connectOpt: IConnectOptions): void;
/**
* 开始请求
* @param reqCfg 请求配置
*/
onStartRequest?(reqCfg: enet.IRequestConfig, connectOpt: IConnectOptions): void;
/**
* 请求响应
* @param decodePkg
*/
onData?(decodePkg: IDecodePackage<ResData>, connectOpt: IConnectOptions, reqCfg?: enet.IRequestConfig): void;
/**
* 被踢下线
* @param decodePkg
* @param connectOpt
*/
onKick?(decodePkg: IDecodePackage<ResData>, connectOpt: IConnectOptions): void;
/**
* 错误信息
* @param data
* @param connectOpt
*/
onCustomError?(data: IDecodePackage<ResData>, connectOpt: IConnectOptions): void;
}
interface IMessage<T = any, ProtoKeyType = any> {
reqId?: number;
/**协议key */
key: ProtoKeyType;
data: T;
}
interface IPackage<T = any> {
/**
* 数据包类型
* 默认的数据包类型:
* 1 HANDSHAKE 客户端和服务端之间的握手数据包类型
* 2 HANDSHAKE_ACK 客户端回应服务端的握手包类型
* 3 HEARTBEAT 客户端和服务端之间的心跳数据包类型
* 4 KICK 服务端发给客户端的下线数据包类型
*/
type: number;
data?: T;
}
/**
* 重连配置接口
*/
interface IReconnectConfig {
/**
* 重连次数
* 默认:4
*/
reconnectCount?: number;
/**
* 连接超时时间,单位毫秒
* 默认: 120000 2分钟
*/
connectTimeout?: number;
}
interface INodeConfig {
/**
* 底层socket实现
*/
socket?: ISocket;
/**
* 网络事件处理器
* 默认:使用log输出方式
*/
netEventHandler?: INetEventHandler;
/**
* 协议编码,解码处理器
* 默认: 使用字符串协议处理器
*/
protoHandler?: IProtoHandler;
/**
* 重连配置,有默认值
*/
reConnectCfg?: IReconnectConfig;
/**心跳间隔阈值 ,默认100*/
heartbeatGapThreashold?: number;
/**使用加密 */
useCrypto?: boolean;
}
interface INode<ProtoKeyType = any> {
/**网络事件处理器 */
netEventHandler: enet.INetEventHandler;
/**协议处理器 */
protoHandler: enet.IProtoHandler;
/**套接字实现 */
socket: enet.ISocket;
/**
* 初始化网络节点,注入自定义处理
* @param config 配置 重连次数,超时时间,网络事件处理,协议处理
*/
init(config?: INodeConfig): void;
/**
* 连接
* @param option 连接参数:可以直接传url|options
*/
connect(option: string | enet.IConnectOptions): void;
/**
* 断开连接
*/
disConnect(): void;
/**
* 重连
*/
reConnect(): void;
/**
* 请求协议接口,处理返回
* @param protoKey 协议key
* @param data 请求数据体
* @param resHandler 返回处理
*/
request<ReqData = any, ResData = any>(protoKey: ProtoKeyType, data: ReqData, resHandler: ICallbackHandler<IDecodePackage<ResData>> | ValueCallback<IDecodePackage<ResData>>): void;
/**
* 发送网络数据
* @param netData
*/
send(netData: NetData): void;
/**
* 通知
* 发送数据给服务器,不处理返回
* @param protoKey 协议key
* @param data 数据体
*/
notify<T>(protoKey: ProtoKeyType, data?: T): void;
/**
* 监听推送
* @param protoKey
* @param handler
*/
onPush<ResData = any>(protoKey: ProtoKeyType, handler: enet.AnyCallback<ResData>): void;
/**
* 监听一次推送
* @param protoKey
* @param handler
*/
oncePush<ResData = any>(protoKey: ProtoKeyType, handler: enet.AnyCallback<ResData>): void;
/**
* 取消监听推送
* @param protoKey 协议
* @param callbackHandler 回调
* @param context 指定上下文的监听
* @param onceOnly 是否只取消 监听一次 的推送监听
*/
offPush(protoKey: ProtoKeyType, callbackHandler: enet.AnyCallback, context?: any, onceOnly?: boolean): void;
/**
* 取消所有监听
* @param protoKey 指定协议的推送,如果为空,则取消所有协议的所有监听
*/
offPushAll(protoKey?: ProtoKeyType): void;
}
}
}
export {};
}
declare module '@ailhc/enet' {
export class DefaultNetEventHandler implements enet.INetEventHandler {
onStartConnenct?(connectOpt: enet.IConnectOptions): void;
onConnectEnd?(connectOpt: enet.IConnectOptions, handshakeRes?: any): void;
onError(event: any, connectOpt: enet.IConnectOptions): void;
onClosed(event: any, connectOpt: enet.IConnectOptions): void;
onStartReconnect?(reConnectCfg: enet.IReconnectConfig, connectOpt: enet.IConnectOptions): void;
onReconnecting?(curCount: number, reConnectCfg: enet.IReconnectConfig, connectOpt: enet.IConnectOptions): void;
onReconnectEnd?(isOk: boolean, reConnectCfg: enet.IReconnectConfig, connectOpt: enet.IConnectOptions): void;
onStartRequest?(reqCfg: enet.IRequestConfig, connectOpt: enet.IConnectOptions): void;
onData?(dpkg: enet.IDecodePackage<any>, connectOpt: enet.IConnectOptions): void;
onRequestTimeout?(reqCfg: enet.IRequestConfig, connectOpt: enet.IConnectOptions): void;
onCustomError?(dpkg: enet.IDecodePackage<any>, connectOpt: enet.IConnectOptions): void;
onKick(dpkg: enet.IDecodePackage<any>, copt: enet.IConnectOptions): void;
}
}
declare module '@ailhc/enet' {
export enum PackageType {
/**握手 */
HANDSHAKE = 1,
/**握手回应 */
HANDSHAKE_ACK = 2,
/**心跳 */
HEARTBEAT = 3,
/**数据 */
DATA = 4,
/**踢下线 */
KICK = 5
}
}
declare module '@ailhc/enet' {
export enum SocketState {
/**连接中 */
CONNECTING = 0,
/**打开 */
OPEN = 1,
/**关闭中 */
CLOSING = 2,
/**关闭了 */
CLOSED = 3
}
}
declare module '@ailhc/enet' {
import { SocketState } from '@ailhc/enet';
export class WSocket implements enet.ISocket {
private _sk;
private _eventHandler;
get state(): SocketState;
get isConnected(): boolean;
setEventHandler(handler: enet.ISocketEventHandler): void;
connect(opt: enet.IConnectOptions): boolean;
send(data: enet.NetData): void;
close(disconnect?: boolean): void;
}
}
declare module '@ailhc/enet' {
export class NetNode<ProtoKeyType> implements enet.INode<ProtoKeyType> {
/**
* 套接字实现
*/
protected _socket: enet.ISocket;
get socket(): enet.ISocket;
/**
* 网络事件处理器
*/
protected _netEventHandler: enet.INetEventHandler;
get netEventHandler(): enet.INetEventHandler<any>;
/**
* 协议处理器
*/
protected _protoHandler: enet.IProtoHandler;
get protoHandler(): enet.IProtoHandler<any>;
/**
* 当前重连次数
*/
protected _curReconnectCount: number;
/**
* 重连配置
*/
protected _reConnectCfg: enet.IReconnectConfig;
/**
* 是否初始化
*/
protected _inited: boolean;
/**
* 连接参数对象
*/
protected _connectOpt: enet.IConnectOptions;
/**
* 是否正在重连
*/
protected _isReconnecting: boolean;
/**
* 计时器id
*/
protected _reconnectTimerId: any;
/**
* 请求id
* 会自增
*/
protected _reqId: number;
/**
* 永久监听处理器字典
* key为请求key = protoKey
* value为 回调处理器或回调函数
*/
protected _pushHandlerMap: {
[key: string]: enet.AnyCallback[];
};
/**
* 一次监听推送处理器字典
* key为请求key = protoKey
* value为 回调处理器或回调函数
*/
protected _oncePushHandlerMap: {
[key: string]: enet.AnyCallback[];
};
/**
* 请求响应回调字典
* key为请求key = protoKey_reqId
* value为 回调处理器或回调函数
*/
protected _reqCfgMap: {
[key: number]: enet.IRequestConfig;
};
/**socket事件处理器 */
protected _socketEventHandler: enet.ISocketEventHandler;
/**
* 获取socket事件处理器
*/
protected get socketEventHandler(): enet.ISocketEventHandler;
/**数据包类型处理 */
protected _pkgTypeHandlers: {
[key: number]: (dpkg: enet.IDecodePackage) => void;
};
/**心跳配置 */
protected _heartbeatConfig: enet.IHeartBeatConfig;
/**心跳间隔阈值 默认100毫秒 */
protected _gapThreashold: number;
/**使用加密 */
protected _useCrypto: boolean;
init(config?: enet.INodeConfig): void;
connect(option: string | enet.IConnectOptions, connectEnd?: VoidFunction): void;
disConnect(): void;
reConnect(): void;
request<ReqData = any, ResData = any>(protoKey: ProtoKeyType, data: ReqData, resHandler: enet.ICallbackHandler<enet.IDecodePackage<ResData>> | enet.ValueCallback<enet.IDecodePackage<ResData>>, arg?: any): void;
notify<T>(protoKey: ProtoKeyType, data?: T): void;
send(netData: enet.NetData): void;
onPush<ResData = any>(protoKey: ProtoKeyType, handler: enet.ICallbackHandler<enet.IDecodePackage<ResData>> | enet.ValueCallback<enet.IDecodePackage<ResData>>): void;
oncePush<ResData = any>(protoKey: ProtoKeyType, handler: enet.ICallbackHandler<enet.IDecodePackage<ResData>> | enet.ValueCallback<enet.IDecodePackage<ResData>>): void;
offPush(protoKey: ProtoKeyType, callbackHandler: enet.AnyCallback, context?: any, onceOnly?: boolean): void;
offPushAll(protoKey?: ProtoKeyType): void;
/**
* 握手包处理
* @param dpkg
*/
protected _onHandshake(dpkg: enet.IDecodePackage): void;
/**
* 握手初始化
* @param dpkg
*/
protected _handshakeInit(dpkg: enet.IDecodePackage): void;
/**心跳超时定时器id */
protected _heartbeatTimeoutId: number;
/**心跳定时器id */
protected _heartbeatTimeId: number;
/**最新心跳超时时间 */
protected _nextHeartbeatTimeoutTime: number;
/**
* 心跳包处理
* @param dpkg
*/
protected _heartbeat(dpkg: enet.IDecodePackage): void;
/**
* 心跳超时处理
*/
protected _heartbeatTimeoutCb(): void;
/**
* 数据包处理
* @param dpkg
*/
protected _onData(dpkg: enet.IDecodePackage): void;
/**
* 踢下线数据包处理
* @param dpkg
*/
protected _onKick(dpkg: enet.IDecodePackage): void;
/**
* socket状态是否准备好
*/
protected _isSocketReady(): boolean;
/**
* 当socket连接成功
* @param event
*/
protected _onSocketConnected(event: any): void;
/**
* 当socket报错
* @param event
*/
protected _onSocketError(event: any): void;
/**
* 当socket有消息
* @param event
*/
protected _onSocketMsg(event: {
data: enet.NetData;
}): void;
/**
* 当socket关闭
* @param event
*/
protected _onSocketClosed(event: any): void;
/**
* 执行回调,会并接上透传数据
* @param handler 回调
* @param depackage 解析完成的数据包
*/
protected _runHandler(handler: enet.AnyCallback, depackage: enet.IDecodePackage): void;
/**
* 停止重连
* @param isOk 重连是否成功
*/
protected _stopReconnect(isOk?: boolean): void;
}
}
declare module '@ailhc/enet' {
export * from '@ailhc/enet';
export * from '@ailhc/enet';
export * from '@ailhc/enet';
export * from '@ailhc/enet';
export * from '@ailhc/enet';
export * from '@ailhc/enet';
} | the_stack |
import {
AST_TOKEN_TYPES,
gl,
GLSLContext,
IComputeModel,
isSafari,
STORAGE_CLASS,
createEntity,
} from '@antv/g-webgpu-core';
import * as WebGPUConstants from '@webgpu/types/dist/constants';
import { isNumber } from 'lodash';
import isNil from 'lodash/isNil';
import { WebGPUEngine } from '.';
import WebGPUBuffer from './WebGPUBuffer';
export default class WebGPUComputeModel implements IComputeModel {
private entity = createEntity();
/**
* 用于后续渲染时动态更新
*/
private uniformGPUBufferLayout: Array<{
name: string;
offset: number;
}> = [];
private uniformBuffer: WebGPUBuffer;
private vertexBuffers: Record<string, WebGPUBuffer> = {};
private outputBuffer: WebGPUBuffer;
private bindGroupEntries: GPUBindGroupEntry[];
private bindGroup: GPUBindGroup;
private computePipeline: GPUComputePipeline;
constructor(private engine: WebGPUEngine, private context: GLSLContext) {}
public async init() {
const { computeStage } = await this.compileComputePipelineStageDescriptor(
this.context.shader!,
);
const buffers = this.context.uniforms.filter(
(uniform) => uniform.storageClass === STORAGE_CLASS.StorageBuffer,
);
const uniforms = this.context.uniforms.filter(
(uniform) => uniform.storageClass === STORAGE_CLASS.Uniform,
);
let bufferBindingIndex = uniforms.length ? 1 : 0;
this.bindGroupEntries = [];
if (bufferBindingIndex) {
let offset = 0;
// FIXME: 所有 uniform 合并成一个 buffer,固定使用 Float32Array 存储,确实会造成一些内存的浪费
// we use std140 layout @see https://www.khronos.org/opengl/wiki/Interface_Block_(GLSL)
const mergedUniformData: number[] = [];
uniforms.forEach((uniform) => {
if (isNumber(uniform.data)) {
this.uniformGPUBufferLayout.push({
name: uniform.name,
offset,
});
offset += 4;
mergedUniformData.push(uniform.data);
} else {
let originDataLength = uniform.data?.length || 1;
if (originDataLength === 3) {
// vec3 -> vec4
// @see http://ptgmedia.pearsoncmg.com/images/9780321552624/downloads/0321552628_AppL.pdf
originDataLength = 4;
uniform.data.push(0);
}
// 4 elements per block/line
const padding = (offset / 4) % 4;
if (padding > 0) {
const space = 4 - padding;
if (originDataLength > 1 && originDataLength <= space) {
if (originDataLength === 2) {
if (space === 3) {
offset += 4;
mergedUniformData.push(0);
}
mergedUniformData.push(...uniform.data);
this.uniformGPUBufferLayout.push({
name: uniform.name,
offset,
});
}
} else {
for (let i = 0; i < space; i++) {
offset += 4;
mergedUniformData.push(0);
}
mergedUniformData.push(...uniform.data);
this.uniformGPUBufferLayout.push({
name: uniform.name,
offset,
});
}
}
offset += 4 * originDataLength;
}
});
this.uniformBuffer = new WebGPUBuffer(this.engine, {
// TODO: 处理 Struct 和 boolean
// @ts-ignore
data:
mergedUniformData instanceof Array
? // @ts-ignore
new Float32Array(mergedUniformData)
: mergedUniformData,
usage:
WebGPUConstants.BufferUsage.Uniform |
WebGPUConstants.BufferUsage.CopyDst,
});
this.bindGroupEntries.push({
binding: 0,
resource: {
buffer: this.uniformBuffer.get(),
},
});
}
// create GPUBuffers for storeage buffers
buffers.forEach((buffer) => {
if (!isNil(buffer.data)) {
if (
buffer.type === AST_TOKEN_TYPES.Vector4FloatArray ||
buffer.type === AST_TOKEN_TYPES.FloatArray
) {
let gpuBuffer;
if (buffer.name === this.context.output.name) {
gpuBuffer = new WebGPUBuffer(this.engine, {
// @ts-ignore
data: isFinite(Number(buffer.data)) ? [buffer.data] : buffer.data,
usage:
WebGPUConstants.BufferUsage.Storage |
WebGPUConstants.BufferUsage.CopyDst |
WebGPUConstants.BufferUsage.CopySrc,
});
this.outputBuffer = gpuBuffer;
this.context.output = {
name: buffer.name,
// @ts-ignore
length: isFinite(Number(buffer.data)) ? 1 : buffer.data.length,
typedArrayConstructor: Float32Array,
gpuBuffer: gpuBuffer.get(),
};
} else {
if (buffer.isReferer) {
// @ts-ignore
if (buffer.data.model && buffer.data.model.outputBuffer) {
// @ts-ignore
gpuBuffer = (buffer.data.model as WebGPUComputeModel)
.outputBuffer;
} else {
// referred kernel haven't been executed
}
} else {
gpuBuffer = new WebGPUBuffer(this.engine, {
// @ts-ignore
data: isFinite(Number(buffer.data))
? [buffer.data]
: buffer.data,
usage:
WebGPUConstants.BufferUsage.Storage |
WebGPUConstants.BufferUsage.CopyDst |
WebGPUConstants.BufferUsage.CopySrc,
});
}
}
this.vertexBuffers[buffer.name] = gpuBuffer;
this.bindGroupEntries.push({
binding: bufferBindingIndex,
resource: {
name: buffer.name,
refer: gpuBuffer ? undefined : buffer.data,
buffer: gpuBuffer ? gpuBuffer.get() : undefined,
},
});
bufferBindingIndex++;
}
}
});
// create compute pipeline layout
this.computePipeline = this.engine.device.createComputePipeline({
computeStage,
});
console.log(this.bindGroupEntries);
this.bindGroup = this.engine.device.createBindGroup({
layout: this.computePipeline.getBindGroupLayout(0),
entries: this.bindGroupEntries,
});
}
public destroy(): void {
if (this.uniformBuffer) {
this.uniformBuffer.destroy();
}
Object.keys(this.vertexBuffers).forEach((bufferName) =>
this.vertexBuffers[bufferName].destroy(),
);
}
public async readData() {
const { output } = this.context;
if (output) {
const { length, typedArrayConstructor, gpuBuffer } = output;
if (gpuBuffer) {
// await gpuBuffer.mapAsync(WebGPUConstants.MapMode.Read);
// const arraybuffer = gpuBuffer.getMappedRange();
// let arraybuffer;
// if (isSafari) {
// arraybuffer = await gpuBuffer.mapReadAsync();
// } else {
const byteCount = length! * typedArrayConstructor!.BYTES_PER_ELEMENT;
// @see https://developers.google.com/web/updates/2019/08/get-started-with-gpu-compute-on-the-web
const gpuReadBuffer = this.engine.device.createBuffer({
size: byteCount,
usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
});
const encoder = this.engine.device.createCommandEncoder();
encoder.copyBufferToBuffer(gpuBuffer, 0, gpuReadBuffer, 0, byteCount);
const queue: GPUQueue = isSafari
? // @ts-ignore
this.engine.device.getQueue()
: this.engine.device.defaultQueue;
queue.submit([encoder.finish()]);
await gpuReadBuffer.mapAsync(WebGPUConstants.MapMode.Read);
const arraybuffer = gpuReadBuffer.getMappedRange();
const typedArray = new typedArrayConstructor!(arraybuffer.slice(0));
gpuReadBuffer.unmap();
return typedArray;
}
}
return new Float32Array();
}
public run() {
if (this.engine.currentComputePass) {
this.engine.currentComputePass.setPipeline(this.computePipeline);
// this.bindGroupEntries.forEach((entry) => {
// if (!entry.resource.buffer) {
// // get referred kernel's output
// const gpuBuffer = (entry.resource.refer.model as WebGPUComputeModel)
// .outputBuffer;
// this.vertexBuffers[entry.resource.name] = gpuBuffer;
// entry.resource.buffer = gpuBuffer.get();
// }
// });
// const bindGroup = this.engine.device.createBindGroup({
// layout: this.computePipeline.getBindGroupLayout(0),
// entries: this.bindGroupEntries,
// });
this.engine.currentComputePass.setBindGroup(0, this.bindGroup);
this.engine.currentComputePass.dispatch(...this.context.dispatch);
}
}
public updateBuffer(
bufferName: string,
data:
| number[]
| Float32Array
| Uint8Array
| Uint16Array
| Uint32Array
| Int8Array
| Int16Array
| Int32Array,
offset: number = 0,
) {
const buffer = this.vertexBuffers[bufferName];
if (buffer) {
buffer.subData({ data, offset });
}
}
public updateUniform(
uniformName: string,
data:
| number
| number[]
| Float32Array
| Uint8Array
| Uint16Array
| Uint32Array
| Int8Array
| Int16Array
| Int32Array,
) {
const layout = this.uniformGPUBufferLayout.find(
(l) => l.name === uniformName,
);
if (layout) {
this.uniformBuffer.subData({
data: Number.isFinite(data)
? new Float32Array([data as number])
: new Float32Array(
data as
| number[]
| Float32Array
| Uint8Array
| Uint16Array
| Uint32Array
| Int8Array
| Int16Array
| Int32Array,
),
offset: layout.offset,
});
}
}
public confirmInput(model: IComputeModel, inputName: string): void {
// copy output GPUBuffer of kernel
const inputBuffer = this.vertexBuffers[inputName];
const outputBuffer = (model as WebGPUComputeModel).outputBuffer;
if (inputBuffer && outputBuffer && inputBuffer !== outputBuffer) {
const encoder = this.engine.device.createCommandEncoder();
const {
length,
typedArrayConstructor,
} = (model as WebGPUComputeModel).context.output;
const byteCount = length! * typedArrayConstructor!.BYTES_PER_ELEMENT;
encoder.copyBufferToBuffer(
outputBuffer.get(),
0,
inputBuffer.get(),
0,
byteCount,
);
const queue: GPUQueue = isSafari
? // @ts-ignore
this.engine.device.getQueue()
: this.engine.device.defaultQueue;
queue.submit([encoder.finish()]);
}
}
private compileShaderToSpirV(
source: string,
type: string,
shaderVersion: string,
): Promise<Uint32Array> {
return this.compileRawShaderToSpirV(shaderVersion + source, type);
}
private compileRawShaderToSpirV(
source: string,
type: string,
): Promise<Uint32Array> {
return this.engine.glslang.compileGLSL(source, type);
}
private async compileComputePipelineStageDescriptor(
computeCode: string,
): Promise<Pick<GPUComputePipelineDescriptor, 'computeStage'>> {
let computeShader: Uint32Array | string = computeCode;
const shaderVersion = '#version 450\n';
if (!this.engine.options.useWGSL) {
computeShader = await this.compileShaderToSpirV(
computeCode,
'compute',
shaderVersion,
);
}
return {
computeStage: {
module: this.engine.device.createShaderModule({
code: computeShader,
// @ts-ignore
isWHLSL: isSafari,
}),
entryPoint: 'main',
},
};
}
} | the_stack |
import type { NestingInfo } from "../../utils/selectors"
import {
isNestingSelector,
isNestingAtRule,
isTypeSelector,
hasNodesSelector,
isSelectorCombinator,
findNestingSelector,
isDescendantCombinator,
} from "../../utils/selectors"
import type {
VCSSStyleSheet,
VCSSNode,
VCSSSelectorNode,
VCSSTypeSelector,
VCSSNestingSelector,
VCSSSelectorValueNode,
VCSSAtRule,
VCSSStyleRule,
VCSSSelector,
VCSSSelectorPseudo,
} from "../../ast"
import {
isVCSSAtRule,
isVCSSContainerNode,
hasSelectorNodes,
} from "../../utils/css-nodes"
export class ResolvedSelectors {
public readonly container:
| (VCSSAtRule & { selectors: VCSSSelectorNode[] })
| VCSSStyleRule
public readonly selectors: ResolvedSelector[] = []
public readonly level: number
public readonly parent: ResolvedSelectors | null
public readonly children: ResolvedSelectors[] = []
/**
* constructor
* @param {Node[]} selector the selector
* @param {Node} container the container node
*/
public constructor(
container:
| (VCSSAtRule & { selectors: VCSSSelectorNode[] })
| VCSSStyleRule,
parent: ResolvedSelectors | null,
) {
this.container = container
this.parent = parent
this.level = (parent?.level ?? -1) + 1
}
}
export class ResolvedSelector {
public readonly owner: ResolvedSelectors
public readonly selector: VCSSSelectorNode[]
/**
* constructor
* @param {Node[]} selector the selector
* @param {Node} container the container node
*/
public constructor(owner: ResolvedSelectors, selector: VCSSSelectorNode[]) {
this.owner = owner
this.selector = selector
}
}
export class CSSSelectorResolver {
/**
* Get the selector that resolved the nesting.
* @param {VCSSStyleSheet} rootStyle The style node
* @returns {ResolvedSelector[]} the selector that resolved the nesting.
*/
public resolveSelectors(rootStyle: VCSSStyleSheet): ResolvedSelectors[] {
return this.resolveNodesSelectors(rootStyle.nodes, null)
}
/**
* Get the selector that resolved the nesting.
* @param {Node[]} nodes the nodes
* @param {ResolvedSelector[]|null} parentSelectors
* @returns {ResolvedSelector[]} resolved selectors
*/
private resolveNodesSelectors(
nodes: VCSSNode[],
parentSelector: ResolvedSelectors | null,
): ResolvedSelectors[] {
const results: ResolvedSelectors[] = []
for (const node of nodes) {
if (this.isIgnoreNode(node)) {
continue
}
if (hasSelectorNodes(node)) {
results.push(this.resolveNodeSelectors(node, parentSelector))
} else {
if (isVCSSContainerNode(node)) {
results.push(
...this.resolveNodesSelectors(
node.nodes,
parentSelector,
),
)
}
}
}
return results
}
/**
* Get the selector that resolved the nesting.
* @param {VCSSStyleSheet} rootStyle The style node
* @returns {ResolvedSelector[]} the selector that resolved the nesting.
*/
private resolveNodeSelectors(
node:
| (VCSSAtRule & { name: "nest"; selectors: VCSSSelectorNode[] })
| VCSSStyleRule,
parentSelector: ResolvedSelectors | null,
): ResolvedSelectors {
const selectorNodes = node.selectors.filter(hasNodesSelector)
const resolved = new ResolvedSelectors(node, parentSelector)
if (!parentSelector) {
resolved.selectors.push(
...selectorNodes.map(
(selectorNode) =>
new ResolvedSelector(resolved, selectorNode.nodes),
),
)
} else {
for (const selectorNode of selectorNodes.filter(hasNodesSelector)) {
resolved.selectors.push(
...this.resolveNestingSelectors(
resolved,
selectorNode.nodes,
parentSelector,
node,
),
)
}
}
if (isVCSSContainerNode(node)) {
resolved.children.push(
...this.resolveNodesSelectors(node.nodes, resolved),
)
}
return resolved
}
private isIgnoreNode(node: VCSSNode) {
return (
isVCSSAtRule(node) &&
node.name === "keyframes" &&
node.identifier === "@"
)
}
/**
* Resolve nesting selector
* @param {Node[]} selectorNodes the selector
* @param {ResolvedSelector[]} parentSelectors parent selectors
* @param {Node} container the container node
* @returns {ResolvedSelector[]} resolved selectors
*/
protected resolveNestingSelectors(
owner: ResolvedSelectors,
selectorNodes: VCSSSelectorNode[],
parentSelectors: ResolvedSelectors | null,
container: VCSSAtRule | VCSSStyleRule,
): ResolvedSelector[] {
if (isNestingAtRule(container)) {
return this.resolveSelectorForNestContaining(
owner,
selectorNodes,
findNestingSelector(selectorNodes),
parentSelectors,
container,
)
}
const nestingIndex = selectorNodes.findIndex(isNestingSelector)
if (nestingIndex === 0) {
return this.resolveSelectorForNestPrefixed(
owner,
selectorNodes,
parentSelectors,
container,
)
}
return [new ResolvedSelector(owner, selectorNodes)]
}
/**
* Resolve selectors that a nesting selector on the first.
* @param {Node[]} selectorNodes the selector
* @param {ResolvedSelector[]} parentSelectors parent selectors
* @param {Node} container the container node
* @returns {ResolvedSelector[]} resolved selectors
*/
private resolveSelectorForNestPrefixed(
owner: ResolvedSelectors,
selectorNodes: VCSSSelectorNode[],
parentSelectors: ResolvedSelectors | null,
container: VCSSAtRule | VCSSStyleRule,
): ResolvedSelector[] {
if (!selectorNodes.length || !isNestingSelector(selectorNodes[0])) {
// To be nest-prefixed, a nesting selector must be the first simple selector in the first compound selector of the selector.
return [new ResolvedSelector(owner, selectorNodes)]
}
const after = selectorNodes.slice(1)
return this.resolveSelectorForNestConcat(
owner,
after,
parentSelectors,
container,
)
}
/**
* Resolves selectors that concatenate nested selectors.
* @param {Node[]} selectorNodes the selector
* @param {ResolvedSelector[]} parentSelectors parent selectors
* @param {Node} container the container node
* @returns {ResolvedSelector[]} resolved selectors
*/
protected resolveSelectorForNestConcat(
owner: ResolvedSelectors,
selectorNodes: VCSSSelectorNode[],
parentSelectors: ResolvedSelectors | null,
_container: VCSSAtRule | VCSSStyleRule,
): ResolvedSelector[] {
if (!parentSelectors) {
const nodes = [...selectorNodes]
if (isDescendantCombinator(nodes[0])) {
nodes.shift()
}
if (isDescendantCombinator(nodes[nodes.length - 1])) {
nodes.pop()
}
return [new ResolvedSelector(owner, [...nodes])]
}
return parentSelectors.selectors.map((parentSelector) => {
const nodes = [...selectorNodes]
const parent = [...parentSelector.selector]
if (
parent.length > 0 &&
isSelectorCombinator(parent[parent.length - 1]) &&
nodes.length > 0 &&
isSelectorCombinator(nodes[0])
) {
if (isDescendantCombinator(nodes[0])) {
nodes.shift()
} else if (isDescendantCombinator(parent[parent.length - 1])) {
parent.pop()
}
}
return new ResolvedSelector(owner, [...parent, ...nodes])
})
}
/**
* Resolve selectors that contain a nesting selector.
* @param {Node[]} selectorNodes the selector
* @param {ResolvedSelector[]} parentSelectors parent selectors
* @param {Node} container the container node
* @returns {ResolvedSelector[]} resolved selectors
*/
protected resolveSelectorForNestContaining(
owner: ResolvedSelectors,
selectorNodes: VCSSSelectorNode[],
nestingInfo: NestingInfo | null,
parentSelectors: ResolvedSelectors | null,
_container: VCSSAtRule | VCSSStyleRule,
): ResolvedSelector[] {
if (!nestingInfo) {
// Must be nest-containing, which means it contains a nesting selector in it somewhere.
return [new ResolvedSelector(owner, selectorNodes)]
}
const {
nestingIndex,
nodes: hasNestingNodes,
node: nestingNode,
} = nestingInfo
const beforeSelector = hasNestingNodes.slice(0, nestingIndex)
const afterSelector = hasNestingNodes.slice(nestingIndex + 1)
const nestingLeftNode =
beforeSelector.length > 0
? beforeSelector[beforeSelector.length - 1]
: null
const nestingRightNode =
afterSelector.length > 0 ? afterSelector[0] : null
const maybeJoinLeft =
nestingLeftNode &&
nestingLeftNode.range[1] === nestingNode.range[0] &&
!isSelectorCombinator(nestingLeftNode)
const maybeJoinRight =
nestingRightNode &&
nestingNode.range[1] === nestingRightNode.range[0] &&
isTypeSelector(nestingRightNode)
let resolved: ResolvedSelector[]
if (parentSelectors) {
resolved = parentSelectors.selectors.map((p) => {
const before = [...beforeSelector]
const after = [...afterSelector]
const parentSelector = [...p.selector]
const needJoinLeft =
maybeJoinLeft && isTypeSelector(parentSelector[0])
const needJoinRight =
maybeJoinRight &&
!isSelectorCombinator(
parentSelector[parentSelector.length - 1],
)
if (
needJoinLeft &&
needJoinRight &&
parentSelector.length === 1
) {
// concat both (e.g. `bar { @nest .foo-&-baz {} }` -> .foo-bar-baz)
before.push(
newNestingConcatBothSelectorNodes(
before.pop() as VCSSSelectorValueNode,
parentSelector.shift() as VCSSTypeSelector,
after.shift() as VCSSTypeSelector,
nestingNode,
),
)
} else {
if (needJoinLeft) {
// concat left (e.g. `bar { @nest .foo-& {} }` -> .foo-bar)
before.push(
newNestingConcatLeftSelectorNodes(
before.pop() as VCSSSelectorValueNode,
parentSelector.shift() as VCSSTypeSelector,
nestingNode,
),
)
}
if (needJoinRight) {
// concat right (e.g. `.foo { @nest &-bar {} }` -> .foo-bar)
after.unshift(
newNestingConcatRightSelectorNodes(
parentSelector.pop() as VCSSSelectorValueNode,
after.shift() as VCSSTypeSelector,
nestingNode,
),
)
}
}
return new ResolvedSelector(owner, [
...before,
...parentSelector,
...after,
])
})
} else {
const before = [...beforeSelector]
const after = [...afterSelector]
while (isDescendantCombinator(before[0])) {
before.shift()
}
if (isDescendantCombinator(after[0])) {
while (isDescendantCombinator(before[before.length - 1])) {
before.pop()
}
}
while (before.length === 0 && isDescendantCombinator(after[0])) {
after.shift()
}
while (isDescendantCombinator(after[after.length - 1])) {
after.pop()
}
resolved = [new ResolvedSelector(owner, [...before, ...after])]
}
let nestingTargetNode: VCSSSelectorNode = nestingNode
while (!selectorNodes.includes(nestingTargetNode)) {
const parent = nestingTargetNode.parent as
| VCSSSelector
| VCSSSelectorPseudo
const index: number = parent.parent.nodes.indexOf(parent as never)
const before = parent.parent.nodes.slice(
0,
index,
) as VCSSSelectorNode[]
const after = parent.parent.nodes.slice(
index + 1,
) as VCSSSelectorNode[]
resolved = resolved.map((selector) => {
const newNode = parent.copy()
newNode.nodes = selector.selector as never
return new ResolvedSelector(owner, [
...before,
newNode,
...after,
])
})
nestingTargetNode = parent
}
return resolved
}
}
/**
* Creates a selector node that concat the left and right selectors of the parent selector and the nested selector.
*/
function newNestingConcatBothSelectorNodes(
left: VCSSSelectorValueNode,
parent: VCSSTypeSelector,
right: VCSSTypeSelector,
_nesting: VCSSNestingSelector,
) {
const loc = {
start: left.loc.start,
end: right.loc.end,
}
const newNode = left.copy({
loc,
start: left.range[0],
end: right.range[1],
parent: left.parent,
value: `${left.value}${parent.selector}${right.selector}`,
})
return newNode
}
/**
* Creates a selector node that concat the left selectors of the parent selector and the nested selector.
*/
function newNestingConcatLeftSelectorNodes(
left: VCSSSelectorValueNode,
parent: VCSSTypeSelector,
nesting: VCSSNestingSelector,
) {
const loc = {
start: left.loc.start,
end: nesting.loc.end,
}
const newNode = left.copy({
loc,
start: left.range[0],
end: nesting.range[1],
parent: left.parent,
value: `${left.value}${parent.selector}`,
})
return newNode
}
/**
* Creates a selector node that concat the right selectors of the parent selector and the nested selector.
*/
function newNestingConcatRightSelectorNodes(
parent: VCSSSelectorValueNode,
right: VCSSTypeSelector,
nesting: VCSSNestingSelector,
) {
const loc = {
start: nesting.loc.start,
end: right.loc.end,
}
const newNode = parent.copy({
node: right.node,
loc,
start: nesting.range[0],
end: right.range[1],
parent: right.parent,
value: `${parent.value}${right.selector}`,
})
return newNode
} | the_stack |
import Graph from "./interfaces/Graph.js";
import SavedNote from "./interfaces/SavedNote.js";
import { FileId } from "./interfaces/FileId.js";
import GraphNodePositionUpdate from "./interfaces/NodePositionUpdate.js";
import { Link } from "./interfaces/Link.js";
import LinkedNote from "./interfaces/LinkedNote.js";
import Note from "./interfaces/Note.js";
import NoteFromUser from "./interfaces/NoteFromUser.js";
import { NoteId } from "./interfaces/NoteId.js";
import NoteListItem from "./interfaces/NoteListItem.js";
import NoteListItemFeatures from "./interfaces/NoteListItemFeatures.js";
import { NoteListSortMode } from "./interfaces/NoteListSortMode.js";
import NoteToTransmit from "./interfaces/NoteToTransmit.js";
import UserNoteChange from "./interfaces/UserNoteChange.js";
import { UserNoteChangeType } from "./interfaces/UserNoteChangeType.js";
import * as Utils from "../utils.js";
import NoteContentBlock, {
NoteContentBlockHeading,
NoteContentBlockLink,
NoteContentBlockParagraph,
NoteContentBlockType,
NoteContentBlockWithFile,
} from "./interfaces/NoteContentBlock.js";
import { NOTE_TITLE_PLACEHOLDER } from "./config.js";
const shortenText = (text:string, maxLength:number):string => {
if (text.length > maxLength) {
return text.trim().substring(0, maxLength) + "…";
} else {
return text;
}
};
const getDisplayNoteTitle = (note:Note, maxLength = 800):string => {
if (note.title.length === 0) {
return NOTE_TITLE_PLACEHOLDER;
}
const titleUnescapedAndTrimmed
= Utils.unescapeHTML(note.title).trim();
const titleShortened = shortenText(titleUnescapedAndTrimmed, maxLength);
if (titleShortened.length === 0) {
return NOTE_TITLE_PLACEHOLDER;
}
return titleShortened;
};
const normalizeNoteTitle = (title:string) => {
return title
.replaceAll(/[\r\n]/g, " ")
.trim();
}
const removeDefaultTextParagraphs = (note:Note):void => {
note.blocks = note.blocks.filter((block) => {
const isDefaultTextParagraph = (
block.type === "paragraph"
&& block.data.text === "Note text"
);
return !isDefaultTextParagraph;
});
};
const removeEmptyLinkBlocks = (note:Note):void => {
note.blocks = note.blocks.filter((block) => {
const isEmptyLinkBlock = (
block.type === "link"
&& block.data.link === ""
);
return !isEmptyLinkBlock;
});
};
const noteWithSameTitleExists = (
userNote:NoteFromUser,
graph:Graph,
):boolean => {
return graph.notes.some((noteFromDB:SavedNote):boolean => {
return (
(noteFromDB.title === userNote.title)
&& (noteFromDB.id !== userNote.id)
);
});
};
const findNote = (graph:Graph, noteId:NoteId):SavedNote | null => {
return Utils.binaryArrayFind(graph.notes, "id", noteId);
};
const getNewNoteId = (graph:Graph):NoteId => {
graph.idCounter = graph.idCounter + 1;
return graph.idCounter;
};
const updateNotePosition = (
graph:Graph,
nodePositionUpdate: GraphNodePositionUpdate,
): boolean => {
const note:SavedNote | null = findNote(graph, nodePositionUpdate.id);
if (note === null) {
return false;
}
note.position = nodePositionUpdate.position;
return true;
};
const getLinksOfNote = (graph:Graph, noteId:NoteId):Link[] => {
const linksOfThisNote:Link[] = graph.links
.filter((link:Link):boolean => {
return (link[0] === noteId) || (link[1] === noteId);
});
return linksOfThisNote;
}
const getLinkedNotes = (graph:Graph, noteId:NoteId):LinkedNote[] => {
const notes:SavedNote[] = getLinksOfNote(graph, noteId)
.map((link:Link):SavedNote => {
const linkedNoteId = (link[0] === noteId) ? link[1] : link[0];
// we are sure that the notes we are retrieving from noteIds in links
// really exist. that's why we cast the result of findNote as
// SavedNote
return findNote(graph, linkedNoteId) as SavedNote;
});
const linkedNotes:LinkedNote[] = notes
.map((note:SavedNote) => {
const linkedNote:LinkedNote = {
id: note.id,
title: getDisplayNoteTitle(note),
creationTime: note.creationTime,
updateTime: note.updateTime,
}
return linkedNote;
});
return linkedNotes;
};
const getNumberOfLinkedNotes = (graph:Graph, noteId:NoteId):number => {
const linksOfThisNote:Link[] = getLinksOfNote(graph, noteId);
const numberOfLinkedNotes = linksOfThisNote.length;
return numberOfLinkedNotes;
}
const getNumberOfLinkedNotesForSeveralNotes = (
graph:Graph,
noteIds:NoteId[],
):any => {
const numbersOfLinkedNotes = {};
noteIds.forEach((noteId) => {
numbersOfLinkedNotes[noteId] = 0;
});
graph.links.forEach((link) => {
if (typeof numbersOfLinkedNotes[link[0]] === "number"){
numbersOfLinkedNotes[link[0]]++;
}
if (typeof numbersOfLinkedNotes[link[1]] === "number"){
numbersOfLinkedNotes[link[1]]++;
}
});
return numbersOfLinkedNotes;
}
const getNumberOfUnlinkedNotes = (graph:Graph):number => {
/*
We could do it like this but then the links array is traversed as many times
as there are notes. So we don't do it like this. We do it faster.
const numberOfUnlinkedNotes = graph.notes.filter((note) => {
return getNumberOfLinkedNotes(graph, note.id) === 0;
}).length;
*/
const linkedNotes = new Set();
graph.links.forEach((link) => {
linkedNotes.add(link[0]);
linkedNotes.add(link[1]);
});
const numberOfAllNotes = graph.notes.length;
const numberOfLinkedNotes = Array.from(linkedNotes).length;
const numberOfUnlinkedNotes = numberOfAllNotes - numberOfLinkedNotes;
return numberOfUnlinkedNotes;
};
const removeLinksOfNote = (graph: Graph, noteId: NoteId):true => {
graph.links = graph.links.filter((link) => {
return (link[0] !== noteId) && (link[1] !== noteId);
});
return true;
};
const getFilesOfNote = (note:SavedNote):FileId[] => {
return note.blocks
.filter(blockHasFile)
.map((block: NoteContentBlockWithFile):FileId => {
return block.data.file.fileId;
});
};
const incorporateUserChangesIntoNote = (
changes:UserNoteChange[] | undefined,
note:SavedNote,
graph:Graph,
):void => {
if (Array.isArray(changes)) {
changes.forEach((change) => {
if (change.type === UserNoteChangeType.LINKED_NOTE_ADDED) {
const link:Link = [note.id, change.noteId];
graph.links.push(link);
}
if (change.type === UserNoteChangeType.LINKED_NOTE_DELETED) {
graph.links = graph.links.filter((link) => {
return !(
link.includes(note.id) && link.includes(change.noteId)
);
});
}
});
}
};
const createNoteToTransmit = (
databaseNote:NonNullable<SavedNote>,
graph: NonNullable<Graph>,
):NoteToTransmit => {
const noteToTransmit:NoteToTransmit = {
id: databaseNote.id,
blocks: databaseNote.blocks,
title: databaseNote.title,
creationTime: databaseNote.creationTime,
updateTime: databaseNote.updateTime,
linkedNotes: getLinkedNotes(graph, databaseNote.id),
position: databaseNote.position,
numberOfCharacters: getNumberOfCharacters(databaseNote),
};
return noteToTransmit;
}
const createNoteListItem = (
databaseNote:SavedNote,
graph: Graph,
// for performance reasons, numberOfLinkedNotes can be given as argument,
// so that this function does not have to find it out by itself for each
// NoteListItem to be created
numberOfLinkedNotes?:number,
):NoteListItem => {
const noteListItem:NoteListItem = {
id: databaseNote.id,
title: getDisplayNoteTitle(databaseNote),
creationTime: databaseNote.creationTime,
updateTime: databaseNote.updateTime,
features: getNoteFeatures(databaseNote),
numberOfLinkedNotes: typeof numberOfLinkedNotes === "number"
? numberOfLinkedNotes
: getNumberOfLinkedNotes(graph, databaseNote.id),
numberOfCharacters: getNumberOfCharacters(databaseNote),
numberOfFiles: getNumberOfFiles(databaseNote),
};
return noteListItem;
};
const createNoteListItems = (
databaseNotes:SavedNote[],
graph: Graph,
):NoteListItem[] => {
/*
Before we transform every SavedNote to a NoteListItem, we get the
number of linked notes for every note in one batch. This is more performant
than traversing all links again and again for every single note.
*/
const noteIds = databaseNotes.map((note) => note.id);
const numbersOfLinkedNotes
= getNumberOfLinkedNotesForSeveralNotes(graph, noteIds);
const noteListItems = databaseNotes.map((databaseNote) => {
return createNoteListItem(
databaseNote,
graph,
numbersOfLinkedNotes[databaseNote.id],
);
})
return noteListItems;
};
const getNoteFeatures = (note:SavedNote):NoteListItemFeatures => {
let containsText = false;
let containsWeblink = false;
let containsCode = false;
let containsImages = false;
let containsDocuments = false;
let containsAudio = false;
let containsVideo = false;
note.blocks.forEach((block) => {
if (block.type === NoteContentBlockType.PARAGRAPH) {
containsText = true;
}
if (block.type === NoteContentBlockType.LINK) {
containsWeblink = true;
}
if (block.type === NoteContentBlockType.CODE) {
containsCode = true;
}
if (block.type === NoteContentBlockType.IMAGE) {
containsImages = true;
}
if (block.type === NoteContentBlockType.DOCUMENT) {
containsDocuments = true;
}
if (block.type === NoteContentBlockType.AUDIO) {
containsAudio = true;
}
if (block.type === NoteContentBlockType.VIDEO) {
containsVideo = true;
}
});
const features:NoteListItemFeatures = {
containsText,
containsWeblink,
containsCode,
containsImages,
containsDocuments,
containsAudio,
containsVideo,
};
return features;
};
const getSortKeyForTitle = (title) => {
return title
.toLowerCase()
.replace(/(["'.“”„‘’—\-»#*[\]/])/g, "")
.trim();
}
/**
* Checks if the block contains a valid file.
* @param block
* @returns {boolean} true or false
*/
const blockHasFile = (
block:NoteContentBlock,
):block is NoteContentBlockWithFile => {
return (
[
NoteContentBlockType.IMAGE,
NoteContentBlockType.DOCUMENT,
NoteContentBlockType.AUDIO,
NoteContentBlockType.VIDEO,
].includes(block.type)
&& (typeof (block as NoteContentBlockWithFile).data.file.fileId === "string")
);
};
const getNumberOfFiles = (note:SavedNote) => {
return note.blocks.filter(blockHasFile).length;
};
const getSortFunction = (
sortMode:NoteListSortMode,
):((a:NoteListItem, b:NoteListItem) => number) => {
const sortFunctions = {
[NoteListSortMode.CREATION_DATE_ASCENDING]: (a, b) => {
return a.creationTime - b.creationTime;
},
[NoteListSortMode.CREATION_DATE_DESCENDING]: (a, b) => {
return b.creationTime - a.creationTime;
},
[NoteListSortMode.UPDATE_DATE_ASCENDING]: (a, b) => {
return a.updateTime - b.updateTime;
},
[NoteListSortMode.UPDATE_DATE_DESCENDING]: (a, b) => {
return b.updateTime - a.updateTime;
},
[NoteListSortMode.TITLE_ASCENDING]: (a, b) => {
const aNormalized = getSortKeyForTitle(a.title);
const bNormalized = getSortKeyForTitle(b.title);
return aNormalized.localeCompare(bNormalized);
},
[NoteListSortMode.TITLE_DESCENDING]: (a, b) => {
const aNormalized = getSortKeyForTitle(a.title);
const bNormalized = getSortKeyForTitle(b.title);
return bNormalized.localeCompare(aNormalized);
},
[NoteListSortMode.NUMBER_OF_LINKS_ASCENDING]: (a, b) => {
return a.numberOfLinkedNotes - b.numberOfLinkedNotes;
},
[NoteListSortMode.NUMBER_OF_LINKS_DESCENDING]: (a, b) => {
return b.numberOfLinkedNotes - a.numberOfLinkedNotes;
},
[NoteListSortMode.NUMBER_OF_FILES_ASCENDING]: (a, b) => {
return a.numberOfFiles - b.numberOfFiles;
},
[NoteListSortMode.NUMBER_OF_FILES_DESCENDING]: (a, b) => {
return b.numberOfFiles - a.numberOfFiles;
},
[NoteListSortMode.NUMBER_OF_CHARACTERS_ASCENDING]: (a, b) => {
return a.numberOfCharacters - b.numberOfCharacters;
},
[NoteListSortMode.NUMBER_OF_CHARACTERS_DESCENDING]: (a, b) => {
return b.numberOfCharacters - a.numberOfCharacters;
},
};
return sortFunctions[sortMode] ?? sortFunctions.UPDATE_DATE_ASCENDING;
};
const getNumberOfCharacters = (note:SavedNote):number => {
return note.blocks.reduce((accumulator, block) => {
if ([
NoteContentBlockType.PARAGRAPH,
NoteContentBlockType.HEADING,
].includes(block.type)) {
return accumulator
+ (block as NoteContentBlockParagraph | NoteContentBlockHeading)
.data.text.length;
} else {
return accumulator;
}
}, 0);
};
const getURLsOfNote = (note:SavedNote):string[] => {
return note.blocks
.filter((block):block is NoteContentBlockLink => {
return block.type === NoteContentBlockType.LINK;
})
.map((block) => {
return block.data.link;
});
}
// https://en.wikipedia.org/wiki/Breadth-first_search
const breadthFirstSearch = (nodes, links, root: SavedNote):SavedNote[] => {
const queue:SavedNote[] = [];
const discovered:SavedNote[] = [];
discovered.push(root);
queue.push(root);
while (queue.length > 0) {
const v = queue.shift() as SavedNote;
const connectedNodes = links
.filter((link:Link):boolean => {
return (link[0] === v.id) || (link[1] === v.id);
})
.map((link:Link):SavedNote => {
const linkedNoteId = (link[0] === v.id) ? link[1] : link[0];
// we are sure that the notes we are retrieving from noteIds in links
// really exist. that's why we cast the result of findNote as
// SavedNote
return nodes.find((n) => (n.id === linkedNoteId));
});
for (let i = 0; i < connectedNodes.length; i++){
const w = connectedNodes[i];
if (!discovered.includes(w)){
discovered.push(w);
queue.push(w);
}
}
}
return discovered;
}
// https://en.wikipedia.org/wiki/Component_(graph_theory)#Algorithms
const getNumberOfComponents = (nodes:SavedNote[], links:Link[]):number => {
let totallyDiscovered:SavedNote[] = [];
let numberOfComponents = 0;
let i = 0;
while (totallyDiscovered.length < nodes.length) {
let root = nodes[i];
while (totallyDiscovered.includes(root)) {
i++;
root = nodes[i];
}
const inComponent = breadthFirstSearch(nodes, links, root);
totallyDiscovered = [...totallyDiscovered, ...inComponent] as SavedNote[];
numberOfComponents++;
i++;
}
return numberOfComponents;
}
// this returns all notes that contain a url that is used in another note too
const getNotesWithDuplicateUrls = (notes:SavedNote[]):SavedNote[] => {
const urlIndex = new Map<string, Set<SavedNote>>();
notes.forEach((note:SavedNote):void => {
const urls = getURLsOfNote(note);
urls.forEach((url) => {
if (urlIndex.has(url)) {
(urlIndex.get(url) as Set<SavedNote>).add(note);
} else {
urlIndex.set(url, new Set([note]));
}
});
});
const duplicates:Set<SavedNote> = new Set();
for (const notesWithUrl of urlIndex.values()) {
if (notesWithUrl.size > 1) {
notesWithUrl.forEach((note) => {
duplicates.add(note);
});
}
}
return Array.from(duplicates);
};
const getNotesWithDuplicateTitles = (notes:SavedNote[]):SavedNote[] => {
const titleIndex = new Map<string, Set<SavedNote>>();
notes.forEach((note:SavedNote):void => {
const noteTitle = note.title;
if (titleIndex.has(noteTitle)) {
(titleIndex.get(noteTitle) as Set<SavedNote>).add(note);
} else {
titleIndex.set(noteTitle, new Set([note]));
}
});
const duplicates:Set<SavedNote> = new Set();
for (const notesWithOneTitle of titleIndex.values()) {
if (notesWithOneTitle.size > 1) {
notesWithOneTitle.forEach((note) => {
duplicates.add(note);
});
}
}
return Array.from(duplicates);
};
const getNotesByTitle = (
notes:SavedNote[],
query: string,
caseSensitive: boolean,
):SavedNote[] => {
return notes.filter((note:SavedNote) => {
const title = note.title;
return caseSensitive
? title === query
: title.toLowerCase() === query.toLowerCase();
});
}
const getNotesWithUrl = (
notes:SavedNote[],
url: string,
):SavedNote[] => {
return notes.filter((note:SavedNote) => {
return note.blocks
.filter((block):block is NoteContentBlockLink => {
return block.type === NoteContentBlockType.LINK;
})
.some((linkBlock) => linkBlock.data.link === url);
});
}
const getNotesWithFile = (
notes: SavedNote[],
file: FileId,
):SavedNote[] => {
return notes.filter((note:SavedNote) => {
return note.blocks
.filter(blockHasFile)
.some((block) => block.data.file.fileId === file);
});
}
const getConcatenatedTextOfNote = (note:SavedNote):string => {
const blockText = note.blocks.reduce((accumulator, block) => {
if (block.type === NoteContentBlockType.PARAGRAPH) {
return accumulator + " " + block.data.text;
} else if (block.type === NoteContentBlockType.HEADING) {
return accumulator + " " + block.data.text;
} else if (block.type === NoteContentBlockType.CODE) {
return accumulator + " " + block.data.code;
} else if (block.type === NoteContentBlockType.LIST) {
const itemsConcatenated = block.data.items.join(" ");
return accumulator + " " + itemsConcatenated;
} else if (block.type === NoteContentBlockType.IMAGE) {
return accumulator + " " + block.data.caption;
} else {
return accumulator;
}
}, "");
return note.title + " " + blockText;
};
const getNotesWithTitleContainingTokens = (
notes: SavedNote[],
query: string,
caseSensitive: boolean
):SavedNote[] => {
return notes.filter((note:SavedNote) => {
if (query.length === 0) {
return true;
}
if (query.length > 0 && query.length < 3) {
return false;
}
const title = getDisplayNoteTitle(note);
const queryTokens = query.split(" ");
if (caseSensitive) {
return queryTokens.every((queryToken) => {
return title.includes(queryToken);
});
} else {
return queryTokens.every((queryToken) => {
return title.toLowerCase().includes(queryToken.toLowerCase());
});
}
});
}
const getNotesThatContainTokens = (
notes:SavedNote[],
query: string,
caseSensitive: boolean,
):SavedNote[] => {
const queryTokens = query.split(" ");
return notes
.filter((note:SavedNote) => {
const noteText = getConcatenatedTextOfNote(note);
// the note text must include every query token to be a positive
return queryTokens.every((queryToken) => {
return caseSensitive
? noteText.includes(queryToken)
: noteText.toLowerCase().includes(queryToken.toLowerCase());
});
});
}
const getNotesWithBlocksOfTypes = (
notes:SavedNote[],
types: NoteContentBlockType[],
notesMustContainAllBlockTypes:boolean,
):SavedNote[] => {
return notesMustContainAllBlockTypes
? notes
// every single note must contain blocks from all the types
.filter((note:SavedNote):boolean => {
return types.every((type) => {
return note.blocks.some((block) => block.type === type);
});
})
// every note must contain one block with only one type of types:
: notes
.filter((note:SavedNote):boolean => {
return note.blocks.some((block) => types.includes(block.type));
});
}
export {
getDisplayNoteTitle,
normalizeNoteTitle,
removeDefaultTextParagraphs,
removeEmptyLinkBlocks,
noteWithSameTitleExists,
findNote,
getNewNoteId,
updateNotePosition,
getLinkedNotes,
getNumberOfLinkedNotes,
removeLinksOfNote,
getFilesOfNote,
incorporateUserChangesIntoNote,
createNoteToTransmit,
getNoteFeatures,
getSortFunction,
getNumberOfCharacters,
getURLsOfNote,
createNoteListItem,
createNoteListItems,
getNumberOfComponents,
getNumberOfUnlinkedNotes,
getNotesWithDuplicateUrls,
getNotesWithDuplicateTitles,
getNotesByTitle,
getNotesWithUrl,
getNotesWithFile,
getConcatenatedTextOfNote,
blockHasFile,
getNotesWithTitleContainingTokens,
getNotesThatContainTokens,
getNotesWithBlocksOfTypes,
}; | the_stack |
import * as qs from 'querystring';
import * as _ from 'lodash';
import { toDate } from './utils';
export interface ParserOptions {
dateFormat?: string | string[];
blacklist?: string[]; // list of fields should not be in filter
casters?: { [key: string]: (val: string) => any };
castParams?: { [key: string]: string };
// rename the keys
selectKey?: string;
populateKey?: string;
sortKey?: string;
skipKey?: string;
limitKey?: string;
filterKey?: string;
}
export interface QueryOptions {
filter: any; // mongodb json query
sort?: string | any; // ie.: { field: 1, field2: -1 }
limit?: number;
skip?: number;
select?: string | any; // ie.: { field: 0, field2: 0 }
populate?: string | any; // path(s) to populate: a space delimited string of the path names or array like: [{path: 'field1', select: 'p1 p2'}, ...]
}
export class MongooseQueryParser {
private readonly builtInCaster = {
string: val => String(val),
date: val => {
const dt = toDate(val, this.options.dateFormat);
if (dt.isValid) {
return dt.toJSDate();
} else {
throw new Error(`Invalid date string: [${val}]`);
}
}
};
private readonly operators = [
{ operator: 'select', method: this.castSelect, defaultKey: 'select' },
{ operator: 'populate', method: this.castPopulate, defaultKey: 'populate' },
{ operator: 'sort', method: this.castSort, defaultKey: 'sort' },
{ operator: 'skip', method: this.castSkip, defaultKey: 'skip' },
{ operator: 'limit', method: this.castLimit, defaultKey: 'limit' },
{ operator: 'filter', method: this.castFilter, defaultKey: 'filter' },
];
constructor(private options: ParserOptions = {}) {
// add builtInCaster
this.options.casters = Object.assign(this.builtInCaster, options.casters);
// build blacklist
this.options.blacklist = options.blacklist || [];
this.operators.forEach(({ operator, method, defaultKey }) => {
this.options.blacklist.push(this.options[`${operator}Key`] || defaultKey);
});
}
/**
* parses query string/object to Mongoose friendly query object/QueryOptions
* @param {string | Object} query
* @param {Object} [context]
* @return {QueryOptions}
*/
parse(query: string | Object, context?: Object): QueryOptions {
const params = _.isString(query) ? qs.parse(query) : query;
const options = this.options;
let result = {};
this.operators.forEach(({ operator, method, defaultKey }) => {
const key = options[`${operator}Key`] || defaultKey;
const value = params[key];
if (value || operator === 'filter') {
result[operator] = method.call(this, value, params);
}
}, this);
result = this.parsePredefinedQuery(result, context);
return result as QueryOptions;
}
/**
* parses string to typed values
* This methods will apply auto type casting on Number, RegExp, Date, Boolean and null
* Also, it will apply defined casters in given options of the instance
* @param {string} value
* @param {string} key
* @return {any} typed value
*/
parseValue(value: string, key?: string): any {
const me = this;
const options = this.options;
// Apply casters
// Match type casting operators like: string(true), _caster(123), $('test')
const casters = options.casters;
const casting = value.match(/^([a-zA-Z_$][0-9a-zA-Z_$]*)\((.*)\)$/);
if (casting && casters[casting[1]]) {
return casters[casting[1]](casting[2]);
}
// Apply casters per params
if (key && options.castParams && options.castParams[key] && casters[options.castParams[key]]) {
return casters[options.castParams[key]](value);
}
// cast array
if (value.includes(',')) {
return value.split(',').map(val => me.parseValue(val, key));
}
// Apply type casting for Number, RegExp, Date, Boolean and null
// Match regex operators like /foo_\d+/i
const regex = value.match(/^\/(.*)\/(i?)$/);
if (regex) {
return new RegExp(regex[1], regex[2]);
}
// Match boolean values
if (value === 'true') {
return true;
}
if (value === 'false') {
return false;
}
// Match null
if (value === 'null') {
return null;
}
// Match numbers (string padded with zeros are not numbers)
if (value !== '' && !isNaN(Number(value)) && !/^0[0-9]+/.test(value)) {
return Number(value);
}
// Match dates
const dt = toDate(value, this.options.dateFormat);
if (dt.isValid) {
return dt.toJSDate();
}
return value;
}
private excludeFilterKeys(obj: any, blacklist: String[]) {
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == "object") {
this.excludeFilterKeys(obj[i], blacklist);
} else if (blacklist.indexOf(i) !== -1) {
delete obj[i];
}
}
return _.isArray(obj) ? _.remove(obj,el => _.isEmpty(el)) : obj
}
private castFilter(filter, params) {
const options = this.options;
const parsedFilter = filter ? this.parseFilter(filter) : {};
// filter out blacklisted keys in JSON filter query
const subsetParsedFilter = this.excludeFilterKeys(parsedFilter, options.blacklist);
return Object.keys(params)
.map(val => {
const join = params[val] ? `${val}=${params[val]}` : val;
// Separate key, operators and value
const [, prefix, key, op, value] = join.match(/(!?)([^><!=]+)([><]=?|!?=|)(.*)/);
return { prefix, key, op: this.parseOperator(op), value: this.parseValue(value, key) };
})
.filter(({ key }) => options.blacklist.indexOf(key) === -1)
.reduce((result, { prefix, key, op, value }) => {
if (!result[key]) {
result[key] = {};
}
if (Array.isArray(value)) {
result[key][op === '$ne' ? '$nin' : '$in'] = value;
} else if (op === '$exists') {
result[key][op] = prefix !== '!';
} else if (op === '$eq') {
result[key] = value;
} else if (op === '$ne' && typeof value === 'object') {
result[key].$not = value;
} else {
result[key][op] = value;
}
return result;
}, subsetParsedFilter);
}
private parseFilter(filter) {
try {
if (typeof filter === 'object') {
return filter;
}
return JSON.parse(filter);
} catch (err) {
throw new Error(`Invalid JSON string: ${filter}`);
}
}
private parseOperator(operator) {
if (operator === '=') {
return '$eq';
} else if (operator === '!=') {
return '$ne';
} else if (operator === '>') {
return '$gt';
} else if (operator === '>=') {
return '$gte';
} else if (operator === '<') {
return '$lt';
} else if (operator === '<=') {
return '$lte';
} else if (!operator) {
return '$exists';
}
}
/**
* cast select query to object like:
* select=a,b or select=-a,-b
* =>
* {select: { a: 1, b: 1 }} or {select: { a: 0, b: 0 }}
* @param val
*/
private castSelect(val) {
const fields = this.parseUnaries(val, { plus: 1, minus: 0 });
/*
From the MongoDB documentation:
"A projection cannot contain both include and exclude specifications, except for the exclusion of the _id field."
*/
const hasMixedValues = Object.keys(fields)
.reduce((set, key) => {
if (key !== '_id') {
set.add(fields[key]);
}
return set;
}, new Set()).size > 1;
if (hasMixedValues) {
Object.keys(fields)
.forEach(key => {
if (fields[key] === 1) {
delete fields[key];
}
});
}
return fields;
}
/**
* cast populate query to object like:
* populate=field1.p1,field1.p2,field2
* =>
* [{path: 'field1', select: 'p1 p2'}, {path: 'field2'}]
* @param val
*/
private castPopulate(val: string) {
return val
.split(',')
.map(qry => {
const [p, s] = qry.split('.', 2);
return s ? { path: p, select: s } : { path: p };
}).reduce((prev, curr, key) => {
// consolidate population array
const path = curr.path;
const select = (curr as any).select;
let found = false;
prev.forEach(e => {
if (e.path === path) {
found = true;
if (select) {
e.select = e.select ? (e.select + ' ' + select) : select;
}
}
});
if (!found) {
prev.push(curr);
}
return prev;
}, []);
}
/**
* cast sort query to object like
* sort=-a,b
* =>
* {sort: {a: -1, b: 1}}
* @param sort
*/
private castSort(sort: string) {
return this.parseUnaries(sort);
}
/**
* Map/reduce helper to transform list of unaries
* like '+a,-b,c' to {a: 1, b: -1, c: 1}
*/
private parseUnaries(unaries, values = { plus: 1, minus: -1 }) {
const unariesAsArray = _.isString(unaries)
? unaries.split(',')
: unaries;
return unariesAsArray
.map(x => x.match(/^(\+|-)?(.*)/))
.reduce((result, [, val, key]) => {
result[key.trim()] = val === '-' ? values.minus : values.plus;
return result;
}, {});
}
/**
* cast skip query to object like
* skip=100
* =>
* {skip: 100}
* @param skip
*/
private castSkip(skip: string) {
return Number(skip);
}
/**
* cast limit query to object like
* limit=10
* =>
* {limit: 10}
* @param limit
*/
private castLimit(limit: string) {
return Number(limit);
}
/**
* transform predefined query strings defined in query string to the actual query object out of the given context
* @param query
* @param context
*/
private parsePredefinedQuery(query, context?: Object) {
if (context) {
// check if given string is the format as predefined query i.e. ${query}
const _match = (str) => {
const reg = /^\$\{([a-zA-Z_$][0-9a-zA-Z_$]*)\}$/;
const match = str.match(reg);
let val = undefined;
if (match) {
val = _.property(match[1])(context);
if (val === undefined) {
throw new Error(`No predefined query found for the provided reference [${match[1]}]`);
}
}
return { match: !!match, val: val };
};
const _transform = (obj) => {
return _.reduce(obj, (prev, curr, key) => {
let val = undefined, match = undefined;
if (_.isString(key)) {
({ match, val } = _match(key));
if (match) {
if (_.has(curr, '$exists')) {
// 1). as a key: {'${qry}': {$exits: true}} => {${qry object}}
return _.merge(prev, val);
} else if (_.isString(val)) {
// 1). as a key: {'${qry}': 'something'} => {'${qry object}': 'something'}
key = val;
} else {
throw new Error(`Invalid query string at ${key}`);
}
}
}
if (_.isString(curr)) {
({ match, val } = _match(curr));
if (match) {
_.isNumber(key)
? (prev as any).push(val) // 3). as an item of array: ['${qry}', ...] => [${qry object}, ...]
: (prev[key] = val); // 2). as a value: {prop: '${qry}'} => {prop: ${qry object}}
return prev;
}
}
if (_.isObject(curr) && !_.isRegExp(curr) && !_.isDate(curr)) {
// iterate all props & keys recursively
_.isNumber(key) ? (prev as any).push(_transform(curr)) : (prev[key] = _transform(curr));
} else {
_.isNumber(key) ? (prev as any).push(curr) : (prev[key] = curr);
}
return prev;
}, _.isArray(obj) ? [] : {});
};
return _transform(query);
}
return query;
}
} | the_stack |
import { BaseResource } from 'ms-rest-azure';
import { CloudError } from 'ms-rest-azure';
import * as moment from 'moment';
export { BaseResource } from 'ms-rest-azure';
export { CloudError } from 'ms-rest-azure';
/**
* @class
* Initializes a new instance of the ErrorResponse class.
* @constructor
* Error reponse indicates Insights service is not able to process the incoming
* request. The reason is provided in the error message.
*
* @member {string} [code] Error code.
* @member {string} [message] Error message indicating why the operation
* failed.
*/
export interface ErrorResponse {
code?: string;
message?: string;
}
/**
* @class
* Initializes a new instance of the OperationDisplay class.
* @constructor
* The object that represents the operation.
*
* @member {string} [provider] Service provider: Microsoft.Cdn
* @member {string} [resource] Resource on which the operation is performed:
* Profile, endpoint, etc.
* @member {string} [operation] Operation type: Read, write, delete, etc.
*/
export interface OperationDisplay {
provider?: string;
resource?: string;
operation?: string;
}
/**
* @class
* Initializes a new instance of the Operation class.
* @constructor
* CDN REST API operation
*
* @member {string} [name] Operation name: {provider}/{resource}/{operation}
* @member {object} [display] The object that represents the operation.
* @member {string} [display.provider] Service provider: Microsoft.Cdn
* @member {string} [display.resource] Resource on which the operation is
* performed: Profile, endpoint, etc.
* @member {string} [display.operation] Operation type: Read, write, delete,
* etc.
*/
export interface Operation {
name?: string;
display?: OperationDisplay;
}
/**
* @class
* Initializes a new instance of the Annotation class.
* @constructor
* Annotation associated with an application insights resource.
*
* @member {string} [annotationName] Name of annotation
* @member {string} [category] Category of annotation, free form
* @member {date} [eventTime] Time when event occurred
* @member {string} [id] Unique Id for annotation
* @member {string} [properties] Serialized JSON object for detailed properties
* @member {string} [relatedAnnotation] Related parent annotation if any.
* Default value: 'null' .
*/
export interface Annotation {
annotationName?: string;
category?: string;
eventTime?: Date;
id?: string;
properties?: string;
relatedAnnotation?: string;
}
/**
* @class
* Initializes a new instance of the InnerError class.
* @constructor
* Inner error
*
* @member {string} [diagnosticcontext] Provides correlation for request
* @member {date} [time] Request time
*/
export interface InnerError {
diagnosticcontext?: string;
time?: Date;
}
/**
* @class
* Initializes a new instance of the AnnotationError class.
* @constructor
* Error associated with trying to create annotation with Id that already exist
*
* @member {string} [code] Error detail code and explanation
* @member {string} [message] Error message
* @member {object} [innererror]
* @member {string} [innererror.diagnosticcontext] Provides correlation for
* request
* @member {date} [innererror.time] Request time
*/
export interface AnnotationError {
code?: string;
message?: string;
innererror?: InnerError;
}
/**
* @class
* Initializes a new instance of the APIKeyRequest class.
* @constructor
* An Application Insights component API Key createion request definition.
*
* @member {string} [name] The name of the API Key.
* @member {array} [linkedReadProperties] The read access rights of this API
* Key.
* @member {array} [linkedWriteProperties] The write access rights of this API
* Key.
*/
export interface APIKeyRequest {
name?: string;
linkedReadProperties?: string[];
linkedWriteProperties?: string[];
}
/**
* @class
* Initializes a new instance of the ApplicationInsightsComponentAPIKey class.
* @constructor
* Properties that define an API key of an Application Insights Component.
*
* @member {string} [id] The unique ID of the API key inside an Applciation
* Insights component. It is auto generated when the API key is created.
* @member {string} [apiKey] The API key value. It will be only return once
* when the API Key was created.
* @member {string} [createdDate] The create date of this API key.
* @member {string} [name] The name of the API key.
* @member {array} [linkedReadProperties] The read access rights of this API
* Key.
* @member {array} [linkedWriteProperties] The write access rights of this API
* Key.
*/
export interface ApplicationInsightsComponentAPIKey {
readonly id?: string;
readonly apiKey?: string;
createdDate?: string;
name?: string;
linkedReadProperties?: string[];
linkedWriteProperties?: string[];
}
/**
* @class
* Initializes a new instance of the ApplicationInsightsComponentExportRequest class.
* @constructor
* An Application Insights component Continuous Export configuration request
* definition.
*
* @member {string} [recordTypes] The document types to be exported, as comma
* separated values. Allowed values include 'Requests', 'Event', 'Exceptions',
* 'Metrics', 'PageViews', 'PageViewPerformance', 'Rdd', 'PerformanceCounters',
* 'Availability', 'Messages'.
* @member {string} [destinationType] The Continuous Export destination type.
* This has to be 'Blob'.
* @member {string} [destinationAddress] The SAS URL for the destination
* storage container. It must grant write permission.
* @member {string} [isEnabled] Set to 'true' to create a Continuous Export
* configuration as enabled, otherwise set it to 'false'.
* @member {string} [notificationQueueEnabled] Deprecated
* @member {string} [notificationQueueUri] Deprecated
* @member {string} [destinationStorageSubscriptionId] The subscription ID of
* the destination storage container.
* @member {string} [destinationStorageLocationId] The location ID of the
* destination storage container.
* @member {string} [destinationAccountId] The name of destination storage
* account.
*/
export interface ApplicationInsightsComponentExportRequest {
recordTypes?: string;
destinationType?: string;
destinationAddress?: string;
isEnabled?: string;
notificationQueueEnabled?: string;
notificationQueueUri?: string;
destinationStorageSubscriptionId?: string;
destinationStorageLocationId?: string;
destinationAccountId?: string;
}
/**
* @class
* Initializes a new instance of the ApplicationInsightsComponentExportConfiguration class.
* @constructor
* Properties that define a Continuous Export configuration.
*
* @member {string} [exportId] The unique ID of the export configuration inside
* an Applciation Insights component. It is auto generated when the Continuous
* Export configuration is created.
* @member {string} [instrumentationKey] The instrumentation key of the
* Application Insights component.
* @member {string} [recordTypes] This comma separated list of document types
* that will be exported. The possible values include 'Requests', 'Event',
* 'Exceptions', 'Metrics', 'PageViews', 'PageViewPerformance', 'Rdd',
* 'PerformanceCounters', 'Availability', 'Messages'.
* @member {string} [applicationName] The name of the Application Insights
* component.
* @member {string} [subscriptionId] The subscription of the Application
* Insights component.
* @member {string} [resourceGroup] The resource group of the Application
* Insights component.
* @member {string} [destinationStorageSubscriptionId] The destination storage
* account subscription ID.
* @member {string} [destinationStorageLocationId] The destination account
* location ID.
* @member {string} [destinationAccountId] The name of destination account.
* @member {string} [destinationType] The destination type.
* @member {string} [isUserEnabled] This will be 'true' if the Continuous
* Export configuration is enabled, otherwise it will be 'false'.
* @member {string} [lastUserUpdate] Last time the Continuous Export
* configuration was updated.
* @member {string} [notificationQueueEnabled] Deprecated
* @member {string} [exportStatus] This indicates current Continuous Export
* configuration status. The possible values are 'Preparing', 'Success',
* 'Failure'.
* @member {string} [lastSuccessTime] The last time data was successfully
* delivered to the destination storage container for this Continuous Export
* configuration.
* @member {string} [lastGapTime] The last time the Continuous Export
* configuration started failing.
* @member {string} [permanentErrorReason] This is the reason the Continuous
* Export configuration started failing. It can be 'AzureStorageNotFound' or
* 'AzureStorageAccessDenied'.
* @member {string} [storageName] The name of the destination storage account.
* @member {string} [containerName] The name of the destination storage
* container.
*/
export interface ApplicationInsightsComponentExportConfiguration {
readonly exportId?: string;
readonly instrumentationKey?: string;
recordTypes?: string;
readonly applicationName?: string;
readonly subscriptionId?: string;
readonly resourceGroup?: string;
readonly destinationStorageSubscriptionId?: string;
readonly destinationStorageLocationId?: string;
readonly destinationAccountId?: string;
readonly destinationType?: string;
readonly isUserEnabled?: string;
readonly lastUserUpdate?: string;
notificationQueueEnabled?: string;
readonly exportStatus?: string;
readonly lastSuccessTime?: string;
readonly lastGapTime?: string;
readonly permanentErrorReason?: string;
readonly storageName?: string;
readonly containerName?: string;
}
/**
* @class
* Initializes a new instance of the ApplicationInsightsComponentDataVolumeCap class.
* @constructor
* An Application Insights component daily data volumne cap
*
* @member {number} [cap] Daily data volume cap in GB.
* @member {number} [resetTime] Daily data volume cap UTC reset hour.
* @member {number} [warningThreshold] Reserved, not used for now.
* @member {boolean} [stopSendNotificationWhenHitThreshold] Reserved, not used
* for now.
* @member {boolean} [stopSendNotificationWhenHitCap] Do not send a
* notification email when the daily data volume cap is met.
* @member {number} [maxHistoryCap] Maximum daily data volume cap that the user
* can set for this component.
*/
export interface ApplicationInsightsComponentDataVolumeCap {
cap?: number;
readonly resetTime?: number;
warningThreshold?: number;
stopSendNotificationWhenHitThreshold?: boolean;
stopSendNotificationWhenHitCap?: boolean;
readonly maxHistoryCap?: number;
}
/**
* @class
* Initializes a new instance of the ApplicationInsightsComponentBillingFeatures class.
* @constructor
* An Application Insights component billing features
*
* @member {object} [dataVolumeCap] An Application Insights component daily
* data volumne cap
* @member {number} [dataVolumeCap.cap] Daily data volume cap in GB.
* @member {number} [dataVolumeCap.resetTime] Daily data volume cap UTC reset
* hour.
* @member {number} [dataVolumeCap.warningThreshold] Reserved, not used for
* now.
* @member {boolean} [dataVolumeCap.stopSendNotificationWhenHitThreshold]
* Reserved, not used for now.
* @member {boolean} [dataVolumeCap.stopSendNotificationWhenHitCap] Do not send
* a notification email when the daily data volume cap is met.
* @member {number} [dataVolumeCap.maxHistoryCap] Maximum daily data volume cap
* that the user can set for this component.
* @member {array} [currentBillingFeatures] Current enabled pricing plan. When
* the component is in the Enterprise plan, this will list both 'Basic' and
* 'Application Insights Enterprise'.
*/
export interface ApplicationInsightsComponentBillingFeatures {
dataVolumeCap?: ApplicationInsightsComponentDataVolumeCap;
currentBillingFeatures?: string[];
}
/**
* @class
* Initializes a new instance of the ApplicationInsightsComponentQuotaStatus class.
* @constructor
* An Application Insights component daily data volume cap status
*
* @member {string} [appId] The Application ID for the Application Insights
* component.
* @member {boolean} [shouldBeThrottled] The daily data volume cap is met, and
* data ingestion will be stopped.
* @member {string} [expirationTime] Date and time when the daily data volume
* cap will be reset, and data ingestion will resume.
*/
export interface ApplicationInsightsComponentQuotaStatus {
readonly appId?: string;
readonly shouldBeThrottled?: boolean;
readonly expirationTime?: string;
}
/**
* @class
* Initializes a new instance of the ApplicationInsightsComponentFeatureCapabilities class.
* @constructor
* An Application Insights component feature capabilities
*
* @member {boolean} [supportExportData] Whether allow to use continuous export
* feature.
* @member {string} [burstThrottlePolicy] Reserved, not used now.
* @member {string} [metadataClass] Reserved, not used now.
* @member {boolean} [liveStreamMetrics] Reserved, not used now.
* @member {boolean} [applicationMap] Reserved, not used now.
* @member {boolean} [workItemIntegration] Whether allow to use work item
* integration feature.
* @member {boolean} [powerBIIntegration] Reserved, not used now.
* @member {boolean} [openSchema] Reserved, not used now.
* @member {boolean} [proactiveDetection] Reserved, not used now.
* @member {boolean} [analyticsIntegration] Reserved, not used now.
* @member {boolean} [multipleStepWebTest] Whether allow to use multiple steps
* web test feature.
* @member {string} [apiAccessLevel] Reserved, not used now.
* @member {string} [trackingType] The applciation insights component used
* tracking type.
* @member {number} [dailyCap] Daily data volume cap in GB.
* @member {number} [dailyCapResetTime] Daily data volume cap UTC reset hour.
* @member {number} [throttleRate] Reserved, not used now.
*/
export interface ApplicationInsightsComponentFeatureCapabilities {
readonly supportExportData?: boolean;
readonly burstThrottlePolicy?: string;
readonly metadataClass?: string;
readonly liveStreamMetrics?: boolean;
readonly applicationMap?: boolean;
readonly workItemIntegration?: boolean;
readonly powerBIIntegration?: boolean;
readonly openSchema?: boolean;
readonly proactiveDetection?: boolean;
readonly analyticsIntegration?: boolean;
readonly multipleStepWebTest?: boolean;
readonly apiAccessLevel?: string;
readonly trackingType?: string;
readonly dailyCap?: number;
readonly dailyCapResetTime?: number;
readonly throttleRate?: number;
}
/**
* @class
* Initializes a new instance of the ApplicationInsightsComponentFeatureCapability class.
* @constructor
* An Application Insights component feature capability
*
* @member {string} [name] The name of the capability.
* @member {string} [description] The description of the capability.
* @member {string} [value] The vaule of the capability.
* @member {string} [unit] The unit of the capability.
* @member {string} [meterId] The meter used for the capability.
* @member {string} [meterRateFrequency] The meter rate of the meter.
*/
export interface ApplicationInsightsComponentFeatureCapability {
readonly name?: string;
readonly description?: string;
readonly value?: string;
readonly unit?: string;
readonly meterId?: string;
readonly meterRateFrequency?: string;
}
/**
* @class
* Initializes a new instance of the ApplicationInsightsComponentFeature class.
* @constructor
* An Application Insights component daily data volume cap status
*
* @member {string} [featureName] The pricing feature name.
* @member {string} [meterId] The meter id used for the feature.
* @member {string} [meterRateFrequency] The meter meter rate for the feature's
* meter.
* @member {string} [resouceId] Reserved, not used now.
* @member {boolean} [isHidden] Reserved, not used now.
* @member {array} [capabilities] A list of Application Insigths component
* feature capability.
* @member {string} [title] Desplay name of the feature.
* @member {boolean} [isMainFeature] Whether can apply addon feature on to it.
* @member {string} [supportedAddonFeatures] The add on features on main
* feature.
*/
export interface ApplicationInsightsComponentFeature {
readonly featureName?: string;
readonly meterId?: string;
readonly meterRateFrequency?: string;
readonly resouceId?: string;
readonly isHidden?: boolean;
readonly capabilities?: ApplicationInsightsComponentFeatureCapability[];
readonly title?: string;
readonly isMainFeature?: boolean;
readonly supportedAddonFeatures?: string;
}
/**
* @class
* Initializes a new instance of the ApplicationInsightsComponentAvailableFeatures class.
* @constructor
* An Application Insights component available features.
*
* @member {array} [result] A list of Application Insigths component feature.
*/
export interface ApplicationInsightsComponentAvailableFeatures {
readonly result?: ApplicationInsightsComponentFeature[];
}
/**
* @class
* Initializes a new instance of the ApplicationInsightsComponentProactiveDetectionConfigurationRuleDefinitions class.
* @constructor
* Static definitions of the ProactiveDetection configuration rule (same values
* for all components).
*
* @member {string} [name] The rule name
* @member {string} [displayName] The rule name as it is displayed in UI
* @member {string} [description] The rule description
* @member {string} [helpUrl] URL which displays aditional info about the
* proactive detection rule
* @member {boolean} [isHidden] A flag indicating whether the rule is hidden
* (from the UI)
* @member {boolean} [isEnabledByDefault] A flag indicating whether the rule is
* enabled by default
* @member {boolean} [isInPreview] A flag indicating whether the rule is in
* preview
* @member {boolean} [supportsEmailNotifications] A flag indicating whether
* email notifications are supported for detections for this rule
*/
export interface ApplicationInsightsComponentProactiveDetectionConfigurationRuleDefinitions {
name?: string;
displayName?: string;
description?: string;
helpUrl?: string;
isHidden?: boolean;
isEnabledByDefault?: boolean;
isInPreview?: boolean;
supportsEmailNotifications?: boolean;
}
/**
* @class
* Initializes a new instance of the ApplicationInsightsComponentProactiveDetectionConfiguration class.
* @constructor
* Properties that define a ProactiveDetection configuration.
*
* @member {string} [name] The rule name
* @member {boolean} [enabled] A flag that indicates whether this rule is
* enabled by the user
* @member {boolean} [sendEmailsToSubscriptionOwners] A flag that indicated
* whether notifications on this rule should be sent to subscription owners
* @member {array} [customEmails] Custom email addresses for this rule
* notifications
* @member {string} [lastUpdatedTime] The last time this rule was updated
* @member {object} [ruleDefinitions] Static definitions of the
* ProactiveDetection configuration rule (same values for all components).
* @member {string} [ruleDefinitions.name] The rule name
* @member {string} [ruleDefinitions.displayName] The rule name as it is
* displayed in UI
* @member {string} [ruleDefinitions.description] The rule description
* @member {string} [ruleDefinitions.helpUrl] URL which displays aditional info
* about the proactive detection rule
* @member {boolean} [ruleDefinitions.isHidden] A flag indicating whether the
* rule is hidden (from the UI)
* @member {boolean} [ruleDefinitions.isEnabledByDefault] A flag indicating
* whether the rule is enabled by default
* @member {boolean} [ruleDefinitions.isInPreview] A flag indicating whether
* the rule is in preview
* @member {boolean} [ruleDefinitions.supportsEmailNotifications] A flag
* indicating whether email notifications are supported for detections for this
* rule
*/
export interface ApplicationInsightsComponentProactiveDetectionConfiguration extends BaseResource {
name?: string;
enabled?: boolean;
sendEmailsToSubscriptionOwners?: boolean;
customEmails?: string[];
lastUpdatedTime?: string;
ruleDefinitions?: ApplicationInsightsComponentProactiveDetectionConfigurationRuleDefinitions;
}
/**
* @class
* Initializes a new instance of the ComponentsResource class.
* @constructor
* An azure resource object
*
* @member {string} [id] Azure resource Id
* @member {string} [name] Azure resource name
* @member {string} [type] Azure resource type
* @member {string} location Resource location
* @member {object} [tags] Resource tags
*/
export interface ComponentsResource extends BaseResource {
readonly id?: string;
readonly name?: string;
readonly type?: string;
location: string;
tags?: { [propertyName: string]: string };
}
/**
* @class
* Initializes a new instance of the TagsResource class.
* @constructor
* A container holding only the Tags for a resource, allowing the user to
* update the tags on a WebTest instance.
*
* @member {object} [tags] Resource tags
*/
export interface TagsResource {
tags?: { [propertyName: string]: string };
}
/**
* @class
* Initializes a new instance of the ApplicationInsightsComponent class.
* @constructor
* An Application Insights component definition.
*
* @member {string} kind The kind of application that this component refers to,
* used to customize UI. This value is a freeform string, values should
* typically be one of the following: web, ios, other, store, java, phone.
* @member {string} [applicationId] The unique ID of your application. This
* field mirrors the 'Name' field and cannot be changed.
* @member {string} [appId] Application Insights Unique ID for your
* Application.
* @member {string} applicationType Type of application being monitored.
* Possible values include: 'web', 'other'. Default value: 'web' .
* @member {string} [flowType] Used by the Application Insights system to
* determine what kind of flow this component was created by. This is to be set
* to 'Bluefield' when creating/updating a component via the REST API. Possible
* values include: 'Bluefield'. Default value: 'Bluefield' .
* @member {string} [requestSource] Describes what tool created this
* Application Insights component. Customers using this API should set this to
* the default 'rest'. Possible values include: 'rest'. Default value: 'rest' .
* @member {string} [instrumentationKey] Application Insights Instrumentation
* key. A read-only value that applications can use to identify the destination
* for all telemetry sent to Azure Application Insights. This value will be
* supplied upon construction of each new Application Insights component.
* @member {date} [creationDate] Creation Date for the Application Insights
* component, in ISO 8601 format.
* @member {string} [tenantId] Azure Tenant Id.
* @member {string} [hockeyAppId] The unique application ID created when a new
* application is added to HockeyApp, used for communications with HockeyApp.
* @member {string} [hockeyAppToken] Token used to authenticate communications
* with between Application Insights and HockeyApp.
* @member {string} [provisioningState] Current state of this component:
* whether or not is has been provisioned within the resource group it is
* defined. Users cannot change this value but are able to read from it. Values
* will include Succeeded, Deploying, Canceled, and Failed.
* @member {number} [samplingPercentage] Percentage of the data produced by the
* application being monitored that is being sampled for Application Insights
* telemetry.
*/
export interface ApplicationInsightsComponent extends ComponentsResource {
kind: string;
readonly applicationId?: string;
readonly appId?: string;
applicationType: string;
flowType?: string;
requestSource?: string;
readonly instrumentationKey?: string;
readonly creationDate?: Date;
readonly tenantId?: string;
hockeyAppId?: string;
readonly hockeyAppToken?: string;
readonly provisioningState?: string;
samplingPercentage?: number;
}
/**
* @class
* Initializes a new instance of the ComponentPurgeBodyFilters class.
* @constructor
* User-defined filters to return data which will be purged from the table.
*
* @member {string} [column] The column of the table over which the given query
* should run
* @member {string} [operator] A query operator to evaluate over the provided
* column and value(s).
* @member {object} [value] the value for the operator to function over. This
* can be a number (e.g., > 100), a string (timestamp >= '2017-09-01') or array
* of values.
*/
export interface ComponentPurgeBodyFilters {
column?: string;
operator?: string;
value?: any;
}
/**
* @class
* Initializes a new instance of the ComponentPurgeBody class.
* @constructor
* Describes the body of a purge request for an App Insights component
*
* @member {string} table Table from which to purge data.
* @member {array} filters The set of columns and filters (queries) to run over
* them to purge the resulting data.
*/
export interface ComponentPurgeBody {
table: string;
filters: ComponentPurgeBodyFilters[];
}
/**
* @class
* Initializes a new instance of the ComponentPurgeResponse class.
* @constructor
* Response containing operationId for a specific purge action.
*
* @member {string} operationId Id to use when querying for status for a
* particular purge operation.
*/
export interface ComponentPurgeResponse {
operationId: string;
}
/**
* @class
* Initializes a new instance of the ComponentPurgeStatusResponse class.
* @constructor
* Response containing status for a specific purge operation.
*
* @member {string} status Status of the operation represented by the requested
* Id. Possible values include: 'pending', 'completed'
*/
export interface ComponentPurgeStatusResponse {
status: string;
}
/**
* @class
* Initializes a new instance of the WorkItemConfiguration class.
* @constructor
* Work item configuration associated with an application insights resource.
*
* @member {string} [connectorId] Connector identifier where work item is
* created
* @member {string} [configDisplayName] Configuration friendly name
* @member {boolean} [isDefault] Boolean value indicating whether configuration
* is default
* @member {string} [id] Unique Id for work item
* @member {string} [configProperties] Serialized JSON object for detailed
* properties
*/
export interface WorkItemConfiguration {
connectorId?: string;
configDisplayName?: string;
isDefault?: boolean;
id?: string;
configProperties?: string;
}
/**
* @class
* Initializes a new instance of the WorkItemCreateConfiguration class.
* @constructor
* Work item configuration creation payload
*
* @member {string} [connectorId] Unique connector id
* @member {string} [connectorDataConfiguration] Serialized JSON object for
* detaile d properties
* @member {boolean} [validateOnly] Boolean indicating validate only
* @member {string} [workItemProperties] Custom work item properties
*/
export interface WorkItemCreateConfiguration {
connectorId?: string;
connectorDataConfiguration?: string;
validateOnly?: boolean;
workItemProperties?: string;
}
/**
* @class
* Initializes a new instance of the WorkItemConfigurationError class.
* @constructor
* Error associated with trying to get work item configuration or
* configurations
*
* @member {string} [code] Error detail code and explanation
* @member {string} [message] Error message
* @member {object} [innererror]
* @member {string} [innererror.diagnosticcontext] Provides correlation for
* request
* @member {date} [innererror.time] Request time
*/
export interface WorkItemConfigurationError {
code?: string;
message?: string;
innererror?: InnerError;
}
/**
* @class
* Initializes a new instance of the ApplicationInsightsComponentFavorite class.
* @constructor
* Properties that define a favorite that is associated to an Application
* Insights component.
*
* @member {string} [name] The user-defined name of the favorite.
* @member {string} [config] Configuration of this particular favorite, which
* are driven by the Azure portal UX. Configuration data is a string containing
* valid JSON
* @member {string} [version] This instance's version of the data model. This
* can change as new features are added that can be marked favorite. Current
* examples include MetricsExplorer (ME) and Search.
* @member {string} [favoriteId] Internally assigned unique id of the favorite
* definition.
* @member {string} [favoriteType] Enum indicating if this favorite definition
* is owned by a specific user or is shared between all users with access to
* the Application Insights component. Possible values include: 'shared',
* 'user'
* @member {string} [sourceType] The source of the favorite definition.
* @member {string} [timeModified] Date and time in UTC of the last
* modification that was made to this favorite definition.
* @member {array} [tags] A list of 0 or more tags that are associated with
* this favorite definition
* @member {string} [category] Favorite category, as defined by the user at
* creation time.
* @member {boolean} [isGeneratedFromTemplate] Flag denoting wether or not this
* favorite was generated from a template.
* @member {string} [userId] Unique user id of the specific user that owns this
* favorite.
*/
export interface ApplicationInsightsComponentFavorite {
name?: string;
config?: string;
version?: string;
readonly favoriteId?: string;
favoriteType?: string;
sourceType?: string;
readonly timeModified?: string;
tags?: string[];
category?: string;
isGeneratedFromTemplate?: boolean;
readonly userId?: string;
}
/**
* @class
* Initializes a new instance of the ApplicationInsightsComponentWebTestLocation class.
* @constructor
* Properties that define a web test location available to an Application
* Insights Component.
*
* @member {string} [displayName] The display name of the web test location.
* @member {string} [tag] Internally defined geographic location tag.
*/
export interface ApplicationInsightsComponentWebTestLocation {
readonly displayName?: string;
readonly tag?: string;
}
/**
* @class
* Initializes a new instance of the WebtestsResource class.
* @constructor
* An azure resource object
*
* @member {string} [id] Azure resource Id
* @member {string} [name] Azure resource name
* @member {string} [type] Azure resource type
* @member {string} location Resource location
* @member {object} [tags] Resource tags
*/
export interface WebtestsResource extends BaseResource {
readonly id?: string;
readonly name?: string;
readonly type?: string;
location: string;
tags?: { [propertyName: string]: string };
}
/**
* @class
* Initializes a new instance of the WebTestGeolocation class.
* @constructor
* Geo-physical location to run a web test from. You must specify one or more
* locations for the test to run from.
*
* @member {string} [location] Location ID for the webtest to run from.
*/
export interface WebTestGeolocation {
location?: string;
}
/**
* @class
* Initializes a new instance of the WebTestPropertiesConfiguration class.
* @constructor
* An XML configuration specification for a WebTest.
*
* @member {string} [webTest] The XML specification of a WebTest to run against
* an application.
*/
export interface WebTestPropertiesConfiguration {
webTest?: string;
}
/**
* @class
* Initializes a new instance of the WebTest class.
* @constructor
* An Application Insights web test definition.
*
* @member {string} [kind] The kind of web test that this web test watches.
* Choices are ping and multistep. Possible values include: 'ping',
* 'multistep'. Default value: 'ping' .
* @member {string} syntheticMonitorId Unique ID of this WebTest. This is
* typically the same value as the Name field.
* @member {string} webTestName User defined name if this WebTest.
* @member {string} [description] Purpose/user defined descriptive test for
* this WebTest.
* @member {boolean} [enabled] Is the test actively being monitored.
* @member {number} [frequency] Interval in seconds between test runs for this
* WebTest. Default value is 300. Default value: 300 .
* @member {number} [timeout] Seconds until this WebTest will timeout and fail.
* Default value is 30. Default value: 30 .
* @member {string} webTestKind The kind of web test this is, valid choices are
* ping and multistep. Possible values include: 'ping', 'multistep'. Default
* value: 'ping' .
* @member {boolean} [retryEnabled] Allow for retries should this WebTest fail.
* @member {array} locations A list of where to physically run the tests from
* to give global coverage for accessibility of your application.
* @member {object} [configuration] An XML configuration specification for a
* WebTest.
* @member {string} [configuration.webTest] The XML specification of a WebTest
* to run against an application.
* @member {string} [provisioningState] Current state of this component,
* whether or not is has been provisioned within the resource group it is
* defined. Users cannot change this value but are able to read from it. Values
* will include Succeeded, Deploying, Canceled, and Failed.
*/
export interface WebTest extends WebtestsResource {
kind?: string;
syntheticMonitorId: string;
webTestName: string;
description?: string;
enabled?: boolean;
frequency?: number;
timeout?: number;
webTestKind: string;
retryEnabled?: boolean;
locations: WebTestGeolocation[];
configuration?: WebTestPropertiesConfiguration;
readonly provisioningState?: string;
}
/**
* @class
* Initializes a new instance of the ApplicationInsightsComponentAnalyticsItemProperties class.
* @constructor
* A set of properties that can be defined in the context of a specific item
* type. Each type may have its own properties.
*
* @member {string} [functionAlias] A function alias, used when the type of the
* item is Function
*/
export interface ApplicationInsightsComponentAnalyticsItemProperties {
functionAlias?: string;
}
/**
* @class
* Initializes a new instance of the ApplicationInsightsComponentAnalyticsItem class.
* @constructor
* Properties that define an Analytics item that is associated to an
* Application Insights component.
*
* @member {string} [id] Internally assigned unique id of the item definition.
* @member {string} [name] The user-defined name of the item.
* @member {string} [content] The content of this item
* @member {string} [version] This instance's version of the data model. This
* can change as new features are added.
* @member {string} [scope] Enum indicating if this item definition is owned by
* a specific user or is shared between all users with access to the
* Application Insights component. Possible values include: 'shared', 'user'
* @member {string} [type] Enum indicating the type of the Analytics item.
* Possible values include: 'query', 'function', 'folder', 'recent'
* @member {string} [timeCreated] Date and time in UTC when this item was
* created.
* @member {string} [timeModified] Date and time in UTC of the last
* modification that was made to this item.
* @member {object} [properties]
* @member {string} [properties.functionAlias] A function alias, used when the
* type of the item is Function
*/
export interface ApplicationInsightsComponentAnalyticsItem {
id?: string;
name?: string;
content?: string;
readonly version?: string;
scope?: string;
type?: string;
readonly timeCreated?: string;
readonly timeModified?: string;
properties?: ApplicationInsightsComponentAnalyticsItemProperties;
}
/**
* @class
* Initializes a new instance of the WorkbookResource class.
* @constructor
* An azure resource object
*
* @member {string} [id] Azure resource Id
* @member {string} [name] Azure resource name
* @member {string} [type] Azure resource type
* @member {string} [location] Resource location
* @member {object} [tags] Resource tags
*/
export interface WorkbookResource extends BaseResource {
readonly id?: string;
readonly name?: string;
readonly type?: string;
location?: string;
tags?: { [propertyName: string]: string };
}
/**
* @class
* Initializes a new instance of the Workbook class.
* @constructor
* An Application Insights workbook definition.
*
* @member {string} [kind] The kind of workbook. Choices are user and shared.
* Possible values include: 'user', 'shared'
* @member {string} workbookName The user-defined name of the workbook.
* @member {string} serializedData Configuration of this particular workbook.
* Configuration data is a string containing valid JSON
* @member {string} [version] This instance's version of the data model. This
* can change as new features are added that can be marked workbook.
* @member {string} workbookId Internally assigned unique id of the workbook
* definition.
* @member {string} sharedTypeKind Enum indicating if this workbook definition
* is owned by a specific user or is shared between all users with access to
* the Application Insights component. Possible values include: 'user',
* 'shared'. Default value: 'shared' .
* @member {string} [timeModified] Date and time in UTC of the last
* modification that was made to this workbook definition.
* @member {string} category Workbook category, as defined by the user at
* creation time.
* @member {array} [workbookTags] A list of 0 or more tags that are associated
* with this workbook definition
* @member {string} userId Unique user id of the specific user that owns this
* workbook.
* @member {string} [sourceResourceId] Optional resourceId for a source
* resource.
*/
export interface Workbook extends WorkbookResource {
kind?: string;
workbookName: string;
serializedData: string;
version?: string;
workbookId: string;
sharedTypeKind: string;
readonly timeModified?: string;
category: string;
workbookTags?: string[];
userId: string;
sourceResourceId?: string;
}
/**
* @class
* Initializes a new instance of the LinkProperties class.
* @constructor
* Contains a sourceId and workbook resource id to link two resources.
*
* @member {string} [sourceId] The source Azure resource id
* @member {string} [targetId] The workbook Azure resource id
* @member {string} [category] The category of workbook
*/
export interface LinkProperties {
sourceId?: string;
targetId?: string;
category?: string;
}
/**
* @class
* Initializes a new instance of the ErrorFieldContract class.
* @constructor
* Error Field contract.
*
* @member {string} [code] Property level error code.
* @member {string} [message] Human-readable representation of property-level
* error.
* @member {string} [target] Property name.
*/
export interface ErrorFieldContract {
code?: string;
message?: string;
target?: string;
}
/**
* @class
* Initializes a new instance of the WorkbookError class.
* @constructor
* Error message body that will indicate why the operation failed.
*
* @member {string} [code] Service-defined error code. This code serves as a
* sub-status for the HTTP error code specified in the response.
* @member {string} [message] Human-readable representation of the error.
* @member {array} [details] The list of invalid fields send in request, in
* case of validation error.
*/
export interface WorkbookError {
code?: string;
message?: string;
details?: ErrorFieldContract[];
}
/**
* @class
* Initializes a new instance of the OperationListResult class.
* @constructor
* Result of the request to list CDN operations. It contains a list of
* operations and a URL link to get the next set of results.
*
* @member {string} [nextLink] URL to get the next set of operation list
* results if there are any.
*/
export interface OperationListResult extends Array<Operation> {
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the AnnotationsListResult class.
* @constructor
* Annotations list result.
*
*/
export interface AnnotationsListResult extends Array<Annotation> {
}
/**
* @class
* Initializes a new instance of the ApplicationInsightsComponentAPIKeyListResult class.
* @constructor
* Describes the list of API Keys of an Application Insights Component.
*
*/
export interface ApplicationInsightsComponentAPIKeyListResult extends Array<ApplicationInsightsComponentAPIKey> {
}
/**
* @class
* Initializes a new instance of the ApplicationInsightsComponentListResult class.
* @constructor
* Describes the list of Application Insights Resources.
*
* @member {string} [nextLink] The URI to get the next set of Application
* Insights component defintions if too many components where returned in the
* result set.
*/
export interface ApplicationInsightsComponentListResult extends Array<ApplicationInsightsComponent> {
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the WorkItemConfigurationsListResult class.
* @constructor
* Work item configuration list result.
*
*/
export interface WorkItemConfigurationsListResult extends Array<WorkItemConfiguration> {
}
/**
* @class
* Initializes a new instance of the ApplicationInsightsWebTestLocationsListResult class.
* @constructor
* Describes the list of web test locations available to an Application
* Insights Component.
*
*/
export interface ApplicationInsightsWebTestLocationsListResult extends Array<ApplicationInsightsComponentWebTestLocation> {
}
/**
* @class
* Initializes a new instance of the WebTestListResult class.
* @constructor
* A list of 0 or more Application Insights web test definitions.
*
* @member {string} [nextLink] The link to get the next part of the returned
* list of web tests, should the return set be too large for a single request.
* May be null.
*/
export interface WebTestListResult extends Array<WebTest> {
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the WorkbooksListResult class.
* @constructor
* Workbook list result.
*
*/
export interface WorkbooksListResult extends Array<Workbook> {
} | the_stack |
import { Encoding, EncodingType } from '../src/encoding';
/**
* Encoding spec modules
*/
describe('Creating instance of Encoding', () => {
it('Encoding instance with null parameter', () => {
let encoding: Encoding = new Encoding(null);
expect(encoding.includeBom).toBe(true);
});
it('Encoding instance with true parameter', () => {
let encoding: Encoding = new Encoding(true);
expect(encoding.includeBom).toBe(true);
expect(encoding.type).toBe('Ansi');
});
it('Encoding instance with false parameter', () => {
let encoding: Encoding = new Encoding(false);
expect(encoding.includeBom).toBe(false);
expect(encoding.type).toBe('Ansi');
});
it('Encoding instance with empty parameter', () => {
let encoding: Encoding = new Encoding();
expect(encoding.includeBom).toBe(true);
expect(encoding.type).toBe('Ansi');
});
});
/**
* Validating getBytes method in Ansi Encoding
* method: getBytes(s:string,index:number,count:number)
* return Array<number>
*/
describe('Validating getBytes method in Ansi encoding', () => {
let encoding: Encoding;
beforeEach((): void => {
encoding = new Encoding(true);
encoding.type = 'Ansi';
});
afterEach((): void => {
encoding.destroy();
encoding = undefined;
});
it('string as null parameter,index and count as null', () => {
expect((): void => { encoding.getBytes(null, null, null); }).toThrow(new Error('ArgumentException: string cannot be null or undefined'));
});
it('string as null parameter', () => {
expect((): void => { encoding.getBytes(null, 0, 1); }).toThrow(new Error('ArgumentException: string cannot be null or undefined'));
});
it('valid string,index and count as Null', () => {
expect((): void => { encoding.getBytes('Stream', null, null); }).toThrow(new Error('ArgumentException: charIndex cannot be null or undefined'));
});
it('valid string,index as Null and count as valid value', () => {
expect((): void => { encoding.getBytes('Stream', null, 1); }).toThrow(new Error('ArgumentException: charIndex cannot be null or undefined'));
});
it('valid string,count as null and index as valid value', () => {
expect((): void => { encoding.getBytes('Stream', 0, null); }).toThrow(new Error('ArgumentException: charCount cannot be null or undefined'));
});
it('string as undefined parameter', () => {
expect((): void => { encoding.getBytes(undefined, undefined, undefined); }).toThrow(new Error('ArgumentException: string cannot be null or undefined'));
});
it('string as valid value,index and count as undefined', () => {
expect((): void => { encoding.getBytes('Stream', undefined, undefined); }).toThrow(new Error('ArgumentException: charIndex cannot be null or undefined'));
});
it('string , index and count as undefined parameter', () => {
expect((): void => { encoding.getBytes(undefined, 0, 1); }).toThrow(new Error('ArgumentException: string cannot be null or undefined'));
});
it('valid string,index and count as negative value', () => {
let s: string = 'StreamWriter';
expect((): void => { encoding.getBytes(s, -1, -1); }).toThrow(new RangeError('Argument Out Of Range Exception: charIndex or charCount is less than zero'));
});
it('valid string,index as negative value and count as 0', () => {
let s: string = 'StreamWriter';
expect((): void => { encoding.getBytes(s, -1, 0); }).toThrow(new RangeError('Argument Out Of Range Exception: charIndex or charCount is less than zero'));
});
it('valid string,index as 0 and count as negative value', () => {
let s: string = 'StreamWriter';
expect((): void => { encoding.getBytes(s, 0, -1); }).toThrow(new RangeError('Argument Out Of Range Exception: charIndex or charCount is less than zero'));
});
it('valid string,index and count as 0', () => {
let s: string = 'a';
let getBytes: ArrayBuffer = encoding.getBytes(s, 0, 0);
expect(getBytes.byteLength).toBe(0);
})
it('valid string with index and count as valid values', () => {
let s: string = 'a';
let getBytes: ArrayBuffer = encoding.getBytes(s, 0, 1);
let byte: Uint8Array = new Uint8Array(getBytes);
expect(byte[0]).toBe(97);
});
it('empty string with valid index and count as invalid', () => {
let s: string = '';
expect((): void => { encoding.getBytes(s, 0, 2) }).toThrow(new RangeError('Argument Out Of Range Exception: charIndex and charCount do not denote a valid range in string'));
});
it('Count value greater than string length', () => {
let s: string = 'Stream';
expect((): void => { encoding.getBytes(s, 5, 7) }).toThrow(new RangeError('Argument Out Of Range Exception: charIndex and charCount do not denote a valid range in string'));
});
it('string with unicode character', () => {
let s: string = '¥';
let getBytes: ArrayBuffer = encoding.getBytes(s, 0, 1);
expect(getBytes.byteLength === 1).toEqual(true);
});
it('string with ASCII text', () => {
let s: string = 'example';
let getBytes: ArrayBuffer = encoding.getBytes(s, 0, s.length);
expect(getBytes.byteLength === 7).toEqual(true);
});
it('string with ASCII and unicode text', () => {
let s: string = 'example ¥';
let getBytes: ArrayBuffer = encoding.getBytes(s, 0, s.length);
expect(getBytes.byteLength === 9).toEqual(true);
});
it('string with valid string, index and count as valid values', () => {
let s: string = 'example';
let getBytes: ArrayBuffer = encoding.getBytes(s, 1, 3);
expect(getBytes.byteLength === 3).toEqual(true);
});
it('string with chinese character, index and count as valid value', () => {
let s: string = '汉字';
let getBytes: ArrayBuffer = encoding.getBytes(s, 0, 2);
let byte: Uint8Array = new Uint8Array(getBytes);
expect(byte[0]).toBe(63);
expect(byte[1]).toBe(63);
});
it('EncodingType with null in getBytes method', () => {
let encoding: Encoding = new Encoding(true);
encoding.type = undefined;
let getBytes: ArrayBuffer = encoding.getBytes('a', 0, 1);
});
});
/**
* Validating getBytes method in UTF-8 encoding
* method: getBytes(s:string,index:number,count:number)
* return ArrayBuffer
*/
describe('Validating getBytes method in UTF-8 encoding', () => {
let encoding: Encoding;
beforeEach((): void => {
encoding = new Encoding(true);
encoding.type = 'Utf8';
});
afterEach((): void => {
encoding.destroy();
encoding = undefined;
});
it('string , index and count as null parameter', () => {
expect((): void => { encoding.getBytes(null, null, null); }).toThrow(new Error('ArgumentException: string cannot be null or undefined'));
});
it('string as null parameter, index and count as valid values', () => {
expect((): void => { encoding.getBytes(null, 0, 1); }).toThrow(new Error('ArgumentException: string cannot be null or undefined'));
});
it('string as valid value,index and count as Null', () => {
expect((): void => { encoding.getBytes('Stream', null, null); }).toThrow(new Error('ArgumentException: charIndex cannot be null or undefined'));
});
it('string and count as valid value, index as null', () => {
expect((): void => { encoding.getBytes('Stream', null, 1); }).toThrow(new Error('ArgumentException: charIndex cannot be null or undefined'));
});
it('string and index as valid value, count as null', () => {
expect((): void => { encoding.getBytes('Stream', 0, null); }).toThrow(new Error('ArgumentException: charCount cannot be null or undefined'));
});
it('string as undefined parameter', () => {
expect((): void => { encoding.getBytes(undefined, undefined, undefined); }).toThrow(new Error('ArgumentException: string cannot be null or undefined'));
});
it('string as valid value,index and count as undefined', () => {
expect((): void => { encoding.getBytes('Stream', undefined, undefined); }).toThrow(new Error('ArgumentException: charIndex cannot be null or undefined'));
});
it('string , index and count as undefined parameter', () => {
expect((): void => { encoding.getBytes(undefined, 0, 1); }).toThrow(new Error('ArgumentException: string cannot be null or undefined'));
});
it('string as valid value,index and count as negative value', () => {
let s: string = 'StreamWriter';
expect((): void => { encoding.getBytes(s, -1, -1); }).toThrow(new RangeError('Argument Out Of Range Exception: charIndex or charCount is less than zero'));
});
it('string as valid value,index as negative value and count as 0', () => {
let s: string = 'StreamWriter';
expect((): void => { encoding.getBytes(s, -1, 0); }).toThrow(new RangeError('Argument Out Of Range Exception: charIndex or charCount is less than zero'));
});
it('string as valid value,index as 0 and count as negative value', () => {
let s: string = 'StreamWriter';
expect((): void => { encoding.getBytes(s, 0, -1); }).toThrow(new RangeError('Argument Out Of Range Exception: charIndex or charCount is less than zero'));
});
it('string as valid value,index and count as 0', () => {
let s: string = 'a';
let getBytes: ArrayBuffer = encoding.getBytes(s, 0, 1);
expect(getBytes.byteLength).toBe(1);
})
it('valid string with index and count as valid values', () => {
let s: string = 'a';
let getBytes: ArrayBuffer = encoding.getBytes(s, 0, 1);
let byte: Uint8Array = new Uint8Array(getBytes);
expect(byte[0]).toBe(97);
});
it('empty string with valid index and count as invalid', () => {
let s: string = '';
expect((): void => { encoding.getBytes(s, 0, 2) }).toThrow(new RangeError('Argument Out Of Range Exception: charIndex and charCount do not denote a valid range in string'));
});
it('Count value greater than string length', () => {
let s: string = 'Hello';
expect((): void => { encoding.getBytes(s, 5, 6) }).toThrow(new RangeError('Argument Out Of Range Exception: charIndex and charCount do not denote a valid range in string'));
});
it('string with unicode character', () => {
let s: string = '¥';
let getBytes: ArrayBuffer = encoding.getBytes(s, 0, 1);
expect(getBytes.byteLength === 2).toEqual(true);
});
it('string with as ASCII text', () => {
let s: string = 'example';
let getBytes: ArrayBuffer = encoding.getBytes(s, 0, 2);
expect(getBytes.byteLength === 2).toEqual(true);
});
it('string as valid and positive index value and count', () => {
let s: string = 'example';
encoding = new Encoding(false);
let getBytes: ArrayBuffer = encoding.getBytes(s, 1, 5);
expect(getBytes.byteLength === 5).toEqual(true);
let text: string = encoding.getString(getBytes, 0, 4);
expect(text).toBe('xamp');
});
it('string with chinese character, index and count as valid value', () => {
let s: string = '汉字';
let getBytes: ArrayBuffer = encoding.getBytes(s, 0, s.length);
expect(getBytes.byteLength).toBe(6);
});
it('string with chinese character, index and count as valid value', () => {
let s: string = '𐍈';
let getBytes: ArrayBuffer = encoding.getBytes(s, 0, 2);
expect(getBytes.byteLength).toBe(4);
});
});
/**
* Validating getBytes method in Unicode encoding
* method: getBytes(s:string,index:number,count:number)
* return ArrayBuffer
*/
describe('Validating getBytes method in Unicode encoding', () => {
let encoding: Encoding;
beforeEach((): void => {
encoding = new Encoding(true);
encoding.type = 'Unicode';
});
afterEach((): void => {
encoding.destroy();
encoding = undefined;
});
it('string , index and count as null parameter', () => {
expect((): void => { encoding.getBytes(null, null, null); }).toThrow(new Error('ArgumentException: string cannot be null or undefined'));
});
it('string as null parameter, index and count as valid values', () => {
expect((): void => { encoding.getBytes(null, 0, 1); }).toThrow(new Error('ArgumentException: string cannot be null or undefined'));
});
it('string as valid value,index and count as Null', () => {
expect((): void => { encoding.getBytes('Stream', null, null); }).toThrow(new Error('ArgumentException: charIndex cannot be null or undefined'));
});
it('string and count as valid value, index as null', () => {
expect((): void => { encoding.getBytes('Stream', null, 1); }).toThrow(new Error('ArgumentException: charIndex cannot be null or undefined'));
});
it('string and index as valid value, count as null', () => {
expect((): void => { encoding.getBytes('Stream', 0, null); }).toThrow(new Error('ArgumentException: charCount cannot be null or undefined'));
});
it('string as undefined parameter', () => {
expect((): void => { encoding.getBytes(undefined, undefined, undefined); }).toThrow(new Error('ArgumentException: string cannot be null or undefined'));
});
it('string as valid value,index and count as undefined', () => {
expect((): void => { encoding.getBytes('Stream', undefined, undefined); }).toThrow(new Error('ArgumentException: charIndex cannot be null or undefined'));
});
it('string , index and count as undefined parameter', () => {
expect((): void => { encoding.getBytes(undefined, 0, 1); }).toThrow(new Error('ArgumentException: string cannot be null or undefined'));
});
it('string as valid value,index and count as negative value', () => {
let s: string = 'StreamWriter';
expect((): void => { encoding.getBytes(s, -1, -1); }).toThrow(new RangeError('Argument Out Of Range Exception: charIndex or charCount is less than zero'));
});
it('string as valid value,index as negative value and count as 0', () => {
let s: string = 'StreamWriter';
expect((): void => { encoding.getBytes(s, -1, 0); }).toThrow(new RangeError('Argument Out Of Range Exception: charIndex or charCount is less than zero'));
});
it('string as valid value,index as 0 and count as negative value', () => {
let s: string = 'StreamWriter';
expect((): void => { encoding.getBytes(s, 0, -1); }).toThrow(new RangeError('Argument Out Of Range Exception: charIndex or charCount is less than zero'));
});
it('string as valid value,index and count as 0', () => {
let s: string = 'a';
let getBytes: ArrayBuffer = encoding.getBytes(s, 0, 1);
expect(getBytes.byteLength).toBe(2);
})
it('valid string with index and count as valid values', () => {
let s: string = 'a';
let getBytes: ArrayBuffer = encoding.getBytes(s, 0, 1);
let byte: Uint8Array = new Uint8Array(getBytes);
expect(byte[0]).toBe(97);
});
it('empty string with valid index and count as invalid', () => {
let s: string = '';
expect((): void => { encoding.getBytes(s, 0, 2) }).toThrow(new RangeError('Argument Out Of Range Exception: charIndex and charCount do not denote a valid range in string'));
});
it('Count value greater than string length', () => {
let s: string = 'Hello';
expect((): void => { encoding.getBytes(s, 5, 6) }).toThrow(new RangeError('Argument Out Of Range Exception: charIndex and charCount do not denote a valid range in string'));
});
it('string with unicode character', () => {
let s: string = '¥';
let getBytes: ArrayBuffer = encoding.getBytes(s, 0, 1);
expect(getBytes.byteLength === 2).toEqual(true);
});
it('string with as ASCII text', () => {
let s: string = 'example';
let getBytes: ArrayBuffer = encoding.getBytes(s, 0, 2);
expect(getBytes.byteLength === 4).toEqual(true);
});
it('string as valid and positive index value and count', () => {
let s: string = 'example';
encoding = new Encoding(false);
encoding.type = 'Unicode';
let getBytes: ArrayBuffer = encoding.getBytes(s, 1, 5);
expect(getBytes.byteLength === 10).toEqual(true);
let text: string = encoding.getString(getBytes, 0, 5);
expect(text).toBe('examp');
});
it('string with chinese character, index and count as valid value', () => {
let s: string = '汉字';
let getBytes: ArrayBuffer = encoding.getBytes(s, 0, 2);
expect(getBytes.byteLength).toBe(4);
});
it('string with chinese character, index and count as valid value', () => {
let s: string = '𐍈';
let getBytes: ArrayBuffer = encoding.getBytes(s, 0, 2);
expect(getBytes.byteLength).toBe(4);
});
});
/**
* Validating getString method in Ansi Encoding
* method: getString(bytes:ArrayBuffer,index:number,count:number)
* return string type
*/
describe('Validating getstring method in Ansi Encoding', () => {
let encoding: Encoding;
beforeEach((): void => {
encoding = new Encoding(true);
encoding.type = 'Ansi';
let getBytes = new ArrayBuffer(3);
});
afterEach((): void => {
encoding.destroy();
encoding = undefined;
});
it('bytes,index,count as null parameter', () => {
expect((): void => { encoding.getString(null, null, null); }).toThrow(new Error('ArgumentException: bytes cannot be null or undefined'));
});
it('bytes as null,index and count as 0', () => {
expect((): void => { encoding.getString(null, 0, 0); }).toThrow(new Error('ArgumentException: bytes cannot be null or undefined'));
});
it('valid bytes,index and count as null parameter', () => {
let getBytes: ArrayBuffer = new ArrayBuffer(1);
let bytes: Uint8Array = new Uint8Array(getBytes);
bytes[0] = 97;
expect((): void => { encoding.getString(getBytes, null, null); }).toThrow(new Error('ArgumentException: index cannot be null or undefined'));
});
it('valid bytes and count,index as null parameter', () => {
let getBytes: ArrayBuffer = new ArrayBuffer(1);
let bytes: Uint8Array = new Uint8Array(getBytes);
bytes[0] = 97;
expect((): void => { encoding.getString(getBytes, null, 1); }).toThrow(new Error('ArgumentException: index cannot be null or undefined'));
});
it('valid bytes and index,count as null parameter', () => {
let getBytes: ArrayBuffer = new ArrayBuffer(1);
let bytes: Uint8Array = new Uint8Array(getBytes);
bytes[0] = 97;
expect((): void => { encoding.getString(getBytes, 0, null); }).toThrow(new Error('ArgumentException: count cannot be null or undefined'));
});
it('bytes,index,count as undefined parameter', () => {
expect((): void => { encoding.getString(undefined, undefined, undefined); }).toThrow(new Error('ArgumentException: bytes cannot be null or undefined'));
});
it('bytes as undefined,index and count as 0', () => {
expect((): void => { encoding.getString(undefined, 0, 0); }).toThrow(new Error('ArgumentException: bytes cannot be null or undefined'));
});
it('valid bytes,index and count as undefined parameter', () => {
let getBytes: ArrayBuffer = new ArrayBuffer(1);
let bytes: Uint8Array = new Uint8Array(getBytes);
bytes[0] = 97;
expect((): void => { encoding.getString(getBytes, undefined, undefined); }).toThrow(new Error('ArgumentException: index cannot be null or undefined'));
});
it('valid bytes and count,index as undefined parameter', () => {
let getBytes: ArrayBuffer = new ArrayBuffer(1);
let bytes: Uint8Array = new Uint8Array(getBytes);
bytes[0] = 97;
expect((): void => { encoding.getString(getBytes, undefined, 1); }).toThrow(new Error('ArgumentException: index cannot be null or undefined'));
});
it('valid bytes and index,count as undefined parameter', () => {
let getBytes: ArrayBuffer = new ArrayBuffer(1);
let bytes: Uint8Array = new Uint8Array(getBytes);
bytes[0] = 97;
expect((): void => { encoding.getString(getBytes, 0, undefined); }).toThrow(new Error('ArgumentException: count cannot be null or undefined'));
});
it('valid bytes,index and count as negative value', () => {
let getBytes: ArrayBuffer = new ArrayBuffer(1);
let bytes: Uint8Array = new Uint8Array(getBytes);
bytes[0] = 97;
expect((): void => { encoding.getString(getBytes, -1, -1); }).toThrow(new RangeError('Argument Out Of Range Exception: index or count is less than zero'));
});
it('valid bytes,index as 0 and count as negative value', () => {
let getBytes: ArrayBuffer = new ArrayBuffer(1);
let bytes: Uint8Array = new Uint8Array(getBytes);
bytes[0] = 97;
expect((): void => { encoding.getString(getBytes, 0, -1); }).toThrow(new RangeError('Argument Out Of Range Exception: index or count is less than zero'));
});
it('valid bytes,index as negative value and count as 0', () => {
let getBytes: ArrayBuffer = new ArrayBuffer(1);
let bytes: Uint8Array = new Uint8Array(getBytes);
bytes[0] = 97;
expect((): void => { encoding.getString(getBytes, -1, 0); }).toThrow(new RangeError('Argument Out Of Range Exception: index or count is less than zero'));
});
it('valid bytes,index as negative value and count as valid value', () => {
let getBytes: ArrayBuffer = new ArrayBuffer(1);
let bytes: Uint8Array = new Uint8Array(getBytes);
bytes[0] = 97;
expect((): void => { encoding.getString(getBytes, -1, 0); }).toThrow(new RangeError('Argument Out Of Range Exception: index or count is less than zero'));
});
it('valid bytes, index and count as 0', () => {
let getBytes: ArrayBuffer = new ArrayBuffer(1);
let bytes: Uint8Array = new Uint8Array(getBytes);
bytes[0] = 97;
let s: string = encoding.getString(bytes, 0, 0);
expect(s === '').toEqual(true);
});
it('valid bytes,index and count as valid value', () => {
let getBytes: ArrayBuffer = new ArrayBuffer(1);
let bytes: Uint8Array = new Uint8Array(getBytes);
bytes[0] = 97;
let s: string = encoding.getString(getBytes, 0, 1);
expect(s === 'a').toEqual(true);
});
it('bytes, index and count has valid values', () => {
// let getBytes: ArrayBuffer = new ArrayBuffer(5);
let bytes: Uint8Array = new Uint8Array([72, 101, 108, 108, 111]);
let s: string = encoding.getString(bytes, 0, 5);
expect(s).toBe('Hello');
});
it('bytes with length 0,index and count as valid ', () => {
let bytes: ArrayBuffer = encoding.getBytes('', 0, 0);
expect(bytes.byteLength).toBe(0);
let s: string = encoding.getString(bytes, 0, 0);
expect(s).toBe('');
});
it('bytes, index and count as valid value', () => {
let bytes: Uint8Array = new Uint8Array([72, 101, 108, 108, 111]);
let s: string = encoding.getString(bytes, 1, 3);
expect(s).toBe('ell');
});
it('bytes and index as valid and count as invalid values', () => {
let bytes: Uint8Array = new Uint8Array([72, 101, 108, 108, 111]);
expect(bytes.length).toBe(5);
expect((): void => { encoding.getString(bytes, 1, 6) }).toThrow(new RangeError('Argument Out Of Range Exception: index and count do not denote a valid range in bytes'));
});
it('bytes and count as valid and index as invalid value', () => {
let bytes: Uint8Array = new Uint8Array([72, 101, 108, 108, 111]);
expect(bytes.length).toBe(5);
expect((): void => { encoding.getString(bytes, 6, 5) }).toThrow(new RangeError('Argument Out Of Range Exception: index and count do not denote a valid range in bytes'));
});
it('string with chinese character, index and count as valid value', () => {
let s: string = '汉字';
let getBytes: Uint8Array = new Uint8Array([216]);
let text: string = encoding.getString(getBytes, 0, 1);
expect(text === '汉字').toEqual(false);
});
it('bytes with unicode character', () => {
let s: string = '¥';
let bytes: ArrayBuffer = encoding.getBytes(s, 0, 1);
let text: string = encoding.getString(bytes, 0, bytes.byteLength);
expect(text === '¥').toEqual(true);
});
it('EncodingType with null in getString method', () => {
let encoding: Encoding = new Encoding(true);
encoding.type = undefined;
let bytes: Uint8Array = new Uint8Array([72, 101, 108, 108, 111]);
let s: string = encoding.getString(bytes, 0, bytes.length);
expect(s).toBe('Hello');
});
});
/**
* Validating getString method in utf-8 encoding
* method: getString(bytes:ArrayBuffer,index:number,count:number)
* return string type
*/
describe('Validating getstring method in UTF-8 Encoding', () => {
let encoding: Encoding;
beforeEach((): void => {
encoding = new Encoding(true);
encoding.type = 'Utf8';
});
afterEach((): void => {
encoding.destroy();
encoding = undefined;
});
it('bytes,index,count as null parameter', () => {
expect((): void => { encoding.getString(null, null, null); }).toThrow(new Error('ArgumentException: bytes cannot be null or undefined'));
});
it('bytes as valid values,index and count as null parameter', () => {
let bytes: Uint8Array = new Uint8Array([72, 101, 108, 108, 111]);
expect((): void => { encoding.getString(bytes, null, null); }).toThrow(new Error('ArgumentException: index cannot be null or undefined'));
});
it('index as null parameter, bytes and count as valid values', () => {
let bytes: Uint8Array = new Uint8Array([72, 101, 108, 108, 111]);
expect((): void => { encoding.getString(bytes, null, 1); }).toThrow(new Error('ArgumentException: index cannot be null or undefined'));
});
it('count as null parameter, bytes and index as valid values', () => {
let bytes: Uint8Array = new Uint8Array([72, 101, 108, 108, 111]);
expect((): void => { encoding.getString(bytes, 0, null); }).toThrow(new Error('ArgumentException: count cannot be null or undefined'));
});
it('bytes,index,count as undefined parameter', () => {
expect((): void => { encoding.getString(undefined, undefined, undefined); }).toThrow(new Error('ArgumentException: bytes cannot be null or undefined'));
});
it('bytes as undefined,index and count as 0', () => {
expect((): void => { encoding.getString(undefined, 0, 0); }).toThrow(new Error('ArgumentException: bytes cannot be null or undefined'));
});
it('valid bytes,index and count as undefined parameter', () => {
let getBytes: ArrayBuffer = new ArrayBuffer(1);
let bytes: Uint8Array = new Uint8Array(getBytes);
bytes[0] = 97;
expect((): void => { encoding.getString(getBytes, undefined, undefined); }).toThrow(new Error('ArgumentException: index cannot be null or undefined'));
});
it('valid bytes and count,index as undefined parameter', () => {
let getBytes: ArrayBuffer = new ArrayBuffer(1);
let bytes: Uint8Array = new Uint8Array(getBytes);
bytes[0] = 97;
expect((): void => { encoding.getString(getBytes, undefined, 1); }).toThrow(new Error('ArgumentException: index cannot be null or undefined'));
});
it('valid bytes and index,count as undefined parameter', () => {
let getBytes: ArrayBuffer = new ArrayBuffer(1);
let bytes: Uint8Array = new Uint8Array(getBytes);
bytes[0] = 97;
expect((): void => { encoding.getString(getBytes, 0, undefined); }).toThrow(new Error('ArgumentException: count cannot be null or undefined'));
});
it('index and count as negative value,bytes as valid values', () => {
let bytes: Uint8Array = new Uint8Array([72, 101, 108, 108, 111]);
expect((): void => { encoding.getString(bytes, -1, -1); }).toThrow(new RangeError('Argument Out Of Range Exception: index or count is less than zero'));
});
it('bytes as valid,index as 0 and count as negative value', () => {
let bytes: Uint8Array = new Uint8Array([72, 101, 108, 108, 111]);
expect((): void => { encoding.getString(bytes, 0, -1); }).toThrow(new RangeError('Argument Out Of Range Exception: index or count is less than zero'));
});
it('bytes as valid,index as negative value and count as 0', () => {
let bytes: Uint8Array = new Uint8Array([72, 101, 108, 108, 111]);
expect((): void => { encoding.getString(bytes, -1, 0); }).toThrow(new RangeError('Argument Out Of Range Exception: index or count is less than zero'));
});
it('valid bytes,index and count as 0', () => {
let bytes: Uint8Array = new Uint8Array([72, 101, 108, 108, 111]);
let s: string = encoding.getString(bytes, 0, 0);
expect(s === '').toEqual(true);
});
it('bytes,index and count as valid value', () => {
let bytes: Uint8Array = new Uint8Array([97, 101, 108, 108, 111]);
let s: string = encoding.getString(bytes, 0, 1);
expect(s === 'a').toEqual(true);
});
it('valid bytes,index as negative value and count as valid value', () => {
let bytes: Uint8Array = new Uint8Array([72, 101, 108, 108, 111]);
expect((): void => { encoding.getString(bytes, -1, 0); }).toThrow(new RangeError('Argument Out Of Range Exception: index or count is less than zero'));
});
it('bytes and index as valid and count as invalid values', () => {
let bytes: Uint8Array = new Uint8Array([72, 101, 108, 108, 111]);
expect(bytes.length).toBe(5);
expect((): void => { encoding.getString(bytes, 1, 6) }).toThrow(new RangeError('Argument Out Of Range Exception: index and count do not denote a valid range in bytes'));
});
it('bytes and count as valid and index as invalid value', () => {
let bytes: Uint8Array = new Uint8Array([72, 101, 108, 108, 111]);
expect(bytes.length).toBe(5);
expect((): void => { encoding.getString(bytes, 6, 5) }).toThrow(new RangeError('Argument Out Of Range Exception: index and count do not denote a valid range in bytes'));
});
it('bytes with valid value', () => {
let bytes: Uint8Array = new Uint8Array([72, 101, 108, 108, 111]);
let s: string = encoding.getString(bytes, 0, 5);
expect(s).toBe('Hello');
});
it('bytes with unicode character', () => {
let s: string = '¥';
let bytes: ArrayBuffer = encoding.getBytes(s, 0, 1);
let text: string = encoding.getString(bytes, 0, 1);
expect(text === '¥').toEqual(false);
});
it('bytes with unicode character', () => {
let s: string = '¥';
let bytes: ArrayBuffer = encoding.getBytes(s, 0, 1);
let text: string = encoding.getString(bytes, 0, 2);
expect(text === '¥').toEqual(true);
});
it('bytes with length 0,index and count as valid values', () => {
let bytes: ArrayBuffer = encoding.getBytes('', 0, 0);
expect(bytes.byteLength).toBe(0);
let s: string = encoding.getString(bytes, 0, 0);
expect(s).toBe('');
});
it('bytes and index as valid and count as invalid values', () => {
let bytes: Uint8Array = new Uint8Array([72, 101, 108, 108, 111]);
expect(bytes.length).toBe(5);
expect((): void => { encoding.getString(bytes, 1, 6) }).toThrow(new RangeError('Argument Out Of Range Exception: index and count do not denote a valid range in bytes'));
});
it('bytes and count as valid and index as invalid value', () => {
let bytes: Uint8Array = new Uint8Array([72, 101, 108, 108, 111]);
expect(bytes.length).toBe(5);
expect((): void => { encoding.getString(bytes, 6, 5) }).toThrow(new RangeError('Argument Out Of Range Exception: index and count do not denote a valid range in bytes'));
});
it('string with chinese character, index and count as valid value', () => {
let s: string = '汉字';
let getBytes: ArrayBuffer = encoding.getBytes(s, 0, 2);
let text: string = encoding.getString(getBytes, 0, getBytes.byteLength)
expect(text).toBe('汉字');
});
it('valid string with chinese character', () => {
let getBytes: Uint8Array = new Uint8Array([240, 141, 160, 128, 240, 141, 189, 136]);
let text: string = encoding.getString(getBytes, 0, getBytes.length)
expect(text).toBe('𐍈');
});
});
/**
* Validating getString method in unicode encoding
* method: getString(bytes:ArrayBuffer,index:number,count:number)
* return string type
*/
describe('Validating getstring method in Unicode Encoding', () => {
let encoding: Encoding;
beforeEach((): void => {
encoding = new Encoding(true);
encoding.type = 'Unicode';
});
afterEach((): void => {
encoding.destroy();
encoding = undefined;
});
it('bytes,index,count as null parameter', () => {
expect((): void => { encoding.getString(null, null, null); }).toThrow(new Error('ArgumentException: bytes cannot be null or undefined'));
});
it('bytes as valid values,index and count as null parameter', () => {
let bytes: Uint16Array = new Uint16Array([72, 101, 108, 108, 111]);
expect((): void => { encoding.getString(bytes, null, null); }).toThrow(new Error('ArgumentException: index cannot be null or undefined'));
});
it('index as null parameter, bytes and count as valid values', () => {
let bytes: Uint16Array = new Uint16Array([72, 101, 108, 108, 111]);
expect((): void => { encoding.getString(bytes, null, 1); }).toThrow(new Error('ArgumentException: index cannot be null or undefined'));
});
it('count as null parameter, bytes and index as valid values', () => {
let bytes: Uint16Array = new Uint16Array([72, 101, 108, 108, 111]);
expect((): void => { encoding.getString(bytes, 0, null); }).toThrow(new Error('ArgumentException: count cannot be null or undefined'));
});
it('bytes,index,count as undefined parameter', () => {
expect((): void => { encoding.getString(undefined, undefined, undefined); }).toThrow(new Error('ArgumentException: bytes cannot be null or undefined'));
});
it('bytes as undefined,index and count as 0', () => {
expect((): void => { encoding.getString(undefined, 0, 0); }).toThrow(new Error('ArgumentException: bytes cannot be null or undefined'));
});
it('valid bytes,index and count as undefined parameter', () => {
let getBytes: ArrayBuffer = new ArrayBuffer(2);
let bytes: Uint16Array = new Uint16Array(getBytes);
bytes[0] = 97;
expect((): void => { encoding.getString(getBytes, undefined, undefined); }).toThrow(new Error('ArgumentException: index cannot be null or undefined'));
});
it('valid bytes and count,index as undefined parameter', () => {
let getBytes: ArrayBuffer = new ArrayBuffer(2);
let bytes: Uint16Array = new Uint16Array(getBytes);
bytes[0] = 97;
expect((): void => { encoding.getString(getBytes, undefined, 1); }).toThrow(new Error('ArgumentException: index cannot be null or undefined'));
});
it('valid bytes and index,count as undefined parameter', () => {
let getBytes: ArrayBuffer = new ArrayBuffer(2);
let bytes: Uint16Array = new Uint16Array(getBytes);
bytes[0] = 97;
expect((): void => { encoding.getString(getBytes, 0, undefined); }).toThrow(new Error('ArgumentException: count cannot be null or undefined'));
});
it('index and count as negative value,bytes as valid values', () => {
let bytes: Uint16Array = new Uint16Array([72, 101, 108, 108, 111]);
expect((): void => { encoding.getString(bytes, -1, -1); }).toThrow(new RangeError('Argument Out Of Range Exception: index or count is less than zero'));
});
it('bytes as valid,index as 0 and count as negative value', () => {
let bytes: Uint16Array = new Uint16Array([72, 101, 108, 108, 111]);
expect((): void => { encoding.getString(bytes, 0, -1); }).toThrow(new RangeError('Argument Out Of Range Exception: index or count is less than zero'));
});
it('bytes as valid,index as negative value and count as 0', () => {
let bytes: Uint16Array = new Uint16Array([72, 101, 108, 108, 111]);
expect((): void => { encoding.getString(bytes, -1, 0); }).toThrow(new RangeError('Argument Out Of Range Exception: index or count is less than zero'));
});
it('valid bytes,index and count as 0', () => {
let bytes: Uint16Array = new Uint16Array([72, 101, 108, 108, 111]);
let s: string = encoding.getString(bytes, 0, 0);
expect(s === '').toEqual(true);
});
it('bytes,index and count as valid value', () => {
let bytes: Uint16Array = new Uint16Array([97, 101, 108, 108, 111]);
let s: string = encoding.getString(bytes, 0, 1);
expect(s === 'a').toEqual(true);
});
it('valid bytes,index as negative value and count as valid value', () => {
let bytes: Uint16Array = new Uint16Array([72, 101, 108, 108, 111]);
expect((): void => { encoding.getString(bytes, -1, 0); }).toThrow(new RangeError('Argument Out Of Range Exception: index or count is less than zero'));
});
it('bytes and index as valid and count as invalid values', () => {
let bytes: Uint16Array = new Uint16Array([72, 101, 108, 108, 111]);
expect(bytes.length).toBe(5);
expect((): void => { encoding.getString(bytes, 1, 12) }).toThrow(new RangeError('Argument Out Of Range Exception: index and count do not denote a valid range in bytes'));
});
it('bytes and count as valid and index as invalid value', () => {
let bytes: Uint16Array = new Uint16Array([72, 101, 108, 108, 111]);
expect(bytes.length).toBe(5);
expect((): void => { encoding.getString(bytes, 6, 5) }).toThrow(new RangeError('Argument Out Of Range Exception: index and count do not denote a valid range in bytes'));
});
it('bytes with valid value', () => {
let bytes: Uint16Array = new Uint16Array([72, 101, 108, 108, 111]);
let s: string = encoding.getString(bytes, 0, 5);
expect(s).toBe('Hello');
});
it('bytes with unicode character', () => {
let s: string = '¥';
let bytes: ArrayBuffer = encoding.getBytes(s, 0, 1);
let text: string = encoding.getString(bytes, 0, 1);
expect(text === '¥').toEqual(true);
});
it('bytes with length 0,index and count as valid values', () => {
let bytes: ArrayBuffer = encoding.getBytes('', 0, 0);
expect(bytes.byteLength).toBe(0);
let s: string = encoding.getString(bytes, 0, 0);
expect(s).toBe('');
});
it('bytes and index as valid and count as invalid values', () => {
let bytes: Uint8Array = new Uint8Array([72, 101, 108, 108, 111]);
expect(bytes.length).toBe(5);
expect((): void => { encoding.getString(bytes, 1, 6) }).toThrow(new RangeError('Argument Out Of Range Exception: index and count do not denote a valid range in bytes'));
});
it('bytes and count as valid and index as invalid value', () => {
let bytes: Uint8Array = new Uint8Array([72, 101, 108, 108, 111]);
expect(bytes.length).toBe(5);
expect((): void => { encoding.getString(bytes, 6, 5) }).toThrow(new RangeError('Argument Out Of Range Exception: index and count do not denote a valid range in bytes'));
});
it('string with chinese character, index and count as valid value', () => {
let s: string = '汉字';
let getBytes: ArrayBuffer = encoding.getBytes(s, 0, 2);
let text: string = encoding.getString(getBytes, 0, 2)
expect(text).toBe('汉字');
});
it('string with chinese character, index and count as valid value', () => {
let s: string = '𤭢';
let getBytes: ArrayBuffer = encoding.getBytes(s, 0, 2);
let text: string = encoding.getString(getBytes, 0, 2)
expect(text).toBe('𤭢');
});
it('string with chinese character, index and count as valid value', () => {
let s: string = '𤭢';
let getBytes: ArrayBuffer = encoding.getBytes(s, 0, 2);
expect(() => { encoding.getString(getBytes, 0, getBytes.byteLength) }).toThrow(new RangeError('ArgumentOutOfRange_Count'));
});
});
/**
* Validating getByteCount Method in Ansi Encoding
* method: getByteCount(chars:string)
* return number
*/
describe('Validating getByteCount Method in Ansi Encoding', () => {
let encoding: Encoding;
beforeEach(() => {
encoding = new Encoding();
encoding.type = 'Ansi';
});
afterEach(() => {
encoding.destroy();
encoding = undefined;
});
it('string as Null', () => {
expect((): void => { encoding.getByteCount(null); }).toThrow(new Error('ArgumentException: string cannot be null or undefined'));
});
it('string as undefined', () => {
expect((): void => { encoding.getByteCount(undefined); }).toThrow(new Error('ArgumentException: string cannot be null or undefined'));
});
it('Empty string', () => {
let byteCount: number = encoding.getByteCount('');
expect(byteCount).toBe(0);
});
it('valid string with ASCII character', () => {
let byteCount: number = encoding.getByteCount('Stream');
expect(byteCount).toBe(6);
});
it('valid string with unicode character', () => {
let byteCount: number = encoding.getByteCount('¥');
expect(byteCount).toBe(1);
});
it('valid string with ascii and unicode text', () => {
let byteCount: number = encoding.getByteCount('example ¥');
expect(byteCount).toBe(9);
});
it('valid string with chinese character', () => {
let byteCount: number = encoding.getByteCount('汉字');
expect(byteCount).toBe(2);
});
it('EncodingType with null in getByteCount method', () => {
let encoding: Encoding = new Encoding(true);
encoding.type = undefined;
let byteCount: number = encoding.getByteCount('encoding');
expect(byteCount).toBe(8);
});
});
/**
* Validating getByteCount Method in UTF8 Encoding
* method: getByteCount(chars:string)
*/
describe('Validating getByteCount Method in UTF8 Encoding', () => {
let encoding: Encoding;
beforeEach(() => {
encoding = new Encoding();
encoding.type = 'Utf8';
});
afterEach(() => {
encoding.destroy();
encoding = undefined;
});
it('string as Null', () => {
expect((): void => { encoding.getByteCount(null); }).toThrow(new Error('ArgumentException: string cannot be null or undefined'));
});
it('string as undefined', () => {
expect((): void => { encoding.getByteCount(undefined); }).toThrow(new Error('ArgumentException: string cannot be null or undefined'));
});
it('Empty string', () => {
let byteCount: number = encoding.getByteCount('');
expect(byteCount).toBe(0);
});
it('valid string with ASCII character', () => {
let byteCount: number = encoding.getByteCount('Stream');
expect(byteCount).toBe(6);
});
it('valid string with unicode character', () => {
let byteCount: number = encoding.getByteCount('¥');
expect(byteCount).toBe(2);
});
it('valid string with ascii and unicode character', () => {
let byteCount: number = encoding.getByteCount('example ¥');
expect(byteCount).toBe(10);
});
it('valid string with chinese character', () => {
let byteCount: number = encoding.getByteCount('汉字');
expect(byteCount).toBe(6);
});
it('string with chinese character, index and count as valid value', () => {
let s: string = '𐍈';
let getBytes: number = encoding.getByteCount(s);
expect(getBytes).toBe(4);
});
});
/**
* Validating getByteCount Method in unicode Encoding
* method: getByteCount(chars:string)
*/
describe('Validating getByteCount Method in unicode Encoding', () => {
let encoding: Encoding;
beforeEach(() => {
encoding = new Encoding();
encoding.type = 'Unicode';
});
afterEach(() => {
encoding.destroy();
encoding = undefined;
});
it('string as Null', () => {
expect((): void => { encoding.getByteCount(null); }).toThrow(new Error('ArgumentException: string cannot be null or undefined'));
});
it('string as undefined', () => {
expect((): void => { encoding.getByteCount(undefined); }).toThrow(new Error('ArgumentException: string cannot be null or undefined'));
});
it('Empty string', () => {
let byteCount: number = encoding.getByteCount('');
expect(byteCount).toBe(0);
});
it('valid string with ASCII character', () => {
let byteCount: number = encoding.getByteCount('Stream');
expect(byteCount).toBe(12);
});
it('valid string with unicode character', () => {
let byteCount: number = encoding.getByteCount('¥');
expect(byteCount).toBe(2);
});
it('valid string with ascii and unicode character', () => {
let byteCount: number = encoding.getByteCount('example ¥');
expect(byteCount).toBe(18);
});
it('valid string with chinese character', () => {
let byteCount: number = encoding.getByteCount('汉字');
expect(byteCount).toBe(4);
});
it('string with chinese character, index and count as valid value', () => {
let s: string = '𐍈';
let getBytes: number = encoding.getByteCount(s);
expect(getBytes).toBe(4);
});
}); | the_stack |
import { ISubmission, SubmissionRating, SubmissionType, FileMap } from '../tables/submission.table';
import { Observable, Subject } from 'rxjs';
import { FileObject, SubmissionFileType } from '../tables/submission-file.table';
import { DescriptionData } from 'src/app/utils/components/description-input/description-input.component';
import { TagData } from 'src/app/utils/components/tag-input/tag-input.component';
import { WebsiteRegistry } from 'src/app/websites/registries/website.registry';
import { copyObject } from 'src/app/utils/helpers/copy.helper';
import { moveItemInArray } from '@angular/cdk/drag-drop';
export interface SubmissionFormData {
websites: string[];
loginProfile: string;
defaults: {
description: DescriptionData;
tags: TagData;
};
[state: string]: any; // WebsiteData
}
interface WebsiteData {
description: DescriptionData;
tags: TagData;
options: any;
}
export interface SubmissionChange {
[key: string]: {
old: any;
current: any;
validate?: boolean;
noUpdate?: boolean;
};
}
export interface PostStats {
success: string[];
fail: string[];
originalCount: number;
errors: string[];
sourceURLs: string[];
}
export class Submission implements ISubmission {
private changeSubject: Subject<SubmissionChange> = new Subject();
public readonly changes: Observable<SubmissionChange>;
public updateAfterInit: boolean = false;
public id: number;
public submissionType: SubmissionType;
get fileInfo(): FileObject { return this._fileInfo }
set fileInfo(file: FileObject) {
const old = this._fileInfo;
this._fileInfo = file;
this._emitChange('fileInfo', old, file, true);
}
private _fileInfo: FileObject;
get additionalFileInfo(): FileObject[] { return this._additionalFileInfo }
set additionalFileInfo(fileInfos: FileObject[]) {
const old = this._additionalFileInfo;
this._additionalFileInfo = fileInfos;
this._emitChange('additionalFileInfo', old, fileInfos, true);
}
private _additionalFileInfo: FileObject[];
get ignoreAdditionalFilesMap(): { [key: string]: string[] } { return this._ignoreAdditionalFilesMap }
set ignoreAdditionalFilesMap(map: { [key: string]: string[] }) {
const old = this._ignoreAdditionalFilesMap;
this._ignoreAdditionalFilesMap = map;
this._emitChange('ignoreAdditionalFilesMap', old, map, true);
}
private _ignoreAdditionalFilesMap: { [key: string]: string[] } = {};
get schedule(): any { return this._schedule }
set schedule(schedule: any) {
const old = this._schedule;
this._schedule = schedule;
this._emitChange('schedule', old, schedule, true);
if (!schedule && this.isScheduled) {
this.isScheduled = false;
}
}
private _schedule: any;
get isScheduled(): boolean { return this._isScheduled }
set isScheduled(isScheduled: boolean) {
const old = this._isScheduled;
this._isScheduled = isScheduled;
this._emitChange('isScheduled', old, isScheduled);
}
private _isScheduled: boolean = false;
get title(): string { return this._title }
set title(title: string) {
title = (title || '').trim();
const old = this._title;
this._title = title;
this._emitChange('title', old, title);
}
private _title: string;
get rating(): SubmissionRating { return this._rating }
set rating(rating: SubmissionRating) {
const old = this._rating;
this._rating = rating;
this._emitChange('rating', old, rating, true);
}
private _rating: SubmissionRating;
// Need to be careful about setting these - have to pass back in the whole object
get fileMap(): FileMap { return copyObject(this._fileMap) }
set fileMap(fileMap: FileMap) {
this._fileMap = fileMap;
}
private _fileMap: FileMap;
get formData(): SubmissionFormData { return this._formData }
set formData(formData: SubmissionFormData) {
const old = this._formData;
if (formData && formData.websites) {
formData.websites = formData.websites.filter(website => !!WebsiteRegistry.getConfigForRegistry(website)); // filter out any removed websites
}
this._formData = formData;
this._emitChange('formData', old, formData, true);
}
private _formData: SubmissionFormData;
get failed(): boolean {
return !!this.postStats.fail.length || !!this.postStats.errors.length;
}
get problems(): string[] { return this._problems }
set problems(problems: string[]) {
this._problems = problems || [];
this.flagUpdate('problems');
}
private _problems: string[] = [];
get warnings(): string[] { return this._warnings }
set warnings(warnings: string[]) {
this._warnings = warnings || [];
this.flagUpdate('warnings');
}
private _warnings: string[] = [];
get queued(): boolean { return this._queued }
set queued(queued: boolean) {
this._queued = queued;
this.flagUpdate('queued');
}
private _queued: boolean = false; // variable that tracks whether or not the submissions is queued
get postStats(): PostStats { return this._postStats }
set postStats(stats: PostStats) {
const old = this._postStats;
this._postStats = stats;
this._emitChange('postStats', old, stats, true);
}
private _postStats: PostStats = {
success: [],
fail: [],
originalCount: 0,
sourceURLs: [],
errors: []
}
constructor(submission: ISubmission) {
this.id = submission.id;
this.title = submission.title;
this.isScheduled = submission.isScheduled;
this.schedule = submission.schedule;
this.submissionType = submission.submissionType;
this.rating = submission.rating;
this.formData = submission.formData || <any>{ websites: [] };
this._fileMap = {
PRIMARY: null,
THUMBNAIL: null,
ADDITIONAL: []
};
if (submission.fileMap) {
this._fileMap.PRIMARY = submission.fileMap.PRIMARY;
this._fileMap.THUMBNAIL = submission.fileMap.THUMBNAIL;
this._fileMap.ADDITIONAL = submission.fileMap.ADDITIONAL || []
}
this.fileInfo = submission.fileInfo;
this.additionalFileInfo = submission.additionalFileInfo || [];
this.ignoreAdditionalFilesMap = submission.ignoreAdditionalFilesMap || {};
// Perform any regeneration form data somehow gets into a bad state
this.formData.websites = this.formData.websites || [];
this.formData.websites = this.formData.websites.filter(website => !!WebsiteRegistry.getConfigForRegistry(website)); // filter out any removed websites
// Try to rejuvinate websites in case of a hard reset
this.updateAfterInit = false;
if (submission.postStats) {
if (submission.postStats.fail.length) {
submission.postStats.fail.forEach(website => {
if (!this.formData.websites.includes(website)) {
this.formData.websites.push(website);
}
});
this.formData.websites = this.formData.websites.sort();
this.updateAfterInit = true;
}
this.postStats.sourceURLs = submission.postStats.sourceURLs || [];
this.postStats.errors = submission.postStats.errors || [];
}
if (this.formData.websites) {
this.postStats.originalCount = this.formData.websites.length;
}
this.changes = this.changeSubject.asObservable();
if (this.updateAfterInit) {
this.postStats = Object.assign({}, this.postStats);
}
}
public asISubmission(): ISubmission {
const { id, rating, title, schedule, submissionType, fileInfo, additionalFileInfo, ignoreAdditionalFilesMap, fileMap, formData } = this;
return copyObject(
{
id,
rating,
title,
schedule,
submissionType,
fileInfo,
additionalFileInfo,
ignoreAdditionalFilesMap,
fileMap,
formData
}
); // using stringify/parse to ensure unique object
}
/**
* Cleans up subscription/subject when object is being destroyed
*/
public cleanUp(): void {
this.changeSubject.complete();
}
public hasPrimary(): boolean {
return this._fileMap.PRIMARY !== null;
}
public hasThumbnail(): boolean {
return this._fileMap.THUMBNAIL !== null;
}
public setPrimaryFile(id: number): void {
if (this._fileMap.PRIMARY !== id) {
const old = copyObject(this._fileMap);
this._fileMap.PRIMARY = id;
this._emitFileMapUpdate(old);
}
}
public setThumbnailFile(id: number): void {
if (this._fileMap.THUMBNAIL !== id) {
const old = copyObject(this._fileMap);
this._fileMap.THUMBNAIL = id;
this._emitFileMapUpdate(old);
}
}
public addAdditionalFile(id: number, file: FileObject): void {
if (!this._fileMap.ADDITIONAL.includes(id)) {
const old = copyObject(this._fileMap);
this._fileMap.ADDITIONAL.push(id);
this._emitFileMapUpdate(old);
const fileInfo = [...this.additionalFileInfo];
fileInfo.push(file);
this.additionalFileInfo = fileInfo;
}
}
public removeAdditionalFile(id: number): void {
const index: number = this._fileMap.ADDITIONAL.indexOf(id);
if (index !== -1) {
const old = copyObject(this._fileMap);
this._fileMap.ADDITIONAL.splice(index, 1);
this._emitFileMapUpdate(old);
const fileInfo = [...this.additionalFileInfo];
fileInfo.splice(index, 1);
this.additionalFileInfo = fileInfo;
}
}
public swapAdditionalFileOrder(prevIndex: number, newIndex: number): void {
const oldMap = copyObject(this._fileMap);
const newFileInfo = [...this.additionalFileInfo];
moveItemInArray(newFileInfo, prevIndex, newIndex);
moveItemInArray(this._fileMap.ADDITIONAL, prevIndex, newIndex);
this._emitFileMapUpdate(oldMap);
this.additionalFileInfo = newFileInfo;
}
private _emitFileMapUpdate(old: any): void {
this._emitChange('fileMap', old, this.fileMap);
}
/**
* Emits an update event for a field that does not trigger any validation or updates naturally
* @param fieldName Fieldname provided in the event
*/
public flagUpdate(fieldName: string): void {
this.changeSubject.next({
[fieldName]: { noUpdate: true, old: null, current: null, validate: false }
});
}
private _emitChange(fieldName: string, old: any, current: any, validate: boolean = false): void {
if (old != current && this.changes) {
this.changeSubject.next({
[fieldName]: {
old,
current,
validate,
noUpdate: false
}
});
}
}
} | the_stack |
import { EventEmitter } from 'events'
import { Logger, LoggerOptions } from 'node-log-it'
import { merge, map, takeRight, includes, find } from 'lodash'
import { Mongoose } from 'mongoose'
import { MongodbValidator } from '../validators/mongodb-validator'
import { BlockDao } from './mongodb/block-dao'
import { BlockMetaDao } from './mongodb/block-meta-dao'
import { TransactionMetaDao } from './mongodb/transaction-meta-dao'
const mongoose = new Mongoose()
mongoose.Promise = global.Promise // Explicitly supply promise library (http://mongoosejs.com/docs/promises.html)
const MODULE_NAME = 'MongodbStorage'
const DEFAULT_OPTIONS: MongodbStorageOptions = {
connectOnInit: true,
reviewIndexesOnConnect: false,
userAgent: 'Unknown',
collectionNames: {
blocks: 'blocks',
blockMetas: 'block_metas',
transactionMetas: 'transaction_metas',
},
loggerOptions: {},
}
export interface MongodbStorageOptions {
connectOnInit?: boolean
reviewIndexesOnConnect?: boolean
connectionString?: string
userAgent?: string
collectionNames?: {
blocks?: string
blockMetas?: string
transactionMetas?: string
}
loggerOptions?: LoggerOptions
}
export class MongodbStorage extends EventEmitter {
private _isReady = false
private blockDao: BlockDao
private blockMetaDao: BlockMetaDao
private transactionMetaDao: TransactionMetaDao
private options: MongodbStorageOptions
private logger: Logger
constructor(options: MongodbStorageOptions = {}) {
super()
// Associate optional properties
this.options = merge({}, DEFAULT_OPTIONS, options)
this.validateOptionalParameters()
// Bootstrapping
this.logger = new Logger(MODULE_NAME, this.options.loggerOptions)
this.blockDao = new BlockDao(mongoose, this.options.collectionNames!.blocks!)
this.blockMetaDao = new BlockMetaDao(mongoose, this.options.collectionNames!.blockMetas!)
this.transactionMetaDao = new TransactionMetaDao(mongoose, this.options.collectionNames!.transactionMetas!)
this.initConnection()
// Event handlers
this.on('ready', this.readyHandler.bind(this))
this.logger.debug('constructor completes.')
}
isReady(): boolean {
return this._isReady
}
/**
* @deprecated
*/
async getBlockCount(): Promise<number> {
throw new Error('getBlockCount() method is deprecated. Please use getHighestBlockHeight() instead.')
}
async getHighestBlockHeight(): Promise<number> {
this.logger.debug('getBlockCount triggered.')
return await this.blockDao.getHighestHeight()
}
async setBlockCount(height: number): Promise<void> {
throw new Error('Not implemented.')
}
async countBlockRedundancy(height: number): Promise<number> {
this.logger.debug('countBlockRedundancy triggered. height:', height)
return await this.blockDao.countByHeight(height)
}
async getBlock(height: number): Promise<object> {
this.logger.debug('getBlock triggered. height:', height)
const doc: any = await this.blockDao.getByHeight(height)
if (!doc) {
throw new Error('No document found.')
}
if (!doc.payload) {
throw new Error('Invalid document result.')
}
return doc.payload
}
async getBlocks(height: number): Promise<object[]> {
this.logger.debug('getBlocks triggered. height:', height)
const docs = await this.blockDao.listByHeight(height)
if (docs.length === 0) {
return []
}
const blocks = map(docs, (doc: any) => doc.payload)
return blocks
}
async getTransaction(transactionId: string): Promise<object> {
this.logger.debug('getTransaction triggered.')
const doc: any = await this.blockDao.getByTransactionId(transactionId)
if (!doc) {
// TODO: undesirable business logic, should return undefined instead.
throw new Error('No result found.')
}
const transaction = find(doc.payload.tx, (t: any) => t.txid === transactionId)
return transaction
}
async setBlock(height: number, block: object, options: object = {}): Promise<void> {
this.logger.debug('setBlock triggered.')
const data = {
height,
source: (options as any).source,
userAgent: (options as any).userAgent, // Source RPC's user agent
createdBy: this.options.userAgent, // neo-js's user agent
payload: block,
}
await this.blockDao.save(data)
}
async pruneBlock(height: number, redundancySize: number): Promise<void> {
this.logger.debug('pruneBlock triggered. height: ', height, 'redundancySize:', redundancySize)
const docs = await this.blockDao.listByHeight(height)
this.logger.debug('blockDao.listByHeight() succeed. docs.length:', docs.length)
if (docs.length > redundancySize) {
const takeCount = docs.length - redundancySize
const toPrune = takeRight(docs, takeCount)
// TODO: allow all removal tasks to run in parallel via Promise.all()
toPrune.forEach(async (doc: any) => {
this.logger.debug('Removing document id:', doc._id)
try {
await this.blockDao.deleteManyById(doc._id)
this.logger.debug('blockDao.deleteManyById() execution succeed.')
} catch (err) {
this.logger.debug('blockDao.deleteManyById() execution failed. error:', err.message)
// Suppress error and continue
}
})
}
}
async analyzeBlocks(startHeight: number, endHeight: number): Promise<object[]> {
this.logger.debug('analyzeBlockHeight triggered.')
return await this.blockDao.analyze(startHeight, endHeight)
}
async getBlockMetaCount(): Promise<number> {
this.logger.debug('getBlockMetaCount triggered.')
return await this.blockMetaDao.count()
}
async getHighestBlockMetaHeight(): Promise<number> {
this.logger.debug('getHighestBlockMetaHeight triggered.')
return await this.blockMetaDao.getHighestHeight()
}
async setBlockMeta(blockMeta: object): Promise<void> {
this.logger.debug('setBlockMeta triggered.')
const data = {
createdBy: this.options.userAgent, // neo-js's user agent
...blockMeta,
}
return await this.blockMetaDao.save(data)
}
async setTransactionMeta(transactionMeta: object): Promise<void> {
this.logger.debug('setTransactionMeta triggered.')
const data = {
createdBy: this.options.userAgent, // neo-js's user agent
...transactionMeta,
}
return await this.transactionMetaDao.save(data)
}
async analyzeBlockMetas(startHeight: number, endHeight: number): Promise<object[]> {
this.logger.debug('analyzeBlockMetas triggered.')
return await this.blockMetaDao.analyze(startHeight, endHeight)
}
async analyzeTransactionMetas(startHeight: number, endHeight: number): Promise<object[]> {
this.logger.debug('analyzeTransactionMetas triggered.')
return await this.transactionMetaDao.analyze(startHeight, endHeight)
}
async removeBlockMetaByHeight(height: number): Promise<void> {
this.logger.debug('removeBlockMetaByHeight triggered. height: ', height)
return await this.blockMetaDao.removeByHeight(height)
}
async countLegacyTransactionMeta(targetApiLevel: number): Promise<number> {
return await this.transactionMetaDao.countByBelowApiLevel(targetApiLevel)
}
async pruneLegacyTransactionMeta(targetApiLevel: number): Promise<void> {
return await this.transactionMetaDao.removeByBelowApiLevel(targetApiLevel)
}
async close(): Promise<void> {
this.logger.debug('close triggered.')
return await mongoose.disconnect()
}
private readyHandler(payload: any) {
this.logger.debug('readyHandler triggered.')
if (this.options.reviewIndexesOnConnect) {
this.reviewIndexes()
}
}
private validateOptionalParameters() {
// TODO
}
private initConnection() {
if (this.options.connectOnInit) {
this.logger.debug('initConnection triggered.')
MongodbValidator.validateConnectionString(this.options.connectionString!)
mongoose
.connect(
this.options.connectionString!,
{ useCreateIndex: true, useNewUrlParser: true }
)
.then(() => {
this.logger.info('MongoDB connected.')
this.setReady()
})
.catch((err: any) => {
this.logger.error('Error establish MongoDB connection.')
throw err
})
}
}
private setReady() {
this._isReady = true
this.emit('ready')
}
private async reviewIndexes(): Promise<void> {
this.logger.debug('Proceed to review indexes...')
this.emit('reviewIndexes:init')
try {
await this.reviewBlockIndexForHeight()
await this.reviewBlockIndexForTransactionId()
await this.reviewBlockMetaIndexForHeight()
await this.reviewBlockMetaIndexForTime()
await this.reviewTransactionMetaIndexForHeight()
await this.reviewTransactionMetaIndexForTime()
await this.reviewTransactionMetaIndexForTransactionId()
await this.reviewTransactionMetaIndexForType()
this.logger.debug('Review indexes succeed.')
this.emit('reviewIndexes:complete', { isSuccess: true })
} catch (err) {
this.logger.debug('reviewIndexes failed. Message:', err.message)
this.emit('reviewIndexes:complete', { isSuccess: false })
}
}
private async reviewBlockIndexForHeight(): Promise<void> {
this.logger.debug('reviewBlockIndexForHeight triggered.')
const key = 'height_1_createdAt_-1'
const keyObj = { height: 1, createdAt: -1 }
return await this.blockDao.reviewIndex(key, keyObj)
}
private async reviewBlockIndexForTransactionId(): Promise<void> {
this.logger.debug('reviewBlockIndexForTransactionId triggered.')
const key = 'payload.tx.txid_1'
const keyObj = { 'payload.tx.txid': 1 }
return await this.blockDao.reviewIndex(key, keyObj)
}
private async reviewBlockMetaIndexForHeight(): Promise<void> {
this.logger.debug('reviewBlockMetaIndexForHeight triggered.')
const key = 'height_1'
const keyObj = { height: 1 }
return await this.blockMetaDao.reviewIndex(key, keyObj)
}
private async reviewBlockMetaIndexForTime(): Promise<void> {
this.logger.debug('reviewBlockMetaIndexForTime triggered.')
const key = 'time_1'
const keyObj = { time: 1 }
return await this.blockMetaDao.reviewIndex(key, keyObj)
}
private async reviewTransactionMetaIndexForHeight(): Promise<void> {
this.logger.debug('reviewTransactionMetaIndexForHeight triggered.')
const key = 'height_1'
const keyObj = { height: 1 }
return await this.transactionMetaDao.reviewIndex(key, keyObj)
}
private async reviewTransactionMetaIndexForTime(): Promise<void> {
this.logger.debug('reviewTransactionMetaIndexForTime triggered.')
const key = 'time_1'
const keyObj = { time: 1 }
return await this.transactionMetaDao.reviewIndex(key, keyObj)
}
private async reviewTransactionMetaIndexForTransactionId(): Promise<void> {
this.logger.debug('reviewTransactionMetaIndexForTransactionId triggered.')
const key = 'transactionId_1'
const keyObj = { transactionId: 1 }
return await this.transactionMetaDao.reviewIndex(key, keyObj)
}
private async reviewTransactionMetaIndexForType(): Promise<void> {
this.logger.debug('reviewTransactionMetaIndexForType triggered.')
const key = 'type_1'
const keyObj = { type: 1 }
return await this.transactionMetaDao.reviewIndex(key, keyObj)
}
} | the_stack |
import {Autowired, PostConstruct} from "../context/context";
import {LoggerFactory, Logger} from "../logger";
import {ColumnController} from "../columnController/columnController";
import {Column} from "../entities/column";
import {Utils as _} from "../utils";
import {DragAndDropService, DraggingEvent} from "../dragAndDrop/dragAndDropService";
import {GridPanel} from "../gridPanel/gridPanel";
import {ColumnGroup} from "../entities/columnGroup";
import {GridOptionsWrapper} from "../gridOptionsWrapper";
export class MoveColumnController {
@Autowired('loggerFactory') private loggerFactory: LoggerFactory;
@Autowired('columnController') private columnController: ColumnController;
@Autowired('gridPanel') private gridPanel: GridPanel;
@Autowired('dragAndDropService') private dragAndDropService: DragAndDropService;
@Autowired('gridOptionsWrapper') private gridOptionsWrapper: GridOptionsWrapper;
private needToMoveLeft = false;
private needToMoveRight = false;
private movingIntervalId: number;
private intervalCount: number;
private logger: Logger;
private pinned: string;
private centerContainer: boolean;
private lastDraggingEvent: DraggingEvent;
// this counts how long the user has been trying to scroll by dragging and failing,
// if they fail x amount of times, then the column will get pinned. this is what gives
// the 'hold and pin' functionality
private failedMoveAttempts: number;
public constructor(pinned: string) {
this.pinned = pinned;
this.centerContainer = !_.exists(pinned);
}
@PostConstruct
public init(): void {
this.logger = this.loggerFactory.create('MoveColumnController');
}
public getIconName(): string {
return this.pinned ? DragAndDropService.ICON_PINNED : DragAndDropService.ICON_MOVE;;
}
public onDragEnter(draggingEvent: DraggingEvent): void {
// we do dummy drag, so make sure column appears in the right location when first placed
var columns = draggingEvent.dragSource.dragItem;
this.columnController.setColumnsVisible(columns, true);
this.columnController.setColumnsPinned(columns, this.pinned);
this.onDragging(draggingEvent, true);
}
public onDragLeave(draggingEvent: DraggingEvent): void {
var hideColumnOnExit = !this.gridOptionsWrapper.isSuppressDragLeaveHidesColumns() && !draggingEvent.fromNudge;
if (hideColumnOnExit) {
var columns = draggingEvent.dragSource.dragItem;
this.columnController.setColumnsVisible(columns, false);
}
this.ensureIntervalCleared();
}
public onDragStop(): void {
this.ensureIntervalCleared();
}
private adjustXForScroll(draggingEvent: DraggingEvent): number {
if (this.centerContainer) {
return draggingEvent.x + this.gridPanel.getHorizontalScrollPosition();
} else {
return draggingEvent.x;
}
}
private workOutNewIndex(displayedColumns: Column[], allColumns: Column[], dragColumn: Column, direction: string, xAdjustedForScroll: number) {
if (direction === DragAndDropService.DIRECTION_LEFT) {
return this.getNewIndexForColMovingLeft(displayedColumns, allColumns, dragColumn, xAdjustedForScroll);
} else {
return this.getNewIndexForColMovingRight(displayedColumns, allColumns, dragColumn, xAdjustedForScroll);
}
}
private checkCenterForScrolling(xAdjustedForScroll: number): void {
if (this.centerContainer) {
// scroll if the mouse has gone outside the grid (or just outside the scrollable part if pinning)
// putting in 50 buffer, so even if user gets to edge of grid, a scroll will happen
var firstVisiblePixel = this.gridPanel.getHorizontalScrollPosition();
var lastVisiblePixel = firstVisiblePixel + this.gridPanel.getCenterWidth();
this.needToMoveLeft = xAdjustedForScroll < (firstVisiblePixel + 50);
this.needToMoveRight = xAdjustedForScroll > (lastVisiblePixel - 50);
if (this.needToMoveLeft || this.needToMoveRight) {
this.ensureIntervalStarted();
} else {
this.ensureIntervalCleared();
}
}
}
public onDragging(draggingEvent: DraggingEvent, fromEnter = false): void {
this.lastDraggingEvent = draggingEvent;
// if moving up or down (ie not left or right) then do nothing
if (!draggingEvent.direction) {
return;
}
var xAdjustedForScroll = this.adjustXForScroll(draggingEvent);
// if the user is dragging into the panel, ie coming from the side panel into the main grid,
// we don't want to scroll the grid this time, it would appear like the table is jumping
// each time a column is dragged in.
if (!fromEnter) {
this.checkCenterForScrolling(xAdjustedForScroll);
}
var columnsToMove = draggingEvent.dragSource.dragItem;
this.attemptMoveColumns(columnsToMove, draggingEvent.direction, xAdjustedForScroll, fromEnter);
}
private attemptMoveColumns(allMovingColumns: Column[], dragDirection: string, xAdjustedForScroll: number, fromEnter: boolean): void {
var displayedColumns = this.columnController.getDisplayedColumns(this.pinned);
var gridColumns = this.columnController.getAllGridColumns();
var draggingLeft = dragDirection === DragAndDropService.DIRECTION_LEFT;
var draggingRight = dragDirection === DragAndDropService.DIRECTION_RIGHT;
var dragColumn: Column;
var displayedMovingColumns = _.filter(allMovingColumns, column => displayedColumns.indexOf(column) >= 0 );
// if dragging left, we want to use the left most column, ie move the left most column to
// under the mouse pointer
if (draggingLeft) {
dragColumn = displayedMovingColumns[0];
// if dragging right, we want to keep the right most column under the mouse pointer
} else {
dragColumn = displayedMovingColumns[displayedMovingColumns.length-1];
}
var newIndex = this.workOutNewIndex(displayedColumns, gridColumns, dragColumn, dragDirection, xAdjustedForScroll);
var oldIndex = gridColumns.indexOf(dragColumn);
// the two check below stop an error when the user grabs a group my a middle column, then
// it is possible the mouse pointer is to the right of a column while been dragged left.
// so we need to make sure that the mouse pointer is actually left of the left most column
// if moving left, and right of the right most column if moving right
// we check 'fromEnter' below so we move the column to the new spot if the mouse is coming from
// outside the grid, eg if the column is moving from side panel, mouse is moving left, then we should
// place the column to the RHS even if the mouse is moving left and the column is already on
// the LHS. otherwise we stick to the rule described above.
// only allow left drag if this column is moving left
if (!fromEnter && draggingLeft && newIndex>=oldIndex) {
return;
}
// only allow right drag if this column is moving right
if (!fromEnter && draggingRight && newIndex<=oldIndex) {
return;
}
// if moving right, the new index is the index of the right most column, so adjust to first column
if (draggingRight) {
newIndex = newIndex - allMovingColumns.length + 1;
}
this.columnController.moveColumns(allMovingColumns, newIndex);
}
private getNewIndexForColMovingLeft(displayedColumns: Column[], allColumns: Column[], dragColumn: Column, x: number): number {
var usedX = 0;
var leftColumn: Column = null;
for (var i = 0; i < displayedColumns.length; i++) {
var currentColumn = displayedColumns[i];
if (currentColumn === dragColumn) { continue; }
usedX += currentColumn.getActualWidth();
if (usedX > x) {
break;
}
leftColumn = currentColumn;
}
var newIndex: number;
if (leftColumn) {
newIndex = allColumns.indexOf(leftColumn) + 1;
var oldIndex = allColumns.indexOf(dragColumn);
if (oldIndex<newIndex) {
newIndex--;
}
} else {
newIndex = 0;
}
return newIndex;
}
private getNewIndexForColMovingRight(displayedColumns: Column[], allColumns: Column[], dragColumnOrGroup: Column | ColumnGroup, x: number): number {
var dragColumn = <Column> dragColumnOrGroup;
var usedX = dragColumn.getActualWidth();
var leftColumn: Column = null;
for (var i = 0; i < displayedColumns.length; i++) {
if (usedX > x) {
break;
}
var currentColumn = displayedColumns[i];
if (currentColumn === dragColumn) { continue; }
usedX += currentColumn.getActualWidth();
leftColumn = currentColumn;
}
var newIndex: number;
if (leftColumn) {
newIndex = allColumns.indexOf(leftColumn) + 1;
var oldIndex = allColumns.indexOf(dragColumn);
if (oldIndex<newIndex) {
newIndex--;
}
} else {
newIndex = 0;
}
return newIndex;
}
private ensureIntervalStarted(): void {
if (!this.movingIntervalId) {
this.intervalCount = 0;
this.failedMoveAttempts = 0;
this.movingIntervalId = setInterval(this.moveInterval.bind(this), 100);
if (this.needToMoveLeft) {
this.dragAndDropService.setGhostIcon(DragAndDropService.ICON_LEFT, true);
} else {
this.dragAndDropService.setGhostIcon(DragAndDropService.ICON_RIGHT, true);
}
}
}
private ensureIntervalCleared(): void {
if (this.moveInterval) {
clearInterval(this.movingIntervalId);
this.movingIntervalId = null;
this.dragAndDropService.setGhostIcon(DragAndDropService.ICON_MOVE);
}
}
private moveInterval(): void {
var pixelsToMove: number;
this.intervalCount++;
pixelsToMove = 10 + (this.intervalCount * 5);
if (pixelsToMove > 100) {
pixelsToMove = 100;
}
var pixelsMoved: number;
if (this.needToMoveLeft) {
pixelsMoved = this.gridPanel.scrollHorizontally(-pixelsToMove);
} else if (this.needToMoveRight) {
pixelsMoved = this.gridPanel.scrollHorizontally(pixelsToMove);
}
if (pixelsMoved !== 0) {
this.onDragging(this.lastDraggingEvent);
this.failedMoveAttempts = 0;
} else {
this.failedMoveAttempts++;
this.dragAndDropService.setGhostIcon(DragAndDropService.ICON_PINNED);
if (this.failedMoveAttempts > 7) {
var columns = this.lastDraggingEvent.dragSource.dragItem;
var pinType = this.needToMoveLeft ? Column.PINNED_LEFT : Column.PINNED_RIGHT;
this.columnController.setColumnsPinned(columns, pinType);
this.dragAndDropService.nudge();
}
}
}
} | the_stack |
export interface IReturn<T>
{
createResponse(): T;
}
export interface IReturnVoid
{
createResponse(): void;
}
export interface IHasSessionId
{
sessionId: string;
}
export interface IHasBearerToken
{
bearerToken: string;
}
export interface IGet
{
}
export interface IPost
{
}
export interface IPut
{
}
export interface IDelete
{
}
export interface IPatch
{
}
export interface IHasVersion
{
version: number;
}
export class QueryBase
{
public constructor(init?:Partial<QueryBase>) { Object.assign(this, init); }
// @DataMember(Order=1)
public skip: number;
// @DataMember(Order=2)
public take: number;
// @DataMember(Order=3)
public orderBy: string;
// @DataMember(Order=4)
public orderByDesc: string;
// @DataMember(Order=5)
public include: string;
// @DataMember(Order=6)
public fields: string;
// @DataMember(Order=7)
public meta: { [index:string]: string; };
}
export class QueryData<T> extends QueryBase
{
public constructor(init?:Partial<QueryData<T>>) { super(init); Object.assign(this, init); }
}
export class RequestLogEntry
{
public constructor(init?:Partial<RequestLogEntry>) { Object.assign(this, init); }
public id: number;
public dateTime: string;
public statusCode: number;
public statusDescription: string;
public httpMethod: string;
public absoluteUri: string;
public pathInfo: string;
// @StringLength(2147483647)
public requestBody: string;
public requestDto: Object;
public userAuthId: string;
public sessionId: string;
public ipAddress: string;
public forwardedFor: string;
public referer: string;
public headers: { [index:string]: string; };
public formData: { [index:string]: string; };
public items: { [index:string]: string; };
public session: Object;
public responseDto: Object;
public errorResponse: Object;
public exceptionSource: string;
public exceptionData: any;
public requestDuration: string;
public meta: { [index:string]: string; };
}
// @DataContract
export class ResponseError
{
public constructor(init?:Partial<ResponseError>) { Object.assign(this, init); }
// @DataMember(Order=1, EmitDefaultValue=false)
public errorCode: string;
// @DataMember(Order=2, EmitDefaultValue=false)
public fieldName: string;
// @DataMember(Order=3, EmitDefaultValue=false)
public message: string;
// @DataMember(Order=4, EmitDefaultValue=false)
public meta: { [index:string]: string; };
}
// @DataContract
export class ResponseStatus
{
public constructor(init?:Partial<ResponseStatus>) { Object.assign(this, init); }
// @DataMember(Order=1)
public errorCode: string;
// @DataMember(Order=2)
public message: string;
// @DataMember(Order=3)
public stackTrace: string;
// @DataMember(Order=4)
public errors: ResponseError[];
// @DataMember(Order=5)
public meta: { [index:string]: string; };
}
export class QueryDb_1<T> extends QueryBase
{
public constructor(init?:Partial<QueryDb_1<T>>) { super(init); Object.assign(this, init); }
}
export class Rockstar
{
public constructor(init?:Partial<Rockstar>) { Object.assign(this, init); }
/**
* Идентификатор
*/
public id: number;
/**
* Фамилия
*/
public firstName: string;
/**
* Имя
*/
public lastName: string;
/**
* Возраст
*/
public age: number;
}
export class ArrayElementInDictionary
{
public constructor(init?:Partial<ArrayElementInDictionary>) { Object.assign(this, init); }
public id: number;
}
export class ObjectDesign
{
public constructor(init?:Partial<ObjectDesign>) { Object.assign(this, init); }
public id: number;
}
export interface IAuthTokens
{
provider: string;
userId: string;
accessToken: string;
accessTokenSecret: string;
refreshToken: string;
refreshTokenExpiry?: string;
requestToken: string;
requestTokenSecret: string;
items: { [index:string]: string; };
}
// @DataContract
export class AuthUserSession
{
public constructor(init?:Partial<AuthUserSession>) { Object.assign(this, init); }
// @DataMember(Order=1)
public referrerUrl: string;
// @DataMember(Order=2)
public id: string;
// @DataMember(Order=3)
public userAuthId: string;
// @DataMember(Order=4)
public userAuthName: string;
// @DataMember(Order=5)
public userName: string;
// @DataMember(Order=6)
public twitterUserId: string;
// @DataMember(Order=7)
public twitterScreenName: string;
// @DataMember(Order=8)
public facebookUserId: string;
// @DataMember(Order=9)
public facebookUserName: string;
// @DataMember(Order=10)
public firstName: string;
// @DataMember(Order=11)
public lastName: string;
// @DataMember(Order=12)
public displayName: string;
// @DataMember(Order=13)
public company: string;
// @DataMember(Order=14)
public email: string;
// @DataMember(Order=15)
public primaryEmail: string;
// @DataMember(Order=16)
public phoneNumber: string;
// @DataMember(Order=17)
public birthDate: string;
// @DataMember(Order=18)
public birthDateRaw: string;
// @DataMember(Order=19)
public address: string;
// @DataMember(Order=20)
public address2: string;
// @DataMember(Order=21)
public city: string;
// @DataMember(Order=22)
public state: string;
// @DataMember(Order=23)
public country: string;
// @DataMember(Order=24)
public culture: string;
// @DataMember(Order=25)
public fullName: string;
// @DataMember(Order=26)
public gender: string;
// @DataMember(Order=27)
public language: string;
// @DataMember(Order=28)
public mailAddress: string;
// @DataMember(Order=29)
public nickname: string;
// @DataMember(Order=30)
public postalCode: string;
// @DataMember(Order=31)
public timeZone: string;
// @DataMember(Order=32)
public requestTokenSecret: string;
// @DataMember(Order=33)
public createdAt: string;
// @DataMember(Order=34)
public lastModified: string;
// @DataMember(Order=35)
public roles: string[];
// @DataMember(Order=36)
public permissions: string[];
// @DataMember(Order=37)
public isAuthenticated: boolean;
// @DataMember(Order=38)
public fromToken: boolean;
// @DataMember(Order=39)
public profileUrl: string;
// @DataMember(Order=40)
public sequence: string;
// @DataMember(Order=41)
public tag: number;
// @DataMember(Order=42)
public authProvider: string;
// @DataMember(Order=43)
public providerOAuthAccess: IAuthTokens[];
// @DataMember(Order=44)
public meta: { [index:string]: string; };
// @DataMember(Order=45)
public audiences: string[];
// @DataMember(Order=46)
public scopes: string[];
// @DataMember(Order=47)
public dns: string;
// @DataMember(Order=48)
public rsa: string;
// @DataMember(Order=49)
public sid: string;
// @DataMember(Order=50)
public hash: string;
// @DataMember(Order=51)
public homePhone: string;
// @DataMember(Order=52)
public mobilePhone: string;
// @DataMember(Order=53)
public webpage: string;
// @DataMember(Order=54)
public emailConfirmed: boolean;
// @DataMember(Order=55)
public phoneNumberConfirmed: boolean;
// @DataMember(Order=56)
public twoFactorEnabled: boolean;
// @DataMember(Order=57)
public securityStamp: string;
// @DataMember(Order=58)
public type: string;
}
export class MetadataTestNestedChild
{
public constructor(init?:Partial<MetadataTestNestedChild>) { Object.assign(this, init); }
public name: string;
}
export class MetadataTestChild
{
public constructor(init?:Partial<MetadataTestChild>) { Object.assign(this, init); }
public name: string;
public results: MetadataTestNestedChild[];
}
export class MenuItemExampleItem
{
public constructor(init?:Partial<MenuItemExampleItem>) { Object.assign(this, init); }
// @DataMember(Order=1)
// @ApiMember()
public name1: string;
}
export class MenuItemExample
{
public constructor(init?:Partial<MenuItemExample>) { Object.assign(this, init); }
// @DataMember(Order=1)
// @ApiMember()
public name1: string;
public menuItemExampleItem: MenuItemExampleItem;
}
// @DataContract
export class MenuExample
{
public constructor(init?:Partial<MenuExample>) { Object.assign(this, init); }
// @DataMember(Order=1)
// @ApiMember()
public menuItemExample1: MenuItemExample;
}
export class MetadataTypeName
{
public constructor(init?:Partial<MetadataTypeName>) { Object.assign(this, init); }
public name: string;
public namespace: string;
public genericArgs: string[];
}
export class MetadataRoute
{
public constructor(init?:Partial<MetadataRoute>) { Object.assign(this, init); }
public path: string;
public verbs: string;
public notes: string;
public summary: string;
}
export class MetadataDataContract
{
public constructor(init?:Partial<MetadataDataContract>) { Object.assign(this, init); }
public name: string;
public namespace: string;
}
export class MetadataDataMember
{
public constructor(init?:Partial<MetadataDataMember>) { Object.assign(this, init); }
public name: string;
public order: number;
public isRequired: boolean;
public emitDefaultValue: boolean;
}
export class MetadataAttribute
{
public constructor(init?:Partial<MetadataAttribute>) { Object.assign(this, init); }
public name: string;
public constructorArgs: MetadataPropertyType[];
public args: MetadataPropertyType[];
}
export class MetadataPropertyType
{
public constructor(init?:Partial<MetadataPropertyType>) { Object.assign(this, init); }
public name: string;
public type: string;
public isValueType: boolean;
public isSystemType: boolean;
public isEnum: boolean;
public typeNamespace: string;
public genericArgs: string[];
public value: string;
public description: string;
public dataMember: MetadataDataMember;
public readOnly: boolean;
public paramType: string;
public displayType: string;
public isRequired: boolean;
public allowableValues: string[];
public allowableMin: number;
public allowableMax: number;
public attributes: MetadataAttribute[];
}
export class MetadataType
{
public constructor(init?:Partial<MetadataType>) { Object.assign(this, init); }
public name: string;
public namespace: string;
public genericArgs: string[];
public inherits: MetadataTypeName;
public implements: MetadataTypeName[];
public displayType: string;
public description: string;
public returnVoidMarker: boolean;
public isNested: boolean;
public isEnum: boolean;
public isEnumInt: boolean;
public isInterface: boolean;
public isAbstract: boolean;
public returnMarkerTypeName: MetadataTypeName;
public routes: MetadataRoute[];
public dataContract: MetadataDataContract;
public properties: MetadataPropertyType[];
public attributes: MetadataAttribute[];
public innerTypes: MetadataTypeName[];
public enumNames: string[];
public enumValues: string[];
public meta: { [index:string]: string; };
}
export class AutoQueryConvention
{
public constructor(init?:Partial<AutoQueryConvention>) { Object.assign(this, init); }
public name: string;
public value: string;
public types: string;
}
export class AutoQueryViewerConfig
{
public constructor(init?:Partial<AutoQueryViewerConfig>) { Object.assign(this, init); }
public serviceBaseUrl: string;
public serviceName: string;
public serviceDescription: string;
public serviceIconUrl: string;
public formats: string[];
public maxLimit: number;
public isPublic: boolean;
public onlyShowAnnotatedServices: boolean;
public implicitConventions: AutoQueryConvention[];
public defaultSearchField: string;
public defaultSearchType: string;
public defaultSearchText: string;
public brandUrl: string;
public brandImageUrl: string;
public textColor: string;
public linkColor: string;
public backgroundColor: string;
public backgroundImageUrl: string;
public iconUrl: string;
public meta: { [index:string]: string; };
}
export class AutoQueryViewerUserInfo
{
public constructor(init?:Partial<AutoQueryViewerUserInfo>) { Object.assign(this, init); }
public isAuthenticated: boolean;
public queryCount: number;
public meta: { [index:string]: string; };
}
export class AutoQueryOperation
{
public constructor(init?:Partial<AutoQueryOperation>) { Object.assign(this, init); }
public request: string;
public from: string;
public to: string;
public meta: { [index:string]: string; };
}
export class RecursiveNode implements IReturn<RecursiveNode>
{
public constructor(init?:Partial<RecursiveNode>) { Object.assign(this, init); }
public id: number;
public text: string;
public children: RecursiveNode[];
public createResponse() { return new RecursiveNode(); }
public getTypeName() { return 'RecursiveNode'; }
}
export class NativeTypesTestService
{
public constructor(init?:Partial<NativeTypesTestService>) { Object.assign(this, init); }
}
export class NestedClass
{
public constructor(init?:Partial<NestedClass>) { Object.assign(this, init); }
public value: string;
}
export class ListResult
{
public constructor(init?:Partial<ListResult>) { Object.assign(this, init); }
public result: string;
}
export class OnlyInReturnListArg
{
public constructor(init?:Partial<OnlyInReturnListArg>) { Object.assign(this, init); }
public result: string;
}
export class ArrayResult
{
public constructor(init?:Partial<ArrayResult>) { Object.assign(this, init); }
public result: string;
}
export enum EnumType
{
Value1 = 'Value1',
Value2 = 'Value2',
}
export enum EnumWithValues
{
Value1 = '1',
Value2 = '2',
}
// @Flags()
export enum EnumFlags
{
Value0 = 0,
Value1 = 1,
Value2 = 2,
Value3 = 3,
Value123 = 3,
}
export enum EnumStyle
{
lower = 'lower',
UPPER = 'UPPER',
PascalCase = 'PascalCase',
camelCase = 'camelCase',
camelUPPER = 'camelUPPER',
PascalUPPER = 'PascalUPPER',
}
export class Poco
{
public constructor(init?:Partial<Poco>) { Object.assign(this, init); }
public name: string;
}
export class AllCollectionTypes
{
public constructor(init?:Partial<AllCollectionTypes>) { Object.assign(this, init); }
public intArray: number[];
public intList: number[];
public stringArray: string[];
public stringList: string[];
public pocoArray: Poco[];
public pocoList: Poco[];
public nullableByteArray: Uint8Array;
public nullableByteList: number[];
public nullableDateTimeArray: string[];
public nullableDateTimeList: string[];
public pocoLookup: { [index:string]: Poco[]; };
public pocoLookupMap: { [index:string]: { [index:string]: Poco; }[]; };
}
export class KeyValuePair<TKey, TValue>
{
public constructor(init?:Partial<KeyValuePair<TKey, TValue>>) { Object.assign(this, init); }
public key: TKey;
public value: TValue;
}
export class SubType
{
public constructor(init?:Partial<SubType>) { Object.assign(this, init); }
public id: number;
public name: string;
}
export class HelloBase
{
public constructor(init?:Partial<HelloBase>) { Object.assign(this, init); }
public id: number;
}
export class HelloResponseBase
{
public constructor(init?:Partial<HelloResponseBase>) { Object.assign(this, init); }
public refId: number;
}
export class HelloBase_1<T>
{
public constructor(init?:Partial<HelloBase_1<T>>) { Object.assign(this, init); }
public items: T[];
public counts: number[];
}
export class Item
{
public constructor(init?:Partial<Item>) { Object.assign(this, init); }
public value: string;
}
export class InheritedItem
{
public constructor(init?:Partial<InheritedItem>) { Object.assign(this, init); }
public name: string;
}
export class HelloWithReturnResponse
{
public constructor(init?:Partial<HelloWithReturnResponse>) { Object.assign(this, init); }
public result: string;
}
export class HelloType
{
public constructor(init?:Partial<HelloType>) { Object.assign(this, init); }
public result: string;
}
export interface IPoco
{
name: string;
}
export interface IEmptyInterface
{
}
export class EmptyClass
{
public constructor(init?:Partial<EmptyClass>) { Object.assign(this, init); }
}
export interface ImplementsPoco
{
name: string;
}
export class TypeB
{
public constructor(init?:Partial<TypeB>) { Object.assign(this, init); }
public foo: string;
}
export class TypeA
{
public constructor(init?:Partial<TypeA>) { Object.assign(this, init); }
public bar: TypeB[];
}
export class InnerType
{
public constructor(init?:Partial<InnerType>) { Object.assign(this, init); }
public id: number;
public name: string;
}
export enum InnerEnum
{
Foo = 'Foo',
Bar = 'Bar',
Baz = 'Baz',
}
export class InnerTypeItem
{
public constructor(init?:Partial<InnerTypeItem>) { Object.assign(this, init); }
public id: number;
public name: string;
}
export enum DayOfWeek
{
Sunday = 'Sunday',
Monday = 'Monday',
Tuesday = 'Tuesday',
Wednesday = 'Wednesday',
Thursday = 'Thursday',
Friday = 'Friday',
Saturday = 'Saturday',
}
// @DataContract
export enum ShortDays
{
Monday = 'MON',
Tuesday = 'TUE',
Wednesday = 'WED',
Thursday = 'THU',
Friday = 'FRI',
Saturday = 'SAT',
Sunday = 'SUN',
}
// @DataContract
export enum ScopeType
{
Global = '1',
Sale = '2',
}
export class Tuple_2<T1, T2>
{
public constructor(init?:Partial<Tuple_2<T1, T2>>) { Object.assign(this, init); }
public item1: T1;
public item2: T2;
}
export class Tuple_3<T1, T2, T3>
{
public constructor(init?:Partial<Tuple_3<T1, T2, T3>>) { Object.assign(this, init); }
public item1: T1;
public item2: T2;
public item3: T3;
}
export interface IEcho
{
sentence: string;
}
// @Flags()
export enum CacheControl
{
None = 0,
Public = 1,
Private = 2,
MustRevalidate = 4,
NoCache = 8,
NoStore = 16,
NoTransform = 32,
ProxyRevalidate = 64,
}
export enum MyColor
{
Red = 'Red',
Green = 'Green',
Blue = 'Blue',
}
export class SwaggerNestedModel
{
public constructor(init?:Partial<SwaggerNestedModel>) { Object.assign(this, init); }
/**
* NestedProperty description
*/
// @ApiMember(Description="NestedProperty description")
public nestedProperty: boolean;
}
export class SwaggerNestedModel2
{
public constructor(init?:Partial<SwaggerNestedModel2>) { Object.assign(this, init); }
/**
* NestedProperty2 description
*/
// @ApiMember(Description="NestedProperty2 description")
public nestedProperty2: boolean;
/**
* MultipleValues description
*/
// @ApiMember(Description="MultipleValues description")
public multipleValues: string;
/**
* TestRange description
*/
// @ApiMember(Description="TestRange description")
public testRange: number;
}
export enum MyEnum
{
A = 'A',
B = 'B',
C = 'C',
}
// @DataContract
export class UserApiKey
{
public constructor(init?:Partial<UserApiKey>) { Object.assign(this, init); }
// @DataMember(Order=1)
public key: string;
// @DataMember(Order=2)
public keyType: string;
// @DataMember(Order=3)
public expiryDate: string;
}
export class PgRockstar extends Rockstar
{
public constructor(init?:Partial<PgRockstar>) { super(init); Object.assign(this, init); }
}
export class QueryDb_2<From, Into> extends QueryBase
{
public constructor(init?:Partial<QueryDb_2<From, Into>>) { super(init); Object.assign(this, init); }
}
export class CustomRockstar
{
public constructor(init?:Partial<CustomRockstar>) { Object.assign(this, init); }
// @AutoQueryViewerField(Title="Name")
public firstName: string;
// @AutoQueryViewerField(HideInSummary=true)
public lastName: string;
public age: number;
// @AutoQueryViewerField(Title="Album")
public rockstarAlbumName: string;
// @AutoQueryViewerField(Title="Genre")
public rockstarGenreName: string;
}
export interface IFilterRockstars
{
}
export class Movie
{
public constructor(init?:Partial<Movie>) { Object.assign(this, init); }
public id: number;
public imdbId: string;
public title: string;
public rating: string;
public score: number;
public director: string;
public releaseDate: string;
public tagLine: string;
public genres: string[];
}
export class RockstarAlbum
{
public constructor(init?:Partial<RockstarAlbum>) { Object.assign(this, init); }
public id: number;
public rockstarId: number;
public name: string;
}
export class RockstarReference
{
public constructor(init?:Partial<RockstarReference>) { Object.assign(this, init); }
public id: number;
public firstName: string;
public lastName: string;
public age: number;
public albums: RockstarAlbum[];
}
export class OnlyDefinedInGenericType
{
public constructor(init?:Partial<OnlyDefinedInGenericType>) { Object.assign(this, init); }
public id: number;
public name: string;
}
export class OnlyDefinedInGenericTypeFrom
{
public constructor(init?:Partial<OnlyDefinedInGenericTypeFrom>) { Object.assign(this, init); }
public id: number;
public name: string;
}
export class OnlyDefinedInGenericTypeInto
{
public constructor(init?:Partial<OnlyDefinedInGenericTypeInto>) { Object.assign(this, init); }
public id: number;
public name: string;
}
export class TypesGroup
{
public constructor(init?:Partial<TypesGroup>) { Object.assign(this, init); }
}
// @DataContract
export class QueryResponse<T>
{
public constructor(init?:Partial<QueryResponse<T>>) { Object.assign(this, init); }
// @DataMember(Order=1)
public offset: number;
// @DataMember(Order=2)
public total: number;
// @DataMember(Order=3)
public results: T[];
// @DataMember(Order=4)
public meta: { [index:string]: string; };
// @DataMember(Order=5)
public responseStatus: ResponseStatus;
}
export class ChangeRequestResponse
{
public constructor(init?:Partial<ChangeRequestResponse>) { Object.assign(this, init); }
public contentType: string;
public header: string;
public queryString: string;
public form: string;
public responseStatus: ResponseStatus;
}
export class DiscoverTypes implements IReturn<DiscoverTypes>
{
public constructor(init?:Partial<DiscoverTypes>) { Object.assign(this, init); }
public elementInDictionary: { [index:string]: ArrayElementInDictionary[]; };
public createResponse() { return new DiscoverTypes(); }
public getTypeName() { return 'DiscoverTypes'; }
}
export class CustomHttpErrorResponse
{
public constructor(init?:Partial<CustomHttpErrorResponse>) { Object.assign(this, init); }
public custom: string;
public responseStatus: ResponseStatus;
}
// @Route("/alwaysthrows")
export class AlwaysThrows implements IReturn<AlwaysThrows>
{
public constructor(init?:Partial<AlwaysThrows>) { Object.assign(this, init); }
public createResponse() { return new AlwaysThrows(); }
public getTypeName() { return 'AlwaysThrows'; }
}
// @Route("/alwaysthrowsfilterattribute")
export class AlwaysThrowsFilterAttribute implements IReturn<AlwaysThrowsFilterAttribute>
{
public constructor(init?:Partial<AlwaysThrowsFilterAttribute>) { Object.assign(this, init); }
public createResponse() { return new AlwaysThrowsFilterAttribute(); }
public getTypeName() { return 'AlwaysThrowsFilterAttribute'; }
}
// @Route("/alwaysthrowsglobalfilter")
export class AlwaysThrowsGlobalFilter implements IReturn<AlwaysThrowsGlobalFilter>
{
public constructor(init?:Partial<AlwaysThrowsGlobalFilter>) { Object.assign(this, init); }
public createResponse() { return new AlwaysThrowsGlobalFilter(); }
public getTypeName() { return 'AlwaysThrowsGlobalFilter'; }
}
export class CustomFieldHttpErrorResponse
{
public constructor(init?:Partial<CustomFieldHttpErrorResponse>) { Object.assign(this, init); }
public custom: string;
public responseStatus: ResponseStatus;
}
export class NoRepeatResponse
{
public constructor(init?:Partial<NoRepeatResponse>) { Object.assign(this, init); }
public id: string;
}
export class BatchThrowsResponse
{
public constructor(init?:Partial<BatchThrowsResponse>) { Object.assign(this, init); }
public result: string;
public responseStatus: ResponseStatus;
}
export class ObjectDesignResponse
{
public constructor(init?:Partial<ObjectDesignResponse>) { Object.assign(this, init); }
public data: ObjectDesign;
}
export class CreateJwtResponse
{
public constructor(init?:Partial<CreateJwtResponse>) { Object.assign(this, init); }
public token: string;
public responseStatus: ResponseStatus;
}
export class CreateRefreshJwtResponse
{
public constructor(init?:Partial<CreateRefreshJwtResponse>) { Object.assign(this, init); }
public token: string;
public responseStatus: ResponseStatus;
}
export class MetadataTestResponse
{
public constructor(init?:Partial<MetadataTestResponse>) { Object.assign(this, init); }
public id: number;
public results: MetadataTestChild[];
}
// @DataContract
export class GetExampleResponse
{
public constructor(init?:Partial<GetExampleResponse>) { Object.assign(this, init); }
// @DataMember(Order=1)
public responseStatus: ResponseStatus;
// @DataMember(Order=2)
// @ApiMember()
public menuExample1: MenuExample;
}
export class AutoQueryMetadataResponse
{
public constructor(init?:Partial<AutoQueryMetadataResponse>) { Object.assign(this, init); }
public config: AutoQueryViewerConfig;
public userInfo: AutoQueryViewerUserInfo;
public operations: AutoQueryOperation[];
public types: MetadataType[];
public responseStatus: ResponseStatus;
public meta: { [index:string]: string; };
}
export class TestAttributeExport implements IReturn<TestAttributeExport>
{
public constructor(init?:Partial<TestAttributeExport>) { Object.assign(this, init); }
// @Display(AutoGenerateField=true, AutoGenerateFilter=true, ShortName="UnitMeasKey")
public unitMeasKey: number;
public createResponse() { return new TestAttributeExport(); }
public getTypeName() { return 'TestAttributeExport'; }
}
// @DataContract
export class HelloACodeGenTestResponse
{
public constructor(init?:Partial<HelloACodeGenTestResponse>) { Object.assign(this, init); }
/**
* Description for FirstResult
*/
// @DataMember
public firstResult: number;
/**
* Description for SecondResult
*/
// @DataMember
// @ApiMember(Description="Description for SecondResult")
public secondResult: number;
}
export class HelloResponse
{
public constructor(init?:Partial<HelloResponse>) { Object.assign(this, init); }
public result: string;
}
/**
* Description on HelloAllResponse type
*/
// @DataContract
export class HelloAnnotatedResponse
{
public constructor(init?:Partial<HelloAnnotatedResponse>) { Object.assign(this, init); }
// @DataMember
public result: string;
}
export class HelloList implements IReturn<ListResult[]>
{
public constructor(init?:Partial<HelloList>) { Object.assign(this, init); }
public names: string[];
public createResponse() { return new Array<ListResult>(); }
public getTypeName() { return 'HelloList'; }
}
export class HelloArray implements IReturn<ArrayResult[]>
{
public constructor(init?:Partial<HelloArray>) { Object.assign(this, init); }
public names: string[];
public createResponse() { return new Array<ArrayResult>(); }
public getTypeName() { return 'HelloArray'; }
}
export class HelloExistingResponse
{
public constructor(init?:Partial<HelloExistingResponse>) { Object.assign(this, init); }
public helloList: HelloList;
public helloArray: HelloArray;
public arrayResults: ArrayResult[];
public listResults: ListResult[];
}
export class AllTypes implements IReturn<AllTypes>
{
public constructor(init?:Partial<AllTypes>) { Object.assign(this, init); }
public id: number;
public nullableId: number;
public byte: number;
public short: number;
public int: number;
public long: number;
public uShort: number;
public uInt: number;
public uLong: number;
public float: number;
public double: number;
public decimal: number;
public string: string;
public dateTime: string;
public timeSpan: string;
public dateTimeOffset: string;
public guid: string;
public char: string;
public keyValuePair: KeyValuePair<string, string>;
public nullableDateTime: string;
public nullableTimeSpan: string;
public stringList: string[];
public stringArray: string[];
public stringMap: { [index:string]: string; };
public intStringMap: { [index:number]: string; };
public subType: SubType;
public point: string;
// @DataMember(Name="aliasedName")
public originalName: string;
public createResponse() { return new AllTypes(); }
public getTypeName() { return 'AllTypes'; }
}
export class HelloAllTypesResponse
{
public constructor(init?:Partial<HelloAllTypesResponse>) { Object.assign(this, init); }
public result: string;
public allTypes: AllTypes;
public allCollectionTypes: AllCollectionTypes;
}
// @DataContract
export class HelloWithDataContractResponse
{
public constructor(init?:Partial<HelloWithDataContractResponse>) { Object.assign(this, init); }
// @DataMember(Name="result", Order=1, IsRequired=true, EmitDefaultValue=false)
public result: string;
}
/**
* Description on HelloWithDescriptionResponse type
*/
export class HelloWithDescriptionResponse
{
public constructor(init?:Partial<HelloWithDescriptionResponse>) { Object.assign(this, init); }
public result: string;
}
export class HelloWithInheritanceResponse extends HelloResponseBase
{
public constructor(init?:Partial<HelloWithInheritanceResponse>) { super(init); Object.assign(this, init); }
public result: string;
}
export class HelloWithAlternateReturnResponse extends HelloWithReturnResponse
{
public constructor(init?:Partial<HelloWithAlternateReturnResponse>) { super(init); Object.assign(this, init); }
public altResult: string;
}
export class HelloWithRouteResponse
{
public constructor(init?:Partial<HelloWithRouteResponse>) { Object.assign(this, init); }
public result: string;
}
export class HelloWithTypeResponse
{
public constructor(init?:Partial<HelloWithTypeResponse>) { Object.assign(this, init); }
public result: HelloType;
}
export class HelloStruct implements IReturn<HelloStruct>
{
public constructor(init?:Partial<HelloStruct>) { Object.assign(this, init); }
public point: string;
public nullablePoint: string;
public createResponse() { return new HelloStruct(); }
public getTypeName() { return 'HelloStruct'; }
}
export class HelloSessionResponse
{
public constructor(init?:Partial<HelloSessionResponse>) { Object.assign(this, init); }
public result: AuthUserSession;
}
export class HelloImplementsInterface implements IReturn<HelloImplementsInterface>, ImplementsPoco
{
public constructor(init?:Partial<HelloImplementsInterface>) { Object.assign(this, init); }
public name: string;
public createResponse() { return new HelloImplementsInterface(); }
public getTypeName() { return 'HelloImplementsInterface'; }
}
export class Request1Response
{
public constructor(init?:Partial<Request1Response>) { Object.assign(this, init); }
public test: TypeA;
}
export class Request2Response
{
public constructor(init?:Partial<Request2Response>) { Object.assign(this, init); }
public test: TypeA;
}
export class HelloInnerTypesResponse
{
public constructor(init?:Partial<HelloInnerTypesResponse>) { Object.assign(this, init); }
public innerType: InnerType;
public innerEnum: InnerEnum;
public innerList: InnerTypeItem[];
}
export class CustomUserSession extends AuthUserSession
{
public constructor(init?:Partial<CustomUserSession>) { super(init); Object.assign(this, init); }
// @DataMember
public customName: string;
// @DataMember
public customInfo: string;
}
// @DataContract
export class QueryResponseTemplate<T>
{
public constructor(init?:Partial<QueryResponseTemplate<T>>) { Object.assign(this, init); }
// @DataMember(Order=1)
public offset: number;
// @DataMember(Order=2)
public total: number;
// @DataMember(Order=3)
public results: T[];
// @DataMember(Order=4)
public meta: { [index:string]: string; };
// @DataMember(Order=5)
public responseStatus: ResponseStatus;
}
export class HelloVerbResponse
{
public constructor(init?:Partial<HelloVerbResponse>) { Object.assign(this, init); }
public result: string;
}
export class EnumResponse
{
public constructor(init?:Partial<EnumResponse>) { Object.assign(this, init); }
public operator: ScopeType;
}
export class ExcludeTestNested
{
public constructor(init?:Partial<ExcludeTestNested>) { Object.assign(this, init); }
public id: number;
}
export class RestrictLocalhost implements IReturn<RestrictLocalhost>
{
public constructor(init?:Partial<RestrictLocalhost>) { Object.assign(this, init); }
public id: number;
public createResponse() { return new RestrictLocalhost(); }
public getTypeName() { return 'RestrictLocalhost'; }
}
export class RestrictInternal implements IReturn<RestrictInternal>
{
public constructor(init?:Partial<RestrictInternal>) { Object.assign(this, init); }
public id: number;
public createResponse() { return new RestrictInternal(); }
public getTypeName() { return 'RestrictInternal'; }
}
export class HelloTuple implements IReturn<HelloTuple>
{
public constructor(init?:Partial<HelloTuple>) { Object.assign(this, init); }
public tuple2: Tuple_2<string, number>;
public tuple3: Tuple_3<string, number, boolean>;
public tuples2: Tuple_2<string,number>[];
public tuples3: Tuple_3<string,number,boolean>[];
public createResponse() { return new HelloTuple(); }
public getTypeName() { return 'HelloTuple'; }
}
export class HelloAuthenticatedResponse
{
public constructor(init?:Partial<HelloAuthenticatedResponse>) { Object.assign(this, init); }
public version: number;
public sessionId: string;
public userName: string;
public email: string;
public isAuthenticated: boolean;
public responseStatus: ResponseStatus;
}
export class Echo implements IEcho
{
public constructor(init?:Partial<Echo>) { Object.assign(this, init); }
public sentence: string;
}
export class ThrowHttpErrorResponse
{
public constructor(init?:Partial<ThrowHttpErrorResponse>) { Object.assign(this, init); }
}
export class ThrowTypeResponse
{
public constructor(init?:Partial<ThrowTypeResponse>) { Object.assign(this, init); }
public responseStatus: ResponseStatus;
}
export class ThrowValidationResponse
{
public constructor(init?:Partial<ThrowValidationResponse>) { Object.assign(this, init); }
public age: number;
public required: string;
public email: string;
public responseStatus: ResponseStatus;
}
export class acsprofileResponse
{
public constructor(init?:Partial<acsprofileResponse>) { Object.assign(this, init); }
public profileId: string;
}
export class ReturnedDto
{
public constructor(init?:Partial<ReturnedDto>) { Object.assign(this, init); }
public id: number;
}
// @Route("/matchroute/html")
export class MatchesHtml implements IReturn<MatchesHtml>
{
public constructor(init?:Partial<MatchesHtml>) { Object.assign(this, init); }
public name: string;
public createResponse() { return new MatchesHtml(); }
public getTypeName() { return 'MatchesHtml'; }
}
// @Route("/matchroute/json")
export class MatchesJson implements IReturn<MatchesJson>
{
public constructor(init?:Partial<MatchesJson>) { Object.assign(this, init); }
public name: string;
public createResponse() { return new MatchesJson(); }
public getTypeName() { return 'MatchesJson'; }
}
export class TimestampData
{
public constructor(init?:Partial<TimestampData>) { Object.assign(this, init); }
public timestamp: number;
}
// @Route("/test/html")
export class TestHtml implements IReturn<TestHtml>
{
public constructor(init?:Partial<TestHtml>) { Object.assign(this, init); }
public name: string;
public createResponse() { return new TestHtml(); }
public getTypeName() { return 'TestHtml'; }
}
export class ViewResponse
{
public constructor(init?:Partial<ViewResponse>) { Object.assign(this, init); }
public result: string;
}
// @Route("/swagger/model")
export class SwaggerModel implements IReturn<SwaggerModel>
{
public constructor(init?:Partial<SwaggerModel>) { Object.assign(this, init); }
public int: number;
public string: string;
public dateTime: string;
public dateTimeOffset: string;
public timeSpan: string;
public createResponse() { return new SwaggerModel(); }
public getTypeName() { return 'SwaggerModel'; }
}
// @Route("/plain-dto")
export class PlainDto implements IReturn<PlainDto>
{
public constructor(init?:Partial<PlainDto>) { Object.assign(this, init); }
public name: string;
public createResponse() { return new PlainDto(); }
public getTypeName() { return 'PlainDto'; }
}
// @Route("/httpresult-dto")
export class HttpResultDto implements IReturn<HttpResultDto>
{
public constructor(init?:Partial<HttpResultDto>) { Object.assign(this, init); }
public name: string;
public createResponse() { return new HttpResultDto(); }
public getTypeName() { return 'HttpResultDto'; }
}
// @Route("/restrict/mq")
export class TestMqRestriction implements IReturn<TestMqRestriction>
{
public constructor(init?:Partial<TestMqRestriction>) { Object.assign(this, init); }
public name: string;
public createResponse() { return new TestMqRestriction(); }
public getTypeName() { return 'TestMqRestriction'; }
}
// @Route("/set-cache")
export class SetCache implements IReturn<SetCache>
{
public constructor(init?:Partial<SetCache>) { Object.assign(this, init); }
public eTag: string;
public age: string;
public maxAge: string;
public expires: string;
public lastModified: string;
public cacheControl: CacheControl;
public createResponse() { return new SetCache(); }
public getTypeName() { return 'SetCache'; }
}
export class SwaggerComplexResponse
{
public constructor(init?:Partial<SwaggerComplexResponse>) { Object.assign(this, init); }
// @DataMember
// @ApiMember()
public isRequired: boolean;
// @DataMember
// @ApiMember(IsRequired=true)
public arrayString: string[];
// @DataMember
// @ApiMember()
public arrayInt: number[];
// @DataMember
// @ApiMember()
public listString: string[];
// @DataMember
// @ApiMember()
public listInt: number[];
// @DataMember
// @ApiMember()
public dictionaryString: { [index:string]: string; };
}
/**
* Api GET All
*/
// @Route("/swaggerexamples", "GET")
// @Api(Description="Api GET All")
export class GetSwaggerExamples implements IReturn<GetSwaggerExamples>
{
public constructor(init?:Partial<GetSwaggerExamples>) { Object.assign(this, init); }
public get: string;
public createResponse() { return new GetSwaggerExamples(); }
public getTypeName() { return 'GetSwaggerExamples'; }
}
/**
* Api GET Id
*/
// @Route("/swaggerexamples/{Id}", "GET")
// @Api(Description="Api GET Id")
export class GetSwaggerExample implements IReturn<GetSwaggerExample>
{
public constructor(init?:Partial<GetSwaggerExample>) { Object.assign(this, init); }
public id: number;
public get: string;
public createResponse() { return new GetSwaggerExample(); }
public getTypeName() { return 'GetSwaggerExample'; }
}
/**
* Api POST
*/
// @Route("/swaggerexamples", "POST")
// @Api(Description="Api POST")
export class PostSwaggerExamples implements IReturn<PostSwaggerExamples>
{
public constructor(init?:Partial<PostSwaggerExamples>) { Object.assign(this, init); }
public post: string;
public createResponse() { return new PostSwaggerExamples(); }
public getTypeName() { return 'PostSwaggerExamples'; }
}
/**
* Api PUT Id
*/
// @Route("/swaggerexamples/{Id}", "PUT")
// @Api(Description="Api PUT Id")
export class PutSwaggerExample implements IReturn<PutSwaggerExample>
{
public constructor(init?:Partial<PutSwaggerExample>) { Object.assign(this, init); }
public id: number;
public get: string;
public createResponse() { return new PutSwaggerExample(); }
public getTypeName() { return 'PutSwaggerExample'; }
}
// @Route("/lists", "GET")
export class GetLists implements IReturn<GetLists>
{
public constructor(init?:Partial<GetLists>) { Object.assign(this, init); }
public id: string;
public createResponse() { return new GetLists(); }
public getTypeName() { return 'GetLists'; }
}
// @DataContract
export class AuthenticateResponse implements IHasSessionId, IHasBearerToken
{
public constructor(init?:Partial<AuthenticateResponse>) { Object.assign(this, init); }
// @DataMember(Order=1)
public userId: string;
// @DataMember(Order=2)
public sessionId: string;
// @DataMember(Order=3)
public userName: string;
// @DataMember(Order=4)
public displayName: string;
// @DataMember(Order=5)
public referrerUrl: string;
// @DataMember(Order=6)
public bearerToken: string;
// @DataMember(Order=7)
public refreshToken: string;
// @DataMember(Order=8)
public responseStatus: ResponseStatus;
// @DataMember(Order=9)
public meta: { [index:string]: string; };
}
// @DataContract
export class AssignRolesResponse
{
public constructor(init?:Partial<AssignRolesResponse>) { Object.assign(this, init); }
// @DataMember(Order=1)
public allRoles: string[];
// @DataMember(Order=2)
public allPermissions: string[];
// @DataMember(Order=3)
public responseStatus: ResponseStatus;
}
// @DataContract
export class UnAssignRolesResponse
{
public constructor(init?:Partial<UnAssignRolesResponse>) { Object.assign(this, init); }
// @DataMember(Order=1)
public allRoles: string[];
// @DataMember(Order=2)
public allPermissions: string[];
// @DataMember(Order=3)
public responseStatus: ResponseStatus;
}
// @DataContract
export class ConvertSessionToTokenResponse
{
public constructor(init?:Partial<ConvertSessionToTokenResponse>) { Object.assign(this, init); }
// @DataMember(Order=1)
public meta: { [index:string]: string; };
// @DataMember(Order=2)
public accessToken: string;
// @DataMember(Order=3)
public responseStatus: ResponseStatus;
}
// @DataContract
export class GetAccessTokenResponse
{
public constructor(init?:Partial<GetAccessTokenResponse>) { Object.assign(this, init); }
// @DataMember(Order=1)
public accessToken: string;
// @DataMember(Order=2)
public responseStatus: ResponseStatus;
}
// @DataContract
export class GetApiKeysResponse
{
public constructor(init?:Partial<GetApiKeysResponse>) { Object.assign(this, init); }
// @DataMember(Order=1)
public results: UserApiKey[];
// @DataMember(Order=2)
public responseStatus: ResponseStatus;
}
// @DataContract
export class RegenerateApiKeysResponse
{
public constructor(init?:Partial<RegenerateApiKeysResponse>) { Object.assign(this, init); }
// @DataMember(Order=1)
public results: UserApiKey[];
// @DataMember(Order=2)
public responseStatus: ResponseStatus;
}
// @DataContract
export class RegisterResponse
{
public constructor(init?:Partial<RegisterResponse>) { Object.assign(this, init); }
// @DataMember(Order=1)
public userId: string;
// @DataMember(Order=2)
public sessionId: string;
// @DataMember(Order=3)
public userName: string;
// @DataMember(Order=4)
public referrerUrl: string;
// @DataMember(Order=5)
public bearerToken: string;
// @DataMember(Order=6)
public refreshToken: string;
// @DataMember(Order=7)
public responseStatus: ResponseStatus;
// @DataMember(Order=8)
public meta: { [index:string]: string; };
}
// @Route("/anontype")
export class AnonType
{
public constructor(init?:Partial<AnonType>) { Object.assign(this, init); }
}
// @Route("/query/requestlogs")
// @Route("/query/requestlogs/{Date}")
export class QueryRequestLogs extends QueryData<RequestLogEntry> implements IReturn<QueryResponse<RequestLogEntry>>
{
public constructor(init?:Partial<QueryRequestLogs>) { super(init); Object.assign(this, init); }
public date: string;
public viewErrors: boolean;
public createResponse() { return new QueryResponse<RequestLogEntry>(); }
public getTypeName() { return 'QueryRequestLogs'; }
}
// @AutoQueryViewer(Name="Today\'s Logs", Title="Logs from Today")
export class TodayLogs extends QueryData<RequestLogEntry> implements IReturn<QueryResponse<RequestLogEntry>>
{
public constructor(init?:Partial<TodayLogs>) { super(init); Object.assign(this, init); }
public createResponse() { return new QueryResponse<RequestLogEntry>(); }
public getTypeName() { return 'TodayLogs'; }
}
export class TodayErrorLogs extends QueryData<RequestLogEntry> implements IReturn<QueryResponse<RequestLogEntry>>
{
public constructor(init?:Partial<TodayErrorLogs>) { super(init); Object.assign(this, init); }
public createResponse() { return new QueryResponse<RequestLogEntry>(); }
public getTypeName() { return 'TodayErrorLogs'; }
}
export class YesterdayLogs extends QueryData<RequestLogEntry> implements IReturn<QueryResponse<RequestLogEntry>>
{
public constructor(init?:Partial<YesterdayLogs>) { super(init); Object.assign(this, init); }
public createResponse() { return new QueryResponse<RequestLogEntry>(); }
public getTypeName() { return 'YesterdayLogs'; }
}
export class YesterdayErrorLogs extends QueryData<RequestLogEntry> implements IReturn<QueryResponse<RequestLogEntry>>
{
public constructor(init?:Partial<YesterdayErrorLogs>) { super(init); Object.assign(this, init); }
public createResponse() { return new QueryResponse<RequestLogEntry>(); }
public getTypeName() { return 'YesterdayErrorLogs'; }
}
// @Route("/query/rockstars")
export class QueryRockstars extends QueryDb_1<Rockstar> implements IReturn<QueryResponse<Rockstar>>
{
public constructor(init?:Partial<QueryRockstars>) { super(init); Object.assign(this, init); }
public age: number;
public createResponse() { return new QueryResponse<Rockstar>(); }
public getTypeName() { return 'QueryRockstars'; }
}
// @Route("/query/rockstars/cached")
export class QueryRockstarsCached extends QueryDb_1<Rockstar> implements IReturn<QueryResponse<Rockstar>>
{
public constructor(init?:Partial<QueryRockstarsCached>) { super(init); Object.assign(this, init); }
public age: number;
public createResponse() { return new QueryResponse<Rockstar>(); }
public getTypeName() { return 'QueryRockstarsCached'; }
}
// @Route("/changerequest/{Id}")
export class ChangeRequest implements IReturn<ChangeRequestResponse>
{
public constructor(init?:Partial<ChangeRequest>) { Object.assign(this, init); }
public id: string;
public createResponse() { return new ChangeRequestResponse(); }
public getTypeName() { return 'ChangeRequest'; }
}
// @Route("/compress/{Path*}")
export class CompressFile
{
public constructor(init?:Partial<CompressFile>) { Object.assign(this, init); }
public path: string;
}
// @Route("/Routing/LeadPost.aspx")
export class LegacyLeadPost
{
public constructor(init?:Partial<LegacyLeadPost>) { Object.assign(this, init); }
public leadType: string;
public myId: number;
}
// @Route("/info/{Id}")
export class Info
{
public constructor(init?:Partial<Info>) { Object.assign(this, init); }
public id: string;
}
export class CustomHttpError implements IReturn<CustomHttpErrorResponse>
{
public constructor(init?:Partial<CustomHttpError>) { Object.assign(this, init); }
public statusCode: number;
public statusDescription: string;
public createResponse() { return new CustomHttpErrorResponse(); }
public getTypeName() { return 'CustomHttpError'; }
}
export class CustomFieldHttpError implements IReturn<CustomFieldHttpErrorResponse>
{
public constructor(init?:Partial<CustomFieldHttpError>) { Object.assign(this, init); }
public createResponse() { return new CustomFieldHttpErrorResponse(); }
public getTypeName() { return 'CustomFieldHttpError'; }
}
export class FallbackRoute
{
public constructor(init?:Partial<FallbackRoute>) { Object.assign(this, init); }
public pathInfo: string;
}
export class NoRepeat implements IReturn<NoRepeatResponse>
{
public constructor(init?:Partial<NoRepeat>) { Object.assign(this, init); }
public id: string;
public createResponse() { return new NoRepeatResponse(); }
public getTypeName() { return 'NoRepeat'; }
}
export class BatchThrows implements IReturn<BatchThrowsResponse>
{
public constructor(init?:Partial<BatchThrows>) { Object.assign(this, init); }
public id: number;
public name: string;
public createResponse() { return new BatchThrowsResponse(); }
public getTypeName() { return 'BatchThrows'; }
}
export class BatchThrowsAsync implements IReturn<BatchThrowsResponse>
{
public constructor(init?:Partial<BatchThrowsAsync>) { Object.assign(this, init); }
public id: number;
public name: string;
public createResponse() { return new BatchThrowsResponse(); }
public getTypeName() { return 'BatchThrowsAsync'; }
}
// @Route("/code/object", "GET")
export class ObjectId implements IReturn<ObjectDesignResponse>
{
public constructor(init?:Partial<ObjectId>) { Object.assign(this, init); }
public objectName: string;
public createResponse() { return new ObjectDesignResponse(); }
public getTypeName() { return 'ObjectId'; }
}
// @Route("/jwt")
export class CreateJwt extends AuthUserSession implements IReturn<CreateJwtResponse>
{
public constructor(init?:Partial<CreateJwt>) { super(init); Object.assign(this, init); }
public jwtExpiry: string;
public createResponse() { return new CreateJwtResponse(); }
public getTypeName() { return 'CreateJwt'; }
}
// @Route("/jwt-refresh")
export class CreateRefreshJwt implements IReturn<CreateRefreshJwtResponse>
{
public constructor(init?:Partial<CreateRefreshJwt>) { Object.assign(this, init); }
public userAuthId: string;
public jwtExpiry: string;
public createResponse() { return new CreateRefreshJwtResponse(); }
public getTypeName() { return 'CreateRefreshJwt'; }
}
export class MetadataTest implements IReturn<MetadataTestResponse>
{
public constructor(init?:Partial<MetadataTest>) { Object.assign(this, init); }
public id: number;
public createResponse() { return new MetadataTestResponse(); }
public getTypeName() { return 'MetadataTest'; }
}
// @Route("/example", "GET")
// @DataContract
export class GetExample implements IReturn<GetExampleResponse>
{
public constructor(init?:Partial<GetExample>) { Object.assign(this, init); }
public createResponse() { return new GetExampleResponse(); }
public getTypeName() { return 'GetExample'; }
}
export class MetadataRequest implements IReturn<AutoQueryMetadataResponse>
{
public constructor(init?:Partial<MetadataRequest>) { Object.assign(this, init); }
public metadataType: MetadataType;
public createResponse() { return new AutoQueryMetadataResponse(); }
public getTypeName() { return 'MetadataRequest'; }
}
export class ExcludeMetadataProperty
{
public constructor(init?:Partial<ExcludeMetadataProperty>) { Object.assign(this, init); }
public id: number;
}
// @Route("/namedconnection")
export class NamedConnection
{
public constructor(init?:Partial<NamedConnection>) { Object.assign(this, init); }
public emailAddresses: string;
}
/**
* Description for HelloACodeGenTest
*/
export class HelloACodeGenTest implements IReturn<HelloACodeGenTestResponse>
{
public constructor(init?:Partial<HelloACodeGenTest>) { Object.assign(this, init); }
/**
* Description for FirstField
*/
public firstField: number;
public secondFields: string[];
public createResponse() { return new HelloACodeGenTestResponse(); }
public getTypeName() { return 'HelloACodeGenTest'; }
}
export class HelloInService implements IReturn<HelloResponse>
{
public constructor(init?:Partial<HelloInService>) { Object.assign(this, init); }
public name: string;
public createResponse() { return new HelloResponse(); }
public getTypeName() { return 'NativeTypesTestService.HelloInService'; }
}
// @Route("/hello")
// @Route("/hello/{Name}")
export class Hello implements IReturn<HelloResponse>
{
public constructor(init?:Partial<Hello>) { Object.assign(this, init); }
// @Required()
public name: string;
public title: string;
public createResponse() { return new HelloResponse(); }
public getTypeName() { return 'Hello'; }
}
/**
* Description on HelloAll type
*/
// @DataContract
export class HelloAnnotated implements IReturn<HelloAnnotatedResponse>
{
public constructor(init?:Partial<HelloAnnotated>) { Object.assign(this, init); }
// @DataMember
public name: string;
public createResponse() { return new HelloAnnotatedResponse(); }
public getTypeName() { return 'HelloAnnotated'; }
}
export class HelloWithNestedClass implements IReturn<HelloResponse>
{
public constructor(init?:Partial<HelloWithNestedClass>) { Object.assign(this, init); }
public name: string;
public nestedClassProp: NestedClass;
public createResponse() { return new HelloResponse(); }
public getTypeName() { return 'HelloWithNestedClass'; }
}
export class HelloReturnList implements IReturn<OnlyInReturnListArg[]>
{
public constructor(init?:Partial<HelloReturnList>) { Object.assign(this, init); }
public names: string[];
public createResponse() { return new Array<OnlyInReturnListArg>(); }
public getTypeName() { return 'HelloReturnList'; }
}
export class HelloExisting implements IReturn<HelloExistingResponse>
{
public constructor(init?:Partial<HelloExisting>) { Object.assign(this, init); }
public names: string[];
public createResponse() { return new HelloExistingResponse(); }
public getTypeName() { return 'HelloExisting'; }
}
export class HelloWithEnum
{
public constructor(init?:Partial<HelloWithEnum>) { Object.assign(this, init); }
public enumProp: EnumType;
public enumWithValues: EnumWithValues;
public nullableEnumProp: EnumType;
public enumFlags: EnumFlags;
public enumStyle: EnumStyle;
}
export class RestrictedAttributes
{
public constructor(init?:Partial<RestrictedAttributes>) { Object.assign(this, init); }
public id: number;
public name: string;
public hello: Hello;
}
/**
* AllowedAttributes Description
*/
// @Route("/allowed-attributes", "GET")
// @Api(Description="AllowedAttributes Description")
// @ApiResponse(Description="Your request was not understood", StatusCode=400)
// @DataContract
export class AllowedAttributes
{
public constructor(init?:Partial<AllowedAttributes>) { Object.assign(this, init); }
// @DataMember
// @Required()
public id: number;
/**
* Range Description
*/
// @DataMember(Name="Aliased")
// @ApiMember(DataType="double", Description="Range Description", IsRequired=true, ParameterType="path")
public range: number;
}
/**
* Multi Line Class
*/
// @Api(Description="Multi \r\nLine \r\nClass")
export class HelloAttributeStringTest
{
public constructor(init?:Partial<HelloAttributeStringTest>) { Object.assign(this, init); }
/**
* Multi Line Property
*/
// @ApiMember(Description="Multi \r\nLine \r\nProperty")
public overflow: string;
/**
* Some \ escaped chars
*/
// @ApiMember(Description="Some \\ escaped \t \n chars")
public escapedChars: string;
}
export class HelloAllTypes implements IReturn<HelloAllTypesResponse>
{
public constructor(init?:Partial<HelloAllTypes>) { Object.assign(this, init); }
public name: string;
public allTypes: AllTypes;
public allCollectionTypes: AllCollectionTypes;
public createResponse() { return new HelloAllTypesResponse(); }
public getTypeName() { return 'HelloAllTypes'; }
}
export class HelloString implements IReturn<string>
{
public constructor(init?:Partial<HelloString>) { Object.assign(this, init); }
public name: string;
public createResponse() { return ''; }
public getTypeName() { return 'HelloString'; }
}
export class HelloVoid implements IReturnVoid
{
public constructor(init?:Partial<HelloVoid>) { Object.assign(this, init); }
public name: string;
public createResponse() {}
public getTypeName() { return 'HelloVoid'; }
}
// @DataContract
export class HelloWithDataContract implements IReturn<HelloWithDataContractResponse>
{
public constructor(init?:Partial<HelloWithDataContract>) { Object.assign(this, init); }
// @DataMember(Name="name", Order=1, IsRequired=true, EmitDefaultValue=false)
public name: string;
// @DataMember(Name="id", Order=2, EmitDefaultValue=false)
public id: number;
public createResponse() { return new HelloWithDataContractResponse(); }
public getTypeName() { return 'HelloWithDataContract'; }
}
/**
* Description on HelloWithDescription type
*/
export class HelloWithDescription implements IReturn<HelloWithDescriptionResponse>
{
public constructor(init?:Partial<HelloWithDescription>) { Object.assign(this, init); }
public name: string;
public createResponse() { return new HelloWithDescriptionResponse(); }
public getTypeName() { return 'HelloWithDescription'; }
}
export class HelloWithInheritance extends HelloBase implements IReturn<HelloWithInheritanceResponse>
{
public constructor(init?:Partial<HelloWithInheritance>) { super(init); Object.assign(this, init); }
public name: string;
public createResponse() { return new HelloWithInheritanceResponse(); }
public getTypeName() { return 'HelloWithInheritance'; }
}
export class HelloWithGenericInheritance extends HelloBase_1<Poco>
{
public constructor(init?:Partial<HelloWithGenericInheritance>) { super(init); Object.assign(this, init); }
public result: string;
}
export class HelloWithGenericInheritance2 extends HelloBase_1<Hello>
{
public constructor(init?:Partial<HelloWithGenericInheritance2>) { super(init); Object.assign(this, init); }
public result: string;
}
export class HelloWithNestedInheritance extends HelloBase_1<Item>
{
public constructor(init?:Partial<HelloWithNestedInheritance>) { super(init); Object.assign(this, init); }
}
export class HelloWithListInheritance extends Array<InheritedItem>
{
public constructor(init?:Partial<HelloWithListInheritance>) { super(); Object.assign(this, init); }
}
export class HelloWithReturn implements IReturn<HelloWithAlternateReturnResponse>
{
public constructor(init?:Partial<HelloWithReturn>) { Object.assign(this, init); }
public name: string;
public createResponse() { return new HelloWithAlternateReturnResponse(); }
public getTypeName() { return 'HelloWithReturn'; }
}
// @Route("/helloroute")
export class HelloWithRoute implements IReturn<HelloWithRouteResponse>
{
public constructor(init?:Partial<HelloWithRoute>) { Object.assign(this, init); }
public name: string;
public createResponse() { return new HelloWithRouteResponse(); }
public getTypeName() { return 'HelloWithRoute'; }
}
export class HelloWithType implements IReturn<HelloWithTypeResponse>
{
public constructor(init?:Partial<HelloWithType>) { Object.assign(this, init); }
public name: string;
public createResponse() { return new HelloWithTypeResponse(); }
public getTypeName() { return 'HelloWithType'; }
}
export class HelloSession implements IReturn<HelloSessionResponse>
{
public constructor(init?:Partial<HelloSession>) { Object.assign(this, init); }
public createResponse() { return new HelloSessionResponse(); }
public getTypeName() { return 'HelloSession'; }
}
export class HelloInterface
{
public constructor(init?:Partial<HelloInterface>) { Object.assign(this, init); }
public poco: IPoco;
public emptyInterface: IEmptyInterface;
public emptyClass: EmptyClass;
public value: string;
}
export class Request1 implements IReturn<Request1Response>
{
public constructor(init?:Partial<Request1>) { Object.assign(this, init); }
public test: TypeA;
public createResponse() { return new Request1Response(); }
public getTypeName() { return 'Request1'; }
}
export class Request2 implements IReturn<Request2Response>
{
public constructor(init?:Partial<Request2>) { Object.assign(this, init); }
public test: TypeA;
public createResponse() { return new Request2Response(); }
public getTypeName() { return 'Request2'; }
}
export class HelloInnerTypes implements IReturn<HelloInnerTypesResponse>
{
public constructor(init?:Partial<HelloInnerTypes>) { Object.assign(this, init); }
public createResponse() { return new HelloInnerTypesResponse(); }
public getTypeName() { return 'HelloInnerTypes'; }
}
export class GetUserSession implements IReturn<CustomUserSession>
{
public constructor(init?:Partial<GetUserSession>) { Object.assign(this, init); }
public createResponse() { return new CustomUserSession(); }
public getTypeName() { return 'GetUserSession'; }
}
export class QueryTemplate implements IReturn<QueryResponseTemplate<Poco>>
{
public constructor(init?:Partial<QueryTemplate>) { Object.assign(this, init); }
public createResponse() { return new QueryResponseTemplate<Poco>(); }
public getTypeName() { return 'QueryTemplate'; }
}
export class HelloReserved
{
public constructor(init?:Partial<HelloReserved>) { Object.assign(this, init); }
public class: string;
public type: string;
public extension: string;
}
export class HelloDictionary implements IReturn<any>
{
public constructor(init?:Partial<HelloDictionary>) { Object.assign(this, init); }
public key: string;
public value: string;
public createResponse() { return {}; }
public getTypeName() { return 'HelloDictionary'; }
}
export class HelloBuiltin
{
public constructor(init?:Partial<HelloBuiltin>) { Object.assign(this, init); }
public dayOfWeek: DayOfWeek;
public shortDays: ShortDays;
}
export class HelloGet implements IReturn<HelloVerbResponse>, IGet
{
public constructor(init?:Partial<HelloGet>) { Object.assign(this, init); }
public id: number;
public createResponse() { return new HelloVerbResponse(); }
public getTypeName() { return 'HelloGet'; }
}
export class HelloPost extends HelloBase implements IReturn<HelloVerbResponse>, IPost
{
public constructor(init?:Partial<HelloPost>) { super(init); Object.assign(this, init); }
public createResponse() { return new HelloVerbResponse(); }
public getTypeName() { return 'HelloPost'; }
}
export class HelloPut implements IReturn<HelloVerbResponse>, IPut
{
public constructor(init?:Partial<HelloPut>) { Object.assign(this, init); }
public id: number;
public createResponse() { return new HelloVerbResponse(); }
public getTypeName() { return 'HelloPut'; }
}
export class HelloDelete implements IReturn<HelloVerbResponse>, IDelete
{
public constructor(init?:Partial<HelloDelete>) { Object.assign(this, init); }
public id: number;
public createResponse() { return new HelloVerbResponse(); }
public getTypeName() { return 'HelloDelete'; }
}
export class HelloPatch implements IReturn<HelloVerbResponse>, IPatch
{
public constructor(init?:Partial<HelloPatch>) { Object.assign(this, init); }
public id: number;
public createResponse() { return new HelloVerbResponse(); }
public getTypeName() { return 'HelloPatch'; }
}
export class HelloReturnVoid implements IReturnVoid
{
public constructor(init?:Partial<HelloReturnVoid>) { Object.assign(this, init); }
public id: number;
public createResponse() {}
public getTypeName() { return 'HelloReturnVoid'; }
}
export class EnumRequest implements IReturn<EnumResponse>, IPut
{
public constructor(init?:Partial<EnumRequest>) { Object.assign(this, init); }
public operator: ScopeType;
public createResponse() { return new EnumResponse(); }
public getTypeName() { return 'EnumRequest'; }
}
export class ExcludeTest1 implements IReturn<ExcludeTestNested>
{
public constructor(init?:Partial<ExcludeTest1>) { Object.assign(this, init); }
public createResponse() { return new ExcludeTestNested(); }
public getTypeName() { return 'ExcludeTest1'; }
}
export class ExcludeTest2 implements IReturn<string>
{
public constructor(init?:Partial<ExcludeTest2>) { Object.assign(this, init); }
public excludeTestNested: ExcludeTestNested;
public createResponse() { return ''; }
public getTypeName() { return 'ExcludeTest2'; }
}
export class HelloAuthenticated implements IReturn<HelloAuthenticatedResponse>, IHasSessionId
{
public constructor(init?:Partial<HelloAuthenticated>) { Object.assign(this, init); }
public sessionId: string;
public version: number;
public createResponse() { return new HelloAuthenticatedResponse(); }
public getTypeName() { return 'HelloAuthenticated'; }
}
/**
* Echoes a sentence
*/
// @Route("/echoes", "POST")
// @Api(Description="Echoes a sentence")
export class Echoes implements IReturn<Echo>
{
public constructor(init?:Partial<Echoes>) { Object.assign(this, init); }
/**
* The sentence to echo.
*/
// @ApiMember(DataType="string", Description="The sentence to echo.", IsRequired=true, Name="Sentence", ParameterType="form")
public sentence: string;
public createResponse() { return new Echo(); }
public getTypeName() { return 'Echoes'; }
}
export class CachedEcho implements IReturn<Echo>
{
public constructor(init?:Partial<CachedEcho>) { Object.assign(this, init); }
public reload: boolean;
public sentence: string;
public createResponse() { return new Echo(); }
public getTypeName() { return 'CachedEcho'; }
}
export class AsyncTest implements IReturn<Echo>
{
public constructor(init?:Partial<AsyncTest>) { Object.assign(this, init); }
public createResponse() { return new Echo(); }
public getTypeName() { return 'AsyncTest'; }
}
// @Route("/throwhttperror/{Status}")
export class ThrowHttpError implements IReturn<ThrowHttpErrorResponse>
{
public constructor(init?:Partial<ThrowHttpError>) { Object.assign(this, init); }
public status: number;
public message: string;
public createResponse() { return new ThrowHttpErrorResponse(); }
public getTypeName() { return 'ThrowHttpError'; }
}
// @Route("/throw404")
// @Route("/throw404/{Message}")
export class Throw404
{
public constructor(init?:Partial<Throw404>) { Object.assign(this, init); }
public message: string;
}
// @Route("/return404")
export class Return404
{
public constructor(init?:Partial<Return404>) { Object.assign(this, init); }
}
// @Route("/return404result")
export class Return404Result
{
public constructor(init?:Partial<Return404Result>) { Object.assign(this, init); }
}
// @Route("/throw/{Type}")
export class ThrowType implements IReturn<ThrowTypeResponse>
{
public constructor(init?:Partial<ThrowType>) { Object.assign(this, init); }
public type: string;
public message: string;
public createResponse() { return new ThrowTypeResponse(); }
public getTypeName() { return 'ThrowType'; }
}
// @Route("/throwvalidation")
export class ThrowValidation implements IReturn<ThrowValidationResponse>
{
public constructor(init?:Partial<ThrowValidation>) { Object.assign(this, init); }
public age: number;
public required: string;
public email: string;
public createResponse() { return new ThrowValidationResponse(); }
public getTypeName() { return 'ThrowValidation'; }
}
// @Route("/api/acsprofiles", "POST,PUT,PATCH,DELETE")
// @Route("/api/acsprofiles/{profileId}")
export class ACSProfile implements IReturn<acsprofileResponse>, IHasVersion, IHasSessionId
{
public constructor(init?:Partial<ACSProfile>) { Object.assign(this, init); }
public profileId: string;
// @Required()
// @StringLength(20)
public shortName: string;
// @StringLength(60)
public longName: string;
// @StringLength(20)
public regionId: string;
// @StringLength(20)
public groupId: string;
// @StringLength(12)
public deviceID: string;
public lastUpdated: string;
public enabled: boolean;
public version: number;
public sessionId: string;
public createResponse() { return new acsprofileResponse(); }
public getTypeName() { return 'ACSProfile'; }
}
// @Route("/return/string")
export class ReturnString implements IReturn<string>
{
public constructor(init?:Partial<ReturnString>) { Object.assign(this, init); }
public data: string;
public createResponse() { return ''; }
public getTypeName() { return 'ReturnString'; }
}
// @Route("/return/bytes")
export class ReturnBytes implements IReturn<Uint8Array>
{
public constructor(init?:Partial<ReturnBytes>) { Object.assign(this, init); }
public data: Uint8Array;
public createResponse() { return new Uint8Array(0); }
public getTypeName() { return 'ReturnBytes'; }
}
// @Route("/return/stream")
export class ReturnStream implements IReturn<Blob>
{
public constructor(init?:Partial<ReturnStream>) { Object.assign(this, init); }
public data: Uint8Array;
public createResponse() { return new Blob(); }
public getTypeName() { return 'ReturnStream'; }
}
// @Route("/Request1/", "GET")
export class GetRequest1 implements IReturn<ReturnedDto[]>, IGet
{
public constructor(init?:Partial<GetRequest1>) { Object.assign(this, init); }
public createResponse() { return new Array<ReturnedDto>(); }
public getTypeName() { return 'GetRequest1'; }
}
// @Route("/Request3", "GET")
export class GetRequest2 implements IReturn<ReturnedDto>, IGet
{
public constructor(init?:Partial<GetRequest2>) { Object.assign(this, init); }
public createResponse() { return new ReturnedDto(); }
public getTypeName() { return 'GetRequest2'; }
}
// @Route("/matchlast/{Id}")
export class MatchesLastInt
{
public constructor(init?:Partial<MatchesLastInt>) { Object.assign(this, init); }
public id: number;
}
// @Route("/matchlast/{Slug}")
export class MatchesNotLastInt
{
public constructor(init?:Partial<MatchesNotLastInt>) { Object.assign(this, init); }
public slug: string;
}
// @Route("/matchregex/{Id}")
export class MatchesId
{
public constructor(init?:Partial<MatchesId>) { Object.assign(this, init); }
public id: number;
}
// @Route("/matchregex/{Slug}")
export class MatchesSlug
{
public constructor(init?:Partial<MatchesSlug>) { Object.assign(this, init); }
public slug: string;
}
// @Route("/{Version}/userdata", "GET")
export class SwaggerVersionTest
{
public constructor(init?:Partial<SwaggerVersionTest>) { Object.assign(this, init); }
public version: string;
}
// @Route("/swagger/range")
export class SwaggerRangeTest
{
public constructor(init?:Partial<SwaggerRangeTest>) { Object.assign(this, init); }
public intRange: string;
public doubleRange: string;
}
// @Route("/test/errorview")
export class TestErrorView
{
public constructor(init?:Partial<TestErrorView>) { Object.assign(this, init); }
public id: string;
}
// @Route("/timestamp", "GET")
export class GetTimestamp implements IReturn<TimestampData>
{
public constructor(init?:Partial<GetTimestamp>) { Object.assign(this, init); }
public createResponse() { return new TimestampData(); }
public getTypeName() { return 'GetTimestamp'; }
}
export class TestMiniverView
{
public constructor(init?:Partial<TestMiniverView>) { Object.assign(this, init); }
}
// @Route("/testexecproc")
export class TestExecProc
{
public constructor(init?:Partial<TestExecProc>) { Object.assign(this, init); }
}
// @Route("/files/{Path*}")
export class GetFile
{
public constructor(init?:Partial<GetFile>) { Object.assign(this, init); }
public path: string;
}
// @Route("/test/html2")
export class TestHtml2
{
public constructor(init?:Partial<TestHtml2>) { Object.assign(this, init); }
public name: string;
}
// @Route("/views/request")
export class ViewRequest implements IReturn<ViewResponse>
{
public constructor(init?:Partial<ViewRequest>) { Object.assign(this, init); }
public name: string;
public createResponse() { return new ViewResponse(); }
public getTypeName() { return 'ViewRequest'; }
}
// @Route("/index")
export class IndexPage
{
public constructor(init?:Partial<IndexPage>) { Object.assign(this, init); }
public pathInfo: string;
}
// @Route("/return/text")
export class ReturnText
{
public constructor(init?:Partial<ReturnText>) { Object.assign(this, init); }
public text: string;
}
// @Route("/gzip/{FileName}")
export class DownloadGzipFile implements IReturn<Uint8Array>
{
public constructor(init?:Partial<DownloadGzipFile>) { Object.assign(this, init); }
public fileName: string;
public createResponse() { return new Uint8Array(0); }
public getTypeName() { return 'DownloadGzipFile'; }
}
// @Route("/match/{Language}/{Name*}")
export class MatchName implements IReturn<HelloResponse>
{
public constructor(init?:Partial<MatchName>) { Object.assign(this, init); }
public language: string;
public name: string;
public createResponse() { return new HelloResponse(); }
public getTypeName() { return 'MatchName'; }
}
// @Route("/match/{Language*}")
export class MatchLang implements IReturn<HelloResponse>
{
public constructor(init?:Partial<MatchLang>) { Object.assign(this, init); }
public language: string;
public createResponse() { return new HelloResponse(); }
public getTypeName() { return 'MatchLang'; }
}
// @Route("/reqlogstest/{Name}")
export class RequestLogsTest implements IReturn<string>
{
public constructor(init?:Partial<RequestLogsTest>) { Object.assign(this, init); }
public name: string;
public createResponse() { return ''; }
public getTypeName() { return 'RequestLogsTest'; }
}
export class InProcRequest1
{
public constructor(init?:Partial<InProcRequest1>) { Object.assign(this, init); }
}
export class InProcRequest2
{
public constructor(init?:Partial<InProcRequest2>) { Object.assign(this, init); }
}
/**
* SwaggerTest Service Description
*/
// @Route("/swagger", "GET")
// @Route("/swagger/{Name}", "GET")
// @Route("/swagger/{Name}", "POST")
// @Api(Description="SwaggerTest Service Description")
// @ApiResponse(Description="Your request was not understood", StatusCode=400)
// @ApiResponse(Description="Oops, something broke", StatusCode=500)
// @DataContract
export class SwaggerTest
{
public constructor(init?:Partial<SwaggerTest>) { Object.assign(this, init); }
/**
* Color Description
*/
// @DataMember
// @ApiMember(DataType="string", Description="Color Description", IsRequired=true, ParameterType="path")
public name: string;
// @DataMember
// @ApiMember()
public color: MyColor;
/**
* Aliased Description
*/
// @DataMember(Name="Aliased")
// @ApiMember(DataType="string", Description="Aliased Description", IsRequired=true)
public original: string;
/**
* Not Aliased Description
*/
// @DataMember
// @ApiMember(DataType="string", Description="Not Aliased Description", IsRequired=true)
public notAliased: string;
/**
* Format as password
*/
// @DataMember
// @ApiMember(DataType="password", Description="Format as password")
public password: string;
// @DataMember
// @ApiMember(AllowMultiple=true)
public myDateBetween: string[];
/**
* Nested model 1
*/
// @DataMember
// @ApiMember(DataType="SwaggerNestedModel", Description="Nested model 1")
public nestedModel1: SwaggerNestedModel;
/**
* Nested model 2
*/
// @DataMember
// @ApiMember(DataType="SwaggerNestedModel2", Description="Nested model 2")
public nestedModel2: SwaggerNestedModel2;
}
// @Route("/swaggertest2", "POST")
export class SwaggerTest2
{
public constructor(init?:Partial<SwaggerTest2>) { Object.assign(this, init); }
// @ApiMember()
public myEnumProperty: MyEnum;
// @ApiMember(DataType="string", IsRequired=true, Name="Token", ParameterType="header")
public token: string;
}
// @Route("/swagger-complex", "POST")
export class SwaggerComplex implements IReturn<SwaggerComplexResponse>
{
public constructor(init?:Partial<SwaggerComplex>) { Object.assign(this, init); }
// @DataMember
// @ApiMember()
public isRequired: boolean;
// @DataMember
// @ApiMember(IsRequired=true)
public arrayString: string[];
// @DataMember
// @ApiMember()
public arrayInt: number[];
// @DataMember
// @ApiMember()
public listString: string[];
// @DataMember
// @ApiMember()
public listInt: number[];
// @DataMember
// @ApiMember()
public dictionaryString: { [index:string]: string; };
public createResponse() { return new SwaggerComplexResponse(); }
public getTypeName() { return 'SwaggerComplex'; }
}
// @Route("/swaggerpost/{Required1}", "GET")
// @Route("/swaggerpost/{Required1}/{Optional1}", "GET")
// @Route("/swaggerpost", "POST")
export class SwaggerPostTest implements IReturn<HelloResponse>
{
public constructor(init?:Partial<SwaggerPostTest>) { Object.assign(this, init); }
// @ApiMember(Verb="POST")
// @ApiMember(ParameterType="path", Route="/swaggerpost/{Required1}", Verb="GET")
// @ApiMember(ParameterType="path", Route="/swaggerpost/{Required1}/{Optional1}", Verb="GET")
public required1: string;
// @ApiMember(Verb="POST")
// @ApiMember(ParameterType="path", Route="/swaggerpost/{Required1}/{Optional1}", Verb="GET")
public optional1: string;
public createResponse() { return new HelloResponse(); }
public getTypeName() { return 'SwaggerPostTest'; }
}
// @Route("/swaggerpost2/{Required1}/{Required2}", "GET")
// @Route("/swaggerpost2/{Required1}/{Required2}/{Optional1}", "GET")
// @Route("/swaggerpost2", "POST")
export class SwaggerPostTest2 implements IReturn<HelloResponse>
{
public constructor(init?:Partial<SwaggerPostTest2>) { Object.assign(this, init); }
// @ApiMember(ParameterType="path", Route="/swaggerpost2/{Required1}/{Required2}", Verb="GET")
// @ApiMember(ParameterType="path", Route="/swaggerpost2/{Required1}/{Required2}/{Optional1}", Verb="GET")
public required1: string;
// @ApiMember(ParameterType="path", Route="/swaggerpost2/{Required1}/{Required2}", Verb="GET")
// @ApiMember(ParameterType="path", Route="/swaggerpost2/{Required1}/{Required2}/{Optional1}", Verb="GET")
public required2: string;
// @ApiMember(ParameterType="path", Route="/swaggerpost2/{Required1}/{Required2}/{Optional1}", Verb="GET")
public optional1: string;
public createResponse() { return new HelloResponse(); }
public getTypeName() { return 'SwaggerPostTest2'; }
}
// @Route("/swagger/multiattrtest", "POST")
// @ApiResponse(Description="Code 1", StatusCode=400)
// @ApiResponse(Description="Code 2", StatusCode=402)
// @ApiResponse(Description="Code 3", StatusCode=401)
export class SwaggerMultiApiResponseTest implements IReturnVoid
{
public constructor(init?:Partial<SwaggerMultiApiResponseTest>) { Object.assign(this, init); }
public createResponse() {}
public getTypeName() { return 'SwaggerMultiApiResponseTest'; }
}
// @Route("/defaultview/class")
export class DefaultViewAttr
{
public constructor(init?:Partial<DefaultViewAttr>) { Object.assign(this, init); }
}
// @Route("/defaultview/action")
export class DefaultViewActionAttr
{
public constructor(init?:Partial<DefaultViewActionAttr>) { Object.assign(this, init); }
}
// @Route("/dynamically/registered/{Name}")
export class DynamicallyRegistered
{
public constructor(init?:Partial<DynamicallyRegistered>) { Object.assign(this, init); }
public name: string;
}
// @Route("/auth")
// @Route("/auth/{provider}")
// @Route("/authenticate")
// @Route("/authenticate/{provider}")
// @DataContract
export class Authenticate implements IReturn<AuthenticateResponse>, IPost
{
public constructor(init?:Partial<Authenticate>) { Object.assign(this, init); }
// @DataMember(Order=1)
public provider: string;
// @DataMember(Order=2)
public state: string;
// @DataMember(Order=3)
public oauth_token: string;
// @DataMember(Order=4)
public oauth_verifier: string;
// @DataMember(Order=5)
public userName: string;
// @DataMember(Order=6)
public password: string;
// @DataMember(Order=7)
public rememberMe: boolean;
// @DataMember(Order=8)
public continue: string;
// @DataMember(Order=9)
public errorView: string;
// @DataMember(Order=10)
public nonce: string;
// @DataMember(Order=11)
public uri: string;
// @DataMember(Order=12)
public response: string;
// @DataMember(Order=13)
public qop: string;
// @DataMember(Order=14)
public nc: string;
// @DataMember(Order=15)
public cnonce: string;
// @DataMember(Order=16)
public useTokenCookie: boolean;
// @DataMember(Order=17)
public accessToken: string;
// @DataMember(Order=18)
public accessTokenSecret: string;
// @DataMember(Order=19)
public meta: { [index:string]: string; };
public createResponse() { return new AuthenticateResponse(); }
public getTypeName() { return 'Authenticate'; }
}
// @Route("/assignroles")
// @DataContract
export class AssignRoles implements IReturn<AssignRolesResponse>, IPost
{
public constructor(init?:Partial<AssignRoles>) { Object.assign(this, init); }
// @DataMember(Order=1)
public userName: string;
// @DataMember(Order=2)
public permissions: string[];
// @DataMember(Order=3)
public roles: string[];
public createResponse() { return new AssignRolesResponse(); }
public getTypeName() { return 'AssignRoles'; }
}
// @Route("/unassignroles")
// @DataContract
export class UnAssignRoles implements IReturn<UnAssignRolesResponse>, IPost
{
public constructor(init?:Partial<UnAssignRoles>) { Object.assign(this, init); }
// @DataMember(Order=1)
public userName: string;
// @DataMember(Order=2)
public permissions: string[];
// @DataMember(Order=3)
public roles: string[];
public createResponse() { return new UnAssignRolesResponse(); }
public getTypeName() { return 'UnAssignRoles'; }
}
// @Route("/session-to-token")
// @DataContract
export class ConvertSessionToToken implements IReturn<ConvertSessionToTokenResponse>, IPost
{
public constructor(init?:Partial<ConvertSessionToToken>) { Object.assign(this, init); }
// @DataMember(Order=1)
public preserveSession: boolean;
public createResponse() { return new ConvertSessionToTokenResponse(); }
public getTypeName() { return 'ConvertSessionToToken'; }
}
// @Route("/access-token")
// @DataContract
export class GetAccessToken implements IReturn<GetAccessTokenResponse>, IPost
{
public constructor(init?:Partial<GetAccessToken>) { Object.assign(this, init); }
// @DataMember(Order=1)
public refreshToken: string;
public createResponse() { return new GetAccessTokenResponse(); }
public getTypeName() { return 'GetAccessToken'; }
}
// @Route("/apikeys")
// @Route("/apikeys/{Environment}")
// @DataContract
export class GetApiKeys implements IReturn<GetApiKeysResponse>, IGet
{
public constructor(init?:Partial<GetApiKeys>) { Object.assign(this, init); }
// @DataMember(Order=1)
public environment: string;
public createResponse() { return new GetApiKeysResponse(); }
public getTypeName() { return 'GetApiKeys'; }
}
// @Route("/apikeys/regenerate")
// @Route("/apikeys/regenerate/{Environment}")
// @DataContract
export class RegenerateApiKeys implements IReturn<RegenerateApiKeysResponse>, IPost
{
public constructor(init?:Partial<RegenerateApiKeys>) { Object.assign(this, init); }
// @DataMember(Order=1)
public environment: string;
public createResponse() { return new RegenerateApiKeysResponse(); }
public getTypeName() { return 'RegenerateApiKeys'; }
}
// @Route("/register")
// @DataContract
export class Register implements IReturn<RegisterResponse>, IPost
{
public constructor(init?:Partial<Register>) { Object.assign(this, init); }
// @DataMember(Order=1)
public userName: string;
// @DataMember(Order=2)
public firstName: string;
// @DataMember(Order=3)
public lastName: string;
// @DataMember(Order=4)
public displayName: string;
// @DataMember(Order=5)
public email: string;
// @DataMember(Order=6)
public password: string;
// @DataMember(Order=7)
public confirmPassword: string;
// @DataMember(Order=8)
public autoLogin: boolean;
// @DataMember(Order=9)
public continue: string;
// @DataMember(Order=10)
public errorView: string;
public createResponse() { return new RegisterResponse(); }
public getTypeName() { return 'Register'; }
}
// @Route("/pgsql/rockstars")
export class QueryPostgresRockstars extends QueryDb_1<Rockstar> implements IReturn<QueryResponse<Rockstar>>
{
public constructor(init?:Partial<QueryPostgresRockstars>) { super(init); Object.assign(this, init); }
public age: number;
public createResponse() { return new QueryResponse<Rockstar>(); }
public getTypeName() { return 'QueryPostgresRockstars'; }
}
// @Route("/pgsql/pgrockstars")
export class QueryPostgresPgRockstars extends QueryDb_1<PgRockstar> implements IReturn<QueryResponse<PgRockstar>>
{
public constructor(init?:Partial<QueryPostgresPgRockstars>) { super(init); Object.assign(this, init); }
public age: number;
public createResponse() { return new QueryResponse<PgRockstar>(); }
public getTypeName() { return 'QueryPostgresPgRockstars'; }
}
export class QueryRockstarsConventions extends QueryDb_1<Rockstar> implements IReturn<QueryResponse<Rockstar>>
{
public constructor(init?:Partial<QueryRockstarsConventions>) { super(init); Object.assign(this, init); }
public ids: number[];
public ageOlderThan: number;
public ageGreaterThanOrEqualTo: number;
public ageGreaterThan: number;
public greaterThanAge: number;
public firstNameStartsWith: string;
public lastNameEndsWith: string;
public lastNameContains: string;
public rockstarAlbumNameContains: string;
public rockstarIdAfter: number;
public rockstarIdOnOrAfter: number;
public createResponse() { return new QueryResponse<Rockstar>(); }
public getTypeName() { return 'QueryRockstarsConventions'; }
}
// @AutoQueryViewer(Description="Use this option to search for Rockstars!", Title="Search for Rockstars")
export class QueryCustomRockstars extends QueryDb_2<Rockstar, CustomRockstar> implements IReturn<QueryResponse<CustomRockstar>>
{
public constructor(init?:Partial<QueryCustomRockstars>) { super(init); Object.assign(this, init); }
public age: number;
public createResponse() { return new QueryResponse<CustomRockstar>(); }
public getTypeName() { return 'QueryCustomRockstars'; }
}
// @Route("/customrockstars")
export class QueryRockstarAlbums extends QueryDb_2<Rockstar, CustomRockstar> implements IReturn<QueryResponse<CustomRockstar>>
{
public constructor(init?:Partial<QueryRockstarAlbums>) { super(init); Object.assign(this, init); }
public age: number;
public rockstarAlbumName: string;
public createResponse() { return new QueryResponse<CustomRockstar>(); }
public getTypeName() { return 'QueryRockstarAlbums'; }
}
export class QueryRockstarAlbumsImplicit extends QueryDb_2<Rockstar, CustomRockstar> implements IReturn<QueryResponse<CustomRockstar>>
{
public constructor(init?:Partial<QueryRockstarAlbumsImplicit>) { super(init); Object.assign(this, init); }
public createResponse() { return new QueryResponse<CustomRockstar>(); }
public getTypeName() { return 'QueryRockstarAlbumsImplicit'; }
}
export class QueryRockstarAlbumsLeftJoin extends QueryDb_2<Rockstar, CustomRockstar> implements IReturn<QueryResponse<CustomRockstar>>
{
public constructor(init?:Partial<QueryRockstarAlbumsLeftJoin>) { super(init); Object.assign(this, init); }
public age: number;
public albumName: string;
public createResponse() { return new QueryResponse<CustomRockstar>(); }
public getTypeName() { return 'QueryRockstarAlbumsLeftJoin'; }
}
export class QueryOverridedRockstars extends QueryDb_1<Rockstar> implements IReturn<QueryResponse<Rockstar>>
{
public constructor(init?:Partial<QueryOverridedRockstars>) { super(init); Object.assign(this, init); }
public age: number;
public createResponse() { return new QueryResponse<Rockstar>(); }
public getTypeName() { return 'QueryOverridedRockstars'; }
}
export class QueryOverridedCustomRockstars extends QueryDb_2<Rockstar, CustomRockstar> implements IReturn<QueryResponse<CustomRockstar>>
{
public constructor(init?:Partial<QueryOverridedCustomRockstars>) { super(init); Object.assign(this, init); }
public age: number;
public createResponse() { return new QueryResponse<CustomRockstar>(); }
public getTypeName() { return 'QueryOverridedCustomRockstars'; }
}
// @Route("/query-custom/rockstars")
export class QueryFieldRockstars extends QueryDb_1<Rockstar> implements IReturn<QueryResponse<Rockstar>>
{
public constructor(init?:Partial<QueryFieldRockstars>) { super(init); Object.assign(this, init); }
public firstName: string;
public firstNames: string[];
public age: number;
public firstNameCaseInsensitive: string;
public firstNameStartsWith: string;
public lastNameEndsWith: string;
public firstNameBetween: string[];
public orLastName: string;
public firstNameContainsMulti: string[];
public createResponse() { return new QueryResponse<Rockstar>(); }
public getTypeName() { return 'QueryFieldRockstars'; }
}
export class QueryFieldRockstarsDynamic extends QueryDb_1<Rockstar> implements IReturn<QueryResponse<Rockstar>>
{
public constructor(init?:Partial<QueryFieldRockstarsDynamic>) { super(init); Object.assign(this, init); }
public age: number;
public createResponse() { return new QueryResponse<Rockstar>(); }
public getTypeName() { return 'QueryFieldRockstarsDynamic'; }
}
export class QueryRockstarsFilter extends QueryDb_1<Rockstar> implements IReturn<QueryResponse<Rockstar>>
{
public constructor(init?:Partial<QueryRockstarsFilter>) { super(init); Object.assign(this, init); }
public age: number;
public createResponse() { return new QueryResponse<Rockstar>(); }
public getTypeName() { return 'QueryRockstarsFilter'; }
}
export class QueryCustomRockstarsFilter extends QueryDb_2<Rockstar, CustomRockstar> implements IReturn<QueryResponse<CustomRockstar>>
{
public constructor(init?:Partial<QueryCustomRockstarsFilter>) { super(init); Object.assign(this, init); }
public age: number;
public createResponse() { return new QueryResponse<CustomRockstar>(); }
public getTypeName() { return 'QueryCustomRockstarsFilter'; }
}
export class QueryRockstarsIFilter extends QueryDb_1<Rockstar> implements IReturn<QueryResponse<Rockstar>>, IFilterRockstars
{
public constructor(init?:Partial<QueryRockstarsIFilter>) { super(init); Object.assign(this, init); }
public age: number;
public createResponse() { return new QueryResponse<Rockstar>(); }
public getTypeName() { return 'QueryRockstarsIFilter'; }
}
// @Route("/OrRockstars")
export class QueryOrRockstars extends QueryDb_1<Rockstar> implements IReturn<QueryResponse<Rockstar>>
{
public constructor(init?:Partial<QueryOrRockstars>) { super(init); Object.assign(this, init); }
public age: number;
public firstName: string;
public createResponse() { return new QueryResponse<Rockstar>(); }
public getTypeName() { return 'QueryOrRockstars'; }
}
export class QueryGetRockstars extends QueryDb_1<Rockstar> implements IReturn<QueryResponse<Rockstar>>
{
public constructor(init?:Partial<QueryGetRockstars>) { super(init); Object.assign(this, init); }
public ids: number[];
public ages: number[];
public firstNames: string[];
public idsBetween: number[];
public createResponse() { return new QueryResponse<Rockstar>(); }
public getTypeName() { return 'QueryGetRockstars'; }
}
export class QueryGetRockstarsDynamic extends QueryDb_1<Rockstar> implements IReturn<QueryResponse<Rockstar>>
{
public constructor(init?:Partial<QueryGetRockstarsDynamic>) { super(init); Object.assign(this, init); }
public createResponse() { return new QueryResponse<Rockstar>(); }
public getTypeName() { return 'QueryGetRockstarsDynamic'; }
}
// @Route("/movies/search")
export class SearchMovies extends QueryDb_1<Movie> implements IReturn<QueryResponse<Movie>>
{
public constructor(init?:Partial<SearchMovies>) { super(init); Object.assign(this, init); }
public createResponse() { return new QueryResponse<Movie>(); }
public getTypeName() { return 'SearchMovies'; }
}
// @Route("/movies")
export class QueryMovies extends QueryDb_1<Movie> implements IReturn<QueryResponse<Movie>>
{
public constructor(init?:Partial<QueryMovies>) { super(init); Object.assign(this, init); }
public ids: number[];
public imdbIds: string[];
public ratings: string[];
public createResponse() { return new QueryResponse<Movie>(); }
public getTypeName() { return 'QueryMovies'; }
}
export class StreamMovies extends QueryDb_1<Movie> implements IReturn<QueryResponse<Movie>>
{
public constructor(init?:Partial<StreamMovies>) { super(init); Object.assign(this, init); }
public ratings: string[];
public createResponse() { return new QueryResponse<Movie>(); }
public getTypeName() { return 'StreamMovies'; }
}
export class QueryUnknownRockstars extends QueryDb_1<Rockstar> implements IReturn<QueryResponse<Rockstar>>
{
public constructor(init?:Partial<QueryUnknownRockstars>) { super(init); Object.assign(this, init); }
public unknownInt: number;
public unknownProperty: string;
public createResponse() { return new QueryResponse<Rockstar>(); }
public getTypeName() { return 'QueryUnknownRockstars'; }
}
// @Route("/query/rockstar-references")
export class QueryRockstarsWithReferences extends QueryDb_1<RockstarReference> implements IReturn<QueryResponse<RockstarReference>>
{
public constructor(init?:Partial<QueryRockstarsWithReferences>) { super(init); Object.assign(this, init); }
public age: number;
public createResponse() { return new QueryResponse<RockstarReference>(); }
public getTypeName() { return 'QueryRockstarsWithReferences'; }
}
export class QueryPocoBase extends QueryDb_1<OnlyDefinedInGenericType> implements IReturn<QueryResponse<OnlyDefinedInGenericType>>
{
public constructor(init?:Partial<QueryPocoBase>) { super(init); Object.assign(this, init); }
public id: number;
public createResponse() { return new QueryResponse<OnlyDefinedInGenericType>(); }
public getTypeName() { return 'QueryPocoBase'; }
}
export class QueryPocoIntoBase extends QueryDb_2<OnlyDefinedInGenericTypeFrom, OnlyDefinedInGenericTypeInto> implements IReturn<QueryResponse<OnlyDefinedInGenericTypeInto>>
{
public constructor(init?:Partial<QueryPocoIntoBase>) { super(init); Object.assign(this, init); }
public id: number;
public createResponse() { return new QueryResponse<OnlyDefinedInGenericTypeInto>(); }
public getTypeName() { return 'QueryPocoIntoBase'; }
}
// @Route("/query/alltypes")
export class QueryAllTypes extends QueryDb_1<AllTypes> implements IReturn<QueryResponse<AllTypes>>
{
public constructor(init?:Partial<QueryAllTypes>) { super(init); Object.assign(this, init); }
public createResponse() { return new QueryResponse<AllTypes>(); }
public getTypeName() { return 'QueryAllTypes'; }
}
// @Route("/querydata/rockstars")
export class QueryDataRockstars extends QueryData<Rockstar> implements IReturn<QueryResponse<Rockstar>>
{
public constructor(init?:Partial<QueryDataRockstars>) { super(init); Object.assign(this, init); }
public age: number;
public createResponse() { return new QueryResponse<Rockstar>(); }
public getTypeName() { return 'QueryDataRockstars'; }
} | the_stack |
import { Syntax, Visitor, eqSourceLocation, nullLoc, eqEndPosition, compEndPosition,
findSourceLocation } from './javascript';
import { sourceAsJavaScriptExpression } from './parser';
import { JSVal } from './model';
import { getOptions } from './options';
declare const console: { log: (s: string) => void };
class Scope {
bindings: Array<[string, any, 'let' | 'const']>;
parent: Scope | null;
constructor (parent: Scope | null = null) {
this.bindings = [];
this.parent = parent;
}
define (name: string, val: any, kind: 'let' | 'const'): void {
if (this.bindings.some(([n]) => n === name)) {
throw new SyntaxError(`Identifier '${name}' has already been declared`);
}
this.bindings.push([name, val, kind]);
}
lookup (name: string): any {
const idx = this.bindings.findIndex(([n]) => n === name);
if (idx >= 0) {
return this.bindings[idx][1];
} else if (this.parent) {
return this.parent.lookup(name);
} else {
throw new ReferenceError(`${name} is not defined`);
}
}
assign (name: string, val: any): void {
const idx = this.bindings.findIndex(([n]) => n === name);
if (idx >= 0) {
if (this.bindings[idx][2] === 'const') {
throw new TypeError('Assignment to constant variable.');
}
this.bindings[idx][1] = val;
} else if (this.parent) {
this.parent.assign(name, val);
} else {
throw new ReferenceError(`ReferenceError: ${name} is not defined`);
}
}
asArray (): Array<Array<[string, any]>> {
const bindings: Array<[string, any]> = this.bindings.map(([name, val]): [string, any] => [name, val]);
return this.parent ? [bindings].concat(this.parent.asArray()) : [bindings];
}
}
function globalScope (): Scope {
const scope = new Scope();
scope.define('Object', Object, 'const');
scope.define('Function', Function, 'const');
scope.define('Array', Array, 'const');
scope.define('String', String, 'const');
scope.define('console', console, 'let');
scope.define('parseInt', parseInt, 'const');
scope.define('Math', Math, 'const');
scope.define('Number', Number, 'const');
scope.define('alert', console.log, 'let');
scope.define('assert', function assert (p: any) { if (!p) throw new Error('assertion failed'); }, 'const');
scope.define('spec', function spec (f: any, id: any, req: any, ens: any) {
if (f._mapping) {
f._mapping[id] = [req, ens];
return f;
} else {
const mapping = { [id]: [req, ens] };
const wrapped: any = function (this: any, ...args: any[]) {
return Object.values(mapping).reduceRight(function (cont, [req, ens]) {
return function (this: any, ...args2: any[]) {
const args3 = req.apply(this, args2);
return ens.apply(this, args3.concat([cont.apply(this, args3)]));
};
}, f).apply(this, args);
};
wrapped._mapping = mapping;
wrapped._orig = f;
return wrapped;
}
}, 'const');
return scope;
}
interface InterpreterFunction extends Function {
scope: Scope;
node: Syntax.Function;
}
function isInterpreterFunction (f: any): f is InterpreterFunction {
return typeof f === 'function' && 'scope' in f && 'node' in f;
}
interface SpecWrappedFunction extends Function {
_mapping: { [id: number]: [InterpreterFunction, InterpreterFunction] };
_orig: Function;
}
function isSpecWrappedFunction (f: any): f is SpecWrappedFunction {
return typeof f === 'function' && '_mapping' in f;
}
enum StepResult { NOP, STEP, DONE, SET }
abstract class BaseStackFrame {
scope: Scope;
pc: Syntax.Expression | Syntax.Statement | null;
operandStack: Array<any>;
iteration: number;
constructor (scope: Scope) {
this.scope = scope;
this.pc = null;
this.operandStack = [];
this.iteration = 0;
}
define (name: string, val: any, kind: 'let' | 'const'): void {
this.scope.define(name, val, kind);
}
lookup (name: string): any {
return this.scope.lookup(name);
}
assign (name: string, val: any): void {
this.scope.assign(name, val);
}
loc (): Syntax.SourceLocation {
if (this.pc === null) return nullLoc();
return this.pc.loc;
}
newBlockScope (): void {
this.scope = new Scope(this.scope);
}
popBlockScope (): void {
if (this.scope.parent === null) throw new Error('no scope to pop');
this.scope = this.scope.parent;
}
scopes (): Array<Array<[string, any]>> {
return this.scope.asArray();
}
nextIteration (): void {
this.iteration++;
}
toString (): string {
return `${this.name()} (${this.loc().file}:${this.loc().start.line}:${this.loc().start.column})`;
}
asTuple (): [string, Syntax.SourceLocation, number] {
return [this.toString(), this.loc(), this.iteration];
}
abstract name (): string;
abstract entry (interpreter: InterpreterVisitor): StepResult;
}
class ProgramStackFrame extends BaseStackFrame {
program: Syntax.Program;
constructor (program: Syntax.Program) {
super(globalScope());
this.program = program;
}
name (): string {
return '<program>';
}
entry (interpreter: InterpreterVisitor): StepResult {
return interpreter.visitProgram(this.program);
}
}
class FunctionStackFrame extends BaseStackFrame {
func: InterpreterFunction;
constructor (func: InterpreterFunction) {
super(new Scope(func.scope));
this.func = func;
}
name (): string {
return this.func.node.id === null ? '<anonymous>' : this.func.node.id.name;
}
entry (interpreter: InterpreterVisitor): StepResult {
const res = interpreter.visitBlockStatement(this.func.node.body);
if (res === StepResult.DONE) {
interpreter.ret(undefined);
}
return StepResult.STEP;
}
}
class SpecStackFrame extends BaseStackFrame {
func: SpecWrappedFunction;
thisArg: any;
args: Array<any>;
preCheckers: Array<InterpreterFunction>;
functionCalled: boolean;
postCheckers: Array<InterpreterFunction>;
constructor (func: SpecWrappedFunction, thisArg: any, args: Array<any>) {
super(new Scope());
this.func = func;
this.thisArg = thisArg;
this.args = args;
this.operandStack.push(args);
this.preCheckers = Object.values(func._mapping).map(([req]) => req);
this.functionCalled = false;
this.postCheckers = Object.values(func._mapping).map(([, ens]) => ens);
}
name (): string {
return `<spec of ${this.func._orig.name || 'anonymous'}>`;
}
entry (interpreter: InterpreterVisitor): StepResult {
const nextPreCheck = this.preCheckers.shift();
if (nextPreCheck !== undefined) {
this.args = this.operandStack.pop();
interpreter.call(nextPreCheck, this.thisArg, this.args);
} else if (!this.functionCalled) {
this.args = this.operandStack.pop();
interpreter.call(this.func._orig, this.thisArg, this.args);
this.functionCalled = true;
} else {
const prevResult = this.operandStack.pop();
const nextPostCheck = this.postCheckers.shift();
if (nextPostCheck !== undefined) {
interpreter.call(nextPostCheck, this.thisArg, this.args.concat([prevResult]));
} else {
interpreter.ret(prevResult);
}
}
return StepResult.STEP;
}
}
class EvaluationStackFrame extends BaseStackFrame {
expression: Syntax.Expression;
constructor (expression: Syntax.Expression, scope: Scope) {
super(new Scope(scope));
this.expression = expression;
}
name (): string {
return '<eval>';
}
entry (interpreter: InterpreterVisitor): StepResult {
return interpreter.visitExpression(this.expression);
}
}
type StackFrame = ProgramStackFrame | FunctionStackFrame | SpecStackFrame | EvaluationStackFrame;
interface MethodCallExpression {
type: 'CallExpression';
callee: Syntax.MemberExpression;
args: Array<Syntax.Expression>;
loc: Syntax.SourceLocation;
}
function isMethodCall (expr: Syntax.CallExpression): expr is MethodCallExpression {
return expr.callee.type === 'MemberExpression';
}
export interface Annotation {
location: Syntax.SourceLocation;
variableName: string;
values: Array<any>;
}
export interface Interpreter {
steps: number;
annotations: Array<Annotation>;
loc (): Syntax.SourceLocation;
iteration (): number;
callstack (): Array<[string, Syntax.SourceLocation, number]>;
scopes (frameIndex: number): Array<Array<[string, any]>>;
goto (pos: Syntax.Position, iteration: number): void;
restart (): void;
canStep (): boolean;
stepInto (): void;
stepOver (): void;
stepOut (): void;
run (): void;
define (name: string, val: any, kind: 'let' | 'const'): void;
eval (source: string, bindings: Array<[string, any]>): any;
evalExpression (expression: Syntax.Expression, bindings: Array<[string, any]>): any;
asValue (val: any): JSVal;
fromValue (val: JSVal): any;
}
class InterpreterVisitor extends Visitor<void, void, StepResult, StepResult> implements Interpreter {
program: Syntax.Program;
steps: number;
annotations: Array<Annotation>;
private stack: Array<StackFrame>;
private breakpoint: [Syntax.SourceLocation, number] | null;
constructor (program: Syntax.Program) {
super();
this.program = program;
this.steps = 0;
this.annotations = [];
this.stack = [new ProgramStackFrame(program)];
this.breakpoint = null;
this.visitProgram(program); // set initial PC
}
// --- Interpreter methods
loc (): Syntax.SourceLocation {
const pc = this.pc();
if (pc === null) return nullLoc();
return pc.loc;
}
iteration (): number {
return this.frame().iteration;
}
callstack (): Array<[string, Syntax.SourceLocation, number]> {
return this.stack.map(frame => frame.asTuple());
}
scopes (frameIndex: number): Array<Array<[string, any]>> {
const idx = Math.max(0, Math.min(this.stack.length - 1, frameIndex));
return this.stack[idx].scopes();
}
restart (): void {
this.reset();
}
canStep (): boolean {
if (this.steps >= getOptions().maxInterpreterSteps) {
return false;
}
if (this.isBreaking()) return false;
return this.stack.length > 0 && this.pc() !== null;
}
goto (pos: Syntax.Position, iteration: number = 0): void {
this.reset();
const loc = findSourceLocation(this.program, pos);
this.breakpoint = [loc, iteration];
this.run();
if (!eqSourceLocation(loc, this.loc()) || iteration !== this.iteration()) {
throw new Error('did not reach breakpoint');
}
}
define (name: string, val: any, kind: 'let' | 'const'): void {
this.frame().define(name, val, kind);
}
eval (source: string, bindings: Array<[string, any]> = []): any {
return this.evalExpression(sourceAsJavaScriptExpression(source), bindings);
}
evalExpression (expression: Syntax.Expression, bindings: Array<[string, any]> = []): any {
this.stack.push(new EvaluationStackFrame(expression, this.frame().scope));
try {
for (const [varname, value] of bindings) {
this.frame().define(varname, value, 'let');
}
while (true) {
const res = this.step();
if (res === StepResult.DONE) {
if (this.steps >= getOptions().maxInterpreterSteps) return undefined;
return this.popOp();
}
}
} finally {
this.stack.pop();
}
}
asValue (val: any): JSVal {
if (typeof val === 'number') {
return { type: 'num', v: val };
} else if (typeof val === 'boolean') {
return { type: 'bool', v: val };
} else if (typeof val === 'string') {
return { type: 'str', v: val };
} else if (val === null) {
return { type: 'null' };
} else if (val === undefined) {
return { type: 'undefined' };
} else if (isInterpreterFunction(val)) {
return {
type: 'fun',
body: {
type: 'FunctionExpression',
body: val.node.body,
ensures: val.node.ensures,
freeVars: val.node.freeVars,
id: val.node.id,
loc: val.node.loc,
params: val.node.params,
requires: val.node.requires
}
};
} else if (isSpecWrappedFunction(val)) {
return this.asValue(val._orig);
} else if (val instanceof Array) {
return { type: 'arr', elems: val.map(e => this.asValue(e)) };
} else if ('_cls_' in val) {
const [cls, ...args] = val._cls_;
return { type: 'obj-cls', cls, args: args.map((a: any) => this.asValue(a)) };
} else if (typeof val === 'object') {
const obj: { [key: string]: JSVal } = {};
Object.keys(val).forEach(key => obj[key] = this.asValue(val[key]));
return { type: 'obj', v: obj };
} else {
const str = String(val);
return { type: 'str', v: `<<${str.length > 30 ? str.substr(0, 27) + '...' : str}>>` };
}
}
fromValue (val: JSVal): any {
switch (val.type) {
case 'num':
case 'bool':
case 'str':
return val.v;
case 'null':
return null;
case 'undefined':
return undefined;
case 'fun':
return this.evalExpression(val.body);
case 'obj':
const obj: { [key: string]: any } = {};
Object.keys(val.v).forEach(key => obj[key] = this.fromValue(val.v[key]));
return obj;
case 'obj-cls':
const constr = this.frame().lookup(val.cls);
const instance = new constr(...val.args.map(arg => this.fromValue(arg)));
instance._cls_ = [constr.name, ...val.args];
return instance;
case 'arr':
return val.elems.map(elem => this.fromValue(elem));
}
}
// --- other methods
annotate (loc: Syntax.SourceLocation, variableName: string, value: any): any {
// find index of annotation
const idx = this.annotations.findIndex(({ location }) => eqEndPosition(loc, location));
if (idx >= 0) {
this.annotations[idx].values.push(value);
} else {
// no such annotation yet
// find index of first annotation that is not earlier
const idx = this.annotations.findIndex(({ location }) => !compEndPosition(loc, location));
const annotation = { location: loc, variableName, values: [value] };
if (idx >= 0) {
this.annotations.splice(idx, 0, annotation);
} else {
// no annotation found that are later, so append
this.annotations.push(annotation);
}
}
}
frame (): StackFrame {
return this.stack[this.stack.length - 1];
}
pc (): Syntax.Expression | Syntax.Statement | null {
return this.frame().pc;
}
setPC (pc: Syntax.Expression | Syntax.Statement | null): void {
this.frame().pc = pc;
}
seeking (): boolean {
return this.frame().pc === null;
}
clearPC (): void {
this.frame().pc = null;
}
pushOp (x: any): void {
this.frame().operandStack.push(x);
}
popOp (): any {
return this.frame().operandStack.pop();
}
call (callee: any, thisArg: any, args: Array<any>): void {
if (isSpecWrappedFunction(callee)) {
const prevPC = this.pc();
const newFrame = new SpecStackFrame(callee, thisArg, args);
this.stack.push(newFrame);
this.setPC(prevPC);
} else if (isInterpreterFunction(callee)) {
const newFrame = new FunctionStackFrame(callee);
newFrame.define('this', thisArg, 'const');
for (let i = 0; i < callee.node.params.length; i++) {
const argVal = i < args.length ? args[i] : undefined;
newFrame.define(callee.node.params[i].name, argVal, 'let');
}
this.stack.push(newFrame);
this.visitBlockStatement(callee.node.body);
} else if (callee instanceof Function) {
const calleeFunction: Function = callee;
this.pushOp(calleeFunction.apply(thisArg, args));
} else {
throw new TypeError('is not a function');
}
}
ret (retValue: any): void {
if (this.stack.length < 2) {
throw new SyntaxError('Illegal return statement');
}
this.stack.pop();
this.pushOp(retValue);
}
closure (func: Syntax.Function): InterpreterFunction {
const interpreter = this;
const f: any = function (this: any, ...args: any[]): any {
interpreter.call(f, this, args);
return interpreter.stepOut();
};
f.node = func;
f.scope = this.frame().scope;
return f;
}
// ---- Interpreter does not evaluate assertions ----
visitIdentifierTerm (term: Syntax.Identifier): void {
throw new Error('Method not implemented.');
}
visitOldIdentifierTerm (term: Syntax.OldIdentifier): void {
throw new Error('Method not implemented.');
}
visitLiteralTerm (term: Syntax.Literal): void {
throw new Error('Method not implemented.');
}
visitUnaryTerm (term: Syntax.UnaryTerm): void {
throw new Error('Method not implemented.');
}
visitBinaryTerm (term: Syntax.BinaryTerm): void {
throw new Error('Method not implemented.');
}
visitLogicalTerm (term: Syntax.LogicalTerm): void {
throw new Error('Method not implemented.');
}
visitConditionalTerm (term: Syntax.ConditionalTerm): void {
throw new Error('Method not implemented.');
}
visitCallTerm (term: Syntax.CallTerm): void {
throw new Error('Method not implemented.');
}
visitMemberTerm (term: Syntax.MemberTerm): void {
throw new Error('Method not implemented.');
}
visitIsIntegerTerm (term: Syntax.IsIntegerTerm): void {
throw new Error('Method not implemented.');
}
visitToIntegerTerm (term: Syntax.ToIntegerTerm): void {
throw new Error('Method not implemented.');
}
visitTermAssertion (assertion: Syntax.Term): void {
throw new Error('Method not implemented.');
}
visitPureAssertion (assertion: Syntax.PureAssertion): void {
throw new Error('Method not implemented.');
}
visitSpecAssertion (assertion: Syntax.SpecAssertion): void {
throw new Error('Method not implemented.');
}
visitEveryAssertion (assertion: Syntax.EveryAssertion): void {
throw new Error('Method not implemented.');
}
visitInstanceOfAssertion (assertion: Syntax.InstanceOfAssertion): void {
throw new Error('Method not implemented.');
}
visitInAssertion (assertion: Syntax.InAssertion): void {
throw new Error('Method not implemented.');
}
visitUnaryAssertion (assertion: Syntax.UnaryAssertion): void {
throw new Error('Method not implemented.');
}
visitBinaryAssertion (assertion: Syntax.BinaryAssertion): void {
throw new Error('Method not implemented.');
}
// ---- Evaluation of expressions and statements ----
visitIdentifier (expr: Syntax.Identifier): StepResult {
if (this.seeking()) {
this.setPC(expr);
return StepResult.SET;
} else if (this.pc() === expr) {
this.pushOp(this.frame().lookup(expr.name));
this.clearPC();
return StepResult.DONE;
} else {
return StepResult.NOP;
}
}
visitLiteral (expr: Syntax.Literal): StepResult {
if (this.seeking()) {
this.setPC(expr);
return StepResult.SET;
} else if (this.pc() === expr) {
this.pushOp(expr.value);
this.clearPC();
return StepResult.DONE;
} else {
return StepResult.NOP;
}
}
visitUnaryExpression (expr: Syntax.UnaryExpression): StepResult {
if (this.seeking()) {
return this.visitExpression(expr.argument);
} else if (this.pc() === expr) {
const arg = this.popOp();
switch (expr.operator) {
case '-':
this.pushOp(-arg);
break;
case '+':
this.pushOp(+arg);
break;
case '!':
this.pushOp(!arg);
break;
case '~':
this.pushOp(~arg);
break;
case 'typeof':
this.pushOp(typeof arg);
break;
case 'void':
this.pushOp(void(0));
break;
}
this.clearPC();
return StepResult.DONE;
} else {
const argRes = this.visitExpression(expr.argument);
if (argRes === StepResult.DONE) {
this.setPC(expr);
return StepResult.STEP;
} else {
return argRes;
}
}
}
visitBinaryExpression (expr: Syntax.BinaryExpression): StepResult {
if (this.seeking()) {
return this.visitExpression(expr.left);
} else if (this.pc() === expr) {
const rightArg = this.popOp();
const leftArg = this.popOp();
switch (expr.operator) {
case '===':
this.pushOp(leftArg === rightArg);
break;
case '!==':
this.pushOp(leftArg !== rightArg);
break;
case '<':
this.pushOp(leftArg < rightArg);
break;
case '<=':
this.pushOp(leftArg <= rightArg);
break;
case '>':
this.pushOp(leftArg > rightArg);
break;
case '>=':
this.pushOp(leftArg >= rightArg);
break;
case '<<':
this.pushOp(leftArg << rightArg);
break;
case '>>':
this.pushOp(leftArg >> rightArg);
break;
case '>>>':
this.pushOp(leftArg >>> rightArg);
break;
case '+':
this.pushOp(leftArg + rightArg);
break;
case '-':
this.pushOp(leftArg - rightArg);
break;
case '*':
this.pushOp(leftArg * rightArg);
break;
case '/':
this.pushOp(leftArg / rightArg);
break;
case '%':
this.pushOp(leftArg % rightArg);
break;
case '|':
this.pushOp(leftArg | rightArg);
break;
case '^':
this.pushOp(leftArg ^ rightArg);
break;
case '&':
this.pushOp(leftArg & rightArg);
break;
}
this.clearPC();
return StepResult.DONE;
} else {
const leftRes = this.visitExpression(expr.left);
if (leftRes === StepResult.NOP) {
const rightRes = this.visitExpression(expr.right);
if (rightRes === StepResult.DONE) {
this.setPC(expr);
return StepResult.STEP;
} else {
return rightRes;
}
} else if (leftRes === StepResult.STEP) {
return StepResult.STEP;
} else {
this.visitExpression(expr.right);
return StepResult.STEP;
}
}
}
visitLogicalExpression (expr: Syntax.LogicalExpression): StepResult {
if (this.seeking()) {
return this.visitExpression(expr.left);
} else {
const leftRes = this.visitExpression(expr.left);
if (leftRes === StepResult.NOP) {
const rightRes = this.visitExpression(expr.right);
if (rightRes === StepResult.DONE) {
return StepResult.DONE;
} else {
return rightRes;
}
} else if (leftRes === StepResult.STEP) {
return StepResult.STEP;
} else {
const leftArg = this.popOp();
if (expr.operator === '&&') {
if (leftArg) {
this.visitExpression(expr.right);
return StepResult.STEP;
} else {
this.pushOp(leftArg);
return StepResult.DONE;
}
} else {
if (leftArg) {
this.pushOp(leftArg);
return StepResult.DONE;
} else {
this.visitExpression(expr.right);
return StepResult.STEP;
}
}
}
}
}
visitConditionalExpression (expr: Syntax.ConditionalExpression): StepResult {
if (this.seeking()) {
return this.visitExpression(expr.test);
} else {
const testRes = this.visitExpression(expr.test);
if (testRes === StepResult.NOP) {
const consequentRes = this.visitExpression(expr.consequent);
if (consequentRes === StepResult.NOP) {
return this.visitExpression(expr.alternate);
} else {
return consequentRes;
}
} else if (testRes === StepResult.STEP) {
return StepResult.STEP;
} else { // testRes === DONE
const testArg = this.popOp();
if (testArg) {
this.visitExpression(expr.consequent);
return StepResult.STEP;
} else {
this.visitExpression(expr.alternate);
return StepResult.STEP;
}
}
}
}
visitAssignmentExpression (expr: Syntax.AssignmentExpression): StepResult {
if (expr.left.type === 'Identifier') {
if (this.seeking()) {
return this.visitExpression(expr.right);
} else {
if (this.pc() === expr) {
const rightArg = this.popOp();
this.frame().assign(expr.left.name, rightArg);
this.pushOp(rightArg);
this.clearPC();
return StepResult.DONE;
} else {
const rightRes = this.visitExpression(expr.right);
if (rightRes === StepResult.DONE) {
this.setPC(expr);
return StepResult.STEP;
} else {
return rightRes;
}
}
}
} else {
if (this.seeking()) {
return this.visitExpression(expr.left.object);
} else {
if (this.pc() === expr) {
const rightArg = this.popOp();
const propertyArg = this.popOp();
const objectArg = this.popOp();
objectArg[propertyArg] = rightArg;
this.pushOp(rightArg);
this.clearPC();
return StepResult.DONE;
} else {
const objectRes = this.visitExpression(expr.left.object);
if (objectRes === StepResult.NOP) {
const propertyRes = this.visitExpression(expr.left.property);
if (propertyRes === StepResult.NOP) {
const rightRes = this.visitExpression(expr.right);
if (rightRes === StepResult.DONE) {
this.setPC(expr);
return StepResult.STEP;
} else {
return rightRes;
}
} else if (propertyRes === StepResult.STEP) {
return StepResult.STEP;
} else {
this.visitExpression(expr.right);
return StepResult.STEP;
}
} else if (objectRes === StepResult.STEP) {
return StepResult.STEP;
} else {
this.visitExpression(expr.left.property);
return StepResult.STEP;
}
}
}
}
}
visitSequenceExpression (expr: Syntax.SequenceExpression): StepResult {
if (expr.expressions.length < 1) throw new Error('empty SequenceExpression');
if (this.seeking()) {
return this.visitExpression(expr.expressions[0]);
} else {
for (let i = 0; i < expr.expressions.length; i++) {
const res = this.visitExpression(expr.expressions[i]);
if (res === StepResult.STEP) {
return StepResult.STEP;
} else if (res === StepResult.DONE) {
if (i < expr.expressions.length - 1) {
this.popOp();
this.visitExpression(expr.expressions[i + 1]);
return StepResult.STEP;
} else {
return StepResult.DONE;
}
}
}
return StepResult.NOP;
}
}
visitMethodCallExpression (expr: MethodCallExpression): StepResult {
if (this.seeking()) {
return this.visitExpression(expr.callee.object);
} else if (this.pc() === expr) {
this.clearPC();
return StepResult.DONE;
} else {
const objectRes = this.visitExpression(expr.callee.object);
if (objectRes === StepResult.STEP) {
return StepResult.STEP;
} else if (objectRes === StepResult.DONE) {
this.visitExpression(expr.callee.property);
return StepResult.STEP;
} else { // objectRes is NOP
const propertyRes = this.visitExpression(expr.callee.property);
if (propertyRes === StepResult.STEP) {
return StepResult.STEP;
} else if (propertyRes === StepResult.DONE) {
if (expr.args.length > 0) {
this.visitExpression(expr.args[0]);
} else {
this.setPC(expr);
const prop = this.popOp();
const object = this.popOp();
this.call(object[prop], object, []);
}
return StepResult.STEP;
} else { // propertyRes is NOP
for (let i = 0; i < expr.args.length; i++) {
const argRes = this.visitExpression(expr.args[i]);
if (argRes === StepResult.STEP) {
return StepResult.STEP;
} else if (argRes === StepResult.DONE) {
if (i < expr.args.length - 1) {
this.visitExpression(expr.args[i + 1]);
} else {
this.setPC(expr);
const args = [];
for (let i = 0; i < expr.args.length; i++) {
args.unshift(this.popOp());
}
const prop = this.popOp();
const object = this.popOp();
this.call(object[prop], object, args);
}
return StepResult.STEP;
}
}
return StepResult.NOP;
}
}
}
}
visitCallExpression (expr: Syntax.CallExpression): StepResult {
if (isMethodCall(expr)) {
return this.visitMethodCallExpression(expr);
} else if (this.seeking()) {
return this.visitExpression(expr.callee);
} else if (this.pc() === expr) {
this.clearPC();
return StepResult.DONE;
} else {
const calleeRes = this.visitExpression(expr.callee);
if (calleeRes === StepResult.STEP) {
return StepResult.STEP;
} else if (calleeRes === StepResult.DONE) {
if (expr.args.length > 0) {
this.visitExpression(expr.args[0]);
} else {
this.setPC(expr);
this.call(this.popOp(), undefined, []);
}
return StepResult.STEP;
} else { // calleeRes is NOP
for (let i = 0; i < expr.args.length; i++) {
const argRes = this.visitExpression(expr.args[i]);
if (argRes === StepResult.STEP) {
return StepResult.STEP;
} else if (argRes === StepResult.DONE) {
if (i < expr.args.length - 1) {
this.visitExpression(expr.args[i + 1]);
} else {
this.setPC(expr);
const args = [];
for (let i = 0; i < expr.args.length; i++) {
args.unshift(this.popOp());
}
this.call(this.popOp(), undefined, args);
}
return StepResult.STEP;
}
}
return StepResult.NOP;
}
}
}
visitNewExpression (expr: Syntax.NewExpression): StepResult {
if (this.seeking()) {
return this.visitExpression(expr.callee);
} else if (this.pc() === expr) {
const args = [];
for (let i = 0; i < expr.args.length; i++) {
args.unshift(this.popOp());
}
const constr = this.popOp();
const instance = new constr(...args);
instance._cls_ = [constr.name, ...args];
this.pushOp(instance);
this.clearPC();
return StepResult.DONE;
} else {
const calleeRes = this.visitExpression(expr.callee);
if (calleeRes === StepResult.STEP) {
return StepResult.STEP;
} else if (calleeRes === StepResult.DONE) {
if (expr.args.length > 0) {
this.visitExpression(expr.args[0]);
} else {
this.setPC(expr);
}
return StepResult.STEP;
} else { // calleeRes is NOP
for (let i = 0; i < expr.args.length; i++) {
const argRes = this.visitExpression(expr.args[i]);
if (argRes === StepResult.STEP) {
return StepResult.STEP;
} else if (argRes === StepResult.DONE) {
if (i < expr.args.length - 1) {
this.visitExpression(expr.args[i + 1]);
} else {
this.setPC(expr);
}
return StepResult.STEP;
}
}
return StepResult.NOP;
}
}
}
visitArrayExpression (expr: Syntax.ArrayExpression): StepResult {
if (this.seeking()) {
if (expr.elements.length > 0) {
return this.visitExpression(expr.elements[0]);
} else {
this.setPC(expr);
return StepResult.SET;
}
} else if (this.pc() === expr) {
const array = [];
for (let i = 0; i < expr.elements.length; i++) {
array.unshift(this.popOp());
}
this.pushOp(array);
this.clearPC();
return StepResult.DONE;
} else {
for (let i = 0; i < expr.elements.length; i++) {
const elementRes = this.visitExpression(expr.elements[i]);
if (elementRes === StepResult.STEP) {
return StepResult.STEP;
} else if (elementRes === StepResult.DONE) {
if (i < expr.elements.length - 1) {
this.visitExpression(expr.elements[i + 1]);
} else {
this.setPC(expr);
}
return StepResult.STEP;
}
}
return StepResult.NOP;
}
}
visitObjectExpression (expr: Syntax.ObjectExpression): StepResult {
if (this.seeking()) {
if (expr.properties.length > 0) {
return this.visitExpression(expr.properties[0].value);
} else {
this.setPC(expr);
return StepResult.SET;
}
} else if (this.pc() === expr) {
const object: { [key: string]: any } = {};
const propValues = [];
for (let i = 0; i < expr.properties.length; i++) {
propValues.unshift(this.popOp());
}
for (let i = 0; i < expr.properties.length; i++) {
const { key } = expr.properties[i];
object[key] = propValues[i];
}
this.pushOp(object);
this.clearPC();
return StepResult.DONE;
} else {
for (let i = 0; i < expr.properties.length; i++) {
const elementRes = this.visitExpression(expr.properties[i].value);
if (elementRes === StepResult.STEP) {
return StepResult.STEP;
} else if (elementRes === StepResult.DONE) {
if (i < expr.properties.length - 1) {
this.visitExpression(expr.properties[i + 1].value);
} else {
this.setPC(expr);
}
return StepResult.STEP;
}
}
return StepResult.NOP;
}
}
visitInstanceOfExpression (expr: Syntax.InstanceOfExpression): StepResult {
if (this.seeking()) {
return this.visitExpression(expr.left);
} else if (this.pc() === expr) {
const rightArg = this.popOp();
const leftArg = this.popOp();
this.pushOp(leftArg instanceof rightArg);
this.clearPC();
return StepResult.DONE;
} else {
const leftRes = this.visitExpression(expr.left);
if (leftRes === StepResult.NOP) {
const rightRes = this.visitExpression(expr.right);
if (rightRes === StepResult.DONE) {
this.setPC(expr);
return StepResult.STEP;
} else {
return rightRes;
}
} else if (leftRes === StepResult.STEP) {
return StepResult.STEP;
} else { // leftRes === DONE
this.visitExpression(expr.right);
return StepResult.STEP;
}
}
}
visitInExpression (expr: Syntax.InExpression): StepResult {
if (this.seeking()) {
return this.visitExpression(expr.property);
} else if (this.pc() === expr) {
const objArg = this.popOp();
const propArg = this.popOp();
this.pushOp(propArg in objArg);
this.clearPC();
return StepResult.DONE;
} else {
const propRes = this.visitExpression(expr.property);
if (propRes === StepResult.NOP) {
const objRes = this.visitExpression(expr.object);
if (objRes === StepResult.DONE) {
this.setPC(expr);
return StepResult.STEP;
} else {
return objRes;
}
} else if (propRes === StepResult.STEP) {
return StepResult.STEP;
} else { // propRes === DONE
this.visitExpression(expr.object);
return StepResult.STEP;
}
}
}
visitMemberExpression (expr: Syntax.MemberExpression): StepResult {
if (this.seeking()) {
return this.visitExpression(expr.object);
} else if (this.pc() === expr) {
const propArg = this.popOp();
const objArg = this.popOp();
this.pushOp(objArg[propArg]);
this.clearPC();
return StepResult.DONE;
} else {
const objRes = this.visitExpression(expr.object);
if (objRes === StepResult.NOP) {
const propRes = this.visitExpression(expr.property);
if (propRes === StepResult.DONE) {
this.setPC(expr);
return StepResult.STEP;
} else {
return propRes;
}
} else if (objRes === StepResult.STEP) {
return StepResult.STEP;
} else { // objRes === DONE
this.visitExpression(expr.property);
return StepResult.STEP;
}
}
}
visitFunctionExpression (expr: Syntax.FunctionExpression): StepResult {
if (this.seeking()) {
this.setPC(expr);
return StepResult.SET;
} else if (this.pc() === expr) {
this.pushOp(this.closure(expr));
this.clearPC();
return StepResult.DONE;
} else {
return StepResult.NOP;
}
}
visitVariableDeclaration (stmt: Syntax.VariableDeclaration): StepResult {
if (this.seeking()) {
return this.visitExpression(stmt.init);
} else if (this.pc() === stmt) {
const val = this.popOp();
this.frame().define(stmt.id.name, val, stmt.kind);
if (stmt.id.name.startsWith('old_')) {
this.annotate(stmt.id.loc, stmt.id.name.substr(4), val);
}
this.clearPC();
return StepResult.DONE;
} else {
const initRes = this.visitExpression(stmt.init);
if (initRes === StepResult.DONE) {
this.setPC(stmt);
return StepResult.STEP;
} else {
return initRes;
}
}
}
visitBlockStatement (stmt: Syntax.BlockStatement): StepResult {
if (this.seeking()) {
for (const substmt of stmt.body) {
const res = this.visitStatement(substmt);
if (res === StepResult.SET) {
this.frame().newBlockScope();
return StepResult.SET;
}
}
return StepResult.NOP;
} else {
for (let i = 0; i < stmt.body.length; i++) {
const res = this.visitStatement(stmt.body[i]);
if (res === StepResult.STEP) {
return StepResult.STEP;
} else if (res === StepResult.DONE) {
for (let j = i + 1; j < stmt.body.length; j++) {
const res = this.visitStatement(stmt.body[j]);
if (res === StepResult.SET) {
return StepResult.STEP;
}
}
this.frame().popBlockScope();
return StepResult.DONE;
}
}
return StepResult.NOP;
}
}
visitExpressionStatement (stmt: Syntax.ExpressionStatement): StepResult {
if (this.seeking()) {
return this.visitExpression(stmt.expression);
} else {
const res = this.visitExpression(stmt.expression);
if (res === StepResult.DONE) this.popOp();
return res;
}
}
visitAssertStatement (stmt: Syntax.AssertStatement): StepResult {
return StepResult.NOP;
}
visitIfStatement (stmt: Syntax.IfStatement): StepResult {
if (this.seeking()) {
return this.visitExpression(stmt.test);
} else {
const testRes = this.visitExpression(stmt.test);
if (testRes === StepResult.NOP) {
const consequentRes = this.visitStatement(stmt.consequent);
if (consequentRes === StepResult.NOP) {
return this.visitStatement(stmt.alternate);
} else { // STEP or DONE
return consequentRes;
}
} else if (testRes === StepResult.STEP) {
return StepResult.STEP;
} else { // testRes === DONE
const testArg = this.popOp();
if (testArg) {
const consequentRes = this.visitStatement(stmt.consequent);
return consequentRes === StepResult.SET ? StepResult.STEP : StepResult.DONE;
} else {
const alternateRes = this.visitStatement(stmt.alternate);
return alternateRes === StepResult.SET ? StepResult.STEP : StepResult.DONE;
}
}
}
}
visitReturnStatement (stmt: Syntax.ReturnStatement): StepResult {
if (this.seeking()) {
return this.visitExpression(stmt.argument);
} else if (this.pc() === stmt) {
const retValue = this.popOp();
this.ret(retValue);
return StepResult.STEP;
} else {
const initRes = this.visitExpression(stmt.argument);
if (initRes === StepResult.DONE) {
this.setPC(stmt);
return StepResult.STEP;
} else {
return initRes;
}
}
}
visitWhileStatement (stmt: Syntax.WhileStatement): StepResult {
if (this.seeking()) {
return this.visitExpression(stmt.test);
} else {
const testRes = this.visitExpression(stmt.test);
if (testRes === StepResult.NOP) {
const bodyRes = this.visitStatement(stmt.body);
if (bodyRes === StepResult.DONE) {
this.frame().nextIteration();
this.visitExpression(stmt.test);
return StepResult.STEP;
} else { // NOP or STEP
return bodyRes;
}
} else if (testRes === StepResult.STEP) {
return StepResult.STEP;
} else { // testRes === DONE
const testArg = this.popOp();
if (testArg) {
const bodyRes = this.visitStatement(stmt.body);
if (bodyRes !== StepResult.SET) {
this.frame().nextIteration();
this.visitExpression(stmt.test);
}
return StepResult.STEP;
} else {
return StepResult.DONE;
}
}
}
}
visitDebuggerStatement (stmt: Syntax.DebuggerStatement): StepResult {
return StepResult.NOP;
}
visitFunctionDeclaration (stmt: Syntax.FunctionDeclaration): StepResult {
if (this.seeking()) {
this.setPC(stmt);
return StepResult.SET;
} else if (this.pc() === stmt) {
this.frame().define(stmt.id.name, this.closure(stmt), 'let');
this.clearPC();
return StepResult.DONE;
} else {
return StepResult.NOP;
}
}
visitClassDeclaration (stmt: Syntax.ClassDeclaration): StepResult {
if (this.seeking()) {
this.setPC(stmt);
return StepResult.SET;
} else if (this.pc() === stmt) {
/* tslint:disable:no-eval */
const constr = eval(`(() => function ${stmt.id.name} (${stmt.fields.join(', ')}) {
${stmt.fields.map(f => ` this.${f} = ${f};\n`).join('')}
})()`);
stmt.methods.forEach(method => {
constr.prototype[method.id.name] = this.closure(method);
});
this.frame().define(stmt.id.name, constr, 'let');
this.clearPC();
return StepResult.DONE;
} else {
return StepResult.NOP;
}
}
visitProgram (prog: Syntax.Program): StepResult {
if (this.seeking()) {
for (const substmt of prog.body) {
const res = this.visitStatement(substmt);
if (res === StepResult.SET) {
return StepResult.SET;
}
}
return StepResult.NOP;
} else {
for (let i = 0; i < prog.body.length; i++) {
const res = this.visitStatement(prog.body[i]);
if (res === StepResult.STEP) {
return StepResult.STEP;
} else if (res === StepResult.DONE) {
for (let j = i + 1; j < prog.body.length; j++) {
const res = this.visitStatement(prog.body[j]);
if (res === StepResult.SET) {
return StepResult.STEP;
}
}
return StepResult.DONE;
}
}
return StepResult.NOP;
}
}
// --- Stepping Methods ---
reset (): void {
this.steps = 0;
this.annotations = [];
this.stack = [new ProgramStackFrame(this.program)];
this.breakpoint = null;
this.visitProgram(this.program);
}
step (): StepResult {
const frame = this.frame();
if (this.steps >= getOptions().maxInterpreterSteps) {
return StepResult.DONE;
}
try {
return frame.entry(this);
} catch (e) {
e.stack = `${e.constructor.name}: ${e.message}`;
for (let i = this.stack.length - 1; i >= 0; i--) {
e.stack += `\n at ${this.stack[i].toString()}`;
}
throw e;
} finally {
this.steps++;
}
}
isBreaking (): boolean {
return this.breakpoint !== null &&
eqSourceLocation(this.breakpoint[0], this.loc()) &&
this.breakpoint[1] === this.iteration();
}
stepInto (): void {
this.step();
}
stepOver (): void {
const origStackHeight = this.stack.length;
do {
const res = this.step();
if (res === StepResult.DONE || this.isBreaking()) return;
} while (this.stack.length > origStackHeight);
}
stepOut (): any { // returns stack frame return value (does not stop at breakpoints)
const origStackHeight = this.stack.length;
do {
const res = this.step();
if (res === StepResult.DONE || this.isBreaking()) return;
} while (this.stack.length >= origStackHeight);
const retVal = this.popOp();
this.pushOp(retVal);
return retVal;
}
run (): void {
while (true) {
const res = this.step();
if (res === StepResult.DONE || this.isBreaking()) return;
}
}
}
export function interpret (program: Syntax.Program): Interpreter {
return new InterpreterVisitor(program);
} | the_stack |
import { useResourceLimitations } from '../src';
import { makeExecutableSchema } from '@graphql-tools/schema';
import { assertSingleExecutionValue, createTestkit } from '@envelop/testing';
const schema = makeExecutableSchema({
typeDefs: /* GraphQL */ `
scalar ConnectionInt
type Query {
viewer: User
}
type User {
id: ID!
repositories(first: Int, last: Int, after: String): RepositoryConnection!
repositoriesCustom(first: ConnectionInt, last: ConnectionInt, after: String): RepositoryConnection!
}
type Repository {
id: ID!
name: String!
issues(first: Int, last: Int, after: String): IssueConnection!
}
type PageInfo {
hasNext: Boolean!
}
type RepositoryEdge {
node: Repository!
cursor: String!
}
type RepositoryConnection {
edges: [RepositoryEdge!]!
pageInfo: PageInfo
}
type Issue {
id: ID!
title: String!
bodyHTML: String!
}
type IssueEdge {
node: Issue!
cursor: String!
}
type IssueConnection {
edges: [IssueEdge!]!
pageInfo: PageInfo
}
`,
});
describe('useResourceLimitations', () => {
it('requires the usage of either the first or last field on fields that resolve to a Connection type.', async () => {
const testkit = createTestkit([useResourceLimitations({ extensions: true })], schema);
const result = await testkit.execute(/* GraphQL */ `
query {
viewer {
repositories {
edges {
node {
name
}
}
}
}
}
`);
assertSingleExecutionValue(result);
expect(result.errors).toBeDefined();
expect(result.errors?.length).toEqual(1);
expect(result.errors?.[0]?.message).toEqual(
"Missing pagination argument for field 'repositories'. Please provide either the 'first' or 'last' field argument."
);
});
it('requires the usage of either the first or last field on fields that resolve to a Connection type (other argument provided).', async () => {
const testkit = createTestkit([useResourceLimitations({ extensions: true })], schema);
const result = await testkit.execute(/* GraphQL */ `
query {
viewer {
repositories(after: "abc") {
edges {
node {
name
}
}
}
}
}
`);
assertSingleExecutionValue(result);
expect(result.errors).toBeDefined();
expect(result.errors?.length).toEqual(1);
expect(result.errors?.[0]?.message).toEqual(
"Missing pagination argument for field 'repositories'. Please provide either the 'first' or 'last' field argument."
);
});
it('requires the first field to be at least 1', async () => {
const testkit = createTestkit([useResourceLimitations({ extensions: true })], schema);
const result = await testkit.execute(/* GraphQL */ `
query {
viewer {
repositories(first: 0) {
edges {
node {
name
}
}
}
}
}
`);
assertSingleExecutionValue(result);
expect(result.errors).toBeDefined();
expect(result.errors?.length).toEqual(1);
expect(result.errors?.[0]?.message).toEqual(
"Invalid pagination argument for field repositories. The value for the 'first' argument must be an integer within 1-100."
);
});
it('requires the first field to be at least a custom minimum value', async () => {
const testkit = createTestkit([useResourceLimitations({ paginationArgumentMinimum: 2, extensions: true })], schema);
const result = await testkit.execute(/* GraphQL */ `
query {
viewer {
repositories(first: 1) {
edges {
node {
name
}
}
}
}
}
`);
assertSingleExecutionValue(result);
expect(result.errors).toBeDefined();
expect(result.errors?.length).toEqual(1);
expect(result.errors?.[0]?.message).toEqual(
"Invalid pagination argument for field repositories. The value for the 'first' argument must be an integer within 2-100."
);
});
it('requires the first field to be not higher than 100', async () => {
const testkit = createTestkit([useResourceLimitations({ extensions: true })], schema);
const result = await testkit.execute(/* GraphQL */ `
query {
viewer {
repositories(first: 101) {
edges {
node {
name
}
}
}
}
}
`);
assertSingleExecutionValue(result);
expect(result.errors).toBeDefined();
expect(result.errors?.length).toEqual(1);
expect(result.errors?.[0]?.message).toEqual(
"Invalid pagination argument for field repositories. The value for the 'first' argument must be an integer within 1-100."
);
});
it('requires the first field to be not higher than a custom maximum value', async () => {
const testkit = createTestkit([useResourceLimitations({ paginationArgumentMaximum: 99, extensions: true })], schema);
const result = await testkit.execute(/* GraphQL */ `
query {
viewer {
repositories(first: 100) {
edges {
node {
name
}
}
}
}
}
`);
assertSingleExecutionValue(result);
expect(result.errors).toBeDefined();
expect(result.errors?.length).toEqual(1);
expect(result.errors?.[0]?.message).toEqual(
"Invalid pagination argument for field repositories. The value for the 'first' argument must be an integer within 1-99."
);
});
it('requires the last field to be at least 1', async () => {
const testkit = createTestkit([useResourceLimitations({ extensions: true })], schema);
const result = await testkit.execute(/* GraphQL */ `
query {
viewer {
repositories(last: 0) {
edges {
node {
name
}
}
}
}
}
`);
assertSingleExecutionValue(result);
expect(result.errors).toBeDefined();
expect(result.errors?.length).toEqual(1);
expect(result.errors?.[0]?.message).toEqual(
"Invalid pagination argument for field repositories. The value for the 'last' argument must be an integer within 1-100."
);
});
it('requires the last field to be at least a custom minimum value', async () => {
const testkit = createTestkit([useResourceLimitations({ paginationArgumentMinimum: 2, extensions: true })], schema);
const result = await testkit.execute(/* GraphQL */ `
query {
viewer {
repositories(last: 1) {
edges {
node {
name
}
}
}
}
}
`);
assertSingleExecutionValue(result);
expect(result.errors).toBeDefined();
expect(result.errors?.length).toEqual(1);
expect(result.errors?.[0]?.message).toEqual(
"Invalid pagination argument for field repositories. The value for the 'last' argument must be an integer within 2-100."
);
});
it('requires the last field to be not higher than 100', async () => {
const testkit = createTestkit([useResourceLimitations({ extensions: true })], schema);
const result = await testkit.execute(/* GraphQL */ `
query {
viewer {
repositories(last: 101) {
edges {
node {
name
}
}
}
}
}
`);
assertSingleExecutionValue(result);
expect(result.errors).toBeDefined();
expect(result.errors?.length).toEqual(1);
expect(result.errors?.[0]?.message).toEqual(
"Invalid pagination argument for field repositories. The value for the 'last' argument must be an integer within 1-100."
);
});
it('requires the last field to be not higher than a custom maximum value', async () => {
const testkit = createTestkit([useResourceLimitations({ paginationArgumentMaximum: 99, extensions: true })], schema);
const result = await testkit.execute(/* GraphQL */ `
query {
viewer {
repositories(last: 100) {
edges {
node {
name
}
}
}
}
}
`);
assertSingleExecutionValue(result);
expect(result.errors).toBeDefined();
expect(result.errors?.length).toEqual(1);
expect(result.errors?.[0]?.message).toEqual(
"Invalid pagination argument for field repositories. The value for the 'last' argument must be an integer within 1-99."
);
});
it('calculates node cost (single)', async () => {
const testkit = createTestkit([useResourceLimitations({ extensions: true })], schema);
const result = await testkit.execute(/* GraphQL */ `
query {
viewer {
repositories(last: 100) {
edges {
node {
name
}
}
}
}
}
`);
assertSingleExecutionValue(result);
expect(result.errors).toBeUndefined();
expect(result.extensions).toEqual({
resourceLimitations: {
nodeCost: 100,
},
});
});
it('calculates node cost on connections with custom argument types (single)', async () => {
const testkit = createTestkit(
[useResourceLimitations({ paginationArgumentScalars: ['ConnectionInt'], extensions: true })],
schema
);
const result = await testkit.execute(/* GraphQL */ `
query {
viewer {
repositoriesCustom(first: 100) {
edges {
node {
name
}
}
}
}
}
`);
assertSingleExecutionValue(result);
expect(result.errors).toBeUndefined();
expect(result.extensions).toEqual({
resourceLimitations: {
nodeCost: 100,
},
});
});
it('calculates node cost (nested)', async () => {
const testkit = createTestkit([useResourceLimitations({ extensions: true })], schema);
const result = await testkit.execute(/* GraphQL */ `
query {
viewer {
repositories(last: 100) {
edges {
node {
name
issues(first: 10) {
edges {
node {
title
bodyHTML
}
}
}
}
}
}
}
}
`);
assertSingleExecutionValue(result);
expect(result.errors).toBeUndefined();
expect(result.extensions).toEqual({
resourceLimitations: {
nodeCost: 1100,
},
});
});
it('calculates node cost (multiple nested)', async () => {
const testkit = createTestkit([useResourceLimitations({ extensions: true })], schema);
const result = await testkit.execute(/* GraphQL */ `
query {
viewer {
repositories(last: 100) {
edges {
node {
name
issues(first: 10) {
edges {
node {
title
bodyHTML
}
}
}
}
}
}
more: repositories(last: 1) {
edges {
node {
name
issues(first: 2) {
edges {
node {
title
bodyHTML
}
}
}
}
}
}
# These should not count towards the total due to invalid argument types
repositoriesCustom(first: 100) {
edges {
node {
name
}
}
}
}
}
`);
assertSingleExecutionValue(result);
expect(result.errors).toBeUndefined();
expect(result.extensions).toEqual({
resourceLimitations: {
nodeCost: 1104,
},
});
});
it('stops execution if node cost limit is exceeded', async () => {
const testkit = createTestkit([useResourceLimitations({ extensions: true, nodeCostLimit: 20 })], schema);
const result = await testkit.execute(/* GraphQL */ `
query {
viewer {
repositories(last: 19) {
edges {
node {
name
issues(first: 2) {
edges {
node {
title
bodyHTML
}
}
}
}
}
}
}
}
`);
assertSingleExecutionValue(result);
expect(result.extensions).toEqual({
resourceLimitations: {
nodeCost: 19 * 2 + 19,
},
});
expect(result.errors).toBeDefined();
expect(result.errors?.[0].message).toEqual(
'Cannot request more than 20 nodes in a single document. Please split your operation into multiple sub operations or reduce the amount of requested nodes.'
);
});
it('minimum cost is always 1', async () => {
const testkit = createTestkit([useResourceLimitations({ extensions: true, nodeCostLimit: 20 })], schema);
const result = await testkit.execute(/* GraphQL */ `
query {
viewer {
id
}
}
`);
assertSingleExecutionValue(result);
expect(result.extensions).toEqual({
resourceLimitations: {
nodeCost: 1,
},
});
expect(result.errors).toBeUndefined();
});
}); | the_stack |
import { Client } from "@notionhq/client"
import {
CreatePageBodyParameters,
CreatePageParameters,
GetDatabaseResponse,
GetPageResponse,
} from "@notionhq/client/build/src/api-endpoints"
import * as _ from "lodash"
import { config } from "dotenv"
config()
import * as faker from "faker"
const notion = new Client({ auth: process.env["NOTION_KEY"] })
const startTime = new Date()
startTime.setSeconds(0, 0)
// Given the properties of a database, generate an object full of
// random data that can be used to generate new rows in our Notion database.
function makeFakePropertiesData(
properties: GetDatabaseResponse["properties"]
): Record<string, CreatePageBodyParameters["properties"]> {
const propertyValues: Record<string, CreatePageBodyParameters["properties"]> =
{}
Object.entries(properties).forEach(([name, property]) => {
if (property.type === "date") {
propertyValues[name] = {
type: "date",
date: {
start: faker.date.past().toISOString(),
},
}
} else if (property.type === "multi_select") {
const multiSelectOption = _.sample(property.multi_select.options)
if (multiSelectOption) {
propertyValues[name] = {
type: "multi_select",
multi_select: [multiSelectOption],
}
}
} else if (property.type === "select") {
const selectOption = _.sample(property.select.options)
if (selectOption) {
propertyValues[name] = {
type: "select",
id: property.id,
select: selectOption,
}
}
} else if (property.type === "email") {
propertyValues[name] = {
type: "email",
id: property.id,
email: faker.internet.email(),
}
} else if (property.type === "checkbox") {
propertyValues[name] = {
type: "checkbox",
id: property.id,
checkbox: faker.datatype.boolean(),
}
} else if (property.type === "url") {
propertyValues[name] = {
type: "url",
id: property.id,
url: faker.internet.url(),
}
} else if (property.type === "number") {
propertyValues[name] = {
type: "number",
id: property.id,
number: faker.datatype.number(),
}
} else if (property.type === "title") {
propertyValues[name] = {
type: "title",
id: property.id,
title: [
{
type: "text",
text: { content: faker.lorem.words(3) },
},
],
}
} else if (property.type === "rich_text") {
propertyValues[name] = {
type: "rich_text",
id: property.id,
rich_text: [
{
type: "text",
text: { content: faker.name.firstName() },
},
],
}
} else if (property.type === "phone_number") {
propertyValues[name] = {
type: "phone_number",
id: property.id,
phone_number: faker.phone.phoneNumber(),
}
} else {
console.log("unimplemented property type: ", property.type)
}
})
return propertyValues
}
function assertUnreachable(_x: never): never {
throw new Error("Didn't expect to get here")
}
function userToString(userBase: { id: string; name?: string | null }) {
return `${userBase.id}: ${userBase.name || "Unknown Name"}`
}
function findRandomSelectColumnNameAndValue(
properties: GetDatabaseResponse["properties"]
): {
name: string
value: string | undefined
} {
const options = _.flatMap(Object.entries(properties), ([name, property]) => {
if (property.type === "select") {
return [
{ name, value: _.sample(property.select.options.map(o => o.name)) },
]
}
return []
})
if (options.length > 0) {
return _.sample(options) || { name: "", value: undefined }
}
return { name: "", value: undefined }
}
function extractValueToString(
property: GetPageResponse["properties"][string]
): string {
switch (property.type) {
case "checkbox":
return property.checkbox.toString()
case "created_by":
return userToString(property.created_by)
case "created_time":
return new Date(property.created_time).toISOString()
case "date":
return new Date(property.date.start).toISOString()
case "email":
return property.email
case "url":
return property.url
case "number":
return property.number.toString()
case "phone_number":
return property.phone_number
case "select":
if (!property.select) {
return ""
}
return `${property.select.id} ${property.select.name}`
case "multi_select":
if (!property.multi_select) {
return ""
}
return property.multi_select
.map(select => `${select.id} ${select.name}`)
.join(", ")
case "people":
return property.people.map(person => userToString(person)).join(", ")
case "last_edited_by":
return userToString(property.last_edited_by)
case "last_edited_time":
return new Date(property.last_edited_time).toISOString()
case "title":
return property.title.map(t => t.plain_text).join(", ")
case "rich_text":
return property.rich_text.map(t => t.plain_text).join(", ")
case "files":
return property.files.map(file => file.name).join(", ")
case "formula":
if (property.formula.type === "string") {
return property.formula.string || "???"
} else if (property.formula.type === "number") {
return property.formula.number?.toString() || "???"
} else if (property.formula.type === "boolean") {
return property.formula.boolean?.toString() || "???"
} else if (property.formula.type === "date") {
return (
(property.formula.date?.start &&
new Date(property.formula.date.start).toISOString()) ||
"???"
)
} else {
return assertUnreachable(property.formula)
}
case "rollup":
if (property.rollup.type === "number") {
return property.rollup.number?.toString() || "???"
} else if (property.rollup.type === "date") {
return (
(property.rollup.date?.start &&
new Date(property.rollup.date?.start).toISOString()) ||
"???"
)
} else if (property.rollup.type === "array") {
return JSON.stringify(property.rollup.array)
} else {
return assertUnreachable(property.rollup)
}
case "relation":
if (property.relation) {
return property.relation.join(",")
}
return "???"
}
return assertUnreachable(property)
}
async function exerciseWriting(
databaseId: string,
properties: GetDatabaseResponse["properties"]
) {
console.log("\n\n********* Exercising Writing *********\n\n")
const RowsToWrite = 10
// generate a bunch of fake pages with fake data
for (let i = 0; i < RowsToWrite; i++) {
const propertiesData = makeFakePropertiesData(properties)
const parameters: CreatePageParameters = {
parent: {
database_id: databaseId,
},
properties: propertiesData,
} as CreatePageParameters
await notion.pages.create(parameters)
}
console.log(`Wrote ${RowsToWrite} rows after ${startTime}`)
}
async function exerciseReading(
databaseId: string,
_properties: GetDatabaseResponse["properties"]
) {
console.log("\n\n********* Exercising Reading *********\n\n")
// and read back what we just did
const queryResponse = await notion.databases.query({
database_id: databaseId,
})
let numOldRows = 0
queryResponse.results.map(page => {
const createdTime = new Date(page.created_time)
if (startTime > createdTime) {
numOldRows++
return
}
console.log(`New page: ${page.id}`)
Object.entries(page.properties).forEach(([name, property]) => {
console.log(
` - ${name} ${property.id} - ${extractValueToString(property)}`
)
})
})
console.log(
`Skipped printing ${numOldRows} rows that were written before ${startTime}`
)
}
async function exerciseFilters(
databaseId: string,
properties: GetDatabaseResponse["properties"]
) {
console.log("\n\n********* Exercising Filters *********\n\n")
// get a random select or multi-select column from the collection with a random value for it
const { name: selectColumnName, value: selectColumnValue } =
findRandomSelectColumnNameAndValue(properties)
if (!selectColumnName || !selectColumnValue) {
throw new Error("need a select column to run this part of the example")
}
console.log(`Looking for ${selectColumnName}=${selectColumnValue}`)
// Check we can search by name
const queryFilterSelectFilterTypeBased = {
property: selectColumnName,
select: { equals: selectColumnValue },
}
const matchingSelectResults = await notion.databases.query({
database_id: databaseId,
filter: queryFilterSelectFilterTypeBased,
})
console.log(
`had ${matchingSelectResults.results.length} matching rows for ${selectColumnName}=${selectColumnValue}`
)
// Let's do it again for text
const textColumn = _.sample(
Object.values(properties).filter(p => p.type === "rich_text")
)
if (!textColumn) {
throw new Error(
"Need a rich_text column for this part of the test, could not find one"
)
}
const textColumnId = decodeURIComponent(textColumn.id)
const letterToFind = faker.lorem.word(1)
console.log(
`\n\nLooking for text column with id "${textColumnId}" contains letter "${letterToFind}"`
)
const textFilter = {
property: textColumnId,
text: { contains: letterToFind },
}
// Check we can search by id
const matchingTextResults = await notion.databases.query({
database_id: databaseId,
filter: textFilter,
})
console.log(
`Had ${matchingTextResults.results.length} matching rows in column with ID "${textColumnId}" containing letter "${letterToFind}"`
)
}
async function main() {
// Find the first database this bot has access to
// TODO(blackmad): move to notion.search()
const databases = await notion.databases.list({})
if (databases.results.length === 0) {
throw new Error("This bot doesn't have access to any databases!")
}
const database = databases.results[0]
if (!database) {
throw new Error("This bot doesn't have access to any databases!")
}
// Get the database properties out of our database
const { properties } = await notion.databases.retrieve({
database_id: database.id,
})
await exerciseWriting(database.id, properties)
await exerciseReading(database.id, properties)
await exerciseFilters(database.id, properties)
}
main() | the_stack |
import { Injectable } from '@angular/core';
import { CoreError } from '@classes/errors/error';
import { CoreCourseActivitySyncBaseProvider } from '@features/course/classes/activity-sync';
import { CoreCourse } from '@features/course/services/course';
import { CoreCourseLogHelper } from '@features/course/services/log-helper';
import { CoreSites, CoreSitesReadingStrategy } from '@services/sites';
import { CoreSync } from '@services/sync';
import { CoreUtils } from '@services/utils/utils';
import { makeSingleton, Translate } from '@singletons';
import { CoreEvents } from '@singletons/events';
import { AddonModScormPrefetchHandler } from './handlers/prefetch';
import {
AddonModScorm,
AddonModScormAttemptCountResult,
AddonModScormDataEntry,
AddonModScormProvider,
AddonModScormScorm,
AddonModScormUserDataMap,
} from './scorm';
import { AddonModScormOffline } from './scorm-offline';
/**
* Service to sync SCORMs.
*/
@Injectable({ providedIn: 'root' })
export class AddonModScormSyncProvider extends CoreCourseActivitySyncBaseProvider<AddonModScormSyncResult> {
static readonly AUTO_SYNCED = 'addon_mod_scorm_autom_synced';
protected componentTranslatableString = 'scorm';
constructor() {
super('AddonModScormSyncProvider');
}
/**
* Add an offline attempt to the right of the new attempts array if possible.
* If the attempt cannot be created as a new attempt then it will be deleted.
*
* @param scormId SCORM ID.
* @param attempt The offline attempt to treat.
* @param lastOffline Last offline attempt number.
* @param newAttemptsSameOrder Attempts that'll be created as new attempts but keeping the current order.
* @param newAttemptsAtEnd Object with attempts that'll be created at the end of the list (should be max 1).
* @param lastOfflineCreated Time when the last offline attempt was created.
* @param lastOfflineIncomplete Whether the last offline attempt is incomplete.
* @param warnings Array where to add the warnings.
* @param siteId Site ID.
* @return Promise resolved when done.
*/
protected async addToNewOrDelete(
scormId: number,
attempt: number,
lastOffline: number,
newAttemptsSameOrder: number[],
newAttemptsAtEnd: Record<number, number>,
lastOfflineCreated: number,
lastOfflineIncomplete: boolean,
warnings: string[],
siteId: string,
): Promise<void> {
if (attempt == lastOffline) {
newAttemptsSameOrder.push(attempt);
return;
}
// Check if the attempt can be created.
const time = await AddonModScormOffline.getAttemptCreationTime(scormId, attempt, siteId);
if (!time || time <= lastOfflineCreated) {
newAttemptsSameOrder.push(attempt);
return;
}
// This attempt was created after the last offline attempt, we'll add it to the end of the list if possible.
if (lastOfflineIncomplete) {
// It can't be added because the last offline attempt is incomplete, delete it.
this.logger.debug(`Try to delete attempt ${attempt} because it cannot be created as a new attempt.`);
await CoreUtils.ignoreErrors(AddonModScormOffline.deleteAttempt(scormId, attempt, siteId));
// eslint-disable-next-line id-blacklist
warnings.push(Translate.instant('addon.mod_scorm.warningofflinedatadeleted', { number: attempt }));
} else {
// Add the attempt at the end.
newAttemptsAtEnd[time] = attempt;
}
}
/**
* Check if can retry an attempt synchronization.
*
* @param scormId SCORM ID.
* @param attempt Attempt number.
* @param lastOnline Last online attempt number.
* @param cmId Module ID.
* @param siteId Site ID.
* @return Promise resolved if can retry the synchronization, rejected otherwise.
*/
protected async canRetrySync(
scormId: number,
attempt: number,
lastOnline: number,
cmId: number,
siteId: string,
): Promise<boolean> {
// If it's the last attempt we don't need to ignore cache because we already did it.
const refresh = lastOnline != attempt;
const siteData = await AddonModScorm.getScormUserData(scormId, attempt, {
cmId,
readingStrategy: refresh ? CoreSitesReadingStrategy.ONLY_NETWORK : undefined,
siteId,
});
// Get synchronization snapshot (if sync fails it should store a snapshot).
const snapshot = await AddonModScormOffline.getAttemptSnapshot(scormId, attempt, siteId);
if (!snapshot || !Object.keys(snapshot).length || !this.snapshotEquals(snapshot, siteData)) {
// No snapshot or it doesn't match, we can't retry the synchronization.
return false;
}
return true;
}
/**
* Create new attempts at the end of the offline attempts list.
*
* @param scormId SCORM ID.
* @param newAttempts Object with the attempts to create. The keys are the timecreated, the values are the attempt number.
* @param lastOffline Number of last offline attempt.
* @param siteId Site ID.
* @return Promise resolved when done.
*/
protected async createNewAttemptsAtEnd(
scormId: number,
newAttempts: Record<number, number>,
lastOffline: number,
siteId: string,
): Promise<void> {
const times = Object.keys(newAttempts).sort(); // Sort in ASC order.
if (!times.length) {
return;
}
await CoreUtils.allPromises(times.map((time, index) => {
const attempt = newAttempts[time];
return AddonModScormOffline.changeAttemptNumber(scormId, attempt, lastOffline + index + 1, siteId);
}));
}
/**
* Finish a sync process: remove offline data if needed, prefetch SCORM data, set sync time and return the result.
*
* @param siteId Site ID.
* @param scorm SCORM.
* @param warnings List of warnings generated by the sync.
* @param lastOnline Last online attempt number before the sync.
* @param lastOnlineWasFinished Whether the last online attempt was finished before the sync.
* @param initialCount Attempt count before the sync.
* @param updated Whether some data was sent to the site.
* @return Promise resolved on success.
*/
protected async finishSync(
siteId: string,
scorm: AddonModScormScorm,
warnings: string[],
lastOnline?: number,
lastOnlineWasFinished?: boolean,
initialCount?: AddonModScormAttemptCountResult,
updated?: boolean,
): Promise<AddonModScormSyncResult> {
const result: AddonModScormSyncResult = {
warnings: warnings,
attemptFinished: false,
updated: !!updated,
};
if (updated) {
try {
// Update downloaded data.
const module = await CoreCourse.getModuleBasicInfoByInstance(scorm.id, 'scorm', { siteId });
await this.prefetchAfterUpdate(AddonModScormPrefetchHandler.instance, module, scorm.course, undefined, siteId);
} catch {
// Ignore errors.
}
}
await CoreUtils.ignoreErrors(this.setSyncTime(scorm.id, siteId));
if (!initialCount) {
return result;
}
// Check if an attempt was finished in Moodle.
// Get attempt count again to check if an attempt was finished.
const attemptsData = await AddonModScorm.getAttemptCount(scorm.id, { cmId: scorm.coursemodule, siteId });
if (attemptsData.online.length > initialCount.online.length) {
result.attemptFinished = true;
} else if (!lastOnlineWasFinished && lastOnline) {
// Last online attempt wasn't finished, let's check if it is now.
const incomplete = await AddonModScorm.isAttemptIncomplete(scorm.id, lastOnline, {
cmId: scorm.coursemodule,
readingStrategy: CoreSitesReadingStrategy.ONLY_NETWORK,
siteId,
});
result.attemptFinished = !incomplete;
}
return result;
}
/**
* Get the creation time and the status (complete/incomplete) of an offline attempt.
*
* @param scormId SCORM ID.
* @param attempt Attempt number.
* @param cmId Module ID.
* @param siteId Site ID.
* @return Promise resolved with the data.
*/
protected async getOfflineAttemptData(
scormId: number,
attempt: number,
cmId: number,
siteId: string,
): Promise<{incomplete: boolean; timecreated?: number}> {
// Check if last offline attempt is incomplete.
const incomplete = await AddonModScorm.isAttemptIncomplete(scormId, attempt, {
offline: true,
cmId,
siteId,
});
const timecreated = await AddonModScormOffline.getAttemptCreationTime(scormId, attempt, siteId);
return {
incomplete,
timecreated,
};
}
/**
* Change the number of some offline attempts. We need to move all offline attempts after the collisions
* too, otherwise we would overwrite data.
* Example: We have offline attempts 1, 2 and 3. #1 and #2 have collisions. #1 can be synced, but #2 needs
* to be a new attempt. #3 will now be #4, and #2 will now be #3.
*
* @param scormId SCORM ID.
* @param newAttempts Attempts that need to be converted into new attempts.
* @param lastOnline Last online attempt.
* @param lastCollision Last attempt with collision (exists in online and offline).
* @param offlineAttempts Numbers of offline attempts.
* @param siteId Site ID.
* @return Promise resolved when attempts have been moved.
*/
protected async moveNewAttempts(
scormId: number,
newAttempts: number[],
lastOnline: number,
lastCollision: number,
offlineAttempts: number[],
siteId: string,
): Promise<void> {
if (!newAttempts.length) {
return;
}
let lastSuccessful: number | undefined;
try {
// Sort offline attempts in DESC order.
offlineAttempts = offlineAttempts.sort((a, b) => Number(a) <= Number(b) ? 1 : -1);
// First move the offline attempts after the collisions. Move them 1 by 1 in order.
for (const i in offlineAttempts) {
const attempt = offlineAttempts[i];
if (attempt > lastCollision) {
const newNumber = attempt + newAttempts.length;
await AddonModScormOffline.changeAttemptNumber(scormId, attempt, newNumber, siteId);
lastSuccessful = attempt;
}
}
const successful: number[] = [];
try {
// Sort newAttempts in ASC order.
newAttempts = newAttempts.sort((a, b) => Number(a) >= Number(b) ? 1 : -1);
// Now move the attempts in newAttempts.
await Promise.all(newAttempts.map(async (attempt, index) => {
// No need to use chain of promises.
const newNumber = lastOnline + index + 1;
await AddonModScormOffline.changeAttemptNumber(scormId, attempt, newNumber, siteId);
successful.push(attempt);
}));
} catch (error) {
// Moving the new attempts failed (it shouldn't happen). Let's undo the new attempts move.
await CoreUtils.allPromises(successful.map((attempt) => {
const newNumber = lastOnline + newAttempts.indexOf(attempt) + 1;
return AddonModScormOffline.changeAttemptNumber(scormId, newNumber, attempt, siteId);
}));
throw error; // It will now enter the catch that moves offline attempts after collisions.
}
} catch (error) {
// Moving offline attempts after collisions failed (it shouldn't happen). Let's undo the changes.
if (!lastSuccessful) {
throw error;
}
for (let attempt = lastSuccessful; offlineAttempts.indexOf(attempt) != -1; attempt++) {
// Move it back.
await AddonModScormOffline.changeAttemptNumber(scormId, attempt + newAttempts.length, attempt, siteId);
}
throw error;
}
}
/**
* Save a snapshot from a synchronization.
*
* @param scormId SCORM ID.
* @param attempt Attemot number.
* @param cmId Module ID.
* @param siteId Site ID.
* @return Promise resolved when the snapshot is stored.
*/
protected async saveSyncSnapshot(scormId: number, attempt: number, cmId: number, siteId: string): Promise<void> {
// Try to get current state from the site.
let userData: AddonModScormUserDataMap;
try {
userData = await AddonModScorm.getScormUserData(scormId, attempt, {
cmId,
readingStrategy: CoreSitesReadingStrategy.ONLY_NETWORK,
siteId,
});
} catch {
// Error getting user data from the site. We'll have to build it ourselves.
// Let's try to get cached data about the attempt.
userData = await CoreUtils.ignoreErrors(
AddonModScorm.getScormUserData(scormId, attempt, { cmId, siteId }),
<AddonModScormUserDataMap> {},
);
// We need to add the synced data to the snapshot.
const syncedData = await AddonModScormOffline.getScormStoredData(scormId, attempt, false, true, siteId);
syncedData.forEach((entry) => {
if (!userData[entry.scoid]) {
userData[entry.scoid] = {
scoid: entry.scoid,
userdata: {},
defaultdata: {},
};
}
userData[entry.scoid].userdata[entry.element] = entry.value || '';
});
}
return AddonModScormOffline.setAttemptSnapshot(scormId, attempt, userData, siteId);
}
/**
* Compares an attempt's snapshot with the data retrieved from the site.
* It only compares elements with dot notation. This means that, if some SCO has been added to Moodle web
* but the user hasn't generated data for it, then the snapshot will be detected as equal.
*
* @param snapshot Attempt's snapshot.
* @param userData Data retrieved from the site.
* @return True if snapshot is equal to the user data, false otherwise.
*/
protected snapshotEquals(snapshot: AddonModScormUserDataMap, userData: AddonModScormUserDataMap): boolean {
// Check that snapshot contains the data from the site.
for (const scoId in userData) {
const siteSco = userData[scoId];
const snapshotSco = snapshot[scoId];
for (const element in siteSco.userdata) {
if (element.indexOf('.') > -1) {
if (!snapshotSco || siteSco.userdata[element] !== snapshotSco.userdata[element]) {
return false;
}
}
}
}
// Now check the opposite way: site userData contains the data from the snapshot.
for (const scoId in snapshot) {
const siteSco = userData[scoId];
const snapshotSco = snapshot[scoId];
for (const element in snapshotSco.userdata) {
if (element.indexOf('.') > -1) {
if (!siteSco || siteSco.userdata[element] !== snapshotSco.userdata[element]) {
return false;
}
}
}
}
return true;
}
/**
* Try to synchronize all the SCORMs in a certain site or in all sites.
*
* @param siteId Site ID to sync. If not defined, sync all sites.
* @param force Wether to force sync not depending on last execution.
* @return Promise resolved if sync is successful, rejected if sync fails.
*/
syncAllScorms(siteId?: string, force?: boolean): Promise<void> {
return this.syncOnSites('all SCORMs', this.syncAllScormsFunc.bind(this, !!force), siteId);
}
/**
* Sync all SCORMs on a site.
*
* @param force Wether to force sync or not.
* @param siteId Site ID to sync.
* @param Promise resolved if sync is successful, rejected if sync fails.
*/
protected async syncAllScormsFunc(force: boolean, siteId: string): Promise<void> {
// Get all offline attempts.
const attempts = await AddonModScormOffline.getAllAttempts(siteId);
const treated: Record<number, boolean> = {}; // To prevent duplicates.
// Sync all SCORMs that haven't been synced for a while and that aren't attempted right now.
await Promise.all(attempts.map(async (attempt) => {
if (treated[attempt.scormid] || CoreSync.isBlocked(AddonModScormProvider.COMPONENT, attempt.scormid, siteId)) {
return;
}
treated[attempt.scormid] = true;
const scorm = await AddonModScorm.getScormById(attempt.courseid, attempt.scormid, { siteId });
const data = force ?
await this.syncScorm(scorm, siteId) :
await this.syncScormIfNeeded(scorm, siteId);
if (data !== undefined) {
// We tried to sync. Send event.
CoreEvents.trigger(AddonModScormSyncProvider.AUTO_SYNCED, {
scormId: scorm.id,
attemptFinished: data.attemptFinished,
warnings: data.warnings,
updated: data.updated,
}, siteId);
}
}));
}
/**
* Send data from a SCORM offline attempt to the site.
*
* @param scormId SCORM ID.
* @param attempt Attempt number.
* @param cmId Module ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the attempt is successfully synced.
*/
protected async syncAttempt(scormId: number, attempt: number, cmId: number, siteId?: string): Promise<void> {
siteId = siteId || CoreSites.getCurrentSiteId();
this.logger.debug(`Try to sync attempt ${attempt} in SCORM ${scormId} and site ${siteId}`);
// Get only not synced entries.
const tracks = await AddonModScormOffline.getScormStoredData(scormId, attempt, true, false, siteId);
const scos: Record<number, AddonModScormDataEntry[]> = {};
let somethingSynced = false;
// Get data to send (only elements with dots like cmi.core.exit, in Mobile we store more data to make offline work).
tracks.forEach((track) => {
if (track.element.indexOf('.') > -1) {
if (!scos[track.scoid]) {
scos[track.scoid] = [];
}
scos[track.scoid].push({
element: track.element,
value: track.value || '',
});
}
});
try {
// Send the data in each SCO.
const promises = Object.entries(scos).map(async ([key, tracks]) => {
const scoId = Number(key);
await AddonModScorm.saveTracksOnline(scormId, scoId, attempt, tracks, siteId);
// Sco data successfully sent. Mark them as synced. This is needed because some SCOs sync might fail.
await CoreUtils.ignoreErrors(AddonModScormOffline.markAsSynced(scormId, attempt, scoId, siteId));
somethingSynced = true;
});
await CoreUtils.allPromises(promises);
} catch (error) {
if (somethingSynced) {
// Some SCOs have been synced and some not.
// Try to store a snapshot of the current state to be able to re-try the synchronization later.
this.logger.error(`Error synchronizing some SCOs for attempt ${attempt} in SCORM ${scormId}. Saving snapshot.`);
await this.saveSyncSnapshot(scormId, attempt, cmId, siteId);
} else {
this.logger.error(`Error synchronizing attempt ${attempt} in SCORM ${scormId}`);
}
throw error;
}
// Attempt has been sent. Let's delete it from local.
await CoreUtils.ignoreErrors(AddonModScormOffline.deleteAttempt(scormId, attempt, siteId));
}
/**
* Sync a SCORM only if a certain time has passed since the last time.
*
* @param scorm SCORM.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the SCORM is synced or if it doesn't need to be synced.
*/
async syncScormIfNeeded(scorm: AddonModScormScorm, siteId?: string): Promise<AddonModScormSyncResult | undefined> {
const needed = await this.isSyncNeeded(scorm.id, siteId);
if (needed) {
return this.syncScorm(scorm, siteId);
}
}
/**
* Try to synchronize a SCORM.
*
* @param scorm SCORM.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved in success.
*/
syncScorm(scorm: AddonModScormScorm, siteId?: string): Promise<AddonModScormSyncResult> {
siteId = siteId || CoreSites.getCurrentSiteId();
const currentSyncPromise = this.getOngoingSync(scorm.id, siteId);
if (currentSyncPromise) {
// There's already a sync ongoing for this SCORM, return the promise.
return currentSyncPromise;
}
// Verify that SCORM isn't blocked.
if (CoreSync.isBlocked(AddonModScormProvider.COMPONENT, scorm.id, siteId)) {
this.logger.debug('Cannot sync SCORM ' + scorm.id + ' because it is blocked.');
throw new CoreError(Translate.instant('core.errorsyncblocked', { $a: this.componentTranslate }));
}
this.logger.debug(`Try to sync SCORM ${scorm.id} in site ${siteId}`);
const syncPromise = this.performSyncScorm(scorm, siteId);
return this.addOngoingSync(scorm.id, syncPromise, siteId);
}
/**
* Try to synchronize a SCORM.
*
* @param scorm SCORM.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved in success.
*/
protected async performSyncScorm(scorm: AddonModScormScorm, siteId: string): Promise<AddonModScormSyncResult> {
let warnings: string[] = [];
let lastOnline = 0;
let lastOnlineWasFinished = false;
// Sync offline logs.
await CoreUtils.ignoreErrors(CoreCourseLogHelper.syncIfNeeded(AddonModScormProvider.COMPONENT, scorm.id, siteId));
// Get attempts data. We ignore cache for online attempts, so this call will fail if offline or server down.
const attemptsData = await AddonModScorm.getAttemptCount(scorm.id, {
cmId: scorm.coursemodule,
readingStrategy: CoreSitesReadingStrategy.ONLY_NETWORK,
siteId,
});
if (!attemptsData.offline || !attemptsData.offline.length) {
// Nothing to sync.
return this.finishSync(siteId, scorm, warnings, lastOnline, lastOnlineWasFinished);
}
const initialCount = attemptsData;
const collisions: number[] = [];
// Check if there are collisions between offline and online attempts (same number).
attemptsData.online.forEach((attempt) => {
lastOnline = Math.max(lastOnline, attempt);
if (attemptsData.offline.indexOf(attempt) > -1) {
collisions.push(attempt);
}
});
// Check if last online attempt is finished. Ignore cache.
let incomplete = lastOnline <= 0 ?
false :
await AddonModScorm.isAttemptIncomplete(scorm.id, lastOnline, {
cmId: scorm.coursemodule,
readingStrategy: CoreSitesReadingStrategy.ONLY_NETWORK,
siteId,
});
lastOnlineWasFinished = !incomplete;
if (!collisions.length) {
if (incomplete) {
// No collisions, but last online attempt is incomplete so we can't send offline attempts.
warnings.push(Translate.instant('addon.mod_scorm.warningsynconlineincomplete'));
return this.finishSync(siteId, scorm, warnings, lastOnline, lastOnlineWasFinished, initialCount, false);
}
// No collisions and last attempt is complete. Send offline attempts to Moodle.
await Promise.all(attemptsData.offline.map(async (attempt) => {
if (!scorm.maxattempt || attempt <= scorm.maxattempt) {
await this.syncAttempt(scorm.id, attempt, scorm.coursemodule, siteId);
}
}));
// All data synced, finish.
return this.finishSync(siteId, scorm, warnings, lastOnline, lastOnlineWasFinished, initialCount, true);
}
// We have collisions, treat them.
warnings = await this.treatCollisions(scorm.id, collisions, lastOnline, attemptsData.offline, scorm.coursemodule, siteId);
// The offline attempts might have changed since some collisions can be converted to new attempts.
const entries = await AddonModScormOffline.getAttempts(scorm.id, siteId);
let cannotSyncSome = false;
// Get only the attempt number.
const attempts = entries.map((entry) => entry.attempt);
if (incomplete && attempts.indexOf(lastOnline) > -1) {
// Last online was incomplete, but it was continued in offline.
incomplete = false;
}
await Promise.all(attempts.map(async (attempt) => {
// We'll always sync attempts previous to lastOnline (failed sync or continued in offline).
// We'll only sync new attemps if last online attempt is completed.
if (!incomplete || attempt <= lastOnline) {
if (!scorm.maxattempt || attempt <= scorm.maxattempt) {
await this.syncAttempt(scorm.id, attempt, scorm.coursemodule, siteId);
}
} else {
cannotSyncSome = true;
}
}));
if (cannotSyncSome) {
warnings.push(Translate.instant('addon.mod_scorm.warningsynconlineincomplete'));
}
return this.finishSync(siteId, scorm, warnings, lastOnline, lastOnlineWasFinished, initialCount, true);
}
/**
* Treat collisions found in a SCORM synchronization process.
*
* @param scormId SCORM ID.
* @param collisions Numbers of attempts that exist both in online and offline.
* @param lastOnline Last online attempt.
* @param offlineAttempts Numbers of offline attempts.
* @param cmId Module ID.
* @param siteId Site ID.
* @return Promise resolved when the collisions have been treated. It returns warnings array.
* @description
*
* Treat collisions found in a SCORM synchronization process. A collision is when an attempt exists both in offline
* and online. A collision can be:
*
* - Two different attempts.
* - An online attempt continued in offline.
* - A failure in a previous sync.
*
* This function will move into new attempts the collisions that can't be merged. It will usually keep the order of the
* offline attempts EXCEPT if the offline attempt was created after the last offline attempt (edge case).
*
* Edge case: A user creates offline attempts and when he syncs we retrieve an incomplete online attempt, so the offline
* attempts cannot be synced. Then the user continues that online attempt and goes offline, so a collision is created.
* When we perform the next sync we detect that this collision cannot be merged, so this offline attempt needs to be
* created as a new attempt. Since this attempt was created after the last offline attempt, it will be added ot the end
* of the list if the last attempt is completed. If the last attempt is not completed then the offline data will de deleted
* because we can't create a new attempt.
*/
protected async treatCollisions(
scormId: number,
collisions: number[],
lastOnline: number,
offlineAttempts: number[],
cmId: number,
siteId: string,
): Promise<string[]> {
const warnings: string[] = [];
const newAttemptsSameOrder: number[] = []; // Attempts that will be created as new attempts but keeping the current order.
const newAttemptsAtEnd: Record<number, number> = {}; // Attempts that'll be created at the end of list (should be max 1).
const lastCollision = Math.max.apply(Math, collisions);
let lastOffline = Math.max.apply(Math, offlineAttempts);
// Get needed data from the last offline attempt.
const lastOfflineData = await this.getOfflineAttemptData(scormId, lastOffline, cmId, siteId);
const promises = collisions.map(async (attempt) => {
// First get synced entries to detect if it was a failed synchronization.
const synced = await AddonModScormOffline.getScormStoredData(scormId, attempt, false, true, siteId);
if (synced.length) {
// The attempt has synced entries, it seems to be a failed synchronization.
// Let's get the entries that haven't been synced, maybe it just failed to delete the attempt.
const tracks = await AddonModScormOffline.getScormStoredData(scormId, attempt, true, false, siteId);
// Check if there are elements to sync.
const hasDataToSend = tracks.find(track => track.element.indexOf('.') > -1);
if (!hasDataToSend) {
// Nothing to sync, delete the attempt.
return CoreUtils.ignoreErrors(AddonModScormOffline.deleteAttempt(scormId, attempt, siteId));
}
// There are elements to sync. We need to check if it's possible to sync them or not.
const canRetry = await this.canRetrySync(scormId, attempt, lastOnline, cmId, siteId);
if (!canRetry) {
// Cannot retry sync, we'll create a new offline attempt if possible.
return this.addToNewOrDelete(
scormId,
attempt,
lastOffline,
newAttemptsSameOrder,
newAttemptsAtEnd,
lastOfflineData.timecreated!,
lastOfflineData.incomplete,
warnings,
siteId,
);
}
} else {
// It's not a failed synchronization. Check if it's an attempt continued in offline.
const snapshot = await AddonModScormOffline.getAttemptSnapshot(scormId, attempt, siteId);
if (!snapshot || !Object.keys(snapshot).length) {
// No snapshot, it's a different attempt.
newAttemptsSameOrder.push(attempt);
return;
}
// It has a snapshot, it means it continued an online attempt. We need to check if they've diverged.
// If it's the last attempt we don't need to ignore cache because we already did it.
const refresh = lastOnline != attempt;
const userData = await AddonModScorm.getScormUserData(scormId, attempt, {
cmId,
readingStrategy: refresh ? CoreSitesReadingStrategy.ONLY_NETWORK : undefined,
siteId,
});
if (!this.snapshotEquals(snapshot, userData)) {
// Snapshot has diverged, it will be converted into a new attempt if possible.
return this.addToNewOrDelete(
scormId,
attempt,
lastOffline,
newAttemptsSameOrder,
newAttemptsAtEnd,
lastOfflineData.timecreated!,
lastOfflineData.incomplete,
warnings,
siteId,
);
}
}
});
await Promise.all(promises);
await this.moveNewAttempts(scormId, newAttemptsSameOrder, lastOnline, lastCollision, offlineAttempts, siteId);
// The new attempts that need to keep the order have been created.
// Now create the new attempts at the end of the list of offline attempts. It should only be 1 attempt max.
lastOffline = lastOffline + newAttemptsSameOrder.length;
await this.createNewAttemptsAtEnd(scormId, newAttemptsAtEnd, lastOffline, siteId);
return warnings;
}
}
export const AddonModScormSync = makeSingleton(AddonModScormSyncProvider);
/**
* Data returned by a SCORM sync.
*/
export type AddonModScormSyncResult = {
warnings: string[]; // List of warnings.
attemptFinished: boolean; // Whether an attempt was finished in the site due to the sync,
updated: boolean; // Whether some data was sent to the site.
};
/**
* Auto sync event data.
*/
export type AddonModScormAutoSyncEventData = {
scormId: number;
attemptFinished: boolean;
warnings: string[];
updated: boolean;
}; | the_stack |
import * as t from '@webassemblyjs/ast';
import { print } from '@webassemblyjs/wast-printer';
declare var global: any;
global['Binaryen'] = {
TOTAL_MEMORY: 16777216 * 8
};
import * as binaryen from 'binaryen';
import _wabt = require('wabt');
import { annotations } from '../annotations';
import { flatten } from '../helpers';
import { Nodes, findNodesByType, PhaseFlags } from '../nodes';
import { findParentType } from '../nodeHelpers';
import { FunctionType, TypeHelpers, IntersectionType, FunctionSignatureType, Type } from '../types';
import { LysCompilerError } from '../NodeError';
import { ParsingContext } from '../ParsingContext';
import { printAST } from '../../utils/astPrinter';
import { getModuleSet } from './helpers';
import { failWithErrors } from '../findAllErrors';
type CompilationModuleResult = {
document: Nodes.DocumentNode;
moduleParts: any[];
starters: any[];
endMemory: number;
imports: any[];
};
const wabt = _wabt();
const starterName = t.identifier('%%START%%');
declare var WebAssembly: any;
const optimizeLevel = 3;
const shrinkLevel = 0;
const secSymbol = Symbol('secuentialId');
function restartFunctionSeqId(node: Nodes.FunctionNode) {
(node as any)[secSymbol] = 0;
}
function getFunctionSeqId(node: Nodes.Node) {
let fun = findParentType(node, Nodes.FunctionNode) || findParentType(node, Nodes.DocumentNode);
let num = (fun as any)[secSymbol] || 0;
num++;
(fun as any)[secSymbol] = num;
return num;
}
function getStarterFunction(statements: any[]) {
const fnType = t.signature([], []);
return t.func(
starterName, // name
fnType, // signature
statements // body
);
}
function getTypeForFunctionType(fn: Type | null, errorNode: Nodes.Node) {
if (!fn) {
throw new LysCompilerError('node has no type', errorNode);
} else if (fn instanceof FunctionSignatureType) {
if (fn.returnType) {
const ret = fn.returnType;
const retType = ret.binaryenType ? [ret.binaryenType] : [];
// tslint:disable:ter-indent
return t.signature(
fn.parameterTypes.map(($, $$) => ({
id: fn.parameterNames[$$] || '$param' + $$,
valtype: $.binaryenType
})),
retType
);
}
throw new LysCompilerError(fn + ' has no return type', errorNode);
} else {
throw new LysCompilerError(fn + ' is not a function 1', errorNode);
}
}
function getTypeForFunction(fn: Nodes.FunctionNode) {
const fnType = TypeHelpers.getNodeType(fn.functionName);
if (fnType && fnType instanceof FunctionType) {
return getTypeForFunctionType(fnType.signature, fn);
} else if (fnType) {
throw new LysCompilerError(fnType + ' is not a function 2', fn);
} else {
throw new LysCompilerError('Function did not resolve any type', fn);
}
}
function emitFunction(fn: Nodes.FunctionNode, document: Nodes.DocumentNode, parsingContext: ParsingContext) {
const fnType = getTypeForFunction(fn);
restartFunctionSeqId(fn);
const locals = fn.additionalLocals.map($ =>
t.instruction('local', [t.identifier($.name), t.valtypeLiteral($.type!.binaryenType)])
);
if (!fn.body) throw new LysCompilerError('Function has no body', fn);
const moduleFun = t.func(
t.identifier(fn.functionName.internalIdentifier), // name
fnType, // signature
[...locals, ...emitList(fn.body, document, parsingContext)] // body
);
return moduleFun;
}
function emitLoop(node: Nodes.LoopNode, document: Nodes.DocumentNode, parsingContext: ParsingContext) {
const loopId = getFunctionSeqId(node);
node.annotate(new annotations.LabelId(loopId));
const continueLabel = t.identifier('Loop' + loopId);
const breakLabel = t.identifier('Break' + loopId);
return t.blockInstruction(breakLabel, [
t.loopInstruction(continueLabel, void 0, emitList(node.body, document, parsingContext))
]);
}
function emitMatchingNode(
match: Nodes.PatternMatcherNode,
document: Nodes.DocumentNode,
parsingContext: ParsingContext
) {
const matchers = match.matchingSet.slice(0);
const ixDefaultBranch = matchers.findIndex($ => $ instanceof Nodes.MatchDefaultNode);
const local = match.getAnnotation(annotations.LocalIdentifier)!.local;
const lhs = t.instruction('local.set', [t.identifier(local.name), emit(match.lhs, document, parsingContext)]);
if (ixDefaultBranch !== -1) {
// the default branch must be the last element
const defaultMatcher = matchers[ixDefaultBranch];
matchers.splice(ixDefaultBranch, 1);
matchers.push(defaultMatcher);
}
const blocks = matchers
.map(function emitNode(node: Nodes.MatcherNode): { condition: any; body: any } {
if (node instanceof Nodes.MatchDefaultNode) {
const body = emit(node.rhs, document, parsingContext);
return { condition: null, body };
} else if (node instanceof Nodes.MatchLiteralNode) {
const ofType = node.resolvedFunctionType;
if (!ofType) throw new LysCompilerError('MatchLiteralNode.resolvedFunctionType is not resolved', node);
const local = match.getAnnotation(annotations.LocalIdentifier)!.local;
const condition = t.callInstruction(t.identifier(ofType.name.internalIdentifier), [
t.instruction('local.get', [t.identifier(local.name)]),
emit(node.literal, document, parsingContext)
]);
const body = emit(node.rhs, document, parsingContext);
return {
condition,
body
};
} else if (node instanceof Nodes.MatchCaseIsNode) {
const ofType = node.resolvedFunctionType;
if (!ofType) throw new LysCompilerError('MatchCaseIsNode.resolvedFunctionType is not resolved', node);
const local = match.getAnnotation(annotations.LocalIdentifier)!.local;
const condition = t.callInstruction(t.identifier(ofType.name.internalIdentifier), [
t.instruction('local.get', [t.identifier(local.name)])
]);
const body = emit(node.rhs, document, parsingContext);
return {
condition,
body
};
}
throw new LysCompilerError("I don't know how handle this", node);
})
.filter($ => !!$);
const exitBlock = 'B' + getFunctionSeqId(match);
const exitLabel = t.identifier(exitBlock);
const breaks = blocks
.filter($ => !!$.condition)
.map(($, $$) => t.instruction('br_if', [t.identifier(`${exitBlock}_${$$}`), $.condition]));
const ret = blocks.reduceRight((prev, curr, ix) => {
const label = t.identifier(`${exitBlock}_${ix}`);
const newBlock = t.blockInstruction(label, flatten(prev));
const ret = flatten([newBlock, curr.body]);
ret.push(t.instruction('br', [exitLabel]));
return ret;
}, breaks);
const matchType = TypeHelpers.getNodeType(match);
if (!matchType) throw new LysCompilerError('ofType not defined', match);
return t.blockInstruction(t.identifier(exitBlock), flatten([lhs, ret]), matchType.binaryenType);
}
function emitList(nodes: Nodes.Node[] | Nodes.Node, document: Nodes.DocumentNode, parsingContext: ParsingContext) {
if (nodes instanceof Array) {
return flatten(nodes.map($ => emit($, document, parsingContext)));
} else {
return flatten([emit(nodes, document, parsingContext)]);
}
}
function emitWast(node: Nodes.WasmAtomNode, document: Nodes.DocumentNode, parsingContext: ParsingContext): any {
if (node instanceof Nodes.ReferenceNode) {
let ofType = TypeHelpers.getNodeType(node);
if (ofType instanceof IntersectionType) {
if (ofType.of.length > 1) {
throw new LysCompilerError(
'This reference has multiple overloads. From WASM you can only reference non-overloaded functions',
node
);
}
ofType = ofType.of[0];
}
if (ofType instanceof FunctionType) {
return t.identifier(ofType.name.internalIdentifier);
} else {
return t.identifier(node.resolvedReference!.referencedNode.internalIdentifier!);
}
}
if (node instanceof Nodes.QNameNode) {
return t.valtypeLiteral(node.text);
}
if (node instanceof Nodes.HexLiteral) {
return t.numberLiteralFromRaw(node.astNode.text);
}
if (node instanceof Nodes.IntegerLiteral) {
return t.numberLiteralFromRaw(node.value);
}
if (node instanceof Nodes.FloatLiteral) {
return t.numberLiteralFromRaw(node.value);
}
return t.instruction(
node.symbol,
(node.args || []).map($ => emitWast($ as any, document, parsingContext))
);
}
function emitImplicitCall(node: Nodes.Node, document: Nodes.DocumentNode, parsingContext: ParsingContext) {
const implicitCallData = node.getAnnotation(annotations.ImplicitCall)!;
const ofType = implicitCallData.implicitCall.resolvedFunctionType;
if (!ofType) throw new LysCompilerError('ofType not defined', node);
if (false === ofType instanceof FunctionType) throw new LysCompilerError('implicit call is not a function', node);
return t.callInstruction(
t.identifier(ofType.name.internalIdentifier),
implicitCallData.implicitCall.argumentsNode.map($ => emit($, document, parsingContext))
);
}
function getReferencedSymbol(node: Nodes.Node): { symbol: string; type: 'VALUE' | 'TABLE' } {
const local = node.getAnnotation(annotations.LocalIdentifier);
if (local) {
return {
symbol: local.local.name,
type: 'VALUE'
};
}
const fn = node.getAnnotation(annotations.FunctionInTable);
if (fn) {
if (!fn.nameIdentifier.internalIdentifier) {
throw new LysCompilerError('fn.nameIdentifier.internalIdentifier is falsy', node);
}
return {
symbol: fn.nameIdentifier.internalIdentifier,
type: 'TABLE'
};
}
throw new LysCompilerError('Cannot resolve WASM symbol', node);
}
function getTypeSignature(fn: Type | null, errorNode: Nodes.Node, parsingContext: ParsingContext): any {
if (!fn) {
throw new LysCompilerError('node has no type', errorNode);
} else if (fn instanceof FunctionSignatureType) {
if (fn.returnType) {
const ret = fn.returnType;
const retType = ret.binaryenType ? [ret.binaryenType] : [];
const name =
'lys::' + fn.parameterTypes.map($ => $.binaryenType).join('_') + '->' + (retType.join('_') || 'void');
if (!parsingContext.signatures.has(name)) {
parsingContext.signatures.set(
name,
t.typeInstruction(
t.identifier(name),
t.signature(
fn.parameterTypes.map($ => ({
valtype: $.binaryenType
})),
retType
)
)
);
}
return t.identifier(name);
}
throw new LysCompilerError(fn + ' has no return type', errorNode);
} else {
throw new LysCompilerError(fn + ' is not a function 1', errorNode);
}
}
function emit(node: Nodes.Node, document: Nodes.DocumentNode, parsingContext: ParsingContext): any {
function _emit() {
if (node.hasAnnotation(annotations.ImplicitCall)) {
return emitImplicitCall(node, document, parsingContext);
} else if (node instanceof Nodes.AbstractFunctionCallNode) {
const funType = node.resolvedFunctionType;
if (!funType && node.hasAnnotation(annotations.ByPassFunction)) {
return emit(node.argumentsNode[0], document, parsingContext);
}
if (!funType && node instanceof Nodes.FunctionCallNode) {
const annotation = node.getAnnotation(annotations.IsFunctionReference);
if (annotation) {
const fnType = TypeHelpers.getNodeType(node.functionNode);
const signature = getTypeSignature(fnType, node, parsingContext);
return t.callIndirectInstruction(
signature,
node.argumentsNode
.map($ => emit($, document, parsingContext))
.concat(emit(node.functionNode, document, parsingContext))
);
}
}
if (!funType) {
throw new LysCompilerError(`funType is falsy`, node);
}
if (!funType.name.internalIdentifier) throw new LysCompilerError(`${funType}.internalIdentifier is falsy`, node);
return t.callInstruction(
t.identifier(funType.name.internalIdentifier),
node.argumentsNode.map($ => emit($, document, parsingContext))
);
} else if (node instanceof Nodes.UnknownExpressionNode) {
return t.instruction('unreachable', []);
} else if (node instanceof Nodes.WasmExpressionNode) {
return flatten(node.atoms.map($ => emitWast($, document, parsingContext)));
} else if (node instanceof Nodes.ContinueNode) {
const loopLabel = node.getAnnotation(annotations.CurrentLoop)!.loop.getAnnotation(annotations.LabelId)!;
return t.instruction('br', [t.identifier('Loop' + loopLabel.label)]);
} else if (node instanceof Nodes.BreakNode) {
const loopLabel = node.getAnnotation(annotations.CurrentLoop)!.loop.getAnnotation(annotations.LabelId)!;
return t.instruction('br', [t.identifier('Break' + loopLabel.label)]);
} else if (node instanceof Nodes.IntegerLiteral) {
const type = TypeHelpers.getNodeType(node)!.binaryenType;
return t.objectInstruction('const', type, [t.numberLiteralFromRaw(node.astNode.text)]);
} else if (node instanceof Nodes.BooleanLiteral) {
return t.objectInstruction('const', 'i32', [t.numberLiteralFromRaw(node.value ? 1 : 0)]);
} else if (node instanceof Nodes.StringLiteral) {
const discriminant = TypeHelpers.getNodeType(node)!.getSchemaValue('discriminant', node.scope!);
const discriminantHex = ('00000000' + discriminant.toString(16)).substr(-8);
const offset = ('00000000' + node.offset!.toString(16)).substr(-8);
return t.objectInstruction('const', 'i64', [t.numberLiteralFromRaw('0x' + discriminantHex + offset, 'i64')]);
} else if (node instanceof Nodes.FloatLiteral) {
return t.objectInstruction('const', 'f32', [t.numberLiteralFromRaw(node.value)]);
} else if (node instanceof Nodes.PatternMatcherNode) {
return emitMatchingNode(node, document, parsingContext);
} else if (node instanceof Nodes.LoopNode) {
return emitLoop(node, document, parsingContext);
} else if (node instanceof Nodes.VarDeclarationNode) {
const local = node.getAnnotation(annotations.LocalIdentifier)!.local;
return t.instruction('local.set', [t.identifier(local.name), emit(node.value, document, parsingContext)]);
} else if (node instanceof Nodes.AssignmentNode) {
if (node.lhs instanceof Nodes.ReferenceNode) {
const isLocal = node.lhs.isLocal;
const isValueNode = node.hasAnnotation(annotations.IsValueNode);
if (isLocal) {
const instr = isValueNode ? 'local.tee' : 'local.set';
const local = node.lhs.getAnnotation(annotations.LocalIdentifier)!.local;
return t.instruction(instr, [t.identifier(local.name), emit(node.rhs, document, parsingContext)]);
} else {
if (isValueNode) {
const local = node.lhs.getAnnotation(annotations.LocalIdentifier)!.local;
return t.blockInstruction(
t.identifier('tee_global_' + getFunctionSeqId(node)),
[
t.instruction('global.set', [t.identifier(local.name), emit(node.rhs, document, parsingContext)]),
t.instruction('global.get', [t.identifier(local.name)])
],
TypeHelpers.getNodeType(node.rhs)!.binaryenType
);
} else {
const local = node.lhs.getAnnotation(annotations.LocalIdentifier)!.local;
return t.instruction('global.set', [t.identifier(local.name), emit(node.rhs, document, parsingContext)]);
}
}
} else {
throw new Error('Error emiting AssignmentNode');
}
} else if (node instanceof Nodes.BlockNode) {
// a if (!node.label) throw new Error('Block node without label');
const label = t.identifier(node.label || 'B' + getFunctionSeqId(node));
const type = TypeHelpers.getNodeType(node)!.binaryenType;
let instr: any[] = [];
node.statements.forEach($ => {
// TODO: Drop here things
let emited = emit($, document, parsingContext);
const type = TypeHelpers.getNodeType($);
if (type && type.binaryenType !== undefined && !$.hasAnnotation(annotations.IsValueNode)) {
if (emited instanceof Array) {
throw new LysCompilerError(`\n\n\nshould drop: ${JSON.stringify(emited, null, 2)}`, $);
} else {
emited = t.instruction('drop', [emited]);
}
}
instr = instr.concat(emited);
});
if (instr.length === 0) {
instr.push(t.instruction('nop'));
}
return t.blockInstruction(label, instr, type);
} else if (node instanceof Nodes.IfNode) {
return t.ifInstruction(
t.identifier('IF' + getFunctionSeqId(node)),
[emit(node.condition, document, parsingContext)],
TypeHelpers.getNodeType(node)!.binaryenType,
emitList(node.truePart, document, parsingContext),
node.falsePart ? emitList(node.falsePart, document, parsingContext) : []
);
} else if (node instanceof Nodes.ReferenceNode) {
const ref = getReferencedSymbol(node);
if (ref.type === 'VALUE') {
const instr = node.isLocal ? 'local.get' : 'global.get';
return t.instruction(instr, [t.identifier(ref.symbol)]);
} else if (ref.type === 'TABLE') {
const index = parsingContext.getFunctionInTableNumber(ref.symbol);
const numberLiteral = t.numberLiteralFromRaw(index, 'i32');
return t.objectInstruction('const', 'i32', [numberLiteral]);
}
} else if (node instanceof Nodes.MemberNode) {
if (node.operator === '.^') {
const schemaType = TypeHelpers.getNodeType(node.lhs);
if (!schemaType) throw new LysCompilerError('schemaType not defined', node);
const type = schemaType.schema()[node.memberName.name];
try {
const value = schemaType.getSchemaValue(node.memberName.name, node.scope!);
if (value === null || isNaN(value)) {
throw new LysCompilerError(`Value was undefined`, node.memberName);
}
return t.objectInstruction('const', type.binaryenType, [t.numberLiteralFromRaw(value)]);
} catch (e) {
if (e instanceof LysCompilerError) throw e;
throw new LysCompilerError(e.message, node.memberName);
}
} else if (node.resolvedReference) {
const instr = node.resolvedReference.isLocalReference ? 'local.get' : 'global.get';
const local = node.getAnnotation(annotations.LocalIdentifier)!.local;
return t.instruction(instr, [t.identifier(local.name)]);
}
console.trace();
}
throw new LysCompilerError(`This node cannot be emited ${node.nodeName}\n${printAST(node)}`, node);
}
const generatedNode = _emit();
if (!generatedNode) throw new LysCompilerError(`Could not emit any code for node ${node.nodeName}`, node);
return generatedNode;
}
export class CodeGenerationPhaseResult {
programAST: any;
buffer?: Uint8Array;
sourceMap: string | null = null;
constructor(public document: Nodes.DocumentNode, public parsingContext: ParsingContext) {
failWithErrors(`Compilation`, parsingContext);
try {
this.execute();
} catch (e) {
this.parsingContext.messageCollector.error(e, this.document.astNode);
}
}
async validate(
optimize: boolean = true,
debug = false
): Promise<{
callGraph?: string;
}> {
let text = print(this.programAST);
const theWabt = await wabt;
let wabtModule: ReturnType<typeof theWabt.parseWat>;
try {
wabtModule = theWabt.parseWat(this.document.moduleName, text, {});
} catch (e) {
const invalidFile = this.parsingContext.system.resolvePath(this.parsingContext.system.getCurrentDirectory(), 'failed_debug_wat.wat')
this.parsingContext.system.writeFile(invalidFile, text)
console.error('Error while parsing generated code. Writing debug WAT to ' + invalidFile)
console.error(e);
throw e;
}
try {
wabtModule.resolveNames();
wabtModule.validate();
} catch (e) {
const invalidFile = this.parsingContext.system.resolvePath(this.parsingContext.system.getCurrentDirectory(), 'failed_debug_wat.wat')
this.parsingContext.system.writeFile(invalidFile, text)
console.error('Error while resolving names and validate code. Writing debug WAT to ' + invalidFile)
console.error(e);
this.parsingContext.messageCollector.error(e, this.document.astNode);
throw e;
}
const binary = wabtModule.toBinary({ log: false, write_debug_names: debug });
wabtModule.destroy();
try {
binaryen.setOptimizeLevel(optimizeLevel);
binaryen.setShrinkLevel(shrinkLevel);
binaryen.setDebugInfo(debug || !optimize);
const module = binaryen.readBinary(binary.buffer);
if (!debug) {
module.runPasses(['duplicate-function-elimination']);
}
module.runPasses(['remove-unused-module-elements']);
if (module.validate() === 0) {
this.parsingContext.messageCollector.error(new LysCompilerError('binaryen validation failed', this.document));
}
if (debug) {
let last = module.emitBinary('sourceMap.map');
if (optimize) {
do {
module.optimize();
let next = module.emitBinary('sourceMap.map');
if (next.binary.length >= last.binary.length) {
// a if (next.length > last.length) {
// a this.parsingContext.system.write('Last converge was suboptimial.\n');
// a }
break;
}
last = next;
} while (true);
}
this.buffer = last.binary;
this.sourceMap = last.sourceMap;
} else {
let last = module.emitBinary();
if (optimize) {
do {
module.optimize();
let next = module.emitBinary();
if (next.length >= last.length) {
// a if (next.length > last.length) {
// a this.parsingContext.system.write('Last converge was suboptimial.\n');
// a }
break;
}
last = next;
} while (true);
}
this.buffer = last;
}
module.dispose();
return {};
} catch (e) {
if (e instanceof Error) throw e;
throw new Error(e);
}
}
emitText() {
if (this.buffer) {
const module = binaryen.readBinary(this.buffer);
const ret = module.emitText();
module.dispose();
return ret;
} else if (this.programAST) {
return print(this.programAST);
}
throw new Error('Impossible to emitText');
}
optimize() {
// stub
}
/** This method only exists for test porpuses */
async toInstance(extra: Record<string, Record<string, any>> = {}) {
if (!this.buffer) throw new Error("You didn't generate a binary yet");
// Create the imports for the module, including the
// standard dynamic library imports
const imports = extra || {
env: {
memoryBase: 0,
tableBase: 0,
memory: new WebAssembly.Memory({ initial: 256 }),
table: new WebAssembly.Table({ initial: 0, element: 'anyfunc' })
}
};
// Create the instance.
const compiled = await WebAssembly.compile(this.buffer);
return new WebAssembly.Instance(compiled, imports);
}
generatePhase(document: Nodes.DocumentNode, startMemory: number): CompilationModuleResult {
const globals = findNodesByType(document, Nodes.VarDirectiveNode);
const functions = findNodesByType(document, Nodes.OverloadedFunctionNode);
const bytesLiterals = findNodesByType(document, Nodes.StringLiteral);
const starters: any[] = [];
const imports: any[] = [];
const exportedElements: any[] = [];
const createdFunctions: any[] = [];
const dataSection: any[] = [];
const endMemory = bytesLiterals.reduce<number>((offset, literal) => {
if (literal.parent instanceof Nodes.DecoratorNode) {
return offset;
} else {
const str = literal.value as string;
const bytes: number[] = [];
const byteSize = str.length * 2;
bytes.push(byteSize & 0xff);
bytes.push((byteSize >> 8) & 0xff);
bytes.push((byteSize >> 16) & 0xff);
bytes.push((byteSize >> 24) & 0xff);
for (let index = 0; index < str.length; index++) {
const char = str.charCodeAt(index);
bytes.push(char & 0xff);
bytes.push(char >> 8);
}
bytes.push(0);
const size = bytes.length;
literal.offset = offset;
literal.length = size;
const numberLiteral = t.numberLiteralFromRaw(offset, 'i32');
const offsetToken = t.objectInstruction('const', 'i32', [numberLiteral]);
dataSection.push(t.data(t.memIndexLiteral(0), offsetToken, t.byteArray(bytes)));
return offset + size;
}
}, startMemory);
const createdGlobals = globals.map($ => {
// TODO: If the value is a literal, do not defer initialization to starters
const mut = 'var'; // TODO: $ instanceof Nodes.ValDeclarationNode ? 'const' : 'var';
const binaryenType = TypeHelpers.getNodeType($.decl.variableName)!.binaryenType;
const localDecl = $.decl.getAnnotation(annotations.LocalIdentifier)!;
const local = localDecl.local;
const identifier = t.identifier(local.name);
starters.push(
t.instruction('global.set', [identifier, ...emitList($.decl.value, document, this.parsingContext)])
);
return t.global(
t.globalType(binaryenType, mut),
[t.objectInstruction('const', binaryenType, [t.numberLiteralFromRaw(0)])], // emitList($.decl.value, compilationPhase.document),
identifier
);
});
functions.forEach($ => {
if ($.parent instanceof Nodes.TraitDirectiveNode) return;
$.functions.forEach(fun => {
const functionName = fun.functionNode.functionName;
if (functionName.hasAnnotation(annotations.Extern)) {
const extern = functionName.getAnnotation(annotations.Extern)!;
const fnType = getTypeForFunction(fun.functionNode);
imports.push(
t.moduleImport(
extern.module,
extern.fn,
t.funcImportDescr(t.identifier(functionName.internalIdentifier), fnType)
)
);
} else {
createdFunctions.push(emitFunction(fun.functionNode, document, this.parsingContext));
}
const exportedAnnotation = functionName.getAnnotation(annotations.Export);
// TODO: verify we are not exporting two things with the same name
if (exportedAnnotation) {
exportedElements.push(
t.moduleExport(
exportedAnnotation.exportedName,
t.moduleExportDescr('Func', t.identifier(functionName.internalIdentifier))
)
);
}
});
});
return {
document,
moduleParts: [...dataSection, ...createdGlobals, ...(exports ? exportedElements : []), ...createdFunctions],
starters,
endMemory,
imports
};
}
protected execute() {
const exportList = [this.document];
const moduleList = getModuleSet(this.document, this.parsingContext);
moduleList.forEach($ => {
const compilation = this.parsingContext.getPhase($, PhaseFlags.Compilation);
if (!exportList.includes(compilation)) {
exportList.push(compilation);
}
});
let currentMemory = 16;
const moduleParts = [];
const generatedModules = exportList.map($ => {
const ret = this.generatePhase($, currentMemory);
currentMemory = ret.endMemory;
moduleParts.push(...ret.imports);
return ret;
});
const starters: any[] = [];
const tableElems = this.parsingContext.getOrderedTable();
this.parsingContext.signatures.forEach($ => moduleParts.push($));
const table = t.table('anyfunc', t.limit(tableElems.length), t.identifier('lys::internal-functions'));
const elem = t.elem(
// table
t.indexLiteral(0),
// offset
[t.objectInstruction('const', 'i32', [t.numberLiteralFromRaw(0)])],
// elems
tableElems.map(x => t.identifier(x))
);
const memory = t.memory(t.limit(1), t.identifier('mem'));
moduleParts.push(table);
if (tableElems.length) {
moduleParts.push(elem);
}
moduleParts.push(memory);
moduleParts.push(t.moduleExport('memory', t.moduleExportDescr('Memory', t.identifier('mem'))));
generatedModules.reverse().forEach(ret => {
moduleParts.push(...ret.moduleParts);
starters.push(...ret.starters);
});
if (starters.length) {
const starter = getStarterFunction(starters);
moduleParts.push(starter);
moduleParts.push(t.start(starterName));
}
const module = t.module(null, moduleParts);
this.programAST = t.program([module]);
}
} | the_stack |
import { JSXSlack } from '../src/index'
import { mrkdwn } from '../src/mrkdwn/index'
beforeEach(() => JSXSlack.exactMode(false))
describe('HTML parser for mrkdwn', () => {
it('throws error when using not supported tag', () => {
// @ts-expect-error
expect(() => mrkdwn(<div>test</div>)).toThrow(/unknown/i)
})
// https://api.slack.com/messaging/composing/formatting#escaping
describe('Escape entity', () => {
it('replaces "&" with "&"', () => {
expect(mrkdwn('&&&')).toBe('&&&')
expect(mrkdwn('&heart;')).toBe('&heart;')
})
it('allows double escaping', () => {
expect(mrkdwn('true && false')).toBe('true &amp;& false')
expect(mrkdwn('A<=>B')).toBe('A&lt;=&gt;B')
})
it('replaces "<" with "<"', () => expect(mrkdwn('a<2')).toBe('a<2'))
it('replaces ">" with ">"', () => expect(mrkdwn('b>0')).toBe('b>0'))
it('does not conflict element-like string with internals', () => {
expect(mrkdwn('<br />')).toBe('<br />')
expect(mrkdwn('<<pre:0>>')).toBe('<<pre:0>>')
})
})
describe('HTML entities', () => {
it('decodes HTML entities passed as JSX', () =>
expect(mrkdwn(<i>♥</i>)).toBe('_\u2665_'))
it('re-encodes special characters in Slack', () =>
expect(mrkdwn(<i><&></i>)).toBe('_<&>_'))
it('does not decode HTML entities passed as string literal', () => {
expect(mrkdwn(<i>{'♥'}</i>)).toBe('_&hearts;_')
expect(mrkdwn(<i>{'<&>'}</i>)).toBe(
'_&lt;&amp;&gt;_'
)
expect(mrkdwn(<i><{'<mixed>'}></i>)).toBe('_<<mixed>>_')
})
it('keeps special spaces around the content', () => {
expect(
mrkdwn(
<i>
{' '}test{' '}
</i>
)
).toBe('_test_')
expect(mrkdwn(<i>		tab		</i>)).toBe('_tab_')
expect(
mrkdwn(<i>    sp    </i>)
).toBe('_\u2009\u00a0\u2002\u2003sp\u2003\u2002\u00a0\u2009_')
})
})
describe('Italic', () => {
it('replaces <i> tag to italic markup', () =>
expect(mrkdwn(<i>Hello</i>)).toBe('_Hello_'))
it('replaces <em> tag to italic markup', () =>
expect(mrkdwn(<em>Hello</em>)).toBe('_Hello_'))
it('allows containing the other markup', () =>
expect(
mrkdwn(
<i>
Hello, <b>World</b>!
</i>
)
).toBe('_Hello, *World*!_'))
it('ignores invalid double markup', () =>
expect(
mrkdwn(
<i>
<i>Double</i>
</i>
)
).toBe('_Double_'))
it('allows containing underscore by using fallback of date formatting', () => {
expect(mrkdwn(<i>italic_text</i>)).toBe(
'_italic<!date^00000000^{_}|_>text_'
)
// Full-width underscore (Alternative for italic markup)
expect(mrkdwn(<i>Hello, _World_!</i>)).toBe(
'_Hello, <!date^00000000^{_}|_>World<!date^00000000^{_}|_>!_'
)
})
it('replaces underscore with similar character within hyperlink', () => {
expect(
mrkdwn(
<a href="https://example.com/">
<i>_test_</i>
</a>
)
).toBe('<https://example.com/|_\u02cdtest\u02cd_>')
expect(
mrkdwn(
<i>
<a href="https://example.com/">_test_</a>
</i>
)
).toBe('_<https://example.com/|\u02cdtest\u02cd>_')
expect(
mrkdwn(
<a href="https://example.com/">
<i>_test_</i>
</a>
)
).toBe('<https://example.com/|_\u2e0ftest\u2e0f_>')
expect(
mrkdwn(
<i>
<a href="https://example.com/">_test_</a>
</i>
)
).toBe('_<https://example.com/|\u2e0ftest\u2e0f>_')
})
it('does not escape underscore contained in valid emoji shorthand', () => {
expect(mrkdwn(<i>:arrow_down:</i>)).toBe('_:arrow_down:_')
expect(mrkdwn(<i>:絵_文字:</i>)).toBe('_:絵_文字:_')
})
it('does not escape underscore contained in valid link', () => {
expect(
mrkdwn(
<i>
<a href="https://example.com/a_b_c">_link_</a>
</i>
)
).toBe('_<https://example.com/a_b_c|\u02cdlink\u02cd>_')
})
it('does not escape underscore contained in valid time formatting', () => {
// NOTE: Fallback text will render as plain text even if containing character for formatting
expect(
mrkdwn(
<i>
<time dateTime={1234567890} fallback="fall_back">
{'{date_num} {time_secs}'}
</time>
</i>
)
).toBe('_<!date^1234567890^{date_num} {time_secs}|fall_back>_')
})
it('applies markup per each lines when text has multiline', () => {
expect(
mrkdwn(
<i>
foo
<br />
bar
</i>
)
).toBe('_foo_\n_bar_')
expect(
mrkdwn(
<i>
<p>foo</p>
<p>bar</p>
</i>
)
).toBe('_foo_\n\n_bar_')
})
it('inserts invisible spaces around markup chars when rendered in exact mode', () => {
JSXSlack.exactMode(true)
expect(mrkdwn(<i>Hello</i>)).toBe('\u200b_\u200bHello\u200b_\u200b')
})
})
describe('Bold', () => {
it('replaces <b> tag to bold markup', () =>
expect(mrkdwn(<b>Hello</b>)).toBe('*Hello*'))
it('replaces <strong> tag to bold markup', () =>
expect(mrkdwn(<strong>Hello</strong>)).toBe('*Hello*'))
it('allows containing the other markup', () =>
expect(
mrkdwn(
<b>
Hello, <i>World</i>!
</b>
)
).toBe('*Hello, _World_!*'))
it('ignores invalid double markup', () =>
expect(
mrkdwn(
<b>
<b>Double</b>
</b>
)
).toBe('*Double*'))
it('allows containing asterisk by using fallback of date formatting', () => {
expect(mrkdwn(<b>bold*text</b>)).toBe('*bold<!date^00000000^{_}|*>text*')
// Full-width asterisk (Alternative for bold markup)
expect(mrkdwn(<b>Hello, *World*!</b>)).toBe(
'*Hello, <!date^00000000^{_}|*>World<!date^00000000^{_}|*>!*'
)
})
it('replaces asterisk with similar character within hyperlink', () => {
expect(
mrkdwn(
<a href="https://example.com/">
<b>*test*</b>
</a>
)
).toBe('<https://example.com/|*\u2217test\u2217*>')
expect(
mrkdwn(
<b>
<a href="https://example.com/">*test*</a>
</b>
)
).toBe('*<https://example.com/|\u2217test\u2217>*')
expect(
mrkdwn(
<a href="https://example.com/">
<b>*test*</b>
</a>
)
).toBe('<https://example.com/|*\ufe61test\ufe61*>')
expect(
mrkdwn(
<b>
<a href="https://example.com/">*test*</a>
</b>
)
).toBe('*<https://example.com/|\ufe61test\ufe61>*')
})
it('applies markup per each lines when text has multiline', () => {
expect(
mrkdwn(
<b>
foo
<br />
bar
</b>
)
).toBe('*foo*\n*bar*')
expect(
mrkdwn(
<b>
<p>foo</p>
<p>bar</p>
</b>
)
).toBe('*foo*\n\n*bar*')
})
it('inserts invisible spaces around markup chars when rendered in exact mode', () => {
JSXSlack.exactMode(true)
expect(mrkdwn(<b>Hello</b>)).toBe('\u200b*\u200bHello\u200b*\u200b')
})
})
describe('Strikethrough', () => {
it('replaces <s> tag to strikethrough markup', () =>
expect(mrkdwn(<s>Hello</s>)).toBe('~Hello~'))
it('replaces <strike> tag to strikethrough markup', () =>
expect(mrkdwn(<strike>Hello</strike>)).toBe('~Hello~'))
it('replaces <del> tag to strikethrough markup', () =>
expect(mrkdwn(<del>Hello</del>)).toBe('~Hello~'))
it('allows containing the other markup', () =>
expect(
mrkdwn(
<s>
Hello, <b>World</b>!
</s>
)
).toBe('~Hello, *World*!~'))
it('ignores invalid double markup', () =>
expect(
mrkdwn(
<s>
<s>Double</s>
</s>
)
).toBe('~Double~'))
it('allows containing tilde by using fallback of date formatting', () =>
expect(mrkdwn(<s>strike~through</s>)).toBe(
'~strike<!date^00000000^{_}|~>through~'
))
it('replaces tilde with tilde operatpr within hyperlink', () => {
expect(
mrkdwn(
<a href="https://example.com/">
<s>~strikethrough~</s>
</a>
)
).toBe('<https://example.com/|~\u223cstrikethrough\u223c~>')
expect(
mrkdwn(
<s>
<a href="https://example.com/">~strikethrough~</a>
</s>
)
).toBe('~<https://example.com/|\u223cstrikethrough\u223c>~')
})
it('applies markup per each lines when text has multiline', () => {
expect(
mrkdwn(
<s>
foo
<br />
bar
</s>
)
).toBe('~foo~\n~bar~')
expect(
mrkdwn(
<s>
<p>foo</p>
<p>bar</p>
</s>
)
).toBe('~foo~\n\n~bar~')
})
it('inserts invisible spaces around markup chars when rendered in exact mode', () => {
JSXSlack.exactMode(true)
expect(mrkdwn(<s>Hello</s>)).toBe('\u200b~\u200bHello\u200b~\u200b')
})
})
describe('Inline code', () => {
it('replaces <code> tag to inline code markup', () => {
expect(mrkdwn(<code>Inline code</code>)).toBe('`Inline code`')
expect(mrkdwn(<code>*allow* _using_ ~markup~</code>)).toBe(
'`*allow* _using_ ~markup~`'
)
})
it('renders HTML special characters correctly', () =>
expect(mrkdwn(<code>{'<abbr title="and">&</abbr>'}</code>)).toBe(
'`<abbr title="and">&</abbr>`'
))
it('ignores invalid double markup', () =>
expect(
mrkdwn(
<code>
<code>Double</code>
</code>
)
).toBe('`Double`'))
it('does never apply nested markup', () =>
expect(
mrkdwn(
<code>
<b>bold</b> <i>italic</i> <s>strikethrough</s>
</code>
)
).toBe('`bold italic strikethrough`'))
it('allows containing backtick by using fallback of date formatting', () => {
expect(mrkdwn(<code>`code`</code>)).toBe(
'`<!date^00000000^{_}|`>code<!date^00000000^{_}|`>`'
)
// Full-width backtick (Alternative for inline code markup)
expect(mrkdwn(<code>`code`</code>)).toBe(
'`<!date^00000000^{_}|`>code<!date^00000000^{_}|`>`'
)
})
it('replaces backtick with similar character within hyperlink', () => {
expect(
mrkdwn(
<a href="https://example.com/">
<code>`code`</code>
</a>
)
).toBe('<https://example.com/|`\u02cbcode\u02cb`>')
expect(
mrkdwn(
<code>
<a href="https://example.com/">`code`</a>
</code>
)
).toBe('`<https://example.com/|\u02cbcode\u02cb>`')
expect(
mrkdwn(
<a href="https://example.com/">
<code>`code`</code>
</a>
)
).toBe('<https://example.com/|`\u02cbcode\u02cb`>')
expect(
mrkdwn(
<code>
<a href="https://example.com/">`code`</a>
</code>
)
).toBe('`<https://example.com/|\u02cbcode\u02cb>`')
})
it('applies markup per each lines when code has multiline', () => {
expect(
mrkdwn(
<code>
foo
<br />
bar
</code>
)
).toBe('`foo`\n`bar`')
expect(
mrkdwn(
<code>
foo
<br />
<br />
bar
</code>
)
).toBe('`foo`\n\n`bar`')
})
it('allows containing link', () => {
expect(
mrkdwn(
<>
<code>
<a href="https://example.com/">{'<example>'}</a>
</code>
<br />
<code>
<a href="@channel" />
</code>
</>
)
).toBe('`<https://example.com/|<example>>`\n`<!channel|channel>`')
})
it('allows containing time tag for localization', () => {
expect(
mrkdwn(
<code>
<time dateTime="1552212000">{'{date_num}'}</time>
</code>
)
).toBe('`<!date^1552212000^{date_num}|2019-03-10>`')
})
it('inserts invisible spaces around markup chars when rendered in exact mode', () => {
JSXSlack.exactMode(true)
expect(mrkdwn(<code>code</code>)).toBe('\u200b`\u200bcode\u200b`\u200b')
})
})
describe('Line break', () => {
it('replaces <br> tag to line break', () =>
expect(
mrkdwn(
<>
Hello,
<br />
<br />
<br />
World!
</>
)
).toBe('Hello,\n\n\nWorld!'))
})
describe('Paragraph', () => {
it('has no differences between 1 paragraph and plain rendering', () =>
expect(mrkdwn(<p>Hello!</p>)).toBe(mrkdwn('Hello!')))
it('makes a blank like between paragraphs', () => {
expect(
mrkdwn(
<>
<p>Hello!</p>
<p>World!</p>
</>
)
).toBe('Hello!\n\nWorld!')
// Combination with plain text
expect(
mrkdwn(
<>
A<p>B</p>C
</>
)
).toBe('A\n\nB\n\nC')
})
it('ignores invalid double markup', () =>
expect(
mrkdwn(
<p>
<p>Double</p>
</p>
)
).toBe('Double'))
})
describe('Blockquote', () => {
it('makes a blank like between blockquotes', () => {
expect(
mrkdwn(
<>
<blockquote>Hello!</blockquote>
<blockquote>World!</blockquote>
</>
)
).toBe('> Hello!\n> \n\n> World!\n> ')
// Combination with plain text and line breaks
expect(
mrkdwn(
<>
A<blockquote>B</blockquote>C
</>
)
).toBe('A\n\n> B\n> \n\nC')
// Combination with paragraph
expect(
mrkdwn(
<>
<p>test</p>
<blockquote>
<p>foo</p>
<p>bar</p>
</blockquote>
<p>test</p>
</>
)
).toBe('test\n\n> foo\n> \n> bar\n> \n\ntest')
expect(
mrkdwn(
<b>
<blockquote>
<p>A</p>
<i>B</i>
<p>C</p>
</blockquote>
</b>
)
).toBe('> *A*\n> \n> *_B_*\n> \n> *C*\n> ')
})
it('renders many tags in the blockquote tag immediately', () => {
// Test against ASCII and multibyte character
for (const testChars of ['abc', '亜']) {
const startTime = Date.now()
mrkdwn(
<blockquote>
{[...Array(30)].map(() => (
<b>{testChars}</b>
))}
</blockquote>
)
const processTime = Date.now() - startTime
expect(processTime).toBeLessThan(500)
}
})
it('ignores invalid double markup', () =>
expect(
mrkdwn(
<blockquote>
<blockquote>Double</blockquote>
</blockquote>
)
).toBe('> Double\n> '))
it('escapes blockquote mrkdwn character by inserting soft hyphen', () =>
expect(mrkdwn(<blockquote>> blockquote</blockquote>)).toBe(
'> \u00ad> blockquote\n> '
))
it('escapes full-width quote character by using fallback of date formatting', () =>
expect(mrkdwn(<blockquote>>blockquote</blockquote>)).toBe(
'> <!date^00000000^{_}|>>blockquote\n> '
))
it('always inserts soft hyphen when included quote character within hyperlink', () => {
expect(
mrkdwn(
<a href="https://example.com/">
<blockquote>> blockquote</blockquote>
</a>
)
).toBe('> <https://example.com/|\u00ad> blockquote>\n> ')
expect(
mrkdwn(
<blockquote>
<a href="https://example.com/">> blockquote</a>
</blockquote>
)
).toBe('> <https://example.com/|\u00ad> blockquote>\n> ')
expect(
mrkdwn(
<a href="https://example.com/">
<blockquote>>blockquote</blockquote>
</a>
)
).toBe('> <https://example.com/|\u00ad>blockquote>\n> ')
expect(
mrkdwn(
<blockquote>
<a href="https://example.com/">>blockquote</a>
</blockquote>
)
).toBe('> <https://example.com/|\u00ad>blockquote>\n> ')
})
})
describe('Pre-formatted text', () => {
it('makes line break and space between around contents', () => {
expect(
mrkdwn(
<>
foo<pre>{'pre\nformatted\ntext'}</pre>bar
</>
)
).toBe('foo\n```\npre\nformatted\ntext\n```\nbar')
expect(
mrkdwn(
<>
<p>foo</p>
<pre>{'pre\nformatted\ntext'}</pre>
<p>bar</p>
</>
)
).toBe('foo\n\n```\npre\nformatted\ntext\n```\n\nbar')
})
it('preserves whitespaces for indent', () => {
const preformatted = '{\n hello\n}'
expect(mrkdwn(<pre>{preformatted}</pre>)).toBe('```\n{\n hello\n}\n```')
// with <a> link
expect(
mrkdwn(
<pre>
{'{\n '}
<a href="https://example.com/">hello</a>
{'\n}'}
</pre>
)
).toBe('```\n{\n <https://example.com/|hello>\n}\n```')
})
it('allows wrapping by text format character', () =>
expect(
mrkdwn(
<b>
<i>
<pre>{'bold\nand italic'}</pre>
</i>
</b>
)
).toBe('*_```\nbold\nand italic\n```_*'))
it('does not apply wrapped strikethrough by Slack restriction', () =>
expect(
mrkdwn(
<s>
<blockquote>
strikethrough and
<pre>{'quoted\ntext'}</pre>
</blockquote>
</s>
)
).toBe('> ~strikethrough and~\n> ```\nquoted\ntext\n```\n> '))
it('renders HTML special characters correctly', () =>
expect(mrkdwn(<pre>{'<abbr title="and">&</abbr>'}</pre>)).toBe(
'```\n<abbr title="and">&</abbr>\n```'
))
it('allows containing link', () => {
expect(
mrkdwn(
<pre>
<a href="https://example.com/">example</a>
</pre>
)
).toBe('```\n<https://example.com/|example>\n```')
// with format
expect(
mrkdwn(
<pre>
<a href="https://example.com/">
<b>Bold</b> link
</a>
<br />
{'and plain\ntext'}
</pre>
)
).toBe('```\n<https://example.com/|*Bold* link>\nand plain\ntext\n```')
})
})
describe('List', () => {
it('converts unordered list to mimicked text', () => {
expect(
mrkdwn(
<ul>
<li>a</li>
<li>
<b>b</b>
</li>
<li>c</li>
</ul>
)
).toBe('• a\n• *b*\n• c')
})
it('converts ordered list to plain text', () => {
expect(
mrkdwn(
<ol>
<li>a</li>
<li>b</li>
<li>
<code>c</code>
</li>
</ol>
)
).toBe('1. a\n2. b\n3. `c`')
})
it('allows multiline content by aligned indent', () => {
expect(
mrkdwn(
<ul>
<li>
Hello, <br />
world!
</li>
<li>
<p>Paragraph</p>
<p>supported</p>
</li>
</ul>
)
).toBe('• Hello,\n\u2007 world!\n• Paragraph\n\u2007 \n\u2007 supported')
expect(
mrkdwn(
<ol>
<li>
Ordered
<br />
list
</li>
<li>
<p>Well</p>
<p>aligned</p>
</li>
</ol>
)
).toBe('1. Ordered\n list\n2. Well\n \n aligned')
})
it('allows setting start number via start attribute in ordered list', () => {
expect(
mrkdwn(
<ol start={9}>
<li>Change</li>
<li>
Start
<br />
number
</li>
</ol>
)
).toBe('\u20079. Change\n10. Start\n number')
// Coerce to integer
expect(
mrkdwn(
<ol start={3.5}>
<li>test</li>
</ol>
)
).toBe(
mrkdwn(
<ol start={3}>
<li>test</li>
</ol>
)
)
})
it('renders ordered number with lowercase latin alphabet when type attribute is "a"', () =>
expect(
mrkdwn(
<ol type={'a'} start={-1}>
<li>-1</li>
<li>0</li>
<li>1</li>
<li>2</li>
<li>3</li>
</ol>
)
).toBe('-1. -1\n 0. 0\n a. 1\n b. 2\n c. 3'))
it('renders ordered number with uppercase latin alphabet when type attribute is "A"', () => {
expect(
mrkdwn(
<ol type={'A'} start={25}>
<li>25</li>
<li>26</li>
<li>27</li>
</ol>
)
).toBe(' Y. 25\n Z. 26\nAA. 27')
expect(
mrkdwn(
<ol type={'A'} start={700}>
<li>700</li>
<li>701</li>
<li>702</li>
<li>703</li>
<li>704</li>
</ol>
)
).toBe(' ZX. 700\n ZY. 701\n ZZ. 702\nAAA. 703\nAAB. 704')
})
it('renders ordered number with lowercase roman numeric when type attribute is "i"', () =>
expect(
mrkdwn(
<ol type={'i'} start={-1}>
{[...Array(12)].map((_, i) => (
<li>{i - 1}</li>
))}
</ol>
)
).toBe(
' -1. -1\n 0. 0\n i. 1\n ii. 2\n iii. 3\n iv. 4\n v. 5\n vi. 6\n vii. 7\nviii. 8\n ix. 9\n x. 10'
))
it('renders ordered number with uppercase roman numeric when type attribute is "I"', () => {
expect(
mrkdwn(
<ol type={'I'} start={45}>
{[...Array(10)].map((_, i) => (
<li>{i + 45}</li>
))}
</ol>
)
).toBe(
' XLV. 45\n XLVI. 46\n XLVII. 47\nXLVIII. 48\n XLIX. 49\n L. 50\n LI. 51\n LII. 52\n LIII. 53\n LIV. 54'
)
expect(
mrkdwn(
<ol type={'I'} start={3991}>
{[...Array(10)].map((_, i) => (
<li>{i + 3991}</li>
))}
</ol>
)
).toBe(
' MMMCMXCI. 3991\n MMMCMXCII. 3992\n MMMCMXCIII. 3993\n MMMCMXCIV. 3994\n MMMCMXCV. 3995\n MMMCMXCVI. 3996\n MMMCMXCVII. 3997\nMMMCMXCVIII. 3998\n MMMCMXCIX. 3999\n 4000. 4000'
)
})
it('changes ordered number in the middle of list through value prop', () =>
expect(
mrkdwn(
<ol>
<li>1</li>
<li>2</li>
<li value={100}>100</li>
<li>101</li>
<li>102</li>
</ol>
)
).toBe(' 1. 1\n 2. 2\n100. 100\n101. 101\n102. 102'))
it('allows sub list', () => {
expect(
mrkdwn(
<ul>
<li>test</li>
<ul>
<li>sub-list with direct nesting</li>
</ul>
<li>
<ul>
<li>sub-list</li>
<li>
and
<ul>
<li>sub-sub-list</li>
</ul>
</li>
</ul>
</li>
</ul>
)
).toBe(
'• test\n ◦ sub-list with direct nesting\n• ◦ sub-list\n ◦ and\n ▪︎ sub-sub-list'
)
})
it('allows sub ordered list', () => {
expect(
mrkdwn(
<ol start={2}>
<li>test</li>
<ol>
<li>sub-list with direct nesting</li>
</ol>
<li>
<ol>
<li>sub-list</li>
<li>
and
<ul>
<li>sub-sub-list</li>
</ul>
</li>
</ol>
</li>
</ol>
)
).toBe(
'2. test\n 1. sub-list with direct nesting\n3. 1. sub-list\n 2. and\n ▪︎ sub-sub-list'
)
})
it('does not allow unsupported block components', () => {
expect(
mrkdwn(
<ul>
<li>
<pre>pre</pre>
</li>
<li>
<blockquote>blockquote</blockquote>
</li>
</ul>
)
).toBe('• pre\n• blockquote')
})
})
describe('Link and mention', () => {
it('converts <a> tag to mrkdwn link format', () => {
expect(mrkdwn(<a href="https://example.com/">Example</a>)).toBe(
'<https://example.com/|Example>'
)
expect(mrkdwn(<a href="mailto:mail@example.com">E-mail</a>)).toBe(
'<mailto:mail@example.com|E-mail>'
)
})
it('allows using elements inside <a> tag', () => {
expect(
mrkdwn(
<a href="https://example.com/">
<i>with</i> <b>text</b> <s>formatting</s>
</a>
)
).toBe('<https://example.com/|_with_ *text* ~formatting~>')
expect(
mrkdwn(
<a href="https://example.com/">
<pre>{'Link\npre-formatted\ntext'}</pre>
</a>
)
).toBe('<https://example.com/|```Link pre-formatted text```>')
// Apply link to the content if wrapped in block element
expect(
mrkdwn(
<a href="https://example.com/">
<blockquote>
Link blockquote
<br />
(Single line only)
</blockquote>
</a>
)
).toBe(
'> <https://example.com/|Link blockquote (Single line only)>\n> '
)
})
it('does not allow multiline contents to prevent breaking link', () =>
expect(
mrkdwn(
<a href="https://example.com/">
Ignore
<br />
multiline
</a>
)
).toBe('<https://example.com/|Ignore multiline>'))
it('is distributed to each content if wrapped in block elements', () =>
expect(
mrkdwn(
<a href="https://example.com/">
text
<p>paragraph</p>
<blockquote>blockquote</blockquote>
</a>
)
).toBe(
'<https://example.com/|text>\n\n<https://example.com/|paragraph>\n\n> <https://example.com/|blockquote>\n> '
))
it('escapes chars in URL by percent encoding', () =>
expect(
mrkdwn(<a href='https://example.com/?regex="<(i|em)>"'>escape test</a>)
).toBe('<https://example.com/?regex=%22%3C(i%7Cem)%3E%22|escape test>'))
it('uses short syntax if the content and URL are exactly same', () => {
expect(
mrkdwn(<a href="https://example.com/">https://example.com/</a>)
).toBe('<https://example.com/>')
const complexURL = `https://example.com/?regex='<b>'&fwc="*"`
expect(mrkdwn(<a href={complexURL}>{complexURL}</a>)).toBe(
`<https://example.com/?regex='<b>'&fwc="*">`
)
})
it('does not use short syntax even though having the same content if URL has included pipe', () =>
expect(
mrkdwn(
<a href="https://example.com/?q=a|b|c">
https://example.com/?q=a|b|c
</a>
)
).toBe('<https://example.com/?q=a%7Cb%7Cc|https://example.com/?q=a|b|c>'))
it('renders as plain text if href is empty', () =>
expect(mrkdwn(<a href="">empty</a>)).toBe('empty'))
it('converts to channel link when referenced public channel ID', () => {
expect(mrkdwn(<a href="#C0123ABCD" />)).toBe('<#C0123ABCD>')
expect(mrkdwn(<a href="#CLONGERCHANNELID" />)).toBe('<#CLONGERCHANNELID>')
expect(mrkdwn(<a href="#CWXYZ9876">Ignore contents</a>)).toBe(
'<#CWXYZ9876>'
)
expect(
mrkdwn(
<b>
<a href="#C0123ABCD" />
</b>
)
).toBe('*<#C0123ABCD>*')
})
it('converts to user mention when referenced user ID', () => {
expect(mrkdwn(<a href="@U0123ABCD" />)).toBe('<@U0123ABCD>')
expect(mrkdwn(<a href="@ULONGERUSERID" />)).toBe('<@ULONGERUSERID>')
expect(mrkdwn(<a href="@WGLOBALID" />)).toBe('<@WGLOBALID>')
expect(mrkdwn(<a href="@UWXYZ9876">Ignore contents</a>)).toBe(
'<@UWXYZ9876>'
)
expect(
mrkdwn(
<i>
<a href="@U0123ABCD" />
</i>
)
).toBe('_<@U0123ABCD>_')
})
it('converts to user group mention when referenced subteam ID', () => {
expect(mrkdwn(<a href="@S0123ABCD" />)).toBe('<!subteam^S0123ABCD>')
expect(mrkdwn(<a href="@SLONGERSUBTEAMID" />)).toBe(
'<!subteam^SLONGERSUBTEAMID>'
)
expect(mrkdwn(<a href="@SWXYZ9876">Ignore contents</a>)).toBe(
'<!subteam^SWXYZ9876>'
)
expect(
mrkdwn(
<s>
<a href="@S0123ABCD" />
</s>
)
).toBe('~<!subteam^S0123ABCD>~')
})
it('converts special mentions', () => {
expect(mrkdwn(<a href="@here" />)).toBe('<!here|here>')
expect(mrkdwn(<a href="@channel" />)).toBe('<!channel|channel>')
expect(mrkdwn(<a href="@everyone" />)).toBe('<!everyone|everyone>')
expect(mrkdwn(<a href="@here">Ignore contents</a>)).toBe('<!here|here>')
expect(
mrkdwn(
<b>
<i>
<a href="@here" />
</i>
</b>
)
).toBe('*_<!here|here>_*')
})
})
describe('Time localization', () => {
const today = new Date()
const yesterday = new Date(today.getTime() - 86400000)
const tomorrow = new Date(today.getTime() + 86400000)
it('converts <time> tag to mrkdwn format', () => {
expect(
mrkdwn(
<time dateTime="1552212000" fallback="fallback">
{'{date_num}'}
</time>
)
).toBe('<!date^1552212000^{date_num}|fallback>')
})
it('has aliased datetime prop into camelCase prop', () => {
expect(
mrkdwn(
// eslint-disable-next-line react/no-unknown-property
<time datetime={1552212000} fallback="fallback">
{'{date_num}'}
</time>
)
).toBe('<!date^1552212000^{date_num}|fallback>')
// Prefers to camelCase
expect(
mrkdwn(
<time
dateTime={'1234567890'}
datetime={1552212000} // eslint-disable-line react/no-unknown-property
fallback="fallback"
>
{'{date_num}'}
</time>
)
).toBe('<!date^1234567890^{date_num}|fallback>')
})
it('generates UTC fallback text from content if fallback attr is not defined', () => {
// 1552212000 => 2019-03-10 10:00:00 UTC (= 02:00 PST = 03:00 PDT)
expect(mrkdwn(<time dateTime={1552212000}>{'{date_num}'}</time>)).toBe(
'<!date^1552212000^{date_num}|2019-03-10>'
)
expect(mrkdwn(<time dateTime={1552212000}>{'{date}'}</time>)).toBe(
'<!date^1552212000^{date}|March 10th, 2019>'
)
expect(mrkdwn(<time dateTime={1552212000}>{'{date_short}'}</time>)).toBe(
'<!date^1552212000^{date_short}|Mar 10, 2019>'
)
expect(mrkdwn(<time dateTime={1552212000}>{'{date_long}'}</time>)).toBe(
'<!date^1552212000^{date_long}|Sunday, March 10th, 2019>'
)
expect(mrkdwn(<time dateTime={1552212000}>{'{time}'}</time>)).toBe(
'<!date^1552212000^{time}|10:00 AM>'
)
expect(mrkdwn(<time dateTime={1552212000}>{'{time_secs}'}</time>)).toBe(
'<!date^1552212000^{time_secs}|10:00:00 AM>'
)
// HTML entities
expect(
mrkdwn(<time dateTime={1552212000}><{'{date_num}'}></time>)
).toBe('<!date^1552212000^<{date_num}>|<2019-03-10>>')
expect(
mrkdwn(<time dateTime={1552212000}>{date_num} ♥</time>)
).toBe('<!date^1552212000^{date_num} \u2665|2019-03-10 \u2665>')
})
test.each`
dateTime | format | contain
${today} | ${'{date_pretty}'} | ${'Today'}
${today} | ${'{date_short_pretty}'} | ${'Today'}
${today} | ${'{date_long_pretty}'} | ${'Today'}
${today} | ${'At {date_pretty}'} | ${'At today'}
${today} | ${'At {date_short_pretty}'} | ${'At today'}
${today} | ${'At {date_long_pretty}'} | ${'At today'}
${yesterday} | ${'{date_pretty}'} | ${'Yesterday'}
${yesterday} | ${'{date_short_pretty}'} | ${'Yesterday'}
${yesterday} | ${'{date_long_pretty}'} | ${'Yesterday'}
${yesterday} | ${'At {date_pretty}'} | ${'At yesterday'}
${yesterday} | ${'At {date_short_pretty}'} | ${'At yesterday'}
${yesterday} | ${'At {date_long_pretty}'} | ${'At yesterday'}
${tomorrow} | ${'{date_pretty}'} | ${'Tomorrow'}
${tomorrow} | ${'{date_short_pretty}'} | ${'Tomorrow'}
${tomorrow} | ${'{date_long_pretty}'} | ${'Tomorrow'}
${tomorrow} | ${'At {date_pretty}'} | ${'At tomorrow'}
${tomorrow} | ${'At {date_short_pretty}'} | ${'At tomorrow'}
${tomorrow} | ${'At {date_long_pretty}'} | ${'At tomorrow'}
`(
'generates prettified fallback date "$contain" with format "$format"',
({ dateTime, format, contain }) => {
expect(mrkdwn(<time dateTime={dateTime}>{format}</time>)).toContain(
`|${contain}>`
)
}
)
it('ignores any elements in children', () => {
const date = new Date(Date.UTC(2019, 2, 10, 10, 0, 0))
expect(
mrkdwn(
<time dateTime={date} fallback="fallback">
<i>with</i> <b>text</b> <s>formatting</s>
</time>
)
).toBe('<!date^1552212000^with text formatting|fallback>')
expect(
mrkdwn(
<time dateTime={date} fallback="fallback">
Convert
<br />
line breaks
<br />
<br />
to a space
</time>
)
).toBe('<!date^1552212000^Convert line breaks to a space|fallback>')
expect(
mrkdwn(
<time dateTime={date} fallback="fallback">
<blockquote>test</blockquote>
<pre>test</pre>
<code>test</code>
<a href="https://example.com/">test</a>
</time>
)
).toBe('<!date^1552212000^testtesttesttest|fallback>')
})
it('integrates mrkdwn when <time> tag is linked', () => {
expect(
mrkdwn(
<a href="https://example.com/">
<time dateTime={1552212000} fallback="2019-03-10">
{'{date_num}'}
</time>
</a>
)
).toBe('<!date^1552212000^{date_num}^https://example.com/|2019-03-10>')
})
it('escapes brackets in contents and fallback', () => {
// NOTE: We have to escape brackets but Slack won't decode entities in fallback.
expect(
mrkdwn(
<time dateTime={1552212000} fallback="<2019-03-10>">
{'<{date_num}>'}
</time>
)
).toBe('<!date^1552212000^<{date_num}>|<2019-03-10>>')
})
it('escapes divider in contents and fallback', () => {
expect(
mrkdwn(
<time dateTime={1552212000} fallback="by XXX | 2019-03-10">
by XXX | {'{date_num}'}
</time>
)
).toBe(
'<!date^1552212000^by XXX \u01c0 {date_num}|by XXX \u01c0 2019-03-10>'
)
})
})
}) | the_stack |
import Vue from 'vue';
import Vuex from 'vuex';
import VueRouter from 'vue-router';
import VAnimateCss from 'v-animate-css';
import VModal from 'vue-js-modal';
import VueI18n from 'vue-i18n';
import SequentialEntrance from 'vue-sequential-entrance';
import VueHotkey from './common/hotkey';
import VueSize from './common/size';
import App from './app.vue';
import checkForUpdate from './common/scripts/check-for-update';
import MiOS from './mios';
import { version, codename, lang, locale } from './config';
import { builtinThemes, applyTheme, futureTheme } from './theme';
import Dialog from './common/views/components/dialog.vue';
if (localStorage.getItem('theme') == null) {
applyTheme(futureTheme);
}
//#region FontAwesome
import { library } from '@fortawesome/fontawesome-svg-core';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
import {
faRetweet,
faPlus,
faUser,
faCog,
faCheck,
faStar,
faReply,
faEllipsisH,
faQuoteLeft,
faQuoteRight,
faAngleUp,
faAngleDown,
faAt,
faHashtag,
faHome,
faGlobe,
faCircle,
faList,
faHeart,
faUnlock,
faRssSquare,
faSort,
faChartPie,
faChartBar,
faPencilAlt,
faColumns,
faComments,
faGamepad,
faCloud,
faPowerOff,
faChevronCircleLeft,
faChevronCircleRight,
faShareAlt,
faTimes,
faThumbtack,
faSearch,
faAngleRight,
faWrench,
faTerminal,
faMoon,
faPalette,
faSlidersH,
faDesktop,
faVolumeUp,
faLanguage,
faInfoCircle,
faExclamationTriangle,
faKey,
faBan,
faCogs,
faUnlockAlt,
faPuzzlePiece,
faMobileAlt,
faSignInAlt,
faSyncAlt,
faPaperPlane,
faUpload,
faMapMarkerAlt,
faEnvelope,
faLock,
faFolderOpen,
faBirthdayCake,
faImage,
faEye,
faDownload,
faFileImport,
faLink,
faArrowRight,
faICursor,
faCaretRight,
faReplyAll,
faCamera,
faMinus,
faCaretDown,
faCalculator,
faUsers,
faBars,
faFileImage,
faPollH,
faFolder,
faMicrochip,
faMemory,
faServer,
faExclamationCircle,
faSpinner,
faBroadcastTower,
faChartLine,
faEllipsisV,
faStickyNote,
faUserClock,
faUserPlus,
faExternalLinkSquareAlt,
faSync,
faArrowLeft,
faMapMarker,
faRobot,
faHourglassHalf,
faGavel
} from '@fortawesome/free-solid-svg-icons';
import {
faBell as farBell,
faEnvelope as farEnvelope,
faComments as farComments,
faTrashAlt as farTrashAlt,
faWindowRestore as farWindowRestore,
faFolder as farFolder,
faLaugh as farLaugh,
faSmile as farSmile,
faEyeSlash as farEyeSlash,
faFolderOpen as farFolderOpen,
faSave as farSave,
faImages as farImages,
faChartBar as farChartBar,
faCommentAlt as farCommentAlt,
faClock as farClock,
faCalendarAlt as farCalendarAlt,
faHdd as farHdd,
faMoon as farMoon,
faPlayCircle as farPlayCircle,
faLightbulb as farLightbulb,
faStickyNote as farStickyNote,
} from '@fortawesome/free-regular-svg-icons';
import {
faTwitter as fabTwitter,
faGithub as fabGithub,
faDiscord as fabDiscord
} from '@fortawesome/free-brands-svg-icons';
import i18n from './i18n';
library.add(
faRetweet,
faPlus,
faUser,
faCog,
faCheck,
faStar,
faReply,
faEllipsisH,
faQuoteLeft,
faQuoteRight,
faAngleUp,
faAngleDown,
faAt,
faHashtag,
faHome,
faGlobe,
faCircle,
faList,
faHeart,
faUnlock,
faRssSquare,
faSort,
faChartPie,
faChartBar,
faPencilAlt,
faColumns,
faComments,
faGamepad,
faCloud,
faPowerOff,
faChevronCircleLeft,
faChevronCircleRight,
faShareAlt,
faTimes,
faThumbtack,
faSearch,
faAngleRight,
faWrench,
faTerminal,
faMoon,
faPalette,
faSlidersH,
faDesktop,
faVolumeUp,
faLanguage,
faInfoCircle,
faExclamationTriangle,
faKey,
faBan,
faCogs,
faUnlockAlt,
faPuzzlePiece,
faMobileAlt,
faSignInAlt,
faSyncAlt,
faPaperPlane,
faUpload,
faMapMarkerAlt,
faEnvelope,
faLock,
faFolderOpen,
faBirthdayCake,
faImage,
faEye,
faDownload,
faFileImport,
faLink,
faArrowRight,
faICursor,
faCaretRight,
faReplyAll,
faCamera,
faMinus,
faCaretDown,
faCalculator,
faUsers,
faBars,
faFileImage,
faPollH,
faFolder,
faMicrochip,
faMemory,
faServer,
faExclamationCircle,
faSpinner,
faBroadcastTower,
faChartLine,
faEllipsisV,
faStickyNote,
faUserClock,
faUserPlus,
faExternalLinkSquareAlt,
faSync,
faArrowLeft,
faMapMarker,
faRobot,
faHourglassHalf,
faGavel,
farBell,
farEnvelope,
farComments,
farTrashAlt,
farWindowRestore,
farFolder,
farLaugh,
farSmile,
farEyeSlash,
farFolderOpen,
farSave,
farImages,
farChartBar,
farCommentAlt,
farClock,
farCalendarAlt,
farHdd,
farMoon,
farPlayCircle,
farLightbulb,
farStickyNote,
fabTwitter,
fabGithub,
fabDiscord
);
//#endregion
Vue.use(Vuex);
Vue.use(VueRouter);
Vue.use(VAnimateCss);
Vue.use(VModal);
Vue.use(VueHotkey);
Vue.use(VueSize);
Vue.use(VueI18n);
Vue.use(SequentialEntrance);
Vue.component('fa', FontAwesomeIcon);
// Register global directives
require('./common/views/directives');
// Register global components
require('./common/views/components');
require('./common/views/widgets');
// Register global filters
require('./common/views/filters');
Vue.mixin({
methods: {
destroyDom() {
this.$destroy();
if (this.$el.parentNode) {
this.$el.parentNode.removeChild(this.$el);
}
}
}
});
/**
* APP ENTRY POINT!
*/
console.info(`CMCC-SNS v${version} (${codename})`);
console.info(
`%c${locale['common']['do-not-copy-paste']}`,
'color: red; background: yellow; font-size: 16px; font-weight: bold;');
// BootTimer解除
window.clearTimeout((window as any).mkBootTimer);
delete (window as any).mkBootTimer;
//#region Set lang attr
const html = document.documentElement;
html.setAttribute('lang', lang);
//#endregion
// iOSでプライベートモードだとlocalStorageが使えないので既存のメソッドを上書きする
try {
localStorage.setItem('kyoppie', 'yuppie');
} catch (e) {
Storage.prototype.setItem = () => { }; // noop
}
// クライアントを更新すべきならする
if (localStorage.getItem('should-refresh') == 'true') {
localStorage.removeItem('should-refresh');
location.reload(true);
}
// MiOSを初期化してコールバックする
export default (callback: (launch: (router: VueRouter) => [Vue, MiOS], os: MiOS) => void, sw = false) => {
const os = new MiOS(sw);
os.init(() => {
// アプリ基底要素マウント
document.body.innerHTML = '<div id="app"></div>';
const launch = (router: VueRouter) => {
//#region theme
os.store.watch(s => {
return s.device.darkmode;
}, v => {
const themes = os.store.state.device.themes.concat(builtinThemes);
const dark = themes.find(t => t.id == os.store.state.device.darkTheme);
const light = themes.find(t => t.id == os.store.state.device.lightTheme);
applyTheme(v ? dark : light);
});
os.store.watch(s => {
return s.device.lightTheme;
}, v => {
const themes = os.store.state.device.themes.concat(builtinThemes);
const theme = themes.find(t => t.id == v);
if (!os.store.state.device.darkmode) {
applyTheme(theme);
}
});
os.store.watch(s => {
return s.device.darkTheme;
}, v => {
const themes = os.store.state.device.themes.concat(builtinThemes);
const theme = themes.find(t => t.id == v);
if (os.store.state.device.darkmode) {
applyTheme(theme);
}
});
//#endregion
/*// Reapply current theme
try {
const themeName = os.store.state.device.darkmode ? os.store.state.device.darkTheme : os.store.state.device.lightTheme;
const themes = os.store.state.device.themes.concat(builtinThemes);
const theme = themes.find(t => t.id == themeName);
if (theme) {
applyTheme(theme);
}
} catch (e) {
console.log(`Cannot reapply theme. ${e}`);
}*/
//#region line width
document.documentElement.style.setProperty('--lineWidth', `${os.store.state.device.lineWidth}px`);
os.store.watch(s => {
return s.device.lineWidth;
}, v => {
document.documentElement.style.setProperty('--lineWidth', `${os.store.state.device.lineWidth}px`);
});
//#endregion
//#region fontSize
document.documentElement.style.setProperty('--fontSize', `${os.store.state.device.fontSize}px`);
os.store.watch(s => {
return s.device.fontSize;
}, v => {
document.documentElement.style.setProperty('--fontSize', `${os.store.state.device.fontSize}px`);
});
//#endregion
document.addEventListener('visibilitychange', () => {
if (!document.hidden) {
os.store.commit('clearBehindNotes');
}
}, false);
window.addEventListener('scroll', () => {
if (window.scrollY <= 8) {
os.store.commit('clearBehindNotes');
}
}, { passive: true });
const app = new Vue({
i18n: i18n(),
store: os.store,
data() {
return {
os: {
windows: os.windows
},
stream: os.stream,
instanceName: os.instanceName
};
},
methods: {
api: os.api,
getMeta: os.getMeta,
getMetaSync: os.getMetaSync,
signout: os.signout,
new(vm, props) {
const x = new vm({
parent: this,
propsData: props
}).$mount();
document.body.appendChild(x.$el);
return x;
},
newAsync(vm, props) {
return new Promise((res) => {
vm().then(vm => {
const x = new vm({
parent: this,
propsData: props
}).$mount();
document.body.appendChild(x.$el);
res(x);
});
});
},
dialog(opts) {
const vm = this.new(Dialog, opts);
const p: any = new Promise((res) => {
vm.$once('ok', result => res({ canceled: false, result }));
vm.$once('cancel', () => res({ canceled: true }));
});
p.close = () => {
vm.close();
};
return p;
}
},
router,
render: createEl => createEl(App)
});
os.app = app;
// マウント
app.$mount('#app');
//#region 更新チェック
setTimeout(() => {
checkForUpdate(app);
}, 3000);
//#endregion
return [app, os] as [Vue, MiOS];
};
// Deck mode
os.store.commit('device/set', {
key: 'inDeckMode',
value: os.store.getters.isSignedIn && os.store.state.device.deckMode
&& (document.location.pathname === '/' || window.performance.navigation.type === 1)
});
callback(launch, os);
});
}; | the_stack |
import test from "ava";
import common from "../src/common";
const { __tests__ } = common;
const { _commonTransfer } = __tests__;
import { CellProvider } from "./cell_provider";
import {
parseAddress,
TransactionSkeleton,
TransactionSkeletonType,
} from "@ckb-lumos/helpers";
import { Cell, Transaction, values, Script } from "@ckb-lumos/base";
import { FromInfo, anyoneCanPay, parseFromInfo } from "../src";
import { Config, predefined } from "@ckb-lumos/config-manager";
const { AGGRON4, LINA } = predefined;
import {
bobSecpInputs,
bobMultisigInputs,
bobMultisigLockInputs,
tipHeader,
bobAcpCells,
aliceAcpCells,
} from "./inputs";
import { bob, alice } from "./account_info";
import { List } from "immutable";
const aliceInput: Cell = {
cell_output: {
capacity: "0x1d1a3543f00",
lock: {
code_hash:
"0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8",
hash_type: "type",
args: "0xe2193df51d78411601796b35b17b4f8f2cd85bd0",
},
},
out_point: {
tx_hash:
"0x42300d78faea694e0e1c2316de091964a0d976a4ed27775597bad2d43a3e17da",
index: "0x1",
},
block_hash:
"0x156ecda80550b6664e5d745b6277c0ae56009681389dcc8f1565d815633ae906",
block_number: "0x1929c",
data: "0x",
};
const multisigInput: Cell = {
cell_output: {
capacity: "0xba37cb7e00",
lock: {
code_hash:
"0x5c5069eb0857efc65e1bca0c07df34c31663b3622fd3876c876320fc9634e2a8",
hash_type: "type",
args: "0x56f281b3d4bb5fc73c751714af0bf78eb8aba0d8",
},
},
out_point: {
tx_hash:
"0xc0018c999d6e7d1f830ea645d980a3a9c3c3832d12e72172708ce8461fc5821e",
index: "0x1",
},
block_hash:
"0x29c8f7d773ccd74724f95f562d049182c2461dd7459ebfc494b7bb0857e8c902",
block_number: "0x1aed9",
data: "0x",
};
const cellProvider = new CellProvider([aliceInput].concat([multisigInput]));
let txSkeleton: TransactionSkeletonType = TransactionSkeleton({ cellProvider });
const aliceAddress = "ckt1qyqwyxfa75whssgkq9ukkdd30d8c7txct0gqfvmy2v";
const fromInfo: FromInfo = {
R: 0,
M: 1,
publicKeyHashes: ["0x36c329ed630d6ce750712a477543672adab57f4c"],
};
test("_commonTransfer, only alice", async (t) => {
const amount: bigint = BigInt(20000 * 10 ** 8);
const result = await _commonTransfer(
txSkeleton,
[aliceAddress],
amount,
BigInt(61 * 10 ** 8),
{ config: AGGRON4 }
);
txSkeleton = result.txSkeleton;
t.is(txSkeleton.get("inputs").size, 1);
t.is(txSkeleton.get("outputs").size, 0);
t.is(result.capacity, amount - BigInt(aliceInput.cell_output.capacity));
});
test("_commonTransfer, alice and fromInfo", async (t) => {
const amount: bigint = BigInt(20000 * 10 ** 8);
const result = await _commonTransfer(
txSkeleton,
[aliceAddress, fromInfo],
amount,
BigInt(61 * 10 ** 8),
{ config: AGGRON4 }
);
txSkeleton = result.txSkeleton;
const inputCapacity = txSkeleton
.get("inputs")
.map((i) => BigInt(i.cell_output.capacity))
.reduce((result, c) => result + c, BigInt(0));
t.is(txSkeleton.get("inputs").size, 2);
t.is(txSkeleton.get("outputs").size, 0);
t.is(result.capacity, BigInt(0));
t.is(result.changeCapacity, inputCapacity - amount);
});
test("transfer, acp => acp", async (t) => {
const cellProvider = new CellProvider([...bobAcpCells, ...aliceAcpCells]);
let txSkeleton: TransactionSkeletonType = TransactionSkeleton({
cellProvider,
});
const amount = BigInt(500 * 10 ** 8);
txSkeleton = await common.transfer(
txSkeleton,
[bob.acpTestnetAddress],
alice.acpTestnetAddress,
amount,
undefined,
undefined,
{ config: AGGRON4 }
);
const sumOfInputCapacity = txSkeleton
.get("inputs")
.map((i) => BigInt(i.cell_output.capacity))
.reduce((result, c) => result + c, BigInt(0));
const sumOfOutputCapcity = txSkeleton
.get("outputs")
.map((o) => BigInt(o.cell_output.capacity))
.reduce((result, c) => result + c, BigInt(0));
t.is(sumOfInputCapacity, sumOfOutputCapcity);
t.is(txSkeleton.get("witnesses").size, 2);
t.is(txSkeleton.get("witnesses").get(0)!, "0x");
const expectedMessage =
"0x5acf7d234fc5c9adbc9b01f4938a5efdf6efde2b0a836f4740e6a79f81b64d65";
txSkeleton = common.prepareSigningEntries(txSkeleton, { config: AGGRON4 });
t.is(txSkeleton.get("signingEntries").size, 1);
t.is(txSkeleton.get("signingEntries").get(0)!.message, expectedMessage);
});
test("lockScriptInfos", (t) => {
common.__tests__.resetLockScriptInfos();
t.is(common.__tests__.getLockScriptInfos().infos.length, 0);
common.registerCustomLockScriptInfos([
{
code_hash: "",
hash_type: "type",
lockScriptInfo: anyoneCanPay,
},
]);
t.is(common.__tests__.getLockScriptInfos().infos.length, 1);
common.__tests__.resetLockScriptInfos();
t.is(common.__tests__.getLockScriptInfos().infos.length, 0);
common.__tests__.generateLockScriptInfos({ config: AGGRON4 });
t.is(common.__tests__.getLockScriptInfos().infos.length, 3);
const configCodeHash = common.__tests__.getLockScriptInfos().configHashCode;
t.not(configCodeHash, 0);
// run again, won't change
common.__tests__.generateLockScriptInfos({ config: AGGRON4 });
t.is(common.__tests__.getLockScriptInfos().infos.length, 3);
t.is(common.__tests__.getLockScriptInfos().configHashCode, configCodeHash);
// using LINA
common.__tests__.generateLockScriptInfos({ config: LINA });
t.is(common.__tests__.getLockScriptInfos().infos.length, 3);
t.not(common.__tests__.getLockScriptInfos().configHashCode, configCodeHash);
});
test("transfer secp => secp", async (t) => {
const cellProvider = new CellProvider([...bobSecpInputs]);
let txSkeleton: TransactionSkeletonType = TransactionSkeleton({
cellProvider,
});
const amount = BigInt(600 * 10 ** 8);
txSkeleton = await common.transfer(
txSkeleton,
[bob.testnetAddress],
aliceAddress,
amount,
undefined,
undefined,
{ config: AGGRON4 }
);
const sumOfInputCapacity = txSkeleton
.get("inputs")
.map((i) => BigInt(i.cell_output.capacity))
.reduce((result, c) => result + c, BigInt(0));
const sumOfOutputCapcity = txSkeleton
.get("outputs")
.map((o) => BigInt(o.cell_output.capacity))
.reduce((result, c) => result + c, BigInt(0));
t.is(sumOfInputCapacity, sumOfOutputCapcity);
t.is(txSkeleton.get("inputs").size, 1);
t.is(txSkeleton.get("outputs").size, 2);
t.is(BigInt(txSkeleton.get("outputs").get(0)!.cell_output.capacity), amount);
t.is(txSkeleton.get("witnesses").size, 1);
const expectedMessages = [
"0x997f7d53307a114104b37c0fcdef97240d250d468189e71632d79e1c3b20a4f9",
];
txSkeleton = common.prepareSigningEntries(txSkeleton, { config: AGGRON4 });
t.deepEqual(
txSkeleton
.get("signingEntries")
.sort((a, b) => a.index - b.index)
.map((s) => s.message)
.toArray(),
expectedMessages
);
});
test("transfer secp & multisig => secp", async (t) => {
const cellProvider = new CellProvider([
bobSecpInputs[0],
...bobMultisigInputs,
]);
let txSkeleton: TransactionSkeletonType = TransactionSkeleton({
cellProvider,
});
const amount = BigInt(1500 * 10 ** 8);
txSkeleton = await common.transfer(
txSkeleton,
[bob.testnetAddress, bob.fromInfo],
aliceAddress,
amount,
undefined,
undefined,
{ config: AGGRON4 }
);
const sumOfInputCapacity = txSkeleton
.get("inputs")
.map((i) => BigInt(i.cell_output.capacity))
.reduce((result, c) => result + c, BigInt(0));
const sumOfOutputCapcity = txSkeleton
.get("outputs")
.map((o) => BigInt(o.cell_output.capacity))
.reduce((result, c) => result + c, BigInt(0));
t.is(sumOfInputCapacity, sumOfOutputCapcity);
t.is(txSkeleton.get("inputs").size, 2);
t.is(txSkeleton.get("outputs").size, 2);
t.is(BigInt(txSkeleton.get("outputs").get(0)!.cell_output.capacity), amount);
t.is(txSkeleton.get("witnesses").size, 2);
const expectedMessages = [
"0x45e7955cbc1ae0f8c2fbb3392a3afcea9ae1ae83c48e4355f131d751325ea615",
"0x051a18a11dacfd6573a689328ea7ee0cc3f2533de9c15e4f9e12f0e4a6e9691c",
];
txSkeleton = common.prepareSigningEntries(txSkeleton, { config: AGGRON4 });
t.deepEqual(
txSkeleton
.get("signingEntries")
.sort((a, b) => a.index - b.index)
.map((s) => s.message)
.toArray(),
expectedMessages
);
});
test("transfer multisig lock => secp", async (t) => {
const cellProvider = new CellProvider([...bobMultisigLockInputs]);
let txSkeleton: TransactionSkeletonType = TransactionSkeleton({
cellProvider,
});
class LocktimePoolCellCollector {
async *collect() {
yield {
...bobMultisigLockInputs[0],
since: "0x0",
depositBlockHash: undefined,
withdrawBlockHash: undefined,
sinceBaseValue: undefined,
};
}
}
const amount = BigInt(600 * 10 ** 8);
txSkeleton = await common.transfer(
txSkeleton,
[bob.fromInfo],
alice.testnetAddress,
amount,
undefined,
tipHeader,
{
config: AGGRON4,
LocktimePoolCellCollector,
}
);
const sumOfInputCapacity = txSkeleton
.get("inputs")
.map((i) => BigInt(i.cell_output.capacity))
.reduce((result, c) => result + c, BigInt(0));
const sumOfOutputCapcity = txSkeleton
.get("outputs")
.map((o) => BigInt(o.cell_output.capacity))
.reduce((result, c) => result + c, BigInt(0));
t.is(sumOfInputCapacity, sumOfOutputCapcity);
t.is(txSkeleton.get("inputs").size, 1);
t.is(txSkeleton.get("outputs").size, 2);
t.is(BigInt(txSkeleton.get("outputs").get(0)!.cell_output.capacity), amount);
t.is(txSkeleton.get("witnesses").size, 1);
const expectedMessages = [
"0x54f766189f91dcf10a23833c5b1f0d318044c7237a2a703ad77ea46990190b8b",
];
txSkeleton = common.prepareSigningEntries(txSkeleton, { config: AGGRON4 });
t.deepEqual(
txSkeleton
.get("signingEntries")
.sort((a, b) => a.index - b.index)
.map((s) => s.message)
.toArray(),
expectedMessages
);
});
test("transfer secp => acp", async (t) => {
const cellProvider = new CellProvider([...bobSecpInputs, ...aliceAcpCells]);
let txSkeleton: TransactionSkeletonType = TransactionSkeleton({
cellProvider,
});
const amount = BigInt(600 * 10 ** 8);
txSkeleton = await common.transfer(
txSkeleton,
[bob.testnetAddress],
alice.acpTestnetAddress,
amount,
undefined,
undefined,
{ config: AGGRON4 }
);
const sumOfInputCapacity = txSkeleton
.get("inputs")
.map((i) => BigInt(i.cell_output.capacity))
.reduce((result, c) => result + c, BigInt(0));
const sumOfOutputCapcity = txSkeleton
.get("outputs")
.map((o) => BigInt(o.cell_output.capacity))
.reduce((result, c) => result + c, BigInt(0));
t.is(sumOfInputCapacity, sumOfOutputCapcity);
t.is(txSkeleton.get("inputs").size, 2);
t.is(txSkeleton.get("outputs").size, 2);
t.is(
BigInt(txSkeleton.get("outputs").get(0)!.cell_output.capacity) -
BigInt(aliceAcpCells[0]!.cell_output.capacity),
amount
);
const expectedWitnesses = [
"0x",
"0x55000000100000005500000055000000410000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
];
t.deepEqual(txSkeleton.get("witnesses").toJS(), expectedWitnesses);
const expectedMessages = [
"0x7449d526fa5fbaf942cbf29f833d89026b6f28322d0bd4725eb8c0b921b3b275",
];
txSkeleton = common.prepareSigningEntries(txSkeleton, { config: AGGRON4 });
t.deepEqual(
txSkeleton
.get("signingEntries")
.sort((a, b) => a.index - b.index)
.map((s) => s.message)
.toArray(),
expectedMessages
);
});
test("transfer secp => acp, no acp previous input", async (t) => {
const cellProvider = new CellProvider([...bobSecpInputs]);
let txSkeleton: TransactionSkeletonType = TransactionSkeleton({
cellProvider,
});
const amount = BigInt(600 * 10 ** 8);
txSkeleton = await common.transfer(
txSkeleton,
[bob.testnetAddress],
alice.acpTestnetAddress,
amount,
undefined,
undefined,
{ config: AGGRON4 }
);
const sumOfInputCapacity = txSkeleton
.get("inputs")
.map((i) => BigInt(i.cell_output.capacity))
.reduce((result, c) => result + c, BigInt(0));
const sumOfOutputCapcity = txSkeleton
.get("outputs")
.map((o) => BigInt(o.cell_output.capacity))
.reduce((result, c) => result + c, BigInt(0));
t.is(sumOfInputCapacity, sumOfOutputCapcity);
t.is(txSkeleton.get("cellDeps").size, 1);
t.is(txSkeleton.get("headerDeps").size, 0);
t.is(txSkeleton.get("inputs").size, 1);
t.is(txSkeleton.get("outputs").size, 2);
t.is(BigInt(txSkeleton.get("outputs").get(0)!.cell_output.capacity), amount);
const expectedWitnesses = [
"0x55000000100000005500000055000000410000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
];
t.deepEqual(txSkeleton.get("witnesses").toJS(), expectedWitnesses);
const expectedMessages = [
"0x68a543a1ef68667281609d9331f3587f4bfac16002f0fbac72e3774de80f45fb",
];
txSkeleton = common.prepareSigningEntries(txSkeleton, { config: AGGRON4 });
t.deepEqual(
txSkeleton
.get("signingEntries")
.sort((a, b) => a.index - b.index)
.map((s) => s.message)
.toArray(),
expectedMessages
);
});
test("transfer acp => secp, destroy", async (t) => {
const cellProvider = new CellProvider([...bobAcpCells]);
let txSkeleton: TransactionSkeletonType = TransactionSkeleton({
cellProvider,
});
const amount = BigInt(1000 * 10 ** 8);
txSkeleton = await common.transfer(
txSkeleton,
[
{
address: bob.acpTestnetAddress,
destroyable: true,
},
],
bob.testnetAddress,
amount,
undefined,
undefined,
{ config: AGGRON4 }
);
const sumOfInputCapacity = txSkeleton
.get("inputs")
.map((i) => BigInt(i.cell_output.capacity))
.reduce((result, c) => result + c, BigInt(0));
const sumOfOutputCapcity = txSkeleton
.get("outputs")
.map((o) => BigInt(o.cell_output.capacity))
.reduce((result, c) => result + c, BigInt(0));
t.is(sumOfInputCapacity, sumOfOutputCapcity);
t.is(txSkeleton.get("inputs").size, 1);
t.is(txSkeleton.get("outputs").size, 1);
t.is(BigInt(txSkeleton.get("outputs").get(0)!.cell_output.capacity), amount);
t.is(txSkeleton.get("witnesses").size, 1);
const expectedMessages = [
"0x3196d29d3365c1d3d599be55e80e4addd631acb6605646329eb39a1b9264ab89",
];
txSkeleton = common.prepareSigningEntries(txSkeleton, { config: AGGRON4 });
t.deepEqual(
txSkeleton
.get("signingEntries")
.sort((a, b) => a.index - b.index)
.map((s) => s.message)
.toArray(),
expectedMessages
);
});
test("Don't update capacity directly when deduct", async (t) => {
const cellProvider = new CellProvider([bobSecpInputs[0]]);
let txSkeleton: TransactionSkeletonType = TransactionSkeleton({
cellProvider,
});
const amount = BigInt(600 * 10 ** 8);
txSkeleton = await common.transfer(
txSkeleton,
[bob.testnetAddress],
aliceAddress,
amount,
undefined,
undefined,
{ config: AGGRON4 }
);
const getCapacities = (cells: List<Cell>): string[] => {
return cells.map((c) => c.cell_output.capacity).toJS();
};
const inputCapacitiesBefore = getCapacities(txSkeleton.get("inputs"));
const outputCapacitiesBefore = getCapacities(txSkeleton.get("outputs"));
let errFlag = false;
try {
await common.transfer(
txSkeleton,
[bob.testnetAddress],
aliceAddress,
BigInt(500 * 10 ** 8),
undefined,
undefined,
{ config: AGGRON4 }
);
} catch {
errFlag = true;
}
const inputCapacitiesAfter = getCapacities(txSkeleton.get("inputs"));
const outputCapacitiesAfter = getCapacities(txSkeleton.get("outputs"));
t.true(errFlag);
t.deepEqual(inputCapacitiesBefore, inputCapacitiesAfter);
t.deepEqual(outputCapacitiesBefore, outputCapacitiesAfter);
});
test("setupInputCell secp", async (t) => {
const cellProvider = new CellProvider([...bobSecpInputs]);
let txSkeleton: TransactionSkeletonType = TransactionSkeleton({
cellProvider,
});
const inputCell: Cell = bobSecpInputs[0];
txSkeleton = await common.setupInputCell(
txSkeleton,
inputCell,
bob.testnetAddress,
{
config: AGGRON4,
}
);
t.is(txSkeleton.get("inputs").size, 1);
t.is(txSkeleton.get("outputs").size, 1);
t.is(txSkeleton.get("witnesses").size, 1);
const input: Cell = txSkeleton.get("inputs").get(0)!;
const output: Cell = txSkeleton.get("outputs").get(0)!;
t.is(input.cell_output.capacity, output.cell_output.capacity);
t.is(input.data, output.data);
t.true(
new values.ScriptValue(input.cell_output.lock, { validate: false }).equals(
new values.ScriptValue(output.cell_output.lock, { validate: false })
)
);
t.true(
(!input.cell_output.type && !output.cell_output.type) ||
new values.ScriptValue(input.cell_output.type!, {
validate: false,
}).equals(
new values.ScriptValue(output.cell_output.type!, { validate: false })
)
);
});
const testTx: Transaction = {
version: "0x0",
cell_deps: [
{
out_point: {
tx_hash:
"0xc12386705b5cbb312b693874f3edf45c43a274482e27b8df0fd80c8d3f5feb8b",
index: "0x0",
},
dep_type: "dep_group",
},
{
out_point: {
tx_hash:
"0x0fb4945d52baf91e0dee2a686cdd9d84cad95b566a1d7409b970ee0a0f364f60",
index: "0x2",
},
dep_type: "code",
},
],
header_deps: [],
inputs: [
{
previous_output: {
tx_hash:
"0x31f695263423a4b05045dd25ce6692bb55d7bba2965d8be16b036e138e72cc65",
index: "0x1",
},
since: "0x0",
},
],
outputs: [
{
capacity: "0x174876e800",
lock: {
code_hash:
"0x68d5438ac952d2f584abf879527946a537e82c7f3c1cbf6d8ebf9767437d8e88",
args: "0x59a27ef3ba84f061517d13f42cf44ed020610061",
hash_type: "type",
},
type: {
code_hash:
"0xece45e0979030e2f8909f76258631c42333b1e906fd9701ec3600a464a90b8f6",
args: "0x",
hash_type: "data",
},
},
{
capacity: "0x59e1416a5000",
lock: {
code_hash:
"0x68d5438ac952d2f584abf879527946a537e82c7f3c1cbf6d8ebf9767437d8e88",
args: "0x59a27ef3ba84f061517d13f42cf44ed020610061",
hash_type: "type",
},
type: undefined,
},
],
outputs_data: ["0x1234", "0x"],
witnesses: [
"0x82df73581bcd08cb9aa270128d15e79996229ce8ea9e4f985b49fbf36762c5c37936caf3ea3784ee326f60b8992924fcf496f9503c907982525a3436f01ab32900",
],
};
test("getTransactionSizeByTx", (t) => {
const size: number = __tests__.getTransactionSizeByTx(testTx);
t.is(size, 536);
});
test("calculateFee, without carry", (t) => {
t.is(__tests__.calculateFee(1035, BigInt(1000)), BigInt(1035));
});
test("calculateFee, with carry", (t) => {
t.is(__tests__.calculateFee(1035, BigInt(900)), BigInt(932));
});
function getExpectedFee(
txSkeleton: TransactionSkeletonType,
feeRate: bigint
): bigint {
return __tests__.calculateFee(
__tests__.getTransactionSize(txSkeleton),
feeRate
);
}
function getFee(txSkeleton: TransactionSkeletonType): bigint {
const sumOfInputCapacity = txSkeleton
.get("inputs")
.map((i) => BigInt(i.cell_output.capacity))
.reduce((result, c) => result + c, BigInt(0));
const sumOfOutputCapcity = txSkeleton
.get("outputs")
.map((o) => BigInt(o.cell_output.capacity))
.reduce((result, c) => result + c, BigInt(0));
return sumOfInputCapacity - sumOfOutputCapcity;
}
// from same address and only secp156k1_blake160 lock
// const ONE_IN_ONE_OUT_SIZE = 355
const ONE_IN_TWO_OUT_SIZE = 464;
// const TWO_IN_ONE_OUT_SIZE = 407
// const TWO_IN_TWO_OUT_SIZE = 516
test("payFeeByFeeRate 1 in 1 out, add 1 in 1 out", async (t) => {
const cellProvider = new CellProvider(bobSecpInputs);
let txSkeleton: TransactionSkeletonType = TransactionSkeleton({
cellProvider,
});
const amount = BigInt(1000 * 10 ** 8);
txSkeleton = await common.transfer(
txSkeleton,
[bob.testnetAddress],
aliceAddress,
amount,
undefined,
undefined,
{ config: AGGRON4 }
);
const feeRate = BigInt(1 * 10 ** 8 * 1000);
txSkeleton = await common.payFeeByFeeRate(
txSkeleton,
[bob.testnetAddress],
feeRate,
undefined,
{
config: AGGRON4,
}
);
t.is(txSkeleton.get("inputs").size, 2);
t.is(txSkeleton.get("outputs").size, 2);
t.is(getFee(txSkeleton), getExpectedFee(txSkeleton, feeRate));
});
test("payFeeByFeeRate 1 in 2 out, add nothing", async (t) => {
const cellProvider = new CellProvider(bobSecpInputs);
let txSkeleton: TransactionSkeletonType = TransactionSkeleton({
cellProvider,
});
const amount = BigInt(600 * 10 ** 8);
txSkeleton = await common.transfer(
txSkeleton,
[bob.testnetAddress],
aliceAddress,
amount,
undefined,
undefined,
{ config: AGGRON4 }
);
const feeRate = BigInt(1 * 10 ** 8);
txSkeleton = await common.payFeeByFeeRate(
txSkeleton,
[bob.testnetAddress],
feeRate,
undefined,
{
config: AGGRON4,
}
);
t.is(txSkeleton.get("inputs").size, 1);
t.is(txSkeleton.get("outputs").size, 2);
t.is(getFee(txSkeleton), getExpectedFee(txSkeleton, feeRate));
});
test("payFeeByFeeRate 1 in 2 out, reduce 1 out", async (t) => {
const cellProvider = new CellProvider(bobSecpInputs);
let txSkeleton: TransactionSkeletonType = TransactionSkeleton({
cellProvider,
});
const amount = BigInt(536 * 10 ** 8);
txSkeleton = await common.transfer(
txSkeleton,
[bob.testnetAddress],
aliceAddress,
amount,
undefined,
undefined,
{ config: AGGRON4 }
);
const feeRate = BigInt(1 * 10 ** 8 * 1000);
txSkeleton = await common.payFeeByFeeRate(
txSkeleton,
[bob.testnetAddress],
feeRate,
undefined,
{
config: AGGRON4,
}
);
// NOTE: 1000CKB => 536CKB + 464CKB(change), need 464CKB for fee, so reduced change cell
// But, new tx is 1000CKB => 536CKB, need 355CKB for fee
// when you add a new change output, fee will up to 464CKB or even a new input, so left 1000CKB => 536CKB is best choice.
t.is(txSkeleton.get("inputs").size, 1);
t.is(txSkeleton.get("outputs").size, 1);
t.is(
getFee(txSkeleton),
__tests__.calculateFee(ONE_IN_TWO_OUT_SIZE, feeRate)
);
});
test("payFeeByFeeRate 1 in 2 out, add 1 in", async (t) => {
const cellProvider = new CellProvider(bobSecpInputs);
let txSkeleton: TransactionSkeletonType = TransactionSkeleton({
cellProvider,
});
const amount = BigInt(600 * 10 ** 8);
txSkeleton = await common.transfer(
txSkeleton,
[bob.testnetAddress],
aliceAddress,
amount,
undefined,
undefined,
{ config: AGGRON4 }
);
const feeRate = BigInt(1 * 10 ** 8 * 1000);
txSkeleton = await common.payFeeByFeeRate(
txSkeleton,
[bob.testnetAddress],
feeRate,
undefined,
{
config: AGGRON4,
}
);
t.is(txSkeleton.get("inputs").size, 2);
t.is(txSkeleton.get("outputs").size, 2);
t.is(getFee(txSkeleton), getExpectedFee(txSkeleton, feeRate));
});
test("payFeeByFeeRate, capacity 500", async (t) => {
const cellProvider = new CellProvider(bobSecpInputs);
let txSkeleton: TransactionSkeletonType = TransactionSkeleton({
cellProvider,
});
const amount = BigInt(500 * 10 ** 8);
txSkeleton = await common.transfer(
txSkeleton,
[bob.testnetAddress],
aliceAddress,
amount,
undefined,
undefined,
{ config: AGGRON4 }
);
const feeRate = BigInt(1000);
txSkeleton = await common.payFeeByFeeRate(
txSkeleton,
[bob.testnetAddress],
feeRate,
undefined,
{
config: AGGRON4,
}
);
const expectedFee: bigint = BigInt(464);
t.is(getFee(txSkeleton), expectedFee);
});
test("payFeeByFeeRate, capacity 1000", async (t) => {
const cellProvider = new CellProvider(bobSecpInputs);
let txSkeleton: TransactionSkeletonType = TransactionSkeleton({
cellProvider,
});
const amount = BigInt(1000 * 10 ** 8);
txSkeleton = await common.transfer(
txSkeleton,
[bob.testnetAddress],
aliceAddress,
amount,
undefined,
undefined,
{ config: AGGRON4 }
);
const feeRate = BigInt(1000);
txSkeleton = await common.payFeeByFeeRate(
txSkeleton,
[bob.testnetAddress],
feeRate,
undefined,
{
config: AGGRON4,
}
);
const expectedFee: bigint = BigInt(516);
t.is(getFee(txSkeleton), expectedFee);
});
test("Should not throw if anyone-can-pay config not provided", async (t) => {
// config without anyone-can-pay
const config: Config = {
PREFIX: AGGRON4.PREFIX,
SCRIPTS: {
SECP256K1_BLAKE160: AGGRON4.SCRIPTS.SECP256K1_BLAKE160,
SECP256K1_BLAKE160_MULTISIG: AGGRON4.SCRIPTS.SECP256K1_BLAKE160_MULTISIG,
DAO: AGGRON4.SCRIPTS.DAO,
},
};
const cellProvider = new CellProvider([...bobSecpInputs]);
let txSkeleton: TransactionSkeletonType = TransactionSkeleton({
cellProvider,
});
const amount = BigInt(600 * 10 ** 8);
await t.notThrowsAsync(async () => {
await common.transfer(
txSkeleton,
[bob.testnetAddress],
aliceAddress,
amount,
undefined,
undefined,
{ config }
);
});
});
// disable deduct capacity
test("transfer secp => secp, without deduct capacity", async (t) => {
const cellProvider = new CellProvider([...bobSecpInputs]);
let txSkeleton: TransactionSkeletonType = TransactionSkeleton({
cellProvider,
});
const amount = BigInt(600 * 10 ** 8);
txSkeleton = await common.transfer(
txSkeleton,
[bob.testnetAddress],
alice.testnetAddress,
amount,
undefined,
undefined,
{ config: AGGRON4 }
);
t.is(txSkeleton.get("inputs").size, 1);
t.is(txSkeleton.get("outputs").size, 2);
const fee: bigint = BigInt(1000);
txSkeleton = await common.payFee(
txSkeleton,
[bob.testnetAddress],
fee,
undefined,
{
config: AGGRON4,
enableDeductCapacity: false,
}
);
t.is(txSkeleton.get("inputs").size, 2);
t.is(txSkeleton.get("outputs").size, 3);
const sumOfInputCapacity = txSkeleton
.get("inputs")
.map((i) => BigInt(i.cell_output.capacity))
.reduce((result, c) => result + c, BigInt(0));
const sumOfOutputCapcity = txSkeleton
.get("outputs")
.map((o) => BigInt(o.cell_output.capacity))
.reduce((result, c) => result + c, BigInt(0));
t.is(sumOfInputCapacity - sumOfOutputCapcity, fee);
t.is(BigInt(txSkeleton.get("outputs").get(0)!.cell_output.capacity), amount);
t.is(
BigInt(txSkeleton.get("outputs").get(1)!.cell_output.capacity),
BigInt(bobSecpInputs[0].cell_output.capacity) - amount
);
t.is(
BigInt(txSkeleton.get("outputs").get(2)!.cell_output.capacity),
BigInt(bobSecpInputs[1].cell_output.capacity) - fee
);
const changeLockScript: Script = parseAddress(bob.testnetAddress, {
config: AGGRON4,
});
t.true(
new values.ScriptValue(txSkeleton.get("outputs").get(1)!.cell_output.lock, {
validate: false,
}).equals(new values.ScriptValue(changeLockScript, { validate: false }))
);
t.true(
new values.ScriptValue(txSkeleton.get("outputs").get(2)!.cell_output.lock, {
validate: false,
}).equals(new values.ScriptValue(changeLockScript, { validate: false }))
);
t.is(txSkeleton.get("fixedEntries").size, 0);
const expectedMessages = [
"0x7bf7f9183d54e3a69d80c1d049d0b1cda7005341f428b70b22abc356286dbf70",
];
txSkeleton = common.prepareSigningEntries(txSkeleton, { config: AGGRON4 });
t.deepEqual(
txSkeleton
.get("signingEntries")
.sort((a, b) => a.index - b.index)
.map((s) => s.message)
.toArray(),
expectedMessages
);
});
test("transfer multisig lock => secp, without deduct capacity", async (t) => {
const cellProvider = new CellProvider([...bobMultisigInputs]);
let txSkeleton: TransactionSkeletonType = TransactionSkeleton({
cellProvider,
});
class LocktimePoolCellCollector {
async *collect() {
for (const cell of bobMultisigInputs) {
yield {
...cell,
since: "0x0",
depositBlockHash: undefined,
withdrawBlockHash: undefined,
sinceBaseValue: undefined,
};
}
}
}
const amount = BigInt(600 * 10 ** 8);
txSkeleton = await common.transfer(
txSkeleton,
[bob.fromInfo],
alice.testnetAddress,
amount,
undefined,
tipHeader,
{
config: AGGRON4,
LocktimePoolCellCollector,
}
);
t.is(txSkeleton.get("inputs").size, 1);
t.is(txSkeleton.get("outputs").size, 2);
const fee = BigInt(1000);
txSkeleton = await common.injectCapacity(
txSkeleton,
[bob.fromInfo],
fee,
undefined,
tipHeader,
{
config: AGGRON4,
LocktimePoolCellCollector,
enableDeductCapacity: false,
}
);
t.is(txSkeleton.get("inputs").size, 2);
t.is(txSkeleton.get("outputs").size, 3);
const sumOfInputCapacity = txSkeleton
.get("inputs")
.map((i) => BigInt(i.cell_output.capacity))
.reduce((result, c) => result + c, BigInt(0));
const sumOfOutputCapcity = txSkeleton
.get("outputs")
.map((o) => BigInt(o.cell_output.capacity))
.reduce((result, c) => result + c, BigInt(0));
t.is(sumOfInputCapacity - sumOfOutputCapcity, fee);
t.is(BigInt(txSkeleton.get("outputs").get(0)!.cell_output.capacity), amount);
t.is(
BigInt(txSkeleton.get("outputs").get(1)!.cell_output.capacity),
BigInt(bobMultisigInputs[0].cell_output.capacity) - amount
);
t.is(
BigInt(txSkeleton.get("outputs").get(2)!.cell_output.capacity),
BigInt(bobMultisigInputs[1].cell_output.capacity) - fee
);
const changeLockScript: Script = parseFromInfo(bob.fromInfo, {
config: AGGRON4,
}).fromScript;
t.true(
new values.ScriptValue(txSkeleton.get("outputs").get(1)!.cell_output.lock, {
validate: false,
}).equals(new values.ScriptValue(changeLockScript, { validate: false }))
);
t.true(
new values.ScriptValue(txSkeleton.get("outputs").get(2)!.cell_output.lock, {
validate: false,
}).equals(new values.ScriptValue(changeLockScript, { validate: false }))
);
t.is(txSkeleton.get("fixedEntries").size, 0);
const expectedMessages = [
"0x01fc08c48a5cab51686b808e65d041966a460a17cfa82bb77cbd270fff4634c0",
];
txSkeleton = common.prepareSigningEntries(txSkeleton, { config: AGGRON4 });
t.deepEqual(
txSkeleton
.get("signingEntries")
.sort((a, b) => a.index - b.index)
.map((s) => s.message)
.toArray(),
expectedMessages
);
}); | the_stack |
import {ResourceBase, ResourceTag} from '../resource'
import {Value, List} from '../dataTypes'
export class ConfluenceAttachmentToIndexFieldMapping {
DataSourceFieldName!: Value<string>
DateFieldFormat?: Value<string>
IndexFieldName!: Value<string>
constructor(properties: ConfluenceAttachmentToIndexFieldMapping) {
Object.assign(this, properties)
}
}
export class SalesforceStandardObjectConfiguration {
Name!: Value<string>
DocumentDataFieldName!: Value<string>
DocumentTitleFieldName?: Value<string>
FieldMappings?: List<DataSourceToIndexFieldMapping>
constructor(properties: SalesforceStandardObjectConfiguration) {
Object.assign(this, properties)
}
}
export class SalesforceChatterFeedConfiguration {
DocumentDataFieldName!: Value<string>
DocumentTitleFieldName?: Value<string>
FieldMappings?: List<DataSourceToIndexFieldMapping>
IncludeFilterTypes?: List<Value<string>>
constructor(properties: SalesforceChatterFeedConfiguration) {
Object.assign(this, properties)
}
}
export class SalesforceConfiguration {
ServerUrl!: Value<string>
SecretArn!: Value<string>
StandardObjectConfigurations?: List<SalesforceStandardObjectConfiguration>
KnowledgeArticleConfiguration?: SalesforceKnowledgeArticleConfiguration
ChatterFeedConfiguration?: SalesforceChatterFeedConfiguration
CrawlAttachments?: Value<boolean>
StandardObjectAttachmentConfiguration?: SalesforceStandardObjectAttachmentConfiguration
IncludeAttachmentFilePatterns?: List<Value<string>>
ExcludeAttachmentFilePatterns?: List<Value<string>>
constructor(properties: SalesforceConfiguration) {
Object.assign(this, properties)
}
}
export class ColumnConfiguration {
DocumentIdColumnName!: Value<string>
DocumentDataColumnName!: Value<string>
DocumentTitleColumnName?: Value<string>
FieldMappings?: List<DataSourceToIndexFieldMapping>
ChangeDetectingColumns!: List<Value<string>>
constructor(properties: ColumnConfiguration) {
Object.assign(this, properties)
}
}
export class ServiceNowKnowledgeArticleConfiguration {
CrawlAttachments?: Value<boolean>
IncludeAttachmentFilePatterns?: List<Value<string>>
ExcludeAttachmentFilePatterns?: List<Value<string>>
DocumentDataFieldName!: Value<string>
DocumentTitleFieldName?: Value<string>
FieldMappings?: List<DataSourceToIndexFieldMapping>
FilterQuery?: Value<string>
constructor(properties: ServiceNowKnowledgeArticleConfiguration) {
Object.assign(this, properties)
}
}
export class ConfluenceSpaceConfiguration {
CrawlPersonalSpaces?: Value<boolean>
CrawlArchivedSpaces?: Value<boolean>
IncludeSpaces?: List<Value<string>>
ExcludeSpaces?: List<Value<string>>
SpaceFieldMappings?: List<ConfluenceSpaceToIndexFieldMapping>
constructor(properties: ConfluenceSpaceConfiguration) {
Object.assign(this, properties)
}
}
export class GoogleDriveConfiguration {
SecretArn!: Value<string>
InclusionPatterns?: List<Value<string>>
ExclusionPatterns?: List<Value<string>>
FieldMappings?: List<DataSourceToIndexFieldMapping>
ExcludeMimeTypes?: List<Value<string>>
ExcludeUserAccounts?: List<Value<string>>
ExcludeSharedDrives?: List<Value<string>>
constructor(properties: GoogleDriveConfiguration) {
Object.assign(this, properties)
}
}
export class S3Path {
Bucket!: Value<string>
Key!: Value<string>
constructor(properties: S3Path) {
Object.assign(this, properties)
}
}
export class ServiceNowConfiguration {
HostUrl!: Value<string>
SecretArn!: Value<string>
ServiceNowBuildVersion!: Value<string>
AuthenticationType?: Value<string>
KnowledgeArticleConfiguration?: ServiceNowKnowledgeArticleConfiguration
ServiceCatalogConfiguration?: ServiceNowServiceCatalogConfiguration
constructor(properties: ServiceNowConfiguration) {
Object.assign(this, properties)
}
}
export class ConfluenceConfiguration {
ServerUrl!: Value<string>
SecretArn!: Value<string>
Version!: Value<string>
SpaceConfiguration?: ConfluenceSpaceConfiguration
PageConfiguration?: ConfluencePageConfiguration
BlogConfiguration?: ConfluenceBlogConfiguration
AttachmentConfiguration?: ConfluenceAttachmentConfiguration
VpcConfiguration?: DataSourceVpcConfiguration
InclusionPatterns?: List<Value<string>>
ExclusionPatterns?: List<Value<string>>
constructor(properties: ConfluenceConfiguration) {
Object.assign(this, properties)
}
}
export class ConfluencePageToIndexFieldMapping {
DataSourceFieldName!: Value<string>
DateFieldFormat?: Value<string>
IndexFieldName!: Value<string>
constructor(properties: ConfluencePageToIndexFieldMapping) {
Object.assign(this, properties)
}
}
export class DatabaseConfiguration {
DatabaseEngineType!: Value<string>
ConnectionConfiguration!: ConnectionConfiguration
VpcConfiguration?: DataSourceVpcConfiguration
ColumnConfiguration!: ColumnConfiguration
AclConfiguration?: AclConfiguration
SqlConfiguration?: SqlConfiguration
constructor(properties: DatabaseConfiguration) {
Object.assign(this, properties)
}
}
export class SqlConfiguration {
QueryIdentifiersEnclosingOption?: Value<string>
constructor(properties: SqlConfiguration) {
Object.assign(this, properties)
}
}
export class S3DataSourceConfiguration {
BucketName!: Value<string>
InclusionPrefixes?: List<Value<string>>
InclusionPatterns?: List<Value<string>>
ExclusionPatterns?: List<Value<string>>
DocumentsMetadataConfiguration?: DocumentsMetadataConfiguration
AccessControlListConfiguration?: AccessControlListConfiguration
constructor(properties: S3DataSourceConfiguration) {
Object.assign(this, properties)
}
}
export class ConfluenceBlogConfiguration {
BlogFieldMappings?: List<ConfluenceBlogToIndexFieldMapping>
constructor(properties: ConfluenceBlogConfiguration) {
Object.assign(this, properties)
}
}
export class ConfluencePageConfiguration {
PageFieldMappings?: List<ConfluencePageToIndexFieldMapping>
constructor(properties: ConfluencePageConfiguration) {
Object.assign(this, properties)
}
}
export class ConnectionConfiguration {
DatabaseHost!: Value<string>
DatabasePort!: Value<number>
DatabaseName!: Value<string>
TableName!: Value<string>
SecretArn!: Value<string>
constructor(properties: ConnectionConfiguration) {
Object.assign(this, properties)
}
}
export class ServiceNowServiceCatalogConfiguration {
CrawlAttachments?: Value<boolean>
IncludeAttachmentFilePatterns?: List<Value<string>>
ExcludeAttachmentFilePatterns?: List<Value<string>>
DocumentDataFieldName!: Value<string>
DocumentTitleFieldName?: Value<string>
FieldMappings?: List<DataSourceToIndexFieldMapping>
constructor(properties: ServiceNowServiceCatalogConfiguration) {
Object.assign(this, properties)
}
}
export class SalesforceStandardObjectAttachmentConfiguration {
DocumentTitleFieldName?: Value<string>
FieldMappings?: List<DataSourceToIndexFieldMapping>
constructor(properties: SalesforceStandardObjectAttachmentConfiguration) {
Object.assign(this, properties)
}
}
export class SalesforceCustomKnowledgeArticleTypeConfiguration {
Name!: Value<string>
DocumentDataFieldName!: Value<string>
DocumentTitleFieldName?: Value<string>
FieldMappings?: List<DataSourceToIndexFieldMapping>
constructor(properties: SalesforceCustomKnowledgeArticleTypeConfiguration) {
Object.assign(this, properties)
}
}
export class ConfluenceBlogToIndexFieldMapping {
DataSourceFieldName!: Value<string>
DateFieldFormat?: Value<string>
IndexFieldName!: Value<string>
constructor(properties: ConfluenceBlogToIndexFieldMapping) {
Object.assign(this, properties)
}
}
export class OneDriveUsers {
OneDriveUserList?: List<Value<string>>
OneDriveUserS3Path?: S3Path
constructor(properties: OneDriveUsers) {
Object.assign(this, properties)
}
}
export class AclConfiguration {
AllowedGroupsColumnName!: Value<string>
constructor(properties: AclConfiguration) {
Object.assign(this, properties)
}
}
export class SalesforceStandardKnowledgeArticleTypeConfiguration {
DocumentDataFieldName!: Value<string>
DocumentTitleFieldName?: Value<string>
FieldMappings?: List<DataSourceToIndexFieldMapping>
constructor(properties: SalesforceStandardKnowledgeArticleTypeConfiguration) {
Object.assign(this, properties)
}
}
export class ConfluenceAttachmentConfiguration {
CrawlAttachments?: Value<boolean>
AttachmentFieldMappings?: List<ConfluenceAttachmentToIndexFieldMapping>
constructor(properties: ConfluenceAttachmentConfiguration) {
Object.assign(this, properties)
}
}
export class DataSourceVpcConfiguration {
SubnetIds!: List<Value<string>>
SecurityGroupIds!: List<Value<string>>
constructor(properties: DataSourceVpcConfiguration) {
Object.assign(this, properties)
}
}
export class SalesforceKnowledgeArticleConfiguration {
IncludedStates!: List<Value<string>>
StandardKnowledgeArticleTypeConfiguration?: SalesforceStandardKnowledgeArticleTypeConfiguration
CustomKnowledgeArticleTypeConfigurations?: List<SalesforceCustomKnowledgeArticleTypeConfiguration>
constructor(properties: SalesforceKnowledgeArticleConfiguration) {
Object.assign(this, properties)
}
}
export class AccessControlListConfiguration {
KeyPath?: Value<string>
constructor(properties: AccessControlListConfiguration) {
Object.assign(this, properties)
}
}
export class DataSourceToIndexFieldMapping {
DataSourceFieldName!: Value<string>
DateFieldFormat?: Value<string>
IndexFieldName!: Value<string>
constructor(properties: DataSourceToIndexFieldMapping) {
Object.assign(this, properties)
}
}
export class ConfluenceSpaceToIndexFieldMapping {
DataSourceFieldName!: Value<string>
DateFieldFormat?: Value<string>
IndexFieldName!: Value<string>
constructor(properties: ConfluenceSpaceToIndexFieldMapping) {
Object.assign(this, properties)
}
}
export class OneDriveConfiguration {
TenantDomain!: Value<string>
SecretArn!: Value<string>
OneDriveUsers!: OneDriveUsers
InclusionPatterns?: List<Value<string>>
ExclusionPatterns?: List<Value<string>>
FieldMappings?: List<DataSourceToIndexFieldMapping>
DisableLocalGroups?: Value<boolean>
constructor(properties: OneDriveConfiguration) {
Object.assign(this, properties)
}
}
export class DataSourceConfiguration {
S3Configuration?: S3DataSourceConfiguration
SharePointConfiguration?: SharePointConfiguration
SalesforceConfiguration?: SalesforceConfiguration
OneDriveConfiguration?: OneDriveConfiguration
ServiceNowConfiguration?: ServiceNowConfiguration
DatabaseConfiguration?: DatabaseConfiguration
ConfluenceConfiguration?: ConfluenceConfiguration
GoogleDriveConfiguration?: GoogleDriveConfiguration
constructor(properties: DataSourceConfiguration) {
Object.assign(this, properties)
}
}
export class SharePointConfiguration {
SharePointVersion!: Value<string>
Urls!: List<Value<string>>
SecretArn!: Value<string>
CrawlAttachments?: Value<boolean>
UseChangeLog?: Value<boolean>
InclusionPatterns?: List<Value<string>>
ExclusionPatterns?: List<Value<string>>
VpcConfiguration?: DataSourceVpcConfiguration
FieldMappings?: List<DataSourceToIndexFieldMapping>
DocumentTitleFieldName?: Value<string>
DisableLocalGroups?: Value<boolean>
constructor(properties: SharePointConfiguration) {
Object.assign(this, properties)
}
}
export class DocumentsMetadataConfiguration {
S3Prefix?: Value<string>
constructor(properties: DocumentsMetadataConfiguration) {
Object.assign(this, properties)
}
}
export interface DataSourceProperties {
Name: Value<string>
IndexId: Value<string>
Type: Value<string>
DataSourceConfiguration?: DataSourceConfiguration
Description?: Value<string>
Schedule?: Value<string>
RoleArn?: Value<string>
Tags?: List<ResourceTag>
}
export default class DataSource extends ResourceBase<DataSourceProperties> {
static ConfluenceAttachmentToIndexFieldMapping = ConfluenceAttachmentToIndexFieldMapping
static SalesforceStandardObjectConfiguration = SalesforceStandardObjectConfiguration
static SalesforceChatterFeedConfiguration = SalesforceChatterFeedConfiguration
static SalesforceConfiguration = SalesforceConfiguration
static ColumnConfiguration = ColumnConfiguration
static ServiceNowKnowledgeArticleConfiguration = ServiceNowKnowledgeArticleConfiguration
static ConfluenceSpaceConfiguration = ConfluenceSpaceConfiguration
static GoogleDriveConfiguration = GoogleDriveConfiguration
static S3Path = S3Path
static ServiceNowConfiguration = ServiceNowConfiguration
static ConfluenceConfiguration = ConfluenceConfiguration
static ConfluencePageToIndexFieldMapping = ConfluencePageToIndexFieldMapping
static DatabaseConfiguration = DatabaseConfiguration
static SqlConfiguration = SqlConfiguration
static S3DataSourceConfiguration = S3DataSourceConfiguration
static ConfluenceBlogConfiguration = ConfluenceBlogConfiguration
static ConfluencePageConfiguration = ConfluencePageConfiguration
static ConnectionConfiguration = ConnectionConfiguration
static ServiceNowServiceCatalogConfiguration = ServiceNowServiceCatalogConfiguration
static SalesforceStandardObjectAttachmentConfiguration = SalesforceStandardObjectAttachmentConfiguration
static SalesforceCustomKnowledgeArticleTypeConfiguration = SalesforceCustomKnowledgeArticleTypeConfiguration
static ConfluenceBlogToIndexFieldMapping = ConfluenceBlogToIndexFieldMapping
static OneDriveUsers = OneDriveUsers
static AclConfiguration = AclConfiguration
static SalesforceStandardKnowledgeArticleTypeConfiguration = SalesforceStandardKnowledgeArticleTypeConfiguration
static ConfluenceAttachmentConfiguration = ConfluenceAttachmentConfiguration
static DataSourceVpcConfiguration = DataSourceVpcConfiguration
static SalesforceKnowledgeArticleConfiguration = SalesforceKnowledgeArticleConfiguration
static AccessControlListConfiguration = AccessControlListConfiguration
static DataSourceToIndexFieldMapping = DataSourceToIndexFieldMapping
static ConfluenceSpaceToIndexFieldMapping = ConfluenceSpaceToIndexFieldMapping
static OneDriveConfiguration = OneDriveConfiguration
static DataSourceConfiguration = DataSourceConfiguration
static SharePointConfiguration = SharePointConfiguration
static DocumentsMetadataConfiguration = DocumentsMetadataConfiguration
constructor(properties: DataSourceProperties) {
super('AWS::Kendra::DataSource', properties)
}
} | the_stack |
import { compress, encodePCM, encodeWAV } from '../transform/transform';
declare let window: any;
declare let Math: any;
declare let navigator: any;
declare let Promise: any;
// 构造函数参数格式
interface recorderConfig {
sampleBits?: number, // 采样位数
sampleRate?: number, // 采样率
numChannels?: number, // 声道数
compiling?: boolean, // 是否边录边播
}
export default class Recorder {
private context: any;
protected config: recorderConfig; // 配置
private analyser: any;
private size: number = 0; // 录音文件总长度
private lBuffer: Array<Float32Array> = []; // pcm音频数据搜集器(左声道)
private rBuffer: Array<Float32Array> = []; // pcm音频数据搜集器(右声道)
private PCM: any; // 最终的PCM数据缓存,避免多次encode
private tempPCM: Array<DataView> = []; // 边录边转时临时存放pcm的
private audioInput: any;
protected inputSampleRate: number; // 输入采样率
protected inputSampleBits: number = 16; // 输入采样位数
protected outputSampleRate: number; // 输出采样率
protected oututSampleBits: number; // 输出采样位数
private source: any; // 音频输入
private recorder: any;
private stream: any; // 流
protected littleEdian: boolean; // 是否是小端字节序
protected fileSize: number = 0; // 录音大小,byte为单位
protected duration: number = 0; // 录音时长
private needRecord: boolean = true; // 由于safari问题,导致使用该方案代替disconnect/connect方案
// 正在录音时间,参数是已经录了多少时间了
public onprocess: (duration: number) => void;
// onprocess 替代函数,保持原来的 onprocess 向下兼容
public onprogress: (payload: {
duration: number,
fileSize: number,
vol: number,
// data: Array<DataView>, // 当前存储的所有录音数据
}) => void;
public onplay: () => void; // 音频播放回调
public onpauseplay: () => void; // 音频暂停回调
public onresumeplay: () => void; // 音频恢复播放回调
public onstopplay: () => void; // 音频停止播放回调
public onplayend: () => void; // 音频正常播放结束
/**
* @param {Object} options 包含以下三个参数:
* sampleBits,采样位数,一般8,16,默认16
* sampleRate,采样率,一般 11025、16000、22050、24000、44100、48000,默认为浏览器自带的采样率
* numChannels,声道,1或2
*/
constructor(options: recorderConfig = {}) {
// 临时audioContext,为了获取输入采样率的
let context = new (window.AudioContext || window.webkitAudioContext)();
this.inputSampleRate = context.sampleRate; // 获取当前输入的采样率
// 设置输出配置
this.setNewOption(options);
// 判断端字节序
this.littleEdian = (function() {
let buffer = new ArrayBuffer(2);
new DataView(buffer).setInt16(0, 256, true);
return new Int16Array(buffer)[0] === 256;
})();
// 兼容 getUserMedia
Recorder.initUserMedia();
}
protected setNewOption(options: recorderConfig = {}) {
this.config = {
// 采样数位 8, 16
sampleBits: ~[8, 16].indexOf(options.sampleBits) ? options.sampleBits : 16,
// 采样率
sampleRate: ~[8000, 11025, 16000, 22050, 24000, 44100, 48000].indexOf(options.sampleRate) ? options.sampleRate : this.inputSampleRate,
// 声道数,1或2
numChannels: ~[1, 2].indexOf(options.numChannels) ? options.numChannels : 1,
// 是否需要边录边转,默认关闭,后期使用web worker
// compiling: !!options.compiling || false, // 先移除
};
// 设置采样的参数
this.outputSampleRate = this.config.sampleRate; // 输出采样率
this.oututSampleBits = this.config.sampleBits; // 输出采样数位 8, 16
}
/**
* 开始录音
*
* @returns {Promise<{}>}
* @memberof Recorder
*/
startRecord(): Promise<{}> {
if (this.context) {
// 关闭先前的录音实例,因为前次的实例会缓存少量前次的录音数据
this.destroyRecord();
}
// 初始化
this.initRecorder();
return navigator.mediaDevices.getUserMedia({
audio: true
}).then(stream => {
// audioInput表示音频源节点
// stream是通过navigator.getUserMedia获取的外部(如麦克风)stream音频输出,对于这就是输入
this.audioInput = this.context.createMediaStreamSource(stream);
this.stream = stream;
}/* 报错丢给外部使用者catch,后期可在此处增加建议性提示
, error => {
// 抛出异常
Recorder.throwError(error.name + " : " + error.message);
} */).then(() => {
// audioInput 为声音源,连接到处理节点 recorder
this.audioInput.connect(this.analyser);
this.analyser.connect(this.recorder);
// this.audioInput.connect(this.recorder);
// 处理节点 recorder 连接到扬声器
this.recorder.connect(this.context.destination);
});
}
/**
* 暂停录音
*
* @memberof Recorder
*/
pauseRecord(): void {
this.needRecord = false;
}
/**
* 继续录音
*
* @memberof Recorder
*/
resumeRecord(): void {
this.needRecord = true;
}
/**
* 停止录音
*
*/
stopRecord(): void {
this.audioInput && this.audioInput.disconnect();
this.source && this.source.stop();
this.recorder.disconnect();
this.analyser.disconnect();
this.needRecord = true;
}
/**
* 销毁录音对象
*
*/
destroyRecord(): Promise<{}> {
this.clearRecordStatus();
// 结束流
this.stopStream();
return this.closeAudioContext();
}
getAnalyseData() {
let dataArray = new Uint8Array(this.analyser.frequencyBinCount);
// 将数据拷贝到dataArray中。
this.analyser.getByteTimeDomainData(dataArray);
return dataArray;
}
// 获取录音数据
getData() {
let data: any = this.flat();
return data;
}
/**
* 清除状态
*
*/
private clearRecordStatus() {
this.lBuffer.length = 0;
this.rBuffer.length = 0;
this.size = 0;
this.fileSize = 0;
this.PCM = null;
this.audioInput = null;
this.duration = 0;
}
/**
* 将二维数组转一维
*
* @private
* @returns {float32array} 音频pcm二进制数据
* @memberof Recorder
*/
private flat() {
let lData = null,
rData = new Float32Array(0); // 右声道默认为0
// 创建存放数据的容器
if (1 === this.config.numChannels) {
lData = new Float32Array(this.size);
} else {
lData = new Float32Array(this.size / 2);
rData = new Float32Array(this.size / 2);
}
// 合并
let offset = 0; // 偏移量计算
// 将二维数据,转成一维数据
// 左声道
for (let i = 0; i < this.lBuffer.length; i++) {
lData.set(this.lBuffer[i], offset);
offset += this.lBuffer[i].length;
}
offset = 0;
// 右声道
for (let i = 0; i < this.rBuffer.length; i++) {
rData.set(this.rBuffer[i], offset);
offset += this.rBuffer[i].length;
}
return {
left: lData,
right: rData
};
}
/**
* 初始化录音实例
*/
private initRecorder(): void {
// 清空数据
this.clearRecordStatus();
this.context = new (window.AudioContext || window.webkitAudioContext)();
this.analyser = this.context.createAnalyser(); // 录音分析节点
this.analyser.fftSize = 2048; // 表示存储频域的大小
// 第一个参数表示收集采样的大小,采集完这么多后会触发 onaudioprocess 接口一次,该值一般为1024,2048,4096等,一般就设置为4096
// 第二,三个参数分别是输入的声道数和输出的声道数,保持一致即可。
let createScript = this.context.createScriptProcessor || this.context.createJavaScriptNode;
this.recorder = createScript.apply(this.context, [4096, this.config.numChannels, this.config.numChannels]);
// 音频采集
this.recorder.onaudioprocess = e => {
if (!this.needRecord) {
return;
}
// 左声道数据
// getChannelData返回Float32Array类型的pcm数据
let lData = e.inputBuffer.getChannelData(0),
rData = null,
vol = 0; // 音量百分比
this.lBuffer.push(new Float32Array(lData));
this.size += lData.length;
// 判断是否有右声道数据
if (2 === this.config.numChannels) {
rData = e.inputBuffer.getChannelData(1);
this.rBuffer.push(new Float32Array(rData));
this.size += rData.length;
}
// 边录边转处理 暂时不支持
// if (this.config.compiling) {
// let pcm = this.transformIntoPCM(lData, rData);
// this.tempPCM.push(pcm);
// // 计算录音大小
// this.fileSize = pcm.byteLength * this.tempPCM.length;
// } else {
// 计算录音大小
this.fileSize = Math.floor(this.size / Math.max( this.inputSampleRate / this.outputSampleRate, 1))
* (this.oututSampleBits / 8)
// }
// 为何此处计算大小需要分开计算。原因是先录后转时,是将所有数据一起处理,边录边转是单个 4096 处理,
// 有小数位的偏差。
// 计算音量百分比
vol = Math.max.apply(Math, lData) * 100;
// 统计录音时长
this.duration += 4096 / this.inputSampleRate;
// 录音时长回调
this.onprocess && this.onprocess(this.duration);
// 录音时长及响度回调
this.onprogress && this.onprogress({
duration: this.duration,
fileSize: this.fileSize,
vol,
// data: this.tempPCM, // 当前所有的pcm数据,调用者控制增量
});
}
}
/**
* 终止流(这可以让浏览器上正在录音的标志消失掉)
* @private
* @memberof Recorder
*/
private stopStream() {
if (this.stream && this.stream.getTracks) {
this.stream.getTracks().forEach(track => track.stop());
this.stream = null;
}
}
/**
* close兼容方案
* 如firefox 30 等低版本浏览器没有 close方法
*/
private closeAudioContext() {
if (this.context && this.context.close && this.context.state !== 'closed') {
return this.context.close();
} else {
return new Promise((resolve) => {
resolve();
});
}
}
// getUserMedia 版本兼容
static initUserMedia() {
if (navigator.mediaDevices === undefined) {
navigator.mediaDevices = {};
}
if (navigator.mediaDevices.getUserMedia === undefined) {
navigator.mediaDevices.getUserMedia = function(constraints) {
let getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
if (!getUserMedia) {
return Promise.reject(new Error('浏览器不支持 getUserMedia !'));
}
return new Promise(function(resolve, reject) {
getUserMedia.call(navigator, constraints, resolve, reject);
});
}
}
}
/**
* 将获取到到左右声道的Float32Array数据编码转化
*
* @param {Float32Array} lData 左声道数据
* @param {Float32Array} rData 有声道数据
* @returns DataView
*/
private transformIntoPCM(lData, rData) {
let lBuffer = new Float32Array(lData),
rBuffer = new Float32Array(rData);
let data = compress({
left: lBuffer,
right: rBuffer,
}, this.inputSampleRate, this.outputSampleRate);
return encodePCM(data, this.oututSampleBits, this.littleEdian);
}
static getPermission(): Promise<{}> {
this.initUserMedia();
return navigator.mediaDevices.getUserMedia({audio: true}).then((stream) => {
stream && stream.getTracks().forEach(track => track.stop());
});
}
} | the_stack |
import { stripNulls } from './array-utils'
import { Either, left, right, mapEither } from './either'
enum RawModifier {}
enum WindowModifier {}
enum CanvasModifier {}
enum LocalModifier {}
type NodeGraphModifier = CanvasModifier
export type CoordinateMarker =
| RawModifier
| WindowModifier
| CanvasModifier
| LocalModifier
| NodeGraphModifier
type PointInner = {
x: number
y: number
}
export type Point<C extends CoordinateMarker> = PointInner & C
export type RawPoint = RawModifier & PointInner
export type WindowPoint = WindowModifier & PointInner
export type CanvasPoint = CanvasModifier & PointInner
export function canvasPoint(p: PointInner): CanvasPoint {
return p as CanvasPoint
}
export function windowPoint(p: PointInner): WindowPoint {
return p as WindowPoint
}
export type LocalPoint = LocalModifier & PointInner
export type NodeGraphPoint = NodeGraphModifier & PointInner
export type Vector<C extends CoordinateMarker> = Point<C>
export type WindowVector = WindowModifier & PointInner
export type CanvasVector = CanvasModifier & PointInner
export type LocalVector = LocalModifier & PointInner
export type UnsafePoint = PointInner
export type Circle = {
cx: number
cy: number
r: number
}
export type Ellipse = {
cx: number
cy: number
rx: number
ry: number
}
export interface Size {
width: number
height: number
}
export function size(width: number, height: number): Size {
return {
width: width,
height: height,
}
}
export type RectangleInner = {
x: number
y: number
width: number
height: number
}
export type SimpleRectangle = RectangleInner
export type Rectangle<C extends CoordinateMarker> = RectangleInner & C
export type WindowRectangle = WindowModifier & RectangleInner
export type CanvasRectangle = CanvasModifier & RectangleInner
export type LocalRectangle = LocalModifier & RectangleInner
export type NodeGraphRectangle = NodeGraphModifier & RectangleInner
export function canvasRectangle(rectangle: null | undefined): null
export function canvasRectangle(rectangle: RectangleInner): CanvasRectangle
export function canvasRectangle(
rectangle: RectangleInner | null | undefined,
): CanvasRectangle | null
export function canvasRectangle(
rectangle: RectangleInner | null | undefined,
): CanvasRectangle | null {
if (rectangle == null) {
return null
}
return rectangle as CanvasRectangle
}
export function localRectangle(rectangle: null | undefined): null
export function localRectangle(rectangle: RectangleInner): LocalRectangle
export function localRectangle(rectangle: RectangleInner | null | undefined): LocalRectangle | null
export function localRectangle(
rectangle: RectangleInner | null | undefined,
): LocalRectangle | null {
if (rectangle == null) {
return null
}
return rectangle as LocalRectangle
}
export function numbersEqual(l: number, r: number): boolean {
// in JS numbers are considered accurate up to 15 digits: https://www.w3schools.com/js/js_numbers.asp
return l <= r + r * 1e-14 && l >= r - r * 1e-14
}
export function numberIsZero(n: number): boolean {
return numbersEqual(n, 0)
}
export function normalizeDegrees(degrees: number): number {
return Math.abs(degrees % 360)
}
export function degreesToRadians(degrees: number): number {
return (degrees * Math.PI) / 180
}
export function radiansToDegrees(radians: number): number {
return (radians * 180) / Math.PI
}
export function scalePoint<C extends CoordinateMarker>(p: Point<C>, by: Vector<C>): Point<C> {
return {
x: p.x * by.x,
y: p.y * by.y,
} as Point<C>
}
export function scaleVector<C extends CoordinateMarker>(vector: Vector<C>, by: number): Vector<C> {
return {
x: vector.x * by,
y: vector.y * by,
} as Vector<C>
}
export function rotateVector<C extends CoordinateMarker>(
vector: Vector<C>,
radians: number,
): Vector<C> {
return {
x: vector.x * Math.cos(radians) - vector.y * Math.sin(radians),
y: vector.x * Math.sin(radians) + vector.y * Math.cos(radians),
} as Vector<C>
}
export const zeroPoint = {
x: 0,
y: 0,
}
export const zeroSize = {
width: 0,
height: 0,
}
export const zeroRectangle = {
x: 0,
y: 0,
width: 0,
height: 0,
}
export const zeroCanvasRect = zeroRectangle as CanvasRectangle
export const zeroLocalRect = zeroRectangle as LocalRectangle
export const zeroCanvasPoint = zeroPoint as CanvasPoint
export function zeroRectangleAtPoint<C extends CoordinateMarker>(p: Point<C>): Rectangle<C> {
return {
x: p.x,
y: p.y,
width: 0,
height: 0,
} as Rectangle<C>
}
export function rect<C extends CoordinateMarker>(
x: number,
y: number,
width: number,
height: number,
): Rectangle<C> {
return {
x: x,
y: y,
width: width,
height: height,
} as Rectangle<C>
}
export function point<C extends CoordinateMarker>(x: number, y: number): Point<C> {
return {
x: x,
y: y,
} as Point<C>
}
export function shiftToOrigin<C extends CoordinateMarker>(rectangle: Rectangle<C>): Rectangle<C> {
return {
x: 0,
y: 0,
width: rectangle.width,
height: rectangle.height,
} as Rectangle<C>
}
export function rectOrigin<C extends CoordinateMarker>(rectangle: Rectangle<C>): Point<C> {
return {
x: rectangle.x,
y: rectangle.y,
} as Point<C>
}
export function rectSize(rectangle: Rectangle<any>): Size {
return {
width: rectangle.width,
height: rectangle.height,
}
}
export function setRectSize<C extends CoordinateMarker>(
rectangle: Rectangle<C>,
sizeToSet: Size,
): Rectangle<C> {
return {
x: rectangle.x,
y: rectangle.y,
width: sizeToSet.width,
height: sizeToSet.height,
} as Rectangle<C>
}
export function rectContainsPoint<C extends CoordinateMarker>(
rectangle: Rectangle<C>,
p: Point<C>,
): boolean {
return (
rectangle.x < p.x &&
rectangle.y < p.y &&
rectangle.x + rectangle.width > p.x &&
rectangle.y + rectangle.height > p.y
)
}
export function circleContainsPoint<C extends CoordinateMarker>(
circle: Circle,
p: Point<C>,
): boolean {
const dist = magnitude({
x: p.x - circle.cx,
y: p.y - circle.cy,
} as LocalPoint)
return dist <= circle.r
}
export function ellipseContainsPoint<C extends CoordinateMarker>(
ellipse: Ellipse,
p: Point<C>,
): boolean {
const { cx, cy, rx, ry } = ellipse
const { x, y } = p
// first check if the point is in the rectangle containing the ellipse
if (rectContainsPoint({ x: cx, y: cy, width: rx * 2, height: ry * 2 } as Rectangle<C>, p)) {
// now check if it is actually in the ellipse
// https://math.stackexchange.com/questions/76457/check-if-a-point-is-within-an-ellipse/76463#76463
const a = Math.pow(x - cx, 2) / Math.pow(rx, 2)
const b = Math.pow(y - cy, 2) / Math.pow(ry, 2)
return a + b <= 1
} else {
return false
}
}
export function negate<C extends CoordinateMarker>(p: Point<C>): Point<C> {
return {
x: -p.x,
y: -p.y,
} as Point<C>
}
export function magnitude<C extends CoordinateMarker>(vector: Vector<C>): number {
return Math.sqrt(Math.pow(vector.x, 2) + Math.pow(vector.y, 2))
}
export function distance<C extends CoordinateMarker>(from: Point<C>, to: Point<C>): number {
return magnitude({ x: from.x - to.x, y: from.y - to.y } as Vector<C>)
}
export function product<C extends CoordinateMarker>(a: Point<C>, b: Point<C>): number {
return a.x * b.x + a.y * b.y
}
export function vectorFromPoints<C extends CoordinateMarker>(
p1: Point<C>,
p2: Point<C>,
): Vector<C> {
return {
x: p2.x - p1.x,
y: p2.y - p1.y,
} as Vector<C>
}
export function interpolateAt<C extends CoordinateMarker>(
p1: Point<C>,
p2: Point<C>,
ratio: number,
): Point<C> {
return {
x: p1.x + (p2.x - p1.x) * ratio,
y: p1.y + (p2.y - p1.y) * ratio,
} as Point<C>
}
export function normalizeRect<C extends CoordinateMarker>(rectangle: Rectangle<C>): Rectangle<C> {
const x = rectangle.width < 0 ? rectangle.x + rectangle.width : rectangle.x
const y = rectangle.height < 0 ? rectangle.y + rectangle.height : rectangle.y
return {
x: x,
y: y,
width: Math.abs(rectangle.width),
height: Math.abs(rectangle.height),
} as Rectangle<C>
}
export function getLocalRectangleInNewParentContext(
newParent: CanvasPoint,
child: CanvasRectangle,
): LocalRectangle {
return asLocal(offsetRect(child, negate(newParent)))
}
export function getLocalPointInNewParentContext(
newParent: CanvasPoint,
child: CanvasPoint,
): LocalPoint {
return asLocal(offsetPoint(child, negate(newParent)))
}
export function getCanvasRectangleWithCanvasOffset(
canvasOffset: CanvasPoint,
child: LocalRectangle,
): CanvasRectangle {
return offsetRect(asGlobal(child), canvasOffset)
}
export function getCanvasPointWithCanvasOffset(
canvasOffset: CanvasPoint,
child: LocalPoint,
): CanvasPoint {
return offsetPoint(asGlobal(child), canvasOffset)
}
export function getCanvasVectorFromWindowVector(
vector: WindowVector,
canvasScale: number,
): CanvasVector {
return asGlobal(scaleVector(vector, 1 / canvasScale))
}
export function asLocal(g: CanvasRectangle | WindowRectangle): LocalRectangle
export function asLocal(g: CanvasPoint | WindowPoint): LocalPoint
export function asLocal(g: CanvasVector | WindowVector): LocalVector
export function asLocal(g: any) {
return g as any
}
export function asGlobal(l: LocalRectangle | WindowRectangle): CanvasRectangle
export function asGlobal(l: LocalPoint | WindowPoint): CanvasPoint
export function asGlobal(l: LocalVector | WindowVector): CanvasVector
export function asGlobal(g: any) {
return g as any
}
export function rectangleDifference<C extends CoordinateMarker>(
from: Rectangle<C>,
to: Rectangle<C>,
): Rectangle<C> {
return {
x: to.x - from.x,
y: to.y - from.y,
width: to.width - from.width,
height: to.height - from.height,
} as Rectangle<C>
}
export function rectangleIntersection<C extends CoordinateMarker>(
rect1: Rectangle<C>,
rect2: Rectangle<C>,
): Rectangle<C> | null {
const maxLeft = Math.max(rect1.x, rect2.x)
const minRight = Math.min(rect1.x + rect1.width, rect2.x + rect2.width)
const top = Math.max(rect1.y, rect2.y)
const bottom = Math.min(rect1.y + rect1.height, rect2.y + rect2.height)
const width = minRight - maxLeft
const height = bottom - top
if (width > 0 && height > 0) {
return {
x: maxLeft,
y: top,
width: minRight - maxLeft,
height: bottom - top,
} as Rectangle<C>
} else {
return null
}
}
export function pointDifference<C extends CoordinateMarker>(
from: Point<C>,
to: Point<C>,
): Point<C> {
return {
x: to.x - from.x,
y: to.y - from.y,
} as Point<C>
}
export function vectorDifference<C extends CoordinateMarker>(
from: Vector<C>,
to: Vector<C>,
): Vector<C> {
return pointDifference(from, to)
}
export function offsetPoint<C extends CoordinateMarker>(p: Point<C>, by: Point<C>): Point<C> {
return {
x: p.x + by.x,
y: p.y + by.y,
} as Point<C>
}
export function offsetRect<C extends CoordinateMarker>(
rectangle: Rectangle<C>,
by: Point<C>,
): Rectangle<C> {
return {
x: rectangle.x + by.x,
y: rectangle.y + by.y,
width: rectangle.width,
height: rectangle.height,
} as Rectangle<C>
}
export function combineRectangles<C extends CoordinateMarker>(
first: Rectangle<C>,
second: Rectangle<C>,
): Rectangle<C> {
return {
x: first.x + second.x,
y: first.y + second.y,
width: first.width + second.width,
height: first.height + second.height,
} as Rectangle<C>
}
export function boundingRectangleArray<C extends CoordinateMarker>(
rectangles: Array<Rectangle<C> | null>,
): Rectangle<C> | null {
const filtered = stripNulls(rectangles)
if (filtered.length === 0) {
return null
}
const [firstRectangle, ...remainingRectangles] = filtered
if (remainingRectangles.length === 0) {
return firstRectangle
} else {
return remainingRectangles.reduce(boundingRectangle, firstRectangle)
}
}
export function boundingRectangle<C extends CoordinateMarker>(
first: Rectangle<C>,
second: Rectangle<C>,
): Rectangle<C> {
const firstTL: Point<C> = first
const firstBR = {
x: first.x + first.width,
y: first.y + first.height,
} as Point<C>
const secondTL: Point<C> = second
const secondBR = {
x: second.x + second.width,
y: second.y + second.height,
} as Point<C>
const newTL = {
x: Math.min(firstTL.x, secondTL.x),
y: Math.min(firstTL.y, secondTL.y),
} as Point<C>
const newBR = {
x: Math.max(firstBR.x, secondBR.x),
y: Math.max(firstBR.y, secondBR.y),
} as Point<C>
return {
x: newTL.x,
y: newTL.y,
width: newBR.x - newTL.x,
height: newBR.y - newTL.y,
} as Rectangle<C>
}
export function stretchRect<C extends CoordinateMarker>(
rectangle: Rectangle<C>,
by: {
w: number
h: number
},
): Rectangle<C> {
const width = rectangle.width + by.w
const height = rectangle.height + by.h
return normalizeRect({
x: rectangle.x,
y: rectangle.y,
width: width,
height: height,
} as Rectangle<C>)
}
export function scaleSize(sizeToScale: Size, by: number): Size {
return {
width: sizeToScale.width * by,
height: sizeToScale.height * by,
}
}
export function scaleRect<Rect extends Rectangle<C>, C extends CoordinateMarker>(
rectangle: Rect,
by: number,
fromCenter: boolean = false,
): Rect {
const width = rectangle.width * by
const height = rectangle.height * by
const xOffset = (width - rectangle.width) / 2
const yOffset = (height - rectangle.height) / 2
return {
x: fromCenter ? rectangle.x - xOffset : rectangle.x * by,
y: fromCenter ? rectangle.y - yOffset : rectangle.y * by,
width: width,
height: height,
} as Rect
}
export function getRectCenter<C extends CoordinateMarker>(rectangle: Rectangle<C>): Point<C> {
return {
x: rectangle.x + rectangle.width / 2,
y: rectangle.y + rectangle.height / 2,
} as Point<C>
}
export function setRectLeftX<C extends CoordinateMarker>(
rectangle: Rectangle<C>,
x: number,
): Rectangle<C> {
return {
x: x,
y: rectangle.y,
width: rectangle.width,
height: rectangle.height,
} as Rectangle<C>
}
export function setRectCenterX<C extends CoordinateMarker>(
rectangle: Rectangle<C>,
x: number,
): Rectangle<C> {
return {
x: x - rectangle.width / 2,
y: rectangle.y,
width: rectangle.width,
height: rectangle.height,
} as Rectangle<C>
}
export function setRectRightX<C extends CoordinateMarker>(
rectangle: Rectangle<C>,
x: number,
): Rectangle<C> {
return {
x: x - rectangle.width,
y: rectangle.y,
width: rectangle.width,
height: rectangle.height,
} as Rectangle<C>
}
export function setRectTopY<C extends CoordinateMarker>(
rectangle: Rectangle<C>,
y: number,
): Rectangle<C> {
return {
x: rectangle.x,
y: y,
width: rectangle.width,
height: rectangle.height,
} as Rectangle<C>
}
export function setRectCenterY<C extends CoordinateMarker>(
rectangle: Rectangle<C>,
y: number,
): Rectangle<C> {
return {
x: rectangle.x,
y: y - rectangle.height / 2,
width: rectangle.width,
height: rectangle.height,
} as Rectangle<C>
}
export function setRectBottomY<C extends CoordinateMarker>(
rectangle: Rectangle<C>,
y: number,
): Rectangle<C> {
return {
x: rectangle.x,
y: y - rectangle.height,
width: rectangle.width,
height: rectangle.height,
} as Rectangle<C>
}
export function setRectWidth<C extends CoordinateMarker>(
rectangle: Rectangle<C>,
width: number,
): Rectangle<C> {
return {
x: rectangle.x,
y: rectangle.y,
width: width,
height: rectangle.height,
} as Rectangle<C>
}
export function setRectHeight<C extends CoordinateMarker>(
rectangle: Rectangle<C>,
height: number,
): Rectangle<C> {
return {
x: rectangle.x,
y: rectangle.y,
width: rectangle.width,
height: height,
} as Rectangle<C>
}
export function rectFromPointVector<C extends CoordinateMarker>(
p: Point<C>,
v: Vector<C>,
pointIsCenter: boolean,
): Rectangle<C> {
const vector = pointIsCenter ? { x: v.x * 2, y: v.y * 2 } : v
const origin = pointIsCenter ? { x: p.x - v.x, y: p.y - v.y } : p
const rectangle = {
x: origin.x,
y: origin.y,
width: vector.x,
height: vector.y,
} as Rectangle<C>
return normalizeRect(rectangle)
}
export function rectSizeToVector<C extends CoordinateMarker>(sizeOfVector: Size): Point<C> {
return {
x: sizeOfVector.width,
y: sizeOfVector.height,
} as Point<C>
}
export function transformFrameUsingBoundingBox<C extends CoordinateMarker>(
newBoundingBox: Rectangle<C>,
currentBoundingBox: Rectangle<C>,
currentFrame: Rectangle<C>,
): Rectangle<C> {
const frame = offsetRect(currentFrame, negate(currentBoundingBox as Point<C>))
// group and multiselect resize
const scaleWidth =
currentBoundingBox.width === 0 ? 1 : newBoundingBox.width / currentBoundingBox.width
const scaleHeight =
currentBoundingBox.height === 0 ? 1 : newBoundingBox.height / currentBoundingBox.height
const updatedFrameInBoundingBox = {
x: frame.x * scaleWidth,
y: frame.y * scaleHeight,
width: currentBoundingBox.width === 0 ? newBoundingBox.width : frame.width * scaleWidth,
height: currentBoundingBox.height === 0 ? newBoundingBox.height : frame.height * scaleHeight,
} as Rectangle<C>
return offsetRect(updatedFrameInBoundingBox, newBoundingBox)
}
export function closestPointOnLine<C extends CoordinateMarker>(
lineA: Point<C>,
lineB: Point<C>,
p: Point<C>,
): Point<C> {
const aToP = pointDifference(lineA, p)
const aToB = pointDifference(lineA, lineB)
const aToBSquared = Math.pow(aToB.x, 2) + Math.pow(aToB.y, 2)
// the dot product of aToP and aToB
const atpDotAtb = product(aToP, aToB)
// The distance from A to the closest point
const t = atpDotAtb / aToBSquared
// Add the distance to A, moving towards B
return {
x: lineA.x + aToB.x * t,
y: lineA.y + aToB.y * t,
} as Point<C>
}
export function lineIntersection<C extends CoordinateMarker>(
line1A: Point<C>,
line1B: Point<C>,
line2A: Point<C>,
line2B: Point<C>,
): Point<C> | null {
// from http://jsfiddle.net/Gd2S2/454/
// if the lines intersect, the result contains the x and y of the intersection (treating the lines as infinite) and booleans for whether line segment 1 or line segment 2 contain the point
const denominator =
(line2B.y - line2A.y) * (line1B.x - line1A.x) - (line2B.x - line2A.x) * (line1B.y - line1A.y)
if (denominator === 0) {
return null
}
let a = line1A.y - line2A.y
let b = line1A.x - line2A.x
const numerator1 = (line2B.x - line2A.x) * a - (line2B.y - line2A.y) * b
const numerator2 = (line1B.x - line1A.x) * a - (line1B.y - line1A.y) * b
a = numerator1 / denominator
b = numerator2 / denominator
// if we cast these lines infinitely in both directions, they intersect here:
// it is worth noting that this should be the same as:
// x = line2A.x + (b * (line2B.x - line2A.x))
// y = line2A.x + (b * (line2B.y - line2A.y))
return {
x: line1A.x + a * (line1B.x - line1A.x),
y: line1A.y + a * (line1B.y - line1A.y),
} as Point<C>
}
export function roundPointTo<C extends CoordinateMarker>(p: Point<C>, precision: number): Point<C> {
return {
x: roundTo(p.x, precision),
y: roundTo(p.y, precision),
} as Point<C>
}
export function roundTo(number: number, digits: number = 0): number {
const multiplicator = Math.pow(10, digits)
const n = parseFloat((number * multiplicator).toFixed(11))
return Math.round(n) / multiplicator
}
export function roundToNearestHalf(n: number): number {
return Math.round(n * 2) / 2
}
export function roundPointToNearestHalf<C extends CoordinateMarker>(p: Point<C>): Point<C> {
return {
x: roundToNearestHalf(p.x),
y: roundToNearestHalf(p.y),
} as Point<C>
}
export function percentToNumber(input: string): string | number {
const newValue = Number(input.replace('%', ''))
return isNaN(newValue) ? input : newValue / 100
}
export function numberToPercent(value: number): string {
return roundTo(value * 100, 2) + '%'
}
export function rectangleToPoints<C extends CoordinateMarker>(
rectangle: Rectangle<C>,
): Array<Point<C>> {
return [
{
x: rectangle.x,
y: rectangle.y,
} as Point<C>,
{
x: rectangle.x + rectangle.width,
y: rectangle.y,
} as Point<C>,
{
x: rectangle.x,
y: rectangle.y + rectangle.height,
} as Point<C>,
{
x: rectangle.x + rectangle.width,
y: rectangle.y + rectangle.height,
} as Point<C>,
]
}
export function pointsEqual<C extends CoordinateMarker>(
first: Point<C>,
second: Point<C>,
): boolean {
return first.x === second.x && first.y === second.y
}
export function sizesEqual(first: Size | null, second: Size | null): boolean {
if (first == null) {
if (second == null) {
return true
} else {
return false
}
} else {
if (second == null) {
return false
} else {
return first.width === second.width && first.height === second.height
}
}
}
export function rectanglesEqual(first: RectangleInner, second: RectangleInner): boolean {
return (
first.x === second.x &&
first.y === second.y &&
first.width === second.width &&
first.height === second.height
)
}
export function proportion(from: number, to: number): number {
if (from < 0 || to < 0) {
throw new Error(`Invalid parameters passed: ${from}, ${to}`)
} else {
if (to === 0) {
return 1
} else if (from === 0) {
return 0
} else {
const total = from + to
return from / total
}
}
}
// In radians.
// Careful as this is the angle from the _downward_ vertical.
export function angleOfPointFromVertical(p: Point<any>): number {
// Need to flip the x coordinate because we're getting the angle
// from the downward vertical.
const maybeNegativeAngle = Math.atan2(-p.x, p.y)
if (maybeNegativeAngle < 0) {
return Math.PI * 2 + maybeNegativeAngle
} else {
return maybeNegativeAngle
}
}
export function forceNotNaN(n: number, errorMessage?: string): number {
if (isNaN(n)) {
throw new Error(errorMessage == null ? 'Is NaN.' : errorMessage)
} else {
return n
}
}
export function nanToZero(n: number): number {
if (isNaN(n)) {
return 0
} else {
return n
}
}
export function safeParseInt(s: string): number {
const n = Number.parseInt(s)
return forceNotNaN(n, `Unable to parse ${s}.`)
}
export function clampValue(value: number, minimum: number, maximum: number): number {
return Math.max(Math.min(value, maximum), minimum)
}
export function parseNumber(value: string): Either<string, number> {
const n = parseFloat(value)
return isNaN(n) ? left(`${value} is not a number`) : right(n)
}
export interface NumberOrPercent {
value: number
isPercent: boolean
}
export function numberOrPercent(value: number, isPercent: boolean): NumberOrPercent {
return {
value: value,
isPercent: isPercent,
}
}
export function parseNumberOrPercent(value: unknown): Either<string, NumberOrPercent> {
switch (typeof value) {
case 'number':
return right(numberOrPercent(value, false))
case 'string':
const split = value.split('%')
const isPercent = split.length !== 1
const parsedNumber = parseNumber(split[0])
return mapEither((r) => {
return { value: r, isPercent: isPercent }
}, parsedNumber)
default:
return left(`Cannot parse as number or percent: ${value}`)
}
}
export function printNumberOrPercent(number: NumberOrPercent): number | string {
if (number.isPercent) {
return `${number.value}%`
} else {
return number.value
}
}
export function numberOrPercentToNumber(n: NumberOrPercent, outOf: number): number {
return n.isPercent ? (n.value * outOf) / 100 : n.value
}
export function clamp(min: number, max: number, value: number): number {
if (value < min) {
return min
} else if (value > max) {
return max
} else {
return value
}
} | the_stack |
import * as _ from 'underscore';
import { Injectable } from "@angular/core";
import { ObjectUtils } from '../../../lib/common/utils/object-utils';
import {TranslatePipe, TranslateService} from '@ngx-translate/core';
declare const d3: any;
@Injectable()
export class Nvd3ChartService {
constructor(
private translateService:TranslateService
) {
}
renderEndUpdated: any = {};
timeoutMap: any = {};
keys: any;
addToDataMap(dataMap: any, labelValueMapArr: any, x: any, value: any, label?: any) {
if (_.isUndefined(label)) {
_.each(labelValueMapArr, (lv: any) => {
if (dataMap[lv.label] == undefined) {
dataMap[lv.label] = {};
}
dataMap[lv.label][x] = value;
});
}
else {
if (dataMap[label] == undefined) {
dataMap[label] = {};
}
dataMap[label][x] = value;
}
}
expireRenderEnd(chart: any) {
delete this.renderEndUpdated[chart];
}
shouldManualUpdate(chart: any) {
if (this.renderEndUpdated[chart] == undefined) {
this.renderEndUpdated[chart] = chart;
if (this.timeoutMap[chart] != undefined) {
clearTimeout(this.timeoutMap[chart]);
}
this.timeoutMap[chart] = setTimeout(() => {
this.expireRenderEnd(chart);
}, 3000);
return true;
}
else {
return false;
}
}
FILL_STRATEGY_TYPE = {
MAX_DATA_POINTS: "MAX_DATA_POINTS",
INTERVAL: "INTERVAL"
}
/**
*
* @param type FILL_STRATEGY_TYPE
* @param value number
* @return {{type: *, value: *}}
*/
fillStrategy(type: any, value: any) {
return { type: type, value: value };
}
fillAllStrategy(minValue: any, maxValue: any, dataMap: any, labelValueMapArr: any,
incrementInterval: any, fillMiddle: any) {
var incrementIntervalVal = incrementInterval;
var diff = maxValue - minValue;
//less than 5 min space out every 5 sec
if (diff <= 300000) {
incrementIntervalVal = 5000;
}
else if (diff <= 3600000) {
// 1 hr diff, increment every 60 sec
incrementIntervalVal = 60000;
}
else if (diff <= 43200000) {
// 12 hr diff every 5 min
incrementIntervalVal = 60000 * 5;
}
else {
// every 20 minutes
incrementIntervalVal = 60000 * 20
}
/**
* The new map to be merged back into the dataMap
* @type {{}}
*/
var newDataMap = {};
/**
* Min value in the dataMap
*/
var minDataPoint = minValue;
/**
* Max Value in the dataMap
*/
var maxDataPoint = maxValue;
if (_.isEmpty(dataMap)) {
var tmpVal = minValue;
while (tmpVal <= maxValue) {
this.addToDataMap(newDataMap, labelValueMapArr, tmpVal, 0)
tmpVal += incrementIntervalVal;
}
}
else {
labelValueMapArr.forEach((lv: any) => {
var label = lv.label;
var labelCounts = dataMap[label] || {};
minDataPoint = minValue;
maxDataPoint = maxValue;
this.keys = Object.keys(labelCounts).map(Number);
//Find the min/Max values if they exist
if (!_.isEmpty(labelCounts)) {
minDataPoint = _.min(this.keys);
maxDataPoint = _.max(this.keys);
}
//Start processing with the minValue on the graph
var tmpVal = minValue;
//iterate and add data points before the minDataPoint value
while (tmpVal < minDataPoint) {
this.addToDataMap(newDataMap, labelValueMapArr, tmpVal, 0, label)
tmpVal += incrementIntervalVal;
}
//Reassign the tmpVal to be the starting dataPoint value
tmpVal = minDataPoint;
if (!_.isEmpty(labelCounts)) {
//fill in the body
//if its empty fill with 0's
if (fillMiddle) {
//attempt to fill in increments with 0
//start with the
var startingTmpVal = tmpVal;
tmpVal = startingTmpVal;
//sort by key
var orderedMap = {};
this.keys.sort().forEach((key: any) => {
orderedMap[key] = labelCounts[key];
});
_.each(orderedMap, (val: any, key: any) => {
var numericKey = parseInt(key);
var diff = numericKey - tmpVal;
if (diff > incrementIntervalVal) {
tmpVal = numericKey;
var len = Math.floor(diff / incrementIntervalVal);
for (var i = 0; i < len; i++) {
tmpVal += incrementIntervalVal;
this.addToDataMap(newDataMap, labelValueMapArr, tmpVal, 0, label)
}
}
});
}
//now start with the max value in the data set
tmpVal = maxDataPoint;
tmpVal += incrementIntervalVal;
}
// add in ending datapoints
while (tmpVal < maxValue) {
this.addToDataMap(newDataMap, labelValueMapArr, tmpVal, 0, label)
tmpVal += incrementIntervalVal;
}
});
}
//merge into the dataMap
Object.keys(newDataMap).forEach((newDataMapKey) => {
if (dataMap[newDataMapKey] == undefined) {
dataMap[newDataMapKey] = newDataMap[newDataMapKey];
}
else {
_.extend(dataMap[newDataMapKey], newDataMap[newDataMapKey])
}
});
}
/**
* toLineChartData(response,[{label:'status',value:'count',valueFn:'optional fn to get the value',color:'optional'}],'date',IconService.colorForJobStatus);
*
* @param response
* @param labelValueMapArr
* @param xAxisKey
* @param colorForSeriesFn
* @param minTime
* @param maxTime
* @param maxDataPoints - max data points requested for the graph
* @returns {Array}
*/
toLineChartData(response: any, labelValueMapArr: any, xAxisKey: any,
colorForSeriesFn: any, minValue?: any, maxValue?: any) {
// var this = this;
var dataMap = {}
var data: any[] = [];
var dateMap = {};
var responseData = response;
var labelColorMap = {};
var labelDisabledMap = {};
var configMap = {};
if (responseData) {
Object.keys(responseData).forEach((key) => {
_.each(labelValueMapArr, (labelValue: any) => {
var label = responseData[key][labelValue.label];
if (label == undefined) {
label = labelValue.label; //label = Completed,Started
}
if (dataMap[label] == undefined) {
dataMap[label] = {};
}
dateMap[responseData[key][xAxisKey]] = responseData[key][xAxisKey]; //dateMap[item[maxEventTime]] = maxEventTime
var value;
// console.log("labelValeu.valueFn = ", labelValue.valueFn);
if (labelValue.valueFn != undefined) {
value = labelValue.valueFn(responseData[key]);
}
else {
value = responseData[key][labelValue.value]; //item[jobsStartedPerSecond]
}
var prevVal = dataMap[label][responseData[key][xAxisKey]];
if (!_.isUndefined(prevVal)) {
value += prevVal;
}
dataMap[label][responseData[key][xAxisKey]] = value; //dataMap[Started][maxEventTime] = jobsStartedPerSecond
if (labelValue['color'] != undefined) {
labelColorMap[label] = labelValue.color;
}
if (labelValue['disabled'] != undefined) {
labelDisabledMap[label] = labelValue.disabled;
}
configMap[label] = labelValue;
});
});
if (!_.isUndefined(minValue) && !_.isUndefined(maxValue)) {
//Fill in gaps, before, after, and optionally in the middle of the data
this.fillAllStrategy(minValue, maxValue, dataMap, labelValueMapArr, 5000, false)
}
Object.keys(dataMap).forEach((key: any) => {
var valuesArray: any[] = [];
var orderedMap: any = {};
Object.keys(dataMap[key]).sort().forEach((dmapKey: any) => {
orderedMap[key] = dataMap[key][dmapKey];
valuesArray.push([parseInt(dmapKey), dataMap[key][dmapKey]]);
});
var color = colorForSeriesFn != undefined ? colorForSeriesFn(key) : labelColorMap[key];
var disabled = labelDisabledMap[key] != undefined ? labelDisabledMap[key] : false;
var area = (configMap[key] != undefined && configMap[key]['area'] != undefined) ? configMap[key]['area'] : true;
var displayLabel = this.translateService ? this.translateService.instant(key) : key;
data.push({ key: displayLabel, values: valuesArray, area: area, color: color, disabled: disabled });
})
}
return data;
}
determineMaxY(nvd3Dataset: any) {
var max = 0;
var max2 = 0;
if (nvd3Dataset && nvd3Dataset[0]) {
max = d3.max(nvd3Dataset[0].values, (d: any) => {
return d[1];
});
}
if (nvd3Dataset && nvd3Dataset[1]) {
max2 = d3.max(nvd3Dataset[1].values, (d: any) => {
return d[1];
});
}
max = max2 > max ? max2 : max;
if (max == undefined || max == 0) {
max = 5;
}
else {
max *= 1.2;
}
max = Math.round(max);
return max
}
} | the_stack |
import * as moment from "moment";
/**
* The key value pair object properties.
*/
export interface KeyValuePair {
/**
* The key parameter.
*/
key?: string;
/**
* The value parameter.
*/
value?: string;
}
/**
* Tag details.
*/
export interface Tag {
/**
* The key parameter.
*/
key?: string;
/**
* The value parameter.
*/
value?: string;
}
/**
* Video frame property details.
*/
export interface Frame {
/**
* Timestamp of the frame.
*/
timestamp?: string;
/**
* Frame image.
*/
frameImage?: string;
/**
* Array of KeyValue.
*/
metadata?: KeyValuePair[];
/**
* Reviewer result tags.
*/
reviewerResultTags?: Tag[];
}
/**
* The response for a Get Frames request.
*/
export interface Frames {
/**
* Id of the review.
*/
reviewId?: string;
videoFrames?: Frame[];
}
/**
* The category1 score details of the text. <a href="https://aka.ms/textClassifyCategories">Click
* here</a> for more details on category classification.
*/
export interface ClassificationCategory1 {
/**
* The category1 score.
*/
score?: number;
}
/**
* The category2 score details of the text. <a href="https://aka.ms/textClassifyCategories">Click
* here</a> for more details on category classification.
*/
export interface ClassificationCategory2 {
/**
* The category2 score.
*/
score?: number;
}
/**
* The category3 score details of the text. <a href="https://aka.ms/textClassifyCategories">Click
* here</a> for more details on category classification.
*/
export interface ClassificationCategory3 {
/**
* The category3 score.
*/
score?: number;
}
/**
* The classification details of the text.
*/
export interface Classification {
/**
* The category1 score details of the text. <a href="https://aka.ms/textClassifyCategories">Click
* here</a> for more details on category classification.
*/
category1?: ClassificationCategory1;
/**
* The category2 score details of the text. <a href="https://aka.ms/textClassifyCategories">Click
* here</a> for more details on category classification.
*/
category2?: ClassificationCategory2;
/**
* The category3 score details of the text. <a href="https://aka.ms/textClassifyCategories">Click
* here</a> for more details on category classification.
*/
category3?: ClassificationCategory3;
/**
* The review recommended flag.
*/
reviewRecommended?: boolean;
}
/**
* Status properties.
*/
export interface Status {
/**
* Status code.
*/
code?: number;
/**
* Status description.
*/
description?: string;
/**
* Exception status.
*/
exception?: string;
}
/**
* Email Address details.
*/
export interface Email {
/**
* Detected Email Address from the input text content.
*/
detected?: string;
/**
* Subtype of the detected Email Address.
*/
subType?: string;
/**
* Email Address in the input text content.
*/
text?: string;
/**
* Index(Location) of the Email address in the input text content.
*/
index?: number;
}
/**
* Detected SSN details.
*/
export interface SSN {
/**
* Detected SSN in the input text content.
*/
text?: string;
/**
* Index(Location) of the SSN in the input text content.
*/
index?: number;
}
/**
* IP Address details.
*/
export interface IPA {
/**
* Subtype of the detected IP Address.
*/
subType?: string;
/**
* Detected IP Address.
*/
text?: string;
/**
* Index(Location) of the IP Address in the input text content.
*/
index?: number;
}
/**
* Phone Property details.
*/
export interface Phone {
/**
* CountryCode of the detected Phone number.
*/
countryCode?: string;
/**
* Detected Phone number.
*/
text?: string;
/**
* Index(Location) of the Phone number in the input text content.
*/
index?: number;
}
/**
* Address details.
*/
export interface Address {
/**
* Detected Address.
*/
text?: string;
/**
* Index(Location) of the Address in the input text content.
*/
index?: number;
}
/**
* Personal Identifier Information details.
*/
export interface PII {
email?: Email[];
sSN?: SSN[];
iPA?: IPA[];
phone?: Phone[];
address?: Address[];
}
/**
* Detected Terms details.
*/
export interface DetectedTerms {
/**
* Index(Location) of the detected profanity term in the input text content.
*/
index?: number;
/**
* Original Index(Location) of the detected profanity term in the input text content.
*/
originalIndex?: number;
/**
* Matched Terms list Id.
*/
listId?: number;
/**
* Detected profanity term.
*/
term?: string;
}
/**
* The response for a Screen text request.
*/
export interface Screen {
/**
* The original text.
*/
originalText?: string;
/**
* The normalized text.
*/
normalizedText?: string;
/**
* The autocorrected text
*/
autoCorrectedText?: string;
/**
* The misrepresentation text.
*/
misrepresentation?: string[];
/**
* The classification details of the text.
*/
classification?: Classification;
/**
* The evaluate status.
*/
status?: Status;
/**
* Personal Identifier Information details.
*/
pII?: PII;
/**
* Language of the input text content.
*/
language?: string;
terms?: DetectedTerms[];
/**
* Unique Content Moderator transaction Id.
*/
trackingId?: string;
}
/**
* Coordinates to the found face.
*/
export interface Face {
/**
* The bottom coordinate.
*/
bottom?: number;
/**
* The left coordinate.
*/
left?: number;
/**
* The right coordinate.
*/
right?: number;
/**
* The top coordinate.
*/
top?: number;
}
/**
* Request object the contains found faces.
*/
export interface FoundFaces {
/**
* The evaluate status
*/
status?: Status;
/**
* The tracking id.
*/
trackingId?: string;
/**
* The cache id.
*/
cacheId?: string;
/**
* True if result was found.
*/
result?: boolean;
/**
* Number of faces found.
*/
count?: number;
/**
* The advanced info.
*/
advancedInfo?: KeyValuePair[];
/**
* The list of faces.
*/
faces?: Face[];
}
/**
* OCR candidate text.
*/
export interface Candidate {
/**
* The text found.
*/
text?: string;
/**
* The confidence level.
*/
confidence?: number;
}
/**
* Contains the text found in image for the language specified.
*/
export interface OCR {
/**
* The evaluate status
*/
status?: Status;
/**
* Array of KeyValue.
*/
metadata?: KeyValuePair[];
/**
* The tracking id.
*/
trackingId?: string;
/**
* The cache id.
*/
cacheId?: string;
/**
* The ISO 639-3 code.
*/
language?: string;
/**
* The found text.
*/
text?: string;
/**
* The list of candidate text.
*/
candidates?: Candidate[];
}
/**
* Evaluate response object.
*/
export interface Evaluate {
/**
* The cache id.
*/
cacheID?: string;
/**
* Evaluate result.
*/
result?: boolean;
/**
* The tracking id.
*/
trackingId?: string;
/**
* The adult classification score.
*/
adultClassificationScore?: number;
/**
* Indicates if an image is classified as adult.
*/
isImageAdultClassified?: boolean;
/**
* The racy classification score.
*/
racyClassificationScore?: number;
/**
* Indicates if the image is classified as racy.
*/
isImageRacyClassified?: boolean;
/**
* The advanced info.
*/
advancedInfo?: KeyValuePair[];
/**
* The evaluate status
*/
status?: Status;
}
/**
* The match details.
*/
export interface Match {
/**
* Confidence score of the image match.
*/
score?: number;
/**
* The match id.
*/
matchId?: number;
/**
* The source.
*/
source?: string;
/**
* The tags for match details.
*/
tags?: number[];
/**
* The label.
*/
label?: string;
}
/**
* The response for a Match request.
*/
export interface MatchResponse {
/**
* The tracking id.
*/
trackingId?: string;
/**
* The cache id.
*/
cacheID?: string;
/**
* Indicates if there is a match.
*/
isMatch?: boolean;
/**
* The match details.
*/
matches?: Match[];
/**
* The evaluate status
*/
status?: Status;
}
/**
* Detect language result.
*/
export interface DetectedLanguage {
/**
* The detected language.
*/
detectedLanguage?: string;
/**
* The detect language status
*/
status?: Status;
/**
* The tracking id.
*/
trackingId?: string;
}
/**
* Image List Properties.
*/
export interface ImageList {
/**
* Image List Id.
*/
id?: number;
/**
* Image List Name.
*/
name?: string;
/**
* Description for image list.
*/
description?: string;
/**
* Image List Metadata.
*/
metadata?: { [propertyName: string]: string };
}
/**
* Term List Properties.
*/
export interface TermList {
/**
* Term list Id.
*/
id?: number;
/**
* Term list name.
*/
name?: string;
/**
* Description for term list.
*/
description?: string;
/**
* Term list metadata.
*/
metadata?: { [propertyName: string]: string };
}
/**
* Refresh Index Response.
*/
export interface RefreshIndex {
/**
* Content source Id.
*/
contentSourceId?: string;
/**
* Update success status.
*/
isUpdateSuccess?: boolean;
/**
* Advanced info list.
*/
advancedInfo?: { [propertyName: string]: string }[];
/**
* Refresh index status.
*/
status?: Status;
/**
* Tracking Id.
*/
trackingId?: string;
}
export interface ImageAdditionalInfoItem {
/**
* Key parameter.
*/
key?: string;
/**
* Value parameter.
*/
value?: string;
}
/**
* Image Properties.
*/
export interface Image {
/**
* Content Id.
*/
contentId?: string;
/**
* Advanced info list.
*/
additionalInfo?: ImageAdditionalInfoItem[];
/**
* Status details.
*/
status?: Status;
/**
* Tracking Id.
*/
trackingId?: string;
}
/**
* Image Id properties.
*/
export interface ImageIds {
/**
* Source of the content.
*/
contentSource?: string;
/**
* Id of the contents.
*/
contentIds?: number[];
/**
* Get Image status.
*/
status?: Status;
/**
* Tracking Id.
*/
trackingId?: string;
}
/**
* Terms in list Id passed.
*/
export interface TermsInList {
/**
* Added term details.
*/
term?: string;
}
/**
* All term Id response properties.
*/
export interface TermsData {
/**
* Language of the terms.
*/
language?: string;
/**
* List of terms.
*/
terms?: TermsInList[];
/**
* Term Status.
*/
status?: Status;
/**
* Tracking Id.
*/
trackingId?: string;
}
/**
* Paging details.
*/
export interface TermsPaging {
/**
* Total details.
*/
total?: number;
/**
* Limit details.
*/
limit?: number;
/**
* Offset details.
*/
offset?: number;
/**
* Returned text details.
*/
returned?: number;
}
/**
* Terms properties.
*/
export interface Terms {
/**
* Term data details.
*/
data?: TermsData;
/**
* Paging details.
*/
paging?: TermsPaging;
}
/**
* The Review object.
*/
export interface Review {
/**
* Id of the review.
*/
reviewId?: string;
/**
* Name of the subteam.
*/
subTeam?: string;
/**
* The status string (<Pending, Complete>).
*/
status?: string;
/**
* Array of KeyValue with Reviewer set Tags.
*/
reviewerResultTags?: KeyValuePair[];
/**
* The reviewer name.
*/
createdBy?: string;
/**
* Array of KeyValue.
*/
metadata?: KeyValuePair[];
/**
* The type of content.
*/
type?: string;
/**
* The content value.
*/
content?: string;
/**
* Id of the content.
*/
contentId?: string;
/**
* The callback endpoint.
*/
callbackEndpoint?: string;
}
/**
* Job Execution Report Values.
*/
export interface JobExecutionReportDetails {
/**
* Time details.
*/
ts?: string;
/**
* Message details.
*/
msg?: string;
}
/**
* The Job object.
*/
export interface Job {
/**
* The job id.
*/
id?: string;
/**
* The team name associated with the job.
*/
teamName?: string;
/**
* The status string (<Pending, Failed, Completed>).
*/
status?: string;
/**
* The Id of the workflow.
*/
workflowId?: string;
/**
* Type of the content.
*/
type?: string;
/**
* The callback endpoint.
*/
callBackEndpoint?: string;
/**
* Review Id if one is created.
*/
reviewId?: string;
/**
* Array of KeyValue pairs.
*/
resultMetaData?: KeyValuePair[];
/**
* Job execution report- Array of KeyValue pairs object.
*/
jobExecutionReport?: JobExecutionReportDetails[];
}
/**
* The list of job ids.
*/
export interface JobListResult {
/**
* The job id.
*/
value?: string[];
}
export interface JobId {
/**
* Id of the created job.
*/
jobId?: string;
}
/**
* Error body.
*/
export interface ErrorModel {
code?: string;
message?: string;
}
/**
* Error information returned by the API
*/
export interface APIError {
error?: ErrorModel;
}
export interface Body {
/**
* Name of the list.
*/
name?: string;
/**
* Description of the list.
*/
description?: string;
/**
* Metadata of the list.
*/
metadata?: { [propertyName: string]: string };
}
export interface CreateReviewBodyItemMetadataItem {
/**
* Your key parameter.
*/
key: string;
/**
* Your value parameter.
*/
value: string;
}
/**
* Schema items of the body.
*/
export interface CreateReviewBodyItem {
/**
* Type of the content. Possible values include: 'Image', 'Text'
*/
type: string;
/**
* Content to review.
*/
content: string;
/**
* Content Identifier.
*/
contentId: string;
/**
* Optional CallbackEndpoint.
*/
callbackEndpoint?: string;
/**
* Optional metadata details.
*/
metadata?: CreateReviewBodyItemMetadataItem[];
}
export interface Content {
/**
* Content to evaluate for a job.
*/
contentValue: string;
}
export interface TranscriptModerationBodyItemTermsItem {
/**
* Index of the word
*/
index: number;
/**
* Detected word.
*/
term: string;
}
/**
* Schema items of the body.
*/
export interface TranscriptModerationBodyItem {
/**
* Timestamp of the image.
*/
timestamp: string;
/**
* Optional metadata details.
*/
terms: TranscriptModerationBodyItemTermsItem[];
}
export interface BodyModel {
dataRepresentation?: string;
value?: string;
}
export interface CreateVideoReviewsBodyItemVideoFramesItemReviewerResultTagsItem {
/**
* Your key parameter.
*/
key: string;
/**
* Your value parameter.
*/
value: string;
}
export interface CreateVideoReviewsBodyItemVideoFramesItemMetadataItem {
/**
* Your key parameter.
*/
key: string;
/**
* Your value parameter.
*/
value: string;
}
export interface CreateVideoReviewsBodyItemVideoFramesItem {
/**
* Id of the frame.
*/
id: string;
/**
* Timestamp of the frame.
*/
timestamp: number;
/**
* Frame image Url.
*/
frameImage: string;
reviewerResultTags?: CreateVideoReviewsBodyItemVideoFramesItemReviewerResultTagsItem[];
/**
* Optional metadata details.
*/
metadata?: CreateVideoReviewsBodyItemVideoFramesItemMetadataItem[];
}
export interface CreateVideoReviewsBodyItemMetadataItem {
/**
* Your key parameter.
*/
key: string;
/**
* Your value parameter.
*/
value: string;
}
/**
* Schema items of the body.
*/
export interface CreateVideoReviewsBodyItem {
/**
* Optional metadata details.
*/
videoFrames?: CreateVideoReviewsBodyItemVideoFramesItem[];
/**
* Optional metadata details.
*/
metadata?: CreateVideoReviewsBodyItemMetadataItem[];
/**
* Video content url to review.
*/
content: string;
/**
* Content Identifier.
*/
contentId: string;
/**
* Status of the video(Complete,Unpublished,Pending). Possible values include: 'Complete',
* 'Unpublished', 'Pending'
*/
status: string;
/**
* Timescale of the video.
*/
timescale?: number;
/**
* Optional CallbackEndpoint.
*/
callbackEndpoint?: string;
}
export interface VideoFrameBodyItemReviewerResultTagsItem {
/**
* Your key parameter.
*/
key: string;
/**
* Your value parameter.
*/
value: string;
}
export interface VideoFrameBodyItemMetadataItem {
/**
* Your key parameter.
*/
key: string;
/**
* Your value parameter.
*/
value: string;
}
/**
* Schema items of the body.
*/
export interface VideoFrameBodyItem {
/**
* Timestamp of the frame.
*/
timestamp: string;
/**
* Content to review.
*/
frameImage: string;
reviewerResultTags?: VideoFrameBodyItemReviewerResultTagsItem[];
/**
* Optional metadata details.
*/
metadata?: VideoFrameBodyItemMetadataItem[];
} | the_stack |
import { CdkVirtualScrollViewport } from '@angular/cdk/scrolling';
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ElementRef,
EventEmitter,
Input,
OnChanges,
OnDestroy,
OnInit,
Output,
SimpleChanges,
TemplateRef,
ViewChild
} from '@angular/core';
import { I18nInterface, I18nService } from 'ng-devui/i18n';
import { fadeInOut } from 'ng-devui/utils';
import { Subscription } from 'rxjs';
import { ToggleMenuListItem } from './toggle-menu.type';
@Component({
selector: 'd-toggle-menu-list',
templateUrl: './toggle-menu-list.component.html',
styleUrls: [`./toggle-menu-list.component.scss`],
animations: [fadeInOut],
changeDetection: ChangeDetectionStrategy.OnPush,
preserveWhitespaces: false,
})
export class ToggleMenuListComponent implements OnInit, OnChanges, OnDestroy {
/**
* 【必选】下拉选项资源,支持Array<string>, Array<{key: value}>
*/
@Input() options: Array<ToggleMenuListItem> = [];
/**
* 【当传入资源(options)类型为Array<{key: value},必选】针对传入资源options的每项对应字段做禁用操作的key
*/
@Input() optionDisabledKey = '';
/**
* 【当传入资源(options)类型为Array<{key: value},必选】针对传入资源options的每项对应字段禁止变更的key
*/
@Input() optionImmutableKey = '';
/**
* 【当传入资源(options)类型为Array<{key: value},可选】如使用分组需设置
*/
@Input() optionGroupKey = '';
/**
* 【可选】下拉选框尺寸
*/
@Input() size: '' | 'sm' | 'lg';
@Input() keyword: string;
/**
* 【可选】是否在搜索过滤状态中
*/
@Input() isFiltering = false;
/**
* 【可选】启用数据懒加载,默认不启用
*/
@Input() enableLazyLoad = false;
/**
* 【可选】是否虚拟滚动
*/
@Input() virtualScroll = false;
/**
* 【必选】下拉列表单项模板
*/
@Input() listItemTemplate: TemplateRef<any>;
/**
* 【可选】自定义 loading 模板
*/
@Input() loadingTemplateRef: TemplateRef<any>;
/**
* 【可选】配置无数据展示
*/
@Input() noResultItemTemplate: TemplateRef<any>;
/**
* 【可选】支持自定义区域显示内容
*/
@Input() customViewTemplate: TemplateRef<any>;
/**
* customViewTemplate的方向,支持下方和右方
*/
@Input() customViewDirection: 'top' | 'bottom' | 'right' | 'left' = 'bottom';
/**
* 【可选】模板高度
*/
@Input() templateItemSize: number; // 模板itemSize,appendToBody为true
/**
* 【可选】下拉菜单高度,建议使用px作为高度单位
*/
@Input() set scrollHeight(value) {
this._scrollHeight = `${parseInt(value, 10)}px`;
}
get scrollHeight() {
return this._scrollHeight;
}
@Input() selectIndex = -1;
/**
* 【可选】是否允许单选状态下无选中值时高亮某项
*/
@Input() hasSelectIndex: boolean;
/**
* 【可选】是否支持多选
*/
@Input() multiple: boolean;
@Input() multiItems = [];
@Input() value: ToggleMenuListItem | Array<ToggleMenuListItem>;
/**
* 【可选】是否支持全选
*/
@Input() isSelectAll = false;
/**
* 【可选】配置多选的时候是否维持原数组排序还是用户选择的顺序排序,默认是用户顺序
*/
@Input() keepMultipleOrder: 'origin' | 'user-select' = 'user-select';
@Input() eventHandle: any;
@Input() closeScope: 'all' | 'blank' | 'none' = 'all';
/**
* select下拉toggle事件,值为true或false
*/
@Output() toggleChange = new EventEmitter<any>();
@Output() valueChange = new EventEmitter<any>();
@Output() loadMore = new EventEmitter<any>();
@ViewChild('dropdownUl') dropdownUl: ElementRef;
@ViewChild(CdkVirtualScrollViewport) virtualScrollViewport: CdkVirtualScrollViewport;
get realVirtualScrollItemSize() {
const itemSize = this.templateItemSize || this.virtualScrollItemSize[this.size || 'normal'];
const num = Math.round(this.scrollHeightNum / itemSize) || 10;
this.minBuffer = num * 1.5 * itemSize;
this.maxBuffer = num * 2.5 * itemSize;
return itemSize;
}
_scrollHeight = '300px';
i18nCommonText: I18nInterface['common'];
i18nSubscription: Subscription;
availableOptions = [];
activeIndex = -1;
allChecked = false;
halfChecked = false;
showLoading = false;
scrollHeightNum: number;
minBuffer: number;
maxBuffer: number;
virtualScrollViewportSizeMightChange = false;
virtualScrollItemSize: any = {
sm: 34,
normal: 38,
lg: 50,
};
constructor(private changeDetectorRef: ChangeDetectorRef, private i18n: I18nService) {}
ngOnInit() {
this.setI18nText();
}
ngOnChanges(changes: SimpleChanges): void {
if (changes.options) {
this.availableOptions = this.options;
this.setAvailableOptions();
// 显示数据变更,需要判断全选半选状态
if (this.isSelectAll) {
const selectedItemForFilterOptions = [];
this.multiItems.forEach((item) => {
this.availableOptions.forEach((option) => {
if (item['id'] === option['id']) {
selectedItemForFilterOptions.push(item);
}
});
});
this.setChecked(selectedItemForFilterOptions);
}
if (
!this.hasSelectIndex &&
!this.multiple &&
(!this.value || (this.availableOptions && !this.availableOptions.find((option) => option.option === this.value)))
) {
this.selectIndex = this.isFiltering && this.availableOptions && this.availableOptions.length > 0 ? 0 : -1;
}
if (this.virtualScroll && this.virtualScrollViewport) {
this.virtualScrollViewportSizeMightChange = true;
this.virtualScrollViewport.checkViewportSize();
}
this.changeDetectorRef.markForCheck();
}
if (changes.value) {
this.setAvailableOptions();
}
if (changes.eventHandle && changes.eventHandle.currentValue) {
const evt = changes['eventHandle'].currentValue;
const { event, type } = evt;
switch (type) {
case 'keydown.esc':
this.onEscKeyup(event);
break;
case 'keydown.ArrowUp':
this.handleKeyUpEvent(event);
break;
case 'keydown.ArrowDown':
this.handleKeyDownEvent(event);
break;
case 'keydown.enter':
this.handleKeyEnterEvent(event);
break;
}
}
}
ngOnDestroy(): void {
if (this.i18nSubscription) {
this.i18nSubscription.unsubscribe();
}
}
setI18nText() {
this.i18nCommonText = this.i18n.getI18nText().common;
this.i18nSubscription = this.i18n.langChange().subscribe((data) => {
this.i18nCommonText = data.common;
});
}
setAvailableOptions() {
if (!Array.isArray(this.availableOptions)) {
return;
}
const _value = this.value ? (this.multiple ? this.value : [this.value]) : [];
this.availableOptions = this.availableOptions.map((item, index) =>
item.id >= 0 && item.option
? {
isChecked: _value.findIndex((i) => JSON.stringify(i) === JSON.stringify(item.option)) > -1,
id: item.id,
option: item.option,
}
: { isChecked: _value.findIndex((i) => JSON.stringify(i) === JSON.stringify(item)) > -1, id: index, option: item }
);
}
setChecked(selectedItem) {
if (!selectedItem) {
return;
}
if (!this.isSelectAll) {
return;
}
this.halfChecked = false;
if (selectedItem.length === this.availableOptions.length) {
this.allChecked = true;
} else if (selectedItem.length === 0) {
this.allChecked = false;
} else {
this.halfChecked = true;
}
}
selectAll() {
const mutableOption = this.optionImmutableKey
? this.availableOptions.filter((item) => !item.option[this.optionImmutableKey])
: this.availableOptions;
const selectedImmutableOption = this.optionImmutableKey ? this.multiItems.filter((item) => item.option[this.optionImmutableKey]) : [];
if (mutableOption && mutableOption.length > this.multiItems.length - selectedImmutableOption.length) {
mutableOption.forEach((item) => {
const indexOfOption = this.multiItems.findIndex((i) => JSON.stringify(i.option) === JSON.stringify(item.option));
if (indexOfOption === -1) {
this.multiItems.push({ id: item.id, option: item.option });
}
});
} else {
this.multiItems = [...selectedImmutableOption];
}
this.value = this.multiItems.map((item) => item.option);
this.valueChange.emit({ value: this.value, multiItems: this.multiItems });
this.setChecked(this.value);
}
trackByFn(index, item) {
return index;
}
onEscKeyup(event?: Event) {
if (event) {
event.stopPropagation();
}
this.toggleChange.emit(false);
}
handleKeyUpEvent(event?: Event) {
if (event) {
event.preventDefault();
event.stopPropagation();
}
this.selectIndex = this.selectIndex === 0 || this.selectIndex === -1 ? this.availableOptions.length - 1 : this.selectIndex - 1;
this.scrollToActive();
}
handleKeyDownEvent(event?: Event) {
if (event) {
event.preventDefault();
event.stopPropagation();
}
this.selectIndex = this.selectIndex === this.availableOptions.length - 1 ? 0 : this.selectIndex + 1;
this.scrollToActive();
}
handleKeyEnterEvent(event?: Event) {
if (event) {
event.preventDefault();
event.stopPropagation();
}
const item = this.availableOptions[this.selectIndex];
if (item) {
this.choose({ option: item.option, index: item.id, event: null });
} else if (this.closeScope === 'all') {
this.toggleChange.emit(false);
}
}
scrollToActive(): void {
const that = this;
setTimeout(() => {
try {
const selectIndex = that.selectIndex + (that.isSelectAll ? 1 : 0); // 多了个全选会导致问题,index需要加1
const scrollPane: any = that.dropdownUl.nativeElement.children[selectIndex];
if (scrollPane.scrollIntoViewIfNeeded) {
scrollPane.scrollIntoViewIfNeeded(false);
} else {
const containerInfo = that.dropdownUl.nativeElement.getBoundingClientRect();
const elementInfo = scrollPane.getBoundingClientRect();
if (elementInfo.bottom > containerInfo.bottom || elementInfo.top < containerInfo.top) {
scrollPane.scrollIntoView(false);
}
}
} catch (e) {}
});
}
resetIndex(resetSelectIndex = true) {
this.selectIndex = resetSelectIndex ? -1 : 0;
this.activeIndex = -1;
this.changeDetectorRef.markForCheck();
}
choose = ({ option, index, event }) => {
if (event) {
event.preventDefault();
event.stopPropagation();
}
if (typeof option === 'object' && Object.keys(option).length === 0) {
this.toggleChange.emit(false);
return;
}
if (this.optionDisabledKey && option[this.optionDisabledKey]) {
return;
}
if (this.optionImmutableKey && option[this.optionImmutableKey]) {
return;
}
if (this.optionGroupKey && option[this.optionGroupKey]) {
return;
}
if (this.multiple) {
const indexOfOption = this.multiItems.findIndex((item) => JSON.stringify(item.option) === JSON.stringify(option));
if (indexOfOption === -1) {
this.multiItems.push({ id: index, option });
} else {
this.multiItems.splice(indexOfOption, 1);
}
if (this.keepMultipleOrder === 'origin') {
this.multiItems.sort((a, b) => a.id - b.id);
}
this.value = this.multiItems.map((item) => item.option);
} else {
this.value = option;
this.activeIndex = index;
this.selectIndex = index;
if (this.closeScope === 'all') {
this.toggleChange.emit(false);
}
if (this.virtualScrollViewportSizeMightChange) {
// 解决虚拟滚动更新options长度展开前无法获取正确高度影响
setTimeout(() => {
if (this.virtualScrollViewportSizeMightChange && this.virtualScrollViewport) {
this.virtualScrollViewportSizeMightChange = false;
this.virtualScrollViewport.checkViewportSize();
}
}, 0);
}
}
this.valueChange.emit({ value: this.value, multiItems: this.multiItems, option, event, index });
this.setAvailableOptions();
this.setChecked(this.value);
};
showSelectAll() {
return this.isSelectAll && this.multiple && this.availableOptions.length > 0;
}
getVirtualScrollHeight(len, size) {
if (len > 0) {
let height = this.templateItemSize ? this.templateItemSize * len : this.virtualScrollItemSize[size ? size : 'normal'] * len;
if (this.isSelectAll && this.multiple) {
height += this.virtualScrollItemSize[size ? size : 'normal'];
}
const scrollHeight = parseInt(this.scrollHeight, 10);
this.scrollHeightNum = height > scrollHeight ? scrollHeight : height;
return `${this.scrollHeightNum}px`;
}
}
loadMoreEvent(event) {
this.showLoading = true;
this.loadMore.emit({ instance: this, event });
}
loadStart() {
this.showLoading = true;
this.changeDetectorRef.detectChanges();
}
loadFinish() {
this.showLoading = false;
this.changeDetectorRef.detectChanges();
}
} | the_stack |
import { getDB } from "../../../db/getDB"
import { MongoDB } from "../../../db/mongo"
import { GitHubInstallation } from "../../../db"
import logger from "../../../logger"
import {
getRecordedWebhook,
setInstallationToRecord,
wipeAllRecordedWebhooks,
} from "../../../plugins/utils/recordWebhookWithRequest"
import { sendWebhookThroughGitHubRunner } from "../../../plugins/utils/sendWebhookThroughGitHubRunner"
import { getDetailsFromPerilSandboxAPIJWT } from "../../../runner/sandbox/jwt"
import { runTaskForInstallation, triggerAFutureDangerRun } from "../../../tasks/startTaskScheduler"
import { GraphQLContext, MSGDangerfileFinished, sendMessageToConnectionsWithAccessToInstallation } from "../../api"
import { getDetailsFromPerilJWT } from "../../auth/generate"
import { createLambdaFunctionForInstallation } from "../../aws/lambda"
import { authD } from "../utils/auth"
import { getUserInstallations } from "../utils/installations"
const confirmAccessToJWT = async (iID: number, jwt: string) => {
if (!iID) {
throw new Error(`No installation ID given`)
}
if (!jwt) {
throw new Error(`No JWT given`)
}
const decodedJWT = await getDetailsFromPerilJWT(jwt)
const installationID = String(iID)
// Check the installation's ID is included inside the signed JWT, to verify access
if (!decodedJWT.iss.includes(installationID)) {
throw new Error(`You don't have access to this installation`)
}
}
type PartialInstallation = Partial<GitHubInstallation> & { iID: number }
// const dangerOrgStagingInstallationID = 135226
export const mutations = {
convertPartialInstallation: authD(async (_: any, params: any, context: GraphQLContext) => {
const opts = params as PartialInstallation
await confirmAccessToJWT(opts.iID, context.jwt)
const decodedJWT = await getDetailsFromPerilJWT(context.jwt)
if (decodedJWT.data.user.name !== "orta") {
return { error: { description: `Sorry folks, only Orta can create a new installation.` } }
}
logger.info(`mutation: convertPartialInstallation ${opts.iID}`)
// Save the changes, then trigger an update from the new repo
const db = getDB() as MongoDB
const updatedInstallation = await db.saveInstallation(opts)
try {
// Try run the mongo updater, if this fails then it will raise
await db.updateInstallation(updatedInstallation.iID)
// OK, that worked, let's set it up
const lambda = await createLambdaFunctionForInstallation(updatedInstallation.login)
// Set the lambda function for the server
await db.saveInstallation({ iID: updatedInstallation.iID, lambdaName: lambda.name })
return updatedInstallation
} catch (error) {
// This is basically the difference between `convertPartialInstallation` and `editInstallation`
//
// Reset the perilSettingsJSONURL so that the next one starts from scratch.
await db.saveInstallation({ perilSettingsJSONURL: undefined })
return {
error: { description: error.message },
}
}
}),
editInstallation: authD(async (_: any, params: any, context: GraphQLContext) => {
const opts = params as PartialInstallation
await confirmAccessToJWT(opts.iID, context.jwt)
logger.info(`mutation: editInstallation ${opts.iID}`)
// Save the changes, then trigger an update from the new repo
const db = getDB() as MongoDB
const updatedInstallation = await db.saveInstallation(opts)
try {
await db.updateInstallation(updatedInstallation.iID)
return updatedInstallation
} catch (error) {
return {
error: { description: error.message },
}
}
}),
makeInstallationRecord: authD(async (_: any, params: any, context: GraphQLContext) => {
await confirmAccessToJWT(params.iID, context.jwt)
logger.info(`mutation: makeInstallationRecord ${params.iID}`)
await wipeAllRecordedWebhooks(params.iID)
await setInstallationToRecord(params.iID)
// Return the modified installation
const installations = await getUserInstallations(context.jwt)
return installations.find(i => i.iID === params.iID)
}),
sendWebhookForInstallation: authD(async (_: any, params: any, context: GraphQLContext) => {
await confirmAccessToJWT(params.iID, context.jwt)
logger.info(`mutation: sendWebhookForInstallation ${params.iiD} webhook ${params.eventID}`)
const webhook = await getRecordedWebhook(params.iID, params.eventID)
if (!webhook) {
return null
}
await sendWebhookThroughGitHubRunner(webhook)
return webhook
}),
changeEnvVarForInstallation: authD(async (_: any, params: any, context: GraphQLContext) => {
const opts = params as { iID: number; key: string; value: string | undefined }
await confirmAccessToJWT(opts.iID, context.jwt)
const db = getDB() as MongoDB
const installation = await db.getInstallation(opts.iID)
if (!installation) {
throw new Error(`Installation not found`)
}
logger.info(`mutation: changeEnvVarForInstallation ${opts.iID} edited ${opts.key}`)
// Make it if it doesn't exist
const envVars = installation.envVars || {}
// Delete it when passing null
if (!opts.value) {
delete envVars[opts.key]
} else {
// Add/overwrite when there's a value
envVars[opts.key] = opts.value
}
// Just update the env vars
await db.saveInstallation({ iID: opts.iID, envVars })
return envVars
}),
runTask: authD(async (_: any, params: any, context: GraphQLContext) => {
const opts = params as { iID: number; task: string; data: any }
await confirmAccessToJWT(opts.iID, context.jwt)
const db = getDB() as MongoDB
const installation = await db.getInstallation(opts.iID)
if (!installation) {
throw new Error(`Installation not found`)
}
if (!installation.tasks[opts.task]) {
throw new Error(`Task not found on installation`)
}
logger.info(`mutation: runTask ${opts.iID} task ${opts.task}`)
await runTaskForInstallation(installation, opts.task, opts.data || {})
return { success: true }
}),
scheduleTask: async (_: any, params: any, __: GraphQLContext) => {
const opts = params as { task: string; time: string; data: string; jwt: string }
const decodedJWT = await getDetailsFromPerilSandboxAPIJWT(opts.jwt)
const db = getDB() as MongoDB
const installation = await db.getInstallation(parseInt(decodedJWT.iss[0]!, 10))
if (!installation) {
throw new Error(`Installation not found from JWT`)
}
if (!installation.tasks[opts.task]) {
throw new Error(`Task not found on installation, found ${Object.keys(installation.tasks)}`)
}
// see createPerilSandboxAPIJWT
if (!decodedJWT.data.actions || !decodedJWT.data.actions.includes("scheduleTask")) {
throw new Error(`This JWT does not have the credentials to schedule a task`)
}
logger.info(`mutation: scheduleTask ${installation.iID} task ${opts.task} ${opts.time}`)
// We need to attach an installation so we can look it up on the
// running aspect.
const schedulerConfig = {
data: JSON.parse(opts.data),
installationID: installation.iID,
taskName: opts.task,
}
triggerAFutureDangerRun(opts.time, schedulerConfig)
return { success: true }
},
createNewRepo: async (_: any, __: any, ___: GraphQLContext) => {
// # Triggers a message to admins in the dashboard, and prepares to grab the logs
// createNewRepo(iID: Int!, repoName: String!): MutationWithRepo
},
requestNewRepo: async (_: any, __: any, ___: GraphQLContext) => {
// # request a PR with Peril settings
// requestNewRepo(iID: Int!, repoName: String!, useTypeScript: Boolean!, setupTests: Boolean!, isPublic: Boolean!): MutationWithRepo
},
dangerfileFinished: async (_: any, params: any, __: GraphQLContext) => {
const opts = params as {
dangerfiles: string[]
time: number
jwt: string
hyperCallID: string | undefined
name: string
}
const decodedJWT = await getDetailsFromPerilSandboxAPIJWT(opts.jwt)
const db = getDB() as MongoDB
const installation = await db.getInstallation(parseInt(decodedJWT.iss[0]!, 10))
if (!installation) {
throw new Error(`Installation not found from JWT`)
}
if (!decodedJWT.data.actions || !decodedJWT.data.actions.includes("dangerfileFinished")) {
throw new Error(`JWT did not have access to run dangerfileFinished`)
}
const message: MSGDangerfileFinished = {
event: opts.name,
filenames: opts.dangerfiles,
time: opts.time,
action: "finished",
}
sendMessageToConnectionsWithAccessToInstallation(installation.iID, message)
// TODO: Store the time in some kind of per-installation analytics document?
// TODO: Bring back live logs?
// // Calls can come from outside hyper now
// const hyperCallID = opts.hyperCallID
// if (hyperCallID) {
// // Wait 2 seconds for the container to finish
// setTimeout(async () => {
// let dangerfileLog: MSGDangerfileLog | undefined
// // Get Hyper logs
// const getLogs = async () => {
// let logs = null
// try {
// logs = "" // await getHyperLogs(hyperCallID)
// } catch (error) {
// logger.error(`Requesting the hyper logs for ${installation.iID} with callID ${hyperCallID} - ${error}`)
// return
// }
// const logMessage: MSGDangerfileLog = {
// event: opts.name,
// action: "log",
// filenames: opts.dangerfiles,
// log: logs as string,
// }
// return logMessage
// }
// // If you have a connected slack webhook, then always grab the logs
// // and store the value somewhere where the websocket to admin connections
// // can also read.
// if (installation.installationSlackUpdateWebhookURL) {
// dangerfileLog = await getLogs()
// sendLogsToSlackForInstallation("Received logs", dangerfileLog!, installation)
// }
// // Callback inside is lazy loaded and only called if there are people
// // in the dashboard
// sendAsyncMessageToConnectionsWithAccessToInstallation(installation.iID, async spark => {
// // If the slack trigger above didn't grab the logs, then re-grab them.
// if (!dangerfileLog) {
// dangerfileLog = await getLogs()
// }
// spark.write(dangerfileLog)
// })
// }, 2000)
// }
return { success: true }
},
} | the_stack |
import { Book, Note, ReturnBody_Note } from "@aidenlx/obsidian-bridge";
import {
excerptPic,
excerptPic_video,
linkComment_pic,
} from "@alx-plugins/marginnote";
import assertNever from "assert-never";
import replaceAsync from "string-replace-async";
import AddNewVideo from "../handlers/add-new-video";
import { AddForEachProp, getBookFromMap, NonTypeProps, toPage } from "../misc";
import MNComp from "../mn-main";
import Comment from "./basic/comment";
import Excerpt from "./basic/excerpt";
import Link from "./basic/link";
import Query from "./basic/query";
import Template, { getViewKeys, PHValMap } from "./template";
type Partials = Record<"Comments" | "CmtBreak", string>;
/**
* for comments, use {{> Comments}}; for excerpt, use {{> Excerpt}}; for title with heading level, use {{Title.1}}
*/
type BodyRec = PHValMap<
"Created" | "Modified" | "FilePath" | "DocTitle" | "DocMd5"
> &
AddForEachProp<{
Excerpt: Excerpt;
Comments: CommentRec[];
RawTitle: string;
Title: string;
Aliases: string;
Link: Link;
Query: Query;
}>;
type CommentRec =
| Comment
| { Excerpt: Excerpt | undefined; Link: Link | undefined };
export const NoteViewKeys = {
partial: getViewKeys<keyof Partials>({
CmtBreak: null,
Comments: null,
}),
body: getViewKeys<Exclude<keyof BodyRec, "Comments">>({
Created: null,
Modified: null,
FilePath: null,
DocTitle: null,
DocMd5: null,
RawTitle: null,
Title: null,
Aliases: null,
Link: null,
Excerpt: null,
Query: null,
}),
cmt_linked: getViewKeys<keyof Exclude<CommentRec, Comment>>({
Excerpt: null,
Link: null,
}),
comment: getViewKeys<keyof NonTypeProps<Comment, Function | boolean>>({
Process: null,
Text: null,
Media: null,
SrcLink: null,
Link: null,
}),
};
const isVideo = (
pic: excerptPic | excerptPic_video | undefined,
): pic is excerptPic_video => !!(pic as excerptPic_video)?.video;
const isPic = (
pic: excerptPic | excerptPic_video | undefined,
): pic is excerptPic => !!pic && !(pic as excerptPic_video).video;
type timeSpan = [start: string | undefined, end: string | undefined];
export default class NoteTemplate extends Template<"note"> {
constructor(plugin: MNComp) {
super(plugin, "note");
}
private getExcerpt(
excerpt: {
textBak?: string | undefined;
picBak?: excerptPic | excerptPic_video | undefined;
note: Note | undefined;
},
mediaMap: Record<string, string>,
): Excerpt {
const { textBak, picBak } = excerpt,
{
startPos,
endPos,
textFirst,
excerptPic: pic,
excerptText: text,
} = excerpt.note ?? {};
return new Excerpt(
textFirst ?? false,
this.getText(text ?? textBak),
this.getExcerptMediaPH(pic ?? picBak, mediaMap, [startPos, endPos]),
);
}
private getComments(body: ReturnBody_Note): CommentRec[] | undefined {
const { mediaMap, linkedNotes } = body,
{ comments } = body.data;
if (!comments || !Array.isArray(comments) || comments.length === 0)
return undefined;
return comments.map<CommentRec>((c) => {
switch (c.type) {
case "TextNote": // LinkedNote (mnUrl in c.text) or comment
return c.text?.startsWith("marginnote3app")
? new Comment(Link.getInst(c.text), c.noteid)
: new Comment(this.getText(c.text), c.noteid);
case "HtmlNote": // if with noteid: from merged note
return new Comment(this.getText(c.html, true), c.noteid);
case "PaintNote": {
let placeholder = undefined;
if (c.paint) placeholder = getPlaceholder("pic", c.paint);
else if (c.strokes) placeholder = "%% Some handwrittings %%";
return new Comment(placeholder, c.noteid);
}
case "LinkNote":
// Merged Note
if (!linkedNotes[c.noteid]) {
console.error(
"Cannot find merged note %s in %o while fetching timeSpan for video",
c.noteid,
linkedNotes,
body,
);
}
return {
Excerpt: this.getExcerpt(
{
note: linkedNotes[c.noteid],
picBak: (c as linkComment_pic).q_hpic,
textBak: c.q_htext,
},
mediaMap,
),
Link: Link.getInst({ id: c.noteid }),
};
default:
assertNever(c);
}
});
}
private getBody(
note: Note,
bookMap: Record<string, Book>,
mediaMap: Record<string, string>,
refCallback?: (refSource: string) => any,
): Omit<BodyRec, "Comments"> {
const Page = toPage(note),
{ noteTitle, createDate, modifiedDate, docMd5: DocMd5, noteId } = note,
{ docTitle: DocTitle, pathFile: FilePath } = getBookFromMap(
DocMd5,
bookMap,
);
return {
RawTitle: noteTitle,
...getTitleAliasesProps(noteTitle),
Created: this.formatDate(createDate),
Modified: this.formatDate(modifiedDate),
Link: Link.getInst({ id: noteId }, undefined, refCallback),
FilePath,
DocTitle,
DocMd5,
Excerpt: this.getExcerpt({ note }, mediaMap),
Query: new Query({ Page, DocMd5, DocTitle, FilePath }),
};
}
prerender(
body: ReturnBody_Note,
tplName: string,
refCallback?: (refSource: string) => any,
): string {
const templates = this.getTemplate(tplName);
const { bookMap, mediaMap } = body;
let refSource = "";
refCallback = refCallback ?? ((ref: string) => (refSource = ref));
const view: BodyRec = {
...this.getBody(body.data, bookMap, mediaMap, refCallback),
Comments: this.getComments(body),
},
parital: Partials = {
Comments:
"{{#Comments}}" +
`{{#isRegular}}${templates.comment}{{/isRegular}}` +
`{{^isRegular}}${templates.cmt_linked}{{/isRegular}}` +
"{{/Comments}}",
CmtBreak: "{{#Comments.length}}\n\n\n{{/Comments.length}}",
};
let rendered: string;
try {
rendered = this.renderTemplate(templates.body, view, parital);
} catch (error) {
throw this.RenderError(error, tplName);
}
if (refSource) {
rendered += Link.getToInsertLast(rendered, refSource);
}
return rendered;
}
/**
* @param refCallback if not given, insert refSource to bottom of rendered text
*/
render(...args: Parameters<NoteTemplate["prerender"]>): Promise<string> {
let prerender = this.prerender(...args);
try {
return this.importAttachments(prerender, args[0]);
} catch (error) {
throw this.RenderError(error, args[1]);
}
}
/** get placeholder for media in excerpt */
getExcerptMediaPH(
excerptPic: excerptPic | excerptPic_video | undefined,
mediaMap: Record<string, string>,
timeSpan?: timeSpan,
): string | undefined {
if (!excerptPic) return undefined;
else if (isPic(excerptPic) && mediaMap[excerptPic.paint]) {
return getPlaceholder("pic", excerptPic.paint);
} else if (isVideo(excerptPic)) {
const { video: videoMd5, paint: SnapshotMd5 } = excerptPic,
getHash = () => {
if (!timeSpan || timeSpan.every((t) => !t)) return "";
const [start, end] = timeSpan.map(videoPosToSec);
return `#t=${start}${end ? "," + end : ""}`;
};
return getPlaceholder("video", videoMd5, getHash(), SnapshotMd5);
} else return undefined;
}
async importAttachments(
rendered: string,
body: ReturnBody_Note,
): Promise<string> {
const { mediaMap, bookMap } = body,
getPicLink = async (
id: string,
data: string,
subpath?: string,
alias?: string,
) => {
const file = await this.saveAttachment(data, id, "png");
if (!file) return undefined;
return this.getFileLink(file, true, subpath, alias);
};
return replaceAsync(rendered, PHRegex, async (_match, type, paramStr) => {
let data: string;
if (typeof type === "string" && typeof paramStr === "string") {
const params = paramStr.split("|");
if (type === "pic" && params.length === 1) {
const [picMd5] = params;
if ((data = mediaMap[picMd5]))
return (await getPicLink(picMd5, data)) ?? _match;
} else if (type === "video" && params.length === 3) {
const [videoMd5, hash, SnapshotMd5] = params,
srcName =
getBookFromMap(videoMd5, bookMap).docTitle ?? "Unknown Video",
target = await new AddNewVideo(
this.plugin,
srcName,
videoMd5,
).getLink();
if (target) {
if (typeof target === "string")
return ``;
else {
return this.getFileLink(target, true, hash);
}
} else if ((data = mediaMap[SnapshotMd5])) {
// fallback to snapshot
return (await getPicLink(SnapshotMd5, data, hash)) ?? _match;
}
}
}
console.error("unexpected match, skipping...", _match, type, paramStr);
return _match;
});
}
}
const PHRegex = /<!--(pic|video):(.+?)-->/g;
const getPlaceholder = (
...args:
| [type: "pic", md5: string]
| [type: "video", videoMd5: string, hash: string, SnapshotMd5: string]
) => {
const [type, ...data] = args;
return `<!--${type}:${data.join("|")}-->`;
};
export const getTitleAliases = (
raw: string,
): [title: string, aliases: string[]] => {
const [title, ...aliases] = raw.split(/[;;]/);
return [title, aliases];
};
const getTitleAliasesProps = (
raw: string | undefined,
): Pick<BodyRec, "Title" | "Aliases"> => {
if (raw) {
const [title, aliases] = getTitleAliases(raw);
return {
Title: title,
Aliases: aliases.length === 0 ? undefined : `[${aliases.join(", ")}]`,
};
} else
return {
Title: undefined,
Aliases: undefined,
};
};
const getAttName = (id: string | undefined): string => {
const date = "YYYYMMDDHHmmss";
return id ?? "MarginNote " + window.moment().format(date);
};
const videoPosToSec = (pos: string | undefined): number | undefined => {
if (!pos || typeof pos !== "string") return undefined;
const [mark, totalStr, propStr, ...others] = pos.split("|"),
total = +totalStr,
prop = +propStr;
if (
mark === "MN3VIDEO" &&
others.length === 0 &&
Number.isFinite(total) &&
Number.isFinite(prop) &&
total > 0 &&
prop >= 0 &&
prop <= 1
)
return total * prop;
else {
console.error("invalid MNVIDEO time: ", pos);
return undefined;
}
}; | the_stack |
import { pick } from "@core/lib/utils/object";
import { apiAction } from "../handler";
import { Api, Rbac } from "@core/types";
import * as R from "ramda";
import {
graphTypes,
getOrphanedLocalKeyIdsForUser,
getGroupMembershipsByObjectId,
getActiveRecoveryKeysByUserId,
getOrgPermissions,
getCurrentEncryptedKeys,
getLocalKeysByUserId,
deleteGraphObjects,
getAppAllowedIps,
authz,
} from "@core/lib/graph";
import { getOrgGraph } from "../graph";
import {
getDeleteEncryptedKeysTransactionItems,
getDeleteUsersWithTransactionItems,
} from "../blob";
import { getDb } from "../db";
import { scimCandidateDbKey } from "../models/provisioning";
import { getOrg } from "../models/orgs";
import produce, { Draft } from "immer";
import { isValidIPOrCIDR, ipMatchesAny } from "@core/lib/utils/ip";
import { log } from "@core/lib/utils/logger";
apiAction<
Api.Action.RequestActions["UpdateOrgSettings"],
Api.Net.ApiResultTypes["UpdateOrgSettings"]
>({
type: Api.ActionType.UPDATE_ORG_SETTINGS,
graphAction: true,
authenticated: true,
graphScopes: [(auth) => () => [auth.user.skey + "$"]],
graphAuthorizer: async (action, orgGraph, userGraph, auth) =>
authz.canUpdateOrgSettings(userGraph, auth.user.id),
graphHandler: async ({ payload }, orgGraph, auth, now) => {
const settings = payload;
return {
type: "graphHandlerResult",
graph: {
...orgGraph,
[auth.org.id]: { ...auth.org, settings, updatedAt: now },
},
logTargetIds: [],
};
},
});
apiAction<
Api.Action.RequestActions["RenameOrg"],
Api.Net.ApiResultTypes["RenameOrg"]
>({
type: Api.ActionType.RENAME_ORG,
graphAction: true,
authenticated: true,
graphScopes: [(auth) => () => [auth.user.skey + "$"]],
graphAuthorizer: async (action, orgGraph, userGraph, auth) =>
authz.canRenameOrg(userGraph, auth.user.id),
graphHandler: async ({ payload }, orgGraph, auth, now) => {
return {
type: "graphHandlerResult",
graph: {
...orgGraph,
[auth.org.id]: {
...auth.org,
name: payload.name,
updatedAt: now,
},
},
logTargetIds: [],
};
},
});
apiAction<
Api.Action.RequestActions["RenameUser"],
Api.Net.ApiResultTypes["RenameUser"]
>({
type: Api.ActionType.RENAME_USER,
graphAction: true,
authenticated: true,
graphAuthorizer: async ({ payload: { id } }, orgGraph, userGraph, auth) =>
authz.canRenameUser(userGraph, auth.user.id, id),
graphHandler: async (
{ payload: { id, firstName, lastName } },
orgGraph,
auth,
now
) => {
return {
type: "graphHandlerResult",
graph: {
...orgGraph,
[id]: { ...orgGraph[id], firstName, lastName, updatedAt: now },
},
logTargetIds: [id],
};
},
});
apiAction<
Api.Action.RequestActions["UpdateUserRole"],
Api.Net.ApiResultTypes["UpdateUserRole"]
>({
type: Api.ActionType.UPDATE_USER_ROLE,
graphAction: true,
authenticated: true,
shouldClearOrphanedLocals: true,
graphAuthorizer: async (
{ payload: { id, orgRoleId } },
orgGraph,
userGraph,
auth
) => authz.canUpdateUserRole(userGraph, auth.user.id, id, orgRoleId),
graphHandler: async ({ payload }, orgGraph, auth, now) => {
const target = orgGraph[payload.id] as Api.Db.OrgUser | Api.Db.CliUser,
userId = target.id,
oldOrgRole = orgGraph[target.orgRoleId] as Api.Db.OrgRole,
newOrgRole = orgGraph[payload.orgRoleId] as Api.Db.OrgRole,
byType = graphTypes(orgGraph),
settingAutoAppRole =
!oldOrgRole.autoAppRoleId && newOrgRole.autoAppRoleId;
let updatedGraph = {
...orgGraph,
[target.id]: {
...target,
orgRoleId: payload.orgRoleId,
orgRoleUpdatedAt: now,
updatedAt: now,
},
},
toDeleteIds: string[] = [];
if (settingAutoAppRole) {
const appUserGrants = byType.appUserGrants.filter(
R.propEq("userId", userId)
),
groupMemberships =
getGroupMembershipsByObjectId(orgGraph)[userId] ?? [],
appGroupUsers = byType.appGroupUsers.filter(R.propEq("userId", userId));
toDeleteIds = [
...appUserGrants.map(R.prop("id")),
...groupMemberships.map(R.prop("id")),
...appGroupUsers.map(R.prop("id")),
];
}
const orphanedLocalKeyIds = getOrphanedLocalKeyIdsForUser(
updatedGraph,
auth.user.id
),
orphanedLocalKeyIdsSet = new Set(orphanedLocalKeyIds),
generatedEnvkeys = byType.generatedEnvkeys.filter(({ keyableParentId }) =>
orphanedLocalKeyIdsSet.has(keyableParentId)
),
generatedEnvkeyIds = generatedEnvkeys.map(R.prop("id"));
toDeleteIds = [
...toDeleteIds,
...orphanedLocalKeyIds,
...generatedEnvkeyIds,
];
if (
getOrgPermissions(orgGraph, oldOrgRole.id).has(
"org_generate_recovery_key"
) &&
!getOrgPermissions(orgGraph, newOrgRole.id).has(
"org_generate_recovery_key"
)
) {
const recoveryKey = getActiveRecoveryKeysByUserId(orgGraph)[userId];
if (recoveryKey) {
toDeleteIds.push(recoveryKey.id);
}
}
if (toDeleteIds.length > 0) {
updatedGraph = deleteGraphObjects(updatedGraph, toDeleteIds, now);
}
const scope: Rbac.OrgAccessScope = {
userIds: new Set([userId]),
envParentIds: "all",
keyableParentIds: "all",
};
return {
type: "graphHandlerResult",
graph: updatedGraph,
encryptedKeysScope: scope,
logTargetIds: [userId],
clearEnvkeySockets: generatedEnvkeyIds.map((generatedEnvkeyId) => ({
orgId: auth.org.id,
generatedEnvkeyId,
})),
};
},
});
apiAction<
Api.Action.RequestActions["RemoveFromOrg"],
Api.Net.ApiResultTypes["RemoveFromOrg"]
>({
type: Api.ActionType.REMOVE_FROM_ORG,
graphAction: true,
authenticated: true,
shouldClearOrphanedLocals: true,
graphAuthorizer: async ({ payload: { id } }, orgGraph, userGraph, auth) =>
authz.canRemoveFromOrg(userGraph, auth.user.id, id),
graphHandler: async (
{ payload },
orgGraph,
auth,
now,
requestParams,
transactionConn
) => {
const target = orgGraph[payload.id] as Api.Db.OrgUser,
userId = target.id,
candidate = target.scim
? await getDb<Api.Db.ScimUserCandidate>(
scimCandidateDbKey({
orgId: auth.org.id,
providerId: target.scim.providerId,
userCandidateId: target.scim.candidateId,
}),
{ transactionConn }
)
: undefined;
const byType = graphTypes(orgGraph);
const localKeys = getLocalKeysByUserId(orgGraph)[userId] ?? [];
const localKeyIds = localKeys.map(R.prop("id"));
const localKeyIdsSet = new Set(localKeyIds);
const generatedEnvkeys = byType.generatedEnvkeys.filter(
({ keyableParentId }) => localKeyIdsSet.has(keyableParentId)
);
const { transactionItems, updatedGraph } =
getDeleteUsersWithTransactionItems(
auth,
orgGraph,
orgGraph,
[userId],
now
);
return {
type: "graphHandlerResult",
graph: updatedGraph,
transactionItems: {
...transactionItems,
puts: candidate
? [
{
...candidate,
orgUserId: undefined,
} as Api.Db.ScimUserCandidate,
]
: undefined,
},
logTargetIds: [userId],
clearUserSockets: [{ orgId: auth.org.id, userId: payload.id }],
clearEnvkeySockets: generatedEnvkeys.map((generatedEnvkeyId) => ({
orgId: auth.org.id,
generatedEnvkeyId,
})),
};
},
});
apiAction<
Api.Action.RequestActions["SetOrgAllowedIps"],
Api.Net.ApiResultTypes["SetOrgAllowedIps"]
>({
type: Api.ActionType.SET_ORG_ALLOWED_IPS,
graphAction: true,
authenticated: true,
graphAuthorizer: async (action, orgGraph, userGraph, auth) =>
authz.hasOrgPermission(orgGraph, auth.user.id, "org_manage_firewall"),
graphHandler: async (
{ payload },
orgGraph,
auth,
now,
requestParams,
transactionConn
) => {
if (!payload.environmentRoleIpsAllowed) {
throw new Api.ApiError("missing environmentRoleIpsAllowed", 422);
}
if (payload.localIpsAllowed) {
// verify that each is a valid ip
// also verify that current ip is allowed so current user
// can't be locked out
if (!R.all(isValidIPOrCIDR, payload.localIpsAllowed)) {
const msg = "Invalid IP or CIDR address";
throw new Api.ApiError(msg, 422);
}
if (!ipMatchesAny(requestParams.ip, payload.localIpsAllowed)) {
const msg = "Current user IP not allowed by localIpsAllowed";
throw new Api.ApiError(msg, 422);
}
}
// verify that each set in environmentRoleIpsAllowed is a valid ip
for (let environmentRoleId in payload.environmentRoleIpsAllowed) {
const ips = payload.environmentRoleIpsAllowed[environmentRoleId];
if (ips) {
if (!R.all(isValidIPOrCIDR, ips)) {
const msg = "Invalid IP or CIDR address";
throw new Api.ApiError(msg, 422);
}
}
}
const updatedGraph = produce(orgGraph, (graphDraft) => {
const orgDraft = graphDraft[auth.org.id] as Draft<Api.Db.Org>;
orgDraft.localIpsAllowed = payload.localIpsAllowed;
orgDraft.environmentRoleIpsAllowed = payload.environmentRoleIpsAllowed;
orgDraft.updatedAt = now;
for (let { id, environmentId, appId } of graphTypes(orgGraph)
.generatedEnvkeys) {
const environment = orgGraph[environmentId] as Api.Db.Environment;
const generatedEnvkeyDraft = graphDraft[
id
] as Draft<Api.Db.GeneratedEnvkey>;
generatedEnvkeyDraft.allowedIps = getAppAllowedIps(
graphDraft,
appId,
environment.environmentRoleId
);
generatedEnvkeyDraft.updatedAt = now;
}
});
return {
type: "graphHandlerResult",
graph: updatedGraph,
logTargetIds: [],
};
},
});
apiAction<
Api.Action.RequestActions["DeleteOrg"],
Api.Net.ApiResultTypes["DeleteOrg"]
>({
type: Api.ActionType.DELETE_ORG,
graphAction: false,
authenticated: true,
broadcastOrgSocket: true,
authorizer: async (action, auth) => {
return auth.orgPermissions.has("org_delete");
},
handler: async (action, auth, now, requestParams, transactionConn) => {
// obtain lock on org
await getOrg(auth.org.id, transactionConn, true);
const orgGraph = await getOrgGraph(auth.org.id, {
transactionConn,
}),
keySet = getCurrentEncryptedKeys(orgGraph, "all", now, true),
{ hardDeleteKeys, hardDeleteEncryptedKeyParams } =
await getDeleteEncryptedKeysTransactionItems(auth, orgGraph, keySet);
return {
type: "handlerResult",
response: {
type: "success",
},
transactionItems: {
hardDeleteKeys,
softDeleteKeys: Object.values(orgGraph).map(pick(["pkey", "skey"])),
hardDeleteEncryptedKeyParams,
hardDeleteEncryptedBlobParams: [{ orgId: auth.org.id }],
},
logTargetIds: [],
clearUserSockets: [{ orgId: auth.org.id }],
clearEnvkeySockets: [{ orgId: auth.org.id }],
};
},
}); | the_stack |
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import globalAxios, { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios';
import { Configuration } from '../../../configuration';
// Some imports not used depending on template conditions
// @ts-ignore
import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from '../../../common';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError } from '../../../base';
// @ts-ignore
import { User } from '../../../model/some/levels/deep';
/**
* UserApi - axios parameter creator
* @export
*/
export const UserApiAxiosParamCreator = function (configuration?: Configuration) {
return {
/**
* This can only be done by the logged in user.
* @summary Create user
* @param {User} body Created user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createUser: async (body: User, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'body' is not null or undefined
assertParamExists('createUser', 'body', body)
const localVarPath = `/user`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(body, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Creates list of users with given input array
* @param {Array<User>} body List of user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createUsersWithArrayInput: async (body: Array<User>, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'body' is not null or undefined
assertParamExists('createUsersWithArrayInput', 'body', body)
const localVarPath = `/user/createWithArray`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(body, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Creates list of users with given input array
* @param {Array<User>} body List of user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createUsersWithListInput: async (body: Array<User>, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'body' is not null or undefined
assertParamExists('createUsersWithListInput', 'body', body)
const localVarPath = `/user/createWithList`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(body, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* This can only be done by the logged in user.
* @summary Delete user
* @param {string} username The name that needs to be deleted
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteUser: async (username: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'username' is not null or undefined
assertParamExists('deleteUser', 'username', username)
const localVarPath = `/user/{username}`
.replace(`{${"username"}}`, encodeURIComponent(String(username)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'DELETE', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Get user by user name
* @param {string} username The name that needs to be fetched. Use user1 for testing.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getUserByName: async (username: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'username' is not null or undefined
assertParamExists('getUserByName', 'username', username)
const localVarPath = `/user/{username}`
.replace(`{${"username"}}`, encodeURIComponent(String(username)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Logs user into the system
* @param {string} username The user name for login
* @param {string} password The password for login in clear text
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
loginUser: async (username: string, password: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'username' is not null or undefined
assertParamExists('loginUser', 'username', username)
// verify required parameter 'password' is not null or undefined
assertParamExists('loginUser', 'password', password)
const localVarPath = `/user/login`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
if (username !== undefined) {
localVarQueryParameter['username'] = username;
}
if (password !== undefined) {
localVarQueryParameter['password'] = password;
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Logs out current logged in user session
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
logoutUser: async (options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/user/logout`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* This can only be done by the logged in user.
* @summary Updated user
* @param {string} username name that need to be deleted
* @param {User} body Updated user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updateUser: async (username: string, body: User, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'username' is not null or undefined
assertParamExists('updateUser', 'username', username)
// verify required parameter 'body' is not null or undefined
assertParamExists('updateUser', 'body', body)
const localVarPath = `/user/{username}`
.replace(`{${"username"}}`, encodeURIComponent(String(username)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'PUT', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(body, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* UserApi - functional programming interface
* @export
*/
export const UserApiFp = function(configuration?: Configuration) {
const localVarAxiosParamCreator = UserApiAxiosParamCreator(configuration)
return {
/**
* This can only be done by the logged in user.
* @summary Create user
* @param {User} body Created user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async createUser(body: User, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.createUser(body, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Creates list of users with given input array
* @param {Array<User>} body List of user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async createUsersWithArrayInput(body: Array<User>, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.createUsersWithArrayInput(body, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Creates list of users with given input array
* @param {Array<User>} body List of user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async createUsersWithListInput(body: Array<User>, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.createUsersWithListInput(body, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
* This can only be done by the logged in user.
* @summary Delete user
* @param {string} username The name that needs to be deleted
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async deleteUser(username: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.deleteUser(username, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Get user by user name
* @param {string} username The name that needs to be fetched. Use user1 for testing.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async getUserByName(username: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<User>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.getUserByName(username, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Logs user into the system
* @param {string} username The user name for login
* @param {string} password The password for login in clear text
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async loginUser(username: string, password: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<string>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.loginUser(username, password, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Logs out current logged in user session
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async logoutUser(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.logoutUser(options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
* This can only be done by the logged in user.
* @summary Updated user
* @param {string} username name that need to be deleted
* @param {User} body Updated user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async updateUser(username: string, body: User, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.updateUser(username, body, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
}
};
/**
* UserApi - factory interface
* @export
*/
export const UserApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) {
const localVarFp = UserApiFp(configuration)
return {
/**
* This can only be done by the logged in user.
* @summary Create user
* @param {User} body Created user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createUser(body: User, options?: any): AxiosPromise<void> {
return localVarFp.createUser(body, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Creates list of users with given input array
* @param {Array<User>} body List of user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createUsersWithArrayInput(body: Array<User>, options?: any): AxiosPromise<void> {
return localVarFp.createUsersWithArrayInput(body, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Creates list of users with given input array
* @param {Array<User>} body List of user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createUsersWithListInput(body: Array<User>, options?: any): AxiosPromise<void> {
return localVarFp.createUsersWithListInput(body, options).then((request) => request(axios, basePath));
},
/**
* This can only be done by the logged in user.
* @summary Delete user
* @param {string} username The name that needs to be deleted
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteUser(username: string, options?: any): AxiosPromise<void> {
return localVarFp.deleteUser(username, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Get user by user name
* @param {string} username The name that needs to be fetched. Use user1 for testing.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getUserByName(username: string, options?: any): AxiosPromise<User> {
return localVarFp.getUserByName(username, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Logs user into the system
* @param {string} username The user name for login
* @param {string} password The password for login in clear text
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
loginUser(username: string, password: string, options?: any): AxiosPromise<string> {
return localVarFp.loginUser(username, password, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Logs out current logged in user session
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
logoutUser(options?: any): AxiosPromise<void> {
return localVarFp.logoutUser(options).then((request) => request(axios, basePath));
},
/**
* This can only be done by the logged in user.
* @summary Updated user
* @param {string} username name that need to be deleted
* @param {User} body Updated user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updateUser(username: string, body: User, options?: any): AxiosPromise<void> {
return localVarFp.updateUser(username, body, options).then((request) => request(axios, basePath));
},
};
};
/**
* UserApi - object-oriented interface
* @export
* @class UserApi
* @extends {BaseAPI}
*/
export class UserApi extends BaseAPI {
/**
* This can only be done by the logged in user.
* @summary Create user
* @param {User} body Created user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApi
*/
public createUser(body: User, options?: AxiosRequestConfig) {
return UserApiFp(this.configuration).createUser(body, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Creates list of users with given input array
* @param {Array<User>} body List of user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApi
*/
public createUsersWithArrayInput(body: Array<User>, options?: AxiosRequestConfig) {
return UserApiFp(this.configuration).createUsersWithArrayInput(body, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Creates list of users with given input array
* @param {Array<User>} body List of user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApi
*/
public createUsersWithListInput(body: Array<User>, options?: AxiosRequestConfig) {
return UserApiFp(this.configuration).createUsersWithListInput(body, options).then((request) => request(this.axios, this.basePath));
}
/**
* This can only be done by the logged in user.
* @summary Delete user
* @param {string} username The name that needs to be deleted
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApi
*/
public deleteUser(username: string, options?: AxiosRequestConfig) {
return UserApiFp(this.configuration).deleteUser(username, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Get user by user name
* @param {string} username The name that needs to be fetched. Use user1 for testing.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApi
*/
public getUserByName(username: string, options?: AxiosRequestConfig) {
return UserApiFp(this.configuration).getUserByName(username, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Logs user into the system
* @param {string} username The user name for login
* @param {string} password The password for login in clear text
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApi
*/
public loginUser(username: string, password: string, options?: AxiosRequestConfig) {
return UserApiFp(this.configuration).loginUser(username, password, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Logs out current logged in user session
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApi
*/
public logoutUser(options?: AxiosRequestConfig) {
return UserApiFp(this.configuration).logoutUser(options).then((request) => request(this.axios, this.basePath));
}
/**
* This can only be done by the logged in user.
* @summary Updated user
* @param {string} username name that need to be deleted
* @param {User} body Updated user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApi
*/
public updateUser(username: string, body: User, options?: AxiosRequestConfig) {
return UserApiFp(this.configuration).updateUser(username, body, options).then((request) => request(this.axios, this.basePath));
}
} | the_stack |
import * as R from 'ramda'
import * as React from 'react'
import { RouteComponentProps } from 'react-router'
import { Link, Redirect } from 'react-router-dom'
import * as M from '@material-ui/core'
import * as Lab from '@material-ui/lab'
import Code from 'components/Code'
import Skeleton from 'components/Skeleton'
import * as Notifications from 'containers/Notifications'
// import * as urls from 'constants/urls' // TODO: uncomment on docs deploy
import AsyncResult from 'utils/AsyncResult'
import * as NamedRoutes from 'utils/NamedRoutes'
import * as Sentry from 'utils/Sentry'
// import StyledLink from 'utils/StyledLink' // TODO: uncomment on docs deploy
import QuerySelect from '../QuerySelect'
import * as requests from '../requests'
import QueryEditor from './QueryEditor'
import Results from './Results'
import History from './History'
import WorkgroupSelect from './WorkgroupSelect'
interface WorkgroupsEmptyProps {
error?: Error
}
function WorkgroupsEmpty({ error }: WorkgroupsEmptyProps) {
return (
<>
{error ? (
<Alert title={error.name} error={error} />
) : (
<Lab.Alert severity="info">
<Lab.AlertTitle>No workgroups configured</Lab.AlertTitle>
</Lab.Alert>
)}
{/* <M.Typography> // TODO: uncomment on docs deploy
Check{' '}
<StyledLink href={`${urls.docs}/catalog/queries#athena`}>
Athena Queries docs
</StyledLink>{' '}
on correct usage
</M.Typography> */}
</>
)
}
function SelectSkeleton() {
return (
<>
<Skeleton height={24} width={128} animate />
<Skeleton height={48} mt={1} animate />
</>
)
}
const useFormSkeletonStyles = M.makeStyles((t) => ({
button: {
height: t.spacing(4),
marginTop: t.spacing(2),
width: t.spacing(14),
},
canvas: {
flexGrow: 1,
height: t.spacing(27),
marginLeft: t.spacing(1),
},
editor: {
display: 'flex',
marginTop: t.spacing(1),
},
helper: {
height: t.spacing(2),
marginTop: t.spacing(1),
},
numbers: {
height: t.spacing(27),
width: t.spacing(5),
},
title: {
height: t.spacing(3),
width: t.spacing(16),
},
}))
function FormSkeleton() {
const classes = useFormSkeletonStyles()
return (
<>
<Skeleton className={classes.title} animate />
<div className={classes.editor}>
<Skeleton className={classes.numbers} animate />
<Skeleton className={classes.canvas} animate />
</div>
<Skeleton className={classes.helper} animate />
<Skeleton className={classes.button} animate />
</>
)
}
interface TableSkeletonProps {
size: number
}
function TableSkeleton({ size }: TableSkeletonProps) {
return (
<>
<Skeleton height={36} animate />
{R.range(0, size).map((key) => (
<Skeleton key={key} height={36} mt={1} animate />
))}
</>
)
}
interface AlertProps {
error: Error
title: string
}
function Alert({ error, title }: AlertProps) {
const sentry = Sentry.use()
React.useEffect(() => {
sentry('captureException', error)
}, [error, sentry])
return (
<Lab.Alert severity="error">
<Lab.AlertTitle>{title}</Lab.AlertTitle>
{error.message}
</Lab.Alert>
)
}
function makeAsyncDataErrorHandler(title: string) {
return (error: Error) => <Alert error={error} title={title} />
}
const useStyles = M.makeStyles((t) => ({
emptySelect: {
margin: t.spacing(5.5, 0, 0),
},
form: {
margin: t.spacing(0, 0, 4),
},
results: {
margin: t.spacing(4, 0, 0),
},
sectionHeader: {
margin: t.spacing(0, 0, 1),
},
select: {
flexBasis: '40%',
'& + &': {
flexBasis: '60%',
marginLeft: t.spacing(3),
marginBottom: t.spacing(-3), // counterpart for Select's optional description
},
},
selects: {
display: 'flex',
margin: t.spacing(3, 0),
},
}))
const useFormStyles = M.makeStyles((t) => ({
actions: {
margin: t.spacing(2, 0),
},
error: {
margin: t.spacing(1, 0, 0),
},
viewer: {
margin: t.spacing(3, 0, 0),
},
}))
interface FormProps {
disabled: boolean
error?: Error
onChange: (value: string) => void
onSubmit: (value: string) => () => void
value: string | null
}
function Form({ disabled, error, value, onChange, onSubmit }: FormProps) {
const classes = useFormStyles()
const handleSubmit = React.useMemo(() => onSubmit(value || ''), [onSubmit, value])
return (
<div>
<QueryEditor className={classes.viewer} onChange={onChange} query={value || ''} />
{error && (
<Lab.Alert className={classes.error} severity="error">
{error.message}
</Lab.Alert>
)}
<div className={classes.actions}>
<M.Button
variant="contained"
color="primary"
disabled={disabled}
onClick={handleSubmit}
>
Run query
</M.Button>
</div>
</div>
)
}
interface QueryRunnerRenderProps {
queryRunData: requests.AsyncData<requests.athena.QueryRunResponse>
}
interface QueryRunnerProps {
children: (props: QueryRunnerRenderProps) => React.ReactElement
queryBody: string
queryExecutionId: string | null
workgroup: string
}
function QueryRunner({
children,
queryBody,
queryExecutionId,
workgroup,
}: QueryRunnerProps) {
const queryRunData = requests.athena.useQueryRun(workgroup, queryBody)
const { push: notify } = Notifications.use()
React.useEffect(() => {
queryRunData.case({
_: () => null,
Ok: ({ id }) => {
if (id === queryExecutionId) notify('Query execution results remain unchanged')
return null
},
})
}, [notify, queryExecutionId, queryRunData])
return children({ queryRunData })
}
interface QueryResultsFetcherRenderProps {
handleQueryResultsLoadMore: (prev: requests.athena.QueryResultsResponse) => void
queryResultsData: requests.AsyncData<requests.athena.QueryResultsResponse>
}
interface QueryResultsFetcherProps {
children: (props: QueryResultsFetcherRenderProps) => React.ReactElement
queryExecutionId: string | null
}
function QueryResultsFetcher({ children, queryExecutionId }: QueryResultsFetcherProps) {
const [prev, usePrev] = React.useState<requests.athena.QueryResultsResponse | null>(
null,
)
const queryResultsData = requests.athena.useQueryResults(queryExecutionId, prev)
return children({ queryResultsData, handleQueryResultsLoadMore: usePrev })
}
interface QueriesFetcherRenderProps {
executionsData: requests.AsyncData<requests.athena.QueryExecutionsResponse>
handleExecutionsLoadMore: (prev: requests.athena.QueryExecutionsResponse) => void
handleQueriesLoadMore: (prev: requests.athena.QueriesResponse) => void
queriesData: requests.AsyncData<requests.athena.QueriesResponse>
}
interface QueriesFetcherProps {
children: (props: QueriesFetcherRenderProps) => React.ReactElement
workgroup: string
}
function QueriesFetcher({ children, workgroup }: QueriesFetcherProps) {
const [prevQueries, setPrevQueries] =
React.useState<requests.athena.QueriesResponse | null>(null)
const [prevExecutions, setPrevExecutions] =
React.useState<requests.athena.QueryExecutionsResponse | null>(null)
const queriesData = requests.athena.useQueries(workgroup, prevQueries)
const executionsData = requests.athena.useQueryExecutions(workgroup, prevExecutions)
return children({
executionsData,
handleExecutionsLoadMore: setPrevExecutions,
handleQueriesLoadMore: setPrevQueries,
queriesData,
})
}
interface WorkgroupsFetcherRenderProps {
workgroupsData: requests.AsyncData<requests.athena.WorkgroupsResponse>
handleWorkgroupsLoadMore: (prev: requests.athena.WorkgroupsResponse) => void
}
interface WorkgroupsFetcherProps {
children: (props: WorkgroupsFetcherRenderProps) => React.ReactElement
}
function WorkgroupsFetcher({ children }: WorkgroupsFetcherProps) {
const [prev, setPrev] = React.useState<requests.athena.WorkgroupsResponse | null>(null)
const workgroupsData = requests.athena.useWorkgroups(prev)
return children({ handleWorkgroupsLoadMore: setPrev, workgroupsData })
}
// TODO:
// refactor data using these principles:
// there is list of items (workgroups, queries, executions, results), user can loadMore items of this list
// also some lists has selected one item (workgroup, queries), user can change selected item
// Something like this:
// {
// [T namespace]: {
// list: T[]
// selected?: T,
// change: (value: T) => void
// loadMore: (prev: T[]) => void
// }
// }
interface StateRenderProps {
customQueryBody: string | null
executionsData: requests.AsyncData<requests.athena.QueryExecutionsResponse>
handleExecutionsLoadMore: (prev: requests.athena.QueryExecutionsResponse) => void
handleQueriesLoadMore: (prev: requests.athena.QueriesResponse) => void
handleQueryBodyChange: (q: string | null) => void
handleQueryMetaChange: (q: requests.Query | requests.athena.AthenaQuery | null) => void
handleQueryResultsLoadMore: (prev: requests.athena.QueryResultsResponse) => void
handleSubmit: (q: string) => () => void
handleWorkgroupChange: (w: requests.athena.Workgroup | null) => void
handleWorkgroupsLoadMore: (prev: requests.athena.WorkgroupsResponse) => void
queriesData: requests.AsyncData<requests.athena.QueriesResponse>
queryMeta: requests.athena.AthenaQuery | null
queryResultsData: requests.AsyncData<requests.athena.QueryResultsResponse>
queryRunData: requests.AsyncData<requests.athena.QueryRunResponse>
workgroup: requests.athena.Workgroup | null
workgroupsData: requests.AsyncData<requests.athena.WorkgroupsResponse>
}
interface StateProps {
children: (props: StateRenderProps) => React.ReactElement
queryExecutionId: string | null
}
function State({ children, queryExecutionId }: StateProps) {
// Info about query: name, url, etc.
const [queryMeta, setQueryMeta] = React.useState<requests.athena.AthenaQuery | null>(
null,
)
// Custom query content, not associated with queryMeta
const [customQueryBody, setCustomQueryBody] = React.useState<string | null>(null)
const handleQueryMetaChange = React.useCallback(
(query) => {
setQueryMeta(query as requests.athena.AthenaQuery | null)
setCustomQueryBody(null)
},
[setQueryMeta, setCustomQueryBody],
)
// Query content requested to Athena
const [queryRequest, setQueryRequest] = React.useState<string | null>(null)
const handleSubmit = React.useMemo(
() => (body: string) => () => setQueryRequest(body),
[setQueryRequest],
)
React.useEffect(() => {
setQueryRequest(null)
}, [queryExecutionId])
const [workgroup, setWorkgroup] = React.useState<requests.athena.Workgroup | null>(null)
const handleWorkgroupChange = React.useCallback(
(w) => {
setWorkgroup(w)
setQueryMeta(null)
},
[setQueryMeta, setWorkgroup],
)
return (
<WorkgroupsFetcher>
{({ handleWorkgroupsLoadMore, workgroupsData }) =>
workgroupsData.case({
_: (workgroupsDataResult) =>
AsyncResult.Init.is(workgroupsDataResult) ||
AsyncResult.Pending.is(workgroupsDataResult) ||
workgroupsDataResult.value?.list?.length ? (
<QueryResultsFetcher queryExecutionId={queryExecutionId}>
{({ queryResultsData, handleQueryResultsLoadMore }) => {
const queryExecution = (
queryResultsData as requests.AsyncData<
requests.athena.QueryResultsResponse,
requests.athena.QueryExecution | null
>
).case({
_: () => null,
Ok: ({ queryExecution: qE }) => qE,
})
const selectedWorkgroup =
workgroup ||
queryExecution?.workgroup ||
workgroupsDataResult.value?.defaultWorkgroup ||
''
return (
<QueriesFetcher workgroup={selectedWorkgroup} key={queryExecutionId}>
{({
queriesData,
executionsData,
handleQueriesLoadMore,
handleExecutionsLoadMore,
}) => (
<QueryRunner
queryBody={queryRequest || ''}
queryExecutionId={queryExecutionId}
workgroup={selectedWorkgroup}
>
{({ queryRunData }) =>
children({
customQueryBody,
executionsData,
handleExecutionsLoadMore,
handleQueriesLoadMore,
handleQueryBodyChange: setCustomQueryBody,
handleQueryMetaChange,
handleQueryResultsLoadMore,
handleSubmit,
handleWorkgroupChange,
handleWorkgroupsLoadMore,
queriesData,
queryMeta,
queryResultsData,
queryRunData,
workgroupsData,
workgroup: selectedWorkgroup,
})
}
</QueryRunner>
)}
</QueriesFetcher>
)
}}
</QueryResultsFetcher>
) : (
<WorkgroupsEmpty />
),
Err: (error) => <WorkgroupsEmpty error={error} />,
})
}
</WorkgroupsFetcher>
)
}
const useOverrideStyles = M.makeStyles({
li: {
'&::before': {
position: 'absolute', // Workaround for sanitize.css a11y styles
},
},
separator: {
alignItems: 'center',
},
})
const useHistoryHeaderStyles = M.makeStyles({
breadcrumb: {
display: 'flex',
},
})
interface HistoryHeaderProps {
queryExecutionId?: string | null
bucket: string
className: string
}
function HistoryHeader({ bucket, className, queryExecutionId }: HistoryHeaderProps) {
const classes = useHistoryHeaderStyles()
const overrideClasses = useOverrideStyles()
const { urls } = NamedRoutes.use()
const rootTitle = 'Query Executions'
if (!queryExecutionId) {
return (
<M.Typography className={className} color="textPrimary">
{rootTitle}
</M.Typography>
)
}
return (
<M.Breadcrumbs className={className} classes={overrideClasses}>
<Link className={classes.breadcrumb} to={urls.bucketAthenaQueries(bucket)}>
{rootTitle}
</Link>
<M.Typography className={classes.breadcrumb} color="textPrimary">
Results for <Code>{queryExecutionId}</Code>
</M.Typography>
</M.Breadcrumbs>
)
}
const isButtonDisabled = (
queryContent: string,
queryRunData: requests.AsyncData<requests.athena.QueryRunResponse>,
error: Error | null,
): boolean => !!error || !queryContent || !!queryRunData.case({ Pending: R.T, _: R.F })
interface AthenaProps
extends RouteComponentProps<{ bucket: string; queryExecutionId?: string }> {}
export default function Athena({
match: {
params: { bucket, queryExecutionId },
},
}: AthenaProps) {
const classes = useStyles()
const { urls } = NamedRoutes.use()
return (
<State queryExecutionId={queryExecutionId || null}>
{({
customQueryBody,
executionsData,
handleExecutionsLoadMore,
handleQueriesLoadMore,
handleQueryBodyChange,
handleQueryMetaChange,
handleQueryResultsLoadMore,
handleSubmit,
handleWorkgroupChange,
handleWorkgroupsLoadMore,
queriesData,
queryMeta,
queryResultsData,
queryRunData,
workgroupsData,
workgroup,
}) =>
queryRunData.case({
_: ({ value: executionData }: { value: { id: string } }) => {
if (executionData?.id && executionData?.id !== queryExecutionId) {
return (
<Redirect
to={urls.bucketAthenaQueryExecution(bucket, executionData?.id)}
/>
)
}
return (
<>
<M.Typography variant="h6">Athena SQL</M.Typography>
<div className={classes.selects}>
<div className={classes.select}>
{workgroupsData.case({
Ok: (workgroups) => (
<>
<M.Typography className={classes.sectionHeader}>
Select workgroup
</M.Typography>
{workgroups.list.length ? (
<WorkgroupSelect
workgroups={workgroups}
onChange={handleWorkgroupChange}
onLoadMore={handleWorkgroupsLoadMore}
value={workgroup}
/>
) : (
<M.FormHelperText>There are no workgroups.</M.FormHelperText>
)}
</>
),
Err: makeAsyncDataErrorHandler('Workgroups Data'),
_: () => <SelectSkeleton />,
})}
</div>
<div className={classes.select}>
{queriesData.case({
Ok: (queries) =>
queries.list.length ? (
<>
<M.Typography
className={classes.sectionHeader}
variant="body1"
>
Select query
</M.Typography>
<QuerySelect
queries={queries.list}
onChange={handleQueryMetaChange}
value={customQueryBody ? null : queryMeta}
onLoadMore={
queries.next
? () => handleQueriesLoadMore(queries)
: undefined
}
/>
</>
) : (
<M.Typography className={classes.emptySelect} variant="body1">
There are no saved queries.
</M.Typography>
),
Err: makeAsyncDataErrorHandler('Select query'),
_: () => <SelectSkeleton />,
})}
</div>
</div>
<div className={classes.form}>
{queryResultsData.case({
_: ({
value: queryResults,
}: {
value: requests.athena.QueryResultsResponse
}) => {
const areQueriesLoaded = queriesData.case({ Ok: R.T, _: R.F })
if (!areQueriesLoaded) return <FormSkeleton />
return (
<Form
disabled={isButtonDisabled(
customQueryBody ||
queryResults?.queryExecution?.query ||
queryMeta?.body ||
'',
queryRunData,
null,
)}
onChange={handleQueryBodyChange}
onSubmit={handleSubmit}
error={(queryRunData as $TSFixMe).case({
Err: R.identity,
_: () => undefined,
})}
value={
customQueryBody ||
queryResults?.queryExecution?.query ||
queryMeta?.body ||
''
}
/>
)
},
Err: makeAsyncDataErrorHandler('Query Body'),
Pending: () => <FormSkeleton />,
})}
</div>
<div>
<HistoryHeader
bucket={bucket}
className={classes.sectionHeader}
queryExecutionId={queryExecutionId}
/>
{!queryExecutionId &&
executionsData.case({
Ok: (executions) => (
<History
bucket={bucket}
executions={executions.list}
onLoadMore={
executions.next
? () => handleExecutionsLoadMore(executions)
: undefined
}
/>
),
Err: makeAsyncDataErrorHandler('Executions Data'),
_: () => <TableSkeleton size={4} />,
})}
</div>
{queryResultsData.case({
Init: () => null,
Ok: (queryResults: requests.athena.QueryResultsResponse) => {
if (queryResults.rows.length) {
return (
<Results
className={classes.results}
rows={queryResults.rows}
columns={queryResults.columns}
onLoadMore={
queryResults.next
? () => handleQueryResultsLoadMore(queryResults)
: undefined
}
/>
)
}
if (queryResults.queryExecution) {
return (
<History
bucket={bucket}
executions={[queryResults.queryExecution!]}
/>
)
}
return makeAsyncDataErrorHandler('Query Results Data')(
new Error("Couldn't fetch query results"),
)
},
Err: makeAsyncDataErrorHandler('Query Results Data'),
_: () => <TableSkeleton size={10} />,
})}
</>
)
},
})
}
</State>
)
} | the_stack |
import * as UserScrapingAPI from '../user-scraping-api'
import * as ExtraScraper from './extra-scraper'
import {
getFollowersCount,
getTotalCountOfReactions,
getParticipantsInAudioSpaceCount,
findNonLinkedMentionsFromTweet,
} from '../../common'
export interface UserScraper {
totalCount: number | null
[Symbol.asyncIterator](): ScrapedUsersIterator
}
// 단순 스크래퍼. 기존 체인블락 방식
class SimpleScraper implements UserScraper {
private retrieverScrapingClient = UserScrapingAPI.UserScrapingAPIClient.fromClientOptions(
this.request.retriever.clientOptions
)
private executorScrapingClient = UserScrapingAPI.UserScrapingAPIClient.fromClientOptions(
this.request.executor.clientOptions
)
public totalCount: number
public constructor(
private request: SessionRequest<FollowerSessionTarget | LockPickerSessionTarget>
) {
const { user, list: followKind } = request.target
this.totalCount = getFollowersCount(user, followKind)!
}
public async *[Symbol.asyncIterator]() {
const { user } = this.request.target
if (user.blocked_by) {
yield* this.iterateBlockBuster()
} else {
yield* this.iterateNormally()
}
}
private async *iterateNormally() {
const { user, list: followKind } = this.request.target
let scraper: ScrapedUsersIterator = this.executorScrapingClient.getAllFollowsUserList(
followKind,
user
)
scraper = ExtraScraper.scrapeUsersOnBio(
this.executorScrapingClient,
scraper,
this.request.extraSessionOptions.bioBlock
)
yield* scraper
}
private async *iterateBlockBuster() {
const { user, list: followKind } = this.request.target
const idsIterator = this.retrieverScrapingClient.getAllFollowsIds(followKind, user)
for await (const response of idsIterator) {
if (!response.ok) {
throw response.error
}
const userIds = response.value.ids
let scraper: ScrapedUsersIterator = this.executorScrapingClient.lookupUsersByIds(userIds)
scraper = ExtraScraper.scrapeUsersOnBio(
this.executorScrapingClient,
scraper,
this.request.extraSessionOptions.bioBlock
)
yield* scraper
}
}
}
// 맞팔로우 스크래퍼
class MutualFollowerScraper implements UserScraper {
private retrieverScrapingClient = UserScrapingAPI.UserScrapingAPIClient.fromClientOptions(
this.request.retriever.clientOptions
)
private executorScrapingClient = UserScrapingAPI.UserScrapingAPIClient.fromClientOptions(
this.request.executor.clientOptions
)
public totalCount: number | null = null
public constructor(private request: SessionRequest<FollowerSessionTarget>) {}
public async *[Symbol.asyncIterator]() {
const { user } = this.request.target
let mutualFollowersIds: string[]
if (user.blocked_by) {
mutualFollowersIds = await this.getMutualFollowersIdsBlockBuster()
} else {
mutualFollowersIds = await this.getMutualFollowersIdsNormally()
}
this.totalCount = mutualFollowersIds.length
let scraper: ScrapedUsersIterator =
this.executorScrapingClient.lookupUsersByIds(mutualFollowersIds)
scraper = ExtraScraper.scrapeUsersOnBio(
this.executorScrapingClient,
scraper,
this.request.extraSessionOptions.bioBlock
)
yield* scraper
}
private async getMutualFollowersIdsNormally() {
return this.executorScrapingClient.getAllMutualFollowersIds(this.request.target.user)
}
private async getMutualFollowersIdsBlockBuster() {
return this.retrieverScrapingClient.getAllMutualFollowersIds(this.request.target.user)
}
}
// 트윗반응 유저 스크래퍼
export class TweetReactedUserScraper implements UserScraper {
private retrieverScrapingClient = UserScrapingAPI.UserScrapingAPIClient.fromClientOptions(
this.request.retriever.clientOptions
)
private executorScrapingClient = UserScrapingAPI.UserScrapingAPIClient.fromClientOptions(
this.request.executor.clientOptions
)
public totalCount: number
public constructor(private request: SessionRequest<TweetReactionSessionTarget>) {
this.totalCount = getTotalCountOfReactions(request.target)
}
public async *[Symbol.asyncIterator]() {
let reactions = this.fetchReactions()
const isBlockBuster = this.request.retriever.user.id_str !== this.request.executor.user.id_str
if (isBlockBuster) {
reactions = this.rehydrate(reactions)
}
yield* reactions
}
private async *rehydrate(scraper: ScrapedUsersIterator): ScrapedUsersIterator {
// retriever를 갖고 가져온 유저들은 followed_by, blocking 등이 retriever기준으로 되어있다.
// 실제로 필요한건 executor기준으로 된 값이므로 유저를 다시 가져온다.
const userIds = new Set<string>()
for await (const response of scraper) {
if (!response.ok) {
continue
}
response.value.users.forEach(({ id_str }) => userIds.add(id_str))
}
const rehydrateScraper = this.executorScrapingClient.lookupUsersByIds(Array.from(userIds))
yield* rehydrateScraper
}
private async *fetchReactions(): ScrapedUsersIterator {
const {
tweet,
includeRetweeters: blockRetweeters,
includeLikers: blockLikers,
includeMentionedUsers: blockMentionedUsers,
includeQuotedUsers: blockQuotedUsers,
includeNonLinkedMentions: blockNonLinkedMentions,
includedReactionsV2,
} = this.request.target
const scrapers: ScrapedUsersIterator[] = []
if (blockRetweeters) {
scrapers.push(this.retrieverScrapingClient.getAllReactedUserList('retweeted', tweet))
}
if (blockLikers) {
scrapers.push(this.retrieverScrapingClient.getAllReactedUserList('liked', tweet))
} else if (includedReactionsV2.length > 0) {
const reactedUserIterator = this.retrieverScrapingClient.getAllReactedV2UserList(
tweet,
includedReactionsV2
)
scrapers.push(reactedUserIterator)
}
if (blockMentionedUsers) {
const mentions = tweet.entities.user_mentions || []
const mentionedUserIds = mentions.map(e => e.id_str)
scrapers.push(this.retrieverScrapingClient.lookupUsersByIds(mentionedUserIds))
}
if (blockQuotedUsers) {
scrapers.push(this.retrieverScrapingClient.getQuotedUsers(tweet))
}
if (blockNonLinkedMentions) {
const userNames = findNonLinkedMentionsFromTweet(this.request.target.tweet)
scrapers.push(this.retrieverScrapingClient.lookupUsersByNames(userNames))
}
for (const scraper of scrapers) {
yield* ExtraScraper.scrapeUsersOnBio(
this.retrieverScrapingClient,
scraper,
this.request.extraSessionOptions.bioBlock
)
}
}
}
class ImportUserScraper implements UserScraper {
private scrapingClient = UserScrapingAPI.UserScrapingAPIClient.fromClientOptions(
this.request.executor.clientOptions
)
public totalCount = this.request.target.userIds.length + this.request.target.userNames.length
public constructor(private request: SessionRequest<ImportSessionTarget>) {}
public async *[Symbol.asyncIterator]() {
// 여러 파일을 import한다면 유저ID와 유저네임 둘 다 있을 수 있다.
const { userIds, userNames } = this.request.target
let scraper: ScrapedUsersIterator
if (userIds.length > 0) {
scraper = this.scrapingClient.lookupUsersByIds(userIds)
scraper = ExtraScraper.scrapeUsersOnBio(
this.scrapingClient,
scraper,
this.request.extraSessionOptions.bioBlock
)
yield* scraper
}
if (userNames.length > 0) {
scraper = this.scrapingClient.lookupUsersByNames(userNames)
scraper = ExtraScraper.scrapeUsersOnBio(
this.scrapingClient,
scraper,
this.request.extraSessionOptions.bioBlock
)
yield* scraper
}
}
}
class UserSearchScraper implements UserScraper {
private scrapingClient = UserScrapingAPI.UserScrapingAPIClient.fromClientOptions(
this.request.executor.clientOptions
)
public totalCount = null
public constructor(private request: SessionRequest<UserSearchSessionTarget>) {}
public async *[Symbol.asyncIterator]() {
let scraper: ScrapedUsersIterator = this.scrapingClient.getUserSearchResults(
this.request.target.query
)
scraper = ExtraScraper.scrapeUsersOnBio(
this.scrapingClient,
scraper,
this.request.extraSessionOptions.bioBlock
)
yield* scraper
}
}
export class AudioSpaceScraper implements UserScraper {
private scrapingClient = UserScrapingAPI.UserScrapingAPIClient.fromClientOptions(
this.request.executor.clientOptions
)
public totalCount = getParticipantsInAudioSpaceCount(this.request.target)
public constructor(private request: SessionRequest<AudioSpaceSessionTarget>) {}
public async *[Symbol.asyncIterator]() {
const { audioSpace, includeHostsAndSpeakers, includeListeners } = this.request.target
let scraper: ScrapedUsersIterator = this.scrapingClient.getParticipantsInAudioSpace({
audioSpace,
hostsAndSpeakers: includeHostsAndSpeakers,
listeners: includeListeners,
})
scraper = ExtraScraper.scrapeUsersOnBio(
this.scrapingClient,
scraper,
this.request.extraSessionOptions.bioBlock
)
yield* scraper
}
}
export function initScraper(request: SessionRequest<AnySessionTarget>): UserScraper {
const { target } = request
switch (target.type) {
case 'import':
return new ImportUserScraper(request as SessionRequest<ImportSessionTarget>)
case 'tweet_reaction':
return new TweetReactedUserScraper(request as SessionRequest<TweetReactionSessionTarget>)
case 'user_search':
return new UserSearchScraper(request as SessionRequest<UserSearchSessionTarget>)
case 'lockpicker':
return new SimpleScraper(request as SessionRequest<LockPickerSessionTarget>)
case 'follower':
if (target.list === 'mutual-followers') {
return new MutualFollowerScraper(request as SessionRequest<FollowerSessionTarget>)
} else {
return new SimpleScraper(request as SessionRequest<FollowerSessionTarget>)
}
case 'audio_space':
return new AudioSpaceScraper(request as SessionRequest<AudioSpaceSessionTarget>)
case 'export_my_blocklist':
// 오로지 export만 쓰므로 userScraper는 안 쓴다 (user-id scraper만 쓰지)
throw new Error('unreachable')
}
} | the_stack |
import * as dom5 from 'dom5';
import {Program} from 'estree';
import * as jsc from 'jscodeshift';
import * as parse5 from 'parse5';
import {Document, Import, isPositionInsideRange, ParsedHtmlDocument, Severity, Warning} from 'polymer-analyzer';
import * as recast from 'recast';
import {ConversionSettings} from './conversion-settings';
import {attachCommentsToEndOfProgram, attachCommentsToFirstStatement, canDomModuleBeInlined, createDomNodeInsertStatements, filterClone, getCommentsBetween, getNodePathInProgram, insertStatementsIntoProgramBody, serializeNodeToTemplateLiteral} from './document-util';
import {ImportWithDocument, isImportWithDocument} from './import-with-document';
import {removeNamespaceInitializers} from './passes/remove-namespace-initializers';
import {removeToplevelUseStrict} from './passes/remove-toplevel-use-strict';
import {removeUnnecessaryEventListeners} from './passes/remove-unnecessary-waits';
import {removeWrappingIIFEs} from './passes/remove-wrapping-iife';
import {rewriteToplevelThis} from './passes/rewrite-toplevel-this';
import {ConvertedDocumentFilePath, ConvertedDocumentUrl, OriginalDocumentUrl} from './urls/types';
import {UrlHandler} from './urls/url-handler';
import {isOriginalDocumentUrlFormat} from './urls/util';
import {replaceHtmlExtensionIfFound} from './urls/util';
/**
* Keep a set of elements to ignore when Recreating HTML contents by adding
* code to the top of a program.
*/
const generatedElementBlacklist = new Set<string|undefined>([
'base',
'link',
'meta',
'script',
]);
/**
* An abstract superclass for our document scanner and document converters.
*/
export abstract class DocumentProcessor {
protected readonly originalPackageName: string;
protected readonly originalUrl: OriginalDocumentUrl;
/**
* N.B. that this converted url always points to .js, even if this document
* will be converted to an HTML file.
*/
protected readonly convertedUrl: ConvertedDocumentUrl;
protected readonly convertedFilePath: ConvertedDocumentFilePath;
protected readonly urlHandler: UrlHandler;
protected readonly conversionSettings: ConversionSettings;
protected readonly document: Document<ParsedHtmlDocument>;
protected readonly program: Program;
protected readonly convertedHtmlScripts: ReadonlySet<ImportWithDocument>;
protected readonly leadingCommentsToPrepend: string[]|undefined;
constructor(
document: Document<ParsedHtmlDocument>, originalPackageName: string,
urlHandler: UrlHandler, conversionSettings: ConversionSettings) {
// The `originalPackageName` given by `PackageConverter` is sometimes
// incorrect because it is always the name of the root package being
// converted, even if this `DocumentConverter` is converting a file in a
// dependency of the root package. Instead, it should be the name of the
// package containing this document.
this.originalPackageName = originalPackageName;
this.conversionSettings = conversionSettings;
this.urlHandler = urlHandler;
this.document = document;
this.originalUrl = urlHandler.getDocumentUrl(document);
this.convertedUrl = this.convertDocumentUrl(this.originalUrl);
const relativeConvertedUrl =
this.urlHandler.convertedUrlToPackageRelative(this.convertedUrl);
this.convertedFilePath =
this.urlHandler.packageRelativeConvertedUrlToConvertedDocumentFilePath(
originalPackageName, relativeConvertedUrl);
const prepareResult = this.prepareJsModule();
this.program = prepareResult.program;
this.convertedHtmlScripts = prepareResult.convertedHtmlScripts;
this.leadingCommentsToPrepend = prepareResult.leadingCommentsToPrepend;
}
private isInternalNonModuleImport(scriptImport: ImportWithDocument): boolean {
const oldScriptUrl = this.urlHandler.getDocumentUrl(scriptImport.document);
const newScriptUrl = this.convertScriptUrl(oldScriptUrl);
const isModuleImport = scriptImport.astNode !== undefined &&
scriptImport.astNode.language === 'html' &&
dom5.getAttribute(scriptImport.astNode.node, 'type') === 'module';
const isInternalImport =
this.urlHandler.isImportInternal(this.convertedUrl, newScriptUrl);
return isInternalImport && !isModuleImport;
}
/**
* Creates a single program from all the JavaScript in the current document.
* The standard program result can be used for either scanning or conversion.
*
* TODO: this does a lot of mutation of the program. Could we only do that
* when we're converting, and not when we're scanning?
*/
private prepareJsModule() {
const combinedToplevelStatements = [];
const convertedHtmlScripts = new Set<ImportWithDocument>();
const claimedDomModules = new Set<parse5.ASTNode>();
let prevScriptNode: parse5.ASTNode|undefined = undefined;
/**
* Inserting leading comments is surprisingly tricky, because they must
* be attached to a node, but very few nodes can come before an import,
* and in general we don't want to insert fake nodes, so instead we
* pass these up to be added onto the first node in the final output script.
*/
let htmlCommentsBeforeFirstScriptNode: undefined|string[];
for (const script of this.document.getFeatures()) {
let scriptDocument: Document;
if (script.kinds.has('html-script')) {
const scriptImport = script as Import;
if (!isImportWithDocument(scriptImport)) {
console.warn(
new Warning({
code: 'import-ignored',
message: `Import could not be loaded and will be ignored.`,
parsedDocument: this.document.parsedDocument,
severity: Severity.WARNING,
sourceRange: scriptImport.sourceRange!,
}).toString());
continue;
}
if (!this.isInternalNonModuleImport(scriptImport)) {
continue;
}
scriptDocument = scriptImport.document;
convertedHtmlScripts.add(scriptImport);
} else if (script.kinds.has('js-document')) {
scriptDocument = script as Document;
} else {
continue;
}
const scriptProgram =
recast.parse(scriptDocument.parsedDocument.contents).program;
rewriteToplevelThis(scriptProgram);
removeToplevelUseStrict(scriptProgram);
// We need to inline templates on a per-script basis, otherwise we run
// into trouble matching up analyzer AST nodes with our own.
const localClaimedDomModules =
this.inlineTemplates(scriptProgram, scriptDocument);
for (const claimedDomModule of localClaimedDomModules) {
claimedDomModules.add(claimedDomModule);
}
if (this.conversionSettings.addImportMeta) {
this.addImportMetaToElements(scriptProgram, scriptDocument);
}
const statements = scriptProgram.body;
if (script.astNode && script.astNode.language === 'html') {
if (prevScriptNode !== undefined) {
const comments: string[] = getCommentsBetween(
this.document.parsedDocument.ast,
prevScriptNode,
script.astNode.node);
attachCommentsToFirstStatement(comments, statements);
} else {
htmlCommentsBeforeFirstScriptNode = getCommentsBetween(
this.document.parsedDocument.ast,
prevScriptNode,
script.astNode.node);
}
prevScriptNode = script.astNode.node;
}
combinedToplevelStatements.push(...statements);
}
const program = jsc.program(combinedToplevelStatements);
removeUnnecessaryEventListeners(program);
removeWrappingIIFEs(program);
const trailingComments = getCommentsBetween(
this.document.parsedDocument.ast, prevScriptNode, undefined);
attachCommentsToEndOfProgram(trailingComments, combinedToplevelStatements);
this.insertCodeToGenerateHtmlElements(program, claimedDomModules);
removeNamespaceInitializers(program, this.conversionSettings.namespaces);
return {
program,
convertedHtmlScripts,
leadingCommentsToPrepend: htmlCommentsBeforeFirstScriptNode
};
}
/**
* Recreate the HTML contents from the original HTML document by adding
* code to the top of program that constructs equivalent DOM and insert
* it into `window.document`.
*/
private insertCodeToGenerateHtmlElements(
program: Program, claimedDomModules: Set<parse5.ASTNode>) {
const ast = this.document.parsedDocument.ast as parse5.ASTNode;
if (ast.childNodes === undefined) {
return;
}
const htmlElement = ast.childNodes!.find((n) => n.tagName === 'html');
const head = htmlElement!.childNodes!.find((n) => n.tagName === 'head')!;
const body = htmlElement!.childNodes!.find((n) => n.tagName === 'body')!;
const elements = [
...head.childNodes!.filter(
(n: parse5.ASTNode) => n.tagName !== undefined),
...body.childNodes!.filter((n: parse5.ASTNode) => n.tagName !== undefined)
];
const genericElements = filterClone(elements, (e) => {
return !(
generatedElementBlacklist.has(e.tagName) || claimedDomModules.has(e));
});
if (genericElements.length === 0) {
return;
}
const statements = createDomNodeInsertStatements(genericElements);
insertStatementsIntoProgramBody(statements, program);
}
/**
* Find Polymer element templates in the original HTML. Insert these
* templates as strings as part of the javascript element declaration.
*/
private inlineTemplates(program: Program, scriptDocument: Document) {
const elements = scriptDocument.getFeatures({'kind': 'polymer-element'});
const claimedDomModules = new Set<parse5.ASTNode>();
for (const element of elements) {
// This is an analyzer wart. There's no way to avoid getting features
// from the containing document when querying an inline document. Filed
// as https://github.com/Polymer/polymer-analyzer/issues/712
if (element.sourceRange === undefined ||
!isPositionInsideRange(
element.sourceRange.start, scriptDocument.sourceRange)) {
continue;
}
const domModule = element.domModule;
if (domModule === undefined) {
continue;
}
if (!canDomModuleBeInlined(domModule)) {
continue;
}
claimedDomModules.add(domModule);
const template = dom5.query(domModule, (e) => e.tagName === 'template');
if (template === null) {
continue;
}
// It's ok to tag templates with the expression `Polymer.html` without
// adding an import because `Polymer.html` is re-exported by both
// polymer.html and polymer-element.html and, crucially, template
// inlining happens before rewriting references.
const templateLiteral = jsc.taggedTemplateExpression(
jsc.memberExpression(
jsc.identifier('Polymer'), jsc.identifier('html')),
serializeNodeToTemplateLiteral(
parse5.treeAdapters.default.getTemplateContent(template)));
const nodePath = getNodePathInProgram(program, element.astNode);
if (nodePath === undefined) {
console.warn(
new Warning({
code: 'not-found',
message: `Can't find recast node for element ${element.tagName}`,
parsedDocument: this.document.parsedDocument,
severity: Severity.WARNING,
sourceRange: element.sourceRange!
}).toString());
continue;
}
const node = nodePath.node;
if (node.type === 'ClassDeclaration' || node.type === 'ClassExpression') {
// A Polymer 2.0 class-based element
node.body.body.splice(
0,
0,
jsc.methodDefinition(
'get',
jsc.identifier('template'),
jsc.functionExpression(
null, [], jsc.blockStatement([jsc.returnStatement(
templateLiteral)])),
true));
} else if (node.type === 'CallExpression') {
// A Polymer hybrid/legacy factory function element
const arg = node.arguments[0];
if (arg && arg.type === 'ObjectExpression') {
arg.properties.unshift(jsc.property(
'init', jsc.identifier('_template'), templateLiteral));
}
} else {
console.error(`Internal Error, Class or CallExpression expected, got ${
node.type}`);
}
}
return claimedDomModules;
}
/**
* Adds a static importMeta property to Polymer elements.
*/
private addImportMetaToElements(program: Program, scriptDocument: Document) {
const elements = scriptDocument.getFeatures({'kind': 'polymer-element'});
for (const element of elements) {
// This is an analyzer wart. There's no way to avoid getting features
// from the containing document when querying an inline document. Filed
// as https://github.com/Polymer/polymer-analyzer/issues/712
if (element.sourceRange === undefined ||
!isPositionInsideRange(
element.sourceRange.start, scriptDocument.sourceRange)) {
continue;
}
const nodePath = getNodePathInProgram(program, element.astNode);
if (nodePath === undefined) {
console.warn(
new Warning({
code: 'not-found',
message: `Can't find recast node for element ${element.tagName}`,
parsedDocument: this.document.parsedDocument,
severity: Severity.WARNING,
sourceRange: element.sourceRange!
}).toString());
continue;
}
const importMeta = jsc.memberExpression(
jsc.identifier('import'), jsc.identifier('meta'));
const node = nodePath.node;
if (node.type === 'ClassDeclaration' || node.type === 'ClassExpression') {
// A Polymer 2.0 class-based element
const getter = jsc.methodDefinition(
'get',
jsc.identifier('importMeta'),
jsc.functionExpression(
null,
[],
jsc.blockStatement([jsc.returnStatement(importMeta)])),
true);
node.body.body.splice(0, 0, getter);
} else if (node.type === 'CallExpression') {
// A Polymer hybrid/legacy factory function element
const arg = node.arguments[0];
if (arg && arg.type === 'ObjectExpression') {
arg.properties.unshift(
jsc.property('init', jsc.identifier('importMeta'), importMeta));
}
} else {
console.error(`Internal Error, Class or CallExpression expected, got ${
node.type}`);
}
}
}
/**
* Converts an HTML Document's path from old world to new. Use new NPM naming
* as needed in the path, and change any .html extension to .js.
*/
protected convertDocumentUrl(htmlUrl: OriginalDocumentUrl):
ConvertedDocumentUrl {
// TODO(fks): This can be removed later if type-checking htmlUrl is enough
if (!isOriginalDocumentUrlFormat(htmlUrl)) {
throw new Error(
`convertDocumentUrl() expects an OriginalDocumentUrl string` +
`from the analyzer, but got "${htmlUrl}"`);
}
// Use the layout-specific UrlHandler to convert the URL.
let jsUrl: string = this.urlHandler.convertUrl(htmlUrl);
// Temporary workaround for imports of some shadycss files that wrapped
// ES6 modules.
if (jsUrl.endsWith('shadycss/apply-shim.html')) {
jsUrl = jsUrl.replace(
'shadycss/apply-shim.html', 'shadycss/entrypoints/apply-shim.js');
}
if (jsUrl.endsWith('shadycss/custom-style-interface.html')) {
jsUrl = jsUrl.replace(
'shadycss/custom-style-interface.html',
'shadycss/entrypoints/custom-style-interface.js');
}
// This is a special case for renaming 'polymer.html' in Polymer to
// 'polymer-legacy.html'.
if (this.originalPackageName === 'polymer' && jsUrl === './polymer.html') {
// We're converting 'polymer.html' itself:
jsUrl = './polymer-legacy.html';
} else if (jsUrl.endsWith('polymer/polymer.html')) {
// We're converting something that references 'polymer.html':
jsUrl = jsUrl.replace(
/polymer\/polymer\.html$/, 'polymer/polymer-legacy.html');
}
// Convert any ".html" URLs to point to their new ".js" module equivilent
jsUrl = replaceHtmlExtensionIfFound(jsUrl);
return jsUrl as ConvertedDocumentUrl;
}
/**
* Converts the URL for a script that is already being loaded in a
* pre-conversion HTML document via the <script> tag. This is similar to
* convertDocumentUrl(), but can skip some of the more complex .html -> .js
* conversion/rewriting.
*/
protected convertScriptUrl(oldUrl: OriginalDocumentUrl):
ConvertedDocumentUrl {
// TODO(fks): This can be removed later if type-checking htmlUrl is enough
if (!isOriginalDocumentUrlFormat(oldUrl)) {
throw new Error(
`convertDocumentUrl() expects an OriginalDocumentUrl string` +
`from the analyzer, but got "${oldUrl}"`);
}
// Use the layout-specific UrlHandler to convert the URL.
return this.urlHandler.convertUrl(oldUrl);
}
} | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { Snapshots } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { ContainerServiceClient } from "../containerServiceClient";
import {
Snapshot,
SnapshotsListNextOptionalParams,
SnapshotsListOptionalParams,
SnapshotsListByResourceGroupNextOptionalParams,
SnapshotsListByResourceGroupOptionalParams,
SnapshotsListResponse,
SnapshotsListByResourceGroupResponse,
SnapshotsGetOptionalParams,
SnapshotsGetResponse,
SnapshotsCreateOrUpdateOptionalParams,
SnapshotsCreateOrUpdateResponse,
TagsObject,
SnapshotsUpdateTagsOptionalParams,
SnapshotsUpdateTagsResponse,
SnapshotsDeleteOptionalParams,
SnapshotsListNextResponse,
SnapshotsListByResourceGroupNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing Snapshots operations. */
export class SnapshotsImpl implements Snapshots {
private readonly client: ContainerServiceClient;
/**
* Initialize a new instance of the class Snapshots class.
* @param client Reference to the service client
*/
constructor(client: ContainerServiceClient) {
this.client = client;
}
/**
* Gets a list of snapshots in the specified subscription.
* @param options The options parameters.
*/
public list(
options?: SnapshotsListOptionalParams
): PagedAsyncIterableIterator<Snapshot> {
const iter = this.listPagingAll(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listPagingPage(options);
}
};
}
private async *listPagingPage(
options?: SnapshotsListOptionalParams
): AsyncIterableIterator<Snapshot[]> {
let result = await this._list(options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listNext(continuationToken, options);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listPagingAll(
options?: SnapshotsListOptionalParams
): AsyncIterableIterator<Snapshot> {
for await (const page of this.listPagingPage(options)) {
yield* page;
}
}
/**
* Lists snapshots in the specified subscription and resource group.
* @param resourceGroupName The name of the resource group.
* @param options The options parameters.
*/
public listByResourceGroup(
resourceGroupName: string,
options?: SnapshotsListByResourceGroupOptionalParams
): PagedAsyncIterableIterator<Snapshot> {
const iter = this.listByResourceGroupPagingAll(resourceGroupName, options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByResourceGroupPagingPage(resourceGroupName, options);
}
};
}
private async *listByResourceGroupPagingPage(
resourceGroupName: string,
options?: SnapshotsListByResourceGroupOptionalParams
): AsyncIterableIterator<Snapshot[]> {
let result = await this._listByResourceGroup(resourceGroupName, options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listByResourceGroupNext(
resourceGroupName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listByResourceGroupPagingAll(
resourceGroupName: string,
options?: SnapshotsListByResourceGroupOptionalParams
): AsyncIterableIterator<Snapshot> {
for await (const page of this.listByResourceGroupPagingPage(
resourceGroupName,
options
)) {
yield* page;
}
}
/**
* Gets a list of snapshots in the specified subscription.
* @param options The options parameters.
*/
private _list(
options?: SnapshotsListOptionalParams
): Promise<SnapshotsListResponse> {
return this.client.sendOperationRequest({ options }, listOperationSpec);
}
/**
* Lists snapshots in the specified subscription and resource group.
* @param resourceGroupName The name of the resource group.
* @param options The options parameters.
*/
private _listByResourceGroup(
resourceGroupName: string,
options?: SnapshotsListByResourceGroupOptionalParams
): Promise<SnapshotsListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, options },
listByResourceGroupOperationSpec
);
}
/**
* Gets a snapshot.
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the managed cluster resource.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
resourceName: string,
options?: SnapshotsGetOptionalParams
): Promise<SnapshotsGetResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, resourceName, options },
getOperationSpec
);
}
/**
* Creates or updates a snapshot.
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the managed cluster resource.
* @param parameters The snapshot to create or update.
* @param options The options parameters.
*/
createOrUpdate(
resourceGroupName: string,
resourceName: string,
parameters: Snapshot,
options?: SnapshotsCreateOrUpdateOptionalParams
): Promise<SnapshotsCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, resourceName, parameters, options },
createOrUpdateOperationSpec
);
}
/**
* Updates tags on a snapshot.
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the managed cluster resource.
* @param parameters Parameters supplied to the Update snapshot Tags operation.
* @param options The options parameters.
*/
updateTags(
resourceGroupName: string,
resourceName: string,
parameters: TagsObject,
options?: SnapshotsUpdateTagsOptionalParams
): Promise<SnapshotsUpdateTagsResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, resourceName, parameters, options },
updateTagsOperationSpec
);
}
/**
* Deletes a snapshot.
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the managed cluster resource.
* @param options The options parameters.
*/
delete(
resourceGroupName: string,
resourceName: string,
options?: SnapshotsDeleteOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ resourceGroupName, resourceName, options },
deleteOperationSpec
);
}
/**
* ListNext
* @param nextLink The nextLink from the previous successful call to the List method.
* @param options The options parameters.
*/
private _listNext(
nextLink: string,
options?: SnapshotsListNextOptionalParams
): Promise<SnapshotsListNextResponse> {
return this.client.sendOperationRequest(
{ nextLink, options },
listNextOperationSpec
);
}
/**
* ListByResourceGroupNext
* @param resourceGroupName The name of the resource group.
* @param nextLink The nextLink from the previous successful call to the ListByResourceGroup method.
* @param options The options parameters.
*/
private _listByResourceGroupNext(
resourceGroupName: string,
nextLink: string,
options?: SnapshotsListByResourceGroupNextOptionalParams
): Promise<SnapshotsListByResourceGroupNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, nextLink, options },
listByResourceGroupNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const listOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/providers/Microsoft.ContainerService/snapshots",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SnapshotListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.$host, Parameters.subscriptionId],
headerParameters: [Parameters.accept],
serializer
};
const listByResourceGroupOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/snapshots",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SnapshotListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName
],
headerParameters: [Parameters.accept],
serializer
};
const getOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/snapshots/{resourceName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.Snapshot
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.resourceName
],
headerParameters: [Parameters.accept],
serializer
};
const createOrUpdateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/snapshots/{resourceName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.Snapshot
},
201: {
bodyMapper: Mappers.Snapshot
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.parameters8,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.resourceName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const updateTagsOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/snapshots/{resourceName}",
httpMethod: "PATCH",
responses: {
200: {
bodyMapper: Mappers.Snapshot
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.parameters1,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.resourceName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const deleteOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/snapshots/{resourceName}",
httpMethod: "DELETE",
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.resourceName
],
headerParameters: [Parameters.accept],
serializer
};
const listNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SnapshotListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
};
const listByResourceGroupNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SnapshotListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
const TIMEZONE_LOCATION_MAP = {
'Asia/Dubai': [25.2697, 55.3094],
'Asia/Kabul': [34.5328, 69.1658],
'Asia/Yerevan': [40.1814, 44.5144],
'Africa/Luanda': [-8.8383, 13.2344],
'America/Argentina/Buenos_Aires': [-34.5997, -58.3819],
'America/Argentina/Cordoba': [-31.4167, -64.1833],
'America/Argentina/Salta': [-24.7883, -65.4106],
'America/Argentina/Catamarca': [-28.4686, -65.7792],
'America/Argentina/La_Rioja': [-29.4131, -66.8558],
'America/Argentina/San_Juan': [-31.5375, -68.5364],
'America/Argentina/Mendoza': [-32.8833, -68.8333],
'America/Argentina/San_Luis': [-33.2994, -66.3392],
'America/Argentina/Rio_Gallegos': [-51.6333, -69.2333],
'America/Argentina/Ushuaia': [-54.8072, -68.3044],
'Pacific/Pago_Pago': [-14.274, -170.7046],
'Europe/Vienna': [48.2083, 16.3731],
'Australia/Hobart': [-42.8806, 147.325],
'Australia/Melbourne': [-37.8136, 144.9631],
'Australia/Sydney': [-33.865, 151.2094],
'Australia/Broken_Hill': [-31.9567, 141.4678],
'Australia/Brisbane': [-27.4678, 153.0281],
'Australia/Adelaide': [-34.9289, 138.6011],
'Australia/Darwin': [-12.4381, 130.8411],
'Australia/Perth': [-31.9522, 115.8589],
'Asia/Baku': [40.3667, 49.8352],
'Europe/Sarajevo': [43.8667, 18.4167],
'Asia/Dhaka': [23.7289, 90.3944],
'Europe/Brussels': [50.8333, 4.3333],
'Africa/Ouagadougou': [12.3572, -1.5353],
'Europe/Sofia': [42.6979, 23.3217],
'Africa/Bujumbura': [-3.3825, 29.3611],
'Africa/Porto-Novo': [6.4833, 2.6167],
'America/Belem': [-1.4558, -48.5039],
'America/Fortaleza': [-3.7275, -38.5275],
'America/Recife': [-8.0539, -34.8808],
'America/Araguaina': [-7.1908, -48.2069],
'America/Maceio': [-9.6658, -35.735],
'America/Sao_Paulo': [-23.5504, -46.6339],
'America/Campo_Grande': [-20.4686, -54.6222],
'America/Cuiaba': [-15.5958, -56.0969],
'America/Santarem': [-2.4431, -54.7083],
'America/Porto_Velho': [-8.7619, -63.9039],
'America/Boa_Vista': [2.82, -60.6719],
'America/Manaus': [-3.1, -60.0167],
'America/Eirunepe': [-6.6597, -69.8744],
'America/Rio_Branco': [-9.9781, -67.8117],
'Asia/Thimphu': [27.4833, 89.6333],
'Africa/Gaborone': [-24.6569, 25.9086],
'Europe/Minsk': [53.9022, 27.5618],
'America/Halifax': [44.6475, -63.5906],
'America/Moncton': [46.1328, -64.7714],
'America/Toronto': [43.7417, -79.3733],
'America/Thunder_Bay': [48.3822, -89.2461],
'America/Iqaluit': [63.7598, -68.5107],
'America/Winnipeg': [49.8844, -97.1464],
'America/Regina': [50.4547, -104.6067],
'America/Swift_Current': [50.2881, -107.7939],
'America/Edmonton': [53.5344, -113.4903],
'America/Yellowknife': [62.4709, -114.4053],
'America/Creston': [49.09, -116.51],
'America/Dawson_Creek': [55.7606, -120.2356],
'America/Whitehorse': [60.7029, -135.0691],
'America/Vancouver': [49.25, -123.1],
'Africa/Bangui': [4.3732, 18.5628],
'Europe/Zurich': [47.3786, 8.54],
'America/Santiago': [-33.45, -70.6667],
'America/Punta_Arenas': [-53.1627, -70.9081],
'Africa/Douala': [4.05, 9.7],
'Asia/Shanghai': [31.1667, 121.4667],
'Asia/Urumqi': [43.8225, 87.6125],
'America/Bogota': [4.6126, -74.0705],
'America/Havana': [23.1367, -82.3589],
'Asia/Nicosia': [35.1725, 33.365],
'Asia/Famagusta': [35.1167, 33.95],
'Europe/Prague': [50.0833, 14.4167],
'Europe/Berlin': [52.5167, 13.3833],
'Africa/Djibouti': [11.595, 43.1481],
'Europe/Copenhagen': [55.6761, 12.5689],
'America/Santo_Domingo': [18.4764, -69.8933],
'Africa/Algiers': [36.7764, 3.0586],
'America/Guayaquil': [-2.1833, -79.8833],
'Europe/Tallinn': [59.4372, 24.745],
'Africa/Cairo': [30.0561, 31.2394],
'Africa/Asmara': [15.3333, 38.9167],
'Europe/Madrid': [40.4167, -3.7167],
'Africa/Addis_Ababa': [9.0272, 38.7369],
'Europe/Helsinki': [60.1756, 24.9342],
'Europe/Paris': [48.8566, 2.3522],
'Africa/Libreville': [0.3901, 9.4544],
'Asia/Tbilisi': [41.7225, 44.7925],
'America/Cayenne': [4.933, -52.33],
'Africa/Accra': [5.6037, -0.187],
'Europe/Gibraltar': [36.1324, -5.3781],
'America/Nuuk': [64.175, -51.7333],
'America/Scoresbysund': [70.4853, -21.9667],
'Africa/Conakry': [9.5092, -13.7122],
'Africa/Malabo': [3.7521, 8.7737],
'Europe/Athens': [37.9842, 23.7281],
'Africa/Bissau': [11.8592, -15.5956],
'Asia/Hong_Kong': [22.305, 114.185],
'America/Tegucigalpa': [14.0942, -87.2067],
'Europe/Zagreb': [45.8, 15.95],
'America/Port-au-Prince': [18.5425, -72.3386],
'Europe/Budapest': [47.4983, 19.0408],
'Asia/Jakarta': [-6.2146, 106.8451],
'Asia/Pontianak': [-0.0206, 109.3414],
'Asia/Makassar': [-5.1331, 119.4136],
'Asia/Jayapura': [-2.5333, 140.7167],
'Europe/Dublin': [53.3497, -6.2603],
'Asia/Jerusalem': [31.7833, 35.2167],
'Asia/Kolkata': [22.5411, 88.3378],
'Asia/Baghdad': [33.35, 44.4167],
'Atlantic/Reykjavik': [64.1475, -21.935],
'Europe/Rome': [41.8931, 12.4828],
'Asia/Amman': [31.95, 35.9333],
'Asia/Tokyo': [35.6897, 139.6922],
'Africa/Nairobi': [-1.2864, 36.8172],
'Asia/Bishkek': [42.8667, 74.5667],
'Asia/Phnom_Penh': [11.5696, 104.921],
'Pacific/Tarawa': [1.3382, 173.0176],
'Asia/Almaty': [43.25, 76.9],
'Asia/Qyzylorda': [44.8479, 65.4999],
'Asia/Qostanay': [53.2144, 63.6246],
'Asia/Aqtobe': [50.3, 57.1667],
'Asia/Aqtau': [43.65, 51.15],
'Asia/Atyrau': [47.1167, 51.8833],
'Asia/Oral': [51.2333, 51.3667],
'Asia/Beirut': [33.8869, 35.5131],
'Europe/Vaduz': [47.1415, 9.5215],
'Asia/Colombo': [6.9167, 79.8333],
'Africa/Monrovia': [6.3106, -10.8047],
'Africa/Maseru': [-29.31, 27.48],
'Europe/Vilnius': [54.6833, 25.2833],
'Europe/Luxembourg': [49.6106, 6.1328],
'Europe/Riga': [56.9475, 24.1069],
'Africa/Tripoli': [32.8752, 13.1875],
'Africa/Casablanca': [33.5992, -7.62],
'Europe/Monaco': [43.7396, 7.4069],
'Europe/Podgorica': [42.4397, 19.2661],
'Indian/Antananarivo': [-18.9386, 47.5214],
'Pacific/Majuro': [7.0918, 171.3802],
'Europe/Skopje': [41.9833, 21.4333],
'Africa/Bamako': [12.6458, -7.9922],
'Asia/Ulaanbaatar': [47.9203, 106.9172],
'Asia/Hovd': [48.0167, 91.5667],
'Africa/Nouakchott': [18.0858, -15.9785],
'Africa/Blantyre': [-15.7861, 35.0058],
'America/Mexico_City': [19.4333, -99.1333],
'America/Cancun': [21.1606, -86.8475],
'America/Merida': [20.97, -89.62],
'America/Monterrey': [25.6667, -100.3],
'America/Matamoros': [25.533, -103.25],
'America/Mazatlan': [23.22, -106.42],
'America/Chihuahua': [28.6353, -106.0889],
'America/Ojinaga': [29.5644, -104.4164],
'America/Hermosillo': [29.0989, -110.9542],
'America/Tijuana': [32.525, -117.0333],
'Asia/Kuala_Lumpur': [3.1478, 101.6953],
'Asia/Kuching': [1.5397, 110.3542],
'Africa/Maputo': [-25.9153, 32.5764],
'Africa/Windhoek': [-22.57, 17.0836],
'Pacific/Noumea': [-22.2625, 166.4443],
'Africa/Niamey': [13.5086, 2.1111],
'Africa/Lagos': [6.45, 3.4],
'America/Managua': [12.15, -86.2667],
'Europe/Amsterdam': [52.3667, 4.8833],
'Europe/Oslo': [59.9111, 10.7528],
'Asia/Kathmandu': [27.7167, 85.3667],
'Pacific/Auckland': [-36.85, 174.7833],
'Asia/Muscat': [23.6139, 58.5922],
'America/Lima': [-12.05, -77.0333],
'Pacific/Port_Moresby': [-9.4789, 147.1494],
'Asia/Manila': [14.6, 120.9833],
'Asia/Karachi': [24.86, 67.01],
'Europe/Warsaw': [52.2167, 21.0333],
'Europe/Lisbon': [38.7452, -9.1604],
'America/Asuncion': [-25.3, -57.6333],
'Europe/Bucharest': [44.4, 26.0833],
'Europe/Belgrade': [44.8167, 20.4667],
'Europe/Kaliningrad': [54.7167, 20.5],
'Europe/Moscow': [55.7558, 37.6178],
'Europe/Simferopol': [44.9484, 34.1],
'Europe/Kirov': [58.6, 49.65],
'Europe/Volgograd': [48.7086, 44.5147],
'Europe/Astrakhan': [46.3333, 48.0167],
'Europe/Saratov': [51.5333, 46.0],
'Europe/Ulyanovsk': [54.3167, 48.3667],
'Europe/Samara': [53.1833, 50.1167],
'Asia/Yekaterinburg': [56.8356, 60.6128],
'Asia/Omsk': [54.9667, 73.3833],
'Asia/Novosibirsk': [55.0333, 82.9167],
'Asia/Barnaul': [53.3567, 83.7872],
'Asia/Tomsk': [56.4886, 84.9522],
'Asia/Novokuznetsk': [53.75, 87.1167],
'Asia/Krasnoyarsk': [56.0167, 92.8667],
'Asia/Irkutsk': [52.2833, 104.3],
'Asia/Chita': [52.0333, 113.5],
'Asia/Yakutsk': [62.0272, 129.7319],
'Asia/Khandyga': [62.666, 135.6],
'Asia/Vladivostok': [43.1167, 131.9],
'Asia/Magadan': [59.5667, 150.8],
'Asia/Srednekolymsk': [67.45, 153.7],
'Asia/Anadyr': [64.7333, 177.5167],
'Africa/Kigali': [-1.9536, 30.0606],
'Asia/Riyadh': [24.65, 46.71],
'Africa/Khartoum': [15.6031, 32.5265],
'Europe/Stockholm': [59.3294, 18.0686],
'Asia/Singapore': [1.3, 103.8],
'Europe/Ljubljana': [46.05, 14.5167],
'Europe/Bratislava': [48.1447, 17.1128],
'Africa/Freetown': [8.4833, -13.2331],
'Europe/San_Marino': [43.932, 12.4484],
'Africa/Dakar': [14.7319, -17.4572],
'Africa/Mogadishu': [2.0408, 45.3425],
'America/Paramaribo': [5.8667, -55.1667],
'Africa/Juba': [4.85, 31.6],
'Africa/Sao_Tome': [0.3333, 6.7333],
'America/Grand_Turk': [21.4664, -71.136],
'Africa/Lome': [6.1319, 1.2228],
'Asia/Bangkok': [13.75, 100.5167],
'Asia/Dushanbe': [38.5731, 68.7864],
'Asia/Dili': [-8.5586, 125.5736],
'Asia/Ashgabat': [37.95, 58.3833],
'Africa/Tunis': [36.8008, 10.18],
'Europe/Istanbul': [41.01, 28.9603],
'America/Port_of_Spain': [10.6667, -61.5167],
'Pacific/Funafuti': [-8.5167, 179.2167],
'Africa/Kampala': [0.3136, 32.5811],
'America/Montevideo': [-34.8667, -56.1667],
'Asia/Samarkand': [39.6542, 66.9597],
'Asia/Tashkent': [41.3, 69.2667],
'Pacific/Apia': [-13.8333, -171.8333],
'Asia/Aden': [12.8, 45.0333],
'Africa/Johannesburg': [-26.2044, 28.0416],
'Africa/Lusaka': [-15.4167, 28.2833],
'Africa/Harare': [-17.8292, 31.0522],
'Africa/Abidjan': [5.359952, -4.008256],
'Africa/Banjul': [13.45129, -16.573],
'Africa/Brazzaville': [-4.26336, 15.242885],
'Africa/Ceuta': [35.888241, -5.31618],
'Africa/Dar_es_Salaam': [-6.792354, 39.208328],
'Africa/El_Aaiun': [27.154512, -13.1953921],
'Africa/Kinshasa': [-4.3217055, 15.3125974],
'Africa/Lubumbashi': [-11.6642316, 27.4826264],
'Africa/Mbabane': [-26.325745, 31.144663],
'Africa/Ndjamena': [12.1191543, 15.0502758],
'America/Adak': [51.8666057, -176.64575],
'America/Anchorage': [61.2163129, -149.894852],
'America/Anguilla': [18.1954947, -63.0750234],
'America/Antigua': [17.1037151, -61.7904505],
'America/Argentina/Jujuy': [-23.3161458, -65.7595288],
'America/Argentina/Tucuman': [-26.5643582, -64.882397],
'America/Aruba': [12.4902998, -69.9609842],
'America/Atikokan': [48.762526, -91.624603],
'America/Bahia': [-12.285251, -41.9294776],
'America/Bahia_Banderas': [20.99083, -97.39361],
'America/Barbados': [13.1500331, -59.5250305],
'America/Belize': [16.8259793, -88.7600927],
'America/Blanc-Sablon': [51.4121624, -57.2018488],
'America/Boise': [43.6166163, -116.200886],
'America/Cambridge_Bay': [69.1178442, -105.0603881],
'America/Caracas': [10.506098, -66.9146017],
'America/Cayman': [1.654606, -74.8004171],
'America/Chicago': [41.8755616, -87.6244212],
'America/Costa_Rica': [10.2735633, -84.0739102],
'America/Curacao': [12.1176488, -68.9309263],
'America/Danmarkshavn': [76.769517, -18.6736769],
'America/Dawson': [32.7410762, -101.9576048],
'America/Denver': [39.7392364, -104.9848623],
'America/Detroit': [42.3315509, -83.0466403],
'America/Dominica': [19.0974031, -70.3028026],
'America/El_Salvador': [13.8000382, -88.9140683],
'America/Fort_Nelson': [58.8062066, -122.6942704],
'America/Glace_Bay': [46.19695, -59.95698],
'America/Goose_Bay': [53.333333, -60.416667],
'America/Grenada': [12.1360374, -61.6904045],
'America/Guadeloupe': [16.2490067, -61.5650444],
'America/Guatemala': [15.6871007, -90.1226545],
'America/Guyana': [4.8417097, -58.6416891],
'America/Indiana/Indianapolis': [39.7683331, -86.1583502],
'America/Indiana/Knox': [41.2958751, -86.6250139],
'America/Indiana/Marengo': [32.201002, -87.7569365],
'America/Indiana/Petersburg': [38.4919935, -87.278624],
'America/Indiana/Tell_City': [37.9514447, -86.7677663],
'America/Indiana/Vevay': [38.7478401, -85.0671725],
'America/Indiana/Vincennes': [48.8474508, 2.4396714],
'America/Indiana/Winamac': [41.0514299, -86.6030648],
'America/Inuvik': [68.3602632, -133.720386],
'America/Jamaica': [18.1850507, -77.3947693],
'America/Juneau': [58.3019496, -134.419734],
'America/Kentucky/Louisville': [38.2542376, -85.759407],
'America/Kentucky/Monticello': [42.617236, 8.9546269],
'America/Kralendijk': [12.1471741, -68.2740783],
'America/La_Paz': [-16.4955455, -68.1336229],
'America/Los_Angeles': [34.0536909, -118.242766],
'America/Lower_Princes': [51.4407039, -0.4215339],
'America/Marigot': [18.0668544, -63.0848869],
'America/Martinique': [14.6367927, -61.0158269],
'America/Menominee': [45.5785741, -87.562159],
'America/Metlakatla': [55.119358, -131.5747417],
'America/Miquelon': [47.045425, -56.3190627],
'America/Montserrat': [16.7417041, -62.1916844],
'America/Nassau': [25.0783456, -77.3383331],
'America/New_York': [40.7127281, -74.0060152],
'America/Nipigon': [49.8009665, -88.3242875],
'America/Nome': [64.4989922, -165.3987994],
'America/Noronha': [-8.7530783, -35.098822],
'America/North_Dakota/Beulah': [47.26334, -101.777946],
'America/North_Dakota/Center': [47.118507385253906, -101.29815673828125],
'America/North_Dakota/New_Salem': [39.7075473, -90.8476304],
'America/Panama': [8.559559, -81.1308434],
'America/Pangnirtung': [66.1480197, -65.7172826],
'America/Phoenix': [33.4484367, -112.0741417],
'America/Puerto_Rico': [18.1989769, -66.2615222],
'America/Rainy_River': [48.722679, -94.564819],
'America/Rankin_Inlet': [62.81732, -92.08324],
'America/Resolute': [74.697029, -94.840851],
'America/Sitka': [57.0524973, -135.337612],
'America/St_Barthelemy': [17.8957043, -62.8508372],
'America/St_Johns': [29.91218, -81.40989],
'America/St_Kitts': [17.33333, -62.75],
'America/St_Lucia': [-27.5, 153],
'America/St_Thomas': [11.6403162, 76.3021009],
'America/St_Vincent': [45.75082, 7.64815],
'America/Thule': [77.4686357, -69.2222746],
'America/Tortola': [18.4210568, -64.6388325],
'America/Yakutat': [59.5727345, -139.5783124],
'Antarctica/Casey': [-66.2825954, 110.5266062],
'Antarctica/Davis': [-68.5766666, 77.967496],
'Antarctica/DumontDUrville': [-66.6632764, 140.0010954],
'Antarctica/Macquarie': [-67.6028962, 62.8737541],
'Antarctica/Mawson': [-35.3633679, 149.0988944],
'Antarctica/McMurdo': [-77.8483347, 166.6683349],
'Antarctica/Palmer': [61.5995703, -149.11109],
'Antarctica/Rothera': [-67.5677836, -68.127636],
'Antarctica/Syowa': [34.9378883, 135.0174633],
'Antarctica/Troll': [-72.0116589, 2.5355412],
'Antarctica/Vostok': [-10.0620702, -152.3125816],
'Arctic/Longyearbyen': [78.2231558, 15.6463656],
'Asia/Bahrain': [26.1551249, 50.5344606],
'Asia/Brunei': [4.4137155, 114.5653908],
'Asia/Choibalsan': [48.8967118, 115.4966781],
'Asia/Damascus': [33.5130695, 36.3095814],
'Asia/Gaza': [31.4432234, 34.360007],
'Asia/Hebron': [31.528902, 35.0944873],
'Asia/Ho_Chi_Minh': [10.7238881, 106.7313051],
'Asia/Kamchatka': [57.1914882, 160.0383819],
'Asia/Kuwait': [29.2733964, 47.4979476],
'Asia/Macau': [22.1757605, 113.5514142],
'Asia/Pyongyang': [39.0167979, 125.7473609],
'Asia/Qatar': [25.3336984, 51.2295295],
'Asia/Sakhalin': [50.159476, 143.0264412],
'Asia/Seoul': [37.5666791, 126.9782914],
'Asia/Taipei': [25.0375198, 121.5636796],
'Asia/Tehran': [35.6892523, 51.3896004],
'Asia/Ust-Nera': [64.566376, 143.237839],
'Asia/Vientiane': [17.9640988, 102.6133707],
'Asia/Yangon': [16.7967129, 96.1609916],
'Atlantic/Azores': [37.8085274, -25.4730853],
'Atlantic/Bermuda': [32.3018217, -64.7603583],
'Atlantic/Canary': [28.2935785, -16.6214471],
'Atlantic/Cape_Verde': [16.0000552, -24.0083947],
'Atlantic/Faroe': [62.0448724, -7.0322972],
'Atlantic/Madeira': [32.7517488, -16.981752],
'Atlantic/South_Georgia': [-54.25, -36.75],
'Atlantic/Stanley': [-51.6948723, -57.8452297],
'Atlantic/St_Helena': [-15.9654552, -5.7025756],
'Australia/Eucla': [-31.6768407, 128.8865164],
'Australia/Lindeman': [-20.444732, 149.0432115],
'Australia/Lord_Howe': [-31.5540166, 159.0856256],
'Europe/Andorra': [42.5407167, 1.5732033],
'Europe/Busingen': [47.6966197, 8.6907071],
'Europe/Chisinau': [47.0245117, 28.8322923],
'Europe/Guernsey': [49.4566233, -2.5822348],
'Europe/Isle_of_Man': [54.1936805, -4.5591148],
'Europe/Jersey': [49.2214561, -2.1358386],
'Europe/Kiev': [50.4500336, 30.5241361],
'Europe/London': [51.5073219, -0.1276474],
'Europe/Malta': [35.8885993, 14.4476911],
'Europe/Mariehamn': [60.102423, 19.94126],
'Europe/Tirane': [41.3305141, 19.8255629],
'Europe/Uzhgorod': [48.6223732, 22.3022569],
'Europe/Vatican': [41.9034912, 12.4528349],
'Europe/Zaporozhye': [47.8507859, 35.1182867],
'Indian/Chagos': [-6.6847676, 71.3833275],
'Indian/Christmas': [-10, 70],
'Indian/Cocos': [-14.1811222, -44.5382117],
'Indian/Comoro': [-5.9259567, 138.6326357],
'Indian/Kerguelen': [-49.237442, 69.622759],
'Indian/Mahe': [-10, 70],
'Indian/Maldives': [4.7064352, 73.3287853],
'Indian/Mauritius': [-20.2759451, 57.5703566],
'Indian/Mayotte': [-12.823048, 45.1520755],
'Indian/Reunion': [-21.1307379, 55.5364801],
// TODO: Pacific/Bougainville
// TODO: Pacific/Chatham
// TODO: Pacific/Chuuk
// TODO: Pacific/Easter
// TODO: Pacific/Efate
// TODO: Pacific/Fakaofo
// TODO: Pacific/Fiji
'Pacific/Galapagos': [-0.6288151, -90.3638752],
'Pacific/Gambier': [-23.346037, -134.4805901],
'Pacific/Guadalcanal': [-9.5984209, 160.1485117],
'Pacific/Guam': [13.4501257, 144.757551],
// TODO: Pacific/Honolulu
// TODO: Pacific/Kanton
// TODO: Pacific/Kiritimati
// TODO: Pacific/Kosrae
// TODO: Pacific/Kwajalein
// TODO: Pacific/Marquesas
// TODO: Pacific/Midway
// TODO: Pacific/Nauru
// TODO: Pacific/Niue
// TODO: Pacific/Norfolk
// TODO: Pacific/Palau
// TODO: Pacific/Pitcairn
// TODO: Pacific/Pohnpei
// TODO: Pacific/Rarotonga
// TODO: Pacific/Saipan
// TODO: Pacific/Tahiti
// TODO: Pacific/Tongatapu
// TODO: Pacific/Wake
// TODO: Pacific/Wallis
}
export default function getLocationFromTimezone(timezoneName: string) {
if (!(timezoneName in TIMEZONE_LOCATION_MAP)) {
throw new Error(
'Cannot detect location based on timezone. Please set location manually.'
)
}
const [latitude, longitude] = (
TIMEZONE_LOCATION_MAP as unknown as { [key: string]: [number, number] }
)[timezoneName]
return { latitude, longitude }
} | the_stack |
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js";
import * as msRest from "@azure/ms-rest-js";
export { BaseResource, CloudError };
/**
* Resource provider available operation display model
*/
export interface AvailableOperationDisplay {
/**
* Description of the operation for display purposes
*/
description?: string;
/**
* Name of the operation for display purposes
*/
operation?: string;
/**
* Name of the provider for display purposes
*/
provider?: string;
/**
* Name of the resource type for display purposes
*/
resource?: string;
}
/**
* Available operation display property service specification metrics item
*/
export interface AvailableOperationDisplayPropertyServiceSpecificationMetricsItem {
/**
* Metric's aggregation type for e.g. (Average, Total). Possible values include: 'Average',
* 'Total'
*/
aggregationType: AggregationType;
/**
* Metric's description
*/
displayDescription: string;
/**
* Human readable metric's name
*/
displayName: string;
/**
* Metric's name/id
*/
name: string;
/**
* Metric's unit
*/
unit: string;
}
/**
* List of available operation display property service specification metrics
*/
export interface AvailableOperationDisplayPropertyServiceSpecificationMetricsList {
/**
* Metric specifications of operation
*/
metricSpecifications?: AvailableOperationDisplayPropertyServiceSpecificationMetricsItem[];
}
/**
* Resource provider available operation model
*/
export interface AvailableOperation {
/**
* The list of operations
*/
display?: AvailableOperationDisplay;
/**
* Indicating whether the operation is a data action or not. Default value: false.
*/
isDataAction?: boolean;
/**
* {resourceProviderNamespace}/{resourceType}/{read|write|delete|action}
*/
name?: string;
/**
* The origin of operation. Possible values include: 'user', 'system', 'user,system'
*/
origin?: OperationOrigin;
/**
* The list of specification's service metrics
*/
serviceSpecification?: AvailableOperationDisplayPropertyServiceSpecificationMetricsList;
}
/**
* Error properties
*/
export interface CSRPErrorBody {
/**
* Error's code
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly code?: string;
/**
* Error's details
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly details?: CSRPErrorBody[];
/**
* Error's message
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly message?: string;
/**
* Error's target
*/
target?: string;
}
/**
* General error model
*/
export interface CSRPError {
/**
* Error's body
*/
error?: CSRPErrorBody;
}
/**
* The purchase SKU for CloudSimple paid resources
*/
export interface Sku {
/**
* The capacity of the SKU
*/
capacity?: string;
/**
* dedicatedCloudNode example: 8 x Ten-Core Intel® Xeon® Processor E5-2640 v4 2.40GHz 25MB Cache
* (90W); 12 x 64GB PC4-19200 2400MHz DDR4 ECC Registered DIMM, ...
*/
description?: string;
/**
* If the service has different generations of hardware, for the same SKU, then that can be
* captured here
*/
family?: string;
/**
* The name of the SKU for VMWare CloudSimple Node
*/
name: string;
/**
* The tier of the SKU
*/
tier?: string;
}
/**
* Dedicated cloud node model
*/
export interface DedicatedCloudNode extends BaseResource {
/**
* /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/dedicatedCloudNodes/{dedicatedCloudNodeName}
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* Azure region
*/
location: string;
/**
* {dedicatedCloudNodeName}
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* Availability Zone id, e.g. "az1"
*/
availabilityZoneId: string;
/**
* Availability Zone name, e.g. "Availability Zone 1"
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly availabilityZoneName?: string;
/**
* VMWare Cloud Rack Name
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly cloudRackName?: string;
/**
* date time the resource was created
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly created?: any;
/**
* count of nodes to create
*/
nodesCount: number;
/**
* Placement Group id, e.g. "n1"
*/
placementGroupId: string;
/**
* Placement Name, e.g. "Placement Group 1"
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly placementGroupName?: string;
/**
* Private Cloud Id
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly privateCloudId?: string;
/**
* Resource Pool Name
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly privateCloudName?: string;
/**
* The provisioning status of the resource
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: string;
/**
* purchase id
*/
purchaseId: string;
/**
* SKU's id
*/
id1: string;
/**
* SKU's name
*/
name1: string;
/**
* Node status, indicates is private cloud set up on this node or not. Possible values include:
* 'unused', 'used'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly status?: NodeStatus;
/**
* VMWare Cluster Name
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly vmwareClusterName?: string;
/**
* Dedicated Cloud Nodes SKU
*/
sku?: Sku;
/**
* Dedicated Cloud Nodes tags
*/
tags?: { [propertyName: string]: string };
/**
* {resourceProviderNamespace}/{resourceType}
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
}
/**
* Dedicated cloud service model
*/
export interface DedicatedCloudService extends BaseResource {
/**
* /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/dedicatedCloudServices/{dedicatedCloudServiceName}
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* Azure region
*/
location: string;
/**
* {dedicatedCloudServiceName}
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* gateway Subnet for the account. It will collect the subnet address and always treat it as /28
*/
gatewaySubnet: string;
/**
* indicates whether account onboarded or not in a given region. Possible values include:
* 'notOnBoarded', 'onBoarded', 'onBoardingFailed', 'onBoarding'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly isAccountOnboarded?: OnboardingStatus;
/**
* total nodes purchased
*/
nodes?: number;
/**
* link to a service management web portal
*/
serviceURL?: string;
/**
* The list of tags
*/
tags?: { [propertyName: string]: string };
/**
* {resourceProviderNamespace}/{resourceType}
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
}
/**
* Operation error model
*/
export interface OperationError {
/**
* Error's code
*/
code?: string;
/**
* Error's message
*/
message?: string;
}
/**
* Operation status response
*/
export interface OperationResource {
/**
* End time of the operation
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly endTime?: Date;
/**
* Error Message if operation failed
*/
error?: OperationError;
/**
* Operation Id
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* Operation ID
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* Start time of the operation
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly startTime?: Date;
/**
* Operation status
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly status?: string;
}
/**
* General patch payload modal
*/
export interface PatchPayload {
/**
* The tags key:value pairs
*/
tags?: { [propertyName: string]: string };
}
/**
* Resource pool model
*/
export interface ResourcePool {
/**
* resource pool id (privateCloudId:vsphereId)
*/
id: string;
/**
* Azure region
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly location?: string;
/**
* {ResourcePoolName}
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* The Private Cloud Id
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly privateCloudId?: string;
/**
* Hierarchical resource pool name
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly fullName?: string;
/**
* {resourceProviderNamespace}/{resourceType}
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
}
/**
* Virtual disk controller model
*/
export interface VirtualDiskController {
/**
* Controller's id
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* The display name of Controller
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* dik controller subtype (VMWARE_PARAVIRTUAL, BUS_PARALLEL, LSI_PARALLEL, LSI_SAS)
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly subType?: string;
/**
* disk controller type (SCSI)
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
}
/**
* Virtual disk model
*/
export interface VirtualDisk {
/**
* Disk's Controller id
*/
controllerId: string;
/**
* Disk's independence mode type. Possible values include: 'persistent',
* 'independent_persistent', 'independent_nonpersistent'
*/
independenceMode: DiskIndependenceMode;
/**
* Disk's total size
*/
totalSize: number;
/**
* Disk's id
*/
virtualDiskId?: string;
/**
* Disk's display name
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly virtualDiskName?: string;
}
/**
* Virtual network model
*/
export interface VirtualNetwork {
/**
* can be used in vm creation/deletion
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly assignable?: boolean;
/**
* virtual network id (privateCloudId:vsphereId)
*/
id: string;
/**
* Azure region
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly location?: string;
/**
* {VirtualNetworkName}
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* The Private Cloud id
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly privateCloudId?: string;
/**
* {resourceProviderNamespace}/{resourceType}
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
}
/**
* Virtual NIC model
*/
export interface VirtualNic {
/**
* NIC ip address
*/
ipAddresses?: string[];
/**
* NIC MAC address
*/
macAddress?: string;
/**
* Virtual Network
*/
network: VirtualNetwork;
/**
* NIC type. Possible values include: 'E1000', 'E1000E', 'PCNET32', 'VMXNET', 'VMXNET2',
* 'VMXNET3'
*/
nicType: NICType;
/**
* Is NIC powered on/off on boot
*/
powerOnBoot?: boolean;
/**
* NIC id
*/
virtualNicId?: string;
/**
* NIC name
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly virtualNicName?: string;
}
/**
* Virtual machine template model
*/
export interface VirtualMachineTemplate {
/**
* virtual machine template id (privateCloudId:vsphereId)
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* Azure region
*/
location?: string;
/**
* {virtualMachineTemplateName}
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* The amount of memory
*/
amountOfRam?: number;
/**
* The list of Virtual Disk Controllers
*/
controllers?: VirtualDiskController[];
/**
* The description of Virtual Machine Template
*/
description?: string;
/**
* The list of Virtual Disks
*/
disks?: VirtualDisk[];
/**
* Expose Guest OS or not
*/
exposeToGuestVM?: boolean;
/**
* The Guest OS
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly guestOS?: string;
/**
* The Guest OS types
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly guestOSType?: string;
/**
* The list of Virtual NICs
*/
nics?: VirtualNic[];
/**
* The number of CPU cores
*/
numberOfCores?: number;
/**
* path to folder
*/
path?: string;
/**
* The Private Cloud Id
*/
privateCloudId: string;
/**
* The list of VSphere networks
*/
vSphereNetworks?: string[];
/**
* The tags from VSphere
*/
vSphereTags?: string[];
/**
* The VMware tools version
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly vmwaretools?: string;
/**
* {resourceProviderNamespace}/{resourceType}
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
}
/**
* Private cloud model
*/
export interface PrivateCloud {
/**
* Azure Id, e.g.
* "/subscriptions/4da99247-a172-4ed6-8ae9-ebed2d12f839/providers/Microsoft.VMwareCloudSimple/privateClouds/cloud123"
*/
id?: string;
/**
* Location where private cloud created, e.g "westus"
*/
location?: string;
/**
* Private cloud name
*/
name?: string;
/**
* Availability Zone id, e.g. "az1"
*/
availabilityZoneId?: string;
/**
* Availability Zone name, e.g. "Availability Zone 1"
*/
availabilityZoneName?: string;
/**
* Number of clusters
*/
clustersNumber?: number;
/**
* User's emails who created cloud
*/
createdBy?: string;
/**
* When private cloud was created
*/
createdOn?: Date;
/**
* Array of DNS servers
*/
dnsServers?: string[];
/**
* Expiration date of PC
*/
expires?: string;
/**
* Nsx Type, e.g. "Advanced"
*/
nsxType?: string;
/**
* Placement Group id, e.g. "n1"
*/
placementGroupId?: string;
/**
* Placement Group name
*/
placementGroupName?: string;
/**
* Id of a private cloud
*/
privateCloudId?: string;
/**
* The list of Resource Pools
*/
resourcePools?: ResourcePool[];
/**
* Private Cloud state, e.g. "operational"
*/
state?: string;
/**
* Number of cores
*/
totalCpuCores?: number;
/**
* Number of nodes
*/
totalNodes?: number;
/**
* Memory size
*/
totalRam?: number;
/**
* Disk space in TB
*/
totalStorage?: number;
/**
* Virtualization type e.g. "vSphere"
*/
privateCloudPropertiesType?: string;
/**
* e.g. "6.5u2"
*/
vSphereVersion?: string;
/**
* FQDN for vcenter access
*/
vcenterFqdn?: string;
/**
* Vcenter ip address
*/
vcenterRefid?: string;
/**
* The list of Virtual Machine Templates
*/
virtualMachineTemplates?: VirtualMachineTemplate[];
/**
* The list of Virtual Networks
*/
virtualNetworks?: VirtualNetwork[];
/**
* Is Vrops enabled/disabled
*/
vrOpsEnabled?: boolean;
/**
* Azure Resource type. Possible values include: 'Microsoft.VMwareCloudSimple/privateClouds'
*/
type?: PrivateCloudResourceType;
}
/**
* SKU availability model
*/
export interface SkuAvailability {
/**
* CloudSimple Availability Zone id
*/
dedicatedAvailabilityZoneId?: string;
/**
* CloudSimple Availability Zone Name
*/
dedicatedAvailabilityZoneName?: string;
/**
* CloudSimple Placement Group Id
*/
dedicatedPlacementGroupId?: string;
/**
* CloudSimple Placement Group name
*/
dedicatedPlacementGroupName?: string;
/**
* indicates how many resources of a given SKU is available in a AZ->PG
*/
limit: number;
/**
* resource type e.g. DedicatedCloudNodes
*/
resourceType?: string;
/**
* sku id
*/
skuId?: string;
/**
* sku name
*/
skuName?: string;
}
/**
* User name model
*/
export interface UsageName {
/**
* e.g. "Virtual Machines"
*/
localizedValue?: string;
/**
* resource type or resource type sku name, e.g. virtualMachines
*/
value?: string;
}
/**
* Usage model
*/
export interface Usage {
/**
* The current usage value. Default value: 0.
*/
currentValue: number;
/**
* limit of a given sku in a region for a subscription. The maximum permitted value for the usage
* quota. If there is no limit, this value will be -1. Default value: 0.
*/
limit: number;
/**
* Usage name value and localized name
*/
name?: UsageName;
/**
* The usages' unit. Possible values include: 'Count', 'Bytes', 'Seconds', 'Percent',
* 'CountPerSecond', 'BytesPerSecond'
*/
unit?: UsageCount;
}
/**
* Virtual machine model
*/
export interface VirtualMachine extends BaseResource {
/**
* /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/virtualMachines/{virtualMachineName}
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* Azure region
*/
location: string;
/**
* {virtualMachineName}
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* The amount of memory
*/
amountOfRam: number;
/**
* The list of Virtual Disks' Controllers
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly controllers?: VirtualDiskController[];
/**
* The list of Virtual Disks
*/
disks?: VirtualDisk[];
/**
* The DNS name of Virtual Machine in VCenter
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly dnsname?: string;
/**
* Expose Guest OS or not
*/
exposeToGuestVM?: boolean;
/**
* The path to virtual machine folder in VCenter
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly folder?: string;
/**
* The name of Guest OS
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly guestOS?: string;
/**
* The Guest OS type. Possible values include: 'linux', 'windows', 'other'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly guestOSType?: GuestOSType;
/**
* The list of Virtual NICs
*/
nics?: VirtualNic[];
/**
* The number of CPU cores
*/
numberOfCores: number;
/**
* Password for login
*/
password?: string;
/**
* Private Cloud Id
*/
privateCloudId: string;
/**
* The provisioning status of the resource
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: string;
/**
* The public ip of Virtual Machine
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly publicIP?: string;
/**
* Virtual Machines Resource Pool
*/
resourcePool?: ResourcePool;
/**
* The status of Virtual machine. Possible values include: 'running', 'suspended', 'poweredoff',
* 'updating', 'deallocating', 'deleting'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly status?: VirtualMachineStatus;
/**
* Virtual Machine Template Id
*/
templateId?: string;
/**
* Username for login
*/
username?: string;
/**
* The list of Virtual VSphere Networks
*/
vSphereNetworks?: string[];
/**
* The internal id of Virtual Machine in VCenter
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly vmId?: string;
/**
* VMware tools version
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly vmwaretools?: string;
/**
* The list of tags
*/
tags?: { [propertyName: string]: string };
/**
* {resourceProviderNamespace}/{resourceType}
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
}
/**
* List of virtual machine stop modes
*/
export interface VirtualMachineStopMode {
/**
* mode indicates a type of stop operation - reboot, suspend, shutdown or power-off. Possible
* values include: 'reboot', 'suspend', 'shutdown', 'poweroff'
*/
mode?: StopMode;
}
/**
* Optional Parameters.
*/
export interface DedicatedCloudNodesListBySubscriptionOptionalParams extends msRest.RequestOptionsBase {
/**
* The filter to apply on the list operation
*/
filter?: string;
/**
* The maximum number of record sets to return
*/
top?: number;
/**
* to be used by nextLink implementation
*/
skipToken?: string;
}
/**
* Optional Parameters.
*/
export interface DedicatedCloudNodesListByResourceGroupOptionalParams extends msRest.RequestOptionsBase {
/**
* The filter to apply on the list operation
*/
filter?: string;
/**
* The maximum number of record sets to return
*/
top?: number;
/**
* to be used by nextLink implementation
*/
skipToken?: string;
}
/**
* Optional Parameters.
*/
export interface DedicatedCloudNodesUpdateOptionalParams extends msRest.RequestOptionsBase {
/**
* The tags key:value pairs
*/
tags?: { [propertyName: string]: string };
}
/**
* Optional Parameters.
*/
export interface DedicatedCloudServicesListBySubscriptionOptionalParams extends msRest.RequestOptionsBase {
/**
* The filter to apply on the list operation
*/
filter?: string;
/**
* The maximum number of record sets to return
*/
top?: number;
/**
* to be used by nextLink implementation
*/
skipToken?: string;
}
/**
* Optional Parameters.
*/
export interface DedicatedCloudServicesListByResourceGroupOptionalParams extends msRest.RequestOptionsBase {
/**
* The filter to apply on the list operation
*/
filter?: string;
/**
* The maximum number of record sets to return
*/
top?: number;
/**
* to be used by nextLink implementation
*/
skipToken?: string;
}
/**
* Optional Parameters.
*/
export interface DedicatedCloudServicesUpdateOptionalParams extends msRest.RequestOptionsBase {
/**
* The tags key:value pairs
*/
tags?: { [propertyName: string]: string };
}
/**
* Optional Parameters.
*/
export interface SkusAvailabilityListOptionalParams extends msRest.RequestOptionsBase {
/**
* sku id, if no sku is passed availability for all skus will be returned
*/
skuId?: string;
}
/**
* Optional Parameters.
*/
export interface UsagesListOptionalParams extends msRest.RequestOptionsBase {
/**
* The filter to apply on the list operation. only name.value is allowed here as a filter e.g.
* $filter=name.value eq 'xxxx'
*/
filter?: string;
}
/**
* Optional Parameters.
*/
export interface VirtualMachinesListBySubscriptionOptionalParams extends msRest.RequestOptionsBase {
/**
* The filter to apply on the list operation
*/
filter?: string;
/**
* The maximum number of record sets to return
*/
top?: number;
/**
* to be used by nextLink implementation
*/
skipToken?: string;
}
/**
* Optional Parameters.
*/
export interface VirtualMachinesListByResourceGroupOptionalParams extends msRest.RequestOptionsBase {
/**
* The filter to apply on the list operation
*/
filter?: string;
/**
* The maximum number of record sets to return
*/
top?: number;
/**
* to be used by nextLink implementation
*/
skipToken?: string;
}
/**
* Optional Parameters.
*/
export interface VirtualMachinesUpdateOptionalParams extends msRest.RequestOptionsBase {
/**
* The tags key:value pairs
*/
tags?: { [propertyName: string]: string };
}
/**
* Optional Parameters.
*/
export interface VirtualMachinesStopOptionalParams extends msRest.RequestOptionsBase {
/**
* query stop mode parameter (reboot, shutdown, etc...). Possible values include: 'reboot',
* 'suspend', 'shutdown', 'poweroff'
*/
mode?: StopMode;
/**
* mode indicates a type of stop operation - reboot, suspend, shutdown or power-off. Possible
* values include: 'reboot', 'suspend', 'shutdown', 'poweroff'
*/
mode1?: StopMode;
}
/**
* Optional Parameters.
*/
export interface VirtualMachinesBeginUpdateOptionalParams extends msRest.RequestOptionsBase {
/**
* The tags key:value pairs
*/
tags?: { [propertyName: string]: string };
}
/**
* Optional Parameters.
*/
export interface VirtualMachinesBeginStopOptionalParams extends msRest.RequestOptionsBase {
/**
* query stop mode parameter (reboot, shutdown, etc...). Possible values include: 'reboot',
* 'suspend', 'shutdown', 'poweroff'
*/
mode?: StopMode;
/**
* mode indicates a type of stop operation - reboot, suspend, shutdown or power-off. Possible
* values include: 'reboot', 'suspend', 'shutdown', 'poweroff'
*/
mode1?: StopMode;
}
/**
* An interface representing VMwareCloudSimpleClientOptions.
*/
export interface VMwareCloudSimpleClientOptions extends AzureServiceClientOptions {
baseUri?: string;
}
/**
* Defines headers for Get operation.
*/
export interface OperationsGetHeaders {
location: string;
retryAfter: number;
contentType: string;
}
/**
* Defines headers for CreateOrUpdate operation.
*/
export interface DedicatedCloudNodesCreateOrUpdateHeaders {
azureAsyncOperation: string;
locationHeader: string;
retryAfter: number;
}
/**
* Defines headers for Delete operation.
*/
export interface DedicatedCloudNodesDeleteHeaders {
contentType: string;
}
/**
* Defines headers for Delete operation.
*/
export interface DedicatedCloudServicesDeleteHeaders {
contentType: string;
}
/**
* Defines headers for CreateOrUpdate operation.
*/
export interface VirtualMachinesCreateOrUpdateHeaders {
azureAsyncOperation: string;
}
/**
* Defines headers for Delete operation.
*/
export interface VirtualMachinesDeleteHeaders {
azureAsyncOperation: string;
location: string;
retryAfter: number;
contentType: string;
}
/**
* Defines headers for Start operation.
*/
export interface VirtualMachinesStartHeaders {
azureAsyncOperation: string;
location: string;
retryAfter: number;
contentType: string;
}
/**
* Defines headers for Stop operation.
*/
export interface VirtualMachinesStopHeaders {
azureAsyncOperation: string;
location: string;
retryAfter: number;
contentType: string;
}
/**
* @interface
* List of available operations
* @extends Array<AvailableOperation>
*/
export interface AvailableOperationsListResponse extends Array<AvailableOperation> {
/**
* Link for next list of available operations
*/
nextLink?: string;
}
/**
* @interface
* List of dedicated nodes response model
* @extends Array<DedicatedCloudNode>
*/
export interface DedicatedCloudNodeListResponse extends Array<DedicatedCloudNode> {
/**
* Link for next list of DedicatedCloudNode
*/
nextLink?: string;
}
/**
* @interface
* List of dedicated cloud services
* @extends Array<DedicatedCloudService>
*/
export interface DedicatedCloudServiceListResponse extends Array<DedicatedCloudService> {
/**
* Link for next list of DedicatedCloudNode
*/
nextLink?: string;
}
/**
* @interface
* List of SKU availabilities
* @extends Array<SkuAvailability>
*/
export interface SkuAvailabilityListResponse extends Array<SkuAvailability> {
/**
* Link for next list of DedicatedCloudNode
*/
nextLink?: string;
}
/**
* @interface
* List of private clouds
* @extends Array<PrivateCloud>
*/
export interface PrivateCloudList extends Array<PrivateCloud> {
/**
* Link for next list of Private Clouds
*/
nextLink?: string;
}
/**
* @interface
* List of resource pools response model
* @extends Array<ResourcePool>
*/
export interface ResourcePoolsListResponse extends Array<ResourcePool> {
/**
* Link for next list of ResourcePoolsList
*/
nextLink?: string;
}
/**
* @interface
* List of virtual machine templates
* @extends Array<VirtualMachineTemplate>
*/
export interface VirtualMachineTemplateListResponse extends Array<VirtualMachineTemplate> {
/**
* Link for next list of VirtualMachineTemplate
*/
nextLink?: string;
}
/**
* @interface
* List of virtual networks
* @extends Array<VirtualNetwork>
*/
export interface VirtualNetworkListResponse extends Array<VirtualNetwork> {
/**
* Link for next list of VirtualNetwork
*/
nextLink?: string;
}
/**
* @interface
* List of usages
* @extends Array<Usage>
*/
export interface UsageListResponse extends Array<Usage> {
/**
* Link for next list of DedicatedCloudNode
*/
nextLink?: string;
}
/**
* @interface
* List of virtual machines
* @extends Array<VirtualMachine>
*/
export interface VirtualMachineListResponse extends Array<VirtualMachine> {
/**
* Link for next list of VirtualMachines
*/
nextLink?: string;
}
/**
* Defines values for OperationOrigin.
* Possible values include: 'user', 'system', 'user,system'
* @readonly
* @enum {string}
*/
export type OperationOrigin = 'user' | 'system' | 'user,system';
/**
* Defines values for AggregationType.
* Possible values include: 'Average', 'Total'
* @readonly
* @enum {string}
*/
export type AggregationType = 'Average' | 'Total';
/**
* Defines values for NodeStatus.
* Possible values include: 'unused', 'used'
* @readonly
* @enum {string}
*/
export type NodeStatus = 'unused' | 'used';
/**
* Defines values for OnboardingStatus.
* Possible values include: 'notOnBoarded', 'onBoarded', 'onBoardingFailed', 'onBoarding'
* @readonly
* @enum {string}
*/
export type OnboardingStatus = 'notOnBoarded' | 'onBoarded' | 'onBoardingFailed' | 'onBoarding';
/**
* Defines values for DiskIndependenceMode.
* Possible values include: 'persistent', 'independent_persistent', 'independent_nonpersistent'
* @readonly
* @enum {string}
*/
export type DiskIndependenceMode = 'persistent' | 'independent_persistent' | 'independent_nonpersistent';
/**
* Defines values for NICType.
* Possible values include: 'E1000', 'E1000E', 'PCNET32', 'VMXNET', 'VMXNET2', 'VMXNET3'
* @readonly
* @enum {string}
*/
export type NICType = 'E1000' | 'E1000E' | 'PCNET32' | 'VMXNET' | 'VMXNET2' | 'VMXNET3';
/**
* Defines values for PrivateCloudResourceType.
* Possible values include: 'Microsoft.VMwareCloudSimple/privateClouds'
* @readonly
* @enum {string}
*/
export type PrivateCloudResourceType = 'Microsoft.VMwareCloudSimple/privateClouds';
/**
* Defines values for UsageCount.
* Possible values include: 'Count', 'Bytes', 'Seconds', 'Percent', 'CountPerSecond',
* 'BytesPerSecond'
* @readonly
* @enum {string}
*/
export type UsageCount = 'Count' | 'Bytes' | 'Seconds' | 'Percent' | 'CountPerSecond' | 'BytesPerSecond';
/**
* Defines values for GuestOSType.
* Possible values include: 'linux', 'windows', 'other'
* @readonly
* @enum {string}
*/
export type GuestOSType = 'linux' | 'windows' | 'other';
/**
* Defines values for VirtualMachineStatus.
* Possible values include: 'running', 'suspended', 'poweredoff', 'updating', 'deallocating',
* 'deleting'
* @readonly
* @enum {string}
*/
export type VirtualMachineStatus = 'running' | 'suspended' | 'poweredoff' | 'updating' | 'deallocating' | 'deleting';
/**
* Defines values for StopMode.
* Possible values include: 'reboot', 'suspend', 'shutdown', 'poweroff'
* @readonly
* @enum {string}
*/
export type StopMode = 'reboot' | 'suspend' | 'shutdown' | 'poweroff';
/**
* Contains response data for the list operation.
*/
export type OperationsListResponse = AvailableOperationsListResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: AvailableOperationsListResponse;
};
};
/**
* Contains response data for the get operation.
*/
export type OperationsGetResponse = OperationResource & OperationsGetHeaders & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The parsed HTTP response headers.
*/
parsedHeaders: OperationsGetHeaders;
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: OperationResource;
};
};
/**
* Contains response data for the listNext operation.
*/
export type OperationsListNextResponse = AvailableOperationsListResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: AvailableOperationsListResponse;
};
};
/**
* Contains response data for the listBySubscription operation.
*/
export type DedicatedCloudNodesListBySubscriptionResponse = DedicatedCloudNodeListResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: DedicatedCloudNodeListResponse;
};
};
/**
* Contains response data for the listByResourceGroup operation.
*/
export type DedicatedCloudNodesListByResourceGroupResponse = DedicatedCloudNodeListResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: DedicatedCloudNodeListResponse;
};
};
/**
* Contains response data for the get operation.
*/
export type DedicatedCloudNodesGetResponse = DedicatedCloudNode & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: DedicatedCloudNode;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type DedicatedCloudNodesCreateOrUpdateResponse = DedicatedCloudNode & DedicatedCloudNodesCreateOrUpdateHeaders & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The parsed HTTP response headers.
*/
parsedHeaders: DedicatedCloudNodesCreateOrUpdateHeaders;
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: DedicatedCloudNode;
};
};
/**
* Contains response data for the deleteMethod operation.
*/
export type DedicatedCloudNodesDeleteResponse = DedicatedCloudNodesDeleteHeaders & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The parsed HTTP response headers.
*/
parsedHeaders: DedicatedCloudNodesDeleteHeaders;
};
};
/**
* Contains response data for the update operation.
*/
export type DedicatedCloudNodesUpdateResponse = DedicatedCloudNode & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: DedicatedCloudNode;
};
};
/**
* Contains response data for the listBySubscriptionNext operation.
*/
export type DedicatedCloudNodesListBySubscriptionNextResponse = DedicatedCloudNodeListResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: DedicatedCloudNodeListResponse;
};
};
/**
* Contains response data for the listByResourceGroupNext operation.
*/
export type DedicatedCloudNodesListByResourceGroupNextResponse = DedicatedCloudNodeListResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: DedicatedCloudNodeListResponse;
};
};
/**
* Contains response data for the listBySubscription operation.
*/
export type DedicatedCloudServicesListBySubscriptionResponse = DedicatedCloudServiceListResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: DedicatedCloudServiceListResponse;
};
};
/**
* Contains response data for the listByResourceGroup operation.
*/
export type DedicatedCloudServicesListByResourceGroupResponse = DedicatedCloudServiceListResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: DedicatedCloudServiceListResponse;
};
};
/**
* Contains response data for the get operation.
*/
export type DedicatedCloudServicesGetResponse = DedicatedCloudService & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: DedicatedCloudService;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type DedicatedCloudServicesCreateOrUpdateResponse = DedicatedCloudService & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: DedicatedCloudService;
};
};
/**
* Contains response data for the deleteMethod operation.
*/
export type DedicatedCloudServicesDeleteResponse = DedicatedCloudServicesDeleteHeaders & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The parsed HTTP response headers.
*/
parsedHeaders: DedicatedCloudServicesDeleteHeaders;
};
};
/**
* Contains response data for the update operation.
*/
export type DedicatedCloudServicesUpdateResponse = DedicatedCloudService & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: DedicatedCloudService;
};
};
/**
* Contains response data for the listBySubscriptionNext operation.
*/
export type DedicatedCloudServicesListBySubscriptionNextResponse = DedicatedCloudServiceListResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: DedicatedCloudServiceListResponse;
};
};
/**
* Contains response data for the listByResourceGroupNext operation.
*/
export type DedicatedCloudServicesListByResourceGroupNextResponse = DedicatedCloudServiceListResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: DedicatedCloudServiceListResponse;
};
};
/**
* Contains response data for the list operation.
*/
export type SkusAvailabilityListResponse = SkuAvailabilityListResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: SkuAvailabilityListResponse;
};
};
/**
* Contains response data for the listNext operation.
*/
export type SkusAvailabilityListNextResponse = SkuAvailabilityListResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: SkuAvailabilityListResponse;
};
};
/**
* Contains response data for the list operation.
*/
export type PrivateCloudsListResponse = PrivateCloudList & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: PrivateCloudList;
};
};
/**
* Contains response data for the get operation.
*/
export type PrivateCloudsGetResponse = PrivateCloud & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: PrivateCloud;
};
};
/**
* Contains response data for the listNext operation.
*/
export type PrivateCloudsListNextResponse = PrivateCloudList & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: PrivateCloudList;
};
};
/**
* Contains response data for the list operation.
*/
export type ResourcePoolsListResponse2 = ResourcePoolsListResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ResourcePoolsListResponse;
};
};
/**
* Contains response data for the get operation.
*/
export type ResourcePoolsGetResponse = ResourcePool & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ResourcePool;
};
};
/**
* Contains response data for the listNext operation.
*/
export type ResourcePoolsListNextResponse = ResourcePoolsListResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ResourcePoolsListResponse;
};
};
/**
* Contains response data for the list operation.
*/
export type VirtualMachineTemplatesListResponse = VirtualMachineTemplateListResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualMachineTemplateListResponse;
};
};
/**
* Contains response data for the get operation.
*/
export type VirtualMachineTemplatesGetResponse = VirtualMachineTemplate & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualMachineTemplate;
};
};
/**
* Contains response data for the listNext operation.
*/
export type VirtualMachineTemplatesListNextResponse = VirtualMachineTemplateListResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualMachineTemplateListResponse;
};
};
/**
* Contains response data for the list operation.
*/
export type VirtualNetworksListResponse = VirtualNetworkListResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkListResponse;
};
};
/**
* Contains response data for the get operation.
*/
export type VirtualNetworksGetResponse = VirtualNetwork & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetwork;
};
};
/**
* Contains response data for the listNext operation.
*/
export type VirtualNetworksListNextResponse = VirtualNetworkListResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkListResponse;
};
};
/**
* Contains response data for the list operation.
*/
export type UsagesListResponse = UsageListResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: UsageListResponse;
};
};
/**
* Contains response data for the listNext operation.
*/
export type UsagesListNextResponse = UsageListResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: UsageListResponse;
};
};
/**
* Contains response data for the listBySubscription operation.
*/
export type VirtualMachinesListBySubscriptionResponse = VirtualMachineListResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualMachineListResponse;
};
};
/**
* Contains response data for the listByResourceGroup operation.
*/
export type VirtualMachinesListByResourceGroupResponse = VirtualMachineListResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualMachineListResponse;
};
};
/**
* Contains response data for the get operation.
*/
export type VirtualMachinesGetResponse = VirtualMachine & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualMachine;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type VirtualMachinesCreateOrUpdateResponse = VirtualMachine & VirtualMachinesCreateOrUpdateHeaders & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The parsed HTTP response headers.
*/
parsedHeaders: VirtualMachinesCreateOrUpdateHeaders;
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualMachine;
};
};
/**
* Contains response data for the deleteMethod operation.
*/
export type VirtualMachinesDeleteResponse = VirtualMachinesDeleteHeaders & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The parsed HTTP response headers.
*/
parsedHeaders: VirtualMachinesDeleteHeaders;
};
};
/**
* Contains response data for the update operation.
*/
export type VirtualMachinesUpdateResponse = VirtualMachine & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualMachine;
};
};
/**
* Contains response data for the start operation.
*/
export type VirtualMachinesStartResponse = VirtualMachinesStartHeaders & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The parsed HTTP response headers.
*/
parsedHeaders: VirtualMachinesStartHeaders;
};
};
/**
* Contains response data for the stop operation.
*/
export type VirtualMachinesStopResponse = VirtualMachinesStopHeaders & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The parsed HTTP response headers.
*/
parsedHeaders: VirtualMachinesStopHeaders;
};
};
/**
* Contains response data for the beginUpdate operation.
*/
export type VirtualMachinesBeginUpdateResponse = VirtualMachine & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualMachine;
};
};
/**
* Contains response data for the listBySubscriptionNext operation.
*/
export type VirtualMachinesListBySubscriptionNextResponse = VirtualMachineListResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualMachineListResponse;
};
};
/**
* Contains response data for the listByResourceGroupNext operation.
*/
export type VirtualMachinesListByResourceGroupNextResponse = VirtualMachineListResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualMachineListResponse;
};
}; | the_stack |
import React, { useEffect, useRef } from "react";
import * as THREE from "three";
// @ts-ignore
import { BlurPass, EffectComposer, RenderPass } from "postprocessing";
const WHITE = new THREE.Color(0xFFFFFF),
GREY = new THREE.Color(0xCCCCCC),
RED = new THREE.Color(0xFF0000),
YELLOW = new THREE.Color(0xFFFF00),
BLUE = new THREE.Color(0x0000FF),
CYAN = new THREE.Color(0x00FFFF),
LIGHT_GREEN = new THREE.Color(0x70C4CE),
ORANGE = new THREE.Color(0xf66023),
PURPLE = new THREE.Color(0x590D82),
MAGENTA = new THREE.Color(0xff00ff),
PINK = new THREE.Color(0xCE70A5);
const CAMERA_FACTOR = 40;
// const CAMERA_FACTOR = 180;
const TIME_DILATION = 1 / 2;
const BRIGHTNESS = .8;
type SceneState = {
renderer: THREE.WebGLRenderer,
camera: THREE.OrthographicCamera,
scene: THREE.Scene,
geometry: THREE.BufferGeometry,
material: THREE.MeshStandardMaterial,
mesh: THREE.Mesh
}
export function ThreeJSAnimationShader() {
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const sceneStateRef = useRef<SceneState | null>(null);
function initScene(ref: HTMLCanvasElement, width: number, height: number): SceneState {
const renderer = new THREE.WebGLRenderer({
// antialias: true,
// alpha: true,
canvas: ref
});
renderer.setClearColor(0xffffff);
renderer.setSize(width, height);
renderer.setPixelRatio(1);
const scene = new THREE.Scene();
const geometry = new THREE.SphereBufferGeometry(15,
60,
60,
// 0,
// Math.PI,
// Math.PI / 4,
// Math.PI / 2
);
// let geometry = new THREE.DodecahedronGeometry(10, 10);
console.log("pointsCount", geometry.attributes.position.array.length);
const material = new THREE.MeshStandardMaterial();
// material.wireframe = true;
material.userData.delta = { value: 0 };
material.userData.brightness = { value: BRIGHTNESS };
// material.side = THREE.DoubleSide;
material.onBeforeCompile = function(shader) {
shader.uniforms.delta = material.userData.delta;
shader.uniforms.brightness = material.userData.brightness;
// shader.fragmentShader = "uniform float delta;\n" + shader.fragmentShader;
shader.fragmentShader = buildFragmentShader();
shader.vertexShader = buildVertexShader();
};
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
// BG plane
const planeGeometry = new THREE.PlaneGeometry(500, 500);
const plane = new THREE.Mesh(planeGeometry, material);
plane.position.z = -500;
scene.add(plane);
const left = width / -CAMERA_FACTOR ;
const right = width / CAMERA_FACTOR;
const top = height / CAMERA_FACTOR;
const bottom = height / -CAMERA_FACTOR;
const near = 1;
const far = 1000;
const camera = new THREE.OrthographicCamera(left, right, top, bottom, near, far);
camera.position.z = 500;
camera.position.y = -13;
camera.position.x = 2;
return {
renderer,
camera,
scene,
geometry,
material,
mesh
};
}
function setSize(state: SceneState, width: number, height: number) {
console.log(state);
state.renderer.setSize(width, height);
state.camera.left = width / -CAMERA_FACTOR;
state.camera.right = width / CAMERA_FACTOR;
state.camera.top = height / CAMERA_FACTOR;
state.camera.bottom = height / -CAMERA_FACTOR;
state.camera.updateProjectionMatrix();
}
useEffect(() => {
if (!canvasRef.current)
return;
const width = canvasRef.current.offsetWidth,
height = canvasRef.current.offsetHeight;
const sceneState = initScene(canvasRef.current, width, height);
sceneStateRef.current = sceneState;
const {
renderer,
camera,
scene,
material
} = sceneState;
const clock = new THREE.Clock();
//RENDER LOOP
render();
function render() {
// const delta = clock.getDelta();
// mesh.rotation.y += delta * 0.05 * (1) % Math.PI;
// mesh.rotation.x += delta * 0.05 * (-1) % Math.PI;
material.userData.delta.value = clock.getElapsedTime() * TIME_DILATION;
material.userData.brightness.value = BRIGHTNESS;
// updateLightsPosition(delta, light, light2, light4, light5, mesh);
renderer.render(scene, camera);
requestAnimationFrame(render);
}
return () => {
// Callback to cleanup three js, cancel animationFrame, etc
};
}, [canvasRef.current]);
useEffect(() => {
function handleResize() {
if (sceneStateRef.current && canvasRef.current) {
console.log("resizing");
const width = window.innerWidth,
height = window.innerHeight;
canvasRef.current.width= width;
setSize(sceneStateRef.current, width, height);
}
}
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, [window.innerHeight, window.innerWidth]);
return <canvas
className={"h-screen w-screen"}
ref={canvasRef}
/>;
}
function buildVertexShader() {
return `
uniform float delta;
varying vec2 vUv;
varying vec3 vNormal;
varying vec3 vPosition;
varying float v_displacement_amount;
vec3 mod289(vec3 x)
{
return x - floor(x * (1.0 / 289.0)) * 289.0;
}
vec4 mod289(vec4 x)
{
return x - floor(x * (1.0 / 289.0)) * 289.0;
}
vec4 permute(vec4 x)
{
return mod289(((x*34.0)+1.0)*x);
}
vec4 taylorInvSqrt(vec4 r)
{
return 1.79284291400159 - 0.85373472095314 * r;
}
vec3 fade(vec3 t) {
return t*t*t*(t*(t*6.0-15.0)+10.0);
}
// Classic Perlin noise
float cnoise(vec3 P)
{
vec3 Pi0 = floor(P); // Integer part for indexing
vec3 Pi1 = Pi0 + vec3(1.0); // Integer part + 1
Pi0 = mod289(Pi0);
Pi1 = mod289(Pi1);
vec3 Pf0 = fract(P); // Fractional part for interpolation
vec3 Pf1 = Pf0 - vec3(1.0); // Fractional part - 1.0
vec4 ix = vec4(Pi0.x, Pi1.x, Pi0.x, Pi1.x);
vec4 iy = vec4(Pi0.yy, Pi1.yy);
vec4 iz0 = Pi0.zzzz;
vec4 iz1 = Pi1.zzzz;
vec4 ixy = permute(permute(ix) + iy);
vec4 ixy0 = permute(ixy + iz0);
vec4 ixy1 = permute(ixy + iz1);
vec4 gx0 = ixy0 * (1.0 / 7.0);
vec4 gy0 = fract(floor(gx0) * (1.0 / 7.0)) - 0.5;
gx0 = fract(gx0);
vec4 gz0 = vec4(0.5) - abs(gx0) - abs(gy0);
vec4 sz0 = step(gz0, vec4(0.0));
gx0 -= sz0 * (step(0.0, gx0) - 0.5);
gy0 -= sz0 * (step(0.0, gy0) - 0.5);
vec4 gx1 = ixy1 * (1.0 / 7.0);
vec4 gy1 = fract(floor(gx1) * (1.0 / 7.0)) - 0.5;
gx1 = fract(gx1);
vec4 gz1 = vec4(0.5) - abs(gx1) - abs(gy1);
vec4 sz1 = step(gz1, vec4(0.0));
gx1 -= sz1 * (step(0.0, gx1) - 0.5);
gy1 -= sz1 * (step(0.0, gy1) - 0.5);
vec3 g000 = vec3(gx0.x,gy0.x,gz0.x);
vec3 g100 = vec3(gx0.y,gy0.y,gz0.y);
vec3 g010 = vec3(gx0.z,gy0.z,gz0.z);
vec3 g110 = vec3(gx0.w,gy0.w,gz0.w);
vec3 g001 = vec3(gx1.x,gy1.x,gz1.x);
vec3 g101 = vec3(gx1.y,gy1.y,gz1.y);
vec3 g011 = vec3(gx1.z,gy1.z,gz1.z);
vec3 g111 = vec3(gx1.w,gy1.w,gz1.w);
vec4 norm0 = taylorInvSqrt(vec4(dot(g000, g000), dot(g010, g010), dot(g100, g100), dot(g110, g110)));
g000 *= norm0.x;
g010 *= norm0.y;
g100 *= norm0.z;
g110 *= norm0.w;
vec4 norm1 = taylorInvSqrt(vec4(dot(g001, g001), dot(g011, g011), dot(g101, g101), dot(g111, g111)));
g001 *= norm1.x;
g011 *= norm1.y;
g101 *= norm1.z;
g111 *= norm1.w;
float n000 = dot(g000, Pf0);
float n100 = dot(g100, vec3(Pf1.x, Pf0.yz));
float n010 = dot(g010, vec3(Pf0.x, Pf1.y, Pf0.z));
float n110 = dot(g110, vec3(Pf1.xy, Pf0.z));
float n001 = dot(g001, vec3(Pf0.xy, Pf1.z));
float n101 = dot(g101, vec3(Pf1.x, Pf0.y, Pf1.z));
float n011 = dot(g011, vec3(Pf0.x, Pf1.yz));
float n111 = dot(g111, Pf1);
vec3 fade_xyz = fade(Pf0);
vec4 n_z = mix(vec4(n000, n100, n010, n110), vec4(n001, n101, n011, n111), fade_xyz.z);
vec2 n_yz = mix(n_z.xy, n_z.zw, fade_xyz.y);
float n_xyz = mix(n_yz.x, n_yz.y, fade_xyz.x);
return 2.2 * n_xyz;
}
void main() {
vUv = uv;
float s = 1.35;
float r = delta * 0.25;
vNormal = normal;
vPosition = position;
float displacement = cnoise(s * normal + r) / 3.0 + 1.0;
v_displacement_amount = displacement;
vec3 newPosition = position * displacement ;
gl_Position = projectionMatrix * modelViewMatrix * vec4( newPosition, 1.0 );
// gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}
`;
}
// https://zz85.github.io/glsl-optimizer/
function buildFragmentShaderOptimized() {
return `
uniform float delta;
uniform float brightness;
varying vec3 vNormal;
varying vec3 vPosition;
varying float v_displacement_amount;
void main ()
{
vec3 hsv_1;
float tmpvar_2;
float tmpvar_3;
tmpvar_3 = (v_displacement_amount / 3.0);
tmpvar_2 = (((
abs((((
((sin((
(vPosition.x / 4.0)
+ vNormal.x)) + (sin(
((vPosition.y / 3.0) + vNormal.y)
) * 2.0)) + (sin((
(vPosition.z / 4.0)
+ vNormal.z)) * 2.0))
+
sin(tmpvar_3)
) + (
sin((delta / 2.0))
* 4.0)) + 10.0))
/ 20.0) * 0.65) + 0.35);
vec3 tmpvar_4;
tmpvar_4.x = tmpvar_2;
tmpvar_4.y = ((abs(
sin((tmpvar_3 + (delta / 7.0)))
) * 0.2) + 0.55);
tmpvar_4.z = ((abs(
cos((tmpvar_3 + (delta / 3.0)))
) * 0.3) + brightness);
hsv_1.yz = tmpvar_4.yz;
hsv_1.x = (tmpvar_2 + 0.05);
vec4 tmpvar_5;
tmpvar_5.w = 1.0;
tmpvar_5.xyz = (tmpvar_4.z * mix (vec3(1.0, 1.0, 1.0), clamp (
(abs(((
fract((hsv_1.xxx + vec3(1.0, 0.6666667, 0.3333333)))
* 6.0) - vec3(3.0, 3.0, 3.0))) - vec3(1.0, 1.0, 1.0))
, 0.0, 1.0), tmpvar_4.y));
gl_FragColor = tmpvar_5;
}
`;
}
function buildFragmentShader() {
return `
uniform float delta;
uniform float brightness;
varying vec2 vUv;
varying vec3 vNormal;
varying vec3 vPosition;
varying float v_displacement_amount;
vec3 hsv2rgb(vec3 c)
{
vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
}
void main( void ) {
float h =
(abs(
sin(vPosition.x / 4.0 + vNormal.x)
+ sin(vPosition.y / 3.0 + vNormal.y) * 2.0
+ sin(vPosition.z / 4.0 + vNormal.z) * 2.0
+ sin(v_displacement_amount / 3.0)
+ sin(delta / 2.0) * 4.0
) )
/ 11.0 * 0.65 + .35;
float s = abs(sin(v_displacement_amount / 3.0 + delta / 7.0)) * 0.2 + .55;
float v = abs(cos(v_displacement_amount / 3.0 + delta / 3.0 )) * 0.3 + brightness;
vec3 hsv = vec3(h,s,v);
hsv.x = hsv.x + .05;
gl_FragColor = vec4( hsv2rgb(hsv), 1.0 );
}
`;
} | the_stack |
import {IOas30NodeVisitor, IOasNodeVisitor} from "../../visitors/visitor.iface";
import {Oas30XML} from "./xml.model";
import {OasSchema} from "../common/schema.model";
import {Oas30ExternalDocumentation} from "./external-documentation.model";
import {Oas30Discriminator} from "./discriminator.model";
/**
* Models an OAS 3.0 Schema object. Example:
*
* {
* "type": "object",
* "required": [
* "name"
* ],
* "properties": {
* "name": {
* "type": "string"
* },
* "address": {
* "$ref": "#/definitions/Address"
* },
* "age": {
* "type": "integer",
* "format": "int32",
* "minimum": 0
* }
* }
*/
export class Oas30Schema extends OasSchema {
public oneOf: OasSchema[];
public anyOf: OasSchema[];
public not: OasSchema;
public discriminator: Oas30Discriminator;
public nullable: boolean;
public writeOnly: boolean;
public deprecated: boolean;
/**
* Creates a child Discriminator model.
* @return {Oas30Discriminator}
*/
public createDiscriminator(): Oas30Discriminator {
let rval: Oas30Discriminator = new Oas30Discriminator();
rval._ownerDocument = this._ownerDocument;
rval._parent = this;
return rval;
}
/**
* Creates a child external documentation model.
* @return {Oas30ExternalDocumentation}
*/
public createExternalDocumentation(): Oas30ExternalDocumentation {
let rval: Oas30ExternalDocumentation = new Oas30ExternalDocumentation();
rval._ownerDocument = this._ownerDocument;
rval._parent = this;
return rval;
}
/**
* Creates a child XML model.
* @return {Oas30XML}
*/
public createXML(): Oas30XML {
let rval: Oas30XML = new Oas30XML();
rval._ownerDocument = this._ownerDocument;
rval._parent = this;
return rval;
}
/**
* Creates a child schema model.
* @return {Oas30Schema}
*/
public createAllOfSchema(): Oas30AllOfSchema {
let rval: Oas30AllOfSchema = new Oas30AllOfSchema();
rval._ownerDocument = this._ownerDocument;
rval._parent = this;
return rval;
}
/**
* Creates a child schema model.
* @return {Oas30Schema}
*/
public createOneOfSchema(): Oas30OneOfSchema {
let rval: Oas30OneOfSchema = new Oas30OneOfSchema();
rval._ownerDocument = this._ownerDocument;
rval._parent = this;
return rval;
}
/**
* Creates a child schema model.
* @return {Oas30Schema}
*/
public createAnyOfSchema(): Oas30AnyOfSchema {
let rval: Oas30AnyOfSchema = new Oas30AnyOfSchema();
rval._ownerDocument = this._ownerDocument;
rval._parent = this;
return rval;
}
/**
* Creates a child schema model.
* @return {Oas30Schema}
*/
public createNotSchema(): Oas30NotSchema {
let rval: Oas30NotSchema = new Oas30NotSchema();
rval._ownerDocument = this._ownerDocument;
rval._parent = this;
return rval;
}
/**
* Creates a child schema model.
* @return {Oas30Schema}
*/
public createItemsSchema(): Oas30ItemsSchema {
let rval: Oas30ItemsSchema = new Oas30ItemsSchema();
rval._ownerDocument = this._ownerDocument;
rval._parent = this;
return rval;
}
/**
* Creates a child schema model.
* @return {Oas30Schema}
*/
public createAdditionalPropertiesSchema(): Oas30AdditionalPropertiesSchema {
let rval: Oas30AdditionalPropertiesSchema = new Oas30AdditionalPropertiesSchema();
rval._ownerDocument = this._ownerDocument;
rval._parent = this;
return rval;
}
/**
* Creates a child schema model.
* @return {Oas30Schema}
*/
public createPropertySchema(propertyName: string): Oas30PropertySchema {
let rval: Oas30PropertySchema = new Oas30PropertySchema(propertyName);
rval._ownerDocument = this._ownerDocument;
rval._parent = this;
return rval;
}
}
/**
* Subclass of Schema to indicate that this is actually a Property schema (a schema
* defined as a property of another schema). References:
*
* http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.16
* https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#schemaObject
*/
export class Oas30PropertySchema extends Oas30Schema {
private _propertyName: string;
/**
* Constructor.
* @param propertyName
*/
constructor(propertyName: string) {
super()
this._propertyName = propertyName;
}
/**
* Accepts the given OAS node visitor and calls the appropriate method on it to visit this node.
* @param visitor
*/
public accept(visitor: IOasNodeVisitor): void {
let viz: IOas30NodeVisitor = <IOas30NodeVisitor> visitor;
viz.visitPropertySchema(this);
}
/**
* Gets the schema's property name.
* @return {string}
*/
public propertyName(): string {
return this._propertyName;
}
}
/**
* Subclass of Schema to indicate that this is actually an "All Of" schema (a schema
* included in the array of "allOf" schemas, which is a property of any valid schema).
*
* http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.22
* https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#schemaObject
*
* Example:
*
* {
* "allOf": [
* { "type": "string" },
* { "maxLength": 5 }
* ]
* }
*/
export class Oas30AllOfSchema extends Oas30Schema {
/**
* Accepts the given OAS node visitor and calls the appropriate method on it to visit this node.
* @param visitor
*/
public accept(visitor: IOasNodeVisitor): void {
let viz: IOas30NodeVisitor = <IOas30NodeVisitor> visitor;
viz.visitAllOfSchema(this);
}
}
/**
* Subclass of Schema to indicate that this is actually an "Any Of" schema (a schema
* included in the array of "anyOf" schemas, which is a property of any valid schema).
*
* http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.22
* https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#schemaObject
*/
export class Oas30AnyOfSchema extends Oas30Schema {
/**
* Accepts the given OAS node visitor and calls the appropriate method on it to visit this node.
* @param visitor
*/
public accept(visitor: IOasNodeVisitor): void {
let viz: IOas30NodeVisitor = <IOas30NodeVisitor> visitor;
viz.visitAnyOfSchema(this);
}
}
/**
* Subclass of Schema to indicate that this is actually an "One Of" schema (a schema
* included in the array of "oneOf" schemas, which is a property of any valid schema).
*
* http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.22
* https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#schemaObject
*/
export class Oas30OneOfSchema extends Oas30Schema {
/**
* Accepts the given OAS node visitor and calls the appropriate method on it to visit this node.
* @param visitor
*/
public accept(visitor: IOasNodeVisitor): void {
let viz: IOas30NodeVisitor = <IOas30NodeVisitor> visitor;
viz.visitOneOfSchema(this);
}
}
/**
* Subclass of Schema to indicate that this is actually a "Not" schema (a schema
* set in the "not" property of a schema).
*
* http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.22
* https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#schemaObject
*/
export class Oas30NotSchema extends Oas30Schema {
/**
* Accepts the given OAS node visitor and calls the appropriate method on it to visit this node.
* @param visitor
*/
public accept(visitor: IOasNodeVisitor): void {
let viz: IOas30NodeVisitor = <IOas30NodeVisitor> visitor;
viz.visitNotSchema(this);
}
}
/**
* Subclass of Schema to indicate that this is actually an "items" schema (a schema
* that is assigned to the 'items' property).
*
* http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.9
* https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#schemaObject
*
* Example:
*
* {
* "items": [
* { "type": "string" },
* { "maxLength": 5 }
* ]
* }
*/
export class Oas30ItemsSchema extends Oas30Schema {
/**
* Accepts the given OAS node visitor and calls the appropriate method on it to visit this node.
* @param visitor
*/
public accept(visitor: IOasNodeVisitor): void {
let viz: IOas30NodeVisitor = <IOas30NodeVisitor> visitor;
viz.visitItemsSchema(this);
}
}
/**
* Subclass of Schema to indicate that this is actually an Additional Properties schema (a schema
* defined as a property of another schema). References:
*
* http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.18
* https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#schemaObject
*/
export class Oas30AdditionalPropertiesSchema extends Oas30Schema {
/**
* Accepts the given OAS node visitor and calls the appropriate method on it to visit this node.
* @param visitor
*/
public accept(visitor: IOasNodeVisitor): void {
let viz: IOas30NodeVisitor = <IOas30NodeVisitor> visitor;
viz.visitAdditionalPropertiesSchema(this);
}
}
/**
* Subclass of Schema to indicate that this is actually a Definition (a schema defined in
* the "components" section of the OpenAPI document).
*/
export class Oas30SchemaDefinition extends Oas30Schema {
private _name: string;
/**
* Constructor.
* @param name
*/
constructor(name: string) {
super();
this._name = name;
}
/**
* Accepts the given OAS node visitor and calls the appropriate method on it to visit this node.
* @param visitor
*/
public accept(visitor: IOasNodeVisitor): void {
let viz: IOas30NodeVisitor = <IOas30NodeVisitor> visitor;
viz.visitSchemaDefinition(this);
}
/**
* Gets the schema's property name.
* @return {string}
*/
public name(): string {
return this._name;
}
} | the_stack |
import * as vscode from "vscode";
import * as fs from "fs";
import * as os from "os";
import * as moment from "moment";
import * as path from "path";
module.exports = function () {
vscode.commands.executeCommand("workbench.action.files.save").then(() => {
let config = vscode.workspace.getConfiguration("vsorg");
let folderPath = config.get("folderPath");
let dateFormat: any = config.get("dateFormat");
let folder: any;
let taskText: any;
let taskTextGetTodo: any = "";
let getDateFromTaskText: any;
let convertedDateArray: any = [];
let unsortedObject: any = {};
let sortedObject: any = {};
var itemInSortedObject: any = "";
//call the function
readFiles();
function readFiles() {
//read the directory
fs.readdir(setMainDir(), (err, items: any) => {
//loop through all of the files in the directory
for (let i = 0; i < items.length; i++) {
//make sure its a vsorg file
if (items[i].includes(".vsorg")) {
//read the file and puth the text in an array
let fileText
if (os.platform() === "darwin" || os.platform() === "linux") {
fileText = fs
.readFileSync(setMainDir() + "/" + items[i])
.toString()
.split(/\r?\n/);
} else {
fileText = fs
.readFileSync(setMainDir() + "\\" + items[i])
.toString()
.split(/\r?\n/);
}
fileText.forEach(element => {
// for each element check for scheduled and not done
if (element.includes("SCHEDULED") && !element.includes("DONE")) {
//get everything before scheduled
taskText = element.trim().match(/.*(?=.*SCHEDULED)/g);
//get todo
taskTextGetTodo = element.match(/\bTODO\b/);
//remove keywords and unicode chars
taskText = taskText[0].replace("⊙", "");
taskText = taskText.replace("TODO", "");
taskText = taskText.replace("DONE", "");
taskText = taskText.replace("⊘", "");
taskText = taskText.replace("⊖", "");
taskText = taskText.trim();
//get the date
getDateFromTaskText = element.match(/\[(.*)\]/);
//if there is a TODO
if (taskTextGetTodo !== null) {
taskText =
'<span class="filename">' +
items[i] +
":</span> " +
'<span class="todo" data-filename="' +
items[i] +
'" data-text= "' +
taskText +
'" ' +
'" data-date= "' +
getDateFromTaskText[0] +
'"> ' +
taskTextGetTodo +
"</span>" +
'<span class="taskText">' +
taskText +
"</span>" +
'<span class="scheduled">SCHEDULED</span>';
} else {
taskText =
'<span class="filename">' +
items[i] +
":</span> " +
'<span class="taskText">' +
taskText +
"</span>" +
'<span class="scheduled">SCHEDULED</span>';
}
//get the day of the week for items scheduled in the future
let d = moment(getDateFromTaskText[1], dateFormat).day();
let nameOfDay;
if (d === 0) {
nameOfDay = "Sunday";
} else if (d === 1) {
nameOfDay = "Monday";
} else if (d === 2) {
nameOfDay = "Tuesday";
} else if (d === 3) {
nameOfDay = "Wednesday";
} else if (d === 4) {
nameOfDay = "Thursday";
} else if (d === 5) {
nameOfDay = "Friday";
} else if (d === 6) {
nameOfDay = "Saturday";
}
convertedDateArray = [];
if (moment(getDateFromTaskText[1], dateFormat) >= moment(new Date(), dateFormat)) {
if (nameOfDay !== undefined) {
convertedDateArray.push({
date:
'<div class="heading' +
nameOfDay +
" " +
getDateFromTaskText[0] +
'"><h4 class="' +
getDateFromTaskText[0] +
'">' +
getDateFromTaskText[0] +
", " +
nameOfDay.toUpperCase() +
"</h4></div>",
text: '<div class="panel ' + getDateFromTaskText[0] + '">' + taskText + "</div>"
});
}
} else {
//todays date for incomplete items in the past
var today: any = new Date();
var dd: any = today.getDate();
var mm: any = today.getMonth() + 1;
var yyyy: any = today.getFullYear();
var getDayOverdue: any = today.getDay();
var overdue: any;
if (dd < 10) {
dd = "0" + dd;
}
if (mm < 10) {
mm = "0" + mm;
}
if (dateFormat === "MM-DD-YYYY") {
today = mm + "-" + dd + "-" + yyyy;
} else {
today = dd + "-" + mm + "-" + yyyy;
}
if (getDayOverdue === 0) {
overdue = "Sunday";
} else if (getDayOverdue === 1) {
overdue = "Monday";
} else if (getDayOverdue === 2) {
overdue = "Tuesday";
} else if (getDayOverdue === 3) {
overdue = "Wednesday";
} else if (getDayOverdue === 4) {
overdue = "Thursday";
} else if (getDayOverdue === 5) {
overdue = "Friday";
} else if (getDayOverdue === 6) {
overdue = "Saturday";
}
//if date is a day in the past
if (moment(getDateFromTaskText[1], dateFormat) < moment(new Date().getDate(), dateFormat)) {
convertedDateArray.push({
date:
'<div class="heading' +
overdue +
" " +
"[" +
today +
"]" +
'"><h4 class="' +
"[" +
today +
"]" +
'">' +
"[" +
today +
"]" +
", " +
overdue.toUpperCase() +
"</h4></div>",
text:
'<div class="panel ' +
"[" +
today +
"]" +
'">' +
taskText +
'<span class="late">LATE: ' +
getDateFromTaskText[1] +
"</span></div>"
});
}
}
//converted array to object with date as keys
convertedDateArray.forEach((element: any) => {
if (!unsortedObject[element.date]) {
unsortedObject[element.date] = " " + element.text;
} else {
unsortedObject[element.date] += " " + element.text;
}
});
}
});
//sort the object by date
Object.keys(unsortedObject).forEach(function (key) {
sortedObject[key] = unsortedObject[key];
});
}
}
Object.keys(sortedObject)
.sort(function (a: any, b: any) {
let first: any = moment(a.match(/\[(.*)\]/), dateFormat).toDate();
let second: any = moment(b.match(/\[(.*)\]/), dateFormat).toDate();
return first - second;
})
.forEach(function (property) {
itemInSortedObject += property + sortedObject[property] + "</br>";
});
createWebview();
});
}
/**
* Get the Main Directory
*/
function setMainDir() {
if (folderPath === "") {
let homeDir = os.homedir();
if (os.platform() === "darwin" || os.platform() === "linux") {
folder = homeDir + "/VSOrgFiles";
} else {
folder = homeDir + "\\VSOrgFiles";
}
} else {
folder = folderPath;
}
return folder;
}
function createWebview() {
let reload = false;
let fullAgendaView = vscode.window.createWebviewPanel(
"fullAgenda",
"Full Agenda View",
vscode.ViewColumn.Beside,
{
// Enable scripts in the webview
enableScripts: true
}
);
// Set The HTML content
fullAgendaView.webview.html = getWebviewContent(sortedObject);
//reload on save
vscode.workspace.onDidSaveTextDocument((document: vscode.TextDocument) => {
reload = true;
fullAgendaView.dispose();
});
fullAgendaView.onDidDispose(() => {
if (reload === true) {
reload = false;
vscode.commands.executeCommand("extension.viewAgenda");
}
});
// Handle messages from the webview
fullAgendaView.webview.onDidReceiveMessage(message => {
switch (message.command) {
case "open":
let fullPath = path.join(setMainDir(), message.text);
vscode.workspace.openTextDocument(vscode.Uri.file(fullPath)).then(doc => {
vscode.window.showTextDocument(doc, vscode.ViewColumn.One, false);
});
return;
case "changeTodo":
let textArray = message.text.split(",");
let fileName = path.join(setMainDir(), textArray[1]);
let text = textArray[2];
let contents = fs.readFileSync(fileName, "utf-8");
let x = contents.split(/\r?\n/);
for (let i = 0; i < x.length; i++) {
if (x[i].indexOf(text) > -1 && x[i].indexOf(textArray[3]) > -1) {
let removeSchedule: any = x[i].match(/\bSCHEDULED\b(.*)/g);
let date = moment().format('Do MMMM YYYY, h:mm:ss a');
x[i] = x[i].replace(removeSchedule[0], "");
x[i] = x[i].replace(
"TODO " + text,
"DONE " +
text +
" SCHEDULED: " +
textArray[3] +
"\n COMPLETED:" +
"[" +
date +
"]"
);
contents = x.join("\r\n");
fs.writeFileSync(fileName, contents, "utf-8");
return;
}
}
case "changeDone":
let textArrayD = message.text.split(",");
let fileNameD = path.join(setMainDir(), textArrayD[1]);
let textD = textArrayD[2];
let contentsD = fs.readFileSync(fileNameD, "utf-8");
let y = contentsD.split(/\r?\n/);
for (let i = 0; i < y.length; i++) {
if (y[i].indexOf(textD) > -1 && y[i].indexOf(textArrayD[3]) > -1) {
let removeSchedule: any = y[i].match(/\bSCHEDULED\b(.*)/g);
y[i] = y[i].replace(removeSchedule[0], "");
y[i] = y[i].replace("DONE " + textD, "TODO " + textD + " SCHEDULED: " + textArrayD[3]);
y.splice(i + 1, 1);
contentsD = y.join("\r\n");
fs.writeFileSync(fileNameD, contentsD, "utf-8");
return;
}
}
}
});
}
function getWebviewContent(task: keyof typeof sortedObject) {
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cat Coding</title>
<link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,700|Roboto:400,700" rel="stylesheet">
</head>
<style>
body{
font-family: 'Roboto', sans-serif;
}
.headingSunday {
background-color: #2f6999;
color: #ffffff;
cursor: pointer;
padding: 1px;
padding-left: 10px;
border: none;
text-align: left;
outline: none;
}
.headingMonday {
background-color: #2f996e;
cursor: pointer;
padding: 1px;
padding-left: 10px;
border: none;
text-align: left;
outline: none;
color: #ffffff;
}
.headingTuesday {
background-color: #802f99;
cursor: pointer;
padding: 1px;
padding-left: 10px;
border: none;
text-align: left;
outline: none;
color: #ffffff;
}
.headingWednesday {
background-color: #992f2f;
cursor: pointer;
padding: 1px;
padding-left: 10px;
border: none;
text-align: left;
outline: none;
color: #ffffff;
}
.headingThursday {
background-color: #992f67;
cursor: pointer;
padding: 1px;
padding-left: 10px;
border: none;
text-align: left;
outline: none;
color: #ffffff;
}
.headingFriday {
background-color: #44992f;
color: #ffffff;
cursor: pointer;
padding: 1px;
padding-left: 10px;
border: none;
text-align: left;
outline: none;
}
.headingSaturday {
background-color: #3c2e96;
color: #ffffff;
cursor: pointer;
padding: 1px;
padding-left: 10px;
border: none;
text-align: left;
outline: none;
}
.active, .accordion:hover {
background-color: #ccc;
}
.panel {
padding-right: 10px;
padding-bottom: 10px;
padding-bottom: 10px;
background-color: white;
overflow: hidden;
color: #000000;
border-bottom: 1px solid black;
box-shadow: 0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23);
display: none;
}
.todo{
color: #d12323;
padding-left: 10px;
font-weight: 700;
float: left;
padding-top: 13px;
padding-bottom: -10px;
height: 67%;
transition: all .5s ease;
cursor: pointer;
}
.done{
color: #4286f4;
padding-left: 10px;
font-weight: 700;
float: left;
padding-top: 13px;
padding-bottom: -10px;
height: 67%;
transition: all .5s ease;
cursor: pointer;
}
.filename{
font-size: 15px;
font-weight: 700;
float: left;
margin-left: 10px;
margin-top: 10px;
cursor: pointer;
}
.filename:hover{
color: #095fea;
}
.scheduled{
background-color: #76E6E6;
padding-left: 10px;
padding-right: 10px;
padding-top: 5px;
color: #5d5d5d;
font-weight: 700;
border-radius: 27px;
font-size: 9px;
/* margin-left: auto; */
height: 15px;
float: right;
margin-left: 10px;
margin-top: 10px;
box-shadow: 0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23);
}
.textDiv{
width: 100%;
margin: 0;
height: 40px;
}
.taskText{
font-size: 15px;
float: left;
margin-left: 10px;
margin-top: 10px;
width: 50%;
font-family: 'Roboto Mono', sans-serif;
font-weight: 400;
}
.late{
background-color: #DF9930;
padding-left: 10px;
padding-right: 10px;
padding-top: 5px;
color: #ffffff;
font-weight: 700;
border-radius: 27px;
font-size: 9px;
/* margin-left: auto; */
height: 15px;
float: right;
margin-left: 10px;
margin-top: 10px;
box-shadow: 0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23);
}
</style>
<body>
<h1>Agenda View</h1>
<div id="display-agenda">
${itemInSortedObject}
</div>
<script>
const vscode = acquireVsCodeApi();
document.addEventListener('click', function(event) {
let class0 = event.srcElement.classList[0];
let class1 = event.srcElement.classList[1];
let panels = document.getElementsByClassName('panel');
//show or hide panels
if (!event.srcElement.classList.contains('panel')) {
for (let i = 0; i < panels.length; i++) {
if (panels[i].classList.contains(class0) || panels[i].classList.contains(class1)) {
if (panels[i].style.display === 'block') {
panels[i].style.display = 'none';
} else {
panels[i].style.display = 'block';
}
}
}
}
//send filename to open file
if (event.srcElement.classList.contains('filename')) {
//send message to open text file
vscode.postMessage({
command: 'open',
text: event.target.innerText.replace(':', "")
});
}
//change TODO to DONE and vice versa
if(event.target.innerText === "TODO"){
event.target.innerText = "DONE";
event.srcElement.classList.add('done');
event.srcElement.classList.remove('todo');
vscode.postMessage({
command: 'changeTodo',
text: event.target.innerText + "," + event.target.dataset.filename + "," + event.target.dataset.text + "," + event.target.dataset.date
})
} else if(event.target.innerText === "DONE") {
event.target.innerText = "TODO";
event.srcElement.classList.add('todo');
event.srcElement.classList.remove('done');
vscode.postMessage({
command: 'changeDone',
text: event.target.innerText + "," + event.target.dataset.filename + "," + event.target.dataset.text + "," + event.target.dataset.date
})
}
});
</script>
</body>
</html>`;
}
});
}; | the_stack |
import * as cp from 'child_process';
import * as fs from 'fs';
import * as fse from 'fs-extra';
import * as glob from 'glob';
import * as path from 'path';
import {
ConfigurationTarget,
ExtensionContext,
OutputChannel,
TextDocument,
Uri,
WorkspaceConfiguration,
env,
window,
workspace,
} from 'vscode';
import {
Location,
NotificationType,
RequestType,
TextDocumentPositionParams,
} from 'vscode-languageclient';
import javaPatterns from '../../config/api_ref/patterns_java.json';
const expandHomeDir = require('expand-home-dir');
const isWindows: boolean = process.platform.indexOf('win') === 0;
const JAVAC_FILENAME = 'javac' + (isWindows ? '.exe' : '');
const JAVA_FILENAME = 'java' + (isWindows ? '.exe' : '');
export const ACTIVE_BUILD_TOOL_STATE = 'java.activeBuildTool';
export const DEBUG_VSCODE_JAVA = 'DEBUG_VSCODE_JAVA';
export const EXTENSION_NAME_STANDARD = 'stripeJavaLanguageServer (Standard)';
export const EXTENSION_NAME_SYNTAX = 'stripeJavaLanguageServer (Syntax)';
export const IS_WORKSPACE_JDK_ALLOWED = 'java.ls.isJdkAllowed';
export interface JDKInfo {
javaHome: string;
javaVersion: number;
}
export interface StatusReport {
message: string;
type: string;
}
export enum ClientStatus {
Uninitialized = 'Uninitialized',
Initialized = 'Initialized',
Starting = 'Starting',
Started = 'Started',
Error = 'Error',
Stopping = 'Stopping',
}
export enum ServerMode {
STANDARD = 'Standard',
LIGHTWEIGHT = 'LightWeight',
HYBRID = 'Hybrid',
}
export namespace StatusNotification {
export const type = new NotificationType<StatusReport>('language/status');
}
export interface FindLinksParams {
type: string;
position: TextDocumentPositionParams;
}
export interface LinkLocation extends Location {
displayName: string;
kind: string;
}
export namespace FindLinks {
export const type = new RequestType<FindLinksParams, LinkLocation[], void>('java/findLinks');
}
export function getJavaConfiguration(): WorkspaceConfiguration {
return workspace.getConfiguration('java');
}
export function getJavaServerLaunchMode(): ServerMode {
return workspace.getConfiguration().get('java.server.launchMode') || ServerMode.HYBRID;
}
export async function hasNoBuildToolConflicts(
context: ExtensionContext,
): Promise<boolean> {
const isMavenEnabled: boolean =
getJavaConfiguration().get<boolean>('import.maven.enabled') || false;
const isGradleEnabled: boolean =
getJavaConfiguration().get<boolean>('import.gradle.enabled') || false;
if (isMavenEnabled && isGradleEnabled) {
const activeBuildTool: string | undefined = context.workspaceState.get(ACTIVE_BUILD_TOOL_STATE);
if (!activeBuildTool) {
if (!(await hasBuildToolConflicts())) {
return true;
}
return false;
}
}
return true;
}
async function hasBuildToolConflicts(): Promise<boolean> {
const projectConfigurationUris: Uri[] = await getBuildFilesInWorkspace();
const projectConfigurationFsPaths: string[] = projectConfigurationUris.map((uri) => uri.fsPath);
const eclipseDirectories = getDirectoriesByBuildFile(projectConfigurationFsPaths, [], '.project');
// ignore the folders that already has .project file (already imported before)
const gradleDirectories = getDirectoriesByBuildFile(
projectConfigurationFsPaths,
eclipseDirectories,
'.gradle',
);
const gradleDirectoriesKts = getDirectoriesByBuildFile(
projectConfigurationFsPaths,
eclipseDirectories,
'.gradle.kts',
);
gradleDirectories.concat(gradleDirectoriesKts);
const mavenDirectories = getDirectoriesByBuildFile(
projectConfigurationFsPaths,
eclipseDirectories,
'pom.xml',
);
return gradleDirectories.some((gradleDir) => {
return mavenDirectories.includes(gradleDir);
});
}
async function getBuildFilesInWorkspace(): Promise<Uri[]> {
const buildFiles: Uri[] = [];
const inclusionFilePatterns: string[] = getBuildFilePatterns();
inclusionFilePatterns.push('**/.project');
const inclusionFolderPatterns: string[] = getInclusionPatternsFromNegatedExclusion();
// Since VS Code API does not support put negated exclusion pattern in findFiles(),
// here we first parse the negated exclusion to inclusion and do the search.
if (inclusionFilePatterns.length > 0 && inclusionFolderPatterns.length > 0) {
buildFiles.push(
...(await workspace.findFiles(
convertToGlob(inclusionFilePatterns, inclusionFolderPatterns),
null,
)),
);
}
const inclusionBlob: string = convertToGlob(inclusionFilePatterns);
const exclusionBlob: string = getExclusionBlob();
if (inclusionBlob) {
buildFiles.push(...(await workspace.findFiles(inclusionBlob, exclusionBlob)));
}
return buildFiles;
}
function getDirectoriesByBuildFile(
inclusions: string[],
exclusions: string[],
fileName: string,
): string[] {
return inclusions
.filter((fsPath) => fsPath.endsWith(fileName))
.map((fsPath) => {
return path.dirname(fsPath);
})
.filter((inclusion) => {
return !exclusions.includes(inclusion);
});
}
export function getBuildFilePatterns(): string[] {
const config = getJavaConfiguration();
const isMavenImporterEnabled: boolean = config.get<boolean>('import.maven.enabled') || false;
const isGradleImporterEnabled: boolean = config.get<boolean>('import.gradle.enabled') || false;
const patterns: string[] = [];
if (isMavenImporterEnabled) {
patterns.push('**/pom.xml');
}
if (isGradleImporterEnabled) {
patterns.push('**/*.gradle');
patterns.push('**/*.gradle.kts');
}
return patterns;
}
export function getInclusionPatternsFromNegatedExclusion(): string[] {
const config = getJavaConfiguration();
const exclusions: string[] = config.get<string[]>('import.exclusions', []);
const patterns: string[] = [];
for (const exclusion of exclusions) {
if (exclusion.startsWith('!')) {
patterns.push(exclusion.substr(1));
}
}
return patterns;
}
export function convertToGlob(filePatterns: string[], basePatterns?: string[]): string {
if (!filePatterns || filePatterns.length === 0) {
return '';
}
if (!basePatterns || basePatterns.length === 0) {
return parseToStringGlob(filePatterns);
}
const patterns: string[] = [];
for (const basePattern of basePatterns) {
for (const filePattern of filePatterns) {
patterns.push(path.join(basePattern, `/${filePattern}`).replace(/\\/g, '/'));
}
}
return parseToStringGlob(patterns);
}
export function getExclusionBlob(): string {
const config = getJavaConfiguration();
const exclusions: string[] = config.get<string[]>('import.exclusions', []);
const patterns: string[] = [];
for (const exclusion of exclusions) {
if (exclusion.startsWith('!')) {
continue;
}
patterns.push(exclusion);
}
return parseToStringGlob(patterns);
}
function parseToStringGlob(patterns: string[]): string {
if (!patterns || patterns.length === 0) {
return '';
}
return `{${patterns.join(',')}}`;
}
export function ensureExists(folder: string) {
if (!fs.existsSync(folder)) {
fs.mkdirSync(folder);
}
}
export function deleteDirectory(dir: string) {
if (fs.existsSync(dir)) {
fs.readdirSync(dir).forEach((child) => {
const entry = path.join(dir, child);
if (fs.lstatSync(entry).isDirectory()) {
deleteDirectory(entry);
} else {
fs.unlinkSync(entry);
}
});
fs.rmdirSync(dir);
}
}
export function getTimestamp(file: string) {
if (!fs.existsSync(file)) {
return -1;
}
const stat = fs.statSync(file);
return stat.mtimeMs;
}
// see https://github.com/redhat-developer/vscode-java/blob/master/src/extension.ts
export function makeRandomHexString(length: number) {
const chars = [
'0',
'1',
'2',
'3',
'4',
'5',
'6',
'6',
'7',
'8',
'9',
'a',
'b',
'c',
'd',
'e',
'f',
];
let result = '';
for (let i = 0; i < length; i++) {
const idx = Math.floor(chars.length * Math.random());
result += chars[idx];
}
return result;
}
export function getJavaFilePathOfTextDocument(document: TextDocument): string | undefined {
if (document) {
const resource = document.uri;
if (resource.scheme === 'file' && resource.fsPath.endsWith('.java')) {
return path.normalize(resource.fsPath);
}
}
return undefined;
}
export function isPrefix(parentPath: string, childPath: string): boolean {
if (!childPath) {
return false;
}
const relative = path.relative(parentPath, childPath);
return !!relative && !relative.startsWith('..') && !path.isAbsolute(relative);
}
export async function getJavaSDKInfo(
context: ExtensionContext,
outputChannel: OutputChannel,
): Promise<JDKInfo> {
let source: string;
let javaVersion: number = 0;
let javaHome = (await checkJavaPreferences(context)) || '';
if (javaHome) {
source = `java.home variable defined in ${env.appName} settings`;
javaHome = expandHomeDir(javaHome);
if (!(await fse.pathExists(javaHome))) {
outputChannel.appendLine(
`The ${source} points to a missing or inaccessible folder (${javaHome})`,
);
} else if (!(await fse.pathExists(path.resolve(javaHome, 'bin', JAVAC_FILENAME)))) {
let msg: string;
if (await fse.pathExists(path.resolve(javaHome, JAVAC_FILENAME))) {
msg = `'bin' should be removed from the ${source} (${javaHome})`;
} else {
msg = `The ${source} (${javaHome}) does not point to a JDK.`;
}
outputChannel.appendLine(msg);
}
javaVersion = (await getJavaVersion(javaHome)) || 0;
}
return {javaHome, javaVersion};
}
async function checkJavaPreferences(context: ExtensionContext) {
const allow = 'Allow';
const disallow = 'Disallow';
let inspect = workspace.getConfiguration().inspect<string>('java.home');
let javaHome = inspect && inspect.workspaceValue;
let isVerified = javaHome === undefined || javaHome === null;
if (isVerified) {
javaHome = getJavaConfiguration().get('home');
}
const key = getKey(IS_WORKSPACE_JDK_ALLOWED, context.storagePath, javaHome);
const globalState = context.globalState;
if (!isVerified) {
isVerified = globalState.get(key) || false;
if (isVerified === undefined) {
await window
.showErrorMessage(
`Do you allow this workspace to set the java.home variable? \n java.home: ${javaHome}`,
disallow,
allow,
)
.then(async (selection) => {
if (selection === allow) {
globalState.update(key, true);
} else if (selection === disallow) {
globalState.update(key, false);
await workspace
.getConfiguration()
.update('java.home', undefined, ConfigurationTarget.Workspace);
}
});
isVerified = globalState.get(key) || false;
}
}
if (!isVerified) {
inspect = workspace.getConfiguration().inspect<string>('java.home');
javaHome = inspect && inspect.globalValue;
}
return javaHome;
}
async function getJavaVersion(javaHome: string): Promise<number | undefined> {
let javaVersion = await checkVersionInReleaseFile(javaHome);
if (!javaVersion) {
javaVersion = await checkVersionByCLI(javaHome);
}
return javaVersion;
}
/**
* Get version by checking file JAVA_HOME/release
* see https://github.com/redhat-developer/vscode-java/blob/master/src/requirements.ts
*/
async function checkVersionInReleaseFile(javaHome: string): Promise<number> {
const releaseFile = path.join(javaHome, 'release');
try {
const content = await fse.readFile(releaseFile);
const regexp = /^JAVA_VERSION="(.*)"/gm;
const match = regexp.exec(content.toString());
if (!match) {
return 0;
}
const majorVersion = parseMajorVersion(match[1]);
return majorVersion;
} catch (error) {
// ignore
}
return 0;
}
/**
* Get version by parsing `JAVA_HOME/bin/java -version`
* see https://github.com/redhat-developer/vscode-java/blob/master/src/requirements.ts
*/
function checkVersionByCLI(javaHome: string): Promise<number> {
return new Promise((resolve, reject) => {
const javaBin = path.join(javaHome, 'bin', JAVA_FILENAME);
cp.execFile(javaBin, ['-version'], {}, (error: any, stdout: any, stderr: string) => {
const regexp = /version "(.*)"/g;
const match = regexp.exec(stderr);
if (!match) {
return resolve(0);
}
const javaVersion = parseMajorVersion(match[1]);
resolve(javaVersion);
});
});
}
function parseMajorVersion(version: string): number {
if (!version) {
return 0;
}
// Ignore '1.' prefix for legacy Java versions
if (version.startsWith('1.')) {
version = version.substring(2);
}
// look into the interesting bits now
const regexp = /\d+/g;
const match = regexp.exec(version);
let javaVersion = 0;
if (match) {
javaVersion = parseInt(match[0], 10);
}
return javaVersion;
}
function getKey(prefix: string, storagePath: any, value: any) {
const workspacePath = path.resolve(storagePath + '/jdt_ws');
if (workspace.name !== undefined) {
return `${prefix}::${workspacePath}::${value}`;
} else {
return `${prefix}::${value}`;
}
}
export function getJavaEncoding(): string {
const config = workspace.getConfiguration();
const languageConfig: any = config.get('[java]');
let javaEncoding = null;
if (languageConfig) {
javaEncoding = languageConfig['files.encoding'];
}
if (!javaEncoding) {
javaEncoding = config.get<string>('files.encoding', 'UTF-8');
}
return javaEncoding;
}
export function getJavaApiDocLink(namespace: string): string {
const baseUrl = 'https://stripe.com/docs/api';
const patterns = Object.entries(javaPatterns);
const found = patterns.filter((item) => item[0] === namespace);
if (found) {
const apiUrl = found[0][1];
return baseUrl + apiUrl;
}
return '';
}
export function getServerLauncher(serverHome: string): Array<string> {
return glob.sync('**/plugins/org.eclipse.equinox.launcher_*.jar', {
cwd: serverHome,
});
}
export function checkPathExists(filepath: string) {
return fs.existsSync(filepath);
}
export function startedInDebugMode(): boolean {
const args = (process as any).execArgv as string[];
if (args) {
// See https://nodejs.org/en/docs/guides/debugging-getting-started/
return args.some((arg) => /^--inspect/.test(arg) || /^--debug/.test(arg));
}
return false;
}
export function startedFromSources(): boolean {
return process.env[DEBUG_VSCODE_JAVA] === 'true';
} | the_stack |
export const version = '1.5.17';
export const author = 'Tianyu Dai <dtysky@outlook.com>';
/* tslint:disable-line */
console.log(`Sein.js verison: ${version}`);
/* -------------- types --------------- */
export * from './types/Common';
export * from './types/Event';
export * from './types/Physic';
export * from './types/Renderer';
export * from './types/Resource';
export * from './types/Global';
/* -------------- Core --------------- */
export {default as SName, isSName} from './Core/SName';
export {default as SObject, isSObject} from './Core/SObject';
export {default as Actor, isActor} from './Core/Actor';
export {default as Component, isComponent} from './Core/Component';
export {default as ChildActorComponent, IChildActorComponentState} from './Core/ChildActorComponent';
export {default as Engine, isEngine} from './Core/Engine';
export {default as Game, IGameOptions, isGame} from './Core/Game';
export {default as World, isWorld} from './Core/World';
export {default as Level, isLevel} from './Core/Level';
export {default as Ticker, isTicker} from './Core/Ticker';
export {default as Tween} from './Core/Tween';
export {default as Observable, isObservable} from './Core/Observable';
export {default as Hilo3d} from './Core/Hilo3d';
export * from './Core/Decorator';
export {default as Constants} from './Core/Constants';
export * from './Core/MetaTypes';
/* -------------- Info --------------- */
export {default as InfoActor, isInfoActor} from './Info/InfoActor';
export {default as GameModeActor, isGameModeActor} from './Info/GameModeActor';
export {default as LevelScriptActor, isLevelScriptActor} from './Info/LevelScriptActor';
export {default as SystemActor, isSystemActor} from './Info/SystemActor';
export {default as StateActor, isStateActor} from './Info/StateActor';
export {default as TimerActor, isTimerActor, ITimerState} from './Info/TimerActor';
/* -------------- Math --------------- */
export * from './Core/Math';
/* -------------- DataStructure --------------- */
export {default as SIterable} from './DataStructure/SIterable';
export {default as SArray} from './DataStructure/SArray';
export {default as SMap} from './DataStructure/SMap';
export {default as SSet} from './DataStructure/SSet';
/* -------------- Exception --------------- */
export {default as BaseException, isBaseException} from './Exception/BaseException';
export {default as BreakGuardException, isBreakGuardException} from './Exception/BreakGuardException';
export {default as MemberConflictException, isMemberConflictException} from './Exception/MemberConflictException';
export {default as MissingMemberException, isMissingMemberException} from './Exception/MissingMemberException';
export {default as TypeConflictException, isTypeConflictException} from './Exception/TypeConflictException';
export {default as UnmetRequireException, isUnmetRequireException} from './Exception/UnmetRequireException';
export {default as ResourceLoadException, isResourceLoadException} from './Exception/ResourceLoadException';
export {default as throwException} from './Exception/throwException';
/* -------------- Player --------------- */
export {default as Player, isPlayer} from './Player/Player';
export {default as ControllerActor, IControllerActorState, isControllerActor} from './Player/ControllerActor';
export {default as PlayerControllerActor, isPlayerControllerActor} from './Player/PlayerControllerActor';
export {default as PlayerStateActor, isPlayerStateActor} from './Player/PlayerStateActor';
/* -------------- AI --------------- */
export {default as AIControllerActor, isAIControllerActor} from './AI/AIControllerActor';
export {default as FSMComponent, isFSMComponent} from './AI/FSMComponent';
export {default as FSMState, isFSMState} from './AI/FSMState';
// export {default as BehaviorTree} from './AI/BehaviorTree';
/* -------------- Renderer --------------- */
export {default as ISceneComponent} from './Renderer/ISceneComponent';
export {default as SceneComponent, isSceneComponent, ISceneComponentState} from './Renderer/SceneComponent';
export {default as ISceneActor} from './Renderer/ISceneActor';
export {default as SceneActor, isSceneActor} from './Renderer/SceneActor';
export {
default as PrimitiveComponent, IPrimitiveComponentState,
isPrimitiveComponent, isPrimitiveActor
} from './Renderer/PrimitiveComponent';
export {
default as StaticMeshComponent, IStaticMeshComponentState,
isStaticMeshActor, isStaticMeshComponent
} from './Renderer/StaticMeshComponent';
export {default as StaticMeshActor} from './Renderer/StaticMeshActor';
export {
default as SkeletalMeshComponent, ISkeletalMeshComponentState,
isSkeletalMeshActor, isSkeletalMeshComponent
} from './Renderer/SkeletalMeshComponent';
export {default as SkeletalMeshActor} from './Renderer/SkeletalMeshActor';
export {default as SpriteComponent, ISpriteComponentState, isSpriteActor, isSpriteComponent} from './Renderer/SpriteComponent';
export {default as SpriteActor} from './Renderer/SpriteActor';
export {default as Layers, isLayers} from './Renderer/Layers';
export {default as Fog, isFog} from './Renderer/Fog';
export {default as FrameBuffer, isFrameBuffer, IFrameBufferOptions} from './Renderer/FrameBuffer';
export {default as RenderSystemActor, isRenderSystemActor} from './Renderer/RenderSystemActor';
export {default as VertexArrayObject} from './Renderer/VertexArrayObject';
export {default as Program} from './Renderer/Program';
export {default as Shader} from './Renderer/Shader';
export {default as GLCapabilities} from './Renderer/GLCapabilities';
export {default as GLExtensions} from './Renderer/GLExtensions';
export {default as Buffer} from './Renderer/Buffer';
/* -------------- BSP --------------- */
export {default as BSPComponent, isBSPActor, isBSPComponent} from './BSP/BSPComponent';
export {default as BSPBoxComponent, IBSPBoxComponentState, isBSPBoxActor, isBSPBoxComponent} from './BSP/BSPBoxComponent';
export {default as BSPPlaneComponent, IBSPPlaneComponentState, isBSPPlaneActor, isBSPPlaneComponent} from './BSP/BSPPlaneComponent';
export {default as BSPSphereComponent, IBSPSphereComponentState, isBSPSphereActor, isBSPSphereComponent} from './BSP/BSPSphereComponent';
export {default as BSPMorphComponent, IBSPMorphComponentState, isBSPMorphActor, isBSPMorphComponent} from './BSP/BSPMorphComponent';
export {
default as BSPCylinderComponent, IBSPCylinderComponentState,
isBSPCylinderActor, isBSPCylinderComponent
} from './BSP/BSPCylinderComponent';
export {default as BSPBoxActor} from './BSP/BSPBoxActor';
export {default as BSPCylinderActor} from './BSP/BSPCylinderActor';
export {default as BSPMorphActor} from './BSP/BSPMorphActor';
export {default as BSPPlaneActor} from './BSP/BSPPlaneActor';
export {default as BSPSphereActor} from './BSP/BSPSphereActor';
/* -------------- Textures --------------- */
export {default as Texture, isTexture} from './Texture/Texture';
export {default as CubeTexture, isCubeTexture} from './Texture/CubeTexture';
export {default as LazyTexture, isLazyTexture} from './Texture/LazyTexture';
export {default as DataTexture, isDataTexture} from './Texture/DataTexture';
export {default as DynamicTexture, isDynamicTexture, IDynamicTextureOptions} from './Texture/DynamicTexture';
export {default as AtlasManager, isAtlasManager, IAtlasOptions, IAtlasCreationOptions} from './Texture/AtlasManager';
/* -------------- Material --------------- */
export {default as Material, IMaterial, isMaterial} from './Material/Material';
export {default as BasicMaterial, isBasicMaterial} from './Material/BasicMaterial';
export {default as GeometryMaterial, isGeometryMaterial} from './Material/GeometryMaterial';
export {default as PBRMaterial, isPBRMaterial} from './Material/PBRMaterial';
export {default as RawShaderMaterial, IShaderMaterialOptions, isRawShaderMaterial} from './Material/RawShaderMaterial';
export {default as ShaderMaterial, isShaderMaterial} from './Material/ShaderMaterial';
export {default as SkyboxMaterial, isSkyboxMaterial} from './Material/SkyboxMaterial';
export {
default as ShaderChunk, IMaterialUniform,
IShaderChunk, IShaderChunkCode, IMaterialAttribute, isShaderChunk
} from './Material/ShaderChunk';
export {default as shaderChunks} from './Material/shaderChunks';
export {default as Semantic, ISemanticObject} from './Material/Semantic';
/* -------------- Geometry --------------- */
export {default as GeometryData, isGeometryData} from './Geometry/GeometryData';
export {default as Geometry, isGeometry} from './Geometry/Geometry';
export {default as BoxGeometry, isBoxGeometry} from './Geometry/BoxGeometry';
export {default as SphereGeometry, isSphereGeometry} from './Geometry/SphereGeometry';
export {default as PlaneGeometry, isPlaneGeometry} from './Geometry/PlaneGeometry';
export {default as CylinderGeometry, isCylinderGeometry} from './Geometry/CylinderGeometry';
export {default as MorphGeometry, isMorphGeometry} from './Geometry/MorphGeometry';
/* -------------- Mesh --------------- */
export {default as Mesh, isMesh} from './Mesh/Mesh';
export {default as SkeletalMesh, isSkeletalMesh} from './Mesh/SkeletalMesh';
export {default as Skeleton} from './Mesh/Skeleton';
/* -------------- Camera --------------- */
export {default as CameraComponent, isCameraActor} from './Camera/CameraComponent';
export {
default as PerspectiveCameraComponent, IPerspectiveCameraComponentState,
isPerspectiveCameraActor, isPerspectiveCameraComponent
} from './Camera/PerspectiveCameraComponent';
export {default as PerspectiveCameraActor} from './Camera/PerspectiveCameraActor';
export {
default as OrthographicCameraComponent, IOrthographicCameraComponentState,
isOrthographicCameraActor, isOrthographicCameraComponent
} from './Camera/OrthographicCameraComponent';
export {default as OrthographicCameraActor} from './Camera/OrthographicCameraActor';
/* -------------- Light --------------- */
export {
default as LightComponent, ILightComponentState,
isLightComponent, isLightActor
} from './Light/LightComponent';
export {
default as AmbientLightComponent, IAmbientLightComponentState,
isAmbientLightComponent, isAmbientLightActor
} from './Light/AmbientLightComponent';
export {
default as DirectionalLightComponent, IDirectionalLightComponentState,
isDirectionalLightActor, isDirectionalLightComponent
} from './Light/DirectionalLightComponent';
export {
default as PointLightComponent, IPointLightComponentState,
isPointLightActor, isPointLightComponent
} from './Light/PointLightComponent';
export {
default as SpotLightComponent, ISpotLightComponentState,
isSpotLightActor, isSpotLightComponent
} from './Light/SpotLightComponent';
export {default as AmbientLightActor} from './Light/AmbientLightActor';
export {default as DirectionalLightActor} from './Light/DirectionalLightActor';
export {default as PointLightActor} from './Light/PointLightActor';
export {default as SpotLightActor} from './Light/SpotLightActor';
/* -------------- Animation --------------- */
export {default as AnimatorComponent, IAnimatorComponentState, isAnimatorComponent} from './Animation/AnimatorComponent';
export {default as Animation, IAnimationState, isAnimation} from './Animation/Animation';
export {default as ModelAnimation, IModelAnimationState, isModelAnimation} from './Animation/ModelAnimation';
export {default as SpriteAnimation, ISpriteAnimationState, isSpriteAnimation} from './Animation/SpriteAnimation';
export {default as TweenAnimation, ITweenAnimationState, isTweenAnimation} from './Animation/TweenAnimation';
export {default as CombineAnimation, ICombineAnimationState, isCombineAnimation} from './Animation/CombineAnimation';
/* -------------- Physic --------------- */
export {default as CannonPhysicWorld} from './Physic/CannonPhysicWorld';
export {default as RigidBodyComponent, IRigidBodyComponentState, isRigidBodyComponent} from './Physic/RigidBodyComponent';
export {default as ColliderComponent, isColliderComponent} from './Physic/ColliderComponent';
export {default as BoxColliderComponent, isBoxColliderComponent} from './Physic/BoxColliderComponent';
export {default as CylinderColliderComponent, isCylinderColliderComponent} from './Physic/CylinderColliderComponent';
export {default as PlaneColliderComponent, isPlaneColliderComponent} from './Physic/PlaneColliderComponent';
export {default as SphereColliderComponent, isSphereColliderComponent} from './Physic/SphereColliderComponent';
export {default as JointComponent, isJointComponent} from './Physic/JointComponent';
export {default as PointToPointJointComponent, isPointToPointJointComponent} from './Physic/PointToPointJointComponent';
export {default as DistanceJointComponent, isDistanceJointComponent} from './Physic/DistanceJointComponent';
export {default as HingeJointComponent, isHingeJointComponent} from './Physic/HingeJointComponent';
export {default as LockJointComponent, isLockJointComponent} from './Physic/LockJointComponent';
export {default as SpringJointComponent, isSpringJointComponent} from './Physic/SpringJointComponent';
export {default as PhysicPicker, isPhysicPicker} from './Physic/PhysicPicker';
/* -------------- Event --------------- */
export {default as EventManager, isEventManager} from './Event/EventManager';
export {default as EventTrigger, isEventTrigger} from './Event/EventTrigger';
/* -------------- HID --------------- */
export * from './HID/MouseTrigger';
export * from './HID/TouchTrigger';
export * from './HID/KeyboardTrigger';
export {default as WindowResizeTrigger} from './HID/WindowResizeTrigger';
/* -------------- Resource --------------- */
export {default as ResourceManager, isResourceManager} from './Resource/ResourceManager';
export {default as ResourceLoader, isResourceLoader} from './Resource/ResourceLoader';
export {default as GlTFLoader, isGlTFLoader} from './Resource/GlTFLoader';
export {default as ImageLoader, isImageLoader} from './Resource/ImageLoader';
export {default as TextureLoader, isTextureLoader} from './Resource/TextureLoader';
export {default as CubeTextureLoader, isCubeTextureLoader} from './Resource/CubeTextureLoader';
export {default as AtlasLoader, isAtlasLoader} from './Resource/AtlasLoader';
export {IGlTFExtension, AliAMCExtension} from './Resource/GlTFExtensions';
/* -------------- NetWork --------------- */
export {default as HTTP} from './Network/HTTP';
/* -------------- Utils --------------- */
export * from './utils/actorIterators';
export * from './utils/actorFinders';
export {default as ContextSupports} from './utils/ContextSupports';
/* -------------- Debug --------------- */
export {default as Debug} from './Debug';
if(typeof window !== 'undefined' && !window['Sein']) {
window['Sein'] = module.exports;
} | the_stack |
import { SizeCache } from './shared/SizeCache.js';
import {BaseLayout, BaseLayoutConfig, dim1} from './shared/BaseLayout.js';
import {ItemBox, Positions, Size, Margins, margin, ScrollDirection, offsetAxis} from './shared/Layout.js';
type ItemBounds = {
pos: number,
size: number
};
type FlowLayoutConstructor = {
prototype: FlowLayout,
new(config?: BaseLayoutConfig): FlowLayout
}
type FlowLayoutSpecifier = BaseLayoutConfig & {
type: FlowLayoutConstructor
}
type FlowLayoutSpecifierFactory = (config?: BaseLayoutConfig) => FlowLayoutSpecifier;
export const flow: FlowLayoutSpecifierFactory = (config?: BaseLayoutConfig) => Object.assign({
type: FlowLayout
}, config);
function leadingMargin(direction: ScrollDirection): margin {
return direction === 'horizontal' ? 'marginLeft' : 'marginTop';
}
function trailingMargin(direction: ScrollDirection): margin {
return direction === 'horizontal' ? 'marginRight' : 'marginBottom';
}
function offset(direction: ScrollDirection): offsetAxis {
return direction === 'horizontal' ? 'xOffset' : 'yOffset';
}
function collapseMargins(a: number, b: number): number {
const m = [a, b].sort();
return m[1] <= 0
? Math.min(...m)
: m[0] >= 0
? Math.max(...m)
: m[0] + m[1];
}
class MetricsCache {
private _childSizeCache = new SizeCache();
private _marginSizeCache = new SizeCache();
private _metricsCache: Map<number, Size & Margins> = new Map();
update(metrics: {[key: number]: Size & Margins}, direction: ScrollDirection) {
const marginsToUpdate: Set<number> = new Set();
Object.keys(metrics).forEach((key) => {
const k = Number(key);
this._metricsCache.set(k, metrics[k]);
this._childSizeCache.set(k, metrics[k][dim1(direction)]);
marginsToUpdate.add(k);
marginsToUpdate.add(k + 1);
});
for (const k of marginsToUpdate) {
const a = this._metricsCache.get(k)?.[leadingMargin(direction)] || 0;
const b = this._metricsCache.get(k - 1)?.[trailingMargin(direction)] || 0;
this._marginSizeCache.set(k, collapseMargins(a, b))
}
}
get averageChildSize(): number {
return this._childSizeCache.averageSize;
}
get totalChildSize(): number {
return this._childSizeCache.totalSize;
}
get averageMarginSize(): number {
return this._marginSizeCache.averageSize;
}
get totalMarginSize(): number {
return this._marginSizeCache.totalSize;
}
getLeadingMarginValue(index: number, direction: ScrollDirection) {
return this._metricsCache.get(index)?.[leadingMargin(direction)] || 0;
}
getChildSize(index: number) {
return this._childSizeCache.getSize(index);
}
getMarginSize(index: number) {
return this._marginSizeCache.getSize(index);
}
clear() {
this._childSizeCache.clear();
this._marginSizeCache.clear();
this._metricsCache.clear();
}
}
export class FlowLayout extends BaseLayout<BaseLayoutConfig> {
/**
* Initial estimate of item size
*/
_itemSize: Size = {width: 100, height: 100};
/**
* Indices of children mapped to their (position and length) in the scrolling
* direction. Used to keep track of children that are in range.
*/
_physicalItems: Map<number, ItemBounds> = new Map();
/**
* Used in tandem with _physicalItems to track children in range across
* reflows.
*/
_newPhysicalItems: Map<number, ItemBounds> = new Map();
/**
* Width and height of children by their index.
*/
_metricsCache = new MetricsCache();
/**
* anchorIdx is the anchor around which we reflow. It is designed to allow
* jumping to any point of the scroll size. We choose it once and stick with
* it until stable. _first and _last are deduced around it.
*/
_anchorIdx: number | null = null;
/**
* Position in the scrolling direction of the anchor child.
*/
_anchorPos: number | null = null;
/**
* Whether all children in range were in range during the previous reflow.
*/
_stable = true;
/**
* Whether to remeasure children during the next reflow.
*/
_needsRemeasure = false;
private _measureChildren = true;
_estimate = true;
// protected _defaultConfig: BaseLayoutConfig = Object.assign({}, super._defaultConfig, {
// })
// constructor(config: Layout1dConfig) {
// super(config);
// }
get measureChildren() {
return this._measureChildren;
}
/**
* Determine the average size of all children represented in the sizes
* argument.
*/
updateItemSizes(sizes: {[key: number]: ItemBox}) {
this._metricsCache.update(sizes as Size & Margins, this.direction);
// if (this._nMeasured) {
// this._updateItemSize();
this._scheduleReflow();
// }
}
/**
* Set the average item size based on the total length and number of children
* in range.
*/
// _updateItemSize() {
// // Keep integer values.
// this._itemSize[this._sizeDim] = this._metricsCache.averageChildSize;
// }
_getPhysicalItem(idx: number): ItemBounds | undefined {
return this._newPhysicalItems.get(idx) ?? this._physicalItems.get(idx);
}
_getSize(idx: number): number | undefined {
const item = this._getPhysicalItem(idx);
return item && this._metricsCache.getChildSize(idx);
}
_getAverageSize(): number {
return this._metricsCache.averageChildSize || this._itemSize[this._sizeDim];
}
/**
* Returns the position in the scrolling direction of the item at idx.
* Estimates it if the item at idx is not in the DOM.
*/
_getPosition(idx: number): number {
const item = this._getPhysicalItem(idx);
const { averageMarginSize } = this._metricsCache;
return idx === 0
? this._metricsCache.getMarginSize(0) ?? averageMarginSize
: item
? item.pos
: averageMarginSize + idx * (averageMarginSize + this._getAverageSize());
}
_calculateAnchor(lower: number, upper: number): number {
if (lower <= 0) {
return 0;
}
if (upper > this._scrollSize - this._viewDim1) {
return this._totalItems - 1;
}
return Math.max(
0,
Math.min(
this._totalItems - 1,
Math.floor(((lower + upper) / 2) / this._delta)));
}
_getAnchor(lower: number, upper: number): number {
if (this._physicalItems.size === 0) {
return this._calculateAnchor(lower, upper);
}
if (this._first < 0) {
console.error('_getAnchor: negative _first');
return this._calculateAnchor(lower, upper);
}
if (this._last < 0) {
console.error('_getAnchor: negative _last');
return this._calculateAnchor(lower, upper);
}
const firstItem = this._getPhysicalItem(this._first),
lastItem = this._getPhysicalItem(this._last),
firstMin = firstItem!.pos,
lastMin = lastItem!.pos,
lastMax = lastMin + this._metricsCache.getChildSize(this._last)!;
if (lastMax < lower) {
// Window is entirely past physical items, calculate new anchor
return this._calculateAnchor(lower, upper);
}
if (firstMin > upper) {
// Window is entirely before physical items, calculate new anchor
return this._calculateAnchor(lower, upper);
}
// Window contains a physical item
// Find one, starting with the one that was previously first visible
let candidateIdx = this._firstVisible - 1;
let cMax = -Infinity;
while (cMax < lower) {
const candidate = this._getPhysicalItem(++candidateIdx);
cMax = candidate!.pos + this._metricsCache.getChildSize(candidateIdx)!;
}
return candidateIdx;
}
/**
* Updates _first and _last based on items that should be in the current
* viewed range.
*/
_getActiveItems() {
if (this._viewDim1 === 0 || this._totalItems === 0) {
this._clearItems();
} else {
this._getItems();
}
}
/**
* Sets the range to empty.
*/
_clearItems() {
this._first = -1;
this._last = -1;
this._physicalMin = 0;
this._physicalMax = 0;
const items = this._newPhysicalItems;
this._newPhysicalItems = this._physicalItems;
this._newPhysicalItems.clear();
this._physicalItems = items;
this._stable = true;
}
/*
* Updates _first and _last based on items that should be in the given range.
*/
_getItems() {
const items = this._newPhysicalItems;
this._stable = true;
let lower, upper;
// The anchorIdx is the anchor around which we reflow. It is designed to
// allow jumping to any point of the scroll size. We choose it once and
// stick with it until stable. first and last are deduced around it.
// If we have a scrollToIndex, we anchor on the given
// index and set the scroll position accordingly
if (this._scrollToIndex >= 0) {
this._anchorIdx = Math.min(this._scrollToIndex, this._totalItems - 1);
this._anchorPos = this._getPosition(this._anchorIdx);
this._scrollIfNeeded();
}
// Determine the lower and upper bounds of the region to be
// rendered, relative to the viewport
lower = this._scrollPosition - this._overhang;//leadingOverhang;
upper = this._scrollPosition + this._viewDim1 + this._overhang;// trailingOverhang;
if (upper < 0 || lower > this._scrollSize) {
this._clearItems();
return;
}
// If we are scrolling to a specific index or if we are doing another
// pass to stabilize a previously started reflow, we will already
// have an anchor. If not, establish an anchor now.
if (this._anchorIdx === null || this._anchorPos === null) {
this._anchorIdx = this._getAnchor(lower, upper);
this._anchorPos = this._getPosition(this._anchorIdx);
}
let anchorSize = this._getSize(this._anchorIdx);
if (anchorSize === undefined) {
this._stable = false;
anchorSize = this._getAverageSize();
}
let anchorLeadingMargin = this._metricsCache.getMarginSize(this._anchorIdx) ?? this._metricsCache.averageMarginSize;
let anchorTrailingMargin = this._metricsCache.getMarginSize(this._anchorIdx + 1) ?? this._metricsCache.averageMarginSize;
if (this._anchorIdx === 0) {
this._anchorPos = anchorLeadingMargin;
}
if (this._anchorIdx === this._totalItems - 1) {
this._anchorPos = this._scrollSize - anchorTrailingMargin - anchorSize;
}
// Anchor might be outside bounds, so prefer correcting the error and keep
// that anchorIdx.
let anchorErr = 0;
if (this._anchorPos + anchorSize + anchorTrailingMargin < lower) {
anchorErr = lower - (this._anchorPos + anchorSize + anchorTrailingMargin);
}
if (this._anchorPos - anchorLeadingMargin > upper) {
anchorErr = upper - (this._anchorPos - anchorLeadingMargin);
}
if (anchorErr) {
this._scrollPosition -= anchorErr;
lower -= anchorErr;
upper -= anchorErr;
this._scrollError += anchorErr;
}
items.set(this._anchorIdx, {pos: this._anchorPos, size: anchorSize});
this._first = (this._last = this._anchorIdx);
this._physicalMin = this._anchorPos;
this._physicalMax = this._anchorPos + anchorSize;
while (this._physicalMin > lower && this._first > 0) {
let size = this._getSize(--this._first);
if (size === undefined) {
this._stable = false;
size = this._getAverageSize();
}
let margin = this._metricsCache.getMarginSize(this._first + 1);
if (margin === undefined) {
this._stable = false;
margin = this._metricsCache.averageMarginSize;
}
this._physicalMin -= size + margin;
const pos = this._physicalMin;
items.set(this._first, {pos, size});
if (this._stable === false && this._estimate === false) {
break;
}
}
while (this._physicalMax < upper && this._last < this._totalItems - 1) {
let margin = this._metricsCache.getMarginSize(++this._last);
if (margin === undefined) {
this._stable = false;
margin = this._metricsCache.averageMarginSize;
}
let size = this._getSize(this._last);
if (size === undefined) {
this._stable = false;
size = this._getAverageSize();
}
const pos = this._physicalMax + margin;
items.set(this._last, {pos, size});
this._physicalMax += margin + size;
if (this._stable === false && this._estimate === false) {
break;
}
}
// This handles the cases where we were relying on estimated sizes.
const extentErr = this._calculateError();
if (extentErr) {
this._physicalMin -= extentErr;
this._physicalMax -= extentErr;
this._anchorPos -= extentErr;
this._scrollPosition -= extentErr;
items.forEach((item) => item.pos -= extentErr);
this._scrollError += extentErr;
}
if (this._stable) {
this._newPhysicalItems = this._physicalItems;
this._newPhysicalItems.clear();
this._physicalItems = items;
}
}
_calculateError(): number {
const { averageMarginSize } = this._metricsCache;
if (this._first === 0) {
return this._physicalMin - (this._metricsCache.getMarginSize(0) ?? averageMarginSize);
} else if (this._physicalMin <= 0) {
return this._physicalMin - (this._first * this._delta);
} else if (this._last === this._totalItems - 1) {
return (this._physicalMax + (this._metricsCache.getMarginSize(this._totalItems) ?? averageMarginSize)) - this._scrollSize;
} else if (this._physicalMax >= this._scrollSize) {
return (
(this._physicalMax - this._scrollSize) +
((this._totalItems - 1 - this._last) * this._delta));
}
return 0;
}
// TODO: Can this be made to inherit from base, with proper hooks?
_reflow() {
const {_first, _last, _scrollSize} = this;
this._updateScrollSize();
this._getActiveItems();
if (this._scrollSize !== _scrollSize) {
this._emitScrollSize();
}
this._updateVisibleIndices();
this._emitRange();
if (this._first === -1 && this._last === -1) {
this._resetReflowState();
} else if (
this._first !== _first || this._last !== _last ||
this._needsRemeasure) {
this._emitChildPositions();
this._emitScrollError();
} else {
this._emitChildPositions();
this._emitScrollError();
this._resetReflowState();
}
}
_resetReflowState() {
this._anchorIdx = null;
this._anchorPos = null;
this._stable = true;
}
_updateScrollSize() {
const { averageMarginSize } = this._metricsCache;
this._scrollSize = Math.max(1, this._totalItems * (averageMarginSize + this._getAverageSize()) + averageMarginSize);
}
/**
* Returns the average size (precise or estimated) of an item in the scrolling direction,
* including any surrounding space.
*/
protected get _delta(): number {
const { averageMarginSize } = this._metricsCache;
return this._getAverageSize() + averageMarginSize;
}
/**
* Returns the top and left positioning of the item at idx.
*/
_getItemPosition(idx: number): Positions {
return {
[this._positionDim]: this._getPosition(idx),
[this._secondaryPositionDim]: 0,
[offset(this.direction)]: -(this._metricsCache.getLeadingMarginValue(idx, this.direction) ?? this._metricsCache.averageMarginSize)
} as Positions;
}
/**
* Returns the height and width of the item at idx.
*/
_getItemSize(idx: number): Size {
return {
[this._sizeDim]: (this._getSize(idx) || this._getAverageSize()) + (this._metricsCache.getMarginSize(idx + 1) ?? this._metricsCache.averageMarginSize),
[this._secondarySizeDim]: this._itemSize[this._secondarySizeDim]
} as Size;
}
_viewDim2Changed() {
this._needsRemeasure = true;
this._scheduleReflow();
}
_emitRange() {
const remeasure = this._needsRemeasure;
const stable = this._stable;
this._needsRemeasure = false;
super._emitRange({remeasure, stable});
}
} | the_stack |
import { GraphQLError } from 'graphql';
import { areGraphQLErrors, extendedTypeof, isObject } from './utils';
/**
* The WebSocket sub-protocol used for the [GraphQL over WebSocket Protocol](/PROTOCOL.md).
*
* @category Common
*/
export const GRAPHQL_TRANSPORT_WS_PROTOCOL = 'graphql-transport-ws';
/**
* The deprecated subprotocol used by [subscriptions-transport-ws](https://github.com/apollographql/subscriptions-transport-ws).
*
* @private
*/
export const DEPRECATED_GRAPHQL_WS_PROTOCOL = 'graphql-ws';
/**
* `graphql-ws` expected and standard close codes of the [GraphQL over WebSocket Protocol](/PROTOCOL.md).
*
* @category Common
*/
export enum CloseCode {
InternalServerError = 4500,
InternalClientError = 4005,
BadRequest = 4400,
BadResponse = 4004,
/** Tried subscribing before connect ack */
Unauthorized = 4401,
Forbidden = 4403,
SubprotocolNotAcceptable = 4406,
ConnectionInitialisationTimeout = 4408,
ConnectionAcknowledgementTimeout = 4504,
/** Subscriber distinction is very important */
SubscriberAlreadyExists = 4409,
TooManyInitialisationRequests = 4429,
}
/**
* ID is a string type alias representing
* the globally unique ID used for identifying
* subscriptions established by the client.
*
* @category Common
*/
export type ID = string;
/** @category Common */
export interface Disposable {
/** Dispose of the instance and clear up resources. */
dispose: () => void | Promise<void>;
}
/**
* A representation of any set of values over any amount of time.
*
* @category Common
*/
export interface Sink<T = unknown> {
/** Next value arriving. */
next(value: T): void;
/**
* An error that has occured. Calling this function "closes" the sink.
* Besides the errors being `Error` and `readonly GraphQLError[]`, it
* can also be a `CloseEvent`, but to avoid bundling DOM typings because
* the client can run in Node env too, you should assert the close event
* type during implementation.
*/
error(error: unknown): void;
/** The sink has completed. This function "closes" the sink. */
complete(): void;
}
/**
* Types of messages allowed to be sent by the client/server over the WS protocol.
*
* @category Common
*/
export enum MessageType {
ConnectionInit = 'connection_init', // Client -> Server
ConnectionAck = 'connection_ack', // Server -> Client
Ping = 'ping', // bidirectional
Pong = 'pong', /// bidirectional
Subscribe = 'subscribe', // Client -> Server
Next = 'next', // Server -> Client
Error = 'error', // Server -> Client
Complete = 'complete', // bidirectional
}
/** @category Common */
export interface ConnectionInitMessage {
readonly type: MessageType.ConnectionInit;
readonly payload?: Record<string, unknown>;
}
/** @category Common */
export interface ConnectionAckMessage {
readonly type: MessageType.ConnectionAck;
readonly payload?: Record<string, unknown>;
}
/** @category Common */
export interface PingMessage {
readonly type: MessageType.Ping;
readonly payload?: Record<string, unknown>;
}
/** @category Common */
export interface PongMessage {
readonly type: MessageType.Pong;
readonly payload?: Record<string, unknown>;
}
/** @category Common */
export interface SubscribeMessage {
readonly id: ID;
readonly type: MessageType.Subscribe;
readonly payload: SubscribePayload;
}
/** @category Common */
export interface SubscribePayload {
readonly operationName?: string | null;
readonly query: string;
readonly variables?: Record<string, unknown> | null;
readonly extensions?: Record<string, unknown> | null;
}
/** @category Common */
export interface ExecutionResult<
Data = Record<string, unknown>,
Extensions = Record<string, unknown>,
> {
errors?: ReadonlyArray<GraphQLError>;
data?: Data | null;
hasNext?: boolean;
extensions?: Extensions;
}
/** @category Common */
export interface ExecutionPatchResult<
Data = unknown,
Extensions = Record<string, unknown>,
> {
errors?: ReadonlyArray<GraphQLError>;
data?: Data | null;
path?: ReadonlyArray<string | number>;
label?: string;
hasNext: boolean;
extensions?: Extensions;
}
/** @category Common */
export interface NextMessage {
readonly id: ID;
readonly type: MessageType.Next;
readonly payload: ExecutionResult | ExecutionPatchResult;
}
/** @category Common */
export interface ErrorMessage {
readonly id: ID;
readonly type: MessageType.Error;
readonly payload: readonly GraphQLError[];
}
/** @category Common */
export interface CompleteMessage {
readonly id: ID;
readonly type: MessageType.Complete;
}
/** @category Common */
export type Message<T extends MessageType = MessageType> =
T extends MessageType.ConnectionAck
? ConnectionAckMessage
: T extends MessageType.ConnectionInit
? ConnectionInitMessage
: T extends MessageType.Ping
? PingMessage
: T extends MessageType.Pong
? PongMessage
: T extends MessageType.Subscribe
? SubscribeMessage
: T extends MessageType.Next
? NextMessage
: T extends MessageType.Error
? ErrorMessage
: T extends MessageType.Complete
? CompleteMessage
: never;
/**
* Validates the message against the GraphQL over WebSocket Protocol.
*
* Invalid messages will throw descriptive errors.
*
* @category Common
*/
export function validateMessage(val: unknown): Message {
if (!isObject(val)) {
throw new Error(
`Message is expected to be an object, but got ${extendedTypeof(val)}`,
);
}
if (!val.type) {
throw new Error(`Message is missing the 'type' property`);
}
if (typeof val.type !== 'string') {
throw new Error(
`Message is expects the 'type' property to be a string, but got ${extendedTypeof(
val.type,
)}`,
);
}
switch (val.type) {
case MessageType.ConnectionInit:
case MessageType.ConnectionAck:
case MessageType.Ping:
case MessageType.Pong: {
if ('payload' in val && !isObject(val.payload)) {
throw new Error(
`"${val.type}" message expects the 'payload' property to be an object or missing, but got "${val.payload}"`,
);
}
break;
}
case MessageType.Subscribe: {
if (typeof val.id !== 'string') {
throw new Error(
`"${
val.type
}" message expects the 'id' property to be a string, but got ${extendedTypeof(
val.id,
)}`,
);
}
if (!val.id) {
throw new Error(
`"${val.type}" message requires a non-empty 'id' property`,
);
}
if (!isObject(val.payload)) {
throw new Error(
`"${
val.type
}" message expects the 'payload' property to be an object, but got ${extendedTypeof(
val.payload,
)}`,
);
}
if (typeof val.payload.query !== 'string') {
throw new Error(
`"${
val.type
}" message payload expects the 'query' property to be a string, but got ${extendedTypeof(
val.payload.query,
)}`,
);
}
if (val.payload.variables != null && !isObject(val.payload.variables)) {
throw new Error(
`"${
val.type
}" message payload expects the 'variables' property to be a an object or nullish or missing, but got ${extendedTypeof(
val.payload.variables,
)}`,
);
}
if (
val.payload.operationName != null &&
extendedTypeof(val.payload.operationName) !== 'string'
) {
throw new Error(
`"${
val.type
}" message payload expects the 'operationName' property to be a string or nullish or missing, but got ${extendedTypeof(
val.payload.operationName,
)}`,
);
}
if (val.payload.extensions != null && !isObject(val.payload.extensions)) {
throw new Error(
`"${
val.type
}" message payload expects the 'extensions' property to be a an object or nullish or missing, but got ${extendedTypeof(
val.payload.extensions,
)}`,
);
}
break;
}
case MessageType.Next: {
if (typeof val.id !== 'string') {
throw new Error(
`"${
val.type
}" message expects the 'id' property to be a string, but got ${extendedTypeof(
val.id,
)}`,
);
}
if (!val.id) {
throw new Error(
`"${val.type}" message requires a non-empty 'id' property`,
);
}
if (!isObject(val.payload)) {
throw new Error(
`"${
val.type
}" message expects the 'payload' property to be an object, but got ${extendedTypeof(
val.payload,
)}`,
);
}
break;
}
case MessageType.Error: {
if (typeof val.id !== 'string') {
throw new Error(
`"${
val.type
}" message expects the 'id' property to be a string, but got ${extendedTypeof(
val.id,
)}`,
);
}
if (!val.id) {
throw new Error(
`"${val.type}" message requires a non-empty 'id' property`,
);
}
if (!areGraphQLErrors(val.payload)) {
throw new Error(
`"${
val.type
}" message expects the 'payload' property to be an array of GraphQL errors, but got ${JSON.stringify(
val.payload,
)}`,
);
}
break;
}
case MessageType.Complete: {
if (typeof val.id !== 'string') {
throw new Error(
`"${
val.type
}" message expects the 'id' property to be a string, but got ${extendedTypeof(
val.id,
)}`,
);
}
if (!val.id) {
throw new Error(
`"${val.type}" message requires a non-empty 'id' property`,
);
}
break;
}
default:
throw new Error(`Invalid message 'type' property "${val.type}"`);
}
return val as unknown as Message;
}
/**
* Checks if the provided value is a valid GraphQL over WebSocket message.
*
* @deprecated Use `validateMessage` instead.
*
* @category Common
*/
export function isMessage(val: unknown): val is Message {
try {
validateMessage(val);
return true;
} catch {
return false;
}
}
/**
* Function for transforming values within a message during JSON parsing
* The values are produced by parsing the incoming raw JSON.
*
* Read more about using it:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#using_the_reviver_parameter
*
* @category Common
*/
export type JSONMessageReviver = (this: any, key: string, value: any) => any;
/**
* Parses the raw websocket message data to a valid message.
*
* @category Common
*/
export function parseMessage(
data: unknown,
reviver?: JSONMessageReviver,
): Message {
try {
return validateMessage(data);
} catch {
if (typeof data !== 'string') {
throw new Error('Only strings are parsable messages');
}
const message = JSON.parse(data, reviver);
return validateMessage(message);
}
}
/**
* Function that allows customization of the produced JSON string
* for the elements of an outgoing `Message` object.
*
* Read more about using it:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_replacer_parameter
*
* @category Common
*/
export type JSONMessageReplacer = (this: any, key: string, value: any) => any;
/**
* Stringifies a valid message ready to be sent through the socket.
*
* @category Common
*/
export function stringifyMessage<T extends MessageType>(
msg: Message<T>,
replacer?: JSONMessageReplacer,
): string {
validateMessage(msg);
return JSON.stringify(msg, replacer);
} | the_stack |
import {IOutParam} from "./Interfaces/IOutParam";
import {PropertyDefinitionBase} from "./PropertyDefinitions/PropertyDefinitionBase";
import {StringHelper} from "./ExtensionMethods";
export interface IndexerWithStringKey<TValue> {
[index: string]: TValue;
}
export interface IndexerWithNumericKey<TValue> {
[index: number]: TValue;
}
export interface KeyValuePair<TKey, TValue> {
key: TKey;
value: TValue;
}
interface StringPropertyDefinitionArray<TKey, TValue> {
[index: string]: TValue;
}
export interface StringKeyPicker<TValue> {
(value: TValue): string;
}
export class Dictionary<TKey, TValue>{
private keys: string[] = [];
private keysToObjs: IndexerWithStringKey<TKey> = {}
private objects: IndexerWithStringKey<TValue> = {};// {[key:string]:TValue};
private keyPicker: StringKeyPicker<TKey>;
/** get all keys */
get Keys(): TKey[] {
var keys: TKey[] = [];
for (var key of this.keys) {
keys.push(this.keysToObjs[key]);
}
return keys;
}
/**get all items in key,value pair array */
get Items(): KeyValuePair<TKey, TValue>[] {
var items: KeyValuePair<TKey, TValue>[] = [];
for (var k of this.keys) {
items.push({ key: this.keysToObjs[k], value: this.objects[k] });
}
return items;
}
/** get all values */
get Values(): TValue[] {
var ret: TValue[] = [];
for (var key of this.keys) {
ret.push(this.objects[key]);
}
return ret;
}
/** get number of objects in dictionary */
get length(): number { return this.keys.length; }
/** get number of objects in the dictionary */
get Count(): number { return this.length; }
constructor(keyPickerFunc: StringKeyPicker<TKey>) {
if (typeof keyPickerFunc !== 'function')
throw new Error("Dictionary - keyPickerFunc must be a function");
this.keyPicker = keyPickerFunc;
}
/** get string values of all keys */
getStringKeys(): string[] { return this.keys; }
/** add value or update the value for key */
Add(key: TKey, value: TValue): void { return this.addUpdate(key, value); }
/** add value or update the value for key */
addUpdate(key: TKey, value: TValue): void {
var strKey = this.keyPicker(key);
if (StringHelper.IsNullOrEmpty(strKey))
throw new Error("Dictionary - invalid key object, keyPicker return null");
if (!this.containsKey(strKey)) {
this.keys.push(strKey);
}
this.keysToObjs[strKey] = key;
this.objects[strKey] = value;
}
/** Set value for key */
set(key: TKey, value: TValue): void {
this.addUpdate(key, value);
}
/** sets the new entry with old value or optionally new value, use isnull parameter to make sure you are setting a null value instead of old value */
setEntry(oldKey: string, newKey: TKey): void;
setEntry(oldKey: TKey, newKey: TKey): void;
setEntry(oldKey: string | TKey, newKey: TKey): void {
var strKey: string = <any>oldKey;
if (typeof oldKey !== 'string')
strKey = this.keyPicker(oldKey);
if (StringHelper.IsNullOrEmpty(strKey))
throw new Error("Dictionary - invalid key object, keyPicker return null");
if (this.containsKey(strKey)) {
throw new Error("Dictionary - does not contain old key");
}
var oldval = this.objects[strKey];
//oldval = null:value;
this.remove(strKey);
this.addUpdate(newKey, oldval);
}
/** get value for key */
get(key: string): TValue;
get(key: TKey): TValue;
get(key: string | TKey): TValue {
var strKey: string = <any>key;
if (typeof key !== 'string')
strKey = this.keyPicker(key);
if (StringHelper.IsNullOrEmpty(strKey))
throw new Error("Dictionary - invalid key object, keyPicker return null");
return this.objects[strKey];
}
/**try get value for key or return exception in IOutParam.exception */
tryGetValue(key: string, outValue: IOutParam<TValue>): boolean;
tryGetValue(key: TKey, outValue: IOutParam<TValue>): boolean;
tryGetValue(key: string | TKey, outValue: IOutParam<TValue>): boolean {
outValue.outValue = null;
outValue.success = false;
var strKey: string = <any>key;
if (typeof key !== 'string')
strKey = this.keyPicker(key);
if (StringHelper.IsNullOrEmpty(strKey)) {
outValue.exception = new Error("Dictionary - invalid key,not a string value or keyPicker return null");
return false;
}
if (this.containsKey(strKey)) {
outValue.outValue = this.objects[strKey]
outValue.success = true;
return true;
}
return false;
}
/**remove key and value for key */
remove(key: string): boolean;
remove(key: TKey): boolean;
remove(key: string | TKey): boolean {
var strKey: string = <any>key;
if (typeof key !== 'string')
strKey = this.keyPicker(key);
if (StringHelper.IsNullOrEmpty(strKey))
throw new Error("Dictionary - invalid key,not a string value or keyPicker return null");
if (!this.containsKey(strKey))
return false;
var keyindex = this.keys.indexOf(strKey);
var delKeyAr: string[] = this.keys.splice(keyindex, 1);
var delkeyObj: boolean = delete this.keysToObjs[strKey];
var delObj: boolean = delete this.objects[strKey];
return delKeyAr.length > 0 && delkeyObj && delObj;
}
/** check if key exist */
containsKey(key: string): boolean;
containsKey(key: TKey): boolean;
containsKey(key: string | TKey): boolean {
var strKey: string = <any>key;
if (typeof key !== 'string')
strKey = this.keyPicker(key);
if (StringHelper.IsNullOrEmpty(strKey))
throw new Error("Dictionary - invalid key object, keyPicker return null");
if (this.keys.indexOf(strKey) >= 0)
return true;
return false;
}
/** clear dictionary */
clear(): void {
this.keys = [];
this.keysToObjs = {};
this.objects = {};
}
}
/**@internal */
export class StringPropertyDefinitionBaseDictionary<TKey extends string, TValue extends PropertyDefinitionBase> extends Dictionary<string, TValue>{
//private keys: string[] = [];
//private objects: StringPropertyDefinitionArray<TKey, TValue> = {};// {[key:string]:TValue};
}
/**@internal */
export class PropertyDefinitionDictionary extends StringPropertyDefinitionBaseDictionary<string, PropertyDefinitionBase>{
}
export interface IndexerWithEnumKey<TKey, TValue> {
[index: number]: TValue;
}
interface PropDictionaryKey {
name?: string;
key?: string;
id?: string;
}
interface PropDictionaryValue<TKey, TValue> {
key: string;
keyObject: TKey;
value: TValue;
}
interface StringArray<TKey, TValue> {
[index: string]: PropDictionaryValue<TKey, TValue>;
}
/**@internal */
export class DictionaryWithStringKey<TValue> extends Dictionary<string, TValue>{
constructor() {
super((value) => value);
}
}
/**@internal */
export class DictionaryWithNumericKey<TValue> extends Dictionary<number, TValue>{
constructor() {
super((value) => value.toString());
}
}
/**@internal */
export class DictionaryWithPropertyDefitionKey<TKey extends { Name?: string }, TValue> extends Dictionary<TKey, TValue>{
constructor() {
super((value: TKey) => value.Name);
}
}
class PropDictionary2<TKey extends { Name?: string }, TValue>{
private keys: string[] = [];
private objects: StringArray<TKey, TValue> = {};// {[key:string]:TValue};
get KeyNames(): string[] { return this.keys; }
get Keys(): TKey[] {
var ret: TKey[] = [];
for (var key in this.objects) {
ret.push(this.objects[key].keyObject);
}
return ret;
}
get Items(): KeyValuePair<TKey, TValue>[] {
var all: any[] = [];
for (var obj in this.objects) {
all.push({ key: this.objects[obj].keyObject, value: this.objects[obj].value });
}
return all;
}
get Values(): TValue[] {
var ret: TValue[] = [];
for (var key in this.objects) {
ret.push(this.objects[key].value);
}
return ret;
}
get length(): number { return this.keys.length; }
constructor() {
}
add(key: TKey, value: TValue): void {
var keyString = key.Name;
if (this.keys.indexOf(key.Name) == -1) {
this.keys.push(keyString);
}
this.objects[keyString] = { key: keyString, keyObject: key, value: value };
}
set(key: TKey, value: TValue): void {
this.add(key, value);
}
setEntry(oldKeyString: string, oldKey: TKey, value?: TValue, isNull: boolean = false): void {
if (this.keys.indexOf(oldKeyString) == -1 || typeof this.objects[oldKeyString] === 'undefined') {
throw new Error("invalid old keystring");
}
var oldval = isNull ? null : value || this.objects[oldKeyString].value;
//oldval = null:value;
this.objects[oldKeyString] = { key: oldKey.Name, keyObject: oldKey, value: value || oldval };
}
get(key: TKey): TValue {
if (StringHelper.IsNullOrEmpty(key.Name))
throw new Error("invalid operation, object does not have valid Name property");
//if(this.keys.indexOf(key.Name)>=0)
var val = this.objects[key.Name]
return val ? val.value : undefined;
}
tryGet(key: TKey, outValue: IOutParam<TValue>): boolean {
outValue.outValue = null;
outValue.success = false;
if (StringHelper.IsNullOrEmpty(key.Name))
outValue.exception = new Error("invalid operation, object does not have valid Name property");
if (this.containsKey(key)) {
var val = this.objects[key.Name]
outValue.outValue = val ? val.value : null;
return true;
}
return false;
}
remove(key: TKey): boolean {
if (StringHelper.IsNullOrEmpty(key.Name)) throw new Error("missing keyString")
return delete this.objects[key.Name];
}
containsKey(key: TKey): boolean {
if (this.keys.indexOf(key.Name) >= 0 || typeof this.objects[key.Name] !== 'undefined')
return true;
return false;
}
clear(): void {
this.keys = [];
this.objects = {};
}
} | the_stack |
import {
GraphQLResolveInfo,
GraphQLScalarType,
GraphQLScalarTypeConfig
} from "graphql";
export type Maybe<T> = T | null;
export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] };
export type MakeOptional<T, K extends keyof T> = Omit<T, K> &
{ [SubKey in K]?: Maybe<T[SubKey]> };
export type MakeMaybe<T, K extends keyof T> = Omit<T, K> &
{ [SubKey in K]: Maybe<T[SubKey]> };
export type RequireFields<T, K extends keyof T> = {
[X in Exclude<keyof T, K>]?: T[X];
} &
{ [P in K]-?: NonNullable<T[P]> };
/** All built-in and custom scalars, mapped to their actual values */
export type Scalars = {
ID: string;
String: string;
Boolean: boolean;
Int: number;
Float: number;
Date: any;
};
export type IEntry = {
__typename?: "Entry";
id: Maybe<Scalars["ID"]>;
title: Maybe<Scalars["String"]>;
author: Maybe<IAuthor>;
content: Maybe<Scalars["String"]>;
public: Maybe<Scalars["Boolean"]>;
dateAdded: Maybe<Scalars["Date"]>;
dateModified: Maybe<Scalars["Date"]>;
excerpt: Maybe<Scalars["String"]>;
user: Maybe<Scalars["String"]>;
};
export type IAuthor = {
__typename?: "Author";
username: Maybe<Scalars["String"]>;
gradient: Maybe<Array<Maybe<Scalars["String"]>>>;
};
export type IPreview = {
__typename?: "Preview";
title: Maybe<Scalars["String"]>;
id: Maybe<Scalars["ID"]>;
content: Maybe<Scalars["String"]>;
author: Maybe<IAuthor>;
dateAdded: Maybe<Scalars["Date"]>;
};
export type IUser = {
__typename?: "User";
username: Scalars["String"];
email: Scalars["String"];
admin: Maybe<Scalars["Boolean"]>;
};
export type IUserSettingsInput = {
username: Maybe<Scalars["String"]>;
email: Maybe<Scalars["String"]>;
};
export type IAuthUserPayload = {
__typename?: "AuthUserPayload";
token: Maybe<Scalars["String"]>;
};
export type IUsageDetails = {
__typename?: "UsageDetails";
entryCount: Scalars["Int"];
privateEntries: Scalars["Int"];
publicEntries: Scalars["Int"];
};
export type IMe = {
__typename?: "Me";
details: Maybe<IUser>;
token: Maybe<Scalars["String"]>;
usage: IUsageDetails;
};
export type IQuery = {
__typename?: "Query";
/** Markdown document */
entry: Maybe<IEntry>;
/** List of Markdown documents */
feed: Array<IEntry>;
/** Public preview of Markdown document */
preview: Maybe<IPreview>;
/** User Settings */
settings: Maybe<IUser>;
me: Maybe<IMe>;
};
export type IQueryEntryArgs = {
id: Scalars["ID"];
};
export type IQueryPreviewArgs = {
id: Scalars["ID"];
};
export type IMutation = {
__typename?: "Mutation";
createEntry: Maybe<IEntry>;
updateEntry: Maybe<IEntry>;
deleteEntry: Maybe<IEntry>;
createUser: Maybe<IAuthUserPayload>;
authenticateUser: Maybe<IAuthUserPayload>;
updateUserSettings: Maybe<IUser>;
updatePassword: Maybe<IAuthUserPayload>;
};
export type IMutationCreateEntryArgs = {
content: Maybe<Scalars["String"]>;
title: Maybe<Scalars["String"]>;
};
export type IMutationUpdateEntryArgs = {
id: Scalars["String"];
content: Scalars["String"];
title: Scalars["String"];
status: Scalars["Boolean"];
};
export type IMutationDeleteEntryArgs = {
id: Scalars["ID"];
};
export type IMutationCreateUserArgs = {
username: Scalars["String"];
email: Scalars["String"];
password: Scalars["String"];
};
export type IMutationAuthenticateUserArgs = {
username: Scalars["String"];
password: Scalars["String"];
};
export type IMutationUpdateUserSettingsArgs = {
settings: IUserSettingsInput;
};
export type IMutationUpdatePasswordArgs = {
currentPassword: Scalars["String"];
newPassword: Scalars["String"];
};
export type IEntryInfoFragment = { __typename?: "Entry" } & Pick<
IEntry,
"title" | "dateAdded" | "id" | "public"
>;
export type IAllPostsQueryVariables = Exact<{ [key: string]: never }>;
export type IAllPostsQuery = { __typename?: "Query" } & {
feed: Array<{ __typename?: "Entry" } & IEntryInfoFragment>;
};
export type IEditQueryVariables = Exact<{
id: Scalars["ID"];
}>;
export type IEditQuery = { __typename?: "Query" } & {
entry: Maybe<
{ __typename?: "Entry" } & Pick<IEntry, "content"> & IEntryInfoFragment
>;
};
export type IPreviewQueryVariables = Exact<{
id: Scalars["ID"];
}>;
export type IPreviewQuery = { __typename?: "Query" } & {
preview: Maybe<
{ __typename?: "Preview" } & Pick<
IPreview,
"title" | "dateAdded" | "id" | "content"
> & { author: Maybe<{ __typename?: "Author" } & Pick<IAuthor, "username">> }
>;
};
export type IUserDetailsQueryVariables = Exact<{ [key: string]: never }>;
export type IUserDetailsQuery = { __typename?: "Query" } & {
settings: Maybe<{ __typename?: "User" } & Pick<IUser, "username" | "email">>;
me: Maybe<
{ __typename?: "Me" } & {
usage: { __typename?: "UsageDetails" } & Pick<
IUsageDetails,
"entryCount" | "publicEntries" | "privateEntries"
>;
}
>;
};
export type IUpdateEntryMutationVariables = Exact<{
id: Scalars["String"];
content: Scalars["String"];
title: Scalars["String"];
status: Scalars["Boolean"];
}>;
export type IUpdateEntryMutation = { __typename?: "Mutation" } & {
updateEntry: Maybe<
{ __typename?: "Entry" } & Pick<IEntry, "content"> & IEntryInfoFragment
>;
};
export type ICreateEntryMutationVariables = Exact<{
content: Maybe<Scalars["String"]>;
title: Maybe<Scalars["String"]>;
}>;
export type ICreateEntryMutation = { __typename?: "Mutation" } & {
createEntry: Maybe<{ __typename?: "Entry" } & IEntryInfoFragment>;
};
export type IRemoveEntryMutationVariables = Exact<{
id: Scalars["ID"];
}>;
export type IRemoveEntryMutation = { __typename?: "Mutation" } & {
deleteEntry: Maybe<{ __typename?: "Entry" } & Pick<IEntry, "title" | "id">>;
};
export type ILoginUserMutationVariables = Exact<{
username: Scalars["String"];
password: Scalars["String"];
}>;
export type ILoginUserMutation = { __typename?: "Mutation" } & {
authenticateUser: Maybe<
{ __typename?: "AuthUserPayload" } & Pick<IAuthUserPayload, "token">
>;
};
export type ICreateUserMutationVariables = Exact<{
username: Scalars["String"];
email: Scalars["String"];
password: Scalars["String"];
}>;
export type ICreateUserMutation = { __typename?: "Mutation" } & {
createUser: Maybe<
{ __typename?: "AuthUserPayload" } & Pick<IAuthUserPayload, "token">
>;
};
export type IUpdateUserSettingsMutationVariables = Exact<{
settings: IUserSettingsInput;
}>;
export type IUpdateUserSettingsMutation = { __typename?: "Mutation" } & {
updateUserSettings: Maybe<
{ __typename?: "User" } & Pick<IUser, "username" | "email">
>;
};
export type IUpdatePasswordMutationVariables = Exact<{
current: Scalars["String"];
newPassword: Scalars["String"];
}>;
export type IUpdatePasswordMutation = { __typename?: "Mutation" } & {
updatePassword: Maybe<
{ __typename?: "AuthUserPayload" } & Pick<IAuthUserPayload, "token">
>;
};
export type IIsMeQueryVariables = Exact<{ [key: string]: never }>;
export type IIsMeQuery = { __typename?: "Query" } & {
me: Maybe<{ __typename?: "Me" } & Pick<IMe, "token">>;
};
export type WithIndex<TObject> = TObject & Record<string, any>;
export type ResolversObject<TObject> = WithIndex<TObject>;
export type ResolverTypeWrapper<T> = Promise<T> | T;
export type LegacyStitchingResolver<TResult, TParent, TContext, TArgs> = {
fragment: string;
resolve: ResolverFn<TResult, TParent, TContext, TArgs>;
};
export type NewStitchingResolver<TResult, TParent, TContext, TArgs> = {
selectionSet: string;
resolve: ResolverFn<TResult, TParent, TContext, TArgs>;
};
export type StitchingResolver<TResult, TParent, TContext, TArgs> =
| LegacyStitchingResolver<TResult, TParent, TContext, TArgs>
| NewStitchingResolver<TResult, TParent, TContext, TArgs>;
export type Resolver<TResult, TParent = {}, TContext = {}, TArgs = {}> =
| ResolverFn<TResult, TParent, TContext, TArgs>
| StitchingResolver<TResult, TParent, TContext, TArgs>;
export type ResolverFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => Promise<TResult> | TResult;
export type SubscriptionSubscribeFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => AsyncIterator<TResult> | Promise<AsyncIterator<TResult>>;
export type SubscriptionResolveFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => TResult | Promise<TResult>;
export interface SubscriptionSubscriberObject<
TResult,
TKey extends string,
TParent,
TContext,
TArgs
> {
subscribe: SubscriptionSubscribeFn<
{ [key in TKey]: TResult },
TParent,
TContext,
TArgs
>;
resolve?: SubscriptionResolveFn<
TResult,
{ [key in TKey]: TResult },
TContext,
TArgs
>;
}
export interface SubscriptionResolverObject<TResult, TParent, TContext, TArgs> {
subscribe: SubscriptionSubscribeFn<any, TParent, TContext, TArgs>;
resolve: SubscriptionResolveFn<TResult, any, TContext, TArgs>;
}
export type SubscriptionObject<
TResult,
TKey extends string,
TParent,
TContext,
TArgs
> =
| SubscriptionSubscriberObject<TResult, TKey, TParent, TContext, TArgs>
| SubscriptionResolverObject<TResult, TParent, TContext, TArgs>;
export type SubscriptionResolver<
TResult,
TKey extends string,
TParent = {},
TContext = {},
TArgs = {}
> =
| ((...args: any[]) => SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>)
| SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>;
export type TypeResolveFn<TTypes, TParent = {}, TContext = {}> = (
parent: TParent,
context: TContext,
info: GraphQLResolveInfo
) => Maybe<TTypes> | Promise<Maybe<TTypes>>;
export type IsTypeOfResolverFn<T = {}, TContext = {}> = (
obj: T,
context: TContext,
info: GraphQLResolveInfo
) => boolean | Promise<boolean>;
export type NextResolverFn<T> = () => Promise<T>;
export type DirectiveResolverFn<
TResult = {},
TParent = {},
TContext = {},
TArgs = {}
> = (
next: NextResolverFn<TResult>,
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => TResult | Promise<TResult>;
/** Mapping between all available schema types and the resolvers types */
export type IResolversTypes = ResolversObject<{
Date: ResolverTypeWrapper<Scalars["Date"]>;
Entry: ResolverTypeWrapper<IEntry>;
ID: ResolverTypeWrapper<Scalars["ID"]>;
String: ResolverTypeWrapper<Scalars["String"]>;
Boolean: ResolverTypeWrapper<Scalars["Boolean"]>;
Author: ResolverTypeWrapper<IAuthor>;
Preview: ResolverTypeWrapper<IPreview>;
User: ResolverTypeWrapper<IUser>;
UserSettingsInput: IUserSettingsInput;
AuthUserPayload: ResolverTypeWrapper<IAuthUserPayload>;
UsageDetails: ResolverTypeWrapper<IUsageDetails>;
Int: ResolverTypeWrapper<Scalars["Int"]>;
Me: ResolverTypeWrapper<IMe>;
Query: ResolverTypeWrapper<{}>;
Mutation: ResolverTypeWrapper<{}>;
}>;
/** Mapping between all available schema types and the resolvers parents */
export type IResolversParentTypes = ResolversObject<{
Date: Scalars["Date"];
Entry: IEntry;
ID: Scalars["ID"];
String: Scalars["String"];
Boolean: Scalars["Boolean"];
Author: IAuthor;
Preview: IPreview;
User: IUser;
UserSettingsInput: IUserSettingsInput;
AuthUserPayload: IAuthUserPayload;
UsageDetails: IUsageDetails;
Int: Scalars["Int"];
Me: IMe;
Query: {};
Mutation: {};
}>;
export interface IDateScalarConfig
extends GraphQLScalarTypeConfig<IResolversTypes["Date"], any> {
name: "Date";
}
export type IEntryResolvers<
ContextType = any,
ParentType extends IResolversParentTypes["Entry"] = IResolversParentTypes["Entry"]
> = ResolversObject<{
id: Resolver<Maybe<IResolversTypes["ID"]>, ParentType, ContextType>;
title: Resolver<Maybe<IResolversTypes["String"]>, ParentType, ContextType>;
author: Resolver<Maybe<IResolversTypes["Author"]>, ParentType, ContextType>;
content: Resolver<Maybe<IResolversTypes["String"]>, ParentType, ContextType>;
public: Resolver<Maybe<IResolversTypes["Boolean"]>, ParentType, ContextType>;
dateAdded: Resolver<Maybe<IResolversTypes["Date"]>, ParentType, ContextType>;
dateModified: Resolver<Maybe<IResolversTypes["Date"]>, ParentType, ContextType>;
excerpt: Resolver<Maybe<IResolversTypes["String"]>, ParentType, ContextType>;
user: Resolver<Maybe<IResolversTypes["String"]>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}>;
export type IAuthorResolvers<
ContextType = any,
ParentType extends IResolversParentTypes["Author"] = IResolversParentTypes["Author"]
> = ResolversObject<{
username: Resolver<Maybe<IResolversTypes["String"]>, ParentType, ContextType>;
gradient: Resolver<
Maybe<Array<Maybe<IResolversTypes["String"]>>>,
ParentType,
ContextType
>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}>;
export type IPreviewResolvers<
ContextType = any,
ParentType extends IResolversParentTypes["Preview"] = IResolversParentTypes["Preview"]
> = ResolversObject<{
title: Resolver<Maybe<IResolversTypes["String"]>, ParentType, ContextType>;
id: Resolver<Maybe<IResolversTypes["ID"]>, ParentType, ContextType>;
content: Resolver<Maybe<IResolversTypes["String"]>, ParentType, ContextType>;
author: Resolver<Maybe<IResolversTypes["Author"]>, ParentType, ContextType>;
dateAdded: Resolver<Maybe<IResolversTypes["Date"]>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}>;
export type IUserResolvers<
ContextType = any,
ParentType extends IResolversParentTypes["User"] = IResolversParentTypes["User"]
> = ResolversObject<{
username: Resolver<IResolversTypes["String"], ParentType, ContextType>;
email: Resolver<IResolversTypes["String"], ParentType, ContextType>;
admin: Resolver<Maybe<IResolversTypes["Boolean"]>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}>;
export type IAuthUserPayloadResolvers<
ContextType = any,
ParentType extends IResolversParentTypes["AuthUserPayload"] = IResolversParentTypes["AuthUserPayload"]
> = ResolversObject<{
token: Resolver<Maybe<IResolversTypes["String"]>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}>;
export type IUsageDetailsResolvers<
ContextType = any,
ParentType extends IResolversParentTypes["UsageDetails"] = IResolversParentTypes["UsageDetails"]
> = ResolversObject<{
entryCount: Resolver<IResolversTypes["Int"], ParentType, ContextType>;
privateEntries: Resolver<IResolversTypes["Int"], ParentType, ContextType>;
publicEntries: Resolver<IResolversTypes["Int"], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}>;
export type IMeResolvers<
ContextType = any,
ParentType extends IResolversParentTypes["Me"] = IResolversParentTypes["Me"]
> = ResolversObject<{
details: Resolver<Maybe<IResolversTypes["User"]>, ParentType, ContextType>;
token: Resolver<Maybe<IResolversTypes["String"]>, ParentType, ContextType>;
usage: Resolver<IResolversTypes["UsageDetails"], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}>;
export type IQueryResolvers<
ContextType = any,
ParentType extends IResolversParentTypes["Query"] = IResolversParentTypes["Query"]
> = ResolversObject<{
entry: Resolver<
Maybe<IResolversTypes["Entry"]>,
ParentType,
ContextType,
RequireFields<IQueryEntryArgs, "id">
>;
feed: Resolver<Array<IResolversTypes["Entry"]>, ParentType, ContextType>;
preview: Resolver<
Maybe<IResolversTypes["Preview"]>,
ParentType,
ContextType,
RequireFields<IQueryPreviewArgs, "id">
>;
settings: Resolver<Maybe<IResolversTypes["User"]>, ParentType, ContextType>;
me: Resolver<Maybe<IResolversTypes["Me"]>, ParentType, ContextType>;
}>;
export type IMutationResolvers<
ContextType = any,
ParentType extends IResolversParentTypes["Mutation"] = IResolversParentTypes["Mutation"]
> = ResolversObject<{
createEntry: Resolver<
Maybe<IResolversTypes["Entry"]>,
ParentType,
ContextType,
RequireFields<IMutationCreateEntryArgs, never>
>;
updateEntry: Resolver<
Maybe<IResolversTypes["Entry"]>,
ParentType,
ContextType,
RequireFields<IMutationUpdateEntryArgs, "id" | "content" | "title" | "status">
>;
deleteEntry: Resolver<
Maybe<IResolversTypes["Entry"]>,
ParentType,
ContextType,
RequireFields<IMutationDeleteEntryArgs, "id">
>;
createUser: Resolver<
Maybe<IResolversTypes["AuthUserPayload"]>,
ParentType,
ContextType,
RequireFields<IMutationCreateUserArgs, "username" | "email" | "password">
>;
authenticateUser: Resolver<
Maybe<IResolversTypes["AuthUserPayload"]>,
ParentType,
ContextType,
RequireFields<IMutationAuthenticateUserArgs, "username" | "password">
>;
updateUserSettings: Resolver<
Maybe<IResolversTypes["User"]>,
ParentType,
ContextType,
RequireFields<IMutationUpdateUserSettingsArgs, "settings">
>;
updatePassword: Resolver<
Maybe<IResolversTypes["AuthUserPayload"]>,
ParentType,
ContextType,
RequireFields<IMutationUpdatePasswordArgs, "currentPassword" | "newPassword">
>;
}>;
export type IResolvers<ContextType = any> = ResolversObject<{
Date: GraphQLScalarType;
Entry: IEntryResolvers<ContextType>;
Author: IAuthorResolvers<ContextType>;
Preview: IPreviewResolvers<ContextType>;
User: IUserResolvers<ContextType>;
AuthUserPayload: IAuthUserPayloadResolvers<ContextType>;
UsageDetails: IUsageDetailsResolvers<ContextType>;
Me: IMeResolvers<ContextType>;
Query: IQueryResolvers<ContextType>;
Mutation: IMutationResolvers<ContextType>;
}>; | the_stack |
import { HttpClient, HttpResponse, HttpEvent } from '@angular/common/http';
import { Inject, Injectable, Optional } from '@angular/core';
import { NotificationsAPIClientInterface } from './notifications-api-client.interface';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { USE_DOMAIN, USE_HTTP_OPTIONS, NotificationsAPIClient } from './notifications-api-client.service';
import { DefaultHttpOptions, HttpOptions } from '../../types';
import * as models from '../../models';
import * as guards from '../../guards';
@Injectable()
export class GuardedNotificationsAPIClient extends NotificationsAPIClient implements NotificationsAPIClientInterface {
constructor(
readonly httpClient: HttpClient,
@Optional() @Inject(USE_DOMAIN) domain?: string,
@Optional() @Inject(USE_HTTP_OPTIONS) options?: DefaultHttpOptions,
) {
super(httpClient, domain, options);
}
/**
* List your notifications.
* List all notifications for the current user, grouped by repository.
*
* Response generated for [ 200 ] HTTP response code.
*/
getNotifications(
args?: NotificationsAPIClientInterface['getNotificationsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Notifications>;
getNotifications(
args?: NotificationsAPIClientInterface['getNotificationsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Notifications>>;
getNotifications(
args?: NotificationsAPIClientInterface['getNotificationsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Notifications>>;
getNotifications(
args: NotificationsAPIClientInterface['getNotificationsParams'] = {},
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Notifications | HttpResponse<models.Notifications> | HttpEvent<models.Notifications>> {
return super.getNotifications(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isNotifications(res) || console.error(`TypeGuard for response 'models.Notifications' caught inconsistency.`, res)));
}
/**
* Mark as read.
* Marking a notification as "read" removes it from the default view on GitHub.com.
*
* Response generated for [ 205 ] HTTP response code.
*/
putNotifications(
args: Exclude<NotificationsAPIClientInterface['putNotificationsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
putNotifications(
args: Exclude<NotificationsAPIClientInterface['putNotificationsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
putNotifications(
args: Exclude<NotificationsAPIClientInterface['putNotificationsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
putNotifications(
args: Exclude<NotificationsAPIClientInterface['putNotificationsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.putNotifications(args, requestHttpOptions, observe);
}
/**
* View a single thread.
* Response generated for [ 200 ] HTTP response code.
*/
getNotificationsThreadsId(
args: Exclude<NotificationsAPIClientInterface['getNotificationsThreadsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Notifications>;
getNotificationsThreadsId(
args: Exclude<NotificationsAPIClientInterface['getNotificationsThreadsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Notifications>>;
getNotificationsThreadsId(
args: Exclude<NotificationsAPIClientInterface['getNotificationsThreadsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Notifications>>;
getNotificationsThreadsId(
args: Exclude<NotificationsAPIClientInterface['getNotificationsThreadsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Notifications | HttpResponse<models.Notifications> | HttpEvent<models.Notifications>> {
return super.getNotificationsThreadsId(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isNotifications(res) || console.error(`TypeGuard for response 'models.Notifications' caught inconsistency.`, res)));
}
/**
* Mark a thread as read
* Response generated for [ 205 ] HTTP response code.
*/
patchNotificationsThreadsId(
args: Exclude<NotificationsAPIClientInterface['patchNotificationsThreadsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
patchNotificationsThreadsId(
args: Exclude<NotificationsAPIClientInterface['patchNotificationsThreadsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
patchNotificationsThreadsId(
args: Exclude<NotificationsAPIClientInterface['patchNotificationsThreadsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
patchNotificationsThreadsId(
args: Exclude<NotificationsAPIClientInterface['patchNotificationsThreadsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.patchNotificationsThreadsId(args, requestHttpOptions, observe);
}
/**
* Delete a Thread Subscription.
* Response generated for [ 204 ] HTTP response code.
*/
deleteNotificationsThreadsIdSubscription(
args: Exclude<NotificationsAPIClientInterface['deleteNotificationsThreadsIdSubscriptionParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteNotificationsThreadsIdSubscription(
args: Exclude<NotificationsAPIClientInterface['deleteNotificationsThreadsIdSubscriptionParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteNotificationsThreadsIdSubscription(
args: Exclude<NotificationsAPIClientInterface['deleteNotificationsThreadsIdSubscriptionParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deleteNotificationsThreadsIdSubscription(
args: Exclude<NotificationsAPIClientInterface['deleteNotificationsThreadsIdSubscriptionParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.deleteNotificationsThreadsIdSubscription(args, requestHttpOptions, observe);
}
/**
* Get a Thread Subscription.
* Response generated for [ 200 ] HTTP response code.
*/
getNotificationsThreadsIdSubscription(
args: Exclude<NotificationsAPIClientInterface['getNotificationsThreadsIdSubscriptionParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Subscription>;
getNotificationsThreadsIdSubscription(
args: Exclude<NotificationsAPIClientInterface['getNotificationsThreadsIdSubscriptionParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Subscription>>;
getNotificationsThreadsIdSubscription(
args: Exclude<NotificationsAPIClientInterface['getNotificationsThreadsIdSubscriptionParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Subscription>>;
getNotificationsThreadsIdSubscription(
args: Exclude<NotificationsAPIClientInterface['getNotificationsThreadsIdSubscriptionParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Subscription | HttpResponse<models.Subscription> | HttpEvent<models.Subscription>> {
return super.getNotificationsThreadsIdSubscription(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isSubscription(res) || console.error(`TypeGuard for response 'models.Subscription' caught inconsistency.`, res)));
}
/**
* Set a Thread Subscription.
* This lets you subscribe to a thread, or ignore it. Subscribing to a thread
* is unnecessary if the user is already subscribed to the repository. Ignoring
* a thread will mute all future notifications (until you comment or get @mentioned).
*
* Response generated for [ 200 ] HTTP response code.
*/
putNotificationsThreadsIdSubscription(
args: Exclude<NotificationsAPIClientInterface['putNotificationsThreadsIdSubscriptionParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Subscription>;
putNotificationsThreadsIdSubscription(
args: Exclude<NotificationsAPIClientInterface['putNotificationsThreadsIdSubscriptionParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Subscription>>;
putNotificationsThreadsIdSubscription(
args: Exclude<NotificationsAPIClientInterface['putNotificationsThreadsIdSubscriptionParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Subscription>>;
putNotificationsThreadsIdSubscription(
args: Exclude<NotificationsAPIClientInterface['putNotificationsThreadsIdSubscriptionParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Subscription | HttpResponse<models.Subscription> | HttpEvent<models.Subscription>> {
return super.putNotificationsThreadsIdSubscription(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isSubscription(res) || console.error(`TypeGuard for response 'models.Subscription' caught inconsistency.`, res)));
}
} | the_stack |
import { isDevMode } from "@angular/core"
import { def, hasChanged, hasOwn, isArray, isObject, isSymbol, ITERATE_KEY, makeMap, MAP_KEY_ITERATE_KEY, toRaw, toRawType } from "./utils"
import { ReactiveFlags, Target, UnwrapNestedRefs } from "./interfaces"
import { isRef, track, trigger } from "./ref"
import { TrackOpTypes, TriggerOpTypes } from "./operations"
// BASE HANDLERS
const builtInSymbols = new Set(
Object.getOwnPropertyNames(Symbol)
.map((key) => (Symbol as any)[key])
.filter(isSymbol),
)
const get = /*#__PURE__*/ createGetter()
const shallowGet = /*#__PURE__*/ createGetter(false, true)
const readonlyGet = /*#__PURE__*/ createGetter(true)
const shallowReadonlyGet = /*#__PURE__*/ createGetter(true, true)
const arrayInstrumentations: Record<string, Function> = {}
;["includes", "indexOf", "lastIndexOf"].forEach((key) => {
arrayInstrumentations[key] = function (...args: any[]): any {
const arr = toRaw(this) as any
for (let i = 0, l = (this as any).length; i < l; i++) {
track(arr, TrackOpTypes.GET, i + "")
}
// we run the method using the original args first (which may be reactive)
const res = arr[key](...args)
if (res === -1 || res === false) {
// if that didn't work, run it again using raw values.
return arr[key](...args.map(toRaw))
} else {
return res
}
}
})
function createGetter(isReadonly = false, shallow = false) {
return function get(
target: object,
key: string | symbol,
receiver: object,
) {
if (key === ReactiveFlags.isReactive) {
return !isReadonly
} else if (key === ReactiveFlags.isReadonly) {
return isReadonly
} else if (key === ReactiveFlags.raw) {
return target
}
const targetIsArray = isArray(target)
if (targetIsArray && hasOwn(arrayInstrumentations, key)) {
return Reflect.get(arrayInstrumentations, key, receiver)
}
const res = Reflect.get(target, key, receiver)
if ((isSymbol(key) && builtInSymbols.has(key)) || key === "__proto__") {
return res
}
if (shallow) {
!isReadonly && track(target, TrackOpTypes.GET, key)
return res
}
if (isRef(res)) {
if (targetIsArray) {
!isReadonly && track(target, TrackOpTypes.GET, key)
return res
} else {
// ref unwrapping, only for Objects, not for Arrays.
return res.value
}
}
!isReadonly && track(target, TrackOpTypes.GET, key)
return isObject(res)
? isReadonly
? // need to lazy access readonly and reactive here to avoid
// circular dependency
readonly(res)
: reactive(res)
: res
}
}
const set = /*#__PURE__*/ createSetter()
const shallowSet = /*#__PURE__*/ createSetter(true)
function createSetter(shallow = false) {
return function set(
target: object,
key: string | symbol,
value: unknown,
receiver: object,
): boolean {
const oldValue = (target as any)[key]
if (!shallow) {
value = toRaw(value)
if (!isArray(target) && isRef(oldValue) && !isRef(value)) {
oldValue.value = value
return true
}
} else {
// in shallow mode, objects are set as-is regardless of reactive or not
}
const hadKey = hasOwn(target, key)
const result = Reflect.set(target, key, value, receiver)
// don't trigger if target is something up in the prototype chain of original
if (target === toRaw(receiver)) {
if (!hadKey) {
trigger(target, TriggerOpTypes.ADD, key, value)
} else if (hasChanged(value, oldValue)) {
trigger(target, TriggerOpTypes.SET, key, value, oldValue)
}
}
return result
}
}
function deleteProperty(target: object, key: string | symbol): boolean {
const hadKey = hasOwn(target, key)
const oldValue = (target as any)[key]
const result = Reflect.deleteProperty(target, key)
if (result && hadKey) {
trigger(target, TriggerOpTypes.DELETE, key, undefined, oldValue)
}
return result
}
function has(target: object, key: string | symbol): boolean {
const result = Reflect.has(target, key)
track(target, TrackOpTypes.HAS, key)
return result
}
function ownKeys(target: object): (string | number | symbol)[] {
track(target, TrackOpTypes.ITERATE, ITERATE_KEY)
return Reflect.ownKeys(target)
}
export const mutableHandlers: ProxyHandler<object> = {
get,
set,
deleteProperty,
has,
ownKeys,
}
export const readonlyHandlers: ProxyHandler<object> = {
get: readonlyGet,
has,
ownKeys,
set(target, key) {
if (isDevMode()) {
console.warn(
`Set operation on key "${String(
key,
)}" failed: target is readonly.`,
target,
)
}
return true
},
deleteProperty(target, key) {
if (isDevMode()) {
console.warn(
`Delete operation on key "${String(
key,
)}" failed: target is readonly.`,
target,
)
}
return true
},
}
export const shallowReactiveHandlers: ProxyHandler<object> = {
...mutableHandlers,
get: shallowGet,
set: shallowSet,
}
// Props handlers are special in the sense that it should not unwrap top-level
// refs (in order to allow refs to be explicitly passed down), but should
// retain the reactivity of the normal readonly object.
export const shallowReadonlyHandlers: ProxyHandler<object> = {
...readonlyHandlers,
get: shallowReadonlyGet,
}
// COLLECTION HANDLERS
export type CollectionTypes = IterableCollections | WeakCollections
type IterableCollections = Map<any, any> | Set<any>
type WeakCollections = WeakMap<any, any> | WeakSet<any>
type MapTypes = Map<any, any> | WeakMap<any, any>
type SetTypes = Set<any> | WeakSet<any>
const toReactive = <T extends unknown>(value: T): T =>
(isObject(value) ? reactive(value) : value) as T
const toReadonly = <T extends unknown>(value: T): T =>
(isObject(value) ? readonly(value) : value) as T
const toShallow = <T extends unknown>(value: T): T => value
const getProto = <T extends CollectionTypes>(v: T): any =>
Reflect.getPrototypeOf(v)
function _get(
target: MapTypes,
key: unknown,
wrap: typeof toReactive | typeof toReadonly | typeof toShallow,
) {
target = toRaw(target)
const rawKey = toRaw(key)
if (key !== rawKey) {
track(target, TrackOpTypes.GET, key)
}
track(target, TrackOpTypes.GET, rawKey)
const { has, get } = getProto(target)
if (has.call(target, key)) {
return wrap(get.call(target, key))
} else if (has.call(target, rawKey)) {
return wrap(get.call(target, rawKey))
}
}
function _has(this: CollectionTypes, key: unknown): boolean {
const target = toRaw(this)
const rawKey = toRaw(key)
if (key !== rawKey) {
track(target, TrackOpTypes.HAS, key)
}
track(target, TrackOpTypes.HAS, rawKey)
const has = getProto(target).has
return has.call(target, key) || has.call(target, rawKey)
}
function size(target: IterableCollections) {
target = toRaw(target)
track(target, TrackOpTypes.ITERATE, ITERATE_KEY)
return Reflect.get(getProto(target), "size", target)
}
function add(this: SetTypes, value: unknown) {
value = toRaw(value)
const target = toRaw(this)
const proto = getProto(target)
const hadKey = proto.has.call(target, value)
const result = proto.add.call(target, value)
if (!hadKey) {
trigger(target, TriggerOpTypes.ADD, value, value)
}
return result
}
function _set(this: MapTypes, key: unknown, value: unknown) {
value = toRaw(value)
const target = toRaw(this)
const { has, get, set } = getProto(target)
let hadKey = has.call(target, key)
if (!hadKey) {
key = toRaw(key)
hadKey = has.call(target, key)
} else if (isDevMode()) {
checkIdentityKeys(target, has, key)
}
const oldValue = get.call(target, key)
const result = set.call(target, key, value)
if (!hadKey) {
trigger(target, TriggerOpTypes.ADD, key, value)
} else if (hasChanged(value, oldValue)) {
trigger(target, TriggerOpTypes.SET, key, value, oldValue)
}
return result
}
function deleteEntry(this: CollectionTypes, key: unknown) {
const target = toRaw(this)
const { has, get, delete: del } = getProto(target)
let hadKey = has.call(target, key)
if (!hadKey) {
key = toRaw(key)
hadKey = has.call(target, key)
} else if (isDevMode()) {
checkIdentityKeys(target, has, key)
}
const oldValue = get ? get.call(target, key) : undefined
// forward the operation before queueing reactions
const result = del.call(target, key)
if (hadKey) {
trigger(target, TriggerOpTypes.DELETE, key, undefined, oldValue)
}
return result
}
function clear(this: IterableCollections) {
const target = toRaw(this)
const hadItems = target.size !== 0
const oldTarget = isDevMode()
? target instanceof Map
? new Map(target)
: new Set(target)
: undefined
// forward the operation before queueing reactions
const result = getProto(target).clear.call(target)
if (hadItems) {
trigger(target, TriggerOpTypes.CLEAR, undefined, undefined, oldTarget)
}
return result
}
function createForEach(isReadonly: boolean, shallow: boolean) {
return function forEach(
this: IterableCollections,
callback: Function,
thisArg?: unknown,
) {
const observed = this
const target = toRaw(observed)
const wrap = isReadonly ? toReadonly : shallow ? toShallow : toReactive
!isReadonly && track(target, TrackOpTypes.ITERATE, ITERATE_KEY)
// important: create sure the callback is
// 1. invoked with the reactive map as `this` and 3rd arg
// 2. the value received should be a corresponding reactive/readonly.
function wrappedCallback(value: unknown, key: unknown) {
return callback.call(thisArg, wrap(value), wrap(key), observed)
}
return getProto(target).forEach.call(target, wrappedCallback)
}
}
function createIterableMethod(
method: string | symbol,
isReadonly: boolean,
shallow: boolean,
) {
return function (this: IterableCollections, ...args: unknown[]) {
const target = toRaw(this)
const isMap = target instanceof Map
const isPair =
method === "entries" || (method === Symbol.iterator && isMap)
const isKeyOnly = method === "keys" && isMap
const innerIterator = getProto(target)[method].apply(target, args)
const wrap = isReadonly ? toReadonly : shallow ? toShallow : toReactive
!isReadonly &&
track(
target,
TrackOpTypes.ITERATE,
isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY,
)
// return a wrapped iterator which returns observed versions of the
// values emitted from the real iterator
return {
// iterator protocol
next() {
const { value, done } = innerIterator.next()
return done
? { value, done }
: {
value: isPair
? [wrap(value[0]), wrap(value[1])]
: wrap(value),
done,
}
},
// iterable protocol
[Symbol.iterator]() {
return this
},
}
}
}
function createReadonlyMethod(type: TriggerOpTypes): Function {
return function (this: CollectionTypes, ...args: unknown[]) {
if (isDevMode()) {
const key = args[0] ? `on key "${args[0]}" ` : ``
console.warn(
`${type} operation ${key}failed: target is readonly.`,
toRaw(this),
)
}
return type === TriggerOpTypes.DELETE ? false : this
}
}
const mutableInstrumentations: Record<string, Function> = {
get(this: MapTypes, key: unknown) {
return _get(this, key, toReactive)
},
get size() {
return size((this as unknown) as IterableCollections)
},
has: _has,
add,
set: _set,
delete: deleteEntry,
clear,
forEach: createForEach(false, false),
}
const shallowInstrumentations: Record<string, Function> = {
get(this: MapTypes, key: unknown) {
return _get(this, key, toShallow)
},
get size() {
return size((this as unknown) as IterableCollections)
},
has: _has,
add,
set: _set,
delete: deleteEntry,
clear,
forEach: createForEach(false, true),
}
const readonlyInstrumentations: Record<string, Function> = {
get(this: MapTypes, key: unknown) {
return _get(this, key, toReadonly)
},
get size() {
return size((this as unknown) as IterableCollections)
},
has: _has,
add: createReadonlyMethod(TriggerOpTypes.ADD),
set: createReadonlyMethod(TriggerOpTypes.SET),
delete: createReadonlyMethod(TriggerOpTypes.DELETE),
clear: createReadonlyMethod(TriggerOpTypes.CLEAR),
forEach: createForEach(true, false),
}
const iteratorMethods = ["keys", "values", "entries", Symbol.iterator]
iteratorMethods.forEach((method) => {
mutableInstrumentations[method as string] = createIterableMethod(
method,
false,
false,
)
readonlyInstrumentations[method as string] = createIterableMethod(
method,
true,
false,
)
shallowInstrumentations[method as string] = createIterableMethod(
method,
true,
true,
)
})
function createInstrumentationGetter(isReadonly: boolean, shallow: boolean) {
const instrumentations = shallow
? shallowInstrumentations
: isReadonly
? readonlyInstrumentations
: mutableInstrumentations
return (
target: CollectionTypes,
key: string | symbol,
receiver: CollectionTypes,
) => {
if (key === ReactiveFlags.isReactive) {
return !isReadonly
} else if (key === ReactiveFlags.isReadonly) {
return isReadonly
} else if (key === ReactiveFlags.raw) {
return target
}
return Reflect.get(
hasOwn(instrumentations, key) && key in target
? instrumentations
: target,
key,
receiver,
)
}
}
export const mutableCollectionHandlers: ProxyHandler<CollectionTypes> = {
get: createInstrumentationGetter(false, false),
}
export const shallowCollectionHandlers: ProxyHandler<CollectionTypes> = {
get: createInstrumentationGetter(false, true),
}
export const readonlyCollectionHandlers: ProxyHandler<CollectionTypes> = {
get: createInstrumentationGetter(true, false),
}
function checkIdentityKeys(
target: CollectionTypes,
has: (key: unknown) => boolean,
key: unknown,
) {
const rawKey = toRaw(key)
if (rawKey !== key && has.call(target, rawKey)) {
const type = toRawType(target)
console.warn(
`Reactive ${type} contains both the raw and reactive ` +
`versions of the same object${
type === `Map` ? `as keys` : ``
}, ` +
`which can lead to inconsistencies. ` +
`Avoid differentiating between the raw and reactive versions ` +
`of an object and only use the reactive version if possible.`,
)
}
}
// REACTIVE FACTORY
const collectionTypes = new Set<Function>([Set, Map, WeakMap, WeakSet])
const isObservableType = makeMap("Object,Array,Map,Set,WeakMap,WeakSet")
const canObserve = (value: Target): boolean => {
return (
!value.__ng_skip &&
isObservableType(toRawType(value)) &&
!Object.isFrozen(value)
)
}
export function reactive<T extends object>(target: T): UnwrapNestedRefs<T>
export function reactive(target: object) {
// if trying to observe a readonly proxy, return the readonly version.
if (target && (target as Target).__ng_isReadonly) {
return target
}
return createReactiveObject(
target,
false,
mutableHandlers,
mutableCollectionHandlers,
)
}
// Return a reactive-copy of the original object, where only the root level
// properties are reactive, and does NOT unwrap refs nor recursively convert
// returned properties.
export function shallowReactive<T extends object>(target: T): T {
return createReactiveObject(
target,
false,
shallowReactiveHandlers,
shallowCollectionHandlers,
)
}
export function readonly<T extends object>(
target: T,
): Readonly<UnwrapNestedRefs<T>> {
return createReactiveObject(
target,
true,
readonlyHandlers,
readonlyCollectionHandlers,
)
}
// Return a reactive-copy of the original object, where only the root level
// properties are readonly, and does NOT unwrap refs nor recursively convert
// returned properties.
// This is used for creating the props proxy object for stateful components.
export function shallowReadonly<T extends object>(
target: T,
): Readonly<{ [K in keyof T]: UnwrapNestedRefs<T[K]> }> {
return createReactiveObject(
target,
true,
shallowReadonlyHandlers,
readonlyCollectionHandlers,
)
}
function createReactiveObject(
target: Target,
isReadonly: boolean,
baseHandlers: ProxyHandler<any>,
collectionHandlers: ProxyHandler<any>,
) {
if (!isObject(target)) {
if (isDevMode()) {
console.warn(`value cannot be made reactive: ${String(target)}`)
}
return target
}
// target is already a Proxy, return it.
// exception: calling readonly() on a reactive object
if (target.__ng_raw && !(isReadonly && target.__ng_isReactive)) {
return target
}
// target already has corresponding Proxy
if (
hasOwn(
target,
isReadonly ? ReactiveFlags.readonly : ReactiveFlags.reactive,
)
) {
return isReadonly ? target.__ng_readonly : target.__ng_reactive
}
// only a whitelist of value types can be observed.
if (!canObserve(target)) {
return target
}
const observed = new Proxy(
target,
collectionTypes.has(target.constructor)
? collectionHandlers
: baseHandlers,
)
def(
target,
isReadonly ? ReactiveFlags.readonly : ReactiveFlags.reactive,
observed,
)
return observed
} | the_stack |
import { spawn } from 'child_process';
import * as path from 'path';
import { Access } from '../../models/';
import {
assert,
makeLogger,
KError,
checkMinimalWoobVersion,
UNKNOWN_WOOB_VERSION,
} from '../../helpers';
import {
WOOB_NOT_INSTALLED,
INTERNAL_ERROR,
INVALID_PARAMETERS,
UNKNOWN_WOOB_MODULE,
GENERIC_EXCEPTION,
INVALID_PASSWORD,
EXPIRED_PASSWORD,
} from '../../shared/errors.json';
import { UserActionField, UserActionKind, UserActionResponse } from '../../shared/types';
import {
Provider,
FetchOperationsOptions,
FetchAccountsOptions,
SessionManager,
ProviderAccountResponse,
ProviderTransactionResponse,
} from '../';
const log = makeLogger('providers/woob');
// Subcommand error code indicating malformed argparse parameters.
const ARGPARSE_MALFORMED_OPTIONS_CODE = 2;
// The list of errors which should trigger a reset of the session when raised.
const RESET_SESSION_ERRORS = [INVALID_PARAMETERS, INVALID_PASSWORD, EXPIRED_PASSWORD];
const NOT_INSTALLED_ERRORS = [
WOOB_NOT_INSTALLED,
INTERNAL_ERROR,
GENERIC_EXCEPTION,
UNKNOWN_WOOB_MODULE,
];
interface OptionalEnvParams extends NodeJS.ProcessEnv {
KRESUS_WOOB_PWD?: string;
KRESUS_WOOB_SESSION?: string;
}
// Runs the subcommad `command`, with the given array of args, setting the
// environment to the given value.
function subcommand(
command: string,
args: string[],
env: OptionalEnvParams
): Promise<{ code: number; stderr: string; stdout: string }> {
return new Promise(accept => {
const script = spawn(command, args, { env });
let stdoutBuffer = Buffer.from('');
script.stdout.on('data', (data: Buffer) => {
stdoutBuffer = Buffer.concat([stdoutBuffer, data]);
});
let stderrBuffer = Buffer.from('');
script.stderr.on('data', (data: Buffer) => {
stderrBuffer = Buffer.concat([stderrBuffer, data]);
});
script.on('close', (code: number) => {
const stderr = stderrBuffer.toString('utf8').trim();
const stdout = stdoutBuffer.toString('utf8').trim();
accept({
code,
stderr,
stdout,
});
});
});
}
interface PythonResponse {
kind: 'error' | 'user_action' | 'success';
session: Record<string, unknown>;
}
// An error returned by Woob.
interface WoobErrorResponse extends PythonResponse {
kind: 'error';
// eslint-disable-next-line camelcase
error_code: string;
// eslint-disable-next-line camelcase
error_message: string;
// eslint-disable-next-line camelcase
error_short: string;
}
// The woob connection requires a user action.
interface WoobUserActionResponse extends PythonResponse {
kind: 'user_action';
// eslint-disable-next-line camelcase
action_kind: UserActionKind;
message?: string;
fields: UserActionField[];
}
// Successful execution of woob, with a range of values, to be interpreted in
// the context of the caller's query.
interface WoobSuccessResponse extends PythonResponse {
kind: 'success';
values: [Record<string, unknown>];
}
type WoobResponse = WoobErrorResponse | WoobSuccessResponse | WoobUserActionResponse;
async function woobCommand(envParam: OptionalEnvParams, cliArgs: string[]): Promise<WoobResponse> {
// We need to copy the whole `process.env` to ensure we don't break any
// user setup, such as virtualenvs, NODE_ENV, etc.
const env = Object.assign({ ...process.env }, envParam);
// Fill in other common environment variables.
if (process.kresus.woobDir) {
env.WOOB_DIR = process.kresus.woobDir;
}
if (process.kresus.woobSourcesList) {
env.WOOB_SOURCES_LIST = process.kresus.woobSourcesList;
}
env.KRESUS_DIR = process.kresus.dataDir;
// Variable for PyExecJS, necessary for the Paypal module.
env.EXECJS_RUNTIME = 'Node';
const { code, stderr, stdout } = await subcommand(
process.kresus.pythonExec,
[path.join(path.dirname(__filename), 'py', 'main.py')].concat(cliArgs),
env
);
log.info(`exited with code ${code}.`);
if (stderr.length) {
// Log anything that went to stderr.
log.warn(`stderr: ${stderr}`);
}
// Parse JSON response. Any error (be it a crash of the Python script or a
// legit error from Woob) will result in a non-zero error code. Hence, we
// should first try to parse stdout as JSON, to retrieve an eventual legit
// error, and THEN check the return code.
let jsonResponse;
try {
jsonResponse = JSON.parse(stdout);
} catch (e) {
// We got an invalid JSON response, there is a real and important error.
if (code === ARGPARSE_MALFORMED_OPTIONS_CODE) {
throw new KError('Options are malformed', null, INTERNAL_ERROR);
}
if (code !== 0) {
// If code is non-zero, treat as stderr, that is a crash of the Python script.
throw new KError(
`Process exited with non-zero error code ${code}. Unknown error. Stderr was:
${stderr}`
);
}
// Else, treat it as invalid JSON. This should never happen, it would
// be a programming error.
throw new KError(`Invalid JSON response: ${e.message}.`);
}
if (typeof jsonResponse.error_code !== 'undefined') {
jsonResponse.kind = 'error';
} else if (typeof jsonResponse.action_kind !== 'undefined') {
jsonResponse.kind = 'user_action';
} else {
jsonResponse.kind = 'success';
}
return jsonResponse;
}
interface WoobOptions {
debug: boolean;
forceUpdate: boolean;
isInteractive: boolean;
resume2fa: boolean;
useNss?: boolean;
fromDate: Date | null;
userActionFields: Record<string, string> | null;
}
function defaultOptions(): WoobOptions {
return {
debug: false,
forceUpdate: false,
isInteractive: false,
resume2fa: false,
useNss: false,
fromDate: null,
userActionFields: null,
};
}
async function callWoob(
command: string,
options: WoobOptions,
sessionManager: SessionManager | null,
access: Access | null = null
): Promise<any> {
log.info(`Calling woob: command ${command}...`);
const cliArgs = [command];
if (options.isInteractive) {
cliArgs.push('--interactive');
}
if (options.userActionFields !== null) {
const fields = Object.keys(options.userActionFields);
if (fields.length === 0) {
// AppValidation resume.
cliArgs.push('--resume');
} else {
for (const name of fields) {
cliArgs.push('--field', name, options.userActionFields[name]);
}
}
}
if (options.debug) {
cliArgs.push('--debug');
}
if (options.forceUpdate) {
cliArgs.push('--update');
log.info(`Woob will be updated prior to command "${command}"`);
}
if (typeof options.useNss !== 'undefined' && options.useNss) {
cliArgs.push('--nss');
}
const env: OptionalEnvParams = {};
if (command === 'accounts' || command === 'operations') {
assert(access !== null, 'Access must not be null for accounts/operations.');
cliArgs.push('--module', access.vendorId, '--login', access.login);
// Pass the password via an environment variable to hide it.
assert(access.password !== null, 'Access must have a password for fetching.');
env.KRESUS_WOOB_PWD = access.password;
// Pass the session information as environment variable to hide it.
assert(
sessionManager !== null,
'session manager must be provided for accounts/operations.'
);
const session = await sessionManager.read(access);
if (session) {
env.KRESUS_WOOB_SESSION = JSON.stringify(session);
}
const { fields = [] } = access;
for (const { name, value } of fields) {
if (typeof name === 'undefined' || typeof value === 'undefined') {
throw new KError(
`Missing 'name' (${name}) or 'value' (${value}) for field`,
null,
INVALID_PARAMETERS
);
}
cliArgs.push('--field', name, value);
}
if (command === 'operations' && options.fromDate !== null) {
const timestamp = `${options.fromDate.getTime() / 1000}`;
cliArgs.push('--fromDate', timestamp);
}
}
const response = (await woobCommand(env, cliArgs)) as WoobResponse;
// If valid JSON output, check for an error within JSON.
if (response.kind === 'error') {
log.info('Command returned an error code.');
if (access && RESET_SESSION_ERRORS.includes(response.error_code)) {
assert(sessionManager !== null, 'session manager required.');
log.warn(
`Resetting session for access from bank ${access.vendorId} with login ${access.login}`
);
await sessionManager.reset(access);
}
throw new KError(
response.error_message ? response.error_message : response.error_code,
null,
response.error_code,
response.error_short
);
}
if (access && response.session) {
assert(sessionManager !== null, 'session manager required.');
log.info(
`Saving session for access from bank ${access.vendorId} with login ${access.login}`
);
await sessionManager.save(access, response.session);
}
if (response.kind === 'user_action') {
switch (response.action_kind) {
case 'decoupled_validation': {
log.info('Decoupled validation is required; propagating information to the user.');
assert(typeof response.message === 'string', 'message must be filled by woob');
return {
kind: 'user_action',
actionKind: 'decoupled_validation',
message: response.message,
};
}
case 'browser_question': {
log.info('Browser question is required; propagating question to the user.');
assert(response.fields instanceof Array, 'fields must be filled by woob');
for (const field of response.fields) {
assert(typeof field.id === 'string', 'field id must be filled by woob');
}
return {
kind: 'user_action',
actionKind: 'browser_question',
fields: response.fields,
};
}
default: {
throw new KError(
`Likely a programmer error: unknown user action kind ${response.action_kind}`
);
}
}
}
assert(response.kind === 'success', 'Must be a successful woob response');
log.info('OK: woob exited normally with non-empty JSON content.');
return {
kind: 'values',
values: response.values,
};
}
let cachedVersion: string | null = UNKNOWN_WOOB_VERSION;
async function testInstall() {
try {
log.info('Checking that woob is installed and can actually be called…');
await callWoob('test', defaultOptions(), null);
return true;
} catch (err) {
log.error(`When testing install: ${err}`);
cachedVersion = UNKNOWN_WOOB_VERSION;
return false;
}
}
async function _fetchHelper<T>(
command: string,
options: WoobOptions,
sessionManager: SessionManager,
access: Access
): Promise<T | UserActionResponse> {
try {
return await callWoob(command, options, sessionManager, access);
} catch (err) {
if (NOT_INSTALLED_ERRORS.includes(err.errCode) && !(await testInstall())) {
throw new KError(
"Woob doesn't seem to be installed, skipping fetch.",
null,
WOOB_NOT_INSTALLED
);
}
log.error(`Got error while running command "${command}": ${err.message}`);
if (typeof err.errCode !== 'undefined') {
log.error(`\t(error code: ${err.errCode})`);
}
throw err;
}
}
export async function fetchAccounts(
{ access, debug, update, isInteractive, userActionFields, useNss }: FetchAccountsOptions,
sessionManager: SessionManager
): Promise<ProviderAccountResponse | UserActionResponse> {
return await _fetchHelper<ProviderAccountResponse>(
'accounts',
{
...defaultOptions(),
debug,
forceUpdate: update,
isInteractive,
userActionFields,
useNss,
},
sessionManager,
access
);
}
export async function fetchOperations(
{ access, debug, fromDate, isInteractive, userActionFields, useNss }: FetchOperationsOptions,
sessionManager: SessionManager
): Promise<ProviderTransactionResponse | UserActionResponse> {
return await _fetchHelper<ProviderTransactionResponse>(
'operations',
{
...defaultOptions(),
debug,
isInteractive,
fromDate,
userActionFields,
useNss,
},
sessionManager,
access
);
}
export const SOURCE_NAME = 'woob';
// It's not possible to type-check the exports themselves, so make a synthetic
// object that represents those, to make sure that the exports behave as
// expected, and use it.
export const _: Provider = {
SOURCE_NAME: 'woob',
fetchAccounts,
fetchOperations,
};
export async function getVersion(forceFetch = false) {
if (
cachedVersion === UNKNOWN_WOOB_VERSION ||
!checkMinimalWoobVersion(cachedVersion) ||
forceFetch
) {
try {
const response = await callWoob('version', defaultOptions(), null);
assert(response.kind === 'values', 'getting the version number should always succeed');
cachedVersion = response.values as string;
if (cachedVersion === '?') {
cachedVersion = UNKNOWN_WOOB_VERSION;
}
} catch (err) {
log.error(`When getting Woob version: ${err}`);
cachedVersion = UNKNOWN_WOOB_VERSION;
}
}
return cachedVersion;
}
// Can throw.
export async function updateModules() {
await callWoob('test', { ...defaultOptions(), forceUpdate: true }, null);
}
export const testing = {
callWoob,
defaultOptions,
}; | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.